agents

package
v1.2.9 Latest Latest
Warning

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

Go to latest
Published: Oct 7, 2026 License: MIT Imports: 134 Imported by: 0

Documentation

Overview

Package agents backs /tools/agents — the Agents UI Manager. It lets users manage AI agent sessions, workspaces, and presets from the browser and streams real-time agent output via Server-Sent Events.

Index

Constants

View Source
const (
	ApprovalAccept           = "accept"
	ApprovalAcceptForSession = "accept_for_session"
	ApprovalDecline          = "decline"
)

Approval card decisions (the codex app-server enum), mapped onto the gate's own decisions so a card click resolves exactly as the modal does.

View Source
const RoleViewer = "viewer"

RoleViewer marks a roster item shared with the caller: the front-end locks every menu but chat and info.

View Source
const TicketRESTBase = "/api"

TicketRESTBase is the public, machine-facing mount of the ticket REST API. The tool-internal routes stay under /tools/agents/api where the browser SPA fetches them; this short root path is what integrations are told to use, so the documented base URL does not leak the internal tool layout.

Variables

View Source
var SPAFS fs.FS = func() fs.FS { return spaLoader.FS() }()

SPAFS is kept for backward compatibility with spa_handler.go (reads the FS directly to serve assets + the shell). Points at the same FS as spaLoader.

Functions

func A2ADirectory added in v1.2.9

func A2ADirectory() a2aserver.Directory

A2ADirectory is the Team side of the A2A server: agents and their sessions.

func AirouterAutostart added in v0.31.0

func AirouterAutostart(logf func(string))

AirouterAutostart starts every auto-start-enabled router at boot. Called from server.go after the tool router mounts (so the config store is wired).

func AirouterEnabled added in v0.31.0

func AirouterEnabled() bool

AirouterEnabled reports the master switch. Absent row = ON (default true, matching DefaultGeneralConfig) so an existing setup keeps working until an admin disables it. Falls back to the legacy router9enabled key.

func AirouterExternalAllowed added in v0.31.0

func AirouterExternalAllowed(id string) bool

AirouterExternalAllowed reports whether router id's /v1 API may be reached off-machine — the host-allowlist exemption in server.go consults this for a non-loopback caller on the /airouter/<id>/v1 subtree.

func AirouterVisible added in v0.31.0

func AirouterVisible(ctx context.Context) bool

AirouterVisible reports whether the AI Router nav entry should show: master on AND the caller has access.

func AnyAirouterAutostart added in v0.31.0

func AnyAirouterAutostart() bool

AnyAirouterAutostart reports whether at least one router has auto-start on.

func AutoInstallMCP added in v0.13.4

func AutoInstallMCP()

AutoInstallMCP installs wick into every detected MCP client that doesn't have it yet, skipping blocklisted (manually-uninstalled) clients. Called once at server startup; the mcp_auto_installed flag prevents re-runs so page renders never trigger spurious re-installs.

func CLIAPIAuthMW added in v1.2.9

func CLIAPIAuthMW(next http.Handler) http.Handler

CLIAPIAuthMW resolves a wick_cli_ bearer into its grant.

Separate from the ticket middleware on purpose: these tokens are not Personal Access Tokens and must not reach the ticket surface, and a PAT must not reach this one. Each validator owns its own prefix and its own paths, so neither can widen the other by accident.

func ChannelNumberPostback added in v1.2.9

func ChannelNumberPostback(ctx context.Context, sessionID, source, text string) (label string, ok bool, err error)

ChannelNumberPostback maps a bare-number reply on a channel without buttons (Telegram, plain text) to a click on the open card's n-th button. ok=false when text is not a number or no card is open, so the caller sends it as an ordinary message.

func ChannelPostback added in v1.2.9

func ChannelPostback(ctx context.Context, sessionID, source, cardID, value string) (string, error)

ChannelPostback is a card button clicked in a chat channel (Slack): the same check and send as the web endpoint. Returns the button's label.

func HasManageableProvider added in v1.2.9

func HasManageableProvider(c *tool.Ctx) bool

HasManageableProvider reports whether the caller may manage ANY instance — the one question the sidebar asks, since a menu that opens onto an empty page is worse than no menu.

Exported because the layout builder lives beside it and the templ view takes it as a plain bool.

func IsRemoteAgent added in v1.2.9

func IsRemoteAgent(p entity.AgentPersona) bool

IsRemoteAgent reports whether p is a remote agent of any source (A2A, Slack): no local process, its brain lives elsewhere.

func NewTeamLinkHub added in v1.2.9

func NewTeamLinkHub(svc *team.Service, deliver func(ctx context.Context, sessionID, text string) error) *teamlink.Hub

NewTeamLinkHub builds the Hub over the Team service and the pool. deliver wakes a session with a late reply (the sub-agent delivery path).

func ParseNumberReply added in v1.2.9

func ParseNumberReply(text string) (int, bool)

ParseNumberReply reads text as a bare 1-based choice ("2", " 2. ").

func RESTDirectory added in v1.2.9

func RESTDirectory() rest.AgentDirectory

RESTDirectory is the Team side of the REST channel's `agent:<handle>` models.

func RecordApprovalRequest added in v1.2.9

func RecordApprovalRequest(sessionID string, r gate.ApprovalRequest)

RecordApprovalRequest writes a gate approval prompt into its session's thread as a kind:"approval_request" turn — the card is made by the server, never by the agent.

func RecordApprovalResolved added in v1.2.9

func RecordApprovalResolved(sessionID, requestID, decision string)

RecordApprovalResolved writes how the prompt was settled under the same approval_id; decision is the gate's (approve_once, approve_session, approve_always, block, guide, or a timeout's block).

func RecordAskRequest added in v1.2.9

func RecordAskRequest(req askuser.AskRequest)

RecordAskRequest writes a pending ask_user question into its session's thread as a kind:"input_request" turn.

func RecordAskSettled added in v1.2.9

func RecordAskSettled(req askuser.AskRequest, ans askuser.Answer, outcome string)

RecordAskSettled writes how the question ended: answered (with the answer as shown to the user), timeout or cancelled.

func RecordChannelDelivery added in v1.2.9

func RecordChannelDelivery(sessionID, turnID string, d store.Delivery) string

RecordChannelDelivery is the channels' delivery recorder (see slack.DeliveryFunc): it saves d against turnID — the session's newest assistant turn when turnID is "" — and pushes it to open viewers. Returns the turn ID recorded against, "" when nothing was.

func RedactIntegrations added in v1.2.9

RedactIntegrations returns a copy safe to send to a client.

Secrets never leave the server: a stored one reads as the sentinel so the UI can show "signed" without ever holding the key. Callers rendering the settings page must go through this.

func Register

func Register(r tool.Router)

Register mounts all Agents routes under /tools/agents.

func RegisterAgentSlackInstances added in v1.2.9

func RegisterAgentSlackInstances(ctx context.Context)

RegisterAgentSlackInstances adds every enabled agent's bot to the registry at boot, before the server wires and starts the channels.

func RegisterAgentTelegramInstances added in v1.2.9

func RegisterAgentTelegramInstances(ctx context.Context)

RegisterAgentTelegramInstances adds every enabled agent's bot to the registry at boot, before the server wires and starts the channels.

func RegisterAirouter added in v0.31.0

func RegisterAirouter(r tool.Router)

RegisterAirouter wires the AI Router control endpoints + SPA page onto the agents tool router. Called from handler.go's Register.

func RemoteSpawnerFor added in v1.2.9

func RemoteSpawnerFor(sessionID string) (provider.Spawner, bool)

RemoteSpawnerFor is the pool factory's RemoteSpawnerLoader: a session bound to an A2A remote agent runs on that remote. The auth secret is decrypted here, per spawn, and kept only in the spawner's memory.

func SetA2AServer added in v1.2.9

func SetA2AServer(s *a2aserver.Server)

SetA2AServer is called once by the server after it registers the channel.

func SetApprovals

func SetApprovals(m *gate.ApprovalManager)

SetApprovals wires in the gate ApprovalManager. nil = gate disabled (handler endpoints fall back to 503).

func SetAskUsers

func SetAskUsers(m *askuser.Manager)

SetAskUsers wires in the ask_user Manager. nil = ask_user MCP tool returns errors and the answer endpoint 503s.

func SetAuth added in v0.14.21

func SetAuth(a *login.Service)

SetAuth wires the login service so per-user preferences (pinned project) can be read/written from the agents tool.

func SetBroadcaster

func SetBroadcaster(b *Broadcaster)

SetBroadcaster wires in the SSE event broadcaster.

func SetChannelRegistry added in v0.10.0

func SetChannelRegistry(r *agentchannels.Registry)

SetChannelRegistry wires the live channel registry so picker fields can issue lookup queries against each channel's upstream (Slack API, etc.). Without this, /channels/{slug}/lookup returns 503.

func SetChannelWirer added in v1.2.9

func SetChannelWirer(fn func(agentchannels.Channel))

SetChannelWirer is called once by the server after it builds its per-channel wiring.

func SetConfigs

func SetConfigs(c *configs.Service)

SetConfigs wires the shared configs service so the Providers page can toggle agents.gate_enabled inline. Without this, the toggle endpoint 503s.

It also hands the wick provider a secret decryptor so its in-process engine can decrypt per-model API keys (wick_cenc_ tokens) at spawn time without the wick package importing configs (avoids a cycle).

func SetConnectors added in v0.17.0

func SetConnectors(c *connectors.Service)

SetConnectors wires the connectors service so the session Config tab can read a connector's field schema (to render the form) and resolve which connectors opted into per-session overrides.

func SetDB

func SetDB(db *gorm.DB)

SetDB wires the shared GORM DB so channel handlers can read/write agent_channels rows. Without this, channel config endpoints 503.

Workflow data is DB-primary. Folders left on disk from before the DB migration are not imported automatically — use the SPA or MCP to recreate them, then remove the old folders.

func SetDataTables added in v0.13.1

func SetDataTables(s datatable.Service)

SetDataTables registers the shared data-table service. nil is allowed during early boot; handlers fall back to 503.

func SetDelegation added in v0.36.0

func SetDelegation(s *delegation.Service)

SetDelegation wires the delegation service for the HTTP layer.

func SetGateStatus

func SetGateStatus(s GateStatus)

SetGateStatus records the boot-time gate-resolution result. Read by the Providers page. Call exactly once during server boot.

func SetLayout

func SetLayout(l agentconfig.Layout)

SetLayout wires in the on-disk layout used for direct file reads.

It also enables persistence for per-session provider overrides (the composer's /thinking popover): the store needs a session-ID → dir resolver to find its overrides.json sidecar, and this is the one place the layout is known. Without it the store stays memory-only and a toggle dies with the engine goroutine.

func SetManager

func SetManager(m *registry.Manager)

SetManager wires in the agents registry manager.

func SetPool

func SetPool(p *pool.Pool)

SetPool wires in the agent subprocess pool.

func SetResourceGuard added in v1.2.9

func SetResourceGuard(g *resourceguard.Guard)

SetResourceGuard installs the watchdog the Resources page reports on.

func SetResourceHistory added in v0.39.0

func SetResourceHistory(h *memreport.History)

SetResourceHistory installs the buffer the API reads from. Called once from server startup, alongside the sampler that fills it.

func SetSkillStore added in v0.17.0

func SetSkillStore(s *skills.Store)

SetSkillStore wires the skills ownership store so delete/upload/sync handlers can enforce owner-or-admin access control.

func SetSpawnLogger

func SetSpawnLogger(s *provider.SpawnLogger)

SetSpawnLogger wires in the per-spawn jsonl writer/reader. The Providers page reads from it via List + Read; the pool factory already writes through it.

func SetSyncManager added in v0.11.0

func SetSyncManager(m *providersync.Manager)

SetSyncManager wires the provider storage sync manager.

func SetTagsService added in v0.17.0

func SetTagsService(svc *tags.Service)

SetTagsService wires the tags service for skill ownership checks.

func SetTeam added in v1.2.9

func SetTeam(s *team.Service)

SetTeam wires the Agents-app store.

func SetTeamHub added in v1.2.9

func SetTeamHub(f func() *teamlink.Hub)

SetTeamHub hands the Hub accessor to the HTTP handlers.

func SetTicketAPIAuth added in v1.2.9

func SetTicketAPIAuth(tokens TokenAuthenticator, users UserLookup)

SetTicketAPIAuth wires the token authenticator used by the ticket REST surface. Called once at boot; leaving it unset simply means the API stays cookie-only, which is the pre-integration behaviour.

func SetTicketDispatcher added in v1.2.9

func SetTicketDispatcher(d *ticket.Dispatcher)

SetTicketDispatcher installs the dispatcher used for test deliveries and the delivery log. The same value is registered as the ticket emitter.

func SetWorkflowEncService added in v0.16.0

func SetWorkflowEncService(s *enc.Service)

SetWorkflowEncService wires the cipher used by the env save handler.

func SetWorkflowManager added in v0.13.0

func SetWorkflowManager(m *setup.Manager)

SetWorkflowManager wires in the workflow Manager constructed by server.go. After the JSON migration, workflow body is DB-primary — no file→DB importer runs here.

func TeamAgentOf added in v1.2.9

func TeamAgentOf(ctx context.Context, sessionID string) string

TeamAgentOf returns the Team agent a session belongs to, "" for none.

func TeamAgentOps added in v1.2.9

func TeamAgentOps() teamagents.Ops

TeamAgentOps is the late-bound accessor the connector registers with; nil until the Team service is wired.

func TeamSubagentsChanged added in v1.2.9

func TeamSubagentsChanged(parentSessionID string)

TeamSubagentsChanged signals the roster of the agent whose main chat is parentSessionID that its background sub-agents started or ended, so the card's "sub-agent working" state follows them without a poll: the agent's own turn is long over by then and no activity event would say so. Any other session is ignored.

func TicketAPIAuthMW added in v1.2.9

func TicketAPIAuthMW(next http.Handler) http.Handler

ticketAPIAuthMW lets a Personal Access Token stand in for the session cookie on the ticket REST endpoints.

Why a dedicated middleware rather than teaching login.Session about bearers: the cookie is the browser's credential for the WHOLE app, and making every page token-authable would widen the attack surface for a feature only the ticket API needs. It is mounted on the /api shim only (see TicketRESTShim) — a bearer works nowhere else; /tools/ stays cookie-only.

A cookie session already in context wins — a browser request carrying a stale Authorization header should not be downgraded to whatever that token maps to. It must run BEFORE RequireToolAccess: that middleware rejects a request with no user in context, so a bearer-only caller has to be resolved into a user first or it never reaches the handler.

func TicketRESTShim added in v1.2.9

func TicketRESTShim(gated http.Handler) http.Handler

TicketRESTShim serves the ticket REST API at TicketRESTBase by rewriting the path onto the tool-internal prefix and handing the request to the same gated chain mounted at /tools/ — bearer auth, tool access, and per-project checks all apply unchanged.

A path outside the token allowlist answers JSON 404 instead of falling through to cookie auth: everything under /api is a machine caller, and a machine must never be answered with a login redirect.

func TrackTeamAgentChange added in v1.2.9

func TrackTeamAgentChange(ctx context.Context, agentID string) func()

TrackTeamAgentChange is agentChangeHook for writes made outside the team store — the admin page's share tags. Call the result once the write is saved.

func WithTicketStreamSignal added in v1.2.9

func WithTicketStreamSignal(next ticket.Emitter) ticket.Emitter

WithTicketStreamSignal wraps the process-wide ticket emitter so every ticket write also signals open boards. Pass the result to ticket.SetEmitter.

func WorkflowEventHook added in v0.13.0

func WorkflowEventHook(b *Broadcaster) func(id, runID string, ev wf.RunEvent)

WorkflowEventHook builds an engine.OnEvent callback that fans workflow run events out to the SSE broadcaster.

func WorkflowSSESession added in v0.13.0

func WorkflowSSESession(id string) string

WorkflowSSESession returns the broadcaster session key used for workflow run events.

Types

type AIRouterChoiceDTO added in v0.31.0

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

AIRouterChoiceDTO is one selectable router backend.

type AIRouterDetailDTO added in v0.31.0

type AIRouterDetailDTO struct {
	Supported bool                `json:"supported"`
	Enabled   bool                `json:"enabled"`
	Provider  string              `json:"provider"`
	Routers   []AIRouterChoiceDTO `json:"routers"`
	Models    map[string]string   `json:"models"`
	KeySet    bool                `json:"key_set"`
	RawConfig string              `json:"raw_config"`
	// Preview is the effective config wick injects at spawn for the current
	// saved settings — env vars (claude) or -c overrides (codex), one per line,
	// secret values masked. Shown read-only in the Advanced section so the user
	// can see exactly what gets set (and which keys to override via RawConfig).
	Preview string `json:"preview"`
}

AIRouterDetailDTO carries the instance's current AI-router settings so the detail page can seed its widget. The API key is never returned — only a flag indicating one is stored. Routers lists the available backends to pick from.

type AccountQuota added in v1.2.9

type AccountQuota struct {
	Provider string
	// Supported is false for provider types with no usage API at all
	// (gemini, wick). Reason says so in words a caller can print.
	Supported bool
	Reason    string

	Connected  bool
	Plan       string
	Org        string
	AuthMethod string
	ExpiresAt  time.Time

	Windows []AccountQuotaWindow

	// FetchedAt is when the reading was taken — never omitted, because a
	// cached number passed off as live is how a stale quota gets acted on.
	FetchedAt time.Time
	// Pending: no reading yet, one is queued behind the pacing gate.
	Pending bool
	// Checking: a probe is in flight right now.
	Checking bool
	// NextAt is the earliest a manual re-check would be accepted. The
	// panel shows it as a countdown; a caller that knows it will not ask
	// again before then.
	NextAt time.Time
	// Err is a failed probe (expired token, rate limit), reported as
	// itself rather than as an empty set of windows.
	Err string
}

AccountQuota is the whole reading for one provider instance.

func ProviderAccountQuota added in v1.2.9

func ProviderAccountQuota(ctx context.Context, key string) (AccountQuota, bool)

ProviderAccountQuota reads the cached quota for a provider key ("claude/default"). ok is false when no such provider exists.

Never forces a probe: it serves what the cache knows and lets the background refresh do the rest.

type AccountQuotaWindow added in v1.2.9

type AccountQuotaWindow struct {
	Key         string
	Utilization float64
	ResetsAt    time.Time
	ObservedAt  time.Time
}

AccountQuotaWindow is one rate-limit window of an account.

type ActionButton added in v1.2.9

type ActionButton = actioncard.Button

ActionCard and ActionButton are the fence schema (package actioncard, shared with the chat channels that render cards without the web UI).

type ActionCard added in v1.2.9

type ActionCard = actioncard.Card

ActionCard and ActionButton are the fence schema (package actioncard, shared with the chat channels that render cards without the web UI).

type AgentA2AStatus added in v1.2.9

type AgentA2AStatus struct {
	Enabled        bool       `json:"enabled"`
	PublicCard     bool       `json:"public_card"`
	AllowedCallers []string   `json:"allowed_callers"`
	KeySet         bool       `json:"key_set"`
	KeyHint        string     `json:"key_hint,omitempty"`
	RotatedAt      *time.Time `json:"rotated_at,omitempty"`
	EndpointURL    string     `json:"endpoint_url"`
	CardURL        string     `json:"card_url"`
	APIKey         string     `json:"api_key,omitempty"`
}

AgentA2AStatus is GET /api/team/agents/{id}/a2a. APIKey is set only in the response that minted the key; nothing else ever carries it.

type AgentProfileItem added in v0.36.0

type AgentProfileItem struct {
	ID string `json:"id"`
	// ProjectID is the scope. Empty = global; non-empty = owned by that
	// project and invisible elsewhere.
	ProjectID          string   `json:"project_id"`
	Key                string   `json:"key"`
	Name               string   `json:"name"`
	Description        string   `json:"description"`
	Icon               string   `json:"icon"`
	Provider           string   `json:"provider"`
	Model              string   `json:"model"`
	SystemPrompt       string   `json:"system_prompt"`
	AllowedTagIDs      []string `json:"allowed_tag_ids"`
	AllowedNativeTools []string `json:"allowed_native_tools"`
	StrictMCP          bool     `json:"strict_mcp"`
	DefaultMaxTurns    int      `json:"default_max_turns"`
	CanDelegate        bool     `json:"can_delegate"`
	AllowTakeOver      bool     `json:"allow_take_over"`
	Disabled           bool     `json:"disabled"`
	// Locked freezes the role: no edit, no delete, from any surface. Only
	// this UI can clear it — MCP may set it, never unset it.
	Locked bool `json:"locked"`
}

AgentProfileItem is one sub-agent role as the admin UI sees it.

type AgentRESTStatus added in v1.2.9

type AgentRESTStatus struct {
	Enabled   bool   `json:"enabled"`
	BaseURL   string `json:"base_url"`
	Model     string `json:"model"`
	TokensURL string `json:"tokens_url"`
}

AgentRESTStatus is GET /api/team/agents/{id}/rest. It never carries a token: the connection authenticates with the caller's own Personal Access Token, minted on TokensURL.

type AgentSlackInstantStatus added in v1.2.9

type AgentSlackInstantStatus struct {
	Enabled       bool     `json:"enabled"`
	SharedChannel string   `json:"shared_channel,omitempty"`
	BoundChannels []string `json:"bound_channels"`
	PrefixEnabled bool     `json:"prefix_enabled"`
	Username      string   `json:"username"`
	AvatarReady   bool     `json:"avatar_ready"`
	SharedOnline  bool     `json:"shared_online"`
	// CustomizeScope is "ok", "missing" or "unknown" (bot offline / Slack
	// unreachable) for chat:write.customize.
	CustomizeScope string   `json:"customize_scope"`
	Warnings       []string `json:"warnings"`
}

AgentSlackInstantStatus is GET /api/team/agents/{id}/slack/instant. The avatar token is never part of it.

type AgentSlackSettings added in v1.2.9

type AgentSlackSettings struct {
	Fields      []agentSlackField `json:"fields"`
	OwnerID     string            `json:"owner_slack_id,omitempty"`
	OwnerName   string            `json:"owner_slack_name,omitempty"`
	OwnerHandle string            `json:"owner_slack_handle,omitempty"`
}

AgentSlackSettings is GET /api/team/agents/{id}/slack/settings.

type AgentSlackStatus added in v1.2.9

type AgentSlackStatus struct {
	Connected  bool            `json:"connected"`
	Online     bool            `json:"online"`
	Mode       string          `json:"mode"`
	BotID      string          `json:"bot_id,omitempty"`
	BotName    string          `json:"bot_name,omitempty"`
	TeamName   string          `json:"team_name,omitempty"`
	DMMainChat bool            `json:"dm_main_chat"`
	AppID      string          `json:"app_id,omitempty"`
	Secrets    map[string]bool `json:"secrets"`
	Disabled   bool            `json:"disabled"`
}

AgentSlackStatus is GET /api/team/agents/{id}/slack. Secrets are only ever reported as set or not.

type AgentTelegramStatus added in v1.2.9

type AgentTelegramStatus struct {
	Connected   bool   `json:"connected"`
	Online      bool   `json:"online"`
	BotID       string `json:"bot_id,omitempty"`
	BotUsername string `json:"bot_username,omitempty"`
	Link        string `json:"link,omitempty"`
	Disabled    bool   `json:"disabled"`
}

AgentTelegramStatus is GET /api/team/agents/{id}/telegram. The bot token is never part of it, not even masked.

type BoardItem added in v0.36.0

type BoardItem struct {
	ID           string                   `json:"id"`
	Key          string                   `json:"key"`
	Name         string                   `json:"name"`
	Description  string                   `json:"description"`
	Columns      []delegation.BoardColumn `json:"columns"`
	SquadKey     string                   `json:"squad_key,omitempty"`
	GateMode     string                   `json:"gate_mode"`
	AutoDelegate bool                     `json:"auto_delegate"`
	Disabled     bool                     `json:"disabled"`
}

BoardItem is one board as the UI sees it.

type Broadcaster

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

Broadcaster fans out agent events to all subscribed SSE connections. Subscribe returns a receive channel and an unsub func. Publish is called from ClaudeFactory.OnEvent on every AgentEvent.

subs is keyed by sessionID ("" = global subscribers that receive all events). Channels are buffered at 64 so a slow client never stalls the agent reader goroutine.

func NewBroadcaster

func NewBroadcaster() *Broadcaster

NewBroadcaster returns a ready Broadcaster.

func (*Broadcaster) ForgetGitStatus added in v1.2.9

func (b *Broadcaster) ForgetGitStatus(sessionID string)

ForgetGitStatus drops a session's cached payload — called when its watcher stops, so the cache tracks live sessions only.

func (*Broadcaster) HasSubscribers added in v0.38.0

func (b *Broadcaster) HasSubscribers(sessionID string) bool

HasSubscribers reports whether any SSE connection is currently watching sessionID. Global ("") subscribers count too: the sidebar stream renders approval prompts as well, so a user sitting on the session list is still able to answer one.

Used by the approval gate to decide whether a prompt still has a human behind it. Liveness is only as fresh as the SSE keepalive (15s in serveStream) — a tab closed abruptly stays counted until the next keepalive write fails and the handler unsubscribes.

func (*Broadcaster) LastGitStatus added in v1.2.9

func (b *Broadcaster) LastGitStatus(sessionID string) (string, bool)

LastGitStatus returns the most recent git_status payload for a session, for replaying state to a subscriber that joined after it was published.

func (*Broadcaster) Publish

func (b *Broadcaster) Publish(sessionID, agentName string, ev event.AgentEvent)

Publish fires ev to all subscribers of sessionID and all global ("") subscribers. Non-blocking: a full channel's event is dropped rather than blocking.

func (*Broadcaster) PublishApprovalRequest

func (b *Broadcaster) PublishApprovalRequest(sessionID string, req gate.ApprovalRequest)

PublishApprovalRequest fires when the gate binary dials the daemon socket with an unrecognised command. Browsers render this as a modal with 4 decision buttons (approve_once / approve_session / approve_always / block); the user's pick rides back through POST /approve.

Data is the JSON-encoded ApprovalRequest so the front-end can decode it once and use every field (cmd, work_dir, match_key, ...).

func (*Broadcaster) PublishApprovalResolved

func (b *Broadcaster) PublishApprovalResolved(sessionID, requestID, decision string)

PublishApprovalResolved fires once a decision is delivered (UI click, timeout, or listener close). Browsers use this to dismiss any open modal across all tabs subscribed to the session.

func (*Broadcaster) PublishAskUser

func (b *Broadcaster) PublishAskUser(sessionID, agentName string, payload []byte)

PublishAskUser fires when the ask_user MCP tool is invoked by an agent. Front-end renders an inline card with options + freeform input; user's pick rides back through POST /answer. Data is the JSON-encoded request body so every field (question, options, allow_freeform, ...) round-trips exactly once.

func (*Broadcaster) PublishAskUserResolved

func (b *Broadcaster) PublishAskUserResolved(sessionID, requestID string)

PublishAskUserResolved fires once an ask_user request resolves (UI answer or timeout). Used by the UI to dismiss the inline card across all tabs subscribed to the session.

func (*Broadcaster) PublishConnectorRun added in v0.35.0

func (b *Broadcaster) PublishConnectorRun(sessionID, runID, connectorID, opKey, status string, running bool)

PublishConnectorRun broadcasts the start/finish of a connector run to a session's subscribers so the conversation UI can show a per-run Cancel button on an in-flight tool call. running=true is the start (status "running"), carrying the run_id + connector_id the FE needs to hit the cancel route; running=false is the terminal update carrying the final status so the FE drops the button. Wired from connectors.Service via SetRunObserver.

func (*Broadcaster) PublishGitStatusJSON added in v0.15.5

func (b *Broadcaster) PublishGitStatusJSON(sessionID, jsonPayload string)

PublishGitStatusJSON broadcasts a pre-marshalled git_status payload to a session's subscribers. The payload is the full repo+status snapshot (built by the fs watcher) so the FE updates entirely from the event — no follow-up fetch, hence no polling. The marshalling lives in the caller (scm_watch.go) to avoid an import cycle on the scm types.

func (*Broadcaster) PublishLifecycle

func (b *Broadcaster) PublishLifecycle(ctx context.Context, sessionID, agentName, lifecycle, provider string, pid int)

PublishLifecycle pushes a lifecycle transition (Spawning, Killed) to subscribers. Idle/Working transitions are inferred from AgentEvent flow on the client side; only the bookend transitions — which never carry an AgentEvent — go through this channel. PublishLifecycle takes the spawn-time ctx so the broadcast log line carries the originating request_id (set by the HTTP middleware) when the spawn came from an HTTP path. Pass context.Background() when no spawn ctx is in scope.

func (*Broadcaster) PublishPoolStats added in v0.15.2

func (b *Broadcaster) PublishPoolStats(active, max, queueLen int, procs []LiveProcessEntry)

PublishPoolStats broadcasts a pool_stats event to all global SSE subscribers (sessionID == ""). Called after every lifecycle transition so the Providers page stays live.

func (*Broadcaster) PublishRaw added in v0.13.4

func (b *Broadcaster) PublishRaw(sessionID, agentName, evType, data string)

func (*Broadcaster) PublishSessionMeta added in v0.17.0

func (b *Broadcaster) PublishSessionMeta(sessionID, title string, titleCustom bool, status string)

PublishSessionMeta broadcasts a session's current title + status so open tabs update the header/sidebar live — no page reload. Fired after session meta changes (wick_set_title, status transitions), including changes that originated in a sibling stdio process and were relayed in via the agentctl refresh_session op.

func (*Broadcaster) PublishSystemTurn added in v0.13.4

func (b *Broadcaster) PublishSystemTurn(sessionID, agentName, text string, steps []string)

PublishSystemTurn fires a system_turn event so the UI can append it to the conversation without a page reload. Data is JSON with text + steps so the front-end can render the pill + checklist inline.

func (*Broadcaster) PublishUserMessage added in v0.29.0

func (b *Broadcaster) PublishUserMessage(sessionID, agentName, source, text string, sender *store.Sender)

PublishUserMessage fires a user_message event so connected web viewers render a user turn injected from a NON-web source (a channel or the schedule runner) live, instead of only after a manual refresh. Without this the SSE stream carries only the assistant reply, so the incoming user turn silently goes missing until a refetch. Data is JSON with the text + source so the UI can badge where the message came from, plus the resolved sender (when the channel had one) so the live chip names the same person a reloaded turn does.

func (*Broadcaster) Subscribe

func (b *Broadcaster) Subscribe(sessionID string) (<-chan Event, func())

Subscribe registers a listener for a specific session (or "" for all). The caller must call the returned unsub func when the SSE connection closes.

type CaptainOps added in v1.2.9

type CaptainOps struct{}

CaptainOps implements the agents.* connector (teamagents.Ops). Every op resolves the calling agent from the SESSION, requires its "Manage other agents" permission and acts on its owner's agents only.

func (CaptainOps) Create added in v1.2.9

func (o CaptainOps) Create(ctx context.Context, sessionID string, in teamagents.CreateInput) (any, error)

Create implements agents.create: a new agent with no access at all. Suggested access becomes one approval request on the manager's chat.

func (CaptainOps) List added in v1.2.9

func (o CaptainOps) List(ctx context.Context, sessionID string) (any, error)

List implements agents.list.

func (CaptainOps) Schedule added in v1.2.9

func (o CaptainOps) Schedule(ctx context.Context, sessionID string, in teamagents.ScheduleInput) (any, error)

Schedule implements agents.schedule: the Captain works another agent's Scheduled drawer when that agent's captain_can.routines allows it. Like update_persona it applies at once, and every change is announced in the target agent's main chat so the owner sees who moved what.

func (CaptainOps) SetAccess added in v1.2.9

func (o CaptainOps) SetAccess(ctx context.Context, sessionID string, in teamagents.AccessInput) (any, error)

SetAccess implements agents.set_access: it only ever files a proposal.

func (CaptainOps) UpdatePersona added in v1.2.9

func (o CaptainOps) UpdatePersona(ctx context.Context, sessionID string, in teamagents.PersonaInput) (any, error)

UpdatePersona implements agents.update_persona.

type CardState added in v1.2.9

type CardState struct {
	// TurnID is the assistant turn with the newest version. A fence with
	// this id in any other turn is superseded.
	TurnID string `json:"turn_id"`
	// Locked: clicked since the newest version was written, or Final.
	Locked bool `json:"locked"`
	// Postback is the click that locked it, and PostbackTurnID its turn.
	Postback       *store.Postback `json:"postback,omitempty"`
	PostbackTurnID string          `json:"postback_turn_id,omitempty"`
	// contains filtered or unexported fields
}

CardState is what the thread says about one card id, computed from the whole conversation so the UI does not have to: which turn holds its current version, and whether its buttons still take a click.

type ComposerCommand added in v0.30.0

type ComposerCommand struct {
	ID       string `json:"id"`
	Label    string `json:"label"`
	Hint     string `json:"hint,omitempty"`
	Category string `json:"category,omitempty"`
	// Action is an id the FE resolves to a handler (e.g. "switch:provider",
	// "panel:process", "view:commands"). Empty for insert-type entries.
	Action string `json:"action,omitempty"`
	// Insert is the text placed after `/` for insert-type entries (skills).
	Insert string `json:"insert,omitempty"`
}

ComposerCommand is one entry in the composer's `/` menu. It is intentionally data-only: the FE maps Action ids to local handlers (opening a panel, switching provider, changing the view) — those live in the FE because they are UI actions. Skills carry no Action; the FE inserts `/`+Insert instead.

To add a new `/` command that reuses an existing FE action, add an entry here with a known Action id — no FE change needed. A genuinely new behaviour needs one new handler in the FE action map.

type ComposerCommandsResponse added in v0.30.0

type ComposerCommandsResponse struct {
	Commands []ComposerCommand `json:"commands"`
}

ComposerCommandsResponse is the envelope for GET /api/composer/commands.

type ComposerUsageRefreshResponse added in v1.2.9

type ComposerUsageRefreshResponse struct {
	Accepted bool `json:"accepted"`
	Checking bool `json:"checking"`
	WaitS    int  `json:"wait_s,omitempty"`
	// Supported=false for a provider type with no usage API — there is
	// nothing to re-check.
	Supported bool `json:"supported"`
}

ComposerUsageRefreshResponse is POST /api/composer/usage/refresh.

accepted=false is not an error: the cache declined because a probe now would land inside a cooldown (its own floor, or one the upstream asked for). WaitS says how long, so the popover explains the wait instead of looking broken — and so nobody learns to click it repeatedly.

type ComposerUsageResponse added in v1.2.9

type ComposerUsageResponse struct {
	Provider string `json:"provider"`
	// Supported is false for provider types with no usage API at all
	// (codex, gemini, wick today). Reason says so in words the popover
	// can print verbatim.
	Supported bool   `json:"supported"`
	Reason    string `json:"reason,omitempty"`

	Account *composerUsageAccount `json:"account,omitempty"`
	Windows []usageWindowDTO      `json:"windows,omitempty"`

	// Err is a failed probe (expired token, rate limit) — shown as text,
	// never as an empty set of bars.
	Err string `json:"error,omitempty"`
	// Pending: no reading yet, one is queued behind the pacing gate.
	Pending bool `json:"pending,omitempty"`
	// Checking: a probe is in flight right now.
	Checking bool `json:"checking,omitempty"`

	FetchedAt string `json:"fetched_at,omitempty"`
	AgeS      int    `json:"age_s,omitempty"`
	NextS     int    `json:"next_s,omitempty"`

	// CanManage tells the popover whether to offer Re-check.
	CanManage bool `json:"can_manage"`

	// Accounts is one row per account of a multi-account instance (omp's
	// credential pool, opencode's account folders), each with its own
	// windows out of the SAME cached probe — never a request per row.
	// Empty for single-account types, where Account + Windows say it all.
	Accounts []composerUsageAccountRow `json:"accounts,omitempty"`
	// Rotation names who picks the account when the session is on Auto:
	// "omp" (omp rotates natively) or "wick" (wick moves to the next
	// opencode folder on a quota error). "" when the session is pinned.
	Rotation string `json:"rotation,omitempty"`
}

ComposerUsageResponse is GET /api/composer/usage.

type ConfigFieldDTO added in v0.19.0

type ConfigFieldDTO struct {
	Key         string `json:"key"`
	Value       string `json:"value"`
	Type        string `json:"type"`
	Options     string `json:"options,omitempty"`
	IsSecret    bool   `json:"is_secret"`
	Description string `json:"description,omitempty"`
	Required    bool   `json:"required"`
}

ConfigFieldDTO is one config row for the detail page (secret values masked).

type DefaultModelDTO added in v0.35.0

type DefaultModelDTO struct {
	ID   string `json:"id"`
	Desc string `json:"desc,omitempty"`
}

DefaultModelDTO is one catalog seed model surfaced to the detail page's "Load defaults" button — id plus its description.

type DelegationStream added in v0.36.0

type DelegationStream struct {
	Bcast *Broadcaster
}

DelegationStream adapts the SSE Broadcaster to the delegation package's EventStream interface, so a waiting delegation.Run observes exactly the same normalized event flow the UI does — one source of truth for "what did this agent do", rather than a second tap into the provider stream that could drift from it.

func NewDelegationStream added in v0.36.0

func NewDelegationStream(b *Broadcaster) *DelegationStream

NewDelegationStream wraps a live broadcaster.

func (*DelegationStream) SubscribeSession added in v0.36.0

func (d *DelegationStream) SubscribeSession(sessionID string) (<-chan delegation.StreamEvent, func())

SubscribeSession bridges one session's event channel, translating the SSE wire shape back into the typed events the turn counter reads.

type Event

type Event struct {
	SessionID string `json:"session_id"`
	AgentName string `json:"agent_name"`
	Type      string `json:"type"`
	Data      string `json:"data"`
	// Raw is the verbatim provider line, carried IN-MEMORY for the
	// delegation bridge and never serialized to browser subscribers
	// (hence json:"-"): token usage and the provider's own turn count
	// (num_turns) only exist here. Dropping it at this hop was why a
	// sub-agent's spend read tokens_used:0 and a 49-call run billed
	// turns_used:0 — every cap keyed on usage was flying blind.
	Raw string `json:"-"`
	// ToolName, ToolInput, ToolUseID are populated for tool_use events;
	// ToolUseID and IsError are also set for tool_result events.
	ToolName  string `json:"tool_name,omitempty"`
	ToolInput string `json:"tool_input,omitempty"`
	ToolUseID string `json:"tool_use_id,omitempty"`
	IsError   bool   `json:"is_error,omitempty"`
	PID       int    `json:"pid,omitempty"`
	Lifecycle string `json:"lifecycle,omitempty"`
	// SubAgent carries a DELEGATED lifecycle attributed to the session in
	// SessionID — set when a sub-agent of that conversation transitioned,
	// not the conversation's own process. Kept separate from Lifecycle so
	// a child's work can never be mistaken for the leader's, and so a
	// subscriber can render both at once. Sidebar-stream only.
	SubAgent string `json:"sub_agent,omitempty"`
	// At / EndAt carry Unix ms timestamps for tool_use/tool_result events
	// so the UI can show "started HH:MM:SS, took Ns".
	At    int64 `json:"at,omitempty"`
	EndAt int64 `json:"end_at,omitempty"`
	// ContextUsed is how full the window was for the request this frame
	// came from — a mid-turn reading, so the meter beside the composer
	// moves while a long turn is running instead of after it. Carried on
	// whatever event happened to be the one that knew (see
	// event.AgentEvent.ContextUsed); 0 means this event said nothing
	// about the window.
	ContextUsed int `json:"context_used,omitempty"`
}

Event is one SSE payload pushed to browser subscribers. Type distinguishes agent stream events ("text_delta", "tool_use", ...) from lifecycle events ("lifecycle"); the latter carry PID + lifecycle label in Data so the UI can update the status badge without re-fetching the page.

func (Event) JSON

func (e Event) JSON() string

type GateStatus

type GateStatus struct {
	Enabled bool
	Binary  string // absolute path
	Source  string // gate.Source* constant
	Reason  string // populated when Enabled=false
}

GateStatus is the boot-time snapshot of the command gate. Populated once during server.go startup and read by the Providers page so operators can tell at a glance whether the gate sidecar is wired up.

Enabled=false means ResolveGateBinary returned an error — every command will hit fail-safe block at the matcher / no-socket path, except whitelist matches. Reason carries the error message so the UI can show actionable guidance (run `wick build`).

func GetGateStatus

func GetGateStatus() GateStatus

GetGateStatus is the read side. Returns a zero value when boot hasn't reached SetGateStatus yet.

type GateStatusDTO added in v0.19.0

type GateStatusDTO struct {
	Enabled        bool   `json:"enabled"`
	Binary         string `json:"binary"`
	Source         string `json:"source"`
	Reason         string `json:"reason,omitempty"`
	Note           string `json:"note"`
	PermissionMode string `json:"permission_mode"`
	BypassLocked   bool   `json:"bypass_locked"`
}

GateStatusDTO is the gate policy state.

type GitStatusSnapshot added in v0.15.5

type GitStatusSnapshot struct {
	Repos    []RepoSummary               `json:"repos"`
	Statuses map[string]scm.StatusResult `json:"statuses"`
	// Active is the repo this session works in, resolved server-side from
	// session meta (empty only when the cwd holds no repo). It travels
	// with the snapshot so every reader — panel, rail badge, agent —
	// names the SAME repo. The badge used to derive this from the
	// browser's own storage and disagreed with the panel next to it.
	Active         string `json:"active"`
	ActiveExplicit bool   `json:"active_explicit"`
	TotalChanged   int    `json:"total_changed"`
}

GitStatusSnapshot is the full session-wide git state pushed over SSE (git_status event) AND returned by GET /git/repos. The FE renders entirely from this — repos for the switcher, statuses[rel] for the changes list of each repo — so a change event needs no follow-up fetch (zero polling).

type HookCapabilityDTO added in v0.19.0

type HookCapabilityDTO struct {
	Supported bool   `json:"supported"`
	Verified  bool   `json:"verified"`
	ProbedAt  string `json:"probed_at,omitempty"`
	Error     string `json:"error,omitempty"`
	Scope     string `json:"scope,omitempty"`
}

HookCapabilityDTO is the per-event hook capability state for one provider.

type IdleCompactDTO added in v1.2.9

type IdleCompactDTO struct {
	Seconds int    `json:"seconds"`
	Trigger string `json:"trigger"`
	// Threshold is a percentage or a token count, by Trigger.
	Threshold int `json:"threshold"`
	// Scope is skip, whitelist or all; Match its pattern lines.
	Scope string   `json:"scope"`
	Match []string `json:"match,omitempty"`
}

IdleCompactDTO is an enabled idle-compact policy with defaults filled in.

type IncidentSummary added in v0.36.1

type IncidentSummary struct {
	Status        string `json:"status"`
	Iteration     int    `json:"iteration"`
	Summary       string `json:"summary"`
	StopReason    string `json:"stop_reason,omitempty"`
	EvidenceCount int    `json:"evidence_count"`
}

IncidentSummary is the compact incident header the rail shows above the agent list. Deliberately not the whole record: the panel answers "is this an investigation, and how is it going", and the full state belongs to whoever opens it.

type LiveProcessDTO added in v0.19.0

type LiveProcessDTO struct {
	SessionID string `json:"session_id"`
	AgentName string `json:"agent_name"`
	PID       int    `json:"pid"`
	Lifecycle string `json:"lifecycle"`
	Substate  string `json:"substate"`
}

LiveProcessDTO is one active spawn entry.

type LiveProcessEntry added in v0.15.2

type LiveProcessEntry struct {
	SessionID string `json:"session_id"`
	AgentName string `json:"agent_name"`
	Provider  string `json:"provider,omitempty"` // "type/name"
	PID       int    `json:"pid,omitempty"`
	Queued    int    `json:"queued,omitempty"` // messages waiting after current turn
	Alive     bool   `json:"alive"`            // false only for a genuinely dead process (zombie). Respawn-mode idle-between-turns is alive.
	Lifecycle string `json:"lifecycle"`
	Substate  string `json:"substate,omitempty"`
}

LiveProcessEntry is one row in PoolStatsPayload.

type LogRefDTO added in v0.32.0

type LogRefDTO struct {
	Prefix string `json:"prefix"`
	Path   string `json:"path"`
}

LogRefDTO is one process log file relevant to a spawn: its component name (server/daemon/…) and absolute path.

type LogTailResponse added in v0.32.0

type LogTailResponse struct {
	Name      string `json:"name"`
	Path      string `json:"path"`
	Size      int64  `json:"size"`
	Content   string `json:"content"`
	Truncated bool   `json:"truncated"` // older bytes dropped to fit the byte cap
	Modified  string `json:"modified"`
}

LogTailResponse is the JSON envelope for GET /api/providers/logs/{file}.

type LoginTTYSessionDTO added in v1.2.9

type LoginTTYSessionDTO struct {
	ID         string `json:"id"`
	State      string `json:"state"`
	RemainingS int    `json:"remaining_s"`
	CapS       int    `json:"cap_s"`
}

LoginTTYSessionDTO is the running-session view for the SPA.

type LoginTTYStatusResponse added in v1.2.9

type LoginTTYStatusResponse struct {
	Supported   bool                `json:"supported"`
	Account     logintty.Account    `json:"account"`
	Session     *LoginTTYSessionDTO `json:"session,omitempty"`
	DefaultTTLS int                 `json:"default_ttl_s"`
	ExtendS     int                 `json:"extend_s"`
	MaxTTLS     int                 `json:"max_ttl_s"`
	// LoginChoices is the picker shown before Login for types whose login
	// needs a provider choice (omp, opencode). Empty = no picker.
	LoginChoices []logintty.LoginChoice `json:"login_choices,omitempty"`
	// LoginNote is a caveat shown beside the picker (opencode: Claude
	// subscriptions unsupported).
	LoginNote string `json:"login_note,omitempty"`
	// AccountStore names where this instance's single account lives (omp
	// profile / opencode data dir), so the card can show it.
	AccountStore string `json:"account_store,omitempty"`
	// Accounts is the instance's credential pool (omp: several accounts
	// per profile, rotated on usage limits). Empty for other types.
	Accounts []logintty.PoolAccount `json:"accounts,omitempty"`
	// APIKeys are the API-key login choices (omp/opencode), each marked
	// set when the instance Env already carries its var.
	APIKeys []logintty.APIKeyProvider `json:"api_keys,omitempty"`
	// AuthFrom is the instance whose login this one uses (omp/opencode
	// shared login); account and usage above are that owner's, and the
	// card hides login / logout / add-account.
	AuthFrom string `json:"auth_from,omitempty"`
}

LoginTTYStatusResponse is GET /api/providers/{type}/{name}/logintty: whether reconnect is available for this type, who is currently connected per the credential files, and the live session if any.

type MCPClientDTO added in v0.19.0

type MCPClientDTO struct {
	ID          string `json:"id"`
	Label       string `json:"label"`
	Detected    bool   `json:"detected"`
	Installed   bool   `json:"installed"`
	Blocklisted bool   `json:"blocklisted"`
	ConfigPath  string `json:"config_path"`
}

MCPClientDTO is one MCP client install state.

type MCPStatusDTO added in v0.19.0

type MCPStatusDTO struct {
	AppName string         `json:"app_name"`
	Clients []MCPClientDTO `json:"clients"`
}

MCPStatusDTO is the aggregate MCP Wick card state.

type ManagedBinaryDTO added in v1.2.9

type ManagedBinaryDTO struct {
	managedbin.Status
	Enabled bool `json:"enabled"`
	// SessionsOnOld counts running processes per non-current version —
	// "2 sessions still on v18.4.2".
	SessionsOnOld map[string]int `json:"sessions_on_old,omitempty"`
}

ManagedBinaryDTO is one managed type's status.

type MonitorAgent added in v0.36.0

type MonitorAgent struct {
	SessionID    string `json:"session_id"`
	AgentName    string `json:"agent_name"`
	ProviderType string `json:"provider_type"`
	ProviderName string `json:"provider_name"`
	PID          int    `json:"pid"`
	Lifecycle    string `json:"lifecycle"`
	Substate     string `json:"substate"`
	Queued       int    `json:"queued"`
	LastActive   string `json:"last_active,omitempty"`
	// Status is the UI badge: running | idle | spawning | dead.
	Status string `json:"status"`
	// IsSubAgent marks a process that belongs to a delegation rather than
	// a human-facing conversation.
	IsSubAgent bool   `json:"is_sub_agent"`
	ProfileKey string `json:"profile_key,omitempty"`
	// DelegationID lets the UI offer Stop for a sub-agent row.
	DelegationID string `json:"delegation_id,omitempty"`
	RootID       string `json:"root_id,omitempty"`
}

MonitorAgent is one live agent process in the fleet view.

type MonitorTree added in v0.36.0

type MonitorTree struct {
	RootID     string `json:"root_id"`
	RootTask   string `json:"root_task"`
	SubAgents  int    `json:"sub_agents"`
	TurnsUsed  int    `json:"turns_used"`
	TokensUsed int    `json:"tokens_used,omitempty"`
	CostUSD    string `json:"cost_usd,omitempty"`
	Active     int    `json:"active"`
	StartedAt  string `json:"started_at,omitempty"`
	ElapsedSec int    `json:"elapsed_sec"`
	Status     string `json:"status"`
}

MonitorTree summarises one delegation tree. Cheap cost signals — total turns, wall-clock, how many sub-agents — so a tree that is running away is obvious at a glance even before token accounting exists.

type OverviewActiveDTO added in v0.19.0

type OverviewActiveDTO struct {
	SessionID string `json:"session_id"`
	Label     string `json:"label"`
	Lifecycle string `json:"lifecycle"`
	PID       int    `json:"pid,omitempty"`
	ProjectID string `json:"project_id"`
}

OverviewActiveDTO is one row in the active sessions panel returned by /api/overview.

type OverviewDTO added in v0.19.0

type OverviewDTO struct {
	Queued []OverviewQueuedDTO `json:"queued"`
	Active []OverviewActiveDTO `json:"active"`
	Stats  OverviewStatsDTO    `json:"stats"`
}

OverviewDTO is the JSON body returned by GET /api/overview.

type OverviewQueueReasonDTO added in v1.2.9

type OverviewQueueReasonDTO struct {
	Kind   string    `json:"kind"`
	Detail string    `json:"detail,omitempty"`
	Since  time.Time `json:"since,omitempty"`
	// SafePct is the level CPU and memory must drop under before the
	// guard lets agents start again. Only set for guard_hold.
	SafePct int `json:"safe_pct,omitempty"`
}

OverviewQueueReasonDTO is why the queue is not draining, read from the same state the pool admits by.

Kind is guard_hold (the resource guard is holding new agents), slots_full (every pool slot is taken) or waiting (slots are free, but the free-memory floor or a provider's own slot limit is holding the spawn).

type OverviewQueuedDTO added in v0.19.0

type OverviewQueuedDTO struct {
	SessionID string `json:"session_id"`
	AgentName string `json:"agent_name"`
	WaitingMs int64  `json:"waiting_ms"`
	Label     string `json:"label"`
	Project   string `json:"project"`
}

OverviewQueuedDTO is one row in the queue panel returned by /api/overview.

type OverviewStatsDTO added in v0.19.0

type OverviewStatsDTO struct {
	Active   int `json:"active"`
	PoolMax  int `json:"pool_max"`
	QueueLen int `json:"queue_len"`
	// QueueReason says in plain words why sessions are waiting, so the
	// Queue card can explain itself. nil when nothing is queued.
	QueueReason *OverviewQueueReasonDTO `json:"queue_reason,omitempty"`
}

OverviewStatsDTO carries the pool counters for the stats row.

type PoolStatsPayload added in v0.15.2

type PoolStatsPayload struct {
	Active        int                `json:"active"`
	Max           int                `json:"max"`
	QueueLen      int                `json:"queue_len"`
	LiveProcesses []LiveProcessEntry `json:"live_processes"`
}

PublishRaw fires an arbitrary typed SSE event. Used to inject synthetic agent events (e.g. text_delta + done for a switch confirmation reply). PoolStatsPayload is the JSON shape of a pool_stats SSE event. Sent to global ("") subscribers on every lifecycle transition so the Providers page can update the Active Processes panel without reload.

type PresetDetailResponse added in v0.19.0

type PresetDetailResponse struct {
	Name string `json:"name"`
	Body string `json:"body"`
}

PresetDetailResponse is the envelope for GET /api/presets/{name}.

type PresetListItem added in v0.19.0

type PresetListItem struct {
	Name      string `json:"name"`
	IsDefault bool   `json:"is_default,omitempty"`
}

PresetListItem is one row in GET /api/presets.

type PresetListResponse added in v0.19.0

type PresetListResponse struct {
	Presets []PresetListItem `json:"presets"`
}

PresetListResponse is the envelope for GET /api/presets.

type ProjectPinnedSession added in v0.19.0

type ProjectPinnedSession struct {
	ID    string `json:"id"`
	Label string `json:"label"`
}

ProjectPinnedSession is one pinned session row in the API response.

type ProjectSettingsResponse added in v0.19.0

type ProjectSettingsResponse struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Icon        string `json:"icon"`
	Description string `json:"description"`
	CustomPath  string `json:"custom_path"`
	Managed     bool   `json:"managed"`
	// IsProtected reports whether the project cannot be deleted — the
	// built-in "default" project or an auto-created personal project.
	// The SPA hides the delete control when true.
	IsProtected     bool   `json:"is_protected"`
	IsNew           bool   `json:"is_new"`
	DefaultPreset   string `json:"default_preset"`
	DefaultProvider string `json:"default_provider"`
	// DefaultModel pins which model on DefaultProvider this project runs,
	// in that instance's own id space (for wick, down to a live-set leaf).
	// Only meaningful alongside DefaultProvider.
	DefaultModel string `json:"default_model"`
	SystemAddon  string `json:"system_addon"`
	// Widget is this project's stored HTML-artifact CSP override — the raw
	// override, NOT the resolved policy: the editor has to show what the
	// project itself sets, separately from what it inherits.
	Widget agentsconfig.WidgetPolicy `json:"widget"`
	// WidgetInherited is the global policy this project falls back to. The
	// editor shows it read-only so the operator can see what the project's
	// own hosts are being appended TO, instead of having to guess.
	WidgetInherited agentsconfig.WidgetPolicy `json:"widget_inherited"`
	// Ticket is this project's ticket-mode configuration, edited in the
	// settings SPA's "Ticket system" section and saved via the separate
	// PUT /api/projects/{id}/ticket-config endpoint.
	Ticket       project.TicketConfig   `json:"ticket"`
	ChatCount    int                    `json:"chat_count"`
	CreatedAt    string                 `json:"created_at"`
	PresetList   []string               `json:"preset_list"`
	ProviderList []ProviderListItem     `json:"provider_list"`
	Pinned       []ProjectPinnedSession `json:"pinned"`
	MetaJSON     string                 `json:"meta_json"`
	Action       string                 `json:"action"`
}

ProjectSettingsResponse is the envelope for GET /api/projects/{id}.

type ProviderCapDTO added in v0.19.0

type ProviderCapDTO struct {
	Used      int  `json:"used"`
	Max       int  `json:"max"`
	Unlimited bool `json:"unlimited"`
}

ProviderCapDTO is the used / effective-max slot count for one provider.

type ProviderConnectionsResponse added in v1.2.9

type ProviderConnectionsResponse struct {
	Connections []providerConnectionDTO `json:"connections"`
}

ProviderConnectionsResponse is GET /api/providers/connections.

type ProviderDetailResponse added in v0.19.0

type ProviderDetailResponse struct {
	// ReadOnly marks a payload rendered for someone who may look but not
	// edit: every field is shown, every control is disabled, and the API
	// refuses the write anyway (requireProviderAdmin).
	ReadOnly bool `json:"read_only"`
	// CanManage: may this caller reconnect the account and force a usage
	// re-check? Independent of ReadOnly — manage is not edit.
	CanManage bool `json:"can_manage"`
	// SecretsHidden marks a payload whose resolved-config previews were
	// withheld. They contain live auth tokens verbatim, which is fine for
	// the admin who owns the credential and not for a viewer.
	SecretsHidden bool                         `json:"secrets_hidden,omitempty"`
	Instance      ProviderInstanceDTO          `json:"instance"`
	Path          string                       `json:"path"`
	PathFound     bool                         `json:"path_found"`
	Source        string                       `json:"source,omitempty"`
	Version       string                       `json:"version"`
	VersionErr    string                       `json:"version_err,omitempty"`
	Probing       bool                         `json:"probing"`
	Hooks         map[string]HookCapabilityDTO `json:"hooks"`
	HookEnabled   map[string]bool              `json:"hook_enabled"`
	Gate          GateStatusDTO                `json:"gate"`
	GlobalMax     int                          `json:"global_max"`
	ActiveCount   int                          `json:"active_count"`
	ActivePIDs    []LiveProcessDTO             `json:"active_pids"`
	ConfigFields  []ConfigFieldDTO             `json:"config_fields"`
	AIRouter      AIRouterDetailDTO            `json:"airouter"`
	// DefaultModels are the per-type catalog seed models (id + description),
	// shown in the model-selection card so the operator sees what's used when
	// the curated list is empty, and can Load them as an editable starting
	// point (id + desc columns). Sourced from the merged catalog
	// (embedded + GitHub + disk cache). Empty for wick (uses WickModels).
	DefaultModels []DefaultModelDTO `json:"default_models,omitempty"`
}

ProviderDetailResponse is the JSON envelope for GET /api/providers/{type}/{name}.

type ProviderInstanceDTO added in v0.19.0

type ProviderInstanceDTO struct {
	Type          string `json:"type"`
	Name          string `json:"name"`
	Binary        string `json:"binary"`
	Disabled      bool   `json:"disabled"`
	MaxConcurrent int    `json:"max_concurrent"`
	SendMode      string `json:"send_mode"`
	// IdleCompact is the instance's compact-when-idle policy, nil when it
	// is off, so the list can show it without opening the detail page.
	IdleCompact *IdleCompactDTO `json:"idle_compact,omitempty"`
}

ProviderInstanceDTO is the static config of one instance.

type ProviderListItem added in v0.28.1

type ProviderListItem struct {
	Type string `json:"type"`
	Name string `json:"name"`
	// Models are this instance's selectable models (id+label), so the
	// project default picker can descend to a model level — same data the
	// composer's provider picker uses. Empty for single-model instances.
	Models []ProviderModelItem `json:"models,omitempty"`
}

ProviderListItem is one selectable provider instance for the project defaults dropdown. The "type/name" pair is what Defaults.Provider stores; the SPA renders the value as "type/name" so a custom instance (e.g. claude/abc) is selectable, not just the base type.

type ProviderModelItem added in v0.35.0

type ProviderModelItem struct {
	ID      string `json:"id"`
	Label   string `json:"label"`
	Default bool   `json:"default"`
	Desc    string `json:"desc,omitempty"`
	// Live marks a live model SET, not a single model: the picker expands it
	// one level further (lazily, via the models endpoint with ?entry=) and
	// pins a chosen leaf as "<id>@<vendorModelID>". Without this flag the set
	// looked like an ordinary model whose id resolves to nothing runnable.
	Live bool `json:"live,omitempty"`
}

ProviderModelItem is one model choice under a provider instance.

type ProviderStatusDTO added in v0.19.0

type ProviderStatusDTO struct {
	Instance  ProviderInstanceDTO `json:"instance"`
	Path      string              `json:"path"`
	PathFound bool                `json:"path_found"`
	// Source is where Path came from: "managed" (wick-managed version),
	// "registry" (manual Binary path), "path", "scan", "miss".
	Source      string                       `json:"source,omitempty"`
	Version     string                       `json:"version"`
	VersionErr  string                       `json:"version_err,omitempty"`
	Probing     bool                         `json:"probing"`
	Hooks       map[string]HookCapabilityDTO `json:"hooks"`
	Cap         ProviderCapDTO               `json:"cap"`
	HookEnabled map[string]bool              `json:"hook_enabled"`
	// CanManage is the per-instance answer to "may this caller reconnect
	// it and force a usage re-check?" — admins always, everyone else by
	// manage tag. Never implies permission to edit configuration.
	CanManage bool `json:"can_manage"`
}

ProviderStatusDTO is one provider card's data: instance config + live status.

type ProvidersListResponse added in v0.19.0

type ProvidersListResponse struct {
	// IsAdmin tells the SPA which chrome to render at all. Everything
	// that edits configuration is admin-only however the tags are set,
	// so a non-admin gets the read-only page rather than buttons that
	// would come back 403.
	IsAdmin       bool                `json:"is_admin"`
	Providers     []ProviderStatusDTO `json:"providers"`
	Gate          GateStatusDTO       `json:"gate"`
	MCPClients    MCPStatusDTO        `json:"mcp"`
	AutoRescan    bool                `json:"auto_rescan"`
	PoolActive    int                 `json:"pool_active"`
	PoolQueueLen  int                 `json:"pool_queue_len"`
	PoolMax       int                 `json:"pool_max"`
	LiveProcesses []LiveProcessDTO    `json:"live_processes"`
	SupportedKeys []string            `json:"supported_keys"`
}

ProvidersListResponse is the JSON envelope for GET /api/providers.

type RESTTestResult added in v1.2.9

type RESTTestResult struct {
	OK     bool   `json:"ok"`
	Model  string `json:"model"`
	Detail string `json:"detail"`
}

RESTTestResult is POST /api/team/agents/{id}/rest/test: whether a call with the model id would be routed to the agent, checked in-process so the agent is not woken and no token is needed.

type RemoteAgentInfo added in v1.2.9

type RemoteAgentInfo struct {
	CardURL          string         `json:"card_url"`
	Host             string         `json:"host"`
	Card             a2aremote.Card `json:"card"`
	AuthType         string         `json:"auth_type"`
	AuthHeader       string         `json:"auth_header,omitempty"`
	AuthSet          bool           `json:"auth_set"`
	TimeoutSec       int            `json:"timeout_sec"`
	MaxResponseBytes int64          `json:"max_response_bytes"`
	Usage            string         `json:"usage"`
	RefreshedAt      time.Time      `json:"refreshed_at"`
	// Session is set only when GET names a session_id.
	Session *a2aremote.State `json:"session,omitempty"`
}

RemoteAgentInfo is a remote agent's settings as the UI reads them. The secret itself is never in it: AuthSet says one is stored.

type RepoSummary added in v0.15.5

type RepoSummary struct {
	Rel     string `json:"rel"`
	Name    string `json:"name"`
	Branch  string `json:"branch"`
	Changed int    `json:"changed"`
	Ahead   int    `json:"ahead"`
	Behind  int    `json:"behind"`
}

RepoSummary is one repo in the /git/repos listing.

type SessionContextDTO added in v1.2.9

type SessionContextDTO struct {
	SessionID string `json:"session_id"`
	// Provider is the active one ("type/name"), empty for a session that
	// has not run a turn yet.
	Provider string `json:"provider,omitempty"`
	Model    string `json:"model,omitempty"`
	// Used / Window are the last reading. Window is 0 when the CLI does
	// not report a limit — the UI must then show tokens without a ring
	// rather than inventing a denominator.
	Used   int `json:"used"`
	Window int `json:"window"`
	// Pct is Used/Window as a percentage, 0 when Window is unknown.
	Pct float64 `json:"pct"`
	// Turns and Totals cover the whole session, all providers.
	Turns  int                `json:"turns"`
	Totals usagereport.Totals `json:"totals"`
	// Providers lists every provider this session used, newest reading
	// first for the active one.
	Providers []SessionContextProviderDTO `json:"providers"`
	// Trend is the recent per-turn context level for the active provider,
	// oldest first — the rise and fall the ring alone cannot show.
	Trend []int `json:"trend,omitempty"`
	// TrendAt timestamps those points, same order and length. A hovered
	// point has to be able to say WHEN it was: "88k at turn 24" is only
	// half an answer when the question is what made the window jump.
	TrendAt []string `json:"trend_at,omitempty"`
	// TrendSpent is the CUMULATIVE tokens this provider had spent by each
	// of those points. The level says how full the window was; this says
	// what it had cost to get there, which is the other half of every
	// question asked about a step in the curve.
	TrendSpent []int `json:"trend_spent,omitempty"`
	// CanCompact reports whether /compact does anything on this
	// session's provider. False for codex, whose exec mode has no slash
	// commands at all — the panel must not offer a button that would
	// only make the model SAY it compacted. See provider.CanCompact.
	CanCompact bool `json:"can_compact"`
	// CompactNote explains a false CanCompact in one sentence, so the
	// UI never has to keep its own copy of the reason.
	CompactNote string `json:"compact_note,omitempty"`
	// AutoCompact is whether the active provider compacts by itself once
	// the window fills, as it last reported (omp get_state, opencode
	// config); omitted when it never said.
	AutoCompact *bool `json:"auto_compact,omitempty"`
}

SessionContextDTO is the composer's context meter: how full the window is right now, and what the session has spent getting there.

Per provider, because a session that switched providers has two different windows and only the active one belongs in the meter — the others are history, shown in the panel but never in the ring.

type SessionContextProviderDTO added in v1.2.9

type SessionContextProviderDTO struct {
	Provider string             `json:"provider"`
	Model    string             `json:"model,omitempty"`
	Used     int                `json:"used"`
	Window   int                `json:"window"`
	Pct      float64            `json:"pct"`
	Turns    int                `json:"turns"`
	Totals   usagereport.Totals `json:"totals"`
	LastAt   string             `json:"last_at,omitempty"`
}

SessionContextProviderDTO is one provider's row inside the panel.

type SessionListItem added in v0.19.0

type SessionListItem struct {
	ID          string `json:"id"`
	Label       string `json:"label"`
	Status      string `json:"status"`
	ProjectID   string `json:"project_id"`
	ActiveAgent string `json:"active_agent"`
	CreatedAt   string `json:"created_at"`
	LastActive  string `json:"last_active"`
	Lifecycle   string `json:"lifecycle"`
	PID         int    `json:"pid,omitempty"`
	// Participants is how many people have spoken in the session. 0/1 =
	// a single-person chat; >1 is what the list renders as shared. A
	// count, not the ids: the list only needs to draw a marker, and
	// shipping the ids would expose who talks to whom to anyone who can
	// see the row.
	Participants int `json:"participants,omitempty"`
}

SessionListItem is the JSON shape for one session in the /api/sessions list.

type SessionMetaDTO added in v0.19.0

type SessionMetaDTO struct {
	ID          string `json:"id"`
	Label       string `json:"label"`
	Status      string `json:"status"`
	ProjectID   string `json:"project_id"`
	ActiveAgent string `json:"active_agent"`
	TitleCustom bool   `json:"title_custom"`
	CreatedAt   string `json:"created_at"`
	LastActive  string `json:"last_active"`
	// Provider is the active agent's "type/name" provider key — distinct
	// from ActiveAgent (the agent's own name, e.g. "main"). Empty if no
	// agent entry exists yet.
	Provider string `json:"provider,omitempty"`
	// ModelID is the active agent's pinned model id (currently meaningful
	// for wick only). Empty = that provider's own default model.
	ModelID string `json:"model_id,omitempty"`
	// Widget is the already-resolved HTML-artifact CSP policy (global,
	// with this session's project override applied). The SPA builds the
	// iframe CSP from it and never resolves anything itself. Always sent,
	// never omitted: an absent field would leave the SPA guessing, and
	// the safe guess and the real policy are not always the same.
	Widget agentsconfig.WidgetPolicy `json:"widget"`
	// Speaker is the Team agent this session belongs to (via "direct"),
	// so a live assistant turn can be named before the thread is
	// reloaded. Absent for an ordinary session.
	Speaker *agentstore.Speaker `json:"speaker,omitempty"`
}

SessionMetaDTO is the JSON shape returned by /api/sessions/{id}/meta.

type SessionSpawnsResponse added in v0.32.0

type SessionSpawnsResponse struct {
	SessionID    string            `json:"session_id"`
	ProviderType string            `json:"provider_type"`
	ProviderName string            `json:"provider_name"`
	Spawns       []SpawnLogFileDTO `json:"spawns"`
}

SessionSpawnsResponse is the JSON envelope for GET /api/providers/sessions/{id} — every spawn of one session, newest first.

type SessionSummaryDTO added in v0.32.0

type SessionSummaryDTO struct {
	SessionID    string `json:"session_id"`
	ProviderType string `json:"provider_type"`
	ProviderName string `json:"provider_name"`
	SpawnCount   int    `json:"spawn_count"`
	LastStatus   string `json:"last_status"`   // exit reason of the newest spawn ("" → running)
	LastStarted  string `json:"last_started"`  // RFC3339 of the newest spawn
	FirstMessage string `json:"first_message"` // newest spawn's first user message
	Origin       string `json:"origin,omitempty"`
}

SessionSummaryDTO is one row in the per-session Recent Spawns list: a session that spawned one or more processes, collapsed to its latest state. Clicking it opens the session detail (all its spawns).

type SessionsListResponse added in v0.32.0

type SessionsListResponse struct {
	Sessions []SessionSummaryDTO `json:"sessions"`
	Page     int                 `json:"page"`
	HasNext  bool                `json:"has_next"`
	Total    int                 `json:"total"`
}

SessionsListResponse is the JSON envelope for GET /api/providers/sessions.

type SkillDetailResponse added in v0.19.0

type SkillDetailResponse struct {
	Name        string          `json:"name"`
	IsDir       bool            `json:"is_dir"`
	Content     string          `json:"content,omitempty"`
	SourcePath  string          `json:"source_path,omitempty"`
	InDirs      []string        `json:"in_dirs"`
	Entries     []SkillListItem `json:"entries,omitempty"`
	MissingDirs []string        `json:"missing_dirs,omitempty"`
}

SkillDetailResponse is the envelope for GET /api/skills/{name}.

type SkillFileDetailResponse added in v0.19.0

type SkillFileDetailResponse struct {
	Name       string          `json:"name"`
	IsDir      bool            `json:"is_dir"`
	Content    string          `json:"content,omitempty"`
	SourcePath string          `json:"source_path,omitempty"`
	InDirs     []string        `json:"in_dirs"`
	Entries    []SkillListItem `json:"entries,omitempty"`
}

SkillFileDetailResponse is the envelope for GET /api/skills/{folder}/files/{file...}.

type SkillListItem added in v0.19.0

type SkillListItem struct {
	Name        string   `json:"name"`
	IsDir       bool     `json:"is_dir"`
	InDirs      []string `json:"in_dirs"`
	MissingDirs []string `json:"missing_dirs"`
}

SkillListItem is one row in GET /api/skills.

type SkillListResponse added in v0.19.0

type SkillListResponse struct {
	Dirs   []string        `json:"dirs"`
	Skills []SkillListItem `json:"skills"`
}

SkillListResponse is the envelope for GET /api/skills.

type SkillProviderEntryResponse added in v0.19.0

type SkillProviderEntryResponse struct {
	Provider     string          `json:"provider"`
	Path         string          `json:"path"`
	IsDir        bool            `json:"is_dir"`
	Content      string          `json:"content,omitempty"`
	SourcePath   string          `json:"source_path,omitempty"`
	Entries      []SkillListItem `json:"entries,omitempty"`
	AllProviders []string        `json:"all_providers"`
	HasFile      map[string]bool `json:"has_file,omitempty"`
}

SkillProviderEntryResponse is the envelope for GET /api/skills/{provider}/{path...}.

type SlackRemoteInfo added in v1.2.9

type SlackRemoteInfo struct {
	slackremote.Config
	Marker     bool               `json:"marker"`
	Mention    bool               `json:"mention_target"`
	IdleSecEff int                `json:"idle_sec_effective"`
	MaxSecEff  int                `json:"max_sec_effective"`
	ListenEff  string             `json:"listen_effective"`
	UsageEff   string             `json:"usage_effective"`
	Warning    string             `json:"warning"`
	Session    *slackremote.State `json:"session,omitempty"`
}

SlackRemoteInfo is a Slack remote agent's settings as the UI reads them. It never carries a token.

type SpawnDetailResponse added in v0.28.1

type SpawnDetailResponse struct {
	File           SpawnLogFileDTO   `json:"file"`
	Events         []SpawnEventDTO   `json:"events"`
	SessionDeleted bool              `json:"session_deleted"`
	Repro          map[string]string `json:"repro"`
	// HasResume is true when the spawn carried a --resume/resume id, so the
	// Keep/Fresh toggle is meaningful. False on a session's first spawn.
	HasResume bool `json:"has_resume"`
	// PromptSupported is true when this provider needs the prompt added to
	// the reproduce command (claude/gemini take it on stdin). False for
	// codex, whose logged argv already ends with the message.
	PromptSupported bool `json:"prompt_supported"`
	// WickPrompt is the message wick sent on this spawn — the "Wick" option
	// of the Prompt control. It is the spawn log's first_user_message, i.e.
	// the 10-word preview; enough to re-run the same kind of turn, and the
	// Custom option is there when the exact text matters.
	WickPrompt string `json:"wick_prompt,omitempty"`
	// Logs points the operator at the on-disk log files relevant to this
	// spawn so a crash can be copied out for analysis without shelling in.
	Logs SpawnLogsDTO `json:"logs"`
}

SpawnDetailResponse is the full spawn-log detail: metadata, the event timeline, whether the session was since deleted, and the MASKED reproduce commands keyed by view.ReproKey (shell-mode-path). Unmasked variants come from the separate reveal endpoint.

type SpawnEventDTO added in v0.28.1

type SpawnEventDTO struct {
	Type             string   `json:"type"`
	At               string   `json:"at"`
	ProviderType     string   `json:"provider_type,omitempty"`
	ProviderName     string   `json:"provider_name,omitempty"`
	AgentName        string   `json:"agent_name,omitempty"`
	Workspace        string   `json:"workspace,omitempty"`
	ResumeID         string   `json:"resume_id,omitempty"`
	Binary           string   `json:"binary,omitempty"`
	Args             []string `json:"args,omitempty"`
	Env              []string `json:"env,omitempty"`
	PID              int      `json:"pid,omitempty"`
	Origin           string   `json:"origin,omitempty"`
	FirstUserMessage string   `json:"first_user_message,omitempty"`
	ExitReason       string   `json:"exit_reason,omitempty"`
	ReasonDetail     string   `json:"reason_detail,omitempty"`
	ExitCode         int      `json:"exit_code,omitempty"`
	StderrTail       string   `json:"stderr_tail,omitempty"`
	DurationMs       int64    `json:"duration_ms,omitempty"`
	Error            string   `json:"error,omitempty"`
	Message          string   `json:"message,omitempty"`
}

SpawnEventDTO is one event line from a spawn log's timeline.

type SpawnLogFileDTO added in v0.19.0

type SpawnLogFileDTO struct {
	Path             string `json:"path"`
	ProviderType     string `json:"provider_type"`
	ProviderName     string `json:"provider_name"`
	SessionID        string `json:"session_id"`
	StartedAt        string `json:"started_at"`
	PID              int    `json:"pid,omitempty"`
	Origin           string `json:"origin,omitempty"`
	FirstUserMessage string `json:"first_user_message,omitempty"`
	Binary           string `json:"binary,omitempty"`
	ExitReason       string `json:"exit_reason,omitempty"`
	// ReasonDetail is the "why it ended" sentence; ExitCode + StderrTail
	// carry the crash detail. All empty/0 while the spawn is still alive.
	ReasonDetail string `json:"reason_detail,omitempty"`
	ExitCode     int    `json:"exit_code,omitempty"`
	StderrTail   string `json:"stderr_tail,omitempty"`
}

SpawnLogFileDTO is a parsed spawn log file entry.

type SpawnLogsDTO added in v0.32.0

type SpawnLogsDTO struct {
	SpawnPath  string      `json:"spawn_path"`           // full path to the spawn jsonl
	LogsDir    string      `json:"logs_dir,omitempty"`   // absolute logs dir for display
	Components []LogRefDTO `json:"components,omitempty"` // process logs from the spawn day(s)
	Window     SpawnWindow `json:"window"`               // start→end time range to scan
	// LogsPresent is the total number of .log files in the logs dir (any
	// date). 0 = no process logs are being written at all (e.g. dev/console
	// mode) — lets the UI explain an empty Components list.
	LogsPresent int `json:"logs_present"`
}

SpawnLogsDTO carries the on-disk log paths + the spawn's time window for one spawn's detail page. SpawnPath is the spawn's own jsonl (full event timeline incl. crash stderr). Components lists the process logs (app/server/worker/mcp/gate/daemon) written on the spawn's day(s), so the operator can open the right file and scan the Window range.

type SpawnReproRequest added in v1.2.9

type SpawnReproRequest struct {
	Env    string `json:"env,omitempty"`
	Prompt string `json:"prompt,omitempty"`
}

SpawnReproRequest is the body of POST /api/providers/spawns/{file}/repro. Env is "masked" (default) or "live"; Prompt is the user message to fold into the rendered command, empty for the bare spawn command.

type SpawnWindow added in v0.32.0

type SpawnWindow struct {
	Start      string `json:"start"`         // RFC3339
	End        string `json:"end,omitempty"` // RFC3339; "" only while genuinely running
	DurationMs int64  `json:"duration_ms,omitempty"`
	Running    bool   `json:"running"`
	Unclean    bool   `json:"unclean"` // died without an exit event; End is approximate
}

SpawnWindow is the spawn's lifetime — start (spawn) → end. End comes from the exit event when the process shut down cleanly. Running=true only when the process is genuinely still alive. Unclean=true means the process died WITHOUT recording an exit (crash / OS-kill): End is then a best-effort "last sign of life" (the last event's timestamp), not a real exit time.

type SpawnsListResponse added in v0.32.0

type SpawnsListResponse struct {
	Spawns  []SpawnLogFileDTO `json:"spawns"`
	Page    int               `json:"page"`
	HasNext bool              `json:"has_next"`
	Total   int               `json:"total"` // matches after filter, before paging
}

SpawnsListResponse is the JSON envelope for GET /api/providers/spawns — the single source for the Recent Spawns table on both the providers list page (type/name empty = all) and a provider detail page (scoped). Search (q) + pagination happen server-side so one contract serves both.

type SquadItem added in v0.36.0

type SquadItem struct {
	ID               string   `json:"id"`
	Key              string   `json:"key"`
	Name             string   `json:"name"`
	Description      string   `json:"description"`
	LeaderProfileKey string   `json:"leader_profile_key"`
	MemberKeys       []string `json:"member_profile_keys"`
	Disabled         bool     `json:"disabled"`
}

SquadItem is one squad as the UI sees it.

type StorageFileDTO added in v0.19.0

type StorageFileDTO struct {
	ID            uint   `json:"id"`
	ProviderType  string `json:"provider_type"`
	InstanceName  string `json:"instance_name"`
	RelPath       string `json:"rel_path"`
	Name          string `json:"name"`
	IsDir         bool   `json:"is_dir"`
	Size          int    `json:"size"`
	SyncedAt      string `json:"synced_at"`
	RetentionDays int    `json:"retention_days"`
}

StorageFileDTO is one storage file row (without the binary content blob).

type StorageFileVM added in v0.11.0

type StorageFileVM struct {
	entity.ProviderStorage
	SyncedAtFmt string
}

StorageFileVM is the view model for one file row in the storage table.

type StoragePageVM added in v0.11.0

type StoragePageVM struct {
	Base           string
	Files          []StorageFileVM
	FilterProvider string
	FilterInstance string
	ProviderTypes  []string
}

StoragePageVM is the view model for the storage manager page.

type StorageResponse added in v0.19.0

type StorageResponse struct {
	Files          []StorageFileDTO `json:"files"`
	FilterProvider string           `json:"filter_provider,omitempty"`
	FilterInstance string           `json:"filter_instance,omitempty"`
	ProviderTypes  []string         `json:"provider_types"`
}

StorageResponse is the JSON envelope for GET /api/providers/storage.

type SubAgentItem added in v0.36.0

type SubAgentItem struct {
	DelegationID   string `json:"delegation_id"`
	ChildSessionID string `json:"child_session_id"`
	ProfileKey     string `json:"profile_key"`
	// Handle is this instance's address inside its tree — what an @mention
	// resolves to. Empty on rows written before handles existed.
	Handle string `json:"handle,omitempty"`
	// Label is the task, truncated for display.
	Label string `json:"label"`
	// Title is the first leg's task (truncated); Resumes counts continues
	// and LegBaseTurns is where the current leg's turn count started.
	Title        string `json:"title,omitempty"`
	Resumes      int    `json:"resumes,omitempty"`
	LegBaseTurns int    `json:"leg_base_turns,omitempty"`
	Status       string `json:"status"`
	// Lifecycle is merged in from the pool's live snapshot; "" when the
	// child has no active process. Same merge apiSessionList does, so
	// there is only ever one source of truth for liveness.
	Lifecycle string `json:"lifecycle"`
	Depth     int    `json:"depth"`
	TurnsUsed int    `json:"turns_used"`
	MaxTurns  int    `json:"max_turns"`
	// Token spend, as the delegation recorded it. 0 means the provider
	// never reported usage for this run, never "free" — which is why the
	// panel says "not reported" rather than printing a zero.
	InputTokens  int `json:"input_tokens"`
	OutputTokens int `json:"output_tokens"`
	TokensUsed   int `json:"tokens_used"`
	// MaxTokens is this delegation's own cap; 0 = uncapped by the
	// delegation (the per-tree budget still applies), so the panel shows
	// a bare count instead of a ratio.
	MaxTokens int    `json:"max_tokens"`
	Result    string `json:"result,omitempty"`
	StartedAt string `json:"started_at,omitempty"`
	// EndedAt is when the delegation reached a terminal status. Absent
	// while it is queued or running, which is exactly how the UI tells
	// "finished 5m ago" apart from "started 5m ago".
	EndedAt string `json:"ended_at,omitempty"`
	// QueuePosition is the 1-based place this delegation holds in its
	// tree's waiting line, 0 when it is not queued. Computed server-side
	// so the panel never has to infer ordering from timestamps it may
	// have received out of order.
	QueuePosition int `json:"queue_position,omitempty"`
	// Envelope is the sub-agent's structured answer, when it finished.
	// Absent while it is still working.
	Envelope *delegation.ResultEnvelope `json:"envelope,omitempty"`
}

SubAgentItem is one row in the Sub-agents rail panel. Flat and string-typed, matching SessionListItem, so the SPA needs no special decoding.

type TeamAgentAdminRow added in v1.2.9

type TeamAgentAdminRow struct {
	ID, Name, Handle, OwnerUserID, Block string
	Disabled                             bool
}

TeamAgentAdminRow is one Team agent as the admin sharing page lists it. Block is shareBlockOf: non-empty when no tag may share the agent.

func TeamAgentsForAdmin added in v1.2.9

func TeamAgentsForAdmin(ctx context.Context) ([]TeamAgentAdminRow, error)

TeamAgentsForAdmin lists every owner's Team agents for /admin/team-agents.

type TeamAgentItem added in v1.2.9

type TeamAgentItem struct {
	ID     string `json:"id"`
	Handle string `json:"handle"`
	// Kind is "" for a local agent, "a2a-remote" for a remote one; Remote
	// carries the remote's settings then (never its secret).
	Kind   string           `json:"kind"`
	Remote *RemoteAgentInfo `json:"remote,omitempty"`
	// SlackRemote carries a Slack remote agent's settings (kind
	// "slack-remote"); never a token.
	SlackRemote          *SlackRemoteInfo      `json:"slack_remote,omitempty"`
	IsCaptain            bool                  `json:"is_captain"`
	ProjectID            string                `json:"project_id"`
	Name                 string                `json:"name"`
	Icon                 string                `json:"icon"`
	Tagline              string                `json:"tagline"`
	Description          string                `json:"description"`
	SystemPrompt         string                `json:"system_prompt"`
	Provider             string                `json:"provider"`
	Model                string                `json:"model"`
	Preset               string                `json:"preset"`
	Features             team.Features         `json:"features"`
	Avatar               team.Avatar           `json:"avatar"`
	AllowedConnectors    []team.ConnectorGrant `json:"allowed_connectors"`
	IncludeNewConnectors bool                  `json:"include_new_connectors"`
	// AccessMode is team.AccessChoose or team.AccessOwner ("Same as me").
	AccessMode string `json:"access_mode"`
	// AllowedNativeTools, BashRules and DisabledSkills are the Tools &
	// features and Skills tabs (team/tools.go). NativeToolsEnforced is
	// false when the agent's provider cannot be held to them.
	AllowedNativeTools  []string        `json:"allowed_native_tools"`
	BashRules           []team.BashRule `json:"bash_rules"`
	DisabledSkills      []string        `json:"disabled_skills"`
	NativeToolsEnforced bool            `json:"native_tools_enforced"`
	// RunAs is team.RunAsCaller or team.RunAsOwner: whose access a turn
	// runs with (see team.SpawnIdentity).
	RunAs    string `json:"run_as"`
	Disabled bool   `json:"disabled"`
	// MentionFrom, MentionAllow and MaxHops are the Mention tab: who may
	// hand the agent a turn and its agent-to-agent turn cap (effective
	// value, default applied). See teamlink/policy.go.
	MentionFrom  string   `json:"mention_from"`
	MentionAllow []string `json:"mention_allow"`
	MaxHops      int      `json:"max_hops"`
	// UseGlobalPrompt: spawns carry the global system_prompt instead of
	// system_prompt_team (on for agents converted from a project).
	UseGlobalPrompt bool `json:"use_global_prompt"`
	// OwnProject: the agent's project is its own (Team tag), so
	// ShowInProjects applies; a project it was pointed at always shows.
	OwnProject bool `json:"own_project"`
	// ShowInProjects: the project is listed in the sidebar's Projects
	// too (project.ShowsInProjects).
	ShowInProjects bool `json:"show_in_projects"`
	// AllowProviderSwitch is the effective value (default applied).
	AllowProviderSwitch bool                   `json:"allow_provider_switch"`
	SuggestedPrompts    []team.SuggestedPrompt `json:"suggested_prompts"`
	// ManageAgents is the effective "Manage other agents" permission
	// (on for the Captain unless switched off); CaptainCan is what the
	// Captain may do to this agent. See team.ManagesAgents.
	ManageAgents  bool            `json:"manage_agents"`
	CaptainCan    team.CaptainCan `json:"captain_can"`
	MainSessionID string          `json:"main_session_id"`
	LastActive    *time.Time      `json:"last_active"`
	LastPreview   string          `json:"last_preview"`
	// LastSilent is true when LastPreview is a [silent] reply, shown
	// dimmed; the marker itself is stripped.
	LastSilent bool   `json:"last_silent,omitempty"`
	Status     string `json:"status"`
	// Unread is true when the main session moved after the owner last
	// opened the chat (POST /api/team/agents/{id}/read).
	Unread bool `json:"unread"`
	// UnreadCount is how many replies Unread stands for; a reply to
	// another agent that was handed back to it is not one (see
	// team.UnreadCount).
	UnreadCount int `json:"unread_count,omitempty"`
	// NeedsAttention is true while the main session waits on the owner:
	// an ask_user question or a tool approval.
	NeedsAttention bool `json:"needs_attention"`
	// CurrentAction names the tool the main session's running turn is
	// waiting on ("Bash", "query_range"); "" when idle, thinking or
	// writing.
	CurrentAction string `json:"current_action"`
	// ToolError is true while the running turn's newest tool failed and
	// no other has started: the avatar's short error pose.
	ToolError bool `json:"tool_error,omitempty"`
	// AttentionPreview is the short line of what NeedsAttention waits on
	// ("Butuh input: …", "Bash — butuh approval"); also LastPreview then.
	AttentionPreview string `json:"attention_preview,omitempty"`
	// SubagentsWorking holds the handles of the background sub-agents the
	// main session delegated to that are still queued or running, so the
	// card can show work carrying on after the agent's own turn ended.
	// Status is left alone: it stays the agent's own turn state.
	SubagentsWorking []string `json:"subagents_working,omitempty"`
	// SharedWith counts everything else on the same project — other
	// agents of any owner and non-agent web/channel conversations — so
	// the editor can warn that a persona edit changes them too.
	SharedWith int `json:"shared_with"`
	// Role is "" for the caller's own agent and RoleViewer for one another
	// owner shared with them (chat only); SharedBy/SharedByID name that
	// owner then.
	Role       string `json:"role,omitempty"`
	SharedBy   string `json:"shared_by,omitempty"`
	SharedByID string `json:"shared_by_id,omitempty"`
}

TeamAgentItem is one agent as the Agents app renders it. The persona text (name … preset) is read from the agent's project at response time, never stored on the row, so it can never disagree with the project settings.

type TeamAgentSessionItem added in v1.2.9

type TeamAgentSessionItem struct {
	ID         string     `json:"id"`
	Label      string     `json:"label"`
	LastActive *time.Time `json:"last_active"`
	AgentMain  bool       `json:"agent_main"`
	Status     string     `json:"status"`
}

TeamAgentSessionItem is one conversation of an agent.

type TeamGroupItem added in v1.2.9

type TeamGroupItem struct {
	ID               string            `json:"id"`
	Name             string            `json:"name"`
	Members          []TeamGroupMember `json:"members"`
	DefaultResponder string            `json:"default_responder"`
	// Responder is the handle a message with no @ goes to now.
	Responder       string `json:"responder"`
	MaxHopsOverride int    `json:"max_hops_override"`
	// MembersMaxHops is the smallest cap of the members; MaxHops the cap
	// in force (override applied).
	MembersMaxHops int        `json:"members_max_hops"`
	MaxHops        int        `json:"max_hops"`
	LastActive     *time.Time `json:"last_active"`
	LastPreview    string     `json:"last_preview"`
	// LastSilent: LastPreview is a [silent] reply, marker stripped.
	LastSilent bool `json:"last_silent,omitempty"`
	Unread     bool `json:"unread"`
}

TeamGroupItem is one group chat.

type TeamGroupMember added in v1.2.9

type TeamGroupMember struct {
	ID        string      `json:"id"`
	Handle    string      `json:"handle"`
	Name      string      `json:"name"`
	Avatar    team.Avatar `json:"avatar"`
	IsCaptain bool        `json:"is_captain"`
	Disabled  bool        `json:"disabled"`
	MaxHops   int         `json:"max_hops"`
}

TeamGroupMember is one member as the roster and header show it.

type TeamMentionRouter added in v1.2.9

type TeamMentionRouter struct{ Hub func() *teamlink.Hub }

TeamMentionRouter adapts the Hub to delegation.TeamRouter: an @handle line naming a teammate is sent over the same client team_message uses, without waiting.

func (TeamMentionRouter) SendTeam added in v1.2.9

func (r TeamMentionRouter) SendTeam(ctx context.Context, sessionID, handle, body string, human bool) error

func (TeamMentionRouter) TeamHandles added in v1.2.9

func (r TeamMentionRouter) TeamHandles(ctx context.Context, sessionID string) []string

type TerminalStartResponse added in v1.2.9

type TerminalStartResponse struct {
	ID      string `json:"id"`
	URL     string `json:"url"`
	Command string `json:"command"`
}

TerminalStartResponse is POST …/terminal.

type TerminalStatusResponse added in v1.2.9

type TerminalStatusResponse struct {
	Commands       []terminal.Command `json:"commands"`
	GottyInstalled bool               `json:"gotty_installed"`
}

TerminalStatusResponse is GET …/terminal.

type TestCaseItem added in v0.14.20

type TestCaseItem struct {
	Name   string
	Case   wftest.Case
	Result *wftest.Result
}

TestCaseItem pairs an on-disk test case with its last-run result for the spa test panel handlers.

type TicketCard added in v0.40.0

type TicketCard struct {
	ID     string `json:"id"`
	Title  string `json:"title"`
	Status string `json:"status"`
	// Assignee is the first of Assignees. Both travel: a card has room for
	// one avatar, and the older clients that only read this field keep
	// working against a ticket that now has three people on it.
	Assignee  string            `json:"assignee,omitempty"`
	Assignees []string          `json:"assignees,omitempty"`
	Fields    map[string]string `json:"fields,omitempty"`
	// SessionRows are the ticket's sessions, listed on the card so one can
	// be dragged to another ticket without opening anything.
	SessionRows []ticketSessionRow `json:"session_rows,omitempty"`
	Sessions    int                `json:"sessions"`
	Notes       int                `json:"notes"`
	OpenTasks   int                `json:"open_tasks"`
	UpdatedAt   string             `json:"updated_at"`
	CreatedAt   string             `json:"created_at"`
	Stale       bool               `json:"stale"`
}

TicketCard is one card on the project board. A card is a TICKET, not a session: a ticket can hold several sessions, and the board shows the work rather than each conversation about it.

type TodoDetailDTO added in v1.2.9

type TodoDetailDTO struct {
	Format string `json:"format,omitempty"`
	Body   string `json:"body"`
}

TodoDetailDTO is the payload an item carries: a log tail, a JSON result, a small table. Passed through as stored — the client decides how to draw each format, and nothing here interprets it.

type TodoItemDTO added in v1.2.9

type TodoItemDTO struct {
	ID          string           `json:"id,omitempty"`
	Label       string           `json:"label"`
	Description string           `json:"description,omitempty"`
	Status      string           `json:"status"`
	Substeps    []TodoSubstepDTO `json:"substeps,omitempty"`
	Progress    *TodoProgressDTO `json:"progress,omitempty"`
	Detail      *TodoDetailDTO   `json:"detail,omitempty"`
}

TodoItemDTO is one checklist item as the UI needs it. `label` is resolved server-side so the client does not re-implement the title/step fallback.

type TodoListDTO added in v1.2.9

type TodoListDTO struct {
	Items     []TodoItemDTO `json:"items"`
	Total     int           `json:"total"`
	Completed int           `json:"completed"`
	Done      bool          `json:"done"`
	// Stopped says the work was abandoned rather than finished — the two
	// look identical in a half-ticked list, and only one of them means
	// anything got done.
	Stopped   bool   `json:"stopped,omitempty"`
	Note      string `json:"note,omitempty"`
	StartedAt string `json:"started_at,omitempty"`
	UpdatedAt string `json:"updated_at,omitempty"`
}

TodoListDTO is one checklist, with the counts the UI would otherwise compute in three places.

type TodoProgressDTO added in v1.2.9

type TodoProgressDTO struct {
	Done  int    `json:"done"`
	Total int    `json:"total"`
	Label string `json:"label,omitempty"`
}

TodoProgressDTO is how far into one step the work has got — the bar under a step that is long rather than merely unfinished.

type TodoSubstepDTO added in v1.2.9

type TodoSubstepDTO struct {
	Step   string `json:"step"`
	Status string `json:"status"`
}

TodoSubstepDTO is one nested step.

type TodosDTO added in v1.2.9

type TodosDTO struct {
	Active  *TodoListDTO  `json:"active,omitempty"`
	History []TodoListDTO `json:"history"`
}

TodosDTO is the whole record for one session.

type TokenAuthenticator added in v1.2.9

type TokenAuthenticator interface {
	Authenticate(ctx context.Context, plain string) (userID string, err error)
}

TokenAuthenticator resolves a Personal Access Token to its owning user. Satisfied by accesstoken.Service — declared here so this package does not import it directly.

type UserLookup added in v1.2.9

type UserLookup interface {
	GetUserByID(ctx context.Context, id string) (*entity.User, error)
	// GetUserFilterTagIDs returns the user's filter tag IDs — the same set
	// the login cookie carries. Without them a token request cannot pass
	// tag-share checks, so a project the user reaches in the browser via a
	// tag grant would answer 404 to their own token.
	GetUserFilterTagIDs(ctx context.Context, userID string) []string
}

UserLookup loads a user by id, so a resolved token can be turned into the same *entity.User the cookie path puts in the context.

Source Files

Directories

Path Synopsis
workflow
Package workflow holds the templ components for /tools/agents/workflows.
Package workflow holds the templ components for /tools/agents/workflows.

Jump to

Keyboard shortcuts

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