clientstate

package
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: MIT Imports: 27 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 clientstate keeps the local MCP client's durable registration state: a stable per-PC client id and, per (project, harness, session), the registration id, assigned name and client-generated resume secret. Nothing here is exposed to the model; the secret proves ownership to the broker.

Index

Constants

View Source
const (
	// DeviceRequested records a request id before its code request is sent,
	// so a lost answer or a restart retries with the same id.
	DeviceRequested = "requested"
	DevicePending   = "pending"
	DeviceRedeemed  = "redeemed"
	DeviceDenied    = "denied"
	DeviceExpired   = "expired"
	DeviceRejected  = "rejected"
	DeviceFailed    = "failed"
)

Device authorization outcomes kept with a session so a restarted client resumes waiting, and never re-requests a code after a final answer without an explicit user request.

View Source
const DiagnosticByteLimit = 128 * 1024
View Source
const DiagnosticEventLimit = 256
View Source
const EnvDir = "AGENT_SESSION_BROKER_STATE_DIR"

Variables

View Source
var ErrHandoverChain = errors.New("handover chain is unavailable")
View Source
var ErrHandoverDetached = errors.New("handover conversation is detached")
View Source
var ErrHandoverNotFound = fmt.Errorf("%w: holder not found", ErrHandoverChain)

ErrHandoverNotFound is an explicit fail-closed resolution: no new admission may be attempted when saved revisions cannot identify one current holder.

View Source
var ErrLocked = errors.New("another local MCP client already holds this registration; stop it before registering again")

ErrLocked means another local client process already owns this registration.

View Source
var ErrSteerChanged = errors.New("steer attempt changed")
View Source
var ErrSteerRecovery = errors.New("steer recovery unavailable")

Functions

func DefaultDir

func DefaultDir() (string, error)

DefaultDir is the per-user state directory, overridable for tests and unusual profiles through EnvDir.

func MACAddress

func MACAddress() string

MACAddress reports the first hardware address of a non-loopback interface in index order, as registration metadata only. It is empty when no interface exposes one.

func NewSecret

func NewSecret() string

NewSecret returns a 64-character hex resume secret from 32 random bytes.

func RegistrationKey

func RegistrationKey(scope, harness, sessionID string) string

RegistrationKey names the state file for one registration. scope should identify the broker endpoint and project so the same session registered with two brokers keeps separate secrets and locks.

func SessionKey

func SessionKey(scope, harness, sessionID, clientID string) string

SessionKey names one conversation's state directory. Unlike RegistrationKey it includes the PC client id, so a copied auth directory on another PC does not silently share a session's ownership proof.

Types

type AutoRecovery

type AutoRecovery struct {
	Kind          string    `json:"kind,omitempty"`
	StopReason    string    `json:"stop_reason,omitempty"`
	Attempts      int       `json:"attempts,omitempty"`
	NextAttemptAt time.Time `json:"next_attempt_at,omitzero"`
}

SessionState is one conversation's durable state under the auth directory: registration ownership (resume secret, revision, replayable request), the session credential and the device authorization progress. AutoRecovery records automatic recovery without persisting a bearer in diagnostics. Retry deadlines survive restart, including Retry-After.

type DeviceAuthorization

type DeviceAuthorization struct {
	VerificationURIComplete string    `json:"verification_uri_complete,omitempty"`
	RequestedNickname       string    `json:"requested_nickname,omitempty"`
	RequestID               string    `json:"request_id"`
	DeviceCode              string    `json:"device_code,omitempty"`
	UserCode                string    `json:"user_code,omitempty"`
	VerificationURI         string    `json:"verification_uri,omitempty"`
	ExpiresAt               time.Time `json:"expires_at,omitzero"`
	Interval                int       `json:"interval,omitempty"`
	Status                  string    `json:"status"`
	Error                   string    `json:"error,omitempty"`
}

DeviceAuthorization is the pending or finished code request for a session.

type DiagnosticEvent

type DiagnosticEvent struct {
	At             time.Time `json:"at"`
	SessionID      string    `json:"sessionId"`
	RegistrationID string    `json:"registrationId,omitempty"`
	Generation     uint64    `json:"generation,omitempty"`
	Event          string    `json:"event"`
	Reason         string    `json:"reason,omitempty"`
	ErrorClass     string    `json:"errorClass,omitempty"`
	AuthState      string    `json:"authState,omitempty"`
	// contains filtered or unexported fields
}

DiagnosticEvent accepts identifiers and closed reason vocabularies only. It deliberately has no free-form message, error, endpoint or credential field.

func (DiagnosticEvent) MarshalJSON

func (e DiagnosticEvent) MarshalJSON() ([]byte, error)

func (*DiagnosticEvent) UnmarshalJSON

func (e *DiagnosticEvent) UnmarshalJSON(raw []byte) (err error)

type DiagnosticSummary

type DiagnosticSummary struct {
	UnknownCodes      int       `json:"unknownCodes,omitempty"`
	HandoverSkipped   string    `json:"handoverSkipped,omitempty"`
	Unavailable       bool      `json:"unavailable,omitempty"`
	LastRenewSuccess  time.Time `json:"lastRenewSuccess,omitzero"`
	LastFailureAt     time.Time `json:"lastFailureAt,omitzero"`
	LastFailureReason string    `json:"lastFailureReason,omitempty"`
	LastFailureCode   string    `json:"lastFailureCode,omitempty"`
	LastFailureClass  string    `json:"lastFailureClass,omitempty"`
	LastReceiverExit  string    `json:"lastReceiverExit,omitempty"`
	AuthState         string    `json:"authState,omitempty"`
	// contains filtered or unexported fields
}

func (DiagnosticSummary) MarshalJSON

func (s DiagnosticSummary) MarshalJSON() ([]byte, error)

func (*DiagnosticSummary) UnmarshalJSON

func (s *DiagnosticSummary) UnmarshalJSON(raw []byte) (err error)

type Diagnostics

type Diagnostics struct {
	Format  int               `json:"format,omitempty"`
	Summary DiagnosticSummary `json:"summary"`
	Events  []DiagnosticEvent `json:"events"`
	// contains filtered or unexported fields
}

func SafeDiagnostics

func SafeDiagnostics(d Diagnostics) Diagnostics

SafeDiagnostics projects only known typed fields, never extension data or raw codes.

func (Diagnostics) MarshalJSON

func (d Diagnostics) MarshalJSON() ([]byte, error)

func (*Diagnostics) UnmarshalJSON

func (d *Diagnostics) UnmarshalJSON(raw []byte) (err error)

type DirectAuthorization

type DirectAuthorization struct {
	Reattach          bool      `json:"reattach,omitempty"`
	RequestID         string    `json:"request_id"`
	RequestedNickname string    `json:"requested_nickname,omitempty"`
	CreatedAt         time.Time `json:"created_at"`
	Status            string    `json:"status"`
	Restricted        bool      `json:"restricted,omitempty"`
}

type HandoverAttempt

type HandoverAttempt struct {
	Manual       bool         `json:"manual,omitempty"`
	StopReason   string       `json:"stopReason,omitempty"`
	SourceKey    string       `json:"sourceKey"`
	RequestID    string       `json:"requestId"`
	Registration Registration `json:"registration"`
}

type ProjectKnowledge

type ProjectKnowledge struct {
	GenerationID string `json:"generation_id,omitempty"`
	Supported    bool   `json:"supported,omitempty"`
	Terminal     string `json:"terminal,omitempty"`
}

Provenance is a credential fingerprint, never a bearer or diagnostic field.

type PruneResult

type PruneResult struct {
	Sessions      int
	Registrations int
	Diagnostics   int
	SteerAttempts int
	Skipped       int
	Errors        int
}

PruneResult contains counts only; filenames and credential contents are never reported.

type ReceiverIdentity

type ReceiverIdentity struct {
	Scope string
	// contains filtered or unexported fields
}

func NewReceiverIdentity

func NewReceiverIdentity(scope string) *ReceiverIdentity

func (*ReceiverIdentity) Current

func (*ReceiverIdentity) Dead

func (*ReceiverIdentity) DiagnosticCause

func (r *ReceiverIdentity) DiagnosticCause() string

type Registration

type Registration struct {
	ParentPID      int                    `json:"parent_pid,omitempty"`
	ProcessKey     string                 `json:"process_key,omitempty"`
	SavedAt        time.Time              `json:"saved_at,omitzero"`
	HandedOverTo   string                 `json:"handed_over_to,omitempty"`
	HandoverFrom   *protocol.HandoverFrom `json:"handoverFrom,omitempty"`
	Detached       bool                   `json:"detached,omitempty"`
	InitialAttempt string                 `json:"initial_registration_attempt,omitempty"`
	RegistrationID string                 `json:"registration_id,omitempty"`
	Name           string                 `json:"name,omitempty"`
	Secret         string                 `json:"secret"`
	Revision       uint64                 `json:"revision,omitempty"`
	Project        string                 `json:"project"`
	Harness        string                 `json:"harness"`
	SessionID      string                 `json:"session_id"`
	// Pending fields describe a register request whose answer may have been
	// lost. Retrying the exact same request id, lease and revision lets the
	// broker answer idempotently instead of creating or fencing anew.
	PendingRequestID string `json:"pending_request_id,omitempty"`
	PendingLease     string `json:"pending_lease,omitempty"`
	PendingRevision  uint64 `json:"pending_revision,omitempty"`
}

type SavedConversation

type SavedConversation struct {
	Key   string
	State SessionState
}

type SessionCredential

type SessionCredential struct {
	Scopes         []string  `json:"scopes,omitempty"`
	AdmissionMode  string    `json:"admission_mode,omitempty"`
	AccessToken    string    `json:"access_token"`
	TokenType      string    `json:"token_type"`
	IssuedAt       time.Time `json:"issued_at,omitzero"`
	ExpiresAt      time.Time `json:"expires_at,omitzero"`
	SessionGrantID string    `json:"session_grant_id,omitempty"`
	Nickname       string    `json:"nickname,omitempty"`
}

SessionCredential is the broker-issued per-session bearer credential. It is the only value sent to /mcp; the project token never reaches that endpoint.

type SessionState

type SessionState struct {
	Handover             *HandoverAttempt     `json:"handover,omitempty"`
	AdmissionFingerprint string               `json:"admission_fingerprint,omitempty"`
	RestrictedAdmission  bool                 `json:"restricted_admission,omitempty"`
	LastAdmissionMode    string               `json:"last_admission_mode,omitempty"`
	AutoRecovery         *AutoRecovery        `json:"auto_recovery,omitempty"`
	SchemaVersion        int                  `json:"schema_version"`
	Scope                string               `json:"scope"`
	Project              string               `json:"project"`
	Harness              string               `json:"harness"`
	SessionID            string               `json:"session_id"`
	ClientID             string               `json:"client_id"`
	Registration         Registration         `json:"registration"`
	Credential           *SessionCredential   `json:"credential,omitempty"`
	Direct               *DirectAuthorization `json:"direct,omitempty"`
	Device               *DeviceAuthorization `json:"device,omitempty"`
}

type SteerAttempt

type SteerAttempt struct {
	ClientID  string   `json:"clientId"`
	Sequences []uint64 `json:"sequences"`
	Turns     []string `json:"turns"`
}

type SteerAttemptRecord

type SteerAttemptRecord struct {
	Format       int           `json:"format"`
	Scope        string        `json:"scopeDigest"`
	Thread       string        `json:"thread"`
	Registration string        `json:"registration,omitempty"`
	Epoch        string        `json:"epoch,omitempty"`
	Pending      *SteerAttempt `json:"pending,omitempty"`
}

type Store

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

func Open

func Open(dir string) (*Store, error)

func (*Store) AdoptLegacyRegistration

func (s *Store) AdoptLegacyRegistration(key, legacyKey string) (bool, error)

AdoptLegacyRegistration copies the ownership proof of a legacy registration file into a new session state when none exists yet. The legacy file stays untouched, and a legacy client that still holds its lock blocks adoption: the broker would otherwise see two owners of one registration.

func (*Store) ClearHandedOver

func (s *Store) ClearHandedOver(key string) error

Only a successful, proved handover may clear the destination's old marker. Ordinary credential writes cannot clear it because it remains a separate file.

func (*Store) ClientID

func (s *Store) ClientID() (string, error)

ClientID returns the stable per-PC identity, creating it on first use. Two clients starting at once on the same PC serialize on an OS lock so both observe the single identity.

func (*Store) DeleteDeliveryWatermark

func (s *Store) DeleteDeliveryWatermark(scope, registration, epoch string) error

DeleteDeliveryWatermark removes only this proven-obsolete epoch. Busy writers are skipped, and the lock inode stays available to current and older clients.

func (*Store) Dir

func (s *Store) Dir() string

func (*Store) FlushDiagnostics

func (s *Store) FlushDiagnostics() error

FlushDiagnostics persists pending success summaries after the owner's writers have stopped. A failed write stays pending so a later flush can retry.

func (*Store) HandoverCandidates

func (s *Store) HandoverCandidates(scope, harness, client string) ([]SavedConversation, error)

Only this client's own validated saved states are candidates. No broker list or arbitrary file path can provide a registration ownership proof.

func (*Store) HandoverHolder

func (s *Store) HandoverHolder(key, scope, harness, client string, allowDetached bool) (SavedConversation, error)

HandoverHolder validates the bounded hint walk, then resolves ownership from saved revisions. A marker cannot erase the destination's committed credential or make an older source authoritative when either marker write was interrupted. Only an explicit handover may allow a detached registration to be revived.

func (*Store) LoadDeliveryWatermark

func (s *Store) LoadDeliveryWatermark(scope, registration, epoch string) (uint64, error)

func (*Store) LoadDiagnostics

func (s *Store) LoadDiagnostics(key string) (Diagnostics, error)

func (*Store) LoadProjectKnowledge

func (s *Store) LoadProjectKnowledge(scope string) (map[string]ProjectKnowledge, error)

func (*Store) LoadRegistration

func (s *Store) LoadRegistration(key string) (Registration, bool, error)

func (*Store) LoadSession

func (s *Store) LoadSession(key string) (SessionState, bool, error)

func (*Store) LoadSteerAttempt

func (s *Store) LoadSteerAttempt(scope, thread string) (SteerAttemptRecord, error)

func (*Store) Lock

func (s *Store) Lock(key string) (func(), error)

Lock takes the OS-level exclusive lock for one registration so a second client process on the same PC cannot run a competing receiver. The lock is released by the returned function or by process exit.

func (*Store) LockSession

func (s *Store) LockSession(key string) (func(), error)

LockSession is the per-conversation OS lock for the new state layout. It is held for the binding's lifetime like Lock is for legacy registrations.

func (*Store) MarkHandedOver

func (s *Store) MarkHandedOver(key, to string) error

A separate handover marker cannot be erased by a late old client's credential/state write. LoadSession overlays it on the saved registration.

func (*Store) Prune

func (s *Store) Prune(now time.Time) (result PruneResult, err error)

Prune removes only recognized, idle direct children of the local state store. Only steer attempts require bounded strict decoding; no live lock is awaited.

func (*Store) RecordDiagnostic

func (s *Store) RecordDiagnostic(key string, e DiagnosticEvent) error

RecordDiagnostic atomically replaces a bounded recent-event file using the same 0600 writer as credentials. Successful heartbeats update memory every time but persist at most once a minute; every other event persists immediately.

func (*Store) RemoveRegistration

func (s *Store) RemoveRegistration(key string) error

func (*Store) SaveDeliveryWatermark

func (s *Store) SaveDeliveryWatermark(scope, registration, epoch string, through uint64) error

Serialize read/replace across client processes; metadata never contains a payload.

func (*Store) SaveProjectKnowledge

func (s *Store) SaveProjectKnowledge(scope string, entries map[string]ProjectKnowledge) error

func (*Store) SaveRegistration

func (s *Store) SaveRegistration(key string, r Registration) error

func (*Store) SaveSession

func (s *Store) SaveSession(key string, state SessionState) error

func (*Store) SaveSteerAttempt

func (s *Store) SaveSteerAttempt(scope, thread string, before, next SteerAttemptRecord) error

Compare the whole body-free record: a retired writer cannot clear its successor.

Jump to

Keyboard shortcuts

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