agent

package
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: Apache-2.0 Imports: 27 Imported by: 1 module, 0 packages

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

Documentation

Overview

Package agent is the contract between the hopsesh core and its agent modules. A module knows one coding agent (Claude Code, Codex, ...): where it keeps sessions, how they are listed, moved, resumed and converted. The core knows none of that; it owns all I/O, transport, safety, conversion and the user interfaces, and hands each module a Host.

A module is a Spec (data the core acts on before running module code) plus the Module interface, plus any optional capability interfaces it implements. Modules hold no state and never import os, os/exec, net, path/filepath or the core: everything goes through the Host, so every write is confined, journaled and undoable.

Index

Constants

View Source
const (
	HookTrusted     = "trusted"      // every hopsesh hook runs
	HookNeedsReview = "needs-review" // new or changed: the agent skips it until the user trusts it
	HookDisabled    = "disabled"     // the user turned a hopsesh hook off in the agent
	HookMissing     = "missing"      // the agent does not see (or does not load) the hook at all
	HookUnknown     = "unknown"      // the agent could not be asked
)

Hook trust states.

View Source
const (
	RemoteOn  = "on"
	RemoteOff = "off"
)

Remote Control states (LiveInfo.RemoteControl).

View Source
const (
	DefaultSQLMaxRows       = 100_000
	DefaultSQLMaxBytes      = 64 << 20
	DefaultSQLBatchMaxBytes = 128 << 20        // every statement of one Batch together
	DefaultSQLTimeout       = 30 * time.Second // one Query, Batch or Columns call
)

Default SQL limits: a long session's messages fit, a runaway query does not.

View Source
const ImageMark = "‹image›"

ImageMark stands for an image in preview text.

View Source
const MaxPreviewText = 1200

MaxPreviewText is the longest message text in a preview, in characters.

View Source
const MaxTitle = 200

MaxTitle is the longest title Rename accepts, in characters.

View Source
const NotePrefix = "[hopsesh] "

NotePrefix begins every message hopsesh itself adds to a conversation (a move's first prompt, a continuation's briefing). Session lists do not show such a message as the user's last prompt.

View Source
const RuntimeApp = "app"

RuntimeApp marks Install.Binary as the desktop app's bundled runtime.

View Source
const SpaceReserve = 256 << 20

SpaceReserve is kept free besides the bytes written, so a transfer never fills a disk.

Variables

View Source
var (
	ErrSignedOut       = errors.New("the agent is not signed in with the account its cloud needs")
	ErrNotEligible     = errors.New("plan or organization policy does not allow cloud sessions")
	ErrRepoUnsupported = errors.New("the cloud cannot clone or push this repository")
	// ErrNoEnvironment: the cloud has no environment of that name or id for this account,
	// or none at all (for clouds with NeedEnvironment).
	ErrNoEnvironment = errors.New("the cloud has no such environment")
	// ErrNoSession: a terminal step ended without starting a session and without a
	// refusal hopsesh knows (the user left it, or answered no). The user interfaces offer
	// to paste the session's link, in case one started that hopsesh did not see.
	ErrNoSession = errors.New("no cloud session started")
)

Errors a cloud capability returns, wrapped with detail; like the others, modules never invent other top-level kinds.

View Source
var (
	ErrNotInstalled    = errors.New("the agent is not installed there")
	ErrNotFound        = errors.New("session not found")
	ErrLive            = errors.New("the session is open")
	ErrUnsupported     = errors.New("not supported")
	ErrAccountMismatch = errors.New("signed in to a different account")
	ErrDiverged        = errors.New("both copies changed")
	ErrDenied          = errors.New("denied by the host")
	// ErrRestartsService is a resume that would restart the agent's background service,
	// which other windows share (OpenCode's, when no program of its version is here). A
	// person may agree: the caller asks, then resumes with ResumeOptions.RestartService.
	ErrRestartsService = errors.New("it would restart the agent's background service")
)

Errors a module returns, wrapped with detail. The user interfaces map each to a state; modules never invent other top-level kinds.

View Source
var CloudNameSyntax = regexp.MustCompile(`^[a-z][a-z0-9-]{1,31}$`)

CloudNameSyntax is what a cloud's name looks like: lower case letters, digits and dashes, no spaces (legacy title labels end the location at a space).

View Source
var ErrTooLarge = errors.New("more data than hopsesh reads at once")

ErrTooLarge is a query whose rows went over its limits.

Functions

func AnchorRel added in v0.9.0

func AnchorRel(agent ID, id SessionID) string

AnchorRel is where a virtual session's anchor file sits, relative to its install's main root (slash-separated): hopsesh/<agent>/sessions/<id>.jsonl. A module with VirtualSessions keeps Summary.Path there, so the core finds a session's anchor, and the lineage beside it, from the session's id alone (a notice hook gets no path).

func ApprovesHooks added in v0.9.0

func ApprovesHooks(m Module) bool

ApprovesHooks reports whether m runs a new hook only after the user approves it there.

func CapacityFor added in v0.4.0

func CapacityFor(ctx context.Context, m Module, h Host, in Install, s *Summary) (ir.Capacity, error)

func CheckClouds added in v0.4.0

func CheckClouds(m Module) error

CheckClouds checks a module's clouds the way the registry and the conformance kit do: every cloud has a name of CloudNameSyntax, driven by one of the Spec's binaries and declares what it carries each way; a module that implements a cloud capability declares at least one cloud.

func CheckRows added in v0.9.0

func CheckRows(r Rows, lim SQLLimits) error

CheckRows applies limits to rows read another way (a remote reader's JSON), whose Columns the reader fills in the query's order, repeats included.

func CheckSQLQuery added in v0.9.0

func CheckSQLQuery(q string, allow, deny []string) error

CheckSQLQuery checks a query's text before it reaches a database: one SELECT (or WITH, VALUES) that writes nothing, reads only tables in allow (and the names its leading WITH clause defines), and never mentions a table in deny. Names compare without regard to case. A quoted string where a table belongs, a WITH inside the query and a schema other than main are refused. It is a guard on the text; a Host also refuses reads below it where it can (SQLTableLimiter).

func CheckSpace added in v0.4.2

func CheckSpace(fsys FS, p string, need int64) error

CheckSpace refuses a write of need bytes at p when the filesystem reports too little free space (a LimitError naming the archive setting); unknown free space passes, and the atomic write still leaves existing files unchanged if it fails.

func CheckTitle added in v0.4.0

func CheckTitle(title string) (string, error)

CheckTitle validates a title given to Rename and returns it trimmed: it must not be empty, longer than MaxTitle, hold control characters or look like a label an older hopsesh wrote (it would be read as one).

func CompareVersions added in v0.5.0

func CompareVersions(a, b string) (int, bool)

CompareVersions orders two semantic versions by precedence: -1, 0 or 1, and ok=false when either does not parse. A pre-release is below its release (0.129.0-alpha < 0.129.0) and above every lower release (0.129.0 < 0.162.0-alpha.17.2).

func DirectlyIn added in v0.9.0

func DirectlyIn(in Install, root, p string, pa Path) bool

DirectlyIn reports whether p is a file directly in the folder of in's root ("" for the main root).

func EncodedPowerShellHook added in v0.4.0

func EncodedPowerShellHook(script string) string

EncodedPowerShellHook is a whitespace-only command launch usable under Codex's selected Windows shell (PowerShell, cmd fallback, or Git Bash). Encoding the fixed script avoids outer-shell expansion of paths, %, $, ! and embedded quotes. Explicit Text output avoids implicit CLIXML serialization by nested PowerShell.

func Expand

func Expand(p, home string, roots map[string]string, pa Path) string

Expand replaces a leading "~" with home and "{name}" with resolved roots.

func Has

func Has(m Module, c Capability) bool

Has reports whether a module has a capability.

func HookDirInterrupted added in v0.9.0

func HookDirInterrupted(fsys HookDirFS, pa Path, d *HookDir) bool

HookDirInterrupted reports whether a replace of the folder stopped between its two renames (a crash, or a failure on Windows): the folder is gone and its old copy waits in Staging. The next InstallHookDir or RemoveHookDir puts it back first.

func HookVersionAtLeast added in v0.4.0

func HookVersionAtLeast(version, minimum string) bool

HookVersionAtLeast is VersionAtLeast within minimum's major compatibility family: a new major version may change the vendor's hook or launch contract, so it fails closed until a module verifies it.

func InheritJSON added in v0.9.0

func InheritJSON(src []byte, fields []string) ([]byte, error)

InheritJSON picks settings out of a JSON (or JSONC, with comments) settings file for a new account folder: each field a dot path to one plain value ("model", "tui.theme"), kept at the same place, as plain JSON. Keys that name a credential (apiKey, token, password, headers, env, environment, …) are never copied: a field that is one is an error. A field whose value is an object or an array, or a string that looks like it carries a credential (a URL with a password or key, a known token form), is left out, since a credential can hide inside it under any name. It returns nil when none of the fields is copied. src is the default folder's file, which may hold credentials; only the picked values leave the call.

func InstallHookDir added in v0.9.0

func InstallHookDir(fsys HookDirFS, pa Path, d *HookDir) (bool, error)

InstallHookDir puts hopsesh's files in the folder (Merge) and reports whether it changed anything.

func InstallsViaVendor added in v0.9.0

func InstallsViaVendor(m Module) bool

InstallsViaVendor reports whether a module's sessions are installed by the agent itself.

func IsCloudCapability added in v0.4.0

func IsCloudCapability(c Capability) bool

IsCloudCapability reports whether c is one of the cloud capabilities.

func IsExperimental

func IsExperimental(m Module, c Capability) bool

IsExperimental reports whether a module marks a capability experimental.

func IsVirtual added in v0.9.0

func IsVirtual(m Module) bool

IsVirtual reports whether a module keeps virtual sessions.

func LegacyLabelPrefixes added in v0.4.2

func LegacyLabelPrefixes() []string

LegacyLabelPrefixes are the beginnings of every legacy label (for dropping an old label from a copy that moves on).

func LinkOn added in v0.4.0

func LinkOn(s string, hosts ...string) (*url.URL, bool)

LinkOn reads one link the user gave (a session's link, pasted): https on exactly one of hosts, with no user info and no port. A link without a scheme ("claude.ai/code/…") is read as https; plain http, another host, or a host before or after the named one is not a link here. A module reads a pasted link this way, never by cutting a prefix off a string.

func LinksIn added in v0.4.0

func LinksIn(text string, hosts ...string) []*url.URL

LinksIn returns the https links in a command's output whose host is exactly one of hosts: no other host before or after it, no user info, no port, and not inside another link (a link starts its word, after at most an opening bracket or quote). A module reads a cloud session's link from what its driver printed with it this way, never with a regular expression that could match a link to another host.

func NeedsVersion added in v0.5.0

func NeedsVersion(name, version, minimum string) string

NeedsVersion says why HookVersionAtLeast(version, minimum) failed, for people: "needs Codex 0.129.0 or newer; found 0.120.1".

func NoticeHookCommand added in v0.4.0

func NoticeHookCommand(bin string, id ID, profile string, args ...string) (string, error)

NoticeHookCommand quotes every argument; no hook payload is interpolated into the shell. The executable must be an absolute installed CLI path.

func NoticeHookPowerShellScript added in v0.4.0

func NoticeHookPowerShellScript(bin string, id ID, profile string, args ...string) (string, error)

NoticeHookPowerShellScript uses single-quoted literals (doubled apostrophes), explicitly passes UTF-8 stdin, and combines --profile= so Windows PowerShell 5.1 cannot discard an empty native argument. Suppress progress before any command can trigger first-use module initialization. Allocate the input buffer through .NET so the wrapper itself needs no cmdlet module. Genuine errors keep their stderr stream; no payload becomes script text.

func NoticeHookProgram added in v0.9.0

func NoticeHookProgram(b []byte, id ID) (string, bool)

NoticeHookProgram finds agent id's notice hook command (NoticeHookCommand, also inside a JSON string) in a hook file, and returns the program it runs.

func OwnText

func OwnText(text string) string

OwnText is the person's own part of a user message: "" for a message hopsesh added, and the text before hopsesh's note when one was added to the person's last message (a continuation's briefing joins it so that roles keep alternating).

func PathParts added in v0.4.0

func PathParts(u *url.URL) []string

PathParts are a link's path segments, without empty ones ("/a/b/" → a, b).

func PreviewText added in v0.4.0

func PreviewText(s string) string

PreviewText keeps Markdown structure for the inspector's safe renderer. It removes control sequences, hopsesh's own notes and images, and bounds the text at a word.

func PromptTitle added in v0.4.0

func PromptTitle(s string) string

PromptTitle returns a short title from a real prompt, excluding command and paste stubs.

func ReadHookDir added in v0.9.0

func ReadHookDir(fsys HookDirFS, pa Path, d *HookDir) (map[string][]byte, error)

ReadHookDir reads the folder's files (none when it does not exist).

func ReadNative added in v0.4.2

func ReadNative(ctx context.Context, fsys FS, p string) ([]byte, error)

ReadNative reads a whole native file (fork verification, write recovery, staged verification) within the operation's native file budget. A file over the budget is a LimitError naming the setting; nothing is read partially.

func RemoveHookDir added in v0.9.0

func RemoveHookDir(fsys HookDirFS, pa Path, d *HookDir) (bool, error)

RemoveHookDir takes hopsesh's files out (Remove, or the whole folder) and reports whether it changed anything.

func SQLTableFuncs added in v0.9.0

func SQLTableFuncs() []string

SQLTableFuncs are the table-valued functions a query may read from. A Host's authorizer allows reads of them (SQLite reports a read of json_each.value) on top of the module's tables.

func StagedKey

func StagedKey(f PlacedFile) string

StagedKey names a placed file in Module.Verify's staged map.

func SystemPrograms added in v0.9.0

func SystemPrograms() bool

SystemPrograms reports whether hopsesh may look for agent programs outside PATH and the home folder: in the system's program folders (/opt/homebrew/bin, /usr/local/bin), inside desktop apps, and on the login shell's PATH. A test must never run this machine's real agents, which share the person's real services and data, so it is false on a test machine (HOPSESH_APP_RUNTIMES=off, which every test binary sets; see init) and in any test binary, unless the test sets HOPSESH_APP_RUNTIMES=on or runs against the installed agents (HOPSESH_REAL_AGENTS=1).

func VersionAtLeast added in v0.5.0

func VersionAtLeast(version, minimum string) bool

VersionAtLeast reports whether version reaches minimum by semantic version precedence; a pre-release past the floor counts. An unknown or unparseable version fails closed.

func VersionLess added in v0.5.0

func VersionLess(a, b string) bool

VersionLess orders dotted versions for display and warnings: semantic version precedence when both parse, else numerically component by component (partial versions such as "0.153" included). Non-numeric suffixes in that fallback compare equal, as before.

func VersionOf

func VersionOf(line string) string

VersionOf extracts a dotted version ("2.1.284") from a --version line.

func WithListingHooks added in v0.4.1

func WithListingHooks(ctx context.Context, hooks ListingHooks) context.Context

Types

type Account

type Account struct {
	IsolationWhy string `json:"isolationWhy,omitempty"`
	LoggedIn     bool   `json:"loggedIn"`
	Provider     string `json:"provider,omitempty"`
	Email        string `json:"email,omitempty"`
	Confidence   string `json:"confidence,omitempty"` // verified, limited, unknown
	// Observation detects visible login changes; never proves account equality.
	Observation string `json:"observation,omitempty"`
	Key         string `json:"key"` // never sufficient for native cross-account replay
	// Person fingerprints the signed-in user within Key's account, when the agent's own
	// public identity file names one (Claude Code's accountUuid, Codex's user id).
	Person string `json:"person,omitempty"`
	Label  string `json:"label,omitempty"` // for people: "Max plan", "Team org"
	// RemoteControl is whether this login can use the agent's own remote control.
	RemoteControl bool   `json:"remoteControl"`
	Why           string `json:"why,omitempty"` // why not
}

Account contains public vendor login metadata, never credentials. Key is legacy Remote Control ownership metadata; it does not prove cross-profile identity.

type AccountPrep added in v0.9.0

type AccountPrep struct {
	// Taken are the ports other account folders on the machine were given.
	Taken []int
	// Free reports whether nothing listens on a port of the machine now (nil: unknown).
	Free func(port int) bool
}

AccountPrep is what hopsesh knows of the machine for PrepareAccount.

type AccountPrepared added in v0.9.0

type AccountPrepared struct {
	Port int // its background service's port; 0 none
}

AccountPrepared is what PrepareAccount set up, recorded with the folder.

type AccountPreparer added in v0.9.0

type AccountPreparer interface {
	PrepareAccount(ctx context.Context, h Host, in Install, o AccountPrep) (AccountPrepared, error)
}

AccountPreparer readies an account folder hopsesh has just made for the agent, before anyone signs in to it: h runs commands with the folder's variables (in.Profile is the new folder's). OpenCode gives the folder its own background-service port, so its service can run beside the default one. It returns what to record with the folder.

type AccountProber

type AccountProber interface {
	Account(ctx context.Context, h Host, in Install) (Account, error)
}

AccountProber identifies the login the agent uses on a machine, without reading credentials.

type Adopt added in v0.4.0

type Adopt struct {
	Root    string
	Dir     string
	Since   time.Time
	Session SessionID
}

Adopt says where a driver writes a session file: under the install's root Root, in folder Dir (root-relative, slash-separated), a file created after Since that names Session, or holds the vendor's own sign that it is a copy of it.

type Adoption added in v0.4.0

type Adoption struct {
	Session Summary
	// Remote is the cloud session it copies (the vendor's own picker chose it when the Adopt
	// named none).
	Remote SessionID
	// Restored is how many messages the copy holds; Expected, how many the vendor said it
	// restored, when it said (Stated).
	Restored int
	Expected int
	Stated   bool
	// Replies is how many of the restored messages are the agent's; First is the copy's
	// first user message, as it reads, so the core can check the copy begins where the
	// session began (the briefing hopsesh sent) when the vendor states no count.
	Replies int
	First   string
	// Title names the cloud conversation ("" : the copy's own title stands).
	Title string
}

Adoption is a session a driver wrote for a fetch.

type AppChecker added in v0.4.0

type AppChecker interface {
	CheckApp(Install, SessionKey, ResumeOptions) error
}

AppChecker validates an installation-specific desktop resume before it is offered or run.

type AppFocusVerifier added in v0.4.0

type AppFocusVerifier interface {
	VerifyAppFocus(context.Context, Host, Install, SessionKey) error
}

AppFocusVerifier rechecks ownership before a vendor focus route that could otherwise import a stale session ID. It is not needed for pure navigation URLs.

type AppendOptions

type AppendOptions struct {
	NewLine   bool // start on a new line if the file does not end with one
	KeepMtime bool // restore the modification time (marks must not look like activity)
	// Standalone: nothing written after these bytes builds on them (a title record, a
	// line in an index every session shares), so undo takes them out from between later
	// lines. Otherwise (a session's new turns) later lines continue from them, and undo
	// counts them as the file being used since.
	Standalone bool
}

AppendOptions control FS.Append.

type Binary

type Binary struct {
	Name string // "claude"
	// Candidates are extra places to look besides PATH, by GOOS ("*" for all); "~" is the
	// home folder.
	Candidates  map[string][]string
	VersionArgs []string // ["--version"]
}

Binary is a program the module may run.

type BinaryFact

type BinaryFact struct {
	Path    string `json:"path"`
	Version string `json:"version,omitempty"` // first line of VersionArgs output
}

BinaryFact is a binary found on a machine.

type Bundle

type Bundle struct {
	Files []BundleFile `json:"files"`
	// Warnings are what the module wants a move's preview to say about the session (what
	// it cannot see or carry), as full sentences.
	Warnings []string `json:"warnings,omitempty"`
}

Bundle is every file of one session.

func (Bundle) Main

func (b Bundle) Main() (BundleFile, bool)

Main returns the bundle's main file.

type BundleFile

type BundleFile struct {
	Root     string      `json:"root"`
	Rel      string      `json:"rel"` // slash-separated
	Size     int64       `json:"size"`
	Role     FileRole    `json:"role"`
	Rewrite  RewriteKind `json:"rewrite"`
	Growable bool        `json:"growable,omitempty"` // may still be appended to while copied
	// Virtual: the module makes the file's bytes (Materializer) from a session the agent
	// keeps elsewhere, in a database; nothing at Root/Rel is read for it. Size is then an
	// estimate.
	Virtual bool `json:"virtual,omitempty"`
}

BundleFile is one file of a session, relative to a root of its install.

type Capability

type Capability string

Capability names something a module can do beyond the required interface.

const (
	CapLive          Capability = "live"           // LiveDetector
	CapStop          Capability = "stop"           // Stopper
	CapAccount       Capability = "account"        // AccountProber
	CapSanitize      Capability = "sanitize"       // Sanitizer: same-agent move to another account
	CapPostInstall   Capability = "post-install"   // PostInstaller
	CapRead          Capability = "read"           // Reader: a conversion source
	CapWrite         Capability = "write"          // Writer: a conversion target
	CapNativeReplay  Capability = "native-replay"  // Writer renders tool calls natively (Profile.NativeReplay)
	CapIntegrate     Capability = "integrate"      // Integrator: skill and approval rules
	CapFork          Capability = "fork"           // Resume honours ResumeOptions.Fork (Spec.Features)
	CapRemoteControl Capability = "remote-control" // Resume honours ResumeOptions.RemoteControl (Spec.Features)
	CapApp           Capability = "app"            // Resume honours ResumeOptions.App (Spec.Features)
	CapImport        Capability = "import"         // Importer: the agent converts another agent's sessions itself
	CapPreview       Capability = "preview"        // Previewer: the end of a conversation, for the app
	CapRename        Capability = "rename"         // Renamer: a new title in the agent's own data
)
const (
	CapCloudList    Capability = "cloud-list"    // CloudLister
	CapCloudSend    Capability = "cloud-send"    // CloudSender
	CapCloudFetch   Capability = "cloud-fetch"   // CloudFetcher
	CapCloudFollow  Capability = "cloud-follow"  // CloudFollower
	CapCloudArchive Capability = "cloud-archive" // CloudArchiver
)

Cloud capabilities. Each is carried out by running the cloud's Driver through Host.Exec on the machine running hopsesh.

const CapChangeDir Capability = "change-dir"

CapChangeDir is DirChanger: a session continued in another folder on the same machine and account profile.

func Capabilities

func Capabilities(m Module) []Capability

Capabilities lists what a module can do, from the interfaces it implements and the features its Spec declares.

type Cloud added in v0.4.0

type Cloud struct {
	Name   string // the location name: "codex-cloud"
	Title  string // for people: "Codex cloud"
	Driver string // the Spec binary that holds the login and runs the cloud verbs: "codex"
	// Tested lists the driver versions the cloud verbs were tested with, as version
	// prefixes (Spec.Tested's form).
	Tested []string
	// Hosts are the repository hosts the cloud can clone from and push to: "github.com".
	Hosts []string
	Up    Fidelity // a conversation going up: FidBrief everywhere today
	Down  Fidelity // coming down to the same agent here: FidNative, FidCode, FidText
	// CodeUp and CodeDown are how code travels each way, preferred first.
	CodeUp   []CodeWay
	CodeDown []CodeWay
	Needs    []Need
	// VendorPrefix starts the names of the branches the cloud's agent pushes ("claude/").
	// Brought home, such a branch is renamed under hopsesh/from/<cloud>/ (unless the user
	// turned that off).
	VendorPrefix string
	// Problems are upstream issues that explain a fetch's known failures, by outcome
	// ("partial", "empty"), for the user interfaces to point to.
	Problems map[string]string
	// Unset are environment variables the driver must not inherit: a marker that makes it
	// save nothing (a nested session's), or an API key that would take the place of the
	// subscription login. The core removes them from every run of the cloud capabilities
	// and from a command the user runs (Fetched.Run).
	Unset []string
	// Noun is what the vendor calls one of its sessions, for people ("task"); "" is
	// "session".
	Noun string
	// Limits are parts of the vendor's cloud the driver cannot reach, in short sentences
	// the user interfaces show beside the cloud (the hand-off menu, its card, `hopsesh clouds
	// test`), so a missing path is said, never faked.
	Limits []string
	// Summary: a cloud whose Down is FidCode still brings the task's own words back (its
	// title and what came of it, in Fetched.Segment), which the core writes as a local
	// session beside the code.
	Summary bool
	// EnvHint says how the user makes an environment, for a cloud with NeedEnvironment
	// ("open `codex cloud` once to create one").
	EnvHint string
	// BriefBranch: the driver cannot choose the branch a new session starts from (the cloud
	// clones the repository's default branch, or one hopsesh cannot name), so the core's
	// briefing asks the cloud agent to check out the handoff branch first, and the plan says
	// so.
	BriefBranch bool
	// NoFollowUp says, for people, why hopsesh sends this cloud's sessions no follow-up
	// and where the user can ("Claude Code has no command that sends one without its own
	// terminal session; open the session on claude.ai to write to it"). The user interfaces
	// show it in place of a follow-up. "" for a cloud whose module is a CloudFollower, or
	// where nothing needs saying.
	NoFollowUp string
	// SignIn are the arguments, after Driver, of the driver's own sign-in command
	// (["auth", "login"]): the app runs it in a sign-in tab the user answers, which
	// hopsesh never reads or records. Empty: the app offers no Sign in button.
	SignIn []string
	Watch  Watch
}

Cloud is one vendor cloud a module reaches, declared as data in Spec.Clouds: what the core may promise, and what the drift check watches.

func (Cloud) SessionNoun added in v0.4.0

func (c Cloud) SessionNoun() string

SessionNoun is what a cloud calls its sessions ("session" unless it says).

func (Cloud) TestedWith added in v0.4.0

func (c Cloud) TestedWith(version string) bool

TestedWith reports whether a driver version matches one of the cloud's tested version prefixes.

type CloudAdopter added in v0.4.0

type CloudAdopter interface {
	// Adopted returns the session, or ErrNotFound while the driver has not written it.
	Adopted(ctx context.Context, h Host, in Install, a Adopt) (Adoption, error)
}

CloudAdopter finds the session a driver wrote for a fetch once it is there (Fetched.Adopt), so the core can journal it and tell a complete copy from a partial one. A module whose FetchCloud returns an Adopt implements it.

type CloudArchiver added in v0.4.0

type CloudArchiver interface {
	Archive(ctx context.Context, h Host, in Install, id SessionID) error
}

CloudArchiver archives a cloud session (Jules, Devin, Cursor; not the Claude Code or Codex CLIs).

type CloudCheck added in v0.4.0

type CloudCheck struct {
	OK   bool   `json:"ok"`
	Text string `json:"text"`
}

CloudCheck is one finding of a probe.

type CloudFetcher added in v0.4.0

type CloudFetcher interface {
	FetchCloud(ctx context.Context, h Host, in Install, id SessionID, t FetchTarget) (Fetched, error)
}

CloudFetcher brings a cloud session to this machine (Claude Code's teleport, codex cloud apply, jules remote pull).

type CloudFollower added in v0.4.0

type CloudFollower interface {
	FollowUp(ctx context.Context, h Host, in Install, id SessionID, text string) (CloudSession, error)
}

CloudFollower sends a follow-up message to a cloud session (fakecloud remote message; none of the vendors' CLIs hopsesh drives has a non-interactive one as of 2026-10).

type CloudLink struct {
	Cloud string    `json:"cloud"`
	ID    SessionID `json:"id"`
	URL   string    `json:"url,omitempty"`
	// Account is the module's fingerprint of the account that owns it, when recorded.
	Account string `json:"account,omitempty"`
}

CloudLink is the vendor's cloud copy of a session that runs on a machine (Claude Code's Remote Control keeps one on claude.ai while it is connected).

type CloudLinker added in v0.4.0

type CloudLinker interface {
	ParseCloudLink(s string) (cloud string, id SessionID, ok bool)
	CloudURL(cloud string, id SessionID) string
}

CloudLinker reads a cloud session's link or id as the vendor shows it ("Paste a link"), and makes its page's link.

type CloudLister added in v0.4.0

type CloudLister interface {
	ListCloud(ctx context.Context, h Host, in Install, q CloudQuery) (CloudListing, error)
}

CloudLister lists a cloud's sessions (codex cloud list --json, gh agent-task list).

type CloudListing added in v0.4.0

type CloudListing struct {
	Sessions []CloudSession
	// Partial: the vendor cannot list everything (Claude Code has no list command), so
	// these are the sessions the module could find; the vendor's own picker has the rest.
	Partial bool
	Errors  []SessionError
}

CloudListing is the result of ListCloud. One unreadable session goes in Errors.

type CloudQuery added in v0.4.0

type CloudQuery struct {
	Cloud string
	Repo  string // only this repository's sessions ("" for all)
	// Known are ids hopsesh recorded for this cloud (lineage): refresh them even
	// when the vendor's own listing leaves them out.
	Known []SessionID
	// Local are the module's sessions on this machine from the same scan, so a module can
	// find mirrors among them (Summary.Mirror) without listing again; nil: it lists them
	// itself when it needs them.
	Local []Summary
	Limit int
	// Env lists only the sessions of one of the vendor's environments ("" for all).
	Env string
}

CloudQuery narrows a cloud listing.

type CloudSender added in v0.4.0

type CloudSender interface {
	SendCloud(ctx context.Context, h Host, in Install, r SendRequest) (Sent, error)
}

CloudSender starts a cloud session from a briefing and code the core prepared (codex cloud exec, gh agent-task create), or says what the user runs to start it where the driver needs a terminal (claude --cloud "<briefing>").

type CloudSession added in v0.4.0

type CloudSession struct {
	// Key's Agent is the module; Session is the vendor's id ("session_01…", "task_e_…").
	Key   SessionKey `json:"key"`
	Cloud string     `json:"cloud"` // the cloud's name
	URL   string     `json:"url,omitempty"`
	Title string     `json:"title,omitempty"`
	// Repo is the repository's identity: host/owner/repo.
	Repo     string     `json:"repo,omitempty"`
	Branch   string     `json:"branch,omitempty"`
	Base     string     `json:"base,omitempty"` // the commit the cloud started from, when known
	PR       string     `json:"pr,omitempty"`
	State    CloudState `json:"state"`
	Updated  time.Time  `json:"updated"`
	Attempts int        `json:"attempts,omitempty"`
	// Mirror: a local session mirrored to the vendor (Remote Control), not a cloud run.
	Mirror bool `json:"mirror,omitempty"`
	// Local is the session a Mirror mirrors, on the machine running hopsesh.
	Local SessionID `json:"local,omitempty"`
	// Account is the module's fingerprint of the account that owns the session (Account.Key's
	// form), when the module knows it.
	Account string `json:"account,omitempty"`
	// Env and EnvLabel are the vendor's environment the session runs in (its id, and its
	// name for people), for clouds that need one.
	Env      string `json:"env,omitempty"`
	EnvLabel string `json:"envLabel,omitempty"`
	// Changes sums up the code the session changed, as the vendor reports it
	// ("+12 −3 · 2 files").
	Changes string `json:"changes,omitempty"`
}

CloudSession is one session in a vendor's cloud.

type CloudState added in v0.4.0

type CloudState string

CloudState is a cloud session's state, in the vendor's terms mapped to these.

const (
	CloudRunning  CloudState = "running"
	CloudIdle     CloudState = "idle" // waiting for the user (a Claude Code cloud session stays open)
	CloudDone     CloudState = "done"
	CloudFailed   CloudState = "failed"
	CloudArchived CloudState = "archived"
	CloudUnknown  CloudState = "unknown"
)

type CloudStepReader added in v0.4.0

type CloudStepReader interface {
	ReadStep(cloud string, out StepOutput) (CloudSession, error)
}

CloudStepReader reads the session a terminal step started (a SendCloud's Sent.Run) from what it printed, or maps its refusal onto the cloud sentinels. A step that printed no session and no refusal returns an error that says what was seen.

type CloudTest added in v0.4.0

type CloudTest struct {
	Account string       `json:"account,omitempty"` // the login, for people: "claude.ai · max"
	Checks  []CloudCheck `json:"checks"`
}

CloudTest is what a probe found.

type CloudTester added in v0.4.0

type CloudTester interface {
	TestCloud(ctx context.Context, h Host, in Install, cloud string) (CloudTest, error)
}

CloudTester probes a cloud through its driver without changing anything or starting a model turn: the login it uses, and that the driver still has what the module relies on. A login the cloud cannot use returns ErrSignedOut or ErrNotEligible, with the checks so far.

type CodeResult added in v0.4.0

type CodeResult struct {
	Way    CodeWay `json:"way,omitempty"`
	Branch string  `json:"branch,omitempty"` // the cloud's branch (ViaBranch, ViaPR)
	PR     string  `json:"pr,omitempty"`
	// Diff is a unified diff the core applies and commits on a hopsesh branch (ViaDiff),
	// unless the driver applied it in FetchTarget.Dir itself (Applied).
	Diff    []byte `json:"-"`
	Applied bool   `json:"applied,omitempty"`
}

CodeResult is the code a fetch brought.

type CodeWay added in v0.4.0

type CodeWay string

CodeWay is how code travels between a machine and a cloud.

const (
	ViaBranch       CodeWay = "branch"        // a pushed branch the cloud clones, or pushes back
	ViaBundle       CodeWay = "bundle"        // the driver uploads the repository itself (Claude Code's git bundle)
	ViaStartingDiff CodeWay = "starting-diff" // a patch sent with the task (Codex's CODEX_STARTING_DIFF)
	ViaPR           CodeWay = "pr"            // a pull request the cloud opened
	ViaDiff         CodeWay = "diff"          // the driver prints or applies a unified diff
)

type Command

type Command struct {
	// TTY requests a transient pseudo-terminal for a short-lived desktop launcher.
	// It never creates a visible tab or sends input; the caller waits for completion.
	TTY bool `json:"tty,omitempty"`
	// Wait requests error reporting from a short-lived desktop launcher.
	Wait bool     `json:"wait,omitempty"`
	Argv []string `json:"argv"`
	Dir  string   `json:"dir"`
	// Unset are environment variables the program must run without (a cloud driver's
	// Cloud.Unset); the core leaves them out of the shell line and the process.
	Unset []string `json:"unset,omitempty"`
	// Env are variables ("NAME=value") the program runs with on top of the user's
	// (CCR_FORCE_BUNDLE=1); never a credential.
	Env []string `json:"env,omitempty"`
}

Command is a program to run, never a shell string; the core quotes it for the user's shell.

type ContextSizer added in v0.4.0

type ContextSizer interface {
	ContextCapacity(context.Context, Host, Install, *Summary) (ir.Capacity, error)
}

ContextSizer measures the destination's active context using its native semantics. A nil session resolves capacity for a new conversation on this host/account.

type Desktop added in v0.9.0

type Desktop struct {
	// Tool names the app beside the agent's command-line tool ("Claude desktop", "Codex
	// app").
	Tool string
	// Product is the app as it names itself, before its version ("Claude desktop",
	// "ChatGPT desktop").
	Product string
	// OwnSignIn: the app keeps a sign-in of its own (Install.DesktopAccount) and its
	// sessions go in the main root's default folder, whatever the environment says (Claude
	// desktop). Otherwise it shares that folder's sign-in with the terminal (the Codex app).
	OwnSignIn bool
	// Shared: one app process runs every session, so the app is shown and opened, never
	// quit (the Codex app).
	Shared bool
}

Desktop is an agent's desktop app as the user interfaces show it.

type DirChangeHelp added in v0.9.0

type DirChangeHelp interface {
	ChangeDirHelp() (how, undo string)
}

DirChangeHelp tells people how a module's agent changes a session's folder (how) and how undo puts it back (undo), each a phrase ("Claude Code's files move back"). Optional, beside DirChanger.

type DirChanger added in v0.6.2

type DirChanger interface {
	// PlanChangeDir says what moving s to dir (an absolute, symlink-resolved folder) does.
	// It only reads through h.
	PlanChangeDir(ctx context.Context, h Host, in Install, s Summary, dir string) (DirPlan, error)
	// ChangeDir carries the plan out through h: files through h.FS (journaled), or the
	// agent's own program (DirAgent).
	ChangeDir(ctx context.Context, h Host, in Install, s Summary, p DirPlan) error
	// InSession is what to type in the open session to change its folder the agent's own
	// way, keeping the session ("/cd <dir>"), or "" when the agent cannot do that without
	// starting another session.
	InSession(in Install, dir string) string
}

DirChanger continues a session in another working directory on the same machine and account profile, keeping the session itself: its id and every record the agent wrote. Each module does it the way its agent's own folder change does.

type DirMethod added in v0.6.2

type DirMethod string

DirMethod is how a module changes a session's folder.

const (
	// DirRecord: hopsesh writes what the agent's own folder change writes (files moved,
	// records appended), journaled, so undo reverses it byte for byte.
	DirRecord DirMethod = "record"
	// DirAgent: the agent's own program records the change; undo changes the folder back.
	DirAgent DirMethod = "agent"
)

type DirPlan added in v0.6.2

type DirPlan struct {
	From   string    `json:"from"` // the folder the session is in now
	To     string    `json:"to"`
	Method DirMethod `json:"method"`
	// Moves are the session's files that move (absolute paths on its machine); the first
	// is the main file when it moves.
	Moves []FileMove `json:"moves,omitempty"`
	// Main is the main file's path afterwards.
	Main     string   `json:"main"`
	Records  []string `json:"records,omitempty"` // what is added, in words
	Notes    []string `json:"notes,omitempty"`
	Warnings []string `json:"warnings,omitempty"`
	Blockers []string `json:"blockers,omitempty"`
}

DirPlan is what changing a session's folder does.

type ElemMatch

type ElemMatch struct {
	Array  string   `json:"array"` // "message.content"
	Field  string   `json:"field"`
	Values []string `json:"values"`
}

ElemMatch matches elements of the array at Array (dot path) by a string field.

type EnvSub added in v0.9.0

type EnvSub struct {
	Env string `json:"env"` // "XDG_DATA_HOME"
	Sub string `json:"sub"` // "opencode", slash-separated
}

EnvSub is a variable that names a folder the root is inside (XDG base directories).

type Exec

type Exec interface {
	Run(ctx context.Context, argv []string, o RunOptions) (Result, error)
}

Exec runs the module's Spec binaries on the machine.

type FS

type FS interface {
	Stat(p string) (fs.FileInfo, error)
	ReadDir(p string) ([]fs.FileInfo, error)
	Open(p string) (File, error)
	// RealPath resolves symbolic links (agents key sessions by the real working directory).
	RealPath(p string) (string, error)
	// ReadFile reads a whole file, failing if it is larger than limit bytes.
	ReadFile(p string, limit int64) ([]byte, error)
	// WriteFile replaces a file atomically, creating parent folders. Journaled.
	WriteFile(p string, b []byte, perm fs.FileMode) error
	// Append adds bytes at the end of a file, creating it (and parent folders) when it does
	// not exist. Journaled: undo takes out these bytes, and refuses while anything follows
	// them unless they are Standalone.
	Append(p string, b []byte, o AppendOptions) error
	// Rename moves a file within the module's roots. Journaled.
	Rename(from, to string) error
}

FS is a machine's filesystem, with that machine's absolute paths.

type Facts

type Facts struct {
	DesktopProtocols map[string]bool `json:"desktopProtocols,omitempty"`
	Machine          string          `json:"machine"` // the name hopsesh knows it by
	Local            bool            `json:"local"`   // this machine
	OS               string          `json:"os"`      // darwin | linux | windows
	Arch             string          `json:"arch"`
	Home             string          `json:"home"`
	// Env holds the variables the module's Spec declares (Roots[].Env, LoginEnv),
	// with pinned profile roots applied ("" when unset).
	Env map[string]string `json:"env"`
	// UserEnv preserves the declared machine environment before profile scoping.
	// Nil means Env has not been scoped. Detection can distinguish a user's
	// explicit config override from a root injected for a pinned profile.
	UserEnv map[string]string `json:"userEnv,omitempty"`
	// Binaries are the module's Spec binaries as found there.
	Binaries map[string]BinaryFact `json:"binaries"`
}

Facts is what the core learned about a machine in one probe.

type Feed added in v0.4.0

type Feed struct {
	Kind FeedKind
	URL  string // markdown and feed
	Repo string // releases: "openai/codex"
	Tag  string // releases: the tag's prefix before the version ("rust-v")
}

Feed is one changelog or release feed.

type FeedKind added in v0.4.0

type FeedKind string

FeedKind is how the drift check reads a feed.

const (
	FeedMarkdown FeedKind = "markdown" // a CHANGELOG.md, cut at the tested version
	FeedRSS      FeedKind = "feed"     // RSS or Atom: the items since the last run
	FeedReleases FeedKind = "releases" // a GitHub repository's releases since Tag+tested
)

type FetchTarget added in v0.4.0

type FetchTarget struct {
	// Dir is a worktree the core made on the cloud's branch, so the user's own checkout
	// stays as it is.
	Dir  string
	Code CodeWay
}

FetchTarget is where a fetched session lands.

type Fetched added in v0.4.0

type Fetched struct {
	Code CodeResult
	// Run is a command the user runs in a terminal when the driver needs one
	// (claude --teleport <id>).
	Run *Command
	// Adopt is where the driver writes a native session, so the core can journal it.
	Adopt *Adopt
	// Segment is the conversation in the IR when no native copy exists (text-only clouds).
	Segment *ir.Segment
	// Expected is how many messages the vendor says it restored, when it says, so the core
	// can tell a partial copy (Claude Code 2.1.289's teleport says nothing).
	Expected int
	// Loss names what stays in the cloud: "tool calls stay in the cloud".
	Loss []string
	// Note is what the user must do in Run's terminal for the copy to be saved ("Claude
	// Code saves its copy only after you send a message in it"), shown with the command.
	Note string
}

Fetched is what a fetch brought, or what the user must run to bring it.

type Fidelity added in v0.4.0

type Fidelity string

Fidelity is how much of a conversation survives one direction between a cloud and a machine. Each cloud declares it per direction, so the core can promise it before any module code runs.

const (
	FidNative Fidelity = "native" // the vendor's own copy of the conversation (Claude Code's teleport)
	FidText   Fidelity = "text"   // messages, perhaps the plan and shell output; no native tool calls
	FidCode   Fidelity = "code"   // the code and the task's title and summary; no conversation
	FidBrief  Fidelity = "brief"  // a briefing in the first prompt (every upload, as of 2026)
	FidNone   Fidelity = "none"   // nothing goes this way
)

type FieldMatch

type FieldMatch struct {
	Field    string   `json:"field"` // a dot path into the record ("payload.type")
	Values   []string `json:"values,omitempty"`
	Prefixes []string `json:"prefixes,omitempty"`
}

FieldMatch matches a record by a top-level string field: equal to one of Values, or starting with one of Prefixes.

type File

type File interface {
	io.Reader
	io.ReaderAt
	io.Closer
	Stat() (fs.FileInfo, error)
}

File is an open file with random access.

type FileMove added in v0.6.2

type FileMove struct {
	From string `json:"from"`
	To   string `json:"to"`
}

FileMove is a file moved from one path to another.

type FileRole

type FileRole string

FileRole says what a bundle file is.

const (
	RoleMain FileRole = "main" // the session transcript the agent resumes
	RoleSide FileRole = "side" // anything else the session needs (subagents, tool output, history)
)

type FormatError

type FormatError struct {
	Path string
	Line int // 1-based, 0 when unknown
	Err  error
}

FormatError is native data a module could not read.

func (*FormatError) Error

func (e *FormatError) Error() string

func (*FormatError) Unwrap

func (e *FormatError) Unwrap() error

type HookApprover added in v0.9.0

type HookApprover interface {
	ApprovesHooks()
}

HookApprover marks an agent that runs a new or changed hook only after the user approves it in the agent (Codex reviews each hook definition and skips it silently until trusted). Approving stays in the agent's own review UI; hopsesh only reports it. Where the agent cannot be asked (a machine read over SSH), such a hook's state is unknown. An agent that reports trust without an approval step (OpenCode) does not implement it.

type HookDir added in v0.9.0

type HookDir struct {
	// Root names the Spec root the folder is inside ("" for the main root); Path is the
	// folder, anywhere inside that root's folder.
	Root string
	Path string
	// Staging is where the new and old copies wait while the folder is replaced: a folder
	// inside the same root, outside Path, that the agent does not scan for plugins (not
	// beside Path in plugins/). Required.
	Staging string
	// Merge returns the folder's files with hopsesh's installed, from what is there now
	// (empty when there is no folder).
	Merge func(existing map[string][]byte) (map[string][]byte, error)
	// Remove returns what stays after hopsesh's are taken out; nil or empty removes the
	// folder. A nil Remove always removes it.
	Remove func(existing map[string][]byte) (map[string][]byte, error)
	// Has reports whether the folder runs this hopsesh, with these arguments.
	Has func(existing map[string][]byte) bool
	// Runs returns the program the folder's notice hook runs, whatever its arguments, as
	// HookFile.Runs.
	Runs func(existing map[string][]byte) (program string, ok bool)
}

HookDir is a folder hopsesh owns whole, holding several files: an agent plugin ({config}/plugins/hopsesh) rather than entries in a shared settings file. Its functions are pure, over the folder's files by slash-separated path. InstallHookDir and RemoveHookDir build the new folder aside and swap it in with renames, so the agent never loads a half-written one. The caller holds the machine's hook lock around them: two at once would share the staging copies.

func (*HookDir) In added in v0.9.0

func (d *HookDir) In(in Install, pa Path) bool

In reports whether the folder is inside its root's folder of in, and its Staging is in that root too and not inside the folder.

type HookDirFS added in v0.9.0

type HookDirFS interface {
	ReadDir(p string) ([]fs.FileInfo, error)
	ReadFile(p string, limit int64) ([]byte, error)
	WriteFile(p string, b []byte, perm fs.FileMode) error
	MkdirAll(p string) error
	Rename(from, to string) error
	RemoveAll(p string) error
}

HookDirFS is the filesystem a HookDir is read and replaced through, with that machine's paths. WriteFile creates parent folders; Rename moves a folder. ReadDir describes a symbolic link as a link (Lstat), never as what it points to, so a link is refused rather than copied.

type HookFile added in v0.4.0

type HookFile struct {
	// Root names the Spec root the file sits directly in ("" for the main root): the only
	// place the app edits it.
	Root   string
	Path   string
	Merge  func([]byte) ([]byte, error)
	Remove func([]byte) ([]byte, error)
	Has    func([]byte) bool
	// Runs finds this agent's notice hook in the file whatever its arguments, and returns
	// the program it runs: how another machine's hook is checked from here, where the
	// exact arguments hopsesh there used are unknown. nil: only Has is known.
	Runs func([]byte) (program string, ok bool)
}

HookFile edits only hooks owned by this integration in a shared vendor file. All functions are pure; the app owns bounded local reads and atomic writes.

func JSONMovementHookFile added in v0.4.0

func JSONMovementHookFile(path, command string) *HookFile

JSONMovementHookFile implements the shared command-hook JSON schema used by Claude and Codex. Keeping unknown values as RawMessage avoids numeric rounding or dropping future vendor fields. Only exact generated handlers are removed.

func JSONMovementHookFileWithHandler added in v0.4.0

func JSONMovementHookFileWithHandler(path string, handler map[string]any) *HookFile

JSONMovementHookFileWithHandler retains module-owned shell and platform fields.

func (*HookFile) In added in v0.9.0

func (f *HookFile) In(in Install, pa Path) bool

In reports whether the file sits directly in its root's folder of in.

type HookIntegration added in v0.4.0

type HookIntegration struct {
	File *HookFile
	// Dir is a folder hopsesh owns whole (an agent plugin), for an agent whose hooks are
	// not entries in a shared file; nil when File is used.
	Dir            *HookDir
	Reason         string
	Evidence       string
	DisabledReason string // vendor setting prevents delivery; install/remove must preserve it
}

type HookTrust added in v0.4.2

type HookTrust struct {
	State  string   `json:"state"`
	Events []string `json:"events,omitempty"` // hooks in State (other than trusted)
	Fix    string   `json:"fix,omitempty"`    // what the user does, in the agent
	Detail string   `json:"detail,omitempty"`
	// Failures counts the hook's calls that failed and let the agent go on (a hook fails
	// open), where the agent keeps that count (OpenCode's plugin); Detail then says when
	// the last one was and why.
	Failures int `json:"failures,omitempty"`
	// Excluded marks a missing hook that the agent leaves out by its own settings (a
	// config entry or a policy removes OpenCode's plugin), or has not reloaded since it
	// was installed: installing it again does not change that. Another missing hook (one
	// that failed to load, or another of the same name runs) is installed again.
	Excluded bool `json:"excluded,omitempty"`
}

HookTrust is what the agent reports for the hopsesh hooks.

type HookTrustReporter added in v0.4.2

type HookTrustReporter interface {
	HookTrust(ctx context.Context, h Host, in Install, commands []string) HookTrust
}

HookTrustReporter is for agents that can say whether the hopsesh hooks they have installed actually run (Codex lists each hook with its trust; OpenCode lists the plugins it loaded). It asks the agent itself, never re-implementing its trust hash, and never trusts on the user's behalf.

type Host

type Host interface {
	Facts() Facts
	FS() FS
	Exec() Exec
	Path() Path
	Locks() Locks
	Procs() Procs
	Log() *slog.Logger
}

Host is a module's only way to reach a machine: this one, or another over SSH. The core confines it to the module's Spec: writes only under its roots (and journaled for undo), no reads of its Secrets, and only its Binaries run.

func Confine

func Confine(h Host, s Spec, in Install) Host

Confine wraps a Host so a module can write only under its install's roots, never opens its Spec's Secrets (paths, or patterns with * ? [), and runs only its Spec's Binaries. When the Host reads databases (SQLHost), the module reads only its Spec's SQLTables, from the files its SQLFiles name, which are Secrets for every other use. The core gives every module a confined Host; the conformance kit does the same.

type HostResumer added in v0.9.0

type HostResumer interface {
	ResumeOn(ctx context.Context, h Host, in Install, key SessionKey, p Placement, o ResumeOptions) (Command, error)
}

HostResumer is Resume for an agent whose resume command depends on the machine as it is now: it checks the session is there (OpenCode makes an empty session for an id it does not have) and picks the program to run (OpenCode's must be of its running background service's version, or it restarts that service). The core uses it, when a module has it, to resume a session already on this machine; a plan's command, made before the session is there, still comes from Resume.

type HostStarter added in v0.9.0

type HostStarter interface {
	StartProgram(ctx context.Context, h Host, in Install, restart bool) (string, error)
}

HostStarter picks the program a new session runs, for an agent whose program depends on the machine as it is now (OpenCode's TUI restarts its running background service when it is of another version). Without restart (the person agreed) a start that would restart the service is ErrRestartsService. The core uses it, when a module has it, for a new session on this machine; otherwise the program Detect found runs.

type ID

type ID string

ID names an agent module: lower case letters and digits, 2 to 16 characters.

type Icon

type Icon struct {
	// SVG is a mark drawn for hopsesh: a complete <svg> document with no scripts or
	// external references. It must not reproduce a vendor's logo or trademark.
	SVG string
	// Apps are where the agent's desktop app may be installed, by GOOS ("~" is the home
	// folder): a macOS .app bundle or a Windows .exe. Its icon is read from this machine
	// and never shipped.
	Apps map[string][]string
}

Icon pictures an agent. The installed desktop app's own icon comes first (unless the user turns that off), then the module's mark, then the agent's initials.

type IdentityFS added in v0.5.0

type IdentityFS interface {
	ReadIdentity(p string, pick func([]byte) (map[string]string, error)) (map[string]string, error)
}

IdentityFS reads public identity fields out of a credentials file on this machine. The file's bytes go only to pick, which returns the few fields it names (an account id, a user id, an email); nothing else leaves the call. A remote machine's credentials are never read: there it fails with ErrUnsupported.

type Importer

type Importer interface {
	CanImport(from ID) bool
	// Import converts the session file at path (on h's machine) into a new session of this
	// agent and returns its id. If validation fails after creation, return both its
	// id and an error so the core can adopt the file for undo without launching it.
	Import(ctx context.Context, h Host, in Install, from ID, path, cwd, title string) (SessionID, error)
}

Importer is the agent's own importer of another agent's sessions: it converts a native session file itself, an alternative to the core's conversion through Writer.

type Install

type Install struct {
	// NativeDefaultRoot is launch metadata verified by the module from the detected
	// machine's home and original environment. Empty means native config lookup is
	// unverified or explicitly overridden. It grants no filesystem access.
	NativeDefaultRoot string       `json:"nativeDefaultRoot,omitempty"`
	Accounts          *ProfileSpec `json:"-"`
	OS                string       `json:"os,omitempty"`
	Desktop           string       `json:"desktop,omitempty"`
	DesktopVersion    string       `json:"desktopVersion,omitempty"`
	DesktopWhy        string       `json:"desktopWhy,omitempty"`
	// DesktopAccount is who the desktop app is signed in as, when it keeps its own
	// sign-in (Claude desktop): its account and user fingerprints, never more.
	DesktopAccount *OwnerRun `json:"desktopAccount,omitempty"`
	// DesktopEngine is the version of the agent the desktop app runs, its own copy
	// (Claude desktop's Claude Code, the Codex app's codex).
	DesktopEngine string            `json:"desktopEngine,omitempty"`
	Profile       *RuntimeProfile   `json:"profile,omitempty"`
	Agent         ID                `json:"agent"`
	Version       string            `json:"version,omitempty"` // "" when the binary was not found
	Binary        string            `json:"binary,omitempty"`  // absolute path
	Runtime       string            `json:"runtime,omitempty"` // RuntimeApp: Binary is the desktop app's bundled runtime, no CLI
	Roots         map[string]string `json:"roots"`             // name → absolute path on that machine
	// MainRoot names the main root in Roots (Spec.MainRoot); see Main.
	MainRoot string `json:"mainRoot,omitempty"`
	Present  bool   `json:"present"` // the main root exists
}

Install is an agent as found on one machine.

func DefaultInstall

func DefaultInstall(s Spec, h Host) Install

DefaultInstall resolves a Spec's roots and first binary from a machine's facts.

func (Install) BindingID added in v0.4.0

func (in Install) BindingID() string

func (Install) Main added in v0.9.0

func (in Install) Main() string

Main returns the path of the main root. An install that does not name it (one decoded from an older peer) has a single root, which is the main one.

func (Install) ProfileEnv added in v0.4.0

func (in Install) ProfileEnv() []string

func (Install) ProfileID added in v0.4.0

func (in Install) ProfileID() string

func (Install) Root

func (in Install) Root(name string) string

Root returns the path of a named root.

func (Install) ScopeCommand added in v0.4.0

func (in Install) ScopeCommand(c Command) Command

ScopeCommand applies the profile last. Caller-supplied roots and inherited account overrides cannot redirect a managed launch into a sibling profile.

type InstallChecker added in v0.9.0

type InstallChecker interface {
	CheckInstall(ctx context.Context, h Host, in Install, version string) error
}

InstallChecker is a VendorInstaller that can tell, before anything changes on the target, that its agent there will not import a session last written by version (the agent version of the session moved, Summary.AgentVersion; "" when unknown). The core asks it before it sets aside the copy a move replaces, so a refusal leaves the target as it was. AfterInstall still checks the copy it imports.

type Integration

type Integration struct {
	SkillDir string    // folder that holds skills ("~/.claude/skills"); the skill goes in SkillDir/hopsesh
	Rules    *RuleFile // nil when the agent has no rules the core can manage
}

Integration is an agent's integration points.

type Integrator

type Integrator interface {
	Integration(h Host, in Install) Integration
}

Integrator says where the shared hopsesh skill goes for this agent, and how the agent is told which hopsesh commands may run without asking.

type LabelKind added in v0.4.2

type LabelKind string

LabelKind is what a legacy label said happened to a copy left behind.

const (
	LabelPrepared  LabelKind = "prepared"  // destination written; no inference claimed
	LabelMoved     LabelKind = "moved"     // the session moved to another location
	LabelContinued LabelKind = "continued" // the session continues in another agent
)

type LegacyLabel added in v0.4.2

type LegacyLabel struct {
	Kind     LabelKind `json:"kind"`
	Location string    `json:"location,omitempty"` // where it went: a machine's or a cloud's name
	Agent    ID        `json:"agent,omitempty"`    // the agent it continues in (LabelContinued)
	// AgentName is that agent's display name, as the label carried it (the core resolves
	// Agent from it).
	AgentName string `json:"agentName,omitempty"`
}

LegacyLabel is what a title label written by an older hopsesh said (StripLegacyLabel).

func StripLegacyLabel added in v0.4.2

func StripLegacyLabel(t string) (LegacyLabel, string, bool)

StripLegacyLabel splits a title an older hopsesh labelled into what the label said and the original title; ok is false for an ordinary title, which is returned as it is.

type Listing

type Listing struct {
	Sessions []Summary
	Errors   []SessionError
}

Listing is the result of Module.List.

type ListingHooks added in v0.4.1

type ListingHooks struct {
	Load  func(path, signature string) (*Summary, bool)
	Save  func(path, signature string, summary *Summary)
	Found func(Summary)
}

ListingHooks are supplied by the core for browsing only. Bundle, import and transfer validation never use this cache. Found may be called concurrently.

type LiveDetector

type LiveDetector interface {
	Live(ctx context.Context, h Host, in Install, ids []SessionID) (map[SessionID]LiveInfo, error)
}

LiveDetector reports which sessions are open right now.

type LiveInfo

type LiveInfo struct {
	State  Liveness `json:"state"`
	PID    int      `json:"pid,omitempty"`
	Status string   `json:"status,omitempty"` // agent words: "busy", "waiting for input"
	// App is true when the agent's own desktop app runs it (Claude Code in the Claude
	// app), not a terminal: there is no terminal tab to show.
	App bool `json:"app,omitempty"`
	// Procs are every process that has the session open (Claude Code can run one session
	// in several), PID among them; empty when the module can't say.
	Procs []LiveProc `json:"procs,omitempty"`
	// Name is the session's name as the running agent reports it (the Claude app names
	// sessions), "" when none.
	Name string `json:"name,omitempty"`
	// RemoteControl is whether a process has the session connected to the agent's
	// Remote Control (reachable from its website and phone app): RemoteOn, RemoteOff, or
	// "" when the agent doesn't say.
	RemoteControl string `json:"remoteControl,omitempty"`
	// RemoteURL is the page Remote Control reaches the session at, when it is on.
	RemoteURL string `json:"remoteUrl,omitempty"`
}

LiveInfo describes a live session.

type LiveProc added in v0.4.0

type LiveProc struct {
	ObservedAt time.Time `json:"observedAt,omitempty"` // registry evidence timestamp, not process start time
	PID        int       `json:"pid"`
	// App is true when the agent's desktop app runs it.
	App bool `json:"app,omitempty"`
	// Waiting is true when it waits for the person (a question, a permission).
	Waiting bool `json:"waiting,omitempty"`
	// RemoteControl is this process's Remote Control state, as LiveInfo.RemoteControl.
	RemoteControl string `json:"remoteControl,omitempty"`
}

LiveProc is one process that has a session open.

type Liveness

type Liveness string

Liveness says whether a session is open right now.

const (
	Live    Liveness = "live"
	Ended   Liveness = "ended"
	Unknown Liveness = "unknown"
)

type LocalIdentifier added in v0.5.0

type LocalIdentifier interface {
	LocalIdentity(root string, native bool) (OwnerRun, bool)
}

LocalIdentifier reads which account a root on this machine is signed in to now from the agent's own public identity record (never credentials, never by running the agent), fast enough for a prompt hook. native is true when the root is the agent's default, found without its override variable.

type Location added in v0.4.0

type Location struct {
	Kind LocationKind `json:"kind"`
	// Name is the machine's name, or the cloud's ("codex-cloud"). Cloud names match
	// CloudNameSyntax, so names in legacy title labels read back.
	Name string `json:"name"`
}

Location is where a session lives.

func CloudLocation added in v0.4.0

func CloudLocation(name string) Location

CloudLocation is a cloud's location.

func MachineLocation added in v0.4.0

func MachineLocation(name string) Location

MachineLocation is a machine's location.

func (Location) IsCloud added in v0.4.0

func (l Location) IsCloud() bool

IsCloud reports whether the location is a cloud.

func (Location) String added in v0.4.0

func (l Location) String() string

type LocationKind added in v0.4.0

type LocationKind string

LocationKind says what a location is.

const (
	AtMachine LocationKind = "machine" // this machine, one reached over SSH, or a peer's snapshot
	AtCloud   LocationKind = "cloud"   // a vendor's cloud, reached through its CLI
)

type LockState

type LockState string

LockState is what a lock probe found.

const (
	LockHeld    LockState = "held"
	LockFree    LockState = "free"
	LockUnknown LockState = "unknown"
)

type Locks

type Locks interface {
	Probe(ctx context.Context, paths []string) (map[string]LockState, error)
	// Holders returns the processes holding each lock file (none when it is free). A machine
	// that cannot tell returns ErrUnsupported.
	Holders(ctx context.Context, paths []string) (map[string][]int, error)
}

Locks probes advisory file locks without taking them.

type Mapping

type Mapping struct {
	From  string `json:"from"`
	To    string `json:"to"`
	ToSep string `json:"toSep,omitempty"` // also convert separators after a match ("/" or `\`)
}

Mapping replaces an absolute path prefix (as it appears on the source) with another.

type Materializer added in v0.9.0

type Materializer interface {
	Materialize(ctx context.Context, h Host, in Install, s Summary, f BundleFile) ([]byte, error)
}

Materializer makes the bytes of a session's Virtual bundle files: the session as the module's own file format (JSON lines), read from where the agent keeps it. The core stages, rewrites, packages and installs those bytes like any other file. A module with Virtual files implements it.

type Module

type Module interface {
	Spec() Spec

	// Detect turns the probe facts of a machine into an Install. Most modules return
	// DefaultInstall(spec, facts) with checks of their own.
	Detect(ctx context.Context, h Host) (Install, error)

	// List returns the sessions on the machine. One unreadable session goes in
	// Listing.Errors; only a failure to list at all returns an error.
	List(ctx context.Context, h Host, in Install) (Listing, error)

	// Bundle names the files that make up one session.
	Bundle(ctx context.Context, h Host, in Install, s Summary) (Bundle, error)

	// PlanMove places a bundle on the target (pure): where each file goes, how it is
	// rewritten, and records to append. src and dst are the same agent's installs.
	PlanMove(src, dst Install, s Summary, b Bundle, p Placement) (MovePlan, error)

	// Verify checks staged files (already rewritten, on the target machine) before they are
	// installed, for example that the session's working directory is the target's.
	Verify(ctx context.Context, h Host, mp MovePlan, staged map[string]string, p Placement) error

	// Resume is how the user continues a session on this machine.
	Resume(in Install, key SessionKey, p Placement, o ResumeOptions) Command
}

Module is what every agent module implements.

type MovePlan

type MovePlan struct {
	Files  []PlacedFile  `json:"files"`
	Policy RewritePolicy `json:"policy"`
}

MovePlan is how a module places a bundle on the target.

type MovementHookIntegrator added in v0.4.0

type MovementHookIntegrator interface {
	MovementHooks(h Host, in Install, bin string, args ...string) HookIntegration
}

MovementHookIntegrator describes passive, local lifecycle hooks. It never invokes an agent or requests a model turn. Unsupported installations retain a file contract for removal, with a human-readable Reason that prevents installation. args pins launcher settings/state directories through literal CLI flags.

type NativeForkOrphans added in v0.4.2

type NativeForkOrphans interface {
	NativeParentGone(context.Context, Host, Install, Summary) (bool, error)
}

NativeForkOrphans is implemented by a module whose native forks can hold their whole inherited history. A fork whose declared parent is absent from the listing starts its own family only when the module reports the parent definitively gone from the install (not archived, unreadable or skipped) and the fork does not read the parent's history.

type NativeForkVerifier added in v0.4.0

type NativeForkVerifier interface {
	VerifyNativeFork(context.Context, Host, Install, Summary, Summary) ([]NativeInheritance, error)
}

NativeForkVerifier requires vendor-declared parent identity plus exact native-prefix evidence. Similar conversation text alone never establishes a fork relationship.

type NativeInheritance added in v0.4.0

type NativeInheritance struct {
	ParentAnchor string
	ChildAnchor  string
	Hash         string
}

type Need added in v0.4.0

type Need string

Need is something a cloud requires, checked by the core while planning. The user interfaces have a sentence for each.

const (
	NeedSubscriptionLogin Need = "subscription-login" // a claude.ai or ChatGPT login, not an API key
	NeedGitHub            Need = "github"             // a repository host the cloud can clone and push
	NeedPushedBranch      Need = "pushed-branch"      // the cloud starts from a branch on the remote
	NeedCleanTree         Need = "clean-tree"         // the driver refuses uncommitted changes (teleport)
	NeedSameAccount       Need = "same-account"       // only the account that owns the session can fetch it
	NeedEnvironment       Need = "environment"        // a vendor environment id (codex cloud exec --env)
	NeedTerminal          Need = "terminal"           // the driver step is interactive
)

type NoLocal added in v0.4.0

type NoLocal struct{}

NoLocal is embedded by a cloud-only module (no data folders on any machine) for the methods that act on local files: it lists nothing, and the rest are unsupported.

func (NoLocal) Bundle added in v0.4.0

Bundle is unsupported.

func (NoLocal) List added in v0.4.0

List returns an empty listing.

func (NoLocal) PlanMove added in v0.4.0

PlanMove is unsupported.

func (NoLocal) Resume added in v0.4.0

Resume has no command: a cloud-only module's sessions are resumed in the vendor's cloud.

func (NoLocal) Verify added in v0.4.0

Verify is unsupported.

type NoticeHookAnswer added in v0.9.0

type NoticeHookAnswer struct {
	Text  string
	Block bool
}

NoticeHookAnswer is hopsesh's answer to a call: a notice for the session, or with Block the reason the session's original is blocked. Both empty: nothing to say.

type NoticeHookCall added in v0.9.0

type NoticeHookCall struct {
	Session string // the session's id
	Path    string // its transcript file, when the agent names one ("" for a database)
	Event   string // "SessionStart" or "UserPromptSubmit"
	Source  string // SessionStart: startup, resume, clear or compact, when the agent says
}

NoticeHookCall is one call of the notice hook, as the agent's hook sent it. Every field is untrusted input; the core checks them after decoding.

type NoticeHookProtocol added in v0.9.0

type NoticeHookProtocol interface {
	DecodeNoticeHook(raw []byte) (NoticeHookCall, bool)
	EncodeNoticeHook(call NoticeHookCall, answer NoticeHookAnswer) []byte
}

NoticeHookProtocol is for agents whose notice hook speaks other JSON than the command hooks of Claude Code and Codex (an agent plugin that runs the notice hook itself). Decode reads a call (false: not one to answer). Encode writes the answer, or nil for none; it is called with an empty answer too, so a plugin can tell "nothing to say" from a hook that failed (which writes nothing). Without it the core speaks the command-hook JSON.

type OwnedTabCommander added in v0.9.0

type OwnedTabCommander interface {
	OwnedTabCommand(in Install, c Command, getenv func(string) string) Command
}

OwnedTabCommander adjusts the command that resumes a session in a terminal tab hopsesh owns on this machine (it started the process and can stop it): Codex runs its own server there instead of the shared one. getenv reads hopsesh's environment, which the tab inherits. It returns c as it is when nothing applies, and never changes c's Dir, Env or Unset; applying it twice changes nothing more.

type OwnerRun added in v0.5.0

type OwnerRun struct {
	Key    string `json:"key"`
	Person string `json:"person,omitempty"`
	Source string `json:"source,omitempty"`
}

OwnerRun is an account a session ran under, as recorded. Key is the module's account fingerprint (comparable with Account.Key); Person, when recorded, the user's (comparable with Account.Person). Source says who recorded it: "agent" or "hopsesh".

func AddOwner added in v0.5.0

func AddOwner(runs []OwnerRun, r OwnerRun) []OwnerRun

AddOwner appends a run, merging it into the last one when it is the same account.

type Path

type Path interface {
	Join(elem ...string) string
	Base(p string) string
	Dir(p string) string
	Clean(p string) string
	IsAbs(p string) bool
	// Rel returns target relative to base, or ok=false when it is not inside it.
	Rel(base, target string) (string, bool)
	Sep() string
}

Path manipulates paths in the machine's own form (a Windows machine seen from a Mac uses backslashes and drive letters).

func PathFor

func PathFor(goos string) Path

PathFor returns the path rules of an operating system.

type PlacedFile

type PlacedFile struct {
	From   BundleFile `json:"from"`
	ToRoot string     `json:"toRoot"`
	ToRel  string     `json:"toRel"`
	// Append are complete records (without newline) added after the rewrite.
	Append [][]byte `json:"-"`
}

PlacedFile is a bundle file with its destination.

type Placement

type Placement struct {
	Key      SessionKey `json:"key"` // the session's key on the target (renamed for keep-both)
	SourceID SessionID  `json:"sourceId"`
	CWD      string     `json:"cwd"`   // the working directory on the target
	Title    string     `json:"title"` // title to give the copy ("" keeps it)
	// Name is the session's own name, for agents that keep names outside the session's
	// files (they record it again after installing; "" when it has none).
	Name     string    `json:"name,omitempty"`
	Mappings []Mapping `json:"mappings"`
	Location string    `json:"location"` // where the session lands: this machine's name
	// OtherAccount: the target is signed in to another account than the source, so
	// account-bound content must be removed (the module's Sanitizer policy applies).
	OtherAccount bool `json:"otherAccount,omitempty"`
}

Placement is what the core decided about where a session lands on the target.

type PosixPath

type PosixPath struct{}

PosixPath is the path form of macOS and Linux.

func (PosixPath) Base

func (PosixPath) Base(p string) string

func (PosixPath) Clean

func (PosixPath) Clean(p string) string

func (PosixPath) Dir

func (PosixPath) Dir(p string) string

func (PosixPath) IsAbs

func (PosixPath) IsAbs(p string) bool

func (PosixPath) Join

func (PosixPath) Join(elem ...string) string

func (PosixPath) Rel

func (PosixPath) Rel(base, target string) (string, bool)

func (PosixPath) Sep

func (PosixPath) Sep() string

type PostInstaller

type PostInstaller interface {
	AfterInstall(ctx context.Context, h Host, in Install, key SessionKey, p Placement) error
}

PostInstaller runs after a session was installed (for example to make the agent index it).

type Preview added in v0.4.0

type Preview struct {
	Items []PreviewItem `json:"items"`
	More  bool          `json:"more"`            // earlier messages exist
	First *PreviewItem  `json:"first,omitempty"` // the first real prompt, when found
}

Preview is the end of a conversation: the last n messages, oldest first, with a line for the tool calls between a prompt and its reply and a marker where it was compacted.

func BuildPreview added in v0.4.0

func BuildPreview(items []PreviewItem, n int, earlier bool) Preview

BuildPreview turns a conversation's items, in order, into its preview: the last n messages and what lies between them. Modules pass what they read: user prompts, agent text (one item per block or record, as the agent wrote it), PreviewTools items and PreviewCompacted markers. In each turn the agent's message is its last run of text and its tool calls become one PreviewTools item; message text goes through PreviewText, and a message left empty is dropped. earlier says the items do not start at the beginning of the conversation (a tail window), so More is set even when every message is returned.

func (Preview) Messages added in v0.4.0

func (p Preview) Messages() int

Messages counts the preview's user and agent messages (not its tool lines or markers).

type PreviewItem added in v0.4.0

type PreviewItem struct {
	Role  PreviewRole         `json:"role"`
	Text  string              `json:"text,omitempty"` // PreviewText of the message
	Time  time.Time           `json:"time"`
	Tools map[ir.ToolKind]int `json:"tools,omitempty"` // PreviewTools: calls by kind
}

PreviewItem is one line of a preview.

type PreviewRole added in v0.4.0

type PreviewRole string

PreviewRole says what a preview item is.

const (
	PreviewUser      PreviewRole = "user"
	PreviewAgent     PreviewRole = "agent"
	PreviewTools     PreviewRole = "tools"     // the tool calls of one turn (Tools)
	PreviewCompacted PreviewRole = "compacted" // the conversation was compacted here
)

type Previewer added in v0.4.0

type Previewer interface {
	Preview(ctx context.Context, h Host, in Install, s Summary, n int) (Preview, error)
}

Previewer reads the end of a session's conversation for the app's preview. It is never called during a scan: only when the user selects a session.

type ProcCommands added in v0.5.0

type ProcCommands interface {
	Commands(ctx context.Context, pids []int) (map[int]string, error)
}

ProcCommands is implemented by a Procs that can read each running process's command line (program path and arguments, as ps shows them); exited ones are left out. Modules use it to tell a shared server from a process they may stop.

type Procs

type Procs interface {
	Alive(ctx context.Context, pids []int) (map[int]bool, error)
	// Names returns the program name of each running process ("codex"); exited ones are
	// left out.
	Names(ctx context.Context, pids []int) (map[int]string, error)
	// Terminate asks a process to exit (SIGTERM; unsupported on Windows).
	Terminate(ctx context.Context, pid int) error
}

Procs checks and stops processes on the machine.

type ProfileSpec added in v0.4.0

type ProfileSpec struct {
	// RootEnv are variables an account's commands run with, each set to the account
	// folder.
	RootEnv []string `json:"rootEnv,omitempty"`
	// RootVars are variables set to folders inside the account folder, for an agent with
	// several roots (OpenCode: XDG_DATA_HOME=<folder>/data, OPENCODE_CONFIG_DIR=
	// <folder>/config).
	RootVars []ProfileVar `json:"rootVars,omitempty"`
	Unset    []string     `json:"unset,omitempty"`
	Login    []string     `json:"login,omitempty"`
	// LoginElsewhere signs in from another machine's browser: the agent prints a link
	// and a code instead of opening a browser where it runs (empty: Login).
	LoginElsewhere []string          `json:"loginElsewhere,omitempty"`
	InitialFiles   map[string]string `json:"initialFiles,omitempty"`
	// Inherit are settings a new folder copies from the agent's default folders, by file:
	// relative to the main root, or to another root when it starts with one
	// ("{config}/opencode.json"). Top-level keys of a TOML file (Codex's
	// cli_auth_credentials_store, so a new folder keeps its sign-in where the default one
	// does), or dot paths into a .json or .jsonc file (InheritJSON). Only the listed
	// settings are copied, never one that holds a credential, into the same root of the
	// new folder (ProfileLocate), which must be inside it.
	Inherit map[string][]string `json:"inherit,omitempty"`
	// InheritsSignIn: a new folder keeps its sign-in where the default folder does, so
	// the user interfaces say so (Codex). Inherit may carry other settings too.
	InheritsSignIn bool `json:"inheritsSignIn,omitempty"`
}

ProfileSpec is the module's declaration of vendor-supported account isolation. Only module code supplies it; peer payloads never control launch policy.

func (*ProfileSpec) EnvFor added in v0.9.0

func (p *ProfileSpec) EnvFor(root string, pa Path) []string

EnvFor is the variables ("NAME=value") that pin the agent to the account folder root, with pa the rules of root's machine.

func (*ProfileSpec) Vars added in v0.9.0

func (p *ProfileSpec) Vars() []string

Vars are every variable an account folder sets.

type ProfileVar added in v0.9.0

type ProfileVar struct {
	Env string `json:"env"`
	Sub string `json:"sub,omitempty"` // slash-separated; "" is the account folder itself
}

ProfileVar is a variable an account folder sets to a folder inside it.

type Reader

type Reader interface {
	Read(ctx context.Context, h Host, in Install, s Summary, from ir.Cursor) (ir.Segment, error)
}

Reader lifts a session into the conversation IR, from a cursor (incremental reads for round trips).

type RemoteControlDefaulter added in v0.7.0

type RemoteControlDefaulter interface {
	// RemoteControlDefault is the setting in in's profile; nil when this install has none.
	RemoteControlDefault(h Host, in Install) *SettingFile
}

RemoteControlDefaulter is an agent with its own "start Remote Control for every session" setting in a profile's settings file (Claude Code's remoteControlAtStartup).

type RemoteControlTyper added in v0.9.0

type RemoteControlTyper interface {
	RemoteControlInSession() string
}

RemoteControlTyper is what to type in an open, idle session to turn its agent's remote control on there ("/remote-control"); optional beside CapRemoteControl.

type Renamer added in v0.4.0

type Renamer interface {
	Rename(ctx context.Context, h Host, in Install, s Summary, title string) error
}

Renamer gives a session a new title in the agent's own data, the way the agent's own rename does, so the agent's session list shows it too.

type Result

type Result struct {
	Stdout []byte
	Stderr []byte
	Code   int
}

Result is a finished command. A non-zero exit is not an error.

type ResumeOptions

type ResumeOptions struct {
	// AppRunning is set by the core from current live detection, never by a CLI flag.
	// It distinguishes focusing an owned desktop session from importing a saved one.
	AppRunning    bool
	Fork          bool
	RemoteControl bool
	App           bool   // open in the agent's desktop app instead of the terminal
	Name          string // a name for Remote Control / the session list
	Prompt        string // a first message, "" for none
	// RestartService: the person agreed to restart the agent's background service to
	// resume (ErrRestartsService); never set without asking.
	RestartService bool
}

ResumeOptions shape the resume command.

type RewriteKind

type RewriteKind string

RewriteKind says how the core rewrites paths in a file.

const (
	RewriteJSONL RewriteKind = "jsonl" // JSON lines: string values only, with the module's policy
	RewriteText  RewriteKind = "text"  // plain text
	RewriteNone  RewriteKind = "none"  // copied byte for byte
)

type RewritePolicy

type RewritePolicy struct {
	// Protect: string values under these object keys are never changed (signatures,
	// encrypted content, opaque blobs).
	Protect []string `json:"protect,omitempty"`
	// DropRecords removes whole records whose top-level field has one of the values.
	DropRecords []FieldMatch `json:"dropRecords,omitempty"`
	// RenumberOrdinal rebases this top-level integer field after dropping records in a
	// newly installed copy. All other bytes stay intact; append never uses this policy.
	RenumberOrdinal string `json:"renumberOrdinal,omitempty"`
	// DropElems removes array elements (only when Placement.OtherAccount, via Sanitizer).
	DropElems []ElemMatch `json:"dropElems,omitempty"`
	// Rename gives a keep-both copy a new session id ({"old","new"}; empty for none): the id
	// changes inside every rewritable string, and in the RenameKeys fields even when they
	// are protected.
	Rename     [2]string `json:"rename,omitempty"`
	RenameKeys []string  `json:"renameKeys,omitempty"`
}

RewritePolicy is data the core's JSON rewriter applies to RewriteJSONL files.

type Root

type Root struct {
	Name string   // "home"
	Env  []string // overriding variables, first set wins: ["CLAUDE_CONFIG_DIR"]
	// EnvSub are variables that set the root as a folder inside their value, tried after
	// Env, first set wins: {XDG_DATA_HOME, "opencode"} is $XDG_DATA_HOME/opencode.
	EnvSub []EnvSub
	// Default is the folder when no variable is set, by GOOS ("*" for all); "~" is the home
	// folder, "{name}" another root.
	Default map[string]string
}

Root is one data folder of the agent.

func (Root) DefaultFor added in v0.9.0

func (r Root) DefaultFor(goos string) string

DefaultFor is the root's folder on goos when no variable sets it ("~/.claude").

func (Root) Locate added in v0.9.0

func (r Root) Locate(goos string, getenv func(string) string) string

Locate is the root's folder on a machine, before Expand: its first set Env variable, else the first set EnvSub variable with its subfolder, else its default for goos. getenv reads that machine's environment.

func (Root) Vars added in v0.9.0

func (r Root) Vars() []string

Vars are the environment variables that can set the root, in the order Locate tries them. Code that keys on or resolves a root's environment goes through Vars and Locate, never Env or EnvSub themselves.

type Row added in v0.9.0

type Row map[string]any

Row is one row of Rows: its values by column name.

func (Row) Float added in v0.9.0

func (r Row) Float(col string) float64

Float is a REAL value (0 when NULL; an INTEGER or a decimal TEXT is read too, as Int does).

func (Row) Int added in v0.9.0

func (r Row) Int(col string) int64

Int is an INTEGER value (0 when NULL; a whole REAL or a decimal TEXT is read too, as a remote reader's JSON gives them, and any other text is 0).

func (Row) Null added in v0.9.0

func (r Row) Null(col string) bool

Null reports whether a column is NULL or missing.

func (Row) String added in v0.9.0

func (r Row) String(col string) string

String is a TEXT value ("" when NULL or not text; a BLOB is read as text).

type Rows added in v0.9.0

type Rows struct {
	Columns []string `json:"columns"`
	Rows    []Row    `json:"rows"`
}

Rows are a query's rows, read into memory. Values are int64 (INTEGER), float64 (REAL), string (TEXT), []byte (BLOB) or nil (NULL), keyed by column name.

func ScanRows added in v0.9.0

func ScanRows(rs *sql.Rows, lim SQLLimits) (Rows, error)

ScanRows reads database/sql rows into Rows within limits, for a Host's SQL. It closes rs. Going over a limit is ErrTooLarge; two columns of one name (SELECT a.*, b.*) are an error, since a Row keeps one value per name.

type RuleFile

type RuleFile struct {
	Path string
	// Owned: hopsesh writes the whole file (Render). Otherwise it is the agent's shared
	// settings file, edited with Merge and checked with Has.
	Owned  bool
	Render func(r Rules) []byte
	Merge  func(existing []byte, r Rules) ([]byte, error)
	Has    func(existing []byte, r Rules) bool
	Remove func(existing []byte, r Rules) ([]byte, error)
}

RuleFile is where an agent keeps approval rules.

type Rules

type Rules struct {
	Bin   string     // the command as the agent runs it ("hopsesh")
	Allow [][]string // run without asking: {"ls"}, {"show"}
	Ask   [][]string // ask first: {"pull"}, {"undo"}
}

Rules are hopsesh command prefixes (after the binary) by approval.

type RunOptions

type RunOptions struct {
	Dir string
	Env []string // extra KEY=value pairs
	// Unset are variables removed from the program's environment (a cloud driver's
	// Cloud.Unset).
	Unset []string
	Stdin []byte
	// HoldStdin keeps standard input open this long after Stdin is written (or until the
	// program exits, or its output contains StdinUntil), for programs that stop at the end
	// of their input before answering it.
	HoldStdin  time.Duration
	StdinUntil []byte
	// StdinReply receives complete output lines and may send the next protocol input.
	// Returning done closes stdin. It must not block or retain the supplied line.
	StdinReply func([]byte) (input []byte, done bool)
	Timeout    time.Duration
}

RunOptions control Exec.Run.

type RuntimeProfile added in v0.4.0

type RuntimeProfile struct {
	IdentitySource string    `json:"identitySource,omitempty"`
	CheckedAt      time.Time `json:"checkedAt,omitempty"`
	Machine        string    `json:"machine,omitempty"`
	ID             string    `json:"id"`
	Endpoint       string    `json:"endpoint"`
	Agent          ID        `json:"agent"`
	Name           string    `json:"name"`
	Tags           []string  `json:"tags"`
	Root           string    `json:"root"`
	Default        bool      `json:"default"`
	Managed        bool      `json:"managed"`
	Generation     int       `json:"generation"`
	Binding        string    `json:"binding,omitempty"`
	Account        *Account  `json:"account,omitempty"`
	Error          string    `json:"error,omitempty"`
	// Command is the shell command hopsesh added on its machine to run the agent in this
	// folder ("claude-work"; "" none).
	Command string `json:"command,omitempty"`
	// Port is the port the agent's background service listens on for this folder, when
	// hopsesh gave it one (OpenCode: each account folder's own, so its service can run
	// beside the default one); 0 none.
	Port int `json:"port,omitempty"`
}

RuntimeProfile is a pinned, agent-specific state root, independent of account labels. Binding describes the observed login; it is not a credential or proof of ownership.

type SQL added in v0.9.0

type SQL interface {
	// Query runs one SELECT and returns its rows, refusing more than the default limits.
	Query(ctx context.Context, db, q string, args ...any) (Rows, error)
	// Batch runs several SELECTs in one read transaction, so they see one snapshot of the
	// database (messages and their parts), and returns their rows in order. Each
	// statement keeps to its Limits, and the whole batch to DefaultSQLBatchMaxBytes
	// (SQLBudget).
	Batch(ctx context.Context, db string, stmts []Statement) ([]Rows, error)
	// Columns lists a table's columns, for a module's check of the schema it reads; a
	// missing table has none.
	Columns(ctx context.Context, db, table string) ([]string, error)
}

SQL reads a SQLite database on the machine, read only: no query writes, checkpoints or vacuums. db is the database file's absolute path. The confined Host a module gets lets it read only its Spec's SQLTables, from the files its SQLFiles name, and gives each call at most DefaultSQLTimeout (less when ctx ends sooner).

A database file that is not there is ErrNotInstalled: ErrNotFound is left to the module for a session the database does not hold, since the core takes it to mean the session was deleted. A read the machine's tools cannot do (another machine's WAL database that no program has open, which its SQLite cannot open read only) is ErrUnsupported: the module then reads with its agent's own program.

func HostSQL added in v0.9.0

func HostSQL(h Host) (SQL, bool)

HostSQL returns h's SQL reader, when it has one.

type SQLBudget added in v0.9.0

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

SQLBudget caps the bytes one Batch brings into memory across its statements, on top of each statement's own limits. A Host's SQL makes one per Batch.

func NewSQLBudget added in v0.9.0

func NewSQLBudget() *SQLBudget

NewSQLBudget is a budget of DefaultSQLBatchMaxBytes.

func (*SQLBudget) CheckRows added in v0.9.0

func (b *SQLBudget) CheckRows(r Rows, lim SQLLimits) error

CheckRows is CheckRows, also spending the budget.

func (*SQLBudget) ScanRows added in v0.9.0

func (b *SQLBudget) ScanRows(rs *sql.Rows, lim SQLLimits) (Rows, error)

ScanRows is ScanRows, also spending the budget.

type SQLHost added in v0.9.0

type SQLHost interface {
	// SQL returns the machine's reader, or nil when it has none.
	SQL() SQL
}

SQLHost is a Host that can read SQLite databases on its machine, for an agent that keeps its sessions in one (OpenCode). Other hosts do not implement it; modules find it with HostSQL.

type SQLLimits added in v0.9.0

type SQLLimits struct {
	MaxRows  int
	MaxBytes int64 // the sum of every value's size: strings and blobs by length, others 8
}

SQLLimits guard how much of a database one query may bring into memory. MaxBytes counts the values kept; a Host's reader also caps one value's length (SQLite's SQLITE_LIMIT_LENGTH) so a single huge value fails before it is read whole.

func (SQLLimits) WithDefaults added in v0.9.0

func (l SQLLimits) WithDefaults() SQLLimits

WithDefaults fills zero limits with the defaults.

type SQLTableLimiter added in v0.9.0

type SQLTableLimiter interface {
	// Only returns an SQL that reads only the tables in allow and never those in deny.
	Only(allow, deny []string) SQL
}

SQLTableLimiter is an SQL that refuses reads of tables itself, below the query text (SQLite's authorizer): Confine hands it the module's tables.

type SanitizedProjection added in v0.4.0

type SanitizedProjection interface {
	ProjectSanitized(source, target ir.Segment) ([]ir.Projection, error)
}

SanitizedProjection maps native nodes after the module's own Sanitizer dropped account-bound records. The module must prove its rewrite retained native order.

type Sanitizer

type Sanitizer interface {
	Sanitize() RewritePolicy
}

Sanitizer is the extra policy for a same-agent move to a machine signed in to another account (content bound to the source account is removed).

type SendRequest added in v0.4.0

type SendRequest struct {
	Cloud string
	// Dir is a worktree the core made, on Branch (Claude Code clones "your current
	// branch").
	Dir    string
	Repo   string // the repository's identity
	Branch string // already pushed by the core
	Base   string
	// Brief is the first prompt, rendered and redacted by the core; it begins with
	// NotePrefix.
	Brief string
	Diff  []byte // only with ViaStartingDiff
	Env   string // the vendor's environment id, when the cloud has NeedEnvironment
	// Attempts asks for that many attempts at once (best-of-N), where the cloud runs them; 0
	// is the cloud's default.
	Attempts int
	Title    string
	// Code is how the code goes up: ViaBranch (Branch is pushed; the default) or ViaBundle
	// (the driver uploads the repository from Dir itself, and nothing is pushed).
	Code CodeWay
}

SendRequest is a cloud session to start.

type Sent added in v0.4.0

type Sent struct {
	// Session is the session started (empty when Run is set).
	Session CloudSession
	// Run is a command for the user's terminal (claude --cloud "<briefing>" in
	// SendRequest.Dir). The core runs it where the user sees it and answers what it asks
	// (Claude Code's question whether the folder is trusted); hopsesh never types into it.
	// It watches only what the command prints and its exit code, and the module reads the
	// session from them (CloudStepReader, which it then implements).
	Run *Command
}

Sent is what SendCloud did: the session it started, or, when the driver starts one only in a terminal, the command for it.

type SessionError

type SessionError struct {
	Path string
	Err  error
}

SessionError is one session that could not be read.

func (SessionError) Error

func (e SessionError) Error() string

type SessionID

type SessionID string

SessionID is an agent's own id for a session, opaque to the core.

func NewSessionID added in v0.9.0

func NewSessionID(m Module, in Install, now time.Time, fallback func() string) SessionID

NewSessionID is a new id from the module's minter, else from fallback.

type SessionIDMinter added in v0.9.0

type SessionIDMinter interface {
	NewSessionID(in Install, now time.Time) SessionID
}

SessionIDMinter makes new session ids in the agent's own form (OpenCode: "ses_…"), for a copy kept beside the original or a session written from another agent. Without it the core makes a UUID.

type SessionKey

type SessionKey struct {
	Agent   ID        `json:"agent"`
	Profile string    `json:"profile,omitempty"`
	Session SessionID `json:"session"`
}

SessionKey identifies a session across agents: the only key the core, the lineage manifests and the user interfaces use.

func ParseKey

func ParseKey(s string) (SessionKey, error)

ParseKey parses "agent/session".

func (SessionKey) String

func (k SessionKey) String() string

type SessionKind added in v0.5.0

type SessionKind struct {
	ID   string // "voice"
	Name string // "Voice conversations"
	Note string // what they are, for the setting
}

SessionKind is a kind of session hidden by default (Spec.Kinds).

type SessionStamp added in v0.9.0

type SessionStamp string

SessionStamp is a module's opaque mark of a session's state: two equal stamps mean nothing was added or changed in between. "" is no stamp. A stamp starts with its form and a colon ("v1:…"), and a module that changes how it stamps changes that prefix, so a stamp journaled before can be told apart from a session that changed since (the core then asks instead of refusing an undo for good).

func StampOf added in v0.9.0

func StampOf(ctx context.Context, m Module, h Host, in Install, s Summary) (stamp SessionStamp, ok bool, err error)

StampOf is a session's stamp from its module: SessionStamper's, else SummaryStamp for a virtual module. ok is false when the module has neither, and the core compares the main file's size and time instead. For SummaryStamp, s must be fresh (from a listing or a summary made now), never one from the listing cache, or a guard compares old with old.

func SummaryStamp added in v0.9.0

func SummaryStamp(s Summary) SessionStamp

SummaryStamp is the stamp of a listed virtual session: its record count and last activity.

func (SessionStamp) Format added in v0.9.0

func (s SessionStamp) Format() string

Format is the stamp's form, the text before its first colon ("" when it has none).

type SessionStamper added in v0.9.0

type SessionStamper interface {
	SessionStamp(ctx context.Context, h Host, in Install, id SessionID) (SessionStamp, error)
}

SessionStamper gives a session's stamp without listing every session, for caches and for guards that refuse to undo over later work. A missing session is ErrNotFound.

type SessionStore added in v0.9.0

type SessionStore interface {
	SessionStamper
	// Backup saves the session as the agent exports it, with its child sessions (Delete
	// removes them too), to a file under the install's roots (through h.FS, journaled) and
	// returns that file and the stamp it was taken at.
	Backup(ctx context.Context, h Host, in Install, id SessionID) (backup string, stamp SessionStamp, err error)
	// Delete removes the session (and its child sessions) only while its stamp is still
	// expect; otherwise ErrDiverged, and nothing is deleted. A session already gone is
	// ErrNotFound. An empty expect is always refused (ErrDenied): a delete names the
	// state it deletes.
	Delete(ctx context.Context, h Host, in Install, id SessionID, expect SessionStamp) error
	// Restore imports a Backup again, keeping the session's id, and returns the new stamp.
	// It is idempotent: a session already there with the backup's content is left as it
	// is. A session there with other content (continued since) is ErrDiverged and left
	// as it is, so an undo never reports success over newer work.
	Restore(ctx context.Context, h Host, in Install, id SessionID, backup string) (SessionStamp, error)
}

SessionStore changes sessions the agent keeps in a database, through the agent's own program, never by writing the database. The core journals each change as a vendor-session operation and undoes it with these methods.

type SessionWatchProvider added in v0.4.1

type SessionWatchProvider interface {
	SessionWatchPaths(Install, Path) []string
}

SessionWatchProvider narrows filesystem notifications to session and metadata paths, excluding vendor diagnostics that a listing probe itself may write. Paths are absolute and use the host's path rules; missing paths are supported.

type SettingFile added in v0.7.0

type SettingFile struct {
	Path     string
	Key      string
	Evidence string // the vendor's documentation of the key
	// Reason is why this install can't use it ("" when it can).
	Reason string
}

SettingFile is one boolean key of a shared JSON settings file. Set changes only that key: on writes true, off removes it (the agent's own default again). All functions are pure; the app owns bounded local reads and atomic writes.

func (SettingFile) Get added in v0.7.0

func (f SettingFile) Get(b []byte) (on bool, err error)

Get reads the key: on is true only when it is the JSON true.

func (SettingFile) Set added in v0.7.0

func (f SettingFile) Set(b []byte, on bool) ([]byte, error)

Set turns the key on (true) or off (removed), leaving every other key as it was.

type SpaceReporter added in v0.4.2

type SpaceReporter interface {
	FreeSpace(p string) (int64, error)
}

SpaceReporter is a filesystem that can tell how many bytes are free for p (its nearest existing parent directory). Filesystems that cannot tell do not implement it.

type Spec

type Spec struct {
	Accounts *ProfileSpec
	// ResumeAcrossAccounts: a session resumes under another account than the one that ran
	// it, the vendor dropping what is bound to that account (Claude Code: signed reasoning).
	// Without it such a session must continue as a cleaned copy.
	ResumeAcrossAccounts bool
	// DesktopScheme is the registered URL protocol a desktop resume uses.
	DesktopScheme string
	ID            ID
	Name          string // "Claude Code"
	Vendor        string // "Anthropic"
	Stability     Stability
	// Tested lists the agent versions this module was verified against, oldest first,
	// as version prefixes ("2.1"). Other versions work but are reported as untested.
	Tested []string
	// Binaries the module may run through Host.Exec (the first is the agent itself).
	Binaries []Binary
	// Roots are the agent's data folders. The first is the main one; writes are allowed
	// only under a root. A cloud-only module has none.
	Roots []Root
	// LoginEnv are environment variables a GUI app must adopt from the user's login shell
	// (an app started from Finder does not inherit them).
	LoginEnv []string
	// Secrets are root-relative paths ("{home}/auth.json") the Host never opens.
	Secrets []string
	// Worktrees are worktree folders the agent creates inside a repository
	// (".claude/worktrees"); git status ignores them.
	Worktrees []string
	// Instructions are the project instruction files the agent reads, in its order of
	// preference ("CLAUDE.md", "AGENTS.md"). A session continued in another agent is told
	// about files only the other agent read.
	Instructions []string
	// GlobalInstructions are the user's instructions for every project, root-relative
	// ("{home}/CLAUDE.md"). A continued session reports them, and carries them when asked.
	GlobalInstructions []string
	// Tools names the agent's own tools for people and for a continued session's briefing
	// ("shell, apply_patch, update_plan").
	Tools string
	// Features are capabilities without a method of their own: the module honours the
	// matching ResumeOptions (CapFork, CapRemoteControl).
	Features []Capability
	// Experimental marks capabilities that are not yet trustworthy; the user interfaces
	// say so and keep them opt-in.
	Experimental []Capability
	// Icon is how the user interfaces picture the agent (optional; its initials otherwise).
	Icon Icon
	// Desktop is how the agent's desktop app signs in and runs sessions, for the user
	// interfaces (nil: it has none, or nothing to say).
	Desktop *Desktop
	// Plans is what an account's plan is named after when the module's Account.Label is a
	// bare plan ("max" reads "Claude Max"); empty when the label names it ("ChatGPT Pro").
	Plans string
	// Clouds are the vendor clouds the module reaches through its agent's CLI. A module
	// with clouds may have no Roots (a cloud-only module, see NoLocal).
	Clouds []Cloud
	// Kinds are kinds of session the module marks (Summary.Kinds) that hopsesh hides
	// unless the user turns them on for this agent: conversations that are not coding
	// sessions to move (the Codex app's voice and Work threads).
	Kinds []SessionKind
	// ServiceTurns: the agent's terminal program attaches to its background service, which
	// runs the turns (OpenCode): a terminal that ends leaves a turn running there.
	ServiceTurns bool
	// TerminalEnv are variables ("NAME=value") the agent's programs get in hopsesh's own
	// terminal tabs, on top of the user's: settings that suit that terminal
	// (CLAUDE_CODE_FORCE_SYNC_OUTPUT=1). Never a credential; not used in other terminals.
	TerminalEnv []string
	// SQLTables are the database tables the module may read through the Host's SQL
	// (SQLHost), for an agent that keeps sessions in SQLite. Every other table is refused.
	SQLTables []string
	// SQLFiles are the database files SQL may open: paths or patterns (* ? [) with {root}
	// and ~ as Secrets have ("{data}/opencode*.db", "{db}" for an Install root that a
	// variable sets). A pattern whose root the install lacks matches nothing. Each file,
	// with its -wal, -shm and -journal companions, is a Secret too: no file read, copy or
	// package reaches it.
	SQLFiles []string
	// SQLDenied are tables that are never read, even through a view, and whose name
	// refuses any query that mentions it (credentials, accounts).
	SQLDenied []string
}

Spec is what a module declares as data. The core resolves roots, probes binaries, confines writes and refuses secret reads from it, before any module code runs.

func (Spec) FindCloud added in v0.4.0

func (s Spec) FindCloud(name string) (Cloud, bool)

FindCloud returns the Spec's cloud with this name.

func (Spec) MainRoot added in v0.9.0

func (s Spec) MainRoot() Root

MainRoot is the main data folder: the first declared root (zero for a cloud-only module).

func (Spec) PinMain added in v0.9.0

func (s Spec) PinMain(in Install, path string) Install

PinMain returns in with its main root set from the account folder path and no other root, before Detect resolves the other roots against the pinned environment. For an added account (in.Profile set, not the default) of an agent whose account folders hold its roots (ProfileSpec.RootVars), the main root is inside path (ProfileLocate); else it is path itself. Set in.Profile first.

func (Spec) ProfileLocate added in v0.9.0

func (s Spec) ProfileLocate(name, root, goos string, getenv func(string) string) string

ProfileLocate is where a root of the Spec is for the account folder root: Locate with the folder's variables over the machine's (getenv), before Expand.

func (Spec) Short added in v0.9.0

func (s Spec) Short() string

Short is the agent's name where space is tight: the first word of its Name ("Claude").

func (Spec) TestedWith

func (s Spec) TestedWith(version string) bool

TestedWith reports whether a version matches one of the Spec's tested version prefixes.

type Stability

type Stability string

Stability says how far a module (or one of its capabilities) can be trusted.

const (
	Experimental Stability = "experimental"
	Stable       Stability = "stable"
)

type Statement added in v0.9.0

type Statement struct {
	Query string
	Args  []any
	// Limits are this query's guards; zero fields take the defaults.
	Limits SQLLimits
}

Statement is one query of a Batch.

type StepOutput added in v0.4.0

type StepOutput struct {
	Text  string
	Width int
	Code  int
}

StepOutput is what a terminal step (Sent.Run) printed, as hopsesh saw it go by: plain text with the terminal's control sequences taken out, at most its last 64 KB; the terminal's width (a line that wide may go on in the next one, where the program broke it); and the exit code (-1 when it is unknown).

type Stopper

type Stopper interface {
	Stop(ctx context.Context, h Host, in Install, s Summary, grace time.Duration) error
}

Stopper asks an open session to end, waiting up to grace.

type Summary

type Summary struct {
	ContextOverflow bool       `json:"contextOverflow,omitempty"`
	NativeParent    SessionID  `json:"nativeParent,omitempty"` // module-declared parent; core verifies before linking lineage
	Key             SessionKey `json:"key"`
	Title           string     `json:"title"`
	TitleSource     string     `json:"titleSource,omitempty"` // custom | generated | prompt | reply
	// CWD is the session's project folder, as the agent resumes it.
	CWD          string    `json:"cwd"`
	LastPrompt   string    `json:"lastPrompt,omitempty"`
	LastActivity time.Time `json:"lastActive"`
	Size         int64     `json:"size"`
	GitBranch    string    `json:"gitBranch,omitempty"`
	AgentVersion string    `json:"agentVersion,omitempty"` // the agent version that last wrote it
	// WorktreeRoot is set when CWD is a worktree the agent itself manages inside a
	// repository (for example <repo>/.claude/worktrees/<name>).
	WorktreeRoot string `json:"worktreeRoot,omitempty"`
	Subagents    int    `json:"subagents,omitempty"`
	// LegacyLabel is set when the title carried a label an older hopsesh wrote on a copy
	// left behind (Title is then the title without it).
	LegacyLabel *LegacyLabel `json:"legacyLabel,omitempty"`
	// Path is the session's main file on its machine (the lineage manifest sits beside it).
	Path string `json:"path"`
	// Account is the module's opaque account fingerprint for the session, when the agent
	// records one (bound reasoning cannot cross accounts).
	Account string `json:"account,omitempty"`
	// Owners are the accounts the agent recorded running the session, oldest first, with
	// consecutive runs under one account merged. Empty when the agent recorded none.
	Owners []OwnerRun `json:"owners,omitempty"`
	// Mirror is the vendor's cloud copy of this session while it runs here (Claude Code's
	// Remote Control), when the agent records one: the session is still this one.
	Mirror *CloudLink `json:"mirror,omitempty"`
	// Kinds are the Spec.Kinds this session is (Codex: "voice", "work"); the user
	// interfaces leave such sessions out unless the user shows that kind.
	Kinds []string `json:"kinds,omitempty"`
}

Summary describes one session, the same way for every agent.

func ListingSummary added in v0.4.1

func ListingSummary(ctx context.Context, h Host, file string, info fs.FileInfo, salt string, dependencies []string, parse func() (*Summary, error)) (*Summary, error)

ListingSummary reuses a parsed summary only while all its dependencies match. A missing dependency is part of the signature; other stat failures disable caching. Modules version their parsers in salt.

func ListingSummaryKey added in v0.9.0

func ListingSummaryKey(ctx context.Context, _ Host, key, signature, salt string, parse func() (*Summary, error)) (*Summary, error)

ListingSummaryKey is ListingSummary for a session that is not one file (a row of a database): key names it in the cache ("<db>#<session id>") and signature is what the module read that changes with it (OpenCode: id|time_updated|settled count|part count), read before parse. Modules version their parsers in salt.

type VendorInstaller added in v0.9.0

type VendorInstaller interface {
	PostInstaller
	InstallsViaVendor() bool
}

VendorInstaller is a PostInstaller whose AfterInstall is the install itself: the staged files are input for the agent's own importer (OpenCode's session import), not the session. When InstallsViaVendor is true the core runs AfterInstall, after placing a moved session's files, before it records lineage, treats its failure as the operation's failure, and runs it again when it recovers an interrupted operation, so AfterInstall must be idempotent. A session already at the id with other content than the placed copy is ErrDiverged, never success (it may be work done since a first, interrupted run).

Such a module's Writer imports in Write itself, and its WriteRecoverer again when an interrupted Write had not: the core runs no AfterInstall after a write.

type VersionError

type VersionError struct {
	Agent    ID
	Have     string
	Tested   []string
	Blocking bool
}

VersionError is an agent version the module cannot handle (Blocking) or has not been tested with.

func (*VersionError) Error

func (e *VersionError) Error() string

type VirtualSessions added in v0.9.0

type VirtualSessions interface {
	VirtualSessions()
}

VirtualSessions marks a module whose sessions are not one growing file: Summary.Size and ir.Cursor.Offset count the session's records (settled messages), not bytes, and Summary.Path is an anchor file hopsesh keeps, which may be missing. The core then compares stamps (SessionStamp) instead of file sizes and times.

type Watch added in v0.4.0

type Watch struct {
	// Surface is what hopsesh uses there, in plain words, for the drift review.
	Surface string
	// Docs are Markdown pages and llms.txt indexes, hashed and diffed week to week.
	Docs []string
	// Feeds are changelogs and release feeds.
	Feeds []Feed
	// Grep is an extended regular expression for the feeds' new entries and the docs
	// diffs.
	Grep string
	// Help are commands that need no login, whose output is diffed between the tested and
	// the latest driver: {"codex", "cloud", "exec", "--help"}.
	Help [][]string
	// Relies are the flags and subcommands in that help the cloud code uses; one that
	// disappears is a break.
	Relies []string
	// Issues are upstream issues and pull requests: "anthropics/claude-code#95873".
	Issues []string
	// Searches are GitHub issue searches, limited to issues opened since the last run.
	Searches []string
	// Code is part of an upstream repository whose commits and canaries are watched.
	Code *WatchCode
}

Watch is what the weekly upstream-drift check watches for a cloud (read by internal/devtools/driftmanifest): the single place a module says which vendor surfaces its cloud code relies on.

type WatchCode added in v0.4.0

type WatchCode struct {
	Repo     string
	Paths    []string
	Canaries []string
}

WatchCode is part of an upstream repository: the commits on Paths since the last run, and how many files hold each canary (strings the cloud code depends on, such as "CODEX_STARTING_DIFF").

type WindowsPath

type WindowsPath struct{}

WindowsPath is the path form of Windows: drive letters, backslashes, and names compared without regard to case.

func (WindowsPath) Base

func (w WindowsPath) Base(p string) string

func (WindowsPath) Clean

func (w WindowsPath) Clean(p string) string

func (WindowsPath) Dir

func (w WindowsPath) Dir(p string) string

func (WindowsPath) IsAbs

func (WindowsPath) IsAbs(p string) bool

func (WindowsPath) Join

func (w WindowsPath) Join(elem ...string) string

func (WindowsPath) Rel

func (w WindowsPath) Rel(base, target string) (string, bool)

func (WindowsPath) Sep

func (WindowsPath) Sep() string

type WriteRecoverer added in v0.4.0

type WriteRecoverer interface {
	RecoverWrite(context.Context, Host, Install, ir.WriteRequest) (ir.WriteResult, error)
}

WriteRecoverer verifies an already-written operation without writing native history. A module whose agent installs its own sessions (VendorInstaller) imports again here when the interrupted Write had not (doing nothing when it had), and finds the session Write made also when Write gave it an id of its own.

type Writer

type Writer interface {
	Profile(in Install) ir.Profile
	Write(ctx context.Context, h Host, in Install, req ir.WriteRequest) (ir.WriteResult, error)
}

Writer writes IR into the agent's native format: a new session, or an append to one it can extend.

Directories

Path Synopsis
Package agenttest is the conformance kit for agent modules: an in-memory Host and a suite every module must pass.
Package agenttest is the conformance kit for agent modules: an in-memory Host and a suite every module must pass.

Jump to

Keyboard shortcuts

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