feat(agent): add built-in image and video generation tools and settings (#382)

* feat(agent): add built-in image and video generation tools and settings

* fix(settings): refine media generation layout and expose media tools in agent and quota forms

* feat(media-generation): add alibaba, bytedance, minimax, prodia, and azure providers

* feat(agent): support s3 key references for media generation and s3KeyOnly in read_asset
This commit is contained in:
Yiling-J
2026-09-06 09:28:53 +08:00
committed by GitHub
parent 1e60933cdb
commit 6285ff8618
114 changed files with 6392 additions and 78 deletions
+108 -15
View File
@@ -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=="],
+210
View File
@@ -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()
}
})
})
+20
View File
@@ -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'
@@ -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.',
)
})
})
})
@@ -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<string> {
)
}
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<typeof downloadAssetSchema> {
return {
name: 'download_asset',
@@ -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')
})
})
+182
View File
@@ -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<string, { apiKey?: string }>,
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<typeof generateImageSchema>
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,
},
}
},
}
}
@@ -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')
})
})
+302
View File
@@ -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<string, { apiKey?: string }>,
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<typeof generateVideoSchema>
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,
},
}
},
}
}
+100
View File
@@ -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")',
)
})
})
})
+121 -59
View File
@@ -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<typeof readAssetS
'Optionally provide annotationId to view visual markups drawn on the asset.',
parameters: readAssetSchema,
execute: async (_toolCallId, params) => {
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<typeof readAssetS
throw new Error('No media content found for this asset.')
}
const { annotations } = await resolveAnnotationsById(asset.id, annotationId)
let keyToUse = mediaKey
let mimeType = getFileMimeType(null, keyToUse, asset.mediaType || 'image/png')
if (annotations) {
const task = await prisma.workflowTask.create({
data: {
assetId: asset.id,
projectId: asset.projectId || 'none',
type: WorkflowTaskType.transcode_image_annotation,
status: WorkflowTaskStatus.pending,
payload: {
if (annotationId) {
const { annotations } = await resolveAnnotationsById(asset.id, annotationId)
if (annotations && annotations.length > 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<typeof readAssetS
asset.name || undefined,
)
const content: Array<TextContent | ImageContent> = [
{
const content: Array<TextContent | ImageContent> = []
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<typeof readAssetS
]
for (const shot of screenshots) {
const { buffer, contentType } = await s3Service.getObject(bucket, shot.key)
const mimeType =
contentType && contentType !== 'application/octet-stream' ? contentType : 'image/webp'
const downloadUrl = await s3Service.presign(
bucket,
shot.key,
@@ -341,18 +357,33 @@ export function createReadAssetTool(userId: string): AgentTool<typeof readAssetS
asset.name || undefined,
)
textLines.push(`- Frame at ${shot.timestamp}s: S3 Key: "${shot.key}"`)
content.push({
type: 'image',
data: buffer.toString('base64'),
mimeType,
})
sourceKeys.push(shot.key)
results.push({
key: shot.key,
timestamp: shot.timestamp,
downloadUrl,
})
if (s3KeyOnly) {
const mimeType = getFileMimeType(null, shot.key, 'image/webp')
textLines.push(
`- Frame at ${shot.timestamp}s (S3 Key: "${shot.key}", MIME: ${mimeType})`,
)
} else {
const { buffer, contentType } = await s3Service.getObject(bucket, shot.key)
const mimeType =
contentType && contentType !== 'application/octet-stream'
? contentType
: getFileMimeType(buffer, shot.key, 'image/webp')
textLines.push(
`- Frame at ${shot.timestamp}s (S3 Key: "${shot.key}", MIME: ${mimeType})`,
)
content.push({
type: 'image',
data: buffer.toString('base64'),
mimeType,
})
}
}
content.unshift({
@@ -411,6 +442,37 @@ export function createReadAssetTool(userId: string): AgentTool<typeof readAssetS
throw new Error(`No media content found for asset ${asset.id}.`)
}
const docMimeType =
asset.mediaType || getFileMimeType(null, asset.name || mediaKey, 'text/plain')
const downloadUrl = await s3Service.presign(
bucket,
mediaKey,
'GET',
true,
asset.name || undefined,
)
if (s3KeyOnly) {
return {
content: [
{
type: 'text',
text: `Document "${asset.name}" (ID: ${asset.id}, MIME: ${docMimeType}, S3 Key: "${mediaKey}")`,
},
],
details: {
assetId: asset.id,
name: asset.name,
mediaType: asset.mediaType,
key: mediaKey,
downloadUrl,
sourceKeys: [mediaKey],
size: 0,
isTruncated: false,
},
}
}
const { buffer } = await s3Service.getObject(bucket, mediaKey)
const rawText = buffer.toString('utf-8')
let text = rawText
@@ -431,19 +493,11 @@ export function createReadAssetTool(userId: string): AgentTool<typeof readAssetS
text += `\n\n[Content truncated to ${MAX_TEXT_LINES} lines / ${MAX_TEXT_BYTES / 1024}KB limit. Use download_asset to process the full file.]`
}
const downloadUrl = await s3Service.presign(
bucket,
mediaKey,
'GET',
true,
asset.name || undefined,
)
return {
content: [
{
type: 'text',
text: `Document "${asset.name}" (ID: ${asset.id}, S3 Key: "${mediaKey}"):\n\n${text}`,
text: `Document "${asset.name}" (ID: ${asset.id}, MIME: ${docMimeType}, S3 Key: "${mediaKey}"):\n\n${text}`,
},
],
details: {
@@ -525,9 +579,6 @@ export function createReadAssetTool(userId: string): AgentTool<typeof readAssetS
]
for (const pageItem of pages) {
const { buffer, contentType } = await s3Service.getObject(bucket, pageItem.key)
const mimeType =
contentType && contentType !== 'application/octet-stream' ? contentType : 'image/webp'
const downloadUrl = await s3Service.presign(
bucket,
pageItem.key,
@@ -536,18 +587,29 @@ export function createReadAssetTool(userId: string): AgentTool<typeof readAssetS
asset.name || undefined,
)
textLines.push(`- Page ${pageItem.page}: S3 Key: "${pageItem.key}"`)
content.push({
type: 'image',
data: buffer.toString('base64'),
mimeType,
})
sourceKeys.push(pageItem.key)
results.push({
key: pageItem.key,
page: pageItem.page,
downloadUrl,
})
if (s3KeyOnly) {
const mimeType = getFileMimeType(null, pageItem.key, 'image/webp')
textLines.push(`- Page ${pageItem.page} (S3 Key: "${pageItem.key}", MIME: ${mimeType})`)
} else {
const { buffer, contentType } = await s3Service.getObject(bucket, pageItem.key)
const mimeType =
contentType && contentType !== 'application/octet-stream'
? contentType
: getFileMimeType(buffer, pageItem.key, 'image/webp')
textLines.push(`- Page ${pageItem.page} (S3 Key: "${pageItem.key}", MIME: ${mimeType})`)
content.push({
type: 'image',
data: buffer.toString('base64'),
mimeType,
})
}
}
content.unshift({
+2
View File
@@ -26,6 +26,7 @@ import teamRoute from './team'
import uploadRoute, { localUploadRoute } from './upload'
import versionStackRoute from './versionStack'
import kanbanRoute from './kanban'
import mediaGenerationRoute from './media-generation'
type User = Prisma.UserGetPayload<Record<string, never>>
@@ -69,6 +70,7 @@ const apiRoute = new Hono<{ Variables: { user: User } }>()
.route('/', watermarkTemplateRoute)
.route('/', quotaRoute)
.route('/', kanbanRoute)
.route('/', mediaGenerationRoute)
app.route('/files', s3Route)
+134
View File
@@ -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')
})
})
+97
View File
@@ -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<Record<string, never>>
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
+19
View File
@@ -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",
+1
View File
@@ -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'
@@ -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)
}
}
})
})
@@ -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<string, BuiltinMediaProviderDef> = {
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<string | Uint8Array | Buffer>
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<string | Uint8Array | Buffer>
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<MediaGenerationSettingsResponse> {
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<void> {
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<EnabledMediaModel> {
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<void> {
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<string, { apiKey?: string }>
}> {
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<string, boolean>()
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<typeof aiGenerateImage>[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<typeof aiGenerateVideo>[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<GenerateVideoOptions['frameImages']> = []
if (params.firstFrame) {
frames.push({
image: params.firstFrame,
frameType: 'first_frame',
} as unknown as NonNullable<GenerateVideoOptions['frameImages']>[number])
}
if (params.lastFrame) {
frames.push({
image: params.lastFrame,
frameType: 'last_frame',
} as unknown as NonNullable<GenerateVideoOptions['frameImages']>[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()
+19
View File
@@ -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<string, MediaProviderConfig>
enabledModels?: EnabledMediaModelConfig[]
}
export interface Settings {
transcode: TranscodeSettings
mediaGeneration?: MediaGenerationSettings
}
// ----------------------------------------------------------------------
+1
View File
@@ -27,3 +27,4 @@ export * from './quota'
export * from './kanban'
export * from './recents'
export * from './context'
export * from './media-generation'
+63
View File
@@ -0,0 +1,63 @@
import { z } from 'zod'
export const mediaModelTypeSchema = z.enum(['image', 'video'])
export type MediaModelType = z.infer<typeof mediaModelTypeSchema>
export const mediaProviderStatusTypeSchema = z.enum([
'configured_custom',
'configured_env',
'not_configured',
])
export type MediaProviderStatusType = z.infer<typeof mediaProviderStatusTypeSchema>
export const updateMediaProviderApiKeySchema = z.object({
apiKey: z.string().optional().or(z.literal('')),
})
export type UpdateMediaProviderApiKeyRequest = z.infer<typeof updateMediaProviderApiKeySchema>
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<typeof createEnabledMediaModelSchema>
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<typeof enabledMediaModelSchema>
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<typeof mediaProviderStatusSchema>
export const mediaGenerationSettingsResponseSchema = z.object({
providers: z.array(mediaProviderStatusSchema),
enabledModels: z.array(enabledMediaModelSchema),
})
export type MediaGenerationSettingsResponse = z.infer<typeof mediaGenerationSettingsResponseSchema>
export const curatedMediaModelSchema = z.object({
modelId: z.string(),
name: z.string(),
type: mediaModelTypeSchema,
})
export type CuratedMediaModel = z.infer<typeof curatedMediaModelSchema>
export const getCuratedMediaModelsQuerySchema = z.object({
provider: z.string().optional(),
type: mediaModelTypeSchema.optional(),
})
export type GetCuratedMediaModelsQuery = z.infer<typeof getCuratedMediaModelsQuerySchema>
@@ -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(
<QueryClientProvider client={queryClient}>
<AgentFormDialog
isOpen={true}
onClose={vi.fn()}
teamId="team-123"
type="chat"
title="Create Agent"
/>
</QueryClientProvider>,
)
expect(screen.getByText('Generate Image')).toBeDefined()
expect(screen.getByText('Generate Video')).toBeDefined()
expect(screen.getByText('Sandboxed Terminal')).toBeDefined()
expect(screen.getByText('Read Asset')).toBeDefined()
})
})
@@ -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<typeof agentFormSchema>
@@ -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(
<QueryClientProvider client={queryClient}>
<ImageVideoGenerationSettings teamId="team-123" />
</QueryClientProvider>,
)
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: '' },
})
})
})
})
@@ -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<string, string> = {
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<MediaProviderStatus | null>(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<string>('')
const [selectedModelId, setSelectedModelId] = useState<string>('')
const [customModelId, setCustomModelId] = useState<string>('')
const [modelDisplayName, setModelDisplayName] = useState<string>('')
// Delete Model Confirmation State
const [modelToDelete, setModelToDelete] = useState<EnabledMediaModel | null>(null)
// Fetch Media Generation Settings
const { data: settings, isLoading } = useQuery<MediaGenerationSettingsResponse>({
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<CuratedMediaModel[]>({
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 (
<div className="flex h-64 items-center justify-center">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
)
}
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 (
<ScrollArea className="h-full pr-1">
<div className="space-y-8 pb-12">
{/* Section 1: Media Providers */}
<Card className="border-border">
<CardHeader>
<CardTitle className="text-base font-semibold">{m.media_providers()}</CardTitle>
<CardDescription>{m.media_providers_description()}</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-2.5">
{providers.map((provider) => {
const displayName = PROVIDER_NAMES[provider.provider] || provider.provider
const isCustom = provider.status === 'configured_custom'
const isEnv = provider.status === 'configured_env'
return (
<div
key={provider.provider}
className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 p-3.5 rounded-lg border border-border bg-card/50 hover:bg-card/80 transition-colors"
>
<div className="flex flex-col sm:flex-row sm:items-center gap-3 sm:gap-4 min-w-0 flex-1">
<div className="min-w-[160px] flex items-center gap-2">
<span className="font-medium text-sm text-foreground truncate">
{displayName}
</span>
{isCustom && (
<Badge
variant="outline"
className="bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/20 text-[11px] shrink-0"
>
<CheckCircle2 className="w-3 h-3 mr-1" />
{m.provider_status_configured_custom()}
</Badge>
)}
{isEnv && (
<Badge
variant="outline"
className="bg-sky-500/10 text-sky-600 dark:text-sky-400 border-sky-500/20 text-[11px] shrink-0"
>
<CheckCircle2 className="w-3 h-3 mr-1" />
{m.provider_status_configured_env()}
</Badge>
)}
{!isCustom && !isEnv && (
<Badge
variant="outline"
className="bg-muted text-muted-foreground border-border text-[11px] shrink-0"
>
{m.provider_status_not_configured()}
</Badge>
)}
</div>
<div className="flex items-center gap-2 flex-wrap">
<div className="flex items-center gap-1.5">
{provider.supportedTypes.includes('image') && (
<span className="inline-flex items-center gap-1 text-[11px] text-muted-foreground bg-accent/60 px-1.5 py-0.5 rounded">
<ImageIcon className="w-3 h-3" />
{m.media_type_image()}
</span>
)}
{provider.supportedTypes.includes('video') && (
<span className="inline-flex items-center gap-1 text-[11px] text-muted-foreground bg-accent/60 px-1.5 py-0.5 rounded">
<VideoIcon className="w-3 h-3" />
{m.media_type_video()}
</span>
)}
</div>
<span className="text-xs text-muted-foreground font-mono opacity-70">
{provider.defaultEnvKey}
</span>
</div>
</div>
<div className="flex items-center justify-end shrink-0">
<Button
variant="outline"
size="sm"
className="text-xs h-8 whitespace-nowrap"
onClick={() => handleOpenKeyDialog(provider)}
>
<Key className="w-3.5 h-3.5 mr-1.5" />
{provider.apiKeyConfigured ? m.edit_api_key() : m.configure_api_key()}
</Button>
</div>
</div>
)
})}
</div>
</CardContent>
</Card>
{/* Section 2: Enabled Models */}
<Card className="border-border">
<CardHeader className="flex flex-row items-center justify-between space-y-0">
<div>
<CardTitle className="text-base font-semibold">{m.enabled_media_models()}</CardTitle>
<CardDescription className="mt-1">
{m.enabled_media_models_description()}
</CardDescription>
</div>
<Button
size="sm"
onClick={() => {
resetAddForm()
setAddDialogOpen(true)
}}
>
<Plus className="w-4 h-4 mr-1.5" />
{m.add_media_model()}
</Button>
</CardHeader>
<CardContent>
{enabledModels.length === 0 ? (
<div className="text-center py-8 text-sm text-muted-foreground">
<p>{m.no_enabled_models()}</p>
</div>
) : (
<div className="rounded-md border border-border">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-[100px]">{m.model_type()}</TableHead>
<TableHead>{m.providers()}</TableHead>
<TableHead>{m.model()}</TableHead>
<TableHead className="w-[80px] text-right"></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{enabledModels.map((model) => {
const isConfigured = activeProvidersMap.get(model.provider) ?? false
const providerDisplayName = PROVIDER_NAMES[model.provider] || model.provider
return (
<TableRow key={model.id}>
<TableCell>
{model.type === 'image' ? (
<Badge
variant="outline"
className="bg-primary/10 text-primary border-primary/20 text-xs gap-1"
>
<ImageIcon className="w-3 h-3" />
{m.media_type_image()}
</Badge>
) : (
<Badge
variant="outline"
className="bg-purple-500/10 text-purple-600 dark:text-purple-400 border-purple-500/20 text-xs gap-1"
>
<VideoIcon className="w-3 h-3" />
{m.media_type_video()}
</Badge>
)}
</TableCell>
<TableCell className="font-medium text-sm">
{providerDisplayName}
</TableCell>
<TableCell>
<div className="flex items-center gap-2">
<span className="font-mono text-xs">{model.modelId}</span>
{model.name && (
<span className="text-xs text-muted-foreground">
({model.name})
</span>
)}
{!isConfigured && (
<div
className="flex items-center gap-1 text-xs text-amber-600 dark:text-amber-400 bg-amber-500/10 px-2 py-0.5 rounded"
title={m.model_requires_api_key_warning()}
>
<AlertCircle className="w-3 h-3" />
<span>{m.provider_status_not_configured()}</span>
</div>
)}
</div>
</TableCell>
<TableCell className="text-right">
<Button
variant="ghost"
size="icon"
className="h-8 w-8 text-muted-foreground hover:text-destructive"
onClick={() => setModelToDelete(model)}
disabled={isRemovingModel}
>
<Trash2 className="w-4 h-4" />
</Button>
</TableCell>
</TableRow>
)
})}
</TableBody>
</Table>
</div>
)}
</CardContent>
</Card>
{/* Dialog: Configure Provider API Key */}
<Dialog open={keyDialogOpen} onOpenChange={setKeyDialogOpen}>
<DialogContent className="sm:max-w-[480px]">
<DialogHeader>
<DialogTitle>
{editingProvider
? `${PROVIDER_NAMES[editingProvider.provider] || editingProvider.provider} API Key`
: m.configure_api_key()}
</DialogTitle>
<DialogDescription>
{editingProvider &&
m.api_key_or_env_var_hint({ envKey: editingProvider.defaultEnvKey })}
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-3">
<div className="space-y-2">
<label className="text-xs font-medium text-foreground">
{m.api_key_or_env_var()}
</label>
<Input
type="password"
value={apiKeyInput}
onChange={(e) => 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"
/>
</div>
</div>
<DialogFooter className="flex items-center justify-between w-full">
{editingProvider?.status === 'configured_custom' ? (
<Button
variant="destructive"
size="sm"
onClick={handleRemoveKey}
disabled={isSavingKey}
>
{m.remove_key()}
</Button>
) : (
<div />
)}
<div className="flex items-center gap-2">
<Button
variant="outline"
onClick={() => setKeyDialogOpen(false)}
disabled={isSavingKey}
>
{m.cancel()}
</Button>
<Button onClick={handleSaveKey} disabled={isSavingKey}>
{isSavingKey && <Loader2 className="w-4 h-4 mr-1.5 animate-spin" />}
{m.save()}
</Button>
</div>
</DialogFooter>
</DialogContent>
</Dialog>
{/* Dialog: Add Model */}
<Dialog open={addDialogOpen} onOpenChange={setAddDialogOpen}>
<DialogContent className="sm:max-w-[500px]">
<DialogHeader>
<DialogTitle>{m.add_media_model()}</DialogTitle>
<DialogDescription>{m.add_media_model_desc()}</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-3">
{/* Type Select */}
<div className="space-y-1.5">
<label className="text-xs font-medium text-foreground">{m.model_type()}</label>
<Select
value={addType}
onValueChange={(val: 'image' | 'video') => {
setAddType(val)
setAddProvider('')
setSelectedModelId('')
setCustomModelId('')
}}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="image">
<div className="flex items-center gap-2">
<ImageIcon className="w-4 h-4" />
<span>{m.media_type_image()}</span>
</div>
</SelectItem>
<SelectItem value="video">
<div className="flex items-center gap-2">
<VideoIcon className="w-4 h-4" />
<span>{m.media_type_video()}</span>
</div>
</SelectItem>
</SelectContent>
</Select>
</div>
{/* Provider Select */}
<div className="space-y-1.5">
<label className="text-xs font-medium text-foreground">{m.select_provider()}</label>
<Select
value={addProvider}
onValueChange={(val) => {
setAddProvider(val)
setSelectedModelId('')
setCustomModelId('')
}}
>
<SelectTrigger>
<SelectValue placeholder={m.select_provider()} />
</SelectTrigger>
<SelectContent>
{compatibleProviders.map((p) => (
<SelectItem key={p.provider} value={p.provider}>
<div className="flex items-center justify-between w-full gap-4">
<span>{PROVIDER_NAMES[p.provider] || p.provider}</span>
{!p.apiKeyConfigured && (
<span className="text-[11px] text-muted-foreground">
({m.provider_status_not_configured()})
</span>
)}
</div>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* Model Select */}
{addProvider && (
<div className="space-y-1.5">
<label className="text-xs font-medium text-foreground">{m.select_model()}</label>
{isLoadingCurated ? (
<div className="flex items-center gap-2 text-xs text-muted-foreground py-2">
<Loader2 className="w-3.5 h-3.5 animate-spin" />
<span>{m.loading_models()}</span>
</div>
) : (
<Select
value={selectedModelId}
onValueChange={(val) => {
setSelectedModelId(val)
if (val !== '__custom__') {
const found = curatedModels?.find((m) => m.modelId === val)
if (found) setModelDisplayName(found.name)
} else {
setModelDisplayName('')
}
}}
>
<SelectTrigger>
<SelectValue placeholder={m.select_model()} />
</SelectTrigger>
<SelectContent>
{curatedModels?.map((curated) => (
<SelectItem key={curated.modelId} value={curated.modelId}>
<div className="flex items-center justify-between w-full gap-2">
<span>{curated.name}</span>
<span className="font-mono text-[11px] text-muted-foreground">
{curated.modelId}
</span>
</div>
</SelectItem>
))}
<SelectItem value="__custom__">
<span className="italic text-muted-foreground">
{m.custom_model_option()}
</span>
</SelectItem>
</SelectContent>
</Select>
)}
</div>
)}
{/* Custom Model ID Input */}
{selectedModelId === '__custom__' && (
<div className="space-y-1.5">
<label className="text-xs font-medium text-foreground">
{m.custom_model_id()}
</label>
<Input
value={customModelId}
onChange={(e) => setCustomModelId(e.target.value)}
placeholder={m.enter_custom_model_id()}
className="font-mono text-sm"
/>
</div>
)}
{/* Display Name Input */}
{addProvider && selectedModelId && (
<div className="space-y-1.5">
<label className="text-xs font-medium text-foreground">
{m.model_display_name()}
</label>
<Input
value={modelDisplayName}
onChange={(e) => setModelDisplayName(e.target.value)}
placeholder={m.model_display_name_placeholder()}
/>
</div>
)}
</div>
<DialogFooter>
<Button
variant="outline"
onClick={() => setAddDialogOpen(false)}
disabled={isAddingModel}
>
{m.cancel()}
</Button>
<Button
onClick={handleAddModelSubmit}
disabled={
isAddingModel ||
!addProvider ||
!selectedModelId ||
(selectedModelId === '__custom__' && !customModelId.trim())
}
>
{isAddingModel && <Loader2 className="w-4 h-4 mr-1.5 animate-spin" />}
{m.add()}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* Alert Dialog: Confirm Model Deletion */}
<AlertDialog
open={!!modelToDelete}
onOpenChange={(open) => {
if (!open) setModelToDelete(null)
}}
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{m.remove_model_confirm()}</AlertDialogTitle>
<AlertDialogDescription>
{modelToDelete &&
m.remove_model_prompt({
modelId: modelToDelete.modelId,
provider: PROVIDER_NAMES[modelToDelete.provider] || modelToDelete.provider,
})}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={isRemovingModel}>{m.cancel()}</AlertDialogCancel>
<AlertDialogAction
onClick={() => {
if (modelToDelete) removeModel(modelToDelete.id)
}}
disabled={isRemovingModel}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{isRemovingModel && <Loader2 className="w-4 h-4 mr-1.5 animate-spin" />}
{m.delete()}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</ScrollArea>
)
}
@@ -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(
<QueryClientProvider client={queryClient}>
<QuotaRuleDialog open={true} onOpenChange={vi.fn()} teamId="team-123" rule={existingRule} />
</QueryClientProvider>,
)
// The select trigger and option both display the selected tool name
expect(screen.getAllByText('Generate Image').length).toBeGreaterThan(0)
})
})
@@ -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 */
+44 -1
View File
@@ -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"
}
+44 -1
View File
@@ -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": "移除密钥"
}
+41
View File
@@ -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;
+42 -1
View File
@@ -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'
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'
+16
View File
@@ -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<Add_Media_ModelInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Add_Media_ModelInputs = {};
+29
View File
@@ -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<Add_Media_ModelInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_add_media_model(inputs)
return zh_add_media_model(inputs)
});
+16
View File
@@ -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<Add_Media_Model_DescInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Add_Media_Model_DescInputs = {};
@@ -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<Add_Media_Model_DescInputs, { locale?: "en" | "zh" }, {}>} */ ((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)
});
+16
View File
@@ -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<Agent_Tool_Generate_Image_DescInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Agent_Tool_Generate_Image_DescInputs = {};
@@ -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<Agent_Tool_Generate_Image_DescInputs, { locale?: "en" | "zh" }, {}>} */ ((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)
});
+16
View File
@@ -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<Agent_Tool_Generate_Image_NameInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Agent_Tool_Generate_Image_NameInputs = {};
@@ -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<Agent_Tool_Generate_Image_NameInputs, { locale?: "en" | "zh" }, {}>} */ ((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)
});
+16
View File
@@ -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<Agent_Tool_Generate_Video_DescInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Agent_Tool_Generate_Video_DescInputs = {};
@@ -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<Agent_Tool_Generate_Video_DescInputs, { locale?: "en" | "zh" }, {}>} */ ((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)
});
+16
View File
@@ -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<Agent_Tool_Generate_Video_NameInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Agent_Tool_Generate_Video_NameInputs = {};
@@ -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<Agent_Tool_Generate_Video_NameInputs, { locale?: "en" | "zh" }, {}>} */ ((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)
});
+16
View File
@@ -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<Api_Key_Or_Env_VarInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Api_Key_Or_Env_VarInputs = {};
+29
View File
@@ -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<Api_Key_Or_Env_VarInputs, { locale?: "en" | "zh" }, {}>} */ ((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)
});
+18
View File
@@ -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<Api_Key_Or_Env_Var_HintInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Api_Key_Or_Env_Var_HintInputs = {
envKey: NonNullable<unknown>;
};
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{ envKey: NonNullable<unknown> }} 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<Api_Key_Or_Env_Var_HintInputs, { locale?: "en" | "zh" }, {}>} */ ((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)
});
+18
View File
@@ -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<Api_Key_Or_Env_Var_PlaceholderInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Api_Key_Or_Env_Var_PlaceholderInputs = {
envKey: NonNullable<unknown>;
};
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{ envKey: NonNullable<unknown> }} 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<Api_Key_Or_Env_Var_PlaceholderInputs, { locale?: "en" | "zh" }, {}>} */ ((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)
});
+16
View File
@@ -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<Api_Key_Saved_SuccessfullyInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Api_Key_Saved_SuccessfullyInputs = {};
@@ -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<Api_Key_Saved_SuccessfullyInputs, { locale?: "en" | "zh" }, {}>} */ ((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)
});
+16
View File
@@ -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<Configure_Api_KeyInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Configure_Api_KeyInputs = {};
+29
View File
@@ -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<Configure_Api_KeyInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_configure_api_key(inputs)
return zh_configure_api_key(inputs)
});
+16
View File
@@ -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<Custom_Model_IdInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Custom_Model_IdInputs = {};
+29
View File
@@ -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<Custom_Model_IdInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_custom_model_id(inputs)
return zh_custom_model_id(inputs)
});
+16
View File
@@ -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<Custom_Model_OptionInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Custom_Model_OptionInputs = {};
+29
View File
@@ -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<Custom_Model_OptionInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_custom_model_option(inputs)
return zh_custom_model_option(inputs)
});
+16
View File
@@ -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<Edit_Api_KeyInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Edit_Api_KeyInputs = {};
+29
View File
@@ -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<Edit_Api_KeyInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_edit_api_key(inputs)
return zh_edit_api_key(inputs)
});
+16
View File
@@ -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<Enabled_Media_ModelsInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Enabled_Media_ModelsInputs = {};
@@ -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<Enabled_Media_ModelsInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_enabled_media_models(inputs)
return zh_enabled_media_models(inputs)
});
@@ -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<Enabled_Media_Models_DescriptionInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Enabled_Media_Models_DescriptionInputs = {};
@@ -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<Enabled_Media_Models_DescriptionInputs, { locale?: "en" | "zh" }, {}>} */ ((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)
});
+16
View File
@@ -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<Enter_Custom_Model_IdInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Enter_Custom_Model_IdInputs = {};
@@ -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<Enter_Custom_Model_IdInputs, { locale?: "en" | "zh" }, {}>} */ ((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)
});
+16
View File
@@ -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<Failed_To_Add_ModelInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Failed_To_Add_ModelInputs = {};
+29
View File
@@ -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<Failed_To_Add_ModelInputs, { locale?: "en" | "zh" }, {}>} */ ((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)
});
+16
View File
@@ -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<Failed_To_Remove_ModelInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Failed_To_Remove_ModelInputs = {};
@@ -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<Failed_To_Remove_ModelInputs, { locale?: "en" | "zh" }, {}>} */ ((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)
});
+16
View File
@@ -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<Failed_To_Save_Api_KeyInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Failed_To_Save_Api_KeyInputs = {};
@@ -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<Failed_To_Save_Api_KeyInputs, { locale?: "en" | "zh" }, {}>} */ ((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)
});
+16
View File
@@ -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<Image_Video_GenerationInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Image_Video_GenerationInputs = {};
@@ -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<Image_Video_GenerationInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_image_video_generation(inputs)
return zh_image_video_generation(inputs)
});
+16
View File
@@ -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<Loading_ModelsInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Loading_ModelsInputs = {};
+29
View File
@@ -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<Loading_ModelsInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_loading_models(inputs)
return zh_loading_models(inputs)
});
@@ -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<Media_Generation_Settings_DescriptionInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Media_Generation_Settings_DescriptionInputs = {};
@@ -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<Media_Generation_Settings_DescriptionInputs, { locale?: "en" | "zh" }, {}>} */ ((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)
});
+16
View File
@@ -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<Media_ProvidersInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Media_ProvidersInputs = {};
+29
View File
@@ -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<Media_ProvidersInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_media_providers(inputs)
return zh_media_providers(inputs)
});
+16
View File
@@ -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<Media_Providers_DescriptionInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Media_Providers_DescriptionInputs = {};
@@ -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<Media_Providers_DescriptionInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_media_providers_description(inputs)
return zh_media_providers_description(inputs)
});
+16
View File
@@ -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<Media_Type_ImageInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Media_Type_ImageInputs = {};
+29
View File
@@ -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<Media_Type_ImageInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_media_type_image(inputs)
return zh_media_type_image(inputs)
});
+16
View File
@@ -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<Media_Type_VideoInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Media_Type_VideoInputs = {};
+29
View File
@@ -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<Media_Type_VideoInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_media_type_video(inputs)
return zh_media_type_video(inputs)
});
+16
View File
@@ -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<Model_Added_SuccessfullyInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Model_Added_SuccessfullyInputs = {};
@@ -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<Model_Added_SuccessfullyInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_model_added_successfully(inputs)
return zh_model_added_successfully(inputs)
});
+16
View File
@@ -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<Model_Display_NameInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Model_Display_NameInputs = {};
+29
View File
@@ -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<Model_Display_NameInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_model_display_name(inputs)
return zh_model_display_name(inputs)
});
+16
View File
@@ -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<Model_Display_Name_PlaceholderInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Model_Display_Name_PlaceholderInputs = {};
@@ -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<Model_Display_Name_PlaceholderInputs, { locale?: "en" | "zh" }, {}>} */ ((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)
});
+16
View File
@@ -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<Model_Removed_SuccessfullyInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Model_Removed_SuccessfullyInputs = {};
@@ -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<Model_Removed_SuccessfullyInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_model_removed_successfully(inputs)
return zh_model_removed_successfully(inputs)
});
+16
View File
@@ -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<Model_Requires_Api_Key_WarningInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Model_Requires_Api_Key_WarningInputs = {};
@@ -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<Model_Requires_Api_Key_WarningInputs, { locale?: "en" | "zh" }, {}>} */ ((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)
});
+16
View File
@@ -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<Model_TypeInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Model_TypeInputs = {};
+29
View File
@@ -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<Model_TypeInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_model_type(inputs)
return zh_model_type(inputs)
});
+16
View File
@@ -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<No_Enabled_ModelsInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type No_Enabled_ModelsInputs = {};
+29
View File
@@ -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<No_Enabled_ModelsInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_no_enabled_models(inputs)
return zh_no_enabled_models(inputs)
});
@@ -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<Provider_Status_Configured_CustomInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Provider_Status_Configured_CustomInputs = {};

Some files were not shown because too many files have changed in this diff Show More