handlers

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 17, 2026 License: MIT Imports: 47 Imported by: 0

Documentation

Overview

code.go implements the read-only Code tab backend:

GET /api/code/tree?path=&worktree=[&show_hidden=1]
GET /api/code/file?path=&worktree=
GET /api/code/diff?worktree=[&path=]

The routes are registered at /api/code/ and dispatched by ServeHTTP based on the first path segment. They work under the WorkspaceScope middleware (/api/workspaces/{id}/code/*) which rewrites the URL and stashes the resolved workspace in the request context, and also transparently for the legacy /api/code/* form using the active workspace.

Every filesystem read is sandboxed via pkg/files.SafeJoin; .git/ and .bc/ subdirs are hidden by default; file reads cap at 2 MiB.

code_search.go — ripgrep-backed `/api/code/search` endpoint.

Emits a compact JSON envelope the Code tab's search panel can render directly:

{
  "matches":    [{path, line, col, text, before:[...], after:[...]}],
  "truncated":  bool,
  "elapsed_ms": int
}

The handler is read-only and sandboxed to the resolved worktree root. Case sensitivity, regex vs literal, and a single optional subdir are passed through; everything else (globs, context tuning, type filters) can be layered on later without changing the response shape.

Package handlers implements HTTP handlers for the bcd REST API. Each handler file covers one resource (agents, channels, workspace, etc.).

workspace_ctx.go — handler-side shim for per-request workspace resolution.

Phase M3 wires the server's WorkspaceServicesFromContext lookup into the handlers package without creating an import cycle. Handlers read their per-workspace dependencies via WorkspaceFromContext(r.Context()) at the top of each method; if the lookup returns nil they fall back to the closure fields captured at construction time (legacy single-workspace code path).

Phase M4 will delete the closure fields; every handler will then rely solely on context.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func APIKeyAuth

func APIKeyAuth(apiKey string) func(http.Handler) http.Handler

APIKeyAuth returns middleware that validates Bearer token authentication. If apiKey is empty, the middleware is a no-op (auth disabled). Exempt paths (health, SSE) skip authentication.

func CORS

func CORS(next http.Handler) http.Handler

CORS returns a middleware with permissive CORS headers (Allow-Origin: *). Safe because bcd only binds to loopback by default.

func CORSWithOrigin

func CORSWithOrigin(allowedOrigin string, next http.Handler) http.Handler

CORSWithOrigin returns a middleware that adds CORS headers with the specified allowed origin. Use "*" for permissive (safe on loopback) or a specific origin like "http://localhost:9374" when exposed beyond loopback.

func Gzip

func Gzip(next http.Handler) http.Handler

Gzip returns a middleware that compresses responses with gzip when the client sends Accept-Encoding: gzip. Skips SSE and MCP streaming endpoints because gzip buffering breaks chunked encoding required by EventSource.

func MaxBodySize

func MaxBodySize(maxBytes int64) func(http.Handler) http.Handler

MaxBodySize returns a middleware that limits request body size. Returns 413 Payload Too Large if the body exceeds maxBytes.

MCP endpoints (/_mcp/*) are excluded because MCP tools like send_file legitimately handle large payloads (up to 50MB) and enforce their own per-tool size limits in server/mcp/tools.go.

func RateLimit

func RateLimit(limiter *RateLimiter) func(http.Handler) http.Handler

RateLimit returns middleware that enforces a global request rate limit. Returns 429 Too Many Requests when the limit is exceeded.

func Recovery

func Recovery(next http.Handler) http.Handler

Recovery returns a middleware that recovers from panics, logs the error, and returns a 500 JSON response instead of crashing the server.

func RequestID

func RequestID(next http.Handler) http.Handler

RequestID returns a middleware that generates a unique request ID for each request. If the incoming request has an X-Request-ID header, it is reused. The ID is set on the response header and available via the request context.

func RequestLogger

func RequestLogger(next http.Handler) http.Handler

RequestLogger returns middleware that logs every HTTP request. SSE and MCP long-lived connections are excluded to avoid log spam.

func SetWorkspaceFromContext added in v0.2.0

func SetWorkspaceFromContext(fn func(context.Context) *WorkspaceView)

SetWorkspaceFromContext installs the server's resolver. Passing nil clears it (useful for tests).

func SetWorkspaceIDFromContext added in v0.2.0

func SetWorkspaceIDFromContext(fn func(context.Context) string)

SetWorkspaceIDFromContext lets the server plug the real WorkspaceIDFromContext lookup in without introducing an import cycle. Must be called once during server startup.

Types

type AgentHandler

type AgentHandler struct {
	// contains filtered or unexported fields
}

AgentHandler handles /api/agents routes.

func NewAgentHandler

func NewAgentHandler(svc *agent.AgentService, costs *cost.Store, ws *workspace.Workspace, hub *ws.Hub) *AgentHandler

NewAgentHandler creates an AgentHandler. costs, ws, hub, and eventStore may be nil; enrichment fields will be omitted when unavailable.

func (*AgentHandler) Register

func (h *AgentHandler) Register(mux *http.ServeMux)

Register mounts agent routes on mux. Exact-path routes must be registered before the prefix route "/api/agents/".

func (*AgentHandler) SetEventStore

func (h *AgentHandler) SetEventStore(es events.EventStore)

SetEventStore sets the event store for persisting hook events.

func (*AgentHandler) SetStatsStore

func (h *AgentHandler) SetStatsStore(s *stats.Store)

SetStatsStore sets the stats store for resource metrics enrichment.

func (*AgentHandler) SetTemplateStore added in v0.2.0

func (h *AgentHandler) SetTemplateStore(store *template.Store)

SetTemplateStore sets the template store used during agent creation.

func (*AgentHandler) SetTerminalHandler

func (h *AgentHandler) SetTerminalHandler(th *TerminalHandler)

SetTerminalHandler sets the terminal handler for WebSocket terminal access.

type AgentHealthInfo

type AgentHealthInfo struct {
	Name          string `json:"name"`
	Role          string `json:"role"`
	Status        string `json:"status"`
	LastUpdated   string `json:"last_updated"`
	StaleDuration string `json:"stale_duration,omitempty"`
	ErrorMessage  string `json:"error_message,omitempty"`
	TmuxAlive     bool   `json:"tmux_alive"`
	StateFresh    bool   `json:"state_fresh"`
}

AgentHealthInfo represents health status of an agent.

type AgentSummary

type AgentSummary struct {
	Name  string `json:"name"`
	Role  string `json:"role"`
	State string `json:"state"`
}

AgentSummary is a lightweight agent reference.

type CodeHandler added in v0.2.0

type CodeHandler struct {
	// contains filtered or unexported fields
}

CodeHandler serves the read-only Code tab endpoints.

func NewCodeHandler added in v0.2.0

func NewCodeHandler(resolver WorkspaceResolver) *CodeHandler

NewCodeHandler constructs a CodeHandler bound to a workspace resolver.

func (*CodeHandler) Register added in v0.2.0

func (h *CodeHandler) Register(mux *http.ServeMux)

Register mounts the handler on mux at /api/code/.

func (*CodeHandler) ServeHTTP added in v0.2.0

func (h *CodeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP dispatches on the first path segment after /api/code/.

type CostHandler

type CostHandler struct {
	// contains filtered or unexported fields
}

CostHandler handles /api/costs routes.

func NewCostHandler

func NewCostHandler(store *cost.Store, importer *cost.Importer) *CostHandler

NewCostHandler creates a CostHandler.

func (*CostHandler) Register

func (h *CostHandler) Register(mux *http.ServeMux)

Register mounts cost routes on mux.

type CostReport added in v0.2.0

type CostReport struct {
	Range struct {
		Start string `json:"start"`
	} `json:"range"`
	GroupBy string    `json:"groupBy"`
	Rows    []CostRow `json:"rows"`
}

CostReport is the envelope returned by /api/global/costs.

type CostRow added in v0.2.0

type CostRow struct {
	Key   string  `json:"key"`   // workspace id or project label
	Label string  `json:"label"` // human-readable name
	Total float64 `json:"total"` // USD
}

CostRow is one row of the /api/global/costs response.

type CronHandler

type CronHandler struct {
	// contains filtered or unexported fields
}

CronHandler handles /api/cron routes.

func NewCronHandler

func NewCronHandler(store *cron.Store, scheduler *cron.Scheduler) *CronHandler

NewCronHandler creates a CronHandler.

func (*CronHandler) Register

func (h *CronHandler) Register(mux *http.ServeMux)

Register mounts cron routes on mux.

type DepsHandler added in v0.2.0

type DepsHandler struct {
	// contains filtered or unexported fields
}

DepsHandler exposes the optional dependencies manager (see pkg/deps).

Security: Start/Stop can spawn arbitrary docker commands, so we require the request to originate from loopback unless BC_REMOTE=1 is explicitly set by the operator.

func NewDepsHandler added in v0.2.0

func NewDepsHandler(registry *deps.Registry) *DepsHandler

NewDepsHandler constructs a DepsHandler around an existing registry.

func (*DepsHandler) Register added in v0.2.0

func (h *DepsHandler) Register(mux *http.ServeMux)

Register mounts the deps routes on mux.

Routes:

GET  /api/deps                 -> list deps + status
GET  /api/deps/{id}            -> one dep detail
GET  /api/deps/{id}/status     -> same as detail (compat)
POST /api/deps/{id}/start      -> start (loopback-only)
POST /api/deps/{id}/stop       -> stop  (loopback-only)
GET  /api/deps/{id}/logs       -> SSE stream of log tails

type DiscoveryHandler added in v0.2.0

type DiscoveryHandler struct {
	// contains filtered or unexported fields
}

DiscoveryHandler exposes the workspace-discovery endpoints proposed in §4.4: local filesystem scan, GitHub repo list, clone + register, plus the small GitHub auth surface (/api/auth/github) used to authorize the repo-list call.

func NewDiscoveryHandler added in v0.2.0

func NewDiscoveryHandler(registry *workspace.Registry) *DiscoveryHandler

NewDiscoveryHandler constructs the handler bound to a registry.

func (*DiscoveryHandler) Register added in v0.2.0

func (h *DiscoveryHandler) Register(mux *http.ServeMux)

Register mounts all /api/workspaces/discover/* and /api/auth/github routes on mux.

type DoctorHandler

type DoctorHandler struct {
	// contains filtered or unexported fields
}

DoctorHandler handles /api/doctor routes.

func NewDoctorHandler

func NewDoctorHandler(ws *workspace.Workspace) *DoctorHandler

NewDoctorHandler creates a DoctorHandler.

func (*DoctorHandler) Register

func (h *DoctorHandler) Register(mux *http.ServeMux)

Register mounts doctor routes on mux.

type EventHandler

type EventHandler struct {
	// contains filtered or unexported fields
}

EventHandler handles /api/logs (historical event log).

func NewEventHandler

func NewEventHandler(store events.EventStore) *EventHandler

NewEventHandler creates an EventHandler.

func (*EventHandler) Register

func (h *EventHandler) Register(mux *http.ServeMux)

Register mounts event log routes on mux.

func (*EventHandler) SetWriter

func (h *EventHandler) SetWriter(w *events.JSONLWriter)

SetWriter attaches a JSONLWriter for the /api/events/history endpoint.

type FileHandler

type FileHandler struct {
	// contains filtered or unexported fields
}

FileHandler handles file upload and download routes.

func NewFileHandler

func NewFileHandler(store *attachment.Store) *FileHandler

NewFileHandler creates a FileHandler.

func (*FileHandler) Register

func (h *FileHandler) Register(mux *http.ServeMux)

Register mounts file routes on mux.

type GatewayHandler

type GatewayHandler struct {
	// contains filtered or unexported fields
}

GatewayHandler handles /api/gateways routes.

func NewGatewayHandler

func NewGatewayHandler(gw *gateway.Manager, ws *workspace.Workspace) *GatewayHandler

NewGatewayHandler creates a GatewayHandler.

func (*GatewayHandler) Register

func (h *GatewayHandler) Register(mux *http.ServeMux)

Register mounts gateway routes.

func (*GatewayHandler) SetNotifyService

func (h *GatewayHandler) SetNotifyService(svc *notify.Service)

SetNotifyService sets the notification service for subscription management.

type GlobalCostsHandler added in v0.2.0

type GlobalCostsHandler struct {
	// contains filtered or unexported fields
}

GlobalCostsHandler serves cross-workspace cost rollups from the user-global ledger at ~/.bc/costs.db.

GET /api/global/costs?start=<RFC3339|YYYY-MM-DD>&groupBy=workspace|project

  • Mount OUTSIDE WorkspaceScope so the response spans every workspace.
  • `start` defaults to 30 days ago when omitted.
  • `end` is not honored because the underlying store only accepts a lower bound (`since`); callers that need a window should narrow on the client. TODO(#250): widen pkg/cost to accept a full range.

func NewGlobalCostsHandler added in v0.2.0

func NewGlobalCostsHandler(store *cost.Store, reg *workspace.Registry) *GlobalCostsHandler

NewGlobalCostsHandler builds a handler. If store is nil the endpoint returns 503, keeping production test harnesses that don't wire a global ledger from panicking.

func (*GlobalCostsHandler) ServeHTTP added in v0.2.0

func (h *GlobalCostsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler.

type HookEventRequest added in v0.2.0

type HookEventRequest struct {
	ToolInput any            `json:"tool_input,omitempty"`
	Metadata  map[string]any `json:"metadata,omitempty"`
	TaskTitle string         `json:"task_title,omitempty"`
	TaskID    string         `json:"task_id,omitempty"`
	ToolName  string         `json:"tool_name,omitempty"`
	Error     string         `json:"error,omitempty"`
	Event     string         `json:"event"`
}

HookEventRequest is the rich payload accepted by POST /api/agents/{name}/hook. All fields except Event are optional; callers may send any subset. The handler accepts the full agent.HookPayload; this struct documents the additional fields introduced in Phase 1c (TaskID, TaskTitle, Metadata).

type MCPHandler

type MCPHandler struct {
	// contains filtered or unexported fields
}

MCPHandler handles /api/mcp routes.

TODO(m8d-followup): the HTTP surface currently reads from the workspace-scoped *mcp.Store. pkg/mcp now provides a GlobalStore (~/.bc/mcps.json) + LayeredView for workspace-over-global merging; a follow-up will teach this handler to return the merged view and accept a scope query parameter for Add/Remove.

func NewMCPHandler

func NewMCPHandler(store *mcp.Store) *MCPHandler

NewMCPHandler creates an MCPHandler.

func (*MCPHandler) Register

func (h *MCPHandler) Register(mux *http.ServeMux)

Register mounts MCP server routes on mux.

type MCPServer

type MCPServer struct {
	Name      string `json:"name"`
	Transport string `json:"transport"`
	URL       string `json:"url,omitempty"`
	Command   string `json:"command,omitempty"`
	Enabled   bool   `json:"enabled"`
}

MCPServer describes an MCP server configured for a provider.

type ModelCost

type ModelCost struct {
	Model        string  `json:"model"`
	TotalTokens  int64   `json:"total_tokens"`
	TotalCostUSD float64 `json:"total_cost_usd"`
}

ModelCost holds per-model cost data.

type ProviderCommand

type ProviderCommand struct {
	Name        string `json:"name"`
	Command     string `json:"command"`
	Description string `json:"description"`
	Args        string `json:"args,omitempty"`
}

ProviderCommand describes a CLI command available for a provider.

type ProviderDetail

type ProviderDetail struct {
	ProviderInfo
	Config      map[string]string `json:"config"`
	Agents      []AgentSummary    `json:"agents"`
	CostByModel []ModelCost       `json:"cost_by_model"`
}

ProviderDetail extends ProviderInfo with per-model cost breakdown and agent list.

type ProviderHandler

type ProviderHandler struct {
	// contains filtered or unexported fields
}

ProviderHandler handles /api/providers routes.

func NewProviderHandler

func NewProviderHandler(registry *provider.Registry, agents *agent.AgentService, costs *cost.Store, ws *workspace.Workspace) *ProviderHandler

NewProviderHandler creates a ProviderHandler.

func (*ProviderHandler) Register

func (h *ProviderHandler) Register(mux *http.ServeMux)

Register mounts provider routes on mux.

type ProviderInfo

type ProviderInfo struct {
	Name         string  `json:"name"`
	Description  string  `json:"description"`
	Binary       string  `json:"binary"`
	Command      string  `json:"command"`
	InstallHint  string  `json:"install_hint"`
	Version      string  `json:"version"`
	Status       string  `json:"status"`
	TotalCostUSD float64 `json:"total_cost_usd"`
	TotalTokens  int64   `json:"total_tokens"`
	AgentCount   int     `json:"agent_count"`
	Installed    bool    `json:"installed"`
	Enabled      bool    `json:"enabled"`
}

ProviderInfo represents a provider with usage stats.

type RateLimiter

type RateLimiter struct {
	// contains filtered or unexported fields
}

RateLimiter implements a simple token bucket rate limiter.

func NewRateLimiter

func NewRateLimiter(rps float64, burst int) *RateLimiter

NewRateLimiter creates a rate limiter with the given requests-per-second rate and burst size.

func (*RateLimiter) Allow

func (rl *RateLimiter) Allow() bool

Allow returns true if the request is allowed under the rate limit.

type RolesHandler

type RolesHandler struct {
	// contains filtered or unexported fields
}

RolesHandler handles /api/roles routes.

func NewRolesHandler

func NewRolesHandler(ws *workspace.Workspace) *RolesHandler

NewRolesHandler creates a RolesHandler.

func (*RolesHandler) Register

func (h *RolesHandler) Register(mux *http.ServeMux)

Register mounts roles routes on mux.

type SecretHandler

type SecretHandler struct {
	// contains filtered or unexported fields
}

SecretHandler handles /api/secrets routes. Values are never returned — only metadata.

func NewSecretHandler

func NewSecretHandler(store *secret.Store) *SecretHandler

NewSecretHandler creates a SecretHandler.

func (*SecretHandler) Register

func (h *SecretHandler) Register(mux *http.ServeMux)

Register mounts secret routes on mux.

type SettingsHandler

type SettingsHandler struct {
	// contains filtered or unexported fields
}

SettingsHandler handles /api/settings routes.

func NewSettingsHandler

func NewSettingsHandler(ws *workspace.Workspace) *SettingsHandler

NewSettingsHandler creates a SettingsHandler.

func (*SettingsHandler) Register

func (h *SettingsHandler) Register(mux *http.ServeMux)

Register mounts settings routes on mux.

type StatsHandler

type StatsHandler struct {
	// contains filtered or unexported fields
}

StatsHandler handles /api/stats routes.

func NewStatsHandler

func NewStatsHandler(
	agents *agent.AgentService,
	costs *cost.Store,
	tools *tool.Store,
	ws *workspace.Workspace,
	statsStore *stats.Store,
) *StatsHandler

NewStatsHandler creates a StatsHandler.

func (*StatsHandler) Register

func (h *StatsHandler) Register(mux *http.ServeMux)

func (*StatsHandler) RegisterAgentStats

func (h *StatsHandler) RegisterAgentStats(mux *http.ServeMux)

RegisterAgentStats mounts agent stats routes on the mux.

func (*StatsHandler) RegisterChannelStats

func (h *StatsHandler) RegisterChannelStats(mux *http.ServeMux)

RegisterChannelStats mounts channel stats routes on the mux.

func (*StatsHandler) RegisterSystemStats

func (h *StatsHandler) RegisterSystemStats(mux *http.ServeMux)

RegisterSystemStats mounts system stats routes on the mux.

func (*StatsHandler) SetGateway

func (h *StatsHandler) SetGateway(gw *gateway.Manager)

Register mounts stats routes on mux. SetGateway sets the gateway manager for channel count.

func (*StatsHandler) SetNotify

func (h *StatsHandler) SetNotify(svc *notify.Service)

SetNotify sets the notify service for subscription count.

type TemplateHandler added in v0.2.0

type TemplateHandler struct {
	// contains filtered or unexported fields
}

TemplateHandler handles /api/templates routes.

func NewTemplateHandler added in v0.2.0

func NewTemplateHandler(store *template.Store) *TemplateHandler

NewTemplateHandler creates a TemplateHandler backed by the given store.

func (*TemplateHandler) Register added in v0.2.0

func (h *TemplateHandler) Register(mux *http.ServeMux)

Register mounts template routes on mux.

type TerminalHandler

type TerminalHandler struct {
	// contains filtered or unexported fields
}

TerminalHandler handles /api/agents/:name/terminal WebSocket connections. It bridges the browser to a tmux session via a PTY.

func NewTerminalHandler

func NewTerminalHandler(svc *agent.AgentService, corsOrigin string) *TerminalHandler

NewTerminalHandler creates a TerminalHandler. corsOrigin is the allowed origin for WebSocket connections (empty or "*" allows all).

func (*TerminalHandler) HandleTerminal

func (h *TerminalHandler) HandleTerminal(w http.ResponseWriter, r *http.Request, agentName string)

HandleTerminal upgrades an HTTP request to a WebSocket and bridges it to a tmux session.

type ToolHandler

type ToolHandler struct {
	// contains filtered or unexported fields
}

ToolHandler handles /api/tools routes.

func NewToolHandler

func NewToolHandler(store *tool.Store) *ToolHandler

NewToolHandler creates a ToolHandler.

func (*ToolHandler) Register

func (h *ToolHandler) Register(mux *http.ServeMux)

Register mounts tool routes on mux.

type UnifiedTool

type UnifiedTool struct {
	Name       string `json:"name"`
	Type       string `json:"type"`
	Status     string `json:"status"`
	Transport  string `json:"transport,omitempty"`
	Command    string `json:"command,omitempty"`
	URL        string `json:"url,omitempty"`
	Version    string `json:"version,omitempty"`
	Error      string `json:"error,omitempty"`
	InstallCmd string `json:"install_cmd,omitempty"`
	UpgradeCmd string `json:"upgrade_cmd,omitempty"`
	Required   bool   `json:"required"`
}

UnifiedTool represents a tool (MCP or CLI) with its status.

type UnifiedToolsHandler

type UnifiedToolsHandler struct {
	// contains filtered or unexported fields
}

UnifiedToolsHandler handles the merged /api/tools endpoint.

func NewUnifiedToolsHandler

func NewUnifiedToolsHandler(mcpStore *mcp.Store, toolStore *tool.Store, agents *agent.AgentService, ws *workspace.Workspace) *UnifiedToolsHandler

NewUnifiedToolsHandler creates a UnifiedToolsHandler.

func (*UnifiedToolsHandler) Register

func (h *UnifiedToolsHandler) Register(mux *http.ServeMux)

Register mounts unified tools routes.

type UpdateCheck

type UpdateCheck struct {
	CurrentVersion  string `json:"current_version"`
	LatestVersion   string `json:"latest_version"`
	UpdateCommand   string `json:"update_command"`
	UpdateAvailable bool   `json:"update_available"`
}

UpdateCheck holds the result of a provider version check.

type WorkspaceHandler

type WorkspaceHandler struct {
	// contains filtered or unexported fields
}

WorkspaceHandler handles /api/workspace routes.

func NewWorkspaceHandler

func NewWorkspaceHandler(svc *agent.AgentService, ws *workspace.Workspace) *WorkspaceHandler

NewWorkspaceHandler creates a WorkspaceHandler.

func (*WorkspaceHandler) Register

func (h *WorkspaceHandler) Register(mux *http.ServeMux)

Register mounts workspace routes on mux.

type WorkspaceResolver added in v0.2.0

type WorkspaceResolver interface {
	// ActiveRoot returns the filesystem root of the currently-active
	// workspace (used for legacy /api/code/* requests), or "" if none.
	ActiveRoot() string
	// RootByID returns the filesystem root for the workspace with the
	// given registry ID, or "" if the ID is unknown.
	RootByID(id string) string
}

WorkspaceResolver is the minimal slice of the server's workspace manager that the Code handler needs. It is defined as an interface so tests and server.go can supply lightweight implementations without importing the full WorkspaceManager type.

func NewRegistryWorkspaceResolver added in v0.2.0

func NewRegistryWorkspaceResolver(registry *workspace.Registry, active *workspace.Workspace) WorkspaceResolver

NewRegistryWorkspaceResolver builds a resolver out of the registry and the active workspace; either may be nil.

type WorkspaceView added in v0.2.0

type WorkspaceView struct {
	Workspace    *workspace.Workspace
	Agents       *agent.AgentService
	Events       events.EventStore
	EventWriter  *events.JSONLWriter
	Costs        *cost.Store
	CostImporter *cost.Importer
	Cron         *cron.Store
	CronSched    *cron.Scheduler
	Templates    *template.Store
	Secrets      *secret.Store
	MCP          *mcp.Store
	Tools        *tool.Store
	Gateway      *gateway.Manager
	Notify       *notify.Service
	Stats        *stats.Store
	Hub          *ws.Hub
}

WorkspaceView is the subset of per-workspace dependencies handlers need. The server populates this in-process and exposes a lookup via SetWorkspaceFromContext.

func WorkspaceFromContext added in v0.2.0

func WorkspaceFromContext(ctx context.Context) *WorkspaceView

WorkspaceFromContext returns the per-request workspace view installed by the scoping middleware, or nil if no resolver is wired or the request was not scoped.

type WorkspacesHandler added in v0.2.0

type WorkspacesHandler struct {
	// contains filtered or unexported fields
}

WorkspacesHandler exposes the global multi-workspace registry API. Unlike WorkspaceHandler (singular, /api/workspace/*) which reports on the currently-active workspace, this handler manages the registry itself: list / add / remove / activate entries so bcd can hold several workspaces open at once.

func NewWorkspacesHandler added in v0.2.0

func NewWorkspacesHandler(registry *workspace.Registry, agentSvc *agent.AgentService) *WorkspacesHandler

NewWorkspacesHandler constructs a registry handler.

func (*WorkspacesHandler) Register added in v0.2.0

func (h *WorkspacesHandler) Register(mux *http.ServeMux)

Register mounts all /api/workspaces routes on mux.

REST surface:

GET    /api/workspaces              -> list
POST   /api/workspaces              -> add (body: {path, name?, alias?})
GET    /api/workspaces/{id}         -> detail
PATCH  /api/workspaces/{id}         -> update name/alias/github
DELETE /api/workspaces/{id}         -> unregister
POST   /api/workspaces/{id}/activate -> set active

func (*WorkspacesHandler) SetActiveRefreshHook added in v0.2.0

func (h *WorkspacesHandler) SetActiveRefreshHook(fn func())

SetActiveRefreshHook installs a callback that fires after a successful POST /api/workspaces/{id}/activate. Useful for reloading server state.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL