Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 36 additions & 17 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,9 @@ It works particularly well in:
exact `INPUT NEEDED` and `APPROVAL NEEDED` states. Without it, a completed
open turn is definite `INPUT NEEDED`; an otherwise active session with no
rollout activity for three minutes is cautiously labelled `CHECK SESSION`.
For a root with linked agents, fresh activity from any member suppresses that
uncertain fallback; definite input or approval signals still propagate from
the member that raised them.
- An opt-in deterministic coding benchmark comparing every visible Codex model
and supported reasoning effort by correctness, elapsed time, token use, and
estimated standard API-equivalent cost.
Expand Down Expand Up @@ -435,7 +438,11 @@ matches reroute and token-usage events to rollout calls by thread ID, turn ID,
cumulative token checkpoint, and the complete response token breakdown. For a
subscribed thread, costing waits for one refresh when that exact match is not
yet available; a matching notification uses the resolved model, otherwise the
call safely returns to requested-model pricing. Late attachment, disconnects,
call safely returns to requested-model pricing. A call awaiting that decision
is kept in a separate pending count and does not enter the cumulative priced or
unpriced totals. This makes finalized accounting monotonic; a quota observation
that overlaps pending or newly finalized accounting is deferred instead of
silently moving its learning baseline. Late attachment, disconnects,
ordinary non-daemon clients, and already historical reroutes also retain
requested-model pricing rather than being guessed; these remaining coverage
limits are one reason confidence never rises above Medium. Ordinary input, cached input,
Expand All @@ -452,12 +459,16 @@ Benchmark view and making stale compiled pricing conspicuous wherever a priced
figure appears.

Each refresh brackets the account quota request with local accounting reads.
If their cost or call counters differ, `OBSERVATION DEFERRED` is shown and no
sample is taken, preventing a response completed during the request from being
paired with the wrong quota snapshot. Learning starts with a stable quota
percentage and cumulative local API-equivalent cost anchor. Once the same
window advances by at least five displayed percentage points without a reset
or an unpriced call, a sample is calculated:
If their cost, finalized-call, or pending-call counters differ—or a call is
still pending—`OBSERVATION DEFERRED` is shown and no sample is taken, preventing
a response completed during the request from being paired with the wrong quota
snapshot. Learning starts with a stable quota percentage and cumulative local
API-equivalent cost anchor. A pause in activity does not expire or reduce clean
movement. The backend may revise an upcoming rolling-window reset timestamp;
Codexometer retains the earliest observed boundary and does not restart merely
because that future timestamp moved. Once the same window advances by at least
five displayed percentage points without a reset or an unpriced call, a sample
is calculated:

```text
central 100% estimate = observed API-equivalent cost × 100 / percentage-point movement
Expand All @@ -475,12 +486,16 @@ Confidence is intentionally capped at Medium because local telemetry cannot
prove that no other machine, cloud task, unobserved client, or server-side model
reroute outside the shared-daemon subscription also affected the account quota.

An interval is discarded and re-anchored if the window resets, the counters
An interval is discarded and re-anchored if its earliest reset boundary passes,
used quota falls, the account or window definition changes, finalized counters
regress, the quota moves five points without any matching priced local call, or
an unknown/unpriced model occurs. `LOCAL COVERAGE GAP` signals the unmatched
movement. Even a valid estimate can still vary with reasoning effort, model
mix, caching, prompt shape, and backend quota weighting, so compare ranges and
sample counts rather than treating the midpoint as a fixed entitlement.
an unknown/unpriced model occurs. The learning readout retains the reason, for
example `RESTARTED: WINDOW RESET`, `WINDOW DEFINITION CHANGED`, `LOCAL
ACCOUNTING REBASED`, `UNPRICED MODEL MIX`, or `LOCAL COVERAGE GAP`, while new
clean movement accumulates. It never silently returns to `0/5PP`. Even a valid
estimate can still vary with reasoning effort, model mix, caching, prompt
shape, and backend quota weighting, so compare ranges and sample counts rather
than treating the midpoint as a fixed entitlement.

Samples remain process-local and are never written to the preferences file, so
evidence cannot leak from one login into another on a later run. During a run,
Expand Down Expand Up @@ -562,7 +577,8 @@ The other top-level views are:
`APPROVAL NEEDED` and `INPUT NEEDED`. If no shared server is available, an
otherwise active open session with no new token or rollout activity for three
minutes receives `CHECK SESSION`: a deliberately uncertain prompt that can
also mean a long-running local tool. Any subsequent activity clears it.
also mean a long-running local tool. Subsequent activity from the root or any
linked agent clears the uncertain group-level warning.
Codexometer never guesses `APPROVAL NEEDED` from inactivity. Closing the CLI
releases its per-thread writer lock and clears every attention badge.
A session already included in the current Monitor recording can remain as an
Expand Down Expand Up @@ -650,7 +666,10 @@ Monitor does not retain the input question, approval text, response, or
conversation content. A linked child's attention state is folded into its root
so one remote Monitor row identifies the CLI session that needs intervention.
A definite approval signal takes precedence, then definite input, then the
inferred check state when linked members have mixed states.
inferred check state when linked members have mixed states. Because `CHECK
SESSION` is only an inactivity inference, fresh activity anywhere in the group
suppresses a stale sibling's check; definite input and approval are never
suppressed this way.

`CALLS` counts upstream model-response cycles observed after Monitor Start, not
complete user turns. A single Codex turn can make several calls while using
Expand Down Expand Up @@ -997,9 +1016,9 @@ need Go or Codexometer's source dependencies.
## Versioning

Codexometer follows semantic versioning; the current source version is
`v0.7.3`. The Git tag is the release source of truth. Go automatically embeds
`v0.7.4`. The Git tag is the release source of truth. Go automatically embeds
that tag in binaries built with
`go install github.com/merefield/codexometer@v0.7.3`; direct source builds fall
`go install github.com/merefield/codexometer@v0.7.4`; direct source builds fall
back to the maintained value in `internal/version/version.go`.

Both forms report the embedded version and exit without starting the interface:
Expand All @@ -1012,7 +1031,7 @@ codexometer --version
Release automation can override the source-build fallback without editing code:

```sh
go build -ldflags="-s -w -X github.com/merefield/codexometer/internal/version.Fallback=0.7.3" .
go build -ldflags="-s -w -X github.com/merefield/codexometer/internal/version.Fallback=0.7.4" .
```

## How refresh works
Expand Down
72 changes: 41 additions & 31 deletions internal/codex/live_usage.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,10 @@ const (
fallbackAttentionAfter = 3 * time.Minute
)

// LiveUsageSnapshot is a process-local, monotonically increasing count built
// from token-count events appended to locally persisted Codex rollouts.
// LiveUsageSnapshot is a process-local accounting view built from token-count
// events appended to locally persisted Codex rollouts. Finalized API-equivalent
// totals increase monotonically; APIEqPendingCalls is an instantaneous count
// kept separate until daemon model resolution or requested-model fallback.
type LiveUsageSnapshot struct {
TotalTokens int64
LastActivity time.Time
Expand All @@ -34,6 +36,7 @@ type LiveUsageSnapshot struct {
APIEqUSD float64
APIEqPricedCalls int64
APIEqUnpricedCalls int64
APIEqPendingCalls int64
}

// LiveUsageSession is one independently started local Codex session. Token
Expand Down Expand Up @@ -74,6 +77,7 @@ type LiveModelCall struct {
Model string
APIEqUSD float64
APIEqKnown bool
apiEqFinalized bool
}

// LiveTurnTiming contains the persisted latency measurement for one completed
Expand Down Expand Up @@ -350,6 +354,7 @@ func (r *LiveUsageReader) fetchTokenUsage(ctx context.Context, forceFullDiscover
SessionCount: activeSessions, Sessions: sessions,
APIEqUSD: r.apiEqUSD, APIEqPricedCalls: r.apiEqPricedCalls,
APIEqUnpricedCalls: r.apiEqUnknownCalls,
APIEqPendingCalls: int64(len(r.pendingModelResolutions)),
}, nil
}

Expand Down Expand Up @@ -568,23 +573,26 @@ func (r *LiveUsageReader) consume(path string, cursor *rolloutCursor) error {
model, pricingUsage, resolved = observation.Model, observation.Usage, true
}
}
resolutionDeferred := usageMatchesDelta && resolutionPending && !resolved
call := LiveModelCall{
Sequence: r.nextEventSequence, At: record.at, OutputTokens: record.outputTokens,
OutputAvailable: record.outputKnown, Model: model,
}
if usageMatchesDelta && (!resolutionPending || resolved) {
if cost, known, _ := EstimateStandardAPIEqCost(model, pricingUsage); known {
call.APIEqUSD, call.APIEqKnown = cost, true
call.APIEqUSD, call.APIEqKnown, call.apiEqFinalized = cost, true, true
r.apiEqUSD += cost
r.apiEqPricedCalls++
} else {
call.apiEqFinalized = true
r.apiEqUnknownCalls++
}
} else {
} else if !resolutionDeferred {
call.apiEqFinalized = true
r.apiEqUnknownCalls++
}
cursor.modelCalls = appendBounded(cursor.modelCalls, call, telemetryHistoryMax)
if usageMatchesDelta && resolutionPending && !resolved {
if resolutionDeferred {
r.pendingModelResolutions = append(r.pendingModelResolutions, pendingModelResolution{
callSequence: call.Sequence, threadID: cursor.threadID,
turnID: cursor.currentTurnID, usage: record.usage, cumulativeTotal: record.total,
Expand Down Expand Up @@ -639,33 +647,24 @@ func (r *LiveUsageReader) ingestResolvedModelObservations(observations []resolve

func (r *LiveUsageReader) reconcilePendingModelResolutions() {
for _, pending := range r.pendingModelResolutions {
observation, ok := r.takeResolvedModelObservation(pending.threadID, pending.turnID, pending.usage, pending.cumulativeTotal)
if !ok {
call := r.modelCall(pending.callSequence)
if call != nil {
r.apiEqUnknownCalls--
call.APIEqUSD, call.APIEqKnown, _ = EstimateStandardAPIEqCost(call.Model, pending.usage)
if call.APIEqKnown {
r.apiEqUSD += call.APIEqUSD
r.apiEqPricedCalls++
} else {
r.apiEqUnknownCalls++
}
}
continue
}
call := r.modelCall(pending.callSequence)
if call == nil {
// The call aged out of the bounded per-session history before it
// could be finalized. Preserve fail-closed monotonic accounting.
r.apiEqUnknownCalls++
continue
}
if call.APIEqKnown {
r.apiEqUSD -= call.APIEqUSD
r.apiEqPricedCalls--
} else {
r.apiEqUnknownCalls--
if call.apiEqFinalized {
continue
}
call.Model = observation.Model
call.APIEqUSD, call.APIEqKnown, _ = EstimateStandardAPIEqCost(observation.Model, observation.Usage)
observation, ok := r.takeResolvedModelObservation(pending.threadID, pending.turnID, pending.usage, pending.cumulativeTotal)
pricingUsage := pending.usage
if ok {
call.Model = observation.Model
pricingUsage = observation.Usage
}
call.APIEqUSD, call.APIEqKnown, _ = EstimateStandardAPIEqCost(call.Model, pricingUsage)
call.apiEqFinalized = true
if call.APIEqKnown {
r.apiEqUSD += call.APIEqUSD
r.apiEqPricedCalls++
Expand Down Expand Up @@ -1088,12 +1087,15 @@ func (r *LiveUsageReader) sessionSnapshots(now time.Time, liveWriters map[string
}

groups := make(map[string]*LiveUsageSession)
groupHasFreshActivity := make(map[string]bool)
for _, cursor := range r.files {
active := now.Sub(cursor.lastModified) <= 5*time.Minute
quietFor := now.Sub(cursor.lastModified)
active := quietFor <= 5*time.Minute
_, writerActive := liveWriters[cursor.threadID]
exactStatus, exact := exactStatuses[cursor.threadID]
attention := sessionAttention(cursor.attention, writerActive, writerLocksSupported, now.Sub(cursor.lastModified), exactStatus, exact)
if !active && attention == SessionAttentionNone && cursor.observedTokens == 0 && len(cursor.modelCalls) == 0 && len(cursor.turnTimings) == 0 {
exactWorking := exact && exactStatus == sessionRuntimeWorking
attention := sessionAttention(cursor.attention, writerActive, writerLocksSupported, quietFor, exactStatus, exact)
if !active && !exactWorking && attention == SessionAttentionNone && cursor.observedTokens == 0 && len(cursor.modelCalls) == 0 && len(cursor.turnTimings) == 0 {
continue
}
rootID, unattributed := rolloutRoot(cursor, byID)
Expand All @@ -1105,8 +1107,13 @@ func (r *LiveUsageReader) sessionSnapshots(now time.Time, liveWriters map[string
group.TotalTokens += cursor.observedTokens
group.ModelCalls = append(group.ModelCalls, cursor.modelCalls...)
group.TurnTimings = append(group.TurnTimings, cursor.turnTimings...)
group.Active = group.Active || active || attention != SessionAttentionNone
group.Active = group.Active || active || exactWorking || attention != SessionAttentionNone
group.Attention = mergeSessionAttention(group.Attention, attention)
// CHECK SESSION is only an inactivity inference. A freshly writing
// member—or an authoritatively working daemon thread—means the grouped
// root is demonstrably active, even if a linked child was left quiet
// overnight. Definite input and approval signals still propagate.
groupHasFreshActivity[rootID] = groupHasFreshActivity[rootID] || quietFor < fallbackAttentionAfter || exactWorking
if cursor.lastModified.After(group.LastActivity) {
group.LastActivity = cursor.lastModified
}
Expand All @@ -1127,6 +1134,9 @@ func (r *LiveUsageReader) sessionSnapshots(now time.Time, liveWriters map[string
sessions := make([]LiveUsageSession, 0, len(groups))
activeCount := 0
for _, session := range groups {
if session.Attention == SessionAttentionCheck && groupHasFreshActivity[session.ID] {
session.Attention = SessionAttentionNone
}
sort.Slice(session.ModelCalls, func(i, j int) bool { return session.ModelCalls[i].Sequence < session.ModelCalls[j].Sequence })
sort.Slice(session.TurnTimings, func(i, j int) bool { return session.TurnTimings[i].Sequence < session.TurnTimings[j].Sequence })
if session.Active {
Expand Down
Loading
Loading