apps

package
v0.16.399 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: AGPL-3.0 Imports: 64 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"
	// CodeAuthRequired: the server wants the person signed in and nobody is (no token, no connection signed in). The
	// error's SignIn says where the person signs in.
	CodeAuthRequired = "auth_required"
	// CodeAuthExpired: the person was signed in and the server takes the sign-in no more (an expired or revoked token,
	// a refresh the identity provider refused). Signing in again mends it.
	CodeAuthExpired = "auth_expired"
	// CodeAuthDenied: the person is signed in and the server (or the identity provider) refuses them this: HTTP 403, an
	// insufficient scope, access_denied. Signing in again does not mend it; an admin of the server does.
	CodeAuthDenied = "auth_denied"
	// CodeIdPUnreachable: the identity provider (its token or discovery endpoint) did not answer, so no token could be
	// had. Nothing is wrong with the sign-in; the call may be repeated later.
	CodeIdPUnreachable = "idp_unreachable"
)

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 (
	CheckOK          = "ok"
	CheckFailed      = "failed"
	CheckWaiting     = "waiting"
	CheckOff         = "off"
	CheckUnreachable = "unreachable"
)

The states of a check.

View Source
const (
	AccessRead = "read"
	AccessAll  = "all"
)

The two levels of access to a connection.

View Source
const (
	KindUI      = "ui"
	KindRuntime = "runtime"
	KindTool    = "tool"
)

Extensions. An app is harnessly's one extension package; three kinds of thing are told apart so a person and a check can say what a package is:

  • ui an extension of the interface: it only fills slots (settings, onboarding, object-action, hub-settings, branding, home) with sandboxed views. No agent, no chat, no backend.
  • runtime an extension of the runtime: views in a pane or a screen of its own, chat cards and commands, Sinopia documents, a backend; it may carry an agent profile too.
  • tool a tool for the agent: instructions, skills, MCP servers, no view at all.

The Hub has its own extensions (internal/hub/ext, an address the Hub talks to); they are not apps and are not in this list. `kind` in the manifest is optional: it is worked out from what the package contains, and when it is written it has to agree with that.

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
	TargetHome         = "home"          // a block on the start page, under the field of a new chat
)

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 (
	WidgetSourceLimits    = "limits"
	WidgetSourceMachine   = "machine"
	WidgetSourceSubagents = "subagents"
)

The host's data a side widget may be given; the page reads each itself, the view gets only the ones it names.

View Source
const (
	WidgetRefreshMin     = 30
	WidgetRefreshMax     = 24 * 60 * 60
	WidgetSmartEveryMin  = 5
	WidgetSmartEveryMax  = 24 * 60
	WidgetSmartPromptMax = 2000
)

The bounds of a side widget.

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 (
	AuthRequiredMessage   = "the server wants a sign-in: sign in, then repeat the call"
	AuthExpiredMessage    = "the server no longer takes the sign-in: sign in again, then repeat the call"
	AuthDeniedMessage     = "the server refuses this to the signed-in person: ask its admin for access"
	IdPUnreachableMessage = "the sign-in service did not answer: try again later"
)

What a view is told of a refused sign-in. The server's own words stay in the log.

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 (
	// AuthPlatform: the host puts the platform's JWT for the person (apptoken) in Authorization.
	AuthPlatform = "platform"
	// AuthOIDC: the host puts the organization's identity provider's token for the server, got by token exchange.
	AuthOIDC = "oidc"
	// AuthOAuth: the person signs in to the server itself, the way a connection does (MCP authorization: discovery,
	// dynamic registration, PKCE); the host keeps the token in the safe and puts it in Authorization.
	AuthOAuth = "oauth"
	// AuthSecret: the headers carry ${secret:…} of the install, as without auth.
	AuthSecret = "secret"
)

The kinds of ServerAuth.

View Source
const (
	CommandQueued   = "queued"
	CommandSent     = "sent"
	CommandAcked    = "acked"
	CommandDone     = "done"
	CommandFailed   = "failed"
	CommandRejected = "rejected"
	CommandExpired  = "expired"
	CommandCanceled = "canceled"
)

The statuses of a command.

View Source
const (
	// PageCallResend is how long a command the page took and did not acknowledge waits before it is handed out again.
	PageCallResend = 5 * time.Second
	// PageCallReack is the same for a command the page acknowledged and has not answered: its page may have been
	// reloaded. The page that still runs it ignores the repeat, and a window that ran it answers what it answered.
	PageCallReack = 15 * time.Second
	// PageGone is how long a page that took a command must be silent before another page of the chat is given it.
	PageGone = 5 * time.Second
	// PageCallOrphan is how long a command nobody waits for is kept for its caller to come back with the same key (the
	// proxy repeats a call it lost at once). Until the caller is back the command is not handed to a page; after this
	// long it is canceled: an agent that was stopped, or was told its call was lost, does not have it run later.
	PageCallOrphan = 10 * time.Second
	// PageCommandsKept is how long a command that is over is remembered: for the proxy's repeat of the call, and for a
	// page that still holds it.
	PageCommandsKept = 10 * time.Minute
	// PageCommandsFile is the journal's file in the runtime's data folder.
	PageCommandsFile = "page-commands.db"
)
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 (
	ScopeInstall = appstore.ScopeInstall
	ScopeUser    = appstore.ScopeUser
	ScopeChat    = appstore.ScopeChat
	ScopeSpace   = appstore.ScopeSpace
	ScopeDoc     = appstore.ScopeDoc
)
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 (
	ViewLogMax      = 200
	ViewLogTextMax  = 1000
	ViewLogBatchMax = 50
)

ViewLogMax is how many lines an app's log keeps; ViewLogTextMax the longest line, in characters; ViewLogBatchMax how many lines one report may carry.

View Source
const (
	ViewLogError  = "error"
	ViewLogWarn   = "warn"
	ViewLogBridge = "bridge"
	// The host's own lines: a file of a view the server refused, a call of the app's MCP backend that failed,
	// and the steps of a load (a view opened, its handshake answered, no handshake in time).
	ViewLogServe = "serve"
	ViewLogMCP   = "mcp"
	ViewLogLoad  = "load"
)

The levels of a line: the view's console, an exception, a failed bridge call.

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"
	// SDKClassicPath is the classic SDK under a name of its own, the same in the runtime and in a copy a site hosts
	// (SDKFiles, where app-sdk.js is the module): what the loader loads.
	SDKClassicPath = "/__hl/app-sdk.classic.js"
	// LoaderPath is the loader of a site that exists already; LoaderInlinePath is the line its shell carries.
	LoaderPath       = "/__hl/loader.js"
	LoaderInlinePath = "/__hl/loader-inline.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 (
	// WindowToolWait is how long a call of a window's tool waits for the tool to be there: the window may still load, or
	// its view has not registered the tool yet.
	WindowToolWait = 15 * time.Second

	// MaxWindowToolName: Claude Code names the tool mcp__harnessly-app__<name>, and the whole name has to fit the 64
	// characters a tool name may have.
	MaxWindowToolName = 64 - len("mcp__"+hostServer+"__")
)
View Source
const (
	MaxWorkflowStatuses    = 16
	MaxWorkflowTransitions = 64
	MaxWorkflowJournal     = 200
	MaxWorkflowNote        = 500
	MaxWorkflowTitle       = 60
)

Limits of a workflow and of its record.

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 ChatStatusFile = "status.json"

ChatStatusFile is the name of the status file in a launch's folder.

View Source
const CheckTTL = 2 * time.Minute

CheckTTL is how long a link of a check lives.

View Source
const ChromeNone = "none"

ChromeNone is a view of the app's own screen that draws its own bar: the host shows none of its own above it.

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 DevUnsignedWarning = "в этом контуре приложения ставятся только с подписью издателя, а установка для разработки (dev) подпись не проверяет: " +
	"это исключение для автора, оно записано в журнал приложения. Для обычной установки подпишите пакет: harnessly app pack --sign"

DevUnsignedWarning is what an install for development says where signatures are required: the folder is not checked (the author's own work), and that is a conscious exception, written in the app's journal.

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 ExtendsSite = "site"

The documents of Sinopia's own an app's type may extend.

View Source
const FirstVersion = "0.16.36"

FirstVersion is the first host version with apps.

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 GuestsDir = "guests/"

GuestsDir is the folder of the links in the apps collection.

View Source
const HeightStage = "stage"

SlotTargets are the targets above, in the order the docs name them. HeightStage: a home view that fills the start page under the field, as the page of the day it brings.

View Source
const HookTimeout = 5 * time.Second

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

View Source
const HostMCPFile = "app-mcp.json"

HostMCPFile is the name, in the runtime's data folder, of the harnessly-app config a chat without apps starts with.

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 JournalConsentPolicy = "consent.policy"

JournalConsentPolicy is the journal's line of rights given by the organization's rule; its detail is the version.

View Source
const LostCall = "harnessly's runtime restarted while this call was running, so its answer is lost and the call may or " +
	"may not have been done. Check what it changed before repeating it."

LostCall is what a repeated call is answered when nothing remembers the first one: a tool of the host that is not a command of a window runs once, and whether it ran before the runtime restarted cannot be told.

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 MaxChatDocs = 32

MaxChatDocs bounds the documents kept for one chat.

View Source
const MaxConnectionNeeds = 16

MaxConnectionNeeds bounds the list: an app that wants everything is asked about piece by piece.

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 MaxTeamState = maxStoredTeam

MaxTeamState bounds the team's file a reader takes.

View Source
const MaxWindowBrief = 2560

MaxWindowBrief is the most one app's block may take. It was 1536 while the block gave the tools' names only; with the arguments' names beside them (the agent calls a tool from the block alone, with no tools/list of the window behind it) a form of twenty fields takes about 400 bytes for its tool and as much for its value, and a window has several tools.

View Source
const MemberPrefix = "/apps/space/"

MemberPrefix is where the hub serves the apps of a space to its members.

View Source
const MovedFile = ".moved-to-hub.json"

MovedFile is the move's journal, under the storage's root.

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 OpenEventTag = "app-event"

OpenEventTag is the envelope of the event in the message's text: the feed and the agent tell it from the person's own words by it.

View Source
const PermissionsEnv = "RUNTIME_APPS_PERMISSIONS"

PermissionsEnv is the deployment's switch: "on" turns the apps' permissions on; anything else leaves them off.

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 SDKMajor = 1

SDKMajor is the major version of the SDK's contract with a site that loads it by address. The files are served under /__hl/v<SDKMajor>/ too, and a site's loader line names that folder: a change that would break such a site gets a new number and the old folder keeps what it served.

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 (
	// SetRecordVersion is the version of a record's shape.
	SetRecordVersion = 1
)
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 SigSuffix = ".sig"

SigSuffix is what is added to the name of a .hlapp for the name of its signature.

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 TargetSide = "side"

TargetSide is a widget under the chat's right column on a computer: a small card the person adds, moves and folds. Not a slot: the person puts it there, so it is never gated by HARNESSLY_UI_SLOTS.

View Source
const TeamStateFile = "team/state.json"

TeamStateFile is the team in the apps collection.

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

TemplateBoard is the board file inside a template folder.

View Source
const TemplateVersion = "0.16.68"

TemplateVersion is the host version a new package asks for: the lowest that has what the templates use (the host's hl-ui.css, protocol 2, widgets). The guide (docs/build-apps) says the same, and a test keeps them equal.

View Source
const ViteTemplateVersion = "0.16.198"

ViteTemplateVersion is the host that serves a view's module scripts, fetch and fonts to its opaque-origin frame (the files carry open CORS and the slot lets "Origin: null" through): what a bundler's build needs.

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.

View Source
const WorkflowKey = "__hl_workflow"

WorkflowKey is the key of the doc area that holds a document's statuses. Keys with the host's prefix are not a view'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")
	// ErrNotGranted: the app was not given that access, so there is nothing to take back.
	ErrNotGranted = errors.New("apps: the access is not granted")
	// 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")
	// ErrEnvOwnItem: the app already comes with an item of the organization's own; the platform's item of the same app
	// gives way to it.
	ErrEnvOwnItem = errors.New("apps: the app comes with the organization's own item")
)
View Source
var (
	// ErrSecretUndeclared is a secret the manifest does not name.
	ErrSecretUndeclared = errors.New("apps: the app declares no such secret")
	// ErrSecretRight is a secret the app has no secrets:<name> permission for.
	ErrSecretRight = errors.New("apps: the app has no right to this secret")
	// ErrDisabled is an app that is switched off.
	ErrDisabled = errors.New("apps: the app is disabled")
)
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 (
	WidgetSources = []string{WidgetSourceLimits, WidgetSourceMachine, WidgetSourceSubagents}
	WidgetSizes   = []string{"s", "m", "l"}
)

WidgetSources are the data a side widget may name, and WidgetSizes its heights.

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 (
	ErrUnsigned     = errors.New("пакет не подписан")
	ErrUntrustedKey = errors.New("подпись не от доверенного издателя")
	ErrBadSignature = errors.New("подпись не сходится с пакетом")
)

Why a package was refused, in words for the person; errors.Is tells the kind.

View Source
var (
	// ErrQuota: the write would take the area past its limit.
	ErrQuota = appstore.ErrQuota
	// ErrStorageArgs: a scope, owner or key that is not one.
	ErrStorageArgs = appstore.ErrArgs
	// 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 = appstore.ErrConflict
)
View Source
var (
	// ErrNoTeam: this machine is not in a team.
	ErrNoTeam = errors.New("apps: this machine is not in a team")
	// ErrNotOwner: the person is a member; installing for the team is an owner's.
	ErrNotOwner = errors.New("apps: only an owner of the team does this")
	// ErrTeamApp: the app is the team's; a person turns it off for themselves, they do not remove it.
	ErrTeamApp = errors.New("apps: the app is the team's: turn it off for yourself instead")
	// ErrTrustedTeam: a trusted app is installed by hand, never for a team.
	ErrTrustedTeam = errors.New("apps: a trusted app is installed by hand, not for the team")
	// ErrNotInCatalog: the team's catalog has no such entry.
	ErrNotInCatalog = errors.New("apps: the team's catalog has no such app")
	// ErrStaleTeam: the snapshot is older than the one held.
	ErrStaleTeam = errors.New("apps: stale team snapshot")
)
View Source
var (
	// ErrWidgetArgs: an id, a title, the data or a file past its limit, or a view that is not one.
	ErrWidgetArgs = errors.New("apps: bad widget")
	// ErrWidgetsFull: the chat has as many widgets as it may keep.
	ErrWidgetsFull = errors.New("apps: the chat has too many widgets")
	// ErrWidgetGone: no such widget in the chat.
	ErrWidgetGone = errors.New("apps: no such widget")
	// ErrWidgetKind: the id is a widget of another app or kind; it is not changed into one.
	ErrWidgetKind = errors.New("apps: the id is another widget's")
)
View Source
var (
	ErrNoWorkflow    = errors.New("apps: the app has no workflow")
	ErrWorkflowMove  = errors.New("apps: no such move from the current status")
	ErrWorkflowRole  = errors.New("apps: the person's role does not allow this move")
	ErrWorkflowStale = errors.New("apps: the document changed: the move names a version that is not the current one")
	ErrWorkflowNote  = errors.New("apps: the note is too long")
)

Errors of a move. ErrWorkflowStale: the version the move names is not the current one any more.

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 ErrCheckRemote = errors.New("apps: the view is at an address of its own; a check opens only a view the package carries")

ErrCheckRemote: the view lives at an address of its own, which a check on the machine does not open.

View Source
var ErrExtendNotAllowed = errors.New("apps: the deployment does not let this app extend Sinopia's editor")

ErrExtendNotAllowed: the app's type extends Sinopia's editor, and the deployment did not let the app do it.

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 ErrPageCallDead = errors.New("apps: the command is over")

ErrPageCallDead: the command is over, and a page's word about it comes too late.

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 ExtensionKinds = []string{KindUI, KindRuntime, KindTool}

ExtensionKinds are the kinds above in the order the docs name them.

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 SDKVersionedPrefix = "/__hl/v" + strconv.Itoa(SDKMajor) + "/"

SDKVersionedPrefix is the folder of the SDK's files by major version.

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.

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

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

View Source
var WidgetChatRe = regexp.MustCompile(`^tab-[A-Za-z0-9_-]{1,80}$`)

WidgetChatRe is what a conversation id looks like: the runtime's tab id.

Functions

func AccessCodes

func AccessCodes(list []Access) []string

AccessCodes are the codes of a list, as the manifest writes them: what a line of the CLI names.

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 BundlePath

func BundlePath(app, sum string) string

BundlePath is where an app's package is in the apps collection, by the sum of its archive.

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 CallRepeats

func CallRepeats(ctx context.Context) bool

CallRepeats says whether the tool call of ctx repeats one whose answer its caller lost.

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 ChatStatusNotice

func ChatStatusNotice(statuses map[string]ChatDocStatus, manifest func(app string) *Manifest) string

ChatStatusNotice is what the agent is told of the statuses of the chat's documents: the status, the version, and what the app's rules of that status keep the agent from. names gives an app's name and workflow.

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 ClientCertFor

func ClientCertFor(m Manifest, srv MCPServer, pem func(secret string) (string, error)) (*tls.Certificate, error)

ClientCertFor is the certificate an app presents to the MCP server srv (network.clientCert of its manifest): the PEM in the app's secret, for the hosts the manifest names, or for the app's own servers when it names none. nil when the app has none or srv is another host. pem reads the secret; a secret with no value, or one that is no certificate with its key, is told in words: the call is not made without the certificate the app needs.

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 CommandOver

func CommandOver(status string) bool

CommandOver says whether a status is a final one.

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 ConsentWhere

func ConsentWhere(id string) string

ConsentWhere says where the person gives the word an app waits for: only a click of theirs in the host's page, since the CLI is every agent's too.

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 ExtendAllowed

func ExtendAllowed(app string) bool

ExtendAllowed says whether the deployment lets an app extend Sinopia's editor (app.extend).

func FillInstall

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

FillInstall puts the installation's values into a JSON text; a name without a value stays as written and is reported. A value goes in as the inside of a JSON string.

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 GenerateKey

func GenerateKey() (private, public string, err error)

GenerateKey makes a publisher's key pair: the private key as base64 of its 64 bytes (to keep in the safe) and the public one as base64 of 32 bytes (to give to the deployment's admin).

func GuestHash

func GuestHash(token string) string

GuestHash is the hash a link keeps of its token.

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 GuestPath

func GuestPath(person, hash string) string

GuestPath is where a person's link is in the apps collection.

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 HostInstructions

func HostInstructions() string

HostInstructions are the words of the host's tools, as the server gives them at initialize and as the agent of a chat that turned an app on later gets them on its next turn (live.go).

func HostToolName

func HostToolName(name string) string

HostToolName is the name Claude Code calls a tool of the host's server by.

func InstallNames

func InstallNames(s string) []string

InstallNames are the names a text asks the installation for, each once, sorted.

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 IsAuthCode

func IsAuthCode(code string) bool

IsAuthCode says whether a code is one of a refused sign-in.

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 IsWindowToolName

func IsWindowToolName(name string) bool

IsWindowToolName says whether a tool name has the shape of a window tool's.

func JournalSource

func JournalSource(id string) string

JournalSource is the journal's source of an app's lines: Sinopia's own, or an app's.

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 KeyID

func KeyID(key string) string

KeyID is a short fingerprint of a public key for messages (the first 8 bytes of its SHA-256, hex).

func KindsOf

func KindsOf(list []Installed) map[string]string

KindsOf is the kind of every installed app, by id.

func LaunchNeeds

func LaunchNeeds(pkg *Package) string

LaunchNeeds names what of the app only a launch of the agent gives; "" when a running agent can take it as it is.

func LiveBrief

func LiveBrief(a Installed) (string, error)

LiveBrief is what the agent of a running chat is told of an app turned on in it: its instructions and where its skills are. Its slash commands come with the next start only.

func LiveContext

func LiveContext(lines, open []string) string

LiveContext is the short context of every person's turn while apps are on in the chat: which apps, where their words are, their tools and what of them is open beside the chat. lines are LiveLine's; "" with no app.

func LiveLine

func LiveLine(a Installed) string

LiveLine is one app in the short context of every person's turn: its name and where its instructions and skills are.

func LiveNotice

func LiveNotice(on, waiting, off []string) string

LiveNotice is the additionalContext of the agent's next turn after apps were turned on or off in its chat; "" when nothing changed. on are the briefs of the apps turned on (LiveBrief), waiting the refusals of the ones that wait for a new start, off the names of the apps turned off.

func LiveRefusal

func LiveRefusal(name, needs string) string

LiveRefusal is what the app's tools answer while it waits for a new launch of the agent.

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 MemberPath

func MemberPath(spaceID, appID string) string

MemberPath is the page of an app of a space at the hub.

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 OpenEvent

func OpenEvent(app, name, screen string) string

OpenEvent is the text of the message that gives the agent its turn: the app, its name and the screen the window shows ("" when it named none).

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 PageCallTool

func PageCallTool() any

PageCallTool is the definition of page_call, the tool of the host's server that is always there and always loaded: a running agent learns of an app turned on, or of a window opened, from the block of its turn, and may not have heard that the server's tools changed. It is the one tool a chat with no app on pays for.

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 PermissionsFromEnv

func PermissionsFromEnv()

PermissionsFromEnv sets the switch from PermissionsEnv.

func PermissionsOn

func PermissionsOn() bool

PermissionsOn says whether the apps' permissions are on.

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 ProxiedServers

func ProxiedServers(pkg *Package) []string

ProxiedServers are the package's MCP servers the host's harnessly-app server proxies for an agent that runs already the remote ones, an address or the person's connection, by name. A server with a command is not among them.

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 ProxyMCPAs

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

ProxyMCPAs is ProxyMCP for the app called name. When the server cannot be reached or answers that it is unavailable (502, 503, 504), a JSON-RPC request is answered in JSON-RPC: a tool call gets a tool result with isError and a sentence the agent can pass on, any other request an error with the same sentence. The agent then reads «the service is unavailable» and not a transport's failure. A notification or a batch keeps the bare HTTP status.

func ProxyToolName

func ProxyToolName(app, server, tool string) string

ProxyToolName is the name the host lists a tool of an app's server under: <app>_<server>_<tool> in the letters MCP clients take ([A-Za-z0-9_-], at most 64), a longer one cut with a hash of the whole.

func PublicOf

func PublicOf(private string) (string, error)

PublicOf is the public key of a private one (base64 both).

func PutSecret

func PutSecret(safe *secrets.Store, m *Manifest, name, value string) error

PutSecret writes one secret the manifest declares into the safe (app/<id>/<name>); the page and the CLI never read it back.

func ReadChatStatus

func ReadChatStatus(path string) map[string][]string

ReadChatStatus reads a launch's status file: the statuses of the chat's documents by app. Nothing there, or a file that is not one, is none.

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 RemoveSecret

func RemoveSecret(safe *secrets.Store, m *Manifest, name string) error

RemoveSecret forgets one declared secret; a secret that was never set is not an error.

func Request

func Request(ctx context.Context, srv MCPServer, method string, params map[string]any) (json.RawMessage, error)

Request sends one request to an app's remote MCP server after its initialize: a new session each time.

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 RevealSecrets

func RevealSecrets(safe *secrets.Store, m *Manifest, names []string) (map[string]string, error)

RevealSecrets opens the values of names for one process of the app: each has to be declared in the manifest and granted by its secrets:<name> permission. The values go to the process (harnessly app run) and nowhere else.

func RoleAtLeast

func RoleAtLeast(role, min string) bool

RoleAtLeast says whether a project role is min or stronger; no role is never enough.

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. A site that exists already takes the loader instead: the line of loader-inline.js in its shell, and loader.js, bridge-shim.js and app-sdk.classic.js in the folder the line names.

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 SetArchivePath

func SetArchivePath(sum string) string

func SetNetwork added in v0.16.154

func SetNetwork(n DeployNetwork)

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

func SetPath

func SetPath(id string) string

SetPath is the path of an app's record in the room; SetArchivePath that of a package.

func SetPermissions

func SetPermissions(on bool)

SetPermissions turns the apps' permissions on or off for this process (the runtime reads PermissionsEnv at start; tests of the refusals turn them on).

func SignaturesRequired

func SignaturesRequired() bool

SignaturesRequired says whether this deployment installs signed packages only.

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 TeamArchivePath

func TeamArchivePath(id, version string) string

TeamArchivePath is where the store keeps the package of an app's version.

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 Transport

func Transport(host string) http.RoundTripper

Transport is the transport of a call an app makes from the machine to host (a feed of the start page, docs/apps/day-feed.md): the same rules as the proxy's MCP calls.

func UnavailableText

func UnavailableText(name string) string

UnavailableText is what the agent reads when an app's server is down.

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 ValidViewLevel

func ValidViewLevel(level string) bool

ValidViewLevel says whether a level is one a line may carry.

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 ViewLogFailure

func ViewLogFailure(l ViewLogLine) bool

ViewLogFailure says whether a line is a failure: everything but a load step and a warning.

func WallRefusal

func WallRefusal(name string) string

WallRefusal is what the tools of an app answer in a deployment that requires the wall when the agent started without it.

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 WindowBrief

func WindowBrief(name string, r PageReport, tools []WindowTool) string

WindowBrief is the block of one app's open window: name is the app's name, r its window's report with what its rights open, tools the report's tools under their names in the host's server. At most MaxWindowBrief bytes.

func WindowNotice

func WindowNotice(blocks, closed []string) string

WindowNotice is the live hook's text of the open windows: the blocks that are new or changed since the agent was last told, and the names of the apps whose windows were closed. "" when there is nothing to say.

func WindowScreen

func WindowScreen(raw json.RawMessage) string

WindowScreen is the title of the screen a window's context names, or its route when it has no title; "" when the context names no screen.

func WithCallKey

func WithCallKey(ctx context.Context, key string, again bool) context.Context

WithCallKey marks a tool call's context with the caller's idempotency key (internal/appmcp sends it); again says the request repeats a call whose answer was lost with the connection.

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 AppMCP

type AppMCP struct {
	// Apps are the apps whose servers are proxied: on in the chat, live, and not of the agent's launch.
	Apps func() []string
	// Package is an installed app's package (Registry.Package).
	Package func(app string) (*Package, error)
	// ListServer and CallServer reach one server of an app with the host's credentials for it (a connection, a secret, a token).
	ListServer func(ctx context.Context, app, server string) ([]RemoteTool, error)
	CallServer func(ctx context.Context, app, server, tool string, args map[string]any) (json.RawMessage, error)
	// Cache keeps the servers' lists between the agent's tools/list; nil keeps nothing.
	Cache *RemoteTools
	// Failed is told of a server whose list could not be had, and of a failed call (the journal, the app's log).
	Failed func(ctx context.Context, app, what string, err error)
}

AppMCP is the part of the harnessly-app server that proxies the remote MCP servers of the apps turned on in a chat after its agent started. Such an agent has no plugin of the app, so the host lists the servers' tools under names of its own (ProxyToolName: the app, the server, the tool) and runs a call from the machine with the host's credentials for the server, the way a view's hl.tools.call does. The list follows the apps on in the chat: the server's GET stream tells the agent when it changes (v2_applive.go), so an app turned off takes its tools along.

func (AppMCP) Call

func (a AppMCP) Call(ctx context.Context, name string, args *jsvalue.Object) *jsvalue.Object

func (AppMCP) Has

func (a AppMCP) Has(name string) bool

func (AppMCP) Instructions

func (AppMCP) Instructions() string

func (AppMCP) Tools

func (a AppMCP) Tools() []any

type AppSet

type AppSet struct {
	Reg     *Registry
	Storage *Storage
	Room    SetRoom
	// Machine names this VM in the records it writes.
	Machine string
	// Host is the runtime's version, which a package is checked against.
	Host string
	// CarryConsent: the rights the person agreed to on another VM are agreed here too, as far as they cover what the
	// package reaches (the room is the person's own machines'). Off, an app that reaches anything waits for a click.
	CarryConsent bool
	Log          *slog.Logger
	Now          func() time.Time
	// contains filtered or unexported fields
}

AppSet reconciles one VM's registry with the person's set in the hub.

func (*AppSet) Reconcile

func (s *AppSet) Reconcile(ctx context.Context) (SetReport, error)

Reconcile makes one pass: it publishes what changed here, applies what changed in the room, and says what it did.

func (*AppSet) Run

func (s *AppSet) Run(ctx context.Context)

Run keeps the VM's apps in step with the person's set until ctx ends: a pass now, after every change of the registry or of an app's settings made here (the VM publishes it), when another VM puts something into the room (the hub's changes feed), and every ten minutes anyway.

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
	// SignIn, for an auth code, is where the person signs in; nil when no sign-in mends it.
	SignIn *SignIn
	// Hint is a sentence for the person: what is wrong and who can fix it (a host outside the deployment's network
	// policy). It names nothing the page could not know: the host is the one the app asked for.
	Hint 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
	// Status are the statuses of the chat's documents by app (chatstatus.go), for the rules of agent.tools.when.
	Status map[string][]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 Center

type Center struct {
	Files  appstore.Files
	Person string
}

Center is the hub's store as the storage keeps its areas there: Files in the space's apps collection, Person the name of the person's user area ("" keeps the user area on the machine, as with a hub that names nobody).

type CenterClient

type CenterClient interface {
	appstore.Client
	Changes(ctx context.Context, since int64, wait time.Duration) (filestore.Changes, error)
	Put(ctx context.Context, path string, data []byte, author string) (filestore.Entry, error)
}

CenterClient is the store's API the apps speak under a hub (filesync.Client).

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 ChatDocStatus

type ChatDocStatus struct {
	App     string `json:"app"`
	Doc     string `json:"doc"`
	Version int    `json:"version"`
	Status  string `json:"status"`
	// At is when it was noted (ms): past MaxChatDocs the oldest goes.
	At int64 `json:"at"`
}

ChatDocStatus is the status of one app's document in a chat.

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 ClientCert

type ClientCert struct {
	Secret string   `json:"secret"`
	Hosts  []string `json:"hosts,omitempty"`
}

ClientCert names the secret with an app's client certificate and, when the app has several backends, which of the hosts of its own MCP servers (.mcp.json) it is for; none listed: every one. It is never sent to another host.

type CompatApp

type CompatApp struct {
	ID       string        `json:"id"`
	Version  string        `json:"version"`
	Kind     string        `json:"kind"`
	Disabled bool          `json:"disabled,omitempty"`
	Range    string        `json:"harnessly"`
	Issues   []CompatIssue `json:"issues,omitempty"`
}

CompatApp is one app's result.

func (CompatApp) OK

func (a CompatApp) OK() bool

OK says whether the app has no error.

type CompatIssue

type CompatIssue struct {
	Warning bool   `json:"warning,omitempty"`
	Message string `json:"message"`
}

CompatIssue is one thing that would stop an extension after the upgrade.

type CompatReport

type CompatReport struct {
	Host string      `json:"host"`
	Apps []CompatApp `json:"apps"`
	OK   bool        `json:"ok"`
}

CompatReport is the check of every installed app.

func CheckCompat

func CheckCompat(list []Installed, host string, st *Storage) CompatReport

CheckCompat is Compat over a list; st may be nil (stored data is not looked at).

type ConflictError added in v0.16.154

type ConflictError = appstore.ConflictError

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

type ConnectionNeed

type ConnectionNeed struct {
	ID       string `json:"id,omitempty"`
	Category string `json:"category,omitempty"`
	Access   string `json:"access,omitempty"`
	// Reason is one line the consent card shows: what the app does with the connection.
	Reason string `json:"reason,omitempty"`
}

ConnectionNeed is one connection (or group of them) the app asks for.

func (ConnectionNeed) Level

func (n ConnectionNeed) Level() string

Level is the need's access with the default put in: read unless it says all.

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
	// ConsentPolicy: the organization's rule gives the app what it asks for (an install that would be ConsentAsk while
	// the rule is on). The journal says so: consent.policy.
	ConsentPolicy
)

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 DataSpec

type DataSpec struct {
	Version    int               `json:"version"`
	Migrations map[string]string `json:"migrations,omitempty"`
}

DataSpec is the version of the app's own data and the JSON Patch file that brings it from each earlier version.

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 = egress.Policy

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, the organization's root certificates, its proxy and a client certificate. It is the one policy of internal/egress, which Connections share. An app cannot widen it.

func NetworkFromEnv added in v0.16.154

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

NetworkFromEnv reads the machine's overrides of the deployment's network (egress.FromEnv).

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"`
	// Missing are the installation's addresses the package asks for and the hub gave none of: the app is installed but
	// not configured, and the person does not see it (Installed.Unconfigured).
	Missing []string `json:"missing,omitempty"`
}

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
	// Install are the installation's values the hub gave with the item (${install:<name>} of the package).
	Install map[string]string
	// Keep are the app items of the list being applied. An app whose item is not among them is taken over by the item
	// that brings it now (the organization replaced its item with another of the same app): the install, its settings
	// and the person's switch stay.
	Keep []string
}

EnvInstallOptions say how the environment installs an app.

type ErrPageCallRejected

type ErrPageCallRejected struct{ Why string }

ErrPageCallRejected: the command was not run because its condition did not hold; the error's text says what the window shows now.

func (ErrPageCallRejected) Error

func (e ErrPageCallRejected) Error() string

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
	// ViewLog are the last lines its views reported (viewlog.go), oldest first.
	ViewLog []ViewLogLine
}

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"`
	// Policy: the rights were given by the organization's rule, not by a click.
	Policy bool `json:"policy,omitempty"`
}

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"`
	// Check marks a link `harnessly app check` made for the machine's own headless browser: any local view, a
	// couple of minutes, never listed, and the only kind whose page reports to the app's log.
	Check     bool  `json:"check,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 NewGuestsFrom

func NewGuestsFrom(lookup func(hash string) (GuestLink, Installed, error), storage *Storage) *Guests

NewGuestsFrom serves links that lookup finds by the token's hash (with the app they show, unpacked somewhere), the links' areas in storage: the hub answers a link from the store this way with the machine that made it off. It makes no links of its own.

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

func (g *Guests) CreateCheck(appID, view string) (token string, link GuestLink, err error)

CreateCheck makes a link of a check to an installed app's view (any local one); the token comes back once.

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

func (g *Guests) PublishGuests(ctx context.Context, c CenterClient, person string, bundles *bundleOf) error

PublishGuests makes the store's links of person this machine's live ones: each with its app's package, and the links that ended taken out.

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
	// Check opens an app's view in a browser of the machine and judges the load (app_check); nil refuses the tool.
	Check func(ctx context.Context, app, view string) (LoadCheck, error)
	// WidgetChanged tells the chat's pages that a widget of the chat was shown or changed; may be nil.
	WidgetChanged func(conv string)
	// Live says why an app on in the chat cannot be used by the agent as it runs now ("" when it can): an app turned on
	// after the agent started that needs what only a launch gives (live.go). nil: every app on can be.
	Live func(app string) 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 (t HostTools) Instructions() string

func (HostTools) Offering

func (t HostTools) Offering() string

Offering is what the server's tools follow: the apps on in the chat, whether a Sinopia document is open beside it and the tools the open windows of the apps offer (windowtools.go). The GET stream tells the client of a change of it (notifications/tools/list_changed).

func (HostTools) Tools added in v0.16.86

func (t HostTools) Tools() []any

func (HostTools) WindowBriefs

func (t HostTools) WindowBriefs() []WindowBriefOf

WindowBriefs are the blocks of the chat's open windows, by app: only of the apps on in the chat (or builtin), each with what its rights open.

func (HostTools) WindowTools

func (t HostTools) WindowTools() []WindowTool

WindowTools are the tools the open windows of the chat's apps offer now.

type HubLink struct {
	Client CenterClient
	// Person names the person's user and chat areas ("" keeps them on the machine).
	Person   string
	Registry *Registry
	// Host is the runtime's version, which a team's package is checked against.
	Host string
	Log  *slog.Logger
	Now  func() time.Time
}

HubLink is what the apps keep in the hub's store: the storage's areas, and the team's apps when Registry is set.

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
	// AskedIn is the chat the install was made from; "" keeps the chat an earlier install was made from.
	AskedIn string
	// Signed: the package's signature was checked and is a trusted publisher's (VerifyArchive). Only the paths that hold a
	// signature set it; where the deployment requires signatures an install without it is refused unless it is Dev.
	Signed bool
}

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.
	// EnvSum identifies the package selected by the environment and is never read from a personal install.
	EnvSum      string `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"`
	// AskedIn is the chat whose agent installed or updated the app last: its consent card shows there and in
	// that chat's right pane. "" for an install from outside a chat.
	AskedIn string `json:"askedIn,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 UnpackBundle

func UnpackBundle(raw []byte, sum, app, version, dir string) (Installed, error)

UnpackBundle puts an app's archive (checked against its sum) into dir/<sum> once, and answers the app as installed there, for a link of the store to show.

func (Installed) AccessNow

func (a Installed) AccessNow() []Access

AccessNow is everything the install reaches now, as the install screen lists it: what a click on it grants. It is read from where NeedsConsent reads, so the screen never shows less than the consent asks for.

func (Installed) DevSourceGone

func (a Installed) DevSourceGone() bool

DevSourceGone says a dev install points at a folder that is not there any more: a scratch folder a reboot wiped, a checkout that was removed. The install is still listed and can still be turned on in a chat, but nothing of it can be served: its views never load and its window never reports, which looked like a window "not connected".

func (Installed) GrantedKeys

func (a Installed) GrantedKeys() []string

GrantedKeys are the keys the app is given now: each can be taken back alone (Revoke).

func (Installed) LiveManifest

func (a Installed) LiveManifest() *Manifest

LiveManifest is the manifest the install runs now: a dev install's folder as it is (the author edits it after the install, and NeedsConsent reads it from there), any other install the manifest it was installed with. A dev folder that cannot be read leaves the installed one.

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

func (a Installed) Unconfigured() bool

Unconfigured says whether the app still waits for an address of the installation: a placeholder is left in its manifest or in its .mcp.json.

func (Installed) WaitingAccess

func (a Installed) WaitingAccess() []Access

WaitingAccess is what waits for the person's word: what an install kept off reaches beyond what was granted, or what a waiting update adds; empty when nothing waits.

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"`
	// Extends is the document of Sinopia's own the type is made of ("site"); its documents open in Sinopia's editor.
	Extends string `json:"extends,omitempty"`
}

KindInfo is a document type as the page lists it.

func DocumentKindsOf

func DocumentKindsOf(list []Installed) []KindInfo

DocumentKindsOf are the document types of the installed apps, by id (the hub reads them from the packages of a space's team).

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
	// CLIBin is the harnessly CLI the agents can start, by its path; "" when the deployment names none. With it the
	// harnessly-app server is the CLI's stdio proxy (`harnessly app-mcp`), which outlives the runtime's restarts.
	CLIBin 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) AppsDropped

func (l *Launcher) AppsDropped(conversation string, ids []string, why error)

AppsDropped puts in each app's log, and the machine's, that a chat started without it and why: `harnessly app logs` and the app's card say it, where before the chat did not start at all.

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.

func (*Launcher) HostMCP

func (l *Launcher) HostMCP() (string, error)

HostMCP is the --mcp-config of the harnessly-app server for a Claude Code chat that starts with no app on: the server is quiet until an app turns on in the chat, then its tools come live (live.go). It holds the person's token, as the runtime's own config beside it does, so it lives in the data folder, which the wall of a launch with apps leaves unreadable (seal.go). "" when the runtime has no MCP config.

func (*Launcher) Launchable

func (l *Launcher) Launchable(ids []string) ([]string, map[string]error)

Launchable splits ids into the apps a chat's agent can be given now and the others with why: an app uninstalled since it was turned on, one that is not for a chat, one whose instructions do not read. The chat starts with the first, so one broken app does not keep it from starting.

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 LoadCheck

type LoadCheck struct {
	App  string `json:"app"`
	View string `json:"view,omitempty"`
	// State is ok (the handshake came and nothing failed), failed (a failure line, or no handshake), waiting (the app
	// waits for the person's consent), off (turned off) or unreachable (no browser, or the page did not open).
	State     string        `json:"state"`
	Handshake bool          `json:"handshake"`
	Ms        int64         `json:"ms,omitempty"`
	Errors    int           `json:"errors"`
	Problem   string        `json:"problem,omitempty"`
	Lines     []ViewLogLine `json:"lines"`
}

LoadCheck is what `harnessly app check` and the agent's app_check tool answer: did the app's view load in a browser of the machine, how long its handshake took, and every line the load wrote to the app's log.

func Judge

func Judge(app, view string, lines []ViewLogLine) LoadCheck

Judge fills a result from the lines a load wrote (those since its start): the handshake, the time, the failures.

func (LoadCheck) OK

func (c LoadCheck) OK() bool

OK says whether the view loaded cleanly.

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"`
	// Auth says how the host signs the person in to the server (docs/build-apps/10-auth.md); nil: as the headers say.
	Auth *ServerAuth `json:"auth,omitempty"`
	// Credentialed: the headers carry a credential (a secret the install keeps, a connection's token, the platform's
	// token). A 401 to such a call is an expired sign-in, not a missing one. Set by the host, never read from a package.
	Credentialed bool `json:"-"`
	// ClientCert is the app's certificate for mutual TLS to this server (network.clientCert); set by the host, never read
	// from a package, and used for this server's calls only.
	ClientCert *tls.Certificate `json:"-"`
}

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

func (MCPServer) AudienceFor

func (s MCPServer) AudienceFor() string

AudienceFor is the audience of the server's token: the origin of its url, or for oidc the declared one.

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

func (s MCPServer) Origin() string

Origin is the origin (scheme://host[:port]) of the server's url; "" for a server without one.

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"`
	// Connections are the person's connections (Settings → Connections) the views read through hl.connections, and how far
	// each goes (connections_manifest.go).
	Connections []ConnectionNeed `json:"connections,omitempty"`
	// Workflow is the statuses of the app's documents and the moves between them (workflow.go).
	Workflow *Workflow `json:"workflow,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"`
	// Kind says which of the extension kinds the package is: "ui", "runtime" or "tool", see ext.go. Empty is
	// worked out from what the package contains.
	Kind string `json:"kind,omitempty"`
	// Data is the version of the app's own data in hl.storage and the steps that bring older data to it.
	Data *DataSpec `json:"data,omitempty"`
	// QuickEdit is how the app's objects take a quick edit by voice: the app's own tools that read an object as
	// text, apply exact replacements to it and take the last edit back. The host plans the edit, the app applies it.
	QuickEdit *QuickEdit `json:"quickEdit,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) ExtensionKind

func (m *Manifest) ExtensionKind() string

ExtensionKind is the kind of the package: the one written in the manifest or, when none is, the one its contents make.

func (*Manifest) FeedURL

func (m *Manifest) FeedURL(feed string) (string, bool)

FeedURL is the address of a view's day feed when the page may read it: https, no credentials in it, and its host listed in network.connect.

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"), or the kind is its own and extends Sinopia's editor.

func (*Manifest) PinnedView

func (m *Manifest) PinnedView(kind string) *View

PinnedView is the app's pinned tab for a document of a kind: its view, or nil.

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 Member

type Member struct {
	Space  string
	Person string
}

Member is who opens an app at the hub: the space, and the person's name in the store (the name of their user area, storehub.PersonName). The hub checks the session and the role before it hands a request over.

type Members

type Members struct {
	// Lookup finds an app installed for a space, unpacked where the files can be read; ErrNotInstalled when it is not
	// (or its package is not in the store).
	Lookup func(ctx context.Context, spaceID, appID string) (Installed, error)
	// Storage is the storage of a space as a person sees it: its areas in the store, the user area the person's.
	Storage func(ctx context.Context, m Member) (*Storage, error)
}

Members serves the apps of the spaces' teams to their members.

func (*Members) ServeMember

func (ms *Members) ServeMember(w http.ResponseWriter, r *http.Request, m Member)

ServeMember answers a member's request under MemberPrefix; the space in the path must be the member's.

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 Moved

type Moved struct {
	// To is the area's path in the store, under storage/.
	To string `json:"to"`
	// Sha is the local file's sha256 when it was moved.
	Sha string `json:"sha"`
	// Status: "moved" (the keys the store lacked are there now), "same" (the store had them all), "skipped" (a user
	// or chat area with no person to name it: it stays on the machine), "failed".
	Status string `json:"status"`
	Keys   int    `json:"keys,omitempty"`
	Error  string `json:"error,omitempty"`
	At     string `json:"at"`
}

Moved is the journal's record of one local area.

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"`
	// ClientCert is the app's own certificate for mutual TLS to its own backend: the name of one of its secrets,
	// which holds the certificate and its key as PEM. The key is in the machine's safe, never in the manifest.
	ClientCert *ClientCert `json:"clientCert,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) ConnectionNeeds

func (p *Package) ConnectionNeeds() []ConnectionNeed

ConnectionNeeds is everything the package asks of the person's connections: the manifest's list, and each server of .mcp.json that names a connection (it takes the whole of it).

func (*Package) ConnectionReason

func (p *Package) ConnectionReason(id string) string

ConnectionReason is the line the app gave for the connection, for the consent card ("" when it gave none).

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

func (p *Package) DeclaredAccess(id string) string

DeclaredAccess is how far the app may go with the person's connection from catalog entry id: the widest of what the manifest's list names for the id or its group, and "all" for a server of .mcp.json that names it (that server is the whole connection). "" when the app names the connection nowhere.

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"`
	// ExpiresAt is when the command's term runs out, in milliseconds; Attempt how many times it was handed out.
	ExpiresAt int64 `json:"expiresAt,omitempty"`
	Attempt   int   `json:"attempt,omitempty"`
}

PageCall is a call the page takes to the view.

type PageCommand

type PageCommand struct {
	ID   string
	Conv string
	App  string
	Tool string
	Args json.RawMessage
	// Key is the caller's idempotency key of the call, "" when it gave none.
	Key    string
	Status string
	// The condition: the window's screen and the hash of its tools when the call was made, "" when not known.
	Screen string
	Offer  string
	// Result is the window's result (done); Error its error (failed) or the words of the refusal.
	Result json.RawMessage
	Error  string
	// Times in milliseconds; 0 when it has not happened.
	Created, Sent, Acked, Ended, Expires int64
	// Deliveries is how many times it was handed to a page, Page the page that has it, Legacy whether that page does
	// not acknowledge (an older page: it gets a command once).
	Deliveries int
	Page       string
	Legacy     bool
}

PageCommand is one row of the journal.

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, CallTTL and ToolWait (WindowToolWait when 0) are for tests; so are Resend and Reack (PageCallResend and
	// PageCallReack when 0).
	Now      func() time.Time
	CallTTL  time.Duration
	ToolWait time.Duration
	Resend   time.Duration
	Reack    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) Ack

func (p *PageTools) Ack(conv, id, page string) (status string, dead bool, err error)

Ack is the page's word that it has a command and is about to run it. The status that comes back is the command's now; dead says it is over, and the page must not run it.

func (*PageTools) Answer

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

Answer brings a view's answer to the command that waits for it; conv must be the command's chat. An answer to a command that is over is dropped: ErrPageCallDead, unless it only repeats the answer that ended it.

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

func (p *PageTools) CloseCommands() error

CloseCommands closes the journal's file.

func (*PageTools) Command

func (p *PageTools) Command(conv, id string) (PageCommand, bool)

Command is a command's row as it is now; false when the chat has none of that id.

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. A hook is not a command of the journal: it is asked once and its word is needed at once or not at all.

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

func (p *PageTools) OpenCommands(path string) error

OpenCommands gives the page tools their journal on the disk (PageCommandsFile in the runtime's data folder) and takes up what a runtime before this one left: a command that is not over and still within its term goes on being delivered, one past its term is expired, and those that ended lately are remembered for the proxy's repeat of the call.

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

func (p *PageTools) Resume(ctx context.Context, conv string) (PageAnswer, PageCommand, error, bool)

Resume finds the command of a call the caller makes again with the same idempotency key (its proxy lost the answer when the runtime restarted) and waits for its end as the first call did; found is false when the chat has no command of that key.

func (*PageTools) Take

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

Take hands a page that does not acknowledge (an older page) the commands of a chat nobody took yet; each goes to such a page once.

func (*PageTools) TakeBy

func (p *PageTools) TakeBy(conv, page string, acks bool) []PageCall

TakeBy hands a chat's page its commands. page names the page (a tab of the browser), acks says it acknowledges what it takes (Ack). A command goes out when nobody took it yet; and again, to a page that acknowledges, when the page that took it did not acknowledge it within PageCallResend or has not answered it within PageCallReack, and that page is this one or has been silent for PageGone. A command whose term ran out or whose condition holds no more is ended and not handed out.

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"`
	// Signature is the publisher's signature of the archive, when it has one.
	Signature *Signature `json:"signature,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 QuickEdit

type QuickEdit struct {
	// Read answers {text, version} of an object: {object, selection?}.
	Read string `json:"read"`
	// Apply takes {object, version, edits: [{old, new}], confirmed?} and answers {changed, version, hint, ids?}.
	Apply string `json:"apply"`
	// Undo takes {object, version}: the apply that answered that version is put back; empty: no undo.
	Undo string `json:"undo,omitempty"`
}

QuickEdit names the app's tools of a quick edit, each as `<server>.<tool>` of its backend.

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

func (r *Registry) AppendViewLog(id string, lines []ViewLogLine, now time.Time) ([]ViewLogLine, error)

AppendViewLog adds lines to an app's log and trims it to ViewLogMax; lines of an unknown level or with no text are dropped, a longer text is cut, and at most ViewLogBatchMax lines are taken. It returns the lines kept.

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

func (r *Registry) ApplyStoredTeam(ctx context.Context, c TeamClient, e filestore.Entry, host string, now time.Time) ([]string, error)

ApplyStoredTeam applies the team the store has (the revision e of TeamStateFile) as the platform's snapshot is applied, with this machine's own role and the archives it does not hold yet read from the store.

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

func (r *Registry) ChatStatuses(conv string) map[string]ChatDocStatus

ChatStatuses are the statuses kept for a chat, by app and document; none for a chat that has none.

func (*Registry) ClearViewLog

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

ClearViewLog empties an app's log.

func (*Registry) Compat

func (r *Registry) Compat(host string) (CompatReport, error)

Compat checks the apps of this machine against a harnessly version.

func (*Registry) ConnectionAccess

func (r *Registry) ConnectionAccess(app, id string) string

ConnectionAccess is how far the person agreed to the app using their connection from catalog entry id: "" (not at all), "read" or "all".

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 whole connection from catalog entry id (a server of .mcp.json goes through it).

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

func (r *Registry) EffectiveConnectionAccess(app, id string) string

EffectiveConnectionAccess is how far the app may go with the connection now: the person's agreement, cut to what the installed version still declares (an update that dropped the connection or narrowed it ends what the old one was agreed to). "" when the app may not use it at all.

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

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

Find is one installed app whatever its state: turned off, or waiting for the person's consent (Get skips those).

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 as far as the app's package asks for the connection. The package must name the connection.

func (*Registry) GrantConnectionAccess

func (r *Registry) GrantConnectionAccess(app, id, access string) error

GrantConnectionAccess records the agreement as far as access says (read or all; "" is as far as the app asks). The app may not be given more than it declared: .mcp.json's servers and `connections` of the manifest.

func (*Registry) GrantWaiting

func (r *Registry) GrantWaiting(now time.Time) ([]Installed, error)

GrantWaiting gives what waits for the person its rights by the organization's rule: a pending update takes the place of the running version, a first install or a dev folder that grew is turned on. It is called when the rule comes on and, while it is on, for the dev folders that grow; with the rule off it does nothing. Each grant is in the journal.

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

func (r *Registry) InstallArchive(raw []byte, sig *Signature, opt InstallOptions) (Installed, Problems, Verified, error)

InstallArchive installs a .hlapp: the archive's signature is checked under the deployment's policy first (VerifyArchive: a signature that does not match is always refused, a missing or untrusted one when the deployment requires signatures), then the archive is unpacked into a folder of its own and installed from it like any package.

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

func (r *Registry) LogEvent(id, view, level, text string)

LogEvent adds one line of the host's own to an app's log; a failure to write it is not the caller's concern. The line goes to the machine's journal too.

func (*Registry) LogEventOnce

func (r *Registry) LogEventOnce(id, view, level, text string)

LogEventOnce is LogEvent, but the same line of the same app is written once in ten seconds: a view that asks for a missing file on every load fills its log with one line, not a hundred.

func (*Registry) LogEventOnceJ

func (r *Registry) LogEventOnceJ(id, view, level, text string, je journal.Entry)

LogEventOnceJ is LogEventOnce with the journal's line given whole (its chat, trace, address and status).

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

func (r *Registry) NoteChatStatus(conv string, s ChatDocStatus) (bool, error)

NoteChatStatus keeps the status of an app's document in a chat and hands it to the chat's launches; it says whether it changed. A chat id that is not one is ignored.

func (*Registry) OnChange

func (r *Registry) OnChange(f func())

OnChange adds what is called after the installed list is written on this machine: an agent's widget made, changed or removed reaches every open page by it, with no reload. The function must not block.

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 adds 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): the cluster's event and the hub's store each have one. It is not called for a snapshot applied from the platform or the store, 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) PaneWhyNot

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

PaneWhyNot says why an app the text names opens no pane view, when the reason is the app's own state and not a wrong name: it waits for the person's consent (with what it waits for and where to give it), or the person turned it off. "" when the app is not installed or the reason is the view itself.

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

func (r *Registry) PublishArchive(raw []byte, sig *Signature, ch Channel, opt PublishOptions) (PublishedVersion, Problems, Verified, error)

PublishArchive publishes a .hlapp on a channel, the signature checked first as for an install. On stable the published version is the archive itself, so the signature is kept with it and travels to the team's catalog (PublishToTeam) and to the public one (PublishPublic). A pre-release channel rewrites the version in the manifest, which the signature does not cover: that version is published unsigned.

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

func (r *Registry) PublishTeam(ctx context.Context, c TeamClient) error

PublishTeam writes this machine's team into the store: the archives the store does not hold yet, then the team, on top of the one there unless that one is newer (then this machine takes it when it follows the store).

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

func (r *Registry) Revoke(id, key string, now time.Time) (Installed, error)

Revoke takes one access back: the key leaves the grant, so the app reaches it no more. What the app still wants is then not covered, and it waits for the person's word like a first install: it is kept off, its views' calls are refused at once (Get), and the card offers «Разрешить» again. It works for every kind of key: perm:, net:, frame:, server:, secret: and part:. A host's install or one from before consent had no grant: it is made from what it reaches now, minus the key. A waiting update is not touched.

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

func (r *Registry) SetConsentPolicy(on func() bool)

SetConsentPolicy sets what says whether the organization's rule «Не спрашивать разрешений» is on; nil (the default, a machine without a hub) asks the person. It is called with the registry's lock held, so it must not use the registry.

func (*Registry) SetDisabled

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

SetDisabled switches an installed app off or on. The team's apps are the team's: a person turns them off for themselves (Mute), they are not disabled here.

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

func (r *Registry) SetOrgOff(off func(link, itemID string) bool)

SetOrgOff sets what says whether the organization turned off the app of a link's environment item; nil (the default, a machine without a hub) turns nothing off. It is called with the registry's lock held, so it must not use the registry.

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

func (r *Registry) Uninstall(id string, purge bool, safe *secrets.Store) error

Uninstall removes the app; with purge it also forgets its settings, its secrets in the safe and its stored data. The safe may be nil (nothing in it is touched). Without purge they stay for a later install of the same app.

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.

func (*Registry) ViewLog

func (r *Registry) ViewLog(id string, limit int) ([]ViewLogLine, error)

ViewLog is the last limit lines of an app's log, oldest first; none kept is an empty list.

func (*Registry) ViewLogSince

func (r *Registry) ViewLogSince(id string, since int64, limit int) ([]ViewLogLine, error)

ViewLogSince is the lines of an app's log written at or after since (milliseconds), oldest first, at most limit of the last ones (0: all kept).

type RemoteTool

type RemoteTool struct {
	Name        string          `json:"name"`
	Description string          `json:"description,omitempty"`
	InputSchema json.RawMessage `json:"inputSchema,omitempty"`
	Annotations json.RawMessage `json:"annotations,omitempty"`
}

RemoteTool is a tool of a remote MCP server as its tools/list gives it: the definition is kept as the server wrote it.

func ListTools

func ListTools(ctx context.Context, srv MCPServer) ([]RemoteTool, error)

ListTools is the tools a remote MCP server offers (tools/list, its pages followed), under the same rules as CallTool.

type RemoteTools

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

RemoteTools keeps the tool lists of apps' servers for a while: a list for 5 minutes, a failure for 30 seconds.

func NewRemoteTools

func NewRemoteTools() *RemoteTools

func (*RemoteTools) Forget

func (c *RemoteTools) Forget(app string)

Forget drops the lists of an app's servers: its package changed, or it was turned on again.

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 = appstore.Scope

Scope is an area of the storage.

const ScopeConnections Scope = "connections"

ScopeConnections is the scope of a Change that is no key: the app's connections changed (an agreement given or taken back, a connection signed in, turned on or off). The views that hold connections.read hear it as the event `connections`.

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 ServerAuth

type ServerAuth struct {
	Type     string `json:"type"`
	Audience string `json:"audience,omitempty"`
	Scope    string `json:"scope,omitempty"`
}

ServerAuth is how the host signs the person in to an app's remote server. A platform token's aud is always the server's origin (https://host[:port]): an app cannot ask a token for another backend and send it to its own address. Audience names the identity provider's audience for oidc, which the hub's admin must have allowed for that origin (HUB_APP_TOKEN_EXCHANGE_AUDIENCES); the origin when empty. Scope is asked of the provider for oidc and oauth. The view never sees a token of any kind: the host adds it to the calls it makes for the view and the agent.

type Session added in v0.16.86

type Session struct {
	// ManagedSum binds a document reader to the package that opened this view.
	ManagedSum string
	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
	// Trace is the journal's trace of the page's action that mounted the view: the view server's lines of the
	// session carry it, so a file the view could not load reads in one chain with the page's lines.
	Trace string
	// contains filtered or unexported fields
}

Session is one mounted view.

type SetRecord

type SetRecord struct {
	V       int    `json:"v"`
	ID      string `json:"id"`
	Version string `json:"version,omitempty"`
	// Sum is the SHA-256 of the packed package at archives/<sum>.tgz.
	Sum     string `json:"sum,omitempty"`
	Removed bool   `json:"removed,omitempty"`
	Off     bool   `json:"off,omitempty"`
	Trust   string `json:"trust,omitempty"`
	// Settings are the values of the app's settings form (the install area's SettingsKey).
	Settings json.RawMessage `json:"settings,omitempty"`
	// Grant is what the person agreed to on the VM that wrote the record.
	Grant *Grant `json:"grant,omitempty"`
	// Source is where the VM that wrote the record installed it from (a note, never read back).
	Source string `json:"source,omitempty"`
	At     int64  `json:"at"`
	By     string `json:"by,omitempty"`
}

SetRecord is one app of the person's set as the room keeps it.

type SetReport

type SetReport struct {
	Published []string `json:"published,omitempty"`
	Installed []string `json:"installed,omitempty"`
	Updated   []string `json:"updated,omitempty"`
	Removed   []string `json:"removed,omitempty"`
	Changed   []string `json:"changed,omitempty"` // on/off, settings or rights
	// LocalOnly are the apps installed for development: they stay on this VM.
	LocalOnly []string `json:"localOnly,omitempty"`
	Problems  []string `json:"problems,omitempty"`
}

SetReport says what a pass did.

func (SetReport) Empty

func (r SetReport) Empty() bool

Empty tells whether the pass changed nothing.

type SetRoom

type SetRoom interface {
	Changes(ctx context.Context, since int64, wait time.Duration) (filestore.Changes, error)
	Current(ctx context.Context, path string) (*filestore.Entry, error)
	GetBlob(ctx context.Context, sha string, w io.Writer) error
	Put(ctx context.Context, path string, data []byte, author string) (filestore.Entry, error)
}

SetRoom is the person's room (filesync.Client of filestore.KindAppSet).

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 SignIn

type SignIn struct {
	Connection string `json:"connection,omitempty"`
	App        string `json:"app,omitempty"`
	Server     string `json:"server,omitempty"`
}

SignIn says where a refused call is mended by a sign-in: the host shows «Войти» on it. Connection is the catalog id of the person's connection the app's server goes through; App and Server name an app's own server that the host signs in to (auth: oauth). A view reads it and may not act on it by itself: the sign-in is the host's, in a top window.

type Signature

type Signature struct {
	Alg       string `json:"alg"`
	Publisher string `json:"publisher"`
	// Key is the public key, base64 of 32 bytes.
	Key string `json:"key"`
	// SHA256 is the archive's sum (hex); the signature is over it.
	SHA256    string `json:"sha256"`
	Signature string `json:"signature"`
}

Signature is the content of <name>.hlapp.sig.

func ParseSignature

func ParseSignature(raw []byte) (*Signature, error)

ParseSignature reads a .sig file.

func Sign

func Sign(archive []byte, publisher, private string) (Signature, error)

Sign signs the archive as publisher with the private key (base64).

func (Signature) Marshal

func (s Signature) Marshal() []byte

Marshal is the signature as the file holds 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"`
	// Extends names a document of Sinopia's own the type is made of: "site". Such a document is a project of
	// that kind, opened in Sinopia's own editor with the chat's right pane; the app adds to it (its panels, checks,
	// tab), and its contributions hold only in the documents of its type. It needs the permission app.extend and the
	// deployment's word (ExtendAllowed); the editor view is then optional.
	Extends string `json:"extends,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"`
	// Status is the status of the chat's documents by app, which the guard reads beside the launch (chatstatus.go); a
	// call that names none is decided by it.
	Status map[string][]string `json:"-"`
}

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"`
	// Signature and PreviousSignature are the publisher's signatures of those archives, when they have them.
	Signature         *Signature `json:"signature,omitempty"`
	PreviousSignature *Signature `json:"previousSignature,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"`
	Signature *Signature `json:"signature,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) ContentHash

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

ContentHash is a sha256 of an area's values without the host's own keys: what the app keeps of a document, so a change of it is a change of the document's version (workflow.go).

func (*Storage) DataVersion

func (s *Storage) DataVersion(app string) int

DataVersion is the version the app's stored data is at; 0 when the app has stored none.

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

func (s *Storage) HostUpdate(app string, scope Scope, owner, key string, change func(old json.RawMessage) (json.RawMessage, error)) (json.RawMessage, error)

HostUpdate changes one of the host's own keys of an area (appstore.HostKeyPrefix, as WorkflowKey), which no view reaches: change gets the value kept (nil for none) and answers the new one, or nil to leave it as it is.

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

func (s *Storage) MigrateData(p *Package) (from, to int, err error)

MigrateData brings the app's stored data to the version the package declares: every area goes through the steps in turn, all in memory first, and nothing is written when one of them fails. Data of an app with no earlier version is only stamped. A package that declares no data version leaves the data alone.

func (*Storage) MoveToCenter

func (s *Storage) MoveToCenter(ctx context.Context, files appstore.Files, person string) (moved, failed int, err error)

MoveToCenter moves the local user, space, chat and doc areas into files (see above) and answers how many it moved now and how many failed; an area the journal has as moved with the same file is not read again.

func (*Storage) NoticeCenter

func (s *Storage) NoticeCenter(rel string, raw []byte, quiet bool)

NoticeCenter is an area of the center as the store has it now (rel under storage/; nil raw for one deleted), whoever wrote it: the views hear of every key whose version moved since this machine last knew the area. quiet only learns the area, for the catch-up when the storage first links.

func (*Storage) NotifyConnections

func (s *Storage) NotifyConnections(app string)

NotifyConnections tells the views of an app that its connections changed.

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

func (s *Storage) Purge(app string) error

Purge deletes everything the app stored.

func (*Storage) RunCenter

func (s *Storage) RunCenter(ctx context.Context, l HubLink)

RunCenter keeps the apps in the hub's store until ctx ends: it moves the local areas, switches the storage to the store, writes this machine's team there and writes it again whenever it changes here, and follows the store's changes (the areas' keys to the views, the team to the registry). It returns when ctx ends; the storage stays on the store.

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.

func (*Storage) UseCenter

func (s *Storage) UseCenter(c *Center)

UseCenter keeps the user, space, chat and doc areas in the hub's store from now on; nil puts them back on the machine. The runtime sets it when it links to a hub's store (cmd/runtime).

type StoredGuest

type StoredGuest struct {
	Link GuestLink `json:"link"`
	// Version and Sum are the app's package the link shows; its archive is BundlePath(app, Sum).
	Version string `json:"version"`
	Sum     string `json:"sum"`
}

StoredGuest is a link as the store keeps it.

func ReadStoredGuest

func ReadStoredGuest(raw []byte, hash string) (StoredGuest, error)

ReadStoredGuest reads a link of the store and checks it is the one asked for.

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 TeamApp

type TeamApp struct {
	ID      string   `json:"id"`
	Name    string   `json:"name"`
	Version string   `json:"version"`
	Sum     string   `json:"-"`
	Targets []string `json:"targets"`
}

TeamApp is an app installed for a space, as the store's team has it: the pinned version and its archive's sum, and what the catalog says of it.

func TeamInstalls

func TeamInstalls(raw []byte) ([]TeamApp, error)

TeamInstalls is the apps installed for the space in the store's team (TeamStateFile's bytes), sorted by id.

type TeamClient

type TeamClient interface {
	Current(ctx context.Context, path string) (*filestore.Entry, error)
	GetBlob(ctx context.Context, sha string, w io.Writer) error
	Commit(ctx context.Context, req filestore.CommitRequest) (filestore.CommitResponse, error)
	PutBlob(ctx context.Context, sha string, data []byte) error
	Put(ctx context.Context, path string, data []byte, author string) (filestore.Entry, error)
}

TeamClient is the store's API the team speaks (filesync.Client).

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"`
	// When are rules that hold only while the document the chat works on is in one of the statuses (workflow.go); they
	// join the rules above, and the most specific rule decides as ever.
	When []ToolWhen `json:"when,omitempty"`
}

ToolPolicy is checked deny → confirm → allow.

type ToolWhen

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

ToolWhen is a set of rules for some statuses of the app's workflow.

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 Verified

type Verified struct {
	Publisher string
	// Signed: the archive carries a signature that matches it and a trusted key.
	Signed bool
}

Verified is what a successful check says: whose signature it is, when there was one.

func VerifyArchive

func VerifyArchive(archive []byte, sig *Signature, policy *egress.Policy) (Verified, error)

VerifyArchive checks an archive against its signature (nil: none) under the deployment's policy. A signature that does not match the archive is always refused. With RequireSigned a package without a signature, or signed by a key the policy does not list, is refused too; without it such a package is installed as unsigned.

type View

type View struct {
	ID      string   `json:"id"`
	Title   string   `json:"title,omitempty"`
	Entry   string   `json:"entry"`
	Targets []string `json:"targets"`
	// Height is "stage" for a view of the start page (home) that takes the whole stage under the field instead of a
	// block there; nothing else is run.
	Height string `json:"height,omitempty"`
	// Chrome "none": the app's own screen (target app) has its own bar, and the host draws none above it. The
	// host's actions — share, the right pane, its menu — reach the view through hl.host.actions / hl.host.run, and the
	// view shows them in its own bar or menu.
	Chrome string `json:"chrome,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"`
	// Pinned: the view is the app's tab in the chat's right pane beside a document of its type made of a Sinopia site
	// the first tab, never closed, shown only in the app's own documents.
	Pinned bool `json:"pinned,omitempty"`
	// Feed is the https address of a day feed (docs/apps/day-feed.md) for a view of the start page's stage: the host draws
	// the page of the day itself from what the feed answers, in its own interface, and the entry stays for a host that
	// cannot. Its host must be in network.connect.
	Feed string `json:"feed,omitempty"`
	// FeedSecret names a secret of the app the machine sends to the feed as a bearer token: the page then reads the feed
	// through its own runtime (the feedPath of the list of apps), signed in already, and never shows the feed's own sign-in.
	FeedSecret string `json:"feedSecret,omitempty"`
	// Widget is how a view of the side target is drawn and fed.
	Widget *ViewWidget `json:"widget,omitempty"`
}

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

type ViewLogLine

type ViewLogLine struct {
	At    int64  `json:"at"`
	Level string `json:"level"`
	View  string `json:"view,omitempty"`
	Text  string `json:"text"`
}

ViewLogLine is one line of an app's log.

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

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

func (*ViewSessions) Mounted

func (s *ViewSessions) Mounted(conv string) []Session

Mounted are the live sessions of the views the page mounted beside a chat: what of the apps is open there.

func (*ViewSessions) Peek

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

Peek is the live session of a token, not renewed by the look; a token unknown or gone is a zero session.

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.

func (*ViewSessions) SetTrace

func (s *ViewSessions) SetTrace(token, trace string)

SetTrace gives a live session the journal's trace of the action that mounted it.

type ViewWidget

type ViewWidget struct {
	// Size is the frame's height: "s" (96 px, the default), "m" (160) or "l" (240).
	Size string `json:"size,omitempty"`
	// Refresh is how often, in seconds, the host gives the view its data again while it is on screen (30 at least);
	// 0 gives it once.
	Refresh int `json:"refresh,omitempty"`
	// Sources are the host's data the view is given in hl.context.data.sources: WidgetSources.
	Sources []string `json:"sources,omitempty"`
	// Smart makes the widget ask a model now and then; its short answer is in hl.context.data.smart.
	Smart *WidgetSmart `json:"smart,omitempty"`
	// Chat is the conversation the widget was made for: the page shows it in that chat, and in the ones the
	// person pins it to, not in every chat. Empty: a widget for every chat.
	Chat string `json:"chat,omitempty"`
	// Shell names the part of the widget a change of its markup or style does not touch (its script): while it stays the
	// same the page keeps the card's frame and hands the new markup to it as data (hl.context.data.content), so an update
	// does not blink. Empty: any new install starts the frame anew.
	Shell string `json:"shell,omitempty"`
}

ViewWidget is a side widget's manifest: its height, how often the host hands it its data again, which of the host's data it is given (nothing else of the page reaches it), and the request of a smart widget the host puts to a model.

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 WidgetSmart

type WidgetSmart struct {
	Prompt string `json:"prompt"`
	Every  int    `json:"every,omitempty"`
}

WidgetSmart is a smart widget's request: what to ask the model over the widget's sources, and how often (minutes).

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.

type WindowBriefOf

type WindowBriefOf struct {
	App  string
	Name string
	Text string
}

WindowBriefOf is the block of an app's open window in a chat.

type WindowOpens

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

WindowOpens remembers the apps whose window was opened in each chat.

func OpenWindowOpens

func OpenWindowOpens(dataDir string) *WindowOpens

OpenWindowOpens is the process's one WindowOpens of a data folder.

func (*WindowOpens) Claim

func (o *WindowOpens) Claim(conv, app string) bool

Claim marks the app's window as opened in the chat; true only the first time. A mark that could not be written is not a first time: better no greeting than one at every report.

type WindowTool

type WindowTool struct {
	// Name is the tool's name in the host's server.
	Name string
	App  string
	PageTool
}

WindowTool is a tool of an app's open window under the name the agent calls it by.

func WindowTools

func WindowTools(reports []PageReport) []WindowTool

WindowTools names the tools of the reports, in the reports' order. A name depends only on the app, the tool and whether the long name is taken twice in the reports, never on the order.

func (WindowTool) Tool

func (w WindowTool) Tool() string

Tool is the tool's name in its window.

type Workflow

type Workflow struct {
	Statuses    []WorkflowStatus     `json:"statuses"`
	Transitions []WorkflowTransition `json:"transitions"`
}

Workflow is the manifest's `workflow`.

func (*Workflow) Follow

func (w *Workflow) Follow(r *WorkflowRecord, hash string, now time.Time) bool

Follow brings the record up to the document's content now (hash): the first version of a new document, the hash of a version that may be edited, or the next version when one that may not be edited was changed. A status the workflow no longer has counts as the first one. It says whether the record changed.

func (*Workflow) Move

func (w *Workflow) Move(r *WorkflowRecord, to, who, role string, version int, hash, note string, now time.Time) error

Move makes a move of the current version to `to`, by who with role; version and hash, when given, are the version the person saw, and the move is refused when the document is at another one.

func (*Workflow) Moves

func (w *Workflow) Moves(status, role string) []WorkflowMove

Moves are the moves from a status, in the manifest's order.

func (*Workflow) State

func (w *Workflow) State(r WorkflowRecord, role string) WorkflowState

State is the record as a view reads it, for a person with role.

func (*Workflow) Status

func (w *Workflow) Status(id string) (WorkflowStatus, bool)

Status is a status of the workflow by id.

type WorkflowEntry

type WorkflowEntry struct {
	At      int64  `json:"at"` // ms
	Who     string `json:"who,omitempty"`
	From    string `json:"from,omitempty"`
	To      string `json:"to"`
	Version int    `json:"version"`
	Hash    string `json:"hash"`
	Note    string `json:"note,omitempty"`
	// Rev is the project's named version the move was made on (Sinopia's history): the decision is on that point.
	Rev string `json:"rev,omitempty"`
	// Link opens Rev read only; it is filled in what a view reads, never kept.
	Link string `json:"link,omitempty"`
}

WorkflowEntry is one line of the journal: a move, or a new version started by a change.

type WorkflowMove

type WorkflowMove struct {
	To      string `json:"to"`
	Title   string `json:"title"`
	Role    string `json:"role"`
	Allowed bool   `json:"allowed"`
}

WorkflowMove is a move offered from the current status, and whether this person may make it.

type WorkflowRecord

type WorkflowRecord struct {
	Versions []WorkflowVersion `json:"versions"`
	Journal  []WorkflowEntry   `json:"journal"`
}

WorkflowRecord is what the host keeps of a document: its versions (the last is the current one) and the journal.

func ParseWorkflowRecord

func ParseWorkflowRecord(raw json.RawMessage) (WorkflowRecord, error)

ParseWorkflowRecord reads a kept record; nothing kept is an empty one.

func (*WorkflowRecord) Current

func (r *WorkflowRecord) Current() WorkflowVersion

Current is the current version; zero before Follow.

func (*WorkflowRecord) MarkRev

func (r *WorkflowRecord) MarkRev(at int64, version int, rev string) bool

MarkRev puts the named version a move was made on in its journal entry (the one at at, of that version); it says whether there was one.

type WorkflowState

type WorkflowState struct {
	Version  int               `json:"version"`
	Hash     string            `json:"hash"`
	Status   WorkflowStatus    `json:"status"`
	Statuses []WorkflowStatus  `json:"statuses"`
	Moves    []WorkflowMove    `json:"moves"`
	Role     string            `json:"role"`
	Journal  []WorkflowEntry   `json:"journal"`
	Versions []WorkflowVersion `json:"versions"`
}

WorkflowState is what a view and the agent are told: the current version, its status, the moves and the journal.

type WorkflowStatus

type WorkflowStatus struct {
	ID    string `json:"id"`
	Title string `json:"title"`
	Edit  bool   `json:"edit,omitempty"`
	Tone  string `json:"tone,omitempty"`
}

WorkflowStatus is one status. Tone is how the host may colour it: neutral, info, warning, success, danger.

type WorkflowTransition

type WorkflowTransition struct {
	From  string `json:"from"`
	To    string `json:"to"`
	Title string `json:"title"`
	Role  string `json:"role,omitempty"`
}

WorkflowTransition is a move from one status to another; Role is the least project role that may make it (view, comment, edit, manage, owner; edit when empty).

type WorkflowVersion

type WorkflowVersion struct {
	N      int    `json:"n"`
	Hash   string `json:"hash"`
	Status string `json:"status"`
}

WorkflowVersion is a version of the document with its status.

Jump to

Keyboard shortcuts

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