agentinstance

package
v0.5.1 Latest Latest
Warning

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

Go to latest
Published: Mar 16, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Index

Constants

View Source
const (

	// ExcessivePrimeThreshold is the number of prime calls per instance before warning.
	// Agents should typically call prime once at session start. Multiple calls suggest
	// context compaction issues or agent misconfiguration.
	ExcessivePrimeThreshold = 5
)

Variables

View Source
var ErrInstanceNotFound = errors.New("instance not found")

ErrInstanceNotFound is returned when an operation targets an agent ID that doesn't exist in the store.

Functions

func ClassifyBadID added in v0.2.0

func ClassifyBadID(id string) string

ClassifyBadID returns a diagnostic message explaining why id is not a valid agent ID. Returns empty string if id is valid or doesn't match a known wrong-format pattern (caller should use generic error).

func GenerateAgentID

func GenerateAgentID(existingIDs []string) (string, error)

GenerateAgentID generates a new unique agent ID checking for collisions against existing IDs in the store.

The ID format is Ox<4-char> where chars are [0-9A-Za-z]. This provides 62^4 = 14,776,336 possible combinations.

Examples:

  • GenerateAgentID([]string{}) -> "OxA1b2"
  • GenerateAgentID([]string{"OxA1b2"}) -> "OxC3d4" (different ID)
  • GenerateAgentID([]string{"OxA1b2", ...}) -> error if can't find unique ID after 10 retries

func IsValidAgentID

func IsValidAgentID(id string) bool

IsValidAgentID checks if a string is a valid agent ID format.

Valid format requirements:

  • Must start with "Ox"
  • Must be exactly 6 characters total
  • Suffix (4 chars) must be alphanumeric [0-9A-Za-z]

Examples:

  • IsValidAgentID("OxA1b2") -> true
  • IsValidAgentID("Ox1234") -> true
  • IsValidAgentID("OxZzZz") -> true
  • IsValidAgentID("ox1234") -> false (wrong prefix)
  • IsValidAgentID("OX1234") -> false (wrong prefix)
  • IsValidAgentID("Ox123") -> false (too short)
  • IsValidAgentID("Ox12345") -> false (too long)
  • IsValidAgentID("Ox12#4") -> false (invalid character)
  • IsValidAgentID("") -> false
  • IsValidAgentID("random") -> false

func ParseAgentID

func ParseAgentID(id string) (string, error)

ParseAgentID extracts the 4-char suffix from an agent ID. Returns error if format is invalid.

Examples:

  • ParseAgentID("OxA1b2") -> "A1b2", nil
  • ParseAgentID("Ox1234") -> "1234", nil
  • ParseAgentID("ox1234") -> "", error (invalid prefix)
  • ParseAgentID("Ox123") -> "", error (wrong length)
  • ParseAgentID("") -> "", error (invalid format)

Types

type CountingWriter added in v0.3.0

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

CountingWriter wraps an io.Writer and counts bytes written through it. Used to measure how much context ox commands inject into agent windows.

func NewCountingWriter added in v0.3.0

func NewCountingWriter(w io.Writer) *CountingWriter

NewCountingWriter wraps w with byte counting.

func (*CountingWriter) BytesWritten added in v0.3.0

func (cw *CountingWriter) BytesWritten() int64

BytesWritten returns the total bytes written through this writer.

func (*CountingWriter) Write added in v0.3.0

func (cw *CountingWriter) Write(p []byte) (int, error)

Write passes through to the inner writer and counts bytes.

type Instance

type Instance struct {
	AgentID         string    `json:"agent_id"` // "Ox" + 4-char identifier (e.g., "Oxa7b3")
	ServerSessionID string    `json:"oxsid"`    // Full server-generated session ID (JSON: oxsid for compat)
	CreatedAt       time.Time `json:"created_at"`
	ExpiresAt       time.Time `json:"expires_at"`
	// Coding agent metadata
	AgentType string `json:"agent_type,omitempty"` // claude-code, droid, cursor, windsurf
	AgentVer  string `json:"agent_ver,omitempty"`  // Agent version (e.g., "1.0.42")
	Model     string `json:"model,omitempty"`      // Model used (e.g., "claude-opus-4-5")
	// Process tracking — PPID is the parent agent process (e.g., Claude Code).
	// Captured at prime time via os.Getppid(). Used by "ox agent list" to
	// check liveness with kill(pid, 0) without needing the daemon.
	ParentPID int `json:"parent_pid,omitempty"`
	// Agent hierarchy — detected at prime time by reading SAGEOX_AGENT_ID env var.
	// If already set when a new agent primes, the existing value is the parent
	// (orchestrator inherits env vars to subagents).
	ParentAgentID string `json:"parent_agent_id,omitempty"`
	// Usage tracking
	PrimeCallCount int `json:"prime_call_count,omitempty"` // number of times prime was called
}

Instance represents an agent instance with server-assigned identifiers.

func (*Instance) IsExpired

func (i *Instance) IsExpired() bool

IsExpired checks if the instance has expired

func (*Instance) IsPrimeExcessive

func (i *Instance) IsPrimeExcessive() bool

IsPrimeExcessive returns true if prime has been called more than the threshold. This indicates potential context compaction issues or agent misconfiguration.

func (*Instance) IsProcessAlive added in v0.3.0

func (i *Instance) IsProcessAlive() bool

IsProcessAlive checks if the parent agent process is still running. Uses kill(pid, 0) which checks existence without sending a signal. Returns false if no PID was recorded or the process is gone.

type Store

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

Store manages instance persistence using JSONL format

Design decision: Per-user instance directories Rationale: Multiple git users (or pair programmers) can work on the same repo without instance conflicts. Path: .sageox/agent_instances/<user-slug>/agent_instances.jsonl

func NewStore

func NewStore(projectRoot string) (*Store, error)

NewStore initializes an instance store for the given project root. Uses "anonymous" as the user slug for backward compatibility. Prefer NewStoreForUser when git identity is available.

func NewStoreForUser

func NewStoreForUser(projectRoot string, userSlug string) (*Store, error)

NewStoreForUser initializes an instance store for a specific user. The userSlug should be generated from GitIdentity.Slug() for per-user isolation. Path: .sageox/agent_instances/<user-slug>/agent_instances.jsonl

func (*Store) Add

func (s *Store) Add(inst *Instance) error

Add appends a new instance to the JSONL file

func (*Store) Count

func (s *Store) Count() int

Count returns the number of active instances

func (*Store) Get

func (s *Store) Get(agentID string) (*Instance, error)

Get retrieves an instance by agent ID, pruning expired instances during read.

Design decision: Prune on read Rationale: Amortizes cleanup cost; ensures Get() never returns expired instances without extra syscall. Triggers async compaction if thresholds exceeded.

func (*Store) IncrementPrimeCallCount

func (s *Store) IncrementPrimeCallCount(agentID string) (*Instance, bool, error)

IncrementPrimeCallCount increments the prime call count for an instance. Returns the updated instance and whether the prime count is now excessive.

func (*Store) List

func (s *Store) List() ([]*Instance, error)

List returns all active (non-expired) instances

func (*Store) Prune

func (s *Store) Prune() (int, error)

Prune removes expired instances and compacts the file if needed

func (*Store) Update

func (s *Store) Update(inst *Instance) error

Update modifies an existing instance in the store. Rewrites the file with the updated instance data. Returns error if instance not found.

Jump to

Keyboard shortcuts

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