File size: 9,755 Bytes
857a91b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
package api

import (
	"encoding/json"
	"net/http"
	"strconv"
	"strings"

	"github.com/agent-matrix/matrix-runtime/internal/hf"
	"github.com/agent-matrix/matrix-runtime/internal/jobs"
	"github.com/agent-matrix/matrix-runtime/internal/models"
	"github.com/agent-matrix/matrix-runtime/internal/store"
)

// currentUser resolves the session bearer token to a user, or returns false.
func (s *Server) currentUser(r *http.Request) (*store.User, bool) {
	if s.store == nil {
		return nil, false
	}
	u, err := s.store.UserBySession(bearer(r))
	if err != nil {
		return nil, false
	}
	return u, true
}

// handleHFSearch proxies the Hugging Face model search server-side (avoiding
// browser CORS) for the console's generic Import Model flow. On any failure it
// returns 200 with live=false and an empty list so the UI can fall back to
// sample data gracefully.
func (s *Server) handleHFSearch(w http.ResponseWriter, r *http.Request) {
	q := r.URL.Query().Get("q")
	task := r.URL.Query().Get("task")
	limit := 16
	if v := r.URL.Query().Get("limit"); v != "" {
		if n, err := strconv.Atoi(v); err == nil {
			limit = n
		}
	}
	items, err := hf.NewClient(s.cfg.HFToken).Search(r.Context(), q, task, limit)
	if err != nil {
		writeJSON(w, http.StatusOK, map[string]any{"items": []any{}, "live": false, "error": err.Error()})
		return
	}
	writeJSON(w, http.StatusOK, map[string]any{"items": items, "live": true})
}

// resolveReq describes a generic model source to resolve into a profile preview.
type resolveReq struct {
	SourceType string `json:"sourceType"`
	SourceURI  string `json:"sourceUri"`
	Provider   string `json:"provider"`
	ExternalID string `json:"externalId"` // e.g. HF model id
	Model      string `json:"model"`      // e.g. hf:owner/name
	Path       string `json:"path"`
	Branch     string `json:"branch"`
	Private    bool   `json:"private"`
}

// handleResolveSource resolves a source into a model-profile preview. Hugging
// Face is resolved for real via model.inspect; other sources are constructed
// from the supplied location.
func (s *Server) handleResolveSource(w http.ResponseWriter, r *http.Request) {
	var req resolveReq
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		writeError(w, http.StatusBadRequest, "invalid JSON body")
		return
	}
	isHF := req.SourceType == "huggingface" || strings.HasPrefix(req.Model, "hf:") || (req.Provider == "Hugging Face")
	if isHF {
		id := req.ExternalID
		if id == "" {
			id = strings.TrimPrefix(req.Model, "hf:")
		}
		meta, err := models.Inspect(r.Context(), "hf:"+id, "main", s.cfg.HFToken)
		if err != nil {
			writeError(w, http.StatusBadGateway, "could not resolve model: "+err.Error())
			return
		}
		writeJSON(w, http.StatusOK, map[string]any{
			"source_type": "huggingface", "provider": "Hugging Face", "external_id": id,
			"display_name": id, "source_uri": "hf:" + id,
			"task": meta.PipelineTag, "library": meta.LibraryName, "license": meta.License,
			"requires_gpu": meta.RequiresGPU, "recommended_runtime": meta.RecommendedRuntime,
			"estimated_parameters": meta.EstimatedParameters, "tags": meta.Tags, "private": req.Private,
		})
		return
	}
	// Generic (GitHub/GitLab/S3/R2/Ollama/URL): construct a profile from the form.
	uri := req.SourceURI
	if req.Path != "" {
		uri = strings.TrimRight(uri, "/") + "/" + strings.TrimLeft(req.Path, "/")
	}
	name := req.ExternalID
	if name == "" {
		name = uri
	}
	writeJSON(w, http.StatusOK, map[string]any{
		"source_type": req.SourceType, "provider": req.Provider, "external_id": name,
		"display_name": name, "source_uri": uri, "task": "text-generation",
		"library": "custom", "license": "review required", "private": req.Private,
		"recommended_runtime": "vLLM / SGLang",
	})
}

// profileJSON shapes a stored profile for the API.
func profileJSON(p store.ModelProfile) map[string]any {
	return map[string]any{
		"id": p.ID, "source_type": p.SourceType, "source_uri": p.SourceURI,
		"provider": p.Provider, "external_id": p.ExternalID, "display_name": p.DisplayName,
		"task": p.Task, "library": p.Library, "license": p.License, "tags": p.Tags,
		"status": p.Status, "created_at": p.CreatedAt, "metadata": p.Metadata,
	}
}

// handleListProfiles lists model profiles for the caller's workspace.
func (s *Server) handleListProfiles(w http.ResponseWriter, r *http.Request) {
	u, ok := s.currentUser(r)
	if !ok {
		writeError(w, http.StatusUnauthorized, "not authenticated")
		return
	}
	list, err := s.store.ListProfiles(u.WorkspaceID)
	if err != nil {
		writeError(w, http.StatusInternalServerError, err.Error())
		return
	}
	out := make([]map[string]any, 0, len(list))
	for _, p := range list {
		out = append(out, profileJSON(p))
	}
	writeJSON(w, http.StatusOK, map[string]any{"profiles": out})
}

type importReq struct {
	SourceType  string         `json:"source_type"`
	SourceURI   string         `json:"source_uri"`
	Provider    string         `json:"provider"`
	ExternalID  string         `json:"external_id"`
	DisplayName string         `json:"display_name"`
	Task        string         `json:"task"`
	Library     string         `json:"library"`
	License     string         `json:"license"`
	Tags        []string       `json:"tags"`
	Metadata    map[string]any `json:"metadata"`
}

// handleImportProfile creates a model profile (status profile_only).
func (s *Server) handleImportProfile(w http.ResponseWriter, r *http.Request) {
	u, ok := s.currentUser(r)
	if !ok {
		writeError(w, http.StatusUnauthorized, "not authenticated")
		return
	}
	var req importReq
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		writeError(w, http.StatusBadRequest, "invalid JSON body")
		return
	}
	if req.DisplayName == "" {
		req.DisplayName = req.ExternalID
	}
	p, err := s.store.CreateProfile(store.ModelProfile{
		WorkspaceID: u.WorkspaceID, SourceType: req.SourceType, SourceURI: req.SourceURI,
		Provider: req.Provider, ExternalID: req.ExternalID, DisplayName: req.DisplayName,
		Task: req.Task, Library: req.Library, License: req.License, Tags: req.Tags,
		Metadata: req.Metadata, Status: "profile_only",
	})
	if err != nil {
		writeError(w, http.StatusInternalServerError, err.Error())
		return
	}
	s.audit(r, u.WorkspaceID, u.ID, "model.imported", p.DisplayName, "success", map[string]any{"provider": p.Provider, "external_id": p.ExternalID})
	writeJSON(w, http.StatusCreated, map[string]any{"profile": profileJSON(*p)})
}

type attachReq struct {
	RuntimeID     string `json:"runtimeId"`
	InstallMode   string `json:"installMode"`
	ServingEngine string `json:"servingEngine"`
}

// handleAttachProfile creates an installation row and a model.attach job that
// streams real progress and persists it.
func (s *Server) handleAttachProfile(w http.ResponseWriter, r *http.Request) {
	u, ok := s.currentUser(r)
	if !ok {
		writeError(w, http.StatusUnauthorized, "not authenticated")
		return
	}
	pid := r.PathValue("id")
	p, err := s.store.GetProfile(u.WorkspaceID, pid)
	if err != nil {
		writeError(w, http.StatusNotFound, "model profile not found")
		return
	}
	var req attachReq
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		writeError(w, http.StatusBadRequest, "invalid JSON body")
		return
	}
	if req.RuntimeID == "" {
		writeError(w, http.StatusBadRequest, "runtimeId is required")
		return
	}
	if req.InstallMode == "" {
		req.InstallMode = "pull_from_source"
	}
	inst, err := s.store.CreateInstallation(store.ModelInstallation{
		WorkspaceID: u.WorkspaceID, ModelProfileID: p.ID, RuntimeID: req.RuntimeID,
		InstallMode: req.InstallMode, ServingEngine: req.ServingEngine, Status: "queued",
	})
	if err != nil {
		writeError(w, http.StatusInternalServerError, err.Error())
		return
	}
	_ = s.store.SetProfileStatus(p.ID, "queued")

	model := p.SourceURI
	if p.Provider == "Hugging Face" {
		model = "hf:" + p.ExternalID
	}
	payload, _ := json.Marshal(map[string]any{
		"installation_id": inst.ID, "profile_id": p.ID, "model": model, "provider": p.Provider,
		"runtime_id": req.RuntimeID, "install_mode": req.InstallMode, "serving_engine": req.ServingEngine,
	})
	job, err := s.manager.Create(jobs.CreateRequest{Type: jobs.TypeModelAttach, TTLSeconds: 180, Payload: payload})
	if err != nil {
		writeError(w, http.StatusUnprocessableEntity, err.Error())
		return
	}
	_ = s.store.SetInstallationJob(inst.ID, job.ID)
	s.audit(r, u.WorkspaceID, u.ID, "model.attached", p.DisplayName, "success", map[string]any{"runtime_id": req.RuntimeID, "job_id": job.ID})

	writeJSON(w, http.StatusAccepted, map[string]any{
		"installation_id": inst.ID,
		"profile_id":      p.ID,
		"job_id":          job.ID,
		"events_url":      "/v1/jobs/" + job.ID + "/events",
	})
}

// installationJSON shapes a stored installation for the API.
func installationJSON(in store.ModelInstallation) map[string]any {
	return map[string]any{
		"id": in.ID, "model_profile_id": in.ModelProfileID, "runtime_id": in.RuntimeID,
		"install_mode": in.InstallMode, "serving_engine": in.ServingEngine,
		"status": in.Status, "progress": in.Progress, "local_path": in.LocalPath,
		"endpoint_url": in.EndpointURL, "job_id": in.JobID,
		"model_name": in.ModelName, "provider": in.Provider, "updated_at": in.UpdatedAt,
	}
}

// handleListInstallations lists runtime-cache installations for the workspace.
func (s *Server) handleListInstallations(w http.ResponseWriter, r *http.Request) {
	u, ok := s.currentUser(r)
	if !ok {
		writeError(w, http.StatusUnauthorized, "not authenticated")
		return
	}
	list, err := s.store.ListInstallations(u.WorkspaceID)
	if err != nil {
		writeError(w, http.StatusInternalServerError, err.Error())
		return
	}
	out := make([]map[string]any, 0, len(list))
	for _, in := range list {
		out = append(out, installationJSON(in))
	}
	writeJSON(w, http.StatusOK, map[string]any{"installations": out})
}