@katlux/toolkit 0.1.1-alpha.146 → 0.1.1-alpha.147

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 (231) hide show
  1. package/README.md +32 -22
  2. package/bin/ai-init.mjs +71 -13
  3. package/bin/ai-tokens/adapters/antigravityAdapter.mjs +22 -0
  4. package/bin/ai-tokens/adapters/claudeCodeAdapter.mjs +192 -0
  5. package/bin/ai-tokens/adapters/codexAdapter.mjs +176 -0
  6. package/bin/ai-tokens/adapters/cursorAdapter.mjs +202 -0
  7. package/bin/ai-tokens/adapters/index.mjs +30 -0
  8. package/bin/ai-tokens/cliViews.mjs +301 -0
  9. package/bin/ai-tokens/formatAndDates.mjs +89 -0
  10. package/bin/ai-tokens/reportGenerator.mjs +232 -0
  11. package/bin/ai-tokens/transcriptParser.mjs +299 -0
  12. package/bin/ai-tokens.mjs +38 -1030
  13. package/bin/cli.mjs +14 -10
  14. package/bin/preset-contracts.json +66 -10
  15. package/dist/compiled/composables/locales/asianAndPacific.mjs +296 -0
  16. package/dist/compiled/composables/locales/northernAndEasternEuropean.mjs +342 -0
  17. package/dist/compiled/composables/locales/westernEuropean.mjs +268 -0
  18. package/dist/compiled/composables/locales.mjs +28 -895
  19. package/dist/compiled/composables/useDataProvider.mjs +3 -1
  20. package/dist/compiled/composables/useKatluxForm.mjs +7 -7
  21. package/dist/compiled/composables/usePresetComponent.mjs +2 -0
  22. package/dist/compiled/composables/useRequestQueue.mjs +3 -1
  23. package/dist/compiled/composables/useVirtualDataset.mjs +322 -354
  24. package/dist/compiled/composables/useVirtualScroll.mjs +69 -62
  25. package/dist/compiled/composables/virtualDataset/cacheStateHelpers.mjs +76 -0
  26. package/dist/compiled/composables/virtualDataset/keyboardNavHelpers.mjs +60 -0
  27. package/dist/compiled/composables/virtualDataset/treeSelectionHelpers.mjs +103 -0
  28. package/dist/compiled/composables/virtualDataset/types.mjs +0 -0
  29. package/dist/compiled/utils/deprecation.mjs +44 -0
  30. package/dist/compiled/utils/dom.mjs +124 -0
  31. package/dist/module.cjs +0 -5
  32. package/dist/module.json +1 -1
  33. package/dist/module.mjs +1 -6
  34. package/dist/runtime/app.config.d.ts +3 -0
  35. package/dist/runtime/components/KAccordion/KAccordion.global.d.vue.ts +1 -1
  36. package/dist/runtime/components/KAccordion/KAccordion.global.vue.d.ts +1 -1
  37. package/dist/runtime/components/KBulkActions/KBulkActions.logic.d.ts +8 -0
  38. package/dist/runtime/components/KBulkActions/KBulkActions.logic.js +21 -55
  39. package/dist/runtime/components/KButton/KButton.global.d.vue.ts +2 -2
  40. package/dist/runtime/components/KButton/KButton.global.vue.d.ts +2 -2
  41. package/dist/runtime/components/KButton/KButton.logic.d.ts +1 -1
  42. package/dist/runtime/components/KCalendar/KCalendar.global.d.vue.ts +4 -4
  43. package/dist/runtime/components/KCalendar/KCalendar.global.vue.d.ts +4 -4
  44. package/dist/runtime/components/KCalendar/KCalendar.logic.js +8 -4
  45. package/dist/runtime/components/KCalendar/KCalendarMonth.global.vue +4 -0
  46. package/dist/runtime/components/KCalendar/KCalendarMonth.logic.d.ts +2 -0
  47. package/dist/runtime/components/KCalendar/KCalendarMonth.logic.js +41 -26
  48. package/dist/runtime/components/KCalendar/recurringUtils.js +6 -5
  49. package/dist/runtime/components/KCheckbox/KCheckbox.global.d.vue.ts +1 -1
  50. package/dist/runtime/components/KCheckbox/KCheckbox.global.vue.d.ts +1 -1
  51. package/dist/runtime/components/KCombobox/KCombobox.global.d.vue.ts +17 -2
  52. package/dist/runtime/components/KCombobox/KCombobox.global.vue +9 -4
  53. package/dist/runtime/components/KCombobox/KCombobox.global.vue.d.ts +17 -2
  54. package/dist/runtime/components/KCombobox/KCombobox.logic.d.ts +10 -2
  55. package/dist/runtime/components/KCombobox/KCombobox.logic.js +32 -13
  56. package/dist/runtime/components/KCompositeInput/KCompositeInput.global.d.vue.ts +7 -7
  57. package/dist/runtime/components/KCompositeInput/KCompositeInput.global.vue.d.ts +7 -7
  58. package/dist/runtime/components/KCompositeInput/KCompositeInput.logic.d.ts +3 -3
  59. package/dist/runtime/components/KContextMenu/KContextMenu.global.d.vue.ts +3 -3
  60. package/dist/runtime/components/KContextMenu/KContextMenu.global.vue +4 -1
  61. package/dist/runtime/components/KContextMenu/KContextMenu.global.vue.d.ts +3 -3
  62. package/dist/runtime/components/KContextMenu/KContextMenu.logic.d.ts +24 -4
  63. package/dist/runtime/components/KContextMenu/KContextMenu.logic.js +43 -27
  64. package/dist/runtime/components/KDatatable/KDataIterator.global.d.vue.ts +25 -2
  65. package/dist/runtime/components/KDatatable/KDataIterator.global.vue +19 -7
  66. package/dist/runtime/components/KDatatable/KDataIterator.global.vue.d.ts +25 -2
  67. package/dist/runtime/components/KDatatable/KDataIterator.logic.d.ts +20 -0
  68. package/dist/runtime/components/KDatatable/KDataIterator.logic.js +54 -14
  69. package/dist/runtime/components/KDatatable/KDatatable.global.d.vue.ts +1 -1
  70. package/dist/runtime/components/KDatatable/KDatatable.global.vue.d.ts +1 -1
  71. package/dist/runtime/components/KDatatable/KDatatable.logic.js +6 -5
  72. package/dist/runtime/components/KDatePicker/KDatePicker.global.d.vue.ts +5 -3
  73. package/dist/runtime/components/KDatePicker/KDatePicker.global.vue +45 -26
  74. package/dist/runtime/components/KDatePicker/KDatePicker.global.vue.d.ts +5 -3
  75. package/dist/runtime/components/KDatePicker/KDatePicker.logic.d.ts +2 -0
  76. package/dist/runtime/components/KDatePicker/KDatePicker.logic.js +66 -20
  77. package/dist/runtime/components/KDateTimePicker/KDateTimePicker.global.d.vue.ts +2 -2
  78. package/dist/runtime/components/KDateTimePicker/KDateTimePicker.global.vue.d.ts +2 -2
  79. package/dist/runtime/components/KDropdown/KDropdown.global.d.vue.ts +4 -4
  80. package/dist/runtime/components/KDropdown/KDropdown.global.vue.d.ts +4 -4
  81. package/dist/runtime/components/KDropdown/KDropdown.logic.d.ts +3 -2
  82. package/dist/runtime/components/KDropdown/KDropdown.logic.js +14 -13
  83. package/dist/runtime/components/KGantt/KGantt.global.d.vue.ts +3 -1
  84. package/dist/runtime/components/KGantt/KGantt.global.vue +7 -1
  85. package/dist/runtime/components/KGantt/KGantt.global.vue.d.ts +3 -1
  86. package/dist/runtime/components/KGrid/KGrid.global.d.vue.ts +1 -1
  87. package/dist/runtime/components/KGrid/KGrid.global.vue.d.ts +1 -1
  88. package/dist/runtime/components/KHourPicker/KHourPicker.global.d.vue.ts +1 -1
  89. package/dist/runtime/components/KHourPicker/KHourPicker.global.vue.d.ts +1 -1
  90. package/dist/runtime/components/KIcon/KIcon.global.d.vue.ts +1 -1
  91. package/dist/runtime/components/KIcon/KIcon.global.vue.d.ts +1 -1
  92. package/dist/runtime/components/KLayout/KLayout.global.d.vue.ts +4 -1
  93. package/dist/runtime/components/KLayout/KLayout.global.vue +4 -1
  94. package/dist/runtime/components/KLayout/KLayout.global.vue.d.ts +4 -1
  95. package/dist/runtime/components/KLoader/KLoader.global.d.vue.ts +9 -0
  96. package/dist/runtime/components/KLoader/KLoader.global.vue +1 -0
  97. package/dist/runtime/components/KLoader/KLoader.global.vue.d.ts +9 -0
  98. package/dist/runtime/components/KLoader/KLoader.logic.d.ts +5 -0
  99. package/dist/runtime/components/KLoader/KLoader.logic.js +4 -0
  100. package/dist/runtime/components/KMaskTextbox/KMaskTextbox.global.d.vue.ts +1 -1
  101. package/dist/runtime/components/KMaskTextbox/KMaskTextbox.global.vue.d.ts +1 -1
  102. package/dist/runtime/components/KMaskTextbox/KMaskTextbox.logic.js +30 -7
  103. package/dist/runtime/components/KMultiTabs/KMultiTabs.logic.d.ts +1 -0
  104. package/dist/runtime/components/KMultiTabs/MultiTabs.global.vue +6 -4
  105. package/dist/runtime/components/KPagination/KPagination.logic.d.ts +1 -1
  106. package/dist/runtime/components/KPagination/KPagination.logic.js +17 -9
  107. package/dist/runtime/components/KRadiobox/KRadiobox.global.d.vue.ts +1 -1
  108. package/dist/runtime/components/KRadiobox/KRadiobox.global.vue.d.ts +1 -1
  109. package/dist/runtime/components/KTabs/KTabs.logic.js +33 -11
  110. package/dist/runtime/components/KTextarea/KTextarea.global.d.vue.ts +2 -2
  111. package/dist/runtime/components/KTextarea/KTextarea.global.vue.d.ts +2 -2
  112. package/dist/runtime/components/KTextbox/KTextbox.global.d.vue.ts +14 -3
  113. package/dist/runtime/components/KTextbox/KTextbox.global.vue +8 -2
  114. package/dist/runtime/components/KTextbox/KTextbox.global.vue.d.ts +14 -3
  115. package/dist/runtime/components/KTextbox/KTextbox.logic.d.ts +5 -0
  116. package/dist/runtime/components/KTextbox/KTextbox.logic.js +4 -0
  117. package/dist/runtime/components/KTooltip/KTooltip.global.d.vue.ts +1 -1
  118. package/dist/runtime/components/KTooltip/KTooltip.global.vue.d.ts +1 -1
  119. package/dist/runtime/components/KTooltip/KTooltip.logic.d.ts +11 -2
  120. package/dist/runtime/components/KTooltip/KTooltip.logic.js +7 -5
  121. package/dist/runtime/components/KTree/KTree.global.d.vue.ts +1 -1
  122. package/dist/runtime/components/KTree/KTree.global.vue.d.ts +1 -1
  123. package/dist/runtime/components/KTree/KTree.logic.js +21 -1
  124. package/dist/runtime/components/KTreePicker/KTreePicker.global.d.vue.ts +8 -4
  125. package/dist/runtime/components/KTreePicker/KTreePicker.global.vue +4 -2
  126. package/dist/runtime/components/KTreePicker/KTreePicker.global.vue.d.ts +8 -4
  127. package/dist/runtime/components/KTreePicker/KTreePicker.logic.d.ts +3 -2
  128. package/dist/runtime/components/KTreePicker/KTreePicker.logic.js +10 -1
  129. package/dist/runtime/components/KTreeView/KTreeView.global.d.vue.ts +3 -3
  130. package/dist/runtime/components/KTreeView/KTreeView.global.vue.d.ts +3 -3
  131. package/dist/runtime/components/KTreeView/KTreeView.logic.d.ts +1 -1
  132. package/dist/runtime/components/KTreeView/KTreeView.logic.js +36 -12
  133. package/dist/runtime/composables/locales/asianAndPacific.d.ts +11 -0
  134. package/dist/runtime/composables/locales/asianAndPacific.js +296 -0
  135. package/dist/runtime/composables/locales/northernAndEasternEuropean.d.ts +12 -0
  136. package/dist/runtime/composables/locales/northernAndEasternEuropean.js +342 -0
  137. package/dist/runtime/composables/locales/westernEuropean.d.ts +10 -0
  138. package/dist/runtime/composables/locales/westernEuropean.js +268 -0
  139. package/dist/runtime/composables/locales.d.ts +4 -24
  140. package/dist/runtime/composables/locales.js +28 -895
  141. package/dist/runtime/composables/useDataProvider.js +3 -1
  142. package/dist/runtime/composables/useKatluxForm.js +7 -7
  143. package/dist/runtime/composables/usePresetComponent.js +2 -0
  144. package/dist/runtime/composables/useRequestQueue.d.ts +2 -0
  145. package/dist/runtime/composables/useRequestQueue.js +3 -1
  146. package/dist/runtime/composables/useVirtualDataset.d.ts +6 -118
  147. package/dist/runtime/composables/useVirtualDataset.js +322 -354
  148. package/dist/runtime/composables/useVirtualScroll.d.ts +9 -9
  149. package/dist/runtime/composables/useVirtualScroll.js +69 -62
  150. package/dist/runtime/composables/virtualDataset/cacheStateHelpers.d.ts +49 -0
  151. package/dist/runtime/composables/virtualDataset/cacheStateHelpers.js +76 -0
  152. package/dist/runtime/composables/virtualDataset/keyboardNavHelpers.d.ts +26 -0
  153. package/dist/runtime/composables/virtualDataset/keyboardNavHelpers.js +60 -0
  154. package/dist/runtime/composables/virtualDataset/treeSelectionHelpers.d.ts +24 -0
  155. package/dist/runtime/composables/virtualDataset/treeSelectionHelpers.js +103 -0
  156. package/dist/runtime/composables/virtualDataset/types.d.ts +113 -0
  157. package/dist/runtime/composables/virtualDataset/types.js +0 -0
  158. package/dist/runtime/directives/clickOutside.d.ts +1 -1
  159. package/dist/runtime/directives/clickOutside.js +41 -13
  160. package/dist/runtime/plugins/nuxtCompatPlugin.d.ts +2 -1
  161. package/dist/runtime/plugins/nuxtCompatPlugin.js +7 -0
  162. package/dist/runtime/plugins/toastPlugin.client.js +2 -2
  163. package/dist/runtime/presets/default/components/KCalendar/KCalendarMonth.d.vue.ts +2 -0
  164. package/dist/runtime/presets/default/components/KCalendar/KCalendarMonth.vue +24 -0
  165. package/dist/runtime/presets/default/components/KCalendar/KCalendarMonth.vue.d.ts +2 -0
  166. package/dist/runtime/presets/default/components/KCalendar/KCalendarWeek.vue +6 -5
  167. package/dist/runtime/presets/default/components/KCombobox/KCombobox.d.vue.ts +4 -1
  168. package/dist/runtime/presets/default/components/KCombobox/KCombobox.vue +27 -17
  169. package/dist/runtime/presets/default/components/KCombobox/KCombobox.vue.d.ts +4 -1
  170. package/dist/runtime/presets/default/components/KCombobox/KComboboxList.d.vue.ts +1 -1
  171. package/dist/runtime/presets/default/components/KCombobox/KComboboxList.vue +10 -10
  172. package/dist/runtime/presets/default/components/KCombobox/KComboboxList.vue.d.ts +1 -1
  173. package/dist/runtime/presets/default/components/KContextMenu/KContextMenu.d.vue.ts +2 -0
  174. package/dist/runtime/presets/default/components/KContextMenu/KContextMenu.vue +60 -21
  175. package/dist/runtime/presets/default/components/KContextMenu/KContextMenu.vue.d.ts +2 -0
  176. package/dist/runtime/presets/default/components/KDataIterator/KDataIterator.d.vue.ts +12 -1
  177. package/dist/runtime/presets/default/components/KDataIterator/KDataIterator.vue +109 -15
  178. package/dist/runtime/presets/default/components/KDataIterator/KDataIterator.vue.d.ts +12 -1
  179. package/dist/runtime/presets/default/components/KDatatable/KDatatable.d.vue.ts +1 -1
  180. package/dist/runtime/presets/default/components/KDatatable/KDatatable.vue +14 -0
  181. package/dist/runtime/presets/default/components/KDatatable/KDatatable.vue.d.ts +1 -1
  182. package/dist/runtime/presets/default/components/KDropdown/KDropdown.d.vue.ts +5 -2
  183. package/dist/runtime/presets/default/components/KDropdown/KDropdown.vue +15 -12
  184. package/dist/runtime/presets/default/components/KDropdown/KDropdown.vue.d.ts +5 -2
  185. package/dist/runtime/presets/default/components/KGantt/KGantt.d.vue.ts +10 -0
  186. package/dist/runtime/presets/default/components/KGantt/KGantt.vue +23 -69
  187. package/dist/runtime/presets/default/components/KGantt/KGantt.vue.d.ts +10 -0
  188. package/dist/runtime/presets/default/components/KGantt/KGanttTimeline.d.vue.ts +6 -2
  189. package/dist/runtime/presets/default/components/KGantt/KGanttTimeline.vue +22 -8
  190. package/dist/runtime/presets/default/components/KGantt/KGanttTimeline.vue.d.ts +6 -2
  191. package/dist/runtime/presets/default/components/KLayout/KLayout.vue +2 -2
  192. package/dist/runtime/presets/default/components/KLoader/KLoader.d.vue.ts +1 -0
  193. package/dist/runtime/presets/default/components/KLoader/KLoader.vue +13 -2
  194. package/dist/runtime/presets/default/components/KLoader/KLoader.vue.d.ts +1 -0
  195. package/dist/runtime/presets/default/components/KMaskTextbox/KMaskTextbox.vue +1 -94
  196. package/dist/runtime/presets/default/components/KMultiTabs/KMultiTabs.vue +69 -4
  197. package/dist/runtime/presets/default/components/KRangeSlider/KRangeSlider.vue +18 -46
  198. package/dist/runtime/presets/default/components/KSlider/KSlider.vue +11 -23
  199. package/dist/runtime/presets/default/components/KTextbox/KTextbox.d.vue.ts +4 -1
  200. package/dist/runtime/presets/default/components/KTextbox/KTextbox.vue +24 -8
  201. package/dist/runtime/presets/default/components/KTextbox/KTextbox.vue.d.ts +4 -1
  202. package/dist/runtime/presets/default/components/KTree/KTree.d.vue.ts +1 -1
  203. package/dist/runtime/presets/default/components/KTree/KTree.vue +51 -80
  204. package/dist/runtime/presets/default/components/KTree/KTree.vue.d.ts +1 -1
  205. package/dist/runtime/presets/default/components/KTree/KTreeNodeItem.d.vue.ts +1 -0
  206. package/dist/runtime/presets/default/components/KTree/KTreeNodeItem.vue +12 -2
  207. package/dist/runtime/presets/default/components/KTree/KTreeNodeItem.vue.d.ts +1 -0
  208. package/dist/runtime/server/middleware/session.js +7 -0
  209. package/dist/runtime/utils/deprecation.d.ts +14 -0
  210. package/dist/runtime/utils/deprecation.js +44 -0
  211. package/dist/runtime/utils/dom.d.ts +31 -0
  212. package/dist/runtime/utils/dom.js +124 -0
  213. package/dist/skills/KATLUX_INDEX.md +15 -19
  214. package/dist/skills/katlux-components/components/KBulkActions.md +1 -1
  215. package/dist/skills/katlux-components/components/KDataIterator.md +5 -0
  216. package/dist/skills/katlux-components/components/KLayout.md +4 -0
  217. package/dist/skills/katlux-components/components/KLoader.md +3 -0
  218. package/dist/skills/katlux-components/components/KTextbox.md +1 -0
  219. package/dist/skills/katlux-config/SKILL.md +15 -7
  220. package/dist/skills/katlux-presets/SKILL.md +42 -2
  221. package/dist/skills/katlux-providers/SKILL.md +12 -0
  222. package/dist/skills/katlux-providers/providers/ADataProvider.md +1 -0
  223. package/dist/skills/katlux-providers/providers/CAPITreeServerDataProvider.md +13 -0
  224. package/dist/skills/katlux-providers/providers/RequestProvider.md +2 -2
  225. package/dist/skills/katlux-providers/providers/encryption-field-level.md +5 -2
  226. package/dist/skills/katlux-providers/providers/encryption-key-management.md +5 -2
  227. package/dist/skills/katlux-providers/providers/encryption-searchable.md +150 -27
  228. package/dist/skills/katlux-providers/providers/encryption-symmetric.md +4 -1
  229. package/dist/skills/katlux-providers/providers/encryption-threat-model.md +12 -6
  230. package/dist/skills/katlux-providers/providers/encryption.md +1 -1
  231. package/package.json +3 -3
package/bin/ai-tokens.mjs CHANGED
@@ -3,1041 +3,49 @@
3
3
  * packages/katlux-toolkit/bin/ai-tokens.mjs
4
4
  * Dynamic Week-by-Week Token Usage Analyzer, Project-by-Project Filter,
5
5
  * and Efficiency Reporter for AI coding assistant sessions (Antigravity IDE transcripts).
6
- *
7
- * Shipped with @katlux/toolkit to measure real-world AI context efficiency,
8
- * track week-over-week token trends, and identify token spikes per project.
9
- *
10
- * Usage:
11
- * npx @katlux/toolkit tokens # Analyzes latest active session (#1)
12
- * npx @katlux/toolkit tokens --report # Week-by-week executive report (all projects)
13
- * npx @katlux/toolkit tokens -r -P KatluxShowcase # Week-by-week report for specific project
14
- * npx @katlux/toolkit tokens --projects # List all detected projects and session counts
15
- * npx @katlux/toolkit tokens -r -w W43 # Filter report to a specific calendar week
16
- * npx @katlux/toolkit tokens -r --save # Saves week-by-week report to token-report.md
17
- * npx @katlux/toolkit tokens -r --md # Outputs pure Markdown
18
- * npx @katlux/toolkit tokens -p 1 # Paginated session browser (100 per page)
19
- * npx @katlux/toolkit tokens -p 1 -P <ProjectName> # Browse sessions of a specific project
20
- * npx @katlux/toolkit tokens <#|id> # Inspect details of a specific conversation
21
- * npx @katlux/toolkit tokens <#|id> -d # Full step-by-step chronology
22
6
  */
23
7
 
24
- import { existsSync, readdirSync, statSync, readFileSync, writeFileSync, openSync, readSync, closeSync } from 'node:fs'
25
- import { join, resolve, basename } from 'node:path'
26
- import { homedir } from 'node:os'
27
-
28
- const RESET = '\x1b[0m'
29
- const BOLD = '\x1b[1m'
30
- const DIM = '\x1b[2m'
31
- const CYAN = '\x1b[36m'
32
- const GREEN = '\x1b[32m'
33
- const YELLOW = '\x1b[33m'
34
- const RED = '\x1b[31m'
35
- const MAGENTA = '\x1b[35m'
36
- const BLUE = '\x1b[34m'
37
-
38
- const BRAIN_DIRS = [
39
- resolve(homedir(), '.gemini/antigravity/brain'),
40
- resolve(homedir(), '.gemini/antigravity-ide/brain')
41
- ]
42
- const BRAIN_DIR = BRAIN_DIRS.find(d => existsSync(d)) || BRAIN_DIRS[0]
43
-
44
- // Standard token estimation for code and conversation JSON (~3.75 chars per token)
45
- export function estimateTokens(input = 0) {
46
- if (!input) return 0
47
- const chars = typeof input === 'number' ? input : (input.length || 0)
48
- return Math.ceil(chars / 3.75)
49
- }
50
-
51
- export function formatTokens(count) {
52
- if (count >= 1_000_000) return (count / 1_000_000).toFixed(2) + 'M'
53
- if (count >= 1_000) return (count / 1_000).toFixed(1) + 'k'
54
- return (count || 0).toLocaleString()
55
- }
56
-
57
- export function formatBytes(bytes) {
58
- if (bytes >= 1024 * 1024) return (bytes / (1024 * 1024)).toFixed(2) + ' MB'
59
- if (bytes >= 1024) return (bytes / 1024).toFixed(1) + ' KB'
60
- return (bytes || 0) + ' B'
61
- }
62
-
63
- export function formatDateTime(d) {
64
- if (!d) return '-'
65
- const dateStr = d.toLocaleDateString('en-US', { month: '2-digit', day: '2-digit', year: 'numeric' })
66
- const timeStr = d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
67
- return `${dateStr} ${timeStr}`
68
- }
69
-
70
- function cleanString(val) {
71
- if (!val) return ''
72
- return String(val).replace(/^["']|["']$/g, '').trim()
73
- }
74
-
75
- function makeBar(percent, maxLen = 16) {
76
- const filled = Math.min(maxLen, Math.round((percent / 100) * maxLen))
77
- return '█'.repeat(filled) + '░'.repeat(maxLen - filled)
78
- }
79
-
80
- // Calculate standard ISO Week (e.g. "2026-W43")
81
- export function getWeekKey(date) {
82
- const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()))
83
- const dayNum = d.getUTCDay() || 7
84
- d.setUTCDate(d.getUTCDate() + 4 - dayNum)
85
- const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1))
86
- const weekNo = Math.ceil((((d - yearStart) / 86400000) + 1) / 7)
87
- return `${d.getUTCFullYear()}-W${String(weekNo).padStart(2, '0')}`
88
- }
89
-
90
- export function getWeekDateRange(weekKey) {
91
- const match = weekKey.match(/^(\d{4})-W(\d{2})$/)
92
- if (!match) return weekKey
93
- const year = parseInt(match[1], 10)
94
- const week = parseInt(match[2], 10)
95
-
96
- // Jan 4th is always in week 1
97
- const jan4 = new Date(Date.UTC(year, 0, 4))
98
- const jan4Day = jan4.getUTCDay() || 7
99
- const mondayWeek1 = new Date(jan4.getTime() - (jan4Day - 1) * 86400000)
100
- const monday = new Date(mondayWeek1.getTime() + (week - 1) * 7 * 86400000)
101
- const sunday = new Date(monday.getTime() + 6 * 86400000)
102
-
103
- const monStr = monday.toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' })
104
- const sunStr = sunday.toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' })
105
- return `${monStr} – ${sunStr}`
106
- }
107
-
108
- // Fast 16KB header inspection to avoid loading full multimegabyte JSONL files into memory
109
- export function getConversationPreviewFast(dirPath, searchQuery = '') {
110
- const pFull = join(dirPath, '.system_generated/logs/transcript_full.jsonl')
111
- const pNorm = join(dirPath, '.system_generated/logs/transcript.jsonl')
112
- const p = existsSync(pFull) ? pFull : pNorm
113
- if (!existsSync(p)) return { project: 'Unknown', title: '(empty transcript)', fullTitle: '', rawSize: 0, estimatedTokens: 0, matchesSearch: false, stepsCount: 0 }
114
-
8
+ import { realpathSync } from 'node:fs'
9
+ import { fileURLToPath } from 'node:url'
10
+ import { runAiTokensCli } from './ai-tokens/cliViews.mjs'
11
+
12
+ export {
13
+ estimateTokens,
14
+ formatTokens,
15
+ formatBytes,
16
+ formatDateTime,
17
+ getWeekKey,
18
+ getWeekDateRange
19
+ } from './ai-tokens/formatAndDates.mjs'
20
+ export {
21
+ getConversationPreviewFast,
22
+ getConversations,
23
+ parseTranscript,
24
+ analyzeSession
25
+ } from './ai-tokens/transcriptParser.mjs'
26
+ export {
27
+ listDetectedProjects,
28
+ generateWeekReport
29
+ } from './ai-tokens/reportGenerator.mjs'
30
+ export {
31
+ getIdeAdapter,
32
+ SUPPORTED_IDES,
33
+ antigravityAdapter,
34
+ claudeCodeAdapter,
35
+ cursorAdapter,
36
+ codexAdapter
37
+ } from './ai-tokens/adapters/index.mjs'
38
+ export { parseIdeArg } from './ai-tokens/cliViews.mjs'
39
+
40
+ const isDirectExecution = () => {
41
+ if (!process.argv[1]) return false
115
42
  try {
116
- const stat = statSync(p)
117
- if (stat.size === 0) return { project: 'Unknown', title: '(empty transcript)', fullTitle: '', rawSize: 0, estimatedTokens: 0, matchesSearch: false, stepsCount: 0 }
118
-
119
- let fd
120
- let chunk = ''
121
- try {
122
- fd = openSync(p, 'r')
123
- const buf = Buffer.alloc(16384)
124
- const bytesRead = readSync(fd, buf, 0, 16384, 0)
125
- closeSync(fd)
126
- chunk = buf.toString('utf-8', 0, bytesRead)
127
- } catch {
128
- if (fd !== undefined) try { closeSync(fd) } catch {}
129
- }
130
-
131
- // Detect project name dynamically
132
- let project = 'Unknown'
133
- const m1 = chunk.match(/\[URI\] -> \[CorpusName\]:\s*\n([^\s\n\r]+)\s*->/)
134
- if (m1) {
135
- project = basename(m1[1])
136
- } else {
137
- const m2 = chunk.match(/\/Desktop\/projects\/([a-zA-Z0-9_\-]+)/)
138
- if (m2) project = m2[1]
139
- else {
140
- const m3 = chunk.match(/\/projects\/([a-zA-Z0-9_\-]+)/)
141
- if (m3) project = m3[1]
142
- }
143
- }
144
-
145
- // Detect initial prompt title
146
- let title = '(no user prompt recorded)'
147
- const reqMatch = chunk.match(/<USER_REQUEST>([\s\S]*?)<\/USER_REQUEST>/)
148
- if (reqMatch) {
149
- title = reqMatch[1].replace(/\\n/g, ' ').replace(/[\r\n\t]+/g, ' ').trim()
150
- } else {
151
- const contentMatch = chunk.match(/"type":"USER_INPUT"[\s\S]*?"content":"([^"]+)"/)
152
- if (contentMatch) title = contentMatch[1].replace(/\\n/g, ' ').replace(/[\r\n\t]+/g, ' ').trim()
153
- }
154
-
155
- let matchesSearch = false
156
- if (searchQuery) {
157
- matchesSearch = chunk.toLowerCase().includes(searchQuery)
158
- }
159
-
160
- // Approximate step count based on average JSONL line size (~1.5KB)
161
- const estimatedTokens = Math.ceil(stat.size / 3.75)
162
- const approxSteps = Math.max(1, Math.round(stat.size / 1450))
163
-
164
- return {
165
- project,
166
- title: title.slice(0, 42),
167
- fullTitle: title,
168
- rawSize: stat.size,
169
- estimatedTokens,
170
- matchesSearch,
171
- stepsCount: approxSteps
172
- }
43
+ return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url))
173
44
  } catch {
174
- return { project: 'Unknown', title: '(read error)', fullTitle: '', rawSize: 0, estimatedTokens: 0, matchesSearch: false, stepsCount: 0 }
175
- }
176
- }
177
-
178
- export function getConversations() {
179
- const validDirs = BRAIN_DIRS.filter(d => existsSync(d))
180
- if (validDirs.length === 0) return []
181
-
182
- const seen = new Set()
183
- const results = []
184
-
185
- for (const bDir of validDirs) {
186
- const entries = readdirSync(bDir, { withFileTypes: true })
187
- for (const e of entries) {
188
- if (!e.isDirectory() || e.name === 'tempmediaStorage' || e.name.startsWith('.')) continue
189
- if (seen.has(e.name)) continue
190
- seen.add(e.name)
191
-
192
- const dirPath = join(bDir, e.name)
193
- const transcriptPath = join(dirPath, '.system_generated/logs/transcript.jsonl')
194
- const dirStat = statSync(dirPath)
195
- let lastActive = dirStat.mtime
196
- if (existsSync(transcriptPath)) {
197
- try {
198
- lastActive = statSync(transcriptPath).mtime
199
- } catch {}
200
- }
201
- results.push({
202
- id: e.name,
203
- path: dirPath,
204
- createdAt: dirStat.mtime,
205
- lastActive,
206
- mtime: lastActive,
207
- weekKey: getWeekKey(lastActive)
208
- })
209
- }
45
+ return false
210
46
  }
211
-
212
- return results.sort((a, b) => b.lastActive.getTime() - a.lastActive.getTime())
213
47
  }
214
48
 
215
- export function parseTranscript(conversationDir) {
216
- const transcriptFullPath = join(conversationDir, '.system_generated/logs/transcript_full.jsonl')
217
- const transcriptPath = join(conversationDir, '.system_generated/logs/transcript.jsonl')
218
- const targetPath = existsSync(transcriptFullPath) ? transcriptFullPath : transcriptPath
219
- if (!existsSync(targetPath)) return null
220
-
221
- const raw = readFileSync(targetPath, 'utf-8')
222
- const lines = raw.trim().split('\n').filter(Boolean)
223
-
224
- const steps = []
225
- for (let i = 0; i < lines.length; i++) {
226
- try {
227
- const obj = JSON.parse(lines[i])
228
- steps.push(obj)
229
- } catch {}
230
- }
231
- return steps
232
- }
233
-
234
- export function analyzeSession(steps, conversationId, mtime = new Date(), previewProject = 'Unknown') {
235
- let totalChars = 0
236
- let inputChars = 0
237
- let outputChars = 0
238
-
239
- const categories = {
240
- USER_INPUT: { count: 0, chars: 0, tokens: 0, label: 'User Prompts' },
241
- PLANNER_RESPONSE: { count: 0, chars: 0, tokens: 0, label: 'Assistant / Model' },
242
- VIEW_FILE: { count: 0, chars: 0, tokens: 0, label: 'view_file / read_file' },
243
- MCP_TOOL: { count: 0, chars: 0, tokens: 0, label: 'MCP Tools' },
244
- CODE_ACTION: { count: 0, chars: 0, tokens: 0, label: 'Code Edit / Write' },
245
- RUN_COMMAND: { count: 0, chars: 0, tokens: 0, label: 'run_command Outputs' },
246
- GREP_SEARCH: { count: 0, chars: 0, tokens: 0, label: 'grep_search Outputs' },
247
- LIST_DIRECTORY: { count: 0, chars: 0, tokens: 0, label: 'list_dir Outputs' },
248
- CONVERSATION_HISTORY: { count: 0, chars: 0, tokens: 0, label: 'Injected History' },
249
- SYSTEM_MESSAGE: { count: 0, chars: 0, tokens: 0, label: 'System Notifications' },
250
- OTHER: { count: 0, chars: 0, tokens: 0, label: 'Other Metadata' }
251
- }
252
-
253
- const spikes = []
254
- const userPrompts = []
255
- const filesViewed = new Map()
256
- const filesModified = new Map()
257
- const mcpCalls = {
258
- inspectProject: 0,
259
- validateCode: 0,
260
- otherMcp: 0,
261
- total: 0
262
- }
263
- let sessionTitle = ''
264
- let detectedProject = previewProject
265
-
266
- const pendingToolCalls = []
267
-
268
- steps.forEach(step => {
269
- const type = step.type || 'OTHER'
270
- let content = ''
271
- if (type === 'PLANNER_RESPONSE') {
272
- const parts = []
273
- if (typeof step.content === 'string' && step.content) {
274
- parts.push(step.content)
275
- } else if (step.content && typeof step.content !== 'string') {
276
- parts.push(JSON.stringify(step.content))
277
- }
278
- if (step.thinking && typeof step.thinking === 'string') {
279
- parts.push(step.thinking)
280
- }
281
- if (step.tool_calls) {
282
- parts.push(JSON.stringify(step.tool_calls))
283
- }
284
- content = parts.join('\n')
285
- } else {
286
- if (typeof step.content === 'string') {
287
- content = step.content
288
- } else if (step.tool_calls) {
289
- content = JSON.stringify(step.tool_calls)
290
- } else if (step.content) {
291
- content = JSON.stringify(step.content)
292
- }
293
- }
294
-
295
- if (detectedProject === 'Unknown' && content) {
296
- const m1 = content.match(/\[URI\] -> \[CorpusName\]:\s*\n([^\s\n\r]+)\s*->/)
297
- if (m1) detectedProject = basename(m1[1])
298
- else {
299
- const m2 = content.match(/\/Desktop\/projects\/([a-zA-Z0-9_\-]+)/)
300
- if (m2) detectedProject = m2[1]
301
- }
302
- }
303
-
304
- if (type === 'USER_INPUT' && content) {
305
- const match = content.match(/<USER_REQUEST>([\s\S]*?)<\/USER_REQUEST>/)
306
- const promptText = (match ? match[1] : content).replace(/[\r\n\t]+/g, ' ').trim()
307
- if (!sessionTitle) sessionTitle = promptText
308
- const timeStr = step.created_at ? formatDateTime(new Date(step.created_at)) : ''
309
- userPrompts.push({ step: step.step_index, text: promptText, time: timeStr })
310
- }
311
-
312
- // Track tool call targets
313
- if (step.tool_calls && Array.isArray(step.tool_calls)) {
314
- step.tool_calls.forEach(tc => {
315
- pendingToolCalls.push(tc)
316
- const args = tc.args || {}
317
- let toolName = tc.name
318
- if (tc.name === 'call_mcp_tool') {
319
- toolName = cleanString(args.ToolName)
320
- }
321
- if (toolName === 'katlux_inspect_project') {
322
- mcpCalls.inspectProject++
323
- mcpCalls.total++
324
- } else if (toolName === 'katlux_validate_code') {
325
- mcpCalls.validateCode++
326
- mcpCalls.total++
327
- } else if (tc.name === 'call_mcp_tool' || (toolName && toolName.startsWith('katlux_'))) {
328
- mcpCalls.otherMcp++
329
- mcpCalls.total++
330
- }
331
-
332
- if ((tc.name === 'view_file' || tc.name === 'read_file') && (args.AbsolutePath || args.Path)) {
333
- const fn = basename(cleanString(args.AbsolutePath || args.Path))
334
- if (fn) filesViewed.set(fn, (filesViewed.get(fn) || 0) + 1)
335
- } else if ((tc.name === 'replace_file_content' || tc.name === 'multi_replace_file_content' || tc.name === 'write_to_file' || tc.name === 'edit_file' || tc.name === 'write_file') && (args.TargetFile || args.Path)) {
336
- const fn = basename(cleanString(args.TargetFile || args.Path))
337
- if (fn) filesModified.set(fn, (filesModified.get(fn) || 0) + 1)
338
- }
339
- })
340
- }
341
-
342
- const chars = content.length
343
- const tokens = estimateTokens(chars)
344
-
345
- totalChars += chars
346
-
347
- if (type === 'PLANNER_RESPONSE') {
348
- outputChars += chars
349
- } else {
350
- inputChars += chars
351
- }
352
-
353
- let catType = type
354
- if (type === 'READ_FILE') catType = 'VIEW_FILE'
355
- if (type === 'MCP_TOOL' || type === 'CALL_MCP_TOOL') catType = 'MCP_TOOL'
356
-
357
- if (type === 'GENERIC') {
358
- const correspondingTool = pendingToolCalls.shift()
359
- if (correspondingTool) {
360
- const toolName = correspondingTool.name || ''
361
- if (toolName === 'read_file' || toolName === 'view_file') {
362
- catType = 'VIEW_FILE'
363
- } else if (toolName === 'run_command' || toolName === 'manage_task') {
364
- catType = 'RUN_COMMAND'
365
- } else if (
366
- toolName === 'edit_file' ||
367
- toolName === 'write_file' ||
368
- toolName === 'replace_file_content' ||
369
- toolName === 'multi_replace_file_content' ||
370
- toolName === 'write_to_file'
371
- ) {
372
- catType = 'CODE_ACTION'
373
- } else if (
374
- toolName === 'call_mcp_tool' ||
375
- toolName.startsWith('mcp_') ||
376
- toolName.startsWith('katlux_')
377
- ) {
378
- catType = 'MCP_TOOL'
379
- } else if (toolName === 'grep_search') {
380
- catType = 'GREP_SEARCH'
381
- } else if (toolName === 'list_dir' || toolName === 'find_by_name') {
382
- catType = 'LIST_DIRECTORY'
383
- } else {
384
- catType = 'OTHER'
385
- }
386
- } else {
387
- catType = 'OTHER'
388
- }
389
- }
390
-
391
- const cat = categories[catType] || categories.OTHER
392
- cat.count++
393
- cat.chars += chars
394
- cat.tokens += tokens
395
-
396
- spikes.push({
397
- step_index: step.step_index,
398
- type: type === 'GENERIC' && catType !== 'OTHER' ? `${type} (${catType})` : type,
399
- tokens,
400
- chars,
401
- preview: content.replace(/[\r\n\t]+/g, ' ').slice(0, 80).trim()
402
- })
403
- })
404
-
405
- const totalTokens = estimateTokens(totalChars)
406
- const inputTokens = estimateTokens(inputChars)
407
- const outputTokens = estimateTokens(outputChars)
408
-
409
- spikes.sort((a, b) => b.tokens - a.tokens)
410
-
411
- const topViewedFiles = [...filesViewed.entries()].sort((a, b) => b[1] - a[1]).slice(0, 5)
412
- const topModifiedFiles = [...filesModified.entries()].sort((a, b) => b[1] - a[1]).slice(0, 5)
413
-
414
- return {
415
- conversationId,
416
- project: detectedProject,
417
- sessionTitle: sessionTitle || '(no title)',
418
- mtime,
419
- weekKey: getWeekKey(mtime),
420
- totalSteps: steps.length,
421
- totalChars,
422
- totalTokens,
423
- inputTokens,
424
- outputTokens,
425
- categories,
426
- mcpCalls,
427
- spikes: spikes.slice(0, 5),
428
- userPrompts,
429
- topViewedFiles,
430
- topModifiedFiles,
431
- allFilesViewed: filesViewed,
432
- allFilesModified: filesModified
433
- }
434
- }
435
-
436
- // ── Project List View ───────────────────────────────────────────────────────
437
- export function listDetectedProjects(conversations) {
438
- console.log(`\n${BOLD}╭──────────────────────────────────────────────────────────────────────────────╮${RESET}`)
439
- console.log(`${BOLD}│ DETECTED ANTIGRAVITY PROJECTS │${RESET}`)
440
- console.log(`${BOLD}╰──────────────────────────────────────────────────────────────────────────────╯${RESET}`)
441
-
442
- const projectMap = new Map()
443
-
444
- conversations.forEach(c => {
445
- const prj = c.preview.project
446
- if (prj === 'Unknown' || c.preview.rawSize === 0) return
447
- if (!projectMap.has(prj)) {
448
- projectMap.set(prj, { name: prj, count: 0, tokens: 0, latest: c.mtime })
449
- }
450
- const p = projectMap.get(prj)
451
- p.count++
452
- p.tokens += c.preview.estimatedTokens
453
- if (c.mtime > p.latest) p.latest = c.mtime
454
- })
455
-
456
- console.log(` ${'#'.padStart(3)} ${'PROJECT NAME'.padEnd(26)} ${'SESSIONS'.padStart(10)} ${'TOTAL TOKENS'.padStart(14)} LAST ACTIVE`)
457
- console.log(` ${'─'.repeat(3)} ${'─'.repeat(26)} ${'─'.repeat(10)} ${'─'.repeat(14)} ${'─'.repeat(16)}`)
458
-
459
- let idx = 1
460
- for (const p of projectMap.values()) {
461
- const dateStr = p.latest.toLocaleDateString() + ' ' + p.latest.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
462
- console.log(
463
- ` ${CYAN}${String(idx++).padStart(3)}${RESET} ` +
464
- `${BOLD}${p.name.padEnd(26)}${RESET} ` +
465
- `${String(p.count).padStart(10)} ` +
466
- `${formatTokens(p.tokens).padStart(14)} ` +
467
- `${DIM}${dateStr}${RESET}`
468
- )
469
- }
470
-
471
- console.log(`\n${BOLD}Filter Commands:${RESET}`)
472
- for (const p of projectMap.values()) {
473
- console.log(` • View ${p.name}: ${CYAN}npx @katlux/toolkit tokens -P ${p.name} --report${RESET}`)
474
- }
475
- console.log()
476
- }
477
-
478
- // ── Week-by-Week Executive Token Report Generator ───────────────────────────
479
- export function generateWeekReport({ weekFilter = '', projectFilter = '', asMarkdown = false, saveFile = false }) {
480
- const all = getConversations()
481
- if (all.length === 0) {
482
- console.log(`${RED}No conversations found in ${BRAIN_DIR}${RESET}`)
483
- return
484
- }
485
-
486
- // Attach previews quickly using fast header scan
487
- const mapped = all.map((c, i) => ({
488
- ...c,
489
- originalIndex: i + 1,
490
- preview: getConversationPreviewFast(c.path)
491
- }))
492
-
493
- // Filter by project if requested
494
- let filtered = mapped
495
- if (projectFilter) {
496
- const q = projectFilter.toLowerCase()
497
- filtered = mapped.filter(c => c.preview.project.toLowerCase().includes(q))
498
- if (filtered.length === 0) {
499
- console.log(`\n${RED}No sessions found for project matching "${projectFilter}".${RESET}`)
500
- console.log(`Run ${CYAN}npx @katlux/toolkit tokens --projects${RESET} to view all detected projects.\n`)
501
- return
502
- }
503
- }
504
-
505
- // Filter out completely empty bootstrap directories
506
- const activeConversations = filtered.filter(c => c.preview.rawSize > 0)
507
-
508
- // Group sessions into calendar weeks
509
- const weeklyMap = new Map()
510
-
511
- activeConversations.forEach(conv => {
512
- const wk = conv.weekKey
513
- if (!weeklyMap.has(wk)) {
514
- weeklyMap.set(wk, {
515
- weekKey: wk,
516
- dateRange: getWeekDateRange(wk),
517
- dirs: []
518
- })
519
- }
520
- weeklyMap.get(wk).dirs.push(conv)
521
- })
522
-
523
- // Process each week's sessions
524
- const weeklyStats = []
525
-
526
- for (const [wk, entry] of weeklyMap.entries()) {
527
- if (weekFilter && !wk.toLowerCase().includes(weekFilter.toLowerCase())) {
528
- continue
529
- }
530
-
531
- const analyzedSessions = entry.dirs.map(d => {
532
- const steps = parseTranscript(d.path)
533
- return steps ? analyzeSession(steps, d.id, d.mtime, d.preview.project) : null
534
- }).filter(Boolean)
535
-
536
- if (analyzedSessions.length === 0) continue
537
-
538
- // Filter out trivial (< 6 steps) ping/hello sessions from task averages
539
- const realTasks = analyzedSessions.filter(s => s.totalSteps >= 6)
540
- const targetSessions = realTasks.length > 0 ? realTasks : analyzedSessions
541
- const trivialCount = analyzedSessions.length - targetSessions.length
542
-
543
- const count = targetSessions.length
544
- const sum = (fn) => targetSessions.reduce((s, x) => s + fn(x), 0)
545
- const avg = (fn) => Math.round(sum(fn) / count)
546
-
547
- const avgTotalTokens = avg(s => s.totalTokens)
548
- const avgInputTokens = avg(s => s.inputTokens)
549
- const avgOutputTokens = avg(s => s.outputTokens)
550
- const avgRunCmdTokens = avg(s => s.categories.RUN_COMMAND?.tokens || 0)
551
- const avgViewFileTokens = avg(s => s.categories.VIEW_FILE?.tokens || 0)
552
- const avgMcpTokens = avg(s => s.categories.MCP_TOOL?.tokens || 0)
553
- const avgMcpCalls = avg(s => s.mcpCalls?.total || 0)
554
- const avgSteps = avg(s => s.totalSteps)
555
-
556
- const claudeCost = ((avgInputTokens / 1_000_000) * 3.00 + (avgOutputTokens / 1_000_000) * 15.00).toFixed(2)
557
- const geminiCost = ((avgInputTokens / 1_000_000) * 0.35 + (avgOutputTokens / 1_000_000) * 1.05).toFixed(3)
558
-
559
- // Aggregate files and categories for this specific week
560
- const weekCategories = {}
561
- const weekViewedFiles = new Map()
562
- const weekModifiedFiles = new Map()
563
-
564
- targetSessions.forEach(s => {
565
- Object.entries(s.categories).forEach(([k, cat]) => {
566
- if (!weekCategories[k]) weekCategories[k] = { label: cat.label, count: 0, tokens: 0 }
567
- weekCategories[k].count += cat.count
568
- weekCategories[k].tokens += cat.tokens
569
- })
570
- s.allFilesViewed.forEach((c, f) => weekViewedFiles.set(f, (weekViewedFiles.get(f) || 0) + c))
571
- s.allFilesModified.forEach((c, f) => weekModifiedFiles.set(f, (weekModifiedFiles.get(f) || 0) + c))
572
- })
573
-
574
- weeklyStats.push({
575
- weekKey: wk,
576
- dateRange: entry.dateRange,
577
- sessionCount: count,
578
- trivialCount,
579
- totalTokensSum: sum(s => s.totalTokens),
580
- avgTotalTokens,
581
- avgRunCmdTokens,
582
- avgViewFileTokens,
583
- avgMcpTokens,
584
- avgMcpCalls,
585
- avgSteps,
586
- claudeCost,
587
- geminiCost,
588
- categories: weekCategories,
589
- topViewed: [...weekViewedFiles.entries()].sort((a, b) => b[1] - a[1]).slice(0, 5),
590
- topModified: [...weekModifiedFiles.entries()].sort((a, b) => b[1] - a[1]).slice(0, 5)
591
- })
592
- }
593
-
594
- // Sort newest week first
595
- weeklyStats.sort((a, b) => b.weekKey.localeCompare(a.weekKey))
596
-
597
- // Compute Week-over-Week (WoW) efficiency changes dynamically
598
- for (let i = 0; i < weeklyStats.length; i++) {
599
- const current = weeklyStats[i]
600
- const prior = weeklyStats[i + 1]
601
- if (prior && prior.avgTotalTokens > 0) {
602
- const diff = current.avgTotalTokens - prior.avgTotalTokens
603
- const pct = ((diff / prior.avgTotalTokens) * 100).toFixed(1)
604
- current.wowPct = pct
605
- } else {
606
- current.wowPct = null
607
- }
608
- }
609
-
610
- const projectLabel = projectFilter ? `Project: ${projectFilter}` : 'All Projects'
611
-
612
- // Markdown generation
613
- const md = []
614
- md.push(`# Antigravity AI Token Usage: Week-by-Week Report`)
615
- md.push(`*Scope: ${projectLabel} | Analyzed ${activeConversations.length} sessions across ${weeklyStats.length} calendar weeks*\n`)
616
-
617
- md.push(`## 1. Week-by-Week Token & Efficiency Progression\n`)
618
- md.push(`| Calendar Week | Date Range | Tasks | Avg Tokens / Task | Avg Test Tokens | Avg File View | Avg MCP Tokens | Avg Steps | Avg Cost (Claude) | WoW Trend |`)
619
- md.push(`| :--- | :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |`)
620
-
621
- weeklyStats.forEach((w, idx) => {
622
- const isCurrent = idx === 0 ? ' **(Current)**' : ''
623
- const wowStr = w.wowPct !== null ? `${Number(w.wowPct) <= 0 ? w.wowPct + '%' : '+' + w.wowPct + '%'}` : '—'
624
- md.push(`| **${w.weekKey}**${isCurrent} | ${w.dateRange} | ${w.sessionCount} | **${formatTokens(w.avgTotalTokens)}** | ${formatTokens(w.avgRunCmdTokens)} | ${formatTokens(w.avgViewFileTokens)} | ${formatTokens(w.avgMcpTokens)} | ${w.avgSteps} | $${w.claudeCost} | ${wowStr} |`)
625
- })
626
- md.push('')
627
-
628
- md.push(`## 2. Weekly Details & Most Frequent Files\n`)
629
- weeklyStats.forEach(w => {
630
- const trivialSuffix = w.trivialCount > 0 ? ` (+${w.trivialCount} trivial)` : ''
631
- md.push(`### ${w.weekKey} (${w.dateRange}) — ${w.sessionCount} Tasks${trivialSuffix} | Avg ${formatTokens(w.avgTotalTokens)} Tokens | Cost $${w.claudeCost}`)
632
- if (w.topViewed.length > 0) {
633
- md.push(`- **Most Read Files:** ${w.topViewed.map(([f, n]) => `\`${f}\` (${n}x)`).join(', ')}`)
634
- }
635
- if (w.topModified.length > 0) {
636
- md.push(`- **Most Edited Files:** ${w.topModified.map(([f, n]) => `\`${f}\` (${n}x)`).join(', ')}`)
637
- }
638
- const totalWeekTokens = Object.values(w.categories).reduce((s, x) => s + x.tokens, 0)
639
- const catPcts = Object.values(w.categories)
640
- .filter(c => c.tokens > 0)
641
- .sort((a, b) => b.tokens - a.tokens)
642
- .map(c => `${c.label}: ${((c.tokens / totalWeekTokens) * 100).toFixed(0)}%`)
643
- .slice(0, 4)
644
- .join(' | ')
645
- if (catPcts) {
646
- md.push(`- **Key Categories:** ${catPcts}`)
647
- }
648
- md.push('')
649
- })
650
-
651
- const mdOutput = md.join('\n')
652
-
653
- if (saveFile) {
654
- const outPath = resolve(process.cwd(), 'token-report.md')
655
- writeFileSync(outPath, mdOutput, 'utf-8')
656
- console.log(`${GREEN}✓ Week-by-week report saved to ${outPath}${RESET}\n`)
657
- }
658
-
659
- if (asMarkdown) {
660
- console.log(mdOutput)
661
- return
662
- }
663
-
664
- // Terminal Visual Output
665
- console.log(`\n${BOLD}╭──────────────────────────────────────────────────────────────────────────────╮${RESET}`)
666
- console.log(`${BOLD}│ ANTIGRAVITY AI TOKEN USAGE: WEEK-BY-WEEK REPORT │${RESET}`)
667
- console.log(`${BOLD}╰──────────────────────────────────────────────────────────────────────────────╯${RESET}`)
668
- console.log(` Scope: ${BOLD}${projectLabel}${RESET} (${activeConversations.length} total sessions analyzed across ${weeklyStats.length} calendar weeks)\n`)
669
-
670
- console.log(`${BOLD}1. WEEK-BY-WEEK PROGRESSION TABLE${RESET}`)
671
- console.log(` ${'WEEK'.padEnd(10)} ${'DATE RANGE'.padEnd(16)} ${'TASKS'.padStart(6)} ${'AVG TOKENS'.padStart(11)} ${'TESTS'.padStart(8)} ${'VIEW'.padStart(8)} ${'MCP'.padStart(8)} ${'STEPS'.padStart(6)} ${'COST'.padStart(7)} ${'WoW TREND'.padStart(10)}`)
672
- console.log(` ${'─'.repeat(10)} ${'─'.repeat(16)} ${'─'.repeat(6)} ${'─'.repeat(11)} ${'─'.repeat(8)} ${'─'.repeat(8)} ${'─'.repeat(8)} ${'─'.repeat(6)} ${'─'.repeat(7)} ${'─'.repeat(10)}`)
673
-
674
- weeklyStats.forEach((w, idx) => {
675
- const isCurrent = idx === 0
676
- const weekLabel = (w.weekKey.replace('2026-', '') + (isCurrent ? '*' : '')).padEnd(10)
677
- const wowColor = w.wowPct && Number(w.wowPct) <= 0 ? GREEN : (w.wowPct ? RED : DIM)
678
- const wowStr = w.wowPct !== null ? (Number(w.wowPct) <= 0 ? w.wowPct + '%' : '+' + w.wowPct + '%') : '—'
679
-
680
- console.log(
681
- ` ${isCurrent ? GREEN : CYAN}${weekLabel}${RESET} ` +
682
- `${w.dateRange.padEnd(16)} ` +
683
- `${String(w.sessionCount).padStart(6)} ` +
684
- `${BOLD}${formatTokens(w.avgTotalTokens).padStart(11)}${RESET} ` +
685
- `${formatTokens(w.avgRunCmdTokens).padStart(8)} ` +
686
- `${formatTokens(w.avgViewFileTokens).padStart(8)} ` +
687
- `${formatTokens(w.avgMcpTokens).padStart(8)} ` +
688
- `${String(w.avgSteps).padStart(6)} ` +
689
- `${('$' + w.claudeCost).padStart(7)} ` +
690
- `${wowColor}${wowStr.padStart(10)}${RESET}`
691
- )
692
- })
693
-
694
- console.log(` ${DIM}* Current calendar week. Costs estimated using Claude 3.5 Sonnet.${RESET}\n`)
695
-
696
- console.log(`${BOLD}2. WEEKLY DETAILS & MOST FREQUENT FILES${RESET}`)
697
- weeklyStats.forEach(w => {
698
- const totalWeekTokens = Object.values(w.categories).reduce((s, x) => s + x.tokens, 0)
699
- const trivialSuffix = w.trivialCount > 0 ? ` (+${w.trivialCount} trivial)` : ''
700
- console.log(` ${CYAN}${BOLD}[Week ${w.weekKey}: ${w.dateRange}]${RESET} — ${w.sessionCount} Tasks${trivialSuffix} | Avg ${formatTokens(w.avgTotalTokens)} Tokens | Avg Steps: ${w.avgSteps}`)
701
- if (w.topViewed.length > 0) {
702
- console.log(` ${CYAN}Most Read:${RESET} ${w.topViewed.map(([f, n]) => `${f} (${n}x)`).join(', ')}`)
703
- }
704
- if (w.topModified.length > 0) {
705
- console.log(` ${YELLOW}Most Edited:${RESET} ${w.topModified.map(([f, n]) => `${f} (${n}x)`).join(', ')}`)
706
- }
707
-
708
- // Top categories
709
- const topCats = Object.values(w.categories)
710
- .filter(c => c.tokens > 0)
711
- .sort((a, b) => b.tokens - a.tokens)
712
- .slice(0, 4)
713
- .map(c => `${c.label}: ${((c.tokens / totalWeekTokens) * 100).toFixed(0)}%`)
714
- .join(' | ')
715
- if (topCats) {
716
- console.log(` ${DIM}Categories:${RESET} ${DIM}${topCats}${RESET}`)
717
- }
718
- console.log()
719
- })
720
-
721
- console.log(`${DIM}Commands:${RESET}`)
722
- console.log(` • Filter project: ${CYAN}npx @katlux/toolkit tokens -P <projectName> --report${RESET}`)
723
- console.log(` • List projects: ${CYAN}npx @katlux/toolkit tokens --projects${RESET}`)
724
- console.log(` • Save as Markdown: ${CYAN}npx @katlux/toolkit tokens --report --save${RESET}`)
725
- console.log(` • Filter single week:${CYAN}npx @katlux/toolkit tokens -w W43${RESET}`)
726
- console.log(` • Browse sessions: ${CYAN}npx @katlux/toolkit tokens -p 1${RESET}\n`)
727
- }
728
-
729
- // ── CLI Argument Parsing & Routing ──────────────────────────────────────────
730
- const args = process.argv.slice(2)
731
- const showDetail = args.includes('-d') || args.includes('--detail')
732
-
733
- // Project filter flag
734
- let projectFilter = ''
735
- const prjArgIdx = args.findIndex(a => a === '-P' || a === '--project')
736
- if (prjArgIdx !== -1 && args[prjArgIdx + 1] && !args[prjArgIdx + 1].startsWith('-')) {
737
- projectFilter = args[prjArgIdx + 1]
738
- if (projectFilter === 'current' || projectFilter === '.') {
739
- projectFilter = basename(process.cwd())
740
- }
741
- }
742
-
743
- // List projects mode
744
- if (args.includes('--projects') || args.includes('-P') && !projectFilter) {
745
- const all = getConversations().map(c => ({
746
- ...c,
747
- preview: getConversationPreviewFast(c.path)
748
- }))
749
- listDetectedProjects(all)
750
- process.exit(0)
751
- }
752
-
753
- // Report mode (default if called with --report, -r, or if --week is provided)
754
- const isReport = args.includes('--report') || args.includes('-r') || args.includes('--weekly')
755
- const asMarkdown = args.includes('--md') || args.includes('--markdown')
756
- const saveFile = args.includes('--save')
757
-
758
- // Week filter
759
- let weekFilter = ''
760
- const weekArgIdx = args.findIndex(a => a === '-w' || a === '--week')
761
- if (weekArgIdx !== -1 && args[weekArgIdx + 1]) {
762
- weekFilter = args[weekArgIdx + 1]
763
- }
764
-
765
- if (isReport || weekFilter) {
766
- generateWeekReport({ weekFilter, projectFilter, asMarkdown, saveFile })
767
- process.exit(0)
768
- }
769
-
770
- // Search term
771
- let searchQuery = ''
772
- const searchArgIdx = args.findIndex(a => a === '-s' || a === '--search' || a === '-q')
773
- if (searchArgIdx !== -1 && args[searchArgIdx + 1]) {
774
- searchQuery = args[searchArgIdx + 1].toLowerCase()
775
- }
776
-
777
- // Extract page
778
- let page = 1
779
- const pageArgIdx = args.findIndex(a => a === '-p' || a === '--page')
780
- if (pageArgIdx !== -1 && args[pageArgIdx + 1]) {
781
- page = Math.max(1, parseInt(args[pageArgIdx + 1], 10) || 1)
782
- }
783
-
784
- // Extract limit (default 100 per page)
785
- let limit = 100
786
- const limitArgIdx = args.findIndex(a => a === '-l' || a === '--limit')
787
- if (limitArgIdx !== -1 && args[limitArgIdx + 1]) {
788
- limit = Math.max(1, parseInt(args[limitArgIdx + 1], 10) || 100)
789
- }
790
-
791
- const allConversations = getConversations()
792
-
793
- if (allConversations.length === 0) {
794
- console.log(`${RED}No conversations found in ${BRAIN_DIR}${RESET}`)
795
- process.exit(1)
796
- }
797
-
798
- // Map previews quickly using fast header inspection
799
- const mappedConversations = allConversations.map((c, i) => {
800
- const preview = getConversationPreviewFast(c.path, searchQuery)
801
- return {
802
- ...c,
803
- originalIndex: i + 1,
804
- preview
805
- }
806
- })
807
-
808
- // Filter by project if specified
809
- let projectFilteredConversations = mappedConversations
810
- if (projectFilter) {
811
- const q = projectFilter.toLowerCase()
812
- projectFilteredConversations = mappedConversations.filter(c => c.preview.project.toLowerCase().includes(q))
813
- }
814
-
815
- // Filter if search query provided
816
- let filteredConversations = projectFilteredConversations
817
- if (searchQuery) {
818
- filteredConversations = projectFilteredConversations.filter(c =>
819
- c.id.toLowerCase().includes(searchQuery) ||
820
- (c.preview.fullTitle && c.preview.fullTitle.toLowerCase().includes(searchQuery)) ||
821
- c.preview.matchesSearch
822
- )
823
- }
824
-
825
- // Positional argument
826
- const positionalArgs = args.filter(a =>
827
- !a.startsWith('-') &&
828
- a !== String(page) &&
829
- a !== String(limit) &&
830
- a !== searchQuery &&
831
- a !== weekFilter &&
832
- a !== projectFilter
833
- )
834
- const targetArg = positionalArgs[0]
835
- const targetIndex = targetArg && /^\d+$/.test(targetArg) ? parseInt(targetArg, 10) : null
836
-
837
- const isExplicitList = args.includes('--list') || pageArgIdx !== -1 || searchArgIdx !== -1 || projectFilter !== ''
838
-
839
- // ── 1. Page-by-Page Conversation List View ──────────────────────────────────
840
- if ((isExplicitList && !targetIndex) || (searchQuery && !targetIndex)) {
841
- const total = filteredConversations.length
842
- const totalPages = Math.max(1, Math.ceil(total / limit))
843
- page = Math.min(page, totalPages)
844
-
845
- const startIndex = (page - 1) * limit
846
- const pageItems = filteredConversations.slice(startIndex, startIndex + limit)
847
-
848
- console.log(`\n${BOLD}╭──────────────────────────────────────────────────────────────────────────────╮${RESET}`)
849
- console.log(`${BOLD}│ ANTIGRAVITY CONVERSATIONS BROWSER │${RESET}`)
850
- console.log(`${BOLD}╰──────────────────────────────────────────────────────────────────────────────╯${RESET}`)
851
- if (projectFilter) {
852
- console.log(` Project Filter: ${GREEN}${projectFilter}${RESET}`)
853
- }
854
- if (searchQuery) {
855
- console.log(` Filtered by: ${YELLOW}"${searchQuery}"${RESET} (${total} matching)`)
856
- }
857
- console.log(` Showing Page ${BOLD}${page}${RESET} of ${BOLD}${totalPages}${RESET} (${total === 0 ? 0 : startIndex + 1}–${Math.min(startIndex + limit, total)} of ${total} conversations)\n`)
858
-
859
- if (total === 0) {
860
- console.log(` ${RED}No conversations found matching criteria.${RESET}\n`)
861
- process.exit(0)
862
- }
863
-
864
- console.log(` ${'#'.padStart(4)} ${'ID'.padEnd(9)} ${'PROJECT'.padEnd(16)} ${'WEEK'.padEnd(6)} ${'TOPIC / PROMPT'.padEnd(34)} ${'TOKENS'.padStart(8)} ${'LAST ACTIVE'.padEnd(19)} STARTED`)
865
- console.log(` ${'─'.repeat(4)} ${'─'.repeat(9)} ${'─'.repeat(16)} ${'─'.repeat(6)} ${'─'.repeat(34)} ${'─'.repeat(8)} ${'─'.repeat(19)} ${'─'.repeat(19)}`)
866
-
867
- pageItems.forEach(conv => {
868
- const preview = conv.preview
869
- const shortId = conv.id.slice(0, 8)
870
- const lastActiveStr = formatDateTime(conv.lastActive)
871
- const createdStr = formatDateTime(conv.createdAt)
872
- const shortWeek = conv.weekKey.replace('2026-', '')
873
- const prjStr = (preview.project || 'Unknown').slice(0, 15)
874
-
875
- const indexColor = conv.originalIndex === 1 ? GREEN : CYAN
876
- console.log(
877
- ` ${indexColor}${String(conv.originalIndex).padStart(4)}${RESET} ` +
878
- `${shortId.padEnd(9)} ` +
879
- `${YELLOW}${prjStr.padEnd(16)}${RESET} ` +
880
- `${DIM}${shortWeek.padEnd(6)}${RESET} ` +
881
- `${preview.title.padEnd(34)} ` +
882
- `${BOLD}${formatTokens(preview.estimatedTokens).padStart(8)}${RESET} ` +
883
- `${GREEN}${lastActiveStr.padEnd(19)}${RESET} ` +
884
- `${DIM}${createdStr}${RESET}`
885
- )
886
- })
887
-
888
- console.log(`\n${BOLD}Navigation & Actions:${RESET}`)
889
- if (page < totalPages) {
890
- console.log(` • Next page: ${CYAN}npx @katlux/toolkit tokens -p ${page + 1}${projectFilter ? ` -P ${projectFilter}` : ''}${RESET}`)
891
- }
892
- if (page > 1) {
893
- console.log(` • Previous page: ${CYAN}npx @katlux/toolkit tokens -p ${page - 1}${projectFilter ? ` -P ${projectFilter}` : ''}${RESET}`)
894
- }
895
- console.log(` • Filter project:${CYAN}npx @katlux/toolkit tokens -P <projectName>${RESET}`)
896
- console.log(` • Weekly report: ${CYAN}npx @katlux/toolkit tokens --report${projectFilter ? ` -P ${projectFilter}` : ''}${RESET}`)
897
- console.log(` • Inspect one: ${CYAN}npx @katlux/toolkit tokens <#>${RESET} (e.g. ${CYAN}tokens ${pageItems[0]?.originalIndex}${RESET} or ${CYAN}tokens ${pageItems[0]?.id.slice(0, 8)}${RESET})`)
898
- console.log(` • Detailed steps:${CYAN} npx @katlux/toolkit tokens <#> -d${RESET}\n`)
899
- process.exit(0)
900
- }
901
-
902
- // ── 2. Single Conversation Detail View ──────────────────────────────────────
903
- let selectedConv = allConversations[0]
904
-
905
- if (targetIndex !== null) {
906
- if (targetIndex < 1 || targetIndex > allConversations.length) {
907
- console.log(`${RED}Invalid index #${targetIndex}. Available: 1 to ${allConversations.length}.${RESET}`)
908
- process.exit(1)
909
- }
910
- selectedConv = allConversations[targetIndex - 1]
911
- } else if (targetArg) {
912
- const found = allConversations.find(c => c.id.toLowerCase().startsWith(targetArg.toLowerCase()))
913
- if (!found) {
914
- console.log(`${RED}Conversation matching "${targetArg}" not found.${RESET}`)
915
- console.log(`Run ${CYAN}npx @katlux/toolkit tokens -p 1${RESET} to view all conversations.`)
916
- process.exit(1)
917
- }
918
- selectedConv = found
919
- }
920
-
921
- const steps = parseTranscript(selectedConv.path)
922
- if (!steps) {
923
- console.log(`${RED}No transcript found for conversation ${selectedConv.id}${RESET}`)
924
- process.exit(1)
925
- }
926
-
927
- const previewMeta = getConversationPreviewFast(selectedConv.path)
928
- const data = analyzeSession(steps, selectedConv.id, selectedConv.mtime, previewMeta.project)
929
- const convIndex = allConversations.findIndex(c => c.id === selectedConv.id) + 1
930
-
931
- // Print Dashboard
932
- console.log(`\n${BOLD}╭──────────────────────────────────────────────────────────────────────────╮${RESET}`)
933
- console.log(`${BOLD}│ AI CONVERSATION TOKEN LOG │${RESET}`)
934
- console.log(`${BOLD}╰──────────────────────────────────────────────────────────────────────────╯${RESET}`)
935
- console.log(` ${BOLD}Conversation Index:${RESET} ${GREEN}#${convIndex}${RESET} of ${allConversations.length}`)
936
- console.log(` ${BOLD}Project:${RESET} ${YELLOW}${data.project}${RESET} (${CYAN}${data.weekKey}${RESET})`)
937
- console.log(` ${BOLD}Conversation ID:${RESET} ${CYAN}${data.conversationId}${RESET}`)
938
- console.log(` ${BOLD}Topic / Prompt:${RESET} ${YELLOW}"${data.sessionTitle}"${RESET}`)
939
- console.log(` ${BOLD}Started:${RESET} ${formatDateTime(selectedConv.createdAt)}`)
940
- console.log(` ${BOLD}Last Active:${RESET} ${GREEN}${formatDateTime(selectedConv.lastActive)}${RESET}`)
941
- console.log(` ${BOLD}Total Steps:${RESET} ${data.totalSteps} recorded steps`)
942
- console.log(` ${BOLD}Transcript Size:${RESET} ${formatBytes(data.totalChars)} total characters\n`)
943
-
944
- console.log(`${BOLD}Token Summary (Estimated BPE):${RESET}`)
945
- console.log(` ${GREEN}● Total Tokens:${RESET} ${BOLD}${formatTokens(data.totalTokens)}${RESET} tokens (~${data.totalTokens.toLocaleString()})`)
946
- console.log(` ${BLUE}↳ Input Tokens:${RESET} ${formatTokens(data.inputTokens)} tokens (${Math.round((data.inputTokens / data.totalTokens) * 100 || 0)}%)`)
947
- console.log(` ${MAGENTA}↳ Output Tokens:${RESET} ${formatTokens(data.outputTokens)} tokens (${Math.round((data.outputTokens / data.totalTokens) * 100 || 0)}%)\n`)
948
-
949
- console.log(`${BOLD}Approximate Model Cost (if fresh API query):${RESET}`)
950
- const geminiCost = ((data.inputTokens / 1_000_000) * 0.35 + (data.outputTokens / 1_000_000) * 1.05).toFixed(4)
951
- const claudeCost = ((data.inputTokens / 1_000_000) * 3.00 + (data.outputTokens / 1_000_000) * 15.00).toFixed(4)
952
- const gptCost = ((data.inputTokens / 1_000_000) * 2.50 + (data.outputTokens / 1_000_000) * 10.00).toFixed(4)
953
- console.log(` Gemini 1.5/2.0 Flash : ${GREEN}$${geminiCost}${RESET}`)
954
- console.log(` Claude 3.5 Sonnet : ${YELLOW}$${claudeCost}${RESET}`)
955
- console.log(` GPT-4o : ${CYAN}$${gptCost}${RESET}\n`)
956
-
957
- // User turns / questions in this conversation
958
- if (data.userPrompts.length > 0) {
959
- console.log(`${BOLD}Conversation Turns (${data.userPrompts.length} User Requests):${RESET}`)
960
- if (data.userPrompts.length <= 8) {
961
- data.userPrompts.forEach((p, idx) => {
962
- const timeLabel = p.time ? `${DIM}(${p.time})${RESET} ` : ''
963
- console.log(` ${CYAN}Turn ${idx + 1}${RESET} [Step #${p.step}] ${timeLabel}${p.text.slice(0, 85)}${p.text.length > 85 ? '...' : ''}`)
964
- })
965
- } else {
966
- data.userPrompts.slice(0, 2).forEach((p, idx) => {
967
- const timeLabel = p.time ? `${DIM}(${p.time})${RESET} ` : ''
968
- console.log(` ${CYAN}Turn ${idx + 1}${RESET} [Step #${p.step}] ${timeLabel}${p.text.slice(0, 85)}${p.text.length > 85 ? '...' : ''}`)
969
- })
970
- console.log(` ${DIM}... and ${data.userPrompts.length - 8} earlier turns ...${RESET}`)
971
- const lastTurns = data.userPrompts.slice(-6)
972
- const startIdx = data.userPrompts.length - 6
973
- lastTurns.forEach((p, i) => {
974
- const idx = startIdx + i
975
- const timeLabel = p.time ? `${GREEN}(${p.time})${RESET} ` : ''
976
- console.log(` ${CYAN}Turn ${idx + 1}${RESET} [Step #${p.step}] ${timeLabel}${p.text.slice(0, 85)}${p.text.length > 85 ? '...' : ''}`)
977
- })
978
- }
979
- console.log(` ${DIM}Tip: Run with -d to see full chronology of every turn and tool call.${RESET}\n`)
980
- }
981
-
982
- console.log(`${BOLD}Token Breakdown by Event Category:${RESET}`)
983
- console.log(` ${'CATEGORY'.padEnd(25)} ${'CALLS'.padStart(6)} ${'TOKENS'.padStart(10)} ${'PERCENT'.padStart(8)}`)
984
- console.log(` ${'─'.repeat(25)} ${'─'.repeat(6)} ${'─'.repeat(10)} ${'─'.repeat(8)}`)
985
-
986
- Object.entries(data.categories)
987
- .filter(([_, cat]) => cat.count > 0)
988
- .sort((a, b) => b[1].tokens - a[1].tokens)
989
- .forEach(([type, cat]) => {
990
- const pct = Math.round((cat.tokens / data.totalTokens) * 100) || 0
991
- const color = pct > 40 ? RED : pct > 20 ? YELLOW : CYAN
992
- console.log(
993
- ` ${cat.label.padEnd(25)} ` +
994
- `${String(cat.count).padStart(6)} ` +
995
- `${BOLD}${formatTokens(cat.tokens).padStart(10)}${RESET} ` +
996
- `${color}${String(pct + '%').padStart(8)}${RESET}`
997
- )
998
- })
999
-
1000
- // Top Files Accessed
1001
- if (data.topViewedFiles.length > 0 || data.topModifiedFiles.length > 0) {
1002
- console.log(`\n${BOLD}Key Files Touched in this Session:${RESET}`)
1003
- if (data.topModifiedFiles.length > 0) {
1004
- console.log(` ${YELLOW}Modified:${RESET} ${data.topModifiedFiles.map(([f, n]) => `${f} (${n}x)`).join(', ')}`)
1005
- }
1006
- if (data.topViewedFiles.length > 0) {
1007
- console.log(` ${CYAN}Viewed:${RESET} ${data.topViewedFiles.map(([f, n]) => `${f} (${n}x)`).join(', ')}`)
1008
- }
1009
- }
1010
-
1011
- if (data.mcpCalls && data.mcpCalls.total > 0) {
1012
- console.log(`\n${BOLD}MCP Introspection Invocations:${RESET}`)
1013
- console.log(` katlux_inspect_project : ${data.mcpCalls.inspectProject} call(s)`)
1014
- console.log(` katlux_validate_code : ${data.mcpCalls.validateCode} call(s)`)
1015
- if (data.mcpCalls.otherMcp > 0) {
1016
- console.log(` other MCP tools : ${data.mcpCalls.otherMcp} call(s)`)
1017
- }
1018
- }
1019
-
1020
- console.log(`\n${BOLD}Top 5 Largest Token Spikes in this Session:${RESET}`)
1021
- data.spikes.forEach((spike, idx) => {
1022
- console.log(` ${idx + 1}. [Step #${spike.step_index}] ${YELLOW}${formatTokens(spike.tokens)} tokens${RESET} (${spike.type})`)
1023
- console.log(` ${DIM}"${spike.preview}..."${RESET}`)
1024
- })
1025
-
1026
- if (showDetail) {
1027
- console.log(`\n${BOLD}Full Step Chronology:${RESET}`)
1028
- steps.forEach(s => {
1029
- let c = ''
1030
- if (typeof s.content === 'string') c = s.content
1031
- else if (s.tool_calls) c = JSON.stringify(s.tool_calls)
1032
- else if (s.content) c = JSON.stringify(s.content)
1033
- const tok = estimateTokens(c)
1034
- const preview = c.replace(/[\r\n\t]+/g, ' ').slice(0, 60).trim()
1035
- console.log(` [#${String(s.step_index).padStart(3)}] ${s.type.padEnd(20)} ${formatTokens(tok).padStart(8)} tokens ${DIM}${preview}${RESET}`)
1036
- })
1037
- } else {
1038
- console.log(`\n${DIM}Commands:${RESET}`)
1039
- console.log(` • Weekly Report: ${CYAN}npx @katlux/toolkit tokens --report${RESET}`)
1040
- console.log(` • Browse list: ${CYAN}npx @katlux/toolkit tokens -p 1${RESET}`)
1041
- console.log(` • Search topic: ${CYAN}npx @katlux/toolkit tokens -s "<keyword>"${RESET}`)
1042
- console.log(` • View step log: ${CYAN}npx @katlux/toolkit tokens ${convIndex} -d${RESET}\n`)
49
+ if (isDirectExecution()) {
50
+ runAiTokensCli(process.argv.slice(2))
1043
51
  }