| 1 | package serve |
| 2 | |
| 3 | import ( |
| 4 | "crypto/rand" |
| 5 | "encoding/json" |
| 6 | "fmt" |
| 7 | "net/http" |
| 8 | "sort" |
| 9 | "strings" |
| 10 | |
| 11 | "reasonix/internal/config" |
| 12 | "reasonix/internal/control" |
| 13 | ) |
| 14 | |
| 15 | const modelSettingsProtocolVersion = 1 |
| 16 | |
| 17 | func currentModelRef(c control.SessionAPI) string { |
| 18 | ref := strings.TrimSpace(c.ModelRef()) |
| 19 | if ref != "" { |
| 20 | return ref |
| 21 | } |
| 22 | return strings.TrimSpace(c.Label()) |
| 23 | } |
| 24 | |
| 25 | type modelSettingsStatusView struct { |
| 26 | Application *control.ModelApplicationDetails `json:"application,omitempty"` |
| 27 | config.ModelSettingsOwnership |
| 28 | Version int `json:"version"` |
| 29 | Revision string `json:"revision"` |
| 30 | Model string `json:"model"` |
| 31 | SessionPath string `json:"sessionPath"` |
| 32 | OwnedRevisions []string `json:"ownedRevisions"` |
| 33 | UnversionedOwners bool `json:"unversionedOwners"` |
| 34 | } |
| 35 | |
| 36 | func (s *Server) modelSettingsStatus(w http.ResponseWriter, r *http.Request) { |
| 37 | s.bindMu.Lock() |
| 38 | defer s.bindMu.Unlock() |
| 39 | if !s.validateExpectedSessionLocked(w, r) { |
| 40 | return |
| 41 | } |
| 42 | view := s.modelSettingsStatusLocked() |
| 43 | view.Application = s.modelApplicationDetailsLocked(r.Context()) |
| 44 | writeJSON(w, view) |
| 45 | } |
| 46 | |
| 47 | // Caller holds bindMu across validation, refresh and turn admission. |
| 48 | func (s *Server) admitModelSettingsRunLocked(w http.ResponseWriter, r *http.Request) bool { |
| 49 | if !s.validateExpectedSessionLocked(w, r) { |
| 50 | return false |
| 51 | } |
| 52 | if s.rejectMirroredForegroundLocked(w) { |
| 53 | return false |
| 54 | } |
| 55 | if err := s.refreshRunModelSettingsLocked(r.Context()); err != nil { |
| 56 | s.rejectModelApplication(w, r, err) |
| 57 | return false |
| 58 | } |
| 59 | if !s.validateExpectedSessionLocked(w, r) { |
| 60 | return false |
| 61 | } |
| 62 | return true |
| 63 | } |
| 64 | |
| 65 | func (s *Server) modelSettingsStatusLocked() modelSettingsStatusView { |
| 66 | if s.modelSettingsOwnership.OwnershipIncarnation == "" { |
| 67 | s.modelSettingsOwnership.OwnershipIncarnation = rand.Text() |
| 68 | } |
| 69 | s.modelSettingsOwnership.OwnershipSeq++ |
| 70 | current := s.ctl() |
| 71 | view := modelSettingsStatusView{Version: modelSettingsProtocolVersion, Model: current.ModelRef(), SessionPath: current.SessionPath(), OwnedRevisions: []string{}} |
| 72 | view.ModelSettingsOwnership = s.modelSettingsOwnership |
| 73 | owners := []control.SessionAPI{current} |
| 74 | s.detachedMu.Lock() |
| 75 | for _, detached := range s.detached { |
| 76 | if detached != nil && detached.ctrl != nil { |
| 77 | owners = append(owners, detached.ctrl) |
| 78 | } |
| 79 | } |
| 80 | s.detachedMu.Unlock() |
| 81 | seen := map[string]bool{} |
| 82 | for _, owner := range owners { |
| 83 | revision := "" |
| 84 | if snapshot, ok := owner.(interface{ ModelSettingsSourceRevision() string }); ok { |
| 85 | revision = snapshot.ModelSettingsSourceRevision() |
| 86 | } |
| 87 | if owner == current { |
| 88 | view.Revision = revision |
| 89 | } |
| 90 | if revision == "" { |
| 91 | view.UnversionedOwners = true |
| 92 | } else if !seen[revision] { |
| 93 | seen[revision] = true |
| 94 | view.OwnedRevisions = append(view.OwnedRevisions, revision) |
| 95 | } |
| 96 | } |
| 97 | sort.Strings(view.OwnedRevisions) |
| 98 | return view |
| 99 | } |
| 100 | |
| 101 | // applyModelSettings publishes a complete resolver at the same session binding |
| 102 | // boundary as /model. No provider config or real credential is written remotely. |
| 103 | // A failed build leaves the old controller and its bundle intact. |
| 104 | func (s *Server) applyModelSettings(w http.ResponseWriter, r *http.Request) { |
| 105 | var request struct { |
| 106 | Version int `json:"version"` |
| 107 | Ref string `json:"ref"` |
| 108 | Settings config.ModelRuntimeSettings `json:"settings"` |
| 109 | } |
| 110 | decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4<<20)) |
| 111 | decoder.DisallowUnknownFields() |
| 112 | if err := decoder.Decode(&request); err != nil || request.Version != modelSettingsProtocolVersion || strings.TrimSpace(request.Settings.Revision) == "" { |
| 113 | http.Error(w, "invalid model settings snapshot", http.StatusBadRequest) |
| 114 | return |
| 115 | } |
| 116 | ref, ok := modelSettingsCatalogRef(request.Settings.Providers, request.Ref) |
| 117 | if !ok { |
| 118 | http.Error(w, "model is not included in the snapshot", http.StatusBadRequest) |
| 119 | return |
| 120 | } |
| 121 | s.bindMu.Lock() |
| 122 | defer s.bindMu.Unlock() |
| 123 | if !s.validateExpectedSessionLocked(w, r) { |
| 124 | return |
| 125 | } |
| 126 | if control.ModelReplacementBlocked(s.ctl()) { |
| 127 | s.deferModelApplicationLocked() |
| 128 | http.Error(w, "cannot apply model settings while active work or background jobs are running", http.StatusConflict) |
| 129 | return |
| 130 | } |
| 131 | if view := s.modelSettingsStatusLocked(); view.Revision == request.Settings.Revision && view.Model == ref { |
| 132 | writeJSON(w, view) |
| 133 | return |
| 134 | } |
| 135 | previous := s.managedModels |
| 136 | s.modelApplicationRetry.mu.Lock() |
| 137 | s.modelApplicationRetry.failedRevision, s.modelApplicationRetry.failure = "", "" |
| 138 | s.modelApplicationRetry.mu.Unlock() |
| 139 | s.managedModels = &request.Settings |
| 140 | if err := s.switchModelLocked(r.Context(), ref); err != nil { |
| 141 | s.managedModels = previous |
| 142 | http.Error(w, fmt.Sprintf("apply saved model settings: %s", err), runtimeSwitchErrorStatus(err)) |
| 143 | return |
| 144 | } |
| 145 | writeJSON(w, s.modelSettingsStatusLocked()) |
| 146 | } |
| 147 | |
| 148 | func modelSettingsCatalogRef(providers []config.ProviderEntry, requested string) (string, bool) { |
| 149 | requested = strings.TrimSpace(requested) |
| 150 | for _, entry := range providers { |
| 151 | models := entry.ChatModelList() |
| 152 | if len(models) == 0 { |
| 153 | models = entry.ModelList() |
| 154 | } |
| 155 | for _, model := range models { |
| 156 | ref := entry.Name + "/" + model |
| 157 | if requested == ref { |
| 158 | return ref, true |
| 159 | } |
| 160 | } |
| 161 | } |
| 162 | return "", false |
| 163 | } |
| 164 |