apps

package
v0.16.154 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2026 License: Apache-2.0 Imports: 50 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

Package apps is harnessly's apps: a package an author writes once (a Claude Code plugin plus the manifest harnessly/app.json) that a person installs on a machine and turns on in a chat, a pane tab, a full screen of its own or a Sinopia document. A plugin is an app without views.

This file reads and checks the manifest. The checks are the ones `harnessly app validate` reports and an install refuses on: every problem carries the path of the field (targets[2], agent.tools.deny[0]) so an author, or an agent editing the package, can find it.

Index

Constants

View Source
const (
	// AskTTL is how long a choice stays open; past it the agent's call ends as cancelled.
	AskTTL = 10 * time.Minute
	// MaxAsksPerChat bounds the open choices of one chat.
	MaxAsksPerChat = 5
	MaxAskOptions  = 8
	MaxAskOption   = 80
	MaxAskQuestion = 300
)
View Source
const (
	CodePermissionDenied = "permission_denied"
	CodeNotInTarget      = "not_in_target"
	CodePolicyBlocked    = "policy_blocked"
	CodeNetworkDenied    = "network_denied"
	// CodeHostNotAllowed: the server's address is no https one and no internal host the deployment lists.
	CodeHostNotAllowed = "host_not_allowed"
	// CodeTLSUntrusted: the server's certificate ends in no root the machine trusts (RUNTIME_APPS_CA_FILE adds some).
	CodeTLSUntrusted = "tls_untrusted"
	// CodeUpstreamError: the server answered, with an HTTP error or with something else than JSON-RPC.
	CodeUpstreamError   = "upstream_error"
	CodeRateLimited     = "rate_limited"
	CodeHostUnavailable = "host_unavailable"
	CodeInvalidParams   = "invalid_params"
	// CodeConflict: a storage write named the version it read (ifVersion) and the key has moved on; the error says the
	// current version and nothing was written.
	CodeConflict = "conflict"
	// CodeQuotaExceeded: a storage write would take its area past its limit.
	CodeQuotaExceeded = "quota_exceeded"
)

Error codes a view sees as HarnesslyError.code.

View Source
const (
	// ChatInstructionsBudgetBytes is the most the instructions of all the apps on in one chat should weigh together:
	// 48 KB, about 12k tokens. That is three apps at the 16 KB cap each, or a dozen of the usual 4 KB: past it the
	// agent's own work crowds out of a window every turn pays for. Past it the app is still turned on, with a warning:
	// the person decides what to take off.
	ChatInstructionsBudgetBytes = 48 << 10
	// AppContextWarnBytes is what an app's instructions, tool descriptions and server instructions may weigh together
	// before `harnessly app validate --strict` warns (not an error: it is the author's call, and a server can change).
	AppContextWarnBytes = 16 << 10
)
View Source
const (
	DefaultGuestTTL = 7 * 24 * time.Hour
	MaxGuestTTL     = 30 * 24 * time.Hour
)

Limits of a link's life.

View Source
const (
	ReadOnlyNewer      = "newer"      // the document is of a newer version than the app knows
	ReadOnlyFailed     = "failed"     // a migration step does not fit the document
	ReadOnlyNoRoom     = "no-room"    // no room to keep the old copy next to the new one
	ReadOnlyUnreadable = "unreadable" // the version or the document cannot be read
	ReadOnlyNoApp      = "no-package" // the app's package cannot be read, or names no key for the document
	ReadOnlyViewOnly   = "view-only"  // the person may only view the project (its role is below edit)
)

The codes of a read-only opening.

View Source
const (
	TrustDeclarative = "declarative"
	TrustSandboxed   = "sandboxed"
	TrustTrusted     = "trusted"
)

Trust levels: what a package may carry. A declarative app is text only (instructions, skills, commands, remote MCP servers, views as static files); a sandboxed one also runs its views' scripts in the sandboxed frame; a trusted one may start local processes (stdio MCP servers, validator commands) and is installed by hand only.

View Source
const (
	TargetChat = "chat"
	TargetPane = "pane"
	TargetApp  = "app"
)

Targets an app works in. sinopia.<kind> names one Sinopia document type, sinopia.* all of them.

View Source
const (
	TargetSettings     = "settings"      // a page in the settings
	TargetOnboarding   = "onboarding"    // a step of the first run
	TargetObjectAction = "object-action" // a button at an object (a machine, a chat) that opens the view
	TargetHubSettings  = "hub-settings"  // a page in the settings of a Hub
	TargetBranding     = "branding"      // the product's name and accent; no view, see Branding
)

The slots of the interface an extension fills: a view in a sandboxed frame at a place the page declares, or, for branding, a few declared values. With the runtime's HARNESSLY_UI_SLOTS off the page shows none of them.

View Source
const (
	OnManual   = "manual"
	OnView     = "view"
	OnDocument = "document"
	OnAlways   = "always"
)

Activations: how an app turns on.

View Source
const (
	ToolUnreachable = "unreachable"
	ToolTimeout     = "timeout"
	ToolRefused     = "refused"
	ToolError       = "tool-error"
)

What a view is told of a failed tool call: one of these words. The remote's own error text and the transport's are logged (BridgeError.Detail), never sent to the page.

View Source
const (
	// MaxPackageBytes is the most a package may weigh, every file counted.
	MaxPackageBytes = 50 << 20
	// MaxInstructionsBytes is the most the always-in-context instructions may weigh; past InstructionsWarnBytes the
	// check warns that every turn pays for them.
	MaxInstructionsBytes  = 16 << 10
	InstructionsWarnBytes = 4 << 10
)
View Source
const (
	ReviewApproved = "approved"
	ReviewPending  = "pending"
)

Review states of a public entry.

View Source
const (
	// SessionIdle is how long a session lives without a use; every use renews it.
	SessionIdle = time.Hour
	// SessionMax is the longest a session lives, used or not.
	SessionMax = 12 * time.Hour
)
View Source
const (
	CheckOnSave  = "save"
	CheckOnShare = "share"
)

Check triggers.

View Source
const (
	LevelError   = "error"
	LevelWarning = "warning"
	LevelInfo    = "info"
)

Levels of a finding.

View Source
const (
	RoleOwner  = "owner"
	RoleMember = "member"
)

Roles of the person in the team.

View Source
const (
	ValidatorPostToolUse = "PostToolUse"
	ValidatorStop        = "Stop"
	// ValidatorDefaultRetries is how many times a validator may block in a row when it does not say; ValidatorMaxRetries
	// is the most it may ask for.
	ValidatorDefaultRetries = 3
	ValidatorMaxRetries     = 10
	// ValidatorTimeoutSeconds is how long a script may run.
	ValidatorTimeoutSeconds = 30
	// ValidatorReasonBytes bounds the remark the agent gets.
	ValidatorReasonBytes = 4 << 10
	// ValidatorHookTimeoutSeconds is how long Claude waits for the hook: a script's time plus the hook's own.
	ValidatorHookTimeoutSeconds = ValidatorTimeoutSeconds + 10
)
View Source
const (
	SDKPath       = "/__hl/app-sdk.js"
	SDKModulePath = "/__hl/app-sdk.mjs"
	// ShimPath is the script the server puts first in every page it serves: it makes the handshake with the page's nonce
	// and gives the view a window.parent that speaks on the MessageChannel port the host hands over.
	ShimPath = "/__hl/bridge-shim.js"
	// WidgetBaseCSSPath is the host's base style of an agent's widget; any view may load it.
	WidgetBaseCSSPath = "/__hl/widget.css"
	// UICSSPath is hl-ui.css, the host's primitives (.hl-btn, .hl-card, .hl-stat, …) on the platform's tokens; any view
	// may load it.
	UICSSPath = "/__hl/hl-ui.css"
	// EChartsPath is the charts library every view may load (window.echarts).
	EChartsPath = "/__hl/lib/echarts.js"
)

SDKPath is where every view finds @harnessly/app-sdk as a classic script (window.harnessly); SDKModulePath is the same code as an ES module. A view runs on an opaque origin (see ViewCSP), where a module script cannot carry the slot's cookie, so the classic one is what a view loads.

View Source
const (
	WidgetView = "view"
	WidgetHTML = "html"
)

The kinds of widget.

View Source
const (
	MaxWidgetData    = 64 << 10
	MaxWidgetHTML    = 128 << 10
	MaxWidgetScript  = 256 << 10
	MaxWidgetStyle   = 64 << 10
	MaxWidgetTitle   = 120
	MaxWidgetsInChat = 200
)
View Source
const AgentTokenTTL = 30 * 24 * time.Hour

AgentTokenTTL is how long the token of a launch holds. A chat that runs longer is given a new one when the agent starts next (a resume is a launch); the files of older launches are removed when a new one is written.

View Source
const BoundaryProbeFile = ".boundary-probe"

BoundaryProbeFile is the file the probe tries to create in the protected folder: its being there after a probe means the wall did not hold.

View Source
const CommandPrompt = "prompt"

Command kinds: a prompt is sent to the agent as the slash command; a view would open an app view in the pane (the manifest does not tell the two apart yet, so every command is a prompt).

View Source
const ContextMaxBytes = 16 << 10

ContextMaxBytes bounds what one context item may add: a tool that answers more is cut, as an app's instructions are.

View Source
const ContextTimeoutSeconds = 30

ContextTimeoutSeconds is how long Claude waits for the context hook, which calls the app's tool through the runtime.

View Source
const DecisionReasonMax = 300

DecisionReasonMax is the longest reason (in characters) a line keeps.

View Source
const DecisionsMax = 500

DecisionsMax is how many lines a conversation's journal keeps; past it the oldest go.

View Source
const DefaultEvalThreshold = 0.8

DefaultEvalThreshold is the share of passed evals a version needs to go to stable.

View Source
const DefaultEvalTimeout = 5 * time.Minute

DefaultEvalTimeout is how long one run may take.

View Source
const EvalDir = "evals"

EvalDir is where a package keeps its scenarios.

View Source
const EvalReportPath = ".harnessly/eval.json"

EvalReportPath is where `harnessly app eval` leaves its report in the package; it travels with the published copy.

View Source
const FirstVersion = "0.16.36"

FirstVersion is the first host version with apps: the range a new package starts with.

View Source
const GuardTimeoutSeconds = 15

GuardTimeoutSeconds is how long Claude waits for the guard. The guard reads one local file and answers at once; one that could not read it refuses the call.

View Source
const GuestPrefix = "/apps/guest/"

GuestPrefix is where the guest routes are.

View Source
const HostServer = hostServer

HostServer is the name of the MCP server of the host's tools for the agent of a chat with apps. Claude names its tools mcp__harnessly-app__<tool> with '.' written '_', and the policy reads them as app.open, app.data.get, app.data.set and app.ask (policy.go).

View Source
const ManifestPath = "harnessly/app.json"

ManifestPath is where the manifest lives inside a package.

View Source
const MaxArchiveBytes = 16 << 20

MaxArchiveBytes is the most a packed package may weigh, the bytes that travel.

View Source
const MaxFileBytes = 4 << 20

MaxFileBytes is the most one hl.files call moves.

View Source
const MaxKindsPerApp = 8

MaxKindsPerApp bounds the types one app adds.

View Source
const MaxSnapshotEntries = 200

MaxSnapshotEntries bounds a snapshot's catalog.

View Source
const NonceMeta = "hl-nonce"

NonceMeta is the name of the meta tag that carries a view session's nonce in the view's pages; the SDK reads it.

View Source
const ProxyPrefix = "/api/cli/apps/mcp/"

ProxyPrefix is where the runtime's MCP proxy for the apps' remote servers answers: <prefix><app>/<server>.

View Source
const SchemaKey = "@schema"

SchemaKey is the key of the area that holds the format version of the document, written by the host.

View Source
const SelfSSHFix = `` /* 295-byte string literal not displayed */

SelfSSHFix refuses logins that come from the machine itself. sshd has no way to refuse a user in a Match block, so it takes away every way of proving who one is; logins from elsewhere are as they were.

View Source
const SettingsKey = "_settings"

SettingsKey is the key of the install area that holds the settings' values. A view cannot write it through hl.storage: the form is the way (the host checks the values against the schema).

View Source
const TemplateBoard = "board.dc.html"

TemplateBoard is the board file inside a template folder.

View Source
const WidgetsApp = "harnessly.widgets"

WidgetsApp is the app id under which the agent's own widgets (kind "html") are served and bridged. No package has it: an app id names its publisher first, and harnessly is the host's.

Variables

View Source
var (
	// ErrAskArgs: a question or options past the limits.
	ErrAskArgs = errors.New("apps: bad ask")
	// ErrAskBusy: the chat has too many open choices.
	ErrAskBusy = errors.New("apps: too many open choices in this chat")
	// ErrAskGone: no such open choice.
	ErrAskGone = errors.New("apps: no such choice")
	// ErrAskAnswer: the answer is none of the options.
	ErrAskAnswer = errors.New("apps: the answer is not one of the options")
)
View Source
var (
	// ErrVersionExists: the version is published; a number is never used twice.
	ErrVersionExists = errors.New("apps: this version is already published")
	// ErrChannelVersion: the manifest's version does not suit the channel.
	ErrChannelVersion = errors.New("apps: the version does not suit the channel")
	// ErrNoVersion: nothing is published under that name.
	ErrNoVersion = errors.New("apps: no such published version")
	// ErrNoChannel: the channel has no version yet.
	ErrNoChannel = errors.New("apps: nothing is published on this channel")
	// ErrNoPrevious: the channel has no earlier version to go back to.
	ErrNoPrevious = errors.New("apps: the channel has no earlier version")
	// ErrEvalGate: the evals do not let the version go to stable.
	ErrEvalGate = errors.New("apps: the evals do not pass")
)
View Source
var (
	// ErrEnvApp: the app is the environment's; the person cannot remove it.
	ErrEnvApp = errors.New("apps: the app comes with the environment")
	// ErrEnvLocked: the environment's app is pinned; the person cannot turn it off.
	ErrEnvLocked = errors.New("apps: the environment's app is pinned")
	// ErrTrustedEnv: a trusted app is installed by hand, not by the environment.
	ErrTrustedEnv = errors.New("apps: a trusted app is installed by hand, not by the environment")
)
View Source
var (
	// ErrGuestTarget: the app or the view is not one that can be shared by link.
	ErrGuestTarget = errors.New("apps: only a view for the app target can be shared by link")
	// ErrGuestGone: no such link, or it ended.
	ErrGuestGone = errors.New("apps: the link is gone")
	// ErrGuestLimit: too many links.
	ErrGuestLimit = errors.New("apps: too many links; revoke some")
)
View Source
var (
	// ErrTrustedPublic: a trusted app is installed by hand, never from a catalog.
	ErrTrustedPublic = errors.New("apps: a trusted app is installed by hand, it is not in the public catalog")
	// ErrNotOnStable: only the version a person promoted to stable goes public.
	ErrNotOnStable = errors.New("apps: only the version on stable goes to the public catalog")
	// ErrPublishChecks: the package does not pass what the public catalog asks.
	ErrPublishChecks = errors.New("apps: the package does not pass the public catalog's checks")
	// ErrNotPublic: the public catalog has no such app, or it is not listed yet.
	ErrNotPublic = errors.New("apps: the public catalog has no such app")
	// ErrPublicChanged: the entry is not the one the person was shown.
	ErrPublicChanged = errors.New("apps: the catalog's entry changed since it was shown")
)
View Source
var (
	// ErrNotInstalled: no installed app has that id.
	ErrNotInstalled = errors.New("apps: not installed")
	// ErrInvalid: the package has errors; the Problems say which.
	ErrInvalid = errors.New("apps: the package has errors")
	// ErrPluginName: another installed app has the same plugin name.
	ErrPluginName = errors.New("apps: another installed app has the same plugin name")
	// ErrCommandTaken: another installed app turns on by the same slash command.
	ErrCommandTaken = errors.New("apps: another installed app has the same command")
	// ErrHostVersion: the app does not work with this host's version.
	ErrHostVersion = errors.New("apps: needs another harnessly version")
)
View Source
var (
	// ErrQuota: the write would take the area past its limit.
	ErrQuota = errors.New("apps: the storage area is full")
	// ErrStorageArgs: a scope, owner or key that is not one.
	ErrStorageArgs = errors.New("apps: bad storage arguments")
	// ErrConflict: a write that named the version it read (ifVersion) found the key moved on. The error is a
	// *ConflictError, which carries the version the key has now.
	ErrConflict = errors.New("apps: the key changed since it was read")
)
View Source
var (
	// ErrNoTeam: this machine is not in a team.
	ErrNoTeam = errors.New("apps: this machine is not in a team")
	// ErrNotOwner: the person is a member; installing for the team is an owner's.
	ErrNotOwner = errors.New("apps: only an owner of the team does this")
	// ErrTeamApp: the app is the team's; a person turns it off for themselves, they do not remove it.
	ErrTeamApp = errors.New("apps: the app is the team's: turn it off for yourself instead")
	// ErrTrustedTeam: a trusted app is installed by hand, never for a team.
	ErrTrustedTeam = errors.New("apps: a trusted app is installed by hand, not for the team")
	// ErrNotInCatalog: the team's catalog has no such entry.
	ErrNotInCatalog = errors.New("apps: the team's catalog has no such app")
	// ErrStaleTeam: the snapshot is older than the one held.
	ErrStaleTeam = errors.New("apps: stale team snapshot")
)
View Source
var (
	// ErrWidgetArgs: an id, a title, the data or a file past its limit, or a view that is not one.
	ErrWidgetArgs = errors.New("apps: bad widget")
	// ErrWidgetsFull: the chat has as many widgets as it may keep.
	ErrWidgetsFull = errors.New("apps: the chat has too many widgets")
	// ErrWidgetGone: no such widget in the chat.
	ErrWidgetGone = errors.New("apps: no such widget")
	// ErrWidgetKind: the id is a widget of another app or kind; it is not changed into one.
	ErrWidgetKind = errors.New("apps: the id is another widget's")
)
View Source
var ErrArchive = errors.New("apps: not a usable package archive")

ErrArchive: the bytes are not a package archive this host unpacks.

View Source
var ErrFileRefused = errors.New("apps: the app may not reach this file")

ErrFileRefused: the app may not reach this path.

View Source
var ErrKindTaken = errors.New("apps: another installed app adds this document type")

ErrKindTaken: another installed app already adds this document type.

View Source
var ErrMigration = errors.New("apps: a migration failed")

ErrMigration: a migration step could not be applied.

View Source
var ErrNoBwrap = errors.New("bubblewrap (bwrap) is not installed")

ErrNoBwrap: the machine has no bubblewrap.

View Source
var ErrSelfSSH = errors.New("ssh from this machine to itself logs in, and a shell got that way is outside the wall")

ErrSelfSSH: the person's own login over ssh from this machine works, and such a shell is outside the wall.

View Source
var ErrUnknownMethod = errors.New("apps: unknown bridge method")

ErrUnknownMethod: the bridge has no such method.

View Source
var ErrViewNotFound = errors.New("apps: no such view")

ErrViewNotFound: the app or the view is not there, or the view is not for this target.

View Source
var ObjectKinds = []string{"machine", "chat"}

Objects an object-action view can sit at.

View Source
var SinopiaMethods = map[string]string{
	"document":   "sinopia.read",
	"selection":  "sinopia.read",
	"node":       "sinopia.read",
	"query":      "sinopia.read",
	"fields":     "sinopia.read",
	"mark":       "sinopia.read",
	"patch":      "sinopia.write",
	"setFields":  "sinopia.write",
	"boards.add": "sinopia.write",
	"render":     "sinopia.export",
	"comment":    "sinopia.comment",
}

SinopiaMethods are the methods of the Document API with the permission each needs.

SlotTargets are the targets above, in the order the docs name them.

View Source
var Templates = []string{"chat", "pane-chat", "widget"}

Templates are the starting points of `harnessly app new --template`.

Functions

func AppendDecision added in v0.16.154

func AppendDecision(dir, conv string, e DecisionEntry) error

AppendDecision adds a line to the conversation's journal in dir and trims it to DecisionsMax lines.

func ApplyPatch added in v0.16.86

func ApplyPatch(doc json.RawMessage, ops []PatchOp) (json.RawMessage, error)

ApplyPatch applies a step to a document. The input is not changed; an operation that does not fit fails the step.

func ArchiveNameProblem added in v0.16.86

func ArchiveNameProblem(rel string) string

ArchiveNameProblem says why a file's name (slash-separated, relative to the package) cannot go in an archive; "" when it can: the name must be ASCII and at most 100 bytes.

func ArchiveSum added in v0.16.86

func ArchiveSum(raw []byte) string

ArchiveSum is the SHA-256 of archive bytes as hex.

func BoundDirs added in v0.16.86

func BoundDirs(protected []string) []string

BoundDirs are the folders the wall binds read-only: each protected folder as it really is (the written form leads there, so one bind covers both), only those that exist (bwrap cannot bind a missing one; a missing package folder has nothing to write into, and the hook still refuses one being made), and none inside another one bound already.

func CachedPackage added in v0.16.154

func CachedPackage(dir string) (*Package, Problems)

CachedPackage is LoadPackage for a caller that asks again and again (every tool call, every Sinopia call, every row of a list): the package is read once and kept until the stamp of its manifest files changes. The Package it returns is shared: read it, do not change it.

func CallTool added in v0.16.86

func CallTool(ctx context.Context, srv MCPServer, tool string, args map[string]any) (json.RawMessage, error)

CallTool runs one tool of an app's remote MCP server for a view (hl.tools.call): Streamable HTTP, one initialize and one tools/call per call, nothing kept between calls. The server is the package's own (.mcp.json, an https address); the call goes from the machine, so the address must be a public one, or the host one the deployment's admin listed as internal (DeployNetwork), which may also be plain http.

func ChatBudgetWarning added in v0.16.154

func ChatBudgetWarning(total int) string

ChatBudgetWarning is the warning for a chat whose apps' instructions weigh total bytes; "" while within the budget.

func CheckAppServers added in v0.16.86

func CheckAppServers(pkgDir string, tr Transcript) error

CheckAppServers says plainly when a server of the prepared package did not come up in the run (Claude Code lists the servers in the first event of the stream): an agent without its tools only reports that they are not there, and the scenario fails for a reason the author cannot see.

func CheckMask added in v0.16.86

func CheckMask(mask string) string

CheckMask is "" for a good mask: a relative path of the workspace where * stands for a run of characters inside a segment and ** for any number of segments. A mask never leaves the workspace.

func CheckSource added in v0.16.86

func CheckSource(app, check string) string

CheckSource is what marks of a check are kept under.

func ClaudeRules added in v0.16.154

func ClaudeRules(list []SnapshotApp) (deny, ask []string)

ClaudeRules are the deny and ask rules for the apps' deny and confirm lists.

func CodexDeny added in v0.16.154

func CodexDeny(reason string) []byte

CodexDeny is the answer that refuses a call, with the reason Codex needs.

func CompareVersions

func CompareVersions(a, b string) int

CompareVersions orders two app versions (1.2.0 < 1.10.0); a version that does not parse sorts first.

func ContextDigest added in v0.16.154

func ContextDigest(text string) string

ContextDigest is the hash kept per chat to tell whether a context changed.

func ContextText added in v0.16.154

func ContextText(result json.RawMessage) string

ContextText is the text of a tools/call result: its text parts joined, cut at ContextMaxBytes; "" for an error result or one without text.

func EstimateTokens added in v0.16.154

func EstimateTokens(bytes int) int

EstimateTokens is the rough size in tokens of bytes of text: four bytes to a token. An estimate, not a count: it is there to compare apps and to warn, not to bill.

func FillSecrets added in v0.16.154

func FillSecrets(s string, values map[string]string) (string, []string)

FillSecrets puts the secrets' values into a text; a name with no value is left as written and reported.

func ForegroundExec added in v0.16.86

func ForegroundExec(argv []string) error

ForegroundExec becomes argv (looked up on PATH) in a process group of its own that it makes the terminal's foreground first, when the terminal's foreground is its group: bwrap stays in the group the shell started, so the pane's foreground program (#{pane_current_command}, what tells a running agent) is the CLI and not bwrap, and the terminal's Ctrl-C and window signals go to the CLI. Off a terminal, or not in its foreground, it only execs. The managed launcher does the same for the CLI it starts.

func GuestMatch added in v0.16.86

func GuestMatch(r *http.Request) bool

GuestMatch: the request is one of the guest routes or the public SDK files the views load by absolute path.

func HostAllows added in v0.16.154

func HostAllows(raw []byte, host string) (ok bool, wanted string)

HostAllows says whether the host version is in the range the manifest in raw asks for; true when the manifest names none (the strict parse says what is wrong with it).

func InstructionsBytes added in v0.16.154

func InstructionsBytes(a Installed) int

InstructionsBytes is what an installed app's instructions weigh in the prompt (as the launch cuts them).

func IsSlot added in v0.16.154

func IsSlot(target string) bool

IsSlot says whether a target is one of the slots.

func JudgePrompt added in v0.16.86

func JudgePrompt(criterion, prompt string, tr Transcript) string

JudgePrompt is what the judge is asked: the criterion, and the agent's calls and last words.

func LoadPackage

func LoadPackage(dir string) (*Package, Problems)

LoadPackage reads the package in dir and checks it whole. The package comes back whenever the manifest could be read, with the problems found; nil means there is no manifest to read.

func LocksUnbound added in v0.16.86

func LocksUnbound(list []Installed, kind string) bool

LocksUnbound says whether any app on in the document keeps free hand edits to its bound elements.

func MCPWeight added in v0.16.154

func MCPWeight(ctx context.Context, srv MCPServer) (instructionsBytes, toolsBytes int, err error)

MCPWeight is what a remote server of an app puts into the agent's context: its `instructions` and the names, descriptions and schemas of its tools (the first page of tools/list). Same transport rules as CallTool.

func MatchMask added in v0.16.86

func MatchMask(mask, rel string) bool

MatchMask says whether a clean relative path (slashes) is named by the mask.

func Pack added in v0.16.86

func Pack(dir string) ([]byte, string, error)

Pack makes the archive of a package folder, with the files copyPackage would copy, and its SHA-256 as hex.

func ParseManifest

func ParseManifest(raw []byte) (*Manifest, Problems)

ParseManifest reads the manifest. A syntax error, or a field of the wrong type, comes back as one problem with the line it stands on; otherwise the manifest is checked and every problem found is returned at once.

func ParseVerdict added in v0.16.86

func ParseVerdict(answer string) (bool, string, error)

ParseVerdict reads a judge's answer: PASS or FAIL as the first word of the first line. An answer that says one thing on its first line and the other on a line of its own later (a judge that changed its mind while explaining) is not a verdict: the error says so, and the answer is not counted either way.

func PluginName

func PluginName(id string) string

PluginName is the Claude Code plugin name of an app: its skills are <plugin>:<skill> to the agent.

func PrepareEvalPackage added in v0.16.86

func PrepareEvalPackage(dir string, c EvalCase, bin string) (string, func(), error)

PrepareEvalPackage copies the package into a folder of its own and makes its .mcp.json answer with the case's mocks: a server with a fixture runs `<harnessly> app mock-mcp <fixture>`, any other server is dropped (an eval does not reach the app's real backend). bin is the harnessly executable the mock runs as.

func ProxyMCP added in v0.16.154

func ProxyMCP(w http.ResponseWriter, r *http.Request, srv MCPServer, values map[string]string)

ProxyMCP forwards one request of an agent's MCP client to the app's real remote server, with the headers of the package and the app's secrets in them (launch_secrets.go says why). srv is the server as the package declares it; values are its secrets' values. The call goes from the machine under the rules of hl.tools.call: https, a public address checked at the dial, no proxy, no redirects. A stream (Streamable HTTP, SSE) is passed on as it comes. The client's own headers (its token among them) do not go on; only the ones MCP needs do.

func RecordDocVersion added in v0.16.86

func RecordDocVersion(st *Storage, app, project string, version int) error

RecordDocVersion notes the format version a new document is made at.

func RequiredPermission added in v0.16.86

func RequiredPermission(method string) (string, bool)

RequiredPermission is the right a bridge method needs, and whether the method exists.

func Scaffold

func Scaffold(dir, id, name, template string) error

Scaffold writes a new package for id into dir, which must not exist or be empty.

func SecretsIn added in v0.16.154

func SecretsIn(s string) []string

SecretsIn are the names of the secrets a text names with ${secret:<name>}.

func ServeMockMCP added in v0.16.86

func ServeMockMCP(in io.Reader, out io.Writer, f MockFixture) error

ServeMockMCP answers MCP over stdio (one JSON message per line) until the input ends.

func SetNetwork added in v0.16.154

func SetNetwork(n DeployNetwork)

SetNetwork sets the deployment's network for the apps' calls.

func SnapshotIntact

func SnapshotIntact(path string, body []byte) bool

SnapshotIntact says whether a snapshot's bytes are the ones its name was made from (writeByContent): a snapshot changed after the launch is not one the guard decides by.

func ToolName added in v0.16.86

func ToolName(raw string) string

ToolName is a tool as a scenario names it. Claude calls the tool of a server of the app's package mcp__plugin_<plugin>_<server>__<tool>, and a mock or a host server mcp__<server>__<tool>; both are "<server>.<tool>". Any other tool keeps its name.

func ToolsListBytes added in v0.16.154

func ToolsListBytes(result json.RawMessage) int

ToolsListBytes is the weight of a tools/list result: each tool's name, description and input schema.

func Unpack added in v0.16.86

func Unpack(raw []byte, dst string) error

Unpack writes the archive into dst (a new folder). Nothing outside dst is touched, whatever the names say.

func ValidOwner added in v0.16.86

func ValidOwner(owner string) bool

ValidOwner says whether a text can name the chat or document an area belongs to.

func ValidatorBlockAnswer added in v0.16.154

func ValidatorBlockAnswer(reason string) []byte

ValidatorBlockAnswer is the hook's answer that shows the agent a remark.

func ValidatorEnv added in v0.16.154

func ValidatorEnv(env []string) []string

ValidatorEnv is the part of env a validator gets: PATH, HOME, LANG, LC_*, TMPDIR and the variables of harnessly the CLI needs. Nothing else (tokens and keys of the person's shell stay out).

func WidgetAnswer added in v0.16.154

func WidgetAnswer(w Widget) string

WidgetAnswer is the text a widget tool answers with, one short line: the feed finds the widget by its id in it (the tool's answer reaches the feed through the transcript, which keeps only the start of the first line). A new widget is «shown» and drawn under that step; one shown again is «changed», and changes where it first stood.

func WidgetCSP added in v0.16.154

func WidgetCSP() string

WidgetCSP is the Content-Security-Policy of an agent's own widget: the view's sandbox with no network at all, and no frames or forms that leave it.

func WriteEvalReport added in v0.16.86

func WriteEvalReport(dir string, rep EvalReport) error

WriteEvalReport leaves the report in the package, where publishing to stable looks for it.

Types

type Activation

type Activation struct {
	On       []string `json:"on"`
	OpenView string   `json:"openView,omitempty"`
	Template string   `json:"template,omitempty"`
}

Activation is how the app turns on and what it opens when it does.

type Agent

type Agent struct {
	Instructions string        `json:"instructions,omitempty"`
	Skills       []string      `json:"skills,omitempty"`
	MCP          []string      `json:"mcp,omitempty"`
	Context      []ContextItem `json:"context,omitempty"`
	Tools        *ToolPolicy   `json:"tools,omitempty"`
	Validators   []Validator   `json:"validators,omitempty"`
	Flow         string        `json:"flow,omitempty"`
	Exclusive    bool          `json:"exclusive,omitempty"`
}

Agent is the agent profile: what the agent of a chat gets while the app is on in it.

type Asks added in v0.16.86

type Asks struct {
	Now func() time.Time
	// TTL replaces AskTTL (tests).
	TTL time.Duration
	// contains filtered or unexported fields
}

Asks is the open choices of the machine.

func NewAsks added in v0.16.86

func NewAsks() *Asks

func (*Asks) Answer added in v0.16.86

func (a *Asks) Answer(id string, answer *string) error

Answer closes a choice with one of its options; nil cancels it.

func (*Asks) Ask added in v0.16.86

func (a *Asks) Ask(ctx context.Context, conv, app, appName, question string, options []string) (answer string, cancelled bool, err error)

Ask puts a choice to the person of the chat and waits for the answer: the option picked, or cancelled=true when the person cancelled, the time ran out or ctx ended.

func (*Asks) Pending added in v0.16.86

func (a *Asks) Pending(conv string) []PendingAsk

Pending are the open choices of a chat, oldest first.

type Backend

type Backend struct {
	URL string `json:"url"`
}

Backend is the app's own server.

type Boundary added in v0.16.86

type Boundary struct {
	// Bwrap is bubblewrap's path; "" when the machine has none.
	Bwrap string
	// Helper is the command line of ForegroundExec without its `--` (the runtime binary and `sandbox-exec`).
	Helper []string
	// Run runs a probe; nil runs it as a process of this machine. Gaps uses it too.
	Run func(name string, args ...string) (stdout, stderr []byte, err error)
	// contains filtered or unexported fields
}

Boundary makes the wall: the bwrap it runs and the helper bwrap starts the CLI through.

func (*Boundary) Gaps added in v0.16.86

func (b *Boundary) Gaps() error

Gaps says what the machine leaves open with the wall up: a login to itself, and a kernel without what sandbox-exec asks of it (harden_linux.go). nil when there is nothing to say.

func (*Boundary) Ready added in v0.16.86

func (b *Boundary) Ready(dir string) error

Ready says whether the wall can be made, probing under dir (a protected folder that exists) until a probe passes: one that passed is kept for the process, one that failed is tried again at the next launch, so a package or a setting put right on the machine takes without a restart.

func (*Boundary) SealedWords added in v0.16.86

func (b *Boundary) SealedWords(protected []string, seal *Seal, hidden ...string) string

SealedWords are Words with the data folder and the person's start-up files sealed (seal.go).

func (*Boundary) State added in v0.16.86

func (b *Boundary) State() (probed bool, err error)

State is the last probe's result: probed false before the first one.

func (*Boundary) Words added in v0.16.86

func (b *Boundary) Words(protected []string, hidden ...string) string

Words are the wall as shell words that go in front of the CLI in a launch line; hidden files read as empty inside.

type Branding added in v0.16.154

type Branding struct {
	Name       string `json:"name"`
	Accent     string `json:"accent,omitempty"`     // #rrggbb
	SupportURL string `json:"supportUrl,omitempty"` // https://
	Tagline    string `json:"tagline,omitempty"`
}

Branding is the product's name and accent as an app sets them, for the `branding` target. Declared values, no code: the page takes the name for its title and the sign-in and the accent for its colour.

type BridgeError added in v0.16.86

type BridgeError struct {
	Code    string
	Message string
	// Detail is for the log only: a transport or remote error the page must not read.
	Detail string
}

BridgeError is a refusal with the code a view sees.

func (*BridgeError) Error added in v0.16.86

func (e *BridgeError) Error() string

type Call

type Call struct {
	// Tool is the agent's own name of the tool: Bash, Edit, mcp__bank-cashback__create,
	// mcp__plugin_acme-cashback_bank-cashback__create.
	Tool string
	// Input is the call's arguments: for Bash, command; for the file tools, file_path.
	Input map[string]any
	// Cwd is the agent's folder now (the hook's cwd): a file tool's relative path is taken from it, as the tool takes it.
	Cwd string
	// Root is the folder the chat started in (Claude Code's CLAUDE_PROJECT_DIR of the hook): a rule's relative mask is
	// taken from it. The agent moves Cwd with a cd, never Root, so a rule stays on the folders it named; "" takes Cwd.
	Root string
}

Call is one tool call as the agent's hook reports it.

func CodexCalls added in v0.16.154

func CodexCalls(raw []byte) (calls []Call, skip bool, problem string)

CodexCalls reads one PreToolUse input of Codex into the calls the rules decide. skip is true for a call no rule can concern (a harmless tool). A non-empty problem says why the call cannot be read; the caller refuses it.

type CaseReport added in v0.16.86

type CaseReport struct {
	Name   string `json:"name"`
	Runs   int    `json:"runs"`
	Passed int    `json:"passed"`
	// Failures are the distinct reasons runs failed, with how many runs each.
	Failures map[string]int `json:"failures,omitempty"`
	// Errors are the runs that could not be made or judged (the agent did not start, timed out…); they count as failed.
	Errors []string `json:"errors,omitempty"`
	// Notes are things about the scenario itself the author should know (a server of the package that has no mock here).
	Notes []string `json:"notes,omitempty"`
	// BaselineRuns and BaselinePassed are the runs without the app, when the scenario asks for them.
	BaselineRuns   int `json:"baselineRuns,omitempty"`
	BaselinePassed int `json:"baselinePassed,omitempty"`
	// Unjudged are llm criteria nobody judged.
	Unjudged int `json:"unjudged,omitempty"`
}

CaseReport is what one scenario came to.

type CatalogEntry added in v0.16.86

type CatalogEntry struct {
	ID          string   `json:"id"`
	Channel     string   `json:"channel"`
	Version     string   `json:"version"`
	Previous    string   `json:"previous,omitempty"`
	Name        string   `json:"name"`
	Description string   `json:"description"`
	Trust       string   `json:"trust"`
	Targets     []string `json:"targets"`
	Permissions []string `json:"permissions"`
	By          string   `json:"by"`
	At          int64    `json:"at"`
	// Sum is the SHA-256 of the archive of Version; PreviousSum that of Previous.
	Sum         string `json:"sum"`
	PreviousSum string `json:"previousSum,omitempty"`
}

CatalogEntry is an app in the team's catalog on one channel.

type CatalogView added in v0.16.86

type CatalogView struct {
	CatalogEntry
	// Installed: the team has the app installed on this channel; At is the version it is at.
	Installed bool   `json:"installed"`
	At        string `json:"installedVersion,omitempty"`
}

CatalogView is a catalog entry with whether the team has it installed.

type Change added in v0.16.154

type Change struct {
	App   string
	Scope Scope
	// Owner is the chat or document of an area per owner; empty for the other scopes.
	Owner string
	Key   string
}

Change is a key of an area that was written or deleted; it carries no value.

type Channel added in v0.16.86

type Channel string

Channel is a track a version is published on.

const (
	ChannelDev    Channel = "dev"
	ChannelBeta   Channel = "beta"
	ChannelStable Channel = "stable"
)

func ParseChannel added in v0.16.86

func ParseChannel(s string) (Channel, bool)

ParseChannel reads a channel name.

type ChannelInfo added in v0.16.86

type ChannelInfo struct {
	Current  string `json:"current"`
	Previous string `json:"previous,omitempty"`
}

ChannelInfo is where a channel points and where it pointed before.

type Chat

type Chat struct {
	Commands []string `json:"commands,omitempty"`
	Cards    []string `json:"cards,omitempty"`
}

Chat is what the app adds to the chat.

type ChatCommand added in v0.16.154

type ChatCommand struct {
	// Name is the command without its slash.
	Name string `json:"name"`
	// Slash is what the agent is sent: /<plugin>:<name>, which no other command can take.
	Slash string `json:"slash"`
	// Description is the description of commands/<name>.md; empty when the file has none.
	Description string `json:"description"`
	Kind        string `json:"kind"`
}

ChatCommand is a command of the app as the page's «/» palette lists it.

type CheckResult added in v0.16.86

type CheckResult struct {
	App      string    `json:"app"`
	AppName  string    `json:"appName"`
	Check    string    `json:"check"`
	Title    string    `json:"title,omitempty"`
	Findings []Finding `json:"findings"`
	// Blocks is true when the check keeps the document from being shared as it is.
	Blocks bool `json:"blocks"`
	// Failed says why the check could not run, in words for the person; its findings are then empty.
	Failed string `json:"failed,omitempty"`
}

CheckResult is one check run.

func RunChecks added in v0.16.86

func RunChecks(ctx context.Context, docs SinopiaDocs, state *SinopiaState, project, kind, trigger string, active []Installed, pkgOf func(id string) *Package) []CheckResult

RunChecks runs the checks of the apps on in the document that run on a trigger, keeps their findings as marks and returns each check's result. The tools are called with ctx; a check that cannot run says so and finds nothing.

type ClaudeEval added in v0.16.86

type ClaudeEval struct {
	// Bin is the claude executable; "" is `claude` off the PATH.
	Bin string
	// Harnessly is the harnessly executable the guard hook runs as; "" is this one.
	Harnessly string
	// Model is passed as --model when set.
	Model string
}

ClaudeEval is the EvalAgent over Claude Code.

func (*ClaudeEval) Name added in v0.16.86

func (a *ClaudeEval) Name() string

func (*ClaudeEval) Run added in v0.16.86

func (a *ClaudeEval) Run(ctx context.Context, spec RunSpec) (Transcript, error)

Run runs the prompt once.

type ClaudeJudge added in v0.16.86

type ClaudeJudge struct {
	Bin   string
	Model string
}

ClaudeJudge is the EvalJudge over Claude Code: one print-mode call that reads what the agent did and answers PASS or FAIL on its first line.

func (*ClaudeJudge) Judge added in v0.16.86

func (j *ClaudeJudge) Judge(ctx context.Context, criterion, prompt string, tr Transcript) (bool, string, error)

type ConflictError added in v0.16.154

type ConflictError struct{ Current int64 }

ConflictError is the refusal of a write whose ifVersion is not the key's version; Current is the version it has.

func (*ConflictError) Error added in v0.16.154

func (e *ConflictError) Error() string

func (*ConflictError) Is added in v0.16.154

func (e *ConflictError) Is(target error) bool

type ConnectionSource added in v0.16.154

type ConnectionSource interface {
	// Transport is "http" or "sse" for the person's connection made from catalog entry id; ok is false when there is none
	// or it waits for a sign-in.
	Transport(id string) (transport string, ok bool)
}

ConnectionSource is the person's connections (Settings → Connections) as far as a launch needs them: the connection made from a catalog entry, and whether it can be used now (turned on, signed in).

type ContextItem

type ContextItem struct {
	ID   string `json:"id"`
	Tool string `json:"tool"`
	Mode string `json:"mode"`
}

ContextItem is a source the agent reads on demand or gets on activation.

func ContextItems added in v0.16.154

func ContextItems(m *Manifest) []ContextItem

ContextItems are the app's context items the hooks send.

type Decision

type Decision string

Decision is the guard's answer for one call.

const (
	// DecideNone: no app has a rule for the call; the chat's own permissions decide.
	DecideNone    Decision = ""
	DecideAllow   Decision = "allow"
	DecideConfirm Decision = "confirm"
	DecideDeny    Decision = "deny"
)

type DecisionEntry added in v0.16.154

type DecisionEntry struct {
	// At is the time of the decision, in milliseconds.
	At int64 `json:"at"`
	// Session is the agent's own session the call was made in.
	Session  string `json:"session,omitempty"`
	App      string `json:"app"`
	Tool     string `json:"tool"`
	Rule     string `json:"rule"`
	Decision string `json:"decision"`
	Reason   string `json:"reason,omitempty"`
}

DecisionEntry is one line of the journal.

func ReadDecisions added in v0.16.154

func ReadDecisions(dir, conv, app string, limit int) ([]DecisionEntry, error)

ReadDecisions is the last limit lines of the conversation's journal for an app, newest first. A journal that is not there is an empty list; a line that cannot be read is skipped.

type DeployNetwork added in v0.16.154

type DeployNetwork struct {
	// Internal are host names ("gitlab.corp") or suffixes ("*.corp", any name under corp) whose addresses may be
	// private, loopback or shared (100.64.0.0/10). Link-local addresses (cloud metadata) stay closed even to them.
	Internal []string
	// Roots are the certificates a server's chain may end in besides the system's; nil: the system's only.
	Roots *x509.CertPool
}

DeployNetwork is what the admin of a deployment lets the apps' MCP calls (a view's hl.tools.call, a Sinopia check) reach besides the public internet: internal hosts by name, and the organization's root certificates. An app cannot widen it: the list comes from the machine's environment (RUNTIME_APPS_INTERNAL_HOSTS, RUNTIME_APPS_CA_FILE).

func NetworkFromEnv added in v0.16.154

func NetworkFromEnv(getenv func(string) string) (DeployNetwork, error)

NetworkFromEnv reads the deployment's network: RUNTIME_APPS_INTERNAL_HOSTS (comma-separated names and *.suffixes) and RUNTIME_APPS_CA_FILE (PEM certificates added to the system's roots).

func (*DeployNetwork) IsInternal added in v0.16.154

func (n *DeployNetwork) IsInternal(host string) bool

IsInternal says whether the admin listed the host as an internal one.

type EnvInstall added in v0.16.154

type EnvInstall struct {
	// Link is the hub link (its folder) whose list brought it: each link prunes only its own.
	Link string `json:"link"`
	// ItemID is the hub's environment item that brought it.
	ItemID  string `json:"itemId"`
	ID      string `json:"id"`
	Version string `json:"version"`
	// Sum is the hash of the folder it was installed from: the same version with the same sum is already in place.
	Sum      string    `json:"sum"`
	Dir      string    `json:"dir"`
	Locked   bool      `json:"locked,omitempty"`
	At       int64     `json:"at"`
	Manifest *Manifest `json:"manifest"`
}

EnvInstall is one app the environment installed.

type EnvInstallOptions added in v0.16.154

type EnvInstallOptions struct {
	// Link is the hub link whose list has the item.
	Link string
	// ItemID is the hub's environment item.
	ItemID string
	// Locked: the item is pinned, the person cannot turn the app off.
	Locked      bool
	HostVersion string
	Now         time.Time
}

EnvInstallOptions say how the environment installs an app.

type ErrWallRequired added in v0.16.154

type ErrWallRequired struct{ Cause error }

ErrWallRequired: the deployment requires the wall around the apps (RUNTIME_APPS_REQUIRE_WALL) and this machine cannot make it. The text names the cause and the command that puts it right.

func (ErrWallRequired) Error added in v0.16.154

func (e ErrWallRequired) Error() string

func (ErrWallRequired) Unwrap added in v0.16.154

func (e ErrWallRequired) Unwrap() error

type EvalAgent added in v0.16.86

type EvalAgent interface {
	Name() string
	Run(ctx context.Context, spec RunSpec) (Transcript, error)
}

EvalAgent runs a real agent on one prompt and gives back what it did.

type EvalCase added in v0.16.86

type EvalCase struct {
	// Name is the file's name without .json.
	Name   string `json:"-"`
	Prompt string `json:"prompt"`
	Mocks  struct {
		// MCP maps a server of the package's .mcp.json to a fixture (a file of the package) that answers for it.
		MCP map[string]string `json:"mcp"`
	} `json:"mocks"`
	Expect  EvalExpect   `json:"expect"`
	Graders []EvalGrader `json:"graders"`
	// Runs is how many times the scenario runs; 0 is 3.
	Runs int `json:"runs"`
	// Baseline also runs the scenario without the app, to show what the app changes.
	Baseline bool `json:"baseline"`
}

EvalCase is one scenario.

func LoadEvalCases added in v0.16.86

func LoadEvalCases(dir string) ([]EvalCase, error)

LoadEvalCases reads the scenarios of a package, by name.

func ParseEvalCase added in v0.16.86

func ParseEvalCase(name string, raw []byte) (EvalCase, error)

ParseEvalCase reads one scenario; the error says what is wrong in words.

func (EvalCase) Judge added in v0.16.86

func (c EvalCase) Judge(tr Transcript) []string

Judge checks a transcript against the scenario's expectations; the failures say in words what did not hold. The llm graders are not here (see EvalJudge).

type EvalExpect added in v0.16.86

type EvalExpect struct {
	// ToolUsed and ToolNotUsed name tools as "<server>.<tool>" for an MCP tool, or the agent's own tool name (Bash).
	ToolUsed    []string `json:"tool_used"`
	ToolNotUsed []string `json:"tool_not_used"`
	// FinalText and FinalTextNot are regular expressions the agent's last words must / must not match.
	FinalText    []string `json:"final_text"`
	FinalTextNot []string `json:"final_text_not"`
	// MaxToolCalls bounds the calls; 0 is no bound.
	MaxToolCalls int `json:"max_tool_calls"`
}

EvalExpect is what must hold of a run.

type EvalGrader added in v0.16.86

type EvalGrader struct {
	LLM string `json:"llm"`
}

EvalGrader is a criterion a model judges.

type EvalJudge added in v0.16.86

type EvalJudge interface {
	Judge(ctx context.Context, criterion, prompt string, tr Transcript) (bool, string, error)
}

EvalJudge decides whether a transcript meets a criterion in words.

type EvalOptions added in v0.16.86

type EvalOptions struct {
	Agent EvalAgent
	// Judge answers the llm graders; nil leaves them unjudged (the report says so).
	Judge EvalJudge
	// Threshold is the pass rate the report needs to be ok; 0 is DefaultEvalThreshold.
	Threshold float64
	// RunsOverride replaces every scenario's runs when above 0.
	RunsOverride int
	// Only runs the scenarios named here (all when empty).
	Only []string
	// NoBaseline leaves out the baseline runs.
	NoBaseline bool
	// Prepare makes the package the agent runs on from the author's folder and the case's mocks; nil uses the folder
	// as it is (the mocks are not applied).
	Prepare func(dir string, c EvalCase) (string, func(), error)
	Now     func() time.Time
	Timeout time.Duration
}

EvalOptions say how to run the evals.

type EvalReport added in v0.16.86

type EvalReport struct {
	App     string `json:"app"`
	Version string `json:"version"`
	Agent   string `json:"agent"`
	At      int64  `json:"at"`
	Runs    int    `json:"runs"`
	Passed  int    `json:"passed"`
	// PassRate is Passed / Runs.
	PassRate  float64 `json:"passRate"`
	Threshold float64 `json:"threshold"`
	Ok        bool    `json:"ok"`
	// BaselineRate is the pass rate without the app, over the scenarios that asked for it; nil with none.
	BaselineRate *float64 `json:"baselineRate,omitempty"`
	// ContextTokens is what the app adds to a run's input, on average: the runs with the app less the baseline's.
	ContextTokens *int         `json:"contextTokens,omitempty"`
	Cases         []CaseReport `json:"cases"`
}

EvalReport is the result of `harnessly app eval`; it is what EvalReportPath holds.

func RunEval added in v0.16.86

func RunEval(ctx context.Context, dir string, opt EvalOptions) (EvalReport, error)

RunEval runs the scenarios of the package in dir on the agent in the options and judges them.

type ExplainChat added in v0.16.154

type ExplainChat struct {
	Provider string
	Apps     []string
}

ExplainChat is the chat an explanation is about; nil for none (run outside a chat).

type ExplainInput added in v0.16.154

type ExplainInput struct {
	ID          string
	App         *Installed
	Chat        *ExplainChat
	Waiting     []string
	HostVersion string
	// Wall says whether the wall applies here (Linux); WallErr is what keeps it from standing, nil when it stands.
	Wall      bool
	WallErr   error
	ChatBytes int
}

ExplainInput is what Explain reads: the install (nil when the app is not on this machine), the chat, the required secrets still missing, the running harnessly's version, the wall's state and the chat's apps' weight.

type ExplainLine added in v0.16.154

type ExplainLine struct {
	Layer string `json:"layer"`
	Says  string `json:"says"`
	Off   bool   `json:"off,omitempty"`
}

ExplainLine is one layer's word: Layer names it, Says is what it says, Off marks the layer that keeps the app off.

func Explain added in v0.16.154

func Explain(in ExplainInput) []ExplainLine

Explain is the layers' words for one app, in their order.

type FileScope added in v0.16.86

type FileScope struct {
	// Workspace is the chat's working folder.
	Workspace string
	// Read and Write are the masks of the app's files.read:<mask> and files.write:<mask>.
	ReadMasks, WriteMasks []string
	// Forbidden are absolute folders no app reaches whatever the workspace holds: the host's data folder (the registry, the
	// cli-token), usually outside the workspace but not always.
	Forbidden []string
}

FileScope is what one app, in one workspace, may reach.

func (FileScope) Read added in v0.16.86

func (s FileScope) Read(rel string) ([]byte, error)

Read reads a file of the workspace the app may read, up to MaxFileBytes.

func (FileScope) Resolve added in v0.16.86

func (s FileScope) Resolve(rel string, write bool) (string, error)

Resolve judges a path of the workspace for a read or a write and gives the clean relative path to use with the workspace's root. It does not touch the path's content.

func (FileScope) Write added in v0.16.86

func (s FileScope) Write(rel string, data []byte) error

Write writes a file of the workspace the app may write, creating the folders it lies in.

type Finding added in v0.16.86

type Finding struct {
	Node    string `json:"node"`
	Level   string `json:"level"`
	Message string `json:"message"`
	Rule    string `json:"rule,omitempty"`
	// Fix is a patch (a list of ops) that mends the finding, when the check knows one.
	Fix any `json:"fix,omitempty"`
}

Finding is one thing a check found.

type GuestLink struct {
	ID   string `json:"id"`
	Hash string `json:"hash"`
	App  string `json:"app"`
	View string `json:"view"`
	// Write lets the guest's view write to the link's storage; a link reads only by default.
	Write     bool  `json:"write,omitempty"`
	CreatedAt int64 `json:"createdAt"`
	ExpiresAt int64 `json:"expiresAt"`
	Revoked   bool  `json:"revoked,omitempty"`
}

GuestLink is one link, as it is kept (the token is not: only its hash).

func (GuestLink) Live added in v0.16.86

func (l GuestLink) Live(now time.Time) bool

Live: the link has not ended at now.

type Guests added in v0.16.86

type Guests struct {

	// Now is the clock; nil is the real one.
	Now func() time.Time
	// OnCreate and OnRevoke are told, without blocking, of a link made and of a link ended (revoked, or its app
	// removed). The hash goes with a made link, never the token.
	OnCreate func(GuestLink)
	OnRevoke func(id string)
	// contains filtered or unexported fields
}

Guests keeps the links of a machine.

func NewGuests added in v0.16.86

func NewGuests(reg *Registry, storage *Storage) *Guests

NewGuests is the links of a registry; the storage is where the links' areas are.

func (*Guests) Create added in v0.16.86

func (g *Guests) Create(appID, view string, ttl time.Duration, write bool) (token string, link GuestLink, err error)

Create makes a link to an installed app's view; the token comes back once. A ttl of 0 is DefaultGuestTTL.

func (*Guests) List added in v0.16.86

func (g *Guests) List(appID string) ([]GuestLink, error)

List are the links that have not ended.

func (*Guests) Resolve added in v0.16.86

func (g *Guests) Resolve(token string) (GuestLink, Installed, error)

Resolve is the live link of a token, and the app it shows. A link whose app is gone, or no longer shows an app view, is gone.

func (*Guests) Revoke added in v0.16.86

func (g *Guests) Revoke(id string) error

Revoke ends a link by its id.

func (*Guests) RevokeApp added in v0.16.86

func (g *Guests) RevokeApp(appID string) (int, error)

RevokeApp ends every live link of an app (it was removed); the number ended comes back.

func (*Guests) ServeHTTP added in v0.16.86

func (g *Guests) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP answers the guest routes. No session: the token in the path is the whole authority, and it names one view.

type HostTools added in v0.16.86

type HostTools struct {
	Conv     string
	Registry *Registry
	Storage  *Storage
	Asks     *Asks
	// Enabled are the apps on in the chat now.
	Enabled func() []string
	// Open asks the chat's pane to open an app's tab (target is <id>[/<view>]).
	Open func(target string) error
	// Sinopia serves the Document API to the agent; nil where the machine has no library.
	Sinopia *SinopiaHost
	// Widgets keep what the agent shows in the chat's feed; nil refuses the widget tools.
	Widgets *Widgets
	// WidgetChanged tells the chat's pages that a widget of the chat was shown or changed; may be nil.
	WidgetChanged func(conv string)
}

HostTools is the agent-side host tools of one chat: it answers for the apps on in that chat and nothing else.

func (HostTools) Call added in v0.16.86

func (t HostTools) Call(ctx context.Context, name string, args *jsvalue.Object) *jsvalue.Object

func (HostTools) Has added in v0.16.86

func (HostTools) Has(name string) bool

func (HostTools) Instructions added in v0.16.86

func (HostTools) Instructions() string

func (HostTools) Tools added in v0.16.86

func (HostTools) Tools() []any

type InstallOptions

type InstallOptions struct {
	// Dev points the install at the folder instead of copying it.
	Dev bool
	// Channel is the channel the install follows ("" for none).
	Channel string
	// HostVersion is this harnessly's version, checked against the manifest's range.
	HostVersion string
	// Source is what the install records as where it came from, for a package that was unpacked in a folder of its own
	// that is removed afterwards ("" records the folder installed from).
	Source string
	Now    func() time.Time
}

InstallOptions say how to install.

type Installed

type Installed struct {
	ID      string `json:"id"`
	Version string `json:"version"`
	// Dir is the package's folder: the copy, or the author's folder for a dev install.
	Dir string `json:"dir"`
	// Source is the folder or address it was installed from.
	Source string `json:"source"`
	Dev    bool   `json:"dev,omitempty"`
	// Channel is the channel the install follows (see channels.go); "" is an install of a folder or a pinned version.
	Channel string `json:"channel,omitempty"`
	// Previous is the version the install had before the last update.
	Previous string `json:"previous,omitempty"`
	// Team: the install is the team's, made by an owner for everybody (see team.go); the person can turn it off for
	// themselves (Muted), not remove it. Never written to installed.json.
	Team bool `json:"team,omitempty"`
	// Env: the install is the environment's (see envinstall.go); Locked: its item is pinned, so it cannot be turned off.
	// Never written to installed.json.
	Env         bool  `json:"env,omitempty"`
	Locked      bool  `json:"locked,omitempty"`
	Muted       bool  `json:"muted,omitempty"`
	InstalledAt int64 `json:"installedAt"`
	UpdatedAt   int64 `json:"updatedAt"`
	// Manifest is the manifest as installed, so the list needs no read of every package.
	Manifest *Manifest `json:"manifest"`
}

Installed is one installed app as the registry keeps it.

func ActiveInDocument added in v0.16.86

func ActiveInDocument(list []Installed, kind string) []Installed

ActiveInDocument are the installed apps that are on in a document of a kind.

type KindInfo added in v0.16.86

type KindInfo struct {
	ID            string `json:"id"`
	Title         string `json:"title"`
	Icon          string `json:"icon,omitempty"`
	App           string `json:"app"`
	AppName       string `json:"appName"`
	Editor        string `json:"editor"`
	SchemaVersion int    `json:"schemaVersion"`
}

KindInfo is a document type as the page lists it.

type KindOpen added in v0.16.86

type KindOpen struct {
	// Version is the document's format version after opening (0 when none is recorded); Current is the app's.
	Version int `json:"version"`
	Current int `json:"current"`
	// Migrated is set when this opening migrated the document, from From.
	Migrated bool `json:"migrated"`
	From     int  `json:"from,omitempty"`
	// ReadOnly is set when the document cannot be opened for editing, with Reason.
	ReadOnly bool `json:"readOnly"`
	// Code says why in a word the page turns into plain words of its own language; Reason is the detail.
	Code   string `json:"code,omitempty"`
	Reason string `json:"reason,omitempty"`
}

KindOpen is what opening a document of an app's type found.

type Launcher

type Launcher struct {
	Registry *Registry
	// GuardCommand is the hook command line; "" is `harnessly hook app-guard` off the agents' PATH.
	GuardCommand string
	// GuardProbe runs the hook command line once at a launch and returns an error when the guard does not answer; nil skips
	// the check (a test).
	GuardProbe func(command string) error
	// MCPConfigPath is the runtime's `--mcp-config` file (the preview server's); the host's app tools reach the same
	// endpoint with the same token, under the server name harnessly-app. "" leaves the chat without them.
	MCPConfigPath string
	// Boundary is the operating system's wall around the agent (boundary.go); nil launches without it and says nothing,
	// which only a test does.
	Boundary *Boundary
	// RequireWall refuses a chat with apps whose wall cannot be made, with the reason and the fix (a deployment's
	// RUNTIME_APPS_REQUIRE_WALL=1); false starts it without the wall and says so, as boundary.go says why.
	RequireWall bool
	// AgentToken issues the token of one launch (gate.CLIToken.IssueAgent), which the routes that change the apps
	// refuse; the agent's CLI reads it from the file HARNESSLY_CLI_TOKEN_FILE names. nil gives the agent none (a test).
	AgentToken func(session string, ttl time.Duration) (string, error)
	// Secrets are the machine's safe, for the ${secret:<name>} an app's .mcp.json names (launch_secrets.go); nil leaves
	// the servers that name one out of the launch.
	Secrets SecretSource
	// Connections are the person's connections, for the servers of an app's .mcp.json that name one (launch_connections.go);
	// nil leaves those servers out of the launch.
	Connections ConnectionSource
}

Launcher is agents.AppLauncher over a registry.

func (*Launcher) Claude

func (l *Launcher) Claude(ids []string, settingsPath string) (agents.ClaudeApps, error)

Claude is what a Claude Code chat with the apps adds to its launch.

func (*Launcher) ClaudeFor added in v0.16.154

func (l *Launcher) ClaudeFor(conversation string, ids []string, settingsPath string) (agents.ClaudeApps, error)

ClaudeFor is Claude for the launch of a chat: its grant names the chat (writeGrant).

func (*Launcher) Codex added in v0.16.154

func (l *Launcher) Codex(conversation string, ids []string) (agents.CodexApps, error)

Codex is what a Codex chat with the apps adds to its launch.

type MCPServer

type MCPServer struct {
	Type    string            `json:"type,omitempty"`
	URL     string            `json:"url,omitempty"`
	Command string            `json:"command,omitempty"`
	Args    []string          `json:"args,omitempty"`
	Env     map[string]string `json:"env,omitempty"`
	Headers map[string]string `json:"headers,omitempty"`
	// Connection makes the server the person's own connection (Settings → Connections, internal/mcpconn) from the
	// catalog entry of that id: the address and the sign-in are the connection's, so a server with it names no url,
	// headers or command. Nobody's token is in the package.
	Connection string `json:"connection,omitempty"`
}

MCPServer is one server of .mcp.json: a remote one (url) or, for a trusted app, a local process (command).

func (MCPServer) Filled added in v0.16.154

func (s MCPServer) Filled(values map[string]string) (MCPServer, []string)

Filled is the server with its secrets in place; missing are the names that had no value. The result is for the machine's config files only (0600), never for a view, a log or the agent's context.

func (MCPServer) Secrets added in v0.16.154

func (s MCPServer) Secrets() []string

ServerSecrets are the names of the secrets a server of .mcp.json uses: in its headers and, for a local one, in its environment.

type MCPStatus added in v0.16.86

type MCPStatus struct {
	Name   string `json:"name"`
	Status string `json:"status"`
}

MCPStatus is one MCP server of a session and whether it connected.

type Manifest

type Manifest struct {
	ID          string          `json:"id"`
	Name        string          `json:"name"`
	Description string          `json:"description"`
	Icon        string          `json:"icon,omitempty"`
	Version     string          `json:"version"`
	Harnessly   string          `json:"harnessly"`
	Trust       string          `json:"trust"`
	Targets     []string        `json:"targets"`
	Branding    *Branding       `json:"branding,omitempty"`
	When        string          `json:"when,omitempty"`
	Activation  *Activation     `json:"activation,omitempty"`
	Permissions []string        `json:"permissions"`
	Network     *Network        `json:"network,omitempty"`
	Secrets     []Secret        `json:"secrets,omitempty"`
	Settings    json.RawMessage `json:"settings,omitempty"`
	Agent       *Agent          `json:"agent,omitempty"`
	Views       []View          `json:"views,omitempty"`
	Chat        *Chat           `json:"chat,omitempty"`
	Sinopia     json.RawMessage `json:"sinopia,omitempty"`
	Storage     json.RawMessage `json:"storage,omitempty"`
	Backend     *Backend        `json:"backend,omitempty"`
}

Manifest is harnessly/app.json.

func (*Manifest) ActivatesOn added in v0.16.154

func (m *Manifest) ActivatesOn(on string) bool

ActivatesOn says whether the manifest's activation lists the value (OnAlways, OnDocument, "command:/x").

func (*Manifest) Allows added in v0.16.86

func (m *Manifest) Allows(permission string) bool

Allows says whether the app holds a permission. files.read and files.write are held in the manifest with a mask (files.read:docs/*): the app holds the right when it lists any; which paths it reaches is FileScope's to judge.

func (*Manifest) Authorize added in v0.16.86

func (m *Manifest) Authorize(method, target string, params map[string]any) error

Authorize checks a bridge call of an app's view: the method exists, the app holds its permission and the view is shown in a target the app declared. Storage scope "space" writes need the right of their own.

func (*Manifest) ChatCommands added in v0.16.154

func (m *Manifest) ChatCommands(dir string) []ChatCommand

ChatCommands are the chat.commands of the app, each with the description from its file.

func (*Manifest) Check

func (m *Manifest) Check() Problems

Check is every rule of the manifest on its own, without the package's files (Package.Check adds those).

func (*Manifest) CheckSettings added in v0.16.154

func (m *Manifest) CheckSettings(values map[string]any) map[string]string

CheckSettings judges values against the manifest's schema: a key it does not describe, a value of another type, one outside an enum, a range or a length is a problem, as is a required key left out. The problems are by key.

func (*Manifest) Command added in v0.16.154

func (m *Manifest) Command() string

Command is the slash command that turns the app on in a chat (`activation.on: ["command:/x"]` is "/x"); "" when none.

func (*Manifest) FileScope added in v0.16.86

func (m *Manifest) FileScope(workspace string, forbidden ...string) FileScope

FileScope is the app's reach into a workspace; forbidden are the host's own folders.

func (*Manifest) FrameURL added in v0.16.86

func (m *Manifest) FrameURL(entry string) (string, bool)

FrameURL is the address of a view the app's own server hosts, when it may be framed: https, no credentials in it, and its host listed in network.frames. The page frames nothing else.

func (*Manifest) HasTarget

func (m *Manifest) HasTarget(target string) bool

HasTarget says whether the app works in a target; sinopia.* covers every Sinopia kind.

func (*Manifest) OnInDocument added in v0.16.86

func (m *Manifest) OnInDocument(kind string) bool

OnInDocument says whether the app turns on in an open document of a kind: it works in that kind, and it asks to be on when a document is open (activation.on has "document").

func (*Manifest) SecretStates added in v0.16.154

func (m *Manifest) SecretStates(has func(name string) bool) []SecretState

SecretStates are the manifest's secrets with whether each has a value; has says it by the secret's own name.

func (*Manifest) SettingFields added in v0.16.154

func (m *Manifest) SettingFields() []SettingField

SettingFields are the manifest's settings in the order of their names; nil for an app with none.

func (*Manifest) ShareableView added in v0.16.86

func (m *Manifest) ShareableView(view string) (View, bool)

ShareableView is the view an app shares by link: the one named, or the first whose targets include app.

func (*Manifest) SinopiaOf added in v0.16.86

func (m *Manifest) SinopiaOf() (Sinopia, error)

SinopiaOf is the app's Sinopia contributions; an app that has none gets an empty value. A manifest that was checked has a `sinopia` that reads; one that was not may not, and then the error comes back.

func (*Manifest) ViewCSP added in v0.16.86

func (m *Manifest) ViewCSP() string

ViewCSP is the Content-Security-Policy of an app's views, built from its network: nothing leaves the view unless the manifest names the address. Scripts are files of the view (no inline ones, no eval).

func (*Manifest) ViewPath added in v0.16.86

func (m *Manifest) ViewPath(viewID string) (string, error)

ViewPath is the address of a view's entry on the view server without its session: /<app id>/<entry>. An external entry has none. The page puts the session's token in front.

func (*Manifest) WaitingFor added in v0.16.154

func (m *Manifest) WaitingFor(has func(name string) bool) []string

WaitingFor are the required secrets that have no value: while there are any, the app is «ждёт секрет». Its chat does not fail: the servers that use the missing secrets are left out of the launch, and the rest of the app works.

type Mark added in v0.16.86

type Mark struct {
	Node   string `json:"node"`
	Level  string `json:"level"`
	Note   string `json:"note"`
	Source string `json:"source"`
	Rule   string `json:"rule,omitempty"`
	Fix    any    `json:"fix,omitempty"`
	At     int64  `json:"at"`
}

Mark is a note on a node of a board: a finding of a check, an app's remark, a comment.

type MockFixture added in v0.16.86

type MockFixture struct {
	Tools []MockTool `json:"tools"`
}

MockFixture is a fixture file.

func ReadMockFixture added in v0.16.86

func ReadMockFixture(path string) (MockFixture, error)

ReadMockFixture reads and checks a fixture.

type MockTool added in v0.16.86

type MockTool struct {
	Name        string          `json:"name"`
	Description string          `json:"description"`
	InputSchema json.RawMessage `json:"inputSchema"`
	Result      json.RawMessage `json:"result"`
}

MockTool is one tool of a fixture.

type Network

type Network struct {
	Connect   []string `json:"connect,omitempty"`
	Resources []string `json:"resources,omitempty"`
	Frames    []string `json:"frames,omitempty"`
	Reason    string   `json:"reason,omitempty"`
}

Network lists the hosts a view may reach; "*" needs a reason.

type Package

type Package struct {
	Dir      string
	Manifest *Manifest
	// MCP is the package's .mcp.json servers by name, as written.
	MCP map[string]MCPServer
	// PluginParts are the parts of a Claude Code plugin the package carries beyond what an app is made of: hooks that
	// run commands on the agent's events, agents, output styles and the like (pluginParts). A declarative or sandboxed
	// package may carry none; a trusted one shows them in its permissions.
	PluginParts []string
}

Package is a package read from a folder.

func (*Package) CanCallTool added in v0.16.86

func (p *Package) CanCallTool(name string) (server, tool string, err error)

CanCallTool says whether a view may call a tool by its name "<server>.<tool>": only the servers of the app's own package, never another app's or the host's.

func (*Package) Connections added in v0.16.154

func (p *Package) Connections() []string

Connections are the catalog ids of the connections the package's servers name, sorted, each once.

func (*Package) File

func (p *Package) File(rel string) ([]byte, error)

File reads a file of the package by a manifest path.

func (*Package) ViewFile added in v0.16.86

func (p *Package) ViewFile(rel string) (string, error)

ViewFile resolves a request path of a view (the part after the app id) to a file of the package. Only a view's own files are served: its entry, and the files under ui/ or under the entry's folder. Anything else of the package (the manifest, instructions, .mcp.json with its headers) is not for a view to read.

type PatchOp added in v0.16.86

type PatchOp struct {
	Op    string          `json:"op"`
	Path  string          `json:"path"`
	From  string          `json:"from,omitempty"`
	Value json.RawMessage `json:"value,omitempty"`
}

PatchOp is one operation of a JSON Patch.

func ParsePatch added in v0.16.86

func ParsePatch(raw []byte) ([]PatchOp, error)

ParsePatch reads a JSON Patch and checks its shape (not its fit to any document).

type PendingAsk added in v0.16.86

type PendingAsk struct {
	ID        string   `json:"id"`
	App       string   `json:"app"`
	AppName   string   `json:"appName"`
	Question  string   `json:"question"`
	Options   []string `json:"options"`
	CreatedAt int64    `json:"createdAt"`
}

PendingAsk is an open choice as the page lists it.

type Problem

type Problem struct {
	Path    string `json:"path"`
	Message string `json:"message"`
	// Warning problems do not stop an install; --strict counts them as errors.
	Warning bool `json:"warning,omitempty"`
}

Problem is one thing wrong with a package: the field it is about and what is wrong, in words.

func (Problem) String

func (p Problem) String() string

type Problems

type Problems []Problem

Problems is the list a check returns; empty means the package is fine.

func DesignProblems added in v0.16.154

func DesignProblems(dir string) Problems

DesignProblems reads the package's HTML and CSS for the design warnings, with the file and line of each.

func (Problems) Error

func (ps Problems) Error() string

func (Problems) Errors

func (ps Problems) Errors() Problems

Errors are the problems that are not warnings.

type PromoteOptions added in v0.16.86

type PromoteOptions struct {
	// EvalThreshold is the share of evals that must pass for stable; 0 is DefaultEvalThreshold.
	EvalThreshold float64
	Now           func() time.Time
}

PromoteOptions say how to promote.

type PublicEntry added in v0.16.86

type PublicEntry struct {
	CatalogEntry
	// Review is approved (listed) or pending (waits for a person at the platform).
	Review string `json:"review"`
	// Why says what asks for the look, when Review is pending.
	Why []string `json:"why,omitempty"`
}

PublicEntry is an app in the public catalog.

type PublicInstallOptions added in v0.16.86

type PublicInstallOptions struct {
	HostVersion string
	// Sum is the archive of the entry the person was shown. An entry that has another is not installed.
	Sum string
}

PublicInstallOptions say how a person installs from the public catalog.

type PublicSnapshot added in v0.16.86

type PublicSnapshot struct {
	At      int64                 `json:"at"`
	Entries []PublicSnapshotEntry `json:"entries"`
}

PublicSnapshot is what the platform sends a machine: the reviewed list with the archives, or what a machine sends the platform to be reviewed and passed on.

func (PublicSnapshot) Validate added in v0.16.86

func (s PublicSnapshot) Validate() error

Validate refuses a snapshot this machine must not act on.

type PublicSnapshotEntry added in v0.16.86

type PublicSnapshotEntry struct {
	PublicEntry
	Archive []byte `json:"archive,omitempty"`
}

PublicSnapshotEntry is a public entry on the wire.

type PublishOptions added in v0.16.86

type PublishOptions struct {
	Now func() time.Time
}

PublishOptions say how to publish.

type PublishedVersion added in v0.16.86

type PublishedVersion struct {
	ID       string    `json:"id"`
	Version  string    `json:"version"`
	Channel  Channel   `json:"channel"`
	Dir      string    `json:"dir"`
	Manifest *Manifest `json:"-"`
}

PublishedVersion is a version in the published store.

type Range

type Range [][]comparator

Range is a parsed harnessly field.

func ParseRange

func ParseRange(s string) (Range, error)

ParseRange reads a range; the error says what is wrong in words.

func (Range) Allows

func (r Range) Allows(version string) bool

Allows says whether the host version is in the range. A host built from source ("dev") is in every range.

type Registry

type Registry struct {
	Root string
	// contains filtered or unexported fields
}

Registry reads and writes the list; every writer of this process goes through one Registry.

func Open

func Open(dataDir string) *Registry

Open is the process's one Registry of a data folder.

func (*Registry) ApplyPublic added in v0.16.86

func (r *Registry) ApplyPublic(s PublicSnapshot, host string, now time.Time) ([]string, error)

ApplyPublic takes the platform's list as this machine's public catalog. An entry whose archive is not the one its sum names, or holds a trusted app, is left out; the problems come back and the rest applies.

func (*Registry) ApplyTeam added in v0.16.86

func (r *Registry) ApplyTeam(s TeamSnapshot, host string, now time.Time) ([]string, error)

ApplyTeam takes the platform's snapshot as the machine's team: the catalog, the role and the installs, so the members' registries show the team's apps without an install of their own. An entry whose archive does not match its sum, or holds a trusted app, is left out of the installs (the rest still applies); the problems come back.

func (*Registry) ChannelVersion added in v0.16.86

func (r *Registry) ChannelVersion(id string, ch Channel) (string, error)

ChannelVersion is the version a channel points at now.

func (*Registry) Channels added in v0.16.86

func (r *Registry) Channels(id string) (map[Channel]ChannelInfo, error)

Channels are the channels of a published app that have a version.

func (*Registry) ConnectionGranted added in v0.16.154

func (r *Registry) ConnectionGranted(app, id string) bool

ConnectionGranted says whether the person agreed to the app using their connection from catalog entry id.

func (*Registry) DocKind added in v0.16.86

func (r *Registry) DocKind(project string) (string, bool)

DocKind is the type of a project that is a document of an app's type.

func (*Registry) DocKinds added in v0.16.86

func (r *Registry) DocKinds() map[string]string

DocKinds are the documents of the apps' types: project id → type.

func (*Registry) EnvHasItem added in v0.16.154

func (r *Registry) EnvHasItem(link, itemID string) bool

EnvHasItem: the app of the link's environment item is installed.

func (*Registry) Get

func (r *Registry) Get(id string) (Installed, error)

Get is one installed app.

func (*Registry) Grant added in v0.16.154

func (r *Registry) Grant(session string) (apps []string, conversation string)

Grant is a launch's record: the apps its token may use and the chat it was made for ("" when the runtime did not know the chat). The agent cannot write it: the launch's folder is a read-only bind in the wall (Seal.Open).

func (*Registry) GrantConnection added in v0.16.154

func (r *Registry) GrantConnection(app, id string) error

GrantConnection records the person's agreement. The app's package must name the connection.

func (*Registry) GrantedApps added in v0.16.154

func (r *Registry) GrantedApps(session string) []string

GrantedApps are the apps a launch's token may use the MCP proxy for; none when the launch left no record.

func (*Registry) Install

func (r *Registry) Install(dir string, opt InstallOptions) (Installed, Problems, error)

Install checks the package in dir and installs it, replacing an installed version of the same app. The problems are all the check found (warnings included); an install with errors is refused with ErrInvalid.

func (*Registry) InstallChannel added in v0.16.86

func (r *Registry) InstallChannel(id string, ch Channel, opt InstallOptions) (Installed, Problems, error)

InstallChannel installs the version a channel points at and makes the install follow that channel.

func (*Registry) InstallForEnv added in v0.16.154

func (r *Registry) InstallForEnv(dir string, opt EnvInstallOptions) (EnvInstall, bool, error)

InstallForEnv installs the app in dir as the environment's. It reports changed false when the same version from the same folder contents is already in place (only Locked may change then). Never the trusted tier.

func (*Registry) InstallForTeam added in v0.16.86

func (r *Registry) InstallForTeam(id string, ch Channel, opt TeamInstallOptions) (TeamInstall, error)

InstallForTeam installs the catalog's app on a channel for the whole team. Only an owner; never the trusted tier. The install follows the catalog entry: a later version of the entry reaches the team's machines (patch and minor at once, a new major or new rights only when an owner installs again).

func (*Registry) InstallFromPublic added in v0.16.86

func (r *Registry) InstallFromPublic(id string, opt PublicInstallOptions) (Installed, Problems, error)

InstallFromPublic installs a listed app for the person, from the archive the catalog names. The install is the person's own, like any: it can be removed, and it follows no channel.

func (*Registry) Kind added in v0.16.86

func (r *Registry) Kind(id string) (KindInfo, SinopiaKind, error)

Kind is one document type of an installed app; ErrNotInstalled when no app that is on adds it.

func (*Registry) Kinds added in v0.16.86

func (r *Registry) Kinds() ([]KindInfo, error)

Kinds are the document types of the apps that are on for the person, by id.

func (*Registry) List

func (r *Registry) List() ([]Installed, error)

List is every installed app that is on for the person, by id: their own installs, and the team's that they did not turn off or install themselves (their own install of the same app wins).

func (*Registry) ListAll added in v0.16.86

func (r *Registry) ListAll() ([]Installed, error)

ListAll is List with the team's apps the person turned off, which have Muted set.

func (*Registry) MuteTeamApp added in v0.16.86

func (r *Registry) MuteTeamApp(id string, mute bool) error

MuteTeamApp turns a team app (or the environment's) off for the person (on false: on again). It is theirs alone: nothing is sent anywhere.

func (*Registry) OnPublicChange added in v0.16.86

func (r *Registry) OnPublicChange(f func())

OnPublicChange sets what is called after PublishPublic. It is not called for a list applied from the platform.

func (*Registry) OnTeamChange added in v0.16.86

func (r *Registry) OnTeamChange(f func())

OnTeamChange sets what is called after the team's catalog or installs change on this machine (an owner's install or uninstall, a publish to the team, a rollback of the catalog). It is not called for a snapshot applied from the platform, nor for a person muting an app. The function must not block.

func (*Registry) OpenDocument added in v0.16.86

func (r *Registry) OpenDocument(st *Storage, project string, info KindInfo, k SinopiaKind) KindOpen

OpenDocument migrates a document of an older version, or says why it is read-only. It never leaves a document half migrated: the value and the version change in one write, or neither does.

func (*Registry) Package added in v0.16.86

func (r *Registry) Package(id string) (*Package, error)

Package reads an installed app's package from its folder (its .mcp.json servers included).

func (*Registry) PaneRef added in v0.16.86

func (r *Registry) PaneRef(text string) string

PaneRef is the canonical "<app id>/<view id>" of the pane view a text names: "<id>/<view>", or "<id>" for the app's default one (activation.openView when it is a pane view, else the first). "" when the app is not installed or has no such view for the pane.

func (*Registry) PendingPublic added in v0.16.86

func (r *Registry) PendingPublic() ([]PublicEntry, error)

PendingPublic are the entries that wait for a look, for the platform's reviewers.

func (*Registry) Promote added in v0.16.86

func (r *Registry) Promote(id, ref string, to Channel, opt PromoteOptions) (PublishedVersion, error)

Promote moves a published version up to beta or stable. The version number of the target channel is made from the source: stable takes the base (1.3.0-beta.2 becomes 1.3.0, copied as a version of its own), beta takes the next 1.3.0-beta.N from a dev version. Stable asks the evals (EvalThreshold).

func (*Registry) ProtectedDirs added in v0.16.86

func (r *Registry) ProtectedDirs() ([]string, error)

ProtectedDirs are the folders no app and no tool of the agent writes: the registry, and the package folder and the source folder of every installed app (a dev install points at its author's folder), whichever app owns them. The launch's guard and the files bridge both take this set, so they cannot drift; users of it compare in both the written and the resolved form (protectedForms).

func (*Registry) PruneEnv added in v0.16.154

func (r *Registry) PruneEnv(link string, keep []string) ([]string, error)

PruneEnv takes off the link's environment installs whose item is not among keep, and deletes their copies; the installs of other links are not touched. It returns the ids it took off.

func (*Registry) PublicCatalog added in v0.16.86

func (r *Registry) PublicCatalog(query string) ([]PublicEntry, error)

PublicCatalog is what anyone browses: the entries that are reviewed, narrowed by a query (a word of the id, the name or the description, any case), by name. The trusted tier is never in it, whatever a file says.

func (*Registry) PublicSnapshot added in v0.16.86

func (r *Registry) PublicSnapshot() (PublicSnapshot, error)

Snapshot is this machine's public entries with their archives, for the platform to review and send on.

func (*Registry) Publish added in v0.16.86

func (r *Registry) Publish(dir string, ch Channel, opt PublishOptions) (PublishedVersion, Problems, error)

Publish puts the package in dir on a channel as a new immutable version. A package whose manifest says 1.3.0 goes to stable as 1.3.0, and to dev or beta as 1.3.0-dev.N or 1.3.0-beta.N (the next free N); a manifest that already says a pre-release is published as written, on dev or beta only.

func (*Registry) PublishPublic added in v0.16.86

func (r *Registry) PublishPublic(id, version, by string, now time.Time) (PublicEntry, error)

PublishPublic puts the version on stable into the public catalog. An author's own act, from the machine they publish on.

func (*Registry) PublishToTeam added in v0.16.86

func (r *Registry) PublishToTeam(id, version string, ch Channel, by, host string, now time.Time) (CatalogEntry, error)

PublishToTeam puts a published version into the team's catalog on the channel it was published on. Any member may; the entry only offers the app, the owner's install is what puts it on the team's machines.

func (*Registry) Published added in v0.16.86

func (r *Registry) Published() (map[string]map[Channel]ChannelInfo, error)

Published lists the apps that have published versions, with their channels.

func (*Registry) Remove

func (r *Registry) Remove(id string) error

Remove uninstalls an app and deletes its copy; the author's folder of a dev install is left as it is.

func (*Registry) RevertMigration added in v0.16.86

func (r *Registry) RevertMigration(st *Storage, project string, info KindInfo, k SinopiaKind, to int) error

RevertMigration brings a migrated document back to the version it was before, from the copy the migration kept.

func (*Registry) ReviewPublic added in v0.16.86

func (r *Registry) ReviewPublic(id, version string, approve bool, now time.Time) error

ReviewPublic is the look of a person at the platform: approving lists the entry, refusing takes it out.

func (*Registry) RevokeConnection added in v0.16.154

func (r *Registry) RevokeConnection(app, id string) error

RevokeConnection takes the agreement back (a missing one is fine).

func (*Registry) Rollback added in v0.16.86

func (r *Registry) Rollback(id string, ch Channel) (PublishedVersion, error)

Rollback moves the channel back to the version it pointed at before. The version it leaves stays published, and its number stays taken.

func (*Registry) RollbackCatalog added in v0.16.86

func (r *Registry) RollbackCatalog(id string, ch Channel, host string, now time.Time) (CatalogEntry, error)

RollbackCatalog points a catalog entry back at the version before; the installs that follow it go back too.

func (*Registry) SetDocKind added in v0.16.86

func (r *Registry) SetDocKind(project, kind string) error

SetDocKind records that a project is a document of an app's type.

func (*Registry) SetTeam added in v0.16.86

func (r *Registry) SetTeam(space, role string, now time.Time) error

SetTeam makes this machine a member of a space (or, with an empty space, takes it out), keeping what the catalog already holds: the platform's snapshot normally does this; a self-hosted machine without one is told by hand.

func (*Registry) Snapshot added in v0.16.86

func (r *Registry) Snapshot() (TeamSnapshot, error)

Snapshot is this machine's team as a snapshot, for the platform to send the other machines of the team. The archives of the entries go along.

func (*Registry) SyncChannels added in v0.16.86

func (r *Registry) SyncChannels(opt SyncOptions) ([]SyncResult, error)

SyncChannels moves every install that follows a channel to the version the channel points at. A move back (the channel was rolled back, or the install's version is not in the channel's history any more) is made at once. A move up is made at once for a patch or a minor; a new major, or a new permission or secret, waits for a confirmation.

func (*Registry) Team added in v0.16.86

func (r *Registry) Team() (TeamInfo, error)

Team reads the team; Space is "" for a machine that is in none.

func (*Registry) UninstallForTeam added in v0.16.86

func (r *Registry) UninstallForTeam(id string, now time.Time) error

UninstallForTeam takes the app off the team's machines. Only an owner.

func (*Registry) VersionDir added in v0.16.86

func (r *Registry) VersionDir(id, version string) string

VersionDir is the folder of a published version.

type Rule added in v0.16.86

type Rule struct {
	ID       string `json:"id,omitempty"`
	Select   string `json:"select"`
	MaxWords int    `json:"maxWords,omitempty"`
	MaxChars int    `json:"maxChars,omitempty"`
	// MinFontPx is the smallest inline font-size, in px (pt, rem, em and cqw are read against the board's width).
	MinFontPx float64 `json:"minFontPx,omitempty"`
	Level     string  `json:"level,omitempty"`
	// Message is what the person reads; {n} is the measured value, {limit} the limit.
	Message string `json:"message"`
	// Fix is the style that mends a finding of this rule.
	Fix map[string]string `json:"fix,omitempty"`
}

Rule is one declarative rule of a check: it picks elements by a selector and finds fault with those that break a limit. A text limit counts the words that are the element's own; a font limit reads the element's inline font-size.

type RunSpec added in v0.16.86

type RunSpec struct {
	Prompt string
	// Package is the folder of the package (with the .mcp.json already answering with mocks, see PrepareEvalPackage).
	Package string
	// WithApp: the app is on. False is the baseline: the same agent, the same prompt, no app.
	WithApp bool
	Timeout time.Duration
}

RunSpec is one run of a scenario.

type Scope added in v0.16.86

type Scope string

Scope is an area of the storage.

const (
	ScopeInstall Scope = "install"
	ScopeUser    Scope = "user"
	ScopeChat    Scope = "chat"
	ScopeSpace   Scope = "space"
	ScopeDoc     Scope = "doc"
)

type Seal added in v0.16.86

type Seal struct {
	// Data is the runtime's data folder, Home the person's; "" leaves that part out.
	Data, Home string
	// Open are folders of the data folder that stay readable (read-only) in the wall: the launch folders of this
	// chat's own apps (launch_secrets.go). Every other launch's folder is not there.
	Open []string
}

Seal says what to seal.

type Secret

type Secret struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	Optional    bool   `json:"optional,omitempty"`
}

Secret is a secret the app asks for at install; the person types its value, the app never reads it.

type SecretSource added in v0.16.154

type SecretSource interface {
	HasApp(app, name string) bool
	RevealApp(app string, names []string) (map[string]string, error)
}

SecretSource is the machine's safe as far as the apps need it: the values of an app's secrets, by their own names.

type SecretState added in v0.16.154

type SecretState struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	Optional    bool   `json:"optional"`
	Set         bool   `json:"set"`
}

SecretState is one secret the app asks for, as «О приложении» shows it: whether it has a value, never the value.

type SelectedNode added in v0.16.86

type SelectedNode struct {
	ID          string            `json:"id,omitempty"`
	Page        string            `json:"page,omitempty"`
	Tpl         *int              `json:"tpl,omitempty"`
	Fingerprint string            `json:"fp,omitempty"`
	Selector    string            `json:"selector,omitempty"`
	Field       string            `json:"field,omitempty"`
	Tag         string            `json:"tag"`
	Text        string            `json:"text,omitempty"`
	Rect        *SelectedRect     `json:"rect,omitempty"`
	Hl          map[string]string `json:"hl,omitempty"`
}

SelectedNode is a node the person picked in the editor, as the page reports it.

type SelectedRect added in v0.16.86

type SelectedRect struct {
	X      float64 `json:"x"`
	Y      float64 `json:"y"`
	Width  float64 `json:"width"`
	Height float64 `json:"height"`
}

SelectedRect is where the node shows, in the board's pixels.

type Session added in v0.16.86

type Session struct {
	Token  string
	App    string
	View   string
	Target string
	// Conversation is the chat the view works beside; "" for a view with no chat.
	Conversation string
	// Document is the Sinopia document a view of a sinopia target is shown in; "" for any other view.
	Document string
	// Nonce is what the view's own document carries (a meta tag the view server writes into its pages) and the bridge
	// asks for in ui/initialize: a document the frame navigated to never saw it.
	Nonce string
	// contains filtered or unexported fields
}

Session is one mounted view.

type SettingField added in v0.16.154

type SettingField struct {
	Name        string   `json:"name"`
	Type        string   `json:"type"`
	Title       string   `json:"title"`
	Description string   `json:"description,omitempty"`
	Enum        []any    `json:"enum,omitempty"`
	Default     any      `json:"default,omitempty"`
	Required    bool     `json:"required,omitempty"`
	Min         *float64 `json:"minimum,omitempty"`
	Max         *float64 `json:"maximum,omitempty"`
}

SettingField is one setting as the form draws it.

type Sinopia added in v0.16.86

type Sinopia struct {
	Panels    []SinopiaPanel     `json:"panels,omitempty"`
	Selection []SinopiaSelection `json:"selection,omitempty"`
	Bindings  *SinopiaBindings   `json:"bindings,omitempty"`
	Checks    []SinopiaCheck     `json:"checks,omitempty"`
	Import    []SinopiaImport    `json:"import,omitempty"`
	Export    []SinopiaExport    `json:"export,omitempty"`
	Templates []string           `json:"templates,omitempty"`
	// Kinds are the document types the app adds (kinds.go).
	Kinds []SinopiaKind `json:"kinds,omitempty"`
}

Sinopia is the manifest's `sinopia`.

func (Sinopia) ForKind added in v0.16.86

func (s Sinopia) ForKind(kind string) Sinopia

ForKind is what the app contributes to a document of a kind: the panels, the selection items, the checks, the import and export entries meant for it. The bindings are the app's whole.

type SinopiaBindings added in v0.16.86

type SinopiaBindings struct {
	// Schema is the package file that describes the fields: a JSON Schema of an object; a value outside it is refused.
	Schema string `json:"schema,omitempty"`
	// Inspector is the view that opens when a bound element is clicked.
	Inspector string `json:"inspector"`
	// LockUnbound keeps free hand edits to the elements that are bound.
	LockUnbound bool `json:"lockUnbound,omitempty"`
}

SinopiaBindings ties the elements marked data-hl-field to the app's fields.

type SinopiaCall added in v0.16.86

type SinopiaCall struct {
	Docs  SinopiaDocs
	State *SinopiaState
	App   Installed
	// Pkg is the app's package (its templates and field schema); nil when it could not be read.
	Pkg     *Package
	Project string
	// Who is what the history names the writer: the app's name.
	Who string
	// Tab is the chat tab whose claims on a board do not stop a write, "" for the person's own page.
	Tab string
	// Agent says the call is the agent's, not a view's.
	Agent bool
}

SinopiaCall is one call of the Document API.

func (SinopiaCall) Call added in v0.16.86

func (c SinopiaCall) Call(method string, p map[string]any) (any, error)

Call runs a method with its parameters and returns the result for JSON.

type SinopiaCheck added in v0.16.86

type SinopiaCheck struct {
	ID    string   `json:"id"`
	Title string   `json:"title,omitempty"`
	Tool  string   `json:"tool,omitempty"`
	Rules []Rule   `json:"rules,omitempty"`
	On    []string `json:"on,omitempty"`
	// BlockShare is the level of a finding that keeps the document from being shared: "error" or "warning".
	BlockShare string   `json:"blockShare,omitempty"`
	Kinds      []string `json:"kinds,omitempty"`
}

SinopiaCheck looks at a document and reports what is wrong with it. It is either a tool of the app's own MCP server (Tool: "<server>.<tool>", given the document's nodes) or a list of rules the host evaluates itself (Rules), which needs no server and runs in the document's own process.

type SinopiaDoc added in v0.16.86

type SinopiaDoc struct {
	ID     string              `json:"id"`
	Kind   string              `json:"kind"`
	Title  string              `json:"title"`
	Boards []design.DocPageRef `json:"boards"`
	Rev    int64               `json:"rev"`
}

SinopiaDoc is a document as document() answers.

type SinopiaDocs added in v0.16.86

type SinopiaDocs interface {
	Document(project string) (SinopiaDoc, error)
	Nodes(project, page string) ([]design.DocNode, error)
	Query(project, selector, page string) ([]design.DocNode, error)
	Node(project, id string) (design.DocNode, error)
	Fields(project string) ([]design.DocField, error)
	Patch(project string, ops []design.DocOp, who design.DocActor) (design.DocPatched, error)
	AddBoard(project, title string, src []byte, tpl *design.DocTemplate, who design.DocActor) (design.DocPageRef, error)
}

SinopiaDocs is the library's part the Document API stands on (cmd/runtime gives it over design.Library).

type SinopiaExport added in v0.16.86

type SinopiaExport struct {
	ID    string   `json:"id"`
	Title string   `json:"title"`
	Tool  string   `json:"tool"`
	Kinds []string `json:"kinds,omitempty"`
}

SinopiaExport is an entry of the export menu.

type SinopiaHost added in v0.16.86

type SinopiaHost struct {
	Docs  SinopiaDocs
	State *SinopiaState
	// Tab is the design tab of a chat (the holder of its claims); "" when it has none.
	Tab func(conv string) string
	// Package reads an installed app's package; nil when it cannot be read.
	Package func(id string) *Package
}

SinopiaHost is what the agent's tools need of the machine's Sinopia.

type SinopiaImport added in v0.16.86

type SinopiaImport struct {
	ID     string   `json:"id"`
	Title  string   `json:"title"`
	Accept []string `json:"accept,omitempty"`
	Tool   string   `json:"tool"`
}

SinopiaImport is an entry of the import menu: files of the kinds it accepts go to its tool.

type SinopiaKind added in v0.16.86

type SinopiaKind struct {
	ID    string `json:"id"`
	Title string `json:"title"`
	// Icon is a file of the package (an image or an SVG).
	Icon string `json:"icon,omitempty"`
	// Editor is the id of the view that edits a document of this type.
	Editor string `json:"editor"`
	// Schema is the package file that describes the format: a JSON Schema.
	Schema        string `json:"schema,omitempty"`
	SchemaVersion int    `json:"schemaVersion"`
	// Migrations name a JSON Patch file for each version before the current one, by the version it starts from.
	Migrations map[string]string `json:"migrations,omitempty"`
	// DataKey is the key of hl.storage.doc that holds the document; the host migrates the value under it when a document of
	// an older version is opened. It is required when there are migrations.
	DataKey string `json:"dataKey,omitempty"`
	// Guest is read so that it can be refused with its reason (not supported yet).
	Guest *SinopiaKindGuest `json:"guest,omitempty"`
}

SinopiaKind is a document type an app adds.

func (SinopiaKind) Migrate added in v0.16.86

func (k SinopiaKind) Migrate(p *Package, doc json.RawMessage, from int) (json.RawMessage, error)

Migrate brings a document of the type from a version to the current one: each step in turn, all or nothing.

type SinopiaKindGuest added in v0.16.86

type SinopiaKindGuest struct {
	Render string `json:"render"`
}

SinopiaKindGuest is the static render a guest sees.

type SinopiaPanel added in v0.16.86

type SinopiaPanel struct {
	ID    string   `json:"id"`
	View  string   `json:"view"`
	Title string   `json:"title,omitempty"`
	Kinds []string `json:"kinds,omitempty"`
}

SinopiaPanel is a view of the app shown to the right of the editor of the documents of the kinds.

type SinopiaSelection added in v0.16.86

type SinopiaSelection struct {
	ID    string   `json:"id"`
	Title string   `json:"title"`
	Tool  string   `json:"tool,omitempty"`
	Agent string   `json:"agent,omitempty"`
	Kinds []string `json:"kinds,omitempty"`
}

SinopiaSelection is an item of the menu of a selection: it calls a tool of the app or sends a task to the chat linked to the document, with the selection as an <annotation>.

type SinopiaState added in v0.16.86

type SinopiaState struct {
	Now func() time.Time
	// contains filtered or unexported fields
}

SinopiaState is what the machine keeps of the open documents: the selection the page last reported, the marks, and which document each chat's editor shows. It is in memory: a restart empties it, and the page reports again.

func NewSinopiaState added in v0.16.86

func NewSinopiaState() *SinopiaState

NewSinopiaState is an empty state.

func (*SinopiaState) AddMarks added in v0.16.86

func (s *SinopiaState) AddMarks(project, source string, replace bool, marks []Mark)

AddMarks puts marks on a document; replace takes the earlier marks of the same source away first. Marks past the limits of a source and of a document are dropped.

func (*SinopiaState) ClaimCheck added in v0.16.86

func (s *SinopiaState) ClaimCheck(project string, rev int64) bool

ClaimCheck says a save check for a revision should run now: false when it already ran for it or runs.

func (*SinopiaState) DocumentOf added in v0.16.86

func (s *SinopiaState) DocumentOf(conv string) (project, kind string, ok bool)

DocumentOf is the document and kind a chat's editor shows; false when it shows none.

func (*SinopiaState) DoneCheck added in v0.16.86

func (s *SinopiaState) DoneCheck(project string, rev int64)

DoneCheck ends a save check; rev is the revision it looked at.

func (*SinopiaState) Marks added in v0.16.86

func (s *SinopiaState) Marks(project string) []Mark

Marks are the marks of a document, in the order they were put.

func (*SinopiaState) Open added in v0.16.86

func (s *SinopiaState) Open(conv, project, kind string)

Open says the editor of a chat shows a document; the agent's calls find the document by it.

func (*SinopiaState) Results added in v0.16.86

func (s *SinopiaState) Results(project string) []CheckResult

Results are the last results of the checks of a document.

func (*SinopiaState) Selection added in v0.16.86

func (s *SinopiaState) Selection(project string) []SelectedNode

Selection is the nodes last picked in a document.

func (*SinopiaState) SetResults added in v0.16.86

func (s *SinopiaState) SetResults(project string, results []CheckResult)

SetResults keeps the last run of the checks of a document: results of the same app and check replace the earlier.

func (*SinopiaState) SetSelection added in v0.16.86

func (s *SinopiaState) SetSelection(project string, nodes []SelectedNode)

SetSelection keeps what the page reports as picked (an empty list clears it).

type Snapshot

type Snapshot struct {
	Apps      []SnapshotApp `json:"apps"`
	Protected []string      `json:"protected"`
}

Snapshot is the tool policy a chat's launch was given: its apps' rules as they were at the launch, and the folders the agent must not write (the registry and the apps' packages), so editing a manifest or turning an app off from inside the chat does not loosen the rules of the agent that runs. The launch writes it next to its settings and the guard reads it there: the hook decides alone, with nothing to wait for.

func (Snapshot) CodexAnswer added in v0.16.154

func (s Snapshot) CodexAnswer(raw []byte) []byte

CodexAnswer is what the guard writes to Codex for one PreToolUse input: nil lets the call go on to Codex's own permissions, anything else is a refusal.

func (Snapshot) Decide

func (s Snapshot) Decide(call Call) (Verdict, string)

Decide is the snapshot's verdict for one call, with the reason the agent reads.

func (Snapshot) HasValidators added in v0.16.154

func (s Snapshot) HasValidators() bool

HasValidators says whether any app of the snapshot has a validator.

type SnapshotApp

type SnapshotApp struct {
	ID    string      `json:"id"`
	Name  string      `json:"name"`
	Tools *ToolPolicy `json:"tools,omitempty"`
	// Context are the items the context hook sends (context.go).
	Context []ContextItem `json:"context,omitempty"`
	// Dir and Validators are the package folder and the checks of the turn the validate hook runs (validate.go).
	Dir        string      `json:"dir,omitempty"`
	Validators []Validator `json:"validators,omitempty"`
}

SnapshotApp is one app of a snapshot.

type SnapshotEntry added in v0.16.86

type SnapshotEntry struct {
	CatalogEntry
	Archive         []byte `json:"archive,omitempty"`
	PreviousArchive []byte `json:"previousArchive,omitempty"`
}

SnapshotEntry is a catalog entry on the wire.

type SnapshotInstall added in v0.16.86

type SnapshotInstall struct {
	ID      string `json:"id"`
	Channel string `json:"channel"`
	// Version and Sum pin the package the owner installed; the machine installs exactly that, never the catalog's head.
	Version string `json:"version"`
	Sum     string `json:"sum"`
	// Archive is the pinned version's bytes (the catalog may have moved on from it).
	Archive []byte `json:"archive,omitempty"`
	By      string `json:"by"`
	At      int64  `json:"at"`
}

SnapshotInstall says that the team has an app on a channel installed.

type Storage added in v0.16.86

type Storage struct {
	Root string
	// contains filtered or unexported fields
}

Storage is the machine's app storage.

func OpenStorage added in v0.16.86

func OpenStorage(dataDir string) *Storage

OpenStorage is the process's one Storage of a data folder.

func (*Storage) Delete added in v0.16.86

func (s *Storage) Delete(app string, scope Scope, owner, key string) error

Delete removes a key; a key that is not there is not an error. The key's version goes up by one and is kept.

func (*Storage) Get added in v0.16.86

func (s *Storage) Get(app string, scope Scope, owner, key string) (value json.RawMessage, ok bool, err error)

Get is the value under a key; ok is false when there is none.

func (*Storage) GetVersioned added in v0.16.154

func (s *Storage) GetVersioned(app string, scope Scope, owner, key string) (value json.RawMessage, version int64, ok bool, err error)

GetVersioned is Get with the key's version (0 for data kept before versions, or a key never written).

func (*Storage) Keys added in v0.16.86

func (s *Storage) Keys(app string, scope Scope, owner string) ([]string, error)

Keys lists an area's keys, sorted.

func (*Storage) OnChange added in v0.16.154

func (s *Storage) OnChange(fn func(Change)) (cancel func())

OnChange calls fn for every key written or deleted from now on, whoever wrote it (a view, an agent's host tool, the install's settings form). fn runs on the writer's goroutine after the write is on disk and must not block. It returns the function that stops the calls.

func (*Storage) SaveSettings added in v0.16.154

func (s *Storage) SaveSettings(m *Manifest, app string, values map[string]any) (map[string]string, error)

SaveSettings keeps values (all of the app's settings, as the form sends them) once they pass CheckSettings. The returned problems are by key; the error is the storage's.

func (*Storage) Set added in v0.16.86

func (s *Storage) Set(app string, scope Scope, owner, key string, value json.RawMessage) error

Set stores a value; a write that takes the area past its limit is refused whole.

func (*Storage) SetIf added in v0.16.154

func (s *Storage) SetIf(app string, scope Scope, owner, key string, value json.RawMessage, ifVersion *int64) (int64, error)

SetIf stores a value and answers the key's new version. With ifVersion the write is made only if the key is at that version (0 is a key never written or kept before versions): otherwise it is refused with a *ConflictError and nothing changes.

func (*Storage) SetMany added in v0.16.86

func (s *Storage) SetMany(app string, scope Scope, owner string, values map[string]json.RawMessage) error

SetMany stores several keys of one area in a single write: all of them or, when the area would pass its limit, none.

func (*Storage) Settings added in v0.16.154

func (s *Storage) Settings(m *Manifest, app string) (map[string]any, error)

Settings are the app's settings values: what the person saved, over the schema's defaults. Keys the schema no longer describes are dropped, so an update that removes a setting does not leave it for the app to read.

type SyncOptions added in v0.16.86

type SyncOptions struct {
	HostVersion string
	// Confirm applies the updates that wait for a word (a new major, new rights) of this app; "*" is every app.
	Confirm []string
}

SyncOptions say how to follow the channels.

type SyncResult added in v0.16.86

type SyncResult struct {
	ID   string `json:"id"`
	From string `json:"from"`
	To   string `json:"to"`
	// Applied: the install is now at To. Otherwise Reason says what waits for a person's word: "major", "permissions".
	Applied bool   `json:"applied"`
	Reason  string `json:"reason,omitempty"`
}

SyncResult is what following a channel did for one install.

type TeamInfo added in v0.16.86

type TeamInfo struct {
	Space string `json:"space"`
	Role  string `json:"role"`
	// Catalog is the catalog; Installed marks what the team has installed from it.
	Catalog []CatalogView `json:"catalog"`
	// Muted are the team's apps the person turned off for themselves.
	Muted []string `json:"muted"`
}

TeamInfo is the team as the page shows it.

type TeamInstall added in v0.16.86

type TeamInstall struct {
	ID      string `json:"id"`
	Channel string `json:"channel"`
	Version string `json:"version"`
	// Sum is the SHA-256 of the archive of Version: the exact package the owner approved.
	Sum      string    `json:"sum"`
	By       string    `json:"by"`
	At       int64     `json:"at"`
	Dir      string    `json:"dir"`
	Manifest *Manifest `json:"manifest"`
}

TeamInstall is an app an owner installed for the team: the catalog entry's channel, and the version it is at.

type TeamInstallOptions added in v0.16.86

type TeamInstallOptions struct {
	HostVersion string
	By          string
	Now         time.Time
}

TeamInstallOptions say how an owner installs for the team.

type TeamSnapshot added in v0.16.86

type TeamSnapshot struct {
	Space string `json:"space"`
	// Role is the person's: owner or member. "" with no Space takes the machine out of the team.
	Role string `json:"role"`
	At   int64  `json:"at"`
	// Catalog entries with their archives (the current version, and the previous one for a rollback).
	Catalog  []SnapshotEntry   `json:"catalog"`
	Installs []SnapshotInstall `json:"installs"`
}

TeamSnapshot is what the platform sends a machine: the team, the person's role in it and the catalog with the archives of its entries, and the installs by app and channel.

func (TeamSnapshot) Validate added in v0.16.86

func (s TeamSnapshot) Validate() error

Validate refuses a snapshot this machine must not act on.

type ToolCall added in v0.16.86

type ToolCall struct {
	Name string          `json:"name"`
	Args json.RawMessage `json:"args,omitempty"`
}

ToolCall is a tool the agent called, by the name evals use (see ToolName).

type ToolPolicy

type ToolPolicy struct {
	Allow   []string `json:"allow,omitempty"`
	Deny    []string `json:"deny,omitempty"`
	Confirm []string `json:"confirm,omitempty"`
}

ToolPolicy is checked deny → confirm → allow.

type Transcript added in v0.16.86

type Transcript struct {
	Calls     []ToolCall `json:"calls"`
	FinalText string     `json:"finalText"`
	// InputTokens and OutputTokens add up what the run read and wrote, the cache's included in the input.
	InputTokens  int `json:"inputTokens"`
	OutputTokens int `json:"outputTokens"`
	// MCPServers are the servers Claude Code reports in the first event of a stream (name, status), when it did.
	MCPServers []MCPStatus `json:"mcpServers,omitempty"`
	// contains filtered or unexported fields
}

Transcript is what a run left: the calls, the agent's last words and what it cost.

func ParseTranscript added in v0.16.86

func ParseTranscript(raw []byte) (Transcript, error)

ParseTranscript reads the JSONL a Claude Code session leaves (a transcript file, or the stream of `claude -p --output-format stream-json`): the tool calls of the assistant's messages in order, the text of its last message that has any (or the stream's `result`), and the tokens of the messages' usage. Lines that are not JSON, and kinds it does not know, are skipped: the format is Claude Code's and grows.

type Validator added in v0.16.154

type Validator struct {
	ID         string `json:"id"`
	On         string `json:"on"`
	Match      string `json:"match,omitempty"`
	Run        string `json:"run"`
	MaxRetries int    `json:"maxRetries,omitempty"`
}

Validator is a check of the agent's turn (validate.go): a script of the package that runs on PostToolUse or Stop.

func ValidatorsOf added in v0.16.154

func ValidatorsOf(m *Manifest) []Validator

ValidatorsOf are the app's validators with the default retries filled in.

func (Validator) Applies added in v0.16.154

func (v Validator) Applies(event, appID, tool string, input map[string]any) bool

Applies says whether a validator runs for the event; tool is the call's tool name and input its arguments (PostToolUse).

type ValidatorResult added in v0.16.154

type ValidatorResult struct {
	// Failed is true on exit code 2; Remark is then what the script said, for the agent.
	Failed bool
	Remark string
	// Err is a script that did not work (cannot start, timeout, another exit code): nothing is blocked.
	Err error
}

ValidatorResult is how one run of a script ended.

func RunValidator added in v0.16.154

func RunValidator(ctx context.Context, appDir string, v Validator, input []byte) ValidatorResult

RunValidator runs the script of v from the app's folder with the hook's input on stdin.

type Verdict

type Verdict struct {
	Decision Decision
	App      string
	Rule     string
}

Verdict is the decision with the app and the rule that made it, for the reason the agent reads.

func Decide

func Decide(apps []*Manifest, call Call) Verdict

Decide is the verdict of the apps on in a chat for one call.

func (Verdict) Reason

func (v Verdict) Reason(appName string) string

Reason is the verdict in words for the agent.

type View

type View struct {
	ID      string   `json:"id"`
	Title   string   `json:"title,omitempty"`
	Entry   string   `json:"entry"`
	Targets []string `json:"targets"`
	Height  string   `json:"height,omitempty"`
	// Label, Icon, Order and Objects are for the slots: the name on the settings entry, the step or the button (Title when
	// empty), a name from the icon set, the place among its neighbours, and the kinds of object an object-action view is
	// shown at (machine, chat; every kind when empty).
	Label   string   `json:"label,omitempty"`
	Icon    string   `json:"icon,omitempty"`
	Order   int      `json:"order,omitempty"`
	Objects []string `json:"objects,omitempty"`
}

View is a page of the app: a tab, a full screen, a card in the chat or a Sinopia panel.

type ViewServer added in v0.16.86

type ViewServer struct {

	// Widgets are the agents' own widgets (WidgetsApp), served under a session for their chat; nil serves none.
	Widgets *Widgets
	// Sessions are the mounted views; the page issues one per view it shows.
	Sessions *ViewSessions
	// contains filtered or unexported fields
}

ViewServer serves the views of the installed apps on a loopback port, started on first use. Every request but the SDK's carries the token of a view session (/<token>/<app>/<file>) and the session's app must be the path's.

func NewViewServer added in v0.16.86

func NewViewServer(reg *Registry) *ViewServer

NewViewServer is the view server of a registry.

func (*ViewServer) Close added in v0.16.86

func (s *ViewServer) Close()

Close stops the server.

func (*ViewServer) EnsureServer added in v0.16.86

func (s *ViewServer) EnsureServer() (int, error)

EnsureServer starts the server on first use and returns its port.

func (*ViewServer) Handler added in v0.16.86

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

Handler answers the views' requests.

func (*ViewServer) Port added in v0.16.86

func (s *ViewServer) Port() int

Port is the port once the server is up, 0 before.

type ViewSessions added in v0.16.86

type ViewSessions struct {
	Now func() time.Time
	// contains filtered or unexported fields
}

ViewSessions are the live sessions of a machine.

func NewViewSessions added in v0.16.86

func NewViewSessions() *ViewSessions

NewViewSessions is an empty set of sessions.

func (*ViewSessions) Get added in v0.16.86

func (s *ViewSessions) Get(token string) (Session, bool)

Get is the live session of a token, renewed by the use.

func (*ViewSessions) Issue added in v0.16.86

func (s *ViewSessions) Issue(app, view, target, conversation string) (Session, error)

Issue starts a session for a view and returns its unguessable token.

func (*ViewSessions) IssueIn added in v0.16.86

func (s *ViewSessions) IssueIn(app, view, target, conversation, document string) (Session, error)

IssueIn is Issue for a view shown in a Sinopia document.

func (*ViewSessions) Renew added in v0.16.86

func (s *ViewSessions) Renew(token string) (time.Duration, bool)

Renew keeps a live session for a view that is still mounted but unused, and says how long it now lives at least (the idle time, or what is left of the longest time). An expired or unknown token is refused; the session's app, view, target and chat are not touched.

type Widget added in v0.16.154

type Widget struct {
	ID    string `json:"id"`
	Kind  string `json:"kind"`
	App   string `json:"app"`
	View  string `json:"view,omitempty"`
	Title string `json:"title,omitempty"`
	// Data is what the view reads as hl.context.data; null when none was given.
	Data      json.RawMessage `json:"data"`
	Rev       int             `json:"rev"`
	CreatedAt int64           `json:"createdAt"`
	UpdatedAt int64           `json:"updatedAt"`
}

Widget is a widget as the page lists it.

type WidgetInput added in v0.16.154

type WidgetInput struct {
	ID    string
	Kind  string
	App   string
	View  string
	Title string
	Data  json.RawMessage
	// The files of a kind "html" widget: the body's markup, its stylesheet and its classic script.
	HTML, Style, Script string
}

WidgetInput is a widget to show or change. An empty ID makes a new one.

type Widgets added in v0.16.154

type Widgets struct {
	Root string
	Now  func() time.Time
	// contains filtered or unexported fields
}

Widgets is the widgets of the machine's chats.

func OpenWidgets added in v0.16.154

func OpenWidgets(dataDir string) *Widgets

OpenWidgets is the process's one Widgets of a data folder.

func (*Widgets) Get added in v0.16.154

func (w *Widgets) Get(conv, id string) (Widget, error)

Get is one widget of a chat.

func (*Widgets) List added in v0.16.154

func (w *Widgets) List(conv string) ([]Widget, error)

List is the widgets of a chat, oldest first.

func (*Widgets) Remove added in v0.16.154

func (w *Widgets) Remove(conv, id string) error

Remove takes a widget out of the chat.

func (*Widgets) Show added in v0.16.154

func (w *Widgets) Show(conv string, in WidgetInput) (Widget, error)

Show puts a widget into the chat, or changes the one with the same id where it stands: its data, title and (for kind "html") files are replaced and its revision goes up. A widget keeps its app, view and kind; the same id given to another is refused.

func (*Widgets) WidgetFile added in v0.16.154

func (w *Widgets) WidgetFile(conv, id, name, nonce string) (body []byte, contentType string, ok bool)

WidgetFile is a file the view server serves for a kind "html" widget: the page it builds around the widget's markup, its stylesheet, its script and its data as a script that sets window.widgetData. ok is false for any other name.

Jump to

Keyboard shortcuts

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