Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-3284: server API + daemon (custom runtime PR2) (#4149)
LinYushen52e76e7b23e9
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 3033ad0121..99d0e6c62b 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -497,6 +497,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Post("/heartbeat", h.DaemonHeartbeat)r.Get("/ws", h.DaemonWebSocket)r.Get("/workspaces/{workspaceId}/repos", h.GetDaemonWorkspaceRepos)+ r.Get("/workspaces/{workspaceId}/runtime-profiles", h.DaemonListRuntimeProfiles)r.Post("/runtimes/{runtimeId}/tasks/claim", h.ClaimTaskByRuntime)r.Get("/runtimes/{runtimeId}/tasks/pending", h.ListPendingTasksByRuntime)@@ -575,6 +576,11 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus// the handler strips the management handle and adds a// can_manage hint so the UI can gate connect/disconnect.r.Get("/github/installations", h.ListGitHubInstallations)+ // Custom runtime profiles — listing/reading is member-visible+ // (the Runtime page renders for everyone; create/edit/delete+ // are admin-gated below).+ r.Get("/runtime-profiles", h.ListRuntimeProfiles)+ r.Get("/runtime-profiles/{profileId}", h.GetRuntimeProfile)})// Admin-level accessr.Group(func(r chi.Router) {@@ -587,6 +593,11 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Delete("/", h.DeleteMember)})r.Delete("/invitations/{invitationId}", h.RevokeInvitation)+ // Custom runtime profile mutations (admin-only).+ r.Post("/runtime-profiles", h.CreateRuntimeProfile)+ r.Patch("/runtime-profiles/{profileId}", h.UpdateRuntimeProfile)+ r.Put("/runtime-profiles/{profileId}", h.UpdateRuntimeProfile)+ r.Delete("/runtime-profiles/{profileId}", h.DeleteRuntimeProfile)})// Owner-only accessr.With(middleware.RequireWorkspaceRoleFromURL(queries, "id", "owner")).Delete("/", h.DeleteWorkspace)diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.goindex cdcea09d55..9d18aa8815 100644--- a/server/internal/daemon/client.go+++ b/server/internal/daemon/client.go@@ -462,6 +462,44 @@ func (c *Client) GetWorkspaceRepos(ctx context.Context, workspaceID string) (*Woreturn &resp, nil}+// RuntimeProfile mirrors the server's workspace custom runtime profile+// (MUL-3284). protocol_family is the provider used for task routing (it+// selects the agent backend), while command_name is the actual executable+// the daemon resolves on PATH and launches. fixed_args are launch arguments+// every agent on this runtime inherits — wiring them into the spawned command+// is best-effort and may not be plumbed yet (see the TODO in runTask).+type RuntimeProfile struct {+ ID string `json:"id"`+ WorkspaceID string `json:"workspace_id"`+ DisplayName string `json:"display_name"`+ ProtocolFamily string `json:"protocol_family"`+ CommandName string `json:"command_name"`+ Description *string `json:"description"`+ FixedArgs []string `json:"fixed_args"`+ Visibility string `json:"visibility"`+ Enabled bool `json:"enabled"`+}++// RuntimeProfilesResponse is the body of+// GET /api/daemon/workspaces/{workspaceID}/runtime-profiles. The server only+// returns enabled profiles for the workspace.+type RuntimeProfilesResponse struct {+ WorkspaceID string `json:"workspace_id"`+ RuntimeProfiles []RuntimeProfile `json:"runtime_profiles"`+}++// GetRuntimeProfiles fetches the workspace's enabled custom runtime profiles.+// Mirrors GetWorkspaceRepos. Callers must treat this as best-effort: an older+// server with no profiles route returns 404, which the daemon swallows and+// continues with built-in runtimes only.+func (c *Client) GetRuntimeProfiles(ctx context.Context, workspaceID string) (*RuntimeProfilesResponse, error) {+ var resp RuntimeProfilesResponse+ if err := c.getJSON(ctx, fmt.Sprintf("/api/daemon/workspaces/%s/runtime-profiles", workspaceID), &resp); err != nil {+ return nil, err+ }+ return &resp, nil+}+// defaultTerminalRetrySchedule is the backoff used by postJSONWithRetry for// terminal task callbacks (CompleteTask / FailTask). N entries → N+1 attempts// in the worst case (one immediate + N retries). Five backoffs totallingdiff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 2c93ec5f13..907f3184a0 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -9,6 +9,7 @@ import ("log/slog""math/rand""os"+ "os/exec""path/filepath""strconv""strings"@@ -69,6 +70,11 @@ var (// helpers above.detectAgentVersion = agent.DetectVersioncheckAgentMinVersion = agent.CheckMinVersion++ // lookPath is an indirection over exec.LookPath so registration tests can+ // resolve custom runtime-profile commands without manipulating the+ // process PATH. Mirrors the detectAgentVersion hook above.+ lookPath = exec.LookPath)// workspaceState tracks registered runtimes for a single workspace.@@ -106,6 +112,12 @@ type Daemon struct {mu sync.Mutexworkspaces map[string]*workspaceStateruntimeIndex map[string]Runtime // runtimeID -> Runtime for provider lookups+ // profileCommandPaths maps a custom runtime profile_id -> the absolute+ // executable path resolved on PATH for that profile's command_name+ // (MUL-3284). Populated in registerRuntimesForWorkspace when a profile's+ // command resolves; read by runTask via customCommandPathForRuntime to+ // launch the custom command for a claimed task. Guarded by mu.+ profileCommandPaths map[string]stringreloading sync.Mutex // prevents concurrent workspace syncsruntimeSet *runtimeSetWatcher // multi-subscriber pub/sub for runtime-set changes@@ -187,6 +199,7 @@ func New(cfg Config, logger *slog.Logger) *Daemon {logger: logger,workspaces: make(map[string]*workspaceState),runtimeIndex: make(map[string]Runtime),+ profileCommandPaths: make(map[string]string),runtimeSet: newRuntimeSetWatcher(),agentVersions: make(map[string]string),wsHBLastAck: make(map[string]time.Time),@@ -750,6 +763,45 @@ func (d *Daemon) findRuntime(id string) *Runtime {return nil}+// recordProfileCommandPath remembers the absolute executable path resolved+// for a custom runtime profile's command_name. Called from+// registerRuntimesForWorkspace. Lazily initializes the map so test fixtures+// that build a Daemon literal without seeding every map don't panic.+func (d *Daemon) recordProfileCommandPath(profileID, path string) {+ if profileID == "" || path == "" {+ return+ }+ d.mu.Lock()+ defer d.mu.Unlock()+ if d.profileCommandPaths == nil {+ d.profileCommandPaths = make(map[string]string)+ }+ d.profileCommandPaths[profileID] = path+}++// customCommandPathForRuntime returns the resolved custom executable path for+// a claimed task's RuntimeID, and whether the runtime is a custom-profile+// runtime. It returns ("", false) for built-in runtimes (no profile) and for+// runtimes whose profile command was never resolved on this host. runTask+// uses this to override the launch path so a custom runtime can run even when+// the host has no built-in agent of the same provider installed.+func (d *Daemon) customCommandPathForRuntime(runtimeID string) (string, bool) {+ if runtimeID == "" {+ return "", false+ }+ d.mu.Lock()+ defer d.mu.Unlock()+ rt, ok := d.runtimeIndex[runtimeID]+ if !ok || rt.ProfileID == "" {+ return "", false+ }+ path, ok := d.profileCommandPaths[rt.ProfileID]+ if !ok || path == "" {+ return "", false+ }+ return path, true+}+func (d *Daemon) registerRuntimesForWorkspace(ctx context.Context, workspaceID string) (*RegisterResponse, error) {d.logger.Debug("registering runtimes for workspace", "workspace_id", workspaceID, "agent_count", len(d.cfg.Agents))var runtimes []map[string]string@@ -776,6 +828,14 @@ func (d *Daemon) registerRuntimesForWorkspace(ctx context.Context, workspaceID s"status": "online",})}++ // Append any workspace custom runtime profiles whose command resolves on+ // this host (MUL-3284). This is best-effort: a fetch error (e.g. an older+ // server returning 404) must never fail registration — the daemon simply+ // continues with the built-in runtimes it already collected. A profile+ // whose command_name is not on PATH is skipped (the host doesn't have it).+ d.appendProfileRuntimes(ctx, workspaceID, &runtimes)+if len(runtimes) == 0 {return nil, fmt.Errorf("no agent runtimes could be registered")}@@ -801,6 +861,79 @@ func (d *Daemon) registerRuntimesForWorkspace(ctx context.Context, workspaceID sreturn resp, nil}+// appendProfileRuntimes fetches the workspace's enabled custom runtime+// profiles (MUL-3284) and appends a runtime registration entry for each one+// whose command_name resolves on this host's PATH. For each resolved profile+// it records the absolute command path keyed by profile_id (via+// recordProfileCommandPath) so runTask can later launch the custom executable+// for a claimed task.+//+// Best-effort by contract: any error fetching profiles (older server, network+// blip) is logged and swallowed — registration proceeds with the built-in+// runtimes already collected. A profile whose command is not on PATH is+// skipped with an Info log (this host simply doesn't have that command).+//+// The registration entry mirrors the built-in shape: name = display_name+// (suffixed with the device name like the built-in path), type =+// protocol_family (the routing provider), version = best-effort detected+// version, status = "online", plus the profile_id the server validates.+func (d *Daemon) appendProfileRuntimes(ctx context.Context, workspaceID string, runtimes *[]map[string]string) {+ resp, err := d.client.GetRuntimeProfiles(ctx, workspaceID)+ if err != nil {+ // Best-effort: never fail registration because profiles couldn't be+ // fetched. An older server with no profiles route returns 404.+ d.logger.Info("skip custom runtime profiles: fetch failed (continuing with built-in runtimes)",+ "workspace_id", workspaceID, "error", err)+ return+ }+ if resp == nil {+ return+ }+ for _, profile := range resp.RuntimeProfiles {+ if profile.CommandName == "" || profile.ProtocolFamily == "" {+ d.logger.Warn("skip custom runtime profile: missing command_name or protocol_family",+ "workspace_id", workspaceID, "profile_id", profile.ID, "display_name", profile.DisplayName)+ continue+ }+ resolved, err := lookPath(profile.CommandName)+ if err != nil {+ // Host doesn't have this command — expected on hosts that aren't+ // provisioned for this profile. Skip without failing.+ d.logger.Info("skip custom runtime profile: command not found on PATH",+ "workspace_id", workspaceID, "profile_id", profile.ID,+ "command_name", profile.CommandName, "error", err)+ continue+ }+ // Best-effort version detection; an empty version is acceptable.+ version, verErr := detectAgentVersion(ctx, resolved)+ if verErr != nil {+ d.logger.Debug("custom runtime profile: version probe failed (registering with empty version)",+ "workspace_id", workspaceID, "profile_id", profile.ID, "path", resolved, "error", verErr)+ version = ""+ }+ displayName := profile.DisplayName+ if d.cfg.DeviceName != "" {+ displayName = fmt.Sprintf("%s (%s)", displayName, d.cfg.DeviceName)+ }+ d.recordProfileCommandPath(profile.ID, resolved)+ d.logger.Info("registering custom runtime profile",+ "workspace_id", workspaceID, "profile_id", profile.ID,+ "protocol_family", profile.ProtocolFamily, "command_path", resolved)+ // NOTE: profile.FixedArgs are launch args every agent on this runtime+ // inherits. Wiring them into the spawned command is intentionally not+ // done here — it's an optional, best-effort enhancement (see MUL-3284+ // PR2 task notes). TODO(MUL-3284): plumb FixedArgs into the agent+ // launch command if/when the agent backend exposes a hook for it.+ *runtimes = append(*runtimes, map[string]string{+ "name": displayName,+ "type": profile.ProtocolFamily,+ "version": version,+ "status": "online",+ "profile_id": profile.ID,+ })+ }+}+func newWorkspaceState(workspaceID string, runtimeIDs []string, reposVersion string, repos []RepoData, settings json.RawMessage) *workspaceState {return &workspaceState{workspaceID: workspaceID,@@ -2641,6 +2774,20 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot id.registerTaskRepos(task.WorkspaceID, task.Repos)entry, ok := d.cfg.Agents[provider]+ // A custom runtime profile (MUL-3284) overrides the executable path: the+ // runtime's protocol_family is the provider (so agent.New still selects+ // the right backend), but the actual binary on PATH is the profile's+ // command_name, resolved at registration time and keyed by RuntimeID here.+ // Critically, a custom runtime can live on a host that has NO built-in+ // agent of the same provider installed, so when the runtime is custom we+ // synthesize an AgentEntry instead of hard-failing on the !ok lookup.+ if customPath, isCustom := d.customCommandPathForRuntime(task.RuntimeID); isCustom {+ entry.Path = customPath+ ok = true+ d.logger.Info("task uses custom runtime profile command",+ "task_id", task.ID, "runtime_id", task.RuntimeID,+ "provider", provider, "command_path", customPath)+ }if !ok {return TaskResult{}, fmt.Errorf("no agent configured for provider %q", provider)}diff --git a/server/internal/daemon/runtime_profile_test.go b/server/internal/daemon/runtime_profile_test.gonew file mode 100644index 0000000000..dba26e73b9--- /dev/null+++ b/server/internal/daemon/runtime_profile_test.go@@ -0,0 +1,279 @@+package daemon++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strconv"+ "strings"+ "testing"+)++// stubLookPath swaps the package-level lookPath indirection used by+// registerRuntimesForWorkspace to resolve custom runtime-profile commands,+// so tests don't have to mutate the process PATH. resolved maps a command+// name to the absolute path it should resolve to; an absent name reports+// "not found".+func stubLookPath(t *testing.T, resolved map[string]string) {+ t.Helper()+ orig := lookPath+ lookPath = func(cmd string) (string, error) {+ if p, ok := resolved[cmd]; ok {+ return p, nil+ }+ return "", &osExecNotFound{cmd: cmd}+ }+ t.Cleanup(func() { lookPath = orig })+}++type osExecNotFound struct{ cmd string }++func (e *osExecNotFound) Error() string { return "exec: " + e.cmd + ": not found in $PATH" }++// TestClient_GetRuntimeProfiles_RequestShape asserts the daemon GETs the+// documented path and parses the server's runtime_profiles payload.+func TestClient_GetRuntimeProfiles_RequestShape(t *testing.T) {+ var gotMethod, gotPath string+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ gotMethod = r.Method+ gotPath = r.URL.Path+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{+ "workspace_id":"ws-1",+ "runtime_profiles":[{+ "id":"prof-1",+ "workspace_id":"ws-1",+ "display_name":"Company Codex",+ "protocol_family":"codex",+ "command_name":"company-codex",+ "description":null,+ "fixed_args":["--foo"],+ "visibility":"workspace",+ "created_by":null,+ "enabled":true,+ "created_at":"2026-01-01T00:00:00Z",+ "updated_at":"2026-01-01T00:00:00Z"+ }]+ }`))+ }))+ defer srv.Close()++ c := NewClient(srv.URL)+ c.SetToken("tok")+ resp, err := c.GetRuntimeProfiles(context.Background(), "ws-1")+ if err != nil {+ t.Fatalf("GetRuntimeProfiles: %v", err)+ }+ if gotMethod != http.MethodGet {+ t.Errorf("method = %q, want GET", gotMethod)+ }+ if gotPath != "/api/daemon/workspaces/ws-1/runtime-profiles" {+ t.Errorf("path = %q, want /api/daemon/workspaces/ws-1/runtime-profiles", gotPath)+ }+ if resp.WorkspaceID != "ws-1" || len(resp.RuntimeProfiles) != 1 {+ t.Fatalf("unexpected response: %+v", resp)+ }+ p := resp.RuntimeProfiles[0]+ if p.ID != "prof-1" || p.ProtocolFamily != "codex" || p.CommandName != "company-codex" {+ t.Errorf("profile fields wrong: %+v", p)+ }+ if !p.Enabled {+ t.Errorf("profile should be enabled")+ }+ if len(p.FixedArgs) != 1 || p.FixedArgs[0] != "--foo" {+ t.Errorf("fixed_args = %v, want [--foo]", p.FixedArgs)+ }+}++// profileRegisterFixture wires a Daemon against a fake server that serves a+// configurable set of runtime profiles and captures the runtimes array sent+// to /api/daemon/register.+type profileRegisterFixture struct {+ daemon *Daemon+ server *httptest.Server+ sentRuntimes []map[string]any+}++func newProfileRegisterFixture(t *testing.T, profiles []RuntimeProfile, profilesStatus int) *profileRegisterFixture {+ t.Helper()+ fx := &profileRegisterFixture{}+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch {+ case r.URL.Path == "/api/daemon/register":+ var body struct {+ Runtimes []map[string]any `json:"runtimes"`+ }+ _ = json.NewDecoder(r.Body).Decode(&body)+ fx.sentRuntimes = body.Runtimes+ // Echo back a Runtime row per requested runtime, threading+ // profile_id so the caller can populate runtimeIndex from it.+ var resp RegisterResponse+ for i, rt := range body.Runtimes {+ id := "rt-" + strconv.Itoa(i)+ profileID, _ := rt["profile_id"].(string)+ typ, _ := rt["type"].(string)+ resp.Runtimes = append(resp.Runtimes, Runtime{+ ID: id,+ Name: "n",+ Provider: typ,+ Status: "online",+ ProfileID: profileID,+ })+ }+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(resp)+ case len(r.URL.Path) > len("/runtime-profiles") && strings.HasSuffix(r.URL.Path, "/runtime-profiles"):+ if profilesStatus != 0 && profilesStatus != http.StatusOK {+ w.WriteHeader(profilesStatus)+ return+ }+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(RuntimeProfilesResponse{+ WorkspaceID: "ws-1",+ RuntimeProfiles: profiles,+ })+ default:+ w.WriteHeader(http.StatusOK)+ }+ }))+ t.Cleanup(srv.Close)+ d := freshDaemon(srv.URL)+ d.profileCommandPaths = make(map[string]string)+ fx.daemon = d+ fx.server = srv+ return fx+}++// TestRegisterRuntimes_AppendsProfileRuntime verifies that a custom profile+// whose command resolves on PATH is appended as a runtime entry carrying+// profile_id, and that its resolved command path is recorded for runTask.+// Uses a custom-only host (no built-in agents) to also prove that path still+// registers.+func TestRegisterRuntimes_AppendsProfileRuntime(t *testing.T) {+ t.Cleanup(stubAgentVersion(t))+ stubLookPath(t, map[string]string{"company-codex": "/opt/bin/company-codex"})++ profiles := []RuntimeProfile{{+ ID: "prof-1",+ WorkspaceID: "ws-1",+ DisplayName: "Company Codex",+ ProtocolFamily: "codex",+ CommandName: "company-codex",+ Visibility: "workspace",+ Enabled: true,+ }}+ fx := newProfileRegisterFixture(t, profiles, http.StatusOK)+ d := fx.daemon+ // Custom-only host: no built-in agents configured.+ d.cfg.Agents = map[string]AgentEntry{}++ resp, err := d.registerRuntimesForWorkspace(context.Background(), "ws-1")+ if err != nil {+ t.Fatalf("registerRuntimesForWorkspace: %v", err)+ }++ // The register request must carry exactly one runtime: the profile.+ if len(fx.sentRuntimes) != 1 {+ t.Fatalf("sent runtimes = %d, want 1: %+v", len(fx.sentRuntimes), fx.sentRuntimes)+ }+ sent := fx.sentRuntimes[0]+ if sent["type"] != "codex" {+ t.Errorf("sent type = %v, want codex", sent["type"])+ }+ if sent["profile_id"] != "prof-1" {+ t.Errorf("sent profile_id = %v, want prof-1", sent["profile_id"])+ }+ if sent["status"] != "online" {+ t.Errorf("sent status = %v, want online", sent["status"])+ }++ // The resolved command path must be recorded keyed by profile_id.+ if got := d.profileCommandPaths["prof-1"]; got != "/opt/bin/company-codex" {+ t.Errorf("profileCommandPaths[prof-1] = %q, want /opt/bin/company-codex", got)+ }++ // The response runtime carries the profile_id back.+ if len(resp.Runtimes) != 1 || resp.Runtimes[0].ProfileID != "prof-1" {+ t.Fatalf("response runtimes wrong: %+v", resp.Runtimes)+ }+}++// TestRegisterRuntimes_SkipsProfileNotOnPath verifies a profile whose command+// is missing on this host is skipped, and that a host with no built-in agents+// and no resolvable profiles fails registration (len==0 guard preserved).+func TestRegisterRuntimes_SkipsProfileNotOnPath(t *testing.T) {+ t.Cleanup(stubAgentVersion(t))+ stubLookPath(t, map[string]string{}) // nothing resolves++ profiles := []RuntimeProfile{{+ ID: "prof-1",+ WorkspaceID: "ws-1",+ DisplayName: "Company Codex",+ ProtocolFamily: "codex",+ CommandName: "company-codex",+ Enabled: true,+ }}+ fx := newProfileRegisterFixture(t, profiles, http.StatusOK)+ d := fx.daemon+ d.cfg.Agents = map[string]AgentEntry{}++ _, err := d.registerRuntimesForWorkspace(context.Background(), "ws-1")+ if err == nil {+ t.Fatalf("expected error when no runtimes resolve, got nil")+ }+ if _, ok := d.profileCommandPaths["prof-1"]; ok {+ t.Errorf("profileCommandPaths should not record an unresolved profile")+ }+}++// TestRegisterRuntimes_ProfilesFetchErrorIsBestEffort verifies a 404 from the+// profiles endpoint does not fail registration when a built-in agent exists.+func TestRegisterRuntimes_ProfilesFetchErrorIsBestEffort(t *testing.T) {+ t.Cleanup(stubAgentVersion(t))+ stubLookPath(t, map[string]string{})++ fx := newProfileRegisterFixture(t, nil, http.StatusNotFound)+ d := fx.daemon+ // Built-in agent present so registration has something to register.+ d.cfg.Agents = map[string]AgentEntry{"claude": {Path: "/usr/bin/true"}}++ resp, err := d.registerRuntimesForWorkspace(context.Background(), "ws-1")+ if err != nil {+ t.Fatalf("registration should succeed despite profiles 404: %v", err)+ }+ if len(fx.sentRuntimes) != 1 || fx.sentRuntimes[0]["type"] != "claude" {+ t.Fatalf("expected only the built-in claude runtime, got %+v", fx.sentRuntimes)+ }+ if len(resp.Runtimes) != 1 {+ t.Fatalf("response runtimes = %d, want 1", len(resp.Runtimes))+ }+}++// TestCustomCommandPathForRuntime covers the runtimeID -> command-path+// bookkeeping that runTask relies on to override the launch path.+func TestCustomCommandPathForRuntime(t *testing.T) {+ d := freshDaemon("")+ d.profileCommandPaths = map[string]string{"prof-1": "/opt/bin/company-codex"}+ // rt-custom is a custom-profile runtime; rt-builtin is a normal one.+ d.runtimeIndex["rt-custom"] = Runtime{ID: "rt-custom", Provider: "codex", ProfileID: "prof-1"}+ d.runtimeIndex["rt-builtin"] = Runtime{ID: "rt-builtin", Provider: "claude"}++ if path, ok := d.customCommandPathForRuntime("rt-custom"); !ok || path != "/opt/bin/company-codex" {+ t.Errorf("custom runtime: got (%q, %v), want (/opt/bin/company-codex, true)", path, ok)+ }+ if path, ok := d.customCommandPathForRuntime("rt-builtin"); ok || path != "" {+ t.Errorf("built-in runtime: got (%q, %v), want (\"\", false)", path, ok)+ }+ if path, ok := d.customCommandPathForRuntime("rt-unknown"); ok || path != "" {+ t.Errorf("unknown runtime: got (%q, %v), want (\"\", false)", path, ok)+ }+ // A custom runtime whose profile path was never resolved on this host+ // (profile_id not in profileCommandPaths) must report not-custom so+ // runTask falls back to its normal provider lookup rather than launching+ // an empty path.+ d.runtimeIndex["rt-unresolved"] = Runtime{ID: "rt-unresolved", Provider: "codex", ProfileID: "prof-missing"}+ if path, ok := d.customCommandPathForRuntime("rt-unresolved"); ok || path != "" {+ t.Errorf("unresolved profile: got (%q, %v), want (\"\", false)", path, ok)+ }+}diff --git a/server/internal/daemon/types.go b/server/internal/daemon/types.goindex 19f4df4192..93f9ef68b1 100644--- a/server/internal/daemon/types.go+++ b/server/internal/daemon/types.go@@ -14,6 +14,12 @@ type Runtime struct {Name string `json:"name"`Provider string `json:"provider"`Status string `json:"status"`+ // ProfileID is non-empty when this runtime was registered from a+ // workspace custom runtime profile (MUL-3284). It links the runtime row+ // back to the profile so the daemon can resolve the profile's+ // command_name to the executable to launch. Built-in (provider-detected)+ // runtimes leave this empty.+ ProfileID string `json:"profile_id,omitempty"`}// RepoData holds repository information from the workspace.diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 2cbf383d58..0a9bcd6a1a 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -181,6 +181,11 @@ type DaemonRegisterRequest struct {Type string `json:"type"`Version string `json:"version"` // agent CLI version (claude/codex)Status string `json:"status"`+ // ProfileID, when non-empty, marks this as an instance of a custom+ // runtime_profile (MUL-3284). Empty = built-in runtime (legacy path).+ // Type carries the protocol family for both built-in and custom rows+ // so task routing (agent.New) is unchanged.+ ProfileID string `json:"profile_id"`} `json:"runtimes"`}@@ -333,51 +338,125 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {"launched_by": req.LaunchedBy,})- row, err := h.Queries.UpsertAgentRuntime(r.Context(), db.UpsertAgentRuntimeParams{- WorkspaceID: wsUUID,- DaemonID: strToText(req.DaemonID),- Name: name,- RuntimeMode: "local",- Provider: provider,- Status: status,- DeviceInfo: deviceInfo,- Metadata: metadata,- OwnerID: ownerID,- })- if err != nil {- obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.RuntimeFailed(- uuidToString(ownerID),- req.WorkspaceID,- req.DaemonID,- provider,- "registration_failed",- "db_error",- true,- ))- writeError(w, http.StatusInternalServerError, "failed to register runtime: "+err.Error())- return- }+ var registered db.AgentRuntime+ var inserted bool+ isCustom := strings.TrimSpace(runtime.ProfileID) != ""- registered := db.AgentRuntime{- ID: row.ID,- WorkspaceID: row.WorkspaceID,- DaemonID: row.DaemonID,- Name: row.Name,- RuntimeMode: row.RuntimeMode,- Provider: row.Provider,- Status: row.Status,- DeviceInfo: row.DeviceInfo,- Metadata: row.Metadata,- LastSeenAt: row.LastSeenAt,- CreatedAt: row.CreatedAt,- UpdatedAt: row.UpdatedAt,- OwnerID: row.OwnerID,- LegacyDaemonID: row.LegacyDaemonID,+ if isCustom {+ profileUUID, pok := parseUUIDOrBadRequest(w, strings.TrimSpace(runtime.ProfileID), "profile_id")+ if !pok {+ return+ }+ // The profile must exist in this workspace and be enabled. Trust+ // the profile's stored protocol_family over the daemon-sent type so+ // the provider used for task routing cannot drift from the profile.+ profile, perr := h.Queries.GetRuntimeProfileForWorkspace(r.Context(), db.GetRuntimeProfileForWorkspaceParams{+ ID: profileUUID,+ WorkspaceID: wsUUID,+ })+ if perr != nil {+ writeError(w, http.StatusBadRequest, "unknown runtime profile: "+runtime.ProfileID)+ return+ }+ if !profile.Enabled {+ writeError(w, http.StatusConflict, "runtime profile is disabled: "+runtime.ProfileID)+ return+ }+ provider = profile.ProtocolFamily++ prow, err := h.Queries.UpsertAgentRuntimeWithProfile(r.Context(), db.UpsertAgentRuntimeWithProfileParams{+ WorkspaceID: wsUUID,+ DaemonID: strToText(req.DaemonID),+ Name: name,+ RuntimeMode: "local",+ Provider: provider,+ Status: status,+ DeviceInfo: deviceInfo,+ Metadata: metadata,+ OwnerID: ownerID,+ ProfileID: profileUUID,+ })+ if err != nil {+ obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.RuntimeFailed(+ uuidToString(ownerID),+ req.WorkspaceID,+ req.DaemonID,+ provider,+ "registration_failed",+ "db_error",+ true,+ ))+ writeError(w, http.StatusInternalServerError, "failed to register runtime: "+err.Error())+ return+ }+ inserted = prow.Inserted+ registered = db.AgentRuntime{+ ID: prow.ID,+ WorkspaceID: prow.WorkspaceID,+ DaemonID: prow.DaemonID,+ Name: prow.Name,+ RuntimeMode: prow.RuntimeMode,+ Provider: prow.Provider,+ Status: prow.Status,+ DeviceInfo: prow.DeviceInfo,+ Metadata: prow.Metadata,+ LastSeenAt: prow.LastSeenAt,+ CreatedAt: prow.CreatedAt,+ UpdatedAt: prow.UpdatedAt,+ OwnerID: prow.OwnerID,+ LegacyDaemonID: prow.LegacyDaemonID,+ Visibility: prow.Visibility,+ ProfileID: prow.ProfileID,+ }+ } else {+ row, err := h.Queries.UpsertAgentRuntime(r.Context(), db.UpsertAgentRuntimeParams{+ WorkspaceID: wsUUID,+ DaemonID: strToText(req.DaemonID),+ Name: name,+ RuntimeMode: "local",+ Provider: provider,+ Status: status,+ DeviceInfo: deviceInfo,+ Metadata: metadata,+ OwnerID: ownerID,+ })+ if err != nil {+ obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.RuntimeFailed(+ uuidToString(ownerID),+ req.WorkspaceID,+ req.DaemonID,+ provider,+ "registration_failed",+ "db_error",+ true,+ ))+ writeError(w, http.StatusInternalServerError, "failed to register runtime: "+err.Error())+ return+ }+ inserted = row.Inserted+ registered = db.AgentRuntime{+ ID: row.ID,+ WorkspaceID: row.WorkspaceID,+ DaemonID: row.DaemonID,+ Name: row.Name,+ RuntimeMode: row.RuntimeMode,+ Provider: row.Provider,+ Status: row.Status,+ DeviceInfo: row.DeviceInfo,+ Metadata: row.Metadata,+ LastSeenAt: row.LastSeenAt,+ CreatedAt: row.CreatedAt,+ UpdatedAt: row.UpdatedAt,+ OwnerID: row.OwnerID,+ LegacyDaemonID: row.LegacyDaemonID,+ Visibility: row.Visibility,+ ProfileID: row.ProfileID,+ }}// Inserted is false for normal daemon reconnects/upserts, so// runtime_ready is a first-ready-per-runtime-row signal.- if row.Inserted {+ if inserted {obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.RuntimeRegistered(uuidToString(ownerID),req.WorkspaceID,@@ -404,7 +483,15 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {// (e.g. "host.local", "host", "host-staging"); for each match we// reassign agents + tasks onto the new UUID-keyed row, then delete// the stale row so there's only ever one runtime per machine.- h.mergeLegacyRuntimes(r, registered, provider, req.LegacyDaemonIDs)+ //+ // Only built-in runtimes participate: legacy rows predate custom+ // profiles, so a profile-keyed instance never has a hostname-derived+ // ancestor to merge, and mergeLegacyRuntimes scopes by provider alone+ // (no profile_id), which could otherwise fold a built-in row into a+ // custom one of the same provider.+ if !isCustom {+ h.mergeLegacyRuntimes(r, registered, provider, req.LegacyDaemonIDs)+ }resp = append(resp, runtimeToResponse(registered))}diff --git a/server/internal/handler/runtime.go b/server/internal/handler/runtime.goindex f3e07dab68..6ed4a16dad 100644--- a/server/internal/handler/runtime.go+++ b/server/internal/handler/runtime.go@@ -33,6 +33,9 @@ type AgentRuntimeResponse struct {// can bind agents) or "public" (any workspace member can). See migration// 083 and canUseRuntimeForAgent.Visibility string `json:"visibility"`+ // ProfileID is set when this runtime is an instance of a custom+ // runtime_profile (MUL-3284); null for built-in runtimes.+ ProfileID *string `json:"profile_id"`LastSeenAt *string `json:"last_seen_at"`CreatedAt string `json:"created_at"`UpdatedAt string `json:"updated_at"`@@ -60,6 +63,7 @@ func runtimeToResponse(rt db.AgentRuntime) AgentRuntimeResponse {Metadata: metadata,OwnerID: uuidToPtr(rt.OwnerID),Visibility: rt.Visibility,+ ProfileID: uuidToPtr(rt.ProfileID),LastSeenAt: timestampToPtr(rt.LastSeenAt),CreatedAt: timestampToString(rt.CreatedAt),UpdatedAt: timestampToString(rt.UpdatedAt),diff --git a/server/internal/handler/runtime_profile.go b/server/internal/handler/runtime_profile.gonew file mode 100644index 0000000000..e052bdbb53--- /dev/null+++ b/server/internal/handler/runtime_profile.go@@ -0,0 +1,490 @@+package handler++import (+ "encoding/json"+ "errors"+ "log/slog"+ "net/http"+ "strings"++ "github.com/go-chi/chi/v5"+ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/pkg/agent"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// ---------------------------------------------------------------------------+// Custom Runtime Profiles (MUL-3284)+//+// A runtime_profile is a workspace-level, team-shared definition of a custom+// runtime — e.g. an in-house Codex wrapper. Daemons pull the enabled profiles+// for their workspace, resolve command_name on PATH, and register an+// agent_runtime instance carrying the profile_id. The profile only changes how+// a runtime is launched/displayed; the underlying protocol_family must be a+// backend Multica officially supports (validated against agent.SupportedTypes).+//+// Iron rule: a profile carries NO generic per-agent args. Per-agent launch args+// stay on agent.custom_args. The only args field is fixed_args — args every+// agent on this runtime must inherit to enter a compatible mode.+// ---------------------------------------------------------------------------++type RuntimeProfileResponse struct {+ ID string `json:"id"`+ WorkspaceID string `json:"workspace_id"`+ DisplayName string `json:"display_name"`+ ProtocolFamily string `json:"protocol_family"`+ CommandName string `json:"command_name"`+ Description *string `json:"description"`+ FixedArgs []string `json:"fixed_args"`+ Visibility string `json:"visibility"`+ CreatedBy *string `json:"created_by"`+ Enabled bool `json:"enabled"`+ CreatedAt string `json:"created_at"`+ UpdatedAt string `json:"updated_at"`+}++func runtimeProfileToResponse(p db.RuntimeProfile) RuntimeProfileResponse {+ args := []string{}+ if len(p.FixedArgs) > 0 {+ _ = json.Unmarshal(p.FixedArgs, &args)+ if args == nil {+ args = []string{}+ }+ }+ return RuntimeProfileResponse{+ ID: uuidToString(p.ID),+ WorkspaceID: uuidToString(p.WorkspaceID),+ DisplayName: p.DisplayName,+ ProtocolFamily: p.ProtocolFamily,+ CommandName: p.CommandName,+ Description: textToPtr(p.Description),+ FixedArgs: args,+ Visibility: p.Visibility,+ CreatedBy: uuidToPtr(p.CreatedBy),+ Enabled: p.Enabled,+ CreatedAt: timestampToString(p.CreatedAt),+ UpdatedAt: timestampToString(p.UpdatedAt),+ }+}++// validRuntimeProfileVisibility mirrors the CHECK in migration 120.+func validRuntimeProfileVisibility(v string) bool {+ return v == "workspace" || v == "private"+}++// marshalFixedArgs validates and JSON-encodes the fixed_args list. Each entry+// must be a non-empty string; the column defaults to an empty array.+func marshalFixedArgs(args []string) ([]byte, error) {+ if len(args) == 0 {+ return []byte("[]"), nil+ }+ clean := make([]string, 0, len(args))+ for _, a := range args {+ // fixed_args are launch flags inherited by every agent on the runtime;+ // blank entries are always a client mistake.+ if strings.TrimSpace(a) == "" {+ return nil, errors.New("fixed_args entries must be non-empty")+ }+ clean = append(clean, a)+ }+ return json.Marshal(clean)+}++type createRuntimeProfileRequest struct {+ DisplayName string `json:"display_name"`+ ProtocolFamily string `json:"protocol_family"`+ CommandName string `json:"command_name"`+ Description *string `json:"description"`+ FixedArgs []string `json:"fixed_args"`+ Visibility string `json:"visibility"`+ Enabled *bool `json:"enabled"`+}++// CreateRuntimeProfile creates a workspace runtime profile. Admin-gated by the+// router. protocol_family is validated against the agent backend whitelist.+func (h *Handler) CreateRuntimeProfile(w http.ResponseWriter, r *http.Request) {+ wsID := strings.TrimSpace(chi.URLParam(r, "id"))+ member, ok := h.requireWorkspaceMember(w, r, wsID, "workspace not found")+ if !ok {+ return+ }+ wsUUID, ok := parseUUIDOrBadRequest(w, wsID, "workspace id")+ if !ok {+ return+ }++ var req createRuntimeProfileRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }++ req.DisplayName = strings.TrimSpace(req.DisplayName)+ req.ProtocolFamily = strings.TrimSpace(req.ProtocolFamily)+ req.CommandName = strings.TrimSpace(req.CommandName)+ req.Visibility = strings.TrimSpace(req.Visibility)++ if req.DisplayName == "" {+ writeError(w, http.StatusBadRequest, "display_name is required")+ return+ }+ if !agent.IsSupportedType(req.ProtocolFamily) {+ writeError(w, http.StatusBadRequest, "unsupported protocol_family: must be one of "+strings.Join(agent.SupportedTypes, ", "))+ return+ }+ if req.CommandName == "" {+ writeError(w, http.StatusBadRequest, "command_name is required")+ return+ }+ if req.Visibility == "" {+ req.Visibility = "workspace"+ }+ if !validRuntimeProfileVisibility(req.Visibility) {+ writeError(w, http.StatusBadRequest, "visibility must be 'workspace' or 'private'")+ return+ }+ fixedArgs, err := marshalFixedArgs(req.FixedArgs)+ if err != nil {+ writeError(w, http.StatusBadRequest, err.Error())+ return+ }+ enabled := true+ if req.Enabled != nil {+ enabled = *req.Enabled+ }++ profile, err := h.Queries.CreateRuntimeProfile(r.Context(), db.CreateRuntimeProfileParams{+ WorkspaceID: wsUUID,+ DisplayName: req.DisplayName,+ ProtocolFamily: req.ProtocolFamily,+ CommandName: req.CommandName,+ Description: ptrToText(req.Description),+ FixedArgs: fixedArgs,+ Visibility: req.Visibility,+ CreatedBy: member.UserID,+ Enabled: enabled,+ })+ if err != nil {+ if isUniqueViolation(err) {+ writeError(w, http.StatusConflict, "a runtime profile with this display_name already exists")+ return+ }+ slog.Error("CreateRuntimeProfile failed", "error", err, "workspace_id", wsID)+ writeError(w, http.StatusInternalServerError, "failed to create runtime profile")+ return+ }++ h.publish(protocol.EventDaemonRegister, wsID, "member", uuidToString(member.UserID), map[string]any{+ "runtime_profile_id": uuidToString(profile.ID),+ })++ writeJSON(w, http.StatusCreated, runtimeProfileToResponse(profile))+}++// ListRuntimeProfiles returns every runtime profile in the workspace.+// Member-gated by the router.+func (h *Handler) ListRuntimeProfiles(w http.ResponseWriter, r *http.Request) {+ wsID := strings.TrimSpace(chi.URLParam(r, "id"))+ if _, ok := h.requireWorkspaceMember(w, r, wsID, "workspace not found"); !ok {+ return+ }+ wsUUID, ok := parseUUIDOrBadRequest(w, wsID, "workspace id")+ if !ok {+ return+ }++ profiles, err := h.Queries.ListRuntimeProfiles(r.Context(), wsUUID)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list runtime profiles")+ return+ }+ resp := make([]RuntimeProfileResponse, len(profiles))+ for i, p := range profiles {+ resp[i] = runtimeProfileToResponse(p)+ }+ writeJSON(w, http.StatusOK, map[string]any{"runtime_profiles": resp})+}++// GetRuntimeProfile returns one runtime profile. Member-gated by the router.+func (h *Handler) GetRuntimeProfile(w http.ResponseWriter, r *http.Request) {+ wsID := strings.TrimSpace(chi.URLParam(r, "id"))+ if _, ok := h.requireWorkspaceMember(w, r, wsID, "workspace not found"); !ok {+ return+ }+ wsUUID, ok := parseUUIDOrBadRequest(w, wsID, "workspace id")+ if !ok {+ return+ }+ profileUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "profileId"), "profile id")+ if !ok {+ return+ }++ profile, err := h.Queries.GetRuntimeProfileForWorkspace(r.Context(), db.GetRuntimeProfileForWorkspaceParams{+ ID: profileUUID,+ WorkspaceID: wsUUID,+ })+ if err != nil {+ writeError(w, http.StatusNotFound, "runtime profile not found")+ return+ }+ writeJSON(w, http.StatusOK, runtimeProfileToResponse(profile))+}++type updateRuntimeProfileRequest struct {+ DisplayName *string `json:"display_name"`+ CommandName *string `json:"command_name"`+ Description *string `json:"description"`+ FixedArgs *[]string `json:"fixed_args"`+ Visibility *string `json:"visibility"`+ Enabled *bool `json:"enabled"`+}++// UpdateRuntimeProfile applies a partial update. protocol_family is immutable+// (changing it would silently repoint bound agents onto a different backend).+// Admin-gated by the router.+func (h *Handler) UpdateRuntimeProfile(w http.ResponseWriter, r *http.Request) {+ wsID := strings.TrimSpace(chi.URLParam(r, "id"))+ member, ok := h.requireWorkspaceMember(w, r, wsID, "workspace not found")+ if !ok {+ return+ }+ wsUUID, ok := parseUUIDOrBadRequest(w, wsID, "workspace id")+ if !ok {+ return+ }+ profileUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "profileId"), "profile id")+ if !ok {+ return+ }++ var req updateRuntimeProfileRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }++ params := db.UpdateRuntimeProfileParams{ID: profileUUID, WorkspaceID: wsUUID}+ if req.DisplayName != nil {+ name := strings.TrimSpace(*req.DisplayName)+ if name == "" {+ writeError(w, http.StatusBadRequest, "display_name cannot be empty")+ return+ }+ params.DisplayName = strToText(name)+ }+ if req.CommandName != nil {+ cmd := strings.TrimSpace(*req.CommandName)+ if cmd == "" {+ writeError(w, http.StatusBadRequest, "command_name cannot be empty")+ return+ }+ params.CommandName = strToText(cmd)+ }+ if req.Description != nil {+ params.Description = ptrToText(req.Description)+ }+ if req.FixedArgs != nil {+ fixedArgs, err := marshalFixedArgs(*req.FixedArgs)+ if err != nil {+ writeError(w, http.StatusBadRequest, err.Error())+ return+ }+ params.FixedArgs = fixedArgs+ }+ if req.Visibility != nil {+ vis := strings.TrimSpace(*req.Visibility)+ if !validRuntimeProfileVisibility(vis) {+ writeError(w, http.StatusBadRequest, "visibility must be 'workspace' or 'private'")+ return+ }+ params.Visibility = strToText(vis)+ }+ if req.Enabled != nil {+ params.Enabled = pgtype.Bool{Bool: *req.Enabled, Valid: true}+ }++ profile, err := h.Queries.UpdateRuntimeProfile(r.Context(), params)+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ writeError(w, http.StatusNotFound, "runtime profile not found")+ return+ }+ if isUniqueViolation(err) {+ writeError(w, http.StatusConflict, "a runtime profile with this display_name already exists")+ return+ }+ slog.Error("UpdateRuntimeProfile failed", "error", err, "profile_id", uuidToString(profileUUID))+ writeError(w, http.StatusInternalServerError, "failed to update runtime profile")+ return+ }++ h.publish(protocol.EventDaemonRegister, wsID, "member", uuidToString(member.UserID), map[string]any{+ "runtime_profile_id": uuidToString(profile.ID),+ })++ writeJSON(w, http.StatusOK, runtimeProfileToResponse(profile))+}++// DeleteRuntimeProfile removes a profile and, in the same transaction, the+// agent_runtime instance rows registered against it. Migration 120 dropped the+// DB ON DELETE CASCADE, so this app-layer cleanup is what prevents orphaned+// runtime rows. Refuses (409) while active agents are still bound to the+// profile's runtimes. Admin-gated by the router.+func (h *Handler) DeleteRuntimeProfile(w http.ResponseWriter, r *http.Request) {+ wsID := strings.TrimSpace(chi.URLParam(r, "id"))+ member, ok := h.requireWorkspaceMember(w, r, wsID, "workspace not found")+ if !ok {+ return+ }+ wsUUID, ok := parseUUIDOrBadRequest(w, wsID, "workspace id")+ if !ok {+ return+ }+ profileUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "profileId"), "profile id")+ if !ok {+ return+ }++ // Confirm the profile exists in this workspace before mutating anything.+ if _, err := h.Queries.GetRuntimeProfileForWorkspace(r.Context(), db.GetRuntimeProfileForWorkspaceParams{+ ID: profileUUID,+ WorkspaceID: wsUUID,+ }); err != nil {+ writeError(w, http.StatusNotFound, "runtime profile not found")+ return+ }++ // Enumerate the runtime instance rows registered against this profile.+ // The profile-delete cascade must run the SAME teardown the runtime-delete+ // path uses for each one: agent.runtime_id is ON DELETE RESTRICT, so an+ // archived agent still pointing at one of these rows would turn a bare+ // delete into a 500. We refuse active agents (409) and clean archived+ // agents / their archived squad+autopilot references before deleting.+ runtimeIDs, err := h.Queries.ListAgentRuntimeIDsByProfile(r.Context(), profileUUID)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to enumerate profile runtimes")+ return+ }++ // Guard 1: refuse while any active (non-archived) agent is bound to one of+ // the profile's runtimes. Keep this a 409 — deleting would orphan live+ // agents.+ agentCount, err := h.Queries.CountAgentsByProfile(r.Context(), profileUUID)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to check profile usage")+ return+ }+ if agentCount > 0 {+ writeError(w, http.StatusConflict, "cannot delete runtime profile: active agents are still bound to its runtimes")+ return+ }++ // Guard 2: refuse (before any teardown) if any runtime still has an active+ // squad whose leader is already archived on it — same rule the+ // runtime-delete path enforces. Checked per runtime up front so we never+ // half-tear-down and then 409.+ for _, rid := range runtimeIDs {+ activeSquadCount, err := h.Queries.CountActiveSquadsWithArchivedLeadersByRuntime(r.Context(), rid)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to check runtime squad dependencies")+ return+ }+ if activeSquadCount > 0 {+ writeError(w, http.StatusConflict, "cannot delete runtime profile: a runtime has active squads led by archived agents. Archive those squads or assign them a new leader first.")+ return+ }+ }++ tx, err := h.TxStarter.Begin(r.Context())+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to begin transaction")+ return+ }+ defer tx.Rollback(r.Context())+ qtx := h.Queries.WithTx(tx)++ // App-layer cascade, per runtime, mirroring DeleteAgentRuntime: pause+ // autopilots pointing at the archived agents, drop archived squads led by+ // them, then hard-delete the archived agents so the RESTRICT FK on+ // agent.runtime_id no longer blocks removing the runtime row.+ for _, rid := range runtimeIDs {+ archivedAgentIDs, err := qtx.ListArchivedAgentIDsByRuntime(r.Context(), rid)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to enumerate archived agents")+ return+ }+ if len(archivedAgentIDs) > 0 {+ if err := qtx.PauseAutopilotsByAgentAssignees(r.Context(), archivedAgentIDs); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to pause autopilots")+ return+ }+ }+ if err := qtx.DeleteSquadsByArchivedAgentsOnRuntime(r.Context(), rid); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to clean up squads referencing archived agents")+ return+ }+ if err := qtx.DeleteArchivedAgentsByRuntime(r.Context(), rid); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to clean up archived agents")+ return+ }+ }++ // Now the runtime rows have no agent references; remove them, then the+ // profile itself.+ if _, err := qtx.DeleteAgentRuntimesByProfile(r.Context(), profileUUID); err != nil {+ slog.Error("DeleteAgentRuntimesByProfile failed", "error", err, "profile_id", uuidToString(profileUUID))+ writeError(w, http.StatusInternalServerError, "failed to clean up runtime instances")+ return+ }+ if err := qtx.DeleteRuntimeProfile(r.Context(), db.DeleteRuntimeProfileParams{+ ID: profileUUID,+ WorkspaceID: wsUUID,+ }); err != nil {+ slog.Error("DeleteRuntimeProfile failed", "error", err, "profile_id", uuidToString(profileUUID))+ writeError(w, http.StatusInternalServerError, "failed to delete runtime profile")+ return+ }+ if err := tx.Commit(r.Context()); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to commit transaction")+ return+ }++ // Tell connected clients to refetch the runtime list (instances vanished).+ h.publish(protocol.EventDaemonRegister, wsID, "member", uuidToString(member.UserID), map[string]any{+ "deleted_runtime_profile_id": uuidToString(profileUUID),+ })++ w.WriteHeader(http.StatusNoContent)+}++// DaemonListRuntimeProfiles serves the enabled runtime profiles for a workspace+// to a daemon. The daemon resolves each profile's command_name on PATH and+// registers an agent_runtime instance per profile it can run. Daemon-token+// gated by the router.+func (h *Handler) DaemonListRuntimeProfiles(w http.ResponseWriter, r *http.Request) {+ workspaceID := strings.TrimSpace(chi.URLParam(r, "workspaceId"))+ if !h.requireDaemonWorkspaceAccess(w, r, workspaceID) {+ return+ }+ wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")+ if !ok {+ return+ }++ profiles, err := h.Queries.ListEnabledRuntimeProfilesForWorkspace(r.Context(), wsUUID)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list runtime profiles")+ return+ }+ resp := make([]RuntimeProfileResponse, len(profiles))+ for i, p := range profiles {+ resp[i] = runtimeProfileToResponse(p)+ }+ writeJSON(w, http.StatusOK, map[string]any{+ "workspace_id": workspaceID,+ "runtime_profiles": resp,+ })+}diff --git a/server/internal/handler/runtime_profile_handler_test.go b/server/internal/handler/runtime_profile_handler_test.gonew file mode 100644index 0000000000..2ccea819e5--- /dev/null+++ b/server/internal/handler/runtime_profile_handler_test.go@@ -0,0 +1,137 @@+package handler++import (+ "context"+ "net/http"+ "net/http/httptest"+ "testing"+)++// insertRuntimeProfileFixture creates a runtime_profile in testWorkspaceID and+// returns its id, registering cleanup.+func insertRuntimeProfileFixture(t *testing.T, ctx context.Context, displayName, protocolFamily, commandName string) string {+ t.Helper()+ var profileID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO runtime_profile (workspace_id, display_name, protocol_family, command_name, created_by)+ VALUES ($1, $2, $3, $4, $5)+ RETURNING id+ `, testWorkspaceID, displayName, protocolFamily, commandName, testUserID).Scan(&profileID); err != nil {+ t.Fatalf("insert runtime_profile fixture: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM runtime_profile WHERE id = $1`, profileID)+ })+ return profileID+}++// insertProfileRuntimeFixture creates an agent_runtime instance bound to the+// given profile (so profile_id is set), returning its id.+func insertProfileRuntimeFixture(t *testing.T, ctx context.Context, profileID, name, provider string) string {+ t.Helper()+ var runtimeID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_runtime (+ workspace_id, daemon_id, name, runtime_mode, provider, status,+ device_info, metadata, owner_id, profile_id, last_seen_at+ )+ VALUES ($1, NULL, $2, 'local', $3, 'online', $4, '{}'::jsonb, $5, $6, now())+ RETURNING id+ `, testWorkspaceID, name, provider, name+" device", testUserID, profileID).Scan(&runtimeID); err != nil {+ t.Fatalf("insert profile runtime fixture: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM agent WHERE runtime_id = $1`, runtimeID)+ testPool.Exec(context.Background(), `DELETE FROM agent_runtime WHERE id = $1`, runtimeID)+ })+ return runtimeID+}++// TestDeleteRuntimeProfile_ArchivedAgentCascade is the regression guard for the+// FK-RESTRICT 500: a profile whose only remaining agent is ARCHIVED must still+// delete cleanly. agent.runtime_id is ON DELETE RESTRICT, so without the+// per-runtime archived-agent teardown the DELETE on agent_runtime would raise a+// raw FK error and the handler would 500. The cascade must hard-delete the+// archived agent, the runtime row, and the profile.+func TestDeleteRuntimeProfile_ArchivedAgentCascade(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()++ profileID := insertRuntimeProfileFixture(t, ctx, "Cascade Profile Archived", "codex", "company-codex-arch")+ runtimeID := insertProfileRuntimeFixture(t, ctx, profileID, "Cascade Profile Runtime", "codex")+ agentID := createCascadeFixtureAgent(t, ctx, runtimeID, "Cascade Profile Archived Agent")++ // Archive the agent — the active-agent guard passes, but the FK still pins+ // the runtime row until the archived cascade clears it.+ if _, err := testPool.Exec(ctx, `UPDATE agent SET archived_at = now() WHERE id = $1`, agentID); err != nil {+ t.Fatalf("archive agent: %v", err)+ }++ w := httptest.NewRecorder()+ req := newRequest("DELETE", "/api/workspaces/"+testWorkspaceID+"/runtime-profiles/"+profileID, nil)+ req = withURLParams(req, "id", testWorkspaceID, "profileId", profileID)+ testHandler.DeleteRuntimeProfile(w, req)++ if w.Code != http.StatusNoContent {+ t.Fatalf("expected 204, got %d: %s", w.Code, w.Body.String())+ }++ var profileRows, rtRows, agentRows int+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM runtime_profile WHERE id = $1`, profileID).Scan(&profileRows); err != nil {+ t.Fatalf("count profile rows: %v", err)+ }+ if profileRows != 0 {+ t.Fatalf("expected profile deleted, found %d", profileRows)+ }+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM agent_runtime WHERE id = $1`, runtimeID).Scan(&rtRows); err != nil {+ t.Fatalf("count runtime rows: %v", err)+ }+ if rtRows != 0 {+ t.Fatalf("expected runtime row deleted by cascade, found %d", rtRows)+ }+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM agent WHERE id = $1`, agentID).Scan(&agentRows); err != nil {+ t.Fatalf("count agent rows: %v", err)+ }+ if agentRows != 0 {+ t.Fatalf("expected archived agent hard-deleted by cascade, found %d", agentRows)+ }+}++// TestDeleteRuntimeProfile_ActiveAgentBlocks confirms the guard still refuses+// (409) while an ACTIVE agent is bound to one of the profile's runtimes, and+// leaves the profile + runtime intact.+func TestDeleteRuntimeProfile_ActiveAgentBlocks(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()++ profileID := insertRuntimeProfileFixture(t, ctx, "Cascade Profile Active", "codex", "company-codex-active")+ runtimeID := insertProfileRuntimeFixture(t, ctx, profileID, "Cascade Profile Active Runtime", "codex")+ _ = createCascadeFixtureAgent(t, ctx, runtimeID, "Cascade Profile Active Agent")++ w := httptest.NewRecorder()+ req := newRequest("DELETE", "/api/workspaces/"+testWorkspaceID+"/runtime-profiles/"+profileID, nil)+ req = withURLParams(req, "id", testWorkspaceID, "profileId", profileID)+ testHandler.DeleteRuntimeProfile(w, req)++ if w.Code != http.StatusConflict {+ t.Fatalf("expected 409, got %d: %s", w.Code, w.Body.String())+ }++ var profileRows, rtRows int+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM runtime_profile WHERE id = $1`, profileID).Scan(&profileRows); err != nil {+ t.Fatalf("count profile rows: %v", err)+ }+ if profileRows != 1 {+ t.Fatalf("expected profile to survive 409, found %d", profileRows)+ }+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM agent_runtime WHERE id = $1`, runtimeID).Scan(&rtRows); err != nil {+ t.Fatalf("count runtime rows: %v", err)+ }+ if rtRows != 1 {+ t.Fatalf("expected runtime to survive 409, found %d", rtRows)+ }+}diff --git a/server/migrations/121_agent_runtime_provider_partial_unique.down.sql b/server/migrations/121_agent_runtime_provider_partial_unique.down.sqlnew file mode 100644index 0000000000..76d06a8162--- /dev/null+++ b/server/migrations/121_agent_runtime_provider_partial_unique.down.sql@@ -0,0 +1,15 @@+-- Reverse 121_agent_runtime_provider_partial_unique.up.sql.+--+-- Restoring the non-partial constraint requires that no two rows share+-- (workspace_id, daemon_id, provider). Custom-runtime rows (profile_id IS NOT+-- NULL) can violate that if a built-in and a custom runtime of the same+-- provider coexist on one daemon, so a clean downgrade assumes such rows have+-- been removed first (PR2's feature being rolled back). The DROP INDEX is+-- unconditional; the ADD CONSTRAINT will fail loudly if duplicates remain,+-- which is the correct, non-silent behavior for a rollback.++DROP INDEX IF EXISTS agent_runtime_workspace_daemon_provider_key;++ALTER TABLE agent_runtime+ ADD CONSTRAINT agent_runtime_workspace_id_daemon_id_provider_key+ UNIQUE (workspace_id, daemon_id, provider);diff --git a/server/migrations/121_agent_runtime_provider_partial_unique.up.sql b/server/migrations/121_agent_runtime_provider_partial_unique.up.sqlnew file mode 100644index 0000000000..08a10ff5b1--- /dev/null+++ b/server/migrations/121_agent_runtime_provider_partial_unique.up.sql@@ -0,0 +1,28 @@+-- Custom Runtime, PR2 (registration extension). See MUL-3284 / GitHub #3667.+--+-- PR1 (migration 120) added agent_runtime.profile_id and a partial unique index+-- for custom-runtime instances, but deliberately left the legacy+-- UNIQUE (workspace_id, daemon_id, provider) constraint intact so the existing+-- registration upsert kept working. That non-partial constraint blocks a+-- built-in runtime (profile_id IS NULL) and a custom runtime of the SAME+-- protocol family (provider) from coexisting on one daemon.+--+-- PR2 makes registration profile-aware, so we now convert that legacy key into+-- a PARTIAL unique index scoped to built-in rows only (profile_id IS NULL).+-- Combined with 120's partial index on (workspace_id, daemon_id, profile_id)+-- WHERE profile_id IS NOT NULL, this lets a single daemon host the built-in+-- codex AND any number of custom codex-based profiles without collision, while+-- still enforcing one built-in runtime per (workspace, daemon, provider).+--+-- The matching upserts now spell out the predicate in their ON CONFLICT+-- arbiter (see pkg/db/queries/runtime.sql): built-in registration targets+-- (workspace_id, daemon_id, provider) WHERE profile_id IS NULL; custom+-- registration targets (workspace_id, daemon_id, profile_id) WHERE+-- profile_id IS NOT NULL.++ALTER TABLE agent_runtime+ DROP CONSTRAINT agent_runtime_workspace_id_daemon_id_provider_key;++CREATE UNIQUE INDEX agent_runtime_workspace_daemon_provider_key+ ON agent_runtime (workspace_id, daemon_id, provider)+ WHERE profile_id IS NULL;diff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.goindex 2f94039d36..4ae44692cf 100644--- a/server/pkg/agent/agent.go+++ b/server/pkg/agent/agent.go@@ -134,6 +134,39 @@ type Config struct {// New creates a Backend for the given agent type.// Supported types: "claude", "codebuddy", "codex", "copilot", "opencode", "openclaw", "hermes", "gemini", "pi", "cursor", "kimi", "kiro", "antigravity".+//+// SupportedTypes is the canonical whitelist of agent types New can construct.+// It MUST stay in lockstep with the switch in New below and the+// runtime_profile.protocol_family CHECK constraint (migration 120): a custom+// runtime profile may only be based on a backend Multica officially supports.+var SupportedTypes = []string{+ "claude",+ "codebuddy",+ "codex",+ "copilot",+ "opencode",+ "openclaw",+ "hermes",+ "gemini",+ "pi",+ "cursor",+ "kimi",+ "kiro",+ "antigravity",+}++// IsSupportedType reports whether agentType is in the SupportedTypes whitelist.+// Used to validate a custom runtime profile's protocol_family before it is+// persisted or registered.+func IsSupportedType(agentType string) bool {+ for _, t := range SupportedTypes {+ if t == agentType {+ return true+ }+ }+ return false+}+func New(agentType string, cfg Config) (Backend, error) {if cfg.Logger == nil {cfg.Logger = slog.Default()diff --git a/server/pkg/agent/agent_supported_types_test.go b/server/pkg/agent/agent_supported_types_test.gonew file mode 100644index 0000000000..54904d59c1--- /dev/null+++ b/server/pkg/agent/agent_supported_types_test.go@@ -0,0 +1,52 @@+package agent++import (+ "log/slog"+ "testing"+)++// TestSupportedTypesLockstepWithNew guards the iron-rule whitelist: every type+// in SupportedTypes must be constructable by New, and New must reject anything+// not in SupportedTypes. This is the single source of truth the custom runtime+// profile protocol_family validation (handler) and the runtime_profile+// protocol_family CHECK (migration 120) are aligned to. If a backend is added+// to New, it must be added here too — and to the migration CHECK.+func TestSupportedTypesLockstepWithNew(t *testing.T) {+ cfg := Config{Logger: slog.Default()}++ for _, typ := range SupportedTypes {+ if !IsSupportedType(typ) {+ t.Errorf("IsSupportedType(%q) = false, but it is in SupportedTypes", typ)+ }+ if _, err := New(typ, cfg); err != nil {+ t.Errorf("New(%q) returned error for a SupportedTypes entry: %v", typ, err)+ }+ }++ // A type outside the whitelist must be rejected by both.+ const bogus = "definitely-not-a-real-backend"+ if IsSupportedType(bogus) {+ t.Errorf("IsSupportedType(%q) = true, want false", bogus)+ }+ if _, err := New(bogus, cfg); err == nil {+ t.Errorf("New(%q) succeeded, want error for an unsupported type", bogus)+ }+}++// TestSupportedTypesMatchesMigrationWhitelist pins the exact set so a drift+// from the runtime_profile.protocol_family CHECK in migration 120 fails loudly.+func TestSupportedTypesMatchesMigrationWhitelist(t *testing.T) {+ want := map[string]bool{+ "claude": true, "codebuddy": true, "codex": true, "copilot": true,+ "opencode": true, "openclaw": true, "hermes": true, "gemini": true,+ "pi": true, "cursor": true, "kimi": true, "kiro": true, "antigravity": true,+ }+ if len(SupportedTypes) != len(want) {+ t.Fatalf("SupportedTypes has %d entries, migration whitelist has %d; keep them in lockstep", len(SupportedTypes), len(want))+ }+ for _, typ := range SupportedTypes {+ if !want[typ] {+ t.Errorf("SupportedTypes contains %q which is not in the migration 120 protocol_family CHECK", typ)+ }+ }+}diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex b3f12650e9..936614426e 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -62,6 +62,7 @@ type AgentRuntime struct {OwnerID pgtype.UUID `json:"owner_id"`LegacyDaemonID pgtype.Text `json:"legacy_daemon_id"`Visibility string `json:"visibility"`+ ProfileID pgtype.UUID `json:"profile_id"`}type AgentSkill struct {@@ -550,6 +551,21 @@ type ProjectResource struct {CreatedBy pgtype.UUID `json:"created_by"`}+type RuntimeProfile struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ DisplayName string `json:"display_name"`+ ProtocolFamily string `json:"protocol_family"`+ CommandName string `json:"command_name"`+ Description pgtype.Text `json:"description"`+ FixedArgs []byte `json:"fixed_args"`+ Visibility string `json:"visibility"`+ CreatedBy pgtype.UUID `json:"created_by"`+ Enabled bool `json:"enabled"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+}+type Skill struct {ID pgtype.UUID `json:"id"`WorkspaceID pgtype.UUID `json:"workspace_id"`diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.goindex 8922ebdc43..2637169e57 100644--- a/server/pkg/db/generated/runtime.sql.go+++ b/server/pkg/db/generated/runtime.sql.go@@ -249,7 +249,7 @@ func (q *Queries) FailTasksForOfflineRuntimes(ctx context.Context) ([]AgentTaskQ}const findLegacyRuntimesByDaemonID = `-- name: FindLegacyRuntimesByDaemonID :many-SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility FROM agent_runtime+SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id FROM agent_runtimeWHERE workspace_id = $1AND provider = $2AND LOWER(daemon_id) = LOWER($3)@@ -301,6 +301,7 @@ func (q *Queries) FindLegacyRuntimesByDaemonID(ctx context.Context, arg FindLega&i.OwnerID,&i.LegacyDaemonID,&i.Visibility,+ &i.ProfileID,); err != nil {return nil, err}@@ -360,7 +361,7 @@ func (q *Queries) ForceOfflineRuntimesByIDs(ctx context.Context, runtimeIds []pg}const getAgentRuntime = `-- name: GetAgentRuntime :one-SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility FROM agent_runtime+SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id FROM agent_runtimeWHERE id = $1`@@ -383,12 +384,13 @@ func (q *Queries) GetAgentRuntime(ctx context.Context, id pgtype.UUID) (AgentRun&i.OwnerID,&i.LegacyDaemonID,&i.Visibility,+ &i.ProfileID,)return i, err}const getAgentRuntimeForWorkspace = `-- name: GetAgentRuntimeForWorkspace :one-SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility FROM agent_runtime+SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id FROM agent_runtimeWHERE id = $1 AND workspace_id = $2`@@ -416,12 +418,13 @@ func (q *Queries) GetAgentRuntimeForWorkspace(ctx context.Context, arg GetAgentR&i.OwnerID,&i.LegacyDaemonID,&i.Visibility,+ &i.ProfileID,)return i, err}const listAgentRuntimes = `-- name: ListAgentRuntimes :many-SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility FROM agent_runtime+SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id FROM agent_runtimeWHERE workspace_id = $1ORDER BY created_at ASC`@@ -451,6 +454,7 @@ func (q *Queries) ListAgentRuntimes(ctx context.Context, workspaceID pgtype.UUID&i.OwnerID,&i.LegacyDaemonID,&i.Visibility,+ &i.ProfileID,); err != nil {return nil, err}@@ -463,7 +467,7 @@ func (q *Queries) ListAgentRuntimes(ctx context.Context, workspaceID pgtype.UUID}const listAgentRuntimesByOwner = `-- name: ListAgentRuntimesByOwner :many-SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility FROM agent_runtime+SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id FROM agent_runtimeWHERE workspace_id = $1 AND owner_id = $2ORDER BY created_at ASC`@@ -498,6 +502,7 @@ func (q *Queries) ListAgentRuntimesByOwner(ctx context.Context, arg ListAgentRun&i.OwnerID,&i.LegacyDaemonID,&i.Visibility,+ &i.ProfileID,); err != nil {return nil, err}@@ -537,7 +542,7 @@ func (q *Queries) ListArchivedAgentIDsByRuntime(ctx context.Context, runtimeID p}const lockAgentRuntime = `-- name: LockAgentRuntime :one-SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility FROM agent_runtime+SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id FROM agent_runtimeWHERE id = $1FOR UPDATE`@@ -575,6 +580,7 @@ func (q *Queries) LockAgentRuntime(ctx context.Context, id pgtype.UUID) (AgentRu&i.OwnerID,&i.LegacyDaemonID,&i.Visibility,+ &i.ProfileID,)return i, err}@@ -583,7 +589,7 @@ const markAgentRuntimeOnline = `-- name: MarkAgentRuntimeOnline :oneUPDATE agent_runtimeSET status = 'online', last_seen_at = now(), updated_at = now()WHERE id = $1-RETURNING id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility+RETURNING id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id`// Used on the offline→online transition (and on first heartbeat after@@ -608,6 +614,7 @@ func (q *Queries) MarkAgentRuntimeOnline(ctx context.Context, id pgtype.UUID) (A&i.OwnerID,&i.LegacyDaemonID,&i.Visibility,+ &i.ProfileID,)return i, err}@@ -860,7 +867,7 @@ const updateAgentRuntimeVisibility = `-- name: UpdateAgentRuntimeVisibility :oneUPDATE agent_runtimeSET visibility = $1, updated_at = now()WHERE id = $2-RETURNING id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility+RETURNING id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id`type UpdateAgentRuntimeVisibilityParams struct {@@ -891,6 +898,7 @@ func (q *Queries) UpdateAgentRuntimeVisibility(ctx context.Context, arg UpdateAg&i.OwnerID,&i.LegacyDaemonID,&i.Visibility,+ &i.ProfileID,)return i, err}@@ -908,7 +916,7 @@ INSERT INTO agent_runtime (owner_id,last_seen_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, now())-ON CONFLICT (workspace_id, daemon_id, provider)+ON CONFLICT (workspace_id, daemon_id, provider) WHERE profile_id IS NULLDO UPDATE SETname = EXCLUDED.name,runtime_mode = EXCLUDED.runtime_mode,@@ -918,7 +926,7 @@ DO UPDATE SETowner_id = COALESCE(EXCLUDED.owner_id, agent_runtime.owner_id),last_seen_at = now(),updated_at = now()-RETURNING id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, (xmax = 0) AS inserted+RETURNING id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, (xmax = 0) AS inserted`type UpsertAgentRuntimeParams struct {@@ -949,12 +957,17 @@ type UpsertAgentRuntimeRow struct {OwnerID pgtype.UUID `json:"owner_id"`LegacyDaemonID pgtype.Text `json:"legacy_daemon_id"`Visibility string `json:"visibility"`+ ProfileID pgtype.UUID `json:"profile_id"`Inserted bool `json:"inserted"`}// (xmax = 0) AS inserted distinguishes a fresh insert (true) from an upsert// that updated an existing row (false). Analytics reads this to fire// runtime_registered/runtime_ready only on first-time registration.+// Built-in runtimes carry no profile_id. The arbiter is the partial unique+// index from migration 121 (WHERE profile_id IS NULL); the predicate must be+// spelled out so Postgres selects that partial index, not the custom-runtime+// one on (workspace_id, daemon_id, profile_id).func (q *Queries) UpsertAgentRuntime(ctx context.Context, arg UpsertAgentRuntimeParams) (UpsertAgentRuntimeRow, error) {row := q.db.QueryRow(ctx, upsertAgentRuntime,arg.WorkspaceID,@@ -984,6 +997,111 @@ func (q *Queries) UpsertAgentRuntime(ctx context.Context, arg UpsertAgentRuntime&i.OwnerID,&i.LegacyDaemonID,&i.Visibility,+ &i.ProfileID,+ &i.Inserted,+ )+ return i, err+}++const upsertAgentRuntimeWithProfile = `-- name: UpsertAgentRuntimeWithProfile :one+INSERT INTO agent_runtime (+ workspace_id,+ daemon_id,+ name,+ runtime_mode,+ provider,+ status,+ device_info,+ metadata,+ owner_id,+ profile_id,+ last_seen_at+) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, now())+ON CONFLICT (workspace_id, daemon_id, profile_id) WHERE profile_id IS NOT NULL+DO UPDATE SET+ name = EXCLUDED.name,+ runtime_mode = EXCLUDED.runtime_mode,+ provider = EXCLUDED.provider,+ status = EXCLUDED.status,+ device_info = EXCLUDED.device_info,+ metadata = EXCLUDED.metadata,+ owner_id = COALESCE(EXCLUDED.owner_id, agent_runtime.owner_id),+ last_seen_at = now(),+ updated_at = now()+RETURNING id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, (xmax = 0) AS inserted+`++type UpsertAgentRuntimeWithProfileParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ DaemonID pgtype.Text `json:"daemon_id"`+ Name string `json:"name"`+ RuntimeMode string `json:"runtime_mode"`+ Provider string `json:"provider"`+ Status string `json:"status"`+ DeviceInfo string `json:"device_info"`+ Metadata []byte `json:"metadata"`+ OwnerID pgtype.UUID `json:"owner_id"`+ ProfileID pgtype.UUID `json:"profile_id"`+}++type UpsertAgentRuntimeWithProfileRow struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ DaemonID pgtype.Text `json:"daemon_id"`+ Name string `json:"name"`+ RuntimeMode string `json:"runtime_mode"`+ Provider string `json:"provider"`+ Status string `json:"status"`+ DeviceInfo string `json:"device_info"`+ Metadata []byte `json:"metadata"`+ LastSeenAt pgtype.Timestamptz `json:"last_seen_at"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+ OwnerID pgtype.UUID `json:"owner_id"`+ LegacyDaemonID pgtype.Text `json:"legacy_daemon_id"`+ Visibility string `json:"visibility"`+ ProfileID pgtype.UUID `json:"profile_id"`+ Inserted bool `json:"inserted"`+}++// Custom-runtime registration: a daemon resolved a workspace runtime_profile's+// command_name on PATH and is registering an instance of it. The arbiter is the+// partial unique index from migration 120 (WHERE profile_id IS NOT NULL), so a+// single daemon can host the built-in provider AND any number of custom+// profiles of the same protocol family. provider stays the protocol family so+// task routing (agent.New(provider)) is unchanged; profile_id is the stable+// identity. (xmax = 0) AS inserted mirrors UpsertAgentRuntime.+func (q *Queries) UpsertAgentRuntimeWithProfile(ctx context.Context, arg UpsertAgentRuntimeWithProfileParams) (UpsertAgentRuntimeWithProfileRow, error) {+ row := q.db.QueryRow(ctx, upsertAgentRuntimeWithProfile,+ arg.WorkspaceID,+ arg.DaemonID,+ arg.Name,+ arg.RuntimeMode,+ arg.Provider,+ arg.Status,+ arg.DeviceInfo,+ arg.Metadata,+ arg.OwnerID,+ arg.ProfileID,+ )+ var i UpsertAgentRuntimeWithProfileRow+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.DaemonID,+ &i.Name,+ &i.RuntimeMode,+ &i.Provider,+ &i.Status,+ &i.DeviceInfo,+ &i.Metadata,+ &i.LastSeenAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.OwnerID,+ &i.LegacyDaemonID,+ &i.Visibility,+ &i.ProfileID,&i.Inserted,)return i, errdiff --git a/server/pkg/db/generated/runtime_profile.sql.go b/server/pkg/db/generated/runtime_profile.sql.gonew file mode 100644index 0000000000..2d39b9ff63--- /dev/null+++ b/server/pkg/db/generated/runtime_profile.sql.go@@ -0,0 +1,370 @@+// Code generated by sqlc. DO NOT EDIT.+// versions:+// sqlc v1.31.1+// source: runtime_profile.sql++package db++import (+ "context"++ "github.com/jackc/pgx/v5/pgtype"+)++const countAgentsByProfile = `-- name: CountAgentsByProfile :one+SELECT count(*) FROM agent a+JOIN agent_runtime ar ON ar.id = a.runtime_id+WHERE ar.profile_id = $1 AND a.archived_at IS NULL+`++// Counts active (non-archived) agents bound to any runtime instance of this+// profile. The profile-delete path uses this to refuse deletion (409) while+// agents still depend on it, mirroring the runtime-delete guard.+func (q *Queries) CountAgentsByProfile(ctx context.Context, profileID pgtype.UUID) (int64, error) {+ row := q.db.QueryRow(ctx, countAgentsByProfile, profileID)+ var count int64+ err := row.Scan(&count)+ return count, err+}++const createRuntimeProfile = `-- name: CreateRuntimeProfile :one++INSERT INTO runtime_profile (+ workspace_id,+ display_name,+ protocol_family,+ command_name,+ description,+ fixed_args,+ visibility,+ created_by,+ enabled+) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)+RETURNING id, workspace_id, display_name, protocol_family, command_name, description, fixed_args, visibility, created_by, enabled, created_at, updated_at+`++type CreateRuntimeProfileParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ DisplayName string `json:"display_name"`+ ProtocolFamily string `json:"protocol_family"`+ CommandName string `json:"command_name"`+ Description pgtype.Text `json:"description"`+ FixedArgs []byte `json:"fixed_args"`+ Visibility string `json:"visibility"`+ CreatedBy pgtype.UUID `json:"created_by"`+ Enabled bool `json:"enabled"`+}++// Custom Runtime profiles (MUL-3284). Workspace-level definitions of a custom+// runtime; see migration 120 for the table. Relational integrity (workspace,+// created_by) is enforced in the application layer — there are no DB FKs.+func (q *Queries) CreateRuntimeProfile(ctx context.Context, arg CreateRuntimeProfileParams) (RuntimeProfile, error) {+ row := q.db.QueryRow(ctx, createRuntimeProfile,+ arg.WorkspaceID,+ arg.DisplayName,+ arg.ProtocolFamily,+ arg.CommandName,+ arg.Description,+ arg.FixedArgs,+ arg.Visibility,+ arg.CreatedBy,+ arg.Enabled,+ )+ var i RuntimeProfile+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.DisplayName,+ &i.ProtocolFamily,+ &i.CommandName,+ &i.Description,+ &i.FixedArgs,+ &i.Visibility,+ &i.CreatedBy,+ &i.Enabled,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const deleteAgentRuntimesByProfile = `-- name: DeleteAgentRuntimesByProfile :many+DELETE FROM agent_runtime+WHERE profile_id = $1+RETURNING id, workspace_id, owner_id, daemon_id, provider+`++type DeleteAgentRuntimesByProfileRow struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ OwnerID pgtype.UUID `json:"owner_id"`+ DaemonID pgtype.Text `json:"daemon_id"`+ Provider string `json:"provider"`+}++// Application-layer cascade: migration 120 dropped the DB ON DELETE CASCADE, so+// the profile-delete path must remove the profile's registered runtime+// instances itself. Returns the deleted rows so the caller can broadcast /+// audit. Runs inside the same transaction as DeleteRuntimeProfile.+func (q *Queries) DeleteAgentRuntimesByProfile(ctx context.Context, profileID pgtype.UUID) ([]DeleteAgentRuntimesByProfileRow, error) {+ rows, err := q.db.Query(ctx, deleteAgentRuntimesByProfile, profileID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []DeleteAgentRuntimesByProfileRow{}+ for rows.Next() {+ var i DeleteAgentRuntimesByProfileRow+ if err := rows.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.OwnerID,+ &i.DaemonID,+ &i.Provider,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const deleteRuntimeProfile = `-- name: DeleteRuntimeProfile :exec+DELETE FROM runtime_profile+WHERE id = $1 AND workspace_id = $2+`++type DeleteRuntimeProfileParams struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++func (q *Queries) DeleteRuntimeProfile(ctx context.Context, arg DeleteRuntimeProfileParams) error {+ _, err := q.db.Exec(ctx, deleteRuntimeProfile, arg.ID, arg.WorkspaceID)+ return err+}++const getRuntimeProfile = `-- name: GetRuntimeProfile :one+SELECT id, workspace_id, display_name, protocol_family, command_name, description, fixed_args, visibility, created_by, enabled, created_at, updated_at FROM runtime_profile+WHERE id = $1+`++func (q *Queries) GetRuntimeProfile(ctx context.Context, id pgtype.UUID) (RuntimeProfile, error) {+ row := q.db.QueryRow(ctx, getRuntimeProfile, id)+ var i RuntimeProfile+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.DisplayName,+ &i.ProtocolFamily,+ &i.CommandName,+ &i.Description,+ &i.FixedArgs,+ &i.Visibility,+ &i.CreatedBy,+ &i.Enabled,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const getRuntimeProfileForWorkspace = `-- name: GetRuntimeProfileForWorkspace :one+SELECT id, workspace_id, display_name, protocol_family, command_name, description, fixed_args, visibility, created_by, enabled, created_at, updated_at FROM runtime_profile+WHERE id = $1 AND workspace_id = $2+`++type GetRuntimeProfileForWorkspaceParams struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++func (q *Queries) GetRuntimeProfileForWorkspace(ctx context.Context, arg GetRuntimeProfileForWorkspaceParams) (RuntimeProfile, error) {+ row := q.db.QueryRow(ctx, getRuntimeProfileForWorkspace, arg.ID, arg.WorkspaceID)+ var i RuntimeProfile+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.DisplayName,+ &i.ProtocolFamily,+ &i.CommandName,+ &i.Description,+ &i.FixedArgs,+ &i.Visibility,+ &i.CreatedBy,+ &i.Enabled,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const listAgentRuntimeIDsByProfile = `-- name: ListAgentRuntimeIDsByProfile :many+SELECT id FROM agent_runtime+WHERE profile_id = $1+`++// Enumerates the runtime instance rows registered against a profile. The+// profile-delete cascade walks these so it can run the same archived-agent /+// archived-squad / autopilot teardown the runtime-delete path uses before+// removing each runtime row — agent.runtime_id is ON DELETE RESTRICT, so a+// bare delete would 500 whenever an archived agent still references the row.+func (q *Queries) ListAgentRuntimeIDsByProfile(ctx context.Context, profileID pgtype.UUID) ([]pgtype.UUID, error) {+ rows, err := q.db.Query(ctx, listAgentRuntimeIDsByProfile, profileID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []pgtype.UUID{}+ for rows.Next() {+ var id pgtype.UUID+ if err := rows.Scan(&id); err != nil {+ return nil, err+ }+ items = append(items, id)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listEnabledRuntimeProfilesForWorkspace = `-- name: ListEnabledRuntimeProfilesForWorkspace :many+SELECT id, workspace_id, display_name, protocol_family, command_name, description, fixed_args, visibility, created_by, enabled, created_at, updated_at FROM runtime_profile+WHERE workspace_id = $1 AND enabled = true+ORDER BY created_at ASC+`++// Daemon-facing list: only enabled profiles are candidates for a daemon to+// resolve on PATH and register. Ordered for stable output.+func (q *Queries) ListEnabledRuntimeProfilesForWorkspace(ctx context.Context, workspaceID pgtype.UUID) ([]RuntimeProfile, error) {+ rows, err := q.db.Query(ctx, listEnabledRuntimeProfilesForWorkspace, workspaceID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []RuntimeProfile{}+ for rows.Next() {+ var i RuntimeProfile+ if err := rows.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.DisplayName,+ &i.ProtocolFamily,+ &i.CommandName,+ &i.Description,+ &i.FixedArgs,+ &i.Visibility,+ &i.CreatedBy,+ &i.Enabled,+ &i.CreatedAt,+ &i.UpdatedAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listRuntimeProfiles = `-- name: ListRuntimeProfiles :many+SELECT id, workspace_id, display_name, protocol_family, command_name, description, fixed_args, visibility, created_by, enabled, created_at, updated_at FROM runtime_profile+WHERE workspace_id = $1+ORDER BY created_at ASC+`++func (q *Queries) ListRuntimeProfiles(ctx context.Context, workspaceID pgtype.UUID) ([]RuntimeProfile, error) {+ rows, err := q.db.Query(ctx, listRuntimeProfiles, workspaceID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []RuntimeProfile{}+ for rows.Next() {+ var i RuntimeProfile+ if err := rows.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.DisplayName,+ &i.ProtocolFamily,+ &i.CommandName,+ &i.Description,+ &i.FixedArgs,+ &i.Visibility,+ &i.CreatedBy,+ &i.Enabled,+ &i.CreatedAt,+ &i.UpdatedAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const updateRuntimeProfile = `-- name: UpdateRuntimeProfile :one+UPDATE runtime_profile+SET display_name = COALESCE($1, display_name),+ command_name = COALESCE($2, command_name),+ description = COALESCE($3, description),+ fixed_args = COALESCE($4, fixed_args),+ visibility = COALESCE($5, visibility),+ enabled = COALESCE($6, enabled),+ updated_at = now()+WHERE id = $7 AND workspace_id = $8+RETURNING id, workspace_id, display_name, protocol_family, command_name, description, fixed_args, visibility, created_by, enabled, created_at, updated_at+`++type UpdateRuntimeProfileParams struct {+ DisplayName pgtype.Text `json:"display_name"`+ CommandName pgtype.Text `json:"command_name"`+ Description pgtype.Text `json:"description"`+ FixedArgs []byte `json:"fixed_args"`+ Visibility pgtype.Text `json:"visibility"`+ Enabled pgtype.Bool `json:"enabled"`+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++// Partial update via COALESCE: NULL args leave the column unchanged. The+// protocol_family is intentionally NOT updatable — changing the underlying+// backend of an existing profile would silently repoint every agent bound to+// it onto a different protocol; callers create a new profile instead.+func (q *Queries) UpdateRuntimeProfile(ctx context.Context, arg UpdateRuntimeProfileParams) (RuntimeProfile, error) {+ row := q.db.QueryRow(ctx, updateRuntimeProfile,+ arg.DisplayName,+ arg.CommandName,+ arg.Description,+ arg.FixedArgs,+ arg.Visibility,+ arg.Enabled,+ arg.ID,+ arg.WorkspaceID,+ )+ var i RuntimeProfile+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.DisplayName,+ &i.ProtocolFamily,+ &i.CommandName,+ &i.Description,+ &i.FixedArgs,+ &i.Visibility,+ &i.CreatedBy,+ &i.Enabled,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}diff --git a/server/pkg/db/queries/runtime.sql b/server/pkg/db/queries/runtime.sqlindex 337e4ff05d..efe4cc522d 100644--- a/server/pkg/db/queries/runtime.sql+++ b/server/pkg/db/queries/runtime.sql@@ -45,7 +45,11 @@ INSERT INTO agent_runtime (owner_id,last_seen_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, now())-ON CONFLICT (workspace_id, daemon_id, provider)+-- Built-in runtimes carry no profile_id. The arbiter is the partial unique+-- index from migration 121 (WHERE profile_id IS NULL); the predicate must be+-- spelled out so Postgres selects that partial index, not the custom-runtime+-- one on (workspace_id, daemon_id, profile_id).+ON CONFLICT (workspace_id, daemon_id, provider) WHERE profile_id IS NULLDO UPDATE SETname = EXCLUDED.name,runtime_mode = EXCLUDED.runtime_mode,@@ -57,6 +61,40 @@ DO UPDATE SETupdated_at = now()RETURNING *, (xmax = 0) AS inserted;+-- name: UpsertAgentRuntimeWithProfile :one+-- Custom-runtime registration: a daemon resolved a workspace runtime_profile's+-- command_name on PATH and is registering an instance of it. The arbiter is the+-- partial unique index from migration 120 (WHERE profile_id IS NOT NULL), so a+-- single daemon can host the built-in provider AND any number of custom+-- profiles of the same protocol family. provider stays the protocol family so+-- task routing (agent.New(provider)) is unchanged; profile_id is the stable+-- identity. (xmax = 0) AS inserted mirrors UpsertAgentRuntime.+INSERT INTO agent_runtime (+ workspace_id,+ daemon_id,+ name,+ runtime_mode,+ provider,+ status,+ device_info,+ metadata,+ owner_id,+ profile_id,+ last_seen_at+) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, now())+ON CONFLICT (workspace_id, daemon_id, profile_id) WHERE profile_id IS NOT NULL+DO UPDATE SET+ name = EXCLUDED.name,+ runtime_mode = EXCLUDED.runtime_mode,+ provider = EXCLUDED.provider,+ status = EXCLUDED.status,+ device_info = EXCLUDED.device_info,+ metadata = EXCLUDED.metadata,+ owner_id = COALESCE(EXCLUDED.owner_id, agent_runtime.owner_id),+ last_seen_at = now(),+ updated_at = now()+RETURNING *, (xmax = 0) AS inserted;+-- name: UpdateAgentRuntimeVisibility :one-- Toggles a runtime between 'private' (only owner can bind agents) and-- 'public' (any workspace member can). Default for new rows is 'private'diff --git a/server/pkg/db/queries/runtime_profile.sql b/server/pkg/db/queries/runtime_profile.sqlnew file mode 100644index 0000000000..65b1ddae52--- /dev/null+++ b/server/pkg/db/queries/runtime_profile.sql@@ -0,0 +1,83 @@+-- Custom Runtime profiles (MUL-3284). Workspace-level definitions of a custom+-- runtime; see migration 120 for the table. Relational integrity (workspace,+-- created_by) is enforced in the application layer — there are no DB FKs.++-- name: CreateRuntimeProfile :one+INSERT INTO runtime_profile (+ workspace_id,+ display_name,+ protocol_family,+ command_name,+ description,+ fixed_args,+ visibility,+ created_by,+ enabled+) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)+RETURNING *;++-- name: GetRuntimeProfile :one+SELECT * FROM runtime_profile+WHERE id = $1;++-- name: GetRuntimeProfileForWorkspace :one+SELECT * FROM runtime_profile+WHERE id = $1 AND workspace_id = $2;++-- name: ListRuntimeProfiles :many+SELECT * FROM runtime_profile+WHERE workspace_id = $1+ORDER BY created_at ASC;++-- name: ListEnabledRuntimeProfilesForWorkspace :many+-- Daemon-facing list: only enabled profiles are candidates for a daemon to+-- resolve on PATH and register. Ordered for stable output.+SELECT * FROM runtime_profile+WHERE workspace_id = $1 AND enabled = true+ORDER BY created_at ASC;++-- name: UpdateRuntimeProfile :one+-- Partial update via COALESCE: NULL args leave the column unchanged. The+-- protocol_family is intentionally NOT updatable — changing the underlying+-- backend of an existing profile would silently repoint every agent bound to+-- it onto a different protocol; callers create a new profile instead.+UPDATE runtime_profile+SET display_name = COALESCE(sqlc.narg('display_name'), display_name),+ command_name = COALESCE(sqlc.narg('command_name'), command_name),+ description = COALESCE(sqlc.narg('description'), description),+ fixed_args = COALESCE(sqlc.narg('fixed_args'), fixed_args),+ visibility = COALESCE(sqlc.narg('visibility'), visibility),+ enabled = COALESCE(sqlc.narg('enabled'), enabled),+ updated_at = now()+WHERE id = @id AND workspace_id = @workspace_id+RETURNING *;++-- name: DeleteRuntimeProfile :exec+DELETE FROM runtime_profile+WHERE id = $1 AND workspace_id = $2;++-- name: DeleteAgentRuntimesByProfile :many+-- Application-layer cascade: migration 120 dropped the DB ON DELETE CASCADE, so+-- the profile-delete path must remove the profile's registered runtime+-- instances itself. Returns the deleted rows so the caller can broadcast /+-- audit. Runs inside the same transaction as DeleteRuntimeProfile.+DELETE FROM agent_runtime+WHERE profile_id = $1+RETURNING id, workspace_id, owner_id, daemon_id, provider;++-- name: CountAgentsByProfile :one+-- Counts active (non-archived) agents bound to any runtime instance of this+-- profile. The profile-delete path uses this to refuse deletion (409) while+-- agents still depend on it, mirroring the runtime-delete guard.+SELECT count(*) FROM agent a+JOIN agent_runtime ar ON ar.id = a.runtime_id+WHERE ar.profile_id = $1 AND a.archived_at IS NULL;++-- name: ListAgentRuntimeIDsByProfile :many+-- Enumerates the runtime instance rows registered against a profile. The+-- profile-delete cascade walks these so it can run the same archived-agent /+-- archived-squad / autopilot teardown the runtime-delete path uses before+-- removing each runtime row — agent.runtime_id is ON DELETE RESTRICT, so a+-- bare delete would 500 whenever an archived agent still references the row.+SELECT id FROM agent_runtime+WHERE profile_id = $1;