chompyy 0.4.7 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/README.md +40 -6
  2. package/dist/advice.js +2 -1
  3. package/dist/agentlimits.js +77 -0
  4. package/dist/agentusage.js +96 -0
  5. package/dist/appstate.js +72 -5
  6. package/dist/away.js +44 -5
  7. package/dist/blueprint.js +3 -7
  8. package/dist/board.js +4 -0
  9. package/dist/cli.js +328 -15
  10. package/dist/codexquota.js +106 -0
  11. package/dist/codexusage.js +10 -0
  12. package/dist/config.js +2 -0
  13. package/dist/context.js +30 -0
  14. package/dist/costs.js +1 -0
  15. package/dist/daytime.js +68 -0
  16. package/dist/demon.js +20 -0
  17. package/dist/didwork.js +46 -0
  18. package/dist/label.js +33 -0
  19. package/dist/learning.js +35 -0
  20. package/dist/menu.js +17 -0
  21. package/dist/nightcap.js +60 -0
  22. package/dist/nudge.js +47 -18
  23. package/dist/pacing.js +16 -1
  24. package/dist/questions.js +71 -0
  25. package/dist/recap.js +74 -0
  26. package/dist/receipt.js +48 -0
  27. package/dist/recipe.js +79 -0
  28. package/dist/send.js +46 -20
  29. package/dist/stamps.js +14 -0
  30. package/dist/taste.js +67 -7
  31. package/dist/triggers.js +5 -0
  32. package/dist/unkeep.js +220 -0
  33. package/dist/usage.js +21 -1
  34. package/dist/vendor/codeburn/antigravity.js +309 -0
  35. package/dist/vendor/codeburn/codex.js +429 -0
  36. package/dist/vendor/codeburn/copilot.js +292 -0
  37. package/dist/vendor/codeburn/gemini.js +195 -0
  38. package/dist/vendor/codeburn/grokbot.js +182 -0
  39. package/dist/vendor/codeburn/kimi.js +178 -0
  40. package/dist/vendor/codeburn/shims/chalk.js +14 -0
  41. package/dist/vendor/codeburn/shims/strip-ansi.js +6 -0
  42. package/dist/vendor/codeburn/src/act/backup.js +83 -0
  43. package/dist/vendor/codeburn/src/act/model-defaults.js +151 -0
  44. package/dist/vendor/codeburn/src/act/types.js +37 -0
  45. package/dist/vendor/codeburn/src/bash-utils.js +204 -0
  46. package/dist/vendor/codeburn/src/behavioral-weight.js +47 -0
  47. package/dist/vendor/codeburn/src/cache-dir.js +26 -0
  48. package/dist/vendor/codeburn/src/cache-refresh-lock.js +543 -0
  49. package/dist/vendor/codeburn/src/cache-sweep.js +67 -0
  50. package/dist/vendor/codeburn/src/classifier.js +209 -0
  51. package/dist/vendor/codeburn/src/claude-identity.js +223 -0
  52. package/dist/vendor/codeburn/src/codex-cache.js +377 -0
  53. package/dist/vendor/codeburn/src/codex-fork-replay.js +232 -0
  54. package/dist/vendor/codeburn/src/codex-jsonl-fields.js +99 -0
  55. package/dist/vendor/codeburn/src/codex-session-index.js +113 -0
  56. package/dist/vendor/codeburn/src/codex-throughput.js +544 -0
  57. package/dist/vendor/codeburn/src/compare-stats.js +405 -0
  58. package/dist/vendor/codeburn/src/config.js +145 -0
  59. package/dist/vendor/codeburn/src/content-utils.js +56 -0
  60. package/dist/vendor/codeburn/src/context-tree-codex.js +329 -0
  61. package/dist/vendor/codeburn/src/context-tree.js +664 -0
  62. package/dist/vendor/codeburn/src/copilot-aiu.js +16 -0
  63. package/dist/vendor/codeburn/src/currency.js +189 -0
  64. package/dist/vendor/codeburn/src/cursor-cache.js +238 -0
  65. package/dist/vendor/codeburn/src/cursor-import.js +402 -0
  66. package/dist/vendor/codeburn/src/cursor-sync.js +256 -0
  67. package/dist/vendor/codeburn/src/daily-cache.js +2036 -0
  68. package/dist/vendor/codeburn/src/data/litellm-snapshot.json +1 -0
  69. package/dist/vendor/codeburn/src/data/pricing-fallback.json +1 -0
  70. package/dist/vendor/codeburn/src/day-aggregator.js +327 -0
  71. package/dist/vendor/codeburn/src/editor-data-dir.js +11 -0
  72. package/dist/vendor/codeburn/src/fetch-utils.js +18 -0
  73. package/dist/vendor/codeburn/src/format.js +118 -0
  74. package/dist/vendor/codeburn/src/fs-utils.js +270 -0
  75. package/dist/vendor/codeburn/src/git-origin.js +334 -0
  76. package/dist/vendor/codeburn/src/granular-history.js +328 -0
  77. package/dist/vendor/codeburn/src/hermes-session-ledger.js +512 -0
  78. package/dist/vendor/codeburn/src/launcher-homes.js +142 -0
  79. package/dist/vendor/codeburn/src/live-sessions.js +358 -0
  80. package/dist/vendor/codeburn/src/math-utils.js +8 -0
  81. package/dist/vendor/codeburn/src/menubar-json.js +294 -0
  82. package/dist/vendor/codeburn/src/models.js +1879 -0
  83. package/dist/vendor/codeburn/src/optimize-one-hour-cache.js +92 -0
  84. package/dist/vendor/codeburn/src/optimize.js +4110 -0
  85. package/dist/vendor/codeburn/src/parse-workers.js +219 -0
  86. package/dist/vendor/codeburn/src/parser.js +6953 -0
  87. package/dist/vendor/codeburn/src/path-privacy.js +26 -0
  88. package/dist/vendor/codeburn/src/plans.js +135 -0
  89. package/dist/vendor/codeburn/src/pr-signals.js +132 -0
  90. package/dist/vendor/codeburn/src/project-filter-warnings.js +33 -0
  91. package/dist/vendor/codeburn/src/provider-issues.js +30 -0
  92. package/dist/vendor/codeburn/src/providers/amp.js +286 -0
  93. package/dist/vendor/codeburn/src/providers/antigravity.js +1731 -0
  94. package/dist/vendor/codeburn/src/providers/claude.js +551 -0
  95. package/dist/vendor/codeburn/src/providers/cline-cli.js +401 -0
  96. package/dist/vendor/codeburn/src/providers/cline.js +63 -0
  97. package/dist/vendor/codeburn/src/providers/codebuff.js +336 -0
  98. package/dist/vendor/codeburn/src/providers/codewhale.js +442 -0
  99. package/dist/vendor/codeburn/src/providers/codex.js +1720 -0
  100. package/dist/vendor/codeburn/src/providers/command-code.js +196 -0
  101. package/dist/vendor/codeburn/src/providers/copilot.js +3278 -0
  102. package/dist/vendor/codeburn/src/providers/crush.js +226 -0
  103. package/dist/vendor/codeburn/src/providers/cursor-agent.js +837 -0
  104. package/dist/vendor/codeburn/src/providers/cursor.js +1163 -0
  105. package/dist/vendor/codeburn/src/providers/devin.js +569 -0
  106. package/dist/vendor/codeburn/src/providers/droid.js +324 -0
  107. package/dist/vendor/codeburn/src/providers/dsh.js +690 -0
  108. package/dist/vendor/codeburn/src/providers/forge.js +245 -0
  109. package/dist/vendor/codeburn/src/providers/gemini.js +230 -0
  110. package/dist/vendor/codeburn/src/providers/goose.js +252 -0
  111. package/dist/vendor/codeburn/src/providers/grok.js +581 -0
  112. package/dist/vendor/codeburn/src/providers/grokbot.js +290 -0
  113. package/dist/vendor/codeburn/src/providers/hermes.js +771 -0
  114. package/dist/vendor/codeburn/src/providers/ibm-bob.js +53 -0
  115. package/dist/vendor/codeburn/src/providers/index.js +360 -0
  116. package/dist/vendor/codeburn/src/providers/kilo-code.js +50 -0
  117. package/dist/vendor/codeburn/src/providers/kimi.js +363 -0
  118. package/dist/vendor/codeburn/src/providers/kimicode.js +402 -0
  119. package/dist/vendor/codeburn/src/providers/kiro.js +1174 -0
  120. package/dist/vendor/codeburn/src/providers/lingtai-tui.js +372 -0
  121. package/dist/vendor/codeburn/src/providers/mistral-vibe-unified.js +236 -0
  122. package/dist/vendor/codeburn/src/providers/mistral-vibe.js +405 -0
  123. package/dist/vendor/codeburn/src/providers/mux.js +242 -0
  124. package/dist/vendor/codeburn/src/providers/open-design.js +217 -0
  125. package/dist/vendor/codeburn/src/providers/openclaude.js +309 -0
  126. package/dist/vendor/codeburn/src/providers/openclaw.js +442 -0
  127. package/dist/vendor/codeburn/src/providers/opencode-file-parser.js +131 -0
  128. package/dist/vendor/codeburn/src/providers/opencode.js +91 -0
  129. package/dist/vendor/codeburn/src/providers/pi.js +429 -0
  130. package/dist/vendor/codeburn/src/providers/quickdesk.js +491 -0
  131. package/dist/vendor/codeburn/src/providers/qwen.js +193 -0
  132. package/dist/vendor/codeburn/src/providers/session-message.js +118 -0
  133. package/dist/vendor/codeburn/src/providers/sqlite-session-parser.js +457 -0
  134. package/dist/vendor/codeburn/src/providers/types.js +5 -0
  135. package/dist/vendor/codeburn/src/providers/vercel-gateway.js +135 -0
  136. package/dist/vendor/codeburn/src/providers/vscode-cline-parser.js +212 -0
  137. package/dist/vendor/codeburn/src/providers/warp.js +575 -0
  138. package/dist/vendor/codeburn/src/providers/zcode.js +249 -0
  139. package/dist/vendor/codeburn/src/providers/zed.js +187 -0
  140. package/dist/vendor/codeburn/src/providers/zerostack.js +139 -0
  141. package/dist/vendor/codeburn/src/quota/antigravity.js +310 -0
  142. package/dist/vendor/codeburn/src/quota/claude.js +244 -0
  143. package/dist/vendor/codeburn/src/quota/cursor.js +301 -0
  144. package/dist/vendor/codeburn/src/quota/security.js +299 -0
  145. package/dist/vendor/codeburn/src/quota/types.js +1 -0
  146. package/dist/vendor/codeburn/src/scan-facts.js +99 -0
  147. package/dist/vendor/codeburn/src/session-cache.js +3040 -0
  148. package/dist/vendor/codeburn/src/session-count-label.js +14 -0
  149. package/dist/vendor/codeburn/src/session-output.js +139 -0
  150. package/dist/vendor/codeburn/src/session-population.js +30 -0
  151. package/dist/vendor/codeburn/src/sessions-report.js +1342 -0
  152. package/dist/vendor/codeburn/src/sqlite.js +528 -0
  153. package/dist/vendor/codeburn/src/sync/otlp.js +420 -0
  154. package/dist/vendor/codeburn/src/telemetry-snapshot.js +244 -0
  155. package/dist/vendor/codeburn/src/token-estimate.js +5 -0
  156. package/dist/vendor/codeburn/src/types.js +16 -0
  157. package/dist/vendor/codeburn/src/work-units.js +126 -0
  158. package/dist/vendor/codeburn/src/workflow-insights.js +228 -0
  159. package/dist/vendor/codeburn/src/wsl.js +198 -0
  160. package/dist/vendor/codeburn/src/yield.js +666 -0
  161. package/package.json +11 -3
@@ -0,0 +1,1174 @@
1
+ import { existsSync } from 'fs';
2
+ import { readdir, readFile, stat } from 'fs/promises';
3
+ import { basename, dirname, extname, join } from 'path';
4
+ import { homedir } from 'os';
5
+ import { readSessionFile } from '../fs-utils.js';
6
+ import { flatSlice, flatString } from '../content-utils.js';
7
+ import { calculateCost, ownValue } from '../models.js';
8
+ import { estimateTokensFromChars } from '../token-estimate.js';
9
+ // Kiro bills in credits: individual plans are $20/mo for 1,000 credits and
10
+ // overage is billed at $0.04 per additional credit. We price credits at the
11
+ // public overage rate (the marginal price), mirroring the Codebuff provider's
12
+ // USD_PER_CREDIT approach, so we never understate real cost.
13
+ const USD_PER_KIRO_CREDIT = 0.04;
14
+ const MIN_REASONABLE_TIMESTAMP_MS = 1_000_000_000_000;
15
+ const MODERN_CONVERSATION_KEYS = ['messages', 'conversation', 'chat', 'transcript', 'entries', 'events'];
16
+ const modelDisplayNames = {
17
+ 'claude-sonnet-4-6': 'Sonnet 4.6',
18
+ 'claude-sonnet-4-5': 'Sonnet 4.5',
19
+ 'claude-sonnet-4': 'Sonnet 4',
20
+ 'claude-haiku-4-5': 'Haiku 4.5',
21
+ 'claude-3-7-sonnet': 'Sonnet 3.7',
22
+ 'claude-3-5-sonnet': 'Sonnet 3.5',
23
+ 'claude-3-5-haiku': 'Haiku 3.5',
24
+ };
25
+ const modelDisplayEntries = Object.entries(modelDisplayNames).sort((a, b) => b[0].length - a[0].length);
26
+ const toolNameMap = {
27
+ readFile: 'Read',
28
+ read_file: 'Read',
29
+ read: 'Read',
30
+ writeFile: 'Edit',
31
+ write_file: 'Edit',
32
+ write: 'Edit',
33
+ editFile: 'Edit',
34
+ edit_file: 'Edit',
35
+ createFile: 'Write',
36
+ create_file: 'Write',
37
+ deleteFile: 'Delete',
38
+ listDir: 'LS',
39
+ list_dir: 'LS',
40
+ openFolders: 'LS',
41
+ runCommand: 'Bash',
42
+ run_command: 'Bash',
43
+ shell: 'Bash',
44
+ executeBash: 'Bash',
45
+ searchFiles: 'Grep',
46
+ search_files: 'Grep',
47
+ grep: 'Grep',
48
+ grepSearch: 'Grep',
49
+ findFiles: 'Glob',
50
+ find_files: 'Glob',
51
+ glob: 'Glob',
52
+ fileSearch: 'Glob',
53
+ webSearch: 'WebSearch',
54
+ web_search: 'WebSearch',
55
+ web_fetch: 'WebFetch',
56
+ fsWrite: 'Edit',
57
+ strReplace: 'Edit',
58
+ listDirectory: 'LS',
59
+ code: 'Read',
60
+ subagent: 'Agent',
61
+ };
62
+ function normalizeModelId(raw) {
63
+ return raw.replace(/(\d+)\.(\d+)/g, '$1-$2');
64
+ }
65
+ function extractToolNames(content) {
66
+ const tools = [];
67
+ const regex = /<tool_use>\s*<name>([^<]+)<\/name>/g;
68
+ let match;
69
+ while ((match = regex.exec(content)) !== null) {
70
+ const name = match[1].trim();
71
+ // flatString: regex match groups are V8 SlicedStrings that retain the
72
+ // ENTIRE subject string — storing them in the session cache would pin
73
+ // every scanned assistant-content buffer. Mapped names are flat literals.
74
+ tools.push(ownValue(toolNameMap, name) ?? flatString(name));
75
+ }
76
+ return tools;
77
+ }
78
+ function asRecord(value) {
79
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : null;
80
+ }
81
+ function stringField(record, names) {
82
+ if (!record)
83
+ return '';
84
+ for (const name of names) {
85
+ const value = record[name];
86
+ if (typeof value === 'string' && value.trim())
87
+ return value.trim();
88
+ }
89
+ return '';
90
+ }
91
+ function timeField(record, names) {
92
+ if (!record)
93
+ return undefined;
94
+ for (const name of names) {
95
+ const value = record[name];
96
+ if (typeof value === 'number' || typeof value === 'string')
97
+ return value;
98
+ }
99
+ return undefined;
100
+ }
101
+ function parseKiroTimestamp(value) {
102
+ if (value === undefined)
103
+ return null;
104
+ let parsed = value;
105
+ if (typeof value === 'string') {
106
+ const trimmed = value.trim();
107
+ if (!trimmed)
108
+ return null;
109
+ parsed = /^-?\d+(\.\d+)?$/.test(trimmed) ? Number(trimmed) : trimmed;
110
+ }
111
+ if (typeof parsed === 'number') {
112
+ if (!Number.isFinite(parsed))
113
+ return null;
114
+ const ms = parsed < MIN_REASONABLE_TIMESTAMP_MS ? parsed * 1000 : parsed;
115
+ const date = new Date(ms);
116
+ return Number.isNaN(date.getTime()) || date.getTime() < MIN_REASONABLE_TIMESTAMP_MS ? null : date;
117
+ }
118
+ const date = new Date(parsed);
119
+ return Number.isNaN(date.getTime()) || date.getTime() < MIN_REASONABLE_TIMESTAMP_MS ? null : date;
120
+ }
121
+ function textField(record, names) {
122
+ if (!record)
123
+ return '';
124
+ for (const name of names) {
125
+ const text = extractText(record[name]);
126
+ if (text)
127
+ return text;
128
+ }
129
+ return '';
130
+ }
131
+ function extractText(value) {
132
+ if (typeof value === 'string')
133
+ return value;
134
+ if (Array.isArray(value))
135
+ return value.map(extractText).filter(Boolean).join('\n');
136
+ const record = asRecord(value);
137
+ if (!record)
138
+ return '';
139
+ for (const key of ['content', 'text', 'message', 'value', 'parts', 'entries']) {
140
+ const text = extractText(record[key]);
141
+ if (text)
142
+ return text;
143
+ }
144
+ return '';
145
+ }
146
+ function messageRole(value) {
147
+ const record = asRecord(value);
148
+ if (!record)
149
+ return '';
150
+ return stringField(record, ['role', 'type', 'author']).toLowerCase();
151
+ }
152
+ // Reads tool names from structured fields only. Message text is never scanned:
153
+ // it includes tool OUTPUT (file contents, command output) and model prose, so
154
+ // `<tool_use><name>` markup in it is content, not a call - scanning it turned
155
+ // arbitrary private text into tool names that sync sends upstream. The legacy
156
+ // `.chat` format, which has no structured tool record, scans bot messages via
157
+ // extractToolNames in parseChatFile instead.
158
+ function extractStructuredToolNames(value, options = {}) {
159
+ const tools = [];
160
+ const record = asRecord(value);
161
+ if (!record)
162
+ return tools;
163
+ if (options.includeDirectName ?? true) {
164
+ const directName = stringField(record, ['toolName', 'name']);
165
+ if (directName)
166
+ tools.push(ownValue(toolNameMap, directName) ?? directName);
167
+ }
168
+ for (const key of ['toolCalls', 'tool_calls', 'tools']) {
169
+ const entries = record[key];
170
+ if (!Array.isArray(entries))
171
+ continue;
172
+ for (const entry of entries) {
173
+ const name = stringField(asRecord(entry), ['name', 'toolName', 'tool_name']);
174
+ if (name)
175
+ tools.push(ownValue(toolNameMap, name) ?? name);
176
+ }
177
+ }
178
+ return tools;
179
+ }
180
+ function parseChatFile(data, sessionId, project, seenKeys) {
181
+ const results = [];
182
+ const { chat, metadata } = data;
183
+ let modelId = normalizeModelId(metadata.modelId ?? '');
184
+ if (modelId === 'auto' || !modelId)
185
+ modelId = 'kiro-auto';
186
+ let pendingUserMessage = '';
187
+ // Accumulate every human turn's full length for the input-token estimate,
188
+ // mirroring the modern-execution path (which sums inputChars). The prior
189
+ // code estimated input tokens from pendingUserMessage.length alone - the
190
+ // LAST human turn truncated to 500 chars - so a multi-turn session, or any
191
+ // final prompt over 500 chars, undercounted input tokens (and therefore
192
+ // costUSD) severalfold, while output correctly summed all bot chars.
193
+ let inputChars = 0;
194
+ const allTools = [];
195
+ const toolSequence = [];
196
+ for (const msg of chat) {
197
+ if (msg.role === 'human') {
198
+ if (msg.content.startsWith('<identity>'))
199
+ continue;
200
+ inputChars += msg.content.length;
201
+ pendingUserMessage = flatSlice(msg.content, 500);
202
+ }
203
+ if (msg.role === 'bot') {
204
+ const msgTools = extractToolNames(msg.content);
205
+ allTools.push(...msgTools);
206
+ if (msgTools.length > 0)
207
+ toolSequence.push(msgTools.map(t => ({ tool: t })));
208
+ }
209
+ }
210
+ const botMessages = chat.filter(m => m.role === 'bot' && m.content.length > 0);
211
+ const totalOutputChars = botMessages.reduce((sum, m) => sum + m.content.length, 0);
212
+ if (totalOutputChars === 0)
213
+ return results;
214
+ const dedupKey = `kiro:${sessionId}:${data.executionId}`;
215
+ if (seenKeys.has(dedupKey))
216
+ return results;
217
+ const outputTokens = estimateTokensFromChars(totalOutputChars);
218
+ const inputTokens = estimateTokensFromChars(inputChars);
219
+ const costUSD = calculateCost(modelId, inputTokens, outputTokens, 0, 0, 0);
220
+ const tsDate = parseKiroTimestamp(metadata.startTime);
221
+ if (!tsDate)
222
+ return results;
223
+ const timestamp = tsDate.toISOString();
224
+ seenKeys.add(dedupKey);
225
+ results.push({
226
+ provider: 'kiro',
227
+ model: modelId,
228
+ inputTokens,
229
+ outputTokens,
230
+ cacheCreationInputTokens: 0,
231
+ cacheReadInputTokens: 0,
232
+ cachedInputTokens: 0,
233
+ reasoningTokens: 0,
234
+ webSearchRequests: 0,
235
+ costUSD,
236
+ costIsEstimated: true,
237
+ tools: [...new Set(allTools)],
238
+ bashCommands: [],
239
+ toolSequence: toolSequence.length > 1 ? toolSequence : undefined,
240
+ timestamp,
241
+ speed: 'standard',
242
+ deduplicationKey: dedupKey,
243
+ userMessage: pendingUserMessage,
244
+ sessionId,
245
+ });
246
+ return results;
247
+ }
248
+ function parseModernExecution(data, sourcePath, seenKeys) {
249
+ const results = [];
250
+ if (Array.isArray(data['executions']))
251
+ return results;
252
+ const metadata = asRecord(data['metadata']);
253
+ const modelObj = asRecord(data['model']);
254
+ let modelId = normalizeModelId(stringField(data, ['modelId', 'modelID', 'modelName', 'model']) ||
255
+ stringField(modelObj, ['id', 'name']) ||
256
+ stringField(metadata, ['modelId', 'modelID', 'modelName']));
257
+ if (modelId === 'auto' || !modelId)
258
+ modelId = 'kiro-auto';
259
+ const executionId = stringField(data, ['executionId', 'id']) || basename(sourcePath);
260
+ const sessionId = stringField(data, ['sessionId', 'chatSessionId', 'conversationId', 'workflowId']) ||
261
+ stringField(metadata, ['workflowId', 'sessionId']) ||
262
+ basename(dirname(sourcePath)) ||
263
+ executionId;
264
+ let inputChars = 0;
265
+ let outputChars = 0;
266
+ let pendingUserMessage = '';
267
+ const allTools = [];
268
+ let hasOutputActivity = false;
269
+ const directInput = textField(data, ['prompt', 'input', 'userMessage', 'user_message', 'request']);
270
+ const directOutput = textField(data, ['response', 'output', 'assistantMessage', 'assistant_message', 'result']);
271
+ const directTools = extractStructuredToolNames(data, { includeDirectName: false });
272
+ if (directInput) {
273
+ inputChars += directInput.length;
274
+ pendingUserMessage = flatSlice(directInput, 500);
275
+ }
276
+ if (directOutput) {
277
+ outputChars += directOutput.length;
278
+ hasOutputActivity = true;
279
+ }
280
+ if (directTools.length > 0) {
281
+ hasOutputActivity = true;
282
+ allTools.push(...directTools);
283
+ }
284
+ // Check both data.context[key] and data[key] for conversation arrays.
285
+ // Kiro IDE stores messages at data.context.messages in current builds.
286
+ const context = asRecord(data['context']);
287
+ const conversationSources = context ? [context, data] : [data];
288
+ for (const source of conversationSources) {
289
+ let found = false;
290
+ for (const key of MODERN_CONVERSATION_KEYS) {
291
+ const messages = source[key];
292
+ if (!Array.isArray(messages))
293
+ continue;
294
+ for (const message of messages) {
295
+ const text = extractText(message);
296
+ const role = messageRole(message);
297
+ const tools = extractStructuredToolNames(message);
298
+ if (role === 'human' || role === 'user') {
299
+ if (!text)
300
+ continue;
301
+ inputChars += text.length;
302
+ pendingUserMessage = flatSlice(text, 500);
303
+ }
304
+ else if (role === 'bot' || role === 'assistant' || role === 'ai' || role === 'model') {
305
+ if (text)
306
+ outputChars += text.length;
307
+ if (text || tools.length > 0)
308
+ hasOutputActivity = true;
309
+ allTools.push(...tools);
310
+ }
311
+ else if (role === 'tool' || role === 'system') {
312
+ if (text)
313
+ inputChars += text.length;
314
+ allTools.push(...tools);
315
+ }
316
+ }
317
+ found = true;
318
+ break;
319
+ }
320
+ if (found)
321
+ break;
322
+ }
323
+ // Extract tools and metered credits from usageSummary (reliable structured
324
+ // data in current Kiro builds). usageSummary is an array of per-turn entries
325
+ // with optional usedTools and usage (credits, unit "credit") fields — the
326
+ // v1 predecessor of v2's usage_summary.promptTurnSummaries.
327
+ let executionCredits = 0;
328
+ const usageSummary = data['usageSummary'];
329
+ if (Array.isArray(usageSummary)) {
330
+ for (const entry of usageSummary) {
331
+ const rec = asRecord(entry);
332
+ if (!rec)
333
+ continue;
334
+ const usage = rec['usage'];
335
+ if (typeof usage === 'number' && Number.isFinite(usage))
336
+ executionCredits += usage;
337
+ const usedTools = rec['usedTools'];
338
+ if (Array.isArray(usedTools)) {
339
+ for (const tool of usedTools) {
340
+ if (typeof tool === 'string' && tool) {
341
+ // Strip mcp_ prefix for cleaner display (e.g. mcp_aws_sentral_mcp_search_accounts -> aws_sentral_mcp_search_accounts)
342
+ const cleaned = tool.startsWith('mcp_') ? tool.slice(4) : tool;
343
+ allTools.push(ownValue(toolNameMap, cleaned) ?? cleaned);
344
+ hasOutputActivity = true;
345
+ }
346
+ }
347
+ }
348
+ }
349
+ }
350
+ if (!hasOutputActivity)
351
+ return results;
352
+ const dedupKey = `kiro:${sessionId}:${executionId}`;
353
+ if (seenKeys.has(dedupKey))
354
+ return results;
355
+ const rawStartTime = timeField(data, ['startTime', 'createdAt', 'timestamp']) ??
356
+ timeField(metadata, ['startTime', 'createdAt', 'timestamp']);
357
+ const tsDate = parseKiroTimestamp(rawStartTime);
358
+ if (!tsDate)
359
+ return results;
360
+ const inputTokens = estimateTokensFromChars(inputChars);
361
+ const outputTokens = estimateTokensFromChars(outputChars);
362
+ // Prefer real metered credits at the public overage rate; fall back to
363
+ // token-estimated pricing when the execution has no usage data — same
364
+ // contract as the CLI and v2 parsers.
365
+ const costUSD = executionCredits > 0
366
+ ? executionCredits * USD_PER_KIRO_CREDIT
367
+ : calculateCost(modelId, inputTokens, outputTokens, 0, 0, 0);
368
+ seenKeys.add(dedupKey);
369
+ results.push({
370
+ provider: 'kiro',
371
+ model: modelId,
372
+ inputTokens,
373
+ outputTokens,
374
+ cacheCreationInputTokens: 0,
375
+ cacheReadInputTokens: 0,
376
+ cachedInputTokens: 0,
377
+ reasoningTokens: 0,
378
+ webSearchRequests: 0,
379
+ costUSD,
380
+ costIsEstimated: executionCredits === 0,
381
+ tools: [...new Set(allTools)],
382
+ bashCommands: [],
383
+ timestamp: tsDate.toISOString(),
384
+ speed: 'standard',
385
+ deduplicationKey: dedupKey,
386
+ userMessage: pendingUserMessage,
387
+ sessionId,
388
+ });
389
+ return results;
390
+ }
391
+ function parseCliSession(meta, entries, seenKeys) {
392
+ const results = [];
393
+ const sessionId = meta.session_id;
394
+ const project = basename(meta.cwd || '');
395
+ let modelId = meta.session_state?.rts_model_state?.model_info?.model_id ?? 'auto';
396
+ if (modelId === 'auto' || !modelId)
397
+ modelId = 'kiro-auto';
398
+ else
399
+ modelId = normalizeModelId(modelId);
400
+ const turns = meta.session_state?.conversation_metadata?.user_turn_metadatas ?? [];
401
+ // Walk through JSONL entries grouping by prompt turns
402
+ let turnIndex = 0;
403
+ let pendingUserMessage = '';
404
+ let outputChars = 0;
405
+ let inputChars = 0;
406
+ const allTools = [];
407
+ let turnStartTimestamp;
408
+ function flushTurn() {
409
+ if (outputChars === 0)
410
+ return;
411
+ const turnMeta = turns[turnIndex];
412
+ const dedupKey = `kiro-cli:${sessionId}:${turnIndex}`;
413
+ if (seenKeys.has(dedupKey)) {
414
+ turnIndex++;
415
+ return;
416
+ }
417
+ const timestamp = turnMeta?.end_timestamp ?? turnStartTimestamp ?? meta.created_at;
418
+ const tsDate = parseKiroTimestamp(timestamp);
419
+ if (!tsDate) {
420
+ turnIndex++;
421
+ return;
422
+ }
423
+ const inputTokens = estimateTokensFromChars(inputChars);
424
+ const outputTokens = estimateTokensFromChars(outputChars);
425
+ // metering_usage values are credits (unit: "credit"), not dollars —
426
+ // convert at the public overage rate. Gate on credits > 0, not array
427
+ // presence: real sessions carry empty metering_usage arrays (turn still
428
+ // in flight when the meta was written), which must fall back to
429
+ // token-estimated pricing — same contract as the v1-execution and v2
430
+ // parsers.
431
+ const turnCredits = turnMeta?.metering_usage
432
+ ? turnMeta.metering_usage.reduce((sum, m) => sum + m.value, 0)
433
+ : 0;
434
+ const costUSD = turnCredits > 0
435
+ ? turnCredits * USD_PER_KIRO_CREDIT
436
+ : calculateCost(modelId, inputTokens, outputTokens, 0, 0, 0);
437
+ seenKeys.add(dedupKey);
438
+ results.push({
439
+ provider: 'kiro',
440
+ model: modelId,
441
+ inputTokens,
442
+ outputTokens,
443
+ cacheCreationInputTokens: 0,
444
+ cacheReadInputTokens: 0,
445
+ cachedInputTokens: 0,
446
+ reasoningTokens: 0,
447
+ webSearchRequests: 0,
448
+ costUSD,
449
+ costIsEstimated: turnCredits === 0,
450
+ tools: [...new Set(allTools)],
451
+ bashCommands: [],
452
+ timestamp: tsDate.toISOString(),
453
+ speed: 'standard',
454
+ deduplicationKey: dedupKey,
455
+ userMessage: pendingUserMessage,
456
+ sessionId,
457
+ project,
458
+ // workingDirectory is what sync attribution reads; see PROVIDER_PARSE_VERSIONS.kiro.
459
+ ...(meta.cwd ? { projectPath: meta.cwd, workingDirectory: meta.cwd } : {}),
460
+ });
461
+ turnIndex++;
462
+ }
463
+ let isFirstPrompt = true;
464
+ for (const entry of entries) {
465
+ if (entry.kind === 'Prompt') {
466
+ if (!isFirstPrompt) {
467
+ flushTurn();
468
+ pendingUserMessage = '';
469
+ outputChars = 0;
470
+ inputChars = 0;
471
+ allTools.length = 0;
472
+ }
473
+ isFirstPrompt = false;
474
+ const content = entry.data['content'];
475
+ if (Array.isArray(content)) {
476
+ for (const item of content) {
477
+ const rec = asRecord(item);
478
+ if (rec && rec['kind'] === 'text' && typeof rec['data'] === 'string') {
479
+ pendingUserMessage = flatSlice(rec['data'], 500);
480
+ inputChars += rec['data'].length;
481
+ }
482
+ }
483
+ }
484
+ const meta2 = asRecord(entry.data['meta']);
485
+ if (meta2) {
486
+ const ts = meta2['timestamp'];
487
+ if (typeof ts === 'number')
488
+ turnStartTimestamp = new Date(ts * 1000).toISOString();
489
+ }
490
+ }
491
+ else if (entry.kind === 'AssistantMessage') {
492
+ const content = entry.data['content'];
493
+ if (Array.isArray(content)) {
494
+ for (const item of content) {
495
+ const rec = asRecord(item);
496
+ if (!rec)
497
+ continue;
498
+ if (rec['kind'] === 'text' && typeof rec['data'] === 'string') {
499
+ outputChars += rec['data'].length;
500
+ }
501
+ else if (rec['kind'] === 'toolUse') {
502
+ const toolData = asRecord(rec['data']);
503
+ if (toolData) {
504
+ const name = typeof toolData['name'] === 'string' ? toolData['name'] : '';
505
+ if (name)
506
+ allTools.push(ownValue(toolNameMap, name) ?? name);
507
+ }
508
+ }
509
+ }
510
+ }
511
+ }
512
+ else if (entry.kind === 'ToolResults') {
513
+ // Tool results count as input context
514
+ const content = entry.data['content'];
515
+ if (Array.isArray(content)) {
516
+ for (const item of content) {
517
+ const text = extractText(item);
518
+ if (text)
519
+ inputChars += text.length;
520
+ }
521
+ }
522
+ }
523
+ }
524
+ // Flush last turn
525
+ flushTurn();
526
+ return results;
527
+ }
528
+ // --- Kiro IDE workspace-session parser (workspace-sessions/<b64>/<sessionId>.json) ---
529
+ // Newer v1-era Kiro builds store session state here: history[] carries user prompts
530
+ // and assistant messages, some of which are stubs referencing per-execution files
531
+ // (parsed separately by parseModernExecution).
532
+ async function parseWorkspaceSession(record, source, seenKeys) {
533
+ const results = [];
534
+ const historyArr = record['history'];
535
+ if (!Array.isArray(historyArr) || typeof record['sessionId'] !== 'string')
536
+ return results;
537
+ const sessionId = record['sessionId'];
538
+ const modelRaw = stringField(record, ['selectedModel']);
539
+ let modelId = normalizeModelId(modelRaw);
540
+ if (modelId === 'auto' || !modelId)
541
+ modelId = 'kiro-auto';
542
+ let inputChars = 0;
543
+ let outputChars = 0;
544
+ let pendingUserMessage = '';
545
+ const allTools = [];
546
+ let hasExecutionRefs = false;
547
+ let hasRealAssistantContent = false;
548
+ for (const item of historyArr) {
549
+ const rec = asRecord(item);
550
+ if (!rec)
551
+ continue;
552
+ // Track if this session references execution files (which are parsed separately)
553
+ const execBacked = typeof rec['executionId'] === 'string';
554
+ if (execBacked)
555
+ hasExecutionRefs = true;
556
+ const msg = asRecord(rec['message']);
557
+ if (!msg)
558
+ continue;
559
+ const role = stringField(msg, ['role']);
560
+ const text = extractText(msg['content']);
561
+ if (role === 'user' && text) {
562
+ inputChars += text.length;
563
+ pendingUserMessage = flatSlice(text, 500);
564
+ }
565
+ else if (role === 'assistant' && !execBacked && text && text !== 'On it.') {
566
+ // An item carrying an executionId is execution-backed: its content is
567
+ // counted from the execution file, so counting it here would double-count.
568
+ // 'On it.' is the observed placeholder text Kiro writes for such stubs
569
+ // when the executionId rides a separate history item.
570
+ outputChars += text.length;
571
+ hasRealAssistantContent = true;
572
+ }
573
+ }
574
+ // Skip workspace-session entries that are pure execution stubs:
575
+ // they reference executionIds (parsed separately as execution files)
576
+ // and have no real assistant content beyond "On it." placeholders.
577
+ // This avoids double-counting input tokens from both paths.
578
+ if (hasExecutionRefs && !hasRealAssistantContent)
579
+ return results;
580
+ // Skip sessions with no meaningful content
581
+ if (inputChars === 0 && outputChars === 0)
582
+ return results;
583
+ // Use file mtime as timestamp (workspace-session files don't carry startTime).
584
+ // No stat means no usable timestamp: drop the call like the other parse paths.
585
+ let timestamp;
586
+ try {
587
+ const s = await stat(source.path);
588
+ timestamp = new Date(s.mtimeMs).toISOString();
589
+ }
590
+ catch {
591
+ return results;
592
+ }
593
+ const dedupKey = `kiro:ws-session:${sessionId}`;
594
+ if (seenKeys.has(dedupKey))
595
+ return results;
596
+ seenKeys.add(dedupKey);
597
+ const inputTokens = estimateTokensFromChars(inputChars);
598
+ const outputTokens = estimateTokensFromChars(outputChars);
599
+ const costUSD = calculateCost(modelId, inputTokens, outputTokens, 0, 0, 0);
600
+ results.push({
601
+ provider: 'kiro',
602
+ model: modelId,
603
+ inputTokens,
604
+ outputTokens,
605
+ cacheCreationInputTokens: 0,
606
+ cacheReadInputTokens: 0,
607
+ cachedInputTokens: 0,
608
+ reasoningTokens: 0,
609
+ webSearchRequests: 0,
610
+ costUSD,
611
+ costIsEstimated: true,
612
+ tools: [...new Set(allTools)],
613
+ bashCommands: [],
614
+ timestamp,
615
+ speed: 'standard',
616
+ deduplicationKey: dedupKey,
617
+ userMessage: pendingUserMessage,
618
+ sessionId,
619
+ ...(typeof record['workspaceDirectory'] === 'string' && record['workspaceDirectory']
620
+ ? {
621
+ projectPath: record['workspaceDirectory'],
622
+ workingDirectory: record['workspaceDirectory'],
623
+ }
624
+ : {}),
625
+ });
626
+ return results;
627
+ }
628
+ async function parseV2Session(source, seenKeys) {
629
+ const results = [];
630
+ const content = await readSessionFile(source.path);
631
+ if (content === null)
632
+ return results;
633
+ // Companion session.json carries the real model + session metadata.
634
+ let meta = {};
635
+ try {
636
+ const raw = await readFile(join(dirname(source.path), 'session.json'), 'utf-8');
637
+ meta = JSON.parse(raw);
638
+ }
639
+ catch { /* fall back to defaults below */ }
640
+ const sessionId = (typeof meta.id === 'string' && meta.id) || basename(dirname(source.path));
641
+ let modelId = normalizeModelId(meta.modelId ?? '');
642
+ if (modelId === 'auto' || !modelId)
643
+ modelId = 'kiro-auto';
644
+ // In-flight turn state. A turn spans turn_start..turn_end sharing an
645
+ // executionId; the preceding `user` event carries its prompt.
646
+ let pendingUserMessage = '';
647
+ let pendingUserChars = 0;
648
+ let inTurn = false;
649
+ let execId = '';
650
+ let turnStartTs;
651
+ let outputChars = 0;
652
+ let reasoningChars = 0;
653
+ let toolResultChars = 0;
654
+ let turnCredits = 0;
655
+ let turnUserMessage = '';
656
+ let turnUserChars = 0;
657
+ const tools = [];
658
+ const resetTurn = () => {
659
+ inTurn = false;
660
+ execId = '';
661
+ turnStartTs = undefined;
662
+ outputChars = 0;
663
+ reasoningChars = 0;
664
+ toolResultChars = 0;
665
+ turnCredits = 0;
666
+ turnUserMessage = '';
667
+ turnUserChars = 0;
668
+ tools.length = 0;
669
+ };
670
+ const pushTool = (raw) => {
671
+ if (!raw)
672
+ return;
673
+ // Strip mcp_ prefix for cleaner display, matching the modern-execution parser.
674
+ const cleaned = raw.startsWith('mcp_') ? raw.slice(4) : raw;
675
+ tools.push(ownValue(toolNameMap, cleaned) ?? cleaned);
676
+ };
677
+ const flushTurn = () => {
678
+ if (!inTurn) {
679
+ resetTurn();
680
+ return;
681
+ }
682
+ const hasActivity = outputChars > 0 || reasoningChars > 0 || tools.length > 0;
683
+ if (hasActivity) {
684
+ const dedupKey = `kiro-v2:${sessionId}:${execId || String(results.length)}`;
685
+ const tsDate = parseKiroTimestamp(turnStartTs);
686
+ if (tsDate && !seenKeys.has(dedupKey)) {
687
+ seenKeys.add(dedupKey);
688
+ // Tool results are fed back to the model as input context, so count them
689
+ // toward input tokens — same treatment as the CLI parser's ToolResults.
690
+ const inputTokens = estimateTokensFromChars(turnUserChars + toolResultChars);
691
+ // outputTokens and reasoningTokens are kept disjoint — downstream
692
+ // aggregation (models-report, audit-report, parser) sums the two
693
+ // fields, so folding reasoning into outputTokens would double-count.
694
+ const reasoningTokens = estimateTokensFromChars(reasoningChars);
695
+ const outputTokens = estimateTokensFromChars(outputChars);
696
+ // Prefer real metered credits (converted at the public overage rate)
697
+ // over token estimation; fall back to token pricing when the turn has
698
+ // no usage_summary (e.g. still in progress or null usage). Reasoning
699
+ // text is billed as output, so combine it for pricing only (same as
700
+ // the codex provider).
701
+ const costUSD = turnCredits > 0
702
+ ? turnCredits * USD_PER_KIRO_CREDIT
703
+ : calculateCost(modelId, inputTokens, outputTokens + reasoningTokens, 0, 0, 0);
704
+ results.push({
705
+ provider: 'kiro',
706
+ model: modelId,
707
+ inputTokens,
708
+ outputTokens,
709
+ cacheCreationInputTokens: 0,
710
+ cacheReadInputTokens: 0,
711
+ cachedInputTokens: 0,
712
+ reasoningTokens,
713
+ webSearchRequests: 0,
714
+ costUSD,
715
+ costIsEstimated: turnCredits === 0,
716
+ tools: [...new Set(tools)],
717
+ bashCommands: [],
718
+ timestamp: tsDate.toISOString(),
719
+ speed: 'standard',
720
+ deduplicationKey: dedupKey,
721
+ userMessage: turnUserMessage,
722
+ sessionId,
723
+ project: source.project,
724
+ ...(meta.workspacePaths?.[0]
725
+ ? { projectPath: meta.workspacePaths[0], workingDirectory: meta.workspacePaths[0] }
726
+ : {}),
727
+ });
728
+ }
729
+ }
730
+ resetTurn();
731
+ };
732
+ for (const line of content.split('\n')) {
733
+ if (!line.trim())
734
+ continue;
735
+ let evt;
736
+ try {
737
+ evt = JSON.parse(line);
738
+ }
739
+ catch {
740
+ continue;
741
+ }
742
+ const payload = asRecord(evt['payload']);
743
+ if (!payload)
744
+ continue;
745
+ const type = stringField(payload, ['type']);
746
+ const ts = typeof evt['timestamp'] === 'string' ? evt['timestamp'] : undefined;
747
+ if (type === 'user') {
748
+ // New prompt: close any in-flight turn defensively, then stash the text
749
+ // for the upcoming turn_start.
750
+ if (inTurn)
751
+ flushTurn();
752
+ const text = typeof payload['content'] === 'string' ? payload['content'] : extractText(payload['content']);
753
+ pendingUserMessage = flatSlice(text, 500);
754
+ pendingUserChars = text.length;
755
+ }
756
+ else if (type === 'turn_start') {
757
+ if (inTurn)
758
+ flushTurn();
759
+ inTurn = true;
760
+ execId = stringField(payload, ['executionId']);
761
+ turnStartTs = ts;
762
+ turnUserMessage = pendingUserMessage;
763
+ turnUserChars = pendingUserChars;
764
+ pendingUserMessage = '';
765
+ pendingUserChars = 0;
766
+ }
767
+ else if (type === 'assistant') {
768
+ const text = typeof payload['content'] === 'string' ? payload['content'] : extractText(payload['content']);
769
+ if (stringField(payload, ['operationType']) === 'Reasoning')
770
+ reasoningChars += text.length;
771
+ else
772
+ outputChars += text.length;
773
+ if (!inTurn && text.length > 0)
774
+ inTurn = true;
775
+ if (!turnStartTs && ts)
776
+ turnStartTs = ts;
777
+ }
778
+ else if (type === 'tool_call') {
779
+ pushTool(stringField(payload, ['toolName', 'name']));
780
+ }
781
+ else if (type === 'tool_result') {
782
+ // Tool output re-enters the model as context on the next inference call.
783
+ // content is a plain string in observed logs; extractText covers nesting.
784
+ const text = typeof payload['content'] === 'string' ? payload['content'] : extractText(payload['content']);
785
+ toolResultChars += text.length;
786
+ }
787
+ else if (type === 'usage_summary') {
788
+ // usedTools is a reliable per-turn tool list. Credits are the real billed
789
+ // usage (promptTurnSummaries[].usage with unit "credit") — harvest them
790
+ // for credit-based cost. usage can be null on some turns.
791
+ const summaries = payload['promptTurnSummaries'];
792
+ if (Array.isArray(summaries)) {
793
+ for (const s of summaries) {
794
+ const rec = asRecord(s);
795
+ const used = rec?.['usedTools'];
796
+ if (Array.isArray(used))
797
+ for (const u of used)
798
+ if (typeof u === 'string')
799
+ pushTool(u);
800
+ const usage = rec?.['usage'];
801
+ if (typeof usage === 'number' && Number.isFinite(usage))
802
+ turnCredits += usage;
803
+ }
804
+ }
805
+ }
806
+ else if (type === 'turn_end') {
807
+ flushTurn();
808
+ }
809
+ }
810
+ // Flush a trailing in-progress turn (session still active, no turn_end yet).
811
+ flushTurn();
812
+ return results;
813
+ }
814
+ function createParser(source, seenKeys) {
815
+ return {
816
+ async *parse() {
817
+ // v2 IDE store: ~/.kiro/sessions/<hash>/sess_<id>/messages.jsonl — a
818
+ // self-contained event log. Must be checked BEFORE the generic .jsonl
819
+ // (CLI) branch, since it also ends in .jsonl but has a different schema.
820
+ if (/[/\\]sess_[^/\\]+[/\\]messages\.jsonl$/.test(source.path)) {
821
+ for (const call of await parseV2Session(source, seenKeys))
822
+ yield call;
823
+ return;
824
+ }
825
+ // CLI session: path points to a .jsonl file
826
+ if (source.path.endsWith('.jsonl')) {
827
+ const jsonlContent = await readSessionFile(source.path);
828
+ if (jsonlContent === null)
829
+ return;
830
+ const entries = [];
831
+ for (const line of jsonlContent.split('\n')) {
832
+ if (!line.trim())
833
+ continue;
834
+ try {
835
+ entries.push(JSON.parse(line));
836
+ }
837
+ catch { /* skip malformed lines */ }
838
+ }
839
+ if (entries.length === 0)
840
+ return;
841
+ // Load companion .json for metadata
842
+ const metaPath = source.path.replace(/\.jsonl$/, '.json');
843
+ let meta;
844
+ try {
845
+ const raw = await readFile(metaPath, 'utf-8');
846
+ meta = JSON.parse(raw);
847
+ }
848
+ catch {
849
+ // Minimal fallback
850
+ meta = { session_id: basename(source.path, '.jsonl'), cwd: '', created_at: '', updated_at: '' };
851
+ }
852
+ for (const call of parseCliSession(meta, entries, seenKeys)) {
853
+ yield call;
854
+ }
855
+ return;
856
+ }
857
+ // IDE session: original path
858
+ const content = await readSessionFile(source.path);
859
+ if (content === null)
860
+ return;
861
+ let data;
862
+ try {
863
+ data = JSON.parse(content);
864
+ }
865
+ catch {
866
+ return;
867
+ }
868
+ const record = asRecord(data);
869
+ if (!record)
870
+ return;
871
+ // Workspace-session files (newer Kiro builds): have history[] with message.role/content
872
+ // and a top-level sessionId/selectedModel/workspaceDirectory.
873
+ if (Array.isArray(record['history']) && typeof record['sessionId'] === 'string') {
874
+ for (const call of await parseWorkspaceSession(record, source, seenKeys))
875
+ yield call;
876
+ return;
877
+ }
878
+ const metadata = asRecord(record['metadata']);
879
+ const calls = Array.isArray(record['chat']) && metadata
880
+ ? parseChatFile(record, stringField(metadata, ['workflowId']) || basename(source.path, '.chat'), source.project, seenKeys)
881
+ : parseModernExecution(record, source.path, seenKeys);
882
+ for (const call of calls) {
883
+ yield call;
884
+ }
885
+ },
886
+ };
887
+ }
888
+ // --- Discovery ---
889
+ // Pre-filter candidate list shared by probeRoots and discovery. Must not
890
+ // existsSync-filter: Linux discovery still trims in getKiroAgentDir, but
891
+ // doctor has to report missing defaults. Empty / blank override is unset.
892
+ export function getKiroAgentDirCandidates(override) {
893
+ if (override)
894
+ return [override];
895
+ if (process.platform === 'darwin') {
896
+ return [join(homedir(), 'Library', 'Application Support', 'Kiro', 'User', 'globalStorage', 'kiro.kiroagent')];
897
+ }
898
+ if (process.platform === 'win32') {
899
+ return [join(homedir(), 'AppData', 'Roaming', 'Kiro', 'User', 'globalStorage', 'kiro.kiroagent')];
900
+ }
901
+ return [
902
+ join(homedir(), '.kiro-server', 'data', 'User', 'globalStorage', 'kiro.kiroagent'),
903
+ join(homedir(), '.config', 'Kiro', 'User', 'globalStorage', 'kiro.kiroagent'),
904
+ ];
905
+ }
906
+ function getKiroAgentDir(override) {
907
+ const candidates = getKiroAgentDirCandidates(override);
908
+ if (override || process.platform !== 'linux')
909
+ return candidates;
910
+ // On Linux, scan both ~/.kiro-server/data/... (remote dev boxes) and
911
+ // ~/.config/Kiro/... (local installs). Both can have data simultaneously
912
+ // if the user switches between local and remote, or if .kiro-server exists
913
+ // but is stale while .config/Kiro has current sessions.
914
+ const existing = candidates.filter(p => existsSync(p));
915
+ return existing.length > 0 ? existing : [candidates[candidates.length - 1]];
916
+ }
917
+ function getKiroWorkspaceStorageDir(override) {
918
+ if (override)
919
+ return override;
920
+ if (process.platform === 'darwin') {
921
+ return join(homedir(), 'Library', 'Application Support', 'Kiro', 'User', 'workspaceStorage');
922
+ }
923
+ if (process.platform === 'win32') {
924
+ return join(homedir(), 'AppData', 'Roaming', 'Kiro', 'User', 'workspaceStorage');
925
+ }
926
+ return join(homedir(), '.config', 'Kiro', 'User', 'workspaceStorage');
927
+ }
928
+ async function readWorkspaceProject(workspaceDir) {
929
+ try {
930
+ const raw = await readFile(join(workspaceDir, 'workspace.json'), 'utf-8');
931
+ const data = JSON.parse(raw);
932
+ if (data.folder) {
933
+ const url = data.folder.replace(/^file:\/\//, '');
934
+ return basename(decodeURIComponent(url));
935
+ }
936
+ }
937
+ catch { }
938
+ return basename(workspaceDir);
939
+ }
940
+ async function resolveWorkspaceProject(agentDir, workspaceStorageDir, workspaceHash) {
941
+ const wsDir = join(workspaceStorageDir, workspaceHash);
942
+ const project = await readWorkspaceProject(wsDir);
943
+ if (project !== workspaceHash)
944
+ return project;
945
+ try {
946
+ const sessionsPath = join(agentDir, 'workspace-sessions');
947
+ const dirs = await readdir(sessionsPath);
948
+ for (const dir of dirs) {
949
+ const decoded = Buffer.from(dir.replace(/_$/, ''), 'base64').toString('utf-8');
950
+ if (decoded)
951
+ return basename(decoded);
952
+ }
953
+ }
954
+ catch { }
955
+ return workspaceHash;
956
+ }
957
+ async function discoverSessions(agentDir, workspaceStorageDir, cliSessionsDir) {
958
+ const sources = [];
959
+ // --- Kiro CLI sessions (~/.kiro/sessions/cli/) ---
960
+ // Empty CLI is skipped (do not readdir '' or '.'). Same skip in probeRoots.
961
+ if (cliSessionsDir) {
962
+ try {
963
+ const cliEntries = await readdir(cliSessionsDir, { withFileTypes: true });
964
+ for (const entry of cliEntries) {
965
+ if (!entry.isFile() || !entry.name.endsWith('.jsonl'))
966
+ continue;
967
+ const jsonlPath = join(cliSessionsDir, entry.name);
968
+ // Derive project from companion .json
969
+ const metaPath = jsonlPath.replace(/\.jsonl$/, '.json');
970
+ let project = 'kiro-cli';
971
+ try {
972
+ const raw = await readFile(metaPath, 'utf-8');
973
+ const meta = JSON.parse(raw);
974
+ if (meta.cwd)
975
+ project = basename(meta.cwd);
976
+ }
977
+ catch { }
978
+ sources.push({ path: jsonlPath, project, provider: 'kiro' });
979
+ }
980
+ }
981
+ catch { }
982
+ }
983
+ // --- Kiro IDE sessions ---
984
+ let workspaceDirs;
985
+ try {
986
+ const entries = await readdir(agentDir, { withFileTypes: true });
987
+ workspaceDirs = entries.filter(e => e.isDirectory() && e.name.length === 32).map(e => e.name);
988
+ }
989
+ catch {
990
+ return sources;
991
+ }
992
+ for (const wsHash of workspaceDirs) {
993
+ const wsPath = join(agentDir, wsHash);
994
+ const project = await resolveWorkspaceProject(agentDir, workspaceStorageDir, wsHash);
995
+ let entries;
996
+ try {
997
+ entries = await readdir(wsPath, { withFileTypes: true });
998
+ }
999
+ catch {
1000
+ continue;
1001
+ }
1002
+ for (const entry of entries) {
1003
+ if (entry.name.startsWith('.'))
1004
+ continue;
1005
+ const entryPath = join(wsPath, entry.name);
1006
+ if (entry.isFile() && (entry.name.endsWith('.chat') || extname(entry.name) === '')) {
1007
+ sources.push({ path: entryPath, project, provider: 'kiro' });
1008
+ continue;
1009
+ }
1010
+ if (!entry.isDirectory())
1011
+ continue;
1012
+ const childEntries = await readdir(entryPath, { withFileTypes: true }).catch(() => []);
1013
+ for (const child of childEntries) {
1014
+ if (child.name.startsWith('.'))
1015
+ continue;
1016
+ if (!child.isFile())
1017
+ continue;
1018
+ if (extname(child.name) !== '')
1019
+ continue;
1020
+ sources.push({ path: join(entryPath, child.name), project, provider: 'kiro' });
1021
+ }
1022
+ }
1023
+ }
1024
+ // --- Kiro IDE workspace-sessions (newer builds store session state here) ---
1025
+ // These files contain history[].message with user prompts and assistant stubs
1026
+ // plus executionId references. They capture sessions not written as per-execution files.
1027
+ try {
1028
+ const wsSessionsDir = join(agentDir, 'workspace-sessions');
1029
+ const wsSessionDirs = await readdir(wsSessionsDir, { withFileTypes: true });
1030
+ for (const dir of wsSessionDirs) {
1031
+ if (!dir.isDirectory())
1032
+ continue;
1033
+ // Directory name is base64-encoded workspace path
1034
+ let project = 'kiro-ide';
1035
+ try {
1036
+ const decoded = Buffer.from(dir.name.replace(/_/g, '='), 'base64').toString('utf-8');
1037
+ if (decoded)
1038
+ project = basename(decoded);
1039
+ }
1040
+ catch { }
1041
+ // Skip bare homedir as project name
1042
+ if (project === basename(homedir()))
1043
+ project = 'kiro-ide';
1044
+ const sessionFiles = await readdir(join(wsSessionsDir, dir.name), { withFileTypes: true }).catch(() => []);
1045
+ for (const sf of sessionFiles) {
1046
+ if (!sf.isFile() || !sf.name.endsWith('.json') || sf.name === 'sessions.json')
1047
+ continue;
1048
+ sources.push({ path: join(wsSessionsDir, dir.name, sf.name), project, provider: 'kiro' });
1049
+ }
1050
+ }
1051
+ }
1052
+ catch { }
1053
+ return sources;
1054
+ }
1055
+ // Discover v2 IDE sessions under ~/.kiro/sessions/<workspaceHash>/sess_*/.
1056
+ // Each session is a self-contained directory (session.json + messages.jsonl);
1057
+ // the emitted source points at messages.jsonl and routes to parseV2Session.
1058
+ async function discoverV2Sessions(sessionsRoot) {
1059
+ const sources = [];
1060
+ let hashDirs;
1061
+ try {
1062
+ hashDirs = await readdir(sessionsRoot, { withFileTypes: true });
1063
+ }
1064
+ catch {
1065
+ return sources;
1066
+ }
1067
+ for (const hd of hashDirs) {
1068
+ // Skip the CLI store (scanned separately) and any stray files.
1069
+ if (!hd.isDirectory() || hd.name === 'cli')
1070
+ continue;
1071
+ const hashPath = join(sessionsRoot, hd.name);
1072
+ let sessDirs;
1073
+ try {
1074
+ sessDirs = await readdir(hashPath, { withFileTypes: true });
1075
+ }
1076
+ catch {
1077
+ continue;
1078
+ }
1079
+ for (const sd of sessDirs) {
1080
+ if (!sd.isDirectory() || !sd.name.startsWith('sess_'))
1081
+ continue;
1082
+ const sessDir = join(hashPath, sd.name);
1083
+ const messagesPath = join(sessDir, 'messages.jsonl');
1084
+ if (!existsSync(messagesPath))
1085
+ continue;
1086
+ // Project from session.json workspacePaths; fall back to a generic label.
1087
+ let project = 'kiro-ide';
1088
+ try {
1089
+ const raw = await readFile(join(sessDir, 'session.json'), 'utf-8');
1090
+ const sj = JSON.parse(raw);
1091
+ const wp = sj.workspacePaths?.[0];
1092
+ if (wp)
1093
+ project = basename(wp);
1094
+ }
1095
+ catch { }
1096
+ if (project === basename(homedir()))
1097
+ project = 'kiro-ide';
1098
+ sources.push({ path: messagesPath, project, provider: 'kiro' });
1099
+ }
1100
+ }
1101
+ return sources;
1102
+ }
1103
+ export function createKiroProvider(agentDirOverride, workspaceStorageDirOverride, cliSessionsDirOverride, v2SessionsRootOverride) {
1104
+ const agentCandidates = getKiroAgentDirCandidates(agentDirOverride);
1105
+ const agentDirs = getKiroAgentDir(agentDirOverride);
1106
+ const wsDir = getKiroWorkspaceStorageDir(workspaceStorageDirOverride);
1107
+ const defaultCliDir = join(process.env['KIRO_HOME'] || join(homedir(), '.kiro'), 'sessions', 'cli');
1108
+ // Empty CLI is skipped (do not report '' or '.'). Same skip in discoverSessions.
1109
+ const cliDir = cliSessionsDirOverride === ''
1110
+ ? undefined
1111
+ : cliSessionsDirOverride ?? (agentDirOverride ? join(agentDirOverride, '..', 'cli-sessions') : defaultCliDir);
1112
+ // v2 IDE sessions live under ~/.kiro/sessions/<hash>/sess_*/, a sibling of the
1113
+ // CLI store (.../sessions/cli). Derive the root from an explicit CLI override
1114
+ // or the default CLI parent. Empty CLI does not drop default v2; empty v2
1115
+ // is skipped on its own. When only agentDirOverride is set (tests), do not
1116
+ // derive v2 from the test tmpdir.
1117
+ const v2Root = v2SessionsRootOverride === ''
1118
+ ? undefined
1119
+ : v2SessionsRootOverride ??
1120
+ (cliSessionsDirOverride ? dirname(cliSessionsDirOverride) :
1121
+ agentDirOverride ? undefined : dirname(defaultCliDir));
1122
+ return {
1123
+ name: 'kiro',
1124
+ displayName: 'Kiro',
1125
+ modelDisplayName(model) {
1126
+ if (model === 'kiro-auto')
1127
+ return 'Kiro (auto)';
1128
+ for (const [key, name] of modelDisplayEntries) {
1129
+ if (model === key || model.startsWith(key + '-'))
1130
+ return name;
1131
+ }
1132
+ return model;
1133
+ },
1134
+ toolDisplayName(rawTool) {
1135
+ if (rawTool.startsWith('mcp__'))
1136
+ return rawTool;
1137
+ return ownValue(toolNameMap, rawTool) ?? rawTool;
1138
+ },
1139
+ async probeRoots() {
1140
+ const roots = [
1141
+ ...agentCandidates.map(path => ({ path, label: 'agent' })),
1142
+ { path: wsDir, label: 'workspace' },
1143
+ ];
1144
+ if (cliDir)
1145
+ roots.push({ path: cliDir, label: 'cli' });
1146
+ if (v2Root)
1147
+ roots.push({ path: v2Root, label: 'v2' });
1148
+ return roots;
1149
+ },
1150
+ async discoverSessions() {
1151
+ const allSources = [];
1152
+ for (const agentDir of agentDirs) {
1153
+ const sources = await discoverSessions(agentDir, wsDir, cliDir);
1154
+ allSources.push(...sources);
1155
+ }
1156
+ // v2 IDE sessions: scan the resolved v2 root (undefined = skip, see above).
1157
+ if (v2Root)
1158
+ allSources.push(...await discoverV2Sessions(v2Root));
1159
+ // CLI sessions are only scanned once (first agentDir pass includes them);
1160
+ // deduplicate by path in case multiple agentDirs share the same CLI dir.
1161
+ const seen = new Set();
1162
+ return allSources.filter(s => {
1163
+ if (seen.has(s.path))
1164
+ return false;
1165
+ seen.add(s.path);
1166
+ return true;
1167
+ });
1168
+ },
1169
+ createSessionParser(source, seenKeys) {
1170
+ return createParser(source, seenKeys);
1171
+ },
1172
+ };
1173
+ }
1174
+ export const kiro = createKiroProvider();