From 2bd76930c61b83b23a9552689695c277fc5e5746 Mon Sep 17 00:00:00 2001 From: merefield Date: Fri, 14 Aug 2026 20:45:46 +0100 Subject: [PATCH 1/2] FEAT: resolve live daemon model reroutes --- README.md | 57 ++-- internal/codex/daemon_status.go | 21 +- internal/codex/daemon_status_unix.go | 370 +++++++++++++++++++--- internal/codex/daemon_status_unix_test.go | 56 +++- internal/codex/live_usage.go | 239 ++++++++++++-- internal/codex/live_usage_test.go | 113 ++++++- internal/version/version.go | 2 +- internal/version/version_test.go | 4 +- main_test.go | 2 +- 9 files changed, 763 insertions(+), 101 deletions(-) diff --git a/README.md b/README.md index 348e1bad..8275842e 100644 --- a/README.md +++ b/README.md @@ -185,14 +185,18 @@ Preview all UI features using simulated quota data: codexometer --demo ``` -## Shared Codex daemon for precise Monitor status +## Shared Codex daemon for live status and model resolution Codexometer works without a shared server, but its `CHECK SESSION` fallback cannot distinguish every long-running local tool from a prompt. On Unix systems, a current standalone Codex installation can instead run one shared app-server daemon. Every CLI connected to that daemon exposes its live per-thread `waitingOnApproval` and `waitingOnUserInput` flags, allowing the -Monitor to show definite `APPROVAL NEEDED` and `INPUT NEEDED` badges. +Monitor to show definite `APPROVAL NEEDED` and `INPUT NEEDED` badges. It also +lets Codexometer observe live `model/rerouted` and per-response token-usage +events. When those events match a local rollout response exactly, Quota and +Monitor API-equivalent figures use the model that actually served the response +instead of the requested model. Start the managed daemon and confirm that it is ready: @@ -216,9 +220,11 @@ codexometer No Codexometer option is required. While Monitor is recording, Codexometer automatically probes the same default socket under `CODEX_HOME` and uses exact -runtime status for threads loaded there. Sessions belonging to ordinary, -non-daemon Codex processes continue to use the local rollout and writer-lock -fallback. +runtime status for threads loaded there. Codexometer subscribes only to thread +IDs that are already loaded by that daemon; it does not load unrelated +historical sessions. Sessions belonging to ordinary, non-daemon Codex +processes continue to use the local rollout, requested-model pricing, and +writer-lock fallback. Manage or stop the daemon with: @@ -274,6 +280,13 @@ the final response carried beside timing metadata—reasoning, commands, tool results, and credentials are ignored and never retained by Codexometer. +When the managed shared daemon is available, Codexometer also keeps a local +app-server subscription for already-loaded thread IDs. From that stream it +retains only runtime status flags and content-free model-reroute/token-usage +correlations needed for the features above. It ignores prompts, responses, +reasoning, tool payloads, and server requests, and never sends a turn or an +approval response through this connection. + If you use a nonstandard Codex executable, pass it explicitly: ```sh @@ -385,15 +398,23 @@ narrower question: “At published standard API text-token prices, roughly what would this observed mix of model work cost when mapped onto the movement in my quota meter?” -Codexometer prices each newly completed local model call using the requested -model durably recorded in its turn context. Current Codex rollout files do not -persist transient model-reroute events, so a server-side reroute cannot be -reconstructed from this local source; this is one reason confidence never rises -above Medium. Ordinary input, cached input, cache-write input, and output are -priced separately; requests above the published 272,000-input-token threshold -use the corresponding long-context rates where OpenAI publishes them. Unknown -models or missing price classes fail closed as `UNPRICED MODEL MIX` rather than -being guessed or treated as free. +Codexometer normally prices each newly completed local model call using the +requested model durably recorded in its turn context. Current Codex rollout +files do not persist transient model-reroute events, so a reroute cannot be +reconstructed from that source alone. When Codexometer and the CLI share the +managed daemon described above, Codexometer keeps a live subscription and +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, +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, +cache-write input, and output are priced separately; requests above the +published 272,000-input-token threshold use the corresponding long-context +rates where OpenAI publishes them. Unknown models or missing price classes fail +closed as `UNPRICED MODEL MIX` rather than being guessed or treated as free. The embedded rates come from the [official OpenAI API pricing page](https://developers.openai.com/api/docs/pricing) and were retrieved on **2026-08-13**. @@ -424,7 +445,7 @@ more percentage points can reach `MED` only when both their rounding ranges and their central capacity estimates agree within conservative spread limits. Confidence is intentionally capped at Medium because local telemetry cannot prove that no other machine, cloud task, unobserved client, or server-side model -reroute also affected the account quota. +reroute outside the shared-daemon subscription also affected the account quota. An interval is discarded and re-anchored if the window resets, the counters regress, the quota moves five points without any matching priced local call, or @@ -948,9 +969,9 @@ need Go or Codexometer's source dependencies. ## Versioning Codexometer follows semantic versioning; the current source version is -`v0.7.2`. The Git tag is the release source of truth. Go automatically embeds +`v0.7.3`. 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.2`; direct source builds fall +`go install github.com/merefield/codexometer@v0.7.3`; 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: @@ -963,7 +984,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.2" . +go build -ldflags="-s -w -X github.com/merefield/codexometer/internal/version.Fallback=0.7.3" . ``` ## How refresh works diff --git a/internal/codex/daemon_status.go b/internal/codex/daemon_status.go index 474c7264..2e5c1b3b 100644 --- a/internal/codex/daemon_status.go +++ b/internal/codex/daemon_status.go @@ -13,7 +13,26 @@ const ( ) type sessionStatusProvider interface { - Fetch(context.Context, []string) (map[string]sessionRuntimeStatus, bool) + Fetch(context.Context, []string) (sessionDaemonSnapshot, bool) +} + +type sessionDaemonSnapshot struct { + Statuses map[string]sessionRuntimeStatus + ModelObservations []resolvedModelObservation + SubscribedThreads map[string]struct{} +} + +// resolvedModelObservation links one exact app-server response usage event to +// the model selected by a preceding live reroute event for the same turn. +// Sequence is local to the persistent daemon connection and lets the rollout +// reader consume every observation at most once. +type resolvedModelObservation struct { + Sequence uint64 + ThreadID string + TurnID string + Model string + Usage BenchmarkUsage + CumulativeTotal int64 } func parseSessionRuntimeStatus(kind string, flags []string) sessionRuntimeStatus { diff --git a/internal/codex/daemon_status_unix.go b/internal/codex/daemon_status_unix.go index b99a7790..b8fab382 100644 --- a/internal/codex/daemon_status_unix.go +++ b/internal/codex/daemon_status_unix.go @@ -5,9 +5,12 @@ package codex import ( "context" "encoding/json" + "errors" + "fmt" "net" "net/http" "path/filepath" + "sync" "time" "github.com/gorilla/websocket" @@ -17,51 +20,61 @@ const daemonStatusTimeout = 2 * time.Second type daemonStatusProvider struct { socketPath string + + mu sync.Mutex + connection *websocket.Conn + nextRequestID int64 + pending map[int64]chan daemonEnvelope + subscribed map[string]struct{} + reroutedTurns map[daemonTurnKey]string + observations []resolvedModelObservation + nextSequence uint64 + writeMu sync.Mutex +} + +type daemonTurnKey struct { + threadID string + turnID string +} + +type daemonEnvelope struct { + ID json.RawMessage `json:"id"` + Method string `json:"method"` + Params json.RawMessage `json:"params"` + Result json.RawMessage `json:"result"` + Error json.RawMessage `json:"error"` } func newSessionStatusProvider(codexHome string) sessionStatusProvider { - return daemonStatusProvider{socketPath: filepath.Join(codexHome, "app-server-control", "app-server-control.sock")} + return &daemonStatusProvider{socketPath: filepath.Join(codexHome, "app-server-control", "app-server-control.sock")} } -func (p daemonStatusProvider) Fetch(ctx context.Context, threadIDs []string) (map[string]sessionRuntimeStatus, bool) { - dialer := websocket.Dialer{ - HandshakeTimeout: daemonStatusTimeout, - NetDialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { - return (&net.Dialer{Timeout: daemonStatusTimeout}).DialContext(ctx, "unix", p.socketPath) - }, - } - connection, response, err := dialer.DialContext(ctx, "ws://localhost/", http.Header{}) - if response != nil && response.Body != nil { - _ = response.Body.Close() +func (p *daemonStatusProvider) Fetch(ctx context.Context, threadIDs []string) (sessionDaemonSnapshot, bool) { + if err := p.ensureConnected(ctx); err != nil { + return sessionDaemonSnapshot{}, false } - if err != nil { - return nil, false - } - defer connection.Close() - setDaemonDeadline := func() { - deadline := time.Now().Add(daemonStatusTimeout) - _ = connection.SetReadDeadline(deadline) - _ = connection.SetWriteDeadline(deadline) - } - setDaemonDeadline() - requestID := int64(1) - var initialized struct { - UserAgent string `json:"userAgent"` - } - if err := daemonRequest(connection, requestID, "initialize", map[string]any{ - "clientInfo": map[string]string{"name": "codexometer", "title": "Codexometer", "version": "monitor"}, - }, &initialized); err != nil { - return nil, false - } - if err := connection.WriteJSON(map[string]any{"method": "initialized", "params": map[string]any{}}); err != nil { - return nil, false + loaded, err := p.loadedThreads(ctx) + if err == nil { + p.unsubscribeMissing(ctx, threadIDs) + for _, threadID := range threadIDs { + if _, ok := loaded[threadID]; !ok || p.isSubscribed(threadID) { + continue + } + var resumed json.RawMessage + if err := p.request(ctx, "thread/resume", map[string]any{ + "threadId": threadID, "excludeTurns": true, + }, &resumed); err != nil { + continue + } + p.mu.Lock() + p.subscribed[threadID] = struct{}{} + p.mu.Unlock() + } } statuses := make(map[string]sessionRuntimeStatus, len(threadIDs)) for _, threadID := range threadIDs { - setDaemonDeadline() - requestID++ var result struct { Thread struct { ID string `json:"id"` @@ -71,7 +84,7 @@ func (p daemonStatusProvider) Fetch(ctx context.Context, threadIDs []string) (ma } `json:"status"` } `json:"thread"` } - if err := daemonRequest(connection, requestID, "thread/read", map[string]any{ + if err := p.request(ctx, "thread/read", map[string]any{ "threadId": threadID, "includeTurns": false, }, &result); err != nil { continue @@ -81,29 +94,294 @@ func (p daemonStatusProvider) Fetch(ctx context.Context, threadIDs []string) (ma statuses[threadID] = status } } - return statuses, true + + p.mu.Lock() + observations := append([]resolvedModelObservation(nil), p.observations...) + subscribed := make(map[string]struct{}, len(p.subscribed)) + for threadID := range p.subscribed { + subscribed[threadID] = struct{}{} + } + p.mu.Unlock() + return sessionDaemonSnapshot{ + Statuses: statuses, ModelObservations: observations, SubscribedThreads: subscribed, + }, true +} + +func (p *daemonStatusProvider) unsubscribeMissing(ctx context.Context, threadIDs []string) { + wanted := make(map[string]struct{}, len(threadIDs)) + for _, threadID := range threadIDs { + wanted[threadID] = struct{}{} + } + p.mu.Lock() + stale := make([]string, 0) + for threadID := range p.subscribed { + if _, ok := wanted[threadID]; !ok { + stale = append(stale, threadID) + } + } + p.mu.Unlock() + for _, threadID := range stale { + var result json.RawMessage + if p.request(ctx, "thread/unsubscribe", map[string]any{"threadId": threadID}, &result) != nil { + continue + } + p.mu.Lock() + delete(p.subscribed, threadID) + for key := range p.reroutedTurns { + if key.threadID == threadID { + delete(p.reroutedTurns, key) + } + } + p.mu.Unlock() + } } -func daemonRequest(connection *websocket.Conn, id int64, method string, params any, target any) error { - if err := connection.WriteJSON(map[string]any{"id": id, "method": method, "params": params}); err != nil { +func (p *daemonStatusProvider) ensureConnected(ctx context.Context) error { + p.mu.Lock() + if p.connection != nil { + p.mu.Unlock() + return nil + } + p.mu.Unlock() + + dialer := websocket.Dialer{ + HandshakeTimeout: daemonStatusTimeout, + NetDialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { + return (&net.Dialer{Timeout: daemonStatusTimeout}).DialContext(ctx, "unix", p.socketPath) + }, + } + connection, response, err := dialer.DialContext(ctx, "ws://localhost/", http.Header{}) + if response != nil && response.Body != nil { + _ = response.Body.Close() + } + if err != nil { return err } + + p.mu.Lock() + if p.connection != nil { + p.mu.Unlock() + _ = connection.Close() + return nil + } + p.connection = connection + p.pending = make(map[int64]chan daemonEnvelope) + p.subscribed = make(map[string]struct{}) + p.reroutedTurns = make(map[daemonTurnKey]string) + p.mu.Unlock() + go p.readLoop(connection) + + var initialized struct { + UserAgent string `json:"userAgent"` + } + if err := p.request(ctx, "initialize", map[string]any{ + "clientInfo": map[string]string{"name": "codexometer", "title": "Codexometer", "version": "monitor"}, + "capabilities": map[string]any{"experimentalApi": true}, + }, &initialized); err != nil { + p.disconnect(connection) + return err + } + if err := p.notify("initialized", map[string]any{}); err != nil { + p.disconnect(connection) + return err + } + return nil +} + +func (p *daemonStatusProvider) loadedThreads(ctx context.Context) (map[string]struct{}, error) { + loaded := make(map[string]struct{}) + var cursor any for { - var envelope struct { - ID *int64 `json:"id"` - Result json.RawMessage `json:"result"` - Error json.RawMessage `json:"error"` + params := map[string]any{} + if cursor != nil { + params["cursor"] = cursor } - if err := connection.ReadJSON(&envelope); err != nil { - return err + var result struct { + Data []string `json:"data"` + NextCursor any `json:"nextCursor"` } - if envelope.ID == nil || *envelope.ID != id { - continue + if err := p.request(ctx, "thread/loaded/list", params, &result); err != nil { + return nil, err + } + for _, threadID := range result.Data { + loaded[threadID] = struct{}{} } + if result.NextCursor == nil { + return loaded, nil + } + cursor = result.NextCursor + } +} + +func (p *daemonStatusProvider) isSubscribed(threadID string) bool { + p.mu.Lock() + defer p.mu.Unlock() + _, ok := p.subscribed[threadID] + return ok +} + +func (p *daemonStatusProvider) request(ctx context.Context, method string, params any, target any) error { + p.mu.Lock() + connection := p.connection + if connection == nil { + p.mu.Unlock() + return errors.New("daemon connection is closed") + } + p.nextRequestID++ + id := p.nextRequestID + response := make(chan daemonEnvelope, 1) + p.pending[id] = response + p.mu.Unlock() + + if err := p.write(connection, map[string]any{"id": id, "method": method, "params": params}); err != nil { + p.mu.Lock() + delete(p.pending, id) + p.mu.Unlock() + p.disconnect(connection) + return err + } + timer := time.NewTimer(daemonStatusTimeout) + defer timer.Stop() + select { + case envelope := <-response: if len(envelope.Error) > 0 && string(envelope.Error) != "null" { return &daemonResponseError{payload: string(envelope.Error)} } + if target == nil { + return nil + } return json.Unmarshal(envelope.Result, target) + case <-ctx.Done(): + p.dropPending(id) + return ctx.Err() + case <-timer.C: + p.dropPending(id) + return fmt.Errorf("daemon %s request timed out", method) + } +} + +func (p *daemonStatusProvider) notify(method string, params any) error { + p.mu.Lock() + connection := p.connection + p.mu.Unlock() + if connection == nil { + return errors.New("daemon connection is closed") + } + return p.write(connection, map[string]any{"method": method, "params": params}) +} + +func (p *daemonStatusProvider) write(connection *websocket.Conn, value any) error { + p.writeMu.Lock() + defer p.writeMu.Unlock() + _ = connection.SetWriteDeadline(time.Now().Add(daemonStatusTimeout)) + return connection.WriteJSON(value) +} + +func (p *daemonStatusProvider) dropPending(id int64) { + p.mu.Lock() + delete(p.pending, id) + p.mu.Unlock() +} + +func (p *daemonStatusProvider) readLoop(connection *websocket.Conn) { + for { + var envelope daemonEnvelope + if err := connection.ReadJSON(&envelope); err != nil { + p.disconnect(connection) + return + } + var responseID int64 + if envelope.Method == "" && len(envelope.ID) > 0 && json.Unmarshal(envelope.ID, &responseID) == nil { + p.mu.Lock() + response := p.pending[responseID] + delete(p.pending, responseID) + p.mu.Unlock() + if response != nil { + select { + case response <- envelope: + default: + } + } + continue + } + p.handleNotification(envelope.Method, envelope.Params) + } +} + +func (p *daemonStatusProvider) handleNotification(method string, params json.RawMessage) { + switch method { + case "model/rerouted": + var notification struct { + ThreadID string `json:"threadId"` + TurnID string `json:"turnId"` + ToModel string `json:"toModel"` + } + if json.Unmarshal(params, ¬ification) != nil || notification.ThreadID == "" || + notification.TurnID == "" || notification.ToModel == "" { + return + } + p.mu.Lock() + p.reroutedTurns[daemonTurnKey{notification.ThreadID, notification.TurnID}] = notification.ToModel + p.mu.Unlock() + case "thread/tokenUsage/updated": + var notification struct { + ThreadID string `json:"threadId"` + TurnID string `json:"turnId"` + TokenUsage struct { + Total BenchmarkUsage `json:"total"` + Last BenchmarkUsage `json:"last"` + } `json:"tokenUsage"` + } + if json.Unmarshal(params, ¬ification) != nil { + return + } + key := daemonTurnKey{notification.ThreadID, notification.TurnID} + p.mu.Lock() + model := p.reroutedTurns[key] + if model != "" { + p.nextSequence++ + p.observations = appendBounded(p.observations, resolvedModelObservation{ + Sequence: p.nextSequence, ThreadID: notification.ThreadID, + TurnID: notification.TurnID, Model: model, Usage: notification.TokenUsage.Last, + CumulativeTotal: notification.TokenUsage.Total.TotalTokens, + }, telemetryHistoryMax) + } + p.mu.Unlock() + case "turn/completed": + var notification struct { + ThreadID string `json:"threadId"` + Turn struct { + ID string `json:"id"` + } `json:"turn"` + } + if json.Unmarshal(params, ¬ification) == nil { + p.mu.Lock() + delete(p.reroutedTurns, daemonTurnKey{notification.ThreadID, notification.Turn.ID}) + p.mu.Unlock() + } + } +} + +func (p *daemonStatusProvider) disconnect(connection *websocket.Conn) { + p.mu.Lock() + if connection != nil && p.connection != connection { + p.mu.Unlock() + return + } + current := p.connection + p.connection = nil + for id, response := range p.pending { + delete(p.pending, id) + select { + case response <- daemonEnvelope{Error: json.RawMessage(`{"message":"daemon connection closed"}`)}: + default: + } + } + p.subscribed = nil + p.reroutedTurns = nil + p.mu.Unlock() + if current != nil { + _ = current.Close() } } diff --git a/internal/codex/daemon_status_unix_test.go b/internal/codex/daemon_status_unix_test.go index 79c5acc6..320098d7 100644 --- a/internal/codex/daemon_status_unix_test.go +++ b/internal/codex/daemon_status_unix_test.go @@ -10,6 +10,7 @@ import ( "net/http" "os" "path/filepath" + "sync/atomic" "testing" "github.com/gorilla/websocket" @@ -41,6 +42,7 @@ func TestDaemonStatusProviderReadsExactThreadStates(t *testing.T) { t.Fatal(err) } upgrader := websocket.Upgrader{} + var resumedHistorical atomic.Bool server := &http.Server{Handler: http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { connection, upgradeErr := upgrader.Upgrade(writer, request, nil) if upgradeErr != nil { @@ -62,6 +64,32 @@ func TestDaemonStatusProviderReadsExactThreadStates(t *testing.T) { switch message.Method { case "initialize": _ = connection.WriteJSON(map[string]any{"id": *message.ID, "result": map[string]any{"userAgent": "codex/1.0"}}) + case "thread/loaded/list": + _ = connection.WriteJSON(map[string]any{"id": *message.ID, "result": map[string]any{ + "data": []string{"working", "approval"}, "nextCursor": nil, + }}) + case "thread/resume": + threadID, _ := message.Params["threadId"].(string) + if threadID == "historical" { + resumedHistorical.Store(true) + } + _ = connection.WriteJSON(map[string]any{"id": *message.ID, "result": map[string]any{ + "thread": map[string]any{"id": threadID}, + }}) + if threadID == "working" { + _ = connection.WriteJSON(map[string]any{ + "id": "approval-1", "method": "item/commandExecution/requestApproval", "params": map[string]any{}, + }) + _ = connection.WriteJSON(map[string]any{"method": "model/rerouted", "params": map[string]any{ + "threadId": threadID, "turnId": "turn-1", "fromModel": "gpt-5.6-sol", "toModel": "gpt-5.6-terra", + }}) + _ = connection.WriteJSON(map[string]any{"method": "thread/tokenUsage/updated", "params": map[string]any{ + "threadId": threadID, "turnId": "turn-1", "tokenUsage": map[string]any{ + "total": map[string]any{"inputTokens": 120, "cachedInputTokens": 20, "outputTokens": 30, "totalTokens": 150}, + "last": map[string]any{"inputTokens": 120, "cachedInputTokens": 20, "outputTokens": 30, "totalTokens": 150}, + }, + }}) + } case "thread/read": threadID, _ := message.Params["threadId"].(string) status := map[string]any{"type": "active", "activeFlags": []string{}} @@ -84,21 +112,33 @@ func TestDaemonStatusProviderReadsExactThreadStates(t *testing.T) { <-done }) - provider := daemonStatusProvider{socketPath: socketPath} - statuses, exact := provider.Fetch(context.Background(), []string{"working", "approval"}) + provider := &daemonStatusProvider{socketPath: socketPath} + t.Cleanup(func() { provider.disconnect(nil) }) + snapshot, exact := provider.Fetch(context.Background(), []string{"working", "approval", "historical"}) if !exact { t.Fatal("shared daemon was not detected") } - if statuses["working"] != sessionRuntimeWorking || statuses["approval"] != sessionRuntimeApproval { - t.Fatalf("exact daemon statuses = %#v", statuses) + if snapshot.Statuses["working"] != sessionRuntimeWorking || snapshot.Statuses["approval"] != sessionRuntimeApproval { + t.Fatalf("exact daemon statuses = %#v", snapshot.Statuses) + } + if len(snapshot.ModelObservations) != 1 { + t.Fatalf("reroute observations = %#v", snapshot.ModelObservations) + } + observation := snapshot.ModelObservations[0] + if observation.ThreadID != "working" || observation.TurnID != "turn-1" || + observation.Model != "gpt-5.6-terra" || observation.Usage.TotalTokens != 150 || observation.CumulativeTotal != 150 { + t.Fatalf("reroute observation = %#v", observation) + } + if resumedHistorical.Load() { + t.Fatal("provider subscribed to a thread that was not already loaded") } } func TestDaemonStatusProviderFallsBackWhenSocketIsMissing(t *testing.T) { - provider := daemonStatusProvider{socketPath: filepath.Join(t.TempDir(), "missing.sock")} - statuses, exact := provider.Fetch(context.Background(), []string{"thread"}) - if exact || statuses != nil { - encoded, _ := json.Marshal(statuses) + provider := &daemonStatusProvider{socketPath: filepath.Join(t.TempDir(), "missing.sock")} + snapshot, exact := provider.Fetch(context.Background(), []string{"thread"}) + if exact || snapshot.Statuses != nil || snapshot.ModelObservations != nil { + encoded, _ := json.Marshal(snapshot) t.Fatalf("missing daemon = exact %v statuses %s", exact, encoded) } } diff --git a/internal/codex/live_usage.go b/internal/codex/live_usage.go index d2aede82..82d40f08 100644 --- a/internal/codex/live_usage.go +++ b/internal/codex/live_usage.go @@ -92,18 +92,22 @@ type LiveUsageReader struct { WriterLocksRoot string statusProvider sessionStatusProvider - mu sync.Mutex - initialized bool - startedAt time.Time - lastDiscovery time.Time - lastFullDiscovery time.Time - files map[string]*rolloutCursor - totalTokens int64 - apiEqUSD float64 - apiEqPricedCalls int64 - apiEqUnknownCalls int64 - lastActivity time.Time - nextEventSequence uint64 + mu sync.Mutex + initialized bool + startedAt time.Time + lastDiscovery time.Time + lastFullDiscovery time.Time + files map[string]*rolloutCursor + totalTokens int64 + apiEqUSD float64 + apiEqPricedCalls int64 + apiEqUnknownCalls int64 + lastActivity time.Time + nextEventSequence uint64 + daemonObservationSequence uint64 + resolvedObservations []resolvedModelObservation + pendingModelResolutions []pendingModelResolution + daemonSubscribedThreads map[string]struct{} } type rolloutCursor struct { @@ -116,6 +120,7 @@ type rolloutCursor struct { workingDirectory string startedAt time.Time currentModel string + currentTurnID string nonRoot bool subagentHistoryStartOrdinal *uint64 modelCalls []LiveModelCall @@ -123,6 +128,14 @@ type rolloutCursor struct { attention sessionAttentionState } +type pendingModelResolution struct { + callSequence uint64 + threadID string + turnID string + usage BenchmarkUsage + cumulativeTotal int64 +} + type sessionAttentionState int const ( @@ -176,6 +189,16 @@ type rolloutModelEvent struct { } `json:"payload"` } +type rolloutTurnIdentityEvent struct { + Timestamp time.Time `json:"timestamp"` + Ordinal *uint64 `json:"ordinal"` + Type string `json:"type"` + Payload struct { + Type string `json:"type"` + TurnID string `json:"turn_id"` + } `json:"payload"` +} + type rolloutTurnEvent struct { Timestamp time.Time `json:"timestamp"` Ordinal *uint64 `json:"ordinal"` @@ -284,6 +307,17 @@ func (r *LiveUsageReader) fetchTokenUsage(ctx context.Context, forceFullDiscover } } + exactStatuses := map[string]sessionRuntimeStatus(nil) + r.daemonSubscribedThreads = nil + if r.statusProvider != nil { + if daemonSnapshot, exact := r.statusProvider.Fetch(ctx, r.observedThreadIDs(now)); exact { + exactStatuses = daemonSnapshot.Statuses + r.ingestResolvedModelObservations(daemonSnapshot.ModelObservations) + r.daemonSubscribedThreads = daemonSnapshot.SubscribedThreads + } + } + r.reconcilePendingModelResolutions() + var firstReadErr error readableFiles := 0 for path, cursor := range r.files { @@ -310,10 +344,6 @@ func (r *LiveUsageReader) fetchTokenUsage(ctx context.Context, forceFullDiscover } liveWriters, writerLocksSupported := r.liveWriterThreads() - exactStatuses := map[string]sessionRuntimeStatus(nil) - if r.statusProvider != nil { - exactStatuses, _ = r.statusProvider.Fetch(ctx, r.observedThreadIDs()) - } sessions, activeSessions := r.sessionSnapshots(now, liveWriters, writerLocksSupported, exactStatuses) return LiveUsageSnapshot{ TotalTokens: r.totalTokens, LastActivity: r.lastActivity, @@ -323,11 +353,11 @@ func (r *LiveUsageReader) fetchTokenUsage(ctx context.Context, forceFullDiscover }, nil } -func (r *LiveUsageReader) observedThreadIDs() []string { +func (r *LiveUsageReader) observedThreadIDs(now time.Time) []string { seen := make(map[string]struct{}, len(r.files)) threadIDs := make([]string, 0, len(r.files)) for _, cursor := range r.files { - if cursor.threadID == "" { + if cursor.threadID == "" || now.Sub(cursor.lastModified) > activeRolloutHorizon { continue } if _, ok := seen[cursor.threadID]; ok { @@ -438,6 +468,11 @@ func (r *LiveUsageReader) addFile(path string, info os.FileInfo) error { return modelErr } cursor.currentModel = model + turnID, turnErr := latestRolloutTurnID(path, cursor) + if turnErr != nil { + return turnErr + } + cursor.currentTurnID = turnID total, err := latestTokenTotal(path) if err != nil { return err @@ -467,6 +502,11 @@ func (r *LiveUsageReader) consume(path string, cursor *rolloutCursor) error { } cursor.offset = info.Size() cursor.totalTokens = total + turnID, turnErr := latestRolloutTurnID(path, cursor) + if turnErr != nil { + return turnErr + } + cursor.currentTurnID = turnID attention, attentionErr := latestSessionAttention(path, cursor) if attentionErr != nil { return attentionErr @@ -485,6 +525,10 @@ func (r *LiveUsageReader) consume(path string, cursor *rolloutCursor) error { line, readErr := reader.ReadBytes('\n') if len(line) > 0 && line[len(line)-1] == '\n' { cursor.offset += int64(len(line)) + if turnID, ordinal, at, ok := rolloutTurnIDRecord(line); ok && + tokenRecordIsOwned(ordinal, cursor.subagentHistoryStartOrdinal, at, cursor.nonRoot, cursor.startedAt) { + cursor.currentTurnID = turnID + } if model, ordinal, at, ok := rolloutModelRecord(line); ok && tokenRecordIsOwned(ordinal, cursor.subagentHistoryStartOrdinal, at, cursor.nonRoot, cursor.startedAt) { cursor.currentModel = model @@ -513,12 +557,23 @@ func (r *LiveUsageReader) consume(path string, cursor *rolloutCursor) error { r.lastActivity = record.at } r.nextEventSequence++ + model := cursor.currentModel + pricingUsage := record.usage + usageMatchesDelta := record.usage.TotalTokens == delta + _, daemonSubscribed := r.daemonSubscribedThreads[cursor.threadID] + resolutionPending := daemonSubscribed && cursor.threadID != "" && cursor.currentTurnID != "" + resolved := false + if usageMatchesDelta { + if observation, ok := r.takeResolvedModelObservation(cursor.threadID, cursor.currentTurnID, record.usage, record.total); ok { + model, pricingUsage, resolved = observation.Model, observation.Usage, true + } + } call := LiveModelCall{ Sequence: r.nextEventSequence, At: record.at, OutputTokens: record.outputTokens, - OutputAvailable: record.outputKnown, Model: cursor.currentModel, + OutputAvailable: record.outputKnown, Model: model, } - if record.usage.TotalTokens == delta { - if cost, known, _ := EstimateStandardAPIEqCost(cursor.currentModel, record.usage); known { + if usageMatchesDelta && (!resolutionPending || resolved) { + if cost, known, _ := EstimateStandardAPIEqCost(model, pricingUsage); known { call.APIEqUSD, call.APIEqKnown = cost, true r.apiEqUSD += cost r.apiEqPricedCalls++ @@ -529,6 +584,12 @@ func (r *LiveUsageReader) consume(path string, cursor *rolloutCursor) error { r.apiEqUnknownCalls++ } cursor.modelCalls = appendBounded(cursor.modelCalls, call, telemetryHistoryMax) + if usageMatchesDelta && resolutionPending && !resolved { + r.pendingModelResolutions = append(r.pendingModelResolutions, pendingModelResolution{ + callSequence: call.Sequence, threadID: cursor.threadID, + turnID: cursor.currentTurnID, usage: record.usage, cumulativeTotal: record.total, + }) + } } } cursor.totalTokens = record.total @@ -550,6 +611,103 @@ func (r *LiveUsageReader) consume(path string, cursor *rolloutCursor) error { } } +func rolloutTurnIDRecord(line []byte) (string, *uint64, time.Time, bool) { + if !bytes.Contains(line, []byte(`"turn_id"`)) { + return "", nil, time.Time{}, false + } + var event rolloutTurnIdentityEvent + if json.Unmarshal(line, &event) != nil { + return "", nil, time.Time{}, false + } + if (event.Type != "event_msg" || (event.Payload.Type != "task_started" && event.Payload.Type != "turn_started")) && + event.Type != "turn_context" { + return "", nil, time.Time{}, false + } + turnID := strings.TrimSpace(event.Payload.TurnID) + return turnID, event.Ordinal, event.Timestamp, turnID != "" +} + +func (r *LiveUsageReader) ingestResolvedModelObservations(observations []resolvedModelObservation) { + for _, observation := range observations { + if observation.Sequence <= r.daemonObservationSequence { + continue + } + r.daemonObservationSequence = observation.Sequence + r.resolvedObservations = appendBounded(r.resolvedObservations, observation, telemetryHistoryMax) + } +} + +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 { + continue + } + if call.APIEqKnown { + r.apiEqUSD -= call.APIEqUSD + r.apiEqPricedCalls-- + } else { + r.apiEqUnknownCalls-- + } + call.Model = observation.Model + call.APIEqUSD, call.APIEqKnown, _ = EstimateStandardAPIEqCost(observation.Model, observation.Usage) + if call.APIEqKnown { + r.apiEqUSD += call.APIEqUSD + r.apiEqPricedCalls++ + } else { + r.apiEqUnknownCalls++ + } + } + r.pendingModelResolutions = nil +} + +func (r *LiveUsageReader) takeResolvedModelObservation(threadID, turnID string, usage BenchmarkUsage, cumulativeTotal int64) (resolvedModelObservation, bool) { + for index, observation := range r.resolvedObservations { + if observation.ThreadID != threadID || observation.TurnID != turnID || + observation.CumulativeTotal != cumulativeTotal || !sameBenchmarkUsage(observation.Usage, usage) { + continue + } + r.resolvedObservations = append(r.resolvedObservations[:index], r.resolvedObservations[index+1:]...) + return observation, true + } + return resolvedModelObservation{}, false +} + +func (r *LiveUsageReader) modelCall(sequence uint64) *LiveModelCall { + for _, cursor := range r.files { + for index := range cursor.modelCalls { + if cursor.modelCalls[index].Sequence == sequence { + return &cursor.modelCalls[index] + } + } + } + return nil +} + +func sameBenchmarkUsage(left, right BenchmarkUsage) bool { + return left.TotalTokens == right.TotalTokens && + left.InputTokens == right.InputTokens && + left.CachedInputTokens == right.CachedInputTokens && + left.CacheWriteInputTokens == right.CacheWriteInputTokens && + left.OutputTokens == right.OutputTokens && + left.ReasoningOutputTokens == right.ReasoningOutputTokens +} + func latestSessionAttention(path string, cursor *rolloutCursor) (sessionAttentionState, error) { file, err := os.Open(path) if err != nil { @@ -758,6 +916,45 @@ func latestRolloutModel(path string, cursor *rolloutCursor) (string, error) { return "", nil } +func latestRolloutTurnID(path string, cursor *rolloutCursor) (string, error) { + file, err := os.Open(path) + if err != nil { + return "", err + } + defer file.Close() + info, err := file.Stat() + if err != nil { + return "", err + } + const chunkSize = int64(64 * 1024) + position := info.Size() + var carry []byte + for position > 0 { + readSize := min(chunkSize, position) + position -= readSize + chunk := make([]byte, int(readSize)) + if _, err := file.ReadAt(chunk, position); err != nil && !errors.Is(err, io.EOF) { + return "", err + } + data := make([]byte, 0, len(chunk)+len(carry)) + data = append(data, chunk...) + data = append(data, carry...) + lines := bytes.Split(data, []byte{'\n'}) + firstComplete := 1 + if position == 0 { + firstComplete = 0 + } + for index := len(lines) - 1; index >= firstComplete; index-- { + if turnID, ordinal, at, ok := rolloutTurnIDRecord(lines[index]); ok && + tokenRecordIsOwned(ordinal, cursor.subagentHistoryStartOrdinal, at, cursor.nonRoot, cursor.startedAt) { + return turnID, nil + } + } + carry = append(carry[:0], lines[0]...) + } + return "", nil +} + func turnTimingRecord(line []byte) (time.Duration, bool, *uint64, time.Time, bool) { if !bytes.Contains(line, []byte("task_complete")) && !bytes.Contains(line, []byte("turn_complete")) { return 0, false, nil, time.Time{}, false diff --git a/internal/codex/live_usage_test.go b/internal/codex/live_usage_test.go index a8759360..cfd0f786 100644 --- a/internal/codex/live_usage_test.go +++ b/internal/codex/live_usage_test.go @@ -549,12 +549,112 @@ func TestLiveUsageReaderUsesPerThreadExactStatuses(t *testing.T) { } } +func TestLiveUsageReaderCorrectsRequestedModelFromDelayedDaemonReroute(t *testing.T) { + home := t.TempDir() + now := time.Now() + path := testRolloutPath(t, home, now, "rerouted-thread") + writeRollout(t, path, sessionMetaLine("rerouted-thread", `"cli"`, "/work/rerouted", nil)+"\n") + reader, err := NewLiveUsageReader(home) + if err != nil { + t.Fatal(err) + } + reader.statusProvider = stubSessionStatusProvider{} + if _, err := reader.FetchTokenUsage(context.Background()); err != nil { + t.Fatal(err) + } + + usage := BenchmarkUsage{ + TotalTokens: 130, InputTokens: 100, CachedInputTokens: 20, OutputTokens: 30, + } + appendRollout(t, path, + turnContextWithTurnIDLine(now, "turn-1", "gpt-5.6-sol")+"\n"+ + richTokenCountLine(now.Add(time.Second), 130, 100, 20, 0, 30)+"\n") + reader.statusProvider = stubSessionStatusProvider{subscribed: map[string]struct{}{"rerouted-thread": {}}} + first, err := reader.FetchTokenUsage(context.Background()) + if err != nil || len(first.Sessions) != 1 || len(first.Sessions[0].ModelCalls) != 1 { + t.Fatalf("requested-model reading = %#v, %v", first, err) + } + _, requestedKnown, _ := EstimateStandardAPIEqCost("gpt-5.6-sol", usage) + if call := first.Sessions[0].ModelCalls[0]; call.Model != "gpt-5.6-sol" || + !requestedKnown || call.APIEqKnown || call.APIEqUSD != 0 || first.APIEqUnpricedCalls != 1 { + t.Fatalf("pending reroute call = %#v snapshot %#v", call, first) + } + + reader.statusProvider = stubSessionStatusProvider{ + subscribed: map[string]struct{}{"rerouted-thread": {}}, observations: []resolvedModelObservation{{ + Sequence: 1, ThreadID: "rerouted-thread", TurnID: "turn-1", Model: "gpt-5.6-terra", Usage: usage, CumulativeTotal: 130, + }}} + corrected, err := reader.FetchTokenUsage(context.Background()) + if err != nil || len(corrected.Sessions) != 1 || len(corrected.Sessions[0].ModelCalls) != 1 { + t.Fatalf("reroute-corrected reading = %#v, %v", corrected, err) + } + resolvedCost, resolvedKnown, _ := EstimateStandardAPIEqCost("gpt-5.6-terra", usage) + call := corrected.Sessions[0].ModelCalls[0] + if call.Model != "gpt-5.6-terra" || !resolvedKnown || !call.APIEqKnown || call.APIEqUSD != resolvedCost { + t.Fatalf("reroute-corrected call = %#v", call) + } + if corrected.APIEqUSD != resolvedCost || corrected.APIEqPricedCalls != 1 || corrected.APIEqUnpricedCalls != 0 { + t.Fatalf("reroute-corrected aggregate = %#v", corrected) + } +} + +func TestLiveUsageReaderRerouteCorrectionFailsClosedOnUnpriceableUsage(t *testing.T) { + usage := BenchmarkUsage{TotalTokens: 130, InputTokens: 100, CachedInputTokens: 20, OutputTokens: 30} + reader := &LiveUsageReader{ + files: map[string]*rolloutCursor{"rollout": {modelCalls: []LiveModelCall{{ + Sequence: 1, Model: "gpt-5.6-sol", + }}}}, + apiEqUnknownCalls: 1, + pendingModelResolutions: []pendingModelResolution{{ + callSequence: 1, threadID: "thread", turnID: "turn", usage: usage, cumulativeTotal: 130, + }}, + resolvedObservations: []resolvedModelObservation{{ + Sequence: 1, ThreadID: "thread", TurnID: "turn", Model: "gpt-5.6-terra", + Usage: BenchmarkUsage{ + TotalTokens: 130, InputTokens: 100, CachedInputTokens: 20, OutputTokens: 30, + schemaIssue: "unknown usage field: futureTokens", + }, + CumulativeTotal: 130, + }}, + } + reader.reconcilePendingModelResolutions() + call := reader.files["rollout"].modelCalls[0] + if call.Model != "gpt-5.6-terra" || call.APIEqKnown || reader.apiEqUSD != 0 || + reader.apiEqPricedCalls != 0 || reader.apiEqUnknownCalls != 1 { + t.Fatalf("unpriceable reroute correction = call %#v reader %#v", call, reader) + } +} + +func TestLiveUsageReaderFinalizesRequestedModelWhenDaemonHasNoReroute(t *testing.T) { + usage := BenchmarkUsage{TotalTokens: 110, InputTokens: 100, OutputTokens: 10} + reader := &LiveUsageReader{ + files: map[string]*rolloutCursor{"rollout": {modelCalls: []LiveModelCall{{ + Sequence: 1, Model: "gpt-5.6-sol", + }}}}, + apiEqUnknownCalls: 1, + pendingModelResolutions: []pendingModelResolution{{ + callSequence: 1, threadID: "thread", turnID: "turn", usage: usage, cumulativeTotal: 110, + }}, + } + reader.reconcilePendingModelResolutions() + want, known, _ := EstimateStandardAPIEqCost("gpt-5.6-sol", usage) + call := reader.files["rollout"].modelCalls[0] + if !known || !call.APIEqKnown || call.APIEqUSD != want || reader.apiEqUSD != want || + reader.apiEqPricedCalls != 1 || reader.apiEqUnknownCalls != 0 || len(reader.pendingModelResolutions) != 0 { + t.Fatalf("requested-model fallback = call %#v reader %#v", call, reader) + } +} + type stubSessionStatusProvider struct { - statuses map[string]sessionRuntimeStatus + statuses map[string]sessionRuntimeStatus + observations []resolvedModelObservation + subscribed map[string]struct{} } -func (s stubSessionStatusProvider) Fetch(context.Context, []string) (map[string]sessionRuntimeStatus, bool) { - return s.statuses, true +func (s stubSessionStatusProvider) Fetch(context.Context, []string) (sessionDaemonSnapshot, bool) { + return sessionDaemonSnapshot{ + Statuses: s.statuses, ModelObservations: s.observations, SubscribedThreads: s.subscribed, + }, true } func TestLiveUsageReaderPropagatesWaitingAgentToRoot(t *testing.T) { @@ -892,6 +992,13 @@ func turnContextLine(at time.Time, model string) string { return fmt.Sprintf(`{"timestamp":%q,"type":"turn_context","payload":{"model":%q}}`, at.UTC().Format(time.RFC3339Nano), model) } +func turnContextWithTurnIDLine(at time.Time, turnID, model string) string { + return fmt.Sprintf( + `{"timestamp":%q,"type":"turn_context","payload":{"turn_id":%q,"model":%q}}`, + at.UTC().Format(time.RFC3339Nano), turnID, model, + ) +} + func turnTimingLine(at time.Time, ttftMS int64) string { return fmt.Sprintf( `{"timestamp":%q,"type":"event_msg","payload":{"type":"task_complete","completed_at":%d,"duration_ms":12000,"time_to_first_token_ms":%d}}`, diff --git a/internal/version/version.go b/internal/version/version.go index 2a6e771c..0ea708a6 100644 --- a/internal/version/version.go +++ b/internal/version/version.go @@ -11,7 +11,7 @@ import ( // checkout. Release automation may override it with: // // -X github.com/merefield/codexometer/internal/version.Fallback=1.2.3 -var Fallback = "0.7.2" +var Fallback = "0.7.3" // Current returns the module version embedded by Go for tagged installs, or // Fallback for ordinary source builds. The leading tag prefix is omitted so diff --git a/internal/version/version_test.go b/internal/version/version_test.go index 13fa01b9..d02872df 100644 --- a/internal/version/version_test.go +++ b/internal/version/version_test.go @@ -4,8 +4,8 @@ import "testing" func TestCurrentReportsMaintainedFallbackForSourceBuild(t *testing.T) { got := Current() - if got != "0.7.2" { - t.Fatalf("Current() = %q, want 0.7.2", got) + if got != "0.7.3" { + t.Fatalf("Current() = %q, want 0.7.3", got) } } diff --git a/main_test.go b/main_test.go index ad3fc8e1..64a12d4f 100644 --- a/main_test.go +++ b/main_test.go @@ -16,7 +16,7 @@ func TestRunVersion(t *testing.T) { for _, flag := range []string{"-v", "--version"} { var stdout, stderr bytes.Buffer code := run([]string{flag}, &stdout, &stderr, dependencies{}) - if code != 0 || stdout.String() != "codexometer v0.7.2\n" || stderr.Len() != 0 { + if code != 0 || stdout.String() != "codexometer v0.7.3\n" || stderr.Len() != 0 { t.Errorf("flag=%s code=%d stdout=%q stderr=%q", flag, code, stdout.String(), stderr.String()) } } From b192bc10c33f089158d7c65ec55f1eedeb5f053e Mon Sep 17 00:00:00 2001 From: merefield Date: Fri, 14 Aug 2026 20:55:42 +0100 Subject: [PATCH 2/2] DOC: add recommended Codex setup --- README.md | 112 ++++++++++++++++++++++++++++++++++-------------------- 1 file changed, 70 insertions(+), 42 deletions(-) diff --git a/README.md b/README.md index 8275842e..25860160 100644 --- a/README.md +++ b/README.md @@ -185,46 +185,73 @@ Preview all UI features using simulated quota data: codexometer --demo ``` -## Shared Codex daemon for live status and model resolution - -Codexometer works without a shared server, but its `CHECK SESSION` fallback -cannot distinguish every long-running local tool from a prompt. On Unix -systems, a current standalone Codex installation can instead run one shared -app-server daemon. Every CLI connected to that daemon exposes its live -per-thread `waitingOnApproval` and `waitingOnUserInput` flags, allowing the -Monitor to show definite `APPROVAL NEEDED` and `INPUT NEEDED` badges. It also -lets Codexometer observe live `model/rerouted` and per-response token-usage -events. When those events match a local rollout response exactly, Quota and -Monitor API-equivalent figures use the model that actually served the response -instead of the requested model. - -Start the managed daemon and confirm that it is ready: - -```sh -codex app-server daemon start -codex app-server daemon version -``` - -Then launch each Codex CLI terminal against its default Unix control socket: - -```sh -codex --remote unix:// -``` - -Run that client command in every terminal tab or pane that should share the -daemon. Start Codexometer normally in another terminal: - -```sh -codexometer -``` - -No Codexometer option is required. While Monitor is recording, Codexometer -automatically probes the same default socket under `CODEX_HOME` and uses exact -runtime status for threads loaded there. Codexometer subscribes only to thread -IDs that are already loaded by that daemon; it does not load unrelated -historical sessions. Sessions belonging to ordinary, non-daemon Codex -processes continue to use the local rollout, requested-model pricing, and -writer-lock fallback. +## Recommended Codex CLI setup + +Codexometer works with an ordinary Codex CLI process, but connecting your CLI +sessions through one shared app-server daemon unlocks its most accurate live +telemetry on macOS, Linux, and WSL: + +- **Definite attention states** — Monitor can distinguish `INPUT NEEDED` from + `APPROVAL NEEDED` using live per-thread status instead of eventually showing + the cautious `CHECK SESSION` inactivity fallback. +- **Resolved-model API equivalents** — live model-reroute and response-usage + events let Codexometer price a positively matched call using the model that + actually served it, rather than relying only on the requested model saved in + the rollout. +- **Better multi-session visibility** — every connected CLI tab or pane remains + a separate Monitor session while sharing the same accurate status source; + explicitly linked subagents are still folded into their root session. +- **No extra Codexometer authentication** — the daemon, CLI clients, and + Codexometer continue to use the prevailing Codex login under the same + `CODEX_HOME`. +- **Safe degradation** — sessions not connected to the daemon continue to use + all core quota features with requested-model pricing, rollout lifecycle + signals, and writer-lock attention detection. + +Set up the recommended arrangement as follows. + +1. Confirm that the current standalone Codex CLI and Codexometer see the same + login and `CODEX_HOME`: + + ```sh + codex --version + codexometer --check-auth + ``` + +2. Start the managed daemon and confirm that it is ready: + + ```sh + codex app-server daemon start + codex app-server daemon version + ``` + +3. Launch each working Codex CLI terminal against the daemon's default Unix + control socket: + + ```sh + codex --remote unix:// + ``` + + Run this client command separately in every terminal tab or pane that + Codexometer should monitor through the shared daemon. + +4. Start Codexometer in an adjacent window or split pane before beginning work + that you want attributed: + + ```sh + codexometer + ``` + + Starting it first matters because transient model-reroute events cannot be + reconstructed after the fact. No additional Codexometer option is required; + it automatically probes the same default socket under `CODEX_HOME`. + +5. Leave Codexometer running while you work. Use Monitor Start when you want a + measured interval, and keep unrelated Codex activity quiet while running + Benchmarks if you want the cleanest comparisons. + +Codexometer subscribes only to thread IDs that are already loaded by the +daemon; it does not load unrelated historical sessions. Manage or stop the daemon with: @@ -234,8 +261,9 @@ codex app-server daemon stop ``` The managed daemon lifecycle is currently experimental, Unix-only, and expects -the standalone Codex installation. The app-server also supports a local -WebSocket listener, including on Windows: +the standalone Codex installation. Native Windows and other ordinary CLI +sessions remain fully usable through the fallback described above. The +app-server also supports a local WebSocket listener, including on Windows: ```sh codex app-server --listen ws://127.0.0.1:4500