Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
668 lines (629 loc) · 25.9 KB
/
Copy pathmain.go
File metadata and controls
668 lines (629 loc) · 25.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
package main
import (
"context"
"flag"
"fmt"
"io"
"os"
"os/signal"
"sort"
"strconv"
"strings"
"sync"
"time"
tea "charm.land/bubbletea/v2"
"github.com/merefield/codexometer/internal/codex"
"github.com/merefield/codexometer/internal/digbench"
"github.com/merefield/codexometer/internal/ui"
"github.com/merefield/codexometer/internal/version"
"github.com/merefield/codexometer/internal/web"
)
type demoFetcher struct {
quotaSteps []codex.QuotaStep
approvalDecision string
mu sync.Mutex
snapshot codex.Snapshot
pendingQuota int
suppressUsage bool
lifetimeTokens int64
apiEqUSD float64
apiEqCalls int64
eventSequence uint64
alphaCalls []codex.LiveModelCall
alphaTurns []codex.LiveTurnTiming
bravoCalls []codex.LiveModelCall
bravoTurns []codex.LiveTurnTiming
}
func (d *demoFetcher) QuotaStepPolicy() []codex.QuotaStep {
return append([]codex.QuotaStep(nil), d.quotaSteps...)
}
func (d *demoFetcher) QuotaSessions(ctx context.Context) ([]codex.QuotaSession, error) {
return []codex.QuotaSession{{ID: "019d-demo-a1b2c", Model: "gpt-5.6-sol", Effort: "high"}, {ID: "019d-demo-d4e5f", Model: "gpt-5.6-sol", Effort: "high"}}, ctx.Err()
}
func (d *demoFetcher) ApplyQuotaProfile(ctx context.Context, targets []codex.QuotaSession, step codex.QuotaStep) (int, error) {
if err := ctx.Err(); err != nil {
return 0, err
}
d.mu.Lock()
defer d.mu.Unlock()
return len(targets), nil
}
func (d *demoFetcher) CloseQuotaProfiles() {}
func (d *demoFetcher) ResolveQuotaStep(ctx context.Context, step codex.QuotaStep) (codex.QuotaStep, error) {
return step, ctx.Err()
}
type quotaStepFlags []codex.QuotaStep
func (f *quotaStepFlags) String() string {
values := make([]string, 0, len(*f))
for _, step := range *f {
value := fmt.Sprintf("%d:%s:%s", step.Threshold, step.Model, step.Effort)
if step.ServiceTier != "" || step.Mode != "" {
value += ":" + quotaStepSpeedFlag(step.ServiceTier)
}
if step.Mode != "" {
value += ":" + step.Mode
}
values = append(values, value)
}
return strings.Join(values, ",")
}
func (f *quotaStepFlags) Set(value string) error {
parts := strings.Split(value, ":")
if len(parts) < 3 || len(parts) > 5 {
return fmt.Errorf("must be PERCENT:MODEL:EFFORT[:SPEED[:ask|auto]]")
}
threshold, err := strconv.Atoi(strings.TrimSpace(parts[0]))
if err != nil || threshold < 1 || threshold > 100 {
return fmt.Errorf("percentage must be between 1 and 100")
}
model, effort := strings.TrimSpace(parts[1]), strings.TrimSpace(parts[2])
if model == "" {
return fmt.Errorf("model is required")
}
validEffort := false
for _, candidate := range []string{"none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra"} {
if effort == candidate {
validEffort = true
break
}
}
if !validEffort {
return fmt.Errorf("unsupported reasoning effort %q", effort)
}
for _, step := range *f {
if step.Threshold == threshold {
return fmt.Errorf("percentage %d is configured more than once", threshold)
}
}
serviceTier := ""
if len(parts) >= 4 && !(len(parts) == 5 && strings.TrimSpace(parts[3]) == "") {
switch strings.ToLower(strings.TrimSpace(parts[3])) {
case "fast", "slow", "flex", "priority":
serviceTier = strings.ToLower(strings.TrimSpace(parts[3]))
case "standard", "default":
serviceTier = "default"
default:
return fmt.Errorf("speed must be fast, slow, flex, priority, or standard (and advertised by Codex)")
}
}
mode := ""
if len(parts) == 5 {
mode = strings.ToLower(strings.TrimSpace(parts[4]))
if mode != "ask" && mode != "auto" {
return fmt.Errorf("mode must be ask or auto")
}
}
*f = append(*f, codex.QuotaStep{Threshold: threshold, Model: model, Effort: effort, ServiceTier: serviceTier, Mode: mode})
sort.Slice(*f, func(i, j int) bool { return (*f)[i].Threshold < (*f)[j].Threshold })
return nil
}
func quotaStepSpeedFlag(tier string) string {
switch tier {
case "default":
return "standard"
default:
return tier
}
}
func (d *demoFetcher) FetchAccountUsage(context.Context) (codex.AccountUsage, error) {
now := time.Now()
history := codex.AccountUsage{AccountFingerprint: "demo-account", FetchedAt: now, DailyUsageBuckets: []codex.AccountUsageDay{}}
var total, peak int64
for i := 363; i >= 0; i-- {
tokens := int64((i * 7919) % 80000)
if i%7 == 0 {
tokens = 0
}
total += tokens
peak = max(peak, tokens)
history.DailyUsageBuckets = append(history.DailyUsageBuckets, codex.AccountUsageDay{StartDate: now.UTC().AddDate(0, 0, -i).Format("2006-01-02"), Tokens: tokens})
}
history.Summary.LifetimeTokens = &total
history.Summary.PeakDailyTokens = &peak
longestTurn, currentStreak, longestStreak := int64(547), int64(8), int64(21)
history.Summary.LongestRunningTurnSec = &longestTurn
history.Summary.CurrentStreakDays = ¤tStreak
history.Summary.LongestStreakDays = &longestStreak
history.Reports = codex.DemoUsageReports(now)
return history, nil
}
func (d *demoFetcher) Fetch(context.Context) (codex.Snapshot, error) {
d.mu.Lock()
defer d.mu.Unlock()
if d.snapshot.RateLimits.Primary == nil {
d.snapshot = codex.DemoSnapshot()
d.snapshot.AccountFingerprint = "demo-account"
}
if d.pendingQuota > 0 {
d.snapshot.RateLimits.Primary.UsedPercent = min(97, d.snapshot.RateLimits.Primary.UsedPercent+d.pendingQuota)
d.snapshot.RateLimits.Secondary.UsedPercent = min(97, d.snapshot.RateLimits.Secondary.UsedPercent+d.pendingQuota)
d.pendingQuota = 0
}
d.suppressUsage = true
d.snapshot.FetchedAt = time.Now()
return cloneDemoSnapshot(d.snapshot), nil
}
func cloneDemoSnapshot(snapshot codex.Snapshot) codex.Snapshot {
cloned := snapshot
if snapshot.RateLimits.Primary != nil {
primary := *snapshot.RateLimits.Primary
cloned.RateLimits.Primary = &primary
}
if snapshot.RateLimits.Secondary != nil {
secondary := *snapshot.RateLimits.Secondary
cloned.RateLimits.Secondary = &secondary
}
if snapshot.RateLimitResetCredits != nil {
credits := *snapshot.RateLimitResetCredits
cloned.RateLimitResetCredits = &credits
}
return cloned
}
func (d *demoFetcher) FetchTokenUsage(context.Context) (codex.LiveUsageSnapshot, error) {
d.mu.Lock()
defer d.mu.Unlock()
if d.lifetimeTokens == 0 {
d.lifetimeTokens = 100_000
d.suppressUsage = false
} else if d.suppressUsage {
d.suppressUsage = false
} else {
d.lifetimeTokens += 1_234
d.apiEqUSD += 0.18
d.apiEqCalls++
d.pendingQuota += 5
now := time.Now()
d.eventSequence++
call := codex.LiveModelCall{
Sequence: d.eventSequence, At: now, Model: "gpt-5.6-terra",
OutputTokens: 420 + int64(d.eventSequence%5)*137, OutputAvailable: true,
APIEqUSD: 0.18, APIEqKnown: true,
}
d.eventSequence++
timing := codex.LiveTurnTiming{Sequence: d.eventSequence, At: now, TimeToFirstToken: time.Duration(900+d.eventSequence%7*350) * time.Millisecond, Available: true}
if d.eventSequence/2%2 == 0 {
d.alphaCalls = append(d.alphaCalls, call)
d.alphaTurns = append(d.alphaTurns, timing)
} else {
d.bravoCalls = append(d.bravoCalls, call)
d.bravoTurns = append(d.bravoTurns, timing)
}
}
alphaTokens := d.lifetimeTokens * 3 / 5
attention := codex.SessionAttentionApproval
preview := codex.SessionContext{Kind: codex.SessionContextApproval, Text: "DEMO ONLY — no command will run.\nAllow pushing the documentation update?\nCommand: git push origin main\nDirectory: /projects/alpha", ThreadID: "019d-demo-a1b2c", Source: "DEMO", At: time.Now().Add(-time.Minute), ApprovalToken: "demo-command"}
preview.CommandDetails = codex.ApprovalCommandDetails{Justification: "DEMO ONLY — no command will run.\nAllow pushing the documentation update?", Command: "git push origin main", Directory: "/projects/alpha"}
preview.ApprovalOptions = [8]codex.ApprovalOption{{Kind: "accept", Value: "accept", Wire: `"accept"`}, {Kind: "acceptForSession", Value: "acceptForSession", Wire: `"acceptForSession"`}, {Kind: "cancel", Value: "cancel", Wire: `"cancel"`}}
preview.ApprovalDecisions = "accept, acceptForSession, cancel"
if d.approvalDecision != "" {
attention = codex.SessionAttentionNone
preview.Kind = codex.SessionContextReply
preview.ApprovalToken = ""
preview.Text = "Simulated decision: " + d.approvalDecision + ". No command was executed."
}
return codex.LiveUsageSnapshot{
TotalTokens: d.lifetimeTokens, APIEqUSD: d.apiEqUSD, APIEqPricedCalls: d.apiEqCalls,
LastActivity: time.Now(), SessionCount: 2,
CodexStatusKnown: true, CodexUp: true, CodexWorking: true,
Sessions: []codex.LiveUsageSession{
{ID: "019d-demo-a1b2c", WorkingDirectory: "/projects/alpha", TotalTokens: alphaTokens, LastActivity: time.Now(), AgentCount: 2, Active: true,
Attention: attention, Context: preview, ModelCalls: append([]codex.LiveModelCall(nil), d.alphaCalls...), TurnTimings: append([]codex.LiveTurnTiming(nil), d.alphaTurns...)},
{ID: "019d-demo-d4e5f", WorkingDirectory: "/projects/bravo", TotalTokens: d.lifetimeTokens - alphaTokens, LastActivity: time.Now(), Active: true,
Attention: codex.SessionAttentionComplete, Context: codex.SessionContext{Kind: codex.SessionContextReply, Text: "Pushed directly to main.\nIncludes both README and intro-post updates.", ThreadID: "019d-demo-d4e5f", Source: "DEMO", At: time.Now().Add(-2 * time.Minute)}, ModelCalls: append([]codex.LiveModelCall(nil), d.bravoCalls...), TurnTimings: append([]codex.LiveTurnTiming(nil), d.bravoTurns...)},
},
}, nil
}
func (d *demoFetcher) BenchmarkCombinationCount(context.Context) (int, error) { return 2, nil }
func (d *demoFetcher) SessionApprovalPending(token string) bool {
d.mu.Lock()
defer d.mu.Unlock()
return token == "demo-command" && d.approvalDecision == ""
}
func (d *demoFetcher) RespondSessionApproval(ctx context.Context, token, decision string) error {
d.mu.Lock()
defer d.mu.Unlock()
if err := ctx.Err(); err != nil {
return err
}
if token != "demo-command" || d.approvalDecision != "" || (decision != "accept" && decision != "acceptForSession" && decision != "cancel") {
return fmt.Errorf("invalid or resolved demo approval")
}
d.approvalDecision = decision
return nil
}
func (d *demoFetcher) RunBenchmarkSuite(ctx context.Context, tasks []codex.BenchmarkTaskID, emit func(codex.BenchmarkEvent)) {
d.RunBenchmarkSuiteScoped(ctx, tasks, d.demoBenchmarkPlan().AllScope(), emit)
}
func (d *demoFetcher) BenchmarkPlan(context.Context) (codex.BenchmarkPlan, error) {
return d.demoBenchmarkPlan(), nil
}
func (d *demoFetcher) demoBenchmarkPlan() codex.BenchmarkPlan {
return codex.BenchmarkPlan{
Models: []codex.BenchmarkModelOption{
{Model: "gpt-5.6-sol", DisplayName: "GPT-5.6 Sol", Efforts: []string{"medium"}},
{Model: "gpt-5.6-terra", DisplayName: "GPT-5.6 Terra", Efforts: []string{"low"}},
},
Efforts: []string{"low", "medium"},
}
}
func (d *demoFetcher) RunBenchmarkSuiteScoped(ctx context.Context, tasks []codex.BenchmarkTaskID, scope codex.BenchmarkScope, emit func(codex.BenchmarkEvent)) {
baseResults := []codex.BenchmarkResult{
{Model: "gpt-5.6-sol", DisplayName: "GPT-5.6 Sol", Effort: "medium", ActualModel: "gpt-5.6-sol", Correct: true, Duration: 12_400 * time.Millisecond, Usage: codex.BenchmarkUsage{TotalTokens: 4_820}, UsageKnown: true, CostUSD: 0.0412, CostKnown: true, Interactions: demoBenchmarkInteractions(true)},
{Model: "gpt-5.6-terra", DisplayName: "GPT-5.6 Terra", Effort: "low", ActualModel: "gpt-5.6-terra", Correct: false, Duration: 7_900 * time.Millisecond, Usage: codex.BenchmarkUsage{TotalTokens: 2_210}, UsageKnown: true, CostUSD: 0.0091, CostKnown: true, Failure: "case 17 returned the wrong answer", Interactions: demoBenchmarkInteractions(false)},
}
models, efforts := make(map[string]bool), make(map[string]bool)
for _, model := range scope.Models {
models[model] = true
}
for _, effort := range scope.Efforts {
efforts[effort] = true
}
if len(tasks) == 0 {
tasks = []codex.BenchmarkTaskID{codex.BenchmarkMergeRanges}
}
var results []codex.BenchmarkResult
for _, taskID := range tasks {
for _, task := range codex.BenchmarkTasks() {
if task.ID != taskID {
continue
}
for _, base := range baseResults {
if !models[base.Model] || !efforts[base.Effort] {
continue
}
result := base
result.TaskID, result.TaskName = task.ID, task.Name
results = append(results, result)
}
}
}
emit(codex.BenchmarkEvent{Total: len(results), Combinations: 2})
for index := range results {
select {
case <-ctx.Done():
emit(codex.BenchmarkEvent{Total: len(results), Completed: index, Done: true, Err: ctx.Err()})
return
default:
}
emit(codex.BenchmarkEvent{Total: len(results), Completed: index, CurrentModel: results[index].DisplayName, CurrentEffort: results[index].Effort})
result := results[index]
emit(codex.BenchmarkEvent{Total: len(results), Completed: index + 1, Combinations: 2, CurrentTaskID: result.TaskID, CurrentTask: result.TaskName, CurrentModel: result.DisplayName, CurrentEffort: result.Effort, Result: &result})
}
emit(codex.BenchmarkEvent{Total: len(results), Completed: len(results), Done: true})
}
func demoBenchmarkInteractions(passed bool) []codex.BenchmarkInteraction {
verdict := "case 17 returned the wrong answer"
if passed {
verdict = "Submission passed the deterministic verifier."
}
return []codex.BenchmarkInteraction{
{Kind: codex.BenchmarkInteractionPrompt, Content: "Implement the selected deterministic benchmark as one Starlark function and return a JSON object containing its complete source."},
{Elapsed: 7 * time.Second, Kind: codex.BenchmarkInteractionResponse, Content: "{\"code\":\"def solve(items):\\n return items\\n\"}"},
{Elapsed: 8 * time.Second, Kind: codex.BenchmarkInteractionVerifier, Content: verdict},
}
}
func main() {
os.Exit(run(os.Args[1:], os.Stdout, os.Stderr, defaultDependencies()))
}
type dependencies struct {
checkAuth func(context.Context, string) (codex.Snapshot, error)
listDigBenchGames func(context.Context, string) ([]string, error)
runDigBench func(context.Context, string, string, string, codex.DigBenchOptions) (codex.DigBenchResult, error)
startUI func(ui.Fetcher, time.Duration, bool, int, int) error
startWeb func(web.Source, time.Duration, int, io.Writer, bool) error
}
func defaultDependencies() dependencies {
return dependencies{
checkAuth: func(ctx context.Context, binary string) (codex.Snapshot, error) {
return (codex.Client{Binary: binary}).Fetch(ctx)
},
listDigBenchGames: func(ctx context.Context, token string) ([]string, error) {
response, err := (digbench.Client{Token: token}).ListGames(ctx)
return response.Games, err
},
runDigBench: func(ctx context.Context, binary, token, apiKey string, options codex.DigBenchOptions) (codex.DigBenchResult, error) {
return (codex.Client{Binary: binary, BenchmarkAPIKey: apiKey}).RunDigBench(ctx, digbench.Client{Token: token}, options)
},
startUI: startUI,
startWeb: func(source web.Source, refresh time.Duration, port int, output io.Writer, control bool) error {
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
defer cancel()
return web.Run(ctx, source, refresh, port, output, control)
},
}
}
func run(args []string, stdout, stderr io.Writer, deps dependencies) int {
flags := flag.NewFlagSet("codexometer", flag.ContinueOnError)
flags.SetOutput(stderr)
var quotaSteps quotaStepFlags
var (
codexPath = flags.String("codex", "codex", "path to the Codex CLI")
refresh = flags.Duration("refresh", time.Minute, "quota refresh interval")
demo = flags.Bool("demo", false, "show the UI with simulated quota data")
inline = flags.Bool("inline", false, "render inline instead of using the alternate screen")
webMode = flags.Bool("web", false, "serve the experimental read-only browser interface on loopback")
webControl = flags.Bool("web-control", false, "enable experimental browser session approvals, prompts and configured quota profiles (requires --web)")
webPort = flags.Int("web-port", 0, "local web port (0 chooses an available port; requires --web)")
resetThreshold = flags.Int("reset-threshold", 80, "show reset at this quota consumption (0-100; also shown for expiring credits)")
resetWarningHours = flags.Int("reset-warning-hours", 72, "warn this many hours before a reset credit expires (0 disables expiry warnings)")
checkAuth = flags.Bool("check-auth", false, "verify access to the current Codex login and exit")
digBenchGame = flags.String("digbench-game", "", "run one experimental DigBench game and exit")
digBenchModel = flags.String("digbench-model", "gpt-5.6-sol", "Codex model for --digbench-game")
digBenchEffort = flags.String("digbench-effort", "high", "reasoning effort for --digbench-game")
digBenchTimeout = flags.Duration("digbench-timeout", codex.DefaultDigBenchTimeout, "hard limit for --digbench-game")
printVersion bool
)
flags.Var("aSteps, "quota-step-down", "set PERCENT:MODEL:EFFORT[:SPEED[:ask|auto]] per session (repeatable; default ask; empty SPEED preserves speed)")
flags.BoolVar(&printVersion, "version", false, "print the version and exit")
flags.BoolVar(&printVersion, "v", false, "print the version and exit")
if err := flags.Parse(args); err != nil {
return 2
}
if printVersion {
fmt.Fprintln(stdout, "codexometer "+version.Current())
return 0
}
if *webPort < 0 || *webPort > 65535 || (*webPort != 0 && !*webMode) {
fmt.Fprintln(stderr, "codexometer: --web-port must be between 0 and 65535 and requires --web")
return 2
}
if *webControl && !*webMode {
fmt.Fprintln(stderr, "codexometer: --web-control requires --web")
return 2
}
if *webMode && (*inline || *checkAuth || strings.TrimSpace(*digBenchGame) != "") {
fmt.Fprintln(stderr, "codexometer: --web cannot be combined with --inline, --check-auth or --digbench-game")
return 2
}
if *webMode && len(quotaSteps) > 0 && !*webControl {
fmt.Fprintln(stderr, "codexometer: --quota-step-down in web mode requires --web-control")
return 2
}
if *resetThreshold < 0 || *resetThreshold > 100 {
fmt.Fprintln(stderr, "codexometer: --reset-threshold must be between 0 and 100")
return 2
}
if *resetWarningHours < 0 || *resetWarningHours > ui.MaxResetWarningHours {
fmt.Fprintf(stderr, "codexometer: --reset-warning-hours must be between 0 and %d\n", ui.MaxResetWarningHours)
return 2
}
// Capture credentials for the benchmark components, then remove them before
// any path that can launch Codex. This keeps auth checks and quota reads on
// the user's prevailing Codex login instead of leaking or implicitly using a
// benchmarking credential through the child environment.
benchmarkAPIKey, benchmarkAPIKeySource, err := takeBenchmarkAPIKey()
if err != nil {
fmt.Fprintln(stderr, "codexometer:", err)
return 1
}
digBenchToken, err := takeDigBenchToken()
if err != nil {
fmt.Fprintln(stderr, "codexometer:", err)
return 1
}
if *checkAuth {
snapshot, err := deps.checkAuth(context.Background(), *codexPath)
if err != nil {
fmt.Fprintln(stderr, "Codex auth check failed:", err)
return 1
}
fmt.Fprintf(stdout, "Codex auth OK // %d limit meter(s) online\n", len(snapshot.Meters()))
return 0
}
if strings.TrimSpace(*digBenchGame) != "" {
if *demo {
fmt.Fprintln(stderr, "codexometer: --digbench-game cannot be combined with --demo")
return 2
}
if digBenchToken == "" {
fmt.Fprintln(stderr, "codexometer: DIGBENCH_API_TOKEN is required for --digbench-game")
return 1
}
if deps.runDigBench == nil {
fmt.Fprintln(stderr, "codexometer: DigBench runner unavailable")
return 1
}
billing := "the prevailing Codex login and quota"
if benchmarkAPIKey != "" {
billing = "API-key usage-based billing from " + benchmarkAPIKeySource
}
fmt.Fprintf(stderr, "Starting DigBench %s with %s/%s; this creates a persisted remote session and uses %s.\n",
strings.TrimSpace(*digBenchGame), strings.TrimSpace(*digBenchModel), strings.TrimSpace(*digBenchEffort), billing)
result, err := deps.runDigBench(context.Background(), *codexPath, digBenchToken, benchmarkAPIKey, codex.DigBenchOptions{
Game: strings.TrimSpace(*digBenchGame), Model: strings.TrimSpace(*digBenchModel),
Effort: strings.TrimSpace(*digBenchEffort), Timeout: *digBenchTimeout, ClientVersion: version.Current(),
Progress: func(progress codex.DigBenchProgress) {
fmt.Fprintln(stderr, formatDigBenchProgress(progress))
},
})
if err != nil {
fmt.Fprintln(stderr, "codexometer: DigBench run failed:", err)
return 1
}
fmt.Fprintln(stdout, formatDigBenchResult(result))
if result.Failure != "" {
return 1
}
return 0
}
if *webMode {
// Web mode deliberately gets no benchmark credentials or discovery calls.
client := codex.Client{Binary: *codexPath, QuotaSteps: quotaSteps}
if liveUsage, err := codex.NewLiveUsageReader(""); err == nil {
client.LiveUsage = liveUsage
}
var source web.Source = client
if *demo {
source = &demoFetcher{quotaSteps: quotaSteps}
}
if err := deps.startWeb(source, *refresh, *webPort, stdout, *webControl); err != nil {
fmt.Fprintln(stderr, "codexometer:", err)
return 1
}
return 0
}
var digBenchGames []string
if digBenchToken != "" && deps.listDigBenchGames != nil {
discoveryCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
digBenchGames, err = deps.listDigBenchGames(discoveryCtx, digBenchToken)
cancel()
if err != nil {
fmt.Fprintln(stderr, "codexometer: DigBench game discovery unavailable:", err)
digBenchGames = nil
}
}
digBenchGames = normalizeDigBenchGames(digBenchGames)
client := codex.Client{Binary: *codexPath, BenchmarkAPIKey: benchmarkAPIKey, DigBenchToken: digBenchToken, DigBenchGames: digBenchGames, QuotaSteps: quotaSteps}
if liveUsage, err := codex.NewLiveUsageReader(""); err == nil {
client.LiveUsage = liveUsage
}
var fetcher ui.Fetcher = client
if *demo {
fetcher = &demoFetcher{quotaSteps: quotaSteps}
}
if err := deps.startUI(fetcher, *refresh, *inline, *resetThreshold, *resetWarningHours); err != nil {
fmt.Fprintln(stderr, "codexometer:", err)
return 1
}
return 0
}
func formatDigBenchProgress(progress codex.DigBenchProgress) string {
label := "DIGBENCH PROGRESS"
switch progress.Phase {
case codex.DigBenchProgressSession:
label = "DIGBENCH SESSION CREATED"
case codex.DigBenchProgressTurn:
label = "CODEX TURN STARTED"
case codex.DigBenchProgressHeartbeat:
label = "DIGBENCH WORKING"
}
level := fmt.Sprintf("%d", progress.Level)
if progress.MaxLevel > 0 {
level = fmt.Sprintf("%d/%d", progress.Level, progress.MaxLevel)
}
parts := []string{label, "LEVEL " + level, fmt.Sprintf("BEATEN %d", progress.LevelsBeaten), fmt.Sprintf("STEPS %d", progress.Steps)}
if progress.Status != "" {
parts = append(parts, "STATUS "+progress.Status)
}
if progress.ActualModel != "" && progress.Phase == codex.DigBenchProgressTurn {
parts = append(parts, "MODEL "+progress.ActualModel)
}
parts = append(parts, "ELAPSED "+progress.Elapsed.Round(100*time.Millisecond).String())
return strings.Join(parts, " // ")
}
func takeBenchmarkAPIKey() (key, source string, err error) {
for _, candidate := range []string{"CODEXOMETER_BENCHMARK_API_KEY", "OPENAI_API_KEY"} {
value := strings.TrimSpace(os.Getenv(candidate))
if unsetErr := os.Unsetenv(candidate); unsetErr != nil {
return "", "", fmt.Errorf("remove %s from child environment: %w", candidate, unsetErr)
}
if key == "" && value != "" {
key, source = value, candidate
}
}
return key, source, nil
}
func takeDigBenchToken() (string, error) {
token := strings.TrimSpace(os.Getenv("DIGBENCH_API_TOKEN"))
if err := os.Unsetenv("DIGBENCH_API_TOKEN"); err != nil {
return "", fmt.Errorf("remove DIGBENCH_API_TOKEN from child environment: %w", err)
}
return token, nil
}
func normalizeDigBenchGames(games []string) []string {
seen := make(map[string]bool, len(games))
normalized := make([]string, 0, len(games))
for _, game := range games {
game = strings.TrimSpace(game)
if game != "" && !containsTerminalControl(game) && !seen[game] {
seen[game] = true
normalized = append(normalized, game)
}
}
return normalized
}
func containsTerminalControl(value string) bool {
for _, character := range value {
if character < 0x20 || (character >= 0x7f && character <= 0x9f) {
return true
}
}
return false
}
func formatDigBenchResult(result codex.DigBenchResult) string {
outcome := "LOSS"
if result.Won {
outcome = "WIN"
} else if result.Failure != "" {
outcome = "INCOMPLETE"
}
levels := fmt.Sprintf("%d", result.LevelsBeaten)
if result.MaxLevel > 0 {
levels = fmt.Sprintf("%d/%d", result.LevelsBeaten, result.MaxLevel)
}
tokens := "N/A"
if result.UsageKnown {
tokens = fmt.Sprintf("%d", result.Usage.TotalTokens)
}
cost := "N/A"
if result.CostKnown {
cost = fmt.Sprintf("$%.4f", result.CostUSD)
}
line := fmt.Sprintf("DIGBENCH %s // %s // LEVELS %s // STEPS %d // %s/%s // %s // TOKENS %s // API EQ %s",
result.Game, outcome, levels, result.Steps, result.DisplayName, result.Effort,
result.Duration.Round(time.Millisecond), tokens, cost)
if result.ActualModel != "" && result.ActualModel != result.Model {
line += " // SERVED " + result.ActualModel
}
if result.Seed != nil {
line += fmt.Sprintf(" // SEED %d", *result.Seed)
}
if result.FrameworkVersion != "" {
line += " // ENGINE " + result.FrameworkVersion
}
if result.Failure != "" {
line += " // " + result.Failure
} else if !result.UsageKnown && result.UsageIssue != "" {
line += " // TELEMETRY " + result.UsageIssue
} else if !result.CostKnown && result.CostIssue != "" {
line += " // API EQ " + result.CostIssue
}
return line
}
func startUI(fetcher ui.Fetcher, refresh time.Duration, inline bool, resetThreshold, resetWarningHours int) error {
model := ui.New(fetcher, refresh)
if store, storeErr := ui.NewDefaultPreferenceStore(); storeErr == nil {
model = ui.NewWithPreferences(fetcher, refresh, store)
}
model.SetInline(inline)
model.SetResetThreshold(resetThreshold)
model.SetResetWarningHours(resetWarningHours)
finalModel, runErr := tea.NewProgram(model).Run()
if final, ok := finalModel.(ui.Model); ok {
final.CancelQuotaWork()
}
if controller, ok := fetcher.(interface{ CloseQuotaProfiles() }); ok {
controller.CloseQuotaProfiles()
}
return runErr
}