module

package
v0.19.0 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: MIT Imports: 15 Imported by: 1 module, 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

Package module is the contract between the Surface core and a module.

A Surface app is the core plus modules, compiled into one binary. A module is primitives plus data plus AI: it brings views (what opens in a window), commands (what the palette, a shortcut or an agent can run) and agent tools, and may declare a local store, live settings and context slots for the embedded agent.

This package is the only part of Surface a module imports. The core lives under core/internal and cannot be reached from a module; whatever a module needs from the core it asks of its Host. That is the seam: a module that compiles against this package alone can later be loaded at run time or served from another process, because a Manifest is plain data apart from its handlers.

A module registers itself from an init function, like a database/sql driver:

func init() { module.Register(New()) }

and an app selects modules by importing them (the generated surface_wiring.go).

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNoAgent: the app's agent cannot take an errand (none is configured, or it is not on
	// the conversation wire).
	ErrNoAgent = errors.New("surface: the app's agent cannot take an errand")
	// ErrAgentBusy: the agent is on a run; ask again later.
	ErrAgentBusy = errors.New("surface: the agent is busy")
)
View Source
var (
	ErrKeyNotFound = errors.New("module: no such key")
	ErrKeyScope    = errors.New("module: a key may carry only the app's own scopes")
	ErrBadKey      = errors.New("module: the credential is not valid")
)

Errors.

View Source
var ErrRefNotFound = errors.New("surface: no such record")

ErrRefNotFound is a Record's answer for a reference with nothing behind it (or nothing the owner may read: the services do not tell the two apart).

Functions

func CheckKeyScopes added in v0.17.0

func CheckKeyScopes(app string, scopes []string) error

CheckKeyScopes enforces Create's rule for an app named app: every scope is "<app>.…".

func IsPublic added in v0.17.0

func IsPublic(h http.Handler) bool

IsPublic reports whether h was marked with Public.

func NormalHostName added in v0.18.0

func NormalHostName(h string) (string, bool)

NormalHostName is a host name as PublicHosts compares it (lowercase, no trailing dot), and false for anything that is not a plain DNS name (an IP, a port, a wildcard, empty).

func ProfileFS added in v0.4.0

func ProfileFS(fsys fs.FS, dir string) fs.FS

ProfileFS is the profile directory dir inside fsys (an embed.FS of the module's package), for Manifest.Profile. It panics when dir is not a valid path: a programming error that must stop the first run, as Register does.

func Public added in v0.17.0

func Public(h http.Handler) http.Handler

Public marks a module route that is served without a signed-in caller, for an app with sign-in: the module authenticates it itself (a device token, a single-use code) or it is meant for anyone who can reach the app (an install script). Use it sparingly:

h.Handle("POST /enroll", module.Public(http.HandlerFunc(enroll)))

With auth off it changes nothing.

func Register

func Register(m Module)

Register adds a module to the binary. It panics on an invalid or repeated id: both are programming errors that must stop the build's first run, not surface later.

func Registered

func Registered() []string

Registered lists the ids of every module compiled into the binary, sorted.

func StatusTone added in v0.4.0

func StatusTone(status string) string

StatusTone is the usual tone of a status word: done is success, blocked is danger, and so on. For a module projecting its own records onto RefStatus.

func ValidID

func ValidID(id string) bool

ValidID reports whether id can name a module.

func ValidRefKind added in v0.4.0

func ValidRefKind(s string) bool

ValidRefKind reports whether s can name a reference kind.

func WithActor added in v0.2.0

func WithActor(ctx context.Context, a Actor) context.Context

WithActor returns a context that says who is acting.

func WithUser added in v0.17.0

func WithUser(ctx context.Context, u User) context.Context

WithUser returns a context carrying the signed-in user. The core sets it; a module may set it for work it does on a user's behalf outside a request.

Types

type Actor added in v0.2.0

type Actor string

Actor is who is doing something to the app: the owner at the page, the embedded agent, a reflex, or a client from outside (MCP, the HTTP tools, the CLI). The desk keeps it on the windows it opens, and holds to the owner's say over windows that are theirs (docs/desk-rules.md).

The core sets it where a request comes in; a module only reads it. A context that carries none is treated as the owner's, which is how the desk behaved before actors existed: a module acting on its own (a timer, a background job) is not held to the agent's etiquette unless it says so with WithActor.

const (
	ActorOwner   Actor = "owner"
	ActorAgent   Actor = "agent"
	ActorReflex  Actor = "reflex"
	ActorOutside Actor = "outside"
)

func ActorOf added in v0.2.0

func ActorOf(ctx context.Context) Actor

ActorOf says who is acting, or "" when the context does not say.

func (Actor) Delegate added in v0.2.0

func (a Actor) Delegate() bool

Delegate reports whether the actor acts for the owner rather than as the owner: the agent, a reflex, or an outside client. The owner and an unnamed actor are not delegates.

type Agent added in v0.4.0

type Agent interface {
	// Ask hands the agent a turn that did not come from the owner: the module's own errand,
	// such as mail that asks for something. It runs on the agent's conversation, marked as the
	// module's, and returns its run id without waiting for it. ErrAgentBusy while a run is
	// active (try again later); ErrNoAgent when the app's agent cannot take one.
	Ask(ctx context.Context, a Ask) (string, error)
	// Gateway is the model gateway the app's agent config names, read at the moment of the
	// call: for a module that calls a model itself, and only on the owner's action (the
	// Workbench's eval runs). It carries the key file's path, never the key. Only a module
	// whose manifest declares Gateway gets it; otherwise, and when the config names no model,
	// gateway or key file, ErrNoAgent.
	Gateway(ctx context.Context) (Gateway, error)
}

Agent is the app's embedded agent as a module reaches it.

type Ask added in v0.4.0

type Ask struct {
	// Title names it in a line ("Mail for you: 3 requests").
	Title string `json:"title"`
	// Text is what the agent is asked to do. Write it as the module, not as the owner.
	Text string `json:"text"`
}

Ask is an errand for the agent.

type Base

type Base struct{}

Base gives a module no-op Start and Stop, for one that needs neither.

func (Base) Start

func (Base) Start(context.Context, Host) error

Start does nothing.

func (Base) Stop

func (Base) Stop(context.Context) error

Stop does nothing.

type Caller added in v0.17.0

type Caller struct {
	// ID is the principal: "user:<id>" for a person (or a token minted from their
	// session), "key:<id>" for an API key.
	ID     string
	Kind   string // user or service
	Name   string
	Scopes []string
	// For is the person an API key acts for ("user:<id>", the key's maker), "" for a person's
	// own session or token and for keys a module or the CLI made. Attribute a key's work to it.
	For string
}

Caller is who a verified credential belongs to.

func (Caller) HasScope added in v0.17.0

func (c Caller) HasScope(want string) bool

HasScope reports whether the caller holds want, with the same wildcard rules as User.

type Card

type Card struct {
	ID string `json:"id"`
	// Kind names the card's shape. The core's own are "info", "error", "confirm", "prompt",
	// "choice", "form", "approval", "progress" and "plan"; a module may show a kind of its
	// own, which the page draws with the renderer registered for it.
	Kind string `json:"kind"`
	// Version is the version of the kind's payload. Empty means "1".
	Version string `json:"version,omitempty"`
	Title   string `json:"title,omitempty"`
	// Source is who showed it: a module's id, or "agent".
	Source string `json:"source,omitempty"`
	// Subject is what the card is about (a run, a file). A new card with the same kind,
	// source and subject as an open one replaces it.
	Subject string `json:"subject,omitempty"`
	// Risk is "low", "medium" or "high", for a card that asks to approve something.
	Risk string `json:"risk,omitempty"`
	// Blocking says the sender is waiting on the answer.
	Blocking bool `json:"blocking,omitempty"`
	// Payload is the kind's own content.
	Payload json.RawMessage `json:"payload,omitempty"`
	// Status is empty while the card is open, then "submitted", "canceled", "expired",
	// "superseded", "failed" or "abandoned" (the agent's run that asked it ended while it
	// waited).
	Status string `json:"status,omitempty"`
	// Late is set when the user answered an agent's question after the agent stopped
	// waiting for it (the card was abandoned or expired). A late answer is taken once; a
	// submitted one is handed to the agent as a message.
	Late bool `json:"late,omitempty"`
	// Delivered is when a late answer reached the agent (RFC 3339). Empty: not yet.
	Delivered string `json:"delivered,omitempty"`
	// Outcome is what the user answered, once they have.
	Outcome *CardOutcome `json:"outcome,omitempty"`
	// Revision counts changes, so a page can tell a newer card from an older one.
	Revision int `json:"revision,omitempty"`
	// SupersededBy is the id of the card that replaced this one.
	SupersededBy string `json:"superseded_by,omitempty"`
	Created      string `json:"created,omitempty"`
	Updated      string `json:"updated,omitempty"`
	Responded    string `json:"responded,omitempty"`
	// ExpiresAt is when an unanswered card lapses (RFC 3339). Empty: it does not.
	ExpiresAt string `json:"expires_at,omitempty"`
}

Card is something shown to the user outside a window: a notice, a question, a request to approve, progress on work. The sender says what it is (Kind and Payload); the page picks how it is drawn and where. What the user answers comes back as its Outcome. The server holds the card's state: a card is open until it has a Status.

type CardAnswer

type CardAnswer struct {
	QuestionID string `json:"questionId"`
	Value      any    `json:"value"`
	Note       string `json:"note,omitempty"`
}

CardAnswer is one answer to one question.

type CardDecision

type CardDecision struct {
	ItemID string `json:"itemId"`
	Action string `json:"action"`
	Note   string `json:"note,omitempty"`
}

CardDecision is one decision about one item ("approve", "reject", "skip").

type CardOutcome

type CardOutcome struct {
	Status    string         `json:"status"`
	Data      map[string]any `json:"data,omitempty"`
	Answers   []CardAnswer   `json:"answers,omitempty"`
	Decisions []CardDecision `json:"decisions,omitempty"`
}

CardOutcome is what the user did with a card: answered it ("submitted") or declined ("canceled"). The three channels are kept apart because they are different things: free-form data (a form's values), answers to questions, and decisions about items.

type Cards

type Cards interface {
	// Show puts a card in front of the user and returns it with its id.
	Show(ctx context.Context, c Card) (Card, error)
	// Update replaces an open card's payload (progress moving on), and its title when one
	// is given.
	Update(ctx context.Context, id string, title string, payload json.RawMessage) (Card, error)
	// End closes a card from the sender's side: status is "superseded", "expired",
	// "canceled", "failed" or "abandoned". A card already closed is returned as it is.
	End(ctx context.Context, id, status string) (Card, error)
	// Respond records the user's answer. A card that is no longer open refuses it, except
	// an agent's question that was abandoned or expired: that takes one late answer.
	Respond(ctx context.Context, id string, o CardOutcome) (Card, error)
	// Await returns the card once it is closed, or when ctx ends.
	Await(ctx context.Context, id string) (Card, error)
	Get(ctx context.Context, id string) (Card, bool, error)
	// List returns the open cards, oldest first; with all, the closed ones as well
	// (newest 200).
	List(ctx context.Context, all bool) ([]Card, error)
}

Cards shows cards to the user and reads what they answered.

type Command

type Command struct {
	// ID is unique in the app: "<module>.<verb>".
	ID      string `json:"id"`
	Title   string `json:"title"`
	Section string `json:"section,omitempty"`
	// Keywords are extra words the palette matches on.
	Keywords string `json:"keywords,omitempty"`
	// Keys is the default shortcut, written like "ctrl+alt+t". The user can change it.
	Keys string `json:"keys,omitempty"`
	// Hidden keeps the command out of the palette list; it can still be run.
	Hidden bool `json:"hidden,omitempty"`
	// Run does it. args is whatever the caller passed, or nil. The returned value, when not
	// nil, is given back to the caller as JSON.
	Run func(ctx context.Context, h Host, args map[string]any) (any, error) `json:"-"`
}

Command is a named action. It shows in the palette, can have a shortcut, and can be run by a view, by the agent (through the desk's own run-command tool) or from outside.

type Config

type Config interface {
	String(key string) string
	Bool(key string) bool
	Int(key string) int
	// Set stores a value. It is validated against the setting's type.
	Set(ctx context.Context, key string, value any) error
	// Watch calls fn after the setting changes, with its new value. The returned function
	// stops the watch.
	Watch(key string, fn func(value any)) (stop func())
}

Config is a module's live settings. A read always returns the current value: the user's when one is set, the manifest's default otherwise. Nothing is cached by the caller, so a change takes effect on the next read; Watch is for a module that must act on the change.

type Desk

type Desk interface {
	// Open opens a window of a view, or brings the matching one forward.
	Open(ctx context.Context, view string, opts OpenOptions) (Window, error)
	Close(ctx context.Context, window string) error
	Focus(ctx context.Context, window string) error
	SetTitle(ctx context.Context, window, title string) error
	// SetArgs replaces what the window was opened with (the page a browser window is on).
	SetArgs(ctx context.Context, window string, args map[string]any) error
	Windows(ctx context.Context) []Window
	// Focused is the window in front.
	Focused(ctx context.Context) (Window, bool)
	// Context is what a window is showing; the focused one when window is "".
	Context(ctx context.Context, window string) (WindowContext, bool)

	// Arrange replaces the open windows with a layout's. Windows holding unsaved work
	// are kept.
	Arrange(ctx context.Context, l Layout) error
	// Capture returns the present arrangement as a Layout.
	Capture(ctx context.Context) Layout
	// SaveLayout keeps a layout under its name, replacing one of the same name.
	SaveLayout(ctx context.Context, l Layout) error
	Layouts(ctx context.Context) ([]Layout, error)
	Layout(ctx context.Context, name string) (Layout, bool, error)
	DeleteLayout(ctx context.Context, name string) error
}

Desk is the windows and layouts, as a module may use them.

type Event

type Event struct {
	// Topic is dotted: "notes.saved", "desk.focus". A module's own topics start with its id.
	Topic string `json:"topic"`
	// Data is small and JSON.
	Data json.RawMessage `json:"data,omitempty"`
}

Event is something that happened.

type Events

type Events interface {
	// Publish sends an event. data is marshaled to JSON.
	Publish(topic string, data any)
	// Subscribe calls fn for each event whose topic is prefix or starts with prefix + ".".
	// An empty prefix takes every event. fn must not block.
	Subscribe(prefix string, fn func(Event)) (stop func())
}

Events is the app's event bus. Events also reach the page, where a view can listen for them and refresh; that is how a view learns that the agent changed its data.

type Gateway added in v0.4.0

type Gateway struct {
	Model string `json:"model"`
	URL   string `json:"url"`
	// KeyFile is the path of the file that holds the key. Read it when a request is made;
	// never log it or show the key. It is not marshaled.
	KeyFile string `json:"-"`
}

Gateway is a model gateway as the app's agent config names it: an Anthropic-compatible endpoint (requests go to <URL>/v1/messages with the key as a bearer token).

type Host

type Host interface {
	// ModuleID is the id of the module this Host belongs to.
	ModuleID() string
	Log() *slog.Logger
	// Desk is the windows and layouts.
	Desk() Desk
	// Store is the module's local database, or nil when its manifest declares none.
	Store() *sql.DB
	// DataDir is a directory of the module's own inside the app's data directory, for
	// files that are not database rows. It exists.
	DataDir() string
	// Config is the module's live settings.
	Config() Config
	// Events is the app's event bus.
	Events() Events
	// Marks are the collaboration marks: notes pinned to a part of something.
	Marks() Marks
	// Cards are what the app shows the user outside a window: a notice, a question, a
	// request to approve, progress.
	Cards() Cards
	// Handle serves an HTTP handler for the module's views at /api/m/<id>/<pattern>.
	// pattern is a net/http pattern without the prefix ("GET /items/{id}"). Call it from
	// Start; routes cannot be added once the app serves.
	Handle(pattern string, handler http.Handler)
	// RunCommand runs any command in the app by id.
	RunCommand(ctx context.Context, id string, args map[string]any) (any, error)
	// Agent is the app's embedded agent, for a module to hand it an errand of its own.
	Agent() Agent
}

Host is what the core offers one module. Each module gets its own: its store, its settings and its routes are scoped to it.

type Key added in v0.17.0

type Key struct {
	ID     string `json:"id"`
	Secret string `json:"-"`
}

Key is a minted key: Secret is the bearer credential, shown only here.

type KeyRequest added in v0.17.0

type KeyRequest struct {
	// Name says what the key is for ("orchestrator s_1234"); it shows in the key list.
	Name   string
	Scopes []string
	// TTL is how long the key lives; 0 is until revoked.
	TTL time.Duration
	// CreatedBy is who the key acts for (a user id); "" records the module itself.
	CreatedBy string
}

KeyRequest is a key to mint.

type Keys added in v0.17.0

type Keys interface {
	// Create mints a key with the given scopes. Scopes must be the app's own
	// ("<app>.<anything>"); "*" and other apps' scopes are refused. The key string is
	// returned once; only its hash is kept.
	Create(ctx context.Context, r KeyRequest) (Key, error)
	// Revoke ends a key at once (it is refused by its very next use). Revoking a key that
	// is already revoked is not an error; an unknown id is ErrKeyNotFound.
	Revoke(ctx context.Context, id string) error
	// Verify checks a bearer credential (a key, a session, a token minted from either) and
	// says whose it is. A module whose route is module.Public authenticates callers with it.
	Verify(ctx context.Context, token string) (Caller, error)
}

Keys mints and checks API keys for an app with sign-in (surface.yaml auth: identity), for a module that hands a credential to something outside the page: an agent it launches, a device, a webhook. A key is an identity API key like any other (it shows in the app's key list, the owner can revoke it), so a module never runs a token store of its own.

It is optional: KeysOf reports false when the app has no sign-in (or the host does not provide keys), and the module then falls back to whatever it did before.

func KeysOf added in v0.17.0

func KeysOf(h Host) (Keys, bool)

KeysOf returns the host's key service, and false when the app has none (no sign-in).

type Layout

type Layout struct {
	Name  string `json:"name"`
	About string `json:"about,omitempty"`
	// Mode is "tile" (the first window on the left, the rest stacked on the right) or
	// "float" (every window floating).
	Mode string `json:"mode"`
	// Ratio is the first window's share of the width when tiling (0.2 to 0.8). Zero keeps it.
	Ratio   float64        `json:"ratio,omitempty"`
	Windows []LayoutWindow `json:"windows"`
	// Setup is whatever goes with the arrangement: the user's mode, the reflexes that are
	// on while it is in use. The core reads the keys it knows ("mode", "reflexes",
	// "instructions"); a module may keep its own under its id.
	Setup map[string]any `json:"setup,omitempty"`
	// Tree is the exact arrangement as the desk captured it (how the windows are split,
	// tabbed together and sized), naming each window by its place in Windows. It is the
	// desk's to read and write; leave it out and the desk arranges Windows by Mode and
	// Ratio, which is all a module composing a layout needs to give.
	Tree json.RawMessage `json:"tree,omitempty"`
}

Layout is an arrangement of windows the user can come back to: which views are open, with what, and how they are placed. Saved under a name, it is a saved view.

type LayoutWindow

type LayoutWindow struct {
	View  string         `json:"view"`
	Key   string         `json:"key,omitempty"`
	Title string         `json:"title,omitempty"`
	Args  map[string]any `json:"args,omitempty"`
	// Rect is where a floating window sits, in CSS pixels; nil lets the desk place it.
	Rect *Rect `json:"rect,omitempty"`
	// Floating takes the window out of the tiling. Focus gives it the focus.
	Floating bool `json:"floating,omitempty"`
	Focus    bool `json:"focus,omitempty"`
}

LayoutWindow is one window of a Layout.

type Level

type Level string

Level says how much a tool call changes, and so whether the owner is asked first.

const (
	// LevelRead looks and changes nothing. Never asks.
	LevelRead Level = "read"
	// LevelAct changes what is on screen and is undone as easily (open a window). Never asks.
	LevelAct Level = "act"
	// LevelWrite changes data or reaches outside the app. Asks; the answer can stand.
	LevelWrite Level = "write"
	// LevelConfirm is its own decision each time (deleting, running a command). Always asks.
	LevelConfirm Level = "confirm"
)

type Manifest

type Manifest struct {
	// ID names the module: lower case letters, digits and dashes. It prefixes the module's
	// routes (/api/m/<id>/), its settings and its events.
	ID string `json:"id"`
	// Title is the module's name as a person reads it.
	Title string `json:"title"`
	// About is one line on what the module is for.
	About   string `json:"about,omitempty"`
	Version string `json:"version,omitempty"`

	Views    []View    `json:"views,omitempty"`
	Commands []Command `json:"commands,omitempty"`
	Tools    []Tool    `json:"tools,omitempty"`
	// Palette registers asynchronous search providers; handlers are bound to this module's Host.
	Palette []PaletteProvider `json:"palette,omitempty"`

	// Store, when set, gives the module a local SQLite database of its own.
	Store *Store `json:"store,omitempty"`
	// Settings are the module's live settings. They are kept in the app's database and a
	// change reaches the module without a restart (Host.Config).
	Settings []Setting `json:"settings,omitempty"`
	// Slots are what the module feeds the embedded agent's context when its work is in front.
	Slots []Slot `json:"slots,omitempty"`
	// Around is a few lines the agent carries with every message, whatever the slot: what
	// waits on the owner, what came back while they were away. "" adds nothing. It runs on
	// every message, so it reads what the module already holds; the core bounds its time and
	// caps it at 1500 characters. Optional.
	Around func(ctx context.Context, h Host) (string, error) `json:"-"`
	// Refs are the kinds of reference the module resolves: the records it owns that may be
	// named in any text (a task id, a path) and shown there as a chip with a preview. Each
	// kind is declared by one module. Optional.
	Refs []RefKind `json:"refs,omitempty"`
	// Profile is the module's agent profile: a Nanite agent directory without host.yaml or
	// .mcp.json (agent.md, and optionally skills/, context/, variants/, tools/ and
	// steering.json), kept in modules/<id>/profile/ and embedded:
	//
	//	//go:embed all:profile
	//	var profileFiles embed.FS
	//	... Profile: module.ProfileFS(profileFiles, "profile"),
	//
	// While the module's window is in front, or after an explicit switch, the app's agent
	// works as this profile: same conversation, tools, approvals and identity, with the
	// profile's instructions, context, skills and helper variants. The app owns the runtime,
	// the model, MCP and permissions; a profile cannot change them. A profile with no agent.md
	// is an empty slot (declared, not yet written) and is ignored. Optional; nil is none.
	// The format is in docs/writing-a-module.md.
	Profile fs.FS `json:"-"`
	// Gateway declares that the module calls a model itself, on the owner's action, and so
	// needs Host.Agent().Gateway. A module that does not declare it gets ErrNoAgent there.
	Gateway bool `json:"gateway,omitempty"`
}

Manifest is what a module brings to the app.

The MVP contract is Views, Commands and Tools. Store, Settings, Slots and Profile are optional. A module's skills and its agent's internal helpers come with its Profile. Planned additions (not fields yet, so nothing depends on a guess at their shape): data and service dependencies, and permissions (what the agent may do in the module without asking, put to the user at install).

type Mark

type Mark struct {
	ID string `json:"id"`
	// Ref is what the mark is on, as WindowContext.Ref names it.
	Ref string `json:"ref"`
	// Anchor is the part pointed at, in the module's own terms.
	Anchor json.RawMessage `json:"anchor,omitempty"`
	// Quote is the text pointed at, when the anchor is a passage.
	Quote string `json:"quote,omitempty"`
	Body  string `json:"body"`
	// Author is "owner" or "agent".
	Author string `json:"author"`
	// Status is "open" or "resolved".
	Status  string `json:"status"`
	Created string `json:"created"`
	// Replies are the notes added since, oldest first.
	Replies []MarkReply `json:"replies,omitempty"`
}

Mark is a note pinned to a part of something: a passage, a line range, a region, a node. Marks are how the owner and the agent point at the same thing and talk about it.

type MarkReply

type MarkReply struct {
	Body    string `json:"body"`
	Author  string `json:"author"`
	Created string `json:"created"`
}

MarkReply is one reply on a mark.

type Marks

type Marks interface {
	Add(ctx context.Context, m Mark) (Mark, error)
	// List returns the marks on a ref, oldest first. An empty ref lists every open mark.
	List(ctx context.Context, ref string) ([]Mark, error)
	Reply(ctx context.Context, id string, r MarkReply) (Mark, error)
	Resolve(ctx context.Context, id string) error
}

Marks are the collaboration marks. They live in the core, so every module's documents are marked the same way and one panel can list them all.

type Module

type Module interface {
	// Manifest says what the module brings. It is read once, at boot, and must not change.
	Manifest() Manifest
	// Start is called once, after the module's store is open and before the app serves.
	// The Host is the module's for its whole life and is safe to keep.
	Start(ctx context.Context, h Host) error
	// Stop is called once at shutdown, in reverse start order.
	Stop(ctx context.Context) error
}

Module is one unit of a Surface app.

func Lookup

func Lookup(id string) (Module, bool)

Lookup returns the registered module with this id.

type OpenOptions

type OpenOptions struct {
	Args  map[string]any `json:"args,omitempty"`
	Key   string         `json:"key,omitempty"`
	Title string         `json:"title,omitempty"`
	// Background opens the window without giving it the focus.
	Background bool `json:"background,omitempty"`
	// Reason says what the window is for, for the owner and for whoever reads the desk later.
	Reason string `json:"reason,omitempty"`
	// Retention is "transient" or "deliverable" (the default); see Window.
	Retention string `json:"retention,omitempty"`
}

OpenOptions say how a window opens.

type PaletteProvider added in v0.10.0

type PaletteProvider struct {
	ID     string                                                             `json:"id"` // local to the module, same syntax as a module id
	Title  string                                                             `json:"title"`
	Mode   string                                                             `json:"mode,omitempty"` // commands (default) or tabs
	Search func(context.Context, Host, PaletteQuery) ([]PaletteResult, error) `json:"-"`
}

PaletteProvider contributes read-only, asynchronous search to the command palette. Search must honor ctx cancellation, read live settings and return at most q.Limit rows. It must never change state: only selecting a result runs its action.

type PaletteQuery added in v0.10.0

type PaletteQuery struct {
	Text          string
	Limit         int
	Scope         string // all or focused (tabs only)
	FocusedWindow string // supplied by the core, not the caller
}

type PaletteRef added in v0.10.0

type PaletteRef struct {
	Kind      string `json:"kind"`
	Canonical string `json:"canonical"`
}

PaletteRef is an identity in Cite, resolved/opened through its existing resolver.

type PaletteResult added in v0.10.0

type PaletteResult struct {
	ID          string      `json:"id"`
	Title       string      `json:"title"`
	Description string      `json:"description,omitempty"`
	Icon        string      `json:"icon,omitempty"`
	Ref         *PaletteRef `json:"ref,omitempty"`
	Command     *RefOpen    `json:"command,omitempty"`
	Window      string      `json:"window,omitempty"`
	Close       bool        `json:"close,omitempty"`
}

PaletteResult has one action: Ref, Command, or Window. IDs are stable within a provider. Window results focus an existing desk window; Close offers its normal close action.

type PublicHosts added in v0.18.0

type PublicHosts interface {
	// Set replaces the names this module adds (host names, no port), live. Nil removes them.
	// Invalid names (IPs need no listing; wildcards, ports and empty names are refused) are
	// skipped and returned.
	Set(names []string) (skipped []string)
}

PublicHosts lets a module have the app answer at more host names, for its module.Public routes only, while it runs. The app's host guard (against DNS rebinding) otherwise answers only to IPs, localhost and the names in SURFACE_ALLOWED_HOSTS. A module uses this when a name it no longer serves is still dialed by its own clients: a hub whose public URL changed keeps taking its runners' connections at the old name until they have moved, then drops it.

Only use names the app's operator configured (a previous public URL's), never one a request supplied. The page, sign-in and every route not marked module.Public are not answered at them.

func PublicHostsOf added in v0.18.0

func PublicHostsOf(h Host) (PublicHosts, bool)

PublicHostsOf returns the host's PublicHosts, and false when the app has none (an older core, or a test host without it).

type Rect

type Rect struct {
	X int `json:"x"`
	Y int `json:"y"`
	W int `json:"w"`
	H int `json:"h"`
}

Rect is a rectangle in CSS pixels.

type RefEntity added in v0.4.0

type RefEntity struct {
	Title    string `json:"title"`
	Subtitle string `json:"subtitle,omitempty"`
	// Description is a short preview: a few lines, plain text.
	Description string     `json:"description,omitempty"`
	Status      *RefStatus `json:"status,omitempty"`
	Fields      []RefField `json:"fields,omitempty"`
	// UpdatedAt is when the thing last changed (RFC 3339), for "updated 3m ago".
	UpdatedAt string `json:"updatedAt,omitempty"`
	// ChipLabel is what the inline chip says once resolved ("Task: Fix the thing"). Empty:
	// what was written.
	ChipLabel string `json:"chipLabel,omitempty"`
	// URL is where the thing lives outside the app, offered as a link on the card.
	URL string `json:"url,omitempty"`
	// Open is what opening the reference does in the app: a command and its arguments ("work.open"
	// with the workspace and item). Nil: the core's record window shows it.
	Open *RefOpen `json:"open,omitempty"`
	// Body is the whole record, for the record window. Only a Record fills it. It is Markdown,
	// or a JSON document (text that parses as a JSON object or array, such as a Caster doc a
	// tool wrote): the page draws that as labeled fields and lists, with the raw JSON a toggle
	// away. A Description is never a fragment of JSON text: summarize the document instead.
	Body string `json:"body,omitempty"`
}

RefEntity is what a reference stands for, in the one shape every kind is drawn with: the chip's label, the preview card, and the record window.

type RefField added in v0.4.0

type RefField struct {
	Label string `json:"label"`
	Value string `json:"value"`
	// Mono sets the value in the monospace face (an id, a path).
	Mono bool `json:"mono,omitempty"`
}

RefField is one line of the card: a label and a value.

type RefKind added in v0.4.0

type RefKind struct {
	// Kind names the kind in the app: dotted lower case, "<system>.<thing>" ("torque.task",
	// "fragments.fragment"), or one word ("path"). It is the kind id the page's detector uses.
	Kind string `json:"kind"`
	// Label is the kind as a person reads it ("Torque task").
	Label string `json:"label"`
	// ID, when set, is what an id of this kind looks like. An id that does not match is not
	// passed to Resolve or Record: it is not found.
	ID *regexp.Regexp `json:"-"`
	// Ready reports whether the kind can be resolved now (its service is configured). Nil is
	// always. Read the module's settings here, at the moment of use. It must be quick.
	Ready func(ctx context.Context, h Host) bool `json:"-"`
	// Resolve looks up a batch of ids (at most 50) and returns what it found, by id. An id
	// missing from the map was not found. An error fails the whole batch (the service is
	// down), which the page shows as an error it may retry, not as "not found".
	Resolve func(ctx context.Context, h Host, ids []string) (map[string]RefEntity, error) `json:"-"`
	// Record reads one reference whole, with its Body, for the record window. Nil means the
	// kind has no more to show than its preview. ErrRefNotFound when there is no such record.
	Record func(ctx context.Context, h Host, id string) (RefEntity, error) `json:"-"`
}

RefKind is a kind of reference a module resolves: a Torque task id, a fragment, a path in one of the owner's places. The page finds references in any text (detection is the page's, web/src/cite); when it shows one as a chip, the core asks the module that declared the kind what it is (GET /api/cite/resolve) and, when the owner opens it, for the whole record (GET /api/cite/record).

Resolving is reading. A Resolve or Record must never write anything, here or anywhere it reaches: the page asks for every reference it shows, without the owner doing anything.

type RefOpen added in v0.4.0

type RefOpen struct {
	Command string         `json:"command"`
	Args    map[string]any `json:"args,omitempty"`
}

RefOpen is a command the page runs to open a reference in the app's own window.

type RefStatus added in v0.4.0

type RefStatus struct {
	Label string `json:"label"`
	// Tone is one of neutral, info, success, warning, danger.
	Tone string `json:"tone"`
}

RefStatus is a record's state as a label and a tone.

type Render

type Render struct {
	Kind  RenderKind `json:"kind"`
	Entry string     `json:"entry"`
}

Render names a view's body.

func Component

func Component(entry string) Render

Component is the Render of a compiled-in frontend component.

type RenderKind

type RenderKind string

RenderKind is how a view's body is drawn.

const (
	// RenderComponent is a frontend component compiled into the app, named by Entry: the
	// key the module's web entry exports it under. The MVP's only kind.
	RenderComponent RenderKind = "component"
	// RenderFrame is a page the module serves, shown in a frame; Entry is its path under
	// the module's routes. Reserved for run-time loaded and generated modules.
	RenderFrame RenderKind = "frame"
)

type Setting

type Setting struct {
	// Validate checks a coerced value before persistence. It must not read settings.
	Validate func(any) error `json:"-"`
	Key      string          `json:"key"`
	Title    string          `json:"title"`
	About    string          `json:"about,omitempty"`
	Type     SettingType     `json:"type"`
	// Default is the value until the user sets one. It must match Type.
	Default any `json:"default"`
	// Options are the allowed values of a SettingEnum.
	Options []string `json:"options,omitempty"`
	// Owner marks a setting only the owner changes (the page, the CLI, the HTTP API): the
	// agent's settings_set refuses it. For what decides where a credential goes, or which.
	Owner bool `json:"owner,omitempty"`
}

Setting is one live setting of a module. Its full key in the app is "<module>.<Key>".

type SettingType

type SettingType string

SettingType is the type of a setting's value.

const (
	SettingString SettingType = "string"
	SettingBool   SettingType = "bool"
	SettingInt    SettingType = "int"
	SettingEnum   SettingType = "enum"
	SettingObject SettingType = "object"
)

The setting types.

type Situation

type Situation struct {
	// Focused is the window in front, when there is one.
	Focused *WindowContext `json:"focused,omitempty"`
	// Windows are all the open windows.
	Windows []Window `json:"windows,omitempty"`
	// Mode is the user's mode, when one is set ("writing", "triage").
	Mode string `json:"mode,omitempty"`
	// Layout is the saved layout in use, when there is one.
	Layout string `json:"layout,omitempty"`
	// Input is the user's message, when a turn is being assembled.
	Input string `json:"input,omitempty"`
}

Situation is what is happening when slots are chosen and filled.

type Slot

type Slot struct {
	// Name is unique in the app: usually the module id.
	Name string `json:"name"`
	// About is the kind of work, as the agent is told it.
	About string `json:"about"`
	// Views are the views whose window in front selects this slot.
	Views []string `json:"views,omitempty"`
	// Modes are user modes that select this slot whatever is in front. Reserved for the
	// classifier; the core matches them when a mode is set.
	Modes []string `json:"modes,omitempty"`
	// Tools are top of mind here, by name. The agent's other tools stay available.
	Tools []string `json:"tools,omitempty"`
	// Instructions are standing guidance for this kind of work.
	Instructions string `json:"instructions,omitempty"`
	// Where says where the state of this kind of work is kept, for finding what a note lacks.
	Where string `json:"where,omitempty"`
	// Knowledge returns what the agent should know right now (the open document's outline,
	// today's items). It is called when the slot becomes active and must be quick. Optional.
	Knowledge func(ctx context.Context, h Host, s Situation) (string, error) `json:"-"`
}

Slot is what a module feeds the embedded agent when one kind of work is in front, so one agent does not have to hold everything at once. The core decides which slots are active for a turn (today from the view in front; later from a classifier over input, activity and workspace) and assembles the agent's context from them.

type Store

type Store struct {
	// Migrations holds numbered SQL files ("0001_init.sql", "0002_tags.sql") in Dir. Each
	// runs once, in name order, inside a transaction.
	Migrations fs.FS `json:"-"`
	// Dir is the directory inside Migrations. Empty means its root.
	Dir string `json:"-"`
}

Store declares a module's local store: a SQLite database of its own in the app's data directory, opened and migrated by the core before Start and reached with Host.Store.

Remote stores with a cache come later; they will be a second kind here, not a change to this one.

type Tool

type Tool struct {
	// Name is unique in the app: "<module>_<verb>".
	Name        string `json:"name"`
	Description string `json:"description"`
	// Input is the JSON Schema of the tool's input object.
	Input json.RawMessage `json:"input_schema"`
	// Level defaults to LevelWrite when empty or unknown.
	Level Level `json:"level"`
	// Describe says what one call will do in a plain line, for the permission question and
	// the call's row in the thread. Optional.
	Describe func(input json.RawMessage) string `json:"-"`
	// Run does it. The returned value is what the model is told: a string as is, anything
	// else as JSON. An error is reported to the model as a failed call.
	Run func(ctx context.Context, h Host, input json.RawMessage) (any, error) `json:"-"`
}

Tool is something the agent can call. The same tools are offered to outside agents through the app's MCP endpoint.

type User added in v0.17.0

type User struct {
	// ID is the account id ("usr_…"), or the API key id for a machine caller.
	ID string `json:"id"`
	// Kind is "user" for a person and "service" for an API key or a token minted from one.
	Kind        string `json:"kind"`
	Username    string `json:"username,omitempty"`
	DisplayName string `json:"display_name,omitempty"`
	// Role is the person's role (owner, admin, member, guest), "" for a machine caller.
	Role string `json:"role,omitempty"`
	// Scopes are the effective scopes: the account's own and its role's.
	Scopes []string `json:"scopes"`
	// For is, for an API key a person made (the account menu's API keys), that person
	// ("user:<id>"): attribute the key's work to them. "" for a person and for other keys.
	For string `json:"for,omitempty"`
}

User is who signed in, for an app whose surface.yaml sets auth: identity. The core puts it on the context of every request it lets through (UserOf); with auth off there is none. A module reads it to attribute records (created_by) and to decide what the person may do beyond the app-wide rule (reads need "<app>.read", writes "<app>.use"): an admin-only action checks HasScope("<app>.admin").

func UserOf added in v0.17.0

func UserOf(ctx context.Context) (User, bool)

UserOf returns the signed-in user, and false when there is none (auth off, or work the module started itself).

func (User) HasScope added in v0.17.0

func (u User) HasScope(want string) bool

HasScope reports whether the user holds want: exactly, through "*", or through "<app>.*" for "<app>.<anything>".

func (User) Person added in v0.17.0

func (u User) Person() bool

Person reports whether the caller is a signed-in person rather than a machine.

type View

type View struct {
	// ID is unique in the app. Use the module id for its main view and "<module>.<name>"
	// for the others.
	ID    string `json:"id"`
	Title string `json:"title"`
	// Icon is a lucide icon name ("sticky-note").
	Icon string `json:"icon,omitempty"`
	// Width and Height are the size a floating window opens at, in CSS pixels.
	Width  int `json:"width,omitempty"`
	Height int `json:"height,omitempty"`
	// Menu lists the view under Apps in the launcher and gives it an "Open <title>" command.
	Menu bool `json:"menu,omitempty"`
	// Multi allows several windows of this view. Opening it again makes a new window unless
	// one was opened with the same key, which is brought forward instead.
	Multi bool `json:"multi,omitempty"`
	// DefaultKey is the key a Multi window gets when opened with none, so a plain "open"
	// brings one main window forward.
	DefaultKey string `json:"default_key,omitempty"`
	// Tiling says how multiple windows of this module behave when open together: "tile"
	// autotiles windows within the module (e.g. Terminal), while "full" (the default) opens
	// full-frame and replaces the active view.
	Tiling string `json:"tiling,omitempty"`
	// Bare means the body fills the window edge to edge and scrolls itself.
	Bare bool `json:"bare,omitempty"`
	// Render says how the window body is drawn.
	Render Render `json:"render"`
	// Opens are file name patterns ("*.md") this view opens from Files and the palette.
	Opens []string `json:"opens,omitempty"`
	// Describe adds what the module knows about one of its windows to what the desk already
	// knows (the file, the page, the record in front). It is what the agent and a slot mean
	// by "where the owner is". Optional.
	Describe func(ctx context.Context, h Host, w Window) (WindowContext, error) `json:"-"`
}

View is something that opens in a window.

type Window

type Window struct {
	ID string `json:"id"`
	// View is the id of the view it shows; Module is the module that brought the view.
	View   string `json:"view"`
	Module string `json:"module"`
	Title  string `json:"title"`
	// Key identifies a window of a Multi view (a file path, say).
	Key string `json:"key,omitempty"`
	// Args are what the window was opened with, and what its body keeps there since.
	Args map[string]any `json:"args,omitempty"`
	// State is what the window's body last reported about itself (the selection, the
	// position). Small, and never trusted as more than a report from the page.
	State   map[string]any `json:"state,omitempty"`
	Focused bool           `json:"focused,omitempty"`
	// OpenedBy is who opened the window (an Actor; "" for a window from before actors were
	// kept, which counts as the owner's). Opener is the owner's window that was in front when
	// it opened, where the focus goes back to when it closes. Reason is what the opener said
	// it was for.
	OpenedBy string `json:"opened_by,omitempty"`
	Opener   string `json:"opener,omitempty"`
	Reason   string `json:"reason,omitempty"`
	// Retention is how long a delegate means the window to stay: "transient" (for the task
	// at hand) or "deliverable" (the result, to keep); "" is deliverable.
	Retention string `json:"retention,omitempty"`
	// Kept marks the owner's window: one they opened, or one they took over by working in
	// it. A delegate may not close it.
	Kept bool `json:"kept,omitempty"`
	// Dirty: the owner has unsaved work in it. Composing: the owner has unsent input in it.
	// A module about to change what such a window shows on a delegate's behalf should wait
	// or ask (docs/desk-rules.md, rule 7). Held: a delegate's change is waiting for them.
	Dirty     bool `json:"dirty,omitempty"`
	Composing bool `json:"composing,omitempty"`
	Held      bool `json:"held,omitempty"`
}

Window is one open window.

type WindowContext

type WindowContext struct {
	Window string `json:"window"`
	View   string `json:"view"`
	Module string `json:"module"`
	Title  string `json:"title"`
	// Kind is the kind of thing in front: "document", "url", "file", "folder", "data",
	// "task", "project", "workspace".
	Kind string `json:"kind,omitempty"`
	// Ref names the thing in front in the module's own terms ("notes:ideas/surface.md").
	// It is also what a Mark is pinned to.
	Ref string `json:"ref,omitempty"`
	URL string `json:"url,omitempty"`
	// Selection is the selected text, when there is one.
	Selection string `json:"selection,omitempty"`
	// Extra is anything else worth knowing. Keep it small.
	Extra map[string]any `json:"extra,omitempty"`
}

WindowContext is what a window is showing, as far as its module can say. It is small and safe to put in front of the agent.

Directories

Path Synopsis
Package collab is Caster's "collab" namespace as Basalisk keeps it (contract collab/v1): what the owner and the agent work on together, drafts (code, content, plans), artifacts under review and diagrams.
Package collab is Caster's "collab" namespace as Basalisk keeps it (contract collab/v1): what the owner and the agent work on together, drafts (code, content, plans), artifacts under review and diagrams.
collabtest
Package collabtest is an in-memory Caster for tests of code that reads and writes Caster through module/tetherlink (module/collab, a module's own Caster sync).
Package collabtest is an in-memory Caster for tests of code that reads and writes Caster through module/tetherlink (module/collab, a module's own Caster sync).
Package moduletest runs one Surface module in a test, without the core: a Host with an in-memory desk, live settings, an event bus and marks, and a temporary SQLite store with the module's migrations applied.
Package moduletest runs one Surface module in a test, without the core: a Host with an in-memory desk, live settings, an event bus and marks, and a temporary SQLite store with the module's migrations applied.
Package tetherlink calls Tether's tools over MCP for a module: a stdio command (the local bridge, one process per call) or MCP's streamable HTTP.
Package tetherlink calls Tether's tools over MCP for a module: a stdio command (the local bridge, one process per call) or MCP's streamable HTTP.

Jump to

Keyboard shortcuts

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