gateway

package
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Jun 8, 2026 License: MIT Imports: 36 Imported by: 0

Documentation

Overview

Package gateway: Wave-5 add-to-chat endpoint. It formats a uniform context pill the SPA composer can append as an @-reference. The contents path is root-confined via resolveInRoot (introduced by Wave 1's workspace.go) so a malicious payload cannot read outside the workspace root.

Package gateway: Wave-5 checkpoint/rewind/branch endpoints. They operate directly on the injected *session.Store and *snapshots.Manager (see options.go). When a Handler was built without those, the endpoints return 501 so a misconfigured server fails loudly rather than silently no-op'ing.

CHECKPOINT DISCLAIMER (surfaced in the SPA RewindMenu): rewind restores only (a) the persisted conversation history and (b) files captured by the agent's pre-edit snapshots. Edits made by bash commands or by tools/processes outside the agent are NOT tracked here — git is the source of truth for the working tree. A "code" rewind is best-effort over snapshots; verify with `git diff`.

Package gateway exposes the web SPA's /v1 HTTP+SSE API and serves the embedded SPA itself. It is the single handler that makes the Svelte web app (web/) and the Wails desktop wrapper (desktop/) function end-to-end against the agent.

Routes (the contract is defined by web/src/lib/api.ts; the server matches the SPA, not the other way around):

POST /v1/prompt   {"prompt", "session_id"?} -> {"request_id","session_id"}
GET  /v1/cache                              -> CacheReport JSON
GET  /v1/events?session_id=X                -> text/event-stream SSE
GET  /*                                     -> embedded SPA (webapp.Handler)

The /v1 routes reuse the acp SessionManager + AgentFactory machinery; this package does not reimplement agent streaming. It maps acp.AgentEvent values onto the SPA's named SSE events (delta/tool/step/done).

Package gateway: git branch introspection and checkout endpoints. These shell out to `git` in the workspace root (h.root), following the same pattern as workspace.go's handleDiff/handleChanged. A non-git root or git error yields a graceful empty/default response rather than a 500.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultHandler

func DefaultHandler() (http.Handler, error)

DefaultHandler builds the production gateway handler: a real-agent SessionManager plus a session.Store (~/.deepseek/sessions.db), a snapshots.Manager (./.deepseek/snapshots), and the process working dir as the workspace root. It is what Start serves and what desktop/ drives in-process.

func NewHandler

func NewHandler(sm *acp.SessionManager, tracePath string, opts ...Option) http.Handler

NewHandler builds the gateway handler over an existing SessionManager. The SessionManager supplies the AgentFactory (real in production, a stub in tests). tracePath is read on demand by /v1/cache; an absent file yields a zero-valued report rather than an error.

Optional functional options (WithStore, WithSnapshots, WithWorkspaceRoot) may be passed to wire Wave-5 checkpoint/workspace behaviour; callers that pass no options retain the pre-Wave-5 behaviour unchanged.

func NewHandlerWithRoot deprecated

func NewHandlerWithRoot(sm *acp.SessionManager, tracePath, root string) http.Handler

NewHandlerWithRoot is like NewHandler but also sets the workspace root used by the /v1/files, /v1/file and /v1/changed endpoints. When root is empty those endpoints return "no workspace root" (400). In production, Start passes the process working directory; tests pass a hermetic temp dir.

Deprecated: pass WithWorkspaceRoot as an Option to NewHandler instead.

func ResetConfigSeam

func ResetConfigSeam()

ResetConfigSeam restores production load/save.

func ResetPersistSeam

func ResetPersistSeam()

ResetPersistSeam restores production persistence.

func ResetUpdateSeam

func ResetUpdateSeam()

ResetUpdateSeam restores production funcs.

func ResetValidateKeySeam

func ResetValidateKeySeam()

ResetValidateKeySeam restores the production validator.

func ServeHandler

func ServeHandler(ctx context.Context, port int, handler http.Handler) error

ServeHandler runs an already-built gateway handler on 127.0.0.1:port until ctx is cancelled, applying the same loopback+token auth wrapper as Start. It always binds loopback so the gateway is never exposed to the network.

It exists so the desktop shell can serve the SAME handler instance it composes into the Wails asset middleware (where /v1/* is handled same-origin from the webview). Sharing one handler keeps session/checkpoint state consistent between the in-window webview and the loopback browser fallback (open http://127.0.0.1:port), instead of each path owning a separate SessionManager.

func SetConfigSeam

func SetConfigSeam(load func() (config.Config, error), save func(config.Config) error)

SetConfigSeam overrides the load/save funcs for tests. A nil save leaves the default in place.

func SetPersistSeam

func SetPersistSeam(f func(baseURL, apiKey, model string) error)

SetPersistSeam overrides config persistence for tests.

func SetUpdateSeam

func SetUpdateSeam(latest func(context.Context) (string, string, error), current func() string)

SetUpdateSeam overrides the release lookup + current-version funcs for tests.

func SetValidateKeySeam

func SetValidateKeySeam(f func(context.Context, string, string, *http.Client) error)

SetValidateKeySeam overrides the key validator for tests.

func Start

func Start(ctx context.Context, port int) error

Start builds a default gateway (real agent factory, default trace path) and runs it on 127.0.0.1:port until ctx is cancelled. It is what the desktop wrapper calls in-process; it always binds loopback so the in-process gateway is never exposed to the network.

Types

type CacheReport

type CacheReport struct {
	TotalUsageTurns   int     `json:"total_usage_turns"`
	CacheHitTokens    int     `json:"cache_hit_tokens"`
	CacheMissTokens   int     `json:"cache_miss_tokens"`
	OutputTokens      int     `json:"output_tokens"`
	CostCNY           float64 `json:"cost_cny"`
	FullBodyEvictions int     `json:"full_body_evictions"`
	MaxMissTokens     int     `json:"max_miss_tokens"`
	CacheHitRate      float64 `json:"cache_hit_rate"`
}

CacheReport mirrors the SPA's CacheReport interface (web/src/lib/api.ts). The JSON field names and types are a frozen contract with the SPA; do not rename or reorder without updating the SPA in lockstep.

type ConfigDTO

type ConfigDTO struct {
	Accent          string `json:"accent"`
	Density         string `json:"density"`
	Language        string `json:"language"`
	Model           string `json:"model"`
	ReasoningEffort string `json:"reasoningEffort"`
	BaseURL         string `json:"baseUrl"`
	AutoRoute       bool   `json:"autoRoute"`
	EscalationModel string `json:"escalationModel"`
	DuetEnabled     bool   `json:"duetEnabled"`
	SandboxEnabled  bool   `json:"sandboxEnabled"`
	SandboxNetwork  bool   `json:"sandboxNetwork"`
	AutoReasoning   bool   `json:"autoReasoning"`
	AutoClarify     bool   `json:"autoClarify"`

	// Network / proxy
	ProxyMode   string `json:"proxyMode"`
	ProxyScheme string `json:"proxyScheme"`
	ProxyURL    string `json:"proxyUrl"`
	NoProxy     string `json:"noProxy"`

	// Keybindings
	VimKeybindings bool `json:"vimKeybindings"`

	// Budget / tools
	MaxReadBytes  int64 `json:"maxReadBytes"`
	MaxWriteBytes int64 `json:"maxWriteBytes"`

	// Permissions
	PermissionDefault string `json:"permissionDefault"`

	// Sessions & storage
	SessionTTLDays       int `json:"sessionTTLDays"`
	SessionSnapshotKeep  int `json:"sessionSnapshotKeep"`
	SessionAutoResumeAge int `json:"sessionAutoResumeAge"`

	// Editor / appearance
	TransparentBackground bool `json:"transparentBackground"`
}

ConfigDTO is the SPA-facing settings shape. It is a curated, flat projection of config.Config — only the fields the Settings UI edits — so the wire contract stays stable even as config.Config grows. Field names are the JSON keys the SPA's system.ts depends on.

type Handler

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

Handler is the gateway's composite http.Handler: the three /v1 routes plus a catch-all that serves the embedded SPA.

func (*Handler) ServeHTTP

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

type LedgerRow

type LedgerRow struct {
	Turn         int     `json:"turn"`
	EpochID      string  `json:"epoch_id"`
	HitTokens    int     `json:"hit_tokens"`
	MissTokens   int     `json:"miss_tokens"`
	OutputTokens int     `json:"output_tokens"`
	CostCNY      float64 `json:"cost_cny"`
	Evicted      bool    `json:"evicted"`
	Why          string  `json:"why"`
}

LedgerRow is the SPA-facing per-turn cache row (GET /v1/cache/ledger). It mirrors traceinspect.TurnLedger with snake_case JSON field names.

type Option

type Option func(*Handler)

Option configures a Handler at construction time. Options are additive and optional: a Handler built without any keeps the pre-Wave-5 behaviour, so existing callers and tests are unaffected.

func WithMCPRegistry

func WithMCPRegistry(r *mcp.Registry) Option

WithMCPRegistry attaches the running MCP registry so GET /v1/mcp can report live connection status + tool counts.

func WithSnapshots

func WithSnapshots(m *snapshots.Manager) Option

WithSnapshots attaches a snapshots.Manager so /v1/rewind with a code scope can roll back the working tree via the same pre-edit snapshots /undo uses.

func WithStore

func WithStore(s *session.Store) Option

WithStore attaches a session.Store so checkpoint/rewind/branch endpoints can read and rewrite persisted message history.

func WithWorkspaceRoot

func WithWorkspaceRoot(root string) Option

WithWorkspaceRoot sets the directory the workspace file read (/v1/add-to-chat contents) is confined to. Empty means the process working dir.

Jump to

Keyboard shortcuts

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