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
215 changes: 182 additions & 33 deletions README.md

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ require (
github.com/charmbracelet/bubbletea v1.2.4
github.com/charmbracelet/lipgloss v1.0.0
github.com/charmbracelet/x/ansi v0.4.5
github.com/gorilla/websocket v1.5.3
go.starlark.net v0.0.0-20260708150628-5395d018f003
golang.org/x/sys v0.42.0
)

require (
Expand All @@ -22,6 +24,5 @@ require (
github.com/muesli/termenv v0.15.2 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
golang.org/x/sync v0.9.0 // indirect
golang.org/x/sys v0.42.0 // indirect
golang.org/x/text v0.3.8 // indirect
)
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
Expand Down
44 changes: 44 additions & 0 deletions internal/codex/benchmark.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"math"
"os"
"os/exec"
"sort"
"strings"
"sync"
"time"
Expand All @@ -26,6 +27,12 @@ const (
benchmarkCodeLimit = 64 * 1024
benchmarkStepLimit = 250_000
benchmarkHardStepLimit = 2_000_000

// BenchmarkPricingSourceURL and BenchmarkPricingRetrievedOn identify the
// published rates compiled into this release. Keep both in sync whenever
// standardAPIPrices changes.
BenchmarkPricingSourceURL = "https://developers.openai.com/api/docs/pricing"
BenchmarkPricingRetrievedOn = "2026-08-13"
)

// BenchmarkUsage is the app-server token breakdown for one isolated turn.
Expand All @@ -36,6 +43,40 @@ type BenchmarkUsage struct {
CacheWriteInputTokens int64 `json:"cacheWriteInputTokens"`
OutputTokens int64 `json:"outputTokens"`
ReasoningOutputTokens int64 `json:"reasoningOutputTokens"`
schemaIssue string
}

// UnmarshalJSON records unknown fields instead of silently discarding them.
// A future app-server token class may be billable, so costing must remain
// unavailable until Codexometer knows how to account for it.
func (u *BenchmarkUsage) UnmarshalJSON(data []byte) error {
type wireUsage BenchmarkUsage
var decoded wireUsage
if err := json.Unmarshal(data, &decoded); err != nil {
return err
}
var fields map[string]json.RawMessage
if err := json.Unmarshal(data, &fields); err != nil {
return err
}
known := map[string]struct{}{
"totalTokens": {}, "inputTokens": {}, "cachedInputTokens": {},
"cacheWriteInputTokens": {}, "outputTokens": {}, "reasoningOutputTokens": {},
}
unknown := make([]string, 0)
for name := range fields {
if _, ok := known[name]; !ok {
unknown = append(unknown, name)
}
}
sort.Strings(unknown)
*u = BenchmarkUsage(decoded)
if len(unknown) == 1 {
u.schemaIssue = "unknown usage field: " + unknown[0]
} else if len(unknown) > 1 {
u.schemaIssue = "unknown usage fields: " + strings.Join(unknown, ", ")
}
return nil
}

// BenchmarkUsageSource identifies the telemetry used for a benchmark result.
Expand Down Expand Up @@ -859,6 +900,9 @@ func (u *BenchmarkUsage) add(other BenchmarkUsage) string {
}

func validateBenchmarkUsage(usage BenchmarkUsage) string {
if usage.schemaIssue != "" {
return usage.schemaIssue
}
fields := []struct {
name string
value int64
Expand Down
43 changes: 43 additions & 0 deletions internal/codex/benchmark_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -563,6 +563,49 @@ func TestValidateBenchmarkUsageInvariants(t *testing.T) {
}
}

func TestBenchmarkUsageRejectsUnknownTokenFields(t *testing.T) {
var usage BenchmarkUsage
input := `{
"totalTokens": 130,
"inputTokens": 100,
"cachedInputTokens": 20,
"cacheWriteInputTokens": 10,
"outputTokens": 30,
"reasoningOutputTokens": 15,
"vectorTokens": 2,
"audioTokens": 1
}`
if err := json.Unmarshal([]byte(input), &usage); err != nil {
t.Fatalf("decode usage: %v", err)
}
want := "unknown usage fields: audioTokens, vectorTokens"
if issue := validateBenchmarkUsage(usage); issue != want {
t.Fatalf("usage issue = %q, want %q", issue, want)
}
if _, known, issue := estimateAPICostWithIssue("gpt-5.6-sol", usage); known || !strings.Contains(issue, want) {
t.Fatalf("unknown token fields received a cost: known=%v issue=%q", known, issue)
}

state := newBenchmarkTelemetry()
state.recordCumulative(usage)
var result BenchmarkResult
state.apply(&result)
if result.UsageKnown || !strings.Contains(result.UsageIssue, want) {
t.Fatalf("unknown token fields did not fail telemetry closed: %#v", result)
}
}

func TestBenchmarkUsageAcceptsDocumentedTokenFields(t *testing.T) {
var usage BenchmarkUsage
input := `{"totalTokens":130,"inputTokens":100,"cachedInputTokens":20,"cacheWriteInputTokens":10,"outputTokens":30,"reasoningOutputTokens":15}`
if err := json.Unmarshal([]byte(input), &usage); err != nil {
t.Fatalf("decode usage: %v", err)
}
if issue := validateBenchmarkUsage(usage); issue != "" {
t.Fatalf("documented usage fields rejected: %s", issue)
}
}

func TestExperimentalAPIUnsupported(t *testing.T) {
for _, test := range []struct {
err error
Expand Down
16 changes: 13 additions & 3 deletions internal/codex/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,16 @@ func TestFetchUsesAppServerHandshakeAndDecodesSnapshot(t *testing.T) {
t.Fatal(err)
}
meters := snapshot.Meters()
if len(meters) != 2 || meters[0].Window.UsedPercent != 42 || meters[1].Window.UsedPercent != 5 {
if len(meters) != 3 || meters[0].Window.UsedPercent != 42 || meters[1].Window.UsedPercent != 5 ||
meters[2].Kind != MeterIndividualLimit || meters[2].Window.UsedPercent != 32 {
t.Fatalf("unexpected fetched meters: %#v", meters)
}
if snapshot.RateLimits.SpendControlReached == nil || *snapshot.RateLimits.SpendControlReached {
t.Fatalf("spend-control state was not decoded: %#v", snapshot.RateLimits)
}
if credits, ok := snapshot.CreditStatus(); !ok || credits.Balance == nil || *credits.Balance != "17000" {
t.Fatalf("credit status was not decoded: %#v, %v", credits, ok)
}
if snapshot.FetchedAt.IsZero() {
t.Fatal("fetch time was not recorded")
}
Expand Down Expand Up @@ -114,8 +121,11 @@ func runFakeAppServer() {
"id": *request.ID,
"result": map[string]any{
"rateLimits": map[string]any{
"primary": map[string]any{"usedPercent": 42, "windowDurationMins": 300},
"secondary": map[string]any{"usedPercent": 5, "windowDurationMins": 10_080},
"primary": map[string]any{"usedPercent": 42, "windowDurationMins": 300},
"secondary": map[string]any{"usedPercent": 5, "windowDurationMins": 10_080},
"individualLimit": map[string]any{"limit": "25000", "used": "8000", "remainingPercent": 68, "resetsAt": 1_800_000_000},
"spendControlReached": false,
"credits": map[string]any{"hasCredits": true, "unlimited": false, "balance": "17000"},
},
},
})
Expand Down
36 changes: 36 additions & 0 deletions internal/codex/daemon_status.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package codex

import "context"

type sessionRuntimeStatus int

const (
sessionRuntimeUnknown sessionRuntimeStatus = iota
sessionRuntimeWorking
sessionRuntimeIdle
sessionRuntimeInput
sessionRuntimeApproval
)

type sessionStatusProvider interface {
Fetch(context.Context, []string) (map[string]sessionRuntimeStatus, bool)
}

func parseSessionRuntimeStatus(kind string, flags []string) sessionRuntimeStatus {
if kind == "idle" {
return sessionRuntimeIdle
}
if kind != "active" {
return sessionRuntimeUnknown
}
status := sessionRuntimeWorking
for _, flag := range flags {
switch flag {
case "waitingOnApproval":
return sessionRuntimeApproval
case "waitingOnUserInput":
status = sessionRuntimeInput
}
}
return status
}
5 changes: 5 additions & 0 deletions internal/codex/daemon_status_other.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
//go:build !unix

package codex

func newSessionStatusProvider(string) sessionStatusProvider { return nil }
23 changes: 23 additions & 0 deletions internal/codex/daemon_status_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package codex

import "testing"

func TestParseSessionRuntimeStatus(t *testing.T) {
tests := []struct {
kind string
flags []string
want sessionRuntimeStatus
}{
{"idle", nil, sessionRuntimeIdle},
{"active", nil, sessionRuntimeWorking},
{"active", []string{"waitingOnUserInput"}, sessionRuntimeInput},
{"active", []string{"waitingOnApproval"}, sessionRuntimeApproval},
{"active", []string{"waitingOnUserInput", "waitingOnApproval"}, sessionRuntimeApproval},
{"notLoaded", nil, sessionRuntimeUnknown},
}
for _, test := range tests {
if got := parseSessionRuntimeStatus(test.kind, test.flags); got != test.want {
t.Errorf("parseSessionRuntimeStatus(%q, %v) = %v; want %v", test.kind, test.flags, got, test.want)
}
}
}
112 changes: 112 additions & 0 deletions internal/codex/daemon_status_unix.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
//go:build unix

package codex

import (
"context"
"encoding/json"
"net"
"net/http"
"path/filepath"
"time"

"github.com/gorilla/websocket"
)

const daemonStatusTimeout = 2 * time.Second

type daemonStatusProvider struct {
socketPath string
}

func newSessionStatusProvider(codexHome string) sessionStatusProvider {
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()
}
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
}

statuses := make(map[string]sessionRuntimeStatus, len(threadIDs))
for _, threadID := range threadIDs {
setDaemonDeadline()
requestID++
var result struct {
Thread struct {
ID string `json:"id"`
Status struct {
Type string `json:"type"`
ActiveFlags []string `json:"activeFlags"`
} `json:"status"`
} `json:"thread"`
}
if err := daemonRequest(connection, requestID, "thread/read", map[string]any{
"threadId": threadID, "includeTurns": false,
}, &result); err != nil {
continue
}
status := parseSessionRuntimeStatus(result.Thread.Status.Type, result.Thread.Status.ActiveFlags)
if status != sessionRuntimeUnknown {
statuses[threadID] = status
}
}
return statuses, true
}

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 {
return err
}
for {
var envelope struct {
ID *int64 `json:"id"`
Result json.RawMessage `json:"result"`
Error json.RawMessage `json:"error"`
}
if err := connection.ReadJSON(&envelope); err != nil {
return err
}
if envelope.ID == nil || *envelope.ID != id {
continue
}
if len(envelope.Error) > 0 && string(envelope.Error) != "null" {
return &daemonResponseError{payload: string(envelope.Error)}
}
return json.Unmarshal(envelope.Result, target)
}
}

type daemonResponseError struct{ payload string }

func (e *daemonResponseError) Error() string { return e.payload }
Loading
Loading