web

package
v0.10.6 Latest Latest
Warning

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

Go to latest
Published: Sep 25, 2026 License: MIT Imports: 46 Imported by: 0

Documentation

Overview

Package web is the `uam web` service: a detached per-user process that owns web-surface managed sessions, drives providers through agentapi, and serves the browser interface described in docs/adr/0004-web-interface.md.

Provider conversations and turns belong to the Manager, never to an HTTP request or an event-stream connection. Browsers only observe and submit.

Index

Constants

View Source
const (
	StateIdle               = "idle"
	StateStarting           = "starting"
	StateWorking            = "working"
	StateAwaitingPermission = "awaiting_permission"
	StateAwaitingAnswer     = "awaiting_answer"
	StateCompleted          = "completed"
	StateCancelled          = "cancelled"
	StateFailed             = "failed"
	StateInterrupted        = "interrupted"
	StateClosed             = "closed"
)

Session states reported to browsers.

View Source
const (
	SubmissionAccepted  = "accepted"
	SubmissionRejected  = "rejected"
	SubmissionUncertain = "uncertain"
	SubmissionQueued    = "queued"
	SubmissionCancelled = "cancelled"
)

Submission outcomes. A queued prompt is "queued" until it is sent, then takes the send's outcome; one removed from the queue unsent is "cancelled".

View Source
const (
	StageActive   = ""
	StageSettled  = "settled"
	StageArchived = "archived"
)

Task stages. A Task is active until the user settles or archives it; archived is final.

View Source
const (
	HistoryLoaded      = "loaded"
	HistoryLoading     = "loading"
	HistoryUnavailable = "unavailable"
)

Transcript states of SessionDetail.History. A Task whose conversation is not open has its recorded transcript read without opening it: loading until a "history" event carries it, unavailable when it could not be read.

View Source
const (
	ModeSend  = "send"
	ModeQueue = "queue"
	ModeSteer = "steer"
)

Prompt modes. While a turn runs, send is refused, queue holds the prompt until the turn completes, and steer adds it to the running turn. While the Task is idle, all three send it.

View Source
const (
	ScopeSession   = "session"
	ScopeWorkspace = "workspace"
)

Change scopes.

View Source
const (
	// DefaultListen is the loopback address `uam web` binds by default.
	DefaultListen = "127.0.0.1:8260"
)

Variables

This section is empty.

Functions

func BeyondLoopback

func BeyondLoopback(listen string) bool

BeyondLoopback reports whether listen (host:port) binds a non-loopback IP, which other machines may reach.

func LoadOrCreateToken

func LoadOrCreateToken(path string) (string, error)

LoadOrCreateToken returns the access token stored at path, creating an owner-only file with a new random token when none exists.

func NormalizePublicOrigin

func NormalizePublicOrigin(origin string) (string, error)

NormalizePublicOrigin validates a --public-origin value and returns it as scheme://host[:port].

func RunDaemon

func RunDaemon(cfg DaemonConfig) error

RunDaemon is `uam __web`: it serves until SIGTERM or SIGINT, then shuts down gracefully. Startup errors are reported on the readiness pipe.

func SetToken

func SetToken(path, token string) error

SetToken validates token and atomically replaces the access token file at path with it: a private temp file, renamed over any existing file. A running service keeps its old token until it restarts; the new one then invalidates every session cookie, since cookies are derived from it.

func Spawn

func Spawn(ctx context.Context, exe string, args []string) error

Spawn starts `uam __web` detached, exactly like a session host: its own session, stdio on /dev/null, readiness reported on fd 3. It returns once the service is serving or with the error the service reported.

func Stop

func Stop(ctx context.Context, dir string) (bool, error)

Stop asks the verified running service to shut down gracefully and waits for it. It reports false when nothing was running.

func TokenPath

func TokenPath() string

TokenPath is the access token file, next to sessions.json.

func ValidateListen

func ValidateListen(addr string) (string, error)

ValidateListen accepts an IP literal (loopback, unspecified or an interface address) or localhost, and returns host:port with an IP literal. Other host names are refused.

func ValidateToken

func ValidateToken(token string) error

ValidateToken accepts 24 to 256 printable ASCII characters without whitespace. The generated token (64 hex characters) always qualifies. The error never contains the token.

Types

type AccountUsage

type AccountUsage struct {
	Quotas    []Quota   `json:"quotas"`
	Stale     bool      `json:"stale"`
	UpdatedAt time.Time `json:"updated_at,omitzero"`
}

AccountUsage is the GET /api/usage response: the account quotas of every provider with the usage capability, from the last read that succeeded. Stale is set while the latest read failed; UpdatedAt is when the oldest of the shown quotas was read, omitted before any read succeeded.

type BackgroundTaskCancellation

type BackgroundTaskCancellation struct {
	Accepted        bool                     `json:"accepted"`
	BackgroundTasks agentapi.BackgroundTasks `json:"background_tasks"`
}

type Badge

type Badge struct {
	Text  string `json:"text"`
	Color string `json:"color"`
}

Badge is a Project's badge: Text is two uppercase ASCII letters or digits, unique among Projects; Color is one of badgeColors.

type ChangedFile

type ChangedFile struct {
	Path      string `json:"path"`
	Status    string `json:"status"`
	Additions int    `json:"additions"`
	Deletions int    `json:"deletions"`
}

ChangedFile is one entry of a Changes listing.

type Changes

type Changes struct {
	Scope     string        `json:"scope"`
	Label     string        `json:"label"`
	Supported bool          `json:"supported"`
	Reason    string        `json:"reason"`
	Files     []ChangedFile `json:"files"`
}

Changes lists changed files for one scope. Label states plainly what the scope includes.

type CommandRequest

type CommandRequest struct {
	RequestID   string   `json:"request_id"`
	Name        string   `json:"name"`
	Arguments   string   `json:"arguments"`
	Files       []string `json:"files"`
	Attachments []string `json:"attachments"`
}

CommandRequest is the POST /api/sessions/{id}/command body. Name is a command from GET /api/sessions/{id}/commands, without the slash.

type CreateRequest

type CreateRequest struct {
	ProjectID   string `json:"project_id"`
	Provider    string `json:"provider"`
	Model       string `json:"model"`
	Effort      string `json:"effort"`
	ContextSize string `json:"context_size"`
	Name        string `json:"name"`
	Prompt      string `json:"prompt"`
	RequestID   string `json:"request_id"`
	// Mode is safe (also when empty) or yolo.
	Mode string `json:"mode"`
}

CreateRequest is the POST /api/sessions body. Name may be empty; the provider's title is shown until the user names the Task.

type CustomModel added in v0.9.0

type CustomModel struct {
	Name        string `json:"name"`
	DisplayName string `json:"display_name,omitempty"`
	BaseURL     string `json:"base_url"`
	ModelID     string `json:"model_id"`
	WireAPI     string `json:"wire_api,omitempty"`
	APIKeyEnv   string `json:"api_key_env"`
	KeyPresent  bool   `json:"key_present"`
}

CustomModel is one custom model in Settings. APIKeyEnv only names the service environment variable holding the key; KeyPresent says whether it is set and non-empty there. No key value is ever sent.

type DaemonConfig

type DaemonConfig struct {
	Listen        string
	PublicOrigins []string
	// NoAuth serves every request without authentication.
	NoAuth    bool
	Providers []agentapi.Provider
	Version   string
	// LogHeaders logs every request's headers (see ServerConfig).
	LogHeaders bool
}

DaemonConfig configures `uam __web`.

type DaemonState

type DaemonState struct {
	PID           int       `json:"pid"`
	StartTime     int64     `json:"start_time"`
	Listen        string    `json:"listen"`
	PublicOrigins []string  `json:"public_origins,omitempty"`
	NoAuth        bool      `json:"no_auth,omitempty"`
	LogHeaders    bool      `json:"log_headers,omitempty"`
	Version       string    `json:"version"`
	StartedAt     time.Time `json:"started_at"`
}

DaemonState is web.json: how to find and verify the running service. It never contains the access token.

func ReadRunning

func ReadRunning(dir string) (DaemonState, bool)

ReadRunning returns the running service's state after verifying that its PID still names the same process. A stale file reports not running.

func (DaemonState) LocalAddr

func (st DaemonState) LocalAddr() string

LocalAddr is the host:port clients on this host connect to: the listen address, with an unspecified host replaced by loopback on the same port (0.0.0.0 by 127.0.0.1, :: by ::1).

func (DaemonState) URL

func (st DaemonState) URL() string

URL is the address browsers on this host use (see LocalAddr).

type DirEntry

type DirEntry struct {
	Name string `json:"name"`
	Path string `json:"path"`
	// Git means the folder holds .git, a directory or, in a linked worktree,
	// a file.
	Git    bool `json:"git"`
	Hidden bool `json:"hidden"`
	// Link means the entry is a symbolic link to a directory.
	Link bool `json:"link"`
}

DirEntry is one folder in a listing. Name is the last element of Path; both are displayable as they are (see displayable).

type DirList

type DirList struct {
	Path      string     `json:"path"`
	Parent    string     `json:"parent,omitempty"`
	Entries   []DirEntry `json:"entries"`
	Truncated bool       `json:"truncated"`
}

DirList answers GET /api/fs/dirs. Parent is empty at /.

type DiscoverRequest added in v0.9.0

type DiscoverRequest struct {
	BaseURL   string `json:"base_url"`
	APIKeyEnv string `json:"api_key_env"`
	WireAPI   string `json:"wire_api"`
}

DiscoverRequest names an OpenAI-compatible endpoint whose models to list.

type DiscoverResult added in v0.9.0

type DiscoverResult struct {
	Models     []string `json:"models"`
	Truncated  bool     `json:"truncated,omitempty"`
	KeyPresent bool     `json:"key_present"`
}

DiscoverResult is what the endpoint lists: sorted, distinct model IDs that could be stored, at most maxDiscoverIDs (Truncated when more were listed). KeyPresent is true: discovery refuses a missing key.

type Error

type Error struct {
	Status  int
	Message string
	// ProjectID names the existing Project when adding a directory that
	// already has one.
	ProjectID string
}

Error is a failure with the HTTP status the server reports for it.

func (*Error) Error

func (e *Error) Error() string

type FileEntry

type FileEntry struct {
	Path string `json:"path"`
	// Type is "file" or "directory".
	Type string `json:"type"`
}

FileEntry is one project path the composer can reference.

type FileList

type FileList struct {
	Files  []FileEntry `json:"files"`
	Reason string      `json:"reason"`
}

FileList answers GET /api/sessions/{id}/files and GET /api/projects/{id}/files. Reason says why the list is empty or cut short.

type Manager

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

Manager owns every web session, its provider conversation, and the event fan-out to browsers.

Two locks per session keep provider callbacks non-blocking: session.op serializes operations that call the provider (open, send, close) and may be held across those calls, while Manager.mu guards all observable state and is only ever held for short, allocation-bounded sections. Provider events take only Manager.mu, so a slow provider call or an absent browser never delays event processing.

func NewManager

func NewManager(st *store.Store, providers []agentapi.Provider) *Manager

NewManager builds a manager for providers. Start must run before use.

func (*Manager) AccountUsage

func (m *Manager) AccountUsage() AccountUsage

AccountUsage returns the cached account quotas.

func (*Manager) AddProject

func (m *Manager) AddProject(dir, name string) (Project, error)

AddProject adds the directory dir as a Project and gives it a badge. A directory has at most one Project; adding it again reports the existing one with 409.

func (*Manager) Answer

func (m *Manager) Answer(id, interactionID string, answer agentapi.Answer) (agentapi.Interaction, error)

Answer forwards the user's answer to a pending interaction. The first answer wins. The service answers on the user's behalf only for permission requests of a yolo Task, and never for questions.

func (*Manager) Archive

func (m *Manager) Archive(id string) (SessionSummary, error)

Archive moves an active or settled Task to its final stage; nothing moves it back. An active Task must meet the same conditions as for Settle.

func (*Manager) Attachment

func (m *Manager) Attachment(id, attachmentID string) (agentapi.Attachment, []byte, time.Time, error)

Attachment returns one stored upload of a Task and its bytes.

func (*Manager) Cancel

func (m *Manager) Cancel(id string) (SessionSummary, error)

Cancel aborts the running turn. It is distinct from a viewer leaving and from Close: the conversation stays open.

func (*Manager) CancelBackgroundTask

func (m *Manager) CancelBackgroundTask(id, taskID string) (BackgroundTaskCancellation, error)

func (*Manager) CancelQueued

func (m *Manager) CancelQueued(id, reqID string) error

CancelQueued removes one prompt from the queue before it is sent. It never contacts the provider. Cancelling it again succeeds; a prompt already sent is refused with 409.

func (*Manager) CancelSubagent

func (m *Manager) CancelSubagent(id, agentID string) (agentapi.Subagent, error)

CancelSubagent stops only the selected agent. Successful repeats never resend, and final status is supplied by the provider's subagent event.

func (*Manager) Changes

func (m *Manager) Changes(ctx context.Context, id, scope string) (Changes, error)

Changes lists changed files for a session in the requested scope. It also re-reads the branch of the session's Project.

func (*Manager) ClearQueue

func (m *Manager) ClearQueue(id string) error

ClearQueue removes every queued prompt, as CancelQueued does one.

func (*Manager) Close

func (m *Manager) Close(id string) (SessionSummary, error)

Close disconnects the conversation and keeps the record.

func (*Manager) Command

func (m *Manager) Command(id string, req CommandRequest) (Submission, error)

Command runs one of the provider's listed commands. It follows the rules of a send: a repeated request ID returns the recorded outcome, a running turn refuses it, and there is no queue or steer.

func (*Manager) Commands

func (m *Manager) Commands(ctx context.Context, id string) ([]agentapi.Command, error)

Commands lists the live catalogue, reopening only the exact conversation of an active Task. Discovery never submits a prompt.

func (*Manager) Create

func (m *Manager) Create(req CreateRequest) (SessionSummary, error)

Create opens a new provider conversation in a Project's directory, records the session (a Task), and, when a prompt is given, submits it through the same path as Submit.

func (*Manager) Delete

func (m *Manager) Delete(id string) error

Delete deletes an archived Task's record and its stored attachments. It is refused for any other stage. The conversation is never deleted at the provider.

func (*Manager) Detail

func (m *Manager) Detail(id string) (SessionDetail, error)

Detail returns one session with its retained transcript. Asking for it starts a read-only load of the recorded transcript when the conversation is not open and the transcript is not in memory.

func (*Manager) DiscoverModels added in v0.9.0

func (m *Manager) DiscoverModels(ctx context.Context, req DiscoverRequest) (DiscoverResult, error)

DiscoverModels lists the models an OpenAI-compatible endpoint serves with one GET of base_url + "/models", authenticated with the key read from the named UAM_BYOM_ variable. Only the IDs come back; an upstream failure is reported by status line or kind, never by its body.

func (*Manager) DropSubscribers

func (m *Manager) DropSubscribers()

DropSubscribers disconnects every event stream, for server shutdown.

func (*Manager) FileChange

func (m *Manager) FileChange(ctx context.Context, id, scope, path string) (agentapi.FileDiff, error)

FileChange returns one file's diff in the requested scope. The path must be one the scope's listing reports.

func (*Manager) Files

func (m *Manager) Files(ctx context.Context, id, q string, limit int) (FileList, error)

Files lists up to limit paths in the Task's directory whose path matches q, for the @ picker. Git lists them, so .gitignore applies; parent directories are added, symbolic links are left out.

func (*Manager) Import

func (m *Manager) Import(ctx context.Context, projectID, convID string) (SessionSummary, error)

Import creates an active Task linked to a previous conversation of a Project's directory. Nothing is sent. The Task starts closed with the transcript read without opening the conversation; its next prompt opens it. It keeps the conversation's model when the provider offers it, otherwise takes the Task defaults of Settings, and it takes their mode. A conversation another client holds open, or a Task is linked to, is refused with 409.

func (*Manager) List

func (m *Manager) List() []SessionSummary

List returns every web session, newest first.

func (*Manager) Previous

func (m *Manager) Previous(projectID string) ([]PreviousConversation, error)

Previous lists, newest first and at most maxPrevious, the conversations that providers able to import recorded for a Project's directory and that no Task is linked to, each marked while another client holds it open.

func (*Manager) PreviousCounts

func (m *Manager) PreviousCounts(ctx context.Context) (map[string]int, error)

PreviousCounts lists each provider once without holder checks. Counts use the same cap and linked-conversation exclusions as the Project list.

func (*Manager) ProjectFiles added in v0.10.4

func (m *Manager) ProjectFiles(ctx context.Context, projectID, q string, limit int) (FileList, error)

ProjectFiles is Files for a Project's directory, for the @ picker of a new Task that has no conversation yet.

func (*Manager) Projects

func (m *Manager) Projects() []Project

Projects returns every Project, oldest first.

func (*Manager) PromptSubagent

func (m *Manager) PromptSubagent(id, agentID, text, requestID string) (Submission, error)

PromptSubagent sends text to one idle subagent of an active Task whose conversation is open and runs no turn. The follow-up is not a Task turn: the Task's state, queue and last submission stay as they are, and the subagent's status arrives through its events. A repeated request ID returns the recorded outcome without contacting the provider.

func (*Manager) Providers

func (m *Manager) Providers() []ProviderInfo

Providers lists every provider with its availability.

func (*Manager) RawImage added in v0.10.1

func (m *Manager) RawImage(id, p string) (*ServedFile, error)

RawImage opens the image at p, absolute or relative to the Task's directory, for the raw file route. Symbolic links are resolved first and the real file must lie inside the Task's real directory; anything else, missing files included, is a 404 that says nothing more. Only a regular file whose extension and bytes agree on png, jpeg, gif or webp, at most maxServedImageBytes, is served.

func (*Manager) RecentWorkdirs

func (m *Manager) RecentWorkdirs() []string

RecentWorkdirs returns distinct workdirs of stored records of any surface, most recently seen first.

func (*Manager) RefreshModels

func (m *Manager) RefreshModels()

RefreshModels reloads the catalog of every available provider whose copy is older than modelsMaxAge. A failed load keeps the previous catalog and is retried after modelsMaxAge.

func (*Manager) RemoveProject

func (m *Manager) RemoveProject(id string) error

RemoveProject deletes a Project and its Task records. It is refused unless every Task in it is archived. Conversations are never deleted at the provider, and the directory is not touched.

func (*Manager) Rename

func (m *Manager) Rename(id, name string) (SessionSummary, error)

Rename sets the Task's typed name. An empty name shows the Task's title again; the provider's conversation is not renamed. A title job running meanwhile leaves the Task alone.

func (*Manager) Reopen

func (m *Manager) Reopen(id string) (SessionSummary, error)

Reopen makes a settled Task active again. Its next prompt reopens the same conversation.

func (*Manager) ResumeQueue

func (m *Manager) ResumeQueue(id string) error

ResumeQueue lets a paused queue drain again: at once when no turn is running, otherwise after the running turn completes.

func (*Manager) SetHostProbe

func (m *Manager) SetHostProbe(live func(sessionName string) bool)

SetHostProbe sets how the service tells that a terminal session host runs, for Tasks tied to a terminal session. Call it before Start.

func (*Manager) SetMode

func (m *Manager) SetMode(id, mode string) (SessionSummary, error)

SetMode sets the Task's permission mode at any time, even while a turn runs. It applies to permission requests raised afterwards; switching to yolo also answers the ones already pending.

func (*Manager) SetModel

func (m *Manager) SetModel(id string, model, effort, contextSize *string) (SessionSummary, error)

SetModel changes the supplied settings together for the Task's next turns. An omitted effort or context size survives a model change when supported. With the conversation open, settings are stored only after provider success; otherwise the next open applies them. Changes during a turn are refused.

func (*Manager) Settings

func (m *Manager) Settings() Settings

Settings returns the web interface's settings.

func (*Manager) Settle

func (m *Manager) Settle(id string) (SessionSummary, error)

Settle marks an active Task complete and closes its conversation. It is refused while the Task is busy, has queued prompts or waits for an answer.

func (*Manager) Shutdown

func (m *Manager) Shutdown(ctx context.Context) error

Shutdown ends every conversation this service drives: running turns are recorded as interrupted, conversations are closed, and every provider is asked to stop the runtimes it started.

func (*Manager) Start

func (m *Manager) Start(ctx context.Context) error

Start checks providers, loads their model catalogs and the web records, assigns records from before Projects existed to a Project, and gives each Project without a valid badge one. A provider whose check fails is listed as unavailable; it is not fatal.

func (*Manager) Subagent

func (m *Manager) Subagent(id, agentID string) (SubagentDetail, error)

Subagent returns one subagent of a session with its retained transcript.

func (*Manager) Submit

func (m *Manager) Submit(id string, req PromptRequest) (Submission, error)

Submit sends one prompt in mode: ModeSend ("" too), ModeQueue or ModeSteer. A repeated request ID returns the recorded outcome, or "queued" while the prompt waits in the queue, without contacting the provider.

func (*Manager) Subscribe

func (m *Manager) Subscribe(sessionID string) (*Subscriber, []byte, error)

Subscribe registers a subscriber and returns it with its snapshot frame. Registration and snapshot happen under one lock, so the subscriber sees every later event exactly once and nothing between the two. Subscribing to a session views it, as Detail does.

func (*Manager) Summary

func (m *Manager) Summary(id string) (SessionSummary, error)

Summary returns one session's summary.

func (*Manager) Unsubscribe

func (m *Manager) Unsubscribe(sub *Subscriber)

Unsubscribe removes a subscriber (its viewer left). It has no effect on the provider side.

func (*Manager) UpdateProject

func (m *Manager) UpdateProject(id, name string) (Project, error)

UpdateProject renames a Project. An empty name resets it to the directory's base name.

func (*Manager) UpdateSettings

func (m *Manager) UpdateSettings(p SettingsPatch) (Settings, error)

UpdateSettings applies p. An invalid value is refused with 400 and changes nothing. A change is stored and sent as a settings frame; no change writes nothing. Hidden models are a display preference: nothing else checks them. A Utility model must be one the provider lists now, and the provider must have the titles capability; neither is needed to unset it or opt out.

func (*Manager) Upload

func (m *Manager) Upload(id, name string, data []byte) (agentapi.Attachment, error)

Upload stores one file for the Task and returns its record. The type is sniffed from the bytes, and images and PDFs must pass the Task's model gate.

func (*Manager) View

func (m *Manager) View(ctx context.Context, id string) error

View opens a session's conversation lazily for a viewer and waits a bounded time for it. The open runs on the service, not on ctx: a viewer leaving early does not abort it.

func (*Manager) ViewFile added in v0.10.1

func (m *Manager) ViewFile(id, rel string) (*ServedFile, error)

ViewFile opens the file at rel, relative to the Task's directory, for the view route, with the confinement of RawImage. Its type comes from the extension (viewTypes), else text/plain or application/octet-stream.

type Meta

type Meta struct {
	Version        string         `json:"version"`
	Providers      []ProviderInfo `json:"providers"`
	RecentWorkdirs []string       `json:"recent_workdirs"`
}

Meta is the /api/meta response.

type PreviousConversation

type PreviousConversation struct {
	Provider       string    `json:"provider"`
	ConversationID string    `json:"conversation_id"`
	Title          string    `json:"title"`
	CreatedAt      time.Time `json:"created_at"`
	UpdatedAt      time.Time `json:"updated_at"`
	InUse          bool      `json:"in_use"`
}

PreviousConversation is a provider conversation recorded for a Project's directory that no Task is linked to. InUse is set while another client holds it open.

type Project

type Project struct {
	ID        string    `json:"id"`
	Name      string    `json:"name"`
	Dir       string    `json:"dir"`
	CreatedAt time.Time `json:"created_at"`
	Badge     Badge     `json:"badge"`
	// Branch is the branch checked out in Dir's git work tree, read from git
	// and never stored. It is empty when Dir is not in a work tree, HEAD is
	// detached, or git cannot tell.
	Branch string `json:"branch,omitempty"`
}

Project is a directory the user added; its Tasks are web sessions whose project_id is ID.

type PromptRequest

type PromptRequest struct {
	Text      string `json:"text"`
	RequestID string `json:"request_id"`
	Mode      string `json:"mode"`
	// Files are project paths relative to the Task's directory, sent as
	// structured references.
	Files []string `json:"files"`
	// Attachments are IDs from POST /api/sessions/{id}/attachments.
	Attachments []string `json:"attachments"`
}

PromptRequest is the POST /api/sessions/{id}/prompt body.

type ProviderInfo

type ProviderInfo struct {
	Name         string                `json:"name"`
	DisplayName  string                `json:"display_name"`
	Available    bool                  `json:"available"`
	Reason       string                `json:"reason"`
	Capabilities agentapi.Capabilities `json:"capabilities"`
	// Models are the selectable models; empty means the provider default only.
	Models []agentapi.Model `json:"models"`
	// CheapestModel is the cheapest priced model not hidden in Settings: the
	// Utility model when Settings name none. Omitted when none is priced.
	CheapestModel string `json:"cheapest_model,omitempty"`
}

ProviderInfo describes one provider for the create form.

type QueuedPrompt

type QueuedPrompt struct {
	RequestID string    `json:"request_id"`
	Text      string    `json:"text"`
	QueuedAt  time.Time `json:"queued_at"`
	// Files are the project paths the prompt references; they are checked
	// again when it is sent.
	Files []string `json:"files,omitempty"`
	// Attachments are the uploads the prompt carries.
	Attachments []agentapi.Attachment `json:"attachments,omitempty"`
}

QueuedPrompt is one prompt in a Task's queue.

type Quota

type Quota struct {
	Provider         string    `json:"provider"`
	Type             string    `json:"type"`
	Used             int64     `json:"used"`
	Entitlement      int64     `json:"entitlement"`
	Unlimited        bool      `json:"unlimited"`
	RemainingPercent float64   `json:"remaining_percent"`
	Overage          float64   `json:"overage"`
	ResetAt          time.Time `json:"reset_at,omitzero"`
}

Quota is one account quota. Entitlement is 0 when Unlimited; ResetAt is omitted unless the provider reported a time still in the future.

type ServedFile added in v0.10.1

type ServedFile struct {
	File *os.File
	Info fs.FileInfo
	MIME string
}

ServedFile is a file of a Task's directory, open for reading, with the type it is served as.

type Server

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

Server is the HTTP handler for the web interface.

func NewServer

func NewServer(cfg ServerConfig) (*Server, error)

NewServer validates cfg and builds the handler.

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP applies the security checks every request passes before routing.

type ServerConfig

type ServerConfig struct {
	Manager *Manager
	// Token is the access token browsers present at /api/login.
	Token string
	// Listen is the address the service binds. Beyond loopback, a Host that
	// is an IP literal (such as the LAN address) is also accepted.
	Listen string
	// PublicOrigins are origins (scheme://host[:port]) of same-host reverse
	// proxies whose Host header is accepted besides loopback.
	PublicOrigins []string
	// NoAuth treats every request as authenticated. The Host, cross-origin,
	// content-type and body checks still apply.
	NoAuth  bool
	Version string
	// Assets overrides the embedded frontend (tests).
	Assets fs.FS
	// LogHeaders logs one record per request with its headers (credentials
	// redacted) and the outcome of the checks in ServeHTTP.
	LogHeaders bool
}

ServerConfig configures the HTTP interface.

type SessionDetail

type SessionDetail struct {
	TurnTimings []TurnTiming `json:"turn_timings"`
	SessionSummary
	// Seq orders this snapshot against events on the same service.
	Seq              uint64                    `json:"seq"`
	Items            []agentapi.Item           `json:"items"`
	Interactions     []agentapi.Interaction    `json:"interactions"`
	Subagents        []agentapi.Subagent       `json:"subagents"`
	HistoryTruncated bool                      `json:"history_truncated"`
	LastSubmission   *Submission               `json:"last_submission"`
	BackgroundTasks  *agentapi.BackgroundTasks `json:"background_tasks,omitempty"`
	// Queue holds the prompts waiting for the running turn, oldest first.
	Queue []QueuedPrompt `json:"queue"`
	// QueuePaused is set while the queue waits for the user to resume or
	// clear it; it is never set with an empty queue.
	QueuePaused bool `json:"queue_paused"`
	// History says whether Items and Subagents hold the conversation's
	// recorded transcript (HistoryLoaded, HistoryLoading or
	// HistoryUnavailable); HistoryReason says why it is unavailable.
	History       string `json:"history"`
	HistoryReason string `json:"history_reason,omitempty"`
	// TerminalSession is the uam terminal session tied to the same
	// conversation, present while its host runs.
	TerminalSession *TerminalSession `json:"terminal_session,omitempty"`
}

type SessionSummary

type SessionSummary struct {
	ID             string    `json:"id"`
	Provider       string    `json:"provider"`
	Name           string    `json:"name"`
	Workdir        string    `json:"workdir"`
	ConversationID string    `json:"conversation_id"`
	State          string    `json:"state"`
	StateDetail    string    `json:"state_detail"`
	Open           bool      `json:"open"`
	Pending        int       `json:"pending"`
	CreatedAt      time.Time `json:"created_at"`
	UpdatedAt      time.Time `json:"updated_at"`
	// Capabilities come from the provider so the browser can hide controls
	// the provider does not really support.
	Capabilities agentapi.Capabilities `json:"capabilities"`
	ProjectID    string                `json:"project_id"`
	// Model is the selected model; empty means the provider default.
	Model       string            `json:"model"`
	Effort      string            `json:"effort"`
	ContextSize string            `json:"context_size"`
	Context     *agentapi.Context `json:"context,omitempty"`
	// Usage is the AI units the Task's conversation used, main agent and
	// subagents together, once the provider reports them; it is not
	// persisted and after a restart comes back only from provider history.
	Usage *agentapi.Usage `json:"usage,omitempty"`
	// Title is the provider-generated title. Name may be empty; browsers
	// display name || title || "New task".
	Title string `json:"title"`
	// LastModel is the model the provider reported for the latest turn that
	// reported one. It is not persisted.
	LastModel string `json:"last_model"`
	// SubagentsRunning counts subagents that have not ended.
	SubagentsRunning int `json:"subagents_running"`
	// Queued counts prompts waiting in the Task's queue.
	Queued int `json:"queued"`
	// Mode is safe or yolo. A yolo Task's permission requests are allowed
	// once without asking; questions still wait for the user.
	Mode      string                   `json:"mode"`
	Execution *agentapi.ExecutionState `json:"execution"`
	// Stage is omitted for an active Task, otherwise StageSettled or
	// StageArchived; SettledAt and ArchivedAt say when.
	Stage      string    `json:"stage,omitempty"`
	SettledAt  time.Time `json:"settled_at,omitzero"`
	ArchivedAt time.Time `json:"archived_at,omitzero"`
}

SessionSummary is one web session (a Task) as listed.

type Settings

type Settings struct {
	// SendDefault is what Enter does while a turn runs: steer or queue.
	SendDefault string `json:"send_default"`
	// HiddenModels lists, by provider, the model IDs the browser does not
	// offer, sorted; omitted when none is hidden. IDs the provider no longer
	// lists are kept. The service never refuses a hidden model.
	HiddenModels map[string][]string `json:"hidden_models,omitempty"`
	// TitleModel maps a provider to its Utility model, the model UAM uses for
	// its own small AI jobs such as titling new Tasks: a model ID, or
	// store.WebTitleModelNone when the provider keeps its own title. A
	// provider without an entry uses ProviderInfo.CheapestModel. Omitted when
	// no provider has an entry.
	TitleModel map[string]string `json:"title_model,omitempty"`
	// CustomModels are the OpenAI-compatible models the owner brought;
	// omitted when there are none. Their model IDs are name/model_id.
	CustomModels []CustomModel `json:"custom_models,omitempty"`
	// TaskDefaults are the settings a new Task starts with; omitted when
	// unset, and the browser then starts from the provider's own defaults.
	TaskDefaults TaskDefaults `json:"task_defaults,omitzero"`
}

Settings are the web interface's settings, shared by every browser.

type SettingsPatch

type SettingsPatch struct {
	SendDefault  *string
	HiddenModels map[string][]string
	TitleModel   map[string]string
	CustomModels *[]store.WebCustomModel
	TaskDefaults *TaskDefaults
}

SettingsPatch is a settings change; a nil field changes nothing. HiddenModels replaces the hidden model IDs of each provider it names, and only those; an empty list hides none of that provider's models. TitleModel sets the Utility model of each provider it names: a model ID, or store.WebTitleModelNone to opt out; an empty ID unsets it, so the provider uses its cheapest priced model again.

CustomModels, when not nil, replaces every custom model; an empty list removes them all. TaskDefaults replaces the settings a new Task starts with; they are checked as a Task's selection is.

type SubagentDetail

type SubagentDetail struct {
	// Seq is the SSE sequence captured with the transcript and metadata.
	Seq      uint64            `json:"seq"`
	Subagent agentapi.Subagent `json:"subagent"`
	Items    []agentapi.Item   `json:"items"`
}

SubagentDetail is one subagent and its retained transcript.

type Submission

type Submission struct {
	RequestID     string                  `json:"request_id"`
	Status        string                  `json:"status"`
	Error         string                  `json:"error"`
	Time          time.Time               `json:"time"`
	CommandResult *agentapi.CommandResult `json:"command_result,omitempty"`
}

Submission is the recorded outcome of one prompt request.

type Subscriber

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

Subscriber is one event-stream connection. It only observes: dropping it never affects providers.

func (*Subscriber) Frames

func (s *Subscriber) Frames() <-chan []byte

Frames returns the queue of encoded events for this subscriber.

func (*Subscriber) Gone

func (s *Subscriber) Gone() <-chan struct{}

Gone is closed when the subscriber was dropped (queue overflow or service shutdown).

func (*Subscriber) Sent

func (s *Subscriber) Sent(frame []byte)

Sent records that one queued frame was written.

type TaskDefaults

type TaskDefaults struct {
	Provider    string `json:"provider"`
	Model       string `json:"model"`
	Effort      string `json:"effort"`
	ContextSize string `json:"context_size"`
	Mode        string `json:"mode"`
}

TaskDefaults are the settings a new Task starts with (Settings). The browser resolves them against the live models when it creates a Task. ContextSize is "default" unless a tier is chosen; Mode is safe or yolo.

type TerminalSession

type TerminalSession struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

TerminalSession is a uam terminal session tied to a Task's conversation. It stays the terminal's: the Task only records the link.

type TurnTiming

type TurnTiming = store.TurnTiming

SessionDetail is a summary plus the retained main-agent transcript, interactions and subagents.

Jump to

Keyboard shortcuts

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