diff --git a/bun.lock b/bun.lock index e47f01e4..45369617 100644 --- a/bun.lock +++ b/bun.lock @@ -33,7 +33,7 @@ }, "apps/agent": { "name": "@shumai/agent-app", - "version": "0.3.7", + "version": "0.4.2", "bin": { "shumai-agent": "./src/index.ts", }, @@ -45,7 +45,7 @@ }, "apps/cli": { "name": "@shumai/cli", - "version": "0.3.7", + "version": "0.4.2", "bin": { "shumai-cli": "./src/index.ts", }, @@ -60,7 +60,7 @@ }, "apps/transcode": { "name": "@shumai/transcode-app", - "version": "0.3.7", + "version": "0.4.2", "bin": { "shumai-transcode": "./src/index.ts", }, @@ -72,7 +72,7 @@ }, "apps/web": { "name": "@shumai/web-app", - "version": "0.3.7", + "version": "0.4.2", "dependencies": { "@shumai/agent": "workspace:*", "@shumai/api": "workspace:*", @@ -92,7 +92,7 @@ }, "packages/agent": { "name": "@shumai/agent", - "version": "0.3.7", + "version": "0.4.2", "dependencies": { "@anthropic-ai/sandbox-runtime": "0.0.66", "@earendil-works/pi-agent-core": "0.82.1", @@ -117,7 +117,7 @@ }, "packages/api": { "name": "@shumai/api", - "version": "0.3.7", + "version": "0.4.2", "dependencies": { "@hono/zod-validator": "0.7.6", "@shumai/core": "workspace:*", @@ -131,8 +131,26 @@ }, "packages/core": { "name": "@shumai/core", - "version": "0.3.7", + "version": "0.4.2", "dependencies": { + "@ai-sdk/alibaba": "2.0.38", + "@ai-sdk/amazon-bedrock": "5.0.67", + "@ai-sdk/azure": "4.0.53", + "@ai-sdk/black-forest-labs": "2.0.34", + "@ai-sdk/bytedance": "2.0.36", + "@ai-sdk/deepinfra": "3.0.40", + "@ai-sdk/fal": "3.0.34", + "@ai-sdk/fireworks": "3.0.43", + "@ai-sdk/google": "4.0.57", + "@ai-sdk/google-vertex": "5.0.69", + "@ai-sdk/klingai": "4.0.35", + "@ai-sdk/luma": "3.0.34", + "@ai-sdk/minimax": "3.0.21", + "@ai-sdk/openai": "4.0.51", + "@ai-sdk/prodia": "2.0.34", + "@ai-sdk/replicate": "3.0.34", + "@ai-sdk/togetherai": "3.0.41", + "@ai-sdk/xai": "4.0.49", "@earendil-works/pi-agent-core": "0.82.1", "@earendil-works/pi-ai": "0.82.1", "@modelcontextprotocol/client": "2.0.0", @@ -140,6 +158,7 @@ "@shumai/dtos": "workspace:*", "@sinclair/typebox": "0.34.49", "adm-zip": "0.5.17", + "ai": "7.0.84", "better-auth": "1.6.11", "csv-parse": "7.0.1", "date-fns": "4.4.0", @@ -166,7 +185,7 @@ }, "packages/db": { "name": "@shumai/db", - "version": "0.3.7", + "version": "0.4.2", "dependencies": { "@earendil-works/pi-agent-core": "0.82.1", "@prisma/adapter-pg": "7.8.0", @@ -182,7 +201,7 @@ }, "packages/dtos": { "name": "@shumai/dtos", - "version": "0.3.7", + "version": "0.4.2", "dependencies": { "@earendil-works/pi-agent-core": "0.82.1", "zod": "4.4.3", @@ -190,7 +209,7 @@ }, "packages/e2e": { "name": "@shumai/e2e", - "version": "0.3.7", + "version": "0.4.2", "dependencies": { "@earendil-works/pi-agent-core": "0.82.1", "@google/genai": "1.52.0", @@ -205,11 +224,11 @@ }, "packages/tableprinter": { "name": "@shumai/tableprinter", - "version": "0.3.7", + "version": "0.4.2", }, "packages/transcode": { "name": "@shumai/transcode", - "version": "0.3.7", + "version": "0.4.2", "dependencies": { "@shumai/core": "workspace:*", "@shumai/db": "workspace:*", @@ -223,7 +242,7 @@ }, "packages/webui": { "name": "@shumai/webui", - "version": "0.3.7", + "version": "0.4.2", "dependencies": { "@base-ui/react": "1.5.0", "@dnd-kit/abstract": "0.4.0", @@ -321,7 +340,7 @@ }, "packages/workflow-core": { "name": "@shumai/workflow-core", - "version": "0.3.7", + "version": "0.4.2", "dependencies": { "@shumai/core": "workspace:*", "@shumai/db": "workspace:*", @@ -337,6 +356,54 @@ "@earendil-works/pi-ai@0.82.1": "patches/@earendil-works%2Fpi-ai@0.82.1.patch", }, "packages": { + "@ai-sdk/alibaba": ["@ai-sdk/alibaba@2.0.38", "", { "dependencies": { "@ai-sdk/provider": "4.0.8", "@ai-sdk/provider-utils": "5.0.33" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-cPXqexcd/l94AyDeo2DoRBqQl6jrXwZbv7FBcnrKbz59U3RHJcxOs3a9KnxYYrmI4rs5iCqh3LGI0jb+Efw+ng=="], + + "@ai-sdk/amazon-bedrock": ["@ai-sdk/amazon-bedrock@5.0.67", "", { "dependencies": { "@ai-sdk/anthropic": "4.0.45", "@ai-sdk/openai": "4.0.51", "@ai-sdk/provider": "4.0.8", "@ai-sdk/provider-utils": "5.0.33", "@smithy/eventstream-codec": "^4.3.3", "@smithy/util-utf8": "^4.3.3", "aws4fetch": "^1.0.20" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-GFhqE9rHOTrSwcNcqvBNGdU4DD9a6tsYCz/KelQZJy3XAAaUpLkTvefITLNX2A+n/MHfu6Q9TPhKrOpXj5auSQ=="], + + "@ai-sdk/anthropic": ["@ai-sdk/anthropic@4.0.45", "", { "dependencies": { "@ai-sdk/provider": "4.0.8", "@ai-sdk/provider-utils": "5.0.33" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-2h1WYU1VdfkI6CU3mLes7Vh4Ua3jq5LDE1ciMgUymLNS7ZbtqhgVzBBPhnOdg83lnkYTAOeApCgkGOdwJHxdkA=="], + + "@ai-sdk/azure": ["@ai-sdk/azure@4.0.53", "", { "dependencies": { "@ai-sdk/deepseek": "3.0.36", "@ai-sdk/openai": "4.0.51", "@ai-sdk/provider": "4.0.8", "@ai-sdk/provider-utils": "5.0.33" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-A8tPuNlhrxbuhdvreK/8+LLrPCAvpgWSc6bga9+Hx1fmr2ZkXmXwCAzVaJR5cz6cA35dRYOU2YiXO6egvvuaTw=="], + + "@ai-sdk/black-forest-labs": ["@ai-sdk/black-forest-labs@2.0.34", "", { "dependencies": { "@ai-sdk/provider": "4.0.8", "@ai-sdk/provider-utils": "5.0.33" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-omP8ltApbR4cB/6/w05pbeTX3J5+yCCwc9FVj6VJiYlSQZxHYJfBANeYSblsbaaI7NdO9rPImF6ufU9BQeXmPA=="], + + "@ai-sdk/bytedance": ["@ai-sdk/bytedance@2.0.36", "", { "dependencies": { "@ai-sdk/provider": "4.0.8", "@ai-sdk/provider-utils": "5.0.33" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-ikRYoNUeSLzVJMxTgBAfANyQLkin5hW8huyIyvxpKYqbL6CSfrrOA9iQ0oR+ek+wLcpDPSQhxPQw1sZsesv9dw=="], + + "@ai-sdk/deepinfra": ["@ai-sdk/deepinfra@3.0.40", "", { "dependencies": { "@ai-sdk/openai-compatible": "3.0.40", "@ai-sdk/provider": "4.0.8", "@ai-sdk/provider-utils": "5.0.33" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-RIbiUM0U9Y/l44vInSKboQjcIzeDqj2Laoa4Q9tqAJTfmUnkmI6ekhpRSYhcviQh9w1lttAMQo4TekeII2i3bg=="], + + "@ai-sdk/deepseek": ["@ai-sdk/deepseek@3.0.36", "", { "dependencies": { "@ai-sdk/provider": "4.0.8", "@ai-sdk/provider-utils": "5.0.33" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-W7GntNu2hsPBgimJl7/rKFviikILz2VP+7KnlN4ij9+8PEnwJrM7Dnm/2/vPoG/CHba2ZU6uczTR4DBBC0g7Zg=="], + + "@ai-sdk/fal": ["@ai-sdk/fal@3.0.34", "", { "dependencies": { "@ai-sdk/provider": "4.0.8", "@ai-sdk/provider-utils": "5.0.33" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-HnDyWbd+aGp23AcbRlu22sEK0X4ogKPPqQn4LR9TkpibmS2ML6DjcKLgSksoqW1y5WeJ8CTBye6VsD7bDR4iwQ=="], + + "@ai-sdk/fireworks": ["@ai-sdk/fireworks@3.0.43", "", { "dependencies": { "@ai-sdk/openai-compatible": "3.0.40", "@ai-sdk/provider": "4.0.8", "@ai-sdk/provider-utils": "5.0.33" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-WFxp0Ccw/mP+n5TQNrSKgm/z7nkuLrD5qCQ1TNJAYhWsVuimxPmcUXz2QWvEHjPE4HendZ5JrOs0fUczeQyTYg=="], + + "@ai-sdk/gateway": ["@ai-sdk/gateway@4.0.68", "", { "dependencies": { "@ai-sdk/provider": "4.0.8", "@ai-sdk/provider-utils": "5.0.33", "@vercel/oidc": "3.2.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-XKvZv6HFoMOWK64zXMaQatk4SxBzBDkGg7enXPWsCkxqPP4zDhFewOoBKasf3FPnZP9ceE+Yj3BgW925blAWtw=="], + + "@ai-sdk/google": ["@ai-sdk/google@4.0.57", "", { "dependencies": { "@ai-sdk/provider": "4.0.8", "@ai-sdk/provider-utils": "5.0.33" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-/d4DKIDB5iTQ3X2PDDEdU5cQlLAC3qW7UL2WP+U7QKrr1tCJ58PFRd35NWieahxFe0yQF7PZrHdi212ALSy1Hw=="], + + "@ai-sdk/google-vertex": ["@ai-sdk/google-vertex@5.0.69", "", { "dependencies": { "@ai-sdk/anthropic": "4.0.45", "@ai-sdk/google": "4.0.57", "@ai-sdk/openai-compatible": "3.0.40", "@ai-sdk/provider": "4.0.8", "@ai-sdk/provider-utils": "5.0.33", "google-auth-library": "^10.6.2" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-Bom1zR8Yza53C16qkMGC/6iaXR78nbHnaFSxDQGhedSv2lU8Y452ZDKE/02qkSHjIVUYWiWxe9HSDu8x6ySKBA=="], + + "@ai-sdk/klingai": ["@ai-sdk/klingai@4.0.35", "", { "dependencies": { "@ai-sdk/provider": "4.0.8", "@ai-sdk/provider-utils": "5.0.33" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-MSXfeKU4qxb/tO4Jf8zFbUsnYGeR3ig8n7Af4p2i5CCeZD5DXUQIN5BMw4DZXaakECCVsLWfs2qLRkp6wcDIjw=="], + + "@ai-sdk/luma": ["@ai-sdk/luma@3.0.34", "", { "dependencies": { "@ai-sdk/provider": "4.0.8", "@ai-sdk/provider-utils": "5.0.33" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-s99OTuS+kA+MGzDp6Ytd7eW/OrAAqpw988w7jztiWEHsIiwAVbDzJ1bk6Y7CvEMOtehAT+KyyC+9Q5GOx2maIg=="], + + "@ai-sdk/minimax": ["@ai-sdk/minimax@3.0.21", "", { "dependencies": { "@ai-sdk/anthropic": "4.0.45", "@ai-sdk/provider": "4.0.8", "@ai-sdk/provider-utils": "5.0.33" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-F8SqjZUtYM7paQPbsyC0qGXGQhdBZ0q70u1kiOWGLGHiRoo12FlyvNpZKTvLYjtPaCr4CqD3W8mvR03ein6DaQ=="], + + "@ai-sdk/openai": ["@ai-sdk/openai@4.0.51", "", { "dependencies": { "@ai-sdk/provider": "4.0.8", "@ai-sdk/provider-utils": "5.0.33" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-ByLpf4FrmiAFFV/hI2f3EwtuRR+e0AWttik2UsUgTpS10KIGEOvdO6RSMcMcDINQyqIQh8iCb9V7MC/6RtmDsg=="], + + "@ai-sdk/openai-compatible": ["@ai-sdk/openai-compatible@3.0.40", "", { "dependencies": { "@ai-sdk/provider": "4.0.8", "@ai-sdk/provider-utils": "5.0.33" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-4YvVykS7XfZEJMCe4gjxsT3CbCWXCONIK2QSVjEr+Xc4wbJcAxAM5xIWpx4x8ysFLlImhZc4OP4iTzeeGv76dA=="], + + "@ai-sdk/prodia": ["@ai-sdk/prodia@2.0.34", "", { "dependencies": { "@ai-sdk/provider": "4.0.8", "@ai-sdk/provider-utils": "5.0.33" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-Elh2zQVoLhDWrJVUtASaX0a0PrthQXZUgj3poyXohKhr4GMdsT19xvVNKjA0XRXjsMQ+fAwcfpTmNiDZTVTuqw=="], + + "@ai-sdk/provider": ["@ai-sdk/provider@4.0.8", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-aWO7iwhFUGf347tCwNGggggfmZigaSu7TF739IZSrWWABUp7zkb4Cr3fMqvBe5EIS7ABJJu3Cadn0g/zs1G0QQ=="], + + "@ai-sdk/provider-utils": ["@ai-sdk/provider-utils@5.0.33", "", { "dependencies": { "@ai-sdk/provider": "4.0.8", "@standard-schema/spec": "^1.1.0", "@workflow/serde": "4.1.0", "eventsource-parser": "^3.0.8", "undici": "^7.28.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-TfjJqJmRsQyxAlb+3hGmP1o1xLUIT79yhOgtJuTF4hqsB37IC3CufGsuFhU04EeTOg7R9iptQ6Bzm0MW0n/c3g=="], + + "@ai-sdk/replicate": ["@ai-sdk/replicate@3.0.34", "", { "dependencies": { "@ai-sdk/provider": "4.0.8", "@ai-sdk/provider-utils": "5.0.33" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-mqsGmnux+7yjgdeLW2DhxV4NbD4BBnZxakB+Gz9jj3PyjLxaFgFG/2+zcLqqHJI3/wSid+HI0S9RiqnNDaZ/9w=="], + + "@ai-sdk/togetherai": ["@ai-sdk/togetherai@3.0.41", "", { "dependencies": { "@ai-sdk/openai-compatible": "3.0.40", "@ai-sdk/provider": "4.0.8", "@ai-sdk/provider-utils": "5.0.33" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-nAxT5tkLrC2wNNRlgqMOmiQO6aQU+UAdOc1oNIBfA7v0j8ltxSO4pH9ZSPTowj9SgtlO/TKucMa228JmfTjw3w=="], + + "@ai-sdk/xai": ["@ai-sdk/xai@4.0.49", "", { "dependencies": { "@ai-sdk/provider": "4.0.8", "@ai-sdk/provider-utils": "5.0.33" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-Dl+iPxPygFKAMCFnQZ8YgNYrvMJtL8h+ht1JXKHkEIC2h6mp3P9J0tb8b0KRC6+NakYy/fBofhQ+/OfwtKgTFA=="], + "@alloc/quick-lru": ["@alloc/quick-lru@5.2.0", "", {}, "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw=="], "@anthropic-ai/sandbox-runtime": ["@anthropic-ai/sandbox-runtime@0.0.66", "", { "dependencies": { "@pondwader/socks5-server": "^1.0.10", "commander": "^12.1.0", "node-forge": "^1.4.0", "zod": "^3.24.1" }, "bin": { "srt": "dist/cli.js" } }, "sha512-OE7QiGZJXe7ZshP47U2vk2z9FGSyiSN4ca9krVrE28LS2Qj0AHRWZz+gAce6FzG3gx/4OjNFwIhDuHXnI0WWwA=="], @@ -1085,6 +1152,8 @@ "@smithy/credential-provider-imds": ["@smithy/credential-provider-imds@4.3.7", "", { "dependencies": { "@smithy/core": "^3.24.6", "@smithy/types": "^4.14.3", "tslib": "^2.6.2" } }, "sha512-xj8gq/bjFABAh6qWPSDCYcY3kzQIm4b561C+YnHH4zGq8rOgzQ3Shk+JGlpUxSd41UGiO6FkLdUCtNX1FAeHgg=="], + "@smithy/eventstream-codec": ["@smithy/eventstream-codec@4.5.2", "", { "dependencies": { "@smithy/core": "^3.33.2", "tslib": "^2.6.2" } }, "sha512-u4EAkaviMcQYlorFSnxFUgF/Dnbgiu2TzGmqOU4h3CL4MbvrYyNCXpFkcBwvAEU11EvspKX2zzS2uX7q+43VdQ=="], + "@smithy/fetch-http-handler": ["@smithy/fetch-http-handler@5.4.6", "", { "dependencies": { "@smithy/core": "^3.24.6", "@smithy/types": "^4.14.3", "tslib": "^2.6.2" } }, "sha512-FEwEYJ1jlBKdhe9TPzfghEi1bP55ZeEImlDkEa62bBBYzUcnB6RUCyuiS2mqKt6ZVjUbBgcNhzfIctH+Hevx9g=="], "@smithy/is-array-buffer": ["@smithy/is-array-buffer@2.2.0", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-GGP3O9QFD24uGeAXYUjwSTXARoqpZykHadOmA8G5vfJPK0/DC67qa//0qvqrJzL1xc8WQWX7/yc7fwudjPHPhA=="], @@ -1097,7 +1166,7 @@ "@smithy/util-buffer-from": ["@smithy/util-buffer-from@2.2.0", "", { "dependencies": { "@smithy/is-array-buffer": "^2.2.0", "tslib": "^2.6.2" } }, "sha512-IJdWBbTcMQ6DA0gdNhh/BwrLkDR+ADW5Kr1aZmd4k3DIF6ezMV4R2NIAmT08wQJ3yUK82thHWmC/TnK/wpMMIA=="], - "@smithy/util-utf8": ["@smithy/util-utf8@2.3.0", "", { "dependencies": { "@smithy/util-buffer-from": "^2.2.0", "tslib": "^2.6.2" } }, "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A=="], + "@smithy/util-utf8": ["@smithy/util-utf8@4.5.2", "", { "dependencies": { "@smithy/core": "^3.33.2", "tslib": "^2.6.2" } }, "sha512-7wNWV7SugHpcMA7uzEawJNpE0GrasXM7a9E+1+Wm6NxVuDClESac/AKt+G7jMZNUz5vBLWqKlqVV7Sv7AtUr6Q=="], "@sqlite.org/sqlite-wasm": ["@sqlite.org/sqlite-wasm@3.48.0-build4", "", { "bin": { "sqlite-wasm": "bin/index.js" } }, "sha512-hI6twvUkzOmyGZhQMza1gpfqErZxXRw6JEsiVjUbo7tFanVD+8Oil0Ih3l2nGzHdxPI41zFmfUQG7GHqhciKZQ=="], @@ -1329,6 +1398,8 @@ "@ungap/structured-clone": ["@ungap/structured-clone@1.3.1", "", {}, "sha512-mUFwbeTqrVgDQxFveS+df2yfap6iuP20NAKAsBt5jDEoOTDew+zwLAOilHCeQJOVSvmgCX4ogqIrA0mnyr08yQ=="], + "@vercel/oidc": ["@vercel/oidc@3.2.0", "", {}, "sha512-UycprH3T6n3jH0k44NHMa7pnFHGu/N05MjojYr+Mc6I7obkoLIJujSWwin1pCvdy/eOxrI/l3uDLQsmcrOb4ug=="], + "@videojs/http-streaming": ["@videojs/http-streaming@3.17.4", "", { "dependencies": { "@babel/runtime": "^7.12.5", "@videojs/vhs-utils": "^4.1.1", "aes-decrypter": "^4.0.2", "global": "^4.4.0", "m3u8-parser": "^7.2.0", "mpd-parser": "^1.3.1", "mux.js": "7.1.0", "video.js": "^7 || ^8" } }, "sha512-XAvdG2dolBuV2Fx8bu1kjmQ2D4TonGzZH68Pgv/O9xMSFWdZtITSMFismeQLEAtMmGwze8qNJp3RgV+jStrJqg=="], "@videojs/vhs-utils": ["@videojs/vhs-utils@4.1.1", "", { "dependencies": { "@babel/runtime": "^7.12.5", "global": "^4.4.0" } }, "sha512-5iLX6sR2ownbv4Mtejw6Ax+naosGvoT9kY+gcuHzANyUZZ+4NpeNdKMUhb6ag0acYej1Y7cmr/F2+4PrggMiVA=="], @@ -1379,6 +1450,8 @@ "@webassemblyjs/wast-printer": ["@webassemblyjs/wast-printer@1.14.1", "", { "dependencies": { "@webassemblyjs/ast": "1.14.1", "@xtuc/long": "4.2.2" } }, "sha512-kPSSXE6De1XOR820C90RIo2ogvZG+c3KiHzqUoO/F34Y2shGzesfqv7o57xrxovZJH/MetF5UjroJ/R/3isoiw=="], + "@workflow/serde": ["@workflow/serde@4.1.0", "", {}, "sha512-pav4F2BoirECWR7Nf1TKt+2eETcBj7jj4cBefQ8VXQCA6NPkaKeLfj/zMgi+3zYV5ZIBT4GuUiphsj0/b9hPQQ=="], + "@xmldom/xmldom": ["@xmldom/xmldom@0.8.13", "", {}, "sha512-KRYzxepc14G/CEpEGc3Yn+JKaAeT63smlDr+vjB8jRfgTBBI9wRj/nkQEO+ucV8p8I9bfKLWp37uHgFrbntPvw=="], "@xtuc/ieee754": ["@xtuc/ieee754@1.2.0", "", {}, "sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA=="], @@ -1399,6 +1472,8 @@ "agent-base": ["agent-base@7.1.4", "", {}, "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ=="], + "ai": ["ai@7.0.84", "", { "dependencies": { "@ai-sdk/gateway": "4.0.68", "@ai-sdk/provider": "4.0.8", "@ai-sdk/provider-utils": "5.0.33" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-znHNBWADOy79k8EK7636kDm5LmnjF4tMzegC2TfmlLDobDZbs0z0OXD2sxtH3eDTp5Re+pJQESvjinWJ6+kadQ=="], + "ajv": ["ajv@6.15.0", "", { "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", "json-schema-traverse": "^0.4.1", "uri-js": "^4.2.2" } }, "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw=="], "ajv-formats": ["ajv-formats@2.1.1", "", { "dependencies": { "ajv": "^8.0.0" } }, "sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA=="], @@ -1453,6 +1528,8 @@ "aws-ssl-profiles": ["aws-ssl-profiles@1.1.2", "", {}, "sha512-NZKeq9AfyQvEeNlN0zSYAaWrmBffJh3IELMZfRpJVWgrpEbtEpnjvzqBPf+mxoI287JohRDoa+/nsfqqiZmF6g=="], + "aws4fetch": ["aws4fetch@1.0.20", "", {}, "sha512-/djoAN709iY65ETD6LKCtyyEI04XIBP5xVvfmNxsEP0uJB5tyaGBztSryRr4HqMStr9R06PisQE7m9zDTXKu6g=="], + "b4a": ["b4a@1.8.1", "", { "peerDependencies": { "react-native-b4a": "*" }, "optionalPeers": ["react-native-b4a"] }, "sha512-aiqre1Nr0B/6DgE2N5vwTc+2/oQZ4Wh1t4NznYY4E00y8LCt6NqdRv81so00oo27D8MVKTpUa/MwUUtBLXCoDw=="], "babel-dead-code-elimination": ["babel-dead-code-elimination@1.0.12", "", { "dependencies": { "@babel/core": "^7.23.7", "@babel/parser": "^7.23.6", "@babel/traverse": "^7.23.7", "@babel/types": "^7.23.6" } }, "sha512-GERT7L2TiYcYDtYk1IpD+ASAYXjKbLTDPhBtYj7X1NuRMDTMtAx9kyBenub1Ev41lo91OHCKdmP+egTDmfQ7Ig=="], @@ -2061,6 +2138,8 @@ "json-buffer": ["json-buffer@3.0.1", "", {}, "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ=="], + "json-schema": ["json-schema@0.4.0", "", {}, "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA=="], + "json-schema-to-ts": ["json-schema-to-ts@3.1.1", "", { "dependencies": { "@babel/runtime": "^7.18.3", "ts-algebra": "^2.0.0" } }, "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g=="], "json-schema-traverse": ["json-schema-traverse@0.4.1", "", {}, "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg=="], @@ -2827,10 +2906,16 @@ "zwitch": ["zwitch@2.0.4", "", {}, "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A=="], + "@ai-sdk/provider-utils/undici": ["undici@7.29.0", "", {}, "sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw=="], + "@anthropic-ai/sandbox-runtime/commander": ["commander@12.1.0", "", {}, "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA=="], "@anthropic-ai/sandbox-runtime/zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="], + "@aws-crypto/sha256-browser/@smithy/util-utf8": ["@smithy/util-utf8@2.3.0", "", { "dependencies": { "@smithy/util-buffer-from": "^2.2.0", "tslib": "^2.6.2" } }, "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A=="], + + "@aws-crypto/util/@smithy/util-utf8": ["@smithy/util-utf8@2.3.0", "", { "dependencies": { "@smithy/util-buffer-from": "^2.2.0", "tslib": "^2.6.2" } }, "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A=="], + "@aws-sdk/client-bedrock-runtime/@smithy/node-http-handler": ["@smithy/node-http-handler@4.7.6", "", { "dependencies": { "@smithy/core": "^3.24.6", "@smithy/types": "^4.14.3", "tslib": "^2.6.2" } }, "sha512-3fya8i7GrJilQouk4cZJKdy5k8MWQBpjfXrRNaXDedH8r779tr0jcxyH3+yoTmsluc2+vF4S343yFbnvu8ExDQ=="], "@aws-sdk/credential-provider-http/@smithy/node-http-handler": ["@smithy/node-http-handler@4.7.6", "", { "dependencies": { "@smithy/core": "^3.24.6", "@smithy/types": "^4.14.3", "tslib": "^2.6.2" } }, "sha512-3fya8i7GrJilQouk4cZJKdy5k8MWQBpjfXrRNaXDedH8r779tr0jcxyH3+yoTmsluc2+vF4S343yFbnvu8ExDQ=="], @@ -3055,6 +3140,10 @@ "@reduxjs/toolkit/immer": ["immer@11.1.8", "", {}, "sha512-/tbkHMW7y10Lx6i1crLjD4/OhNkRG+Fo7byZHtah0547nIeXYcpIXaUh0IAQY6gO5459qpGGYapcEOHtFXkIuA=="], + "@smithy/eventstream-codec/@smithy/core": ["@smithy/core@3.33.3", "", { "dependencies": { "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-CsOeKq/9kA3y6VJHt+/+VTCtBaxJ4OTFpgrjIUhPpDIKxBci1k2bJaQASF2h/ELWrulGp+t97DZ0mevfAD8idg=="], + + "@smithy/util-utf8/@smithy/core": ["@smithy/core@3.33.3", "", { "dependencies": { "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-CsOeKq/9kA3y6VJHt+/+VTCtBaxJ4OTFpgrjIUhPpDIKxBci1k2bJaQASF2h/ELWrulGp+t97DZ0mevfAD8idg=="], + "@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/core@1.10.0", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.1", "tslib": "^2.4.0" }, "bundled": true }, "sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw=="], "@tailwindcss/oxide-wasm32-wasi/@emnapi/runtime": ["@emnapi/runtime@1.10.0", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA=="], @@ -3371,6 +3460,10 @@ "@radix-ui/react-tooltip/@radix-ui/react-use-controllable-state/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], + "@smithy/eventstream-codec/@smithy/core/@smithy/types": ["@smithy/types@4.17.2", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-FOKpVZob9MPTn2znRzGrnsMHv7BOsKVw3XiP/cOyYLDVZ9qKp4nifIiSCuUU/fIj5Vu0UOAxCFr+qRAtG0NUkA=="], + + "@smithy/util-utf8/@smithy/core/@smithy/types": ["@smithy/types@4.17.2", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-FOKpVZob9MPTn2znRzGrnsMHv7BOsKVw3XiP/cOyYLDVZ9qKp4nifIiSCuUU/fIj5Vu0UOAxCFr+qRAtG0NUkA=="], + "@tanstack/react-router/@tanstack/react-store/@tanstack/store": ["@tanstack/store@0.9.3", "", {}, "sha512-8reSzl/qGWGGVKhBoxXPMWzATSbZLZFWhwBAFO9NAyp0TxzfBP0mIrGb8CP8KrQTmvzXlR/vFPPUrHTLBGyFyw=="], "@temporalio/proto/protobufjs/@types/node": ["@types/node@22.19.19", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-dyh/xO2Fh5bYrfWaaqGrRQQGkNdmYw6AmaAUvYeUMNTWQtvb796ikLdmTchRmOlOiIJ1TDXfWgVx1QkUlQ6Hew=="], diff --git a/packages/agent/src/index.test.ts b/packages/agent/src/index.test.ts index fe45eb71..df8ab323 100644 --- a/packages/agent/src/index.test.ts +++ b/packages/agent/src/index.test.ts @@ -9,6 +9,7 @@ import { import { createSandboxedBashTool } from './tools/sandboxed-bash' import { SandboxManager, type SandboxAskCallback } from '@anthropic-ai/sandbox-runtime' import { quotaService } from '@shumai/core/src/quota/quota-service' +import { mediaGenerationService } from '@shumai/core/src/media-generation/media-generation' import { prisma } from '@shumai/db' import { setupTestDbHooks } from '@shumai/db/test' import { type TSchema } from 'typebox' @@ -1285,3 +1286,212 @@ describe('getModelFromDb', () => { expect(model.api).toBe('anthropic-messages') }) }) + +describe('createAgentSession media generation tools injection', () => { + setupTestDbHooks() + + it('omits generate_image and generate_video when no valid models are configured', async () => { + const team = await prisma.team.create({ + data: { name: 'No Media Team' }, + }) + const user = await prisma.user.create({ + data: { name: 'User 1', email: 'user1@example.com', password: 'pw' }, + }) + const agentUser = await prisma.user.create({ + data: { + id: 'agent-user-no-media', + name: 'Agent User 1', + email: 'agent1@test.com', + type: 'agent', + }, + }) + const agent = await prisma.agent.create({ + data: { + id: agentUser.id, + teamId: team.id, + type: 'chat', + config: { provider: 'google', model: 'gemini' }, + }, + }) + + vi.spyOn(mediaGenerationService, 'getValidModels').mockResolvedValue({ + imageModels: [], + videoModels: [], + providerKeys: {}, + }) + + const initializeSpy = vi.spyOn(SandboxManager, 'initialize').mockResolvedValue() + try { + const { harness } = await createAgentSession({ + teamId: team.id, + userId: user.id, + agentId: agent.id, + providerName: 'google', + modelId: 'gemini', + systemPrompt: 'prompt', + teamSkills: [], + enabledSkillIds: [], + allowedDomains: [], + providers: mockProviders, + }) + + const tools = harness.getTools() + expect(tools.find((t) => t.name === 'generate_image')).toBeUndefined() + expect(tools.find((t) => t.name === 'generate_video')).toBeUndefined() + } finally { + initializeSpy.mockRestore() + } + }) + + it('injects generate_image and generate_video when valid models are present', async () => { + const team = await prisma.team.create({ + data: { name: 'Media Team' }, + }) + const user = await prisma.user.create({ + data: { name: 'User 2', email: 'user2@example.com', password: 'pw' }, + }) + const agentUser = await prisma.user.create({ + data: { + id: 'agent-user-with-media', + name: 'Agent User 2', + email: 'agent2@test.com', + type: 'agent', + }, + }) + const agent = await prisma.agent.create({ + data: { + id: agentUser.id, + teamId: team.id, + type: 'chat', + config: { provider: 'google', model: 'gemini' }, + }, + }) + + vi.spyOn(mediaGenerationService, 'getValidModels').mockResolvedValue({ + imageModels: [ + { + id: 'im-1', + type: 'image', + provider: 'openai', + modelId: 'dall-e-3', + name: 'DALL-E 3', + createdAt: '2026-01-01T00:00:00.000Z', + }, + ], + videoModels: [ + { + id: 'vm-1', + type: 'video', + provider: 'klingai', + modelId: 'kling-v1-standard', + name: 'Kling v1 Standard', + createdAt: '2026-01-01T00:00:00.000Z', + }, + ], + providerKeys: { + openai: { apiKey: 'key-1' }, + klingai: { apiKey: 'key-2' }, + }, + }) + + const initializeSpy = vi.spyOn(SandboxManager, 'initialize').mockResolvedValue() + try { + const { harness } = await createAgentSession({ + teamId: team.id, + userId: user.id, + agentId: agent.id, + providerName: 'google', + modelId: 'gemini', + systemPrompt: 'prompt', + teamSkills: [], + enabledSkillIds: [], + allowedDomains: [], + providers: mockProviders, + }) + + const tools = harness.getTools() + expect(tools.find((t) => t.name === 'generate_image')).toBeDefined() + expect(tools.find((t) => t.name === 'generate_video')).toBeDefined() + } finally { + initializeSpy.mockRestore() + } + }) + + it('respects deniedTools when generate_image is denied in agent config', async () => { + const team = await prisma.team.create({ + data: { name: 'Denied Media Team' }, + }) + const user = await prisma.user.create({ + data: { name: 'User 3', email: 'user3@example.com', password: 'pw' }, + }) + const agentUser = await prisma.user.create({ + data: { + id: 'agent-user-denied-media', + name: 'Agent User 3', + email: 'agent3@test.com', + type: 'agent', + }, + }) + const agent = await prisma.agent.create({ + data: { + id: agentUser.id, + teamId: team.id, + type: 'chat', + config: { + provider: 'google', + model: 'gemini', + deniedTools: ['generate_image'], + }, + }, + }) + + vi.spyOn(mediaGenerationService, 'getValidModels').mockResolvedValue({ + imageModels: [ + { + id: 'im-1', + type: 'image', + provider: 'openai', + modelId: 'dall-e-3', + name: 'DALL-E 3', + createdAt: '2026-01-01T00:00:00.000Z', + }, + ], + videoModels: [ + { + id: 'vm-1', + type: 'video', + provider: 'klingai', + modelId: 'kling-v1-standard', + name: 'Kling v1 Standard', + createdAt: '2026-01-01T00:00:00.000Z', + }, + ], + providerKeys: { + openai: { apiKey: 'key-1' }, + klingai: { apiKey: 'key-2' }, + }, + }) + + const initializeSpy = vi.spyOn(SandboxManager, 'initialize').mockResolvedValue() + try { + const { harness } = await createAgentSession({ + teamId: team.id, + userId: user.id, + agentId: agent.id, + providerName: 'google', + modelId: 'gemini', + systemPrompt: 'prompt', + teamSkills: [], + enabledSkillIds: [], + allowedDomains: [], + providers: mockProviders, + }) + + const tools = harness.getTools() + expect(tools.find((t) => t.name === 'generate_image')).toBeUndefined() + expect(tools.find((t) => t.name === 'generate_video')).toBeDefined() + } finally { + initializeSpy.mockRestore() + } + }) +}) diff --git a/packages/agent/src/index.ts b/packages/agent/src/index.ts index 6bbf700a..c9b60886 100644 --- a/packages/agent/src/index.ts +++ b/packages/agent/src/index.ts @@ -28,6 +28,9 @@ import { createReadAssetTool } from './tools/read-asset' import { createReadSkillTool } from './tools/read-skill' import { createReadThreadTool } from './tools/read-thread' import { createSandboxedBashTool } from './tools/sandboxed-bash' +import { createGenerateImageTool } from './tools/generate-image' +import { createGenerateVideoTool } from './tools/generate-video' +import { mediaGenerationService } from '@shumai/core/src/media-generation/media-generation' import { serializeContextToXml } from './context/serialize-context' import type { ShumaiMessageContext } from '@shumai/dtos' @@ -321,6 +324,21 @@ export async function createAgentSession(params: CreateAgentSessionParams) { const agentConfig = agent?.config as PrismaJson.AgentConfig | null | undefined const deniedTools = agentConfig?.deniedTools || [] + if (!deniedTools.includes('generate_image') || !deniedTools.includes('generate_video')) { + try { + const { imageModels, videoModels, providerKeys } = + await mediaGenerationService.getValidModels(teamId) + if (imageModels.length > 0 && !deniedTools.includes('generate_image')) { + mediaTools.push(createGenerateImageTool(imageModels, providerKeys, userId)) + } + if (videoModels.length > 0 && !deniedTools.includes('generate_video')) { + mediaTools.push(createGenerateVideoTool(videoModels, providerKeys, userId)) + } + } catch (err) { + logger.error({ err, teamId }, 'Failed to initialize media generation tools') + } + } + const sandboxedBash = createSandboxedBashTool(process.cwd(), skillEnvs, { teamId, userId, @@ -660,3 +678,5 @@ export * from './workflows/agent-autofill' export * from './workflows/agent-chat' export * from './workflows/agent-embedding' export * from './workflows/query-embedding-for-search' +export * from './tools/generate-image' +export * from './tools/generate-video' diff --git a/packages/agent/src/tools/download-asset.test.ts b/packages/agent/src/tools/download-asset.test.ts index 30e9e07a..994c68d0 100644 --- a/packages/agent/src/tools/download-asset.test.ts +++ b/packages/agent/src/tools/download-asset.test.ts @@ -1,5 +1,9 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' -import { createDownloadAssetTool, resolveAssetIdFromKey } from './download-asset' +import { + createDownloadAssetTool, + resolveAssetIdFromKey, + resolveS3MediaBuffer, +} from './download-asset' import { prisma, type Asset, type StorageKey } from '@shumai/db' import { s3Service } from '@shumai/core/src/s3/s3' import { authzService } from '@shumai/core/src/authz/authz' @@ -340,4 +344,44 @@ describe('downloadAssetTool', () => { expect(assetId).toBe('ast-777') }) }) + + describe('resolveS3MediaBuffer helper unit tests', () => { + it('throws authorization error when userId is empty', async () => { + await expect(resolveS3MediaBuffer('files/ast-1/img.png', '')).rejects.toThrow( + 'User ID is required for authorization.', + ) + }) + + it('verifies authz permission on owning asset and returns buffer with mimeType', async () => { + vi.mocked(prisma.asset.findUnique).mockResolvedValue({ id: 'ast-1' } as unknown as Asset) + vi.mocked(authzService.hasPermission).mockResolvedValue() + vi.mocked(s3Service.getObject).mockResolvedValue({ + buffer: Buffer.from('png-bytes'), + contentType: 'image/png', + } as unknown as { buffer: Buffer; contentType: string }) + + const result = await resolveS3MediaBuffer('files/ast-1/image.png', 'user-123') + expect(authzService.hasPermission).toHaveBeenCalledWith({ + user: { id: 'user-123' }, + permission: 'Read', + type: 'asset', + id: 'ast-1', + }) + expect(result.buffer.toString()).toBe('png-bytes') + expect(result.mimeType).toBe('image/png') + }) + + it('throws error when S3 file is not an image', async () => { + vi.mocked(prisma.asset.findUnique).mockResolvedValue({ id: 'ast-1' } as unknown as Asset) + vi.mocked(authzService.hasPermission).mockResolvedValue() + vi.mocked(s3Service.getObject).mockResolvedValue({ + buffer: Buffer.from('some text'), + contentType: 'text/plain', + } as unknown as { buffer: Buffer; contentType: string }) + + await expect(resolveS3MediaBuffer('files/ast-1/readme.txt', 'user-123')).rejects.toThrow( + 'has MIME type "text/plain", but an image is required.', + ) + }) + }) }) diff --git a/packages/agent/src/tools/download-asset.ts b/packages/agent/src/tools/download-asset.ts index 8266f817..740a8028 100644 --- a/packages/agent/src/tools/download-asset.ts +++ b/packages/agent/src/tools/download-asset.ts @@ -4,6 +4,7 @@ import { prisma, type User } from '@shumai/db' import { s3Service } from '@shumai/core/src/s3/s3' import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz' import { sanitizeFilename } from '@shumai/core/src/utils/filename' +import { getFileMimeType } from '@shumai/core/src/utils/file-mime' import * as fs from 'fs' import * as path from 'path' @@ -85,6 +86,39 @@ export async function resolveAssetIdFromKey(key: string): Promise { ) } +export async function resolveS3MediaBuffer( + key: string, + userId: string, +): Promise<{ buffer: Buffer; mimeType: string }> { + if (!userId) { + throw new Error('User ID is required for authorization.') + } + const owningAssetId = await resolveAssetIdFromKey(key) + + await authzService.hasPermission({ + user: { id: userId } as User, + permission: Permission.Read, + type: ResourceType.Asset, + id: owningAssetId, + }) + + const bucket = process.env.S3_BUCKET || 'shumai' + const { buffer, contentType } = await s3Service.getObject(bucket, key) + const mimeType = getFileMimeType( + buffer, + key, + contentType && contentType !== 'application/octet-stream' + ? contentType + : 'application/octet-stream', + ) + + if (!mimeType.startsWith('image/')) { + throw new Error(`Storage key "${key}" has MIME type "${mimeType}", but an image is required.`) + } + + return { buffer, mimeType } +} + export function createDownloadAssetTool(userId: string): AgentTool { return { name: 'download_asset', diff --git a/packages/agent/src/tools/generate-image.test.ts b/packages/agent/src/tools/generate-image.test.ts new file mode 100644 index 00000000..df6e8fe1 --- /dev/null +++ b/packages/agent/src/tools/generate-image.test.ts @@ -0,0 +1,298 @@ +import { vi } from 'vitest' + +vi.mock('fs') + +import { describe, it, expect, beforeEach, afterEach } from 'vitest' +import { createGenerateImageTool } from './generate-image' +import * as downloadAsset from './download-asset' +import { mediaGenerationService } from '@shumai/core/src/media-generation/media-generation' +import { EnabledMediaModel } from '@shumai/dtos' +import * as fs from 'fs' +import * as path from 'path' + +describe('generate_image tool', () => { + const enabledModels: EnabledMediaModel[] = [ + { + id: 'em-1', + type: 'image', + provider: 'openai', + modelId: 'dall-e-3', + name: 'DALL-E 3 (OpenAI)', + createdAt: '2026-01-01T00:00:00.000Z', + }, + { + id: 'em-2', + type: 'image', + provider: 'azure', + modelId: 'dall-e-3', + name: 'DALL-E 3 (Azure)', + createdAt: '2026-01-01T00:00:00.000Z', + }, + { + id: 'em-3', + type: 'image', + provider: 'google', + modelId: 'imagen-3.0-generate-002', + name: 'Imagen 3', + createdAt: '2026-01-01T00:00:00.000Z', + }, + ] + + const providerKeys = { + openai: { apiKey: 'mock-openai-key' }, + azure: { apiKey: 'mock-azure-key' }, + google: { apiKey: 'mock-google-key' }, + } + + const piDir = path.join(process.cwd(), '.pi') + + beforeEach(() => { + vi.restoreAllMocks() + vi.spyOn(fs, 'existsSync').mockReturnValue(true) + vi.spyOn(fs, 'mkdirSync').mockImplementation(() => undefined) + vi.spyOn(fs, 'writeFileSync').mockImplementation(() => {}) + }) + + afterEach(() => { + vi.restoreAllMocks() + }) + + it('creates tool with correct metadata and provider-prefixed model schema', () => { + const tool = createGenerateImageTool(enabledModels, providerKeys, 'user-1') + expect(tool.name).toBe('generate_image') + expect(tool.label).toBe('Generate Image') + expect(tool.description).toContain('Generate an image') + const modelDesc = (tool.parameters as { properties: { model: { description: string } } }) + .properties.model.description + expect(modelDesc).toContain('openai:dall-e-3') + expect(modelDesc).toContain('azure:dall-e-3') + }) + + it('generates an image successfully and writes to .pi directory', async () => { + const tool = createGenerateImageTool(enabledModels, providerKeys, 'user-1') + + const mockBuffer = Buffer.from('fake-image-png-content') + const generateSpy = vi.spyOn(mediaGenerationService, 'generateImage').mockResolvedValue({ + buffer: mockBuffer, + mimeType: 'image/png', + }) + const writeSpy = vi.spyOn(fs, 'writeFileSync').mockImplementation(() => {}) + + const result = await tool.execute( + 'call-1', + { + prompt: 'A futuristic city skyline at dusk', + model: 'openai:dall-e-3', + aspectRatio: '16:9', + size: null, + seed: 42, + images: null, + mask: null, + outputFileName: 'test_city.png', + }, + new AbortController().signal, + ) + + expect(generateSpy).toHaveBeenCalledWith( + expect.objectContaining({ + provider: 'openai', + modelId: 'dall-e-3', + apiKey: 'mock-openai-key', + prompt: 'A futuristic city skyline at dusk', + aspectRatio: '16:9', + seed: 42, + }), + ) + + const expectedPath = path.join(piDir, 'test_city.png') + expect(writeSpy).toHaveBeenCalledWith(expectedPath, mockBuffer) + + const textContent = result.content[0] + expect(textContent.type).toBe('text') + if (textContent.type === 'text') { + expect(textContent.text).toContain('Successfully generated image') + expect(textContent.text).toContain('.pi/test_city.png') + } + expect(result.details).toMatchObject({ + fileName: 'test_city.png', + provider: 'openai', + model: 'dall-e-3', + }) + }) + + it('disambiguates identical model IDs across different providers', async () => { + const tool = createGenerateImageTool(enabledModels, providerKeys, 'user-1') + + const generateSpy = vi.spyOn(mediaGenerationService, 'generateImage').mockResolvedValue({ + buffer: Buffer.from('image-bytes'), + mimeType: 'image/png', + }) + + // Invoke azure:dall-e-3 + await tool.execute( + 'call-azure', + { + prompt: 'Azure generation', + model: 'azure:dall-e-3', + aspectRatio: null, + size: null, + seed: null, + images: null, + mask: null, + outputFileName: null, + }, + new AbortController().signal, + ) + + expect(generateSpy).toHaveBeenLastCalledWith( + expect.objectContaining({ + provider: 'azure', + modelId: 'dall-e-3', + apiKey: 'mock-azure-key', + }), + ) + + // Invoke openai:dall-e-3 + await tool.execute( + 'call-openai', + { + prompt: 'OpenAI generation', + model: 'openai:dall-e-3', + aspectRatio: null, + size: null, + seed: null, + images: null, + mask: null, + outputFileName: null, + }, + new AbortController().signal, + ) + + expect(generateSpy).toHaveBeenLastCalledWith( + expect.objectContaining({ + provider: 'openai', + modelId: 'dall-e-3', + apiKey: 'mock-openai-key', + }), + ) + }) + + it('defaults to first enabled model when model is null', async () => { + const tool = createGenerateImageTool(enabledModels, providerKeys, 'user-1') + + const mockBuffer = Buffer.from('fake-image-bytes') + const generateSpy = vi.spyOn(mediaGenerationService, 'generateImage').mockResolvedValue({ + buffer: mockBuffer, + mimeType: 'image/png', + }) + + await tool.execute( + 'call-2', + { + prompt: 'A cute cat', + model: null, + aspectRatio: null, + size: null, + seed: null, + images: null, + mask: null, + outputFileName: null, + }, + new AbortController().signal, + ) + + expect(generateSpy).toHaveBeenCalledWith( + expect.objectContaining({ + provider: 'openai', + modelId: 'dall-e-3', + }), + ) + }) + + it('resolves reference images and mask via resolveS3MediaBuffer', async () => { + const tool = createGenerateImageTool(enabledModels, providerKeys, 'user-1') + + const generateSpy = vi.spyOn(mediaGenerationService, 'generateImage').mockResolvedValue({ + buffer: Buffer.from('out'), + mimeType: 'image/jpeg', + }) + + const resolverSpy = vi + .spyOn(downloadAsset, 'resolveS3MediaBuffer') + .mockImplementation(async (key: string) => ({ + buffer: Buffer.from(`data-for-${key}`), + mimeType: 'image/png', + })) + + await tool.execute( + 'call-3', + { + prompt: 'Transform into watercolor', + model: 'openai:dall-e-3', + aspectRatio: null, + size: null, + seed: null, + images: ['files/ast-1/ref1.png', 'files/ast-2/ref2.png'], + mask: 'files/ast-mask/mask.png', + outputFileName: 'test_watercolor.jpg', + }, + new AbortController().signal, + ) + + expect(resolverSpy).toHaveBeenCalledWith('files/ast-1/ref1.png', 'user-1') + expect(resolverSpy).toHaveBeenCalledWith('files/ast-2/ref2.png', 'user-1') + expect(resolverSpy).toHaveBeenCalledWith('files/ast-mask/mask.png', 'user-1') + expect(generateSpy).toHaveBeenCalledWith( + expect.objectContaining({ + images: [ + Buffer.from('data-for-files/ast-1/ref1.png'), + Buffer.from('data-for-files/ast-2/ref2.png'), + ], + mask: Buffer.from('data-for-files/ast-mask/mask.png'), + }), + ) + }) + + it('fails gracefully when API key is missing', async () => { + const tool = createGenerateImageTool(enabledModels, {}, 'user-1') // No keys configured + + await expect( + tool.execute( + 'call-4', + { + prompt: 'A sunset', + model: 'openai:dall-e-3', + aspectRatio: null, + size: null, + seed: null, + images: null, + mask: null, + outputFileName: null, + }, + new AbortController().signal, + ), + ).rejects.toThrow('API key for provider "openai" is not configured') + }) + + it('fails gracefully when requested model is not enabled', async () => { + const tool = createGenerateImageTool(enabledModels, providerKeys, 'user-1') + + await expect( + tool.execute( + 'call-5', + { + prompt: 'A sunset', + // eslint-disable-next-line @typescript-eslint/no-explicit-any + model: 'non-existent-model' as any, + aspectRatio: null, + size: null, + seed: null, + images: null, + mask: null, + outputFileName: null, + }, + new AbortController().signal, + ), + ).rejects.toThrow('Image model "non-existent-model" is not enabled') + }) +}) diff --git a/packages/agent/src/tools/generate-image.ts b/packages/agent/src/tools/generate-image.ts new file mode 100644 index 00000000..a4c5d23d --- /dev/null +++ b/packages/agent/src/tools/generate-image.ts @@ -0,0 +1,182 @@ +import { type AgentTool } from '@earendil-works/pi-agent-core' +import { EnabledMediaModel } from '@shumai/dtos' +import { mediaGenerationService } from '@shumai/core/src/media-generation/media-generation' +import { sanitizeFilename } from '@shumai/core/src/utils/filename' +import { Type, type Static, type TSchema } from 'typebox' +import * as fs from 'fs' +import * as path from 'path' +import { ulid } from 'ulid' +import { resolveS3MediaBuffer } from './download-asset' + +export function createGenerateImageTool( + enabledModels: EnabledMediaModel[], + providerKeys: Record, + userId?: string, +): AgentTool { + const modelIdentifiers = enabledModels.map((m) => `${m.provider}:${m.modelId}`) + const modelSchemas = + modelIdentifiers.length === 1 + ? Type.Literal(modelIdentifiers[0]) + : Type.Union( + modelIdentifiers.map((id) => Type.Literal(id)) as unknown as [ + TSchema, + TSchema, + ...TSchema[], + ], + ) + + const generateImageSchema = Type.Object( + { + prompt: Type.String({ + description: 'The text prompt describing the image to generate in detail.', + }), + model: Type.Union([modelSchemas, Type.Null()], { + description: `The image model to use, in "provider:modelId" format. Available enabled models: ${modelIdentifiers.join(', ')}. Pass null to use the first enabled model (${modelIdentifiers[0]}).`, + }), + outputFileName: Type.Union([ + Type.String({ + description: + 'Optional desired filename for the generated image (e.g. "cover.png"). Set to null for auto-generated name.', + }), + Type.Null(), + ]), + images: Type.Union([ + Type.Array(Type.String(), { + description: + 'Optional list of storage S3 keys of images to use as image-to-image or style reference. Call read_asset with s3KeyOnly: true to obtain the S3 key of an asset or video frame without loading its content into context. Set to null if not using.', + }), + Type.Null(), + ]), + mask: Type.Union([ + Type.String({ + description: + 'Optional storage S3 key of an inpainting mask image (white=inpaint, black=keep). Call read_asset with s3KeyOnly: true to obtain the S3 key. Set to null if not inpainting.', + }), + Type.Null(), + ]), + aspectRatio: Type.Union([ + Type.String({ + description: + 'Optional aspect ratio, e.g. "1:1", "16:9", "9:16", "4:3", "3:4", "2:3", "3:2". Set to null for default.', + }), + Type.Null(), + ]), + size: Type.Union([ + Type.String({ + description: + 'Optional target image dimensions, e.g. "1024x1024", "1536x1024". Set to null for default.', + }), + Type.Null(), + ]), + seed: Type.Union([ + Type.Integer({ + description: + 'Optional random seed for reproducible generations. Set to null for random generation.', + }), + Type.Null(), + ]), + }, + { additionalProperties: false }, + ) + + type GenerateImageParams = Static + + return { + name: 'generate_image', + label: 'Generate Image', + description: + 'Generate an image using a configured image model. Supports text-to-image, reference images (image-to-image using S3 keys from read_asset), and inpainting (using a mask image S3 key from read_asset). The generated file is saved in the local .pi/ directory.', + parameters: generateImageSchema, + execute: async (_toolCallId, params) => { + const p = params as GenerateImageParams + + const defaultModel = `${enabledModels[0].provider}:${enabledModels[0].modelId}` + const selected = p.model || defaultModel + const modelConfig = + enabledModels.find((m) => `${m.provider}:${m.modelId}` === selected) || + enabledModels.find((m) => m.modelId === selected) + + if (!modelConfig) { + throw new Error( + `Image model "${selected}" is not enabled. Available enabled models: ${modelIdentifiers.join(', ')}`, + ) + } + + const customKey = providerKeys[modelConfig.provider]?.apiKey + const apiKey = mediaGenerationService.resolveApiKey(modelConfig.provider, customKey) + if (!apiKey) { + throw new Error( + `API key for provider "${modelConfig.provider}" is not configured. Please configure it in settings.`, + ) + } + + let resolvedImages: Buffer[] | undefined + if (p.images && Array.isArray(p.images) && p.images.length > 0) { + resolvedImages = await Promise.all( + p.images.map(async (key: string) => { + const { buffer } = await resolveS3MediaBuffer(key, userId || '') + return buffer + }), + ) + } + + let resolvedMask: Buffer | undefined + if (p.mask) { + const { buffer } = await resolveS3MediaBuffer(p.mask, userId || '') + resolvedMask = buffer + } + + const { buffer, mimeType } = await mediaGenerationService.generateImage({ + provider: modelConfig.provider, + modelId: modelConfig.modelId, + apiKey, + prompt: p.prompt, + images: resolvedImages, + mask: resolvedMask, + aspectRatio: (p.aspectRatio as `${number}:${number}`) || undefined, + size: (p.size as `${number}x${number}`) || undefined, + seed: p.seed !== null && p.seed !== undefined ? p.seed : undefined, + }) + + const piDir = path.join(process.cwd(), '.pi') + if (!fs.existsSync(piDir)) { + fs.mkdirSync(piDir, { recursive: true }) + } + + const safeMime = mimeType || 'image/png' + let ext = '.png' + if (safeMime.includes('jpeg') || safeMime.includes('jpg')) ext = '.jpg' + else if (safeMime.includes('webp')) ext = '.webp' + + let filename: string + if (p.outputFileName) { + const safe = sanitizeFilename(p.outputFileName) + filename = safe.includes('.') ? safe : `${safe}${ext}` + } else { + filename = `generated_image_${ulid()}${ext}` + } + + const targetPath = path.join(piDir, filename) + const relativePath = path.join('.pi', filename) + fs.writeFileSync(targetPath, buffer) + + return { + content: [ + { + type: 'text', + text: `Successfully generated image using model "${modelConfig.modelId}" (${modelConfig.provider}). Saved to "${relativePath}". Size: ${(buffer.length / 1024).toFixed(1)} KB.`, + }, + ], + details: { + fileName: filename, + filePath: relativePath, + absolutePath: targetPath, + size: buffer.length, + mimeType, + provider: modelConfig.provider, + model: modelConfig.modelId, + }, + } + }, + } +} diff --git a/packages/agent/src/tools/generate-video.test.ts b/packages/agent/src/tools/generate-video.test.ts new file mode 100644 index 00000000..ce2fa3a7 --- /dev/null +++ b/packages/agent/src/tools/generate-video.test.ts @@ -0,0 +1,367 @@ +import { vi } from 'vitest' + +vi.mock('fs') + +import { describe, it, expect, beforeEach, afterEach } from 'vitest' +import { createGenerateVideoTool } from './generate-video' +import * as downloadAsset from './download-asset' +import { mediaGenerationService } from '@shumai/core/src/media-generation/media-generation' +import { EnabledMediaModel } from '@shumai/dtos' +import * as fs from 'fs' +import * as path from 'path' + +describe('generate_video tool', () => { + const enabledModels: EnabledMediaModel[] = [ + { + id: 'vm-1', + type: 'video', + provider: 'klingai', + modelId: 'kling-v1-standard', + name: 'Kling v1 Standard', + createdAt: '2026-01-01T00:00:00.000Z', + }, + { + id: 'vm-2', + type: 'video', + provider: 'fal', + modelId: 'kling-v1-standard', + name: 'Kling v1 Standard (fal)', + createdAt: '2026-01-01T00:00:00.000Z', + }, + { + id: 'vm-3', + type: 'video', + provider: 'google', + modelId: 'veo-2.0-generate-001', + name: 'Veo 2', + createdAt: '2026-01-01T00:00:00.000Z', + }, + ] + + const providerKeys = { + klingai: { apiKey: 'mock-kling-key' }, + fal: { apiKey: 'mock-fal-key' }, + google: { apiKey: 'mock-google-key' }, + } + + const piDir = path.join(process.cwd(), '.pi') + + beforeEach(() => { + vi.restoreAllMocks() + vi.spyOn(fs, 'existsSync').mockReturnValue(true) + vi.spyOn(fs, 'mkdirSync').mockImplementation(() => undefined) + vi.spyOn(fs, 'writeFileSync').mockImplementation(() => {}) + }) + + afterEach(() => { + vi.restoreAllMocks() + }) + + it('creates tool with correct metadata and provider-prefixed model schema', () => { + const tool = createGenerateVideoTool(enabledModels, providerKeys, 'user-1') + expect(tool.name).toBe('generate_video') + expect(tool.label).toBe('Generate Video') + expect(tool.description).toContain('Generate a video') + const modelDesc = (tool.parameters as { properties: { model: { description: string } } }) + .properties.model.description + expect(modelDesc).toContain('klingai:kling-v1-standard') + expect(modelDesc).toContain('fal:kling-v1-standard') + }) + + it('generates text_to_video successfully', async () => { + const tool = createGenerateVideoTool(enabledModels, providerKeys, 'user-1') + + const mockBuffer = Buffer.from('fake-mp4-video-stream') + const generateSpy = vi.spyOn(mediaGenerationService, 'generateVideo').mockResolvedValue({ + buffer: mockBuffer, + mimeType: 'video/mp4', + }) + const writeSpy = vi.spyOn(fs, 'writeFileSync').mockImplementation(() => {}) + + const result = await tool.execute( + 'call-vid-1', + { + mode: 'text_to_video', + model: 'klingai:kling-v1-standard', + outputFileName: 'test_nature.mp4', + textToVideoConfig: { + prompt: 'A gentle waterfall in a lush forest with cinematic lighting', + }, + imageToVideoConfig: null, + firstLastFrameConfig: null, + referenceToVideoConfig: null, + aspectRatio: '16:9', + resolution: null, + duration: 5, + fps: 24, + generateAudio: null, + seed: 123, + }, + new AbortController().signal, + ) + + expect(generateSpy).toHaveBeenCalledWith( + expect.objectContaining({ + provider: 'klingai', + modelId: 'kling-v1-standard', + apiKey: 'mock-kling-key', + mode: 'text_to_video', + prompt: 'A gentle waterfall in a lush forest with cinematic lighting', + aspectRatio: '16:9', + duration: 5, + fps: 24, + seed: 123, + }), + ) + + const expectedPath = path.join(piDir, 'test_nature.mp4') + expect(writeSpy).toHaveBeenCalledWith(expectedPath, mockBuffer) + + const textContent = result.content[0] + expect(textContent.type).toBe('text') + if (textContent.type === 'text') { + expect(textContent.text).toContain('Successfully generated video') + expect(textContent.text).toContain('.pi/test_nature.mp4') + } + expect(result.details).toMatchObject({ + fileName: 'test_nature.mp4', + provider: 'klingai', + model: 'kling-v1-standard', + mode: 'text_to_video', + }) + }) + + it('disambiguates identical model IDs across different providers', async () => { + const tool = createGenerateVideoTool(enabledModels, providerKeys, 'user-1') + + const generateSpy = vi.spyOn(mediaGenerationService, 'generateVideo').mockResolvedValue({ + buffer: Buffer.from('video-bytes'), + mimeType: 'video/mp4', + }) + + // Select fal:kling-v1-standard + await tool.execute( + 'call-fal', + { + mode: 'text_to_video', + model: 'fal:kling-v1-standard', + outputFileName: null, + textToVideoConfig: { prompt: 'A soaring eagle' }, + imageToVideoConfig: null, + firstLastFrameConfig: null, + referenceToVideoConfig: null, + aspectRatio: null, + resolution: null, + duration: null, + fps: null, + generateAudio: null, + seed: null, + }, + new AbortController().signal, + ) + + expect(generateSpy).toHaveBeenLastCalledWith( + expect.objectContaining({ + provider: 'fal', + modelId: 'kling-v1-standard', + apiKey: 'mock-fal-key', + }), + ) + + // Select klingai:kling-v1-standard + await tool.execute( + 'call-klingai', + { + mode: 'text_to_video', + model: 'klingai:kling-v1-standard', + outputFileName: null, + textToVideoConfig: { prompt: 'A roaring tiger' }, + imageToVideoConfig: null, + firstLastFrameConfig: null, + referenceToVideoConfig: null, + aspectRatio: null, + resolution: null, + duration: null, + fps: null, + generateAudio: null, + seed: null, + }, + new AbortController().signal, + ) + + expect(generateSpy).toHaveBeenLastCalledWith( + expect.objectContaining({ + provider: 'klingai', + modelId: 'kling-v1-standard', + apiKey: 'mock-kling-key', + }), + ) + }) + + it('generates image_to_video using resolveS3MediaBuffer', async () => { + const tool = createGenerateVideoTool(enabledModels, providerKeys, 'user-1') + + const generateSpy = vi.spyOn(mediaGenerationService, 'generateVideo').mockResolvedValue({ + buffer: Buffer.from('video-bytes'), + mimeType: 'video/mp4', + }) + + const resolverSpy = vi.spyOn(downloadAsset, 'resolveS3MediaBuffer').mockResolvedValue({ + buffer: Buffer.from('resolved-image-data'), + mimeType: 'image/png', + }) + + await tool.execute( + 'call-vid-2', + { + mode: 'image_to_video', + model: 'klingai:kling-v1-standard', + outputFileName: 'animate_cat.mp4', + textToVideoConfig: null, + imageToVideoConfig: { + image: 'files/ast-1/img.png', + prompt: 'Cat starts blinking and looks to the side', + }, + firstLastFrameConfig: null, + referenceToVideoConfig: null, + aspectRatio: null, + resolution: null, + duration: null, + fps: null, + generateAudio: null, + seed: null, + }, + new AbortController().signal, + ) + + expect(resolverSpy).toHaveBeenCalledWith('files/ast-1/img.png', 'user-1') + expect(generateSpy).toHaveBeenCalledWith( + expect.objectContaining({ + mode: 'image_to_video', + image: Buffer.from('resolved-image-data'), + prompt: 'Cat starts blinking and looks to the side', + }), + ) + }) + + it('generates first_last_frame using resolveS3MediaBuffer', async () => { + const tool = createGenerateVideoTool(enabledModels, providerKeys, 'user-1') + + const generateSpy = vi.spyOn(mediaGenerationService, 'generateVideo').mockResolvedValue({ + buffer: Buffer.from('transition-video'), + mimeType: 'video/mp4', + }) + + vi.spyOn(downloadAsset, 'resolveS3MediaBuffer').mockImplementation(async (key: string) => ({ + buffer: Buffer.from(`frame-data-${key}`), + mimeType: 'image/png', + })) + + await tool.execute( + 'call-vid-3', + { + mode: 'first_last_frame', + model: 'klingai:kling-v1-standard', + outputFileName: 'transition.mp4', + textToVideoConfig: null, + imageToVideoConfig: null, + firstLastFrameConfig: { + firstFrame: 'files/ast-1/start.png', + lastFrame: 'files/ast-2/end.png', + prompt: 'Smooth morph from sunrise to night', + }, + referenceToVideoConfig: null, + aspectRatio: null, + resolution: null, + duration: null, + fps: null, + generateAudio: null, + seed: null, + }, + new AbortController().signal, + ) + + expect(generateSpy).toHaveBeenCalledWith( + expect.objectContaining({ + mode: 'first_last_frame', + firstFrame: Buffer.from('frame-data-files/ast-1/start.png'), + lastFrame: Buffer.from('frame-data-files/ast-2/end.png'), + prompt: 'Smooth morph from sunrise to night', + }), + ) + }) + + it('generates reference_to_video using resolveS3MediaBuffer', async () => { + const tool = createGenerateVideoTool(enabledModels, providerKeys, 'user-1') + + const generateSpy = vi.spyOn(mediaGenerationService, 'generateVideo').mockResolvedValue({ + buffer: Buffer.from('ref-video'), + mimeType: 'video/mp4', + }) + + vi.spyOn(downloadAsset, 'resolveS3MediaBuffer').mockImplementation(async (key: string) => ({ + buffer: Buffer.from(`ref-data-${key}`), + mimeType: 'image/png', + })) + + await tool.execute( + 'call-vid-4', + { + mode: 'reference_to_video', + model: 'klingai:kling-v1-standard', + outputFileName: 'reference_output.mp4', + textToVideoConfig: null, + imageToVideoConfig: null, + firstLastFrameConfig: null, + referenceToVideoConfig: { + references: ['files/ast-1/ref1.png', 'files/ast-2/ref2.png'], + prompt: 'Generate an anime dance following these characters', + }, + aspectRatio: null, + resolution: null, + duration: null, + fps: null, + generateAudio: null, + seed: null, + }, + new AbortController().signal, + ) + + expect(generateSpy).toHaveBeenCalledWith( + expect.objectContaining({ + mode: 'reference_to_video', + inputReferences: [ + Buffer.from('ref-data-files/ast-1/ref1.png'), + Buffer.from('ref-data-files/ast-2/ref2.png'), + ], + prompt: 'Generate an anime dance following these characters', + }), + ) + }) + + it('fails gracefully when API key is missing', async () => { + const tool = createGenerateVideoTool(enabledModels, {}, 'user-1') + + await expect( + tool.execute( + 'call-vid-5', + { + mode: 'text_to_video', + model: 'klingai:kling-v1-standard', + outputFileName: null, + textToVideoConfig: { prompt: 'A simple video' }, + imageToVideoConfig: null, + firstLastFrameConfig: null, + referenceToVideoConfig: null, + aspectRatio: null, + resolution: null, + duration: null, + fps: null, + generateAudio: null, + seed: null, + }, + new AbortController().signal, + ), + ).rejects.toThrow('API key for provider "klingai" is not configured') + }) +}) diff --git a/packages/agent/src/tools/generate-video.ts b/packages/agent/src/tools/generate-video.ts new file mode 100644 index 00000000..abc29d7b --- /dev/null +++ b/packages/agent/src/tools/generate-video.ts @@ -0,0 +1,302 @@ +import { type AgentTool } from '@earendil-works/pi-agent-core' +import { EnabledMediaModel } from '@shumai/dtos' +import { mediaGenerationService } from '@shumai/core/src/media-generation/media-generation' +import { sanitizeFilename } from '@shumai/core/src/utils/filename' +import { Type, type Static, type TSchema } from 'typebox' +import * as fs from 'fs' +import * as path from 'path' +import { ulid } from 'ulid' +import { resolveS3MediaBuffer } from './download-asset' + +export function createGenerateVideoTool( + enabledModels: EnabledMediaModel[], + providerKeys: Record, + userId?: string, +): AgentTool { + const modelIdentifiers = enabledModels.map((m) => `${m.provider}:${m.modelId}`) + const modelSchemas = + modelIdentifiers.length === 1 + ? Type.Literal(modelIdentifiers[0]) + : Type.Union( + modelIdentifiers.map((id) => Type.Literal(id)) as unknown as [ + TSchema, + TSchema, + ...TSchema[], + ], + ) + + const generateVideoSchema = Type.Object( + { + mode: Type.Union( + [ + Type.Literal('text_to_video'), + Type.Literal('image_to_video'), + Type.Literal('first_last_frame'), + Type.Literal('reference_to_video'), + ], + { + description: + 'The video generation mode: "text_to_video", "image_to_video", "first_last_frame", or "reference_to_video".', + }, + ), + model: Type.Union([modelSchemas, Type.Null()], { + description: `The video model to use, in "provider:modelId" format. Available enabled models: ${modelIdentifiers.join(', ')}. Pass null to use the first enabled model (${modelIdentifiers[0]}).`, + }), + outputFileName: Type.Union([ + Type.String({ + description: + 'Optional desired filename for the generated video (e.g. "intro.mp4"). Set to null for auto-generated name.', + }), + Type.Null(), + ]), + textToVideoConfig: Type.Union([ + Type.Object( + { + prompt: Type.String({ + description: 'Text prompt describing the desired video scene, action, and motion.', + }), + }, + { additionalProperties: false }, + ), + Type.Null(), + ]), + imageToVideoConfig: Type.Union([ + Type.Object( + { + image: Type.String({ + description: + 'Storage S3 key of the image to animate. Call read_asset with s3KeyOnly: true to obtain the S3 key of an image asset or video frame without loading its content into context.', + }), + prompt: Type.Union([ + Type.String({ + description: 'Optional motion prompt describing how the image should animate.', + }), + Type.Null(), + ]), + }, + { additionalProperties: false }, + ), + Type.Null(), + ]), + firstLastFrameConfig: Type.Union([ + Type.Object( + { + firstFrame: Type.Union([ + Type.String({ + description: + 'Storage S3 key of the starting frame image. Call read_asset with s3KeyOnly: true to obtain the S3 key.', + }), + Type.Null(), + ]), + lastFrame: Type.Union([ + Type.String({ + description: + 'Storage S3 key of the ending frame image. Call read_asset with s3KeyOnly: true to obtain the S3 key.', + }), + Type.Null(), + ]), + prompt: Type.Union([ + Type.String({ description: 'Optional prompt describing the transition.' }), + Type.Null(), + ]), + }, + { additionalProperties: false }, + ), + Type.Null(), + ]), + referenceToVideoConfig: Type.Union([ + Type.Object( + { + references: Type.Array(Type.String(), { + description: + 'List of storage S3 keys for style/motion/character reference images. Call read_asset with s3KeyOnly: true to obtain the S3 keys.', + }), + prompt: Type.Union([ + Type.String({ description: 'Prompt describing the video to generate.' }), + Type.Null(), + ]), + }, + { additionalProperties: false }, + ), + Type.Null(), + ]), + aspectRatio: Type.Union([ + Type.String({ + description: + 'Optional aspect ratio: "16:9", "9:16", "1:1", or "adaptive", or null for default.', + }), + Type.Null(), + ]), + resolution: Type.Union([ + Type.String({ + description: 'Optional target video resolution, e.g. "1280x720", or null for default.', + }), + Type.Null(), + ]), + duration: Type.Union([ + Type.Integer({ description: 'Optional duration in seconds, or null for default.' }), + Type.Null(), + ]), + fps: Type.Union([ + Type.Integer({ description: 'Optional frames per second, or null for default.' }), + Type.Null(), + ]), + generateAudio: Type.Union([ + Type.Boolean({ + description: 'Whether to generate audio alongside video, or null for default.', + }), + Type.Null(), + ]), + seed: Type.Union([ + Type.Integer({ + description: + 'Optional random seed for reproducible video generation, or null for random.', + }), + Type.Null(), + ]), + }, + { additionalProperties: false }, + ) + + type GenerateVideoParams = Static + + return { + name: 'generate_video', + label: 'Generate Video', + description: + 'Generate a video using a configured video model. Supports text-to-video, image-to-video (using an S3 image key from read_asset), first/last frame (using S3 image keys from read_asset), and reference-to-video (using S3 image keys from read_asset). The generated file is saved in the local .pi/ directory.', + parameters: generateVideoSchema, + execute: async (_toolCallId, params) => { + const p = params as GenerateVideoParams + + const defaultModel = `${enabledModels[0].provider}:${enabledModels[0].modelId}` + const selected = p.model || defaultModel + const modelConfig = + enabledModels.find((m) => `${m.provider}:${m.modelId}` === selected) || + enabledModels.find((m) => m.modelId === selected) + + if (!modelConfig) { + throw new Error( + `Video model "${selected}" is not enabled. Available enabled models: ${modelIdentifiers.join(', ')}`, + ) + } + + const customKey = providerKeys[modelConfig.provider]?.apiKey + const apiKey = mediaGenerationService.resolveApiKey(modelConfig.provider, customKey) + if (!apiKey) { + throw new Error( + `API key for provider "${modelConfig.provider}" is not configured. Please configure it in settings.`, + ) + } + + let promptText = '' + let resolvedImage: Buffer | undefined + let resolvedFirstFrame: Buffer | undefined + let resolvedLastFrame: Buffer | undefined + let resolvedReferences: Buffer[] | undefined + + if (p.mode === 'text_to_video') { + if (!p.textToVideoConfig?.prompt) { + throw new Error('textToVideoConfig.prompt is required when mode is "text_to_video"') + } + promptText = p.textToVideoConfig.prompt + } else if (p.mode === 'image_to_video') { + if (!p.imageToVideoConfig?.image) { + throw new Error('imageToVideoConfig.image is required when mode is "image_to_video"') + } + const { buffer } = await resolveS3MediaBuffer(p.imageToVideoConfig.image, userId || '') + resolvedImage = buffer + promptText = p.imageToVideoConfig.prompt || '' + } else if (p.mode === 'first_last_frame') { + if (!p.firstLastFrameConfig?.firstFrame && !p.firstLastFrameConfig?.lastFrame) { + throw new Error( + 'At least one of firstFrame or lastFrame is required in firstLastFrameConfig', + ) + } + if (p.firstLastFrameConfig.firstFrame) { + const { buffer } = await resolveS3MediaBuffer( + p.firstLastFrameConfig.firstFrame, + userId || '', + ) + resolvedFirstFrame = buffer + } + if (p.firstLastFrameConfig.lastFrame) { + const { buffer } = await resolveS3MediaBuffer( + p.firstLastFrameConfig.lastFrame, + userId || '', + ) + resolvedLastFrame = buffer + } + promptText = p.firstLastFrameConfig.prompt || '' + } else if (p.mode === 'reference_to_video') { + if ( + !p.referenceToVideoConfig?.references || + p.referenceToVideoConfig.references.length === 0 + ) { + throw new Error('referenceToVideoConfig.references list is required') + } + resolvedReferences = await Promise.all( + p.referenceToVideoConfig.references.map(async (ref: string) => { + const { buffer } = await resolveS3MediaBuffer(ref, userId || '') + return buffer + }), + ) + promptText = p.referenceToVideoConfig.prompt || '' + } + + const { buffer, mimeType } = await mediaGenerationService.generateVideo({ + provider: modelConfig.provider, + modelId: modelConfig.modelId, + apiKey, + mode: p.mode, + prompt: promptText, + image: resolvedImage, + firstFrame: resolvedFirstFrame, + lastFrame: resolvedLastFrame, + inputReferences: resolvedReferences, + aspectRatio: (p.aspectRatio as `${number}:${number}` | 'adaptive') || undefined, + resolution: (p.resolution as `${number}x${number}`) || undefined, + duration: p.duration !== null && p.duration !== undefined ? p.duration : undefined, + fps: p.fps !== null && p.fps !== undefined ? p.fps : undefined, + generateAudio: p.generateAudio !== null ? p.generateAudio : undefined, + seed: p.seed !== null && p.seed !== undefined ? p.seed : undefined, + }) + + const piDir = path.join(process.cwd(), '.pi') + if (!fs.existsSync(piDir)) { + fs.mkdirSync(piDir, { recursive: true }) + } + + let filename: string + if (p.outputFileName) { + const safe = sanitizeFilename(p.outputFileName) + filename = safe.endsWith('.mp4') ? safe : `${safe}.mp4` + } else { + filename = `generated_video_${ulid()}.mp4` + } + + const targetPath = path.join(piDir, filename) + const relativePath = path.join('.pi', filename) + fs.writeFileSync(targetPath, buffer) + + return { + content: [ + { + type: 'text', + text: `Successfully generated video using model "${modelConfig.modelId}" (${modelConfig.provider}) in mode "${p.mode}". Saved to "${relativePath}". Size: ${(buffer.length / (1024 * 1024)).toFixed(2)} MB.`, + }, + ], + details: { + fileName: filename, + filePath: relativePath, + absolutePath: targetPath, + size: buffer.length, + mimeType, + provider: modelConfig.provider, + model: modelConfig.modelId, + mode: p.mode, + }, + } + }, + } +} diff --git a/packages/agent/src/tools/read-asset.test.ts b/packages/agent/src/tools/read-asset.test.ts index 23c067e8..d36ce07a 100644 --- a/packages/agent/src/tools/read-asset.test.ts +++ b/packages/agent/src/tools/read-asset.test.ts @@ -541,4 +541,104 @@ describe('readAssetTool', () => { expect(result.details.key).toBe('proxy/diagram_v2.webp') }) }) + + describe('s3KeyOnly mode', () => { + it('returns only S3 key and MIME in text for image assets without fetching S3 buffer or attaching base64 image', async () => { + vi.mocked(authzService.hasPermission).mockResolvedValue() + vi.mocked(prisma.asset.findUnique).mockResolvedValue({ + id: 'img-1', + name: 'photo.png', + mediaType: 'image/png', + storageKey: { key: 'raw/photo.png' }, + media: { + proxyType: 'image', + imageTranscodes: [{ key: 'proxy/photo.webp' }], + }, + } as unknown as Asset) + + const tool = createReadAssetTool('user-1') + const result = await tool.execute('call-1', { + assetId: 'img-1', + annotationId: null, + s3KeyOnly: true, + imageConfig: null, + videoConfig: null, + docConfig: null, + }) + + expect(s3Service.getObject).not.toHaveBeenCalled() + expect(result.content.length).toBe(1) + expect(result.content[0].type).toBe('text') + expect((result.content[0] as { type: 'text'; text: string }).text).toBe( + 'Image asset "photo.png" (ID: img-1, MIME: image/webp, S3 Key: "proxy/photo.webp")', + ) + expect(result.details.key).toBe('proxy/photo.webp') + }) + + it('returns only frame S3 keys and MIME in text for video assets without fetching S3 buffers or attaching base64 images', async () => { + vi.mocked(authzService.hasPermission).mockResolvedValue() + vi.mocked(prisma.asset.findUnique).mockResolvedValue({ + id: 'vid-1', + name: 'clip.mp4', + mediaType: 'video/mp4', + projectId: 'project-1', + media: { proxyType: 'video' }, + } as unknown as Asset) + + vi.mocked(prisma.workflowTask.create).mockResolvedValue({ + id: 'task-shot', + } as unknown as WorkflowTask) + vi.mocked(workflowService.executeWait).mockResolvedValue({ + id: 'task-shot', + output: { + screenshots: [{ key: 'screenshots/shot1.webp', timestamp: 1.5 }], + }, + } as unknown as WorkflowTask) + + const tool = createReadAssetTool('user-1') + const result = await tool.execute('call-1', { + assetId: 'vid-1', + annotationId: null, + s3KeyOnly: true, + imageConfig: null, + videoConfig: { start: 1.5, end: 1.5, count: 1 }, + docConfig: null, + }) + + expect(s3Service.getObject).not.toHaveBeenCalled() + expect(result.content.length).toBe(1) + expect(result.content[0].type).toBe('text') + const text = (result.content[0] as { type: 'text'; text: string }).text + expect(text).toContain('- Frame at 1.5s (S3 Key: "screenshots/shot1.webp", MIME: image/webp)') + expect(result.details.keys).toEqual(['screenshots/shot1.webp']) + }) + + it('returns only document S3 key and MIME in text for text mode without fetching S3 buffer', async () => { + vi.mocked(authzService.hasPermission).mockResolvedValue() + vi.mocked(prisma.asset.findUnique).mockResolvedValue({ + id: 'doc-md', + name: 'notes.md', + mediaType: 'text/markdown', + storageKey: { key: 'raw/notes.md' }, + media: { proxyType: 'pdf' }, + } as unknown as Asset) + + const tool = createReadAssetTool('user-1') + const result = await tool.execute('call-1', { + assetId: 'doc-md', + annotationId: null, + s3KeyOnly: true, + imageConfig: null, + videoConfig: null, + docConfig: { mode: 'text', startPage: null, endPage: null }, + }) + + expect(s3Service.getObject).not.toHaveBeenCalled() + expect(result.content.length).toBe(1) + expect(result.content[0].type).toBe('text') + expect((result.content[0] as { type: 'text'; text: string }).text).toBe( + 'Document "notes.md" (ID: doc-md, MIME: text/markdown, S3 Key: "raw/notes.md")', + ) + }) + }) }) diff --git a/packages/agent/src/tools/read-asset.ts b/packages/agent/src/tools/read-asset.ts index 2e53d798..135069d9 100644 --- a/packages/agent/src/tools/read-asset.ts +++ b/packages/agent/src/tools/read-asset.ts @@ -6,6 +6,7 @@ import { s3Service } from '@shumai/core/src/s3/s3' import { workflowService } from '@shumai/workflow-core' import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz' import { resolveAnnotationsById } from './annotation-resolver' +import { getFileMimeType } from '@shumai/core/src/utils/file-mime' export const readAssetSchema = Type.Object( { @@ -19,6 +20,13 @@ export const readAssetSchema = Type.Object( }), Type.Null(), ]), + s3KeyOnly: Type.Optional( + Type.Boolean({ + description: + 'When true, returns only the storage S3 key(s) and MIME types of the asset/frames without attaching base64 image or text content to the agent context. Use this to obtain S3 keys for generate_image or generate_video references without consuming context tokens.', + default: false, + }), + ), imageConfig: Type.Union([ Type.Object( {}, @@ -144,7 +152,7 @@ export function createReadAssetTool(userId: string): AgentTool { - const { assetId, annotationId, videoConfig, docConfig } = params + const { assetId, annotationId, s3KeyOnly, videoConfig, docConfig } = params if (!userId) { throw new Error('User ID is required for authorization.') @@ -196,38 +204,39 @@ export function createReadAssetTool(userId: string): AgentTool 0) { + const task = await prisma.workflowTask.create({ + data: { + assetId: asset.id, projectId: asset.projectId || 'none', - imageAnnotation: { - annotations, + type: WorkflowTaskType.transcode_image_annotation, + status: WorkflowTaskStatus.pending, + payload: { + projectId: asset.projectId || 'none', + imageAnnotation: { + annotations, + }, }, }, - }, - }) + }) - const completedTask = await workflowService.executeWait(task) - // eslint-disable-next-line @typescript-eslint/no-explicit-any -- transcode image annotation task output - const output = completedTask.output as any - if (output?.key) { - keyToUse = output.key - } else { - throw new Error('Image annotation transcode workflow failed to output S3 key.') + const completedTask = await workflowService.executeWait(task) + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- transcode image annotation task output + const output = completedTask.output as any + if (output?.key) { + keyToUse = output.key + mimeType = 'image/webp' + } else { + throw new Error('Image annotation transcode workflow failed to output S3 key.') + } } } - const { buffer, contentType } = await s3Service.getObject(bucket, keyToUse) - const mimeType = - contentType && contentType !== 'application/octet-stream' ? contentType : 'image/webp' const downloadUrl = await s3Service.presign( bucket, keyToUse, @@ -236,17 +245,27 @@ export function createReadAssetTool(userId: string): AgentTool = [ - { + const content: Array = [] + + if (s3KeyOnly) { + content.push({ type: 'text', - text: `Image asset "${asset.name}" (ID: ${asset.id}):\n- S3 Key: "${keyToUse}"`, - }, - { + text: `Image asset "${asset.name}" (ID: ${asset.id}, MIME: ${mimeType}, S3 Key: "${keyToUse}")`, + }) + } else { + const { buffer, contentType } = await s3Service.getObject(bucket, keyToUse) + const actualMimeType = + contentType && contentType !== 'application/octet-stream' ? contentType : mimeType + content.push({ + type: 'text', + text: `Image asset "${asset.name}" (ID: ${asset.id}, MIME: ${actualMimeType}, S3 Key: "${keyToUse}")`, + }) + content.push({ type: 'image', data: buffer.toString('base64'), - mimeType, - }, - ] + mimeType: actualMimeType, + }) + } return { content, @@ -330,9 +349,6 @@ export function createReadAssetTool(userId: string): AgentTool> @@ -69,6 +70,7 @@ const apiRoute = new Hono<{ Variables: { user: User } }>() .route('/', watermarkTemplateRoute) .route('/', quotaRoute) .route('/', kanbanRoute) + .route('/', mediaGenerationRoute) app.route('/files', s3Route) diff --git a/packages/api/src/media-generation.test.ts b/packages/api/src/media-generation.test.ts new file mode 100644 index 00000000..bd5d8d97 --- /dev/null +++ b/packages/api/src/media-generation.test.ts @@ -0,0 +1,134 @@ +import { describe, expect, it, vi, beforeEach } from 'vitest' +import { Hono } from 'hono' +import mediaGenerationRoute from './media-generation' +import { mediaGenerationService } from '@shumai/core/src/media-generation/media-generation' +import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz' + +vi.mock('@shumai/core/src/authz/authz') +vi.mock('@shumai/core/src/media-generation/media-generation') + +describe('media-generation api', () => { + const app = new Hono<{ Variables: { user: { id: string; name: string } } }>() + .use('*', async (c, next) => { + c.set('user', { id: 'user1', name: 'Test User' }) + await next() + }) + .route('/', mediaGenerationRoute) + + beforeEach(() => { + vi.restoreAllMocks() + vi.mocked(authzService.hasPermission).mockResolvedValue(undefined) + }) + + it('GET /teams/:teamId/media-generation returns settings', async () => { + vi.mocked(mediaGenerationService.getSettings).mockResolvedValue({ + providers: [ + { + provider: 'openai', + defaultEnvKey: 'OPENAI_API_KEY', + apiKeyConfigured: true, + status: 'configured_env', + supportedTypes: ['image'], + }, + ], + enabledModels: [], + }) + + const res = await app.request('/teams/t1/media-generation') + + expect(res.status).toBe(200) + const data = await res.json() + expect(data.providers).toHaveLength(1) + expect(data.providers[0].provider).toBe('openai') + expect(authzService.hasPermission).toHaveBeenCalledWith({ + user: expect.anything(), + permission: Permission.Admin, + type: ResourceType.Team, + id: 't1', + }) + expect(mediaGenerationService.getSettings).toHaveBeenCalledWith('t1') + }) + + it('PUT /teams/:teamId/media-generation/providers/:provider updates api key', async () => { + vi.mocked(mediaGenerationService.updateProviderApiKey).mockResolvedValue(undefined) + + const res = await app.request('/teams/t1/media-generation/providers/openai', { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ apiKey: 'sk-new-key' }), + }) + + expect(res.status).toBe(200) + const data = await res.json() + expect(data.success).toBe(true) + expect(authzService.hasPermission).toHaveBeenCalledWith({ + user: expect.anything(), + permission: Permission.Admin, + type: ResourceType.Team, + id: 't1', + }) + expect(mediaGenerationService.updateProviderApiKey).toHaveBeenCalledWith( + 't1', + 'openai', + 'sk-new-key', + ) + }) + + it('POST /teams/:teamId/media-generation/models adds an enabled model', async () => { + vi.mocked(mediaGenerationService.addEnabledModel).mockResolvedValue({ + id: 'm1', + type: 'image', + provider: 'openai', + modelId: 'dall-e-3', + name: 'DALL-E 3', + createdAt: new Date().toISOString(), + }) + + const res = await app.request('/teams/t1/media-generation/models', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + type: 'image', + provider: 'openai', + modelId: 'dall-e-3', + name: 'DALL-E 3', + }), + }) + + expect(res.status).toBe(201) + const data = await res.json() + expect(data.id).toBe('m1') + expect(data.modelId).toBe('dall-e-3') + expect(authzService.hasPermission).toHaveBeenCalledWith({ + user: expect.anything(), + permission: Permission.Admin, + type: ResourceType.Team, + id: 't1', + }) + expect(mediaGenerationService.addEnabledModel).toHaveBeenCalledWith('t1', { + type: 'image', + provider: 'openai', + modelId: 'dall-e-3', + name: 'DALL-E 3', + }) + }) + + it('DELETE /teams/:teamId/media-generation/models/:modelId removes an enabled model', async () => { + vi.mocked(mediaGenerationService.removeEnabledModel).mockResolvedValue(undefined) + + const res = await app.request('/teams/t1/media-generation/models/m1', { + method: 'DELETE', + }) + + expect(res.status).toBe(200) + const data = await res.json() + expect(data.success).toBe(true) + expect(authzService.hasPermission).toHaveBeenCalledWith({ + user: expect.anything(), + permission: Permission.Admin, + type: ResourceType.Team, + id: 't1', + }) + expect(mediaGenerationService.removeEnabledModel).toHaveBeenCalledWith('t1', 'm1') + }) +}) diff --git a/packages/api/src/media-generation.ts b/packages/api/src/media-generation.ts new file mode 100644 index 00000000..79135f90 --- /dev/null +++ b/packages/api/src/media-generation.ts @@ -0,0 +1,97 @@ +import { zValidator } from '@hono/zod-validator' +import { Hono } from 'hono' +import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz' +import { mediaGenerationService } from '@shumai/core/src/media-generation/media-generation' +import { + createEnabledMediaModelSchema, + getCuratedMediaModelsQuerySchema, + updateMediaProviderApiKeySchema, +} from '@shumai/dtos' +import type { Prisma } from '@shumai/db' + +type User = Prisma.UserGetPayload> + +const route = new Hono<{ Variables: { user: User } }>() + .get('/teams/:teamId/media-generation', async (c) => { + const teamId = c.req.param('teamId') + const user = c.get('user') + + await authzService.hasPermission({ + user, + permission: Permission.Admin, + type: ResourceType.Team, + id: teamId, + }) + + const settings = await mediaGenerationService.getSettings(teamId) + return c.json(settings) + }) + + .put( + '/teams/:teamId/media-generation/providers/:provider', + zValidator('json', updateMediaProviderApiKeySchema), + async (c) => { + const teamId = c.req.param('teamId') + const provider = c.req.param('provider') + const user = c.get('user') + const body = c.req.valid('json') + + await authzService.hasPermission({ + user, + permission: Permission.Admin, + type: ResourceType.Team, + id: teamId, + }) + + await mediaGenerationService.updateProviderApiKey(teamId, provider, body.apiKey) + return c.json({ success: true }) + }, + ) + + .post( + '/teams/:teamId/media-generation/models', + zValidator('json', createEnabledMediaModelSchema), + async (c) => { + const teamId = c.req.param('teamId') + const user = c.get('user') + const body = c.req.valid('json') + + await authzService.hasPermission({ + user, + permission: Permission.Admin, + type: ResourceType.Team, + id: teamId, + }) + + const model = await mediaGenerationService.addEnabledModel(teamId, body) + return c.json(model, 201) + }, + ) + + .get( + '/teams/:teamId/media-generation/models/curated', + zValidator('query', getCuratedMediaModelsQuerySchema), + async (c) => { + const { provider, type } = c.req.valid('query') + const models = mediaGenerationService.getCuratedModels(provider, type) + return c.json(models) + }, + ) + + .delete('/teams/:teamId/media-generation/models/:modelId', async (c) => { + const teamId = c.req.param('teamId') + const modelId = c.req.param('modelId') + const user = c.get('user') + + await authzService.hasPermission({ + user, + permission: Permission.Admin, + type: ResourceType.Team, + id: teamId, + }) + + await mediaGenerationService.removeEnabledModel(teamId, modelId) + return c.json({ success: true }) + }) + +export default route diff --git a/packages/core/package.json b/packages/core/package.json index 4c7980aa..5dcd3684 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -6,6 +6,24 @@ "main": "./src/index.ts", "types": "./src/index.ts", "dependencies": { + "@ai-sdk/alibaba": "2.0.38", + "@ai-sdk/amazon-bedrock": "5.0.67", + "@ai-sdk/azure": "4.0.53", + "@ai-sdk/black-forest-labs": "2.0.34", + "@ai-sdk/bytedance": "2.0.36", + "@ai-sdk/deepinfra": "3.0.40", + "@ai-sdk/fal": "3.0.34", + "@ai-sdk/fireworks": "3.0.43", + "@ai-sdk/google": "4.0.57", + "@ai-sdk/google-vertex": "5.0.69", + "@ai-sdk/klingai": "4.0.35", + "@ai-sdk/luma": "3.0.34", + "@ai-sdk/minimax": "3.0.21", + "@ai-sdk/openai": "4.0.51", + "@ai-sdk/prodia": "2.0.34", + "@ai-sdk/replicate": "3.0.34", + "@ai-sdk/togetherai": "3.0.41", + "@ai-sdk/xai": "4.0.49", "@earendil-works/pi-agent-core": "0.82.1", "@earendil-works/pi-ai": "0.82.1", "@modelcontextprotocol/client": "2.0.0", @@ -13,6 +31,7 @@ "@shumai/dtos": "workspace:*", "@sinclair/typebox": "0.34.49", "adm-zip": "0.5.17", + "ai": "7.0.84", "better-auth": "1.6.11", "csv-parse": "7.0.1", "date-fns": "4.4.0", diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index e59fd22f..6760a3cb 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -28,3 +28,4 @@ export * from './gotenberg/gotenberg' export * from './mcp/mcp-service' export * from './quota/quota-service' export * from './kanban/kanban' +export * from './media-generation/media-generation' diff --git a/packages/core/src/media-generation/media-generation.test.ts b/packages/core/src/media-generation/media-generation.test.ts new file mode 100644 index 00000000..a1f5f270 --- /dev/null +++ b/packages/core/src/media-generation/media-generation.test.ts @@ -0,0 +1,212 @@ +import { prisma } from '@shumai/db' +import { setupTestDbHooks } from '@shumai/db/test' +import { mediaGenerationService, BUILTIN_MEDIA_PROVIDERS } from './media-generation' +import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest' + +describe('MediaGenerationService', () => { + setupTestDbHooks() + + let teamId: string + const originalEnv = process.env + + beforeEach(async () => { + process.env = { ...originalEnv } + const team = await prisma.team.create({ + data: { + name: 'Media Team', + settings: { + transcode: { videoStrategy: 'best_match' }, + }, + }, + }) + teamId = team.id + }) + + afterEach(() => { + process.env = originalEnv + vi.restoreAllMocks() + }) + + it('should list all 18 providers in getSettings', async () => { + const settings = await mediaGenerationService.getSettings(teamId) + expect(settings.providers).toHaveLength(18) + expect(settings.enabledModels).toEqual([]) + + const openai = settings.providers.find((p) => p.provider === 'openai') + expect(openai).toBeDefined() + expect(openai?.defaultEnvKey).toBe('OPENAI_API_KEY') + expect(openai?.supportedTypes).toEqual(['image']) + }) + + it('should detect API key from environment variable', async () => { + process.env.OPENAI_API_KEY = 'sk-test-env-key' + const settings = await mediaGenerationService.getSettings(teamId) + const openai = settings.providers.find((p) => p.provider === 'openai') + + expect(openai?.apiKeyConfigured).toBe(true) + expect(openai?.status).toBe('configured_env') + expect(openai?.customApiKeyOrEnv).toBeUndefined() + }) + + it('should allow setting custom API key and custom env variable', async () => { + // 1. Set literal API key + await mediaGenerationService.updateProviderApiKey(teamId, 'openai', 'sk-literal-key') + let settings = await mediaGenerationService.getSettings(teamId) + let openai = settings.providers.find((p) => p.provider === 'openai') + + expect(openai?.apiKeyConfigured).toBe(true) + expect(openai?.status).toBe('configured_custom') + expect(openai?.customApiKeyOrEnv).toBe('••••••••') + + // 2. Set custom ENV var name + process.env.MY_CUSTOM_OPENAI_ENV = 'sk-resolved-custom-env' + await mediaGenerationService.updateProviderApiKey(teamId, 'openai', 'MY_CUSTOM_OPENAI_ENV') + settings = await mediaGenerationService.getSettings(teamId) + openai = settings.providers.find((p) => p.provider === 'openai') + + expect(openai?.apiKeyConfigured).toBe(true) + expect(openai?.status).toBe('configured_custom') + expect(openai?.customApiKeyOrEnv).toBe('••••••••') + expect(mediaGenerationService.resolveApiKey('openai', 'MY_CUSTOM_OPENAI_ENV')).toBe( + 'sk-resolved-custom-env', + ) + + // 3. Clear custom key + await mediaGenerationService.updateProviderApiKey(teamId, 'openai', '') + delete process.env.OPENAI_API_KEY + settings = await mediaGenerationService.getSettings(teamId) + openai = settings.providers.find((p) => p.provider === 'openai') + + expect(openai?.apiKeyConfigured).toBe(false) + expect(openai?.status).toBe('not_configured') + expect(openai?.customApiKeyOrEnv).toBeUndefined() + }) + + it('should add enabled models and reject invalid configurations', async () => { + // Valid model addition + const added = await mediaGenerationService.addEnabledModel(teamId, { + type: 'image', + provider: 'openai', + modelId: 'dall-e-3', + name: 'DALL-E 3 High Quality', + }) + + expect(added.id).toBeDefined() + expect(added.type).toBe('image') + expect(added.provider).toBe('openai') + expect(added.modelId).toBe('dall-e-3') + expect(added.name).toBe('DALL-E 3 High Quality') + + const settings = await mediaGenerationService.getSettings(teamId) + expect(settings.enabledModels).toHaveLength(1) + expect(settings.enabledModels[0].id).toBe(added.id) + + // Rejects duplicate model addition + await expect( + mediaGenerationService.addEnabledModel(teamId, { + type: 'image', + provider: 'openai', + modelId: 'dall-e-3', + }), + ).rejects.toThrow('already enabled') + + // Rejects unsupported type for provider (OpenAI does not support video) + await expect( + mediaGenerationService.addEnabledModel(teamId, { + type: 'video', + provider: 'openai', + modelId: 'some-video-model', + }), + ).rejects.toThrow('does not support video') + + // Rejects unknown provider + await expect( + mediaGenerationService.addEnabledModel(teamId, { + type: 'image', + provider: 'unknown-provider', + modelId: 'model-1', + }), + ).rejects.toThrow('Unknown media provider') + }) + + it('should remove enabled models', async () => { + const model = await mediaGenerationService.addEnabledModel(teamId, { + type: 'image', + provider: 'fal', + modelId: 'fal-ai/flux/dev', + }) + + let settings = await mediaGenerationService.getSettings(teamId) + expect(settings.enabledModels).toHaveLength(1) + + await mediaGenerationService.removeEnabledModel(teamId, model.id) + settings = await mediaGenerationService.getSettings(teamId) + expect(settings.enabledModels).toHaveLength(0) + + // Throws if model does not exist + await expect(mediaGenerationService.removeEnabledModel(teamId, 'non-existent')).rejects.toThrow( + 'not found', + ) + }) + + it('should return valid models only when provider has active API key', async () => { + // Add an image model for OpenAI and a video model for Google + await mediaGenerationService.addEnabledModel(teamId, { + type: 'image', + provider: 'openai', + modelId: 'dall-e-3', + }) + await mediaGenerationService.addEnabledModel(teamId, { + type: 'video', + provider: 'google', + modelId: 'veo-2.0-generate-001', + }) + + // Neither key is configured yet + delete process.env.OPENAI_API_KEY + delete process.env.GEMINI_API_KEY + let valid = await mediaGenerationService.getValidModels(teamId) + expect(valid.imageModels).toHaveLength(0) + expect(valid.videoModels).toHaveLength(0) + + // Configure OpenAI key + process.env.OPENAI_API_KEY = 'sk-test' + valid = await mediaGenerationService.getValidModels(teamId) + expect(valid.imageModels).toHaveLength(1) + expect(valid.imageModels[0].modelId).toBe('dall-e-3') + expect(valid.videoModels).toHaveLength(0) + + // Configure Google key + process.env.GEMINI_API_KEY = 'gemini-key' + valid = await mediaGenerationService.getValidModels(teamId) + expect(valid.imageModels).toHaveLength(1) + expect(valid.videoModels).toHaveLength(1) + expect(valid.videoModels[0].modelId).toBe('veo-2.0-generate-001') + }) + + it('should instantiate image and video models across all supported providers', () => { + for (const [providerKey, def] of Object.entries(BUILTIN_MEDIA_PROVIDERS)) { + if (def.supportedTypes.includes('image')) { + const imageModel = def.curatedModels.find((m) => m.type === 'image')! + const instance = mediaGenerationService.getImageModel( + providerKey, + imageModel.modelId, + 'mock-api-key', + ) + expect(instance).toBeDefined() + expect(instance.modelId).toBe(imageModel.modelId) + } + + if (def.supportedTypes.includes('video')) { + const videoModel = def.curatedModels.find((m) => m.type === 'video')! + const instance = mediaGenerationService.getVideoModel( + providerKey, + videoModel.modelId, + 'mock-api-key', + ) + expect(instance).toBeDefined() + expect(instance.modelId).toBe(videoModel.modelId) + } + } + }) +}) diff --git a/packages/core/src/media-generation/media-generation.ts b/packages/core/src/media-generation/media-generation.ts new file mode 100644 index 00000000..cfa9c3ae --- /dev/null +++ b/packages/core/src/media-generation/media-generation.ts @@ -0,0 +1,843 @@ +import { prisma } from '@shumai/db' +import { + CreateEnabledMediaModelRequest, + CuratedMediaModel, + EnabledMediaModel, + MediaGenerationSettingsResponse, + MediaModelType, + MediaProviderStatus, +} from '@shumai/dtos' +import { ulid } from 'ulid' +import { HTTPException } from 'hono/http-exception' +import { generateImage as aiGenerateImage, experimental_generateVideo as aiGenerateVideo } from 'ai' +import { createOpenAI } from '@ai-sdk/openai' +import { createGoogleGenerativeAI } from '@ai-sdk/google' +import { createGoogleVertex } from '@ai-sdk/google-vertex' +import { createXai } from '@ai-sdk/xai' +import { createFal } from '@ai-sdk/fal' +import { createReplicate } from '@ai-sdk/replicate' +import { createBlackForestLabs } from '@ai-sdk/black-forest-labs' +import { createKlingAI } from '@ai-sdk/klingai' +import { createTogetherAI } from '@ai-sdk/togetherai' +import { createFireworks } from '@ai-sdk/fireworks' +import { createDeepInfra } from '@ai-sdk/deepinfra' +import { createLuma } from '@ai-sdk/luma' +import { createAmazonBedrock } from '@ai-sdk/amazon-bedrock' +import { createAlibaba } from '@ai-sdk/alibaba' +import { createByteDance } from '@ai-sdk/bytedance' +import { createMiniMax } from '@ai-sdk/minimax' +import { createProdia } from '@ai-sdk/prodia' +import { createAzure } from '@ai-sdk/azure' + +export interface CuratedModelItem { + modelId: string + name: string + type: MediaModelType +} + +export interface BuiltinMediaProviderDef { + provider: string + displayName: string + defaultEnvKey: string + supportedTypes: MediaModelType[] + curatedModels: CuratedModelItem[] +} + +export const BUILTIN_MEDIA_PROVIDERS: Record = { + openai: { + provider: 'openai', + displayName: 'OpenAI', + defaultEnvKey: 'OPENAI_API_KEY', + supportedTypes: ['image'], + curatedModels: [ + { modelId: 'dall-e-3', name: 'DALL-E 3', type: 'image' }, + { modelId: 'gpt-image-2', name: 'GPT Image 2', type: 'image' }, + { modelId: 'dall-e-2', name: 'DALL-E 2', type: 'image' }, + { modelId: 'gpt-image-1.5', name: 'GPT Image 1.5', type: 'image' }, + { modelId: 'gpt-image-1', name: 'GPT Image 1', type: 'image' }, + { modelId: 'gpt-image-1-mini', name: 'GPT Image 1 Mini', type: 'image' }, + { modelId: 'chatgpt-image-latest', name: 'ChatGPT Image Latest', type: 'image' }, + ], + }, + google: { + provider: 'google', + displayName: 'Google', + defaultEnvKey: 'GEMINI_API_KEY', + supportedTypes: ['image', 'video'], + curatedModels: [ + { modelId: 'gemini-2.5-flash-image', name: 'Gemini 2.5 Flash Image', type: 'image' }, + { modelId: 'gemini-3-pro-image-preview', name: 'Gemini 3 Pro Image Preview', type: 'image' }, + { + modelId: 'gemini-3.1-flash-image-preview', + name: 'Gemini 3.1 Flash Image Preview', + type: 'image', + }, + { modelId: 'veo-3.1-generate', name: 'Veo 3.1', type: 'video' }, + { modelId: 'veo-3.1-generate-preview', name: 'Veo 3.1 Preview', type: 'video' }, + { modelId: 'veo-3.1-fast-generate-preview', name: 'Veo 3.1 Fast Preview', type: 'video' }, + { modelId: 'veo-3.0-generate-001', name: 'Veo 3.0', type: 'video' }, + { modelId: 'veo-3.0-fast-generate-001', name: 'Veo 3.0 Fast', type: 'video' }, + { modelId: 'veo-2.0-generate-001', name: 'Veo 2.0', type: 'video' }, + ], + }, + 'google-vertex': { + provider: 'google-vertex', + displayName: 'Google Vertex', + defaultEnvKey: 'GOOGLE_CLOUD_API_KEY', + supportedTypes: ['image', 'video'], + curatedModels: [ + { modelId: 'gemini-2.5-flash-image', name: 'Gemini 2.5 Flash Image', type: 'image' }, + { modelId: 'gemini-3-pro-image-preview', name: 'Gemini 3 Pro Image Preview', type: 'image' }, + { modelId: 'veo-3.1-generate-001', name: 'Veo 3.1', type: 'video' }, + { modelId: 'veo-3.1-fast-generate-001', name: 'Veo 3.1 Fast', type: 'video' }, + { modelId: 'veo-3.0-generate-001', name: 'Veo 3.0', type: 'video' }, + { modelId: 'veo-2.0-generate-001', name: 'Veo 2.0', type: 'video' }, + ], + }, + xai: { + provider: 'xai', + displayName: 'xAI', + defaultEnvKey: 'XAI_API_KEY', + supportedTypes: ['image', 'video'], + curatedModels: [ + { modelId: 'grok-imagine-image', name: 'Grok Imagine Image', type: 'image' }, + { modelId: 'grok-imagine-image-pro', name: 'Grok Imagine Image Pro', type: 'image' }, + { modelId: 'grok-imagine-video', name: 'Grok Imagine Video', type: 'video' }, + { modelId: 'grok-imagine-video-1.5', name: 'Grok Imagine Video 1.5', type: 'video' }, + ], + }, + fal: { + provider: 'fal', + displayName: 'Fal', + defaultEnvKey: 'FAL_KEY', + supportedTypes: ['image', 'video'], + curatedModels: [ + { modelId: 'fal-ai/flux/dev', name: 'FLUX Dev', type: 'image' }, + { modelId: 'fal-ai/flux/schnell', name: 'FLUX Schnell', type: 'image' }, + { modelId: 'fal-ai/flux-pro/v1.1-ultra', name: 'FLUX Pro 1.1 Ultra', type: 'image' }, + { modelId: 'fal-ai/flux-pro/v1.1', name: 'FLUX Pro 1.1', type: 'image' }, + { modelId: 'fal-ai/flux-pro/kontext', name: 'FLUX Pro Kontext', type: 'image' }, + { modelId: 'fal-ai/recraft/v3/text-to-image', name: 'Recraft v3', type: 'image' }, + { modelId: 'fal-ai/ideogram/character', name: 'Ideogram Character', type: 'image' }, + { modelId: 'fal-ai/imagen4/preview', name: 'Imagen 4 Preview', type: 'image' }, + { modelId: 'fal-ai/luma-photon', name: 'Luma Photon', type: 'image' }, + { modelId: 'fal-ai/wan/v2.2-5b/text-to-image', name: 'Wan 2.2 5B', type: 'image' }, + { modelId: 'luma-ray-2', name: 'Luma Ray 2', type: 'video' }, + { modelId: 'luma-ray-2-flash', name: 'Luma Ray 2 Flash', type: 'video' }, + { modelId: 'luma-dream-machine', name: 'Luma Dream Machine', type: 'video' }, + { modelId: 'minimax-video', name: 'MiniMax Video', type: 'video' }, + { modelId: 'hunyuan-video', name: 'Hunyuan Video', type: 'video' }, + ], + }, + replicate: { + provider: 'replicate', + displayName: 'Replicate', + defaultEnvKey: 'REPLICATE_API_TOKEN', + supportedTypes: ['image', 'video'], + curatedModels: [ + { modelId: 'black-forest-labs/flux-1.1-pro', name: 'FLUX 1.1 Pro', type: 'image' }, + { + modelId: 'black-forest-labs/flux-1.1-pro-ultra', + name: 'FLUX 1.1 Pro Ultra', + type: 'image', + }, + { modelId: 'black-forest-labs/flux-schnell', name: 'FLUX Schnell', type: 'image' }, + { modelId: 'black-forest-labs/flux-dev', name: 'FLUX Dev', type: 'image' }, + { modelId: 'recraft-ai/recraft-v3', name: 'Recraft v3', type: 'image' }, + { modelId: 'ideogram-ai/ideogram-v2', name: 'Ideogram v2', type: 'image' }, + { modelId: 'stability-ai/stable-diffusion-3.5-large', name: 'SD 3.5 Large', type: 'image' }, + { modelId: 'luma/photon', name: 'Luma Photon', type: 'image' }, + { modelId: 'minimax/video-01', name: 'MiniMax Video-01', type: 'video' }, + ], + }, + 'black-forest-labs': { + provider: 'black-forest-labs', + displayName: 'Black Forest Labs', + defaultEnvKey: 'BFL_API_KEY', + supportedTypes: ['image', 'video'], + curatedModels: [ + { modelId: 'flux-kontext-pro', name: 'FLUX Kontext Pro', type: 'image' }, + { modelId: 'flux-kontext-max', name: 'FLUX Kontext Max', type: 'image' }, + { modelId: 'flux-pro-1.1-ultra', name: 'FLUX Pro 1.1 Ultra', type: 'image' }, + { modelId: 'flux-pro-1.1', name: 'FLUX Pro 1.1', type: 'image' }, + { modelId: 'flux-pro-1.0-fill', name: 'FLUX Pro 1.0 Fill', type: 'image' }, + { modelId: 'flux-3-video', name: 'FLUX 3 Video', type: 'video' }, + ], + }, + klingai: { + provider: 'klingai', + displayName: 'Kling AI', + defaultEnvKey: 'KLINGAI_API_KEY', + supportedTypes: ['video'], + curatedModels: [ + { modelId: 'kling-v3.0-t2v', name: 'Kling v3.0 T2V', type: 'video' }, + { modelId: 'kling-v3.0-i2v', name: 'Kling v3.0 I2V', type: 'video' }, + { modelId: 'kling-v3.0-motion-control', name: 'Kling v3.0 Motion Control', type: 'video' }, + { modelId: 'kling-v2.6-t2v', name: 'Kling v2.6 T2V', type: 'video' }, + { modelId: 'kling-v2.6-i2v', name: 'Kling v2.6 I2V', type: 'video' }, + { modelId: 'kling-v2.6-motion-control', name: 'Kling v2.6 Motion Control', type: 'video' }, + { modelId: 'kling-v2.5-turbo-t2v', name: 'Kling v2.5 Turbo T2V', type: 'video' }, + { modelId: 'kling-v2.1-master-t2v', name: 'Kling v2.1 Master T2V', type: 'video' }, + ], + }, + togetherai: { + provider: 'togetherai', + displayName: 'Together.ai', + defaultEnvKey: 'TOGETHER_API_KEY', + supportedTypes: ['image'], + curatedModels: [ + { modelId: 'black-forest-labs/FLUX.1-schnell', name: 'FLUX.1 Schnell', type: 'image' }, + { modelId: 'black-forest-labs/FLUX.1-dev', name: 'FLUX.1 Dev', type: 'image' }, + { modelId: 'black-forest-labs/FLUX.1.1-pro', name: 'FLUX.1.1 Pro', type: 'image' }, + { + modelId: 'black-forest-labs/FLUX.1-kontext-pro', + name: 'FLUX.1 Kontext Pro', + type: 'image', + }, + { modelId: 'stabilityai/stable-diffusion-xl-base-1.0', name: 'SDXL Base 1.0', type: 'image' }, + ], + }, + fireworks: { + provider: 'fireworks', + displayName: 'Fireworks', + defaultEnvKey: 'FIREWORKS_API_KEY', + supportedTypes: ['image'], + curatedModels: [ + { + modelId: 'accounts/fireworks/models/flux-1-dev-fp8', + name: 'FLUX.1 Dev FP8', + type: 'image', + }, + { + modelId: 'accounts/fireworks/models/flux-1-schnell-fp8', + name: 'FLUX.1 Schnell FP8', + type: 'image', + }, + { + modelId: 'accounts/fireworks/models/flux-kontext-pro', + name: 'FLUX Kontext Pro', + type: 'image', + }, + { + modelId: 'accounts/fireworks/models/playground-v2-5-1024px-aesthetic', + name: 'Playground v2.5', + type: 'image', + }, + ], + }, + deepinfra: { + provider: 'deepinfra', + displayName: 'DeepInfra', + defaultEnvKey: 'DEEPINFRA_API_KEY', + supportedTypes: ['image'], + curatedModels: [ + { modelId: 'black-forest-labs/FLUX-1.1-pro', name: 'FLUX 1.1 Pro', type: 'image' }, + { modelId: 'black-forest-labs/FLUX-1-schnell', name: 'FLUX 1 Schnell', type: 'image' }, + { modelId: 'black-forest-labs/FLUX-1-dev', name: 'FLUX 1 Dev', type: 'image' }, + { modelId: 'stabilityai/sd3.5', name: 'SD 3.5', type: 'image' }, + ], + }, + luma: { + provider: 'luma', + displayName: 'Luma', + defaultEnvKey: 'LUMA_API_KEY', + supportedTypes: ['image'], + curatedModels: [ + { modelId: 'photon-1', name: 'Photon 1', type: 'image' }, + { modelId: 'photon-flash-1', name: 'Photon Flash 1', type: 'image' }, + ], + }, + 'amazon-bedrock': { + provider: 'amazon-bedrock', + displayName: 'Amazon Bedrock', + defaultEnvKey: 'AWS_ACCESS_KEY_ID', + supportedTypes: ['image'], + curatedModels: [ + { modelId: 'amazon.nova-canvas-v1:0', name: 'Amazon Nova Canvas v1', type: 'image' }, + ], + }, + alibaba: { + provider: 'alibaba', + displayName: 'Alibaba', + defaultEnvKey: 'ALIBABA_API_KEY', + supportedTypes: ['video'], + curatedModels: [ + { modelId: 'wan2.6-t2v', name: 'Wan 2.6 T2V', type: 'video' }, + { modelId: 'wan2.6-i2v', name: 'Wan 2.6 I2V', type: 'video' }, + { modelId: 'wan2.6-r2v', name: 'Wan 2.6 R2V', type: 'video' }, + { modelId: 'wan2.7-t2v', name: 'Wan 2.7 T2V', type: 'video' }, + { modelId: 'wan2.7-r2v', name: 'Wan 2.7 R2V', type: 'video' }, + { modelId: 'wan3.0-video', name: 'Wan 3.0 Video', type: 'video' }, + ], + }, + bytedance: { + provider: 'bytedance', + displayName: 'ByteDance', + defaultEnvKey: 'ARK_API_KEY', + supportedTypes: ['image', 'video'], + curatedModels: [ + { modelId: 'seedream-5-0-260128', name: 'Seedream 5.0', type: 'image' }, + { modelId: 'dola-seedream-5-0-pro-260628', name: 'Seedream 5.0 Pro', type: 'image' }, + { modelId: 'seedream-4-5-251128', name: 'Seedream 4.5', type: 'image' }, + { modelId: 'dreamina-seedance-2-0-260128', name: 'Seedance 2.0', type: 'video' }, + { modelId: 'dreamina-seedance-2-0-fast-260128', name: 'Seedance 2.0 Fast', type: 'video' }, + { modelId: 'seedance-1-5-pro-251215', name: 'Seedance 1.5 Pro', type: 'video' }, + { modelId: 'seedance-1-0-pro-fast-251015', name: 'Seedance 1.0 Pro Fast', type: 'video' }, + ], + }, + minimax: { + provider: 'minimax', + displayName: 'MiniMax', + defaultEnvKey: 'MINIMAX_API_KEY', + supportedTypes: ['video'], + curatedModels: [ + { modelId: 'MiniMax-H3', name: 'MiniMax H3', type: 'video' }, + { modelId: 'MiniMax-H3-Max', name: 'MiniMax H3 Max', type: 'video' }, + ], + }, + prodia: { + provider: 'prodia', + displayName: 'Prodia', + defaultEnvKey: 'PRODIA_TOKEN', + supportedTypes: ['image', 'video'], + curatedModels: [ + { + modelId: 'inference.flux.schnell.txt2img.v2', + name: 'FLUX Schnell', + type: 'image', + }, + { + modelId: 'inference.flux-fast.schnell.txt2img.v2', + name: 'FLUX Fast Schnell', + type: 'image', + }, + { + modelId: 'inference.wan2-2.lightning.txt2vid.v0', + name: 'Wan 2.2 Lightning T2V', + type: 'video', + }, + { + modelId: 'inference.wan2-2.lightning.img2vid.v0', + name: 'Wan 2.2 Lightning I2V', + type: 'video', + }, + ], + }, + azure: { + provider: 'azure', + displayName: 'Azure OpenAI', + defaultEnvKey: 'AZURE_API_KEY', + supportedTypes: ['image'], + curatedModels: [ + { modelId: 'dall-e-3', name: 'DALL-E 3', type: 'image' }, + { modelId: 'dall-e-2', name: 'DALL-E 2', type: 'image' }, + ], + }, +} + +export interface GenerateImageServiceParams { + provider: string + modelId: string + apiKey: string + prompt: string + images?: Array + mask?: string | Uint8Array | Buffer + aspectRatio?: `${number}:${number}` + size?: `${number}x${number}` + seed?: number +} + +export interface GenerateVideoServiceParams { + provider: string + modelId: string + apiKey: string + mode: 'text_to_video' | 'image_to_video' | 'first_last_frame' | 'reference_to_video' + prompt?: string + image?: string | Uint8Array | Buffer + firstFrame?: string | Uint8Array | Buffer + lastFrame?: string | Uint8Array | Buffer + inputReferences?: Array + aspectRatio?: `${number}:${number}` | 'adaptive' + resolution?: `${number}x${number}` + duration?: number + fps?: number + generateAudio?: boolean + seed?: number +} + +export class MediaGenerationService { + constructor(private readonly prismaClient: typeof prisma = prisma) {} + + resolveApiKey(provider: string, customApiKeyOrEnv?: string): string | undefined { + if (customApiKeyOrEnv && customApiKeyOrEnv.trim()) { + const trimmed = customApiKeyOrEnv.trim() + // If it matches an environment variable name, use that env var value + if (process.env[trimmed]) { + return process.env[trimmed] + } + return trimmed + } + const def = BUILTIN_MEDIA_PROVIDERS[provider] + if (def?.defaultEnvKey && process.env[def.defaultEnvKey]) { + return process.env[def.defaultEnvKey] + } + return undefined + } + + getCuratedModels(provider?: string, type?: 'image' | 'video'): CuratedMediaModel[] { + const list: CuratedMediaModel[] = [] + for (const [p, def] of Object.entries(BUILTIN_MEDIA_PROVIDERS)) { + if (provider && p !== provider) continue + for (const m of def.curatedModels) { + if (type && m.type !== type) continue + list.push({ + modelId: m.modelId, + name: m.name, + type: m.type, + }) + } + } + return list + } + + async getSettings(teamId: string): Promise { + const team = await this.prismaClient.team.findUnique({ + where: { id: teamId }, + select: { settings: true }, + }) + if (!team) { + throw new HTTPException(404, { message: 'Team not found' }) + } + + const mediaSettings = team.settings?.mediaGeneration || {} + const customProviders = mediaSettings.providers || {} + const enabledModels = (mediaSettings.enabledModels || []).map((m) => ({ + id: m.id, + type: m.type, + provider: m.provider, + modelId: m.modelId, + name: m.name || '', + createdAt: m.createdAt, + })) + + const providers: MediaProviderStatus[] = Object.values(BUILTIN_MEDIA_PROVIDERS).map((def) => { + const customConfig = customProviders[def.provider] + const customKey = customConfig?.apiKey?.trim() + const resolvedKey = this.resolveApiKey(def.provider, customKey) + + let status: MediaProviderStatus['status'] = 'not_configured' + if (customKey) { + status = 'configured_custom' + } else if (resolvedKey) { + status = 'configured_env' + } + + return { + provider: def.provider, + defaultEnvKey: def.defaultEnvKey, + apiKeyConfigured: !!resolvedKey, + status, + customApiKeyOrEnv: customKey ? '••••••••' : undefined, + supportedTypes: def.supportedTypes, + } + }) + + return { + providers, + enabledModels, + } + } + + async updateProviderApiKey(teamId: string, provider: string, apiKey?: string): Promise { + if (!BUILTIN_MEDIA_PROVIDERS[provider]) { + throw new HTTPException(400, { message: `Unknown media provider: "${provider}"` }) + } + + const team = await this.prismaClient.team.findUnique({ + where: { id: teamId }, + select: { settings: true }, + }) + if (!team) { + throw new HTTPException(404, { message: 'Team not found' }) + } + + const currentSettings = team.settings || { transcode: { videoStrategy: 'best_match' } } + const mediaGen = currentSettings.mediaGeneration || {} + const providers = mediaGen.providers || {} + + if (apiKey && apiKey.trim()) { + providers[provider] = { apiKey: apiKey.trim() } + } else { + delete providers[provider] + } + + mediaGen.providers = providers + currentSettings.mediaGeneration = mediaGen + + await this.prismaClient.team.update({ + where: { id: teamId }, + data: { settings: currentSettings }, + }) + } + + async addEnabledModel( + teamId: string, + data: CreateEnabledMediaModelRequest, + ): Promise { + const providerDef = BUILTIN_MEDIA_PROVIDERS[data.provider] + if (!providerDef) { + throw new HTTPException(400, { message: `Unknown media provider: "${data.provider}"` }) + } + + if (!providerDef.supportedTypes.includes(data.type)) { + throw new HTTPException(400, { + message: `Provider "${data.provider}" does not support ${data.type} generation`, + }) + } + + const team = await this.prismaClient.team.findUnique({ + where: { id: teamId }, + select: { settings: true }, + }) + if (!team) { + throw new HTTPException(404, { message: 'Team not found' }) + } + + const currentSettings = team.settings || { transcode: { videoStrategy: 'best_match' } } + const mediaGen = currentSettings.mediaGeneration || {} + const enabledModels = mediaGen.enabledModels || [] + + const alreadyExists = enabledModels.some( + (m) => m.provider === data.provider && m.modelId === data.modelId && m.type === data.type, + ) + if (alreadyExists) { + throw new HTTPException(400, { + message: `Model "${data.modelId}" is already enabled for provider "${data.provider}"`, + }) + } + + const newModel: PrismaJson.EnabledMediaModelConfig = { + id: ulid(), + type: data.type, + provider: data.provider, + modelId: data.modelId, + name: data.name || '', + createdAt: new Date().toISOString(), + } + + enabledModels.push(newModel) + mediaGen.enabledModels = enabledModels + currentSettings.mediaGeneration = mediaGen + + await this.prismaClient.team.update({ + where: { id: teamId }, + data: { settings: currentSettings }, + }) + + return { + id: newModel.id, + type: newModel.type, + provider: newModel.provider, + modelId: newModel.modelId, + name: newModel.name || '', + createdAt: newModel.createdAt, + } + } + + async removeEnabledModel(teamId: string, modelId: string): Promise { + const team = await this.prismaClient.team.findUnique({ + where: { id: teamId }, + select: { settings: true }, + }) + if (!team) { + throw new HTTPException(404, { message: 'Team not found' }) + } + + const currentSettings = team.settings || { transcode: { videoStrategy: 'best_match' } } + const mediaGen = currentSettings.mediaGeneration || {} + const enabledModels = mediaGen.enabledModels || [] + + const nextModels = enabledModels.filter((m) => m.id !== modelId) + if (nextModels.length === enabledModels.length) { + throw new HTTPException(404, { message: `Enabled model "${modelId}" not found` }) + } + + mediaGen.enabledModels = nextModels + currentSettings.mediaGeneration = mediaGen + + await this.prismaClient.team.update({ + where: { id: teamId }, + data: { settings: currentSettings }, + }) + } + + async getValidModels(teamId: string): Promise<{ + imageModels: EnabledMediaModel[] + videoModels: EnabledMediaModel[] + providerKeys: Record + }> { + const team = await this.prismaClient.team.findUnique({ + where: { id: teamId }, + select: { settings: true }, + }) + const providerKeys = team?.settings?.mediaGeneration?.providers || {} + const { providers, enabledModels } = await this.getSettings(teamId) + const activeProviderMap = new Map() + for (const p of providers) { + activeProviderMap.set(p.provider, p.apiKeyConfigured) + } + + const imageModels: EnabledMediaModel[] = [] + const videoModels: EnabledMediaModel[] = [] + + for (const model of enabledModels) { + if (activeProviderMap.get(model.provider)) { + if (model.type === 'image') { + imageModels.push(model) + } else if (model.type === 'video') { + videoModels.push(model) + } + } + } + + return { imageModels, videoModels, providerKeys } + } + + getImageModel(provider: string, modelId: string, apiKey: string) { + switch (provider) { + case 'openai': + // AI SDK provider image method is typed with literal unions, while Shumai supports dynamic model IDs from team configuration + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return createOpenAI({ apiKey }).image(modelId as any) + case 'google': + // AI SDK provider image method is typed with literal unions, while Shumai supports dynamic model IDs from team configuration + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return createGoogleGenerativeAI({ apiKey }).image(modelId as any) + case 'google-vertex': + // AI SDK provider image method is typed with literal unions, while Shumai supports dynamic model IDs from team configuration + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return createGoogleVertex({ apiKey }).image(modelId as any) + case 'xai': + // AI SDK provider image method is typed with literal unions, while Shumai supports dynamic model IDs from team configuration + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return createXai({ apiKey }).image(modelId as any) + case 'fal': + // AI SDK provider image method is typed with literal unions, while Shumai supports dynamic model IDs from team configuration + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return createFal({ apiKey }).image(modelId as any) + case 'replicate': + // AI SDK provider image method is typed with literal unions, while Shumai supports dynamic model IDs from team configuration + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return createReplicate({ apiToken: apiKey }).image(modelId as any) + case 'black-forest-labs': + // AI SDK provider image method is typed with literal unions, while Shumai supports dynamic model IDs from team configuration + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return createBlackForestLabs({ apiKey }).image(modelId as any) + case 'togetherai': + // AI SDK provider image method is typed with literal unions, while Shumai supports dynamic model IDs from team configuration + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return createTogetherAI({ apiKey }).image(modelId as any) + case 'fireworks': + // AI SDK provider image method is typed with literal unions, while Shumai supports dynamic model IDs from team configuration + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return createFireworks({ apiKey }).image(modelId as any) + case 'deepinfra': + // AI SDK provider image method is typed with literal unions, while Shumai supports dynamic model IDs from team configuration + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return createDeepInfra({ apiKey }).image(modelId as any) + case 'luma': + // AI SDK provider image method is typed with literal unions, while Shumai supports dynamic model IDs from team configuration + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return createLuma({ apiKey }).image(modelId as any) + case 'amazon-bedrock': + // AI SDK provider image method is typed with literal unions, while Shumai supports dynamic model IDs from team configuration + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return createAmazonBedrock({ apiKey }).image(modelId as any) + case 'bytedance': + // AI SDK provider image method is typed with literal unions, while Shumai supports dynamic model IDs from team configuration + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return createByteDance({ apiKey }).image(modelId as any) + case 'prodia': + // AI SDK provider image method is typed with literal unions, while Shumai supports dynamic model IDs from team configuration + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return createProdia({ apiKey }).image(modelId as any) + case 'azure': + // AI SDK provider image method is typed with literal unions, while Shumai supports dynamic model IDs from team configuration + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return createAzure({ apiKey }).image(modelId as any) + default: + throw new Error(`Unsupported image provider: "${provider}"`) + } + } + + getVideoModel(provider: string, modelId: string, apiKey: string) { + switch (provider) { + case 'google': + // AI SDK provider video method is typed with literal unions, while Shumai supports dynamic model IDs from team configuration + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return createGoogleGenerativeAI({ apiKey }).video(modelId as any) + case 'google-vertex': + // AI SDK provider video method is typed with literal unions, while Shumai supports dynamic model IDs from team configuration + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return createGoogleVertex({ apiKey }).video(modelId as any) + case 'xai': + // AI SDK provider video method is typed with literal unions, while Shumai supports dynamic model IDs from team configuration + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return createXai({ apiKey }).video(modelId as any) + case 'fal': + // AI SDK provider video method is typed with literal unions, while Shumai supports dynamic model IDs from team configuration + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return createFal({ apiKey }).video(modelId as any) + case 'replicate': + // AI SDK provider video method is typed with literal unions, while Shumai supports dynamic model IDs from team configuration + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return createReplicate({ apiToken: apiKey }).video(modelId as any) + case 'black-forest-labs': + // AI SDK provider video method is typed with literal unions, while Shumai supports dynamic model IDs from team configuration + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return createBlackForestLabs({ apiKey }).video(modelId as any) + case 'klingai': + // AI SDK provider video method is typed with literal unions, while Shumai supports dynamic model IDs from team configuration + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return createKlingAI({ apiKey }).video(modelId as any) + case 'alibaba': + // AI SDK provider video method is typed with literal unions, while Shumai supports dynamic model IDs from team configuration + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return createAlibaba({ apiKey }).video(modelId as any) + case 'bytedance': + // AI SDK provider video method is typed with literal unions, while Shumai supports dynamic model IDs from team configuration + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return createByteDance({ apiKey }).video(modelId as any) + case 'minimax': + // AI SDK provider video method is typed with literal unions, while Shumai supports dynamic model IDs from team configuration + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return createMiniMax({ apiKey }).video(modelId as any) + case 'prodia': + // AI SDK provider video method is typed with literal unions, while Shumai supports dynamic model IDs from team configuration + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return createProdia({ apiKey }).video(modelId as any) + default: + throw new Error(`Unsupported video provider: "${provider}"`) + } + } + + async generateImage(params: GenerateImageServiceParams): Promise<{ + buffer: Buffer + mimeType: string + warnings?: unknown + }> { + const model = this.getImageModel(params.provider, params.modelId, params.apiKey) + + type GenerateImageOptions = Parameters[0] + let promptPayload: GenerateImageOptions['prompt'] = params.prompt + if ((params.images && params.images.length > 0) || params.mask) { + promptPayload = { + text: params.prompt, + images: params.images || [], + mask: params.mask, + } as unknown as GenerateImageOptions['prompt'] + } + + const { image, warnings } = await aiGenerateImage({ + model, + prompt: promptPayload, + aspectRatio: params.aspectRatio, + size: params.size, + seed: params.seed, + }) + + let buffer: Buffer + if (image.uint8Array) { + buffer = Buffer.from(image.uint8Array) + } else if (image.base64) { + buffer = Buffer.from(image.base64, 'base64') + } else { + throw new Error('No image binary data returned by provider') + } + + const imageInfo = image as unknown as { mediaType?: string; mimeType?: string } + const mimeType = imageInfo.mediaType || imageInfo.mimeType || 'image/png' + + return { + buffer, + mimeType, + warnings, + } + } + + async generateVideo(params: GenerateVideoServiceParams): Promise<{ + buffer: Buffer + mimeType: string + warnings?: unknown + }> { + const model = this.getVideoModel(params.provider, params.modelId, params.apiKey) + + type GenerateVideoOptions = Parameters[0] + let promptPayload: GenerateVideoOptions['prompt'] = params.prompt || '' + let frameImages: GenerateVideoOptions['frameImages'] = undefined + let inputReferences: GenerateVideoOptions['inputReferences'] = undefined + + if (params.mode === 'image_to_video' && params.image) { + promptPayload = { + text: params.prompt || '', + image: params.image, + } as unknown as GenerateVideoOptions['prompt'] + } else if (params.mode === 'first_last_frame') { + const frames: NonNullable = [] + if (params.firstFrame) { + frames.push({ + image: params.firstFrame, + frameType: 'first_frame', + } as unknown as NonNullable[number]) + } + if (params.lastFrame) { + frames.push({ + image: params.lastFrame, + frameType: 'last_frame', + } as unknown as NonNullable[number]) + } + if (frames.length > 0) { + frameImages = frames + } + } else if ( + params.mode === 'reference_to_video' && + params.inputReferences && + params.inputReferences.length > 0 + ) { + inputReferences = params.inputReferences as unknown as GenerateVideoOptions['inputReferences'] + } + + const { video, warnings } = await aiGenerateVideo({ + model, + prompt: promptPayload, + frameImages, + inputReferences, + aspectRatio: params.aspectRatio, + resolution: params.resolution, + duration: params.duration, + fps: params.fps, + generateAudio: params.generateAudio, + seed: params.seed, + }) + + let buffer: Buffer + if (video.uint8Array) { + buffer = Buffer.from(video.uint8Array) + } else if (video.base64) { + buffer = Buffer.from(video.base64, 'base64') + } else { + throw new Error('No video binary data returned by provider') + } + + const videoInfo = video as unknown as { mediaType?: string; mimeType?: string } + const mimeType = videoInfo.mediaType || videoInfo.mimeType || 'video/mp4' + + return { + buffer, + mimeType, + warnings, + } + } +} + +export const mediaGenerationService = new MediaGenerationService() diff --git a/packages/db/src/prisma-json-types.ts b/packages/db/src/prisma-json-types.ts index ee4aa120..efc1ac53 100644 --- a/packages/db/src/prisma-json-types.ts +++ b/packages/db/src/prisma-json-types.ts @@ -61,8 +61,27 @@ declare global { hardwareAcceleration?: HardwareAcceleration } + export interface MediaProviderConfig { + apiKey?: string + } + + export interface EnabledMediaModelConfig { + id: string + type: 'image' | 'video' + provider: string + modelId: string + name?: string + createdAt: string + } + + export interface MediaGenerationSettings { + providers?: Record + enabledModels?: EnabledMediaModelConfig[] + } + export interface Settings { transcode: TranscodeSettings + mediaGeneration?: MediaGenerationSettings } // ---------------------------------------------------------------------- diff --git a/packages/dtos/src/index.ts b/packages/dtos/src/index.ts index 0f0248f3..aac9198e 100644 --- a/packages/dtos/src/index.ts +++ b/packages/dtos/src/index.ts @@ -27,3 +27,4 @@ export * from './quota' export * from './kanban' export * from './recents' export * from './context' +export * from './media-generation' diff --git a/packages/dtos/src/media-generation.ts b/packages/dtos/src/media-generation.ts new file mode 100644 index 00000000..056af216 --- /dev/null +++ b/packages/dtos/src/media-generation.ts @@ -0,0 +1,63 @@ +import { z } from 'zod' + +export const mediaModelTypeSchema = z.enum(['image', 'video']) +export type MediaModelType = z.infer + +export const mediaProviderStatusTypeSchema = z.enum([ + 'configured_custom', + 'configured_env', + 'not_configured', +]) +export type MediaProviderStatusType = z.infer + +export const updateMediaProviderApiKeySchema = z.object({ + apiKey: z.string().optional().or(z.literal('')), +}) +export type UpdateMediaProviderApiKeyRequest = z.infer + +export const createEnabledMediaModelSchema = z.object({ + type: mediaModelTypeSchema, + provider: z.string().min(1, 'Provider is required'), + modelId: z.string().min(1, 'Model ID is required'), + name: z.string().optional(), +}) +export type CreateEnabledMediaModelRequest = z.infer + +export const enabledMediaModelSchema = z.object({ + id: z.string(), + type: mediaModelTypeSchema, + provider: z.string(), + modelId: z.string(), + name: z.string(), + createdAt: z.string(), +}) +export type EnabledMediaModel = z.infer + +export const mediaProviderStatusSchema = z.object({ + provider: z.string(), + defaultEnvKey: z.string(), + apiKeyConfigured: z.boolean(), + status: mediaProviderStatusTypeSchema, + customApiKeyOrEnv: z.string().optional(), + supportedTypes: z.array(mediaModelTypeSchema), +}) +export type MediaProviderStatus = z.infer + +export const mediaGenerationSettingsResponseSchema = z.object({ + providers: z.array(mediaProviderStatusSchema), + enabledModels: z.array(enabledMediaModelSchema), +}) +export type MediaGenerationSettingsResponse = z.infer + +export const curatedMediaModelSchema = z.object({ + modelId: z.string(), + name: z.string(), + type: mediaModelTypeSchema, +}) +export type CuratedMediaModel = z.infer + +export const getCuratedMediaModelsQuerySchema = z.object({ + provider: z.string().optional(), + type: mediaModelTypeSchema.optional(), +}) +export type GetCuratedMediaModelsQuery = z.infer diff --git a/packages/webui/components/settings/AgentFormDialog.test.tsx b/packages/webui/components/settings/AgentFormDialog.test.tsx new file mode 100644 index 00000000..f6d1db8a --- /dev/null +++ b/packages/webui/components/settings/AgentFormDialog.test.tsx @@ -0,0 +1,92 @@ +// @vitest-environment happy-dom +import { cleanup, render, screen } from '@testing-library/react' +import React from 'react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { AgentFormDialog } from './AgentFormDialog' + +vi.mock('@/ui/api/client', () => ({ + client: { + api: { + teams: { + ':teamId': { + providers: { + $get: vi.fn().mockResolvedValue({ + ok: true, + json: async () => [], + }), + }, + skills: { + $get: vi.fn().mockResolvedValue({ + ok: true, + json: async () => ({ skills: [] }), + }), + }, + mcp: { + servers: { + $get: vi.fn().mockResolvedValue({ + ok: true, + json: async () => [], + }), + }, + }, + agents: { + $post: vi.fn(), + ':agentId': { + $put: vi.fn(), + }, + }, + }, + }, + }, + }, +})) + +vi.mock('@/ui/hooks/use-permissions', () => ({ + usePermissions: () => ({ + canAdmin: true, + }), +})) + +vi.mock('sonner', () => ({ + toast: { + success: vi.fn(), + error: vi.fn(), + }, +})) + +describe('AgentFormDialog', () => { + let queryClient: QueryClient + + beforeEach(() => { + queryClient = new QueryClient({ + defaultOptions: { + queries: { retry: false }, + mutations: { retry: false }, + }, + }) + }) + + afterEach(() => { + cleanup() + }) + + it('renders all builtin tools including generate_image and generate_video', () => { + render( + + + , + ) + + expect(screen.getByText('Generate Image')).toBeDefined() + expect(screen.getByText('Generate Video')).toBeDefined() + expect(screen.getByText('Sandboxed Terminal')).toBeDefined() + expect(screen.getByText('Read Asset')).toBeDefined() + }) +}) diff --git a/packages/webui/components/settings/AgentFormDialog.tsx b/packages/webui/components/settings/AgentFormDialog.tsx index 0da9ab2b..cc713055 100644 --- a/packages/webui/components/settings/AgentFormDialog.tsx +++ b/packages/webui/components/settings/AgentFormDialog.tsx @@ -95,6 +95,16 @@ const BUILTIN_TOOLS = [ name: () => m.agent_tool_create_version_name(), description: () => m.agent_tool_create_version_desc(), }, + { + id: 'generate_image', + name: () => m.agent_tool_generate_image_name(), + description: () => m.agent_tool_generate_image_desc(), + }, + { + id: 'generate_video', + name: () => m.agent_tool_generate_video_name(), + description: () => m.agent_tool_generate_video_desc(), + }, ] type AgentFormValues = z.infer diff --git a/packages/webui/components/settings/ImageVideoGenerationSettings.test.tsx b/packages/webui/components/settings/ImageVideoGenerationSettings.test.tsx new file mode 100644 index 00000000..7b87b7ba --- /dev/null +++ b/packages/webui/components/settings/ImageVideoGenerationSettings.test.tsx @@ -0,0 +1,240 @@ +// @vitest-environment happy-dom +import { cleanup, render, screen, fireEvent, waitFor } from '@testing-library/react' +import React from 'react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { ImageVideoGenerationSettings } from './ImageVideoGenerationSettings' +import type { MediaGenerationSettingsResponse } from '@shumai/dtos' + +const mockGetSettings = vi.fn() +const mockPutProvider = vi.fn() +const mockPostModel = vi.fn() +const mockDeleteModel = vi.fn() +const mockGetCurated = vi.fn() + +vi.mock('@/ui/api/client', () => ({ + client: { + api: { + teams: { + ':teamId': { + 'media-generation': { + $get: () => mockGetSettings(), + providers: { + ':provider': { + $put: (args: unknown) => mockPutProvider(args), + }, + }, + models: { + $post: (args: unknown) => mockPostModel(args), + ':modelId': { + $delete: (args: unknown) => mockDeleteModel(args), + }, + curated: { + $get: (args: unknown) => mockGetCurated(args), + }, + }, + }, + }, + }, + }, + }, +})) + +vi.mock('sonner', () => ({ + toast: { + success: vi.fn(), + error: vi.fn(), + }, +})) + +describe('ImageVideoGenerationSettings', () => { + const initialSettings: MediaGenerationSettingsResponse = { + providers: [ + { + provider: 'openai', + defaultEnvKey: 'OPENAI_API_KEY', + apiKeyConfigured: true, + status: 'configured_env', + supportedTypes: ['image'], + }, + { + provider: 'klingai', + defaultEnvKey: 'KLINGAI_API_KEY', + apiKeyConfigured: true, + status: 'configured_custom', + customApiKeyOrEnv: 'my-custom-key', + supportedTypes: ['video'], + }, + { + provider: 'fal', + defaultEnvKey: 'FAL_KEY', + apiKeyConfigured: false, + status: 'not_configured', + supportedTypes: ['image', 'video'], + }, + ], + enabledModels: [ + { + id: 'model-1', + type: 'image', + provider: 'openai', + modelId: 'dall-e-3', + name: 'DALL-E 3', + createdAt: '2026-01-01T00:00:00.000Z', + }, + { + id: 'model-2', + type: 'video', + provider: 'klingai', + modelId: 'kling-v1-standard', + name: 'Kling v1', + createdAt: '2026-01-01T00:00:00.000Z', + }, + ], + } + + let queryClient: QueryClient + + beforeEach(() => { + vi.clearAllMocks() + queryClient = new QueryClient({ + defaultOptions: { + queries: { retry: false }, + mutations: { retry: false }, + }, + }) + mockGetSettings.mockResolvedValue({ + ok: true, + json: async () => initialSettings, + }) + mockPutProvider.mockResolvedValue({ + ok: true, + json: async () => ({ success: true }), + }) + mockPostModel.mockResolvedValue({ + ok: true, + json: async () => ({ + id: 'new-model-id', + type: 'image', + provider: 'openai', + modelId: 'dall-e-2', + name: 'DALL-E 2', + createdAt: '2026-01-01T00:00:00.000Z', + }), + }) + mockDeleteModel.mockResolvedValue({ + ok: true, + json: async () => ({ success: true }), + }) + mockGetCurated.mockResolvedValue({ + ok: true, + json: async () => [ + { modelId: 'dall-e-3', name: 'DALL-E 3', type: 'image' }, + { modelId: 'dall-e-2', name: 'DALL-E 2', type: 'image' }, + ], + }) + }) + + afterEach(() => { + cleanup() + }) + + const renderComponent = () => + render( + + + , + ) + + it('renders provider list and enabled models', async () => { + renderComponent() + + await waitFor(() => { + expect(screen.getAllByText('OpenAI').length).toBeGreaterThan(0) + expect(screen.getAllByText('Kling AI').length).toBeGreaterThan(0) + expect(screen.getAllByText('Fal').length).toBeGreaterThan(0) + }) + + // Verify enabled models table + expect(screen.getByText('dall-e-3')).toBeDefined() + expect(screen.getByText('kling-v1-standard')).toBeDefined() + }) + + it('opens configure API key dialog and saves new key', async () => { + renderComponent() + + await waitFor(() => { + expect(screen.getAllByText('OpenAI').length).toBeGreaterThan(0) + }) + + const editButtons = screen.getAllByRole('button', { name: /Edit API Key/i }) + fireEvent.click(editButtons[0]) + + await waitFor(() => { + expect(screen.getByRole('dialog')).toBeDefined() + }) + + const input = document.querySelector('input[type="password"]') as HTMLInputElement + expect(input).toBeDefined() + fireEvent.change(input, { target: { value: 'sk-new-openai-test-key' } }) + + const saveButton = screen.getByRole('button', { name: 'Save' }) + fireEvent.click(saveButton) + + await waitFor(() => { + expect(mockPutProvider).toHaveBeenCalledWith({ + param: { teamId: 'team-123', provider: 'openai' }, + json: { apiKey: 'sk-new-openai-test-key' }, + }) + }) + }) + + it('opens add model dialog and enables adding model', async () => { + renderComponent() + + await waitFor(() => { + expect(screen.getAllByText('OpenAI').length).toBeGreaterThan(0) + }) + + const addModelButtons = screen.getAllByRole('button', { name: /Add Model/i }) + fireEvent.click(addModelButtons[0]) + + await waitFor(() => { + expect(screen.getByRole('dialog')).toBeDefined() + }) + expect( + screen.getByText('Select the media generation type, provider, and model to enable.'), + ).toBeDefined() + }) + + it('masks existing custom key and allows removing custom key', async () => { + renderComponent() + + await waitFor(() => { + expect(screen.getAllByText('Kling AI').length).toBeGreaterThan(0) + }) + + const editButtons = screen.getAllByRole('button', { name: /Edit API Key/i }) + // Kling AI is index 1 + fireEvent.click(editButtons[1]) + + await waitFor(() => { + expect(screen.getByRole('dialog')).toBeDefined() + }) + + const input = document.querySelector('input[type="password"]') as HTMLInputElement + expect(input).toBeDefined() + expect(input.value).toBe('') // Secret is not prefilled in the input + expect(input.placeholder).toBe('••••••••') // Masked indicator + + const removeButton = screen.getByRole('button', { name: 'Remove Key' }) + fireEvent.click(removeButton) + + await waitFor(() => { + expect(mockPutProvider).toHaveBeenCalledWith({ + param: { teamId: 'team-123', provider: 'klingai' }, + json: { apiKey: '' }, + }) + }) + }) +}) diff --git a/packages/webui/components/settings/ImageVideoGenerationSettings.tsx b/packages/webui/components/settings/ImageVideoGenerationSettings.tsx new file mode 100644 index 00000000..97f1dd2d --- /dev/null +++ b/packages/webui/components/settings/ImageVideoGenerationSettings.tsx @@ -0,0 +1,741 @@ +import { useState } from 'react' +import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' +import { client } from '@/ui/api/client' +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/ui/components/ui/card' +import { Button } from '@/ui/components/ui/button' +import { Input } from '@/ui/components/ui/input' +import { Badge } from '@/ui/components/ui/badge' +import { ScrollArea } from '@/ui/components/ui/scroll-area' +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from '@/ui/components/ui/dialog' +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from '@/ui/components/ui/alert-dialog' +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from '@/ui/components/ui/select' +import { + Table, + TableBody, + TableCell, + TableHead, + TableHeader, + TableRow, +} from '@/ui/components/ui/table' +import { + Key, + Plus, + Trash2, + AlertCircle, + ImageIcon, + VideoIcon, + CheckCircle2, + Loader2, +} from 'lucide-react' +import { toast } from 'sonner' +import { m } from '@/ui/paraglide/messages.js' +import type { + MediaGenerationSettingsResponse, + MediaProviderStatus, + EnabledMediaModel, + CuratedMediaModel, +} from '@shumai/dtos' + +const PROVIDER_NAMES: Record = { + openai: 'OpenAI', + google: 'Google', + 'google-vertex': 'Google Vertex AI', + xai: 'xAI', + fal: 'Fal', + replicate: 'Replicate', + 'black-forest-labs': 'Black Forest Labs', + klingai: 'Kling AI', + togetherai: 'Together AI', + fireworks: 'Fireworks AI', + deepinfra: 'DeepInfra', + luma: 'Luma', + 'amazon-bedrock': 'Amazon Bedrock', + alibaba: 'Alibaba', + bytedance: 'ByteDance', + minimax: 'MiniMax', + prodia: 'Prodia', + azure: 'Azure OpenAI', +} + +export function ImageVideoGenerationSettings({ teamId }: { teamId: string }) { + const queryClient = useQueryClient() + + // API Key Dialog State + const [keyDialogOpen, setKeyDialogOpen] = useState(false) + const [editingProvider, setEditingProvider] = useState(null) + const [apiKeyInput, setApiKeyInput] = useState('') + + // Add Model Dialog State + const [addDialogOpen, setAddDialogOpen] = useState(false) + const [addType, setAddType] = useState<'image' | 'video'>('image') + const [addProvider, setAddProvider] = useState('') + const [selectedModelId, setSelectedModelId] = useState('') + const [customModelId, setCustomModelId] = useState('') + const [modelDisplayName, setModelDisplayName] = useState('') + + // Delete Model Confirmation State + const [modelToDelete, setModelToDelete] = useState(null) + + // Fetch Media Generation Settings + const { data: settings, isLoading } = useQuery({ + queryKey: ['teams', teamId, 'media-generation'], + queryFn: async () => { + const res = await client.api.teams[':teamId']['media-generation'].$get({ + param: { teamId }, + }) + if (!res.ok) throw new Error('Failed to fetch media generation settings') + return (await res.json()) as MediaGenerationSettingsResponse + }, + }) + + // Fetch Curated Models for Add Dialog + const { data: curatedModels, isLoading: isLoadingCurated } = useQuery({ + queryKey: ['teams', teamId, 'media-generation', 'curated', addType, addProvider], + queryFn: async () => { + if (!addProvider) return [] + const res = await client.api.teams[':teamId']['media-generation']['models']['curated'].$get({ + param: { teamId }, + query: { provider: addProvider, type: addType }, + }) + if (!res.ok) return [] + return (await res.json()) as CuratedMediaModel[] + }, + enabled: addDialogOpen && !!addProvider, + }) + + // Mutation: Update Provider API Key + const { mutate: updateApiKey, isPending: isSavingKey } = useMutation({ + mutationFn: async ({ provider, apiKey }: { provider: string; apiKey?: string }) => { + const res = await client.api.teams[':teamId']['media-generation']['providers'][ + ':provider' + ].$put({ + param: { teamId, provider }, + json: { apiKey }, + }) + if (!res.ok) { + const err = await res.json().catch(() => ({})) + // eslint-disable-next-line @typescript-eslint/no-explicit-any + throw new Error((err as any)?.message || 'Failed to update API key') + } + return await res.json() + }, + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'media-generation'] }) + toast.success(m.api_key_saved_successfully()) + setKeyDialogOpen(false) + setEditingProvider(null) + setApiKeyInput('') + }, + onError: (err) => { + toast.error(err instanceof Error ? err.message : m.failed_to_save_api_key()) + }, + }) + + // Mutation: Add Enabled Model + const { mutate: addModel, isPending: isAddingModel } = useMutation({ + mutationFn: async (payload: { + type: 'image' | 'video' + provider: string + modelId: string + name?: string + }) => { + const res = await client.api.teams[':teamId']['media-generation']['models'].$post({ + param: { teamId }, + json: payload, + }) + if (!res.ok) { + const err = await res.json().catch(() => ({})) + // eslint-disable-next-line @typescript-eslint/no-explicit-any + throw new Error((err as any)?.message || 'Failed to add model') + } + return await res.json() + }, + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'media-generation'] }) + toast.success(m.model_added_successfully()) + setAddDialogOpen(false) + resetAddForm() + }, + onError: (err) => { + toast.error(err instanceof Error ? err.message : m.failed_to_add_model()) + }, + }) + + // Mutation: Remove Enabled Model + const { mutate: removeModel, isPending: isRemovingModel } = useMutation({ + mutationFn: async (modelId: string) => { + const res = await client.api.teams[':teamId']['media-generation']['models'][ + ':modelId' + ].$delete({ + param: { teamId, modelId }, + }) + if (!res.ok) throw new Error('Failed to remove model') + return await res.json() + }, + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'media-generation'] }) + toast.success(m.model_removed_successfully()) + setModelToDelete(null) + }, + onError: (err) => { + toast.error(err instanceof Error ? err.message : m.failed_to_remove_model()) + }, + }) + + const resetAddForm = () => { + setAddType('image') + setAddProvider('') + setSelectedModelId('') + setCustomModelId('') + setModelDisplayName('') + } + + const handleOpenKeyDialog = (provider: MediaProviderStatus) => { + setEditingProvider(provider) + setApiKeyInput('') + setKeyDialogOpen(true) + } + + const handleSaveKey = () => { + if (!editingProvider) return + const trimmed = apiKeyInput.trim() + if (!trimmed) { + setKeyDialogOpen(false) + return + } + updateApiKey({ + provider: editingProvider.provider, + apiKey: trimmed, + }) + } + + const handleRemoveKey = () => { + if (!editingProvider) return + updateApiKey({ + provider: editingProvider.provider, + apiKey: '', + }) + } + + const handleAddModelSubmit = () => { + const finalModelId = + selectedModelId === '__custom__' ? customModelId.trim() : selectedModelId.trim() + if (!addProvider || !finalModelId) return + + addModel({ + type: addType, + provider: addProvider, + modelId: finalModelId, + name: modelDisplayName.trim() || undefined, + }) + } + + if (isLoading) { + return ( +
+ +
+ ) + } + + const providers = settings?.providers || [] + const enabledModels = settings?.enabledModels || [] + const activeProvidersMap = new Map(providers.map((p) => [p.provider, p.apiKeyConfigured])) + + // Filter providers that support the currently selected addType + const compatibleProviders = providers.filter((p) => p.supportedTypes.includes(addType)) + + return ( + +
+ {/* Section 1: Media Providers */} + + + {m.media_providers()} + {m.media_providers_description()} + + +
+ {providers.map((provider) => { + const displayName = PROVIDER_NAMES[provider.provider] || provider.provider + const isCustom = provider.status === 'configured_custom' + const isEnv = provider.status === 'configured_env' + + return ( +
+
+
+ + {displayName} + + {isCustom && ( + + + {m.provider_status_configured_custom()} + + )} + {isEnv && ( + + + {m.provider_status_configured_env()} + + )} + {!isCustom && !isEnv && ( + + {m.provider_status_not_configured()} + + )} +
+ +
+
+ {provider.supportedTypes.includes('image') && ( + + + {m.media_type_image()} + + )} + {provider.supportedTypes.includes('video') && ( + + + {m.media_type_video()} + + )} +
+ + {provider.defaultEnvKey} + +
+
+ +
+ +
+
+ ) + })} +
+
+
+ + {/* Section 2: Enabled Models */} + + +
+ {m.enabled_media_models()} + + {m.enabled_media_models_description()} + +
+ +
+ + {enabledModels.length === 0 ? ( +
+

{m.no_enabled_models()}

+
+ ) : ( +
+ + + + {m.model_type()} + {m.providers()} + {m.model()} + + + + + {enabledModels.map((model) => { + const isConfigured = activeProvidersMap.get(model.provider) ?? false + const providerDisplayName = PROVIDER_NAMES[model.provider] || model.provider + + return ( + + + {model.type === 'image' ? ( + + + {m.media_type_image()} + + ) : ( + + + {m.media_type_video()} + + )} + + + {providerDisplayName} + + +
+ {model.modelId} + {model.name && ( + + ({model.name}) + + )} + {!isConfigured && ( +
+ + {m.provider_status_not_configured()} +
+ )} +
+
+ + + +
+ ) + })} +
+
+
+ )} +
+
+ + {/* Dialog: Configure Provider API Key */} + + + + + {editingProvider + ? `${PROVIDER_NAMES[editingProvider.provider] || editingProvider.provider} API Key` + : m.configure_api_key()} + + + {editingProvider && + m.api_key_or_env_var_hint({ envKey: editingProvider.defaultEnvKey })} + + +
+
+ + setApiKeyInput(e.target.value)} + placeholder={ + editingProvider?.status === 'configured_custom' + ? '••••••••' + : editingProvider + ? m.api_key_or_env_var_placeholder({ + envKey: editingProvider.defaultEnvKey, + }) + : '' + } + className="font-mono text-sm" + /> +
+
+ + {editingProvider?.status === 'configured_custom' ? ( + + ) : ( +
+ )} +
+ + +
+ + +
+ + {/* Dialog: Add Model */} + + + + {m.add_media_model()} + {m.add_media_model_desc()} + +
+ {/* Type Select */} +
+ + +
+ + {/* Provider Select */} +
+ + +
+ + {/* Model Select */} + {addProvider && ( +
+ + {isLoadingCurated ? ( +
+ + {m.loading_models()} +
+ ) : ( + + )} +
+ )} + + {/* Custom Model ID Input */} + {selectedModelId === '__custom__' && ( +
+ + setCustomModelId(e.target.value)} + placeholder={m.enter_custom_model_id()} + className="font-mono text-sm" + /> +
+ )} + + {/* Display Name Input */} + {addProvider && selectedModelId && ( +
+ + setModelDisplayName(e.target.value)} + placeholder={m.model_display_name_placeholder()} + /> +
+ )} +
+ + + + +
+
+ + {/* Alert Dialog: Confirm Model Deletion */} + { + if (!open) setModelToDelete(null) + }} + > + + + {m.remove_model_confirm()} + + {modelToDelete && + m.remove_model_prompt({ + modelId: modelToDelete.modelId, + provider: PROVIDER_NAMES[modelToDelete.provider] || modelToDelete.provider, + })} + + + + {m.cancel()} + { + if (modelToDelete) removeModel(modelToDelete.id) + }} + disabled={isRemovingModel} + className="bg-destructive text-destructive-foreground hover:bg-destructive/90" + > + {isRemovingModel && } + {m.delete()} + + + + +
+
+ ) +} diff --git a/packages/webui/components/settings/QuotaRuleDialog.test.tsx b/packages/webui/components/settings/QuotaRuleDialog.test.tsx new file mode 100644 index 00000000..eb15c009 --- /dev/null +++ b/packages/webui/components/settings/QuotaRuleDialog.test.tsx @@ -0,0 +1,81 @@ +// @vitest-environment happy-dom +import { cleanup, render, screen } from '@testing-library/react' +import React from 'react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { QuotaRuleDialog } from './QuotaRuleDialog' +import type { QuotaRuleResponse } from '@shumai/dtos' + +vi.mock('@/ui/api/client', () => ({ + client: { + api: { + teams: { + ':teamId': { + members: { + $get: vi.fn().mockResolvedValue({ + ok: true, + json: async () => [], + }), + }, + mcp: { + servers: { + $get: vi.fn().mockResolvedValue({ + ok: true, + json: async () => ({ servers: [] }), + }), + }, + }, + }, + }, + }, + }, +})) + +vi.mock('sonner', () => ({ + toast: { + success: vi.fn(), + error: vi.fn(), + }, +})) + +describe('QuotaRuleDialog', () => { + let queryClient: QueryClient + + beforeEach(() => { + queryClient = new QueryClient({ + defaultOptions: { + queries: { retry: false }, + mutations: { retry: false }, + }, + }) + }) + + afterEach(() => { + cleanup() + }) + + it('displays generate_image and generate_video in tool selector for agent_tool_call_count', () => { + const existingRule: QuotaRuleResponse = { + id: 'rule-1', + teamId: 'team-123', + scopeMode: 'each_member', + role: null, + resource: 'agent_tool_call_count', + resourceData: { name: 'generate_image' }, + limit: 50, + period: '1day', + enabled: true, + createdAt: '2026-01-01T00:00:00.000Z', + updatedAt: '2026-01-01T00:00:00.000Z', + } + + render( + + + , + ) + + // The select trigger and option both display the selected tool name + expect(screen.getAllByText('Generate Image').length).toBeGreaterThan(0) + }) +}) diff --git a/packages/webui/components/settings/QuotaRuleDialog.tsx b/packages/webui/components/settings/QuotaRuleDialog.tsx index 306972ca..2cb2db2f 100644 --- a/packages/webui/components/settings/QuotaRuleDialog.tsx +++ b/packages/webui/components/settings/QuotaRuleDialog.tsx @@ -74,6 +74,8 @@ const STANDARD_TOOLS = [ { value: 'create_folder', label: () => m.agent_tool_create_folder_name() }, { value: 'create_file', label: () => m.agent_tool_create_file_name() }, { value: 'create_version', label: () => m.agent_tool_create_version_name() }, + { value: 'generate_image', label: () => m.agent_tool_generate_image_name() }, + { value: 'generate_video', label: () => m.agent_tool_generate_video_name() }, ] /* eslint-disable @typescript-eslint/naming-convention */ diff --git a/packages/webui/messages/en.json b/packages/webui/messages/en.json index fc100e0e..afa24494 100644 --- a/packages/webui/messages/en.json +++ b/packages/webui/messages/en.json @@ -529,6 +529,10 @@ "agent_tool_create_file_desc": "Allows the agent to create files in Shumai, either by uploading a local file or by providing the file name and content directly.", "agent_tool_create_version_name": "Create Version", "agent_tool_create_version_desc": "Allows the agent to upload and stack a new version of an existing file in Shumai.", + "agent_tool_generate_image_name": "Generate Image", + "agent_tool_generate_image_desc": "Allows the agent to generate images from prompts and reference images using configured AI image models.", + "agent_tool_generate_video_name": "Generate Video", + "agent_tool_generate_video_desc": "Allows the agent to generate videos from text, images, or frame sequences using configured AI video models.", "enabled": "Enabled", "disabled": "Disabled", "no_skills_available": "No skills available.", @@ -1361,5 +1365,44 @@ "delete_session": "Delete Session", "thinking_status": "Thinking...", "contains_drawing_annotations": "Contains drawing annotations", - "page_prefix": "Page {page}" + "page_prefix": "Page {page}", + "image_video_generation": "Image / Video Generation", + "media_generation_settings_description": "Configure providers and enabled models for built-in image and video generation tools.", + "media_providers": "Media Providers", + "media_providers_description": "Configure API keys for built-in media generation providers. Providers can use environment variables or custom keys.", + "enabled_media_models": "Enabled Models", + "enabled_media_models_description": "Models enabled for the generate_image and generate_video tools. The first model of each type serves as default.", + "add_media_model": "Add Model", + "configure_api_key": "Configure API Key", + "edit_api_key": "Edit API Key", + "api_key_or_env_var": "API Key or Environment Variable", + "api_key_or_env_var_placeholder": "Leave empty to use default env var ({envKey})", + "api_key_or_env_var_hint": "Enter an API key or an environment variable name (e.g. {envKey}). Leave empty to restore default environment variable.", + "provider_status_configured_custom": "Configured (Custom)", + "provider_status_configured_env": "Configured (Environment)", + "provider_status_not_configured": "Not Configured", + "supported_types": "Supported", + "model_type": "Model Type", + "media_type_image": "Image", + "media_type_video": "Video", + "select_provider": "Select Provider", + "select_model": "Select Model", + "custom_model_id": "Custom Model ID", + "enter_custom_model_id": "Enter custom model ID", + "model_display_name": "Display Name (Optional)", + "model_display_name_placeholder": "Friendly name for this model", + "custom_model_option": "Custom Model...", + "no_enabled_models": "No media generation models enabled yet. Add at least one image or video model to enable the generation tools.", + "api_key_saved_successfully": "API key updated successfully", + "failed_to_save_api_key": "Failed to update API key", + "model_added_successfully": "Model added successfully", + "failed_to_add_model": "Failed to add model", + "model_removed_successfully": "Model removed successfully", + "failed_to_remove_model": "Failed to remove model", + "remove_model_confirm": "Are you sure you want to remove this model?", + "model_requires_api_key_warning": "This provider is not configured. Tools using this model will not be available until an API key is configured.", + "add_media_model_desc": "Select the media generation type, provider, and model to enable.", + "loading_models": "Loading models...", + "remove_model_prompt": "Remove model {modelId} ({provider}) from enabled models?", + "remove_key": "Remove Key" } diff --git a/packages/webui/messages/zh.json b/packages/webui/messages/zh.json index f5b2c9a2..1aef91bc 100644 --- a/packages/webui/messages/zh.json +++ b/packages/webui/messages/zh.json @@ -529,6 +529,10 @@ "agent_tool_create_file_desc": "允许智能体在 Shumai 中创建文件,既可以通过上传本地文件,也可以直接提供文件名和内容。", "agent_tool_create_version_name": "创建版本", "agent_tool_create_version_desc": "允许智能体在 Shumai 中为已有文件上传并叠加新版本。", + "agent_tool_generate_image_name": "生成图片", + "agent_tool_generate_image_desc": "允许智能体使用已配置的 AI 图片模型根据提示词和参考图片生成图片。", + "agent_tool_generate_video_name": "生成视频", + "agent_tool_generate_video_desc": "允许智能体使用已配置的 AI 视频模型根据提示词、图片或首尾帧生成视频。", "enabled": "已启用", "disabled": "已禁用", "no_skills_available": "暂无可用技能。", @@ -1361,5 +1365,44 @@ "delete_session": "删除会话", "thinking_status": "思考中...", "contains_drawing_annotations": "包含标注绘图", - "page_prefix": "第 {page} 页" + "page_prefix": "第 {page} 页", + "image_video_generation": "图像与视频生成", + "media_generation_settings_description": "配置内置图像和视频生成工具的提供商与已启用模型。", + "media_providers": "媒体提供商", + "media_providers_description": "为内置媒体生成提供商配置 API 密钥。提供商可以使用环境变量或自定义密钥。", + "enabled_media_models": "已启用模型", + "enabled_media_models_description": "供 generate_image 和 generate_video 工具使用的已启用模型。每种类型的第一个模型将作为默认模型。", + "add_media_model": "添加模型", + "configure_api_key": "配置 API 密钥", + "edit_api_key": "修改 API 密钥", + "api_key_or_env_var": "API 密钥或环境变量名", + "api_key_or_env_var_placeholder": "留空以使用默认环境变量 ({envKey})", + "api_key_or_env_var_hint": "输入 API 密钥或环境变量名(例如 {envKey})。留空将恢复默认环境变量。", + "provider_status_configured_custom": "已配置(自定义)", + "provider_status_configured_env": "已配置(环境变量)", + "provider_status_not_configured": "未配置", + "supported_types": "支持类型", + "model_type": "模型类型", + "media_type_image": "图像", + "media_type_video": "视频", + "select_provider": "选择提供商", + "select_model": "选择模型", + "custom_model_id": "自定义模型 ID", + "enter_custom_model_id": "输入自定义模型 ID", + "model_display_name": "显示名称(可选)", + "model_display_name_placeholder": "该模型的易读名称", + "custom_model_option": "自定义模型...", + "no_enabled_models": "尚未启用任何媒体生成模型。添加至少一个图像或视频模型以启用生成工具。", + "api_key_saved_successfully": "API 密钥更新成功", + "failed_to_save_api_key": "更新 API 密钥失败", + "model_added_successfully": "模型添加成功", + "failed_to_add_model": "添加模型失败", + "model_removed_successfully": "模型移除成功", + "failed_to_remove_model": "移除模型失败", + "remove_model_confirm": "确定要移除此模型吗?", + "model_requires_api_key_warning": "此提供商尚未配置。在配置 API 密钥之前,使用此模型的工具将不可用。", + "add_media_model_desc": "选择要启用的媒体生成类型、提供商和模型。", + "loading_models": "正在加载模型...", + "remove_model_prompt": "确定要从已启用模型中移除模型 {modelId}({provider})吗?", + "remove_key": "移除密钥" } diff --git a/packages/webui/paraglide/messages/_index.d.ts b/packages/webui/paraglide/messages/_index.d.ts index 470acc3a..d7acd4e2 100644 --- a/packages/webui/paraglide/messages/_index.d.ts +++ b/packages/webui/paraglide/messages/_index.d.ts @@ -510,6 +510,10 @@ export * from "./agent_tool_create_file_name.js"; export * from "./agent_tool_create_file_desc.js"; export * from "./agent_tool_create_version_name.js"; export * from "./agent_tool_create_version_desc.js"; +export * from "./agent_tool_generate_image_name.js"; +export * from "./agent_tool_generate_image_desc.js"; +export * from "./agent_tool_generate_video_name.js"; +export * from "./agent_tool_generate_video_desc.js"; export * from "./enabled.js"; export * from "./disabled.js"; export * from "./no_skills_available.js"; @@ -1298,4 +1302,41 @@ export * from "./back_to_chat.js"; export * from "./delete_session.js"; export * from "./thinking_status.js"; export * from "./page_prefix.js"; +export * from "./image_video_generation.js"; +export * from "./media_generation_settings_description.js"; +export * from "./media_providers.js"; +export * from "./media_providers_description.js"; +export * from "./enabled_media_models.js"; +export * from "./enabled_media_models_description.js"; +export * from "./add_media_model.js"; +export * from "./configure_api_key.js"; +export * from "./edit_api_key.js"; +export * from "./api_key_or_env_var.js"; +export * from "./api_key_or_env_var_placeholder.js"; +export * from "./api_key_or_env_var_hint.js"; +export * from "./provider_status_configured_custom.js"; +export * from "./provider_status_configured_env.js"; +export * from "./provider_status_not_configured.js"; +export * from "./supported_types.js"; +export * from "./model_type.js"; +export * from "./media_type_image.js"; +export * from "./media_type_video.js"; +export * from "./custom_model_id.js"; +export * from "./enter_custom_model_id.js"; +export * from "./model_display_name.js"; +export * from "./model_display_name_placeholder.js"; +export * from "./custom_model_option.js"; +export * from "./no_enabled_models.js"; +export * from "./api_key_saved_successfully.js"; +export * from "./failed_to_save_api_key.js"; +export * from "./model_added_successfully.js"; +export * from "./failed_to_add_model.js"; +export * from "./model_removed_successfully.js"; +export * from "./failed_to_remove_model.js"; +export * from "./remove_model_confirm.js"; +export * from "./model_requires_api_key_warning.js"; +export * from "./add_media_model_desc.js"; +export * from "./loading_models.js"; +export * from "./remove_model_prompt.js"; +export * from "./remove_key.js"; export type LocalizedString = import("../runtime.js").LocalizedString; diff --git a/packages/webui/paraglide/messages/_index.js b/packages/webui/paraglide/messages/_index.js index 6b5414ae..4887764c 100644 --- a/packages/webui/paraglide/messages/_index.js +++ b/packages/webui/paraglide/messages/_index.js @@ -512,6 +512,10 @@ export * from './agent_tool_create_file_name.js' export * from './agent_tool_create_file_desc.js' export * from './agent_tool_create_version_name.js' export * from './agent_tool_create_version_desc.js' +export * from './agent_tool_generate_image_name.js' +export * from './agent_tool_generate_image_desc.js' +export * from './agent_tool_generate_video_name.js' +export * from './agent_tool_generate_video_desc.js' export * from './enabled.js' export * from './disabled.js' export * from './no_skills_available.js' @@ -1299,4 +1303,41 @@ export * from './entry_id.js' export * from './back_to_chat.js' export * from './delete_session.js' export * from './thinking_status.js' -export * from './page_prefix.js' \ No newline at end of file +export * from './page_prefix.js' +export * from './image_video_generation.js' +export * from './media_generation_settings_description.js' +export * from './media_providers.js' +export * from './media_providers_description.js' +export * from './enabled_media_models.js' +export * from './enabled_media_models_description.js' +export * from './add_media_model.js' +export * from './configure_api_key.js' +export * from './edit_api_key.js' +export * from './api_key_or_env_var.js' +export * from './api_key_or_env_var_placeholder.js' +export * from './api_key_or_env_var_hint.js' +export * from './provider_status_configured_custom.js' +export * from './provider_status_configured_env.js' +export * from './provider_status_not_configured.js' +export * from './supported_types.js' +export * from './model_type.js' +export * from './media_type_image.js' +export * from './media_type_video.js' +export * from './custom_model_id.js' +export * from './enter_custom_model_id.js' +export * from './model_display_name.js' +export * from './model_display_name_placeholder.js' +export * from './custom_model_option.js' +export * from './no_enabled_models.js' +export * from './api_key_saved_successfully.js' +export * from './failed_to_save_api_key.js' +export * from './model_added_successfully.js' +export * from './failed_to_add_model.js' +export * from './model_removed_successfully.js' +export * from './failed_to_remove_model.js' +export * from './remove_model_confirm.js' +export * from './model_requires_api_key_warning.js' +export * from './add_media_model_desc.js' +export * from './loading_models.js' +export * from './remove_model_prompt.js' +export * from './remove_key.js' \ No newline at end of file diff --git a/packages/webui/paraglide/messages/add_media_model.d.ts b/packages/webui/paraglide/messages/add_media_model.d.ts new file mode 100644 index 00000000..8e852ab2 --- /dev/null +++ b/packages/webui/paraglide/messages/add_media_model.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Add Model" | +* +* @param {Add_Media_ModelInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const add_media_model: ((inputs?: Add_Media_ModelInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Add_Media_ModelInputs = {}; diff --git a/packages/webui/paraglide/messages/add_media_model.js b/packages/webui/paraglide/messages/add_media_model.js new file mode 100644 index 00000000..300cda5f --- /dev/null +++ b/packages/webui/paraglide/messages/add_media_model.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Add_Media_ModelInputs */ + +const en_add_media_model = /** @type {(inputs: Add_Media_ModelInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Add Model`) +}; + +const zh_add_media_model = /** @type {(inputs: Add_Media_ModelInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`添加模型`) +}; + +/** +* | output | +* | --- | +* | "Add Model" | +* +* @param {Add_Media_ModelInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const add_media_model = /** @type {((inputs?: Add_Media_ModelInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_add_media_model(inputs) + return zh_add_media_model(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/add_media_model_desc.d.ts b/packages/webui/paraglide/messages/add_media_model_desc.d.ts new file mode 100644 index 00000000..d1b2ee3b --- /dev/null +++ b/packages/webui/paraglide/messages/add_media_model_desc.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Select the media generation type, provider, and model to enable." | +* +* @param {Add_Media_Model_DescInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const add_media_model_desc: ((inputs?: Add_Media_Model_DescInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Add_Media_Model_DescInputs = {}; diff --git a/packages/webui/paraglide/messages/add_media_model_desc.js b/packages/webui/paraglide/messages/add_media_model_desc.js new file mode 100644 index 00000000..4e73d25c --- /dev/null +++ b/packages/webui/paraglide/messages/add_media_model_desc.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Add_Media_Model_DescInputs */ + +const en_add_media_model_desc = /** @type {(inputs: Add_Media_Model_DescInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Select the media generation type, provider, and model to enable.`) +}; + +const zh_add_media_model_desc = /** @type {(inputs: Add_Media_Model_DescInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`选择要启用的媒体生成类型、提供商和模型。`) +}; + +/** +* | output | +* | --- | +* | "Select the media generation type, provider, and model to enable." | +* +* @param {Add_Media_Model_DescInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const add_media_model_desc = /** @type {((inputs?: Add_Media_Model_DescInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_add_media_model_desc(inputs) + return zh_add_media_model_desc(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/agent_tool_generate_image_desc.d.ts b/packages/webui/paraglide/messages/agent_tool_generate_image_desc.d.ts new file mode 100644 index 00000000..bdb834d0 --- /dev/null +++ b/packages/webui/paraglide/messages/agent_tool_generate_image_desc.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Allows the agent to generate images from prompts and reference images using configured AI image models." | +* +* @param {Agent_Tool_Generate_Image_DescInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const agent_tool_generate_image_desc: ((inputs?: Agent_Tool_Generate_Image_DescInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Agent_Tool_Generate_Image_DescInputs = {}; diff --git a/packages/webui/paraglide/messages/agent_tool_generate_image_desc.js b/packages/webui/paraglide/messages/agent_tool_generate_image_desc.js new file mode 100644 index 00000000..9238939d --- /dev/null +++ b/packages/webui/paraglide/messages/agent_tool_generate_image_desc.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Agent_Tool_Generate_Image_DescInputs */ + +const en_agent_tool_generate_image_desc = /** @type {(inputs: Agent_Tool_Generate_Image_DescInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Allows the agent to generate images from prompts and reference images using configured AI image models.`) +}; + +const zh_agent_tool_generate_image_desc = /** @type {(inputs: Agent_Tool_Generate_Image_DescInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`允许智能体使用已配置的 AI 图片模型根据提示词和参考图片生成图片。`) +}; + +/** +* | output | +* | --- | +* | "Allows the agent to generate images from prompts and reference images using configured AI image models." | +* +* @param {Agent_Tool_Generate_Image_DescInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const agent_tool_generate_image_desc = /** @type {((inputs?: Agent_Tool_Generate_Image_DescInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_agent_tool_generate_image_desc(inputs) + return zh_agent_tool_generate_image_desc(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/agent_tool_generate_image_name.d.ts b/packages/webui/paraglide/messages/agent_tool_generate_image_name.d.ts new file mode 100644 index 00000000..69861928 --- /dev/null +++ b/packages/webui/paraglide/messages/agent_tool_generate_image_name.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Generate Image" | +* +* @param {Agent_Tool_Generate_Image_NameInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const agent_tool_generate_image_name: ((inputs?: Agent_Tool_Generate_Image_NameInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Agent_Tool_Generate_Image_NameInputs = {}; diff --git a/packages/webui/paraglide/messages/agent_tool_generate_image_name.js b/packages/webui/paraglide/messages/agent_tool_generate_image_name.js new file mode 100644 index 00000000..5cde37b7 --- /dev/null +++ b/packages/webui/paraglide/messages/agent_tool_generate_image_name.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Agent_Tool_Generate_Image_NameInputs */ + +const en_agent_tool_generate_image_name = /** @type {(inputs: Agent_Tool_Generate_Image_NameInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Generate Image`) +}; + +const zh_agent_tool_generate_image_name = /** @type {(inputs: Agent_Tool_Generate_Image_NameInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`生成图片`) +}; + +/** +* | output | +* | --- | +* | "Generate Image" | +* +* @param {Agent_Tool_Generate_Image_NameInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const agent_tool_generate_image_name = /** @type {((inputs?: Agent_Tool_Generate_Image_NameInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_agent_tool_generate_image_name(inputs) + return zh_agent_tool_generate_image_name(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/agent_tool_generate_video_desc.d.ts b/packages/webui/paraglide/messages/agent_tool_generate_video_desc.d.ts new file mode 100644 index 00000000..96f38460 --- /dev/null +++ b/packages/webui/paraglide/messages/agent_tool_generate_video_desc.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Allows the agent to generate videos from text, images, or frame sequences using configured AI video models." | +* +* @param {Agent_Tool_Generate_Video_DescInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const agent_tool_generate_video_desc: ((inputs?: Agent_Tool_Generate_Video_DescInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Agent_Tool_Generate_Video_DescInputs = {}; diff --git a/packages/webui/paraglide/messages/agent_tool_generate_video_desc.js b/packages/webui/paraglide/messages/agent_tool_generate_video_desc.js new file mode 100644 index 00000000..0d997afb --- /dev/null +++ b/packages/webui/paraglide/messages/agent_tool_generate_video_desc.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Agent_Tool_Generate_Video_DescInputs */ + +const en_agent_tool_generate_video_desc = /** @type {(inputs: Agent_Tool_Generate_Video_DescInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Allows the agent to generate videos from text, images, or frame sequences using configured AI video models.`) +}; + +const zh_agent_tool_generate_video_desc = /** @type {(inputs: Agent_Tool_Generate_Video_DescInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`允许智能体使用已配置的 AI 视频模型根据提示词、图片或首尾帧生成视频。`) +}; + +/** +* | output | +* | --- | +* | "Allows the agent to generate videos from text, images, or frame sequences using configured AI video models." | +* +* @param {Agent_Tool_Generate_Video_DescInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const agent_tool_generate_video_desc = /** @type {((inputs?: Agent_Tool_Generate_Video_DescInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_agent_tool_generate_video_desc(inputs) + return zh_agent_tool_generate_video_desc(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/agent_tool_generate_video_name.d.ts b/packages/webui/paraglide/messages/agent_tool_generate_video_name.d.ts new file mode 100644 index 00000000..26668f44 --- /dev/null +++ b/packages/webui/paraglide/messages/agent_tool_generate_video_name.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Generate Video" | +* +* @param {Agent_Tool_Generate_Video_NameInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const agent_tool_generate_video_name: ((inputs?: Agent_Tool_Generate_Video_NameInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Agent_Tool_Generate_Video_NameInputs = {}; diff --git a/packages/webui/paraglide/messages/agent_tool_generate_video_name.js b/packages/webui/paraglide/messages/agent_tool_generate_video_name.js new file mode 100644 index 00000000..db64e8ff --- /dev/null +++ b/packages/webui/paraglide/messages/agent_tool_generate_video_name.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Agent_Tool_Generate_Video_NameInputs */ + +const en_agent_tool_generate_video_name = /** @type {(inputs: Agent_Tool_Generate_Video_NameInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Generate Video`) +}; + +const zh_agent_tool_generate_video_name = /** @type {(inputs: Agent_Tool_Generate_Video_NameInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`生成视频`) +}; + +/** +* | output | +* | --- | +* | "Generate Video" | +* +* @param {Agent_Tool_Generate_Video_NameInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const agent_tool_generate_video_name = /** @type {((inputs?: Agent_Tool_Generate_Video_NameInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_agent_tool_generate_video_name(inputs) + return zh_agent_tool_generate_video_name(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/api_key_or_env_var.d.ts b/packages/webui/paraglide/messages/api_key_or_env_var.d.ts new file mode 100644 index 00000000..4d644044 --- /dev/null +++ b/packages/webui/paraglide/messages/api_key_or_env_var.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "API Key or Environment Variable" | +* +* @param {Api_Key_Or_Env_VarInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const api_key_or_env_var: ((inputs?: Api_Key_Or_Env_VarInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Api_Key_Or_Env_VarInputs = {}; diff --git a/packages/webui/paraglide/messages/api_key_or_env_var.js b/packages/webui/paraglide/messages/api_key_or_env_var.js new file mode 100644 index 00000000..1939c0b6 --- /dev/null +++ b/packages/webui/paraglide/messages/api_key_or_env_var.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Api_Key_Or_Env_VarInputs */ + +const en_api_key_or_env_var = /** @type {(inputs: Api_Key_Or_Env_VarInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`API Key or Environment Variable`) +}; + +const zh_api_key_or_env_var = /** @type {(inputs: Api_Key_Or_Env_VarInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`API 密钥或环境变量名`) +}; + +/** +* | output | +* | --- | +* | "API Key or Environment Variable" | +* +* @param {Api_Key_Or_Env_VarInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const api_key_or_env_var = /** @type {((inputs?: Api_Key_Or_Env_VarInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_api_key_or_env_var(inputs) + return zh_api_key_or_env_var(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/api_key_or_env_var_hint.d.ts b/packages/webui/paraglide/messages/api_key_or_env_var_hint.d.ts new file mode 100644 index 00000000..a9f44bef --- /dev/null +++ b/packages/webui/paraglide/messages/api_key_or_env_var_hint.d.ts @@ -0,0 +1,18 @@ +/** +* | output | +* | --- | +* | "Enter an API key or an environment variable name (e.g. {envKey}). Leave empty to restore default environment variable." | +* +* @param {Api_Key_Or_Env_Var_HintInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const api_key_or_env_var_hint: ((inputs: Api_Key_Or_Env_Var_HintInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Api_Key_Or_Env_Var_HintInputs = { + envKey: NonNullable; +}; diff --git a/packages/webui/paraglide/messages/api_key_or_env_var_hint.js b/packages/webui/paraglide/messages/api_key_or_env_var_hint.js new file mode 100644 index 00000000..a578445f --- /dev/null +++ b/packages/webui/paraglide/messages/api_key_or_env_var_hint.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{ envKey: NonNullable }} Api_Key_Or_Env_Var_HintInputs */ + +const en_api_key_or_env_var_hint = /** @type {(inputs: Api_Key_Or_Env_Var_HintInputs) => LocalizedString} */ (i) => { + return /** @type {LocalizedString} */ (`Enter an API key or an environment variable name (e.g. ${i?.envKey}). Leave empty to restore default environment variable.`) +}; + +const zh_api_key_or_env_var_hint = /** @type {(inputs: Api_Key_Or_Env_Var_HintInputs) => LocalizedString} */ (i) => { + return /** @type {LocalizedString} */ (`输入 API 密钥或环境变量名(例如 ${i?.envKey})。留空将恢复默认环境变量。`) +}; + +/** +* | output | +* | --- | +* | "Enter an API key or an environment variable name (e.g. {envKey}). Leave empty to restore default environment variable." | +* +* @param {Api_Key_Or_Env_Var_HintInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const api_key_or_env_var_hint = /** @type {((inputs: Api_Key_Or_Env_Var_HintInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_api_key_or_env_var_hint(inputs) + return zh_api_key_or_env_var_hint(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/api_key_or_env_var_placeholder.d.ts b/packages/webui/paraglide/messages/api_key_or_env_var_placeholder.d.ts new file mode 100644 index 00000000..49c704b5 --- /dev/null +++ b/packages/webui/paraglide/messages/api_key_or_env_var_placeholder.d.ts @@ -0,0 +1,18 @@ +/** +* | output | +* | --- | +* | "Leave empty to use default env var ({envKey})" | +* +* @param {Api_Key_Or_Env_Var_PlaceholderInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const api_key_or_env_var_placeholder: ((inputs: Api_Key_Or_Env_Var_PlaceholderInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Api_Key_Or_Env_Var_PlaceholderInputs = { + envKey: NonNullable; +}; diff --git a/packages/webui/paraglide/messages/api_key_or_env_var_placeholder.js b/packages/webui/paraglide/messages/api_key_or_env_var_placeholder.js new file mode 100644 index 00000000..333ead1f --- /dev/null +++ b/packages/webui/paraglide/messages/api_key_or_env_var_placeholder.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{ envKey: NonNullable }} Api_Key_Or_Env_Var_PlaceholderInputs */ + +const en_api_key_or_env_var_placeholder = /** @type {(inputs: Api_Key_Or_Env_Var_PlaceholderInputs) => LocalizedString} */ (i) => { + return /** @type {LocalizedString} */ (`Leave empty to use default env var (${i?.envKey})`) +}; + +const zh_api_key_or_env_var_placeholder = /** @type {(inputs: Api_Key_Or_Env_Var_PlaceholderInputs) => LocalizedString} */ (i) => { + return /** @type {LocalizedString} */ (`留空以使用默认环境变量 (${i?.envKey})`) +}; + +/** +* | output | +* | --- | +* | "Leave empty to use default env var ({envKey})" | +* +* @param {Api_Key_Or_Env_Var_PlaceholderInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const api_key_or_env_var_placeholder = /** @type {((inputs: Api_Key_Or_Env_Var_PlaceholderInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_api_key_or_env_var_placeholder(inputs) + return zh_api_key_or_env_var_placeholder(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/api_key_saved_successfully.d.ts b/packages/webui/paraglide/messages/api_key_saved_successfully.d.ts new file mode 100644 index 00000000..a3633f55 --- /dev/null +++ b/packages/webui/paraglide/messages/api_key_saved_successfully.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "API key updated successfully" | +* +* @param {Api_Key_Saved_SuccessfullyInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const api_key_saved_successfully: ((inputs?: Api_Key_Saved_SuccessfullyInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Api_Key_Saved_SuccessfullyInputs = {}; diff --git a/packages/webui/paraglide/messages/api_key_saved_successfully.js b/packages/webui/paraglide/messages/api_key_saved_successfully.js new file mode 100644 index 00000000..2d7b5341 --- /dev/null +++ b/packages/webui/paraglide/messages/api_key_saved_successfully.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Api_Key_Saved_SuccessfullyInputs */ + +const en_api_key_saved_successfully = /** @type {(inputs: Api_Key_Saved_SuccessfullyInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`API key updated successfully`) +}; + +const zh_api_key_saved_successfully = /** @type {(inputs: Api_Key_Saved_SuccessfullyInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`API 密钥更新成功`) +}; + +/** +* | output | +* | --- | +* | "API key updated successfully" | +* +* @param {Api_Key_Saved_SuccessfullyInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const api_key_saved_successfully = /** @type {((inputs?: Api_Key_Saved_SuccessfullyInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_api_key_saved_successfully(inputs) + return zh_api_key_saved_successfully(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/configure_api_key.d.ts b/packages/webui/paraglide/messages/configure_api_key.d.ts new file mode 100644 index 00000000..6086bf0f --- /dev/null +++ b/packages/webui/paraglide/messages/configure_api_key.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Configure API Key" | +* +* @param {Configure_Api_KeyInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const configure_api_key: ((inputs?: Configure_Api_KeyInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Configure_Api_KeyInputs = {}; diff --git a/packages/webui/paraglide/messages/configure_api_key.js b/packages/webui/paraglide/messages/configure_api_key.js new file mode 100644 index 00000000..98e95242 --- /dev/null +++ b/packages/webui/paraglide/messages/configure_api_key.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Configure_Api_KeyInputs */ + +const en_configure_api_key = /** @type {(inputs: Configure_Api_KeyInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Configure API Key`) +}; + +const zh_configure_api_key = /** @type {(inputs: Configure_Api_KeyInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`配置 API 密钥`) +}; + +/** +* | output | +* | --- | +* | "Configure API Key" | +* +* @param {Configure_Api_KeyInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const configure_api_key = /** @type {((inputs?: Configure_Api_KeyInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_configure_api_key(inputs) + return zh_configure_api_key(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/custom_model_id.d.ts b/packages/webui/paraglide/messages/custom_model_id.d.ts new file mode 100644 index 00000000..c169bf13 --- /dev/null +++ b/packages/webui/paraglide/messages/custom_model_id.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Custom Model ID" | +* +* @param {Custom_Model_IdInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const custom_model_id: ((inputs?: Custom_Model_IdInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Custom_Model_IdInputs = {}; diff --git a/packages/webui/paraglide/messages/custom_model_id.js b/packages/webui/paraglide/messages/custom_model_id.js new file mode 100644 index 00000000..c806a379 --- /dev/null +++ b/packages/webui/paraglide/messages/custom_model_id.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Custom_Model_IdInputs */ + +const en_custom_model_id = /** @type {(inputs: Custom_Model_IdInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Custom Model ID`) +}; + +const zh_custom_model_id = /** @type {(inputs: Custom_Model_IdInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`自定义模型 ID`) +}; + +/** +* | output | +* | --- | +* | "Custom Model ID" | +* +* @param {Custom_Model_IdInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const custom_model_id = /** @type {((inputs?: Custom_Model_IdInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_custom_model_id(inputs) + return zh_custom_model_id(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/custom_model_option.d.ts b/packages/webui/paraglide/messages/custom_model_option.d.ts new file mode 100644 index 00000000..e22e4a73 --- /dev/null +++ b/packages/webui/paraglide/messages/custom_model_option.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Custom Model..." | +* +* @param {Custom_Model_OptionInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const custom_model_option: ((inputs?: Custom_Model_OptionInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Custom_Model_OptionInputs = {}; diff --git a/packages/webui/paraglide/messages/custom_model_option.js b/packages/webui/paraglide/messages/custom_model_option.js new file mode 100644 index 00000000..5d8e128c --- /dev/null +++ b/packages/webui/paraglide/messages/custom_model_option.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Custom_Model_OptionInputs */ + +const en_custom_model_option = /** @type {(inputs: Custom_Model_OptionInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Custom Model...`) +}; + +const zh_custom_model_option = /** @type {(inputs: Custom_Model_OptionInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`自定义模型...`) +}; + +/** +* | output | +* | --- | +* | "Custom Model..." | +* +* @param {Custom_Model_OptionInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const custom_model_option = /** @type {((inputs?: Custom_Model_OptionInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_custom_model_option(inputs) + return zh_custom_model_option(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/edit_api_key.d.ts b/packages/webui/paraglide/messages/edit_api_key.d.ts new file mode 100644 index 00000000..cd80c4fd --- /dev/null +++ b/packages/webui/paraglide/messages/edit_api_key.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Edit API Key" | +* +* @param {Edit_Api_KeyInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const edit_api_key: ((inputs?: Edit_Api_KeyInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Edit_Api_KeyInputs = {}; diff --git a/packages/webui/paraglide/messages/edit_api_key.js b/packages/webui/paraglide/messages/edit_api_key.js new file mode 100644 index 00000000..d1e48665 --- /dev/null +++ b/packages/webui/paraglide/messages/edit_api_key.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Edit_Api_KeyInputs */ + +const en_edit_api_key = /** @type {(inputs: Edit_Api_KeyInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Edit API Key`) +}; + +const zh_edit_api_key = /** @type {(inputs: Edit_Api_KeyInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`修改 API 密钥`) +}; + +/** +* | output | +* | --- | +* | "Edit API Key" | +* +* @param {Edit_Api_KeyInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const edit_api_key = /** @type {((inputs?: Edit_Api_KeyInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_edit_api_key(inputs) + return zh_edit_api_key(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/enabled_media_models.d.ts b/packages/webui/paraglide/messages/enabled_media_models.d.ts new file mode 100644 index 00000000..937632dc --- /dev/null +++ b/packages/webui/paraglide/messages/enabled_media_models.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Enabled Models" | +* +* @param {Enabled_Media_ModelsInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const enabled_media_models: ((inputs?: Enabled_Media_ModelsInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Enabled_Media_ModelsInputs = {}; diff --git a/packages/webui/paraglide/messages/enabled_media_models.js b/packages/webui/paraglide/messages/enabled_media_models.js new file mode 100644 index 00000000..82005108 --- /dev/null +++ b/packages/webui/paraglide/messages/enabled_media_models.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Enabled_Media_ModelsInputs */ + +const en_enabled_media_models = /** @type {(inputs: Enabled_Media_ModelsInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Enabled Models`) +}; + +const zh_enabled_media_models = /** @type {(inputs: Enabled_Media_ModelsInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`已启用模型`) +}; + +/** +* | output | +* | --- | +* | "Enabled Models" | +* +* @param {Enabled_Media_ModelsInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const enabled_media_models = /** @type {((inputs?: Enabled_Media_ModelsInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_enabled_media_models(inputs) + return zh_enabled_media_models(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/enabled_media_models_description.d.ts b/packages/webui/paraglide/messages/enabled_media_models_description.d.ts new file mode 100644 index 00000000..331f08e9 --- /dev/null +++ b/packages/webui/paraglide/messages/enabled_media_models_description.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Models enabled for the generate_image and generate_video tools. The first model of each type serves as default." | +* +* @param {Enabled_Media_Models_DescriptionInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const enabled_media_models_description: ((inputs?: Enabled_Media_Models_DescriptionInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Enabled_Media_Models_DescriptionInputs = {}; diff --git a/packages/webui/paraglide/messages/enabled_media_models_description.js b/packages/webui/paraglide/messages/enabled_media_models_description.js new file mode 100644 index 00000000..48640028 --- /dev/null +++ b/packages/webui/paraglide/messages/enabled_media_models_description.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Enabled_Media_Models_DescriptionInputs */ + +const en_enabled_media_models_description = /** @type {(inputs: Enabled_Media_Models_DescriptionInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Models enabled for the generate_image and generate_video tools. The first model of each type serves as default.`) +}; + +const zh_enabled_media_models_description = /** @type {(inputs: Enabled_Media_Models_DescriptionInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`供 generate_image 和 generate_video 工具使用的已启用模型。每种类型的第一个模型将作为默认模型。`) +}; + +/** +* | output | +* | --- | +* | "Models enabled for the generate_image and generate_video tools. The first model of each type serves as default." | +* +* @param {Enabled_Media_Models_DescriptionInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const enabled_media_models_description = /** @type {((inputs?: Enabled_Media_Models_DescriptionInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_enabled_media_models_description(inputs) + return zh_enabled_media_models_description(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/enter_custom_model_id.d.ts b/packages/webui/paraglide/messages/enter_custom_model_id.d.ts new file mode 100644 index 00000000..ee408efc --- /dev/null +++ b/packages/webui/paraglide/messages/enter_custom_model_id.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Enter custom model ID" | +* +* @param {Enter_Custom_Model_IdInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const enter_custom_model_id: ((inputs?: Enter_Custom_Model_IdInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Enter_Custom_Model_IdInputs = {}; diff --git a/packages/webui/paraglide/messages/enter_custom_model_id.js b/packages/webui/paraglide/messages/enter_custom_model_id.js new file mode 100644 index 00000000..4dbeb6c9 --- /dev/null +++ b/packages/webui/paraglide/messages/enter_custom_model_id.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Enter_Custom_Model_IdInputs */ + +const en_enter_custom_model_id = /** @type {(inputs: Enter_Custom_Model_IdInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Enter custom model ID`) +}; + +const zh_enter_custom_model_id = /** @type {(inputs: Enter_Custom_Model_IdInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`输入自定义模型 ID`) +}; + +/** +* | output | +* | --- | +* | "Enter custom model ID" | +* +* @param {Enter_Custom_Model_IdInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const enter_custom_model_id = /** @type {((inputs?: Enter_Custom_Model_IdInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_enter_custom_model_id(inputs) + return zh_enter_custom_model_id(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/failed_to_add_model.d.ts b/packages/webui/paraglide/messages/failed_to_add_model.d.ts new file mode 100644 index 00000000..8e54a3ea --- /dev/null +++ b/packages/webui/paraglide/messages/failed_to_add_model.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Failed to add model" | +* +* @param {Failed_To_Add_ModelInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const failed_to_add_model: ((inputs?: Failed_To_Add_ModelInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Failed_To_Add_ModelInputs = {}; diff --git a/packages/webui/paraglide/messages/failed_to_add_model.js b/packages/webui/paraglide/messages/failed_to_add_model.js new file mode 100644 index 00000000..12ef59e1 --- /dev/null +++ b/packages/webui/paraglide/messages/failed_to_add_model.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Failed_To_Add_ModelInputs */ + +const en_failed_to_add_model = /** @type {(inputs: Failed_To_Add_ModelInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Failed to add model`) +}; + +const zh_failed_to_add_model = /** @type {(inputs: Failed_To_Add_ModelInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`添加模型失败`) +}; + +/** +* | output | +* | --- | +* | "Failed to add model" | +* +* @param {Failed_To_Add_ModelInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const failed_to_add_model = /** @type {((inputs?: Failed_To_Add_ModelInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_failed_to_add_model(inputs) + return zh_failed_to_add_model(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/failed_to_remove_model.d.ts b/packages/webui/paraglide/messages/failed_to_remove_model.d.ts new file mode 100644 index 00000000..e0a94bc9 --- /dev/null +++ b/packages/webui/paraglide/messages/failed_to_remove_model.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Failed to remove model" | +* +* @param {Failed_To_Remove_ModelInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const failed_to_remove_model: ((inputs?: Failed_To_Remove_ModelInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Failed_To_Remove_ModelInputs = {}; diff --git a/packages/webui/paraglide/messages/failed_to_remove_model.js b/packages/webui/paraglide/messages/failed_to_remove_model.js new file mode 100644 index 00000000..def8c682 --- /dev/null +++ b/packages/webui/paraglide/messages/failed_to_remove_model.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Failed_To_Remove_ModelInputs */ + +const en_failed_to_remove_model = /** @type {(inputs: Failed_To_Remove_ModelInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Failed to remove model`) +}; + +const zh_failed_to_remove_model = /** @type {(inputs: Failed_To_Remove_ModelInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`移除模型失败`) +}; + +/** +* | output | +* | --- | +* | "Failed to remove model" | +* +* @param {Failed_To_Remove_ModelInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const failed_to_remove_model = /** @type {((inputs?: Failed_To_Remove_ModelInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_failed_to_remove_model(inputs) + return zh_failed_to_remove_model(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/failed_to_save_api_key.d.ts b/packages/webui/paraglide/messages/failed_to_save_api_key.d.ts new file mode 100644 index 00000000..20625d8c --- /dev/null +++ b/packages/webui/paraglide/messages/failed_to_save_api_key.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Failed to update API key" | +* +* @param {Failed_To_Save_Api_KeyInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const failed_to_save_api_key: ((inputs?: Failed_To_Save_Api_KeyInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Failed_To_Save_Api_KeyInputs = {}; diff --git a/packages/webui/paraglide/messages/failed_to_save_api_key.js b/packages/webui/paraglide/messages/failed_to_save_api_key.js new file mode 100644 index 00000000..23f489f0 --- /dev/null +++ b/packages/webui/paraglide/messages/failed_to_save_api_key.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Failed_To_Save_Api_KeyInputs */ + +const en_failed_to_save_api_key = /** @type {(inputs: Failed_To_Save_Api_KeyInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Failed to update API key`) +}; + +const zh_failed_to_save_api_key = /** @type {(inputs: Failed_To_Save_Api_KeyInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`更新 API 密钥失败`) +}; + +/** +* | output | +* | --- | +* | "Failed to update API key" | +* +* @param {Failed_To_Save_Api_KeyInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const failed_to_save_api_key = /** @type {((inputs?: Failed_To_Save_Api_KeyInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_failed_to_save_api_key(inputs) + return zh_failed_to_save_api_key(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/image_video_generation.d.ts b/packages/webui/paraglide/messages/image_video_generation.d.ts new file mode 100644 index 00000000..c1472e04 --- /dev/null +++ b/packages/webui/paraglide/messages/image_video_generation.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Image / Video Generation" | +* +* @param {Image_Video_GenerationInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const image_video_generation: ((inputs?: Image_Video_GenerationInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Image_Video_GenerationInputs = {}; diff --git a/packages/webui/paraglide/messages/image_video_generation.js b/packages/webui/paraglide/messages/image_video_generation.js new file mode 100644 index 00000000..658bc208 --- /dev/null +++ b/packages/webui/paraglide/messages/image_video_generation.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Image_Video_GenerationInputs */ + +const en_image_video_generation = /** @type {(inputs: Image_Video_GenerationInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Image / Video Generation`) +}; + +const zh_image_video_generation = /** @type {(inputs: Image_Video_GenerationInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`图像与视频生成`) +}; + +/** +* | output | +* | --- | +* | "Image / Video Generation" | +* +* @param {Image_Video_GenerationInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const image_video_generation = /** @type {((inputs?: Image_Video_GenerationInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_image_video_generation(inputs) + return zh_image_video_generation(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/loading_models.d.ts b/packages/webui/paraglide/messages/loading_models.d.ts new file mode 100644 index 00000000..66a0360c --- /dev/null +++ b/packages/webui/paraglide/messages/loading_models.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Loading models..." | +* +* @param {Loading_ModelsInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const loading_models: ((inputs?: Loading_ModelsInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Loading_ModelsInputs = {}; diff --git a/packages/webui/paraglide/messages/loading_models.js b/packages/webui/paraglide/messages/loading_models.js new file mode 100644 index 00000000..bf135b23 --- /dev/null +++ b/packages/webui/paraglide/messages/loading_models.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Loading_ModelsInputs */ + +const en_loading_models = /** @type {(inputs: Loading_ModelsInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Loading models...`) +}; + +const zh_loading_models = /** @type {(inputs: Loading_ModelsInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`正在加载模型...`) +}; + +/** +* | output | +* | --- | +* | "Loading models..." | +* +* @param {Loading_ModelsInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const loading_models = /** @type {((inputs?: Loading_ModelsInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_loading_models(inputs) + return zh_loading_models(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/media_generation_settings_description.d.ts b/packages/webui/paraglide/messages/media_generation_settings_description.d.ts new file mode 100644 index 00000000..67fc3fc7 --- /dev/null +++ b/packages/webui/paraglide/messages/media_generation_settings_description.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Configure providers and enabled models for built-in image and video generation tools." | +* +* @param {Media_Generation_Settings_DescriptionInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const media_generation_settings_description: ((inputs?: Media_Generation_Settings_DescriptionInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Media_Generation_Settings_DescriptionInputs = {}; diff --git a/packages/webui/paraglide/messages/media_generation_settings_description.js b/packages/webui/paraglide/messages/media_generation_settings_description.js new file mode 100644 index 00000000..ee6c247e --- /dev/null +++ b/packages/webui/paraglide/messages/media_generation_settings_description.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Media_Generation_Settings_DescriptionInputs */ + +const en_media_generation_settings_description = /** @type {(inputs: Media_Generation_Settings_DescriptionInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Configure providers and enabled models for built-in image and video generation tools.`) +}; + +const zh_media_generation_settings_description = /** @type {(inputs: Media_Generation_Settings_DescriptionInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`配置内置图像和视频生成工具的提供商与已启用模型。`) +}; + +/** +* | output | +* | --- | +* | "Configure providers and enabled models for built-in image and video generation tools." | +* +* @param {Media_Generation_Settings_DescriptionInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const media_generation_settings_description = /** @type {((inputs?: Media_Generation_Settings_DescriptionInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_media_generation_settings_description(inputs) + return zh_media_generation_settings_description(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/media_providers.d.ts b/packages/webui/paraglide/messages/media_providers.d.ts new file mode 100644 index 00000000..2f2f1e28 --- /dev/null +++ b/packages/webui/paraglide/messages/media_providers.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Media Providers" | +* +* @param {Media_ProvidersInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const media_providers: ((inputs?: Media_ProvidersInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Media_ProvidersInputs = {}; diff --git a/packages/webui/paraglide/messages/media_providers.js b/packages/webui/paraglide/messages/media_providers.js new file mode 100644 index 00000000..6c7ac5ea --- /dev/null +++ b/packages/webui/paraglide/messages/media_providers.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Media_ProvidersInputs */ + +const en_media_providers = /** @type {(inputs: Media_ProvidersInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Media Providers`) +}; + +const zh_media_providers = /** @type {(inputs: Media_ProvidersInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`媒体提供商`) +}; + +/** +* | output | +* | --- | +* | "Media Providers" | +* +* @param {Media_ProvidersInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const media_providers = /** @type {((inputs?: Media_ProvidersInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_media_providers(inputs) + return zh_media_providers(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/media_providers_description.d.ts b/packages/webui/paraglide/messages/media_providers_description.d.ts new file mode 100644 index 00000000..283b9b78 --- /dev/null +++ b/packages/webui/paraglide/messages/media_providers_description.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Configure API keys for built-in media generation providers. Providers can use environment variables or custom keys." | +* +* @param {Media_Providers_DescriptionInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const media_providers_description: ((inputs?: Media_Providers_DescriptionInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Media_Providers_DescriptionInputs = {}; diff --git a/packages/webui/paraglide/messages/media_providers_description.js b/packages/webui/paraglide/messages/media_providers_description.js new file mode 100644 index 00000000..f3848bc2 --- /dev/null +++ b/packages/webui/paraglide/messages/media_providers_description.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Media_Providers_DescriptionInputs */ + +const en_media_providers_description = /** @type {(inputs: Media_Providers_DescriptionInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Configure API keys for built-in media generation providers. Providers can use environment variables or custom keys.`) +}; + +const zh_media_providers_description = /** @type {(inputs: Media_Providers_DescriptionInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`为内置媒体生成提供商配置 API 密钥。提供商可以使用环境变量或自定义密钥。`) +}; + +/** +* | output | +* | --- | +* | "Configure API keys for built-in media generation providers. Providers can use environment variables or custom keys." | +* +* @param {Media_Providers_DescriptionInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const media_providers_description = /** @type {((inputs?: Media_Providers_DescriptionInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_media_providers_description(inputs) + return zh_media_providers_description(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/media_type_image.d.ts b/packages/webui/paraglide/messages/media_type_image.d.ts new file mode 100644 index 00000000..b0bcff87 --- /dev/null +++ b/packages/webui/paraglide/messages/media_type_image.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Image" | +* +* @param {Media_Type_ImageInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const media_type_image: ((inputs?: Media_Type_ImageInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Media_Type_ImageInputs = {}; diff --git a/packages/webui/paraglide/messages/media_type_image.js b/packages/webui/paraglide/messages/media_type_image.js new file mode 100644 index 00000000..a855c2f4 --- /dev/null +++ b/packages/webui/paraglide/messages/media_type_image.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Media_Type_ImageInputs */ + +const en_media_type_image = /** @type {(inputs: Media_Type_ImageInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Image`) +}; + +const zh_media_type_image = /** @type {(inputs: Media_Type_ImageInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`图像`) +}; + +/** +* | output | +* | --- | +* | "Image" | +* +* @param {Media_Type_ImageInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const media_type_image = /** @type {((inputs?: Media_Type_ImageInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_media_type_image(inputs) + return zh_media_type_image(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/media_type_video.d.ts b/packages/webui/paraglide/messages/media_type_video.d.ts new file mode 100644 index 00000000..73009367 --- /dev/null +++ b/packages/webui/paraglide/messages/media_type_video.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Video" | +* +* @param {Media_Type_VideoInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const media_type_video: ((inputs?: Media_Type_VideoInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Media_Type_VideoInputs = {}; diff --git a/packages/webui/paraglide/messages/media_type_video.js b/packages/webui/paraglide/messages/media_type_video.js new file mode 100644 index 00000000..45b7fa07 --- /dev/null +++ b/packages/webui/paraglide/messages/media_type_video.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Media_Type_VideoInputs */ + +const en_media_type_video = /** @type {(inputs: Media_Type_VideoInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Video`) +}; + +const zh_media_type_video = /** @type {(inputs: Media_Type_VideoInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`视频`) +}; + +/** +* | output | +* | --- | +* | "Video" | +* +* @param {Media_Type_VideoInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const media_type_video = /** @type {((inputs?: Media_Type_VideoInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_media_type_video(inputs) + return zh_media_type_video(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/model_added_successfully.d.ts b/packages/webui/paraglide/messages/model_added_successfully.d.ts new file mode 100644 index 00000000..9fe79231 --- /dev/null +++ b/packages/webui/paraglide/messages/model_added_successfully.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Model added successfully" | +* +* @param {Model_Added_SuccessfullyInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const model_added_successfully: ((inputs?: Model_Added_SuccessfullyInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Model_Added_SuccessfullyInputs = {}; diff --git a/packages/webui/paraglide/messages/model_added_successfully.js b/packages/webui/paraglide/messages/model_added_successfully.js new file mode 100644 index 00000000..08a5bae8 --- /dev/null +++ b/packages/webui/paraglide/messages/model_added_successfully.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Model_Added_SuccessfullyInputs */ + +const en_model_added_successfully = /** @type {(inputs: Model_Added_SuccessfullyInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Model added successfully`) +}; + +const zh_model_added_successfully = /** @type {(inputs: Model_Added_SuccessfullyInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`模型添加成功`) +}; + +/** +* | output | +* | --- | +* | "Model added successfully" | +* +* @param {Model_Added_SuccessfullyInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const model_added_successfully = /** @type {((inputs?: Model_Added_SuccessfullyInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_model_added_successfully(inputs) + return zh_model_added_successfully(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/model_display_name.d.ts b/packages/webui/paraglide/messages/model_display_name.d.ts new file mode 100644 index 00000000..ab21e794 --- /dev/null +++ b/packages/webui/paraglide/messages/model_display_name.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Display Name (Optional)" | +* +* @param {Model_Display_NameInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const model_display_name: ((inputs?: Model_Display_NameInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Model_Display_NameInputs = {}; diff --git a/packages/webui/paraglide/messages/model_display_name.js b/packages/webui/paraglide/messages/model_display_name.js new file mode 100644 index 00000000..9fe5fb31 --- /dev/null +++ b/packages/webui/paraglide/messages/model_display_name.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Model_Display_NameInputs */ + +const en_model_display_name = /** @type {(inputs: Model_Display_NameInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Display Name (Optional)`) +}; + +const zh_model_display_name = /** @type {(inputs: Model_Display_NameInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`显示名称(可选)`) +}; + +/** +* | output | +* | --- | +* | "Display Name (Optional)" | +* +* @param {Model_Display_NameInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const model_display_name = /** @type {((inputs?: Model_Display_NameInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_model_display_name(inputs) + return zh_model_display_name(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/model_display_name_placeholder.d.ts b/packages/webui/paraglide/messages/model_display_name_placeholder.d.ts new file mode 100644 index 00000000..65dced1b --- /dev/null +++ b/packages/webui/paraglide/messages/model_display_name_placeholder.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Friendly name for this model" | +* +* @param {Model_Display_Name_PlaceholderInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const model_display_name_placeholder: ((inputs?: Model_Display_Name_PlaceholderInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Model_Display_Name_PlaceholderInputs = {}; diff --git a/packages/webui/paraglide/messages/model_display_name_placeholder.js b/packages/webui/paraglide/messages/model_display_name_placeholder.js new file mode 100644 index 00000000..5cae07ca --- /dev/null +++ b/packages/webui/paraglide/messages/model_display_name_placeholder.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Model_Display_Name_PlaceholderInputs */ + +const en_model_display_name_placeholder = /** @type {(inputs: Model_Display_Name_PlaceholderInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Friendly name for this model`) +}; + +const zh_model_display_name_placeholder = /** @type {(inputs: Model_Display_Name_PlaceholderInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`该模型的易读名称`) +}; + +/** +* | output | +* | --- | +* | "Friendly name for this model" | +* +* @param {Model_Display_Name_PlaceholderInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const model_display_name_placeholder = /** @type {((inputs?: Model_Display_Name_PlaceholderInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_model_display_name_placeholder(inputs) + return zh_model_display_name_placeholder(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/model_removed_successfully.d.ts b/packages/webui/paraglide/messages/model_removed_successfully.d.ts new file mode 100644 index 00000000..1a96ceb2 --- /dev/null +++ b/packages/webui/paraglide/messages/model_removed_successfully.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Model removed successfully" | +* +* @param {Model_Removed_SuccessfullyInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const model_removed_successfully: ((inputs?: Model_Removed_SuccessfullyInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Model_Removed_SuccessfullyInputs = {}; diff --git a/packages/webui/paraglide/messages/model_removed_successfully.js b/packages/webui/paraglide/messages/model_removed_successfully.js new file mode 100644 index 00000000..febd662c --- /dev/null +++ b/packages/webui/paraglide/messages/model_removed_successfully.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Model_Removed_SuccessfullyInputs */ + +const en_model_removed_successfully = /** @type {(inputs: Model_Removed_SuccessfullyInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Model removed successfully`) +}; + +const zh_model_removed_successfully = /** @type {(inputs: Model_Removed_SuccessfullyInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`模型移除成功`) +}; + +/** +* | output | +* | --- | +* | "Model removed successfully" | +* +* @param {Model_Removed_SuccessfullyInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const model_removed_successfully = /** @type {((inputs?: Model_Removed_SuccessfullyInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_model_removed_successfully(inputs) + return zh_model_removed_successfully(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/model_requires_api_key_warning.d.ts b/packages/webui/paraglide/messages/model_requires_api_key_warning.d.ts new file mode 100644 index 00000000..f329dac3 --- /dev/null +++ b/packages/webui/paraglide/messages/model_requires_api_key_warning.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "This provider is not configured. Tools using this model will not be available until an API key is configured." | +* +* @param {Model_Requires_Api_Key_WarningInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const model_requires_api_key_warning: ((inputs?: Model_Requires_Api_Key_WarningInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Model_Requires_Api_Key_WarningInputs = {}; diff --git a/packages/webui/paraglide/messages/model_requires_api_key_warning.js b/packages/webui/paraglide/messages/model_requires_api_key_warning.js new file mode 100644 index 00000000..16626f56 --- /dev/null +++ b/packages/webui/paraglide/messages/model_requires_api_key_warning.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Model_Requires_Api_Key_WarningInputs */ + +const en_model_requires_api_key_warning = /** @type {(inputs: Model_Requires_Api_Key_WarningInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`This provider is not configured. Tools using this model will not be available until an API key is configured.`) +}; + +const zh_model_requires_api_key_warning = /** @type {(inputs: Model_Requires_Api_Key_WarningInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`此提供商尚未配置。在配置 API 密钥之前,使用此模型的工具将不可用。`) +}; + +/** +* | output | +* | --- | +* | "This provider is not configured. Tools using this model will not be available until an API key is configured." | +* +* @param {Model_Requires_Api_Key_WarningInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const model_requires_api_key_warning = /** @type {((inputs?: Model_Requires_Api_Key_WarningInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_model_requires_api_key_warning(inputs) + return zh_model_requires_api_key_warning(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/model_type.d.ts b/packages/webui/paraglide/messages/model_type.d.ts new file mode 100644 index 00000000..3f31a829 --- /dev/null +++ b/packages/webui/paraglide/messages/model_type.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Model Type" | +* +* @param {Model_TypeInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const model_type: ((inputs?: Model_TypeInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Model_TypeInputs = {}; diff --git a/packages/webui/paraglide/messages/model_type.js b/packages/webui/paraglide/messages/model_type.js new file mode 100644 index 00000000..b64e26bc --- /dev/null +++ b/packages/webui/paraglide/messages/model_type.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Model_TypeInputs */ + +const en_model_type = /** @type {(inputs: Model_TypeInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Model Type`) +}; + +const zh_model_type = /** @type {(inputs: Model_TypeInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`模型类型`) +}; + +/** +* | output | +* | --- | +* | "Model Type" | +* +* @param {Model_TypeInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const model_type = /** @type {((inputs?: Model_TypeInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_model_type(inputs) + return zh_model_type(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/no_enabled_models.d.ts b/packages/webui/paraglide/messages/no_enabled_models.d.ts new file mode 100644 index 00000000..0ad1917f --- /dev/null +++ b/packages/webui/paraglide/messages/no_enabled_models.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "No media generation models enabled yet. Add at least one image or video model to enable the generation tools." | +* +* @param {No_Enabled_ModelsInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const no_enabled_models: ((inputs?: No_Enabled_ModelsInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type No_Enabled_ModelsInputs = {}; diff --git a/packages/webui/paraglide/messages/no_enabled_models.js b/packages/webui/paraglide/messages/no_enabled_models.js new file mode 100644 index 00000000..b0706eb5 --- /dev/null +++ b/packages/webui/paraglide/messages/no_enabled_models.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} No_Enabled_ModelsInputs */ + +const en_no_enabled_models = /** @type {(inputs: No_Enabled_ModelsInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`No media generation models enabled yet. Add at least one image or video model to enable the generation tools.`) +}; + +const zh_no_enabled_models = /** @type {(inputs: No_Enabled_ModelsInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`尚未启用任何媒体生成模型。添加至少一个图像或视频模型以启用生成工具。`) +}; + +/** +* | output | +* | --- | +* | "No media generation models enabled yet. Add at least one image or video model to enable the generation tools." | +* +* @param {No_Enabled_ModelsInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const no_enabled_models = /** @type {((inputs?: No_Enabled_ModelsInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_no_enabled_models(inputs) + return zh_no_enabled_models(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/provider_status_configured_custom.d.ts b/packages/webui/paraglide/messages/provider_status_configured_custom.d.ts new file mode 100644 index 00000000..a9798ebc --- /dev/null +++ b/packages/webui/paraglide/messages/provider_status_configured_custom.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Configured (Custom)" | +* +* @param {Provider_Status_Configured_CustomInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const provider_status_configured_custom: ((inputs?: Provider_Status_Configured_CustomInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Provider_Status_Configured_CustomInputs = {}; diff --git a/packages/webui/paraglide/messages/provider_status_configured_custom.js b/packages/webui/paraglide/messages/provider_status_configured_custom.js new file mode 100644 index 00000000..69ca9ef9 --- /dev/null +++ b/packages/webui/paraglide/messages/provider_status_configured_custom.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Provider_Status_Configured_CustomInputs */ + +const en_provider_status_configured_custom = /** @type {(inputs: Provider_Status_Configured_CustomInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Configured (Custom)`) +}; + +const zh_provider_status_configured_custom = /** @type {(inputs: Provider_Status_Configured_CustomInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`已配置(自定义)`) +}; + +/** +* | output | +* | --- | +* | "Configured (Custom)" | +* +* @param {Provider_Status_Configured_CustomInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const provider_status_configured_custom = /** @type {((inputs?: Provider_Status_Configured_CustomInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_provider_status_configured_custom(inputs) + return zh_provider_status_configured_custom(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/provider_status_configured_env.d.ts b/packages/webui/paraglide/messages/provider_status_configured_env.d.ts new file mode 100644 index 00000000..abf1801d --- /dev/null +++ b/packages/webui/paraglide/messages/provider_status_configured_env.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Configured (Environment)" | +* +* @param {Provider_Status_Configured_EnvInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const provider_status_configured_env: ((inputs?: Provider_Status_Configured_EnvInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Provider_Status_Configured_EnvInputs = {}; diff --git a/packages/webui/paraglide/messages/provider_status_configured_env.js b/packages/webui/paraglide/messages/provider_status_configured_env.js new file mode 100644 index 00000000..fc261be1 --- /dev/null +++ b/packages/webui/paraglide/messages/provider_status_configured_env.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Provider_Status_Configured_EnvInputs */ + +const en_provider_status_configured_env = /** @type {(inputs: Provider_Status_Configured_EnvInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Configured (Environment)`) +}; + +const zh_provider_status_configured_env = /** @type {(inputs: Provider_Status_Configured_EnvInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`已配置(环境变量)`) +}; + +/** +* | output | +* | --- | +* | "Configured (Environment)" | +* +* @param {Provider_Status_Configured_EnvInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const provider_status_configured_env = /** @type {((inputs?: Provider_Status_Configured_EnvInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_provider_status_configured_env(inputs) + return zh_provider_status_configured_env(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/provider_status_not_configured.d.ts b/packages/webui/paraglide/messages/provider_status_not_configured.d.ts new file mode 100644 index 00000000..050bc5ea --- /dev/null +++ b/packages/webui/paraglide/messages/provider_status_not_configured.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Not Configured" | +* +* @param {Provider_Status_Not_ConfiguredInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const provider_status_not_configured: ((inputs?: Provider_Status_Not_ConfiguredInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Provider_Status_Not_ConfiguredInputs = {}; diff --git a/packages/webui/paraglide/messages/provider_status_not_configured.js b/packages/webui/paraglide/messages/provider_status_not_configured.js new file mode 100644 index 00000000..0ef2f6b4 --- /dev/null +++ b/packages/webui/paraglide/messages/provider_status_not_configured.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Provider_Status_Not_ConfiguredInputs */ + +const en_provider_status_not_configured = /** @type {(inputs: Provider_Status_Not_ConfiguredInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Not Configured`) +}; + +const zh_provider_status_not_configured = /** @type {(inputs: Provider_Status_Not_ConfiguredInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`未配置`) +}; + +/** +* | output | +* | --- | +* | "Not Configured" | +* +* @param {Provider_Status_Not_ConfiguredInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const provider_status_not_configured = /** @type {((inputs?: Provider_Status_Not_ConfiguredInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_provider_status_not_configured(inputs) + return zh_provider_status_not_configured(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/remove_key.d.ts b/packages/webui/paraglide/messages/remove_key.d.ts new file mode 100644 index 00000000..8e9a2854 --- /dev/null +++ b/packages/webui/paraglide/messages/remove_key.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Remove Key" | +* +* @param {Remove_KeyInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const remove_key: ((inputs?: Remove_KeyInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Remove_KeyInputs = {}; diff --git a/packages/webui/paraglide/messages/remove_key.js b/packages/webui/paraglide/messages/remove_key.js new file mode 100644 index 00000000..c064c9d7 --- /dev/null +++ b/packages/webui/paraglide/messages/remove_key.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Remove_KeyInputs */ + +const en_remove_key = /** @type {(inputs: Remove_KeyInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Remove Key`) +}; + +const zh_remove_key = /** @type {(inputs: Remove_KeyInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`移除密钥`) +}; + +/** +* | output | +* | --- | +* | "Remove Key" | +* +* @param {Remove_KeyInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const remove_key = /** @type {((inputs?: Remove_KeyInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_remove_key(inputs) + return zh_remove_key(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/remove_model_confirm.d.ts b/packages/webui/paraglide/messages/remove_model_confirm.d.ts new file mode 100644 index 00000000..bc39bba9 --- /dev/null +++ b/packages/webui/paraglide/messages/remove_model_confirm.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Are you sure you want to remove this model?" | +* +* @param {Remove_Model_ConfirmInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const remove_model_confirm: ((inputs?: Remove_Model_ConfirmInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Remove_Model_ConfirmInputs = {}; diff --git a/packages/webui/paraglide/messages/remove_model_confirm.js b/packages/webui/paraglide/messages/remove_model_confirm.js new file mode 100644 index 00000000..c1b35546 --- /dev/null +++ b/packages/webui/paraglide/messages/remove_model_confirm.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Remove_Model_ConfirmInputs */ + +const en_remove_model_confirm = /** @type {(inputs: Remove_Model_ConfirmInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Are you sure you want to remove this model?`) +}; + +const zh_remove_model_confirm = /** @type {(inputs: Remove_Model_ConfirmInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`确定要移除此模型吗?`) +}; + +/** +* | output | +* | --- | +* | "Are you sure you want to remove this model?" | +* +* @param {Remove_Model_ConfirmInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const remove_model_confirm = /** @type {((inputs?: Remove_Model_ConfirmInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_remove_model_confirm(inputs) + return zh_remove_model_confirm(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/remove_model_prompt.d.ts b/packages/webui/paraglide/messages/remove_model_prompt.d.ts new file mode 100644 index 00000000..35701b79 --- /dev/null +++ b/packages/webui/paraglide/messages/remove_model_prompt.d.ts @@ -0,0 +1,19 @@ +/** +* | output | +* | --- | +* | "Remove model {modelId} ({provider}) from enabled models?" | +* +* @param {Remove_Model_PromptInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const remove_model_prompt: ((inputs: Remove_Model_PromptInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Remove_Model_PromptInputs = { + modelId: NonNullable; + provider: NonNullable; +}; diff --git a/packages/webui/paraglide/messages/remove_model_prompt.js b/packages/webui/paraglide/messages/remove_model_prompt.js new file mode 100644 index 00000000..b4330ebd --- /dev/null +++ b/packages/webui/paraglide/messages/remove_model_prompt.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{ modelId: NonNullable, provider: NonNullable }} Remove_Model_PromptInputs */ + +const en_remove_model_prompt = /** @type {(inputs: Remove_Model_PromptInputs) => LocalizedString} */ (i) => { + return /** @type {LocalizedString} */ (`Remove model ${i?.modelId} (${i?.provider}) from enabled models?`) +}; + +const zh_remove_model_prompt = /** @type {(inputs: Remove_Model_PromptInputs) => LocalizedString} */ (i) => { + return /** @type {LocalizedString} */ (`确定要从已启用模型中移除模型 ${i?.modelId}(${i?.provider})吗?`) +}; + +/** +* | output | +* | --- | +* | "Remove model {modelId} ({provider}) from enabled models?" | +* +* @param {Remove_Model_PromptInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const remove_model_prompt = /** @type {((inputs: Remove_Model_PromptInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_remove_model_prompt(inputs) + return zh_remove_model_prompt(inputs) +}); \ No newline at end of file diff --git a/packages/webui/paraglide/messages/supported_types.d.ts b/packages/webui/paraglide/messages/supported_types.d.ts new file mode 100644 index 00000000..59f150e9 --- /dev/null +++ b/packages/webui/paraglide/messages/supported_types.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Supported" | +* +* @param {Supported_TypesInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const supported_types: ((inputs?: Supported_TypesInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Supported_TypesInputs = {}; diff --git a/packages/webui/paraglide/messages/supported_types.js b/packages/webui/paraglide/messages/supported_types.js new file mode 100644 index 00000000..2f3c8782 --- /dev/null +++ b/packages/webui/paraglide/messages/supported_types.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Supported_TypesInputs */ + +const en_supported_types = /** @type {(inputs: Supported_TypesInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Supported`) +}; + +const zh_supported_types = /** @type {(inputs: Supported_TypesInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`支持类型`) +}; + +/** +* | output | +* | --- | +* | "Supported" | +* +* @param {Supported_TypesInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const supported_types = /** @type {((inputs?: Supported_TypesInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_supported_types(inputs) + return zh_supported_types(inputs) +}); \ No newline at end of file diff --git a/packages/webui/routes/teams/$teamId/settings.lazy.tsx b/packages/webui/routes/teams/$teamId/settings.lazy.tsx index 3faf8728..c0c936d2 100644 --- a/packages/webui/routes/teams/$teamId/settings.lazy.tsx +++ b/packages/webui/routes/teams/$teamId/settings.lazy.tsx @@ -13,6 +13,7 @@ import { McpConfigCard } from '@/ui/components/settings/McpConfigCard' import { NotificationSettings } from '@/ui/components/settings/NotificationSettings' import { DeveloperSettings } from '@/ui/components/settings/DeveloperSettings' import { QuotasSettings } from '@/ui/components/settings/QuotasSettings' +import { ImageVideoGenerationSettings } from '@/ui/components/settings/ImageVideoGenerationSettings' import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/ui/components/ui/card' import { cn } from '@/ui/lib/utils' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' @@ -24,6 +25,7 @@ import { Puzzle, Server, Shield, + Sparkles, User, Bell, Key, @@ -53,6 +55,7 @@ type SettingsTab = | 'skills' | 'mcp' | 'providers' + | 'image-video' | 'agents' | 'sandbox' | 'notifications' @@ -65,6 +68,7 @@ const VALID_SETTINGS_TABS: readonly SettingsTab[] = [ 'skills', 'mcp', 'providers', + 'image-video', 'agents', 'sandbox', 'notifications', @@ -163,6 +167,7 @@ function TeamSettingsPage() { 'transcode', 'quotas', 'providers', + 'image-video', 'skills', 'mcp', 'agents', @@ -447,6 +452,22 @@ function TeamSettingsPage() { )} + +