Documentation
¶
Index ¶
- Constants
- Variables
- func CallLocal(client *http.Client, dataDir, tokenHeader, route string, body any, ...) (int, []byte, error)
- func DecodeFrame(frame []byte) (kind byte, tunnelID string, payload []byte, ok bool)
- func DefaultMachineFile(dataDir string) string
- func DefaultPolicy() hubproto.Policy
- func EmitAppsEvent(dataDir, tokenHeader string, ev AppsEvent)
- func EmitDesignEvent(dataDir, tokenHeader, kind, project string)
- func EncodeFrame(kind byte, tunnelID string, payload []byte) []byte
- func EnsureGitKey(home, hostname string) (string, error)
- func EnsureGitKeyIn(home, dataDir, hostname string) (string, error)
- func IsClusterOwnedName(name string) bool
- func IsLayoutStateName(name string) bool
- func LinkStatePath(dataDir string) string
- func Log(level, msg string, fields ...F)
- func Narrowed(old, now hubproto.Policy) bool
- func ParsePolicy(text, source string) (hubproto.Policy, error)
- func RemoveGitKey(home, dataDir string) ([]string, error)
- func RunCLI(args []string, stdout, stderr io.Writer) (code int, handled bool)
- func SendAppsEvent(dataDir, tokenHeader string, ev AppsEvent) error
- func SessionExpiry(secret []byte, token string, now time.Time) (float64, bool)
- func SessionSubject(secret []byte, token string, now time.Time) (string, bool)
- func SignHS256(secret []byte, sub, aud string, ttl time.Duration) string
- func SignPayload(secret []byte, aud string, fields map[string]any, ttl time.Duration) string
- func Unlink(ctx context.Context, m *MachineFile, client *http.Client, now time.Time) error
- func VerifiedAudience(secret []byte, token, audience string, now time.Time) (map[string]any, bool)
- func VerifiedPayload(secret []byte, token string, now time.Time) (map[string]any, bool)
- func VerifyHS256(secret []byte, token, audience string, now time.Time) error
- func VerifySession(secret []byte, token string, now time.Time) error
- func WriteLinkState(path string, s LinkState) error
- type Agent
- type Appended
- type AppsEvent
- type AppsGuest
- type Audit
- type Claims
- type Config
- type DocBinding
- type DocResult
- type F
- type Hello
- type LinkState
- type MachineFile
- type PolicyStore
- func (s *PolicyStore) Current() hubproto.Policy
- func (s *PolicyStore) Disabled() bool
- func (s *PolicyStore) Held() bool
- func (s *PolicyStore) Path() string
- func (s *PolicyStore) ProtectedPaths() []string
- func (s *PolicyStore) Reload(force bool)
- func (s *PolicyStore) Soft() bool
- func (s *PolicyStore) SwitchFiles() []string
- func (s *PolicyStore) Watch(stop <-chan struct{}, d time.Duration)
- type ReadChunk
- type RegisterOptions
- type Roots
- type SitesSession
- type StateFile
- type StateResult
- type TranscriptFile
- type TunnelOpen
- type UsageDeps
- type UsageFeed
Constants ¶
const ( AppsTeamChanged = "apps.team.changed" AppsPublicChanged = "apps.public.changed" AppsGuestCreate = "apps.guest.created" AppsGuestRevoke = "apps.guest.revoked" // AppsGuestSync is runtime → agent only: the full set of live links, which replaces what the agent holds. AppsGuestSync = "apps.guest.sync" )
const ( AuthAuto = "auto" AuthEd25519 = "ed25519" AuthHS256 = "hs256" )
Authentication of the dial.
const ( ListenPath = "/v1" DialPath = "/agent/v1" Protocol = 1 )
const ( DesignCreated = "design.created" DesignClaim = "design.claim" DesignDeleted = "design.deleted" )
const ( FrameData byte = 1 FrameClose byte = 2 )
const MaxPayload = 32 * 1024 * 1024
MaxPayload bounds one frame: a page's own socket message (a long paste into the terminal) travels whole inside one tunnel frame.
Variables ¶
var ( RootStateFiles = []string{"workspaces.json", "quick-prompts.json", "sidebar-items.json", "keybindings.json"} WorkspaceStateFiles = []string{"layout.json", "message-history.json"} )
Files of the runtime's data directory the cluster keeps a copy of.
var BuildVersion = "dev"
BuildVersion is set at link time: -ldflags "-X github.com/ly-solutions/harnessly/internal/agent.BuildVersion=1.2.3".
var ErrNoAgent = errors.New("no machine agent on this machine")
ErrNoAgent: no agent.json lies in the data directory, so no machine agent runs for this account.
Functions ¶
func CallLocal ¶ added in v0.16.5
func CallLocal(client *http.Client, dataDir, tokenHeader, route string, body any, timeout time.Duration) (int, []byte, error)
CallLocal posts a JSON body to a loopback route of the machine agent whose agent.json lies in dataDir, and returns the status and body of its answer. It is how the runtime reaches the cluster for documents.
func DecodeFrame ¶
func DefaultMachineFile ¶ added in v0.16.5
DefaultMachineFile is where machine.json lives in a data folder.
func DefaultPolicy ¶ added in v0.16.5
DefaultPolicy is what a machine without a policy file allows: everything.
func EmitAppsEvent ¶ added in v0.16.86
EmitAppsEvent asks the machine agent whose agent.json lies in dataDir to send an apps event to the cluster. It never blocks the caller and never reports a failure: no agent, no event.
func EmitDesignEvent ¶ added in v0.15.40
func EmitDesignEvent(dataDir, tokenHeader, kind, project string)
EmitDesignEvent asks the machine agent whose agent.json lies in dataDir to send a design event to the cluster. It never blocks the caller and never reports a failure: no agent, no event.
func EnsureGitKey ¶ added in v0.16.5
EnsureGitKey is EnsureGitKeyIn without the record of what was made.
func EnsureGitKeyIn ¶ added in v0.16.5
EnsureGitKeyIn makes the git key when there is none and makes sure ssh offers it to the git hosts; it returns the public half. Run again, it changes nothing. What it makes is recorded in dataDir (when given) for RemoveGitKey.
func IsClusterOwnedName ¶
IsClusterOwnedName: files nothing on the machine writes but the cluster's own routes.
func IsLayoutStateName ¶
IsLayoutStateName: the files the cluster keeps the truth of as versioned documents.
func LinkStatePath ¶ added in v0.16.5
LinkStatePath is where the agent keeps its state in a data folder.
func Log ¶
Log writes one JSON line: level, msg, the extra fields, time. Info goes to stdout, warn and error to stderr.
func Narrowed ¶ added in v0.16.5
Narrowed says the new policy allows less than the old one did: something was switched off or a route denied.
func ParsePolicy ¶ added in v0.16.5
ParsePolicy reads the text of a policy.toml over the defaults. Unknown keys, values of the wrong type and routes that are not paths are errors: a typo must not pass for permission.
func RemoveGitKey ¶ added in v0.16.5
RemoveGitKey undoes EnsureGitKeyIn: the marked block leaves ~/.ssh/config, and what the agent made (the key, its .pub, the config file, the folder, as the record says) goes. A key, a file or a folder that was there before the agent came stays. It returns what it removed.
func RunCLI ¶ added in v0.16.5
RunCLI runs one of the commands and returns the process's exit code. handled is false for no command (run the agent).
func SendAppsEvent ¶ added in v0.16.86
SendAppsEvent hands one event to the machine agent and says whether it took it.
func SessionExpiry ¶
SessionExpiry is the expiry (epoch seconds) of a valid page session token; false for any other token or one without an expiry.
func SessionSubject ¶
SessionSubject is the `sub` of a valid page session token (the machine agent signs its own with its name); false for any other token.
func SignPayload ¶
SignPayload signs fields of its own with aud, iat and exp set: valid from now for ttl. A token with an audience is never a page session.
func Unlink ¶ added in v0.16.5
Unlink asks the hub to remove this machine, with the signature of the machine's own key (DELETE /agent/v1 on the hub that the dial URL points at). It returns nil when the hub no longer has the machine, whether it was removed now or was gone before. The files of the machine stay.
func VerifiedAudience ¶
VerifiedAudience is the payload of a token signed with secret, valid now and naming audience; false otherwise.
func VerifiedPayload ¶
VerifiedPayload is the payload of any token signed with the pair's secret and valid now, audience or not (what the previous runtime's verifySessionToken returned); false otherwise.
func VerifyHS256 ¶
VerifyHS256 accepts a compact HS256 token signed with secret, naming audience, not expired and already valid.
func VerifySession ¶
VerifySession accepts a page session token: signed with the pair's secret, valid now, and naming no audience — a token with one belongs to the agent's link, never to a page.
func WriteLinkState ¶ added in v0.16.5
WriteLinkState replaces the file whole, readable by the account only.
Types ¶
type Agent ¶
type Agent struct {
// contains filtered or unexported fields
}
Agent is the machine end of the cluster link for one Unix account.
func (*Agent) ReloadPolicy ¶ added in v0.16.5
func (a *Agent) ReloadPolicy()
ReloadPolicy reads the policy file again (SIGHUP).
type AppsEvent ¶ added in v0.16.86
type AppsEvent struct {
Event string `json:"event"`
ID string `json:"id,omitempty"`
Hash string `json:"hash,omitempty"`
At int64 `json:"expiresAt,omitempty"`
Links []AppsGuest `json:"links,omitempty"`
}
AppsEvent is the body of the runtime's POST /apps/event.
type AppsGuest ¶ added in v0.16.86
type AppsGuest struct {
ID string `json:"id"`
Hash string `json:"hash"`
ExpiresAt int64 `json:"expiresAt"`
}
AppsGuest is one live guest link as the cluster learns of it.
type Audit ¶ added in v0.16.5
type Audit struct {
// contains filtered or unexported fields
}
Audit is agent-audit.log: one JSON line for each operation that changes something on the machine, and for each thing the policy refused. It says what was done and to which name, never a key, a code, a password or a secret's value.
type Claims ¶
type Claims struct {
Sub string `json:"sub,omitempty"`
Aud string `json:"aud,omitempty"`
Iat int64 `json:"iat"`
Exp int64 `json:"exp"`
}
Claims of the tokens the agent signs. Empty fields are left out.
type Config ¶
type Config struct {
Home string
Host string
Port int
Version string
// ScanInterval is the full transcript scan: a safety net for events the watcher missed.
ScanInterval time.Duration
// DataDir is the runtime's data directory: state files, agent.json, eval runs.
DataDir string
// ConfigFile holds the runtime's authSecret when SecretFile is not given.
ConfigFile string
SecretFile string
// RuntimePort is the runtime's own HTTP API on loopback; FilesPort the disk service next to it. Zero: not here.
RuntimePort int
FilesPort int
// UsageFeed builds what fills the usage outbox for a hub. It is a function handed in by cmd/agent because
// the usage report that reads the transcripts imports this package. nil: the machine reports no spend.
UsageFeed func(UsageDeps) (UsageFeed, error)
// ClusterURL and RuntimeID make the agent dial the cluster itself; without both it only listens.
ClusterURL string
RuntimeID string
// ListenAudience is the audience of a token the cluster presents on /v1; DialAudience the one this agent signs
// when it dials. They differ so a token for one direction is never accepted in the other.
ListenAudience string
DialAudience string
// RuntimeAPI is the prefix of the runtime routes the agent calls: <prefix>/machines, <prefix>/automations/start…
RuntimeAPI string
StateChangedPath string
StatusPath string
SyncPath string
// V2Path is the runtime's v2 API: <prefix>/replica, <prefix>/conversations/<id>/turns.
V2Path string
RuntimeCookie string
// CLITokenHeaders carry the runtime's cli-token when the agent tells it a state file changed.
CLITokenHeaders []string
// LocalTokenHeader carries the token from agent.json on the loopback routes the CLIs call.
LocalTokenHeader string
// ReportPortEnv is the variable a launched automation conversation finds this agent's port in.
ReportPortEnv string
// ExtraStateFiles are files of the data directory's root the platform also keeps a copy of.
ExtraStateFiles []string
// Auth is AGENT_AUTH: "auto" (a hub when machine.json exists, else the closed cluster), "ed25519" or "hs256".
Auth string
// Machine is machine.json when the agent dials a hub (nil: it does not).
Machine *MachineFile
MachineFile string
// ObserveMachine is the machine.json of a hub that only sees this machine while the agent keeps its closed cluster's
// link (AGENT_HUB_OBSERVE_FILE); nil when there is none, or when the agent is a hub's machine already.
ObserveMachine *MachineFile
ObserveMachineFile string
// PolicyFile is AGENT_POLICY_FILE ("": /etc/harnessly/policy.toml if there is one, else the account's).
PolicyFile string
// EnvDir holds the env files the agents' launches source; WorkDir is the folder whose disk the preflight reports.
EnvDir string
WorkDir string
}
Config is everything the agent takes from its environment. Names a particular platform gives its routes, headers and directories are settings with neutral defaults, so one binary serves any deployment.
func (Config) LoadSecret ¶
LoadSecret is the pair's session secret: an explicit file wins, else the runtime config's authSecret.
type DocBinding ¶
type DocBinding struct {
Slug string `json:"slug"`
Kind string `json:"kind"`
Key *string `json:"key"`
Title string `json:"title"`
TabID *string `json:"tabId"`
SessionName *string `json:"sessionName"`
AgentSessionID *string `json:"agentSessionId"`
Provider string `json:"provider"`
SourcePath *string `json:"sourcePath"`
Cwd *string `json:"cwd"`
}
type DocResult ¶ added in v0.16.5
type DocResult struct {
Status int `json:"status"`
Body json.RawMessage `json:"body"`
}
DocResult is the cluster's answer to doc.publish and doc.acl.
type Hello ¶
type Hello struct {
Protocol int `json:"protocol"`
AgentVersion string `json:"agentVersion"`
User string `json:"user"`
Home string `json:"home"`
Hostname string `json:"hostname"`
Features []string `json:"features"`
}
Hello is the answer to `hello`.
type LinkState ¶ added in v0.16.5
type LinkState struct {
PID int `json:"pid"`
MachineID string `json:"machineId"`
HubURL string `json:"hubUrl"`
Linked bool `json:"linked"`
// Since is when the link came up (epoch ms), 0 while there is none.
Since int64 `json:"since,omitempty"`
// Note says why there is no link: dialling, revoked, a refused signature…
Note string `json:"note,omitempty"`
Version string `json:"version,omitempty"`
// UpdatedAt is refreshed every few seconds; a file that stopped being refreshed belongs to an agent that is gone.
UpdatedAt int64 `json:"updatedAt"`
}
LinkState is agent-link.json, what the running agent tells `harnessly-agent status`: the installer waits on it to learn that the machine is linked, and a person looks at it when a machine is not showing up. It holds no secret.
func ReadLinkState ¶ added in v0.16.5
ReadLinkState reads the file; os.ErrNotExist (wrapped) when there is none.
type MachineFile ¶ added in v0.16.5
type MachineFile struct {
MachineID string `json:"machineId"`
HubURL string `json:"hubUrl"`
DialURL string `json:"dialUrl"`
RuntimeBasePath string `json:"runtimeBasePath"`
Profile hubproto.Profile `json:"profile"`
// Ed25519 is the signing key's 32-byte seed, X25519 the sealing key's private key; both base64.
Ed25519 string `json:"ed25519"`
X25519 string `json:"x25519"`
RegisteredAt string `json:"registeredAt"`
}
MachineFile is machine.json: who this machine is to a hub and the two private keys it proved it with. It is written once, by `harnessly-agent register`, readable by its account only.
func LoadMachine ¶ added in v0.16.5
func LoadMachine(path string) (*MachineFile, error)
LoadMachine reads and checks machine.json. os.ErrNotExist is returned (wrapped) when there is none.
func Register ¶ added in v0.16.5
func Register(ctx context.Context, o RegisterOptions) (*MachineFile, error)
Register exchanges the code for a machine id: it makes the machine's keys, tells the hub their public halves, and writes machine.json with the private ones. The file is written only after the hub said yes, and never over another registration without Force. The error's text is what the person should read.
func Reusable ¶ added in v0.16.5
func Reusable(machineFile, hub string, profile hubproto.Profile) (*MachineFile, bool)
Reusable returns the registration in machineFile when it is valid, belongs to hub and has the profile: running the installer again on a registered machine then updates the programs and leaves the one machine the hub already has. It asks nothing of the hub, so a code that was used already does not matter.
func (*MachineFile) Save ¶ added in v0.16.5
func (m *MachineFile) Save(path string) error
Save writes the file: 0600 in a folder of 0700, replaced whole.
func (*MachineFile) SealingKey ¶ added in v0.16.5
func (m *MachineFile) SealingKey() []byte
SealingKey is the X25519 private key envelopes are opened with.
func (*MachineFile) SigningKey ¶ added in v0.16.5
func (m *MachineFile) SigningKey() ed25519.PrivateKey
SigningKey is the Ed25519 key the dial is signed with.
type PolicyStore ¶ added in v0.16.5
type PolicyStore struct {
// OnPolicy is called (outside the lock) when the policy changed; OnSwitch when the kill switch did.
OnPolicy func(old, now hubproto.Policy)
OnSwitch func(off bool)
// contains filtered or unexported fields
}
PolicyStore holds the current policy and the kill switch, and notices when either changes.
func NewPolicyStore ¶ added in v0.16.5
func NewPolicyStore(explicit, home, dataDir string) *PolicyStore
NewPolicyStore starts with the defaults; Reload reads the file.
func (*PolicyStore) Current ¶ added in v0.16.5
func (s *PolicyStore) Current() hubproto.Policy
Current is the policy in force.
func (*PolicyStore) Disabled ¶ added in v0.16.5
func (s *PolicyStore) Disabled() bool
Disabled says the kill switch is on.
func (*PolicyStore) Held ¶ added in v0.16.5
func (s *PolicyStore) Held() bool
Held says a change of the file that allows more than the agent allows is waiting for a SIGHUP or a restart.
func (*PolicyStore) Path ¶ added in v0.16.5
func (s *PolicyStore) Path() string
Path is the policy file in use: the explicit one, else the system one when it exists, else the account's.
func (*PolicyStore) ProtectedPaths ¶ added in v0.16.5
func (s *PolicyStore) ProtectedPaths() []string
ProtectedPaths are the files whose writing the route filter refuses to the hub: the policy file and the kill switch.
func (*PolicyStore) Reload ¶ added in v0.16.5
func (s *PolicyStore) Reload(force bool)
Reload reads the policy file when it changed since the last read (or always, with force), and looks at the kill switch. It reports what changed through OnPolicy and OnSwitch.
force is the start and SIGHUP: what a person at the machine does. Without it, a file the agent's account can write (see the top of this file) is trusted only to narrow the policy: what it allows beyond the policy the agent runs with is held, and the next SIGHUP or restart applies it. A file with an error still closes everything at once, and mending it opens up to what the agent ran with, no further.
func (*PolicyStore) Soft ¶ added in v0.16.5
func (s *PolicyStore) Soft() bool
Soft says the policy file in use is one the agent's account can change, so a change of it that allows more waits for a SIGHUP or a restart. False for a file only root can change, and when there is no file.
func (*PolicyStore) SwitchFiles ¶ added in v0.16.5
func (s *PolicyStore) SwitchFiles() []string
SwitchFiles are the places a `disabled` file switches the agent off: next to the policy file (both candidates when the file is not named), and in the data folder.
func (*PolicyStore) Watch ¶ added in v0.16.5
func (s *PolicyStore) Watch(stop <-chan struct{}, d time.Duration)
Watch looks at the file and the kill switch every d until stop closes.
type ReadChunk ¶
type ReadChunk struct {
Offset int64 `json:"offset"`
Size int64 `json:"size"`
Inode uint64 `json:"inode"`
Data string `json:"data"`
Next int64 `json:"next"`
LineTooLong bool `json:"lineTooLong"`
}
ReadChunk answers `transcripts.read`: complete lines only, base64 of the raw bytes.
type RegisterOptions ¶ added in v0.16.5
type RegisterOptions struct {
Hub string // the hub's public URL
Code string // the one-time registration code, hx_…
Profile hubproto.Profile
Via hubproto.Via // "" means command
// MachineFile is where machine.json goes.
MachineFile string
// Force registers again over an existing machine.json.
Force bool
// Name is what the machine calls itself to the hub ("" means the host's name).
Name string
Version string
// HTTP is the client to call the hub with (nil: one with a 30 s timeout).
HTTP *http.Client
Now func() time.Time
}
RegisterOptions are what `harnessly-agent register` was given.
type Roots ¶
Roots are where the two CLIs keep a Unix account's transcripts.
func TranscriptRoots ¶
func (Roots) IsTranscriptPath ¶
IsTranscriptPath says the request names a transcript this agent serves, not an arbitrary file.
type SitesSession ¶ added in v0.16.15
type SitesSession struct {
URL string `json:"url"`
Space string `json:"space"`
Token string `json:"token"`
ExpiresAt string `json:"expiresAt"`
}
SitesSession is the hub's answer to a machine that asked for a publishing session: where the sites API is, the space the machine belongs to and the token to publish with.
func FetchSitesSession ¶ added in v0.16.15
func FetchSitesSession(ctx context.Context, dataDir, tokenHeader, person string) (SitesSession, error)
FetchSitesSession is what a runtime does to publish: it asks the machine agent whose agent.json lies in dataDir for a session. The error says what to tell the person (no agent, no hub, a hub that does not publish).
func RequestSitesSession ¶ added in v0.16.15
func RequestSitesSession(ctx context.Context, m *MachineFile, client *http.Client, now time.Time, person string) (SitesSession, error)
RequestSitesSession asks the hub (POST /agent/sites on the host the dial URL points at) for a publishing session of the machine's space, signed with the machine's own key.
type StateResult ¶
type StateResult struct {
OK bool `json:"ok"`
Version *float64 `json:"version,omitempty"`
Content json.RawMessage `json:"content,omitempty"`
Error *string `json:"error,omitempty"`
}
StateResult is the cluster's answer to a state commit or patch.
type TranscriptFile ¶
type TranscriptFile struct {
Provider string `json:"provider"`
Path string `json:"path"`
Size int64 `json:"size"`
Inode uint64 `json:"inode"`
MtimeMs float64 `json:"mtimeMs"`
// SeenAt is when the agent noticed the change (events only), to measure delivery latency.
SeenAt *int64 `json:"seenAt,omitempty"`
// Appended carries the complete lines the change added, valid only if the reader's offset equals From.
Appended *Appended `json:"appended,omitempty"`
}
TranscriptFile is one transcript as the agent sees it.
func ListTranscripts ¶
func ListTranscripts(r Roots) ([]TranscriptFile, error)
ListTranscripts is every transcript of the account: Claude — projects/<project>/<session>.jsonl and the subagent transcripts under projects/<project>/<session>/subagents/; Codex — sessions/YYYY/MM/DD/*.jsonl.
type TunnelOpen ¶
TunnelOpen is the request to open one.
type UsageDeps ¶ added in v0.16.86
type UsageDeps struct {
Box *usageoutbox.Outbox
// Dir is the outbox's folder, where the feed keeps what it has written.
Dir string
Home, DataDir string
// RuntimeDir is the runtime's data directory, where it keeps its usage facts file; DataDir is the agent's own
// folder for the hub, which is a subfolder of it on a machine that only observes.
RuntimeDir string
Hostname string
// Getenv is a variable as a CLI started by the agent would see it (provider is claude or codex).
Getenv func(provider, name string) string
}
UsageDeps is what a feed is built from.
type UsageFeed ¶ added in v0.16.86
type UsageFeed interface {
// Run looks at the transcripts now and then every interval until ctx is done; written is told the epoch and newest
// seq of the outbox after a pass that wrote something.
Run(ctx context.Context, every time.Duration, written func(epoch string, last int64))
}
UsageFeed fills the usage outbox from the transcripts' facts. Its package reads the runtime's usage report, which imports this one, so cmd/agent builds it and hands it over in Config.UsageFeed.
Source Files
¶
- agent.go
- appsevent.go
- audit.go
- budget.go
- cli.go
- config.go
- designevent.go
- docrelay.go
- envkeeper.go
- gitkey.go
- hub.go
- hubdial.go
- hubops.go
- jwt.go
- link.go
- linkstate.go
- local.go
- localcall.go
- log.go
- machinefile.go
- metrics.go
- nofollow_unix.go
- notifyrelay.go
- policy.go
- policytrust_unix.go
- protocol.go
- register.go
- relay.go
- replica.go
- restart.go
- routefilter.go
- server.go
- sitesession.go
- stat_linux.go
- stat_unix.go
- state.go
- sysinfo.go
- sysinfo_linux.go
- sysinfo_unix.go
- transcripts.go
- tunnels.go
- unlink.go
- usage.go
- watch.go