httpapi

package
v0.214.1 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: MIT Imports: 90 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

授权管理接口(设计 docs/design/2026-10-14-db-capabilities-and-session-grants-design.md 「接口」一节、§2「授权模型与判定」与 §4「会话授权」,计划 T2.1)。

The design's interfaces live together here, because they are views of ONE model: a grant is a stored pattern, and everything asked about it — the caller's own effective permissions (whoami), the catalog the pattern expands against, the routes that ask for a permission, the grants themselves and the audit of what was decided — is that same model seen from a different side.

What is deliberately NOT here:

  • the permission judgment: authz_resolve.go resolves a caller's effective permissions, and the route gate and the handlers ask through s.can (G021: no entry-layer business logic in the decision itself);
  • the audit WRITE side (授权的增删、被拒的请求与使用计数are the audit task's, plan T2.4). This file reads auth_audit; the store offers the insert seam.

`auth.manage` is the catalog's one root-risk permission, and no grant can ever match it (that is the security property: internal/authz refuses it in Expand, so `*` cannot hand it out). The gate therefore leaves the five management routes to the root administrator alone, whatever the governance switches say. A worker token and a job credential are refused by the caller-kind check below: the route gate deliberately does not judge a non-user caller (design §2「只对 user 类调用方计算」), and a job credential may READ every GET route through SEC-01 (jobcredential.go), which must not open the grant list to a job.

权限参考文档的生成入口(设计「权限参考文档由代码生成」,计划 T1.6)。

The permission reference (docs/reference/permissions.md) is written from code — the catalog of internal/authz and the route declarations of authz_routes.go — so that the checked-in document can never describe a binary that does not exist:

go generate ./internal/httpapi/...

rewrites it, and authz_gen_test.go renders the same bytes and fails when the file has gone stale (the design's 过期检查, which is what keeps the two in step without a human remembering to edit the document).

The document is user-facing: it is what an operator (or an agent reading the docs) consults to learn what a permission means and what a route asks for. It therefore carries no task numbers, design sections or migration history — only what the running code does today (G046).

用户管理接口(配置入库 P1,设计 docs/design/2026-11-03-config-into-db-design.md §「鉴权」「新增用户」,计划 T6)。

What lives here is ONLY the binding and the translation: the request bodies, the caller-kind gate every route repeats, and the mapping of a caller-administration result onto HTTP. A new user, a rotation, a state change and a limit change all run through Core's CallerAdmin seam (internal/core/callers.go): the transaction order, the token, the audit line and the re-merge of the published snapshot are the assembly layer's business (G021), and the entry layer never imports it — the seam is expressed with the config types both sides share.

Two rules are repeated on EVERY route here, and both are load-bearing:

  • `grantAdminOnly` runs FIRST. The route gate requires `auth.manage` (which only a root administrator holds), but the gate deliberately does not judge a non-user caller, so a worker token or a job credential would otherwise reach these handlers. A job credential may read every GET route through SEC-01 (jobcredential.go), which must not hand it the caller list or the audit.
  • the token of a new / rotated caller appears in that ONE response and nowhere else: not in the database (only its sha256), not in an audit line, not in a log (SR1301).

notify_handler.go serves the console's notification settings (gofer-x9mb):

GET  /v1/notify/events  the event catalog (key, group, zh/en description, default flags)
POST /v1/notify/test    send ONE test message through the CURRENT config

Writing the targets themselves stays on PUT /v1/config/server (the notification block is a patch there); these two routes only read the vocabulary and prove a target works. The catalog comes from internal/notify, so the console never carries a second event list.

Package httpapi exposes the gofer control plane over HTTP using github.com/gookit/rux/v2. Handlers only parse params, enforce the auth context and encode responses; all business logic lives in the job service and the project/agent registries (plan §7).

Error responses use a small uniform shape (NOT the company {status,code, message} envelope), because this is a local developer tool, not an internal business service (plan §7):

{"error":"unknown project","detail":"project_key other not found"}

Index

Constants

View Source
const (
	DefaultMailTakeLimit = 5
	DefaultMailTakeChars = 8000
)

Default and ceiling of one take (设计「默认数值」: 单次注入 5 封 / 8000 字).

View Source
const (

	// ApplyDrainTimeout is the drain window the one-click update hands `serve upgrade`
	// (`--drain-timeout`). It is deliberately shorter than the command's own default: the
	// update waited for the machine to be idle a moment earlier, so a longer drain would
	// only delay a restart that cannot become safer. Exported because the serve-side
	// command builder passes it, and the two must stay the same number.
	ApplyDrainTimeout = 2 * time.Minute
)
View Source
const AuthzReferencePath = "../../docs/reference/permissions.md"

AuthzReferencePath is the generated permission reference, relative to this package's directory (the working directory of both `go generate ./internal/httpapi/...` and of the package's own tests, so the generator's -out default and the staleness test share it).

View Source
const (

	// DefaultProbeTimeoutSec is a probe's deadline (and the sync wait around it) when
	// the caller asks for none: long enough for a cold CLI start, short enough that a
	// hung one is reported as a failure rather than as silence.
	DefaultProbeTimeoutSec = 120
)
View Source
const EventNotifyTest = "notify.test"

EventNotifyTest is the event type stamped on a test message. It is deliberately not a real trigger: a bot's X-Gofer-Event header should say "this was a test".

Variables

View Source
var (
	ErrUpgradeWorkerOffline = errors.New("worker offline")
	ErrUpgradeTooOld        = errors.New("worker too old for remote upgrade")
	ErrUpgradeTimeout       = errors.New("worker did not answer the upgrade request in time")
)

Upgrade failure classes the hub adapter (serve) maps its own errors onto, so this layer can pick a status without importing wshub (D2/G022).

Functions

func AuthzReference added in v0.161.0

func AuthzReference() string

AuthzReference renders the permission reference: the catalog (name, what it covers, risk, whether it may be granted to a session, scope, source) and every route declaration (method, path, the user-class category with the permissions it needs, and which other credential reaches the route).

It is exported for the two callers that must agree byte for byte: the generator (./authzgen, behind `go generate`) and TestAuthzReferenceIsUpToDate. Nothing in the request path calls it.

func BodyProject added in v0.171.0

func BodyProject() routeScope

BodyProject marks a route whose project (or the record naming it) is in the request body, so only the handler can check it, after binding.

func Filter added in v0.171.0

func Filter() routeScope

Filter marks a list / aggregate route: what it returns must be narrowed to the scope.

func InHandler added in v0.161.0

func InHandler(mode permMode, perms ...string) userRule

InHandler marks a route whose permissions the HANDLER decides, because the answer depends on the resource (own vs someone else's, or a filtered list). mode records what the handler does about a caller that does not hold the permission.

func Mutating added in v0.171.0

func Mutating() rwClass

Mutating explicitly marks a route as a write although its method is GET (a data-plane connection that can carry writes). Every use must be on the reviewed list of authz_route_dims_test.go.

func NoProject added in v0.171.0

func NoProject() routeScope

NoProject marks a route with no project dimension, explicitly: server-global admin / meta / self routes. It is a statement, not an omission.

func NoUserSurface added in v0.161.0

func NoUserSurface() userRule

NoUserSurface marks a route no user-class caller reaches: it authenticates with its own credential (External) or only a worker calls it. The gate adds nothing there — the handler owns the caller-kind rule, exactly as before T1.4.

func PathProject added in v0.171.0

func PathProject(param string) routeScope

PathProject marks a route whose project key is the path parameter `param`.

func Public added in v0.161.0

func Public() userRule

Public marks a route any user-class caller may reach without a permission of its own.

func ReadSafe added in v0.171.0

func ReadSafe() rwClass

ReadSafe explicitly marks a route a read-only caller may reach although its method is not GET: a personal-preference write, or a POST with read semantics. Every use must be on the reviewed list of authz_route_dims_test.go.

func Require added in v0.161.0

func Require(perms ...string) userRule

Require marks a route a user-class caller may reach only while holding every one of perms: the gate refuses the request with a 403 that names the missing permission. Its mode is permDeny — a plain requirement is always a refusal, it has no filtered form.

func Resource added in v0.171.0

func Resource(kind string) routeScope

Resource marks a route whose project comes from the addressed record of the given kind (job, plan, todo, schedule, workflow, session, work_item, tracker_repo, memory, worker …): the record carries (or resolves to) its project.

func UserPending added in v0.161.0

func UserPending() userRule

UserPending marks a route whose user-side category is not migrated yet (plan T1.4's 待迁移 list): the gate adds nothing and the handler keeps its own check. Such a route must also be on pendingRoutes.

Types

type AgentBrief

type AgentBrief struct {
	Key         string `json:"key"`
	Type        string `json:"type,omitempty"`
	Interactive bool   `json:"interactive,omitempty"`
	Batch       bool   `json:"batch"`
	// Available/Version are DISPLAY-ONLY, and Available is a *bool for a reason —
	// see wsproto.AgentBrief for the full rule. Short version: nil = the worker never
	// reported it (pre-P2 build), false = a probe did not find the CLI. NEITHER means
	// "cannot run": an operator-declared agent stays runnable whatever the probe says.
	// Nothing in this package (or the web console) may filter or grey out an agent on
	// this field; the agent list is the authority on what exists.
	Available *bool  `json:"available,omitempty"`
	Version   string `json:"version,omitempty"`
}

AgentBrief is httpapi's local typed agent capability (key + type + interactive), the detail the web capability cascade needs beyond a bare agent key. It mirrors wsproto.AgentBrief but is redeclared here so httpapi never imports wshub/wsproto (the D2 boundary): the serve-side adapter converts the wshub snapshot into this type. It is exported because that adapter (package serve) constructs it. The JSON tags match wsproto/the web MetaAgent shape (type/interactive omitempty).

type ApplyState added in v0.154.0

type ApplyState struct {
	ID        string        `json:"id"`
	From      string        `json:"from"`
	Version   string        `json:"version"`
	Phase     string        `json:"phase"`
	Error     string        `json:"error,omitempty"`
	Workers   []ApplyWorker `json:"workers"`
	StartedAt int64         `json:"started_at"`
	UpdatedAt int64         `json:"updated_at"`
	// gofer-dzv3: while the apply waits for idle it also reports what it waits for —
	// the jobs that would block a restart (Waiting), how many jobs it has parked
	// (Paused) and when it gives up (WaitDeadline).
	WaitDeadline   int64             `json:"wait_deadline,omitempty"`
	WaitTimeoutSec int               `json:"wait_timeout_sec,omitempty"`
	Waiting        []ApplyWaitingJob `json:"waiting,omitempty"`
	Paused         int               `json:"paused,omitempty"`
}

ApplyState is the progress of the latest update apply.

type ApplyWaitingJob added in v0.156.0

type ApplyWaitingJob struct {
	ID        string `json:"id"`
	Title     string `json:"title,omitempty"`
	Status    string `json:"status"`
	Runner    string `json:"runner,omitempty"`
	StartedAt int64  `json:"started_at,omitempty"`
}

ApplyWaitingJob is one job the update is still waiting for before it restarts, as the progress reports it (gofer-dzv3): the id to click, a title to recognise it by, and what it is doing.

type ApplyWorker added in v0.154.0

type ApplyWorker struct {
	ID   string `json:"id"`
	OS   string `json:"os,omitempty"`
	Arch string `json:"arch,omitempty"`
	// State: pending, accepted (handed over, see the worker's upgrade record),
	// succeeded / failed (the record's outcome), skipped.
	State     string `json:"state"`
	Error     string `json:"error,omitempty"`
	UpgradeID string `json:"upgrade_id,omitempty"`
}

ApplyWorker is one worker of an update apply.

type AttachTicketBinding

type AttachTicketBinding struct {
	Caller       string
	JobID        string
	PtySessionID string
	Mode         string
	Origin       string
	Expiry       int64
	// Session is the terminal session the ticket's request named (empty when it named none).
	Session string
	// Token is the bearer token the issuing request authenticated with (the caller's credential,
	// so a reload that changes or removes it ends the connection the ticket opened).
	Token string
	// Perms are the permissions the issuing request rested on for this connection (empty = the
	// connection needs nothing but its identity: the caller's own job, or the push channel).
	Perms []string
	// Deps are the ids of the database grants behind those permissions.
	Deps []string
	// CeilingOwner is the caller whose scope ceiling governs the connection (gofer-7798 第二期):
	// the issuing caller for a user-class ticket, the ceiling owner of the job credential for a
	// job-issued one. It is resolved against the LIVE configuration on every re-judgment, so a
	// ceiling added or tightened after the ticket was issued still applies to the connection.
	CeilingOwner string
}

AttachTicketBinding is the in-memory binding carried by a browser attach ticket. The ticket token itself is opaque and consumed once by the T7 WS path.

The last three fields exist for the long-connection revocation of design §6: the WS handshake carries no Authorization header, so the ticket records what the handshake cannot ask again — the session the issuing request named, the permissions it was admitted on, and the database grants behind them (the dependency set).

type AttachTicketStore

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

AttachTicketStore holds short-lived one-time browser attach tickets.

func NewAttachTicketStore

func NewAttachTicketStore() *AttachTicketStore

func (*AttachTicketStore) Consume

func (s *AttachTicketStore) Consume(token string, nowUnix int64) (AttachTicketBinding, bool)

func (*AttachTicketStore) Issue

type AttachmentThreadAccess added in v0.177.0

type AttachmentThreadAccess interface {
	MayReadThread(c *rux.Context, threadID string) bool
}

AttachmentThreadAccess decides whether the caller of a request may read the workbench thread an attachment was SENT to. It is the seam the workbench send task plugs its own visibility rule into (SetAttachmentThreadAccess); until then threadReadableByCaller below applies the same rule the thread routes use (the thread's owner, or the matching *.read.others permission). An implementation must fail closed: an unknown or unparseable thread is false.

type CallerAdmin added in v0.211.0

type CallerAdmin interface {
	// AddCaller creates a stored caller and answers its token once.
	AddCaller(spec config.CallerSpec, actor string) (config.CallerChange, error)
	// RotateCaller replaces a stored caller's token and answers the new one once.
	RotateCaller(id, actor string) (config.CallerChange, error)
	// DisableCaller switches a stored caller off (idempotent).
	DisableCaller(id, actor string) (config.CallerChange, error)
	// EnableCaller brings a stored caller back; a caller a file entry took over must have been
	// rotated after the takeover.
	EnableCaller(id, actor string) (config.CallerChange, error)
	// SetCallerCeiling replaces (or, with noCeiling, removes) a caller's upper bound.
	SetCallerCeiling(id string, ceil *config.CallerCeiling, noCeiling bool, actor string) (config.CallerChange, error)
	// SetCallerLimits replaces a caller's quota overrides.
	SetCallerLimits(id string, lim config.CallerLimits, actor string) (config.CallerChange, error)
	// ListCallers reports every caller: file-declared, stored, disabled and taken over.
	ListCallers() ([]config.CallerView, error)
	// ListCallerAudit reports the config_audit lines of every caller change, newest first.
	ListCallerAudit(limit int) ([]jobstore.ConfigAuditEntry, error)
}

CallerAdmin is the narrow seam the caller-administration routes ask for. *core.Core implements it; serve injects the singleton with SetCallers. A nil seam (mcp, most tests) leaves the routes mounted but answering 503 — the same degradation /v1/xfer and the config write surface use — so the router never has to be rebuilt for it.

type ConfigWriter

type ConfigWriter interface {
	Update(mut func(*config.Config) error) error
	ReloadConfigReport() (config.ReloadResult, error)
}

ConfigWriter is the narrow write-transaction seam (D2/G022) for the WEB-04③ V1.1 config write endpoints: the only two things this entry layer asks of the config owner are "run this mutation as one transaction" (clone → apply → validate → save → reload) and "re-read the file by hand". *core.Core satisfies it; serve injects the singleton via SetConfigWriter.

A nil seam (mcp, most tests) leaves the routes mounted but answering 503 — the same degradation /v1/xfer uses — so the router never has to be rebuilt for it.

type DirEntry

type DirEntry struct {
	Path   string `json:"path"`
	Exists bool   `json:"exists"`
}

DirEntry is one directory and whether it exists.

type DirsView

type DirsView struct {
	Workspace *DirEntry         `json:"workspace,omitempty"`
	Roots     []RootEntry       `json:"roots,omitempty"`
	Projects  []ProjectDirEntry `json:"projects,omitempty"`
	// OtherProjects counts configured projects that are not listed because this
	// runner may not run them (allowed_runners excludes it). Their host_path belongs
	// to another worker's machine, so "directory missing here" would be a false alarm.
	OtherProjects int `json:"other_projects,omitempty"`
}

DirsView is where a runner runs things: the machine's default workspace (GOFER_WORKSPACE or ~/.gofer/workspace), the roots mapping of a policy-mode worker and the directory every served project resolves to. Exists is judged on the runner's own machine at report time. A project that could not be resolved at all is not here — its reason is the worker's policy_rejected entry.

type ManagedUpgradeFunc added in v0.154.0

type ManagedUpgradeFunc func(ctx context.Context, binary string) error

ManagedUpgradeFunc replaces the running managed server with binary (gofer serve upgrade). It returns once the upgrade was accepted; the process exits soon after.

type PolicyDegrade

type PolicyDegrade struct {
	Key  string `json:"key"`
	Gate string `json:"gate"`
}

type PolicyRejection

type PolicyRejection struct {
	Key    string `json:"key"`
	Reason string `json:"reason"`
}

type ProjectDirEntry

type ProjectDirEntry struct {
	Key    string `json:"key"`
	Path   string `json:"path"`
	Exists bool   `json:"exists"`
}

ProjectDirEntry is the directory a project resolves to on the runner.

type PtySessionStore

type PtySessionStore interface {
	UpsertPtySession(rec jobstore.PtySessionRecord) error
	GetPtySessionByJob(jobID string) (jobstore.PtySessionRecord, bool, error)
	ListPtySessionsByJob(jobID string) ([]jobstore.PtySessionRecord, error)
	ListRecentPtySessions(limit int) ([]jobstore.PtySessionRecord, error)
}

PtySessionStore is the narrow persistence seam the WEB-03 P3 pty handlers use to record/read pty relay session metadata (design review 高1). It is defined here — rather than the Server holding a raw *jobstore.Store — so the entry layer keeps a minimal, intention-revealing surface; *jobstore.Store satisfies it. A nil PtySessionStore means "no persistence" (mcp / most tests) and handlers (T5/T6) must guard against it.

type RootEntry

type RootEntry struct {
	From   string `json:"from"`
	To     string `json:"to"`
	Exists bool   `json:"exists"`
}

RootEntry is one roots mapping (server-side prefix -> the worker's local path).

type Server

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

Server holds the wired dependencies and the rux router. It is constructed once (New) and either started with Run or exposed as an http.Handler (Handler) for httptest.

func New

func New(serverCfg *config.ServerConfig, token string, allowEmptyToken bool, jobs *job.Service, wf *workflow.Engine, projects *project.Registry, agents *agent.Registry, hub workerHub, runners map[string]config.RunnerConfig, prober runnerProber, workers workerRegistry) *Server

New builds a Server: it resolves the effective token, wires the rux router (routes + auth middleware) and returns it ready to Run or hand to httptest.

token is the already-resolved effective token (serve resolves config.token / token_env / --token before calling New). allowEmptyToken mirrors the config/flag of the same name.

runners is the configured runner set for the C6/P4 GET /v1/runners endpoint (nil/empty => only the implicit local row). prober and workers are the C6/P4 observability sources (both nil-safe: a nil renders the corresponding runner rows `unknown`). serve injects them (config.Runners + the peer-http probe cache + a hub adapter); other callers pass nil.

NOTE (D3, deferred): New is now a wide positional constructor. The plan flags a future functional-option / Deps-struct refactor as optional cleanup; it is intentionally NOT done here to keep the change backward-compatible and focused.

func (*Server) CallerHasPermission added in v0.205.0

func (s *Server) CallerHasPermission(callerID, perm string) bool

CallerHasPermission reports whether the user-class caller currently holds perm in the live effective-permission model (config-derived grants plus database grants). The trigger owner admission asks it on every invocation.

func (*Server) Handler

func (s *Server) Handler() http.Handler

Handler exposes the rux router as an http.Handler (rux.Router implements ServeHTTP), used by httptest and by Run.

func (*Server) HostedForwarders

func (s *Server) HostedForwarders() *tunnel.HostedForwarderManager

func (*Server) LinkIssueFinished

func (s *Server) LinkIssueFinished(snap job.JobResult)

func (*Server) LinkIssueStarted

func (s *Server) LinkIssueStarted(snap job.JobResult)

func (*Server) Live

func (s *Server) Live() *pushhub.Hub

Live returns the browser push hub so assembly can wire its sources (job store hook, event tap, worker presence, ...). It is never nil on a Server built by New.

func (*Server) Mail added in v0.173.0

func (s *Server) Mail() *mail.Service

Mail returns the mailbox the routes use (nil without a job store).

func (*Server) MayAnswerInteraction added in v0.161.0

func (s *Server) MayAnswerInteraction(callerID string) bool

MayAnswerInteraction reports whether the user-class caller callerID may answer an interaction right now (`interaction.answer`, design §1). It is the caller-id form of s.can for the one decision path that has no request to hang an identity on: a browser notification's action buttons, which internal/webpush mints and redeems asynchronously (design §6「动作按钮在签发和兑现时都检查」).

It reads the LIVE configuration snapshot (authzDerivation) and the live database grants, so a revoke or a config reload applies to the next button; the empty caller id of an allow_empty_token deployment resolves like any other caller id (the anonymous caller is 「default」 throughout webpush, see its normalizeCaller). A notification button is minted and redeemed outside any terminal session, so no session grant can apply to it.

func (*Server) NotePreviewPresence added in v0.207.0

func (s *Server) NotePreviewPresence(workerID string, online bool)

NotePreviewPresence forwards worker presence changes to the preview manager, which closes the leases bound to a worker process that went away.

func (*Server) OnSessionStart

func (s *Server) OnSessionStart(jobID string, sess *ptyrunner.PtySession)

OnSessionStart implements ptyrunner.SessionObserver for serve-local pty jobs. It must stay non-blocking because PtyRunner calls it synchronously before the child run loop starts; all relay/session persistence work happens in a goroutine.

func (*Server) Relay added in v0.174.0

func (s *Server) Relay() *sessionrelay.Service

Relay returns the session relay the server delivers through (the mailbox deliverer wakes idle sessions and runs `suga send` over the same transports); nil without a job store.

func (*Server) ResumeServerRestart added in v0.194.0

func (s *Server) ResumeServerRestart()

ResumeServerRestart settles the restart state a previous process left behind and is how a restart becomes observable as finished: the process that asked for it exits, so the new one reads `restarting` and reports done. A `waiting_idle` state whose waiter is gone (a restart the operator cancelled by hand, say) is failed, not left hanging.

func (*Server) ResumeUpdateApply added in v0.154.0

func (s *Server) ResumeUpdateApply(ctx context.Context)

ResumeUpdateApply is the new server's part, run once at startup. It first releases every job a previous process parked (gofer-dzv3): the pause belongs to the process that set it, so whatever this server finds parked was parked by an update that is gone — it must never stay parked forever. Then: when an apply was restarting this server, confirm the new version and upgrade the chosen workers; when it was still waiting for idle, that wait died with the old process and the apply is failed.

func (*Server) Run

func (s *Server) Run(addr string) error

Run starts the HTTP server on addr and blocks until the listener fails, with no graceful-shutdown signal. Retained for callers that do not manage a context.

func (*Server) RunCtx

func (s *Server) RunCtx(ctx context.Context, addr string) error

RunCtx starts the HTTP server on addr and blocks until ctx is cancelled — then it gracefully shuts down (stop accepting new conns, drain in-flight up to shutdownGrace) and returns nil — or until the listener fails. http.ErrServerClosed from a graceful Shutdown is expected and mapped to nil. The address is logged; the token is never logged (plan §11).

func (*Server) RunCtxTLS

func (s *Server) RunCtxTLS(ctx context.Context, addr string, tlsCfg *config.TLSConfig) error

RunCtxTLS serves the same router on the historical HTTP listener and, when configured, an additional HTTPS listener. The HTTP endpoint remains available for workers and CLI clients.

func (*Server) SetAttachmentThreadAccess added in v0.177.0

func (s *Server) SetAttachmentThreadAccess(a AttachmentThreadAccess)

SetAttachmentThreadAccess replaces the default sent-attachment visibility rule; nil restores the default. The default (threadReadableByCaller) is already the workbench's own rule: the owner resolution workbenchThreadOwner plus the job.read.others / session.read.others permissions the thread routes use, so the workbench send path needs no override.

func (*Server) SetAttachments added in v0.177.0

func (s *Server) SetAttachments(a *attachment.Service)

SetAttachments injects the image-attachment store (serve passes the one it also prunes). Like SetXfer the routes are always mounted and answer 503 while it is nil.

func (*Server) SetBuildInfo

func (s *Server) SetBuildInfo(info buildinfo.Info)

SetBuildInfo injects linker build metadata for runtime status endpoints.

func (*Server) SetCallers added in v0.211.0

func (s *Server) SetCallers(admin CallerAdmin)

SetCallers injects the caller-administration seam (plan T6): the same Core the config write surface uses, whose caller methods write the auth_callers rows and publish the merged snapshot without touching the configuration file.

func (*Server) SetCastRecorder

func (s *Server) SetCastRecorder(rec *castrec.Recorder)

SetCastRecorder injects the WEB-03 P3 cast recording factory (nil = recording off, the zero-regression default). Like SetPtyRelay it is a post-construction setter so the wide positional New stays untouched; serve calls it at startup after resolving storage.cast and its encryption key. It mounts no routes, so — unlike SetMetrics/SetPtyRelay — it does NOT rebuild the router.

func (*Server) SetConfigWriter

func (s *Server) SetConfigWriter(cw ConfigWriter)

SetConfigWriter injects the config write transaction (WEB-04③ V1.1) behind the /v1/config write routes. serve passes the *core.Core singleton (which satisfies the narrow interface); a nil writer leaves the routes mounted and answering 503, so — like SetXfer — it mounts nothing and needs no router rebuild.

func (*Server) SetHostedForwarderDial

func (s *Server) SetHostedForwarderDial(dial tunnel.HostedDial)

SetHostedForwarderDial replaces the hosted forwarders' dial. New already wires the production one — the server dials its own process (s.dialHostedTunnel, plan T1.5f/design §6), which needs no listen address and no token — so this is the seam for tests that want an in-process fake or a dial that always fails.

func (*Server) SetMail added in v0.173.0

func (s *Server) SetMail(m *mail.Service)

SetMail replaces the mailbox with the one core assembled, so the routes, the delivery paths and the sender limits all work on exactly one mail.Service. New builds a default one so a server constructed without serve (tests, mcp) still has a mailbox.

func (*Server) SetMetrics

func (s *Server) SetMetrics(m *metrics.Metrics, enabled bool, token string)

SetMetrics injects the E16 Prometheus instrumentation and mounts the /metrics endpoint + the /v1 HTTP middleware (design §6.2). It MUST be called before the server starts serving (serve calls it right after New, before Run). enabled and token come from serverCfg.Metrics. Passing a nil m leaves metrics off.

The router is rebuilt so the /metrics route + the metricsMiddleware on /v1 are registered (rux requires routes/middleware at build time). This is safe because SetMetrics runs single-threaded at assemble time, before any request is served.

func (*Server) SetPtyRelay

func (s *Server) SetPtyRelay(nonces *ptyrelay.NonceStore, relays *ptyrelay.Registry)

SetPtyRelay injects the shared live-only PTY relay state for worker pty-connect and browser attach routes. It is a post-construction setter to avoid widening New's already-large positional constructor.

func (*Server) SetPtySessionStore

func (s *Server) SetPtySessionStore(store PtySessionStore)

SetPtySessionStore injects the pty-session persistence seam (WEB-03 P3). serve passes the *jobstore.Store (which satisfies PtySessionStore); a nil store leaves pty session persistence off (mcp/tests). It mounts no routes → no router rebuild.

func (*Server) SetPtyTranscriptMaxBytes

func (s *Server) SetPtyTranscriptMaxBytes(n int64)

SetPtyTranscriptMaxBytes sets the pty text transcript's tail cap (PTY-01 §四, config key pty.transcript_max_bytes). serve injects ptyrelay.DefaultTranscript… resolved value at startup; hub-less callers (mcp/tests) leave it unset and get the default. <= 0 restores the default.

func (*Server) SetRules

func (s *Server) SetRules(st *rule.Store)

SetRules injects the JOB-06① rule library (serve passes core's store for <config-dir>/rules). Same contract as SetSkills: the /v1/rules routes are always mounted and answer 503 while it is nil.

func (*Server) SetRunners

func (s *Server) SetRunners(runners map[string]config.RunnerConfig)

SetRunners refreshes the runner definitions rendered by GET /v1/runners. The serve hook calls this after Core has rebuilt dynamic worker runners; startup-only runner types remain in the concrete Core registry and are reported as restart-required by the reload result.

func (*Server) SetServerConfig

func (s *Server) SetServerConfig(cfg *config.ServerConfig)

SetServerConfig swaps the live server policy used by auth and worker metadata handlers after a successful core reload. The router itself is unchanged; the whole immutable projection (caller tokens, server policy, root administrators, config-derived grants) is replaced by ONE atomic store, so a request never reads a half-swapped config (design §3「一致性」).

func (*Server) SetSessionInjectCommands

func (s *Server) SetSessionInjectCommands(commands []string)

SetSessionInjectCommands injects the tmux-injection whitelist (SESS-01 §9.1 A, session.inject_commands): the CLI commands a reply may be typed into. Empty keeps the relay's built-in list. Like SetSessionRelayPolicy it is a no-op without a relay service.

func (*Server) SetSessionRelayPolicy

func (s *Server) SetSessionRelayPolicy(idleSec, turnSec int, skipWhenSupervising bool, supervisingWindowSec int)

SetSessionRelayPolicy injects the effective session-relay auto-arm policy (SESS-01 R2 + SUP-01 D): the keyboard idle threshold and the last-human-input fallback threshold, the supervision gate and its look-back window, all in seconds (see config.SessionConfig; 0 disables that criterion). serve calls it with the whole config's effective values — the `session:` block — while a Server built from a bare ServerConfig keeps New's shipped default. No-op without a relay service (a server with no job store).

func (*Server) SetSessionStopJobWait added in v0.158.0

func (s *Server) SetSessionStopJobWait(mode string)

SetSessionStopJobWait injects session.stop_job_wait (gofer-rhux): what a Stop hook does about the session's watched jobs (away / always / never, see config.SessionConfig). The hook decides locally — it is the one holding the keyboard — so the server only carries the value on every session response, which is what lets a hook with no config file of its own (a container) obey the operator. No-op without a relay service.

func (*Server) SetSessionTakeoverAliveSec

func (s *Server) SetSessionTakeoverAliveSec(sec int)

SetSessionTakeoverAliveSec injects session.takeover_alive_sec (the heartbeat window inside which a web takeover is refused as `session_alive`; <= 0 = guard off).

func (*Server) SetSessionWaitBudgets

func (s *Server) SetSessionWaitBudgets(onSec, autoSec int)

SetSessionWaitBudgets injects the Stop-wait budgets (N1 §C): seconds a hook may block for a reply under an explicit `on` switch and under an auto-armed wait (0 = no server cap). Hot-reloaded with the rest of the `session:` block.

func (*Server) SetSettings added in v0.179.0

func (s *Server) SetSettings(svc *settings.Service)

SetSettings wires the extension-settings service (serve builds it over the job store). Without it the /v1/settings routes answer 503; the service is exposed through the same field to the later consumers (work-item drafting, summarizer and steward prompts), which serve hands out through Settings().

func (*Server) SetSkills

func (s *Server) SetSkills(st *skill.Store)

SetSkills injects the JOB-10 skill library (serve passes core's store for <config-dir>/skills). Like SetXfer it needs no router rebuild: the /v1/skills routes are always mounted and answer 503 while no library is wired, so a server without one (mcp, most tests) keeps the identical router.

func (*Server) SetTrackerStore

func (s *Server) SetTrackerStore(store *jobstore.Store)

SetTrackerStore injects the server mirror store used by tracker sync routes.

func (*Server) SetTriggerEngine added in v0.205.0

func (s *Server) SetTriggerEngine(e *trigger.Engine)

SetTriggerEngine installs the inbound trigger engine serve assembled.

func (*Server) SetTunnelPresets

func (s *Server) SetTunnelPresets(st TunnelPresetStore)

SetTunnelPresets injects the preset store (serve wires the metadata store). It mounts no routes, so it does not rebuild the router.

func (*Server) SetUpdateApply added in v0.154.0

func (s *Server) SetUpdateApply(dir string, managed ManagedUpgradeFunc)

SetUpdateApply enables the one-click update: dir keeps the downloads and the apply state; managed is nil for a plain `gofer serve`, which cannot replace itself.

func (*Server) SetUpdateChecker added in v0.153.0

func (s *Server) SetUpdateChecker(c *updatecheck.Checker)

SetUpdateChecker injects the release checker (gofer-6x2n). Without one the update endpoints answer 503.

func (*Server) SetWebPush

func (s *Server) SetWebPush(service WebPushService)

SetWebPush injects W2b after server construction. All routes are registered unconditionally, so no router rebuild is necessary.

func (*Server) SetWorkerEnrollment added in v0.169.0

func (s *Server) SetWorkerEnrollment(svc *workerenroll.Service)

SetWorkerEnrollment injects the worker self-enrollment service. The enrollment routes arrive with the CLI; this only hands the service to the server.

func (*Server) SetWorkerReloader

func (s *Server) SetWorkerReloader(r workerReloader)

SetWorkerReloader injects the worker-reload seam (serve). Mounting no route, it does not rebuild the router: the endpoint is always registered and answers 503 while no reloader is wired.

func (*Server) SetWorkerUpgrader

func (s *Server) SetWorkerUpgrader(u workerUpgrader)

func (*Server) SetWorkerUpgrades

func (s *Server) SetWorkerUpgrades(m *workerupgrade.Manager)

SetWorkerUpgrades injects the staging + upgrade-record store (nil = remote upgrade unavailable, the routes answer 503).

func (*Server) SetXfer

func (s *Server) SetXfer(m *xfer.Manager)

SetXfer injects the XFER-01 transfer manager (serve passes core's). Unlike SetMetrics it needs no router rebuild: the /v1/xfer routes are always mounted and answer 503 while no manager is wired, so a server without transfers (mcp, most tests) keeps the identical router.

func (*Server) Settings added in v0.179.0

func (s *Server) Settings() *settings.Service

Settings returns the extension-settings service, or nil when none is wired.

func (*Server) StartHostedAutostart

func (s *Server) StartHostedAutostart()

StartHostedAutostart restores only stored presets explicitly marked autostart. Forwarder listeners bind immediately; worker dialing remains lazy inside the Forwarder, so a worker reconnect race cannot prevent server startup.

func (*Server) StartNudgeSweeper

func (s *Server) StartNudgeSweeper(stop <-chan struct{})

StartNudgeSweeper runs the session-nudge sweeper (N2 §E) until stop closes: one pass at startup, then every nudgeSweepInterval. It is the server's own goroutine because the relay service lives here; serve only starts it.

func (*Server) Steward

func (s *Server) Steward() *steward.Service

Steward returns the steward service (nil without a job store); serve feeds it config and runs its loop.

func (*Server) StopHostedForwarders

func (s *Server) StopHostedForwarders()

func (*Server) SynthesisEngine added in v0.208.0

func (s *Server) SynthesisEngine() *engine.Engine

SynthesisEngine is the engine behind the explicit run, also driven by serve's built-in daily trigger. nil when the server has no job store; callers treat nil as "no trigger".

func (*Server) TriggerEngine added in v0.205.0

func (s *Server) TriggerEngine() *trigger.Engine

TriggerEngine returns the inbound trigger engine (nil when none was installed).

func (*Server) UserCallerIDs

func (s *Server) UserCallerIDs() []string

UserCallerIDs exposes the already-resolved auth identities to assembly without making webpush parse config tokens a second time.

func (*Server) Work

func (s *Server) Work() *work.Service

Work returns the work-item service (nil without a job store); serve starts its background loop and feeds it config.

type ServerRestartState added in v0.194.0

type ServerRestartState struct {
	ID    string `json:"id"`
	Phase string `json:"phase"`
	Error string `json:"error,omitempty"`
	// Version is the version the restarted server comes back as (this build's).
	Version   string `json:"version,omitempty"`
	StartedAt int64  `json:"started_at"`
	UpdatedAt int64  `json:"updated_at"`
	// The wait-for-idle block, identical to the update's (gofer-dzv3): when it gives up,
	// which jobs block the restart, and how many submits it parked meanwhile.
	WaitDeadline   int64             `json:"wait_deadline,omitempty"`
	WaitTimeoutSec int               `json:"wait_timeout_sec,omitempty"`
	Waiting        []ApplyWaitingJob `json:"waiting,omitempty"`
	Paused         int               `json:"paused,omitempty"`
}

ServerRestartState is the progress of the latest server restart. The phases are the update's waiting_idle / restarting plus the two ways a wait can end without a restart (failed, cancelled); a restart that went through is not observable from the process that asked for it, so the new process reports it as done (see ResumeServerRestart).

type TunnelPresetStore

type TunnelPresetStore interface {
	UpsertTunnelPreset(rec jobstore.TunnelPresetRecord) error
	GetTunnelPreset(name string) (jobstore.TunnelPresetRecord, bool, error)
	ListTunnelPresets() ([]jobstore.TunnelPresetRecord, error)
	DeleteTunnelPreset(name string) error
}

TunnelPresetStore is the narrow persistence seam for those presets, the same shape PtySessionStore uses: the entry layer asks for four operations and *jobstore.Store satisfies it. A nil store leaves the routes mounted but answering 503 (mcp / most tests), which is the degradation /v1/xfer and the config writes already use.

type WebPushService

type WebPushService interface {
	PublicKey() (string, error)
	Subscribe(callerID string, input webpush.SubscriptionInput, userAgent string) (jobstore.PushSubscription, error)
	ListSubscriptions(callerID string) ([]jobstore.PushSubscription, error)
	DeleteSubscription(callerID, endpoint string) (bool, error)
	QueueTestIn(lang i18n.Lang, callerID string) (int, error)
	Act(token, option string) (job.Interaction, error)
}

type WorkerCaps

type WorkerCaps struct {
	Labels        []string     `json:"labels"`
	Projects      []string     `json:"projects"`
	Agents        []string     `json:"agents"`
	AgentCaps     []AgentBrief `json:"agent_caps,omitempty"`
	MaxConcurrent int          `json:"max_concurrent"`
}

WorkerCaps is the worker's capability snapshot after a successful reload — the proof that the new config took effect. It mirrors the hub's caps frame but is redeclared here (like AgentBrief) so httpapi never imports wshub/wsproto; the serve-side adapter constructs it, hence the exported fields.

type WorkerReloadOutcome

type WorkerReloadOutcome struct {
	Status WorkerReloadStatus
	Detail string
	Caps   WorkerCaps
}

WorkerReloadOutcome is the adapter's structured answer to one reload request. It is deliberately (status, detail) rather than a Go error: classifying an error means matching on the types that define it, and those live in wshub — so the matching happens ONCE, in the serve-side adapter, and this package maps a status onto a status code. Detail is the human-readable reason (for WorkerReloadRejected: the worker's verbatim message).

type WorkerReloadStatus

type WorkerReloadStatus string

WorkerReloadStatus classifies the outcome of one worker config reload. It is the transport-agnostic vocabulary the serve-side adapter translates the hub's error taxonomy into, so this package can pick a status code without importing wshub (the D2/G022 boundary — see workerReloader).

const (
	// WorkerReloadApplied: the worker re-read its config and is now running it.
	WorkerReloadApplied WorkerReloadStatus = "applied"
	// WorkerReloadRejected: the worker answered but REFUSED the new config (bad
	// yaml, unknown agent, …) and still runs the previous one. Detail carries its
	// own words and must reach the user unchanged.
	WorkerReloadRejected WorkerReloadStatus = "rejected"
	// WorkerReloadOffline: the worker has no live connection (never connected, or
	// dropped while we waited for the receipt).
	WorkerReloadOffline WorkerReloadStatus = "offline"
	// WorkerReloadTooOld: the worker is connected and healthy but speaks a protocol
	// with no reload frame. It keeps working; it just has to be restarted to pick up
	// a new config.
	WorkerReloadTooOld WorkerReloadStatus = "too_old"
	// WorkerReloadTimedOut: no receipt within the deadline. The reload is NOT known
	// to have failed — the worker may still apply it — so it is reported as "no
	// receipt in time", never as "reload failed".
	WorkerReloadTimedOut WorkerReloadStatus = "timeout"
	// WorkerReloadFailed: anything else (write error, hub not wired, cancelled).
	WorkerReloadFailed WorkerReloadStatus = "failed"
)

type WorkerStatus

type WorkerStatus struct {
	Connected     bool     `json:"connected"`
	LastHeartbeat int64    `json:"last_heartbeat"` // unix millis of the most recent inbound frame
	InFlight      int      `json:"in_flight"`
	Labels        []string `json:"labels,omitempty"`
	Projects      []string `json:"projects,omitempty"`
	// Agents stays the bare agent-key list (validation / selector, back-compat);
	// AgentCaps carries the typed detail (type/interactive) the UI cascade needs.
	Agents    []string     `json:"agents,omitempty"`
	AgentCaps []AgentBrief `json:"agent_caps,omitempty"`
	// Tools are the worker's declared external tools (CFG-16), display only.
	Tools []config.Tool `json:"tools,omitempty"`
	// Node info reported by the worker on register (P1), surfaced for the P4
	// runners observability panel.
	OS   string `json:"os,omitempty"`
	Arch string `json:"arch,omitempty"`
	// Hostname is the worker's self-reported machine hostname; RemoteAddr is the
	// conn's remote address as the hub saw it (may be a NAT/bridge address —
	// hostname is the machine-identifying field).
	Hostname       string `json:"hostname,omitempty"`
	RemoteAddr     string `json:"remote_addr,omitempty"`
	GoferVersion   string `json:"gofer_version,omitempty"`
	UpgradeCapable *bool  `json:"upgrade_capable,omitempty"`
	UpgradeError   string `json:"upgrade_error,omitempty"`
	StartedAt      int64  `json:"started_at,omitempty"` // worker process start, unix seconds
	// ProtocolVersion is the wire version this worker registered with. Surfaced so
	// an operator can spot a too-old worker (reload/policy gated by
	// wsproto.SupportsReload/SupportsPolicy) before a reload/policy push 409s.
	ProtocolVersion int    `json:"protocol_version,omitempty"`
	MessengerStatus string `json:"messenger_status,omitempty"`
	// MessengerDetail and Dirs come from the worker's heartbeat (protocol v16). nil =
	// the worker never reported them (an older build, or no heartbeat yet): the console
	// shows "unknown", not "stopped".
	MessengerDetail *messenger.Snapshot `json:"messenger_detail,omitempty"`
	Dirs            *DirsView           `json:"dirs,omitempty"`
	// Draining is true while the worker is upgrading itself and takes no new jobs.
	Draining       bool              `json:"draining,omitempty"`
	PolicyPending  bool              `json:"policy_pending,omitempty"`
	PolicyRev      int64             `json:"policy_rev,omitempty"`
	AppliedRev     int64             `json:"applied_rev,omitempty"`
	PolicyRejected []PolicyRejection `json:"policy_rejected,omitempty"`
	PolicyDegraded []PolicyDegrade   `json:"policy_degraded,omitempty"`
}

WorkerStatus is the read-only worker view the handler renders (C6/P4). It is produced by the serve-side adapter from the wshub registry snapshot, so httpapi never imports wshub's internal types. Connected=false means offline / never connected (rendered as `disconnected`). The /v1/workers/{id} views serialize it directly, so it carries the API's snake_case field names.

Source Files

Directories

Path Synopsis
Command authzgen writes the generated permission reference (docs/reference/permissions.md) from the running code: the permission catalog and the route declaration table.
Command authzgen writes the generated permission reference (docs/reference/permissions.md) from the running code: the permission catalog and the route declaration table.

Jump to

Keyboard shortcuts

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