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
- Variables
- func DefaultDir() (string, error)
- func MACAddress() string
- func NewSecret() string
- func RegistrationKey(scope, harness, sessionID string) string
- func SessionKey(scope, harness, sessionID, clientID string) string
- type AutoRecovery
- type DeviceAuthorization
- type DiagnosticEvent
- type DiagnosticSummary
- type Diagnostics
- type DirectAuthorization
- type HandoverAttempt
- type ProjectKnowledge
- type PruneResult
- type ReceiverIdentity
- type Registration
- type SavedConversation
- type SessionCredential
- type SessionState
- type SteerAttempt
- type SteerAttemptRecord
- type Store
- func (s *Store) AdoptLegacyRegistration(key, legacyKey string) (bool, error)
- func (s *Store) ClearHandedOver(key string) error
- func (s *Store) ClientID() (string, error)
- func (s *Store) DeleteDeliveryWatermark(scope, registration, epoch string) error
- func (s *Store) Dir() string
- func (s *Store) FlushDiagnostics() error
- func (s *Store) HandoverCandidates(scope, harness, client string) ([]SavedConversation, error)
- func (s *Store) HandoverHolder(key, scope, harness, client string, allowDetached bool) (SavedConversation, error)
- func (s *Store) LoadDeliveryWatermark(scope, registration, epoch string) (uint64, error)
- func (s *Store) LoadDiagnostics(key string) (Diagnostics, error)
- func (s *Store) LoadProjectKnowledge(scope string) (map[string]ProjectKnowledge, error)
- func (s *Store) LoadRegistration(key string) (Registration, bool, error)
- func (s *Store) LoadSession(key string) (SessionState, bool, error)
- func (s *Store) LoadSteerAttempt(scope, thread string) (SteerAttemptRecord, error)
- func (s *Store) Lock(key string) (func(), error)
- func (s *Store) LockSession(key string) (func(), error)
- func (s *Store) MarkHandedOver(key, to string) error
- func (s *Store) Prune(now time.Time) (result PruneResult, err error)
- func (s *Store) RecordDiagnostic(key string, e DiagnosticEvent) error
- func (s *Store) RemoveRegistration(key string) error
- func (s *Store) SaveDeliveryWatermark(scope, registration, epoch string, through uint64) error
- func (s *Store) SaveProjectKnowledge(scope string, entries map[string]ProjectKnowledge) error
- func (s *Store) SaveRegistration(key string, r Registration) error
- func (s *Store) SaveSession(key string, state SessionState) error
- func (s *Store) SaveSteerAttempt(scope, thread string, before, next SteerAttemptRecord) error
Constants ¶
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.
const DiagnosticByteLimit = 128 * 1024
const DiagnosticEventLimit = 256
const EnvDir = "AGENT_SESSION_BROKER_STATE_DIR"
Variables ¶
var ErrHandoverChain = errors.New("handover chain is unavailable")
var ErrHandoverDetached = errors.New("handover conversation is detached")
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.
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.
var ErrSteerChanged = errors.New("steer attempt changed")
var ErrSteerRecovery = errors.New("steer recovery unavailable")
Functions ¶
func DefaultDir ¶
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 ¶
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 ¶
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"`
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 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 (r *ReceiverIdentity) Current(ctx context.Context) *protocol.ReceiverHolder
func (*ReceiverIdentity) Dead ¶
func (r *ReceiverIdentity) Dead(ctx context.Context, c protocol.HolderChallenge) bool
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 SteerAttemptRecord ¶
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
func (*Store) AdoptLegacyRegistration ¶
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 ¶
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 ¶
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 ¶
DeleteDeliveryWatermark removes only this proven-obsolete epoch. Busy writers are skipped, and the lock inode stays available to current and older clients.
func (*Store) FlushDiagnostics ¶
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 (*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 ¶
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 ¶
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 ¶
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 (*Store) SaveDeliveryWatermark ¶
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.