Documentation
¶
Overview ¶
Package route is the router engine: it keys state by thread, turn and request fingerprint, asks the classifier on a turn's first step and in background reviews, runs the policy, checks the compatibility group and context fit, pins a decision for retries, and publishes decisions and snapshots. A decision's evidence leaves the engine as fragments (SupportParts) and as the line they spell (Support), so a panel punctuates it itself and a reader that predates the fragments still shows one line. It implements proxy.Decider, proxy.Observer and, with the endpoint's hello, control.Handler, without importing those packages. Every error fails open: no rewrite.
Index ¶
- Constants
- type Attention
- type Command
- type Decision
- type Deps
- type Engine
- func (e *Engine) Apply(c Command) (err error)
- func (e *Engine) Decide(ctx context.Context, req *responses.Request, m responses.Meta) (rw responses.Rewrite, ok bool)
- func (e *Engine) Intent() Intent
- func (e *Engine) Observe(m responses.Meta, served string, u responses.Usage, status int)
- func (e *Engine) PassThrough(m responses.Meta)
- func (e *Engine) Resumed(threadID string, r config.Route) (resync bool)
- func (e *Engine) Sessions() []SessionInfo
- func (e *Engine) SettingsUpdated(threadID string, r config.Route)
- func (e *Engine) SnapshotFor(threadID string) Snapshot
- type Finding
- type FindingKind
- type Intent
- type Mode
- type Op
- type Reading
- type Scope
- type SessionInfo
- type Share
- type Sink
- type Snapshot
- type Stats
- type Switch
- type ThreadIntent
Constants ¶
const ( ReasonActivityUp policy.Reason = "activity-up" ReasonActivityDown policy.Reason = "activity-down" ReasonActivityPending policy.Reason = "activity-pending" ReasonObserved policy.Reason = "observed" ReasonContinue policy.Reason = "continue" )
Reasons the engine adds to policy's: activity moves inside a tier, a move up on the turn's own tool calls, and a later step keeping the turn's route.
const ( MaxThreads = 256 RecentKept = 64 StripCells = 48 // SessionStrip is how many recent reply tiers a SessionInfo carries. SessionStrip = 24 )
Bounds on remembered state. RecentKept and StripCells are per thread.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Attention ¶ added in v0.3.0
type Attention string
Attention flags a session the user may want to look at.
const ( AttentionPaused Attention = "paused" // this session or its home is paused AttentionManual Attention = "manual" // the footer model was picked with /model AttentionEscalation Attention = "escalation" // a repeated failure holds a higher tier AttentionUnknown Attention = "unknown" // seeded after a restart: held until a reply measures the cache AttentionStateLost Attention = "state-lost" // the saved intent was unreadable: the home is paused )
type Command ¶
type Command struct {
Op Op `json:"op"`
Session string `json:"session,omitempty"`
Scope Scope `json:"scope,omitempty"`
ID string `json:"id,omitempty"`
Tier config.Tier `json:"tier,omitempty"`
Preset config.Preset `json:"preset,omitempty"`
}
Command is what the TUI or hook asks the engine to do. Session is a thread id. Pin and unpin act on a session; preset on the home; pause and resume on either. An empty Scope means the session when Session is set, else the home. ID is the caller's, for matching the reply.
type Decision ¶
type Decision struct {
ThreadID string `json:"ThreadID"`
TurnID string `json:"TurnID"`
Step int `json:"Step"`
Tier config.Tier `json:"Tier"`
Activity config.Activity `json:"Activity"`
Route config.Route `json:"Route"`
Original config.Route `json:"Original"`
Rewritten bool `json:"Rewritten"`
Reason policy.Reason `json:"Reason"`
Why string `json:"Why"`
Support string `json:"Support"`
Estimate *policy.Estimate `json:"Estimate"`
Reading *Reading `json:"Reading"`
MidTurn bool `json:"MidTurn"`
At time.Time `json:"At"`
// SupportParts is Support as the fragments the engine built it from, so a
// panel can punctuate and wrap them itself. It is optional: an engine
// older than this field sends Support alone, and a reader then shows that
// whole (a label may hold the separator, so it must not be split). It is
// last so this additive field moves no existing name on the wire.
SupportParts []string `json:"SupportParts,omitempty"`
}
Decision is one per-request outcome. Its names on the control wire are spelled out, as they are for Snapshot and the types below: the engine's field names are not the protocol, and internal/control pins these spellings with literal fixtures, so a rename here cannot change what a client reads.
type Deps ¶
type Deps struct {
Config config.Config
Catalog catalog.Source
Classifier classifier.Asker
// ClassifierOffReason is why Classifier is nil; the snapshot shows it.
ClassifierOffReason string
Now func() time.Time
Sink Sink
Logger *slog.Logger
Home home.Home
Cwd func(threadID string) string
Intent Intent
IntentLost bool
SaveIntent func(Intent)
HoldUnseeded bool
}
Deps are the engine's boundaries. Home names the Codex home the engine routes for; Cwd gives a thread's working directory (nil: unknown). Intent is the saved intent to start from; IntentLost says it could not be read. SaveIntent (nil: not kept) gets the intent after every change, outside engine locks and possibly concurrently: it keeps the highest Rev. HoldUnseeded (the brain) holds a thread whose first request seen already carries a conversation, as Resumed does: after a restart, a turn's next step can reach the engine before discovery resumes its thread.
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine routes user steps. All state lives under mu; step serializes the requests of one thread so a classifier call never runs under mu. Routing state, tallies and decisions are per thread; paused, lost and the preset (in cfg) are the home's.
func New ¶
New returns an engine started from d.Intent. A nil Now uses time.Now, a nil Logger discards.
func (*Engine) Apply ¶
Apply runs a control command: pin or unpin a session's next turn, pause or resume a session or the whole home, or pick the home's policy preset. Pause writes each affected routed thread's own route back to its settings; resume also ends manual mode. A home resume keeps session pauses and clears a lost intent. Every command but snapshot saves the intent. A panic is logged and returned as an error.
func (*Engine) Decide ¶
func (e *Engine) Decide(ctx context.Context, req *responses.Request, m responses.Meta) (rw responses.Rewrite, ok bool)
Decide returns the rewrite for one request, or false to forward it unchanged. Any panic or error forwards unchanged. Once ctx is done the caller forwards the request unchanged, so a step whose ctx ends before it commits records nothing: no decision, no footer write, no pin spent.
func (*Engine) Observe ¶
Observe records a reply: the cache ledger, the thread's size, and the session stats when the reply answers a routed step.
func (*Engine) PassThrough ¶ added in v0.7.2
PassThrough clears a pending routed reply when metadata identifies a request that will not be routed. The response to that request must not be accounted as the reply to the previous routed decision.
func (*Engine) Resumed ¶ added in v0.3.0
Resumed takes r, the route Codex reports for a thread on thread/resume (an empty effort is the model's default), and reports whether the router's last route should be written to the footer again.
A thread the engine has seen no request on (a brain start) is seeded at r. It keeps r until a reply measures the cache: with an empty ledger the engine takes every cache for cold and would switch on one vote. The turn that reply ends stays on r too.
On a known thread r is checked as thread/settings/updated would be, since a /model pick made while the brain was not subscribed sent it nothing: a route the router wrote, or the thread's native one (a restarted daemon reloads that and lost the router's write), is written again; any other is the user's pick, and the thread goes manual. A pick back to the native route then looks like a restarted daemon and is overwritten.
func (*Engine) Sessions ¶ added in v0.3.0
func (e *Engine) Sessions() []SessionInfo
Sessions lists the threads that have had a user step, most recently active first, then by thread id. Ordinary threads idle for sessionIdle are left out unless they are the engine's most recently active one. Per-thread pause, manual hold and pending pin intent keep a thread listed. Cwd and the label, which reads the cwd's git metadata, are filled outside the engine lock.
func (*Engine) SettingsUpdated ¶
SettingsUpdated takes a thread/settings/updated notification. A value the router wrote is its echo; any other value is the user's own pick (plan D12): the thread goes manual until resume, and the intent is saved. A panic is logged and dropped.
func (*Engine) SnapshotFor ¶ added in v0.3.0
SnapshotFor returns one thread's snapshot; an unknown thread gets the home's state with no thread data.
type Finding ¶
type Finding struct {
Kind FindingKind `json:"Kind"`
Text string `json:"Text"`
}
Finding is one WORTH A LOOK line derived from the session's facts.
type FindingKind ¶
type FindingKind string
FindingKind names what a WORTH A LOOK finding is about, and so where the user changes it.
const ( FindingClassifier FindingKind = "classifier" // paused or failing FindingManual FindingKind = "manual" // the footer model was picked with /model FindingContext FindingKind = "context" // the context guard kept larger windows FindingBlocked FindingKind = "blocked" // configured routes outside the group FindingCache FindingKind = "cache" // low cache reuse after switches FindingState FindingKind = "state" // the saved intent was unreadable )
type Intent ¶ added in v0.3.0
type Intent struct {
Rev uint64 `json:"-"`
Paused bool `json:"paused,omitempty"`
Preset config.Preset `json:"preset,omitempty"`
Threads map[string]ThreadIntent `json:"threads,omitempty"`
}
Intent is the user's routing intent, which a restarted brain restores (plan M11): the home's pause and the preset a command picked, and per thread its pause, a manual hold (a /model pick) and a pending pin. A preset from the config is not intent: a restart reads the config again. Learned state (tiers, votes, escalations, the cache ledger) is not intent. Rev orders exports: a later state has a higher Rev.
type Reading ¶
type Reading struct {
Tiers map[config.Tier]float64 `json:"Tiers"`
Activity config.Activity `json:"Activity"`
ActivityP float64 `json:"ActivityP"`
Alternates []Share `json:"Alternates"`
}
Reading is the classifier answer the decision's turn runs on, for display: the probability per tier, and the activity answer with its probability and the two likeliest alternates. Tiers holds only the tiers the answer scored.
type Scope ¶ added in v0.3.0
type Scope string
Scope says what a command acts on: one session (thread) or the whole home (every thread of this engine).
type SessionInfo ¶ added in v0.3.0
type SessionInfo struct {
ID string `json:"id"`
Home string `json:"home"`
ThreadID string `json:"thread_id"`
Label string `json:"label"`
Cwd string `json:"cwd"`
Mode Mode `json:"mode"`
Tier config.Tier `json:"tier"`
Route config.Route `json:"route"`
Replies int `json:"replies"`
Switches int `json:"switches"`
Strip []config.Tier `json:"strip"`
LastSwitch *Switch `json:"last_switch,omitempty"`
LastActive time.Time `json:"last_active"`
Attention Attention `json:"attention,omitempty"`
PendingPin bool `json:"pending_pin,omitempty"`
PricedReplies int `json:"priced_replies"`
EligibleReplies int `json:"eligible_replies"`
SavedUSD *float64 `json:"saved_usd,omitempty"`
SpentUSD *float64 `json:"spent_usd,omitempty"`
}
SessionInfo is one session's summary for the sessions list: a Codex main thread of this engine's home. ID is "<home id>/<thread id>". Every number comes from the thread's own tallies. The USD fields are set only when every eligible reply has prices for its routed and native models.
type Sink ¶
Sink receives decisions and snapshots; the launcher fans them out to the app-server client and the control socket. Called outside engine locks. OnDecision runs inside Decide, before the request goes upstream, and holds that thread's next step so its settings writes keep their order; an implementation must not block on I/O (queue it instead).
type Snapshot ¶
type Snapshot struct {
// Seq orders snapshots: they are taken under the engine lock but
// published after it, so a consumer drops one older than it holds.
Seq uint64 `json:"Seq"`
ThreadID string `json:"ThreadID"`
At time.Time `json:"At"`
Mode Mode `json:"Mode"`
StateLost bool `json:"StateLost"` // the saved intent was unreadable; the home is paused until resume
Preset config.Preset `json:"Preset"`
Pin *config.Tier `json:"Pin"`
Baseline config.Route `json:"Baseline"`
Last *Decision `json:"Last"`
Recent []Decision `json:"Recent"`
Classifier classifier.Health `json:"Classifier"`
ClassifierOff bool `json:"ClassifierOff"` // no classifier configured (e.g. its key is unset)
// ClassifierOffReason says why it is off, without the key. Empty when on.
ClassifierOffReason string `json:"ClassifierOffReason"`
ClassifierLabel string `json:"ClassifierLabel"`
ClassifierModel string `json:"ClassifierModel"`
ClassifierMedian time.Duration `json:"ClassifierMedian"`
Routes map[config.Tier]config.Route `json:"Routes"`
Group catalog.Group `json:"Group"`
CurrentModelKnown bool `json:"CurrentModelKnown"`
CatalogAvailable bool `json:"CatalogAvailable"`
Blocked []string `json:"Blocked"`
CompatibilityUnknown []string `json:"CompatibilityUnknown"`
Policy config.Policy `json:"Policy"`
Stats Stats `json:"Stats"`
ApproxTokens int `json:"ApproxTokens"`
Window int `json:"Window"`
Worth []Finding `json:"Worth"`
}
Snapshot is one thread's full state, as the control socket publishes it and the TUI renders it. ThreadID is empty when no thread is known.
type Stats ¶
type Stats struct {
Since time.Time `json:"Since"`
Replies int `json:"Replies"`
Switches int `json:"Switches"`
ByTier map[config.Tier]int `json:"ByTier"`
ByActivity map[config.Activity]int `json:"ByActivity"`
Strip []config.Tier `json:"Strip"`
RepliesPerCell int `json:"RepliesPerCell"`
LastSwitch *Switch `json:"LastSwitch"`
CacheReusePct int `json:"CacheReusePct"`
LastInputTokens int `json:"LastInputTokens"`
LastCachedTokens int `json:"LastCachedTokens"`
UncachedSwitchTokens int `json:"UncachedSwitchTokens"`
FitHeld int `json:"FitHeld"`
RoutedUSD float64 `json:"RoutedUSD"`
BaselineUSD float64 `json:"BaselineUSD"`
PricedReplies int `json:"PricedReplies"` // replies with prices for both routed and native models
EligibleReplies int `json:"EligibleReplies"` // routed replies considered for dollar estimates
}
Stats sums the session since its first routed reply. LastInputTokens and LastCachedTokens are the last routed reply's; FitHeld counts the steps the context guard moved off the policy's tier. Pricing coverage counts the replies with prices for both the routed and per-reply native models.