chompyy 0.4.7 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/README.md +40 -6
  2. package/dist/advice.js +2 -1
  3. package/dist/agentlimits.js +77 -0
  4. package/dist/agentusage.js +96 -0
  5. package/dist/appstate.js +72 -5
  6. package/dist/away.js +44 -5
  7. package/dist/blueprint.js +3 -7
  8. package/dist/board.js +4 -0
  9. package/dist/cli.js +328 -15
  10. package/dist/codexquota.js +106 -0
  11. package/dist/codexusage.js +10 -0
  12. package/dist/config.js +2 -0
  13. package/dist/context.js +30 -0
  14. package/dist/costs.js +1 -0
  15. package/dist/daytime.js +68 -0
  16. package/dist/demon.js +20 -0
  17. package/dist/didwork.js +46 -0
  18. package/dist/label.js +33 -0
  19. package/dist/learning.js +35 -0
  20. package/dist/menu.js +17 -0
  21. package/dist/nightcap.js +60 -0
  22. package/dist/nudge.js +47 -18
  23. package/dist/pacing.js +16 -1
  24. package/dist/questions.js +71 -0
  25. package/dist/recap.js +74 -0
  26. package/dist/receipt.js +48 -0
  27. package/dist/recipe.js +79 -0
  28. package/dist/send.js +46 -20
  29. package/dist/stamps.js +14 -0
  30. package/dist/taste.js +67 -7
  31. package/dist/triggers.js +5 -0
  32. package/dist/unkeep.js +220 -0
  33. package/dist/usage.js +21 -1
  34. package/dist/vendor/codeburn/antigravity.js +309 -0
  35. package/dist/vendor/codeburn/codex.js +429 -0
  36. package/dist/vendor/codeburn/copilot.js +292 -0
  37. package/dist/vendor/codeburn/gemini.js +195 -0
  38. package/dist/vendor/codeburn/grokbot.js +182 -0
  39. package/dist/vendor/codeburn/kimi.js +178 -0
  40. package/dist/vendor/codeburn/shims/chalk.js +14 -0
  41. package/dist/vendor/codeburn/shims/strip-ansi.js +6 -0
  42. package/dist/vendor/codeburn/src/act/backup.js +83 -0
  43. package/dist/vendor/codeburn/src/act/model-defaults.js +151 -0
  44. package/dist/vendor/codeburn/src/act/types.js +37 -0
  45. package/dist/vendor/codeburn/src/bash-utils.js +204 -0
  46. package/dist/vendor/codeburn/src/behavioral-weight.js +47 -0
  47. package/dist/vendor/codeburn/src/cache-dir.js +26 -0
  48. package/dist/vendor/codeburn/src/cache-refresh-lock.js +543 -0
  49. package/dist/vendor/codeburn/src/cache-sweep.js +67 -0
  50. package/dist/vendor/codeburn/src/classifier.js +209 -0
  51. package/dist/vendor/codeburn/src/claude-identity.js +223 -0
  52. package/dist/vendor/codeburn/src/codex-cache.js +377 -0
  53. package/dist/vendor/codeburn/src/codex-fork-replay.js +232 -0
  54. package/dist/vendor/codeburn/src/codex-jsonl-fields.js +99 -0
  55. package/dist/vendor/codeburn/src/codex-session-index.js +113 -0
  56. package/dist/vendor/codeburn/src/codex-throughput.js +544 -0
  57. package/dist/vendor/codeburn/src/compare-stats.js +405 -0
  58. package/dist/vendor/codeburn/src/config.js +145 -0
  59. package/dist/vendor/codeburn/src/content-utils.js +56 -0
  60. package/dist/vendor/codeburn/src/context-tree-codex.js +329 -0
  61. package/dist/vendor/codeburn/src/context-tree.js +664 -0
  62. package/dist/vendor/codeburn/src/copilot-aiu.js +16 -0
  63. package/dist/vendor/codeburn/src/currency.js +189 -0
  64. package/dist/vendor/codeburn/src/cursor-cache.js +238 -0
  65. package/dist/vendor/codeburn/src/cursor-import.js +402 -0
  66. package/dist/vendor/codeburn/src/cursor-sync.js +256 -0
  67. package/dist/vendor/codeburn/src/daily-cache.js +2036 -0
  68. package/dist/vendor/codeburn/src/data/litellm-snapshot.json +1 -0
  69. package/dist/vendor/codeburn/src/data/pricing-fallback.json +1 -0
  70. package/dist/vendor/codeburn/src/day-aggregator.js +327 -0
  71. package/dist/vendor/codeburn/src/editor-data-dir.js +11 -0
  72. package/dist/vendor/codeburn/src/fetch-utils.js +18 -0
  73. package/dist/vendor/codeburn/src/format.js +118 -0
  74. package/dist/vendor/codeburn/src/fs-utils.js +270 -0
  75. package/dist/vendor/codeburn/src/git-origin.js +334 -0
  76. package/dist/vendor/codeburn/src/granular-history.js +328 -0
  77. package/dist/vendor/codeburn/src/hermes-session-ledger.js +512 -0
  78. package/dist/vendor/codeburn/src/launcher-homes.js +142 -0
  79. package/dist/vendor/codeburn/src/live-sessions.js +358 -0
  80. package/dist/vendor/codeburn/src/math-utils.js +8 -0
  81. package/dist/vendor/codeburn/src/menubar-json.js +294 -0
  82. package/dist/vendor/codeburn/src/models.js +1879 -0
  83. package/dist/vendor/codeburn/src/optimize-one-hour-cache.js +92 -0
  84. package/dist/vendor/codeburn/src/optimize.js +4110 -0
  85. package/dist/vendor/codeburn/src/parse-workers.js +219 -0
  86. package/dist/vendor/codeburn/src/parser.js +6953 -0
  87. package/dist/vendor/codeburn/src/path-privacy.js +26 -0
  88. package/dist/vendor/codeburn/src/plans.js +135 -0
  89. package/dist/vendor/codeburn/src/pr-signals.js +132 -0
  90. package/dist/vendor/codeburn/src/project-filter-warnings.js +33 -0
  91. package/dist/vendor/codeburn/src/provider-issues.js +30 -0
  92. package/dist/vendor/codeburn/src/providers/amp.js +286 -0
  93. package/dist/vendor/codeburn/src/providers/antigravity.js +1731 -0
  94. package/dist/vendor/codeburn/src/providers/claude.js +551 -0
  95. package/dist/vendor/codeburn/src/providers/cline-cli.js +401 -0
  96. package/dist/vendor/codeburn/src/providers/cline.js +63 -0
  97. package/dist/vendor/codeburn/src/providers/codebuff.js +336 -0
  98. package/dist/vendor/codeburn/src/providers/codewhale.js +442 -0
  99. package/dist/vendor/codeburn/src/providers/codex.js +1720 -0
  100. package/dist/vendor/codeburn/src/providers/command-code.js +196 -0
  101. package/dist/vendor/codeburn/src/providers/copilot.js +3278 -0
  102. package/dist/vendor/codeburn/src/providers/crush.js +226 -0
  103. package/dist/vendor/codeburn/src/providers/cursor-agent.js +837 -0
  104. package/dist/vendor/codeburn/src/providers/cursor.js +1163 -0
  105. package/dist/vendor/codeburn/src/providers/devin.js +569 -0
  106. package/dist/vendor/codeburn/src/providers/droid.js +324 -0
  107. package/dist/vendor/codeburn/src/providers/dsh.js +690 -0
  108. package/dist/vendor/codeburn/src/providers/forge.js +245 -0
  109. package/dist/vendor/codeburn/src/providers/gemini.js +230 -0
  110. package/dist/vendor/codeburn/src/providers/goose.js +252 -0
  111. package/dist/vendor/codeburn/src/providers/grok.js +581 -0
  112. package/dist/vendor/codeburn/src/providers/grokbot.js +290 -0
  113. package/dist/vendor/codeburn/src/providers/hermes.js +771 -0
  114. package/dist/vendor/codeburn/src/providers/ibm-bob.js +53 -0
  115. package/dist/vendor/codeburn/src/providers/index.js +360 -0
  116. package/dist/vendor/codeburn/src/providers/kilo-code.js +50 -0
  117. package/dist/vendor/codeburn/src/providers/kimi.js +363 -0
  118. package/dist/vendor/codeburn/src/providers/kimicode.js +402 -0
  119. package/dist/vendor/codeburn/src/providers/kiro.js +1174 -0
  120. package/dist/vendor/codeburn/src/providers/lingtai-tui.js +372 -0
  121. package/dist/vendor/codeburn/src/providers/mistral-vibe-unified.js +236 -0
  122. package/dist/vendor/codeburn/src/providers/mistral-vibe.js +405 -0
  123. package/dist/vendor/codeburn/src/providers/mux.js +242 -0
  124. package/dist/vendor/codeburn/src/providers/open-design.js +217 -0
  125. package/dist/vendor/codeburn/src/providers/openclaude.js +309 -0
  126. package/dist/vendor/codeburn/src/providers/openclaw.js +442 -0
  127. package/dist/vendor/codeburn/src/providers/opencode-file-parser.js +131 -0
  128. package/dist/vendor/codeburn/src/providers/opencode.js +91 -0
  129. package/dist/vendor/codeburn/src/providers/pi.js +429 -0
  130. package/dist/vendor/codeburn/src/providers/quickdesk.js +491 -0
  131. package/dist/vendor/codeburn/src/providers/qwen.js +193 -0
  132. package/dist/vendor/codeburn/src/providers/session-message.js +118 -0
  133. package/dist/vendor/codeburn/src/providers/sqlite-session-parser.js +457 -0
  134. package/dist/vendor/codeburn/src/providers/types.js +5 -0
  135. package/dist/vendor/codeburn/src/providers/vercel-gateway.js +135 -0
  136. package/dist/vendor/codeburn/src/providers/vscode-cline-parser.js +212 -0
  137. package/dist/vendor/codeburn/src/providers/warp.js +575 -0
  138. package/dist/vendor/codeburn/src/providers/zcode.js +249 -0
  139. package/dist/vendor/codeburn/src/providers/zed.js +187 -0
  140. package/dist/vendor/codeburn/src/providers/zerostack.js +139 -0
  141. package/dist/vendor/codeburn/src/quota/antigravity.js +310 -0
  142. package/dist/vendor/codeburn/src/quota/claude.js +244 -0
  143. package/dist/vendor/codeburn/src/quota/cursor.js +301 -0
  144. package/dist/vendor/codeburn/src/quota/security.js +299 -0
  145. package/dist/vendor/codeburn/src/quota/types.js +1 -0
  146. package/dist/vendor/codeburn/src/scan-facts.js +99 -0
  147. package/dist/vendor/codeburn/src/session-cache.js +3040 -0
  148. package/dist/vendor/codeburn/src/session-count-label.js +14 -0
  149. package/dist/vendor/codeburn/src/session-output.js +139 -0
  150. package/dist/vendor/codeburn/src/session-population.js +30 -0
  151. package/dist/vendor/codeburn/src/sessions-report.js +1342 -0
  152. package/dist/vendor/codeburn/src/sqlite.js +528 -0
  153. package/dist/vendor/codeburn/src/sync/otlp.js +420 -0
  154. package/dist/vendor/codeburn/src/telemetry-snapshot.js +244 -0
  155. package/dist/vendor/codeburn/src/token-estimate.js +5 -0
  156. package/dist/vendor/codeburn/src/types.js +16 -0
  157. package/dist/vendor/codeburn/src/work-units.js +126 -0
  158. package/dist/vendor/codeburn/src/workflow-insights.js +228 -0
  159. package/dist/vendor/codeburn/src/wsl.js +198 -0
  160. package/dist/vendor/codeburn/src/yield.js +666 -0
  161. package/package.json +11 -3
package/dist/cli.js CHANGED
@@ -3,7 +3,7 @@
3
3
  import { execFileSync, spawn } from 'node:child_process';
4
4
  import { backfillTokens, median } from './tokenstore.js';
5
5
  import { compact, formatTokens, totalTokens } from './tokens.js';
6
- import { closeSync, existsSync, openSync, readFileSync } from 'node:fs';
6
+ import { closeSync, existsSync, openSync, readFileSync, writeFileSync } from 'node:fs';
7
7
  import { resolve } from 'node:path';
8
8
  import { parseArgs } from 'node:util';
9
9
  import { away, runCard } from './away.js';
@@ -17,12 +17,21 @@ import { formatDuration, parseDuration } from './duration.js';
17
17
  import { budgetGate } from './gate.js';
18
18
  import { chompyyHome, homePath } from './home.js';
19
19
  import { loadSnapshot, saveSnapshot, statuslineSnapshot, statusLineText, statusText as baseStatusText, windowView } from './quota.js';
20
- import { loadSamples } from './pacing.js';
20
+ import { loadSamples, pacing } from './pacing.js';
21
+ import { demonOffer } from './demon.js';
21
22
  import { cardsSince, formatReport, lastReportAt, markReported, morningLine, rateCard, readTaste, tasteCountLine } from './report.js';
22
23
  import { approvedText, changedFiles, diffCard, keepCard, overlaps, questionsOf, undoCard } from './review.js';
24
+ import { recipeOf } from './recipe.js';
23
25
  import { CappedText, ClaudeRunner, claudeAvailable } from './runner.js';
24
26
  import { branchOf, commitLeftovers, gitRoot, planWorkspace, prepareWorkspace } from './workspace.js';
25
- import { answerCard, appState, cardView, currentBranch, editBlueprint, editIdea, recordCliLocation } from './appstate.js';
27
+ import { answerCard, appState, cardView, currentBranch, editBlueprint, editIdea, nightcapNow, providersState, recordCliLocation, tasteState } from './appstate.js';
28
+ import { codexInstalled, refreshCodexQuota } from './codexquota.js';
29
+ import { refreshAgents } from './agentusage.js';
30
+ import { stampCard } from './stamps.js';
31
+ import { nutritionLabel } from './label.js';
32
+ import { recap, recapMonth } from './recap.js';
33
+ import { menuFrom } from './menu.js';
34
+ import { limitsState, READERS, refreshLimits } from './agentlimits.js';
26
35
  import { detect, detectText } from './detect.js';
27
36
  import { allWindowEnds, archiveWindowEnds, premise, premiseText } from './premise.js';
28
37
  import { keychainAllowed, loadLiveState, refreshLiveQuota } from './livequota.js';
@@ -32,22 +41,25 @@ import { buildDigest, historyRetention, scanHistory } from './history.js';
32
41
  import { acceptColdStart, forgetColdStart, formatColdStart, loadColdStart, runColdStart } from './coldstart.js';
33
42
  import { keepHistory } from './claudesettings.js';
34
43
  import { blueprintHash, drawPicture } from './picture.js';
44
+ import { receipt, receiptText } from './receipt.js';
35
45
  import { costRange, formatCostRange, readRuns, tasteEffect, tasteEffectLine, trendLines } from './costs.js';
36
- import { answerPreference, distill, distillDue, formatPrefs, formatQuestion, formatWhy, getPref, learnedCount, loadStore, nextQuestion, readSignals, recordOutcome, retirePreference, syncTasteFile, tasteChangesSince, } from './taste.js';
46
+ import { answerPreference, distill, distillDue, formatPrefs, formatQuestion, formatWhy, getPref, learnedCount, loadStore, nextQuestion, readSignals, recordOutcome, renderAgentsBlock, retirePreference, syncTasteFile, tasteChangesSince, tasteRulesForProject, } from './taste.js';
37
47
  import { cachedWorkspaces, dream, dreamDue, formatDream, formatWorkspaces, projectsDir, readLogPath, setTicked } from './dream.js';
38
- import { byKind, compare, formatExtras, formatUsage, loadLedger, periodDays, PERIODS, prCosts, usageView } from './usage.js';
48
+ import { byKind, compactTokens, compare, formatExtras, formatUsage, loadLedger, periodDays, PERIODS, prCosts, usageView } from './usage.js';
39
49
  import { formatTrace, traceSession } from './trace.js';
40
50
  import { homedir } from 'node:os';
41
51
  import { clashOf, refreshCard, refreshGate, refreshClashing, withRefreshLock } from './refresh.js';
42
52
  import { adviseText, applyDue, approveAdvice, runAdvise, undoAdvice } from './advice.js';
43
- import { checkWorked, nudgeProof, nudgeProofText, shareText, workedText } from './didwork.js';
53
+ import { daytimeFile, daytimeState, setDaytime } from './daytime.js';
54
+ import { checkWorked, nudgeProofText, savedSoFar, shareText, workedText } from './didwork.js';
44
55
  import { addSuggested, suggestTasks, suggestText } from './suggest.js';
45
56
  import { coldWarningText, hookCommand, impact, loadNudges, nudgeInstalled, nudgeText, runHook, setNudge, setProjectMode, takeGoingCold } from './nudge.js';
46
57
  import { withKeepLock } from './keeplock.js';
47
58
  import { sendKept } from './send.js';
59
+ import { planUnkeep, unkeep } from './unkeep.js';
48
60
  import { cacheText, composeLine, setStatusline, statuslineInstalled, statusLineOutput, wrappedCommand } from './statusline.js';
49
61
  import { formatLive, keepAffectsLive, liveOff, liveSet, liveUpdateLocked, loadLive, startLiveUpdate } from './live.js';
50
- import { agentInstalled, awayRunning, bedtimeKey, decideTrigger, installAgent, loadTriggerState, markFired, noteTick, parseClock, takeAwayLock, uninstallAgent } from './triggers.js';
62
+ import { agentInstalled, awayRunning, bedtimeKey, decideTrigger, installAgent, loadTriggerState, markFired, noteTick, parseClock, takeAwayLock, uninstallAgent, unmarkFired } from './triggers.js';
51
63
  import { exe } from './exe.js';
52
64
  const HELP = `chompyy: use the 5-hour window capacity that would reset unused
53
65
 
@@ -95,10 +107,13 @@ Away
95
107
  Back
96
108
  chompyy report [--all] what ran, and the one thing to do about each
97
109
  chompyy diff <id> the change it made
110
+ chompyy recipe <id> [--json] a kept card as a recipe: files, steps, when it landed
98
111
  chompyy keep <id> merge its branch into the branch it started from (and update the live app, if set)
99
112
  chompyy send [--json] open one PR on GitHub per kept card GitHub's main doesn't have yet
100
113
  chompyy refresh [<id>] bring cards in review up to date with main (Chompyy does this by itself after each Keep)
101
114
  chompyy undo <id> throw it away (removes its branch; yours are untouched)
115
+ a kept card: takes it back off your branch, or opens a revert PR on GitHub
116
+ (--plan says which, changing nothing; --json for the app)
102
117
  chompyy answer <id> answer the run's questions (stdin); the card goes back to approved
103
118
  chompyy redo <id> throw this attempt away and run it again from your latest code
104
119
  chompyy continue <id> ["note"] a done card did only part of the job: run another cycle that builds on it
@@ -122,11 +137,23 @@ Taste (learned from what you keep, undo, edit and rate)
122
137
  chompyy taste why <id> the cards, edits and quotes behind a preference
123
138
  chompyy taste yes|not-now|never <id> answer a question (yes writes it to taste.md)
124
139
  chompyy taste retire <id> stop using a preference (kept, with the reason)
140
+ chompyy taste agents <project> <file> copy Everywhere + <project> rules into a marked block in an AGENTS.md
141
+ chompyy taste daytime on|off your rules in every Claude Code session too (one import line in ~/.claude/CLAUDE.md)
125
142
  chompyy distill [--force] read new signals and update preferences now (one model call; runs after away too)
126
143
 
127
144
  Triggers (start away runs on their own; the budget gate still decides every card)
128
145
  chompyy triggers on|off install or remove the macOS LaunchAgent that runs \`chompyy tick\` every 5 minutes
129
146
  chompyy triggers what is set, and what the last tick decided
147
+ chompyy limits [<agent> on|off] limits for Gemini CLI, Copilot, Antigravity, Kimi Code, Grok Bot (off until you allow each)
148
+ chompyy recap [--month 2026-11] [--json] your month on one shareable card: tokens, busiest day, cards baked
149
+ chompyy menu [--json] every agent you used in 30 days as a café chalkboard: tokens and value, safe to share
150
+ chompyy label [--json] your week as Nutrition Facts: cached reads, cache writes, resent tokens, output; shareable
151
+ chompyy stamps [--json] your loyalty stamp card: one stamp per kept card, ten to a card; shareable
152
+ chompyy agents [--json] every other coding agent on this Mac (Cursor, Copilot, Gemini, …): tokens and value
153
+ chompyy codex [on|off] [--json] Codex's limits and tokens beside Claude's (on = read its login, never change it)
154
+ chompyy nightcap [on [23:30]|skip|unskip] tonight's bedtime run: turn it on, or skip tonight
155
+ chompyy demon [on|off] eat what's left of a window before it resets: run approved cards (on = every window)
156
+ chompyy receipt [--json] your week as a bake-sale receipt: cards baked, kept, burnt, tokens; safe to share
130
157
  chompyy bedtime <23:30|off> run approved cards at bedtime (with the window that is left)
131
158
  chompyy last-hour <on|off> run approved cards in the last hour before a 5-hour reset
132
159
  chompyy missed-reset <on|off> run approved cards on the first tick after a reset nothing used (default off)
@@ -486,9 +513,11 @@ async function main(argv) {
486
513
  share: { type: 'boolean' },
487
514
  quiet: { type: 'boolean' },
488
515
  model: { type: 'string' },
516
+ month: { type: 'string' },
489
517
  column: { type: 'string', multiple: true },
490
518
  help: { type: 'boolean', short: 'h' },
491
519
  json: { type: 'boolean' },
520
+ plan: { type: 'boolean' },
492
521
  refresh: { type: 'boolean' },
493
522
  'allow-keychain': { type: 'boolean' },
494
523
  'no-keychain': { type: 'boolean' },
@@ -514,6 +543,11 @@ async function main(argv) {
514
543
  recordCliLocation();
515
544
  /** Fresh quota before anything that reads it (at most every 5 minutes unless forced). */
516
545
  const freshQuota = async (force = false) => {
546
+ // Codex beside Claude, once you allowed it (read-only; never renews its login).
547
+ if (loadConfig().codexQuota && codexInstalled())
548
+ await refreshCodexQuota({ force }).catch(() => null);
549
+ // And the other agents whose limits you allowed (read-only, each at most every 5 minutes).
550
+ await refreshLimits(loadConfig().agentLimits ?? {}, { force }).catch(() => null);
517
551
  if (loadConfig().quotaSource !== 'api')
518
552
  return null;
519
553
  try {
@@ -570,6 +604,150 @@ async function main(argv) {
570
604
  console.log(statusText(loadSnapshot(), now));
571
605
  return;
572
606
  }
607
+ case 'limits': {
608
+ // Limits for Gemini CLI, Copilot, Antigravity, Kimi Code and Grok Bot: each off until you allow it.
609
+ const [name, sub] = args;
610
+ const config = loadConfig();
611
+ const allowed = { ...(config.agentLimits ?? {}) };
612
+ if (name && (sub === 'on' || sub === 'off')) {
613
+ const r = READERS.find((x) => x.name === name);
614
+ if (!r)
615
+ throw new Error(`No limits reader for "${name}". Agents with one: ${READERS.map((x) => x.name).join(', ')}.`);
616
+ allowed[name] = sub === 'on';
617
+ setConfig('agentLimits', allowed);
618
+ if (sub === 'off')
619
+ return console.log(`${r.displayName} limits off. Chompyy won't use ${r.login}.`);
620
+ const got = (await refreshLimits(allowed, { force: true }))[name];
621
+ if (!r.installed())
622
+ return console.log(`${r.displayName} limits on, once it's on this Mac.`);
623
+ return console.log(got?.primary ? `${r.displayName}: ${Math.round(100 - got.primary.usedPct)}% left (${got.primary.label}). Chompyy only reads ${r.login}.` : `${r.displayName} limits on, but: ${got?.note ?? got?.connection ?? 'nothing read yet'}`);
624
+ }
625
+ if (name || sub)
626
+ throw new Error('Usage: chompyy limits [<agent> on|off] [--json]');
627
+ await refreshLimits(allowed, { force: Boolean(values.refresh) });
628
+ const st = limitsState(allowed);
629
+ if (values.json)
630
+ return json(st);
631
+ const names = Object.keys(st);
632
+ if (!names.length)
633
+ return console.log('No agent with readable limits on this Mac (Gemini CLI, Copilot, Antigravity, Kimi Code, Grok Bot).');
634
+ for (const n of names) {
635
+ const a = st[n];
636
+ if (a.allowed !== true)
637
+ console.log(`${a.displayName}: off. Turn on (uses ${a.login}, read-only): chompyy limits ${n} on`);
638
+ else if (a.limit?.primary)
639
+ console.log(`${a.displayName}: ${Math.round(100 - a.limit.primary.usedPct)}% left (${a.limit.primary.label})${a.limit.plan ? ` · ${a.limit.plan}` : ''}`);
640
+ else
641
+ console.log(`${a.displayName}: ${a.limit?.note ?? a.limit?.connection ?? 'not read yet'}`);
642
+ }
643
+ return;
644
+ }
645
+ case 'recap': {
646
+ // The monthly recap: the month in numbers on one card, safe to share (no names).
647
+ const r = recap(loadLedger().rows, readRuns(), loadBoard().cards, recapMonth(now, values.month));
648
+ if (values.json)
649
+ return json(r);
650
+ if (!r.tokens)
651
+ return console.log(`Nothing to recap for ${r.label} yet.`);
652
+ console.log(`Your ${r.label} with Chompyy`);
653
+ console.log(` ${compactTokens(r.tokens)} tokens ($${r.costUsd.toFixed(2)} API value), about ${r.cookies.toLocaleString('en-US')} cookies`);
654
+ if (r.busiestDay)
655
+ console.log(` Busiest day: ${r.busiestDay.day} (${compactTokens(r.busiestDay.tokens)})`);
656
+ console.log(` ${r.conversations} conversations on ${r.activeDays} days · ${r.cardsBaked} cards baked, ${r.kept} kept`);
657
+ if (r.biggestBake)
658
+ console.log(` Biggest bake: ${compactTokens(r.biggestBake.tokens)} tokens in ${r.biggestBake.minutes} min`);
659
+ return;
660
+ }
661
+ case 'menu': {
662
+ // The chalkboard menu: every agent you used in the last 30 days, tokens and API value. Safe to share.
663
+ const agents = await refreshAgents({});
664
+ const view = usageView(loadLedger(), now, 30);
665
+ const top = view.byModel[0]?.model ?? null;
666
+ const m = menuFrom({ tokens: view.total.tokens, costUsd: view.total.costUsd, model: top }, agents.agents, now);
667
+ if (values.json)
668
+ return json(m);
669
+ if (!m.items.length)
670
+ return console.log('Nothing on the menu: no agent used in the last 30 days.');
671
+ console.log('CHOMPYY CAFÉ · last 30 days');
672
+ for (const i of m.items)
673
+ console.log(` ${i.name.padEnd(16, '.')} ${compactTokens(i.tokens).padStart(7)} · $${i.costUsd.toFixed(2)}`);
674
+ console.log(` ${'Total'.padEnd(16, '.')} ${compactTokens(m.total.tokens).padStart(7)} · $${m.total.costUsd.toFixed(2)}`);
675
+ if (m.special)
676
+ console.log(`Today's special: ${m.special}`);
677
+ return;
678
+ }
679
+ case 'label': {
680
+ // The nutrition label: the week's tokens as Nutrition Facts, safe to share (no names).
681
+ let resent = 0;
682
+ try {
683
+ resent = impact().thisWeek.tokens;
684
+ }
685
+ catch { }
686
+ const l = nutritionLabel(loadLedger().rows, resent, now);
687
+ if (values.json)
688
+ return json(l);
689
+ console.log(`Nutrition Facts · ${compactTokens(l.tokens)} tokens over ${l.servings} conversations`);
690
+ for (const x of l.lines)
691
+ console.log(` ${x.sub ? ' ' : ''}${x.name} (${x.kind})`.padEnd(38) + `${compactTokens(x.tokens).padStart(7)} ${x.pct}%`);
692
+ console.log(l.tip);
693
+ return;
694
+ }
695
+ case 'stamps': {
696
+ // The loyalty stamp card: one stamp per kept card, ten to a card. Safe to share (no titles).
697
+ const c = stampCard(loadBoard().cards);
698
+ if (values.json)
699
+ return json(c);
700
+ console.log(`Stamp card: ${'●'.repeat(c.stamps.length)}${'○'.repeat(c.full ? 0 : c.toGo)} (${c.stamps.length}/10)`);
701
+ console.log(c.full ? `Card full! That's ${c.fullCards} full card${c.fullCards === 1 ? '' : 's'}: ${c.kept} kept in all.` : `${c.toGo} more kept card${c.toGo === 1 ? '' : 's'} to fill it · ${c.fullCards} full so far, ${c.kept} kept in all.`);
702
+ return;
703
+ }
704
+ case 'agents': {
705
+ // Every other coding agent codeburn reads: tokens and API value this week and over 30 and 90 days.
706
+ const f = await refreshAgents({ force: Boolean(values.refresh) });
707
+ if (values.json)
708
+ return json(f);
709
+ if (!f.agents.length)
710
+ return console.log('No other agent used on this Mac in the last 90 days.');
711
+ const usd = (n) => `$${n.toFixed(2)}`;
712
+ for (const a of f.agents.slice(0, 5)) {
713
+ console.log(`${a.displayName}: ${compactTokens(a.week.tokens)} this week · ${compactTokens(a.month.tokens)} in 30 days · ${compactTokens(a.quarter.tokens)} in 90 days (${usd(a.quarter.costUsd)})`);
714
+ }
715
+ if (f.agents.length > 5)
716
+ console.log(`…and ${f.agents.length - 5} more: chompyy agents --json`);
717
+ return;
718
+ }
719
+ case 'codex': {
720
+ // The second provider: Codex's limits (read-only login).
721
+ const sub = args[0];
722
+ if (sub === 'on') {
723
+ setConfig('codexQuota', true);
724
+ const r = await refreshCodexQuota({ force: true });
725
+ return console.log(r.ok ? `Codex quota on. ${r.message} Chompyy only reads Codex's login; it never renews or changes it.` : `Codex quota on, but: ${r.message}`);
726
+ }
727
+ if (sub === 'off') {
728
+ setConfig('codexQuota', false);
729
+ return console.log("Codex quota off. Chompyy won't read Codex's login.");
730
+ }
731
+ if (sub)
732
+ throw new Error('Usage: chompyy codex [on|off] [--json]');
733
+ if (!codexInstalled())
734
+ return console.log('Codex isn\'t on this Mac (no ~/.codex).');
735
+ const config = loadConfig();
736
+ if (config.codexQuota)
737
+ await refreshCodexQuota({ force: Boolean(values.refresh) });
738
+ const p = providersState(config, now).codex;
739
+ if (values.json)
740
+ return json(p);
741
+ if (!config.codexQuota)
742
+ return console.log("Codex quota is off. Turn it on (reads Codex's saved login, never changes it): chompyy codex on");
743
+ if (!p.fiveHour.known)
744
+ return console.log(p.note ?? 'No Codex quota yet.');
745
+ const pct = (n) => `${Math.round(n)}%`;
746
+ console.log(`Codex${p.plan ? ` ${p.plan}` : ''}: 5h ${pct(p.fiveHour.leftPct)} left${p.sevenDay.known ? ` · week ${pct(p.sevenDay.usedPct)} used` : ''}`);
747
+ if (p.usage)
748
+ console.log(`Tokens: ${compactTokens(p.usage.today.tokens)} today ($${p.usage.today.costUsd.toFixed(2)}) · ${compactTokens(p.usage.week.tokens)} this week ($${p.usage.week.costUsd.toFixed(2)})`);
749
+ return;
750
+ }
573
751
  case 'state': {
574
752
  const refreshed = await freshQuota(Boolean(values.refresh));
575
753
  draftPending(now);
@@ -1060,6 +1238,71 @@ async function main(argv) {
1060
1238
  console.log(`last tick ${st.lastTickAt.slice(0, 16).replace('T', ' ')}: ${st.lastDecision ?? ''}`);
1061
1239
  return;
1062
1240
  }
1241
+ case 'nightcap': {
1242
+ // The evening offer in the panel: run approved cards at bedtime, or skip tonight.
1243
+ const sub = args[0];
1244
+ const now2 = now;
1245
+ if (sub === 'on') {
1246
+ const t = args[1] ?? loadConfig().bedtime ?? '23:30';
1247
+ parseClock(t);
1248
+ setConfig('bedtime', t);
1249
+ installAgent();
1250
+ return console.log(`🌙 Tonight at ${t}: approved cards run while you sleep.`);
1251
+ }
1252
+ const cap = nightcapNow(loadBoard(), loadConfig(), now2);
1253
+ if (sub === 'skip' || sub === 'not-tonight') {
1254
+ if (!cap)
1255
+ return console.log('Nothing planned for tonight.');
1256
+ markFired(cap.key, now2, 'skipped tonight from the panel');
1257
+ return console.log(cap.phase === 'offer' ? 'Not tonight. Ask again tomorrow evening.' : `Skipping tonight. Back tomorrow at ${cap.bedtime}.`);
1258
+ }
1259
+ if (sub === 'unskip') {
1260
+ if (!cap || cap.phase !== 'skipped')
1261
+ return console.log('Tonight is not skipped.');
1262
+ unmarkFired(cap.key);
1263
+ return console.log(`Back on: tonight at ${cap.bedtime}.`);
1264
+ }
1265
+ if (sub)
1266
+ throw new Error('Usage: chompyy nightcap [on [23:30]|skip|unskip]');
1267
+ if (values.json)
1268
+ return json(cap);
1269
+ if (!cap)
1270
+ return console.log('No nightcap now: it shows in the evening when cards are approved.');
1271
+ const line = { offer: `Leave it to me tonight? ${cap.cards} card(s) could run at ${cap.bedtime}: chompyy nightcap on ${cap.bedtime}`,
1272
+ armed: `Tonight at ${cap.bedtime}: ${cap.cards} card(s) run while you sleep. Skip: chompyy nightcap skip`,
1273
+ skipped: `Skipping tonight. Back on: chompyy nightcap unskip`, running: 'Running your cards. Sleep well.' }[cap.phase];
1274
+ return console.log(`🌙 ${line}`);
1275
+ }
1276
+ case 'demon': {
1277
+ // Demon mode: run approved cards in the last hour of a window that would otherwise reset unused.
1278
+ const sub = args[0];
1279
+ if (sub === 'on') {
1280
+ setConfig('lastHourTrigger', true);
1281
+ installAgent();
1282
+ return console.log(`😈 Demon mode on: in the last hour before a reset, Chompyy eats what's left (with ≥${loadConfig().lastHourMinLeftPct}% left).`);
1283
+ }
1284
+ if (sub === 'off') {
1285
+ setConfig('lastHourTrigger', false);
1286
+ const c = loadConfig();
1287
+ if (!c.bedtime && !c.missedReset)
1288
+ uninstallAgent();
1289
+ return console.log('Demon mode off. Leftover windows just reset.');
1290
+ }
1291
+ if (sub)
1292
+ throw new Error('Usage: chompyy demon [on|off]');
1293
+ await freshQuota();
1294
+ const snap = loadSnapshot();
1295
+ const config = loadConfig();
1296
+ const offer = demonOffer(windowView(snap?.fiveHour, now), pacing(snap, loadSamples(), now, config.bedtime).fiveHourForecast, loadBoard().cards.filter((c) => c.column === 'approved').length, awayRunning() !== null);
1297
+ const auto = config.lastHourTrigger && agentInstalled();
1298
+ if (values.json)
1299
+ return json({ offer, auto });
1300
+ console.log(offer
1301
+ ? `😈 ~${offer.unusedPct}% of this window resets unused. Eat it: chompyy away ${offer.duration} (${offer.cards} card${offer.cards === 1 ? '' : 's'} ready).`
1302
+ : 'Nothing to eat right now: Chompyy offers in the last 90 minutes when 20% or more would go unused and a card is approved.');
1303
+ console.log(`Every window: ${auto ? 'on' : 'off (chompyy demon on)'}`);
1304
+ return;
1305
+ }
1063
1306
  case 'bedtime': {
1064
1307
  const v = need(args[0], 'chompyy bedtime <23:30|off>');
1065
1308
  if (v === 'off') {
@@ -1181,10 +1424,23 @@ async function main(argv) {
1181
1424
  return json({ added: res.added.map((c) => c.id), updated: res.updated.map((c) => c.id), skipped: res.skipped });
1182
1425
  return console.log(adviseText(res));
1183
1426
  }
1427
+ case 'receipt': {
1428
+ // The Sunday bake-sale receipt: the week in counts, tokens and dollars, safe to share (no names).
1429
+ let resent = null;
1430
+ try {
1431
+ const i = impact();
1432
+ resent = { thisWeek: i.thisWeek.tokens, lastWeek: i.lastWeek.tokens };
1433
+ }
1434
+ catch { }
1435
+ const r = receipt(readRuns(), loadBoard().cards, resent, now);
1436
+ if (values.json)
1437
+ return json(r);
1438
+ return console.log(receiptText(r));
1439
+ }
1184
1440
  case 'worked': {
1185
1441
  // The detective, step 5: each applied/tried advice card against the check it registered (didwork.ts).
1186
1442
  const cards = updateBoard((b) => checkWorked(b, now));
1187
- const proof = nudgeInstalled() || loadNudges().length ? nudgeProof(now) : null;
1443
+ const { proof, total } = savedSoFar(cards, now, { on: nudgeInstalled() || loadNudges().length > 0 });
1188
1444
  if (values.share) {
1189
1445
  // A summary to paste on the tester issue: counts, tokens and dates; no project, skill or file names.
1190
1446
  const text = shareText(cards, proof, { version: cliVersion(), now });
@@ -1193,10 +1449,11 @@ async function main(argv) {
1193
1449
  return console.log(`${text}\n\nNo project, skill or file names in it. Copy it: chompyy worked --share | pbcopy`);
1194
1450
  }
1195
1451
  if (values.json)
1196
- return json({ cards: cards.map((c) => ({ id: c.id, title: c.title, rule: c.advice.rule, lane: c.advice.lane, ...c.advice.result })), nudge: proof });
1452
+ return json({ cards: cards.map((c) => ({ id: c.id, title: c.title, rule: c.advice.rule, lane: c.advice.lane, ...c.advice.result })), nudge: proof, total });
1453
+ const sum = total ? ['', total.line] : [];
1197
1454
  if (!cards.length && proof)
1198
- return console.log(nudgeProofText(proof).join('\n'));
1199
- return console.log([workedText(cards, { all: Boolean(values.all) }), ...(proof ? ['', ...nudgeProofText(proof)] : [])].join('\n'));
1455
+ return console.log([...nudgeProofText(proof), ...sum].join('\n'));
1456
+ return console.log([workedText(cards, { all: Boolean(values.all) }), ...(proof ? ['', ...nudgeProofText(proof)] : []), ...sum].join('\n'));
1200
1457
  }
1201
1458
  case 'suggest': {
1202
1459
  // A few tasks for a repo, from what it wants to become and what its code shows: suggested cards to approve.
@@ -1245,9 +1502,10 @@ async function main(argv) {
1245
1502
  }
1246
1503
  if (values.json) {
1247
1504
  // The menu panel: the trend line, plus did the nudge work (its verdict, from the day it was turned on).
1505
+ // Plus the running total: what was counted (stops, re-counted fixes), from the results `worked` last wrote.
1248
1506
  const i = impact();
1249
- const p = i.on ? nudgeProof(now) : null;
1250
- return json({ ...i, ...(p ? { verdict: { verdict: p.result.verdict, line: p.result.line, dueAt: p.result.dueAt } } : {}) });
1507
+ const { proof: p, total } = savedSoFar(loadBoard().cards, now, { on: i.on });
1508
+ return json({ ...i, ...(p ? { verdict: { verdict: p.result.verdict, line: p.result.line, dueAt: p.result.dueAt } } : {}), ...(total ? { total: { tokens: total.tokens, since: total.since, line: total.line } } : {}) });
1251
1509
  }
1252
1510
  return console.log([nudgeText(nudgeInstalled()), impact().line].join('\n'));
1253
1511
  }
@@ -1266,6 +1524,7 @@ async function main(argv) {
1266
1524
  const lines = trendLines(runs, signals, now);
1267
1525
  console.log(lines.length ? lines.join('\n') : 'Not enough runs yet for trends (needs 3).');
1268
1526
  console.log(tasteEffectLine(tasteEffect(runs, signals)));
1527
+ console.log(tasteState(now).learning.line);
1269
1528
  return;
1270
1529
  }
1271
1530
  case 'report': {
@@ -1283,6 +1542,15 @@ async function main(argv) {
1283
1542
  markReported(now);
1284
1543
  return;
1285
1544
  }
1545
+ case 'recipe': {
1546
+ // A kept card as a recipe (the app's recipe card): ingredients, steps, when it was served.
1547
+ const card = getCard(loadBoard(), need(args[0], 'chompyy recipe <id>'));
1548
+ const r = recipeOf(card);
1549
+ if (values.json)
1550
+ return json(r);
1551
+ console.log([`Ingredients: ${r.ingredients.join(', ') || 'none found'}`, ...r.steps.map((s, i) => `${i + 1}. ${s}`)].join('\n'));
1552
+ return;
1553
+ }
1286
1554
  case 'diff': {
1287
1555
  console.log(diffCard(getCard(loadBoard(), need(args[0], 'chompyy diff <id>'))));
1288
1556
  return;
@@ -1311,7 +1579,7 @@ async function main(argv) {
1311
1579
  case 'send': {
1312
1580
  // Kept cards live on your local main only; this opens (or updates) one PR per card. Main itself is never pushed.
1313
1581
  const sent = sendKept(loadBoard().cards);
1314
- console.log(args.includes('--json') ? JSON.stringify(sent) : sent.message);
1582
+ console.log(values.json ? JSON.stringify(sent) : sent.message);
1315
1583
  return;
1316
1584
  }
1317
1585
  case 'refresh': {
@@ -1333,6 +1601,23 @@ async function main(argv) {
1333
1601
  const undone = getCard(loadBoard(), id);
1334
1602
  if (undone.advice && undone.advice.lane !== 'work')
1335
1603
  return console.log(updateBoard((b) => undoAdvice(getCard(b, id), now)));
1604
+ if (undone.outcome === 'kept') {
1605
+ // Undo after Keep: off your branch, or a revert PR on GitHub once it's there (unkeep.ts). It moves the
1606
+ // branch Keep lands on, so it waits in line with Keeps.
1607
+ if (values.plan)
1608
+ return console.log(planUnkeep(undone).line);
1609
+ const r = withKeepLock(() => unkeep(undone));
1610
+ console.log(values.json ? JSON.stringify({ message: r.message, url: r.url }) : r.message);
1611
+ updateBoard((b) => {
1612
+ const card = getCard(b, id);
1613
+ card.outcome = 'undone';
1614
+ card.unkept = { at: now.toISOString(), ...r.unkept };
1615
+ card.updatedAt = now.toISOString();
1616
+ recordOutcome(card, 'undone', now);
1617
+ return card;
1618
+ });
1619
+ return;
1620
+ }
1336
1621
  const files = changedFiles(undone); // read before Undo removes the branch
1337
1622
  console.log(undoCard(undone));
1338
1623
  updateBoard((b) => {
@@ -1361,6 +1646,7 @@ async function main(argv) {
1361
1646
  c.updatedAt = c.approvedAt;
1362
1647
  delete c.run;
1363
1648
  delete c.outcome;
1649
+ delete c.unkept;
1364
1650
  return c;
1365
1651
  });
1366
1652
  console.log(`🔁 #${card.id} back in approved; it runs again from your latest code on the next away run.`);
@@ -1406,8 +1692,35 @@ async function main(argv) {
1406
1692
  const p = retirePreference(need(args[1], 'chompyy taste retire <id>'), now);
1407
1693
  return console.log(`Retired ${p.id}: "${p.text}". It's kept in \`chompyy taste list\` with the reason.`);
1408
1694
  }
1695
+ if (sub === 'agents') {
1696
+ const usage = 'chompyy taste agents <project> <file>';
1697
+ const project = need(args[1], usage);
1698
+ const file = resolve(need(args[2], usage));
1699
+ const rules = tasteRulesForProject(project);
1700
+ if (!rules)
1701
+ throw new Error(`Add a rule under "## Everywhere" or "## ${project}" in taste.md first: no rules to copy. Nothing changed.`);
1702
+ const before = existsSync(file) ? readFileSync(file, 'utf8') : '';
1703
+ const after = renderAgentsBlock(before, rules);
1704
+ if (after === before)
1705
+ return console.log(`Nothing to do: ${file} already has these rules.`);
1706
+ writeFileSync(file, after);
1707
+ const n = rules.split('\n').filter((l) => !l.startsWith('## ') && l.trim()).length;
1708
+ return console.log(`Wrote ${n} rule${n === 1 ? '' : 's'} for ${project} to ${file}. Text outside the chompyy:taste block is unchanged.`);
1709
+ }
1710
+ if (sub === 'daytime') {
1711
+ const how = args[1];
1712
+ if (how === 'on' || how === 'off') {
1713
+ if (how === 'on')
1714
+ syncTasteFile(now);
1715
+ return console.log(setDaytime(how === 'on'));
1716
+ }
1717
+ if (how)
1718
+ throw new Error('Usage: chompyy taste daytime [on|off]');
1719
+ const st = daytimeState();
1720
+ return console.log(st.on ? `On: Claude Code loads your rules from ${daytimeFile()} at every session start. Turn off: chompyy taste daytime off` : 'Off: only away runs use your taste. Turn on: chompyy taste daytime on');
1721
+ }
1409
1722
  if (sub)
1410
- throw new Error('Usage: chompyy taste [list | why <id> | yes|not-now|never <id> | retire <id>]');
1723
+ throw new Error('Usage: chompyy taste [list | why <id> | yes|not-now|never <id> | retire <id> | agents <project> <file> | daytime [on|off]]');
1411
1724
  const { path, text, created } = readTaste();
1412
1725
  if (created)
1413
1726
  console.log(`(created ${path})\n`);
@@ -0,0 +1,106 @@
1
+ // Codex, the second provider (after Claude): its 5-hour and weekly limits from OpenAI's usage endpoint, via codeburn's
2
+ // reader (src/vendor/codeburn/codex.ts), and its tokens from codeburn's Codex session parser (src/codexusage.ts).
3
+ //
4
+ // Read-only on purpose. codeburn renews Codex's login when it's old or rejected and writes the new one back to
5
+ // ~/.codex/auth.json; a renewal that goes wrong signs you out of Codex. Chompyy never does that: every request to
6
+ // OpenAI's sign-in server is refused before it leaves the Mac, so the saved login is only ever read. When it has
7
+ // expired, opening Codex once renews it.
8
+ import { existsSync } from 'node:fs';
9
+ import { homedir } from 'node:os';
10
+ import { join } from 'node:path';
11
+ import { fetchCodexQuota } from './vendor/codeburn/codex.js';
12
+ import { readSecureFile } from './vendor/codeburn/security.js';
13
+ import { homePath, readJson, writeJson } from './home.js';
14
+ import { codexUsage } from './codexusage.js';
15
+ /** Don't ask OpenAI more often than this. */
16
+ export const CODEX_MIN_INTERVAL_MS = 5 * 60_000;
17
+ const SIGN_IN_HOST = 'https://auth.openai.com';
18
+ const statePath = () => homePath('codex-quota.json');
19
+ export const loadCodexState = () => readJson(statePath(), {});
20
+ /** Codex is on this Mac: it keeps its login and sessions in ~/.codex. */
21
+ export function codexInstalled(home = homedir()) {
22
+ return existsSync(join(home, '.codex'));
23
+ }
24
+ /** fetch that refuses OpenAI's sign-in server, so codeburn's renewal never runs and the login on disk stays as it is. */
25
+ export function readOnlyFetch(real = globalThis.fetch) {
26
+ return ((input, init) => {
27
+ const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
28
+ if (url.startsWith(SIGN_IN_HOST))
29
+ return Promise.resolve(new Response(null, { status: 403, statusText: 'Chompyy never renews the Codex login' }));
30
+ return real(input, init);
31
+ });
32
+ }
33
+ /**
34
+ * Codex's login file as codeburn should see it. Older Codex versions wrote ChatGPT sign-ins without `auth_mode`;
35
+ * codeburn then takes them for an API key and gives up. A file with ChatGPT tokens is a ChatGPT sign-in. In memory
36
+ * only: the file itself is never changed.
37
+ */
38
+ export async function readCodexAuth(path, maxBytes) {
39
+ const raw = await readSecureFile(path, maxBytes);
40
+ if (!raw)
41
+ return raw;
42
+ try {
43
+ const doc = JSON.parse(raw);
44
+ if (!doc.auth_mode && doc.tokens?.access_token)
45
+ return JSON.stringify({ ...doc, auth_mode: 'chatgpt' });
46
+ }
47
+ catch { }
48
+ return raw;
49
+ }
50
+ function windowFrom(p, label) {
51
+ const row = p.details.find((d) => d.label === label);
52
+ if (!row || !row.resetsAt)
53
+ return undefined;
54
+ return { usedPct: Math.round(row.percent * 1000) / 10, resetsAt: Math.floor(Date.parse(row.resetsAt) / 1000) };
55
+ }
56
+ /** Ask OpenAI for Codex's limits and recount its tokens, at most every 5 minutes unless forced. */
57
+ export async function refreshCodexQuota(opts = {}) {
58
+ const now = opts.now ?? new Date();
59
+ const state = loadCodexState();
60
+ if (state.retryAfterAt && Date.parse(state.retryAfterAt) > now.getTime())
61
+ return { ok: false, message: 'OpenAI limits how often Codex quota can be checked. Try again later.' };
62
+ if (!opts.force && state.lastTryAt && now.getTime() - Date.parse(state.lastTryAt) < CODEX_MIN_INTERVAL_MS)
63
+ return { ok: true, message: 'Fresh enough.' };
64
+ const fetchQuota = opts.fetchQuota ?? (() => fetchCodexQuota({ fetch: readOnlyFetch(), readFile: readCodexAuth, allowKeychain: false }));
65
+ const result = await fetchQuota();
66
+ const p = result.quota;
67
+ const next = { ...state, lastTryAt: now.toISOString(), connection: p.connection, plan: p.planLabel };
68
+ delete next.retryAfterAt;
69
+ try {
70
+ next.usage = await (opts.usage ?? codexUsage)(now);
71
+ }
72
+ catch { }
73
+ if (result.retryAfterSeconds)
74
+ next.retryAfterAt = new Date(now.getTime() + result.retryAfterSeconds * 1000).toISOString();
75
+ if (p.connection === 'connected') {
76
+ const five = windowFrom(p, '5-hour');
77
+ const week = windowFrom(p, 'Weekly');
78
+ if (five)
79
+ next.fiveHour = five;
80
+ else
81
+ delete next.fiveHour;
82
+ if (week)
83
+ next.sevenDay = week;
84
+ else
85
+ delete next.sevenDay;
86
+ next.capturedAt = now.toISOString();
87
+ delete next.note;
88
+ writeJson(statePath(), next);
89
+ return { ok: true, message: `Updated from OpenAI${p.planLabel ? ` (Codex ${p.planLabel})` : ''}.` };
90
+ }
91
+ next.note = explainCodex(p);
92
+ writeJson(statePath(), next);
93
+ return { ok: false, message: next.note };
94
+ }
95
+ export function explainCodex(p) {
96
+ switch (p.connection) {
97
+ case 'disconnected':
98
+ return 'No Codex login found. Sign in to Codex once, then try again.';
99
+ case 'transientFailure':
100
+ return "Couldn't read Codex's limits right now. If it keeps failing, open Codex once so it renews its login.";
101
+ case 'terminalFailure':
102
+ return 'OpenAI refused the request. Codex quota works with a ChatGPT sign-in, not an API key.';
103
+ default:
104
+ return "Couldn't reach OpenAI right now.";
105
+ }
106
+ }
@@ -0,0 +1,10 @@
1
+ // Codex tokens and their API value, read by codeburn's own Codex session parser (via agentusage.ts, which reads
2
+ // every agent the same way).
3
+ import { prepareCodeburn, usageFor } from './agentusage.js';
4
+ import { codex } from './vendor/codeburn/src/providers/codex.js';
5
+ export { callTokens } from './agentusage.js';
6
+ export async function codexUsage(now, provider = codex) {
7
+ await prepareCodeburn();
8
+ const { today, week, models } = await usageFor(provider, now);
9
+ return { today, week, models };
10
+ }
package/dist/config.js CHANGED
@@ -66,6 +66,8 @@ export const DEFAULT_CONFIG = {
66
66
  suggestedExpiryDays: 14,
67
67
  quotaSource: 'api',
68
68
  allowKeychain: null,
69
+ codexQuota: null,
70
+ agentLimits: {},
69
71
  extraArgs: [],
70
72
  distillModel: 'sonnet',
71
73
  distillAfterAway: true,