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,372 @@
1
+ // @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
2
+ import { readdir, readFile, stat } from 'fs/promises';
3
+ import { basename, delimiter, dirname, join, resolve } from 'path';
4
+ import { homedir } from 'os';
5
+ import { readSessionLines } from '../fs-utils.js';
6
+ import { calculateCost, getShortModelName } from '../models.js';
7
+ function normalizeOptions(options) {
8
+ return typeof options === 'string'
9
+ ? { lingtaiHomeOverride: options }
10
+ : options ?? {};
11
+ }
12
+ function expandHome(raw) {
13
+ if (raw === '~')
14
+ return homedir();
15
+ if (raw.startsWith('~/') || raw.startsWith('~\\'))
16
+ return join(homedir(), raw.slice(2));
17
+ return raw;
18
+ }
19
+ function splitPathList(raw) {
20
+ return (raw ?? '')
21
+ .split(delimiter)
22
+ .map(p => p.trim())
23
+ .filter(Boolean);
24
+ }
25
+ async function existingDir(path) {
26
+ const resolved = resolve(expandHome(path));
27
+ const s = await stat(resolved).catch(() => null);
28
+ return s?.isDirectory() ? resolved : null;
29
+ }
30
+ function getDefaultLingTaiHome(options) {
31
+ return options.defaultHomeOverride ?? join(homedir(), '.lingtai');
32
+ }
33
+ function getLingTaiGlobalDir(options) {
34
+ return options.globalDirOverride
35
+ ?? process.env['LINGTAI_TUI_GLOBAL_DIR']
36
+ ?? join(homedir(), '.lingtai-tui');
37
+ }
38
+ function projectPrefixFromHome(lingtaiHome, defaultLingTaiHome) {
39
+ const defaultHome = resolve(expandHome(defaultLingTaiHome));
40
+ const resolved = resolve(lingtaiHome);
41
+ if (resolved === defaultHome)
42
+ return undefined;
43
+ const projectName = basename(dirname(resolved));
44
+ return projectName && projectName !== '.' ? sanitizeProject(projectName) : undefined;
45
+ }
46
+ async function readRegisteredProjectPaths(globalDir) {
47
+ const projects = [];
48
+ const registryRaw = await readFile(join(globalDir, 'registry.jsonl'), 'utf-8').catch(() => '');
49
+ for (const line of registryRaw.split(/\r?\n/)) {
50
+ if (!line.trim())
51
+ continue;
52
+ try {
53
+ const obj = asObject(JSON.parse(line));
54
+ const path = stringField(obj, 'path');
55
+ if (path)
56
+ projects.push(path);
57
+ }
58
+ catch {
59
+ // Ignore corrupt registry rows; LingTai treats this as append-only state.
60
+ }
61
+ }
62
+ const briefDir = join(globalDir, 'brief', 'projects');
63
+ const entries = await readdir(briefDir, { withFileTypes: true }).catch(() => []);
64
+ for (const entry of entries) {
65
+ if (!entry.isDirectory())
66
+ continue;
67
+ const meta = await readJson(join(briefDir, entry.name, 'meta.json'));
68
+ const path = stringField(meta, 'project_path');
69
+ if (path)
70
+ projects.push(path);
71
+ }
72
+ return projects;
73
+ }
74
+ function cwdLingTaiHomes(cwd) {
75
+ const homes = [];
76
+ let current = resolve(cwd);
77
+ for (;;) {
78
+ homes.push(join(current, '.lingtai'));
79
+ const parent = dirname(current);
80
+ if (parent === current)
81
+ break;
82
+ current = parent;
83
+ }
84
+ return homes;
85
+ }
86
+ async function getLingTaiHomes(options) {
87
+ const explicit = splitPathList(options.lingtaiHomeOverride ?? process.env['LINGTAI_HOME'] ?? process.env['LINGTAI_TUI_HOME']);
88
+ const defaultHome = getDefaultLingTaiHome(options);
89
+ const candidates = explicit.length
90
+ ? explicit
91
+ : [
92
+ defaultHome,
93
+ ...(await readRegisteredProjectPaths(getLingTaiGlobalDir(options))).map(project => join(project, '.lingtai')),
94
+ ...cwdLingTaiHomes(options.cwdOverride ?? process.cwd()),
95
+ ];
96
+ const seen = new Set();
97
+ const homes = [];
98
+ for (const candidate of candidates) {
99
+ const path = await existingDir(candidate);
100
+ if (!path || seen.has(path))
101
+ continue;
102
+ seen.add(path);
103
+ homes.push({ path, projectPrefix: explicit.length ? undefined : projectPrefixFromHome(path, defaultHome) });
104
+ }
105
+ return homes;
106
+ }
107
+ function sanitizeProject(raw) {
108
+ const trimmed = raw.trim();
109
+ if (!trimmed)
110
+ return 'lingtai';
111
+ return trimmed.replace(/^[/\\]+/, '').replace(/[:/\\]/g, '-');
112
+ }
113
+ function asObject(value) {
114
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : null;
115
+ }
116
+ function stringField(obj, key) {
117
+ const value = obj?.[key];
118
+ return typeof value === 'string' && value.trim() ? value : undefined;
119
+ }
120
+ function numericField(obj, key) {
121
+ const raw = obj[key];
122
+ const n = typeof raw === 'number' ? raw : typeof raw === 'string' ? Number(raw) : NaN;
123
+ if (!Number.isFinite(n) || n <= 0)
124
+ return 0;
125
+ return Math.trunc(n);
126
+ }
127
+ async function readJson(path) {
128
+ const raw = await readFile(path, 'utf-8').catch(() => null);
129
+ if (!raw)
130
+ return null;
131
+ try {
132
+ return JSON.parse(raw);
133
+ }
134
+ catch {
135
+ return null;
136
+ }
137
+ }
138
+ async function readAgentManifest(agentDir) {
139
+ const obj = asObject(await readJson(join(agentDir, '.agent.json')));
140
+ if (!obj)
141
+ return null;
142
+ // .agent.json is untrusted: a planted file can be valid JSON with wrong-typed
143
+ // fields (e.g. `agent_name: {}`). Reading it as a raw cast let a non-string
144
+ // field reach sanitizeProject().trim() and throw — and because
145
+ // discoverAllSessions loops providers without a try/catch, that one file took
146
+ // down usage discovery for EVERY provider. Normalize to string-or-undefined
147
+ // here so no downstream string op ever sees a non-string.
148
+ const llm = asObject(obj['llm']);
149
+ return {
150
+ agent_id: stringField(obj, 'agent_id'),
151
+ agent_name: stringField(obj, 'agent_name'),
152
+ address: stringField(obj, 'address'),
153
+ nickname: stringField(obj, 'nickname') ?? null,
154
+ llm: llm
155
+ ? { model: stringField(llm, 'model'), base_url: stringField(llm, 'base_url') }
156
+ : undefined,
157
+ };
158
+ }
159
+ function agentDirFromLedgerPath(ledgerPath) {
160
+ return dirname(dirname(ledgerPath));
161
+ }
162
+ function projectFromManifest(manifest, fallback, prefix) {
163
+ const name = sanitizeProject(manifest?.nickname
164
+ ?? manifest?.agent_name
165
+ ?? manifest?.address
166
+ ?? fallback);
167
+ return prefix ? `${prefix}-${name}` : name;
168
+ }
169
+ function parseTimestamp(raw) {
170
+ if (typeof raw === 'number' && Number.isFinite(raw)) {
171
+ const ms = raw < 1e12 ? raw * 1000 : raw;
172
+ return new Date(ms).toISOString();
173
+ }
174
+ if (typeof raw !== 'string' || !raw.trim())
175
+ return '';
176
+ const d = new Date(raw);
177
+ return Number.isNaN(d.getTime()) ? '' : d.toISOString();
178
+ }
179
+ function parseLedgerLine(line) {
180
+ const text = Buffer.isBuffer(line) ? line.toString('utf-8') : line;
181
+ if (!text.trim())
182
+ return null;
183
+ try {
184
+ const parsed = JSON.parse(text);
185
+ const obj = asObject(parsed);
186
+ return obj ? obj : null;
187
+ }
188
+ catch {
189
+ return null;
190
+ }
191
+ }
192
+ function activityForSource(sourceLabel) {
193
+ const normalized = sourceLabel.trim().toLowerCase();
194
+ if (normalized === 'tc_wake' || normalized.startsWith('tc_') || normalized.includes('wake')) {
195
+ return {
196
+ userMessage: 'LingTai task coordinator wake',
197
+ tools: ['Agent'],
198
+ subagentTypes: ['lingtai-task-coordinator'],
199
+ };
200
+ }
201
+ if (normalized === 'daemon') {
202
+ return {
203
+ userMessage: 'LingTai daemon task',
204
+ tools: ['Agent'],
205
+ subagentTypes: ['lingtai-daemon'],
206
+ };
207
+ }
208
+ if (normalized === 'summarize_apriori' || normalized.includes('summar')) {
209
+ return {
210
+ userMessage: 'LingTai planning summary',
211
+ tools: ['EnterPlanMode'],
212
+ subagentTypes: [],
213
+ };
214
+ }
215
+ return {
216
+ userMessage: normalized === 'main'
217
+ ? 'LingTai main conversation'
218
+ : `LingTai ${sourceLabel || 'main'} conversation`,
219
+ tools: [],
220
+ subagentTypes: [],
221
+ };
222
+ }
223
+ async function discoverLedgersInHome(home) {
224
+ const entries = await readdir(home.path, { withFileTypes: true }).catch(() => []);
225
+ const sources = [];
226
+ for (const entry of entries) {
227
+ if (!entry.isDirectory())
228
+ continue;
229
+ const agentDir = join(home.path, entry.name);
230
+ const ledgerPath = join(agentDir, 'logs', 'token_ledger.jsonl');
231
+ const s = await stat(ledgerPath).catch(() => null);
232
+ if (!s?.isFile())
233
+ continue;
234
+ const manifest = await readAgentManifest(agentDir);
235
+ sources.push({
236
+ path: ledgerPath,
237
+ project: projectFromManifest(manifest, entry.name, home.projectPrefix),
238
+ provider: 'lingtai-tui',
239
+ });
240
+ }
241
+ return sources;
242
+ }
243
+ async function discoverLedgers(homes) {
244
+ const sources = [];
245
+ const seen = new Set();
246
+ for (const home of homes) {
247
+ for (const source of await discoverLedgersInHome(home)) {
248
+ if (seen.has(source.path))
249
+ continue;
250
+ seen.add(source.path);
251
+ sources.push(source);
252
+ }
253
+ }
254
+ return sources;
255
+ }
256
+ function createParser(source) {
257
+ return {
258
+ async *parse() {
259
+ const agentDir = agentDirFromLedgerPath(source.path);
260
+ const manifest = await readAgentManifest(agentDir);
261
+ const agentId = manifest?.agent_id ?? basename(agentDir);
262
+ const fallbackModel = manifest?.llm?.model ?? 'unknown';
263
+ const fallbackEndpoint = manifest?.llm?.base_url ?? '';
264
+ const project = source.project || projectFromManifest(manifest, basename(agentDir));
265
+ const projectPath = agentDir;
266
+ let lineNo = 0;
267
+ for await (const line of readSessionLines(source.path)) {
268
+ lineNo += 1;
269
+ const entry = parseLedgerLine(line);
270
+ if (!entry)
271
+ continue;
272
+ const obj = entry;
273
+ const inputTotal = numericField(obj, 'input');
274
+ const outputTokens = numericField(obj, 'output');
275
+ const reasoningTokens = numericField(obj, 'thinking');
276
+ const cachedInputTokens = numericField(obj, 'cached');
277
+ const totalTokens = inputTotal + outputTokens + reasoningTokens + cachedInputTokens;
278
+ if (totalTokens === 0)
279
+ continue;
280
+ // LingTai records provider-normalized input totals plus a separate
281
+ // cached count. Match CodeBurn's normal shape by billing cached tokens
282
+ // in cacheReadInputTokens, not again as fresh input.
283
+ const inputTokens = Math.max(0, inputTotal - cachedInputTokens);
284
+ const model = stringField(obj, 'model') ?? fallbackModel;
285
+ const endpoint = stringField(obj, 'endpoint') ?? fallbackEndpoint;
286
+ const timestamp = parseTimestamp(entry.ts);
287
+ const sourceLabel = stringField(obj, 'source') ?? 'main';
288
+ const emId = stringField(obj, 'em_id') ?? '';
289
+ const runId = stringField(obj, 'run_id') ?? '';
290
+ const sessionId = runId || `${agentId}:${sourceLabel}`;
291
+ const activity = activityForSource(sourceLabel);
292
+ const dedupKey = [
293
+ 'lingtai-tui',
294
+ source.path,
295
+ lineNo,
296
+ timestamp,
297
+ model,
298
+ endpoint,
299
+ sourceLabel,
300
+ emId,
301
+ runId,
302
+ inputTotal,
303
+ outputTokens,
304
+ reasoningTokens,
305
+ cachedInputTokens,
306
+ ].join(':');
307
+ const costUSD = calculateCost(model, inputTokens, outputTokens + reasoningTokens, 0, cachedInputTokens, 0);
308
+ yield {
309
+ provider: 'lingtai-tui',
310
+ model,
311
+ inputTokens,
312
+ outputTokens,
313
+ cacheCreationInputTokens: 0,
314
+ cacheReadInputTokens: cachedInputTokens,
315
+ cachedInputTokens,
316
+ reasoningTokens,
317
+ webSearchRequests: 0,
318
+ costUSD,
319
+ tools: activity.tools,
320
+ bashCommands: [],
321
+ subagentTypes: activity.subagentTypes,
322
+ timestamp,
323
+ speed: 'standard',
324
+ deduplicationKey: dedupKey,
325
+ turnId: `${sessionId}:line:${lineNo}`,
326
+ userMessage: activity.userMessage,
327
+ sessionId,
328
+ project,
329
+ projectPath,
330
+ };
331
+ }
332
+ },
333
+ };
334
+ }
335
+ export function createLingTaiTuiProvider(options) {
336
+ const providerOptions = normalizeOptions(options);
337
+ return {
338
+ name: 'lingtai-tui',
339
+ displayName: 'LingTai TUI',
340
+ modelDisplayName(model) {
341
+ return getShortModelName(model);
342
+ },
343
+ toolDisplayName(rawTool) {
344
+ return rawTool;
345
+ },
346
+ async probeRoots() {
347
+ // Deliberately pre-existence-filter: doctor's job is to show where
348
+ // discovery looks, so a missing default home reads as "not installed
349
+ // here" instead of vanishing (getLingTaiHomes drops non-existent
350
+ // candidates, which is right for discovery and wrong for doctor).
351
+ const explicit = splitPathList(providerOptions.lingtaiHomeOverride ?? process.env['LINGTAI_HOME'] ?? process.env['LINGTAI_TUI_HOME']);
352
+ const roots = explicit.length
353
+ ? explicit.map(path => ({ path, label: 'sessions' }))
354
+ : [
355
+ { path: getDefaultLingTaiHome(providerOptions), label: 'sessions' },
356
+ { path: getLingTaiGlobalDir(providerOptions), label: 'registry' },
357
+ ];
358
+ for (const home of await getLingTaiHomes(providerOptions)) {
359
+ if (!roots.some(root => root.path === home.path))
360
+ roots.push({ path: home.path, label: 'sessions' });
361
+ }
362
+ return roots;
363
+ },
364
+ async discoverSessions() {
365
+ return discoverLedgers(await getLingTaiHomes(providerOptions));
366
+ },
367
+ createSessionParser(source) {
368
+ return createParser(source);
369
+ },
370
+ };
371
+ }
372
+ export const lingtaiTui = createLingTaiTuiProvider();
@@ -0,0 +1,236 @@
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 { basename, dirname, join } from 'path';
4
+ import { readSessionFile, readSessionLines } from '../fs-utils.js';
5
+ import { calculateCost } from '../models.js';
6
+ import { extractBashCommands } from '../bash-utils.js';
7
+ function object(value) {
8
+ return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : {};
9
+ }
10
+ function array(value) { return Array.isArray(value) ? value : []; }
11
+ function text(value) { return typeof value === 'string' ? value : ''; }
12
+ function count(value) {
13
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : 0;
14
+ }
15
+ async function json(path) {
16
+ const raw = await readSessionFile(path);
17
+ if (raw === null)
18
+ return null;
19
+ try {
20
+ return object(JSON.parse(raw));
21
+ }
22
+ catch {
23
+ return null;
24
+ }
25
+ }
26
+ function usagePoint(sequence, stateValue) {
27
+ const state = object(stateValue);
28
+ const usage = object(object(state.session).tokenUsage);
29
+ if (!Object.keys(usage).length)
30
+ return null;
31
+ const input = count(usage.inputTokens);
32
+ return { sequence, state, usage: {
33
+ input, output: count(usage.outputTokens), cached: Math.min(input, count(usage.cachedInputTokens)),
34
+ } };
35
+ }
36
+ function content(value) {
37
+ return typeof value === 'string' ? value : array(value).map(part => text(object(part).text)).join(' ');
38
+ }
39
+ function timestamp(value, fallback) {
40
+ if (typeof value !== 'number' || !Number.isFinite(value))
41
+ return fallback;
42
+ const date = new Date(value);
43
+ return Number.isNaN(date.getTime()) ? fallback : date.toISOString();
44
+ }
45
+ /**
46
+ * Vibe 2.25's journal is a recovery log, not an append-only usage ledger.
47
+ * CURRENT selects the committed snapshot; only two journal segments survive
48
+ * checkpoint rotation. Read cumulative projection usage (never contextUsage or
49
+ * duplicate action_result/core_input copies), then take deltas between envelopes.
50
+ */
51
+ export async function readUnifiedVibeCalls(currentPath, toolDisplayName, defaultModel) {
52
+ const dir = dirname(currentPath);
53
+ const current = await json(currentPath);
54
+ if (current?.store_format !== 'mistral.vibe.unified-session-store/v1')
55
+ return [];
56
+ const generation = text(current.generation);
57
+ if (!/^\d{16}$/.test(generation))
58
+ return [];
59
+ const generationDir = join(dir, 'generations', generation);
60
+ const projection = await json(join(generationDir, 'projection-state.json'));
61
+ const runtime = await json(join(generationDir, 'runtime-state.json'));
62
+ const manifest = await json(join(generationDir, 'manifest.json'));
63
+ if (!projection || !runtime || !manifest)
64
+ return [];
65
+ const sessionId = text(current.session_id) || basename(dir);
66
+ if (projection.session_id !== sessionId || runtime.session_id !== sessionId)
67
+ return [];
68
+ const snapshotSequence = count(current.snapshot_sequence);
69
+ const snapshot = object(projection.snapshot);
70
+ const meta = await json(join(dir, 'meta.json'));
71
+ const sessionMetadata = object(runtime.session_metadata);
72
+ // active_model is a pin; an unpinned session runs the configured default.
73
+ const model = text(sessionMetadata.active_model) || text(object(meta?.config).active_model) || defaultModel;
74
+ const fallbackTime = text(meta?.end_time) || text(meta?.start_time);
75
+ const projectPath = text(sessionMetadata.cwd) || text(object(meta?.environment).working_directory);
76
+ const entries = new Map();
77
+ const addEntries = (values) => {
78
+ for (const value of array(values)) {
79
+ const entry = object(value);
80
+ if (typeof entry.id === 'string')
81
+ entries.set(entry.id, entry);
82
+ }
83
+ };
84
+ addEntries(object(snapshot.history).entries);
85
+ // Manifest chunk names are content hashes, never arbitrary paths from a log.
86
+ for (const hash of array(object(manifest.projection_state).chunks)) {
87
+ if (typeof hash !== 'string' || !/^[a-f0-9]{64}$/.test(hash))
88
+ return [];
89
+ const raw = await readSessionFile(join(dir, 'chunks', `${hash}.json`));
90
+ if (raw === null)
91
+ return [];
92
+ try {
93
+ addEntries(JSON.parse(raw));
94
+ }
95
+ catch {
96
+ return [];
97
+ }
98
+ }
99
+ const points = new Map();
100
+ const addPoint = (sequence, state) => {
101
+ const point = usagePoint(sequence, state);
102
+ if (point)
103
+ points.set(sequence, point);
104
+ };
105
+ addPoint(snapshotSequence, snapshot);
106
+ const journalDir = join(dir, 'journal');
107
+ const segments = (await readdir(journalDir).catch(() => []))
108
+ .filter(name => /^\d{16}\.jsonl$/.test(name)).sort();
109
+ const seenSequences = new Set();
110
+ for (const segment of segments) {
111
+ for await (const line of readSessionLines(join(journalDir, segment))) {
112
+ let record;
113
+ try {
114
+ record = object(JSON.parse(line));
115
+ }
116
+ catch {
117
+ continue;
118
+ }
119
+ const sequence = count(record.sequence);
120
+ if (!sequence || seenSequences.has(sequence))
121
+ continue;
122
+ seenSequences.add(sequence);
123
+ const payload = object(record.payload);
124
+ if (record.type === 'projection_advanced') {
125
+ addPoint(sequence, payload.snapshot);
126
+ if (sequence > snapshotSequence) {
127
+ entries.clear();
128
+ addEntries(object(object(payload.snapshot).history).entries);
129
+ }
130
+ }
131
+ else if (record.type === 'projection_delta') {
132
+ for (const value of array(payload.delta)) {
133
+ const op = object(value);
134
+ if (op.op === 'set_envelope')
135
+ addPoint(sequence, op.state);
136
+ if (sequence <= snapshotSequence)
137
+ continue;
138
+ if (op.op === 'append_entry' || op.op === 'replace_entry')
139
+ addEntries([op.entry]);
140
+ else if (op.op === 'remove_entry')
141
+ entries.delete(text(op.id));
142
+ else if (op.op === 'set_history_entries') {
143
+ entries.clear();
144
+ addEntries(op.entries);
145
+ }
146
+ }
147
+ }
148
+ }
149
+ }
150
+ const history = [...entries.values()].sort((a, b) => count(a.createdAt) - count(b.createdAt));
151
+ const steps = [];
152
+ let previous = { input: 0, output: 0, cached: 0 };
153
+ for (const point of [...points.values()].sort((a, b) => a.sequence - b.sequence)) {
154
+ const { usage } = point;
155
+ // Projection counters are cumulative. Replayed/stale envelopes cannot add
156
+ // usage again, and context-window shrinkage is not new billable usage.
157
+ if (usage.input < previous.input || usage.output < previous.output || usage.cached < previous.cached)
158
+ continue;
159
+ const delta = {
160
+ input: usage.input - previous.input,
161
+ output: usage.output - previous.output,
162
+ cached: Math.min(usage.input - previous.input, usage.cached - previous.cached),
163
+ };
164
+ const first = previous.input === 0 && previous.output === 0;
165
+ previous = usage;
166
+ if (delta.input || delta.output)
167
+ steps.push({ point, delta, first });
168
+ }
169
+ // Rotation drops the per-call usage of the prefix, but runtime state still
170
+ // lists every completion, so the prefix splits into that many calls.
171
+ const completions = array(runtime.actions).filter(value => {
172
+ const action = object(value);
173
+ return action.kind === 'completion' && action.state === 'succeeded';
174
+ }).length;
175
+ const journalCalls = steps.filter(step => !step.first && step.point.sequence <= snapshotSequence).length;
176
+ const prefixCalls = Math.max(1, completions - journalCalls);
177
+ const split = (total, index, parts) => Math.floor(total / parts) + (index < total % parts ? 1 : 0);
178
+ const calls = [];
179
+ const turnsWithTools = new Set();
180
+ for (const { point, delta, first } of steps) {
181
+ const session = object(point.state.session);
182
+ const pointTime = count(session.updatedAt);
183
+ const turnId = text(object(point.state.latestTurn).id) || `${sessionId}:snapshot`;
184
+ // After rotation, older per-call usage is gone. Allocate that prefix across
185
+ // its recorded turns, just as the legacy parser allocates cumulative stats.
186
+ const olderTurns = first ? [...new Set(history
187
+ .filter(entry => count(entry.createdAt) <= pointTime && (entry.role === 'assistant' || entry.type === 'effect'))
188
+ .map(entry => text(entry.turnId)).filter(Boolean))] : [];
189
+ const turnIds = olderTurns.length ? olderTurns : [turnId];
190
+ const slots = first
191
+ ? turnIds.flatMap((id, index) => Array(Math.max(1, split(prefixCalls, index, turnIds.length))).fill(id))
192
+ : turnIds;
193
+ for (const [index, id] of slots.entries()) {
194
+ const turnEntries = history.filter(entry => entry.turnId === id);
195
+ const user = turnEntries.find(entry => entry.role === 'user');
196
+ const assistant = turnEntries.find(entry => entry.role === 'assistant' || entry.type === 'effect');
197
+ const tools = [];
198
+ const bashCommands = [];
199
+ // A turn's tools ride on its first call only, so per-call tool counts stay real.
200
+ if (!turnsWithTools.has(id)) {
201
+ turnsWithTools.add(id);
202
+ for (const entry of turnEntries) {
203
+ const detail = object(entry.detail);
204
+ const rawName = text(detail.toolName);
205
+ if (!rawName)
206
+ continue;
207
+ // History names carry the tool group: `file_system.bash`, `ui.ask_user_question`.
208
+ const name = toolDisplayName(rawName.replace(/^.*\./, ''));
209
+ tools.push(name);
210
+ if (name === 'Bash') {
211
+ const command = text(object(detail.input).command);
212
+ if (command)
213
+ bashCommands.push(...extractBashCommands(command));
214
+ }
215
+ }
216
+ }
217
+ const inputTokens = split(delta.input - delta.cached, index, slots.length);
218
+ const outputTokens = split(delta.output, index, slots.length);
219
+ const cacheReadInputTokens = split(delta.cached, index, slots.length);
220
+ calls.push({
221
+ provider: 'mistral-vibe', model, inputTokens, outputTokens,
222
+ cacheReadInputTokens, cachedInputTokens: cacheReadInputTokens,
223
+ cacheCreationInputTokens: 0, reasoningTokens: 0, webSearchRequests: 0,
224
+ costUSD: calculateCost(model, inputTokens, outputTokens, 0, cacheReadInputTokens, 0),
225
+ costIsEstimated: true,
226
+ tools: [...new Set(tools)], bashCommands: [...new Set(bashCommands)],
227
+ timestamp: timestamp(first ? assistant?.createdAt ?? pointTime : pointTime, fallbackTime),
228
+ speed: 'standard', sessionId, turnId: id,
229
+ deduplicationKey: `mistral-vibe:${sessionId}:unified:${point.sequence}:${id}:${index}`,
230
+ userMessage: (content(user?.content) || text(session.preview) || text(meta?.title)).slice(0, 500),
231
+ ...(projectPath ? { projectPath, workingDirectory: projectPath } : {}),
232
+ });
233
+ }
234
+ }
235
+ return calls;
236
+ }