|
| 1 | +package server |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "net/http" |
| 7 | + "os" |
| 8 | + "strings" |
| 9 | + "time" |
| 10 | + |
| 11 | + "github.com/UnicoLab/slmcode/pkg/autoconfig" |
| 12 | + "github.com/UnicoLab/slmcode/pkg/config" |
| 13 | + "github.com/UnicoLab/slmcode/pkg/orchestrator" |
| 14 | +) |
| 15 | + |
| 16 | +// ── Auto-configuration from the Studio ─────────────────────────────────── |
| 17 | +// |
| 18 | +// The same job as `slmcode configure`, reachable from the browser. It has to |
| 19 | +// exist on both surfaces for the same reason the CLI command does: a user whose |
| 20 | +// endpoint is not answering is looking at a Studio that cannot run anything, |
| 21 | +// and telling them to go and find a terminal is the point at which they stop. |
| 22 | +// |
| 23 | +// Split in two on purpose. GET looks and reports; POST writes. A single |
| 24 | +// endpoint that did both would mean the only way to SEE what auto-configuration |
| 25 | +// would do is to let it happen. |
| 26 | + |
| 27 | +// handleConfigureScan probes for a model server and reports what it found, |
| 28 | +// changing nothing. |
| 29 | +func (s *Server) handleConfigureScan(w http.ResponseWriter, r *http.Request) { |
| 30 | + res, cfg := s.discover(r) |
| 31 | + writeJSON(w, configureView(res, cfg, false)) |
| 32 | +} |
| 33 | + |
| 34 | +// handleConfigureApply probes and writes the result. |
| 35 | +func (s *Server) handleConfigureApply(w http.ResponseWriter, r *http.Request) { |
| 36 | + // A run reads the model and endpoint it was started with. Rewriting them |
| 37 | + // underneath it would leave half the run on one model and half on another, |
| 38 | + // which is the same reason PUT /api/config refuses. |
| 39 | + if s.rejectMutationWhileRunning(w) { |
| 40 | + return |
| 41 | + } |
| 42 | + res, probeCfg := s.discover(r) |
| 43 | + if !res.Found { |
| 44 | + w.Header().Set("Content-Type", "application/json") |
| 45 | + w.WriteHeader(http.StatusUnprocessableEntity) |
| 46 | + _ = json.NewEncoder(w).Encode(configureView(res, probeCfg, false)) |
| 47 | + return |
| 48 | + } |
| 49 | + |
| 50 | + choice := res.Choice |
| 51 | + // An explicit model must be one the server actually serves: writing a |
| 52 | + // config whose first run fails is the situation this exists to prevent. |
| 53 | + if want := strings.TrimSpace(requestedModel(r)); want != "" { |
| 54 | + ok := false |
| 55 | + for _, f := range res.Findings { |
| 56 | + if f.Live() && f.Endpoint == choice.Endpoint { |
| 57 | + for _, name := range f.Models { |
| 58 | + if strings.EqualFold(name, want) { |
| 59 | + choice.Model, choice.Why, ok = name, "chosen in the Studio", true |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + if !ok { |
| 65 | + http.Error(w, choice.Endpoint+" does not serve "+want, http.StatusUnprocessableEntity) |
| 66 | + return |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + var saveErr error |
| 71 | + s.withConfigWrite(func(c *config.Config) { |
| 72 | + c.Provider = choice.Provider |
| 73 | + c.Endpoint = choice.Endpoint |
| 74 | + c.Model = choice.Model |
| 75 | + // A detected provider is not a stack choice; a stale highlight would |
| 76 | + // show a stack the config no longer matches. |
| 77 | + c.ActiveStack = "" |
| 78 | + c.Normalize() |
| 79 | + saveErr = c.Save() |
| 80 | + }) |
| 81 | + if saveErr != nil { |
| 82 | + http.Error(w, saveErr.Error(), http.StatusInternalServerError) |
| 83 | + return |
| 84 | + } |
| 85 | + // The running orchestrator holds the old endpoint. Rebuild it, exactly as |
| 86 | + // PUT /api/config does, or the Studio would report a configuration the |
| 87 | + // harness is not using. |
| 88 | + orch, err := orchestrator.New(s.cfg()) |
| 89 | + if err != nil { |
| 90 | + http.Error(w, err.Error(), http.StatusInternalServerError) |
| 91 | + return |
| 92 | + } |
| 93 | + s.setOrch(orch) |
| 94 | + writeJSON(w, configureView(res, s.cfg(), true)) |
| 95 | +} |
| 96 | + |
| 97 | +// discover runs one probe pass for a request. |
| 98 | +func (s *Server) discover(r *http.Request) (autoconfig.Result, *config.Config) { |
| 99 | + cfg := s.cfg() |
| 100 | + probeCfg := *cfg |
| 101 | + if ep := strings.TrimSpace(r.URL.Query().Get("endpoint")); ep != "" { |
| 102 | + probeCfg.Endpoint = ep |
| 103 | + } |
| 104 | + timeout := autoconfig.DefaultProbeTimeout |
| 105 | + ctx, cancel := context.WithTimeout(r.Context(), timeout+7*time.Second) |
| 106 | + defer cancel() |
| 107 | + res := autoconfig.Discover(ctx, &probeCfg, os.Getenv, autoconfig.HTTPProber(timeout)) |
| 108 | + if ep := strings.TrimSpace(r.URL.Query().Get("endpoint")); ep != "" { |
| 109 | + res = narrowTo(res, ep) |
| 110 | + } |
| 111 | + return res, cfg |
| 112 | +} |
| 113 | + |
| 114 | +// narrowTo keeps only the endpoint the caller named, so an explicit choice |
| 115 | +// cannot fall through to whatever else happens to be running. |
| 116 | +func narrowTo(res autoconfig.Result, endpoint string) autoconfig.Result { |
| 117 | + want := strings.TrimRight(strings.TrimSpace(endpoint), "/") |
| 118 | + var kept []autoconfig.Finding |
| 119 | + for _, f := range res.Findings { |
| 120 | + if strings.TrimRight(f.Endpoint, "/") == want { |
| 121 | + kept = append(kept, f) |
| 122 | + } |
| 123 | + } |
| 124 | + out := autoconfig.Result{Findings: kept} |
| 125 | + out.Choice, out.Found = autoconfig.Choose(kept) |
| 126 | + return out |
| 127 | +} |
| 128 | + |
| 129 | +// requestedModel reads an optional model override from the body. |
| 130 | +func requestedModel(r *http.Request) string { |
| 131 | + if r.Body == nil { |
| 132 | + return "" |
| 133 | + } |
| 134 | + var body struct { |
| 135 | + Model string `json:"model"` |
| 136 | + } |
| 137 | + _ = json.NewDecoder(r.Body).Decode(&body) |
| 138 | + return body.Model |
| 139 | +} |
| 140 | + |
| 141 | +// configureView is the shape both endpoints return. |
| 142 | +func configureView(res autoconfig.Result, cfg *config.Config, applied bool) map[string]interface{} { |
| 143 | + tried := make([]map[string]interface{}, 0, len(res.Findings)) |
| 144 | + for _, f := range res.Findings { |
| 145 | + tried = append(tried, map[string]interface{}{ |
| 146 | + "provider": f.Provider, "endpoint": f.Endpoint, "reason": f.Reason, |
| 147 | + "models": f.Models, "live": f.Live(), "error": f.Err, |
| 148 | + "latency_ms": f.Latency.Milliseconds(), |
| 149 | + }) |
| 150 | + } |
| 151 | + out := map[string]interface{}{ |
| 152 | + "ok": res.Found, |
| 153 | + "tried": tried, |
| 154 | + "applied": applied, |
| 155 | + } |
| 156 | + if res.Found { |
| 157 | + out["choice"] = res.Choice |
| 158 | + } else { |
| 159 | + out["reason"] = res.NothingFound() |
| 160 | + } |
| 161 | + if cfg != nil { |
| 162 | + out["current"] = map[string]interface{}{ |
| 163 | + "provider": cfg.Provider, "endpoint": cfg.Endpoint, "model": cfg.Model, |
| 164 | + } |
| 165 | + } |
| 166 | + return out |
| 167 | +} |
0 commit comments