feat(*): 插件中心与模型协议 - 完善声明式协议运行时并增加功能开放控制

This commit is contained in:
ddCat committed 2026-08-23 23:19:27 +08:00
1 parent 7cc6021f6e
commit 919037e5d9
106 files changed
+8816 -499

No files matched your search

-9
View File
@@ -817,15 +817,6 @@ func mergeChannelRequest(req ChannelRequest, channel model.ModelChannel) Channel
return req
}
func validChannelInterfaceType(value model.ChannelInterfaceType) bool {
switch value {
case model.ChannelInterfaceChatCompletion, model.ChannelInterfaceOpenAIResponse, model.ChannelInterfaceOpenAIImage, model.ChannelInterfaceGrokImage, model.ChannelInterfaceVolcengineArkImage, model.ChannelInterfaceVolcengineJiMengImage, model.ChannelInterfaceGeminiImage, model.ChannelInterfaceOpenAIAudio, model.ChannelInterfaceAsyncAudio, model.ChannelInterfaceNewAPIVideo, model.ChannelInterfaceNewAPIChannel1, model.ChannelInterfaceNewAPIChannel2, model.ChannelInterfaceXAIVideo, model.ChannelInterfaceVolcengineArkVideo, model.ChannelInterfaceVolcengineJiMengVideo, model.ChannelInterfaceGeminiVeo, model.ChannelInterfaceNovitaVideo, model.ChannelInterfaceMiniMaxVideo:
return true
default:
return false
}
}
func publicChannel(channel model.ModelChannel, admin bool, channelModels []model.ChannelModel) PublicModelChannel {
models := make([]string, 0, len(channelModels))
modelCosts := make([]PublicChannelModelPrice, 0, len(channelModels))
+27 -16
View File
@@ -11,6 +11,7 @@ import (
"time"
"infinite-canvas/backend/internal/model"
"infinite-canvas/backend/internal/protocol"
"infinite-canvas/backend/internal/repository"
"gorm.io/gorm"
@@ -190,7 +191,7 @@ func (s *Service) SaveAdminChannelModel(actor *model.User, channelID string, id
if err != nil {
return nil, err
}
modelKey, providerModelKey, capability, protocol, err := normalizeChannelModelContract(channel, req)
modelKey, providerModelKey, capability, protocol, err := s.normalizeChannelModelContract(channel, req)
if err != nil {
return nil, err
}
@@ -529,7 +530,7 @@ func (s *Service) TestAdminChannelModel(ctx context.Context, actor *model.User,
if err != nil {
return nil, err
}
modelKey, providerModelKey, capability, protocol, err := normalizeChannelModelContract(channel, req)
modelKey, providerModelKey, capability, protocol, err := s.normalizeChannelModelContract(channel, req)
if err != nil {
return nil, err
}
@@ -610,6 +611,7 @@ func (s *Service) TestAdminChannelModel(ctx context.Context, actor *model.User,
Operation: "admin_model_test", Model: modelKey, VideoSeconds: videoSecondsValue,
})
testCtx = withProviderOutboundPolicy(testCtx, input.Config)
testCtx = withProtocolRegistry(testCtx, s.protocolRegistry())
startedAt := time.Now()
switch capability {
case "text":
@@ -648,6 +650,14 @@ func imageTestDefaults(profile *ImageCapabilityConfig) (string, string) {
}
func normalizeChannelModelContract(channel *model.ModelChannel, req ChannelModelRequest) (string, string, string, model.ChannelInterfaceType, error) {
return normalizeChannelModelContractWithRegistry(protocol.Builtins(), channel, req)
}
func (s *Service) normalizeChannelModelContract(channel *model.ModelChannel, req ChannelModelRequest) (string, string, string, model.ChannelInterfaceType, error) {
return normalizeChannelModelContractWithRegistry(s.protocolRegistry(), channel, req)
}
func normalizeChannelModelContractWithRegistry(registry *protocol.Registry, channel *model.ModelChannel, req ChannelModelRequest) (string, string, string, model.ChannelInterfaceType, error) {
modelKey := strings.TrimPrefix(strings.TrimSpace(req.ModelKey), "models/")
if modelKey == "" {
return "", "", "", "", BadAuthRequest("请填写模型标识")
@@ -660,11 +670,12 @@ func normalizeChannelModelContract(channel *model.ModelChannel, req ChannelModel
if capability == "" {
return "", "", "", "", BadAuthRequest("请选择模型能力")
}
protocol := model.ChannelInterfaceType(strings.TrimSpace(req.Protocol))
if !validChannelInterfaceType(protocol) {
adapter, ok := registry.Resolve(strings.TrimSpace(req.Protocol))
if !ok || !adapter.Metadata().Enabled || adapter.Metadata().UnavailableReason != "" {
return "", "", "", "", BadAuthRequest("请选择有效的模型请求协议")
}
if expected := capabilityForProtocol(protocol); expected != "" && expected != capability {
protocol := model.ChannelInterfaceType(adapter.Metadata().ID)
if expected := protocolCapabilityFromMetadata(adapter.Metadata()); expected != "" && expected != capability {
return "", "", "", "", BadAuthRequest("模型能力与请求协议不匹配")
}
if (protocol == model.ChannelInterfaceVolcengineJiMengImage || protocol == model.ChannelInterfaceVolcengineJiMengVideo) && (strings.TrimSpace(channel.APIKey) == "" || strings.TrimSpace(channel.SecretKey) == "") {
@@ -813,17 +824,17 @@ func (s *Service) syncChannelModelNames(channel *model.ModelChannel) error {
return s.repo.Save(channel)
}
func capabilityForProtocol(protocol model.ChannelInterfaceType) string {
switch protocol {
case model.ChannelInterfaceOpenAIImage, model.ChannelInterfaceGrokImage, model.ChannelInterfaceVolcengineArkImage, model.ChannelInterfaceVolcengineJiMengImage, model.ChannelInterfaceGeminiImage:
return "image"
case model.ChannelInterfaceOpenAIAudio, model.ChannelInterfaceAsyncAudio:
return "audio"
case model.ChannelInterfaceNewAPIVideo, model.ChannelInterfaceNewAPIChannel1, model.ChannelInterfaceNewAPIChannel2, model.ChannelInterfaceXAIVideo, model.ChannelInterfaceVolcengineArkVideo, model.ChannelInterfaceVolcengineJiMengVideo, model.ChannelInterfaceGeminiVeo, model.ChannelInterfaceNovitaVideo, model.ChannelInterfaceMiniMaxVideo:
return "video"
case model.ChannelInterfaceChatCompletion, model.ChannelInterfaceOpenAIResponse:
return "text"
default:
func (s *Service) capabilityForProtocol(protocol model.ChannelInterfaceType) string {
metadata, ok := s.channelProtocolMetadata(string(protocol))
if !ok {
return ""
}
return protocolCapabilityFromMetadata(metadata)
}
func protocolCapabilityFromMetadata(metadata protocol.Metadata) string {
if len(metadata.Categories) == 0 {
return ""
}
return string(metadata.Categories[0])
}
+3
View File
@@ -311,6 +311,9 @@ func (s *Service) AcquireChannelSlot(ctx context.Context, channelID string, fall
}
func (s *Service) ValidateRuntime() error {
if s.pluginRuntimeErr != nil {
return s.pluginRuntimeErr
}
return s.runtimeErr
}
@@ -14,19 +14,23 @@ import (
const featureAvailabilitySettingKey = "feature_availability"
const (
FeatureShortDrama = "shortDrama"
FeatureTaskCenter = "taskCenter"
FeatureCredits = "credits"
FeatureCustomChannels = "customChannels"
FeatureFrontendModels = "frontendModels"
FeatureShortDrama = "shortDrama"
FeatureTaskCenter = "taskCenter"
FeatureCredits = "credits"
FeatureCustomChannels = "customChannels"
FeatureFrontendModels = "frontendModels"
FeaturePluginCenter = "pluginCenter"
FeatureSystemPlugins = "systemPluginsVisibleToUsers"
)
type FeatureAvailability struct {
ShortDramaEnabled bool `json:"shortDramaEnabled"`
TaskCenterEnabled bool `json:"taskCenterEnabled"`
CreditsEnabled bool `json:"creditsEnabled"`
CustomChannelsEnabled bool `json:"customChannelsEnabled"`
FrontendModelsEnabled bool `json:"frontendModelsEnabled"`
ShortDramaEnabled bool `json:"shortDramaEnabled"`
TaskCenterEnabled bool `json:"taskCenterEnabled"`
CreditsEnabled bool `json:"creditsEnabled"`
CustomChannelsEnabled bool `json:"customChannelsEnabled"`
FrontendModelsEnabled bool `json:"frontendModelsEnabled"`
PluginCenterEnabled bool `json:"pluginCenterEnabled"`
SystemPluginsVisibleToUsers bool `json:"systemPluginsVisibleToUsers"`
}
type PublicFeatureAvailability struct {
@@ -39,7 +43,15 @@ type PublicFeatureAvailability struct {
func defaultFeatureAvailability() FeatureAvailability {
// 缺少配置代表尚未由运维接管;前台模型需要明确配置后才开放。
return FeatureAvailability{ShortDramaEnabled: true, TaskCenterEnabled: true, CreditsEnabled: true, CustomChannelsEnabled: true, FrontendModelsEnabled: false}
return FeatureAvailability{
ShortDramaEnabled: true,
TaskCenterEnabled: true,
CreditsEnabled: true,
CustomChannelsEnabled: true,
FrontendModelsEnabled: false,
PluginCenterEnabled: true,
SystemPluginsVisibleToUsers: true,
}
}
func (s *Service) FeatureAvailability() (*PublicFeatureAvailability, error) {
@@ -98,6 +110,10 @@ func (s *Service) FeatureEnabled(feature string) (bool, error) {
return value.CustomChannelsEnabled, nil
case FeatureFrontendModels:
return value.FrontendModelsEnabled, nil
case FeaturePluginCenter:
return value.PluginCenterEnabled, nil
case FeatureSystemPlugins:
return value.SystemPluginsVisibleToUsers, nil
default:
return false, errors.New("未知功能开放配置")
}
@@ -122,6 +138,10 @@ func (s *Service) RequireFeature(feature string) error {
return Forbidden("自定义渠道暂未开放")
case FeatureFrontendModels:
return Forbidden("前台模型目录暂未开放")
case FeaturePluginCenter:
return Forbidden("插件中心暂未开放")
case FeatureSystemPlugins:
return Forbidden("系统插件暂未向普通用户展示")
default:
return Forbidden("该功能暂未开放")
}
@@ -5,6 +5,7 @@ import (
"testing"
"infinite-canvas/backend/internal/model"
"infinite-canvas/backend/internal/protocol"
"infinite-canvas/backend/internal/repository"
"gorm.io/driver/sqlite"
@@ -18,7 +19,7 @@ func TestFeatureAvailabilityDefaultsToDisableFrontendModels(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if setting.Configured || !setting.ShortDramaEnabled || !setting.TaskCenterEnabled || !setting.CreditsEnabled || !setting.CustomChannelsEnabled || setting.FrontendModelsEnabled {
if setting.Configured || !setting.ShortDramaEnabled || !setting.TaskCenterEnabled || !setting.CreditsEnabled || !setting.CustomChannelsEnabled || setting.FrontendModelsEnabled || !setting.PluginCenterEnabled || !setting.SystemPluginsVisibleToUsers {
t.Fatalf("FeatureAvailability() = %#v", setting)
}
}
@@ -34,7 +35,7 @@ func TestFeatureAvailabilityLegacySettingKeepsCustomChannelsEnabled(t *testing.T
if err != nil {
t.Fatal(err)
}
if setting.ShortDramaEnabled || !setting.CustomChannelsEnabled || setting.FrontendModelsEnabled {
if setting.ShortDramaEnabled || !setting.CustomChannelsEnabled || setting.FrontendModelsEnabled || !setting.PluginCenterEnabled || !setting.SystemPluginsVisibleToUsers {
t.Fatalf("FeatureAvailability() = %#v", setting)
}
}
@@ -42,15 +43,18 @@ func TestFeatureAvailabilityLegacySettingKeepsCustomChannelsEnabled(t *testing.T
func TestUpdateFeatureAvailabilityPersistsAndAudits(t *testing.T) {
svc, db := newFeatureAvailabilityTestService(t)
actor := &model.User{ID: "admin-1", Role: model.UserRoleAdmin}
want := FeatureAvailability{ShortDramaEnabled: false, TaskCenterEnabled: true, CreditsEnabled: false, CustomChannelsEnabled: true}
want := FeatureAvailability{ShortDramaEnabled: false, TaskCenterEnabled: true, CreditsEnabled: false, CustomChannelsEnabled: true, PluginCenterEnabled: false, SystemPluginsVisibleToUsers: false}
setting, err := svc.UpdateFeatureAvailability(actor, want)
if err != nil {
t.Fatal(err)
}
if !setting.Configured || setting.ShortDramaEnabled || !setting.TaskCenterEnabled || setting.CreditsEnabled || !setting.CustomChannelsEnabled {
if !setting.Configured || setting.ShortDramaEnabled || !setting.TaskCenterEnabled || setting.CreditsEnabled || !setting.CustomChannelsEnabled || setting.PluginCenterEnabled || setting.SystemPluginsVisibleToUsers {
t.Fatalf("UpdateFeatureAvailability() = %#v", setting)
}
if enabled, err := svc.FeatureEnabled(FeaturePluginCenter); err != nil || enabled {
t.Fatalf("FeatureEnabled(pluginCenter) = %v, %v", enabled, err)
}
if err := svc.RequireFeature(FeatureShortDrama); err == nil {
t.Fatal("RequireFeature(shortDrama) error = nil")
} else {
@@ -68,6 +72,36 @@ func TestUpdateFeatureAvailabilityPersistsAndAudits(t *testing.T) {
}
}
func TestPluginsForUserHidesBundledPluginsOnlyForOrdinaryUsers(t *testing.T) {
svc, _ := newFeatureAvailabilityTestService(t)
admin := &model.User{ID: "admin-1", Role: model.UserRoleAdmin}
if _, err := svc.UpdateFeatureAvailability(admin, FeatureAvailability{
ShortDramaEnabled: true, TaskCenterEnabled: true, CreditsEnabled: true,
CustomChannelsEnabled: true, PluginCenterEnabled: true, SystemPluginsVisibleToUsers: false,
}); err != nil {
t.Fatal(err)
}
svc.pluginRuntime = &pluginRuntime{plugins: map[string]pluginRecord{
"bundled": {Source: "bundled", Metadata: protocol.Metadata{ID: "bundled", Name: "系统协议", Version: "1"}},
"uploaded": {Source: "uploaded", Metadata: protocol.Metadata{ID: "uploaded", Name: "用户协议", Version: "1"}},
}}
visibleToUser, err := svc.PluginsForUser(&model.User{ID: "user-1", Role: model.UserRoleUser})
if err != nil {
t.Fatal(err)
}
if len(visibleToUser) != 1 || visibleToUser[0].Source != "uploaded" {
t.Fatalf("PluginsForUser(user) = %#v", visibleToUser)
}
visibleToAdmin, err := svc.PluginsForUser(admin)
if err != nil {
t.Fatal(err)
}
if len(visibleToAdmin) != 2 {
t.Fatalf("PluginsForUser(admin) = %#v", visibleToAdmin)
}
}
func TestCustomChannelTaskInputRequiresFeature(t *testing.T) {
svc, _ := newFeatureAvailabilityTestService(t)
actor := &model.User{ID: "admin-1", Role: model.UserRoleAdmin}
@@ -36,6 +36,7 @@ type PublicChannelModel struct {
ModelKey string `json:"modelKey"`
DisplayName string `json:"displayName"`
Capability string `json:"capability"`
Protocol model.ChannelInterfaceType `json:"protocol"`
CapabilityConfig map[string]any `json:"capabilityConfig,omitempty"`
PriceTiers []PublicChannelModelPriceTier `json:"priceTiers"`
PricingMode string `json:"pricingMode"`
@@ -180,6 +181,7 @@ func (s *Service) sanitizeChannelModel(cm *model.ChannelModel) PublicChannelMode
ModelKey: cm.ModelKey,
DisplayName: cm.DisplayName,
Capability: cm.Capability,
Protocol: cm.Protocol,
CapabilityConfig: capabilityConfig,
PriceTiers: publicTiers,
PricingMode: pricingMode,
@@ -0,0 +1,399 @@
package service
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"time"
"infinite-canvas/backend/internal/protocol"
)
const protocolPluginMaxBytes = 512 << 10
// PluginView is the backend representation consumed by the single frontend
// plugin center. Protocol-specific runtime data is nested under Protocol so
// the public plugin contract can grow without adding another center API.
type PluginView struct {
Manifest PluginManifestView `json:"manifest"`
Source string `json:"source"`
FileName string `json:"fileName"`
SHA256 string `json:"sha256"`
InstalledAt time.Time `json:"installedAt"`
UpdatedAt time.Time `json:"updatedAt"`
Status string `json:"status"`
Error string `json:"error,omitempty"`
}
type PluginManifestView struct {
ID string `json:"id"`
Name string `json:"name"`
Version string `json:"version"`
APIVersion string `json:"apiVersion"`
Category string `json:"category"`
Description string `json:"description,omitempty"`
Author string `json:"author,omitempty"`
Surfaces []string `json:"surfaces"`
Permissions []string `json:"permissions"`
Trusted bool `json:"trusted"`
Kind string `json:"kind"`
Protocol PluginProtocolView `json:"protocol"`
}
type PluginProtocolView struct {
Categories []string `json:"categories"`
Scopes []string `json:"scopes"`
Create string `json:"create,omitempty"`
Poll string `json:"poll,omitempty"`
Cancel string `json:"cancel,omitempty"`
ContentType string `json:"contentType,omitempty"`
Documentation string `json:"documentation,omitempty"`
Parameters []protocol.Parameter `json:"parameters,omitempty"`
}
type pluginRecord struct {
Raw []byte
Metadata protocol.Metadata
Source string
FileName string
SHA256 string
InstalledAt time.Time
UpdatedAt time.Time
Status string
Error string
}
type pluginRuntime struct {
mu sync.RWMutex
mutationMu sync.Mutex
dir string
plugins map[string]pluginRecord
registry *protocol.Registry
}
func newPluginRuntime(dataDir string) (*pluginRuntime, error) {
dir := filepath.Join(dataDir, "plugins")
if err := os.MkdirAll(dir, 0o755); err != nil {
return nil, fmt.Errorf("create plugin directory: %w", err)
}
center := &pluginRuntime{dir: dir, plugins: make(map[string]pluginRecord)}
if err := center.bootstrapBundledPlugins(); err != nil {
return nil, err
}
if err := center.reload(); err != nil {
return nil, err
}
return center, nil
}
func (c *pluginRuntime) bootstrapBundledPlugins() error {
items := protocol.Builtins().List("", "", true)
for _, metadata := range items {
protocol.AttachDocumentation(&metadata)
metadata.Execution = "host:" + metadata.ID
metadata.Installable = true
path := filepath.Join(c.dir, metadata.ID+".json")
existing, err := os.ReadFile(path)
if err == nil {
var installed protocol.Manifest
if err := json.Unmarshal(existing, &installed); err != nil {
return fmt.Errorf("decode bundled protocol %s: %w", metadata.ID, err)
}
if installed.Metadata.Execution != metadata.Execution {
return fmt.Errorf("protocol id %q is reserved by a bundled plugin", metadata.ID)
}
if metadata.Enabled {
metadata.Enabled = installed.Metadata.Enabled
}
} else if !errors.Is(err, os.ErrNotExist) {
return err
}
manifest := protocol.Manifest{
APIVersion: "v1",
Metadata: metadata,
Create: protocol.ManifestOperation{Method: "POST", Path: "/__host__/" + metadata.ID},
Response: protocol.ManifestResponse{},
}
data, err := json.Marshal(manifest)
if err != nil {
return fmt.Errorf("encode bundled protocol %s: %w", metadata.ID, err)
}
if bytes.Equal(existing, data) {
continue
}
if err := writePluginFile(path, data); err != nil {
return fmt.Errorf("install bundled protocol %s: %w", metadata.ID, err)
}
}
return nil
}
func (c *pluginRuntime) reload() error {
c.mu.Lock()
defer c.mu.Unlock()
entries, err := os.ReadDir(c.dir)
if err != nil {
return err
}
plugins := make(map[string]pluginRecord)
for _, entry := range entries {
if entry.IsDir() || filepath.Ext(entry.Name()) != ".json" {
continue
}
path := filepath.Join(c.dir, entry.Name())
data, readErr := os.ReadFile(path)
if readErr != nil {
return fmt.Errorf("read protocol plugin %s: %w", entry.Name(), readErr)
}
if len(data) > protocolPluginMaxBytes {
return fmt.Errorf("protocol plugin %s exceeds %d bytes", entry.Name(), protocolPluginMaxBytes)
}
var manifest protocol.Manifest
if err := json.Unmarshal(data, &manifest); err != nil {
return fmt.Errorf("decode protocol plugin %s: %w", entry.Name(), err)
}
metadata := manifest.Metadata
if strings.TrimSpace(metadata.ID) == "" {
return fmt.Errorf("protocol plugin %s has no metadata id", entry.Name())
}
if _, exists := plugins[metadata.ID]; exists {
return fmt.Errorf("duplicate installed protocol %q", metadata.ID)
}
now := time.Now().UTC()
stat, _ := os.Stat(path)
updated := now
if stat != nil {
updated = stat.ModTime().UTC()
}
plugins[metadata.ID] = pluginRecord{Raw: data, Metadata: metadata, Source: pluginSource(metadata), FileName: entry.Name(), SHA256: pluginHash(data), InstalledAt: updated, UpdatedAt: updated, Status: "invalid"}
}
registry, err := protocol.NewRegistry()
if err != nil {
return err
}
for id, record := range plugins {
adapter, loadErr := protocol.LoadInstalledPlugin(record.Raw, func(execution string) (protocol.Adapter, bool) {
return protocol.Builtins().Resolve(execution)
})
if loadErr != nil {
record.Metadata.Enabled = false
record.Metadata.UnavailableReason = loadErr.Error()
record.Error = loadErr.Error()
_ = registry.Register(protocol.UnavailableAdapter{Info: record.Metadata})
plugins[id] = record
continue
}
if !record.Metadata.Enabled {
record.Status = "disabled"
_ = registry.Register(protocol.UnavailableAdapter{Info: record.Metadata})
plugins[id] = record
continue
}
if err := registry.Register(adapter); err != nil {
record.Error = err.Error()
plugins[id] = record
continue
}
record.Status = "enabled"
plugins[id] = record
}
c.plugins = plugins
c.registry = registry
return nil
}
func (c *pluginRuntime) list() []PluginView {
c.mu.RLock()
defer c.mu.RUnlock()
items := make([]PluginView, 0, len(c.plugins))
for _, item := range c.plugins {
items = append(items, PluginView{Manifest: pluginManifestView(item.Metadata, item.Source), Source: item.Source, FileName: item.FileName, SHA256: item.SHA256, InstalledAt: item.InstalledAt, UpdatedAt: item.UpdatedAt, Status: item.Status, Error: item.Error})
}
sort.Slice(items, func(i, j int) bool { return items[i].Manifest.ID < items[j].Manifest.ID })
return items
}
func (c *pluginRuntime) registrySnapshot() *protocol.Registry {
c.mu.RLock()
defer c.mu.RUnlock()
return c.registry
}
func (c *pluginRuntime) install(data []byte) (PluginView, error) {
c.mutationMu.Lock()
defer c.mutationMu.Unlock()
if len(data) == 0 || len(data) > protocolPluginMaxBytes {
return PluginView{}, fmt.Errorf("plugin manifest must be between 1 and %d bytes", protocolPluginMaxBytes)
}
var manifest protocol.Manifest
if err := json.Unmarshal(data, &manifest); err != nil {
return PluginView{}, fmt.Errorf("插件清单 JSON 无效:%w", err)
}
if strings.HasPrefix(strings.TrimSpace(manifest.Metadata.Execution), "host:") {
return PluginView{}, errors.New("上传插件不能使用宿主内置执行器")
}
if _, err := protocol.LoadManifest(data); err != nil {
return PluginView{}, err
}
c.mu.RLock()
_, exists := c.plugins[manifest.Metadata.ID]
c.mu.RUnlock()
if exists {
return PluginView{}, fmt.Errorf("插件 ID %q 已存在;当前上传入口不支持覆盖安装", manifest.Metadata.ID)
}
manifest.Metadata.Enabled = true
data, err := json.Marshal(manifest)
if err != nil {
return PluginView{}, err
}
path := filepath.Join(c.dir, manifest.Metadata.ID+".json")
if err := c.persistAndReload(path, data, nil); err != nil {
return PluginView{}, fmt.Errorf("保存插件失败:%w", err)
}
for _, item := range c.list() {
if item.Manifest.ID == manifest.Metadata.ID {
return item, nil
}
}
return PluginView{}, errors.New("插件保存后未加载")
}
func (c *pluginRuntime) setEnabled(id string, enabled bool) (PluginView, error) {
c.mutationMu.Lock()
defer c.mutationMu.Unlock()
c.mu.RLock()
record, ok := c.plugins[strings.TrimSpace(id)]
c.mu.RUnlock()
if !ok {
return PluginView{}, fmt.Errorf("插件 %q 不存在", id)
}
var manifest protocol.Manifest
if err := json.Unmarshal(record.Raw, &manifest); err != nil {
return PluginView{}, err
}
manifest.Metadata.Enabled = enabled
data, err := json.Marshal(manifest)
if err != nil {
return PluginView{}, err
}
if err := c.persistAndReload(filepath.Join(c.dir, record.FileName), data, record.Raw); err != nil {
return PluginView{}, err
}
for _, item := range c.list() {
if item.Manifest.ID == manifest.Metadata.ID {
return item, nil
}
}
return PluginView{}, errors.New("插件状态更新后未加载")
}
func pluginManifestView(metadata protocol.Metadata, source string) PluginManifestView {
if source == "bundled" {
if adapter, ok := protocol.Builtins().Get(metadata.ID); ok {
current := adapter.Metadata()
current.Enabled = current.Enabled && metadata.Enabled
metadata = current
}
protocol.AttachDocumentation(&metadata)
}
categories := make([]string, 0, len(metadata.Categories))
for _, item := range metadata.Categories {
categories = append(categories, string(item))
}
scopes := make([]string, 0, len(metadata.Scopes))
for _, item := range metadata.Scopes {
scopes = append(scopes, string(item))
}
return PluginManifestView{
ID: metadata.ID, Name: metadata.Name, Version: metadata.Version, APIVersion: "v1",
Category: "protocol", Description: metadata.Description, Author: metadata.Vendor,
Surfaces: []string{"hybrid"}, Permissions: []string{"generation.run"},
Trusted: source == "bundled", Kind: "protocol",
Protocol: PluginProtocolView{Categories: categories, Scopes: scopes, Create: metadata.Create, Poll: metadata.Poll, Cancel: metadata.Cancel, ContentType: metadata.ContentType, Documentation: metadata.Documentation, Parameters: metadata.Parameters},
}
}
func (c *pluginRuntime) uninstall(id string) error {
c.mutationMu.Lock()
defer c.mutationMu.Unlock()
c.mu.RLock()
record, ok := c.plugins[strings.TrimSpace(id)]
c.mu.RUnlock()
if !ok {
return fmt.Errorf("协议插件 %q 不存在", id)
}
if record.Source == "bundled" {
return fmt.Errorf("内置协议插件 %q 不能卸载,可停用该插件", id)
}
path := filepath.Join(c.dir, record.FileName)
if err := os.Remove(path); err != nil {
return err
}
if err := c.reload(); err != nil {
_ = writePluginFile(path, record.Raw)
_ = c.reload()
return err
}
return nil
}
func (c *pluginRuntime) persistAndReload(path string, data, rollback []byte) error {
if err := writePluginFile(path, data); err != nil {
return err
}
if err := c.reload(); err != nil {
if rollback == nil {
_ = os.Remove(path)
} else {
_ = writePluginFile(path, rollback)
}
_ = c.reload()
return err
}
return nil
}
func writePluginFile(path string, data []byte) error {
temporary, err := os.CreateTemp(filepath.Dir(path), ".plugin-*.tmp")
if err != nil {
return err
}
temporaryPath := temporary.Name()
defer os.Remove(temporaryPath)
if err := temporary.Chmod(0o600); err != nil {
_ = temporary.Close()
return err
}
if _, err := temporary.Write(data); err != nil {
_ = temporary.Close()
return err
}
if err := temporary.Sync(); err != nil {
_ = temporary.Close()
return err
}
if err := temporary.Close(); err != nil {
return err
}
return os.Rename(temporaryPath, path)
}
func pluginSource(metadata protocol.Metadata) string {
if strings.HasPrefix(strings.TrimSpace(metadata.Execution), "host:") {
return "bundled"
}
return "uploaded"
}
func pluginHash(data []byte) string {
digest := sha256.Sum256(data)
return hex.EncodeToString(digest[:])
}
@@ -0,0 +1,135 @@
package service
import (
"context"
"fmt"
"strings"
"infinite-canvas/backend/internal/model"
"infinite-canvas/backend/internal/protocol"
)
type protocolRegistryContextKey struct{}
func withProtocolRegistry(ctx context.Context, registry *protocol.Registry) context.Context {
return context.WithValue(ctx, protocolRegistryContextKey{}, registry)
}
func declarativeProtocolAdapterForContext(ctx context.Context, id string) (protocol.Adapter, bool) {
registry, _ := ctx.Value(protocolRegistryContextKey{}).(*protocol.Registry)
if registry == nil {
registry = protocol.Builtins()
}
adapter, ok := registry.Resolve(strings.TrimSpace(id))
if !ok || adapter.Metadata().Execution != "declarative" {
return nil, false
}
return adapter, true
}
func agentProtocolAdapterForContext(ctx context.Context, id string) (protocol.AgentAdapter, bool) {
registry, _ := ctx.Value(protocolRegistryContextKey{}).(*protocol.Registry)
if registry == nil {
registry = protocol.Builtins()
}
adapter, ok := registry.Resolve(strings.TrimSpace(id))
if !ok || adapter.Metadata().Execution != "declarative" {
return nil, false
}
agentAdapter, ok := adapter.(protocol.AgentAdapter)
return agentAdapter, ok
}
// ProtocolCatalog is the backend source of truth for the frontend plugin
// center's protocol filtering.
// includeUnavailable is reserved for administrators so incomplete plugins remain visible
// with an explicit reason instead of silently becoming a selectable option.
func (s *Service) ProtocolCatalog(scope, capability string, includeUnavailable bool) []protocol.Metadata {
return s.protocolRegistry().List(protocol.Surface(strings.TrimSpace(scope)), protocol.Capability(strings.TrimSpace(capability)), includeUnavailable)
}
func (s *Service) protocolRegistry() *protocol.Registry {
if s.pluginRuntime != nil {
if registry := s.pluginRuntime.registrySnapshot(); registry != nil {
return registry
}
}
return protocol.Builtins()
}
func (s *Service) protocolMetadata(id string) (protocol.Metadata, bool) {
adapter, ok := s.protocolRegistry().Resolve(strings.TrimSpace(id))
if !ok {
return protocol.Metadata{}, false
}
return adapter.Metadata(), true
}
func (s *Service) channelProtocolMetadata(id string) (protocol.Metadata, bool) {
return s.protocolMetadata(id)
}
func (s *Service) canonicalProtocolID(id string) (string, bool) {
adapter, ok := s.protocolRegistry().Resolve(strings.TrimSpace(id))
if !ok {
return "", false
}
return adapter.Metadata().ID, true
}
func (s *Service) protocolIsSelectable(id string) bool {
metadata, ok := s.channelProtocolMetadata(id)
return ok && metadata.Enabled && metadata.UnavailableReason == ""
}
func (s *Service) Plugins() []PluginView {
if s.pluginRuntime == nil {
return []PluginView{}
}
return s.pluginRuntime.list()
}
// PluginsForUser keeps the plugin center response aligned with the public
// feature switch. Administrators must still be able to inspect and recover
// bundled plugins even when ordinary users cannot see them.
func (s *Service) PluginsForUser(actor *model.User) ([]PluginView, error) {
items := s.Plugins()
if actor != nil && actor.Role == model.UserRoleAdmin {
return items, nil
}
visible, err := s.FeatureEnabled(FeatureSystemPlugins)
if err != nil {
return nil, err
}
if visible {
return items, nil
}
filtered := make([]PluginView, 0, len(items))
for _, item := range items {
if item.Source != "bundled" {
filtered = append(filtered, item)
}
}
return filtered, nil
}
func (s *Service) InstallPlugin(data []byte) (PluginView, error) {
if s.pluginRuntime == nil {
return PluginView{}, fmt.Errorf("插件运行时未初始化")
}
return s.pluginRuntime.install(data)
}
func (s *Service) SetPluginEnabled(id string, enabled bool) (PluginView, error) {
if s.pluginRuntime == nil {
return PluginView{}, fmt.Errorf("插件运行时未初始化")
}
return s.pluginRuntime.setEnabled(id, enabled)
}
func (s *Service) UninstallPlugin(id string) error {
if s.pluginRuntime == nil {
return fmt.Errorf("插件运行时未初始化")
}
return s.pluginRuntime.uninstall(id)
}
@@ -0,0 +1,114 @@
package service
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"infinite-canvas/backend/internal/protocol"
)
func TestPluginViewIncludesDocumentationForEveryBundledProtocol(t *testing.T) {
center, err := newPluginRuntime(t.TempDir())
if err != nil {
t.Fatal(err)
}
plugins := center.list()
if len(plugins) != len(protocol.Builtins().List("", "", true)) {
t.Fatalf("plugin views = %d, builtins = %d", len(plugins), len(protocol.Builtins().List("", "", true)))
}
for _, plugin := range plugins {
if plugin.Source != "bundled" {
continue
}
document := strings.TrimSpace(plugin.Manifest.Protocol.Documentation)
if document == "" || !strings.Contains(document, "## 影策运行时合同") {
t.Errorf("bundled plugin %q has no complete documentation in PluginView", plugin.Manifest.ID)
}
}
}
func TestPluginRuntimeIsTheProtocolSourceOfTruth(t *testing.T) {
dataDir := t.TempDir()
center, err := newPluginRuntime(dataDir)
if err != nil {
t.Fatal(err)
}
if got := center.registrySnapshot().List("", "", false); len(got) == 0 {
t.Fatal("bundled protocols were not reconciled into a new plugin directory")
}
manifest := []byte(`{"apiVersion":"v1","metadata":{"id":"uploaded-runtime","version":"1.0.0","name":"Uploaded Runtime","vendor":"Test","categories":["video"],"scopes":["canvas"],"documentation":"# Uploaded Runtime"},"create":{"method":"POST","path":"/tasks","fields":{"prompt":"request.prompt"}},"response":{"statusPaths":["status"]}}`)
plugin, err := center.install(manifest)
if err != nil {
t.Fatal(err)
}
if plugin.Status != "enabled" || !center.registrySnapshot().IsCapability("uploaded-runtime", protocol.CapabilityVideo) {
t.Fatalf("installed plugin was not activated: %#v", plugin)
}
if _, err := center.install(manifest); err == nil {
t.Fatal("duplicate plugin id overwrote an installed plugin")
}
if _, err := center.setEnabled("uploaded-runtime", false); err != nil {
t.Fatal(err)
}
if _, ok := center.registrySnapshot().Resolve("uploaded-runtime"); !ok {
t.Fatal("disabled plugin was removed from registry snapshot instead of being represented as unavailable")
}
if center.registrySnapshot().IsCapability("uploaded-runtime", protocol.CapabilityVideo) {
t.Fatal("disabled plugin remained selectable")
}
if err := center.uninstall("uploaded-runtime"); err != nil {
t.Fatal(err)
}
if _, ok := center.registrySnapshot().Resolve("uploaded-runtime"); ok {
t.Fatal("uninstalled plugin remained selectable")
}
}
func TestDeclarativeProtocolRuntimeExecutesCreatePollAndDownload(t *testing.T) {
manifest := []byte(`{
"apiVersion":"v1",
"metadata":{"id":"test-declarative-video-runtime","version":"1.0.0","name":"Test Declarative Video","vendor":"Test","categories":["video"],"scopes":["canvas"],"documentation":"# Test Declarative Video"},
"create":{"method":"POST","path":"/tasks","fields":{"model":"request.model","prompt":"request.prompt","seconds":"request.duration"}},
"poll":{"method":"GET","path":"/tasks/{{taskId}}"},
"response":{"taskIdPaths":["id"],"statusPaths":["status"],"resultUrlPaths":["video_url"],"resultKind":"video"}
}`)
center, err := newPluginRuntime(t.TempDir())
if err != nil {
t.Fatal(err)
}
if _, err := center.install(manifest); err != nil {
t.Fatal(err)
}
var server *httptest.Server
server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/v1/tasks":
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"id":"task-1","status":"pending"}`))
case "/v1/tasks/task-1":
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"id":"task-1","status":"succeeded","video_url":"` + server.URL + `/media.mp4"}`))
case "/media.mp4":
w.Header().Set("Content-Type", "video/mp4")
_, _ = w.Write([]byte("video"))
default:
http.NotFound(w, r)
}
}))
defer server.Close()
config := providerConfig{BaseURL: server.URL + "/v1", APIKey: "key", Model: "test-model", APIFormat: "openai", InterfaceType: "test-declarative-video-runtime", AllowLocalChannel: true}
ctx := withProviderOutboundPolicy(context.Background(), config)
ctx = withProtocolRegistry(ctx, center.registrySnapshot())
result, err := runDeclarativeProtocolTask(ctx, canvasGenerationInput{Mode: "video", Prompt: "a clip", Config: config})
if err != nil {
t.Fatal(err)
}
if result["mode"] != "video" {
t.Fatalf("result = %#v", result)
}
}
+608 -26
View File
@@ -22,6 +22,7 @@ import (
"time"
"infinite-canvas/backend/internal/model"
"infinite-canvas/backend/internal/protocol"
"gorm.io/gorm"
)
@@ -253,6 +254,7 @@ func providerPayloadErrorMessage(raw string) string {
}
func (s *Service) processCanvasGenerationTask(ctx context.Context, userID string, taskProjectID string, taskType string, fallbackPrompt string, rawInput string) (map[string]interface{}, error) {
ctx = withProtocolRegistry(ctx, s.protocolRegistry())
var input canvasGenerationInput
if err := json.Unmarshal([]byte(rawInput), &input); err != nil {
return nil, fmt.Errorf("任务输入解析失败:%w", err)
@@ -293,7 +295,7 @@ func (s *Service) processCanvasGenerationTask(ctx context.Context, userID string
if strings.TrimSpace(input.Config.BaseURL) == "" || strings.TrimSpace(input.Config.APIKey) == "" || strings.TrimSpace(input.Config.Model) == "" {
return nil, errors.New("后端生成任务缺少 Base URL、API Key 或模型名")
}
if err := validateGenerationInterface(input.Mode, input.Config.InterfaceType); err != nil {
if err := s.validateGenerationInterface(input.Mode, input.Config.InterfaceType); err != nil {
return nil, err
}
if isVolcengineJiMengProtocol(input.Config.InterfaceType) && strings.TrimSpace(input.Config.SecretKey) == "" {
@@ -345,6 +347,12 @@ func (s *Service) processCanvasGenerationTask(ctx context.Context, userID string
}
func runAgentToolTask(ctx context.Context, input canvasGenerationInput) (map[string]interface{}, error) {
if adapter, ok := agentProtocolAdapterForContext(ctx, input.Config.InterfaceType); ok {
return runDeclarativeAgentTask(ctx, input, adapter)
}
if input.AgentRequests == nil {
return nil, errors.New("画布 Agent 工具请求缺少协议参数")
}
request := input.AgentRequests.ChatCompletion
path := "/chat/completions"
protocol := "chat-completion"
@@ -352,11 +360,17 @@ func runAgentToolTask(ctx context.Context, input canvasGenerationInput) (map[str
request = input.AgentRequests.Responses
path = "/responses"
protocol = "responses"
} else if input.Config.InterfaceType == string(model.ChannelInterfaceClaudeAPI) {
path = "/messages"
protocol = "claude-api"
}
if request == nil {
return nil, errors.New("画布 Agent 工具请求缺少协议参数")
}
body := cloneStringAnyMap(request)
if protocol == "claude-api" {
body = claudeAgentBody(body)
}
body["model"] = input.Config.Model
var payload map[string]interface{}
err := postJSON(ctx, input.Config, path, body, &payload)
@@ -380,6 +394,152 @@ func runAgentToolTask(ctx context.Context, input canvasGenerationInput) (map[str
return parseAgentToolPayload(payload, protocol)
}
func runDeclarativeAgentTask(ctx context.Context, input canvasGenerationInput, adapter protocol.AgentAdapter) (map[string]interface{}, error) {
if input.AgentRequests == nil {
return nil, errors.New("画布 Agent 工具请求缺少协议参数")
}
request := map[string]any{
"chatCompletion": input.AgentRequests.ChatCompletion,
"responses": input.AgentRequests.Responses,
}
spec, err := adapter.BuildAgent(ctx, protocol.AgentRequestContext{BaseURL: input.Config.BaseURL, Model: input.Config.Model, Request: request})
if err != nil {
return nil, err
}
body, err := executeProtocolRequest(ctx, input.Config, spec)
if err != nil {
return nil, err
}
parsed, err := adapter.ParseAgent(ctx, body)
if err != nil {
return nil, err
}
result := map[string]interface{}{"mode": "text", "text": parsed.Text, "toolCalls": []interface{}{}}
if parsed.Reasoning != "" {
result["reasoning"] = parsed.Reasoning
}
calls := make([]interface{}, 0, len(parsed.ToolCalls))
for _, call := range parsed.ToolCalls {
calls = append(calls, map[string]interface{}{
"id": call.ID,
"type": "function",
"function": map[string]interface{}{"name": call.Name, "arguments": call.Arguments},
})
}
result["toolCalls"] = calls
if strings.TrimSpace(parsed.Text) == "" && len(calls) == 0 {
return nil, errors.New("声明式 Agent 接口没有返回内容")
}
return result, nil
}
func claudeAgentBody(request map[string]interface{}) map[string]interface{} {
body := map[string]interface{}{"max_tokens": 4096}
if messages, ok := request["messages"].([]interface{}); ok {
claudeMessages := make([]interface{}, 0, len(messages))
var system []string
for _, value := range messages {
message, _ := value.(map[string]interface{})
role := strings.ToLower(strings.TrimSpace(stringField(message, "role")))
if role == "system" {
if content := strings.TrimSpace(fmt.Sprint(message["content"])); content != "" {
system = append(system, content)
}
continue
}
if role == "tool" {
claudeMessages = append(claudeMessages, map[string]interface{}{"role": "user", "content": []interface{}{map[string]interface{}{
"type": "tool_result", "tool_use_id": stringField(message, "tool_call_id"), "content": fmt.Sprint(message["content"]),
}}})
continue
}
role = mapClaudeMessageRole(role)
content := message["content"]
if content == nil {
content = ""
}
if toolCalls, ok := message["tool_calls"].([]interface{}); ok && len(toolCalls) > 0 {
blocks := make([]interface{}, 0, len(toolCalls))
for _, value := range toolCalls {
toolCall, _ := value.(map[string]interface{})
function, _ := toolCall["function"].(map[string]interface{})
blocks = append(blocks, map[string]interface{}{
"type": "tool_use", "id": stringField(toolCall, "id"), "name": stringField(function, "name"), "input": claudeToolInput(function["arguments"]),
})
}
content = blocks
}
claudeMessages = append(claudeMessages, map[string]interface{}{"role": role, "content": content})
}
body["messages"] = claudeMessages
if len(system) > 0 {
body["system"] = strings.Join(system, "\n\n")
}
}
if tools, ok := request["tools"].([]interface{}); ok && len(tools) > 0 {
claudeTools := make([]interface{}, 0, len(tools))
for _, value := range tools {
tool, _ := value.(map[string]interface{})
function, _ := tool["function"].(map[string]interface{})
if len(function) == 0 {
continue
}
claudeTools = append(claudeTools, map[string]interface{}{
"name": stringField(function, "name"), "description": stringField(function, "description"), "input_schema": function["parameters"],
})
}
if len(claudeTools) > 0 {
body["tools"] = claudeTools
}
}
if choice, ok := request["tool_choice"]; ok {
body["tool_choice"] = claudeToolChoice(choice)
}
return body
}
func mapClaudeMessageRole(role string) string {
if role == "assistant" {
return "assistant"
}
return "user"
}
func claudeToolInput(value interface{}) interface{} {
if raw, ok := value.(string); ok {
var parsed interface{}
if json.Unmarshal([]byte(raw), &parsed) == nil && parsed != nil {
return parsed
}
}
if value != nil {
return value
}
return map[string]interface{}{}
}
func claudeToolChoice(value interface{}) interface{} {
switch choice := value.(type) {
case string:
switch strings.ToLower(strings.TrimSpace(choice)) {
case "required":
return map[string]interface{}{"type": "any"}
case "none":
return map[string]interface{}{"type": "auto"}
default:
return map[string]interface{}{"type": "auto"}
}
case map[string]interface{}:
if function, ok := choice["function"].(map[string]interface{}); ok && stringField(function, "name") != "" {
return map[string]interface{}{"type": "tool", "name": stringField(function, "name")}
}
if name := stringField(choice, "name"); name != "" {
return map[string]interface{}{"type": "tool", "name": name}
}
}
return map[string]interface{}{"type": "auto"}
}
func isAgentToolChoiceCompatibilityError(err error) bool {
if err == nil {
return false
@@ -418,6 +578,28 @@ func parseAgentToolPayload(payload map[string]interface{}, protocol string) (map
result["toolCalls"] = calls
return result, nil
}
if protocol == "claude-api" {
content := interfaceSlice(payload["content"])
calls := make([]interface{}, 0)
for _, value := range content {
item, _ := value.(map[string]interface{})
switch stringField(item, "type") {
case "text":
result["text"] = result["text"].(string) + stringField(item, "text")
case "tool_use":
arguments, err := json.Marshal(item["input"])
if err != nil {
return nil, err
}
calls = append(calls, map[string]interface{}{"id": stringField(item, "id"), "type": "function", "function": map[string]interface{}{"name": stringField(item, "name"), "arguments": string(arguments)}})
}
}
result["toolCalls"] = calls
if result["text"] == "" && len(calls) == 0 {
return nil, errors.New("Claude Agent 接口没有返回内容")
}
return result, nil
}
choices := interfaceSlice(payload["choices"])
if len(choices) == 0 {
return nil, errors.New("画布 Agent 接口没有返回 choices")
@@ -877,6 +1059,8 @@ func (s *Service) resolveProviderConfig(config providerConfig) (providerConfig,
// 模型协议是实际请求契约;混合渠道中鉴权格式也必须随模型协议切换。
if config.InterfaceType == string(model.ChannelInterfaceGeminiVeo) || config.InterfaceType == string(model.ChannelInterfaceGeminiImage) {
config.APIFormat = "gemini"
} else if config.InterfaceType == string(model.ChannelInterfaceClaudeAPI) {
config.APIFormat = "claude"
} else if config.InterfaceType != "" {
config.APIFormat = "openai"
}
@@ -900,21 +1084,37 @@ func providerChannelModelKey(config providerConfig) string {
func systemChannelIDFromBaseURL(baseURL string) string {
value := strings.TrimSpace(baseURL)
for _, marker := range []string{"/api/ai/system/", "api/ai/system/"} {
index := strings.Index(value, marker)
lowerValue := strings.ToLower(value)
for _, marker := range []string{"/api/ai/system/", "/api/"} {
index := strings.LastIndex(lowerValue, marker)
if index < 0 {
continue
}
id := strings.Trim(value[index+len(marker):], "/")
if queryIndex := strings.IndexAny(id, "?#"); queryIndex >= 0 {
id = id[:queryIndex]
}
if slash := strings.Index(id, "/"); slash >= 0 {
id = id[:slash]
continue
}
id = strings.TrimSpace(id)
if id == "" {
continue
}
switch strings.ToLower(id) {
case "v1", "v1beta", "v2", "v3", "plan", "ai":
continue
default:
return id
}
return strings.TrimSpace(id)
}
return ""
}
func runImageTask(ctx context.Context, input canvasGenerationInput) (map[string]interface{}, error) {
if _, ok := declarativeProtocolAdapterForContext(ctx, input.Config.InterfaceType); ok {
return runDeclarativeProtocolTask(ctx, input)
}
if input.Config.InterfaceType == string(model.ChannelInterfaceGrokImage) {
return runGrokImageTask(ctx, input)
}
@@ -1390,11 +1590,16 @@ func normalizeVolcengineArkImageSize(value string) string {
}
func runTextTask(ctx context.Context, input canvasGenerationInput) (map[string]interface{}, error) {
if _, ok := declarativeProtocolAdapterForContext(ctx, input.Config.InterfaceType); ok {
return runDeclarativeProtocolTask(ctx, input)
}
switch input.Config.InterfaceType {
case "chat-completion":
return runChatCompletionsTextTask(ctx, input)
case "openai-response":
return runResponsesTextTask(ctx, input)
case string(model.ChannelInterfaceClaudeAPI):
return runClaudeTextTask(ctx, input)
}
return runLegacyTextTask(ctx, input)
}
@@ -1451,6 +1656,68 @@ func runChatCompletionsTextTask(ctx context.Context, input canvasGenerationInput
return map[string]interface{}{"mode": "text", "text": text}, nil
}
func runClaudeTextTask(ctx context.Context, input canvasGenerationInput) (map[string]interface{}, error) {
if len(input.ReferenceVideos) > 0 {
return nil, errors.New("Claude API 当前不支持视频参考输入")
}
messages := make([]map[string]interface{}, 0, len(input.TextHistory)+1)
for _, message := range validatedTextHistory(input.TextHistory) {
messages = append(messages, message)
}
content, err := claudeTextContent(input)
if err != nil {
return nil, err
}
messages = append(messages, map[string]interface{}{"role": "user", "content": content})
body := map[string]interface{}{"model": input.Config.Model, "max_tokens": 4096, "messages": messages}
if systemPrompt := strings.TrimSpace(input.Config.SystemPrompt); systemPrompt != "" {
body["system"] = systemPrompt
}
text, err := requestTextProvider(ctx, input.Config, "/messages", body, "claude-api", input.StreamText)
if err != nil {
return nil, err
}
return map[string]interface{}{"mode": "text", "text": text}, nil
}
func claudeTextContent(input canvasGenerationInput) (interface{}, error) {
if len(input.ReferenceImages) == 0 {
return input.Prompt, nil
}
content := []map[string]interface{}{{"type": "text", "text": input.Prompt}}
for _, image := range input.ReferenceImages {
value, err := openAIImageInputURL(image)
if err != nil {
return nil, err
}
if strings.HasPrefix(value, "data:") {
mimeType, data, ok := splitDataURL(value)
if !ok {
return nil, errors.New("Claude 参考图片 data URL 无效")
}
content = append(content, map[string]interface{}{"type": "image", "source": map[string]interface{}{"type": "base64", "media_type": mimeType, "data": data}})
} else {
content = append(content, map[string]interface{}{"type": "image", "source": map[string]interface{}{"type": "url", "url": value}})
}
}
return content, nil
}
func splitDataURL(value string) (string, string, bool) {
if !strings.HasPrefix(value, "data:") {
return "", "", false
}
separator := strings.Index(value, ",")
if separator <= len("data:") {
return "", "", false
}
header := strings.TrimPrefix(value[:separator], "data:")
if !strings.HasSuffix(header, ";base64") {
return "", "", false
}
return strings.TrimSuffix(header, ";base64"), value[separator+1:], value[separator+1:] != ""
}
func textResponseInput(input canvasGenerationInput) (interface{}, error) {
systemPrompt := strings.TrimSpace(input.Config.SystemPrompt)
if len(input.TextHistory) == 0 && len(input.ReferenceImages) == 0 && len(input.ReferenceVideos) == 0 {
@@ -1573,6 +1840,9 @@ func shouldFallbackTextToChat(err error) bool {
}
func runAudioTask(ctx context.Context, input canvasGenerationInput) (map[string]interface{}, error) {
if _, ok := declarativeProtocolAdapterForContext(ctx, input.Config.InterfaceType); ok {
return runDeclarativeProtocolTask(ctx, input)
}
if resolved, ok := input.Metadata["resolvedCharacterVersions"].([]interface{}); ok && len(resolved) > 0 {
voiceKey := metadataString(input.Metadata, "resolvedCharacterVoiceKey")
if voiceKey == "" || strings.TrimSpace(input.Config.AudioVoice) != voiceKey {
@@ -1607,6 +1877,215 @@ func runAudioTask(ctx context.Context, input canvasGenerationInput) (map[string]
return map[string]interface{}{"mode": "audio", "audio": map[string]interface{}{"dataUrl": dataURL(mimeType, data), "mimeType": mimeType, "format": format}}, nil
}
// runDeclarativeProtocolTask is the host runtime for JSON manifest plugins.
// Manifest code only describes request/response mapping; credentials, outbound
// policy, polling and result downloads remain owned by the host.
func runDeclarativeProtocolTask(ctx context.Context, input canvasGenerationInput) (map[string]interface{}, error) {
adapter, ok := declarativeProtocolAdapterForContext(ctx, input.Config.InterfaceType)
if !ok {
return nil, fmt.Errorf("接口类型 %s 未安装声明式适配器", input.Config.InterfaceType)
}
request := protocolRequestFromInput(input)
taskID := resumedProviderRequestID(ctx)
var created protocol.CreateResult
if taskID == "" {
spec, err := adapter.BuildCreate(ctx, protocol.RequestContext{BaseURL: input.Config.BaseURL, Request: request})
if err != nil {
return nil, err
}
body, err := executeProtocolRequest(ctx, input.Config, spec)
if err != nil {
return nil, err
}
created, err = adapter.ParseCreate(ctx, body)
if err != nil {
return nil, err
}
taskID = created.TaskID
if created.Status == protocol.StatusFailed || created.Status == protocol.StatusCancelled {
return nil, protocolResultError(created.Message, taskID)
}
if created.Status == protocol.StatusSucceeded {
return finishProtocolResult(ctx, input.Config, input.Mode, created.Result)
}
if taskID == "" {
return nil, errors.New("声明式协议创建请求没有返回任务 ID")
}
}
for deadline := providerPollingDeadline(ctx); time.Now().Before(deadline); {
spec, err := adapter.BuildPoll(ctx, protocol.PollContext{BaseURL: input.Config.BaseURL, Model: request.Model, Request: request, TaskID: taskID})
if err != nil {
return nil, err
}
body, err := executeProtocolRequest(ctx, input.Config, spec)
if err != nil {
return nil, err
}
state, err := adapter.ParsePoll(ctx, protocol.PollContext{BaseURL: input.Config.BaseURL, Model: request.Model, Request: request, TaskID: taskID}, body)
if err != nil {
return nil, err
}
if state.TaskID != "" {
taskID = state.TaskID
}
switch state.Status {
case protocol.StatusSucceeded:
return finishProtocolResult(ctx, input.Config, input.Mode, state.Result)
case protocol.StatusFailed, protocol.StatusCancelled:
return nil, protocolResultError(state.Message, taskID)
}
if err := sleepContext(ctx, 2500*time.Millisecond); err != nil {
return nil, err
}
}
return nil, fmt.Errorf("声明式协议任务超时(任务 %s)", taskID)
}
func protocolRequestFromInput(input canvasGenerationInput) protocol.GenerationRequest {
request := protocol.GenerationRequest{
Model: input.Config.Model,
Prompt: input.Prompt,
Images: protocolMediaReferences(input.ReferenceImages, "image"),
Videos: protocolMediaReferences(input.ReferenceVideos, "video"),
Audios: protocolMediaReferences(input.ReferenceAudios, "audio"),
AspectRatio: input.Config.Size,
Resolution: input.Config.VQuality,
Quality: input.Config.Quality,
GenerateAudio: parseBool(input.Config.VideoGenerateAudio, false),
Watermark: parseBool(input.Config.VideoWatermark, false),
Operation: metadataString(input.Metadata, "videoOperation"),
Extra: map[string]any{
"videoSeconds": input.Config.VideoSeconds,
"audioVoice": input.Config.AudioVoice,
"audioFormat": input.Config.AudioFormat,
"count": input.Config.Count,
},
}
if duration, err := strconv.Atoi(strings.TrimSpace(input.Config.VideoSeconds)); err == nil && duration > 0 {
request.Duration = duration
}
if count, err := strconv.Atoi(strings.TrimSpace(input.Config.Count)); err == nil && count > 0 {
request.ImageCount = count
}
return request
}
func protocolMediaReferences(values []providerMedia, kind string) []protocol.MediaReference {
result := make([]protocol.MediaReference, 0, len(values))
for _, value := range values {
item := protocol.MediaReference{URL: strings.TrimSpace(value.URL), DataURL: strings.TrimSpace(value.DataURL), Kind: kind}
if item.URL != "" || item.DataURL != "" {
result = append(result, item)
}
}
return result
}
func executeProtocolRequest(ctx context.Context, config providerConfig, spec protocol.RequestSpec) ([]byte, error) {
if err := spec.Validate(); err != nil {
return nil, err
}
method := strings.ToUpper(strings.TrimSpace(spec.Method))
var body io.Reader
if spec.Body != nil {
contentType := strings.ToLower(strings.TrimSpace(strings.Split(spec.ContentType, ";")[0]))
if contentType != "" && contentType != "application/json" {
return nil, fmt.Errorf("声明式协议暂不支持 %s 请求体", spec.ContentType)
}
data, err := json.Marshal(spec.Body)
if err != nil {
return nil, err
}
body = bytes.NewReader(data)
}
req, err := http.NewRequestWithContext(ctx, method, apiURL(config.BaseURL, spec.Path), body)
if err != nil {
return nil, err
}
applyProviderAuth(req, config)
if spec.Body != nil {
req.Header.Set("Content-Type", "application/json")
}
for name, value := range spec.Headers {
req.Header.Set(name, value)
}
ApplyOutboundHeaders(req, config.Headers)
data, _, err := doBinary(req)
return data, err
}
func finishProtocolResult(ctx context.Context, config providerConfig, mode string, result *protocol.Result) (map[string]interface{}, error) {
if result == nil {
return nil, errors.New("声明式协议已完成但没有返回结果")
}
if mode == "text" {
output := map[string]interface{}{"mode": "text", "text": result.Text}
if strings.TrimSpace(result.Reasoning) != "" {
output["reasoning"] = result.Reasoning
}
return output, nil
}
var references []protocol.MediaReference
switch mode {
case "image":
references = result.Images
case "video":
references = result.Videos
case "audio":
references = result.Audios
default:
return nil, fmt.Errorf("声明式协议不支持生成模式 %s", mode)
}
if len(references) == 0 {
return nil, errors.New("声明式协议已完成但没有返回媒体地址")
}
items := make([]interface{}, 0, len(references))
for _, reference := range references {
data, mimeType, err := protocolMediaBytes(ctx, config, reference)
if err != nil {
return nil, err
}
item := map[string]interface{}{"dataUrl": dataURL(mimeType, data), "mimeType": mimeType}
items = append(items, item)
}
switch mode {
case "image":
return map[string]interface{}{"mode": "image", "images": items}, nil
case "video":
return map[string]interface{}{"mode": "video", "video": items[0]}, nil
default:
return map[string]interface{}{"mode": "audio", "audio": items[0]}, nil
}
}
func protocolMediaBytes(ctx context.Context, config providerConfig, reference protocol.MediaReference) ([]byte, string, error) {
if strings.TrimSpace(reference.DataURL) != "" {
mimeType, data, err := decodeProviderDataURL(reference.DataURL)
return data, mimeType, err
}
value := strings.TrimSpace(reference.URL)
if value == "" {
return nil, "", errors.New("声明式协议媒体结果地址为空")
}
data, mimeType, err := getProviderExternalBinary(withProviderRequestKind(ctx, "download"), config, value)
if err != nil {
return nil, "", fmt.Errorf("声明式协议媒体结果下载失败:%w", err)
}
return data, normalizedMediaMimeType(mimeType, data), nil
}
func protocolResultError(message, taskID string) error {
message = strings.TrimSpace(message)
if message == "" {
message = "上游返回失败状态"
}
if taskID == "" {
return errors.New(message)
}
return fmt.Errorf("声明式协议任务失败(任务 %s):%s", taskID, message)
}
func runAsyncAudioTask(ctx context.Context, input canvasGenerationInput, body map[string]interface{}, format string) (map[string]interface{}, error) {
id := resumedProviderRequestID(ctx)
var state map[string]interface{}
@@ -1808,6 +2287,9 @@ func audioFormatMimeType(format string) string {
}
func runVideoTask(ctx context.Context, input canvasGenerationInput) (map[string]interface{}, error) {
if _, ok := declarativeProtocolAdapterForContext(ctx, input.Config.InterfaceType); ok {
return runDeclarativeProtocolTask(ctx, input)
}
if input.Config.InterfaceType == string(model.ChannelInterfaceMiniMaxVideo) {
return runMiniMaxVideoTask(ctx, input)
}
@@ -2306,11 +2788,7 @@ func getGeminiBinary(ctx context.Context, config providerConfig, rawURL string)
}
func geminiVeoURL(baseURL string, path string) string {
base := strings.TrimRight(strings.TrimSpace(baseURL), "/")
if !strings.HasSuffix(strings.ToLower(base), "/v1beta") {
base += "/v1beta"
}
return base + "/" + strings.TrimLeft(path, "/")
return apiURLWithDefaultPrefix(baseURL, path, "/v1beta")
}
func findProviderMediaURL(value interface{}) string {
@@ -2798,22 +3276,41 @@ func firstNonEmptyString(values ...string) string {
}
func validateGenerationInterface(mode string, interfaceType string) error {
return validateGenerationInterfaceWithRegistry(protocol.Builtins(), mode, interfaceType)
}
func (s *Service) validateGenerationInterface(mode string, interfaceType string) error {
return validateGenerationInterfaceWithRegistry(s.protocolRegistry(), mode, interfaceType)
}
func validateGenerationInterfaceWithRegistry(registry *protocol.Registry, mode string, interfaceType string) error {
interfaceType = strings.TrimSpace(interfaceType)
if interfaceType == "" {
return nil
}
allowed := map[string]map[string]bool{
"text": {"chat-completion": true, "openai-response": true},
"image": {"openai-image": true, "grok-image": true, "volcengine-ark-image": true, "volcengine-jimeng-image": true, "gemini-image": true},
"video": {"newapi": true, "newapi-channel-1": true, "newapi-channel-2": true, "xai-video": true, "volcengine-ark-video": true, "volcengine-jimeng-video": true, "gemini-veo": true, "novita-video": true, "minimax-video": true},
"audio": {"openai-audio": true, "async-audio": true},
adapter, ok := registry.Resolve(interfaceType)
if !ok {
return fmt.Errorf("接口类型 %s 未安装", interfaceType)
}
if allowed[mode] != nil && !allowed[mode][interfaceType] {
metadata := adapter.Metadata()
if !metadata.Enabled || metadata.UnavailableReason != "" {
return fmt.Errorf("接口类型 %s 当前不可用:%s", interfaceType, metadata.UnavailableReason)
}
if mode != "" && !protocolCapabilityMatches(metadata, protocol.Capability(mode)) {
return fmt.Errorf("接口类型 %s 不支持%s生成", interfaceType, mode)
}
return nil
}
func protocolCapabilityMatches(metadata protocol.Metadata, capability protocol.Capability) bool {
for _, item := range metadata.Categories {
if item == capability {
return true
}
}
return false
}
func grokVideoBody(input canvasGenerationInput) (map[string]interface{}, error) {
if input.Config.InterfaceType == "xai-video" {
body, err := xaiVideoRequestBody(input)
@@ -3076,6 +3573,17 @@ func postStreamingText(ctx context.Context, config providerConfig, path string,
}
func extractTextPayload(payload map[string]interface{}, protocol string) string {
if protocol == "claude-api" {
content, _ := payload["content"].([]interface{})
var result strings.Builder
for _, item := range content {
record, _ := item.(map[string]interface{})
if stringField(record, "type") == "text" {
result.WriteString(stringField(record, "text"))
}
}
return result.String()
}
if protocol == "responses" {
text := stringField(payload, "output_text")
if text == "" {
@@ -3131,6 +3639,11 @@ func parseTextEventStream(data []byte, protocol string) (string, error) {
}
if protocol == "responses" {
text.WriteString(stringField(payload, "delta"))
} else if protocol == "claude-api" {
delta, _ := payload["delta"].(map[string]interface{})
if stringField(delta, "type") == "text_delta" {
text.WriteString(stringField(delta, "text"))
}
} else {
choices, _ := payload["choices"].([]interface{})
for _, choice := range choices {
@@ -3193,7 +3706,7 @@ func postStreamingBinary(ctx context.Context, config providerConfig, path string
if err != nil {
return nil, "", err
}
req.Header.Set("Authorization", "Bearer "+config.APIKey)
applyProviderAuth(req, config)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "text/event-stream")
ApplyOutboundHeaders(req, config.Headers)
@@ -3206,12 +3719,25 @@ func postJSON(ctx context.Context, config providerConfig, path string, body inte
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+config.APIKey)
applyProviderAuth(req, config)
req.Header.Set("Content-Type", "application/json")
ApplyOutboundHeaders(req, config.Headers)
return doJSON(req, target)
}
func applyProviderAuth(req *http.Request, config providerConfig) {
if config.APIFormat == "claude" {
req.Header.Set("x-api-key", config.APIKey)
req.Header.Set("anthropic-version", "2023-06-01")
return
}
if config.APIFormat == "gemini" {
req.Header.Set("x-goog-api-key", config.APIKey)
return
}
req.Header.Set("Authorization", "Bearer "+config.APIKey)
}
func postForm(ctx context.Context, config providerConfig, path string, contentType string, body io.Reader, target interface{}) error {
req, err := http.NewRequestWithContext(ctx, http.MethodPost, apiURL(config.BaseURL, path), body)
if err != nil {
@@ -3269,7 +3795,7 @@ func getProviderExternalBinary(ctx context.Context, config providerConfig, rawUR
return nil, "", err
}
if sameProviderOrigin(config.BaseURL, rawURL) {
req.Header.Set("Authorization", "Bearer "+config.APIKey)
applyProviderAuth(req, config)
ApplyOutboundHeaders(req, config.Headers)
}
return doBinary(req)
@@ -3548,17 +4074,73 @@ func providerRequestKind(method string, path string) string {
}
func apiURL(baseURL string, path string) string {
return apiURLWithDefaultPrefix(baseURL, path, "/v1")
}
// ChannelAPIURL is the single URL join point for provider requests. A channel
// may be configured as host, host/, host/v1 or host/v1/; callers should pass
// protocol paths without hard-coding a version prefix whenever possible.
func ChannelAPIURL(baseURL string, path string) string {
return apiURL(baseURL, path)
}
// ChannelAPIURLForProtocol keeps protocol-specific defaults at the transport
// boundary. In particular, Gemini uses v1beta while OpenAI-compatible APIs
// conventionally use v1. An explicit version in either input wins.
func ChannelAPIURLForProtocol(baseURL string, path string, interfaceType model.ChannelInterfaceType) string {
defaultPrefix := "/v1"
if interfaceType == model.ChannelInterfaceGeminiVeo || interfaceType == model.ChannelInterfaceGeminiImage {
defaultPrefix = "/v1beta"
}
return apiURLWithDefaultPrefix(baseURL, path, defaultPrefix)
}
var channelAPIPrefixes = []string{"/api/plan/v3", "/api/v3", "/v1beta", "/v1", "/v2", "/v3"}
func apiURLWithDefaultPrefix(baseURL string, path string, defaultPrefix string) string {
base := strings.TrimRight(strings.TrimSpace(baseURL), "/")
if strings.HasPrefix(path, "/v2/") {
if strings.HasSuffix(base, "/v2") {
return base + strings.TrimPrefix(path, "/v2")
requestPath := strings.TrimSpace(path)
if requestPath == "" {
return base
}
if !strings.HasPrefix(requestPath, "/") {
requestPath = "/" + requestPath
}
requestPrefix := requestAPIPathPrefix(requestPath)
basePrefix := baseAPIPathPrefix(base)
if requestPrefix != "" {
if basePrefix == requestPrefix {
return base + strings.TrimPrefix(requestPath, requestPrefix)
}
return base + path
// An explicit request version takes precedence over a version accidentally
// left on the configured base URL (for example base=/v1, path=/v2/...).
return strings.TrimSuffix(base, basePrefix) + requestPath
}
if strings.HasSuffix(base, "/v1") || strings.HasSuffix(base, "/v1beta") || strings.HasSuffix(base, "/v2") || strings.HasSuffix(base, "/api/v3") || strings.HasSuffix(base, "/api/plan/v3") {
return base + path
if basePrefix != "" {
return base + requestPath
}
return base + "/v1" + path
return base + defaultPrefix + requestPath
}
func requestAPIPathPrefix(value string) string {
lower := strings.ToLower(value)
for _, prefix := range channelAPIPrefixes {
if lower == prefix || strings.HasPrefix(lower, prefix+"/") || strings.HasPrefix(lower, prefix+"?") || strings.HasPrefix(lower, prefix+"#") {
return prefix
}
}
return ""
}
func baseAPIPathPrefix(value string) string {
lower := strings.ToLower(strings.TrimRight(value, "/"))
for _, prefix := range channelAPIPrefixes {
if lower == prefix || strings.HasSuffix(lower, prefix) {
return prefix
}
}
return ""
}
func writeField(writer *multipart.Writer, key string, value string) {
@@ -0,0 +1,39 @@
package service
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"infinite-canvas/backend/internal/model"
)
func TestRunClaudeTextTaskUsesMessagesAndAPIKeyHeader(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/v1/messages" {
t.Fatalf("path = %q", r.URL.Path)
}
if r.Header.Get("x-api-key") != "claude-key" || r.Header.Get("Authorization") != "" {
t.Fatalf("auth headers = x-api-key %q authorization %q", r.Header.Get("x-api-key"), r.Header.Get("Authorization"))
}
if r.Header.Get("anthropic-version") != "2023-06-01" {
t.Fatalf("anthropic-version = %q", r.Header.Get("anthropic-version"))
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"content":[{"type":"text","text":"claude works"}]}`))
}))
defer server.Close()
config := providerConfig{
BaseURL: server.URL + "/v1", APIKey: "claude-key", Model: "claude-test", APIFormat: "claude", InterfaceType: string(model.ChannelInterfaceClaudeAPI),
AllowLocalChannel: true,
}
result, err := runTextTask(withProviderOutboundPolicy(context.Background(), config), canvasGenerationInput{Mode: "text", Prompt: "hello", Config: config})
if err != nil {
t.Fatal(err)
}
if result["text"] != "claude works" {
t.Fatalf("result = %#v", result)
}
}
@@ -0,0 +1,22 @@
package service
import (
"errors"
"time"
"infinite-canvas/backend/internal/model"
)
// ResourceForUser is the service-layer ownership check used by provider workers.
func (s *Service) ResourceForUser(actor *model.User, id string) (*model.Resource, error) {
if actor == nil || actor.ID == "" {
return nil, errors.New("用户身份无效")
}
return s.repo.ResourceForUser(actor.ID, id)
}
// providerResourceURL gives an upstream a short-lived URL after the resource
// ownership and ready-state checks have already been performed.
func (s *Service) providerResourceURL(resource *model.Resource, expiresAt time.Time) (string, error) {
return s.directResourceURL(resource, expiresAt)
}
+108
View File
@@ -42,6 +42,50 @@ func TestProviderRequestErrorDetails(t *testing.T) {
}
}
func TestChannelAPIURLNormalizesConfiguredVersionPrefix(t *testing.T) {
tests := []struct {
name string
base string
path string
want string
}{
{name: "host", base: "http://provider.test:8000", path: "/chat/completions", want: "http://provider.test:8000/v1/chat/completions"},
{name: "host slash", base: "http://provider.test:8000/", path: "/chat/completions", want: "http://provider.test:8000/v1/chat/completions"},
{name: "v1", base: "http://provider.test:8000/v1", path: "/chat/completions", want: "http://provider.test:8000/v1/chat/completions"},
{name: "v1 slash", base: "http://provider.test:8000/v1/", path: "/chat/completions", want: "http://provider.test:8000/v1/chat/completions"},
{name: "path carries v1beta", base: "http://provider.test:8000", path: "/v1beta/models/model", want: "http://provider.test:8000/v1beta/models/model"},
{name: "same v1beta is not duplicated", base: "http://provider.test:8000/v1beta", path: "/v1beta/models/model", want: "http://provider.test:8000/v1beta/models/model"},
{name: "path carries v2", base: "http://provider.test:8000/v1", path: "/v2/tasks", want: "http://provider.test:8000/v2/tasks"},
{name: "ark v3", base: "https://ark.example.com/api/v3", path: "/images/generations", want: "https://ark.example.com/api/v3/images/generations"},
{name: "path carries ark v3", base: "https://ark.example.com", path: "/api/v3/images/generations", want: "https://ark.example.com/api/v3/images/generations"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := ChannelAPIURL(tt.base, tt.path); got != tt.want {
t.Fatalf("ChannelAPIURL(%q, %q) = %q, want %q", tt.base, tt.path, got, tt.want)
}
})
}
}
func TestChannelAPIURLForProtocolUsesGeminiDefault(t *testing.T) {
if got := ChannelAPIURLForProtocol("https://generativelanguage.googleapis.com", "/models/gemini:generateContent", model.ChannelInterfaceGeminiVeo); got != "https://generativelanguage.googleapis.com/v1beta/models/gemini:generateContent" {
t.Fatalf("Gemini URL = %q", got)
}
}
func TestSystemChannelIDFromBaseURLSupportsShortAndLegacyProxyPaths(t *testing.T) {
for _, test := range []struct{ base, want string }{
{base: "/api/channel-1", want: "channel-1"},
{base: "/api/ai/system/channel-2", want: "channel-2"},
{base: "https://canvas.example.com/api/channel-3", want: "channel-3"},
} {
if got := systemChannelIDFromBaseURL(test.base); got != test.want {
t.Fatalf("systemChannelIDFromBaseURL(%q) = %q, want %q", test.base, got, test.want)
}
}
}
func TestWriteMediaPartSanitizesFilenameAndSetsMimeType(t *testing.T) {
var body bytes.Buffer
writer := multipart.NewWriter(&body)
@@ -105,6 +149,17 @@ data: [DONE]
if got, err := parseTextEventStream(chat, "chat-completion"); err != nil || got != "第一镜:远景" {
t.Fatalf("Chat stream = %q, err = %v", got, err)
}
claude := []byte(`event: content_block_delta
data: {"delta":{"type":"text_delta","text":"第一镜"}}
event: content_block_delta
data: {"delta":{"type":"text_delta","text":":远景"}}
`)
if got, err := parseTextEventStream(claude, "claude-api"); err != nil || got != "第一镜:远景" {
t.Fatalf("Claude stream = %q, err = %v", got, err)
}
}
func TestParseAgentToolPayloadSupportsChatCompletions(t *testing.T) {
@@ -164,6 +219,59 @@ func TestParseAgentToolPayloadSupportsResponses(t *testing.T) {
}
}
func TestParseAgentToolPayloadSupportsClaude(t *testing.T) {
result, err := parseAgentToolPayload(map[string]interface{}{
"content": []interface{}{
map[string]interface{}{"type": "text", "text": "开始操作"},
map[string]interface{}{"type": "tool_use", "id": "call-3", "name": "canvas_get_state", "input": map[string]interface{}{}},
},
}, "claude-api")
if err != nil {
t.Fatalf("parseAgentToolPayload() error = %v", err)
}
if result["text"] != "开始操作" {
t.Fatalf("text = %v", result["text"])
}
calls, _ := result["toolCalls"].([]interface{})
if len(calls) != 1 {
t.Fatalf("toolCalls = %#v", result["toolCalls"])
}
call, _ := calls[0].(map[string]interface{})
function, _ := call["function"].(map[string]interface{})
if call["id"] != "call-3" || function["name"] != "canvas_get_state" || function["arguments"] != "{}" {
t.Fatalf("tool call = %#v", call)
}
}
func TestClaudeAgentBodyMapsOpenAIStyleTools(t *testing.T) {
body := claudeAgentBody(map[string]interface{}{
"messages": []interface{}{
map[string]interface{}{"role": "system", "content": "You are concise."},
map[string]interface{}{"role": "user", "content": "读取画布"},
map[string]interface{}{"role": "assistant", "content": nil, "tool_calls": []interface{}{map[string]interface{}{
"id": "call-4", "function": map[string]interface{}{"name": "canvas_get_state", "arguments": `{}`},
}}},
map[string]interface{}{"role": "tool", "tool_call_id": "call-4", "content": `{"nodes":[]}`},
},
"tools": []interface{}{map[string]interface{}{"type": "function", "function": map[string]interface{}{
"name": "canvas_get_state", "description": "读取画布", "parameters": map[string]interface{}{"type": "object"},
}}},
"tool_choice": "required",
})
if body["system"] != "You are concise." || body["max_tokens"] != 4096 {
t.Fatalf("body = %#v", body)
}
messages, _ := body["messages"].([]interface{})
if len(messages) != 3 {
t.Fatalf("messages = %#v", messages)
}
tools, _ := body["tools"].([]interface{})
tool, _ := tools[0].(map[string]interface{})
if tool["name"] != "canvas_get_state" || body["tool_choice"].(map[string]interface{})["type"] != "any" {
t.Fatalf("tools/choice = %#v / %#v", body["tools"], body["tool_choice"])
}
}
func TestRunAgentToolTaskFallsBackToolChoice(t *testing.T) {
t.Setenv("CANVAS_ALLOW_PRIVATE_UPSTREAMS", "true")
var choices []interface{}
+4 -1
View File
@@ -37,6 +37,8 @@ type Service struct {
sessionCreationCoordinator *sessionCreationCoordinator
sessionUploadCoordinator *sessionUploadCoordinator
runtimeErr error
pluginRuntime *pluginRuntime
pluginRuntimeErr error
workerID string
routeCatalogMu sync.RWMutex
routeCatalogRefreshMu sync.Mutex
@@ -95,7 +97,8 @@ func New(repo *repository.Repository, dataDir string) *Service {
func NewWithRuntimeCapabilities(repo *repository.Repository, dataDir string, capabilities RuntimeCapabilities) *Service {
coordinator, err := newRuntimeCoordinator(repo.Dialect())
service := &Service{repo: repo, dataDir: dataDir, runtimeCapabilities: capabilities, activeCancels: make(map[string]context.CancelFunc), coordinator: coordinator, runtimeErr: err, workerID: newID(), routeCatalogTTL: 30 * time.Second, routeCatalogMaxStale: 5 * time.Minute, routeHealthBlocked: make(map[string]time.Time)}
pluginRuntime, pluginRuntimeErr := newPluginRuntime(dataDir)
service := &Service{repo: repo, dataDir: dataDir, runtimeCapabilities: capabilities, activeCancels: make(map[string]context.CancelFunc), coordinator: coordinator, runtimeErr: err, pluginRuntime: pluginRuntime, pluginRuntimeErr: pluginRuntimeErr, workerID: newID(), routeCatalogTTL: 30 * time.Second, routeCatalogMaxStale: 5 * time.Minute, routeHealthBlocked: make(map[string]time.Time)}
service.taskBillingCoordinator = newTaskBillingCoordinator(service.repo)
service.taskTerminalCoordinator = newTaskTerminalCoordinator(service)
service.taskRouteExecutor = newTaskRouteExecutor(service)
@@ -112,6 +112,7 @@ func parseStoryboardTaskInput(task model.Task, label string) (agentStoryboardInp
}
func (s *Service) generateStoryboardPlan(ctx context.Context, task model.Task, input agentStoryboardInput, shotDuration int, shotCount int) (agentStoryboardPlan, []storyboardAsset, error) {
ctx = withProtocolRegistry(ctx, s.protocolRegistry())
if !providerConfigReady(input.Config) {
return agentStoryboardPlan{}, nil, errors.New("请先配置可用的文本模型")
}