Documentation
¶
Overview ¶
Package agentsession owns the exact binding between a Sidecar-managed shell and the native agent conversation running inside it.
Everything here works on structured values: a reference is a kind plus a value, and a resume is an argument vector. Nothing in this package builds, stores, or replays a shell string, because a session identifier that reaches a shell is an injection waiting for a value with a quote in it.
The package is deliberately free of tmux, CLI, TUI, and provider-config dependencies so the rules can be tested as values and reused by the restore coordinator without a terminal.
Index ¶
- Constants
- Variables
- func CanResumeKind(kind string) bool
- func DedupKey(kind string, ref Ref) string
- func Official(source string) bool
- func OfficialSourceFor(kind string) string
- func OfficialSources() []string
- func OmpAgentDir(home, configDirName, agentDirOverride, profile string) string
- func OmpProfile(ompProfile string, ompSet bool, piProfile string) string
- func PiAgentDir(home, override string) string
- func ValidateID(value string) error
- func ValidatePath(value string) error
- func ValidateSource(source string) error
- func ValidateValue(kind RefKind, value string) error
- type Candidate
- type CandidateConfidence
- type CandidateFinder
- type CandidateQuery
- type Decision
- type DedupResult
- type Holder
- type Policy
- type Ref
- type RefKind
- type Report
- type ResumePlan
- type Roots
- type SessionReader
Constants ¶
const ( // MaxIDBytes bounds an opaque identifier. A UUID is 36 bytes; the headroom // covers prefixed and compound identifiers without admitting a payload. MaxIDBytes = 256 // MaxPathBytes bounds a transcript path, comfortably above PATH_MAX on the // platforms Sidecar targets. MaxPathBytes = 1024 // MaxSourceBytes bounds an integration source identifier. MaxSourceBytes = 128 )
Bounds on a reported reference.
These are refusal thresholds, not buffer sizes. A provider that legitimately needs more than this has changed its contract, and the honest answer is to requalify the adapter rather than to widen the bound and hope.
Variables ¶
var ( // ErrInvalidRef means the reference is not a well-formed reference of its // kind, independent of any provider. ErrInvalidRef = errors.New("invalid session reference") // ErrUntrustedSource means the reporting source is not an official Sidecar // integration and so may not set an auto-resumable reference. ErrUntrustedSource = errors.New("untrusted session reference source") // ErrOutsideStoreRoot means a path reference points outside every store root // the provider is approved to keep conversations in. ErrOutsideStoreRoot = errors.New("session path is outside the provider's approved store roots") // ErrStaleGeneration means the report came from a provider process that is // no longer the one running in the pane. ErrStaleGeneration = errors.New("session report is from a stale provider generation") // ErrUnsupportedKind means the provider does not name sessions that way. ErrUnsupportedKind = errors.New("provider does not support that session reference kind") // ErrKindMismatch means the provider a report names is not the provider // running in the pane it would bind. // // This is a different failure from a stale generation, and the distinction // matters. A stale generation is the right provider talking too late; a kind // mismatch is the wrong provider talking on time. The second is reachable // because a hook entry is a file on disk, not a channel: grok reads // ~/.claude/settings.json deliberately, for Claude Code compatibility, so an // installed Claude session-identity hook fires inside grok sessions too and // arrives with a --kind flag that describes the file it was installed in // rather than the process that ran it. Binding on that flag alone recorded a // grok conversation as kind=claude, which a cold restore would then offer to // resume with `claude --resume <grok-id>` — wrong rather than refused. // // So the flag is treated as a claim to be checked, never as evidence. ErrKindMismatch = errors.New("the reported provider is not the provider running in this pane") )
Errors returned by validation. They are values so callers can map them onto their own refusal codes without matching on message text.
Functions ¶
func CanResumeKind ¶
CanResumeKind reports whether a catalog family has a native resume at all. Surfaces use it to show or hide a resume affordance without building a plan.
func DedupKey ¶
DedupKey is the global per-host identity of one native conversation.
The provider kind is part of the key so two providers that happen to mint the same identifier are not reported as a conflict with each other. The separator cannot occur in a validated reference, so the key cannot be forged by a value that contains it.
func OfficialSourceFor ¶
OfficialSourceFor is the official integration source for a catalog family.
A hook that omits --source gets its provider's own official source rather than an empty one, so the ordinary installed path produces a trusted, resumable reference and only a caller that deliberately names a different source gets an untrusted one.
A provider with no shipped integration returns the empty string, and the report-session command turns that into a refusal naming the cause rather than letting the validator complain that the source is blank. A hand-written hook for such a provider can still report by naming --source explicitly, and what it gets is an untrusted reference, which is the honest amount of authority for an integration Sidecar did not write.
func OfficialSources ¶
func OfficialSources() []string
OfficialSources are the integration sources Sidecar itself ships.
Only a reference reported by one of these is ever marked Reported, and only a Reported reference is eligible for automatic resume. A same-cwd adapter discovery may propose a candidate for a human to confirm, but it can never enter this set, because "the newest conversation in this directory" is a guess and resuming the wrong conversation is worse than resuming none.
"Ships" is the whole test, and it is checked against the adapters rather than against intent. This list once carried "sidecar.pi.extension" alongside a capability entry for Pi, and neither was backed by anything: there was no PiAdapter, no asset under internal/agentintegration/assets/pi, and no code path that installed an extension Pi would load. Nothing Sidecar wrote could ever produce a report carrying that source, so the only caller it could have had was a hook somebody wrote by hand, and trusting one of those is exactly the "resume a conversation nobody proved was the right one" the paragraph above refuses. Both were retracted, and Pi is back here now that the port in docs/plans/implemented/herdr-parity-close-the-gap.md, Slice 1, has shipped PiAdapter and internal/agentintegration/assets/pi/sidecar-lifecycle.js, which is what does the reporting.
Being here is a statement about provenance and nothing else: it says Sidecar wrote the thing that sent the report, so the conversation reference may be resumed without a human confirming it. It is not a tier. Pi's capability entry is session-identity on docs-only evidence, and that is what decides how much its *state* reports are trusted; the two are deliberately separate registers.
func OmpAgentDir ¶ added in v1.14.0
OmpAgentDir resolves OMP's agent directory the way OMP itself does.
It exists for the same reason PiAgentDir does, and it is called from the same two places: the installer, which writes the extension into <this>/extensions, and the store root below, which decides which session paths a report from that extension may name. Deriving it twice is how those two drifted for Pi, so there is one derivation and both call it.
The derivation, read from OMP 18.1.8's own @oh-my-pi/pi-utils/src/dirs.ts rather than from Herdr's installer, because the two disagree in one place:
configRoot = $HOME/${PI_CONFIG_DIR:-.omp} (getBaseConfigRoot)
+ /profiles/<profile> when one is active (getProfileConfigRoot)
agentDir = configRoot/agent
unless no profile is active and PI_CODING_AGENT_DIR is set, in
which case it is that value, path.resolve'd (DirResolver)
Two facts in there are easy to get wrong and both were checked against the source. A NAMED PROFILE IGNORES PI_CODING_AGENT_DIR entirely (`const agentDirOverride = profile ? undefined : options.agentDirOverride`), so an installer that honoured the variable under a profile would write where OMP never looks. And PI_CODING_AGENT_DIR IS NOT TILDE-EXPANDED: OMP calls path.resolve on it, where Pi calls its own tilde expansion and Herdr's omp_extension_dir expands a tilde too. path.resolve makes a relative value — "~/..." included, since a leading tilde is not special to it — resolve against whatever directory OMP was launched from, which Sidecar cannot know. So a non-absolute override returns the empty string here, meaning "unknowable", and the adapter refuses with that reason rather than guessing a directory.
func OmpProfile ¶ added in v1.14.0
OmpProfile resolves OMP's active profile the way OMP resolves it.
OMP_PROFILE is canonical and PI_PROFILE is a legacy fallback consulted only when OMP_PROFILE is not set at all — which is why this takes a separate `ompSet` rather than inferring it from an empty string. An explicitly empty OMP_PROFILE selects the default profile and suppresses PI_PROFILE, and that distinction decides which directory the extension has to be installed into.
An invalid name resolves to no profile here. OMP throws on one, and its CLI turns that into "Invalid OMP profile" and refuses to start; its own module-load path takes the same lenient reading this does. Either way there is no session to report from, so the conservative answer is the default directory.
func PiAgentDir ¶ added in v1.13.0
PiAgentDir resolves Pi's agent directory the way Pi itself does, from the home directory and the raw PI_CODING_AGENT_DIR value. An empty result means the answer is unknowable, which happens only when a tilde has to be expanded and the home directory is unknown.
Pi's getAgentDir trims nothing itself, but Sidecar does, and deliberately: a PI_CODING_AGENT_DIR that is whitespace is a variable somebody exported without a value, not a directory named " ". What matters far more than which reading is right is that there is only one of them. This function exists because there were two -- the installer's, in agentintegration, and the store root's, here -- and they had already disagreed on exactly that case, which is the failure this derivation is worth naming: the installer would write the extension into ~/.pi/agent/extensions while the approved root became " /sessions", so the extension installed cleanly and every session binding it sent was refused for being outside the store.
The tilde expansion is Pi's own (dist/config.js:420-426, verified against pi 0.84.3), not a convenience: getAgentDir expands a leading "~" before using the value, so a Sidecar that did not would read and write a literal directory named "~" while Pi used somewhere else entirely.
It lives in this package rather than in agentintegration because this is the package that already owns where every provider keeps its files, and because it is a leaf: agentintegration may import it, and the reverse edge -- a trust primitive importing an installer that pulls in the UI packages -- is one worth refusing.
func ValidateID ¶
ValidateID checks an opaque identifier's shape and bounds.
func ValidatePath ¶
ValidatePath checks a transcript path's shape and bounds.
It does not touch the filesystem: existence is a restore-time question, and a validator that stats is a validator whose answer changes under it.
func ValidateSource ¶
ValidateSource checks an integration source identifier's shape.
func ValidateValue ¶
ValidateValue checks a value against its kind.
Types ¶
type Candidate ¶ added in v1.15.0
type Candidate struct {
// AgentKind records the provider used to discover this candidate when the
// shell itself has no authoritative provider binding (legacy layouts).
AgentKind string `json:"agentKind,omitempty"`
Ref Ref `json:"ref"`
Title string `json:"title,omitempty"`
LastWriteAt time.Time `json:"lastWriteAt,omitzero"`
Confidence CandidateConfidence `json:"confidence"`
Reason string `json:"reason"`
Picker bool `json:"picker,omitempty"`
}
Candidate is a conversation recovered from a provider's own store. Picker is true when equally near sessions remain and the provider's picker should be typed instead of a session-specific command. Ref.Value is empty in that case; Reason names every conversation still in contention.
type CandidateConfidence ¶ added in v1.15.0
type CandidateConfidence string
CandidateConfidence describes how strongly provider-store evidence identifies one conversation. It is deliberately separate from Ref.Reported: discovery can suggest text for a human to submit, but can never authorize auto-resume.
const ( CandidateLikely CandidateConfidence = "likely" CandidateAmbiguous CandidateConfidence = "ambiguous" )
type CandidateFinder ¶ added in v1.15.0
type CandidateFinder struct {
// contains filtered or unexported fields
}
CandidateFinder reads existing provider adapters; it has no tmux or UI dependency and does not mutate provider stores.
func NewCandidateFinder ¶ added in v1.15.0
func NewCandidateFinder() *CandidateFinder
NewCandidateFinder constructs the production finder for providers whose current adapters expose reliable-enough directory and time evidence.
func NewCandidateFinderWithReaders ¶ added in v1.15.0
func NewCandidateFinderWithReaders(readers map[string]SessionReader) *CandidateFinder
NewCandidateFinderWithReaders constructs a finder around adapter-compatible readers. It is exported so restore coordination and focused fixtures can use the same ranking rules without provider-specific filesystem setup.
func (*CandidateFinder) Find ¶ added in v1.15.0
func (f *CandidateFinder) Find(query CandidateQuery) (Candidate, bool, error)
Find returns the nearest unclaimed session inside the shell's alive window. Several distinct write times remain useful evidence: the nearest one wins and the reason names the alternatives. Only a tie at the nearest instant falls back to a provider picker.
type CandidateQuery ¶ added in v1.15.0
type CandidateQuery struct {
WorkDir string
AgentKind string
CreatedAt time.Time
ServerLostAt time.Time
Claimed []Ref
}
CandidateQuery is the shell lifetime and provider scope used for discovery. Claimed references let a coordinator disambiguate several shells in one directory without assigning the same native conversation twice.
type Decision ¶
type Decision string
Decision is what a report did to a shell's stored session reference.
const ( // DecisionRecorded stored a reference where there was none. DecisionRecorded Decision = "recorded" // DecisionRotated replaced a different reference from the same live pane, // which is what a provider does when a user starts a new conversation. DecisionRotated Decision = "rotated" // DecisionCleared removed the stored reference. DecisionCleared Decision = "cleared" // DecisionUnchanged means the report said what was already stored. Replays // are idempotent rather than errors: a hook that runs twice is normal. DecisionUnchanged Decision = "unchanged" // DecisionIgnored means the report lost the generation fence and nothing // was written. DecisionIgnored Decision = "ignored" )
func Fence ¶
Fence decides whether an incoming report may replace the stored reference.
The rule the plan states is that a report replaces the prior reference only when it comes from the current pinned provider/process generation, and that late output from an exited or replaced process is ignored. Both halves matter and they are different comparisons:
- `incoming.Generation` is derived from the reporting hook's own process ancestry — the provider process that is talking.
- `live` is derived independently from what currently occupies the pane.
When those disagree, the process that is talking is not the process that is running, so the report is late and loses. Comparing the incoming report only against the *stored* generation would not catch this at all: a late report from a dead process still matches the record it wrote itself.
A prior reference from an older generation is not an obstacle. A new provider process in the same pane legitimately takes the binding over, which is the difference between "late" and "new".
func FenceClear ¶
FenceClear decides whether an explicit clear may remove the stored reference.
A clear is fenced exactly like a report. A provider process that has already been replaced must not be able to unbind the conversation its successor just bound, which is the same late-writer problem in the other direction.
type DedupResult ¶
type DedupResult struct {
// Key is the dedup key these holders share.
Key string
// Winner is the single shell allowed to resume the conversation.
Winner Holder
// Conflicts are the other shells claiming it. They restore as plain shells
// and are told which target won.
Conflicts []Holder
}
DedupResult is the verdict for one conversation.
func Conflicts ¶
func Conflicts(holders []Holder) []DedupResult
Conflicts returns only the results where more than one shell claims the same conversation.
func Dedup ¶
func Dedup(holders []Holder) []DedupResult
Dedup enforces that one exact native session reference resumes into at most one managed shell on this host.
The most recently reported claim wins, because it is the one a provider most recently confirmed is live; ties break on the tmux session name so the result is stable rather than dependent on manifest order. Losers are not deleted or rewritten — deduplication decides who may *resume*, and a plan that silently edited shell records to enforce it would be destroying evidence.
type Holder ¶
type Holder struct {
Project string
Session string // tmux session name, the shell's durable identity
Name string // display name, for human output
Kind string
Ref Ref
}
Holder is one managed shell that claims a session reference.
type Policy ¶
type Policy string
Policy is a per-shell restore policy.
const ( // PolicyInherit follows the configured machine default. PolicyInherit Policy = "inherit" // PolicyShell recreates the shell but never resumes the agent. PolicyShell Policy = "shell" // PolicyResume recreates the shell and resumes the exact conversation. PolicyResume Policy = "resume" // PolicyNever leaves the shell alone entirely. PolicyNever Policy = "never" )
func ParsePolicy ¶
ParsePolicy accepts a policy name from a caller. An empty value is Inherit, which is what an older record without the field means.
type Ref ¶
type Ref struct {
// Kind is how Value names the conversation.
Kind RefKind `json:"kind"`
// Value is the identifier or absolute path itself.
Value string `json:"value"`
// Source is the integration that reported it, e.g. "sidecar.codex.hooks".
Source string `json:"source"`
// Reported is true when Source is an official Sidecar integration. Only a
// reported reference is ever eligible for automatic resume; a same-cwd
// discovery may propose a candidate but never sets this.
Reported bool `json:"reported"`
// Generation pins the provider process generation that reported the value,
// in the same "pid=N,start=..." form the lifecycle store uses.
Generation string `json:"generation,omitempty"`
// ReportedAt is when the report was accepted.
ReportedAt time.Time `json:"reportedAt,omitzero"`
}
Ref is an exact native session reference as reported by an integration.
A Ref is only ever produced by validation, so an existing Ref value has already passed its bounds, character, and shape rules.
type RefKind ¶
type RefKind string
RefKind is how a provider names one of its own conversations.
func ParseRefKind ¶
ParseRefKind accepts a kind name from a caller.
type Report ¶
type Report struct {
// Kind is the catalog family id of the provider.
Kind string
// RefKind and Value name the conversation.
RefKind RefKind
Value string
// Source is the reporting integration.
Source string
// Generation is the provider process generation the report came from.
Generation string
}
Report is one integration's claim about the conversation in its pane.
It carries only what a provider is allowed to choose: which conversation it is talking about. Who it is talking about — host, server, pane, process generation — is derived by the caller from the environment and live tmux and is never reachable from a flag.
type ResumePlan ¶
type ResumePlan struct {
// Kind is the catalog family id the plan resumes.
Kind string `json:"kind"`
// Argv is the exact command to run.
Argv []string `json:"argv"`
// Ref is the reference being resumed.
Ref Ref `json:"ref"`
}
ResumePlan is a resume expressed as an argument vector.
There is no command-string field, deliberately. A string here would be the one place a session identifier could reach a shell, and every consumer — the Conversations UI, the CLI, and the restore coordinator — would then be one convenience away from interpolating it.
func PlanCandidatePrefill ¶ added in v1.15.0
func PlanCandidatePrefill(kind string, candidate Candidate) (ResumePlan, error)
PlanCandidatePrefill builds text a human may review and submit. It is kept separate from PlanResume so a discovered reference can never become auto resume authority by passing through the wrong caller.
func PlanResume ¶
func PlanResume(kind string, ref Ref) (ResumePlan, error)
PlanResume builds the structured resume for a bound conversation.
It refuses an unreported reference: only an official integration's report is exact enough to resume from, and a candidate discovered by matching working directories is a suggestion for a human, not a command to run.
type Roots ¶
type Roots struct {
// Home is the user's home directory. Injected so tests do not depend on
// the developer's own tree.
Home string
// Env reads an environment variable. Nil means os.Getenv.
Env func(string) string
}
Roots describes where a provider is allowed to keep its conversations.
A path reference outside every root is refused rather than stored. The point is not that a provider would lie; it is that a hook is untrusted local input, and "an absolute path the agent chose" is otherwise a instruction to read an arbitrary file later, at restore time, with Sidecar's privileges.
func (Roots) For ¶
For returns the approved store roots for a catalog family id.
An unknown provider returns no roots, which makes every path reference for it a refusal. That is the intended direction: a provider earns path references by having its store location recorded here, not by reporting one.
func (Roots) WithinRoots ¶
WithinRoots reports whether an already-validated absolute path lies inside one of the provider's approved roots.
Containment is compared on cleaned paths with a separator boundary, so "/home/u/.codexsessions" does not pass as being inside "/home/u/.codex".