Documentation
¶
Overview ¶
Package server implements the HTTP server layer for the TaskSmith Brain Daemon, providing pluggable modular routers, Server-Sent Events (SSE) streaming, and REST routes that serve the daemon to its clients.
Architecture ¶
The server package is the network-facing boundary of the daemon. It decouples HTTP transport and routing from the daemon's internal runtime (workspace management, session lifecycle, and gateway orchestration) via composed backend interfaces:
Backend Abstraction: Business logic access is factored into cohesive interfaces (SystemBackend, EventBackend, WorkspaceBackend, MCPBackend, SessionBackend, and MetricsBackend), composed into Backend. This allows routers to be tested independently with mock implementations.
Modular Routers: Route declarations are grouped logically into router constructors (NewSystemRouter, NewEventRouter, NewWorkspaceRouter, NewMCPRouter, NewSessionRouter, and NewMetricsRouter). Each produces a Router containing declared Route definitions.
Go 1.22+ Multiplexing: Server.CreateMux combines routers onto an http.ServeMux using Go 1.22+ method-and-path patterns (e.g. `"GET /v1/sessions/{id}"`, `"GET /v1/models/{id...}"`), supporting multiple HTTP methods on shared path patterns natively, and attaching a fallback handler returning api.ErrorResponse with code `"route_not_found"` and HTTP 404 StatusNotFound.
SSE Event Stream: The `GET /v1/events` endpoint connects subscribers to the daemon's topic-based broker. Connections emit an initial `connected` frame carrying the subscriber ID and subscribed topics, stream JSON events (api.EventEntryAdded, api.EventChunk, api.EventPermissionRequested, api.EventCompleted, api.EventError), and emit periodic `: ping\n\n` keep-alives.
REST Routes ¶
The daemon route table includes:
- `GET /v1/health` – Liveness and initialized workspace summary.
- `POST /v1/shutdown` – Graceful shutdown trigger.
- `GET /v1/events` – SSE stream of broker events.
- `POST /v1/events/subscribe` – Add topics to an active SSE stream.
- `POST /v1/events/unsubscribe` – Remove topics from an active SSE stream.
- `GET /v1/workspace` – Workspace metadata.
- `GET /v1/agents` – List configured agents.
- `GET /v1/agents/{name}` – Fetch a single agent.
- `GET /v1/models` – List available models.
- `GET /v1/models/{id...}` – Fetch a single model.
- `GET /v1/quotas` – Multi-bucket quota snapshots across all quota-capable workspace providers.
- `GET /v1/quotas?model=<id>` – Remaining quota buckets for one quota-billed model (204 when the provider reports none).
- `GET /v1/sandbox` – Sandbox scopes, effective settings, host backend availability, and resolved paths.
- `PUT /v1/sandbox` – Validate and overwrite one sandbox.json scope (global or project).
- `GET /v1/workspace/mcps` – List configured MCP servers with status and discoveries.
- `POST /v1/workspace/mcps/{name}/restart` – Reconnect an MCP server and re-discover its items.
- `POST /v1/workspace/mcps/{name}/auth` – Start or resume an MCP server's authorization flow.
- `POST /v1/workspace/mcps/{name}/prompts/{prompt}` – Render an MCP prompt.
- `POST /v1/workspace/mcps/{name}/resources` – Read an MCP resource.
- `POST /v1/workspace/mcps/{name}/policies/allow` – Permit an MCP item in the server manifest.
- `POST /v1/sessions` – Create or idempotently ensure a session.
- `POST /v1/sessions/preview` – Preview draft session model resolution and diagnostics.
- `GET /v1/sessions` – List sessions.
- `GET /v1/sessions/{id}` – Fetch a session.
- `PATCH /v1/sessions/{id}` – Update session metadata.
- `DELETE /v1/sessions/{id}` – Delete a session.
- `GET /v1/sessions/{id}/timeline` – Chronological session timeline events.
- `POST /v1/sessions/{id}/send` – Send a user message / start turn.
- `POST /v1/sessions/{id}/cancel` – Cancel an active turn.
- `GET /v1/sessions/{id}/permissions` – Pending permission requests.
- `POST /v1/sessions/{id}/permissions` – Respond to a permission request.
- `GET /v1/sessions/{id}/mode` – Current permission mode.
- `PUT /v1/sessions/{id}/mode` – Set permission mode.
- `GET /v1/sessions/{id}/changes` – File-change tracker state.
- `GET /v1/sessions/{id}/diff` – Unified diff for a change entry.
- `POST /v1/sessions/{id}/revert` – Revert file changes.
Workspace Scoping ¶
Requests identify their target workspace either via the `X-TaskSmith-CWD` header (api.HeaderCWD) or the `workspace` query parameter.
Error Handling ¶
Handlers return structured github.com/masterkeysrd/tasksmith/api.ErrorResponse JSON bodies with standardized machine-readable codes (`bad_request`, `not_found`, `conflict`, `internal_error`) and human-readable messages.
Index ¶
- func DecodeJSON[T any](r *http.Request) (T, error)
- func DecodeOptionalJSON[T any](r *http.Request) (T, error)
- func RequestWorkspace(r *http.Request) string
- func WriteBadRequest(w http.ResponseWriter, msg string)
- func WriteError(w http.ResponseWriter, err error)
- func WriteJSON(w http.ResponseWriter, status int, data any)
- type Backend
- type EventBackend
- type HandlerFunc
- type MCPBackend
- type MetricsBackend
- type Route
- func DeleteRoute(path string, handler HandlerFunc) Route
- func GetRoute(path string, handler HandlerFunc) Route
- func NewRoute(path, method string, handler HandlerFunc) Route
- func PatchRoute(path string, handler HandlerFunc) Route
- func PostRoute(path string, handler HandlerFunc) Route
- func PutRoute(path string, handler HandlerFunc) Route
- type Router
- type Server
- type SessionBackend
- type SystemBackend
- type WorkspaceBackend
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func DecodeJSON ¶
DecodeJSON reads up to 4MB from the request body and decodes it as JSON into T.
func DecodeOptionalJSON ¶
DecodeOptionalJSON reads up to 4MB from the request body and decodes it into T if present, returning the zero value and nil error if empty or EOF.
func RequestWorkspace ¶
RequestWorkspace extracts the workspace directory from either the X-TaskSmith-CWD header or the "workspace" query parameter.
func WriteBadRequest ¶
func WriteBadRequest(w http.ResponseWriter, msg string)
WriteBadRequest writes a 400 Bad Request error response with a standardized api.ErrorResponse envelope.
func WriteError ¶
func WriteError(w http.ResponseWriter, err error)
WriteError inspects err, unwraps any *api.APIError or known sentinel error, and serializes a structured api.ErrorResponse JSON body with the appropriate HTTP status code.
Types ¶
type Backend ¶
type Backend interface {
SystemBackend
EventBackend
WorkspaceBackend
MCPBackend
SessionBackend
MetricsBackend
}
type EventBackend ¶
type EventBackend interface {
AddSubscriber(ctx context.Context, subscriberID, since string, topics ...string) (*broker.Subscriber, []string, error)
RemoveSubscriber(sub *broker.Subscriber)
Subscribe(ctx context.Context, subscriberID, since string, topics ...string) ([]string, error)
Unsubscribe(ctx context.Context, subscriberID string, topics ...string) ([]string, error)
FormatEvent(msg broker.Message) (api.Event, error)
Done() <-chan struct{}
}
type HandlerFunc ¶
type HandlerFunc func(w http.ResponseWriter, r *http.Request)
HandlerFunc defines the signature of a route handler.
type MCPBackend ¶
type MCPBackend interface {
ListMCPs(ctx context.Context, workspace string) ([]api.MCPServer, error)
// SetMCPEnabled patches MCP server availability (manifest spec.enabled or
// a WORKSPACE.md MCPs policy exclusion) and reloads the workspace.
SetMCPEnabled(ctx context.Context, workspace, name string, enabled bool) ([]api.MCPServer, error)
RestartMCP(ctx context.Context, workspace, name string) (api.MCPServer, error)
AuthenticateMCP(ctx context.Context, workspace, name string) (api.MCPAuthResponse, error)
// CompleteMCPAuth feeds a redirect URL the user copied from their browser to
// the authorization flow in progress for a server.
CompleteMCPAuth(ctx context.Context, workspace, name string, req api.MCPAuthCallbackRequest) error
GetMCPPrompt(ctx context.Context, workspace, name, prompt string, req api.MCPPromptRequest) (api.MCPPromptResponse, error)
ReadMCPResource(ctx context.Context, workspace, name string, req api.MCPResourceRequest) (api.MCPResourceResponse, error)
AllowMCPPolicy(ctx context.Context, workspace, name string, req api.MCPAllowPolicyRequest) (api.MCPServer, error)
}
MCPBackend serves the workspace's configured MCP servers: their discovered tools, prompts, and resources, plus restart, interactive authorization, prompt rendering, resource reads, and manifest policy updates.
type MetricsBackend ¶
type MetricsBackend interface {
MetricsQuery(ctx context.Context, req api.MetricsQuery) (*api.MetricsResult, error)
SessionUsage(ctx context.Context, workspace, id string) (*api.SessionUsage, error)
Usage(ctx context.Context, workspace string, req api.UsageRequest) (*api.UsageSummary, error)
}
MetricsBackend serves read-only usage and metrics queries.
type Route ¶
type Route struct {
Path string
Method string
Handler HandlerFunc
}
Route maps a URL pattern and HTTP method to a HandlerFunc.
func DeleteRoute ¶
func DeleteRoute(path string, handler HandlerFunc) Route
DeleteRoute creates a DELETE route helper.
func GetRoute ¶
func GetRoute(path string, handler HandlerFunc) Route
GetRoute creates a GET route helper.
func NewRoute ¶
func NewRoute(path, method string, handler HandlerFunc) Route
NewRoute constructs a Route with the given path, method, and handler.
func PatchRoute ¶
func PatchRoute(path string, handler HandlerFunc) Route
PatchRoute creates a PATCH route helper.
func PostRoute ¶
func PostRoute(path string, handler HandlerFunc) Route
PostRoute creates a POST route helper.
func PutRoute ¶
func PutRoute(path string, handler HandlerFunc) Route
PutRoute creates a PUT route helper.
type Router ¶
type Router interface {
Routes() []Route
}
Router provides route definitions to Server.CreateMux.
func NewEventRouter ¶
func NewEventRouter(b EventBackend) Router
NewEventRouter constructs the router exposing real-time SSE event streaming and subscription management endpoints.
func NewMCPRouter ¶
func NewMCPRouter(b MCPBackend) Router
NewMCPRouter constructs the router exposing the workspace's configured MCP servers: discovery listings, restart, interactive authorization, prompt rendering, resource reads, and manifest policy updates.
func NewMetricsRouter ¶
func NewMetricsRouter(b MetricsBackend) Router
NewMetricsRouter constructs the router exposing read-only usage and metrics query endpoints.
func NewSessionRouter ¶
func NewSessionRouter(b SessionBackend) Router
NewSessionRouter constructs the router exposing session lifecycle, chronological timeline events, turn execution, permissions, and file changes.
func NewSystemRouter ¶
func NewSystemRouter(b SystemBackend) Router
NewSystemRouter constructs the router exposing system lifecycle and health endpoints.
func NewWorkspaceRouter ¶
func NewWorkspaceRouter(b WorkspaceBackend) Router
NewWorkspaceRouter constructs the router exposing workspace metadata, agent discovery, and provider model queries.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server coordinates HTTP multiplexing and route registration.
type SessionBackend ¶
type SessionBackend interface {
CreateSession(ctx context.Context, workspace string, req api.CreateSessionRequest) (*api.Session, bool, error)
PreviewSession(ctx context.Context, workspace string, req api.PreviewSessionRequest) (*api.SessionPreview, error)
ListSessions(ctx context.Context, workspace string) ([]api.Session, error)
LatestSession(ctx context.Context, workspace string) (*api.Session, error)
GetSession(ctx context.Context, workspace, id string) (*api.Session, error)
UpdateSession(ctx context.Context, workspace, id string, req api.UpdateSessionRequest) (*api.Session, error)
ForkSession(ctx context.Context, workspace, id string, req api.ForkSessionRequest) (*api.Session, error)
DeleteSession(ctx context.Context, workspace, id string) error
Timeline(ctx context.Context, workspace, id string) ([]api.TimelineEntry, error)
Send(ctx context.Context, workspace, id string, req api.SendRequest) error
UploadMedia(ctx context.Context, workspace, id, mimeType, filename string, data []byte) (*api.Media, error)
Cancel(ctx context.Context, workspace, id string) error
Changes(ctx context.Context, workspace, id string) ([]api.FileChange, error)
Diff(ctx context.Context, workspace, id, path, entryID string) (*api.DiffResponse, error)
Revert(ctx context.Context, workspace, id string, req api.RevertRequest) error
Tasks(ctx context.Context, workspace, id string) ([]api.Task, error)
KillTask(ctx context.Context, workspace, id, taskID string) error
StreamTaskOutput(ctx context.Context, workspace, id, taskID string) (<-chan string, string, func(), error)
}
type SystemBackend ¶
type WorkspaceBackend ¶
type WorkspaceBackend interface {
GetWorkspace(ctx context.Context, workspace string) (*api.Workspace, error)
ReloadWorkspace(ctx context.Context, workspace string) error
ListAgents(ctx context.Context, workspace string) ([]api.Agent, error)
GetAgent(ctx context.Context, workspace, name string) (*api.Agent, error)
ListCommands(ctx context.Context, workspace string) ([]api.Command, error)
GetCommand(ctx context.Context, workspace, name string) (*api.Command, error)
ListSkills(ctx context.Context, workspace string) ([]api.Skill, error)
GetSkill(ctx context.Context, workspace, name string) (*api.Skill, error)
ListRules(ctx context.Context, workspace string) ([]api.Rule, error)
ListTools(ctx context.Context, workspace, agent string) ([]api.Tool, error)
// SetToolEnabled patches tool availability (manifest spec.enabled or a
// WORKSPACE.md tools policy exclusion) and reloads the workspace.
SetToolEnabled(ctx context.Context, workspace, name string, enabled bool) ([]api.Tool, error)
ListModels(ctx context.Context, workspace string) ([]api.Model, error)
GetModel(ctx context.Context, workspace, id string) (*api.Model, error)
// GetModelQuota returns a nil payload when the model's provider does not
// report quotas; the router renders that as HTTP 204.
GetModelQuota(ctx context.Context, workspace, id string) (*api.ModelQuota, error)
// GetQuotaSnapshots returns the multi-bucket quota snapshots across all
// quota-capable providers in the workspace.
GetQuotaSnapshots(ctx context.Context, workspace string) (*api.QuotaSnapshotResponse, error)
GetPermissions(ctx context.Context, workspace string) (*api.PermissionsResponse, error)
AddPermissionRule(ctx context.Context, workspace string, req api.PermissionRuleRequest) (*api.PermissionsResponse, error)
RemovePermissionRule(ctx context.Context, workspace string, req api.PermissionRuleRequest) (*api.PermissionsResponse, error)
GetSandbox(ctx context.Context, workspace string) (*api.SandboxResponse, error)
UpdateSandbox(ctx context.Context, workspace string, req api.UpdateSandboxRequest) (*api.SandboxResponse, error)
GetTrustStatus(ctx context.Context, workspace string) (*api.TrustStatus, error)
TrustWorkspace(ctx context.Context, req api.TrustFolderRequest) error
RevokeTrust(ctx context.Context, workspace string) error
GetWorkspaceStatus(ctx context.Context, workspace string) (*api.WorkspaceStatus, error)
InitWorkspace(ctx context.Context, req api.InitWorkspaceRequest) (*api.InitWorkspaceResponse, error)
VerifyProvider(ctx context.Context, req api.VerifyProviderRequest) (*api.VerifyProviderResponse, error)
StartProviderAuth(ctx context.Context, provider string) (*api.ProviderAuthResponse, error)
GetProviderAuthStatus(ctx context.Context, provider string) (*api.ProviderAuthResponse, error)
// CompleteProviderAuth feeds a redirect URL the user copied from their
// browser to the provider OAuth flow in progress.
CompleteProviderAuth(ctx context.Context, provider string, req api.ProviderAuthCallbackRequest) (*api.ProviderAuthResponse, error)
LogoutProviderAuth(ctx context.Context, provider string) (*api.ProviderAuthResponse, error)
ListProviders(ctx context.Context) ([]api.ProviderSummary, error)
// ListWorkspaceProviders returns the ModelProviders this workspace resolved
// across tiers, including disabled and shadowed manifests.
ListWorkspaceProviders(ctx context.Context, workspace string) ([]api.WorkspaceProvider, error)
// SetProviderEnabled patches spec.enabled on the owning manifest (or writes
// a workspace shadow for an inherited provider) and reloads the workspace.
SetProviderEnabled(ctx context.Context, workspace, name string, enabled bool) ([]api.WorkspaceProvider, error)
UpdateProviderModels(ctx context.Context, workspace, name string, req api.UpdateProviderModelsRequest) ([]api.WorkspaceProvider, error)
CreateProvider(ctx context.Context, workspace string, req api.CreateProviderRequest) (*api.WorkspaceProvider, error)
AssignModelAliases(ctx context.Context, workspace string, req api.AssignModelAliasesRequest) (*api.AssignModelAliasesResponse, error)
ListAliasAssignments(ctx context.Context, workspace string) ([]api.AliasAssignment, error)
// ListProviderCatalog lists the models a configured provider's type offers.
// A provider whose type has no catalog answers with an empty listing.
ListProviderCatalog(ctx context.Context, workspace, name string) ([]api.ProviderCatalogEntry, error)
ListWorkspaceFiles(ctx context.Context, workspace string, req api.ListFilesRequest) ([]api.WorkspaceFile, error)
}