chompyy 0.5.0 → 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 (154) hide show
  1. package/README.md +11 -0
  2. package/dist/agentlimits.js +77 -0
  3. package/dist/agentusage.js +96 -0
  4. package/dist/appstate.js +63 -3
  5. package/dist/away.js +44 -5
  6. package/dist/blueprint.js +3 -7
  7. package/dist/board.js +1 -0
  8. package/dist/cli.js +263 -5
  9. package/dist/codexquota.js +106 -0
  10. package/dist/codexusage.js +10 -0
  11. package/dist/config.js +2 -0
  12. package/dist/context.js +30 -0
  13. package/dist/costs.js +1 -0
  14. package/dist/demon.js +20 -0
  15. package/dist/label.js +33 -0
  16. package/dist/menu.js +17 -0
  17. package/dist/nightcap.js +60 -0
  18. package/dist/nudge.js +47 -18
  19. package/dist/pacing.js +16 -1
  20. package/dist/questions.js +71 -0
  21. package/dist/recap.js +74 -0
  22. package/dist/receipt.js +48 -0
  23. package/dist/recipe.js +79 -0
  24. package/dist/stamps.js +14 -0
  25. package/dist/triggers.js +5 -0
  26. package/dist/usage.js +21 -1
  27. package/dist/vendor/codeburn/antigravity.js +309 -0
  28. package/dist/vendor/codeburn/codex.js +429 -0
  29. package/dist/vendor/codeburn/copilot.js +292 -0
  30. package/dist/vendor/codeburn/gemini.js +195 -0
  31. package/dist/vendor/codeburn/grokbot.js +182 -0
  32. package/dist/vendor/codeburn/kimi.js +178 -0
  33. package/dist/vendor/codeburn/shims/chalk.js +14 -0
  34. package/dist/vendor/codeburn/shims/strip-ansi.js +6 -0
  35. package/dist/vendor/codeburn/src/act/backup.js +83 -0
  36. package/dist/vendor/codeburn/src/act/model-defaults.js +151 -0
  37. package/dist/vendor/codeburn/src/act/types.js +37 -0
  38. package/dist/vendor/codeburn/src/bash-utils.js +204 -0
  39. package/dist/vendor/codeburn/src/behavioral-weight.js +47 -0
  40. package/dist/vendor/codeburn/src/cache-dir.js +26 -0
  41. package/dist/vendor/codeburn/src/cache-refresh-lock.js +543 -0
  42. package/dist/vendor/codeburn/src/cache-sweep.js +67 -0
  43. package/dist/vendor/codeburn/src/classifier.js +209 -0
  44. package/dist/vendor/codeburn/src/claude-identity.js +223 -0
  45. package/dist/vendor/codeburn/src/codex-cache.js +377 -0
  46. package/dist/vendor/codeburn/src/codex-fork-replay.js +232 -0
  47. package/dist/vendor/codeburn/src/codex-jsonl-fields.js +99 -0
  48. package/dist/vendor/codeburn/src/codex-session-index.js +113 -0
  49. package/dist/vendor/codeburn/src/codex-throughput.js +544 -0
  50. package/dist/vendor/codeburn/src/compare-stats.js +405 -0
  51. package/dist/vendor/codeburn/src/config.js +145 -0
  52. package/dist/vendor/codeburn/src/content-utils.js +56 -0
  53. package/dist/vendor/codeburn/src/context-tree-codex.js +329 -0
  54. package/dist/vendor/codeburn/src/context-tree.js +664 -0
  55. package/dist/vendor/codeburn/src/copilot-aiu.js +16 -0
  56. package/dist/vendor/codeburn/src/currency.js +189 -0
  57. package/dist/vendor/codeburn/src/cursor-cache.js +238 -0
  58. package/dist/vendor/codeburn/src/cursor-import.js +402 -0
  59. package/dist/vendor/codeburn/src/cursor-sync.js +256 -0
  60. package/dist/vendor/codeburn/src/daily-cache.js +2036 -0
  61. package/dist/vendor/codeburn/src/data/litellm-snapshot.json +1 -0
  62. package/dist/vendor/codeburn/src/data/pricing-fallback.json +1 -0
  63. package/dist/vendor/codeburn/src/day-aggregator.js +327 -0
  64. package/dist/vendor/codeburn/src/editor-data-dir.js +11 -0
  65. package/dist/vendor/codeburn/src/fetch-utils.js +18 -0
  66. package/dist/vendor/codeburn/src/format.js +118 -0
  67. package/dist/vendor/codeburn/src/fs-utils.js +270 -0
  68. package/dist/vendor/codeburn/src/git-origin.js +334 -0
  69. package/dist/vendor/codeburn/src/granular-history.js +328 -0
  70. package/dist/vendor/codeburn/src/hermes-session-ledger.js +512 -0
  71. package/dist/vendor/codeburn/src/launcher-homes.js +142 -0
  72. package/dist/vendor/codeburn/src/live-sessions.js +358 -0
  73. package/dist/vendor/codeburn/src/math-utils.js +8 -0
  74. package/dist/vendor/codeburn/src/menubar-json.js +294 -0
  75. package/dist/vendor/codeburn/src/models.js +1879 -0
  76. package/dist/vendor/codeburn/src/optimize-one-hour-cache.js +92 -0
  77. package/dist/vendor/codeburn/src/optimize.js +4110 -0
  78. package/dist/vendor/codeburn/src/parse-workers.js +219 -0
  79. package/dist/vendor/codeburn/src/parser.js +6953 -0
  80. package/dist/vendor/codeburn/src/path-privacy.js +26 -0
  81. package/dist/vendor/codeburn/src/plans.js +135 -0
  82. package/dist/vendor/codeburn/src/pr-signals.js +132 -0
  83. package/dist/vendor/codeburn/src/project-filter-warnings.js +33 -0
  84. package/dist/vendor/codeburn/src/provider-issues.js +30 -0
  85. package/dist/vendor/codeburn/src/providers/amp.js +286 -0
  86. package/dist/vendor/codeburn/src/providers/antigravity.js +1731 -0
  87. package/dist/vendor/codeburn/src/providers/claude.js +551 -0
  88. package/dist/vendor/codeburn/src/providers/cline-cli.js +401 -0
  89. package/dist/vendor/codeburn/src/providers/cline.js +63 -0
  90. package/dist/vendor/codeburn/src/providers/codebuff.js +336 -0
  91. package/dist/vendor/codeburn/src/providers/codewhale.js +442 -0
  92. package/dist/vendor/codeburn/src/providers/codex.js +1720 -0
  93. package/dist/vendor/codeburn/src/providers/command-code.js +196 -0
  94. package/dist/vendor/codeburn/src/providers/copilot.js +3278 -0
  95. package/dist/vendor/codeburn/src/providers/crush.js +226 -0
  96. package/dist/vendor/codeburn/src/providers/cursor-agent.js +837 -0
  97. package/dist/vendor/codeburn/src/providers/cursor.js +1163 -0
  98. package/dist/vendor/codeburn/src/providers/devin.js +569 -0
  99. package/dist/vendor/codeburn/src/providers/droid.js +324 -0
  100. package/dist/vendor/codeburn/src/providers/dsh.js +690 -0
  101. package/dist/vendor/codeburn/src/providers/forge.js +245 -0
  102. package/dist/vendor/codeburn/src/providers/gemini.js +230 -0
  103. package/dist/vendor/codeburn/src/providers/goose.js +252 -0
  104. package/dist/vendor/codeburn/src/providers/grok.js +581 -0
  105. package/dist/vendor/codeburn/src/providers/grokbot.js +290 -0
  106. package/dist/vendor/codeburn/src/providers/hermes.js +771 -0
  107. package/dist/vendor/codeburn/src/providers/ibm-bob.js +53 -0
  108. package/dist/vendor/codeburn/src/providers/index.js +360 -0
  109. package/dist/vendor/codeburn/src/providers/kilo-code.js +50 -0
  110. package/dist/vendor/codeburn/src/providers/kimi.js +363 -0
  111. package/dist/vendor/codeburn/src/providers/kimicode.js +402 -0
  112. package/dist/vendor/codeburn/src/providers/kiro.js +1174 -0
  113. package/dist/vendor/codeburn/src/providers/lingtai-tui.js +372 -0
  114. package/dist/vendor/codeburn/src/providers/mistral-vibe-unified.js +236 -0
  115. package/dist/vendor/codeburn/src/providers/mistral-vibe.js +405 -0
  116. package/dist/vendor/codeburn/src/providers/mux.js +242 -0
  117. package/dist/vendor/codeburn/src/providers/open-design.js +217 -0
  118. package/dist/vendor/codeburn/src/providers/openclaude.js +309 -0
  119. package/dist/vendor/codeburn/src/providers/openclaw.js +442 -0
  120. package/dist/vendor/codeburn/src/providers/opencode-file-parser.js +131 -0
  121. package/dist/vendor/codeburn/src/providers/opencode.js +91 -0
  122. package/dist/vendor/codeburn/src/providers/pi.js +429 -0
  123. package/dist/vendor/codeburn/src/providers/quickdesk.js +491 -0
  124. package/dist/vendor/codeburn/src/providers/qwen.js +193 -0
  125. package/dist/vendor/codeburn/src/providers/session-message.js +118 -0
  126. package/dist/vendor/codeburn/src/providers/sqlite-session-parser.js +457 -0
  127. package/dist/vendor/codeburn/src/providers/types.js +5 -0
  128. package/dist/vendor/codeburn/src/providers/vercel-gateway.js +135 -0
  129. package/dist/vendor/codeburn/src/providers/vscode-cline-parser.js +212 -0
  130. package/dist/vendor/codeburn/src/providers/warp.js +575 -0
  131. package/dist/vendor/codeburn/src/providers/zcode.js +249 -0
  132. package/dist/vendor/codeburn/src/providers/zed.js +187 -0
  133. package/dist/vendor/codeburn/src/providers/zerostack.js +139 -0
  134. package/dist/vendor/codeburn/src/quota/antigravity.js +310 -0
  135. package/dist/vendor/codeburn/src/quota/claude.js +244 -0
  136. package/dist/vendor/codeburn/src/quota/cursor.js +301 -0
  137. package/dist/vendor/codeburn/src/quota/security.js +299 -0
  138. package/dist/vendor/codeburn/src/quota/types.js +1 -0
  139. package/dist/vendor/codeburn/src/scan-facts.js +99 -0
  140. package/dist/vendor/codeburn/src/session-cache.js +3040 -0
  141. package/dist/vendor/codeburn/src/session-count-label.js +14 -0
  142. package/dist/vendor/codeburn/src/session-output.js +139 -0
  143. package/dist/vendor/codeburn/src/session-population.js +30 -0
  144. package/dist/vendor/codeburn/src/sessions-report.js +1342 -0
  145. package/dist/vendor/codeburn/src/sqlite.js +528 -0
  146. package/dist/vendor/codeburn/src/sync/otlp.js +420 -0
  147. package/dist/vendor/codeburn/src/telemetry-snapshot.js +244 -0
  148. package/dist/vendor/codeburn/src/token-estimate.js +5 -0
  149. package/dist/vendor/codeburn/src/types.js +16 -0
  150. package/dist/vendor/codeburn/src/work-units.js +126 -0
  151. package/dist/vendor/codeburn/src/workflow-insights.js +228 -0
  152. package/dist/vendor/codeburn/src/wsl.js +198 -0
  153. package/dist/vendor/codeburn/src/yield.js +666 -0
  154. package/package.json +1 -1
@@ -0,0 +1,420 @@
1
+ // @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
2
+ /**
3
+ * codeburn sync — OTLP payload builder.
4
+ *
5
+ * Converts ParsedApiCall[] into an ExportTraceServiceRequest (OTLP/HTTP JSON).
6
+ * Span and trace IDs are derived deterministically from deduplicationKey/sessionId.
7
+ */
8
+ import { createHash } from 'crypto';
9
+ import { hostname, userInfo } from 'os';
10
+ import { posix, win32 } from 'path';
11
+ import { isTrustedAbsoluteWorkingDirectory } from '../path-privacy.js';
12
+ import { billableOutputTokens } from '../models.js';
13
+ // --- Device ID (pseudonymous, stable) ---
14
+ let cachedDeviceId = null;
15
+ /** Pure derivation — exposed so the encoding can be golden-pinned in tests. */
16
+ export function deriveDeviceId(host, username) {
17
+ return createHash('sha256').update(`${host}:${username}`).digest('hex').slice(0, 16);
18
+ }
19
+ export function getDeviceId() {
20
+ if (cachedDeviceId)
21
+ return cachedDeviceId;
22
+ cachedDeviceId = deriveDeviceId(hostname(), userInfo().username);
23
+ return cachedDeviceId;
24
+ }
25
+ // --- Span/Trace ID derivation (deterministic) ---
26
+ export function deriveSpanId(deduplicationKey) {
27
+ return createHash('sha256').update(deduplicationKey).digest('hex').slice(0, 16);
28
+ }
29
+ export function deriveTraceId(sessionId) {
30
+ return createHash('sha256').update(sessionId).digest('hex').slice(0, 32);
31
+ }
32
+ /**
33
+ * Wire-safe project identity: the leaf directory name. Several providers key a
34
+ * project by its sanitized absolute path ("-Users-me-Projects-app"), and
35
+ * docs/sync/README.md promises file paths stay local.
36
+ */
37
+ export function wireProjectName(projectPath, fallback) {
38
+ const normalized = projectPath.trim().replace(/\\/g, '/').replace(/\/+$/, '');
39
+ return normalized.split('/').filter(Boolean).pop() ?? fallback;
40
+ }
41
+ // --- Timestamp conversion ---
42
+ function toUnixNano(isoTimestamp) {
43
+ const ms = new Date(isoTimestamp).getTime();
44
+ if (isNaN(ms))
45
+ return '0';
46
+ return (BigInt(ms) * 1000000n).toString();
47
+ }
48
+ function isEmailOrCredentialShaped(value) {
49
+ if (/^(?:\.?(?:ssh|aws|gnupg|kube)|\.env(?:\..*)?|credentials?|id_(?:rsa|dsa|ecdsa|ed25519)|authorized_keys|known_hosts|netrc|npmrc|pypirc)$/i.test(value.trim()))
50
+ return true;
51
+ if (/^[^@\s]{1,64}@(?![^@\s]*@)(?:[A-Za-z0-9-]+\.)+[A-Za-z]{2,}$/.test(value))
52
+ return true;
53
+ if (/(?:^|[^A-Za-z0-9])(?:x[-_]?access[-_]?token|api[-_]?key|access[-_]?token|refresh[-_]?token|id[-_]?token|token|authorization|bearer|password|passwd|private[-_]?key|client[-_]?secret|secret)(?=[:=])/i.test(value))
54
+ return true;
55
+ if (/(?:^|[^A-Za-z0-9])(?:github_pat_|gh[pousr]_|glpat-|sk-[A-Za-z0-9]|[sr]k_(?:live|test)_|whsec_|xox[baprs]-|AIza|npm_|pypi-|hf_)/i.test(value))
56
+ return true;
57
+ if (/(?:^|[^A-Za-z0-9])(?:AKIA|ASIA)[A-Z0-9]{16}(?:$|[^A-Z0-9])/i.test(value))
58
+ return true;
59
+ return false;
60
+ }
61
+ /**
62
+ * Convert a trusted absolute provider cwd into the only project label allowed
63
+ * on usage spans. Imported Windows paths are handled on every host. Anything
64
+ * ambiguous fails closed.
65
+ */
66
+ export function projectBasenameFromWorkingDirectory(workingDirectory) {
67
+ if (!isTrustedAbsoluteWorkingDirectory(workingDirectory))
68
+ return undefined;
69
+ const flavour = posix.isAbsolute(workingDirectory)
70
+ ? posix
71
+ : win32.isAbsolute(workingDirectory)
72
+ ? win32
73
+ : null;
74
+ if (!flavour)
75
+ return undefined;
76
+ const value = flavour.basename(workingDirectory);
77
+ if (!value || value === '.' || value === '..' || value.length > 128)
78
+ return undefined;
79
+ if (/[\\/\u0000-\u001f\u007f]/.test(value))
80
+ return undefined;
81
+ if (/%(?:2f|5c)/i.test(value))
82
+ return undefined;
83
+ if (isEmailOrCredentialShaped(value))
84
+ return undefined;
85
+ return value;
86
+ }
87
+ const IDENTIFIER_SHAPE = /^[A-Za-z0-9][A-Za-z0-9._:+/@-]*$/;
88
+ function isPathUrlOrCredentialShaped(value) {
89
+ if (posix.isAbsolute(value) || win32.isAbsolute(value))
90
+ return true;
91
+ if (/^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(value))
92
+ return true;
93
+ if (/[=?&#\\]/.test(value) || /%(?:2f|5c)/i.test(value))
94
+ return true;
95
+ if (/(?:^|\/)(?:\.{1,2})(?:\/|$)/.test(value))
96
+ return true;
97
+ if (/^(?:users|home|private|tmp|var|etc|root|workspaces?|projects?)\//i.test(value))
98
+ return true;
99
+ if (/^(?:[A-Za-z]--)?(?:users|home|private|tmp|var|etc|root|workspaces?|projects?)[-_]/i.test(value))
100
+ return true;
101
+ return isEmailOrCredentialShaped(value);
102
+ }
103
+ function sanitizeIdentifier(value, maxBytes, fallback) {
104
+ if (/\p{Cc}/u.test(value))
105
+ return fallback;
106
+ if (Buffer.byteLength(value, 'utf8') > maxBytes
107
+ || !IDENTIFIER_SHAPE.test(value)
108
+ || isPathUrlOrCredentialShaped(value)) {
109
+ return fallback;
110
+ }
111
+ return value;
112
+ }
113
+ export function sanitizeProviderIdentifier(value) {
114
+ return sanitizeIdentifier(value, 64, 'unknown') ?? 'unknown';
115
+ }
116
+ export function sanitizeModelIdentifier(value) {
117
+ return sanitizeIdentifier(value, 160, 'unknown') ?? 'unknown';
118
+ }
119
+ export function sanitizeToolIdentifiers(values) {
120
+ const result = [];
121
+ let totalBytes = 0;
122
+ for (const value of values) {
123
+ if (result.length >= 64)
124
+ break;
125
+ const safe = sanitizeIdentifier(value, 128);
126
+ if (!safe)
127
+ continue;
128
+ const bytes = Buffer.byteLength(safe, 'utf8');
129
+ if (totalBytes + bytes > 4096)
130
+ break;
131
+ result.push(safe);
132
+ totalBytes += bytes;
133
+ }
134
+ return result;
135
+ }
136
+ function safeProjectAttribute(project) {
137
+ if (!project || project.length > 128 || /[\\/\u0000-\u001f\u007f]/.test(project)
138
+ || /%(?:2f|5c)/i.test(project) || isEmailOrCredentialShaped(project))
139
+ return null;
140
+ return { key: 'ai.project', value: { stringValue: project } };
141
+ }
142
+ /// Attribute keys the core emitter writes. Plugins add fields; they never
143
+ /// overwrite these, so a plugin cannot lie about cost, tokens, or lineage.
144
+ export const CORE_SYNC_ATTRIBUTE_KEYS = new Set([
145
+ 'ai.provider', 'ai.model', 'ai.input_tokens', 'ai.output_tokens', 'ai.cost_usd', 'ai.speed',
146
+ 'ai.project', 'ai.tools', 'ai.cost_estimated', 'ai.work_unit_id', 'ai.session_role',
147
+ 'ai.lineage_evidence', 'ai.cache_read_tokens', 'ai.cache_write_tokens', 'ai.call_count',
148
+ 'ai.session_duration_ms', 'ai.subscription_covered', 'codeburn.device_id',
149
+ 'codeburn.coverage_through', 'codeburn.attribution_methodology',
150
+ 'git.repo', 'git.sha', 'git.commit_count', 'git.in_main', 'git.was_reverted', 'git.pr_links',
151
+ ]);
152
+ /// Wire guard for plugin-supplied attributes (see BuildOtlpOptions).
153
+ export function filterPluginAttributes(attrs, declaredKeys) {
154
+ const kept = [];
155
+ for (const attr of attrs) {
156
+ if (!declaredKeys.has(attr.key) || CORE_SYNC_ATTRIBUTE_KEYS.has(attr.key))
157
+ continue;
158
+ const v = attr.value;
159
+ if ('stringValue' in v) {
160
+ // Same #1128 sanitizer vocabulary as every other wire string; a plugin
161
+ // value that looks like a path, URL, or credential never ships.
162
+ const safe = sanitizeIdentifier(v.stringValue, 256);
163
+ if (safe)
164
+ kept.push({ key: attr.key, value: { stringValue: safe } });
165
+ }
166
+ else if ('intValue' in v || 'doubleValue' in v || 'boolValue' in v) {
167
+ kept.push(attr);
168
+ }
169
+ // arrayValue and anything else: plugins may not ship structured values.
170
+ }
171
+ return kept;
172
+ }
173
+ export function buildOtlpPayload(calls, opts) {
174
+ const deviceId = getDeviceId();
175
+ const guardedPluginAttributes = opts?.pluginAttributes && opts.pluginAttributeKeys
176
+ ? filterPluginAttributes(opts.pluginAttributes, opts.pluginAttributeKeys)
177
+ : [];
178
+ const spans = calls.map(({ call, sessionId, workingDirectory, session }) => {
179
+ const perCallEnrichment = opts?.pluginEnrichment?.perCall.get(call.deduplicationKey) ?? [];
180
+ const startNano = toUnixNano(call.timestamp);
181
+ // End time = start + 1ms (we don't have real duration, but OTLP requires both)
182
+ const endNano = (BigInt(startNano) + 1000000n).toString();
183
+ const provider = sanitizeProviderIdentifier(call.provider);
184
+ const model = sanitizeModelIdentifier(call.model);
185
+ const project = projectBasenameFromWorkingDirectory(workingDirectory);
186
+ const tools = sanitizeToolIdentifiers(call.tools);
187
+ const attributes = [
188
+ { key: 'ai.provider', value: { stringValue: provider } },
189
+ { key: 'ai.model', value: { stringValue: model } },
190
+ { key: 'ai.input_tokens', value: { intValue: String(call.usage.inputTokens) } },
191
+ // Billable output, not raw: for providers that bill reasoning separately
192
+ // the raw output under-reports by the reasoning volume. Same routing the
193
+ // display layer adopted in #1115/#1116.
194
+ { key: 'ai.output_tokens', value: { intValue: String(billableOutputTokens(call.provider, call.usage.outputTokens, call.usage.reasoningTokens)) } },
195
+ { key: 'ai.cost_usd', value: { doubleValue: call.costUSD } },
196
+ { key: 'ai.speed', value: { stringValue: call.speed } },
197
+ ];
198
+ const projectAttribute = safeProjectAttribute(project);
199
+ if (projectAttribute)
200
+ attributes.push(projectAttribute);
201
+ if (tools.length > 0) {
202
+ attributes.push({
203
+ key: 'ai.tools',
204
+ value: { arrayValue: { values: tools.map(t => ({ stringValue: t })) } },
205
+ });
206
+ }
207
+ attributes.push({ key: 'ai.cost_estimated', value: { boolValue: call.costBasis === 'estimated' } });
208
+ // --- CB-3 additive fields (boundary spec section 7). Each is emitted only
209
+ // when its value is proven; an old receiver ignoring them loses nothing.
210
+ // Lineage: all three or none, and never inferred. The trio survives or
211
+ // falls together through the same #1128 sanitizers as the other strings.
212
+ if (session?.workUnitId && session.sessionRole) {
213
+ const workUnitId = sanitizeIdentifier(session.workUnitId, 64);
214
+ const role = sanitizeIdentifier(session.sessionRole, 16);
215
+ const evidence = sanitizeIdentifier('provider-recorded', 32);
216
+ if (workUnitId && role && evidence) {
217
+ attributes.push({ key: 'ai.work_unit_id', value: { stringValue: workUnitId } }, { key: 'ai.session_role', value: { stringValue: role } }, { key: 'ai.lineage_evidence', value: { stringValue: evidence } });
218
+ }
219
+ }
220
+ // Cache tokens, billable-consistent with ai.input_tokens: providers record
221
+ // cache reads in exactly one vocabulary (Anthropic-style cacheRead or
222
+ // OpenAI-style cached-subset, the display layer's Math.max convention).
223
+ const cacheRead = Math.max(call.usage.cacheReadInputTokens, call.usage.cachedInputTokens);
224
+ if (cacheRead > 0) {
225
+ attributes.push({ key: 'ai.cache_read_tokens', value: { intValue: String(cacheRead) } });
226
+ }
227
+ if (call.usage.cacheCreationInputTokens > 0) {
228
+ attributes.push({ key: 'ai.cache_write_tokens', value: { intValue: String(call.usage.cacheCreationInputTokens) } });
229
+ }
230
+ if (session) {
231
+ attributes.push({ key: 'ai.call_count', value: { intValue: String(session.callCount) } });
232
+ if (session.durationMs !== undefined) {
233
+ attributes.push({ key: 'ai.session_duration_ms', value: { intValue: String(session.durationMs) } });
234
+ }
235
+ if (session.subscriptionCovered !== undefined) {
236
+ attributes.push({ key: 'ai.subscription_covered', value: { boolValue: session.subscriptionCovered } });
237
+ }
238
+ }
239
+ // Plugin socket: declared-and-guarded plugin fields only (see
240
+ // filterPluginAttributes). No plugins => no change to any byte.
241
+ attributes.push(...guardedPluginAttributes);
242
+ // Per-call enrichment from sync exporters
243
+ attributes.push(...perCallEnrichment);
244
+ return {
245
+ traceId: deriveTraceId(sessionId),
246
+ spanId: deriveSpanId(call.deduplicationKey),
247
+ name: `${provider}/${model}`,
248
+ startTimeUnixNano: startNano,
249
+ endTimeUnixNano: endNano,
250
+ attributes,
251
+ };
252
+ });
253
+ const resourceAttributes = [
254
+ { key: 'codeburn.device_id', value: { stringValue: deviceId } },
255
+ ];
256
+ const coverageThrough = opts?.coverageThrough ? sanitizeIdentifier(opts.coverageThrough, 32) : undefined;
257
+ if (coverageThrough) {
258
+ resourceAttributes.push({ key: 'codeburn.coverage_through', value: { stringValue: coverageThrough } });
259
+ }
260
+ // Append extra spans from plugin exporters
261
+ if (opts?.pluginEnrichment?.extraSpans) {
262
+ spans.push(...opts.pluginEnrichment.extraSpans);
263
+ }
264
+ return {
265
+ resourceSpans: [{
266
+ resource: {
267
+ attributes: resourceAttributes,
268
+ },
269
+ scopeSpans: [{
270
+ spans,
271
+ }],
272
+ }],
273
+ };
274
+ }
275
+ /** Split calls into batches of maxBatchSize. */
276
+ export function batchCalls(calls, maxBatchSize) {
277
+ const batches = [];
278
+ for (let i = 0; i < calls.length; i += maxBatchSize) {
279
+ batches.push(calls.slice(i, i + maxBatchSize));
280
+ }
281
+ return batches;
282
+ }
283
+ // --- Attribution spans (sync push --attribution) ---
284
+ export const SESSION_ATTRIBUTION_SPAN_NAME = 'codeburn.session.attribution';
285
+ export const COMMIT_ATTRIBUTION_SPAN_NAME = 'codeburn.commit';
286
+ function attributionProjectFromRepo(repo) {
287
+ if (!repo)
288
+ return undefined;
289
+ const parts = repo.split('/').filter(Boolean);
290
+ // Normalized remotes may be either host/owner/repo or owner/repo.
291
+ if (parts.length < 2)
292
+ return undefined;
293
+ return projectBasenameFromWorkingDirectory(`/${parts.at(-1)}`);
294
+ }
295
+ function stateHash(parts) {
296
+ return createHash('sha256').update(parts.join('\u001e')).digest('hex').slice(0, 16);
297
+ }
298
+ /** Deterministic dedup key for a commit attribution fact (state included). */
299
+ export function commitAttributionKey(sessionId, sha, inMain, wasReverted) {
300
+ return `attr:c:${sessionId}:${sha}:${inMain ? 1 : 0}${wasReverted ? 1 : 0}`;
301
+ }
302
+ /** Deterministic dedup key for a session attribution fact (state included). */
303
+ export function sessionAttributionKey(record) {
304
+ const commitStates = record.commits
305
+ .map(c => `${c.sha}:${c.inMain ? 1 : 0}${c.wasReverted ? 1 : 0}`)
306
+ .sort();
307
+ // Project and both window timestamps are part of the state: an ongoing
308
+ // session whose window grew (or whose project resolution changed) re-emits
309
+ // with the corrected span times instead of freezing at first send.
310
+ return `attr:s:${record.sessionId}:${stateHash([
311
+ record.repo ?? '',
312
+ record.project,
313
+ record.firstTimestamp,
314
+ record.lastTimestamp,
315
+ ...record.prLinks,
316
+ ...commitStates,
317
+ ])}`;
318
+ }
319
+ /** Ledger-key prefix for a session's attribution facts (any state). */
320
+ export function sessionAttributionKeyPrefix(sessionId) {
321
+ return `attr:s:${sessionId}:`;
322
+ }
323
+ /** Flatten attribution records into ledger-able items (one session item + one per commit). */
324
+ export function flattenAttributionRecords(records) {
325
+ const items = [];
326
+ for (const record of records) {
327
+ const project = attributionProjectFromRepo(record.repo);
328
+ items.push({
329
+ kind: 'session',
330
+ dedupKey: sessionAttributionKey(record),
331
+ timestamp: record.firstTimestamp,
332
+ endTimestamp: record.lastTimestamp,
333
+ sessionId: record.sessionId,
334
+ ...(project ? { project } : {}),
335
+ repo: record.repo,
336
+ prLinks: record.prLinks,
337
+ commitCount: record.commits.length,
338
+ });
339
+ for (const commit of record.commits) {
340
+ items.push({
341
+ kind: 'commit',
342
+ dedupKey: commitAttributionKey(record.sessionId, commit.sha, commit.inMain, commit.wasReverted),
343
+ timestamp: commit.timestamp,
344
+ sessionId: record.sessionId,
345
+ ...(project ? { project } : {}),
346
+ repo: record.repo,
347
+ sha: commit.sha,
348
+ inMain: commit.inMain,
349
+ wasReverted: commit.wasReverted,
350
+ });
351
+ }
352
+ }
353
+ return items;
354
+ }
355
+ /**
356
+ * Build an OTLP payload from attribution items. Spans share the session's
357
+ * traceId with the usage spans (`deriveTraceId(sessionId)`), so a receiver
358
+ * can correlate cost and attribution without any extra key.
359
+ */
360
+ export function buildAttributionOtlpPayload(items) {
361
+ const deviceId = getDeviceId();
362
+ const spans = items.map(item => {
363
+ const startNano = toUnixNano(item.timestamp);
364
+ // Clamp like the usage builder: end is never 0 (malformed timestamp) and
365
+ // never earlier than start + 1ms (out-of-order session timestamps).
366
+ const minEndNano = BigInt(startNano) + 1000000n;
367
+ const rawEndNano = item.endTimestamp ? BigInt(toUnixNano(item.endTimestamp)) : 0n;
368
+ const endNano = (rawEndNano > minEndNano ? rawEndNano : minEndNano).toString();
369
+ const attributes = [];
370
+ const projectAttribute = safeProjectAttribute(item.project);
371
+ if (projectAttribute)
372
+ attributes.push(projectAttribute);
373
+ if (item.repo) {
374
+ attributes.push({ key: 'git.repo', value: { stringValue: item.repo } });
375
+ }
376
+ if (item.kind === 'commit') {
377
+ attributes.push({ key: 'git.sha', value: { stringValue: item.sha ?? '' } }, { key: 'git.in_main', value: { boolValue: item.inMain ?? false } }, { key: 'git.was_reverted', value: { boolValue: item.wasReverted ?? false } });
378
+ }
379
+ else {
380
+ attributes.push({ key: 'git.commit_count', value: { intValue: String(item.commitCount ?? 0) } });
381
+ if (item.prLinks && item.prLinks.length > 0) {
382
+ attributes.push({
383
+ key: 'git.pr_links',
384
+ value: { arrayValue: { values: item.prLinks.map(u => ({ stringValue: u })) } },
385
+ });
386
+ }
387
+ }
388
+ return {
389
+ traceId: deriveTraceId(item.sessionId),
390
+ spanId: deriveSpanId(item.dedupKey),
391
+ name: item.kind === 'commit' ? COMMIT_ATTRIBUTION_SPAN_NAME : SESSION_ATTRIBUTION_SPAN_NAME,
392
+ startTimeUnixNano: startNano,
393
+ endTimeUnixNano: endNano,
394
+ attributes,
395
+ };
396
+ });
397
+ return {
398
+ resourceSpans: [{
399
+ resource: {
400
+ attributes: [
401
+ { key: 'codeburn.device_id', value: { stringValue: deviceId } },
402
+ // Honesty marker: this attribution is inferred (timestamp-window
403
+ // correlation), not declared. Receivers should label it as such.
404
+ { key: 'codeburn.attribution_methodology', value: { stringValue: 'timestamp-window' } },
405
+ ],
406
+ },
407
+ scopeSpans: [{
408
+ spans,
409
+ }],
410
+ }],
411
+ };
412
+ }
413
+ /** Split attribution items into batches of maxBatchSize. */
414
+ export function batchAttributionItems(items, maxBatchSize) {
415
+ const batches = [];
416
+ for (let i = 0; i < items.length; i += maxBatchSize) {
417
+ batches.push(items.slice(i, i + maxBatchSize));
418
+ }
419
+ return batches;
420
+ }
@@ -0,0 +1,244 @@
1
+ // @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
2
+ import { isBehavioralTurn } from './behavioral-weight.js';
3
+ import { getShortModelName, modelRowKey } from './models.js';
4
+ import { CATEGORY_LABELS } from './types.js';
5
+ /// The anonymised daily aggregate that both the desktop app and the Windows
6
+ /// tray send as the consent-gated `usage_snapshot` telemetry event. It is
7
+ /// computed here, in the CLI, so the two surfaces cannot drift into two
8
+ /// different shapes.
9
+ ///
10
+ /// Privacy contract, held by construction rather than by a caller's discipline:
11
+ /// - Every magnitude is a bucket label. No exact dollar amounts, no exact
12
+ /// counts, no exact durations.
13
+ /// - Names are configuration or model identifiers only: model names, task
14
+ /// category labels, provider display names, MCP server / skill / tool names.
15
+ /// Nothing here is derived from a working directory, project name, branch
16
+ /// name, file path or message text.
17
+ /// - Leaves are only short strings, finite numbers and booleans, nested at most
18
+ /// two containers deep, so the desktop's whitelist sanitizer passes the block
19
+ /// through unchanged.
20
+ /// - Arrays are capped (see the limits below) so the block stays small.
21
+ export const TELEMETRY_SNAPSHOT_SCHEMA = 2;
22
+ const MAX_MODELS = 8;
23
+ const MAX_TASKS_PER_MODEL = 6;
24
+ const MAX_CATEGORIES = 12;
25
+ const MAX_MODELS_PER_CATEGORY = 3;
26
+ const MAX_PROVIDERS = 8;
27
+ const MAX_NAMED = 12;
28
+ const MAX_NAME = 64;
29
+ const SYNTHETIC_MODEL_NAME = '<synthetic>';
30
+ /// Shared with the desktop renderer's fallback builder: 1, 10, 50, 200 and
31
+ /// 1000 USD boundaries.
32
+ export function costBucket(usd) {
33
+ if (!Number.isFinite(usd) || usd < 1)
34
+ return '<1';
35
+ if (usd < 10)
36
+ return '1-10';
37
+ if (usd < 50)
38
+ return '10-50';
39
+ if (usd < 200)
40
+ return '50-200';
41
+ if (usd < 1000)
42
+ return '200-1k';
43
+ return '1k+';
44
+ }
45
+ /// Occurrence counts (turns, calls, sessions) coarsened the same way dollars
46
+ /// are, with one extra label at the bottom: `0`. Nothing happened is not the
47
+ /// same claim as "between one and ten", and a model the payload lists but that
48
+ /// has no behavioural turns behind it would otherwise report activity it never
49
+ /// had. A count that is not a finite number is unknown, which is likewise not
50
+ /// evidence of use, so it reads as `0` too.
51
+ /// Buckets: `0`, `1-10`, `10-100`, `100-1k`, `1k+`.
52
+ export function countBucket(n) {
53
+ if (!Number.isFinite(n) || n <= 0)
54
+ return '0';
55
+ if (n < 10)
56
+ return '1-10';
57
+ if (n < 100)
58
+ return '10-100';
59
+ if (n < 1000)
60
+ return '100-1k';
61
+ return '1k+';
62
+ }
63
+ /// Wall-clock session length. Coarse enough that a single session cannot be
64
+ /// recognised from its duration.
65
+ export function minutesBucket(minutes) {
66
+ if (!Number.isFinite(minutes) || minutes < 5)
67
+ return '<5';
68
+ if (minutes < 15)
69
+ return '5-15';
70
+ if (minutes < 60)
71
+ return '15-60';
72
+ if (minutes < 240)
73
+ return '60-240';
74
+ return '240+';
75
+ }
76
+ function round2(n) {
77
+ return Math.round(n * 100) / 100;
78
+ }
79
+ /// Rates are reported to 2dp, or -1 when the denominator is empty. -1 is the
80
+ /// established "not computable" marker for these fields, so a consumer never
81
+ /// has to tell a missing rate apart from a genuine zero.
82
+ function rate2(numerator, denominator) {
83
+ if (denominator <= 0)
84
+ return -1;
85
+ return round2(numerator / denominator);
86
+ }
87
+ function safeName(value) {
88
+ return typeof value === 'string' ? value.slice(0, MAX_NAME) : '';
89
+ }
90
+ /// Walks parsed turns once and buckets each behavioural turn under its primary
91
+ /// model and its task category. The primary model is the turn's first
92
+ /// non-synthetic assistant call, matching how `aggregateModelEfficiency`
93
+ /// attributes a turn, and it is shortened with `getShortModelName` so the keys
94
+ /// line up with the payload's `topModels[].name`.
95
+ export function aggregateModelTaskTurns(projects) {
96
+ const rows = new Map();
97
+ for (const project of projects) {
98
+ for (const session of project.sessions) {
99
+ for (const turn of session.turns) {
100
+ if (!isBehavioralTurn(turn))
101
+ continue;
102
+ const primary = turn.assistantCalls.find(call => getShortModelName(call.model) !== SYNTHETIC_MODEL_NAME);
103
+ if (!primary)
104
+ continue;
105
+ const model = modelRowKey(primary.model, primary.route);
106
+ const category = CATEGORY_LABELS[turn.category] ?? turn.category;
107
+ const key = `${model}\u0000${category}`;
108
+ let row = rows.get(key);
109
+ if (!row) {
110
+ row = { model, category, turns: 0, editTurns: 0, oneShotTurns: 0 };
111
+ rows.set(key, row);
112
+ }
113
+ row.turns++;
114
+ if (turn.hasEdits) {
115
+ row.editTurns++;
116
+ if (turn.retries === 0)
117
+ row.oneShotTurns++;
118
+ }
119
+ }
120
+ }
121
+ }
122
+ return [...rows.values()];
123
+ }
124
+ /// Session wall-clock lengths in minutes, for the median duration bucket.
125
+ export function sessionDurationMinutes(projects) {
126
+ const minutes = [];
127
+ for (const project of projects) {
128
+ for (const session of project.sessions) {
129
+ const start = Date.parse(session.firstTimestamp);
130
+ const end = Date.parse(session.lastTimestamp);
131
+ if (!Number.isFinite(start) || !Number.isFinite(end) || end < start)
132
+ continue;
133
+ minutes.push((end - start) / 60_000);
134
+ }
135
+ }
136
+ return minutes;
137
+ }
138
+ function median(values) {
139
+ if (values.length === 0)
140
+ return null;
141
+ const sorted = [...values].sort((a, b) => a - b);
142
+ const mid = Math.floor(sorted.length / 2);
143
+ if (sorted.length % 2 === 1)
144
+ return sorted[mid];
145
+ return (sorted[mid - 1] + sorted[mid]) / 2;
146
+ }
147
+ export function buildTelemetrySnapshot(payload, input = {}) {
148
+ const current = payload.current;
149
+ const byModel = new Map();
150
+ const byCategory = new Map();
151
+ for (const row of input.modelTasks ?? []) {
152
+ const model = safeName(row.model);
153
+ const category = safeName(row.category);
154
+ if (!model || !category || !Number.isFinite(row.turns) || row.turns <= 0)
155
+ continue;
156
+ let rollup = byModel.get(model);
157
+ if (!rollup) {
158
+ rollup = { turns: 0, editTurns: 0, oneShotTurns: 0, tasks: new Map() };
159
+ byModel.set(model, rollup);
160
+ }
161
+ rollup.turns += row.turns;
162
+ rollup.editTurns += Number.isFinite(row.editTurns) ? row.editTurns : 0;
163
+ rollup.oneShotTurns += Number.isFinite(row.oneShotTurns) ? row.oneShotTurns : 0;
164
+ rollup.tasks.set(category, (rollup.tasks.get(category) ?? 0) + row.turns);
165
+ const models = byCategory.get(category) ?? new Map();
166
+ models.set(model, (models.get(model) ?? 0) + row.turns);
167
+ byCategory.set(category, models);
168
+ }
169
+ const models = [];
170
+ for (const model of current.topModels ?? []) {
171
+ if (models.length >= MAX_MODELS)
172
+ break;
173
+ const name = safeName(model.name);
174
+ if (!name)
175
+ continue;
176
+ const rollup = byModel.get(name);
177
+ const tasks = rollup
178
+ ? [...rollup.tasks.entries()]
179
+ .sort((a, b) => b[1] - a[1])
180
+ .slice(0, MAX_TASKS_PER_MODEL)
181
+ .map(([category, turns]) => ({
182
+ name: category,
183
+ turnBucket: countBucket(turns),
184
+ share: rate2(turns, rollup.turns),
185
+ }))
186
+ : [];
187
+ models.push({
188
+ name,
189
+ costBucket: costBucket(model.cost),
190
+ turnBucket: countBucket(rollup?.turns ?? 0),
191
+ oneShotRate: rate2(rollup?.oneShotTurns ?? 0, rollup?.editTurns ?? 0),
192
+ tasks,
193
+ });
194
+ }
195
+ const categories = [];
196
+ for (const activity of current.topActivities ?? []) {
197
+ if (categories.length >= MAX_CATEGORIES)
198
+ break;
199
+ const name = safeName(activity.name);
200
+ if (!name)
201
+ continue;
202
+ categories.push({
203
+ name,
204
+ turnBucket: countBucket(activity.turns),
205
+ oneShotRate: activity.oneShotRate == null ? -1 : round2(activity.oneShotRate),
206
+ topModels: [...(byCategory.get(name) ?? new Map()).entries()]
207
+ .sort((a, b) => b[1] - a[1])
208
+ .slice(0, MAX_MODELS_PER_CATEGORY)
209
+ .map(([model]) => model),
210
+ });
211
+ }
212
+ const providers = Object.entries(current.providers ?? {})
213
+ .sort((a, b) => b[1] - a[1])
214
+ .slice(0, MAX_PROVIDERS)
215
+ .map(([name, cost]) => ({ name: safeName(name), costBucket: costBucket(cost) }))
216
+ .filter(entry => entry.name !== '');
217
+ const named = (rows, name, calls) => (rows ?? [])
218
+ .slice(0, MAX_NAMED)
219
+ .map(row => ({ name: safeName(name(row)), callBucket: countBucket(calls(row)) }))
220
+ .filter(entry => entry.name !== '');
221
+ const medianMinutes = median(input.sessionMinutes ?? []);
222
+ const cacheDenominator = current.inputTokens + current.cacheReadTokens;
223
+ const retryTaxUSD = current.retryTax?.totalUSD ?? 0;
224
+ return {
225
+ schema: TELEMETRY_SNAPSHOT_SCHEMA,
226
+ period: safeName(current.label),
227
+ providerCount: Object.keys(current.providers ?? {}).length,
228
+ costBucket: costBucket(current.cost),
229
+ models,
230
+ categories,
231
+ providers,
232
+ mcpServers: named(current.mcpServers, row => row.name, row => row.calls),
233
+ skills: named(current.skills, row => row.name, row => row.turns),
234
+ tools: named(current.tools, row => row.name, row => row.calls),
235
+ sessions: {
236
+ countBucket: countBucket(current.sessions),
237
+ ...(medianMinutes === null ? {} : { medianMinutesBucket: minutesBucket(medianMinutes) }),
238
+ },
239
+ efficiency: {
240
+ ...(cacheDenominator > 0 ? { cacheHitRate: round2(current.cacheHitPercent / 100) } : {}),
241
+ ...(current.cost > 0 ? { retryTaxShare: round2(retryTaxUSD / current.cost) } : {}),
242
+ },
243
+ };
244
+ }
@@ -0,0 +1,5 @@
1
+ // @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
2
+ export const CHARS_PER_TOKEN = 4;
3
+ export function estimateTokensFromChars(chars) {
4
+ return Math.ceil(chars / CHARS_PER_TOKEN);
5
+ }
@@ -0,0 +1,16 @@
1
+ export const SPEEDS = ['standard', 'fast', 'flex', 'ultrafast'];
2
+ export const CATEGORY_LABELS = {
3
+ coding: 'Coding',
4
+ debugging: 'Debugging',
5
+ feature: 'Feature Dev',
6
+ refactoring: 'Refactoring',
7
+ testing: 'Testing',
8
+ exploration: 'Exploration',
9
+ planning: 'Planning',
10
+ delegation: 'Delegation',
11
+ git: 'Git Ops',
12
+ 'build/deploy': 'Build/Deploy',
13
+ conversation: 'Conversation',
14
+ brainstorming: 'Brainstorming',
15
+ general: 'General',
16
+ };