apps

package
v0.16.187 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2026 License: Apache-2.0 Imports: 52 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 (
	AIPromptMax     = 20000 // characters
	AISystemMax     = 4000
	AIMaxTokens     = 8192
	AIDefaultTokens = 1024
)

The bounds of a call.

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 (
	// MaxListed is how many entries of one folder a listing gives.
	MaxListed = 1000
	// MaxSearchHits is how many lines a search gives at most.
	MaxSearchHits = 500
)
View Source
const (
	DefaultGuestTTL = 7 * 24 * time.Hour
	MaxGuestTTL     = 30 * 24 * time.Hour
)

Limits of a link's life.

View Source
const (
	HookReasonMax  = 1000
	HookContextMax = 4000
)

HookReasonMax bounds what a view says about a stop, and HookContextMax what it adds for the agent.

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 (
	// PageToolsTTL is how long a report holds without being renewed: the page renews it every few seconds while the view
	// is up, so a closed view's tools are gone soon after.
	PageToolsTTL = 15 * time.Second
	// PageCallTTL is how long a call waits for the view's answer.
	PageCallTTL         = 60 * time.Second
	MaxPageTools        = 32
	MaxPageToolSchema   = 16 << 10
	MaxPageToolArgs     = 64 << 10
	MaxPageToolResult   = 256 << 10
	MaxPageContext      = 64 << 10
	MaxPageCallsPerChat = 8
)
View Source
const (
	// RefuseTrust: the app is of the trusted tier (it runs code on the machine), which a catalog never installs.
	RefuseTrust = "trust"
	// RefuseHost: this harnessly is outside the range the app wants; Detail is the range.
	RefuseHost = "host"
	// RefuseName: another installed app has the same plugin name; Detail names it.
	RefuseName = "name"
	// RefuseCommand: another installed app takes the same slash command; Detail is the command and the app.
	RefuseCommand = "command"
	// RefuseKind: another installed app adds the same document type; Detail is the type and the app.
	RefuseKind = "kind"
)

Kinds of refusal.

View Source
const (
	// MaxAppTerminals is how many terminals an app keeps open in a chat; MaxTerminals how many all apps keep.
	MaxAppTerminals = 4
	MaxTerminals    = 16
	// MaxTerminalCols and MaxTerminalRows bound a terminal's size.
	MaxTerminalCols = 1000
	MaxTerminalRows = 500
)
View Source
const (
	ReviewApproved = "approved"
	ReviewPending  = "pending"
)

Review states of a public entry.

View Source
const (
	// DefaultRunTimeout is how long a command runs when the app names no time; MaxRunTimeout is the most it may name.
	DefaultRunTimeout = 2 * time.Minute
	MaxRunTimeout     = 10 * time.Minute
	// MaxRunOutput is how much of a command's output (stdout and stderr together) an answer holds.
	MaxRunOutput = 1 << 20
	// MaxCommand is the longest command an app may pass.
	MaxCommand = 4096
	// RunCPUSeconds is the processor time a command, or a process, may use (RLIMIT_CPU in sandbox-exec).
	RunCPUSeconds = 1800
	// MaxAppProcesses is how many processes an app keeps running in a chat; MaxProcesses on the machine.
	MaxAppProcesses = 4
	MaxProcesses    = 24

	// SandboxCPUEnv carries the processor limit to sandbox-exec, which sets it on itself and drops the variable.
	SandboxCPUEnv = "HARNESSLY_SANDBOX_CPU"
)
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 (
	MaxUSDPerDay      = 5.0
	MaxRunsPerDay     = 20
	DefaultUSDPerDay  = 0.5
	DefaultRunsPerDay = 3
)

The host's caps and the budget of an app that says none.

View Source
const (
	StateReady    = "ready"
	StateWaiting  = "waiting"
	StateFailed   = "failed"
	StateDisabled = "disabled"
)

The state of an installed app with its reason: the person sees why an app does nothing, not only that it is installed.

View Source
const (
	ReasonOff        = "off"        // the person or the environment turned it off
	ReasonSafe       = "safe"       // safe mode is on: the app does not start in new chats
	ReasonSecret     = "secret"     // a required secret has no value; Detail names them
	ReasonConnection = "connection" // a connection its servers need is not made or not signed in; Detail names them
	ReasonHost       = "host"       // this harnessly is outside the range the app wants; Detail is the range
	ReasonPackage    = "package"    // its installed copy cannot be read; Detail says why
	ReasonConsent    = "consent"    // it waits for the person to agree to what it reaches (consent.go)
)

Reasons of a state other than ready.

View Source
const (
	ClassCritical = "critical"
	ClassHigh     = "high"
	ClassMedium   = "medium"
	ClassLow      = "low"
)

The classes of risk, from the most dangerous; the install screen lists them in this order.

View Source
const (
	SurfaceTSPath        = "web/app/next/features/app-views/surface.gen.ts"
	SurfaceReferencePath = "docs/apps/reference.md"
	SurfaceSchemaPath    = "docs/apps/app.schema.json"
)

The files written from the surface (surface.go), by `UPDATE_SURFACE=1 go test ./internal/apps -run TestSurfaceFilesAreCurrent`. Paths are from the repository's root.

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 AgentAfter = 30 * time.Second

AgentAfter is how long after a view answers the agent's call of its tool the view's loud calls still count as the agent's: the page asks the person about them, and the runtime runs them only with the person's yes.

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 DeliveryBuiltin = "builtin"

Delivery of a builtin app; an installed app is a package and names none.

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 HookTimeout = 5 * time.Second

HookTimeout is how long the views have to answer a call.

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 (
	// MaxFileWatches is how many views of the machine watch files at once.
	MaxFileWatches = 32
)
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 SinopiaApp = "harnessly.sinopia"

SinopiaApp is Sinopia, the builtin app (builtin/sinopia/harnessly/app.json) whose points the manifest's `sinopia` contributes to: sinopia.kind, sinopia.panel, sinopia.check and the rest. The targets sinopia.<kind> and sinopia.* are its aliases.

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 (
	// ErrSameVersionGrew: an update reaches more under the same version; a new right comes with a new version only.
	ErrSameVersionGrew = errors.New("apps: the package reaches more than the installed one under the same version; raise its version")
	// ErrNoConsentWaiting: nothing of the app waits for the person's word (or another version does).
	ErrNoConsentWaiting = errors.New("apps: nothing waits for consent")
	// ErrConsentChanged: the package reaches more than the install screen showed (it changed after it was drawn).
	ErrConsentChanged = errors.New("apps: the app reaches more than the install screen showed")
)
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 (
	// ErrPageToolArgs: a report or a call past the limits, or a tool of no valid name.
	ErrPageToolArgs = errors.New("apps: bad page tool")
	// ErrPageToolGone: no view of the app offers that tool now.
	ErrPageToolGone = errors.New("apps: the view that offers this tool is not open")
	// ErrPageCallBusy: too many calls of the chat wait for the page.
	ErrPageCallBusy = errors.New("apps: too many page calls waiting in this chat")
	// ErrPageCallGone: no such waiting call.
	ErrPageCallGone = errors.New("apps: no such page call")
	// ErrPageCallTimeout: the page did not answer in time (the view was closed, or the tool hung).
	ErrPageCallTimeout = errors.New("apps: the view did not answer")
)
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")
)

Classes are the classes from the most dangerous.

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 ErrOverBudget = errors.New("apps: over the app's budget of the day")

ErrOverBudget refuses a call that would go past the app's budget of the day.

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 ErrTooManyTerminals = &BridgeError{Code: CodeRateLimited, Message: "too many terminals open: close one first"}

ErrTooManyTerminals: the app (or all apps) holds as many terminals as it may.

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 EventKinds = []string{"turn", "tool", "message"}

EventKinds are what events:<kind> names: what happened in the chat, without its content.

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

Objects an object-action view can sit at.

View Source
var SDKProtocols = []int{1, 2}

SDKProtocols are the versions of the bridge's protocol the host speaks. A view names its own with harnessly/protocol after the handshake (1 when it names none); the host speaks every one listed, and a behavior that is new is the view's only when it asked for the version that brings it. 2: a refused call resolves to {error: 'denied' | 'unsupported' | 'failed', code, message} instead of rejecting.

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 AccessKeys

func AccessKeys(list []Access) []string

AccessKeys are the keys of a list.

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 CheckCommandMask

func CheckCommandMask(mask string) string

CheckCommandMask is "" for a good mask of terminal.run: a command where * stands for any run of characters.

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 ClassOfMethod

func ClassOfMethod(method string) string

ClassOfMethod is the class of what a bridge method does: its right's class, low for a method that needs none.

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 IsBuiltin

func IsBuiltin(id string) bool

IsBuiltin says whether an id is a builtin app's: no package takes it.

func IsSinopiaTarget

func IsSinopiaTarget(t string) bool

IsSinopiaTarget says whether a target is an alias of Sinopia's screen.

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 Loud

func Loud(class string) bool

Loud says whether a class is shown with its threat and journals what it does: high and critical.

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 Money

func Money(usd float64) string

Money writes an amount the way the install screen and the journal show it: $5, $0.50, $0.0006.

func OverBudget

func OverBudget(b Budget, spent, worst float64) error

OverBudget is the refusal of a call the day's budget cannot pay for: what is spent, and what the call may cost.

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 PermissionNames

func PermissionNames() []string

PermissionNames are the rights in the order the surface lists them.

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 RunDir

func RunDir(workspace, cwd string) (string, error)

RunDir is the folder a command runs in: the chat's folder, or a folder in it the app names.

func SDKFiles

func SDKFiles() map[string][]byte

SDKFiles are the files a view the app's own server hosts serves itself (delivery mode remote): the shim first in its page, then the SDK, by name.

func SafeAllows

func SafeAllows(a Installed) bool

SafeAllows says whether an install works in safe mode: only one the environment pins.

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 SurfaceFiles

func SurfaceFiles() map[string][]byte

SurfaceFiles are the generated files by path.

func SurfaceReference

func SurfaceReference() []byte

SurfaceReference is docs/apps/reference.md.

func SurfaceSchema

func SurfaceSchema() []byte

SurfaceSchema is a JSON Schema of app.json for editors: the fields of the manifest, the targets and the rights. The check (Manifest.Check) is still the judge; the schema only helps an author type the right names.

func SurfaceTS

func SurfaceTS() []byte

SurfaceTS is the page's table: the right of every bridge method, the rights, the targets and the contribution kinds.

func TargetCovers

func TargetCovers(listed, target string) bool

TargetCovers says whether a listed target (of an app or a view) covers the target asked for: the same one, or a wildcard alias of a builtin app's screen over it (sinopia.* over sinopia.slides).

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 AIAnswer

type AIAnswer struct {
	Text string  `json:"text"`
	USD  float64 `json:"usd"`
}

AIAnswer is the model's answer and what it cost.

func CompleteAI

func CompleteAI(ctx context.Context, run AIRun, q AIRequest, capUSD float64) (AIAnswer, error)

CompleteAI asks the model once, spending at most capUSD.

type AIRequest

type AIRequest struct {
	Prompt    string `json:"prompt"`
	System    string `json:"system,omitempty"`
	MaxTokens int    `json:"maxTokens,omitempty"`
	// Model is fast (the default) or smart.
	Model string `json:"model,omitempty"`
}

AIRequest is what a view asks of the model.

func (*AIRequest) Check

func (q *AIRequest) Check() error

Check fills the defaults and refuses what is out of bounds.

func (AIRequest) Worst

func (q AIRequest) Worst() float64

Worst is the most the call can cost.

type AIRun

type AIRun func(ctx context.Context, dir string, args, env []string, stdin string) ([]byte, error)

AIRun runs the model's program; tests put their own.

func RunClaude

func RunClaude(bin string) AIRun

RunClaude is AIRun over the claude program.

type Access

type Access struct {
	// Key names it for the consent: perm:<right>, secret:<name>, net:<host>, frame:<host>, server:<name>, part:<part>.
	Key string `json:"key"`
	// Code is how the manifest writes it; the screen shows it small, on hover.
	Code   string `json:"code"`
	Class  string `json:"class"`
	Label  Text   `json:"label"`
	Threat Text   `json:"threat,omitzero"`
}

Access is one thing an app reaches.

func AccessOf

func AccessOf(m *Manifest, pkg *Package) []Access

AccessOf is what the manifest (and its package, when it can be read) reaches, from the most dangerous; nil pkg leaves out the servers and the plugin parts.

func NewAccess

func NewAccess(next []Access, granted []string) []Access

NewAccess are the items of next whose keys granted lacks: what an update adds.

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 AliasDecl

type AliasDecl struct {
	Name string `json:"name"`
	Doc  string `json:"doc"`
}

AliasDecl is a target of the manifests that names the app's screen: a family (sinopia.<kind>) or a wildcard (sinopia.*). Contributions of such a manifest go into the app's points, scoped by what follows the prefix.

type AppState

type AppState struct {
	State  string `json:"state"`
	Reason string `json:"reason,omitempty"`
	Detail string `json:"detail,omitempty"`
}

AppState is an app's state as the page shows it.

func StateIn

func StateIn(a Installed, safe bool, host string, packageErr error, secrets, connections []string) AppState

StateIn is StateOf with safe mode: on, every app but a pinned one is disabled.

func StateOf

func StateOf(a Installed, host string, packageErr error, secrets, connections []string) AppState

StateOf is the state of an install: off first, then a copy that cannot be read, then what it waits for.

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,omitempty"`
	// Tools are a builtin app's (builtin.go): its backend runs in the runtime's process. Instructions is what the host's
	// tools server says of them to the agent.
	Tools        []BackendTool `json:"tools,omitempty"`
	Instructions string        `json:"instructions,omitempty"`
}

Backend is the app's own server.

type BackendTool

type BackendTool struct {
	Name        string          `json:"name"`
	Description string          `json:"description"`
	InputSchema json.RawMessage `json:"inputSchema"`
	// Call is the method of the app's code the tool runs (for Sinopia, a Document API method).
	Call string `json:"call"`
}

BackendTool is a tool of a builtin app's backend for the agent of a chat: the host's tools server offers it as it is written and the app's code in the runtime answers it.

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 Budget

type Budget struct {
	// USDPerDay is the most the model calls of `ai` cost in a day, in US dollars of the model's price.
	USDPerDay float64 `json:"usdPerDay,omitempty"`
	// RunsPerDay is how many chats `agents.run` starts in a day.
	RunsPerDay int `json:"runsPerDay,omitempty"`
}

Budget is what an app may spend a day.

func BudgetOf

func BudgetOf(m *Manifest) Budget

BudgetOf is the app's budget as the host keeps it: the manifest's, or the defaults, within the caps.

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 Catalog

type Catalog struct {
	Targets       []SurfaceTarget     `json:"targets"`
	Permissions   []SurfacePermission `json:"permissions"`
	Methods       []SurfaceMethod     `json:"methods"`
	Contributions []ContributionKind  `json:"contributions"`
	Tools         []SurfaceTool       `json:"tools"`
}

Catalog is the surface as `harnessly app catalog` and the agent's catalog tool give it.

func SurfaceCatalog

func SurfaceCatalog() Catalog

SurfaceCatalog is the whole surface: the host's own and what the builtin apps declare (their aliases, points and backend tools).

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"`
	// What a machine checks before it downloads the app: the harnessly it wants, the slash command and the
	// document types it takes, the secrets it needs. An entry made before these were kept has none, and is checked at
	// the install as before.
	Harnessly string   `json:"harnessly,omitempty"`
	Command   string   `json:"command,omitempty"`
	Kinds     []string `json:"kinds,omitempty"`
	Secrets   []string `json:"secrets,omitempty"`
	// Check is this machine's answer for the entry, made when the list is given; it is never stored.
	Check *Precheck `json:"check,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"`
	// Starters are lines an empty chat offers under its field; a click puts the text into the field, it sends nothing.
	Starters []Starter `json:"starters,omitempty"`
	// Buttons stand at the chat's field: each runs one of the app's commands or opens one of its views in the pane.
	Buttons []ChatButton `json:"buttons,omitempty"`
	// Links are the addresses the app shows a card for: a message with such a link gets the card under it.
	Links []LinkCard `json:"links,omitempty"`
	// Mentions is what «@» in the chat's field finds in the app: a tool of its own MCP server, asked with what is typed.
	Mentions *ChatMentions `json:"mentions,omitempty"`
}

Chat is what the app adds to the chat.

type ChatButton

type ChatButton struct {
	ID      string `json:"id"`
	Title   string `json:"title"`
	Icon    string `json:"icon,omitempty"`
	Command string `json:"command,omitempty"`
	View    string `json:"view,omitempty"`
}

ChatButton is a button of the app at the chat's field: Command (one of chat.commands) or View (a view with the pane target), one of the two.

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 ChatMentions

type ChatMentions struct {
	Title string `json:"title"`
	Tool  string `json:"tool"`
}

ChatMentions is the app's part of «@»: Tool (<server>.<tool> of its .mcp.json) is called with {"query": "<typed>"} and answers {"items": [{"label", "detail", "insert"}]}; the palette lists them under Title.

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 ConsentFrom

type ConsentFrom int

ConsentFrom is whose word an install carries.

const (
	// ConsentHost: the host installs on its own (its built-in apps, the organization's environment, an eval); what it
	// installs is not the person's to agree to, so it keeps what it reaches as before.
	ConsentHost ConsentFrom = iota
	// ConsentGiven: the person clicked «Установить» on the install screen, which listed everything the app reaches.
	ConsentGiven
	// ConsentAsk: nobody agreed yet (the CLI, a channel's sync): rights not agreed before wait for the person.
	ConsentAsk
)

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 Contribution

type Contribution struct {
	// App is the owner: the app's id.
	App string `json:"app"`
	// Kind is the kind of contribution (view, chat.command, sinopia.panel…).
	Kind string `json:"kind"`
	// ID names the contribution inside its app and kind.
	ID string `json:"id"`
	// Target is where it shows: a target of the surface (chat, pane, settings, sinopia.<kind>…).
	Target string `json:"target"`
	// Spec is the part of the manifest it was read from.
	Spec any `json:"spec,omitempty"`
	// Owner is the app whose point the record goes into (harnessly.sinopia for sinopia.panel); "" for the host's own.
	Owner string `json:"owner,omitempty"`
}

Contribution is one thing an app puts into the host.

func ContributionsOf

func ContributionsOf(m *Manifest) []Contribution

ContributionsOf are the records of one manifest.

type ContributionKind

type ContributionKind struct {
	Name string `json:"name"`
	Doc  string `json:"doc"`
	// Field is where the manifest declares it.
	Field string `json:"field"`
	// Targets are the targets it can show in.
	Targets []string `json:"targets"`
	// Owner is the app that declares the point (builtin.go); "" for a kind of the host's own.
	Owner string `json:"owner,omitempty"`
}

ContributionKind is a kind of contribution as the catalog gives it.

type Contributions

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

Contributions is the registry of a machine: the records of every app that is on (installed and not muted).

func NewContributions

func NewContributions(installed []Installed) *Contributions

NewContributions makes the registry of a list of installs.

func (*Contributions) All

func (c *Contributions) All() []Contribution

All are the records.

func (*Contributions) In

func (c *Contributions) In(target string) []Contribution

In are the records that show in a target; a record of sinopia.* shows in every sinopia.<kind>.

func (*Contributions) Of

func (c *Contributions) Of(kind string) []Contribution

Of are the records of a kind.

func (*Contributions) Without

func (c *Contributions) Without(app string) *Contributions

Without is the registry with every record of an app taken away at once.

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 FileChange

type FileChange struct {
	Session string   `json:"session"`
	Paths   []string `json:"paths"`
}

FileChange is a batch of changed files of one view's watch.

type FileEntry

type FileEntry struct {
	Path string `json:"path"`
	Dir  bool   `json:"dir,omitempty"`
	Size int64  `json:"size,omitempty"`
	// Modified is the time of the last change, in milliseconds.
	Modified int64 `json:"modified,omitempty"`
}

FileEntry is a file or a folder of the workspace an app may see.

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) List

func (s FileScope) List(dir string) ([]FileEntry, error)

List gives the entries of a folder of the workspace the app may see, folders first, by name.

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) Search

func (s FileScope) Search(text string, opt SearchOptions) ([]SearchHit, bool, error)

Search looks for text in the files the app may read; an empty text finds the files by Glob alone. It gives the hits and whether it stopped before the end (too many hits or files).

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 FileWatches

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

FileWatches are the watches of a machine's views.

func NewFileWatches

func NewFileWatches() *FileWatches

NewFileWatches is a machine with no watch.

func (*FileWatches) OnChange

func (fw *FileWatches) OnChange(fn func(FileChange)) (stop func())

OnChange hears every change of every watch until the returned stop.

func (*FileWatches) Start

func (fw *FileWatches) Start(token string, scope FileScope, alive func() bool) error

Start follows the files of scope for a session. alive is asked now and then; the watch ends when it says no (the session is gone). A second Start of the same session takes the place of the first.

func (*FileWatches) Stop

func (fw *FileWatches) Stop(token string)

Stop ends a session's watch; a session with none is no error.

func (*FileWatches) Watching

func (fw *FileWatches) Watching(token string) bool

Watching says whether a session watches.

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 GitCommit

type GitCommit struct {
	Hash    string `json:"hash"`
	Author  string `json:"author"`
	At      int64  `json:"at"`
	Subject string `json:"subject"`
}

GitCommit is a line of `git log`.

type GitDiffOptions

type GitDiffOptions struct {
	// Path is one file or folder of the chat's folder; "" is all of it.
	Path string
	// Staged: what is staged for the next commit; otherwise what is not staged yet.
	Staged bool
	// Ref is a commit to compare the folder with (HEAD~1, a hash); "" compares with the index.
	Ref string
}

GitDiffOptions narrow a diff.

type GitFile

type GitFile struct {
	Path string `json:"path"`
	// From is the old path of a renamed file.
	From string `json:"from,omitempty"`
	// Staged and Unstaged are the letters of git status (M, A, D, R, ?…), "" where nothing changed.
	Staged   string `json:"staged,omitempty"`
	Unstaged string `json:"unstaged,omitempty"`
}

GitFile is a changed file of `git status`.

type GitScope

type GitScope struct {
	Workspace string
	Forbidden []string
}

GitScope is the folder git reads in and the host's folders it never shows.

func (GitScope) Diff

func (g GitScope) Diff(ctx context.Context, opt GitDiffOptions) (diff string, cut bool, err error)

Diff is the unified diff of the workspace (or of a path in it), secrets left out; cut says it was too long.

func (GitScope) Log

func (g GitScope) Log(ctx context.Context, limit int, p string) ([]GitCommit, error)

Log is the last commits of the workspace (or of a path in it).

func (GitScope) Status

func (g GitScope) Status(ctx context.Context) (GitStatus, error)

Status is `git status` of the workspace.

type GitStatus

type GitStatus struct {
	Branch string    `json:"branch"`
	Ahead  int       `json:"ahead,omitempty"`
	Behind int       `json:"behind,omitempty"`
	Files  []GitFile `json:"files"`
	// Cut: there were more files than an answer holds.
	Cut bool `json:"cut,omitempty"`
}

GitStatus is the branch and the changed files of the chat's folder.

type Grant

type Grant struct {
	Keys []string `json:"keys"`
	At   int64    `json:"at"`
}

Grant is what the person agreed to.

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 HookAsk

type HookAsk struct {
	App, Name string
	Strict    bool
	// Live: a view of the app heard the call (it may still have said nothing in time).
	Live bool
	Word *HookWord
}

HookAsk is one app asked about a call: its word, or none (Word nil) when it did not answer in time or had no view.

type HookVerdict

type HookVerdict struct {
	Deny bool `json:"deny,omitempty"`
	// App and Name are the app that stopped the call; Reason is why, in its words.
	App    string `json:"app,omitempty"`
	Name   string `json:"name,omitempty"`
	Reason string `json:"reason,omitempty"`
	// Context is what the apps add for the agent, each under its name.
	Context string `json:"context,omitempty"`
	// Silent are the apps whose view heard the call and said nothing in time: the journal gets a line for each.
	Silent []string `json:"-"`
}

HookVerdict is the apps' words put together.

func MergeHooks

func MergeHooks(asks []HookAsk) HookVerdict

MergeHooks puts the apps' words together: the first stop (in the order asked) wins, contexts add up, and a strict app that did not answer stops the call.

type HookWord

type HookWord struct {
	// Decision is "deny" to stop the call; anything else lets it through.
	Decision string `json:"decision,omitempty"`
	Reason   string `json:"reason,omitempty"`
	Context  string `json:"context,omitempty"`
}

HookWord is what a view answers about the agent's call.

func ParseHookWord

func ParseHookWord(raw json.RawMessage) (*HookWord, error)

ParseHookWord reads a view's answer; one it cannot read lets the call through, as a silence would.

type HostTools added in v0.16.86

type HostTools struct {
	Conv     string
	Registry *Registry
	Storage  *Storage
	Asks     *Asks
	// Pages are the tools and the context the chat's open views offer (pagetools.go); nil refuses page_tools and page_call.
	Pages *PageTools
	// 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
	// Consent is whose word the install carries (consent.go): the host's own (ConsentHost, the zero value), the person's
	// click in the page (ConsentGiven) or none (ConsentAsk: a CLI or a channel, which an agent can drive).
	Consent ConsentFrom
	// Granted are the keys the install screen listed, with ConsentGiven; nil grants all the package reaches.
	Granted []string
}

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"`
	// Wants are the keys of what the install reaches (AccessOf), fixed at install so the list reads no package.
	Wants []string `json:"wants,omitempty"`
	// Grant is what the person agreed to (consent.go); nil is an install made before consent was asked, which keeps
	// what it had.
	Grant *Grant `json:"grant,omitempty"`
	// Pending is a newer version that reaches more and waits for the person's word; the install runs as it was.
	Pending *Installed `json:"pending,omitempty"`
	// Off: the person turned the app off (the switch of its card); it starts nowhere until it is turned on.
	Off bool `json:"off,omitempty"`
}

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.

func (Installed) NeedsConsent

func (a Installed) NeedsConsent() bool

NeedsConsent: the install reaches what the person did not agree to, so it is kept off.

func (Installed) WaitsConsent

func (a Installed) WaitsConsent() bool

WaitsConsent: the install or a newer version of it waits for the person's word.

type JournalEntry

type JournalEntry struct {
	At int64 `json:"at"`
	// What is the method of the bridge or the event: consent, consent.waits, declined, off, on, secret.launch, …
	What  string `json:"what"`
	Class string `json:"class"`
	// Detail is a short note: the version, a file's path, a secret's name.
	Detail string `json:"detail,omitempty"`
	// Chat is the conversation it happened in, when there is one.
	Chat string `json:"chat,omitempty"`
	OK   bool   `json:"ok"`
}

JournalEntry is one line.

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
	// CLIHeader is the request header the runtime takes the CLI's token in; the agent's CLI and the hooks get it, since
	// the guard runs the CLI by its path, past the pane's wrapper that names it. "" leaves the CLI's default.
	CLIHeader string
	// 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) Active

func (l *Launcher) Active(ids []string) []string

Active are the apps of a launch that are installed and on now; in safe mode only the pinned ones. A chat whose app was removed starts without it instead of not starting.

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 LinkCard

type LinkCard struct {
	Match string `json:"match"`
	Card  string `json:"card"`
}

LinkCard is a kind of address the app shows a card for. Match is https://<host>/<path> where the host may start with "*." and the path may end with "*"; Card is one of chat.cards, given the link as its data ({url}).

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"`
	// Budget is what the app may spend a day through `ai` and `agents.run` (spend.go).
	Budget *Budget `json:"budget,omitempty"`
	// Delivery, Points and Aliases are the host's own apps' (builtin.go): an installed app is a package and has none.
	Delivery string      `json:"delivery,omitempty"`
	Points   []PointDecl `json:"points,omitempty"`
	Aliases  []AliasDecl `json:"aliases,omitempty"`
}

Manifest is harnessly/app.json.

func Builtins

func Builtins() []*Manifest

Builtins are the host's own apps, by id.

func PageApp

func PageApp(id string, enabled []string, reg *Registry) *Manifest

PageApp is the manifest of an app whose page may offer tools and context in a chat: a builtin app's (Sinopia runs in the host's page wherever a document is open, and is on in no chat's list), or an installed app on in the chat. nil for any other.

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. A right with a value (files.read:docs/*, events:turn) is held when the app lists any value of it; which paths or kinds it reaches is for the call's own check.

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) EventKindsOf

func (m *Manifest) EventKindsOf() []string

EventKindsOf are the kinds of events:<kind> the app holds.

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) RemoteView

func (m *Manifest) RemoteView(viewID string) (string, bool)

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. RemoteView is the address of a view the app's own server hosts (delivery mode remote): an https entry whose host network.frames lists. A package view, or an address the manifest does not let be framed, is not one.

func (*Manifest) RunRightsOf

func (m *Manifest) RunRightsOf(right string) RunRights

RunRightsOf is what the app's right (terminal.run or process) lets it run.

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)

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 PageAnswer

type PageAnswer struct {
	Result json.RawMessage `json:"result,omitempty"`
	Error  string          `json:"error,omitempty"`
}

PageAnswer is the view's answer: a result, or an error in words.

type PageCall

type PageCall struct {
	ID        string          `json:"id"`
	App       string          `json:"app"`
	Tool      string          `json:"tool"`
	Arguments json.RawMessage `json:"arguments"`
	// Hook: not a tool of the view but the agent's tool call, for the view's hook to stop or let through.
	Hook bool `json:"hook,omitempty"`
}

PageCall is a call the page takes to the view.

type PageReport

type PageReport struct {
	App     string          `json:"app"`
	Tools   []PageTool      `json:"tools"`
	Context json.RawMessage `json:"context,omitempty"`
	// Hooks: a view of the app hears the agent's tool calls before they run (hooks.agent).
	Hooks bool `json:"hooks,omitempty"`
}

PageReport is what the page reports for one app of a chat.

func PageReportAllowed

func PageReportAllowed(m *Manifest, r PageReport) PageReport

PageReportAllowed keeps of a report what the app may offer: tools need tools.page, the context context.publish.

type PageTool

type PageTool struct {
	Name        string          `json:"name"`
	Description string          `json:"description"`
	InputSchema json.RawMessage `json:"inputSchema,omitempty"`
	// Confirm: the page asks the person before it runs the tool; a refusal comes back as the call's error.
	Confirm bool `json:"confirm,omitempty"`
}

PageTool is a tool a view offers, as the view described it.

type PageTools

type PageTools struct {

	// Now and CallTTL are for tests.
	Now     func() time.Time
	CallTTL time.Duration
	// contains filtered or unexported fields
}

PageTools is the page tools of the machine, by chat and app.

func NewPageTools

func NewPageTools() *PageTools

func (*PageTools) Answer

func (p *PageTools) Answer(conv, id string, a PageAnswer) error

Answer brings a view's answer to the call that waits for it; conv must be the call's chat.

func (*PageTools) Call

func (p *PageTools) Call(ctx context.Context, conv, app, tool string, args json.RawMessage) (PageAnswer, error)

Call puts a call to a view's tool and waits for its answer, the context's end or PageCallTTL.

func (*PageTools) Driving

func (p *PageTools) Driving(conv, app string) bool

Driving says whether the agent of a chat is using an app's view: a call of the view's tool waits, or was answered less than AgentAfter ago.

func (*PageTools) Hook

func (p *PageTools) Hook(ctx context.Context, conv, app string, call json.RawMessage, ttl time.Duration) (PageAnswer, error)

Hook hands the agent's tool call to the view of the app that hears them and waits for its word, at most ttl. The view acts in the agent's turn while it decides, so its loud calls count as the agent's, as a tool call's do.

func (*PageTools) Hooked

func (p *PageTools) Hooked(conv, app string) bool

Hooked says whether a view of the app in the chat hears the agent's tool calls now.

func (*PageTools) Offered

func (p *PageTools) Offered(conv string) []PageReport

Offered is what the views of a chat offer now, by app.

func (*PageTools) Report

func (p *PageTools) Report(conv string, reports []PageReport) error

Report replaces what a chat's page offers for the apps it names; the caller has checked the apps are on in the chat and hold their rights (Allowed). An app the page shows no more is dropped when its report runs out (PageToolsTTL).

func (*PageTools) Take

func (p *PageTools) Take(conv string) []PageCall

Take hands the page the calls of a chat nobody took yet; each goes out once.

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 Point

type Point struct {
	PointDecl
	Owner string `json:"owner"`
}

Point is a declared point with its owner.

func AppPoints

func AppPoints() []Point

AppPoints are the points the builtin apps declare, in the order of the apps and their manifests.

type PointDecl

type PointDecl struct {
	// Name is <the app's short name>.<what>, such as sinopia.panel.
	Name string `json:"name"`
	Doc  string `json:"doc"`
	// Field is where a manifest declares contributions to the point (sinopia.panels[]).
	Field string `json:"field"`
}

PointDecl is a point an app declares: a place other apps put contributions in.

type Precheck

type Precheck struct {
	Refusals []Refusal `json:"refusals"`
	Secrets  []string  `json:"secrets"`
	// Access is what the entry says the app reaches, for the install screen. The package may reach more (its
	// network, servers, plugin parts): the install grants only these keys and the rest waits for consent.
	Access []Access `json:"access"`
}

Precheck is the answer for an entry: why it cannot be installed (none: it can), and the secrets the person will be asked for after the install.

func PrecheckEntry

func PrecheckEntry(e CatalogEntry, host string, installed []Installed) Precheck

PrecheckEntry checks an entry against this machine: the host's version and the apps installed here (the entry's own app, an update of it, is no conflict).

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 Process

type Process struct {
	ID        string `json:"id"`
	Command   string `json:"command"`
	StartedAt int64  `json:"startedAt"`
	Running   bool   `json:"running"`
	// Code is the exit code of a process that ended.
	Code *int `json:"code,omitempty"`
}

Process is a long command an app started.

type ProcessOutput

type ProcessOutput struct {
	Process
	Text string `json:"text"`
	Next int64  `json:"next"`
	Lost bool   `json:"lost,omitempty"`
}

ProcessOutput is a piece of a process's output: from offset From to Next; Lost says the start of the piece was dropped (the machine keeps the last 256 KiB).

type Processes

type Processes struct {

	// OnEnd hears a process that ended, for the journal.
	OnEnd func(app, chat string, p Process)
	// contains filtered or unexported fields
}

Processes are the processes the machine's apps started.

func NewProcesses

func NewProcesses() *Processes

NewProcesses is a machine with no process.

func (*Processes) List

func (ps *Processes) List(app, chat string) []Process

List is the processes of an app in a chat, the oldest first.

func (*Processes) Output

func (ps *Processes) Output(app, chat, id string, since int64) (ProcessOutput, error)

Output is the output of a process from offset since (0: what the machine keeps).

func (*Processes) Start

func (ps *Processes) Start(s *Sandbox, app, chat, dir, command string, argv []string, alive func() bool) (Process, error)

Start starts argv in dir inside the wall for an app in a chat. alive is asked every few seconds: the process is stopped when it says no (the app was turned off in the chat, switched off, or lost the right).

func (*Processes) Stop

func (ps *Processes) Stop(app, chat, id string) (Process, error)

Stop ends a process of the app in the chat and waits a moment for it; one that ended already is no error.

func (*Processes) StopApp

func (ps *Processes) StopApp(app, chat string)

StopApp ends every process of an app in a chat ("" chat: in every chat).

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
	// Consent is whose word the install carries (consent.go); with ConsentGiven, Granted are the keys the install screen
	// listed (nil: all the package reaches).
	Consent ConsentFrom
	Granted []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 Refusal

type Refusal struct {
	Code   string `json:"code"`
	Detail string `json:"detail,omitempty"`
}

Refusal is one reason an entry cannot be installed here.

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) ChargeAI

func (r *Registry) ChargeAI(ctx context.Context, id string, b Budget, run AIRun, q AIRequest, now func() time.Time) (AIAnswer, Spent, error)

ChargeAI reserves the call's worst price within the budget, makes the call and charges the day what it cost.

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) Consent

func (r *Registry) Consent(id, version string, shown []string, now time.Time) (Installed, error)

Consent is the person's word on what waits: version and shown are the version and the keys the install screen showed, so a click cannot agree to a version, or a package, that came after it was drawn. A pending update takes the place of the running version; a first install is turned on. What is granted is only what was shown (with what was granted before, for an update): a package that reaches more is refused with ErrConsentChanged.

func (*Registry) Contributions

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

Contributions is the registry of the apps installed on this machine.

func (*Registry) Decline

func (r *Registry) Decline(id string) (removed bool, err error)

Decline is the person's «Отмена»: a pending update is dropped and the running version stays; a first install that waited is removed.

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) HooksOff

func (r *Registry) HooksOff(id string) bool

HooksOff says whether the person turned off the app's hook.

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) Journal

func (r *Registry) Journal(id string, e JournalEntry) error

Journal adds a line to an app's journal; a journal that cannot be written loses the line, the action is not stopped for it.

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 that are not turned off and do not wait for their consent, 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 apps the person turned off (Muted, Off) and those that wait for their consent.

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) Precheck

func (r *Registry) Precheck(entries []*CatalogEntry, host string)

Precheck puts this machine's check into each entry the page is given: the team's catalog and the public one.

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) ReadJournal

func (r *Registry) ReadJournal(id string, n int) ([]JournalEntry, error)

ReadJournal is the last n lines of an app's journal, the newest first; none is an empty list.

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) ReserveUSD

func (r *Registry) ReserveUSD(id string, b Budget, most float64, now time.Time) (float64, error)

ReserveUSD sets aside up to `most` of the app's money for one call and answers how much: the call is made with that cap, and SettleUSD puts back what it did not spend. ErrOverBudget when nothing is left.

func (*Registry) ReturnRun

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

ReturnRun gives back a run that did not start a chat.

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) SafeMode

func (r *Registry) SafeMode() bool

SafeMode says whether safe mode is on.

func (*Registry) Sandbox

func (r *Registry) Sandbox(b *Boundary) (*Sandbox, error)

Sandbox is the wall an app's commands run in on this registry's machine: the registry and the packages read-only, the data folder sealed, the runtime's own credentials read as empty.

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) SetHooksOff

func (r *Registry) SetHooksOff(id string, off bool) error

SetHooksOff turns the app's hook off (or back on) on this machine: its views stop hearing the agent's calls.

func (*Registry) SetOff

func (r *Registry) SetOff(id string, off bool) error

SetOff is the switch of an app the person installed: off, it starts in no new chat and its views' calls are refused at once (they go through Get). A team's or the environment's app is turned off with MuteTeamApp.

func (*Registry) SetSafeMode

func (r *Registry) SetSafeMode(on bool) error

SetSafeMode turns safe mode on or off.

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) SettleUSD

func (r *Registry) SettleUSD(id string, reserved, cost float64, now time.Time) error

SettleUSD replaces a reservation with what the call cost.

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) SpentToday

func (r *Registry) SpentToday(id string, now time.Time) Spent

SpentToday is what the app spent today (UTC).

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) TakeRun

func (r *Registry) TakeRun(id string, b Budget, now time.Time) error

TakeRun counts one chat started by `agents.run`; ErrOverBudget when the day's runs are spent.

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 RunResult

type RunResult struct {
	Code     int    `json:"code"`
	Output   string `json:"output"`
	Cut      bool   `json:"cut,omitempty"`
	TimedOut bool   `json:"timedOut,omitempty"`
	Ms       int64  `json:"ms"`
}

RunResult is what a command did.

type RunRights

type RunRights struct {
	Any   bool
	Masks []string
}

RunRights is what an app may run: any command, or the ones its masks name.

func (RunRights) Argv

func (r RunRights) Argv(command string) ([]string, error)

Argv is what runs for a command: the shell for an app that may run any, the words of the command for one that holds a mask it matches. A refusal says why.

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 Sandbox

type Sandbox struct {
	Boundary *Boundary
	// Root is the folder the wall's probe runs in (the registry's).
	Root string
	// Protected are the folders bound read-only (the registry, the packages); Data the runtime's data folder (sealed);
	// Home the person's; Hidden the files that read as empty (the cli-token, the agents' key).
	Protected []string
	Data      string
	Home      string
	Hidden    []string
}

Sandbox is where an app's command runs: the agent's wall, around the chat's folder.

func (*Sandbox) Run

func (s *Sandbox) Run(ctx context.Context, dir string, argv []string, timeout time.Duration) (RunResult, error)

Run runs argv in dir inside the wall and waits for it, at most timeout (DefaultRunTimeout for 0).

func (*Sandbox) Shell

func (s *Sandbox) Shell(dir string, cols, rows int) (*Terminal, error)

Shell starts a shell on a terminal of cols×rows in dir.

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 SearchHit

type SearchHit struct {
	Path string `json:"path"`
	Line int    `json:"line,omitempty"`
	Text string `json:"text,omitempty"`
}

SearchHit is a line of a file that holds what was looked for; Line 0 is a file found by its name alone.

type SearchOptions

type SearchOptions struct {
	// Glob is a mask the files must match too (src/**/*.go); "" is every file the app may read.
	Glob string
	// Case: the text is matched as written; otherwise case is ignored.
	Case  bool
	Limit int
}

SearchOptions narrow a search.

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 Sinopia's backend needs of the machine.

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) CodexJudge

func (s Snapshot) CodexJudge(raw []byte) ([]byte, Verdict, string)

CodexJudge is CodexAnswer with the rule that refused the call and the call's tool, for the journal; the verdict is empty when no app's rule decided (a call that goes on, or one the guard cannot read).

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"`
	// Hooks: a view of the app hears the agent's calls (hooks.agent): the guard asks the runtime after the rules. Strict:
	// a call the app does not answer is stopped (hooks.strict).
	Hooks  bool `json:"hooks,omitempty"`
	Strict bool `json:"strict,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 Spent

type Spent struct {
	Day  string  `json:"day"`
	USD  float64 `json:"usd"`
	Runs int     `json:"runs"`
}

Spent is an app's spending of one day.

type Starter

type Starter struct {
	Text string `json:"text"`
}

Starter is a line an empty chat offers.

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 SurfaceMethod

type SurfaceMethod struct {
	Name string `json:"name"`
	// Permission is the right the method needs; "" needs none.
	Permission string `json:"permission"`
	// SDK is how a view calls it through @harnessly/app-sdk.
	SDK string `json:"sdk,omitempty"`
	Doc string `json:"doc"`
	// Deprecated names what to call instead. The method keeps working (the SDK only grows); the app's inspector
	// says it is deprecated and what replaces it.
	Deprecated string `json:"deprecated,omitempty"`
}

SurfaceMethod is a method of the host↔view bridge.

type SurfacePermission

type SurfacePermission struct {
	Name string `json:"name"`
	Doc  string `json:"doc"`
	// Param is what follows the right after ':' (files.read:<mask>); "" is a right written alone.
	Param string `json:"param,omitempty"`
	// Alone is the label of a right with a Param that may also be written without one (terminal.run: any command).
	Alone Text `json:"alone,omitzero"`
	// Unsupported: the host accepts the right in no call yet, so the check refuses it.
	Unsupported bool `json:"unsupported,omitempty"`
	// Class is how much the right lets an app do: it orders the install screen and says how loud it is, it
	// forbids nothing.
	Class string `json:"class"`
	// ParamClass is the class with a Param when it is not Class (secrets.write alone is the app's own keys, with a name
	// the person's shared one).
	ParamClass string `json:"paramClass,omitempty"`
	// Label is what the install screen says, in the person's words; {param} stands for what follows ':'.
	Label Text `json:"label"`
	// Threat is the second sentence of a high or critical right: what it can do to the person.
	Threat Text `json:"threat,omitzero"`
}

SurfacePermission is a right an app asks for in `permissions`.

type SurfaceTarget

type SurfaceTarget struct {
	Name string `json:"name"`
	Doc  string `json:"doc"`
	// Slot: a place of the interface filled by a view at a spot the page declares.
	Slot bool `json:"slot,omitempty"`
	// Pattern: the name stands for a family (sinopia.<kind>).
	Pattern bool `json:"pattern,omitempty"`
	// Owner is the builtin app whose screen the target names, as an alias (builtin.go); "" for the host's own.
	Owner string `json:"owner,omitempty"`
}

SurfaceTarget is a place an app works in.

type SurfaceTool

type SurfaceTool struct {
	Name string `json:"name"`
	Doc  string `json:"doc"`
	// Owner is the builtin app whose backend answers the tool; "" for the host's own.
	Owner string `json:"owner,omitempty"`
}

SurfaceTool is a host tool the agent of a chat with apps gets from the harnessly-app server.

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 Terminal

type Terminal struct {
	// Pty is the terminal's side the runtime reads and writes.
	Pty *os.File
	// contains filtered or unexported fields
}

Terminal is a shell started on its pty.

func (*Terminal) Close

func (t *Terminal) Close()

Close ends the shell and everything it started, and the pty.

func (*Terminal) Code

func (t *Terminal) Code() int

Code is how the shell ended: its exit code, -1 for a signal.

func (*Terminal) Done

func (t *Terminal) Done() <-chan struct{}

Done is closed when the shell has ended; Code is then how.

func (*Terminal) Resize

func (t *Terminal) Resize(cols, rows int) error

Resize sets the terminal's size.

type TerminalSlots

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

TerminalSlots counts the open terminals of the apps: each app in each chat, and all of them.

func (*TerminalSlots) Take

func (l *TerminalSlots) Take(app, chat string) (release func(), err error)

Take holds a place for a terminal of app in chat; release gives it back (once).

type Text

type Text struct {
	Ru string `json:"ru"`
	En string `json:"en"`
}

Text is a line in both languages of the page.

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