mirror of
https://github.com/coder/coder.git
synced 2026-11-01 12:53:26 +08:00
## Summary Move chat model management and runtime availability to organization-scoped API routes. The API now identifies the organization in every model-management operation, applies chat model RBAC and ACLs within that organization, and returns only models the caller can use there. Depends on #27958. ## Problem Chat model configurations now belong to organizations, but the existing experimental management and discovery APIs are deployment-shaped. Their routes do not identify an organization, SDK methods do not accept an organization ID, and item operations address a model configuration by ID alone. That contract cannot safely expose organization-owned model configurations. It also does not provide the organization-specific provider information, authorization behavior, ACL management, or recovery guidance needed by the settings and chat clients later in the stack. ## Fix Add organization-scoped chat model endpoints under: ```text /api/experimental/organizations/{organization}/chats/models ``` The new API provides: - Organization-scoped model listing and creation. - Model get, update, and delete operations scoped by both organization and model ID. - Model ACL read and update operations. - Organization-scoped runtime availability and provider status. - Redacted provider descriptors for model-management clients. - Chat model RBAC and row ACL enforcement for writes, runtime discovery, and Chatd model selection. - Recovery guidance when a chat's organization has no usable local model. Historical chats can retain a model reference owned by another organization, but runtime selection uses an authorized local default when one is available. Foreign, inaccessible, disabled, and otherwise unusable models are not exposed as usable selections for the organization. The existing collection and availability routes remain as default-organization compatibility endpoints in this layer: ```text GET /api/experimental/chats/model-configs POST /api/experimental/chats/model-configs GET /api/experimental/chats/models ``` These compatibility routes do not provide access to models in non-default organizations. The previous unscoped item update and delete routes are removed because item operations must include the owning organization. ## Breaking change This changes the experimental HTTP API and Go SDK contracts for chat model management. Clients must migrate model-management and availability requests to the organization-scoped routes and provide an organization identifier. In the Go SDK, the following methods now require an organization ID: - `ChatModelAvailability` - `ChatModels` - `CreateChatModel` - `UpdateChatModel` - `DeleteChatModel` `ChatModels` also changes its return value from `[]ChatModel` to `OrganizationChatModelsResponse`, which includes the organization models and the redacted provider descriptors required by management clients. New item and ACL methods likewise require both the organization ID and model ID. The default-organization compatibility routes reduce the immediate impact for collection and availability callers, but they do not preserve the previous item API or SDK method signatures. Generated clients and direct consumers of the experimental API must be updated before adopting this change. _This pull request description was generated by Coder Agents._
155 lines
4.8 KiB
Go
155 lines
4.8 KiB
Go
package chatd
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"cdr.dev/slog/v3"
|
|
"github.com/coder/coder/v2/coderd/database"
|
|
"github.com/coder/coder/v2/coderd/x/chatd/chatprompt"
|
|
"github.com/coder/coder/v2/codersdk"
|
|
)
|
|
|
|
// providerSwitchStripStats counts provider-executed tool history removed
|
|
// during a provider switch.
|
|
type providerSwitchStripStats struct {
|
|
RemovedToolCalls int
|
|
RemovedToolResults int
|
|
DroppedMessages int
|
|
}
|
|
|
|
// modelConfigProviderIdentity returns a stable identity for the upstream provider
|
|
// behind a model config. When the config has an AIProviderID (the modern path),
|
|
// the identity is the provider instance UUID, so two providers of the same type
|
|
// (e.g. two openai-compat providers at different base URLs) are distinguished.
|
|
// When AIProviderID is invalid (legacy configs with no provider row), the
|
|
// identity falls back to the normalized provider type name.
|
|
func modelConfigProviderIdentity(modelConfig database.ChatModelConfig, normalizedProvider string) string {
|
|
if modelConfig.AIProviderID.Valid {
|
|
return modelConfig.AIProviderID.UUID.String()
|
|
}
|
|
return normalizedProvider
|
|
}
|
|
|
|
// stripForeignProviderExecutedToolRows drops provider-executed tool blocks
|
|
// (calls and results) from assistant rows whose producing provider differs
|
|
// from targetIdentity. Rows with an unknown origin are treated as foreign
|
|
// (fail closed). Rows emptied by stripping are dropped; rows that fail to parse
|
|
// or re-marshal are kept unchanged.
|
|
//
|
|
// See modelConfigProviderIdentity for how identity is derived.
|
|
func stripForeignProviderExecutedToolRows(
|
|
rows []database.ChatMessage,
|
|
targetIdentity string,
|
|
originProvider func(uuid.NullUUID) (string, bool),
|
|
) ([]database.ChatMessage, providerSwitchStripStats) {
|
|
var stats providerSwitchStripStats
|
|
if targetIdentity == "" || len(rows) == 0 {
|
|
return rows, stats
|
|
}
|
|
|
|
out := make([]database.ChatMessage, 0, len(rows))
|
|
for _, row := range rows {
|
|
if row.Role != database.ChatMessageRoleAssistant {
|
|
out = append(out, row)
|
|
continue
|
|
}
|
|
if origin, ok := originProvider(row.ModelConfigID); ok && origin == targetIdentity {
|
|
out = append(out, row)
|
|
continue
|
|
}
|
|
|
|
parts, err := chatprompt.ParseContent(row)
|
|
if err != nil {
|
|
out = append(out, row)
|
|
continue
|
|
}
|
|
|
|
kept := make([]codersdk.ChatMessagePart, 0, len(parts))
|
|
var removedCalls, removedResults int
|
|
for _, part := range parts {
|
|
switch {
|
|
case part.Type == codersdk.ChatMessagePartTypeToolCall && part.ProviderExecuted:
|
|
removedCalls++
|
|
case part.Type == codersdk.ChatMessagePartTypeToolResult && part.ProviderExecuted:
|
|
removedResults++
|
|
default:
|
|
kept = append(kept, part)
|
|
}
|
|
}
|
|
if removedCalls == 0 && removedResults == 0 {
|
|
out = append(out, row)
|
|
continue
|
|
}
|
|
stats.RemovedToolCalls += removedCalls
|
|
stats.RemovedToolResults += removedResults
|
|
if len(kept) == 0 {
|
|
stats.DroppedMessages++
|
|
continue
|
|
}
|
|
|
|
content, err := chatprompt.MarshalParts(kept)
|
|
if err != nil {
|
|
out = append(out, row)
|
|
continue
|
|
}
|
|
row.Content = content
|
|
row.ContentVersion = chatprompt.CurrentContentVersion
|
|
out = append(out, row)
|
|
}
|
|
return out, stats
|
|
}
|
|
|
|
func (server *Server) sanitizeForeignProviderExecutedToolRows(
|
|
ctx context.Context,
|
|
logger slog.Logger,
|
|
rows []database.ChatMessage,
|
|
ownerID uuid.UUID,
|
|
modelConfigID uuid.UUID,
|
|
) []database.ChatMessage {
|
|
targetCfg, targetProvider, err := server.resolveModelConfigAndNormalizedProvider(ctx, ownerID, modelConfigID)
|
|
if err != nil || targetProvider == "" {
|
|
logger.Debug(ctx, "skipping provider-switch sanitization: target provider unresolved",
|
|
slog.F("model_config_id", modelConfigID),
|
|
slog.Error(err),
|
|
)
|
|
return rows
|
|
}
|
|
targetIdentity := modelConfigProviderIdentity(targetCfg, targetProvider)
|
|
|
|
cache := make(map[uuid.UUID]string)
|
|
originProvider := func(id uuid.NullUUID) (string, bool) {
|
|
if !id.Valid {
|
|
return "", false
|
|
}
|
|
if identity, seen := cache[id.UUID]; seen {
|
|
return identity, identity != ""
|
|
}
|
|
originCfg, provider, rErr := server.resolveModelConfigAndNormalizedProvider(ctx, ownerID, id.UUID)
|
|
if rErr != nil {
|
|
logger.Debug(ctx, "provider-switch sanitization: origin provider unresolved, treating as foreign",
|
|
slog.F("model_config_id", id.UUID),
|
|
slog.Error(rErr),
|
|
)
|
|
cache[id.UUID] = ""
|
|
return "", false
|
|
}
|
|
identity := modelConfigProviderIdentity(originCfg, provider)
|
|
cache[id.UUID] = identity
|
|
return identity, identity != ""
|
|
}
|
|
|
|
sanitized, stats := stripForeignProviderExecutedToolRows(rows, targetIdentity, originProvider)
|
|
if stats != (providerSwitchStripStats{}) {
|
|
logger.Debug(ctx, "stripped foreign provider-executed tool history",
|
|
slog.F("phase", "provider_switch"),
|
|
slog.F("target_provider_identity", targetIdentity),
|
|
slog.F("removed_tool_calls", stats.RemovedToolCalls),
|
|
slog.F("removed_tool_results", stats.RemovedToolResults),
|
|
slog.F("dropped_messages", stats.DroppedMessages),
|
|
)
|
|
}
|
|
return sanitized
|
|
}
|