chompyy 0.5.0 → 0.7.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 (162) hide show
  1. package/README.md +14 -1
  2. package/dist/advice.js +98 -1
  3. package/dist/agentlimits.js +77 -0
  4. package/dist/agentusage.js +96 -0
  5. package/dist/approvals.js +129 -0
  6. package/dist/appstate.js +73 -3
  7. package/dist/away.js +48 -5
  8. package/dist/blueprint.js +3 -7
  9. package/dist/board.js +1 -0
  10. package/dist/cli.js +343 -18
  11. package/dist/codexquota.js +106 -0
  12. package/dist/codexusage.js +10 -0
  13. package/dist/config.js +2 -0
  14. package/dist/context.js +30 -0
  15. package/dist/costs.js +41 -2
  16. package/dist/demon.js +20 -0
  17. package/dist/detect.js +38 -6
  18. package/dist/didwork.js +26 -0
  19. package/dist/label.js +33 -0
  20. package/dist/menu.js +17 -0
  21. package/dist/nightcap.js +72 -0
  22. package/dist/nudge.js +70 -24
  23. package/dist/pacing.js +16 -1
  24. package/dist/punchcard.js +39 -0
  25. package/dist/questions.js +71 -0
  26. package/dist/recap.js +74 -0
  27. package/dist/receipt.js +48 -0
  28. package/dist/recipe.js +79 -0
  29. package/dist/savings.js +111 -0
  30. package/dist/stamps.js +14 -0
  31. package/dist/suggest.js +15 -5
  32. package/dist/triggers.js +5 -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 +6955 -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/dist/wastechecks.js +233 -0
  162. package/package.json +1 -1
@@ -0,0 +1,26 @@
1
+ // @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
2
+ import { homedir } from 'node:os';
3
+ import { posix, win32 } from 'node:path';
4
+ function normalizedPath(value) {
5
+ return value.trim().replace(/\\/g, '/').replace(/\/+$/, '');
6
+ }
7
+ /** Provider-owned container roots are not host workspaces, even when absolute. */
8
+ function isProviderContainerWorkingDirectory(value) {
9
+ return /^\/sessions\/[^/]+$/i.test(normalizedPath(value));
10
+ }
11
+ /** True when an absolute path identifies a user home root, not a project. */
12
+ export function isUserHomeRoot(value) {
13
+ if (!value)
14
+ return false;
15
+ const normalized = normalizedPath(value);
16
+ if (normalized.toLowerCase() === normalizedPath(homedir()).toLowerCase())
17
+ return true;
18
+ return /(?:^|\/)(?:users|home|profiles)\/[^/]+$/i.test(normalized)
19
+ || normalized === '/root';
20
+ }
21
+ /** Absolute, non-home provider cwd eligible for outbound provenance. */
22
+ export function isTrustedAbsoluteWorkingDirectory(value) {
23
+ if (!value || isUserHomeRoot(value) || isProviderContainerWorkingDirectory(value))
24
+ return false;
25
+ return posix.isAbsolute(value) || win32.isAbsolute(value);
26
+ }
@@ -0,0 +1,135 @@
1
+ import { AI_CREDIT_USD } from './copilot-aiu.js';
2
+ export const PLAN_PROVIDERS = ['all', 'claude', 'codex', 'cursor', 'grok', 'copilot', 'antigravity'];
3
+ export const PLAN_IDS = ['claude-pro', 'claude-max', 'claude-max-5x', 'cursor-pro', 'supergrok', 'supergrok-heavy', 'copilot-pro', 'copilot-pro-plus', 'copilot-max', 'google-ai-pro', 'google-ai-ultra-5x', 'google-ai-ultra-20x', 'custom', 'none'];
4
+ // Official Copilot individual allotments from GitHub Docs, *Usage-based
5
+ // billing for individuals*, fetched 2026-08-23. Flex is documented as
6
+ // variable — pin this table, do not invent a later flex number.
7
+ // https://docs.github.com/copilot/concepts/billing/usage-based-billing-for-individuals
8
+ // monthlyUsd is credits × $0.01 (the budget equivalent), not the sticker price.
9
+ const COPILOT_PRO_CREDITS = 1500;
10
+ const COPILOT_PRO_PLUS_CREDITS = 7000;
11
+ const COPILOT_MAX_CREDITS = 20000;
12
+ export const PRESET_PLANS = {
13
+ 'claude-pro': {
14
+ id: 'claude-pro',
15
+ monthlyUsd: 20,
16
+ provider: 'claude',
17
+ resetDay: 1,
18
+ },
19
+ 'claude-max': {
20
+ id: 'claude-max',
21
+ monthlyUsd: 200,
22
+ provider: 'claude',
23
+ resetDay: 1,
24
+ },
25
+ 'claude-max-5x': {
26
+ id: 'claude-max-5x',
27
+ monthlyUsd: 100,
28
+ provider: 'claude',
29
+ resetDay: 1,
30
+ },
31
+ 'cursor-pro': {
32
+ id: 'cursor-pro',
33
+ monthlyUsd: 20,
34
+ provider: 'cursor',
35
+ resetDay: 1,
36
+ },
37
+ 'supergrok': {
38
+ id: 'supergrok',
39
+ monthlyUsd: 30,
40
+ provider: 'grok',
41
+ resetDay: 1,
42
+ },
43
+ 'supergrok-heavy': {
44
+ id: 'supergrok-heavy',
45
+ monthlyUsd: 300,
46
+ provider: 'grok',
47
+ resetDay: 1,
48
+ },
49
+ 'copilot-pro': {
50
+ id: 'copilot-pro',
51
+ monthlyCredits: COPILOT_PRO_CREDITS,
52
+ monthlyUsd: COPILOT_PRO_CREDITS * AI_CREDIT_USD,
53
+ provider: 'copilot',
54
+ resetDay: 1,
55
+ },
56
+ 'copilot-pro-plus': {
57
+ id: 'copilot-pro-plus',
58
+ monthlyCredits: COPILOT_PRO_PLUS_CREDITS,
59
+ monthlyUsd: COPILOT_PRO_PLUS_CREDITS * AI_CREDIT_USD,
60
+ provider: 'copilot',
61
+ resetDay: 1,
62
+ },
63
+ 'copilot-max': {
64
+ id: 'copilot-max',
65
+ monthlyCredits: COPILOT_MAX_CREDITS,
66
+ monthlyUsd: COPILOT_MAX_CREDITS * AI_CREDIT_USD,
67
+ provider: 'copilot',
68
+ resetDay: 1,
69
+ },
70
+ // US monthly prices from https://gemini.google/us/subscriptions/, fetched
71
+ // 2026-10-07. Antigravity is the only local tool these plans cover since
72
+ // Google retired Gemini CLI OAuth for individual tiers.
73
+ 'google-ai-pro': {
74
+ id: 'google-ai-pro',
75
+ monthlyUsd: 19.99,
76
+ provider: 'antigravity',
77
+ resetDay: 1,
78
+ },
79
+ 'google-ai-ultra-5x': {
80
+ id: 'google-ai-ultra-5x',
81
+ monthlyUsd: 99.99,
82
+ provider: 'antigravity',
83
+ resetDay: 1,
84
+ },
85
+ 'google-ai-ultra-20x': {
86
+ id: 'google-ai-ultra-20x',
87
+ monthlyUsd: 199.99,
88
+ provider: 'antigravity',
89
+ resetDay: 1,
90
+ },
91
+ };
92
+ export function isPlanProvider(value) {
93
+ return PLAN_PROVIDERS.includes(value);
94
+ }
95
+ export function isPlanId(value) {
96
+ return PLAN_IDS.includes(value);
97
+ }
98
+ export function getPresetPlan(id) {
99
+ if (id in PRESET_PLANS) {
100
+ return PRESET_PLANS[id];
101
+ }
102
+ return null;
103
+ }
104
+ export function planDisplayName(id) {
105
+ switch (id) {
106
+ case 'claude-pro':
107
+ return 'Claude Pro';
108
+ case 'claude-max':
109
+ return 'Claude Max 20x';
110
+ case 'claude-max-5x':
111
+ return 'Claude Max 5x';
112
+ case 'cursor-pro':
113
+ return 'Cursor Pro';
114
+ case 'supergrok':
115
+ return 'SuperGrok';
116
+ case 'supergrok-heavy':
117
+ return 'SuperGrok Heavy';
118
+ case 'copilot-pro':
119
+ return 'Copilot Pro';
120
+ case 'copilot-pro-plus':
121
+ return 'Copilot Pro+';
122
+ case 'copilot-max':
123
+ return 'Copilot Max';
124
+ case 'google-ai-pro':
125
+ return 'Google AI Pro';
126
+ case 'google-ai-ultra-5x':
127
+ return 'Google AI Ultra 5x';
128
+ case 'google-ai-ultra-20x':
129
+ return 'Google AI Ultra 20x';
130
+ case 'custom':
131
+ return 'Custom';
132
+ case 'none':
133
+ return 'None';
134
+ }
135
+ }
@@ -0,0 +1,132 @@
1
+ // @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
2
+ // Local PR signals read from cached Bash commands and subagent descriptions.
3
+ // Only a command is cached, never its result, so a failed push or merge still
4
+ // counts.
5
+ // A description names its PR with a `PR` prefix or a /pull/N URL. A bare `#22`
6
+ // is too often an issue, a worker number, or the PR a fix grew out of.
7
+ const NAMED_PR_RE = /\bPR\s*#?(\d{1,6})\b|github\.com\/([^/\s]+)\/([^/\s]+)\/pull\/(\d+)/g;
8
+ /// The single PR a subagent description names, 'multi' when it names more
9
+ /// than one (or lists "PRs 1689-1692"), null when it names none.
10
+ export function namedPr(text) {
11
+ if (/\bPRs\s*#?\d/.test(text))
12
+ return 'multi';
13
+ const numbers = new Set();
14
+ let repo;
15
+ for (const m of text.matchAll(NAMED_PR_RE)) {
16
+ numbers.add(Number(m[1] ?? m[4]));
17
+ if (m[2])
18
+ repo = `${m[2]}/${m[3]}`;
19
+ }
20
+ if (numbers.size > 1)
21
+ return 'multi';
22
+ const [number] = numbers;
23
+ return number === undefined ? null : { number, ...(repo ? { repo } : {}) };
24
+ }
25
+ export function namedPrNumber(text) {
26
+ const n = namedPr(text);
27
+ return n && n !== 'multi' ? n.number : null;
28
+ }
29
+ // Command position only: `gh`/`git` inside a quoted string (a script or test
30
+ // being written) is not a command that ran.
31
+ const AT_CMD = String.raw `(?:^|[\s;&|(\`])`;
32
+ const GIT = String.raw `${AT_CMD}git(?:\s+-[Cc]\s+\S+)*\s+`;
33
+ const PUSH_RE = new RegExp(`${GIT}push\\b([^|;&\\n]*)`, 'g');
34
+ const COMMIT_RE = new RegExp(`${GIT}commit\\b`);
35
+ const GIT_DIFF_RE = new RegExp(`${GIT}diff\\b`);
36
+ const GH_PR_RE = new RegExp(String.raw `${AT_CMD}gh\s+pr\s+([a-z-]+)([^|;&\n]*)`, 'g');
37
+ const PR_ARG_VERBS = new Set(['view', 'diff', 'checkout', 'checks', 'merge', 'review', 'edit', 'comment', 'close', 'reopen', 'ready']);
38
+ const READ_VERBS = new Set(['view', 'diff', 'checkout', 'review']);
39
+ const PR_URL_RE = /github\.com\/([^/\s]+)\/([^/\s]+)\/pull\/(\d+)/;
40
+ const API_PR_RE = /\/pulls?\/(\d+)\b/g;
41
+ const unquote = (s) => s.replace(/"[^"]*"|'[^']*'/g, ' ');
42
+ export const isPush = (cmd) => pushes(cmd).length > 0;
43
+ export const isCommit = (cmd) => cmd.includes('commit') && COMMIT_RE.test(cmd);
44
+ export const readsCode = (cmd) => (cmd.includes('diff') && GIT_DIFF_RE.test(cmd)) || ghPrCommands(cmd).some(c => READ_VERBS.has(c.verb));
45
+ /// Each `git push` in a command line with the branches it names (the refspec
46
+ /// destination, `HEAD:fix/x` -> `fix/x`); [] for a bare `git push`. A branch
47
+ /// delete is not a push.
48
+ export function pushes(cmd) {
49
+ const out = [];
50
+ if (!cmd.includes('push'))
51
+ return out;
52
+ for (const m of cmd.matchAll(PUSH_RE)) {
53
+ const tokens = unquote(m[1]).trim().split(/\s+/).filter(t => t && !/[<>]/.test(t));
54
+ if (tokens.some(t => t === '--delete' || t === '-d'))
55
+ continue;
56
+ const [, ...refspecs] = tokens.filter(t => !t.startsWith('-'));
57
+ out.push(refspecs
58
+ .map(r => r.replace(/^\+/, '').split(':').pop().replace(/^refs\/heads\//, ''))
59
+ .filter(b => b && b !== 'HEAD' && !b.startsWith('$')));
60
+ }
61
+ return out;
62
+ }
63
+ /// Every `gh pr <verb>` in a command line, with the PR it names (a number or a
64
+ /// PR URL) and its -R/--repo. Quoted text is dropped first so a body's digits
65
+ /// never read as a PR number.
66
+ export function ghPrCommands(cmd) {
67
+ const out = [];
68
+ if (!cmd.includes('gh pr'))
69
+ return out;
70
+ for (const m of cmd.matchAll(GH_PR_RE)) {
71
+ const args = unquote(m[2]);
72
+ const url = PR_URL_RE.exec(args);
73
+ const num = PR_ARG_VERBS.has(m[1]) ? /(?:^|\s)#?(\d{1,6})(?=\s|$)/.exec(args) : null;
74
+ const repo = url ? `${url[1]}/${url[2]}` : /(?:^|\s)(?:-R|--repo)[\s=]+([^\s/$]+\/[^\s/]+)/.exec(args)?.[1];
75
+ const number = url ? Number(url[3]) : num ? Number(num[1]) : undefined;
76
+ out.push({ verb: m[1], args, ...(number !== undefined ? { number } : {}), ...(repo ? { repo } : {}) });
77
+ }
78
+ return out;
79
+ }
80
+ /// The `--head` branch of a `gh pr create`, unless it is a shell variable.
81
+ export function createHead(args) {
82
+ const head = /(?:^|\s)(?:--head|-H)[\s=]+(\S+)/.exec(args)?.[1];
83
+ return head && !head.startsWith('-') && !head.startsWith('$') ? head : undefined;
84
+ }
85
+ /// PR numbers a command names: `gh pr <verb> N`, a PR URL, or an API path.
86
+ export function prNumbersIn(cmd) {
87
+ const out = new Set();
88
+ for (const c of ghPrCommands(cmd))
89
+ if (c.number !== undefined)
90
+ out.add(c.number);
91
+ if (!cmd.includes('/pull'))
92
+ return out;
93
+ for (const m of cmd.matchAll(API_PR_RE))
94
+ out.add(Number(m[1]));
95
+ for (const m of cmd.matchAll(new RegExp(PR_URL_RE.source, 'g')))
96
+ out.add(Number(m[3]));
97
+ return out;
98
+ }
99
+ /// PR numbers a command reads by number (gh pr view/diff/checkout/review N).
100
+ export function readPrNumbers(cmd) {
101
+ return ghPrCommands(cmd).filter(c => READ_VERBS.has(c.verb) && c.number !== undefined).map(c => c.number);
102
+ }
103
+ export function reviewVerdict(args) {
104
+ if (/(?:^|\s)(?:--approve|-a)\b/.test(args))
105
+ return 'approve';
106
+ if (/(?:^|\s)(?:--request-changes|-r)\b/.test(args))
107
+ return 'request-changes';
108
+ if (/(?:^|\s)(?:--comment|-c)\b/.test(args))
109
+ return 'comment';
110
+ return 'review';
111
+ }
112
+ export const FOLLOW_UP_GAP_MS = 10 * 60 * 1000;
113
+ /// Start of each follow-up round: pushes more than 10 minutes apart start a new one.
114
+ export function roundStarts(pushMs) {
115
+ const out = [];
116
+ let last = -Infinity;
117
+ for (const ms of [...pushMs].sort((a, b) => a - b)) {
118
+ if (ms - last > FOLLOW_UP_GAP_MS)
119
+ out.push(ms);
120
+ last = ms;
121
+ }
122
+ return out;
123
+ }
124
+ export const rounds = (pushMs) => roundStarts(pushMs).length;
125
+ export function callCommands(call) {
126
+ const out = [];
127
+ for (const step of call.toolSequence ?? [])
128
+ for (const t of step)
129
+ if (t.command)
130
+ out.push(t.command);
131
+ return out;
132
+ }
@@ -0,0 +1,33 @@
1
+ // @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
2
+ import { isInteractiveScanUI, unmatchedRootedPatterns } from './parser.js';
3
+ /// A rooted --project/--exclude selects one project or nothing, so a typo does
4
+ /// not fail: it reports a total over a set nobody asked for, which reads like a
5
+ /// correct answer. Called once per command, by the command itself, over every
6
+ /// project identity that command could have matched.
7
+ ///
8
+ /// Two callers must never see it. An Ink screen owns the terminal, so the same
9
+ /// `setInteractiveScanUI` latch the parser checks before printing scan progress
10
+ /// gates this too. And `serve` routes process.stderr.write into the progress-
11
+ /// frame emitter (runCaptured), so a warning would reach the desktop app as scan
12
+ /// progress: runStdioServe calls suppressProjectFilterWarnings() rather than
13
+ /// this module reading argv, which `codeburn --verbose serve` would shift.
14
+ let suppressed = false;
15
+ export function suppressProjectFilterWarnings() {
16
+ suppressed = true;
17
+ }
18
+ export async function reportUnmatchedProjectPatterns(projects, include, exclude, alsoKnown) {
19
+ if (suppressed || isInteractiveScanUI())
20
+ return;
21
+ const patterns = [...(include ?? []), ...(exclude ?? [])];
22
+ if (patterns.length === 0)
23
+ return;
24
+ let unmatched = unmatchedRootedPatterns(projects, patterns);
25
+ // Only then, and only for what is still missing: a command whose population is
26
+ // the live parse alone would call a path wrong while the day cache bills it.
27
+ if (unmatched.length > 0 && alsoKnown) {
28
+ unmatched = unmatchedRootedPatterns(await alsoKnown(), unmatched);
29
+ }
30
+ for (const pattern of unmatched) {
31
+ process.stderr.write(`codeburn: no project in this period matches ${pattern} (an absolute path has to be a project's path, or a prefix of it on a segment boundary)\n`);
32
+ }
33
+ }
@@ -0,0 +1,30 @@
1
+ // @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
2
+ import { isBlockedDatabaseError, isSqliteBusyError } from './sqlite.js';
3
+ // Process-wide on purpose: a file that failed to parse is cached as failed and
4
+ // not read again, so a per-run list would lose it on the next poll.
5
+ const issues = new Map();
6
+ export function providerIssueKind(err) {
7
+ const code = err?.code;
8
+ if (code === 'EACCES' || code === 'EPERM' || isBlockedDatabaseError(err))
9
+ return 'eacces';
10
+ if (isSqliteBusyError(err))
11
+ return 'busy';
12
+ if (code === 'ENOENT')
13
+ return 'enoent';
14
+ if (err instanceof SyntaxError)
15
+ return 'malformed';
16
+ return 'error';
17
+ }
18
+ export function recordProviderIssue(provider, stage, err) {
19
+ issues.set(`${provider}:${stage}`, { provider, stage, kind: providerIssueKind(err) });
20
+ }
21
+ /** With `kind`, clears only an entry of that kind: a permission error that Full Disk
22
+ * Access has since fixed, but not a malformed file that is still cached as failed. */
23
+ export function clearProviderIssue(provider, stage, kind) {
24
+ const key = `${provider}:${stage}`;
25
+ if (kind === undefined || issues.get(key)?.kind === kind)
26
+ issues.delete(key);
27
+ }
28
+ export function providerIssues() {
29
+ return [...issues.values()];
30
+ }
@@ -0,0 +1,286 @@
1
+ // @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
2
+ import { readdir } from 'fs/promises';
3
+ import { join } from 'path';
4
+ import { homedir } from 'os';
5
+ import { readSessionFile } from '../fs-utils.js';
6
+ import { calculateCost, getShortModelName } from '../models.js';
7
+ // Amp (Sourcegraph's coding agent, ampcode.com) mirrors every thread it
8
+ // serves as one JSON document per thread at <amp-data>/threads/<id>.json,
9
+ // where amp-data is $AMP_DATA_DIR (comma-separated for extra roots) or
10
+ // ~/.local/share/amp. Mapped against the format ccusage's amp adapter reads
11
+ // (rust/adapters/amp/src/parser.rs) - the same layout its own tests fixture:
12
+ //
13
+ // { id, messages: [...], usageLedger?: { events: [...] } }
14
+ //
15
+ // usageLedger.events is the authoritative per-request record: { id, timestamp,
16
+ // model, tokens: { input, output, total }, toMessageId, credits }. Cache
17
+ // tokens are not on the event - they live on the thread message the event
18
+ // billed for (toMessageId -> message.messageId ->
19
+ // usage.cacheCreationInputTokens / usage.cacheReadInputTokens). Threads
20
+ // without a ledger fall back to the per-assistant-message usage blocks
21
+ // ({ inputTokens, outputTokens, cacheCreationInputTokens,
22
+ // cacheReadInputTokens, totalTokens, timestamp, model }). For ledger
23
+ // events, any positive remainder of tokens.total after input, output and
24
+ // cache counts is added to output; a message block with no individual
25
+ // counts uses its totalTokens as the output count.
26
+ //
27
+ // Costs are priced from tokens; Amp's own credits field is not converted.
28
+ // Every cost uses CodeBurn's model pricing (models.ts) and carries
29
+ // costIsEstimated. Thread files carry no project/cwd, so sessions group under
30
+ // the provider name. Amp's model ids are the underlying OpenAI/Anthropic/
31
+ // Google ids and price through the standard catalog.
32
+ // Amp's data dir can be relocated via AMP_DATA_DIR (its own env var,
33
+ // comma-separated for multiple roots, matching Amp's semantics).
34
+ function ampDataDirs() {
35
+ const override = process.env['AMP_DATA_DIR'];
36
+ if (override) {
37
+ const dirs = override.split(',').map(part => part.trim()).filter(Boolean);
38
+ if (dirs.length > 0)
39
+ return [...new Set(dirs)];
40
+ }
41
+ return [join(homedir(), '.local/share/amp')];
42
+ }
43
+ function threadsDirFor(ampDataDir) {
44
+ return join(ampDataDir, 'threads');
45
+ }
46
+ function isRecord(value) {
47
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
48
+ }
49
+ // Thread files are third-party input that moves with Amp releases. Keep the
50
+ // check local so bad usage fields become absent rather than leaking NaN,
51
+ // negative tokens, or a throwing arithmetic operation into the aggregate.
52
+ function finiteNonNegative(value) {
53
+ if (typeof value === 'number' && Number.isFinite(value) && value >= 0) {
54
+ return Math.min(value, Number.MAX_SAFE_INTEGER);
55
+ }
56
+ return undefined;
57
+ }
58
+ function readNumber(record, field) {
59
+ return finiteNonNegative(record[field]) ?? 0;
60
+ }
61
+ function nonEmptyString(value) {
62
+ return typeof value === 'string' && value.length > 0 ? value : undefined;
63
+ }
64
+ // User text feeds the `userMessage` column. Content may be a plain string or
65
+ // a block array; only the text blocks are usable.
66
+ function messageText(message) {
67
+ const content = message['content'];
68
+ if (typeof content === 'string')
69
+ return content;
70
+ if (Array.isArray(content)) {
71
+ return content
72
+ .filter(isRecord)
73
+ .map(block => nonEmptyString(block['text']) ?? '')
74
+ .filter(Boolean)
75
+ .join(' ');
76
+ }
77
+ return nonEmptyString(message['text']) ?? '';
78
+ }
79
+ function parseThreadFile(content) {
80
+ let thread;
81
+ try {
82
+ thread = JSON.parse(content);
83
+ }
84
+ catch {
85
+ return null;
86
+ }
87
+ if (!isRecord(thread))
88
+ return null;
89
+ const threadId = nonEmptyString(thread['id']);
90
+ if (!threadId)
91
+ return null;
92
+ const messages = Array.isArray(thread['messages']) ? thread['messages'].filter(isRecord) : [];
93
+ const userMessages = messages
94
+ .map((message, index) => ({ index, text: messageText(message) }))
95
+ .filter(entry => entry.text.length > 0);
96
+ // Cache tokens per billed message id: ledger events join
97
+ // toMessageId -> messages[].messageId -> usage.cache*InputTokens. The
98
+ // message's array index travels with it to anchor userMessage attribution.
99
+ const cacheTokensByMessageId = new Map();
100
+ messages.forEach((message, index) => {
101
+ if (message['role'] !== 'assistant')
102
+ return;
103
+ const usage = message['usage'];
104
+ if (!isRecord(usage))
105
+ return;
106
+ const messageId = message['messageId'];
107
+ if (typeof messageId !== 'number' || !Number.isInteger(messageId))
108
+ return;
109
+ cacheTokensByMessageId.set(messageId, {
110
+ index,
111
+ creation: readNumber(usage, 'cacheCreationInputTokens'),
112
+ read: readNumber(usage, 'cacheReadInputTokens'),
113
+ });
114
+ });
115
+ const calls = [];
116
+ // Preferred path: the usage ledger, one event per billed request.
117
+ const ledger = thread['usageLedger'];
118
+ const events = isRecord(ledger) && Array.isArray(ledger['events']) ? ledger['events'] : [];
119
+ for (const raw of events) {
120
+ if (!isRecord(raw))
121
+ continue;
122
+ const timestamp = nonEmptyString(raw['timestamp']);
123
+ const model = nonEmptyString(raw['model']);
124
+ const tokens = raw['tokens'];
125
+ if (!timestamp || !model || !isRecord(tokens))
126
+ continue;
127
+ const inputTokens = readNumber(tokens, 'input');
128
+ const outputTokens = readNumber(tokens, 'output');
129
+ const total = finiteNonNegative(tokens['total']);
130
+ const toMessageId = raw['toMessageId'];
131
+ const billed = typeof toMessageId === 'number' && Number.isInteger(toMessageId)
132
+ ? cacheTokensByMessageId.get(toMessageId)
133
+ : undefined;
134
+ // Attribute any positive remainder to output, after accounting for the
135
+ // explicit input/output counts and both joined cache-token counts.
136
+ const accountedTokens = inputTokens + outputTokens + (billed?.creation ?? 0) + (billed?.read ?? 0);
137
+ const billedOutput = outputTokens + Math.max(0, (total ?? 0) - accountedTokens);
138
+ calls.push({
139
+ model,
140
+ timestamp,
141
+ inputTokens,
142
+ outputTokens: billedOutput,
143
+ cacheCreationInputTokens: billed?.creation ?? 0,
144
+ cacheReadInputTokens: billed?.read ?? 0,
145
+ eventId: nonEmptyString(raw['id']) ?? (typeof raw['id'] === 'number' ? String(raw['id']) : undefined),
146
+ messageIndex: billed?.index,
147
+ });
148
+ }
149
+ if (calls.length > 0)
150
+ return { threadId, calls, userMessages };
151
+ // Fallback: per-assistant-message usage blocks (threads without a ledger).
152
+ messages.forEach((message, index) => {
153
+ if (message['role'] !== 'assistant')
154
+ return;
155
+ const usage = message['usage'];
156
+ if (!isRecord(usage))
157
+ return;
158
+ const timestamp = nonEmptyString(usage['timestamp']) ?? nonEmptyString(message['timestamp']);
159
+ const model = nonEmptyString(usage['model']) ?? nonEmptyString(message['model']);
160
+ if (!timestamp || !model)
161
+ return;
162
+ const inputTokens = readNumber(usage, 'inputTokens');
163
+ const outputTokens = readNumber(usage, 'outputTokens');
164
+ const cacheCreationInputTokens = readNumber(usage, 'cacheCreationInputTokens');
165
+ const cacheReadInputTokens = readNumber(usage, 'cacheReadInputTokens');
166
+ const total = finiteNonNegative(usage['totalTokens']);
167
+ const hasParts = inputTokens > 0 || outputTokens > 0 || cacheCreationInputTokens > 0 || cacheReadInputTokens > 0;
168
+ const billedOutput = hasParts ? outputTokens : total ?? 0;
169
+ calls.push({
170
+ model,
171
+ timestamp,
172
+ inputTokens,
173
+ outputTokens: billedOutput,
174
+ cacheCreationInputTokens,
175
+ cacheReadInputTokens,
176
+ eventId: undefined,
177
+ messageIndex: index,
178
+ });
179
+ });
180
+ return { threadId, calls, userMessages };
181
+ }
182
+ function userMessageFor(parsed, record) {
183
+ // Nearest user message at or before the billed message; the thread's first
184
+ // user text when the record carries no anchor.
185
+ const anchor = record.messageIndex ?? Number.MAX_SAFE_INTEGER;
186
+ for (let i = parsed.userMessages.length - 1; i >= 0; i--) {
187
+ if (parsed.userMessages[i].index < anchor)
188
+ return parsed.userMessages[i].text;
189
+ }
190
+ return parsed.userMessages[0]?.text ?? '';
191
+ }
192
+ function hasPositiveTokens(record) {
193
+ return record.inputTokens > 0
194
+ || record.outputTokens > 0
195
+ || record.cacheCreationInputTokens > 0
196
+ || record.cacheReadInputTokens > 0;
197
+ }
198
+ function createParser(source, seenKeys) {
199
+ return {
200
+ async *parse() {
201
+ const content = await readSessionFile(source.path);
202
+ if (content === null)
203
+ return;
204
+ const parsed = parseThreadFile(content);
205
+ if (!parsed)
206
+ return;
207
+ const threadId = parsed.threadId;
208
+ for (const record of parsed.calls) {
209
+ if (!hasPositiveTokens(record))
210
+ continue;
211
+ const deduplicationKey = record.eventId
212
+ ? `${source.provider}:${threadId}:${record.eventId}`
213
+ : `${source.provider}:${threadId}:${record.timestamp}:${record.model}:${record.inputTokens}x${record.outputTokens}`;
214
+ if (seenKeys.has(deduplicationKey))
215
+ continue;
216
+ seenKeys.add(deduplicationKey);
217
+ yield {
218
+ provider: source.provider,
219
+ model: record.model,
220
+ inputTokens: record.inputTokens,
221
+ outputTokens: record.outputTokens,
222
+ cacheCreationInputTokens: record.cacheCreationInputTokens,
223
+ cacheReadInputTokens: record.cacheReadInputTokens,
224
+ cachedInputTokens: record.cacheReadInputTokens,
225
+ reasoningTokens: 0,
226
+ webSearchRequests: 0,
227
+ costUSD: calculateCost(record.model, record.inputTokens, record.outputTokens, record.cacheCreationInputTokens, record.cacheReadInputTokens, 0),
228
+ // Priced from tokens; Amp's own credits field is not converted.
229
+ costIsEstimated: true,
230
+ tools: [],
231
+ bashCommands: [],
232
+ timestamp: record.timestamp,
233
+ speed: 'standard',
234
+ deduplicationKey,
235
+ userMessage: userMessageFor(parsed, record),
236
+ sessionId: threadId,
237
+ project: source.project,
238
+ };
239
+ }
240
+ },
241
+ };
242
+ }
243
+ async function discoverThreads(roots) {
244
+ const sources = [];
245
+ for (const root of roots) {
246
+ const threadsDir = threadsDirFor(root);
247
+ let entries;
248
+ try {
249
+ entries = await readdir(threadsDir, { recursive: true });
250
+ }
251
+ catch {
252
+ continue;
253
+ }
254
+ // Discovery only walks names. The parser reads and validates each thread
255
+ // once, skipping malformed JSON and files without a thread id.
256
+ for (const name of entries) {
257
+ if (!name.endsWith('.json'))
258
+ continue;
259
+ sources.push({ path: join(threadsDir, name), project: 'Amp', provider: 'amp' });
260
+ }
261
+ }
262
+ return sources;
263
+ }
264
+ export function createAmpProvider(overrideDirs) {
265
+ const roots = overrideDirs ?? ampDataDirs();
266
+ return {
267
+ name: 'amp',
268
+ displayName: 'Amp',
269
+ async probeRoots() {
270
+ return roots.map(root => ({ path: threadsDirFor(root), label: 'threads' }));
271
+ },
272
+ modelDisplayName(model) {
273
+ return getShortModelName(model);
274
+ },
275
+ toolDisplayName(rawTool) {
276
+ return rawTool;
277
+ },
278
+ async discoverSessions() {
279
+ return discoverThreads(roots);
280
+ },
281
+ createSessionParser(source, seenKeys) {
282
+ return createParser(source, seenKeys);
283
+ },
284
+ };
285
+ }
286
+ export const amp = createAmpProvider();