agentsession

package
v1.11.0 Latest Latest
Warning

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

Go to latest
Published: Aug 31, 2026 License: MIT Imports: 10 Imported by: 0 modules, 0 packages

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

Documentation

Overview

Package 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

View Source
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

View Source
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

func CanResumeKind(kind string) bool

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

func DedupKey(kind string, ref Ref) string

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 Official

func Official(source string) bool

Official reports whether source is an official Sidecar integration.

func OfficialSourceFor

func OfficialSourceFor(kind string) string

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.

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.

func ValidateID

func ValidateID(value string) error

ValidateID checks an opaque identifier's shape and bounds.

func ValidatePath

func ValidatePath(value string) error

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

func ValidateSource(source string) error

ValidateSource checks an integration source identifier's shape.

func ValidateValue

func ValidateValue(kind RefKind, value string) error

ValidateValue checks a value against its kind.

Types

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 Decisions

func Decisions() []Decision

Decisions lists the vocabulary in a stable order.

func Fence

func Fence(prior *Ref, incoming Ref, live string) (Decision, error)

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

func FenceClear(prior *Ref, generation, live string) (Decision, error)

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

func ParsePolicy(value string) (Policy, error)

ParsePolicy accepts a policy name from a caller. An empty value is Inherit, which is what an older record without the field means.

func Policies

func Policies() []Policy

Policies lists the vocabulary in a stable order.

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.

func Validate

func Validate(rep Report, roots Roots, now func() time.Time) (Ref, error)

Validate turns an untrusted report into a Ref, or refuses.

Everything a later stage relies on is decided here: bounds, character rules, path shape, store-root containment, provider support for the kind, and whether the source is official enough to mark the result auto-resumable.

func (Ref) Empty

func (r Ref) Empty() bool

Empty reports whether the reference names nothing.

type RefKind

type RefKind string

RefKind is how a provider names one of its own conversations.

const (
	// RefID is an opaque provider-assigned identifier, such as a UUID.
	RefID RefKind = "id"
	// RefPath is an absolute path to the provider's own transcript file.
	RefPath RefKind = "path"
)

func ParseRefKind

func ParseRefKind(value string) (RefKind, error)

ParseRefKind accepts a kind name from a caller.

func RefKinds

func RefKinds() []RefKind

RefKinds lists the kinds in the order the CLI documents them.

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

func OSRoots() Roots

OSRoots reads the ambient environment.

func (Roots) For

func (r Roots) For(kind string) []string

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

func (r Roots) WithinRoots(kind, path string) error

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

Jump to

Keyboard shortcuts

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