agent

package
v0.4.3 Latest Latest
Warning

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

Go to latest
Published: Oct 10, 2026 License: Apache-2.0 Imports: 22 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 the hook at all
	HookUnknown     = "unknown"      // the agent could not be asked
)

Hook trust states.

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

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

Functions

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 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 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 HookVersionAtLeast added in v0.4.0

func HookVersionAtLeast(version, minimum string) bool

HookVersionAtLeast accepts stable, three-component versions in the same major compatibility family. Unknown versions and prereleases fail closed.

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 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 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 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 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 StagedKey

func StagedKey(f PlacedFile) string

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

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
	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 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"`
}

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
}

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.

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 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 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), as set on
	// that machine ("" when unset).
	Env map[string]string `json:"env"`
	// 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 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 HookFile added in v0.4.0

type HookFile struct {
	Path   string
	Merge  func([]byte) ([]byte, error)
	Remove func([]byte) ([]byte, error)
	Has    func([]byte) 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.

type HookIntegration added in v0.4.0

type HookIntegration struct {
	File           *HookFile
	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"`
}

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 run user hooks only after the user trusts them (Codex reviews each hook definition and skips it silently until trusted). It asks the agent itself, never re-implementing its trust hash, and never trusts on the user's behalf: approving a hook stays in the agent's own review UI.

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. The core gives every module a confined Host; the conformance kit does the same.

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 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 {
	Accounts       *ProfileSpec      `json:"-"`
	OS             string            `json:"os,omitempty"`
	Desktop        string            `json:"desktop,omitempty"`
	DesktopVersion string            `json:"desktopVersion,omitempty"`
	DesktopWhy     string            `json:"desktopWhy,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
	Roots          map[string]string `json:"roots"`             // name → absolute path on that machine
	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) 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 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"`
}

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"`
}

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 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 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 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 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      []string          `json:"rootEnv,omitempty"`
	Unset        []string          `json:"unset,omitempty"`
	Login        []string          `json:"login,omitempty"`
	InitialFiles map[string]string `json:"initialFiles,omitempty"`
}

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

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 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
}

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"]
	// 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.

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"`
}

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 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.

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 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 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
	// 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
	// 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
	// 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
}

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) 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 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"`
	// 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"`
}

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.

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 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.

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