@bahulam/code 2.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 (273) hide show
  1. package/README.md +80 -0
  2. package/package.json +49 -0
  3. package/pulse/app/activity/page.tsx +190 -0
  4. package/pulse/app/api/activity/route.ts +138 -0
  5. package/pulse/app/api/benchmark/route.ts +113 -0
  6. package/pulse/app/api/benchmarks/route.ts +195 -0
  7. package/pulse/app/api/costs/route.ts +88 -0
  8. package/pulse/app/api/export/route.ts +77 -0
  9. package/pulse/app/api/history/route.ts +11 -0
  10. package/pulse/app/api/import/route.ts +31 -0
  11. package/pulse/app/api/memory/route.ts +50 -0
  12. package/pulse/app/api/plans/route.ts +9 -0
  13. package/pulse/app/api/projects/[slug]/route.ts +96 -0
  14. package/pulse/app/api/projects/route.ts +121 -0
  15. package/pulse/app/api/sessions/[id]/replay/route.ts +20 -0
  16. package/pulse/app/api/sessions/[id]/route.ts +31 -0
  17. package/pulse/app/api/sessions/route.ts +112 -0
  18. package/pulse/app/api/settings/route.ts +14 -0
  19. package/pulse/app/api/stats/route.ts +143 -0
  20. package/pulse/app/api/todos/route.ts +9 -0
  21. package/pulse/app/api/tools/route.ts +160 -0
  22. package/pulse/app/benchmarks/page.tsx +224 -0
  23. package/pulse/app/costs/page.tsx +179 -0
  24. package/pulse/app/export/page.tsx +465 -0
  25. package/pulse/app/favicon.ico +0 -0
  26. package/pulse/app/globals.css +263 -0
  27. package/pulse/app/help/page.tsx +143 -0
  28. package/pulse/app/history/page.tsx +157 -0
  29. package/pulse/app/layout.tsx +46 -0
  30. package/pulse/app/memory/page.tsx +365 -0
  31. package/pulse/app/overview-client.tsx +393 -0
  32. package/pulse/app/page.tsx +14 -0
  33. package/pulse/app/plans/page.tsx +308 -0
  34. package/pulse/app/projects/[slug]/page.tsx +390 -0
  35. package/pulse/app/projects/page.tsx +110 -0
  36. package/pulse/app/sessions/[id]/page.tsx +243 -0
  37. package/pulse/app/sessions/page.tsx +39 -0
  38. package/pulse/app/settings/page.tsx +188 -0
  39. package/pulse/app/todos/page.tsx +211 -0
  40. package/pulse/app/tools/page.tsx +249 -0
  41. package/pulse/cli.js +164 -0
  42. package/pulse/components/activity/day-of-week-chart.tsx +35 -0
  43. package/pulse/components/activity/streak-card.tsx +36 -0
  44. package/pulse/components/costs/cache-efficiency-panel.tsx +76 -0
  45. package/pulse/components/costs/cost-by-project-chart.tsx +48 -0
  46. package/pulse/components/costs/cost-over-time-chart.tsx +95 -0
  47. package/pulse/components/costs/model-token-table.tsx +60 -0
  48. package/pulse/components/global-search.tsx +193 -0
  49. package/pulse/components/keyboard-nav-provider.tsx +23 -0
  50. package/pulse/components/layout/bottom-nav.tsx +53 -0
  51. package/pulse/components/layout/client-layout.tsx +31 -0
  52. package/pulse/components/layout/sidebar-context.tsx +50 -0
  53. package/pulse/components/layout/sidebar.tsx +183 -0
  54. package/pulse/components/layout/top-bar.tsx +121 -0
  55. package/pulse/components/overview/activity-heatmap.tsx +107 -0
  56. package/pulse/components/overview/conversation-table.tsx +148 -0
  57. package/pulse/components/overview/model-breakdown-donut.tsx +95 -0
  58. package/pulse/components/overview/peak-hours-chart.tsx +87 -0
  59. package/pulse/components/overview/project-activity-donut.tsx +96 -0
  60. package/pulse/components/overview/stat-card.tsx +102 -0
  61. package/pulse/components/overview/usage-over-time-chart.tsx +166 -0
  62. package/pulse/components/projects/project-card.tsx +175 -0
  63. package/pulse/components/sessions/replay/assistant-markdown.tsx +94 -0
  64. package/pulse/components/sessions/replay/compaction-card.tsx +25 -0
  65. package/pulse/components/sessions/replay/session-sidebar.tsx +231 -0
  66. package/pulse/components/sessions/replay/token-accumulation-chart.tsx +98 -0
  67. package/pulse/components/sessions/replay/tool-call-badge.tsx +127 -0
  68. package/pulse/components/sessions/replay/turn-cards.tsx +220 -0
  69. package/pulse/components/sessions/replay/user-tool-result.tsx +158 -0
  70. package/pulse/components/sessions/session-badges.tsx +49 -0
  71. package/pulse/components/sessions/session-table.tsx +299 -0
  72. package/pulse/components/theme-provider.tsx +44 -0
  73. package/pulse/components/tools/feature-adoption-table.tsx +58 -0
  74. package/pulse/components/tools/mcp-server-panel.tsx +45 -0
  75. package/pulse/components/tools/tool-ranking-chart.tsx +57 -0
  76. package/pulse/components/tools/version-history-table.tsx +32 -0
  77. package/pulse/components/ui/alert.tsx +66 -0
  78. package/pulse/components/ui/badge.tsx +48 -0
  79. package/pulse/components/ui/breadcrumb.tsx +109 -0
  80. package/pulse/components/ui/button.tsx +64 -0
  81. package/pulse/components/ui/calendar.tsx +220 -0
  82. package/pulse/components/ui/card.tsx +92 -0
  83. package/pulse/components/ui/command.tsx +158 -0
  84. package/pulse/components/ui/dialog.tsx +158 -0
  85. package/pulse/components/ui/input.tsx +21 -0
  86. package/pulse/components/ui/popover.tsx +89 -0
  87. package/pulse/components/ui/progress.tsx +31 -0
  88. package/pulse/components/ui/select.tsx +190 -0
  89. package/pulse/components/ui/separator.tsx +28 -0
  90. package/pulse/components/ui/sheet.tsx +143 -0
  91. package/pulse/components/ui/skeleton.tsx +13 -0
  92. package/pulse/components/ui/table.tsx +116 -0
  93. package/pulse/components/ui/tabs.tsx +91 -0
  94. package/pulse/components/ui/tooltip.tsx +57 -0
  95. package/pulse/components/use-global-keyboard-nav.ts +79 -0
  96. package/pulse/components.json +23 -0
  97. package/pulse/eslint.config.mjs +18 -0
  98. package/pulse/lib/bahulam-paths.ts +23 -0
  99. package/pulse/lib/claude-reader.ts +592 -0
  100. package/pulse/lib/decode.ts +129 -0
  101. package/pulse/lib/pricing.ts +102 -0
  102. package/pulse/lib/replay-parser.ts +165 -0
  103. package/pulse/lib/tool-categories.ts +127 -0
  104. package/pulse/lib/utils.ts +6 -0
  105. package/pulse/next-env.d.ts +6 -0
  106. package/pulse/next.config.ts +16 -0
  107. package/pulse/package.json +45 -0
  108. package/pulse/postcss.config.mjs +7 -0
  109. package/pulse/public/activity.png +0 -0
  110. package/pulse/public/cc-lens.png +0 -0
  111. package/pulse/public/command-k.png +0 -0
  112. package/pulse/public/costs.png +0 -0
  113. package/pulse/public/dashboard-dark.png +0 -0
  114. package/pulse/public/dashboard-white.png +0 -0
  115. package/pulse/public/export.png +0 -0
  116. package/pulse/public/file.svg +1 -0
  117. package/pulse/public/globe.svg +1 -0
  118. package/pulse/public/next.svg +1 -0
  119. package/pulse/public/projects.png +0 -0
  120. package/pulse/public/session-chat.png +0 -0
  121. package/pulse/public/todos.png +0 -0
  122. package/pulse/public/tools.png +0 -0
  123. package/pulse/public/vercel.svg +1 -0
  124. package/pulse/public/window.svg +1 -0
  125. package/pulse/tsconfig.json +34 -0
  126. package/pulse/types/claude.ts +294 -0
  127. package/src/agents/loader.mjs +94 -0
  128. package/src/agents/multi_workflow_loader.mjs +330 -0
  129. package/src/agents/parser.mjs +205 -0
  130. package/src/agents/scaffold.mjs +222 -0
  131. package/src/agents/teams.mjs +123 -0
  132. package/src/agents/workflow_loader.mjs +122 -0
  133. package/src/agents/workflow_scaffold.mjs +249 -0
  134. package/src/auth/oauth.mjs +220 -0
  135. package/src/auth/tarang-auth.mjs +306 -0
  136. package/src/commands/agent.mjs +220 -0
  137. package/src/commands/workflow.mjs +581 -0
  138. package/src/config/cli-args.mjs +200 -0
  139. package/src/config/env.mjs +263 -0
  140. package/src/config/hook-runner.mjs +100 -0
  141. package/src/config/memory-loader.mjs +32 -0
  142. package/src/config/settings-loader.mjs +45 -0
  143. package/src/config/settings.mjs +132 -0
  144. package/src/context/ast-parser.mjs +298 -0
  145. package/src/context/bm25.mjs +85 -0
  146. package/src/context/retriever.mjs +308 -0
  147. package/src/context/skeleton.mjs +134 -0
  148. package/src/context/symbol-indexer.mjs +375 -0
  149. package/src/core/agent-history.mjs +111 -0
  150. package/src/core/agent-loop.mjs +486 -0
  151. package/src/core/approval-log.mjs +104 -0
  152. package/src/core/approval.mjs +476 -0
  153. package/src/core/attachments.mjs +380 -0
  154. package/src/core/backend-url.mjs +55 -0
  155. package/src/core/cache-control.mjs +92 -0
  156. package/src/core/cache.mjs +105 -0
  157. package/src/core/callback-client.mjs +180 -0
  158. package/src/core/checkpoints.mjs +142 -0
  159. package/src/core/compact-history.mjs +127 -0
  160. package/src/core/context-envelope.mjs +54 -0
  161. package/src/core/context-manager.mjs +198 -0
  162. package/src/core/error-guidance.mjs +311 -0
  163. package/src/core/file-diff.mjs +217 -0
  164. package/src/core/headless.mjs +448 -0
  165. package/src/core/hooks-manager.mjs +87 -0
  166. package/src/core/jsonl-writer.mjs +449 -0
  167. package/src/core/local-agent.mjs +537 -0
  168. package/src/core/local-store.mjs +836 -0
  169. package/src/core/mode-selector.mjs +51 -0
  170. package/src/core/output-filter.mjs +177 -0
  171. package/src/core/paths.mjs +190 -0
  172. package/src/core/policy-resolver.mjs +156 -0
  173. package/src/core/pricing.mjs +336 -0
  174. package/src/core/project-artifacts.mjs +39 -0
  175. package/src/core/project-context-loader.mjs +139 -0
  176. package/src/core/providers.mjs +219 -0
  177. package/src/core/rate-limit-display.mjs +121 -0
  178. package/src/core/rate-limiter.mjs +119 -0
  179. package/src/core/resume-mode.mjs +192 -0
  180. package/src/core/risk-tier.mjs +337 -0
  181. package/src/core/safety.mjs +203 -0
  182. package/src/core/scheduler.mjs +173 -0
  183. package/src/core/session-manager.mjs +360 -0
  184. package/src/core/session.mjs +143 -0
  185. package/src/core/settings-sync.mjs +85 -0
  186. package/src/core/stagnation.mjs +57 -0
  187. package/src/core/stream-client.mjs +829 -0
  188. package/src/core/streaming.mjs +182 -0
  189. package/src/core/system-prompt.mjs +140 -0
  190. package/src/core/tasks.mjs +196 -0
  191. package/src/core/tool-executor.mjs +1950 -0
  192. package/src/core/trust.mjs +158 -0
  193. package/src/core/work-scope.mjs +248 -0
  194. package/src/hooks/engine.mjs +162 -0
  195. package/src/index.mjs +426 -0
  196. package/src/mcp/client.mjs +253 -0
  197. package/src/mcp/transport-shttp.mjs +130 -0
  198. package/src/mcp/transport-sse.mjs +131 -0
  199. package/src/mcp/transport-ws.mjs +134 -0
  200. package/src/onboarding/preflight.mjs +360 -0
  201. package/src/permissions/checker.mjs +57 -0
  202. package/src/permissions/command-classifier.mjs +652 -0
  203. package/src/permissions/injection-check.mjs +60 -0
  204. package/src/permissions/path-check.mjs +102 -0
  205. package/src/permissions/prompt.mjs +73 -0
  206. package/src/permissions/sandbox.mjs +112 -0
  207. package/src/plugins/loader.mjs +138 -0
  208. package/src/skills/installer.mjs +188 -0
  209. package/src/skills/loader.mjs +252 -0
  210. package/src/skills/runner.mjs +55 -0
  211. package/src/state/orbit.mjs +263 -0
  212. package/src/state/verbosity.mjs +99 -0
  213. package/src/telemetry/index.mjs +96 -0
  214. package/src/terminal/agents.mjs +177 -0
  215. package/src/terminal/analytics.mjs +292 -0
  216. package/src/terminal/ansi.mjs +695 -0
  217. package/src/terminal/init.mjs +145 -0
  218. package/src/terminal/main.mjs +269 -0
  219. package/src/terminal/repl-explore.mjs +35 -0
  220. package/src/terminal/repl-format.mjs +257 -0
  221. package/src/terminal/repl-render.mjs +561 -0
  222. package/src/terminal/repl-resume.mjs +625 -0
  223. package/src/terminal/repl-state.mjs +103 -0
  224. package/src/terminal/repl-utils.mjs +34 -0
  225. package/src/terminal/repl.mjs +3832 -0
  226. package/src/terminal/skills.mjs +54 -0
  227. package/src/terminal/tool-display.mjs +240 -0
  228. package/src/tools/agent.mjs +137 -0
  229. package/src/tools/ask-user.mjs +61 -0
  230. package/src/tools/bash.mjs +231 -0
  231. package/src/tools/cron-create.mjs +120 -0
  232. package/src/tools/cron-delete.mjs +49 -0
  233. package/src/tools/cron-list.mjs +37 -0
  234. package/src/tools/edit.mjs +82 -0
  235. package/src/tools/enter-worktree.mjs +69 -0
  236. package/src/tools/exit-worktree.mjs +57 -0
  237. package/src/tools/glob.mjs +117 -0
  238. package/src/tools/grep.mjs +129 -0
  239. package/src/tools/lint.mjs +71 -0
  240. package/src/tools/ls.mjs +58 -0
  241. package/src/tools/lsp.mjs +115 -0
  242. package/src/tools/multi-edit.mjs +94 -0
  243. package/src/tools/notebook-edit.mjs +96 -0
  244. package/src/tools/project-overview.mjs +641 -0
  245. package/src/tools/read-mcp-resource.mjs +57 -0
  246. package/src/tools/read.mjs +138 -0
  247. package/src/tools/registry.mjs +116 -0
  248. package/src/tools/remote-trigger.mjs +84 -0
  249. package/src/tools/send-message.mjs +64 -0
  250. package/src/tools/skill.mjs +52 -0
  251. package/src/tools/test-runner.mjs +49 -0
  252. package/src/tools/todo-write.mjs +68 -0
  253. package/src/tools/tool-search.mjs +77 -0
  254. package/src/tools/web-fetch.mjs +65 -0
  255. package/src/tools/web-search.mjs +89 -0
  256. package/src/tools/write.mjs +55 -0
  257. package/src/ui/approval.mjs +263 -0
  258. package/src/ui/banner.mjs +235 -0
  259. package/src/ui/commands.mjs +537 -0
  260. package/src/ui/formatter.mjs +409 -0
  261. package/src/ui/icons.mjs +164 -0
  262. package/src/ui/input-dock.mjs +444 -0
  263. package/src/ui/markdown.mjs +278 -0
  264. package/src/ui/mission-report.mjs +296 -0
  265. package/src/ui/palette.mjs +189 -0
  266. package/src/ui/slash-commands.mjs +245 -0
  267. package/src/ui/spinner.mjs +116 -0
  268. package/src/ui/sub-agent.mjs +152 -0
  269. package/src/ui/term.mjs +159 -0
  270. package/src/ui/text-layout.mjs +127 -0
  271. package/src/ui/tool-card.mjs +463 -0
  272. package/src/ui/tool-details.mjs +312 -0
  273. package/src/ui/transcript-block.mjs +21 -0
@@ -0,0 +1,20 @@
1
+ import { NextResponse } from 'next/server'
2
+ import { findSessionJSONL } from '@/lib/claude-reader'
3
+ import { parseSessionReplay } from '@/lib/replay-parser'
4
+
5
+ export const dynamic = 'force-dynamic'
6
+
7
+ export async function GET(
8
+ _req: Request,
9
+ { params }: { params: Promise<{ id: string }> }
10
+ ) {
11
+ const { id } = await params
12
+ const jsonlPath = await findSessionJSONL(id)
13
+
14
+ if (!jsonlPath) {
15
+ return NextResponse.json({ error: 'Session JSONL not found' }, { status: 404 })
16
+ }
17
+
18
+ const replay = await parseSessionReplay(jsonlPath, id)
19
+ return NextResponse.json(replay)
20
+ }
@@ -0,0 +1,31 @@
1
+ import { NextResponse } from 'next/server'
2
+ import { readSessionMeta, readFacet, getSessions } from '@/lib/claude-reader'
3
+ import { estimateCostFromUsage } from '@/lib/pricing'
4
+
5
+ export const dynamic = 'force-dynamic'
6
+
7
+ export async function GET(
8
+ _req: Request,
9
+ { params }: { params: Promise<{ id: string }> }
10
+ ) {
11
+ const { id } = await params
12
+ const [meta, facet] = await Promise.all([readSessionMeta(id), readFacet(id)])
13
+
14
+ // readSessionMeta only finds session-meta/*.json files (legacy path).
15
+ // Fall back to JSONL-derived sessions for machines without that directory.
16
+ const resolved = meta ?? (await getSessions()).find(s => s.session_id === id) ?? null
17
+
18
+ if (!resolved) {
19
+ return NextResponse.json({ error: 'Session not found' }, { status: 404 })
20
+ }
21
+
22
+ const estimated_cost = estimateCostFromUsage('claude-opus-4-6', {
23
+ input_tokens: resolved.input_tokens ?? 0,
24
+ output_tokens: resolved.output_tokens ?? 0,
25
+ cache_creation_input_tokens: resolved.cache_creation_input_tokens ?? 0,
26
+ cache_read_input_tokens: resolved.cache_read_input_tokens ?? 0,
27
+ })
28
+
29
+ return NextResponse.json({ session: { ...resolved, facet, estimated_cost } })
30
+ }
31
+
@@ -0,0 +1,112 @@
1
+ import path from 'path'
2
+ import { NextResponse } from 'next/server'
3
+ import {
4
+ getSessions,
5
+ readAllSessionMeta,
6
+ readAllFacets,
7
+ listProjectSlugs,
8
+ listProjectJSONLFiles,
9
+ readJSONLLines,
10
+ } from '@/lib/claude-reader'
11
+ import { estimateCostFromUsage } from '@/lib/pricing'
12
+ import type { SessionWithFacet } from '@/types/claude'
13
+
14
+ export const dynamic = 'force-dynamic'
15
+
16
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
17
+ type AnyLine = Record<string, any>
18
+
19
+ async function enrichSessions(sessions: { session_id: string }[]) {
20
+ // Build a map of sessionId -> { slug, version, gitBranch, has_compaction, has_thinking }
21
+ const enrichment: Record<string, {
22
+ slug?: string
23
+ version?: string
24
+ git_branch?: string
25
+ has_compaction?: boolean
26
+ has_thinking?: boolean
27
+ }> = {}
28
+
29
+ const slugs = await listProjectSlugs()
30
+ await Promise.all(
31
+ slugs.map(async (slug) => {
32
+ const files = await listProjectJSONLFiles(slug)
33
+ await Promise.all(
34
+ files.map(async (f) => {
35
+ const sessionId = path.basename(f, '.jsonl')
36
+ const data: {
37
+ slug?: string; version?: string; gitBranch?: string
38
+ has_compaction?: boolean; has_thinking?: boolean
39
+ } = {}
40
+
41
+ await readJSONLLines(f, (line: AnyLine) => {
42
+ if (!data.slug && line.slug) data.slug = line.slug
43
+ if (!data.version && line.version) data.version = line.version
44
+ if (!data.gitBranch && line.gitBranch && line.gitBranch !== 'HEAD') {
45
+ data.gitBranch = line.gitBranch
46
+ }
47
+ if (line.type === 'system' && line.subtype === 'compact_boundary') {
48
+ data.has_compaction = true
49
+ }
50
+ if (line.type === 'assistant' && Array.isArray(line.message?.content)) {
51
+ if (line.message.content.some((c: AnyLine) => c.type === 'thinking')) {
52
+ data.has_thinking = true
53
+ }
54
+ }
55
+ })
56
+
57
+ enrichment[sessionId] = {
58
+ slug: data.slug,
59
+ version: data.version,
60
+ git_branch: data.gitBranch,
61
+ has_compaction: data.has_compaction,
62
+ has_thinking: data.has_thinking,
63
+ }
64
+ })
65
+ )
66
+ })
67
+ )
68
+ return enrichment
69
+ }
70
+
71
+ export async function GET() {
72
+ const [sessions, metaSessions, facets] = await Promise.all([
73
+ getSessions(),
74
+ readAllSessionMeta(),
75
+ readAllFacets(),
76
+ ])
77
+ const metaMap = new Map(metaSessions.map((s) => [s.session_id, s]))
78
+ const merged = sessions.map((s) => {
79
+ const meta = metaMap.get(s.session_id)
80
+ if (meta) return { ...meta, ...s } as typeof s
81
+ return s
82
+ })
83
+ const enrichment = await enrichSessions(merged)
84
+
85
+ const facetMap = new Map(facets.map(f => [f.session_id, f]))
86
+
87
+ const result: SessionWithFacet[] = merged.map(s => {
88
+ const facet = facetMap.get(s.session_id)
89
+ const enrich = enrichment[s.session_id] ?? {}
90
+
91
+ // Estimate cost from session tokens (rough: treat all as opus)
92
+ const estimated_cost = estimateCostFromUsage('claude-opus-4-6', {
93
+ input_tokens: s.input_tokens ?? 0,
94
+ output_tokens: s.output_tokens ?? 0,
95
+ cache_creation_input_tokens: s.cache_creation_input_tokens ?? 0,
96
+ cache_read_input_tokens: s.cache_read_input_tokens ?? 0,
97
+ })
98
+
99
+ return {
100
+ ...s,
101
+ facet,
102
+ estimated_cost,
103
+ slug: enrich.slug,
104
+ version: enrich.version,
105
+ git_branch: enrich.git_branch,
106
+ has_compaction: enrich.has_compaction ?? false,
107
+ has_thinking: enrich.has_thinking ?? false,
108
+ }
109
+ })
110
+
111
+ return NextResponse.json({ sessions: result, total: result.length })
112
+ }
@@ -0,0 +1,14 @@
1
+ import { NextResponse } from 'next/server'
2
+ import { readSettings, getClaudeStorageBytes, readSkills, readInstalledPlugins } from '@/lib/claude-reader'
3
+
4
+ export const dynamic = 'force-dynamic'
5
+
6
+ export async function GET() {
7
+ const [settings, storageBytes, skills, plugins] = await Promise.all([
8
+ readSettings(),
9
+ getClaudeStorageBytes(),
10
+ readSkills(),
11
+ readInstalledPlugins(),
12
+ ])
13
+ return NextResponse.json({ settings, storageBytes, skills, plugins })
14
+ }
@@ -0,0 +1,143 @@
1
+ import { NextResponse } from 'next/server'
2
+ import { readStatsCache, getSessions, getClaudeStorageBytes } from '@/lib/claude-reader'
3
+ import { estimateTotalCostFromModel, getPricing } from '@/lib/pricing'
4
+ import type { DailyActivity, SessionMeta } from '@/types/claude'
5
+
6
+ export const dynamic = 'force-dynamic'
7
+
8
+ /** Compute daily activity from session JSONL — fresher than stats-cache */
9
+ function computeDailyActivityFromSessions(sessions: SessionMeta[]): DailyActivity[] {
10
+ const byDate = new Map<string, { messages: number; sessions: number; tools: number }>()
11
+ for (const s of sessions) {
12
+ const date = s.start_time.slice(0, 10)
13
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) continue
14
+ const existing = byDate.get(date) ?? { messages: 0, sessions: 0, tools: 0 }
15
+ existing.messages += (s.user_message_count ?? 0) + (s.assistant_message_count ?? 0)
16
+ existing.sessions += 1
17
+ existing.tools += Object.values(s.tool_counts ?? {}).reduce((a, b) => a + b, 0)
18
+ byDate.set(date, existing)
19
+ }
20
+ return Array.from(byDate.entries())
21
+ .map(([date, { messages, sessions: count, tools }]) => ({
22
+ date,
23
+ messageCount: messages,
24
+ sessionCount: count,
25
+ toolCallCount: tools,
26
+ }))
27
+ .sort((a, b) => a.date.localeCompare(b.date))
28
+ }
29
+
30
+ /** Merge stats dailyActivity with session-derived data; session data overrides for same dates */
31
+ function mergeDailyActivity(
32
+ fromStats: DailyActivity[],
33
+ fromSessions: DailyActivity[]
34
+ ): DailyActivity[] {
35
+ const map = new Map<string, DailyActivity>()
36
+ for (const d of fromStats) map.set(d.date, d)
37
+ for (const d of fromSessions) map.set(d.date, d)
38
+ return Array.from(map.values()).sort((a, b) => a.date.localeCompare(b.date))
39
+ }
40
+
41
+ export async function GET() {
42
+ const [stats, sessions, storageBytes] = await Promise.all([
43
+ readStatsCache(),
44
+ getSessions(),
45
+ getClaudeStorageBytes(),
46
+ ])
47
+
48
+ const dailyFromSessions = computeDailyActivityFromSessions(sessions)
49
+ const dailyActivity = stats
50
+ ? mergeDailyActivity(stats.dailyActivity ?? [], dailyFromSessions)
51
+ : dailyFromSessions
52
+
53
+ const modelUsage = stats?.modelUsage ?? {}
54
+
55
+ // Compute estimated total cost from modelUsage
56
+ let totalCost = 0
57
+ let totalCacheSavings = 0
58
+ for (const [model, usage] of Object.entries(modelUsage)) {
59
+ const cost = estimateTotalCostFromModel(model, usage)
60
+ totalCost += cost
61
+ const p = getPricing(model)
62
+ totalCacheSavings += (usage.cacheReadInputTokens ?? 0) * (p.input - p.cacheRead)
63
+ }
64
+
65
+ // Compute total tokens
66
+ let totalInputTokens = 0
67
+ let totalOutputTokens = 0
68
+ let totalCacheReadTokens = 0
69
+ let totalCacheWriteTokens = 0
70
+ for (const usage of Object.values(modelUsage)) {
71
+ totalInputTokens += usage.inputTokens ?? 0
72
+ totalOutputTokens += usage.outputTokens ?? 0
73
+ totalCacheReadTokens += usage.cacheReadInputTokens ?? 0
74
+ totalCacheWriteTokens += usage.cacheCreationInputTokens ?? 0
75
+ }
76
+ const totalTokens = totalInputTokens + totalOutputTokens + totalCacheReadTokens + totalCacheWriteTokens
77
+
78
+ // Aggregate tool calls total
79
+ let totalToolCalls = 0
80
+ for (const s of sessions) {
81
+ for (const count of Object.values(s.tool_counts ?? {})) {
82
+ totalToolCalls += count
83
+ }
84
+ }
85
+
86
+ // Active days (days with at least 1 session)
87
+ const activeDays = dailyActivity.filter(d => d.sessionCount > 0).length
88
+
89
+ // Average session length
90
+ const avgSessionMinutes =
91
+ sessions.length > 0
92
+ ? sessions.reduce((sum, s) => sum + (s.duration_minutes ?? 0), 0) / sessions.length
93
+ : 0
94
+
95
+ // Sessions this month & week
96
+ const now = new Date()
97
+ const monthStart = new Date(now.getFullYear(), now.getMonth(), 1)
98
+ const weekStart = new Date(now)
99
+ weekStart.setDate(now.getDate() - 7)
100
+
101
+ const sessionsThisMonth = sessions.filter(
102
+ s => new Date(s.start_time) >= monthStart
103
+ ).length
104
+ const sessionsThisWeek = sessions.filter(
105
+ s => new Date(s.start_time) >= weekStart
106
+ ).length
107
+
108
+ const statsOut = stats
109
+ ? { ...stats, dailyActivity }
110
+ : {
111
+ version: 0,
112
+ lastComputedDate: '',
113
+ dailyActivity,
114
+ tokensByDate: [],
115
+ modelUsage: {},
116
+ totalSessions: sessions.length,
117
+ totalMessages: sessions.reduce((s, m) => s + (m.user_message_count ?? 0) + (m.assistant_message_count ?? 0), 0),
118
+ longestSession: { sessionId: '', duration: 0, messageCount: 0, timestamp: '' },
119
+ firstSessionDate: sessions[sessions.length - 1]?.start_time ?? '',
120
+ hourCounts: {},
121
+ totalSpeculationTimeSavedMs: 0,
122
+ }
123
+
124
+ return NextResponse.json({
125
+ stats: statsOut,
126
+ computed: {
127
+ totalCost,
128
+ totalCacheSavings,
129
+ totalTokens,
130
+ totalInputTokens,
131
+ totalOutputTokens,
132
+ totalCacheReadTokens,
133
+ totalCacheWriteTokens,
134
+ totalToolCalls,
135
+ activeDays,
136
+ avgSessionMinutes,
137
+ sessionsThisMonth,
138
+ sessionsThisWeek,
139
+ storageBytes,
140
+ sessionCount: sessions.length,
141
+ },
142
+ })
143
+ }
@@ -0,0 +1,9 @@
1
+ import { NextResponse } from 'next/server'
2
+ import { readTodos } from '@/lib/claude-reader'
3
+
4
+ export const dynamic = 'force-dynamic'
5
+
6
+ export async function GET() {
7
+ const todos = await readTodos()
8
+ return NextResponse.json({ todos })
9
+ }
@@ -0,0 +1,160 @@
1
+ import path from 'path'
2
+ import { NextResponse } from 'next/server'
3
+ import { getSessions, listProjectSlugs, listProjectJSONLFiles, readJSONLLines } from '@/lib/claude-reader'
4
+ import { categorizeTool, isMcpTool, parseMcpTool } from '@/lib/tool-categories'
5
+ import type { ToolsAnalytics, ToolSummary, McpServerSummary, VersionRecord } from '@/types/claude'
6
+
7
+ export const dynamic = 'force-dynamic'
8
+
9
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
10
+ type AnyLine = Record<string, any>
11
+
12
+ export async function GET() {
13
+ const sessions = await getSessions()
14
+ const totalSessions = sessions.length
15
+
16
+ // ── Aggregate tool counts across all sessions ──────────────────────────────
17
+ const toolTotals = new Map<string, number>()
18
+ const toolSessionCount = new Map<string, Set<string>>()
19
+ const mcpServerCalls = new Map<string, Map<string, number>>()
20
+ const mcpServerSessions = new Map<string, Set<string>>()
21
+ const errorCategories: Record<string, number> = {}
22
+ let totalErrors = 0
23
+
24
+ for (const s of sessions) {
25
+ const sid = s.session_id
26
+ for (const [tool, count] of Object.entries(s.tool_counts ?? {})) {
27
+ toolTotals.set(tool, (toolTotals.get(tool) ?? 0) + count)
28
+ if (!toolSessionCount.has(tool)) toolSessionCount.set(tool, new Set())
29
+ toolSessionCount.get(tool)!.add(sid)
30
+
31
+ if (isMcpTool(tool)) {
32
+ const parsed = parseMcpTool(tool)
33
+ if (parsed) {
34
+ if (!mcpServerCalls.has(parsed.server)) mcpServerCalls.set(parsed.server, new Map())
35
+ if (!mcpServerSessions.has(parsed.server)) mcpServerSessions.set(parsed.server, new Set())
36
+ const srv = mcpServerCalls.get(parsed.server)!
37
+ srv.set(parsed.tool, (srv.get(parsed.tool) ?? 0) + count)
38
+ mcpServerSessions.get(parsed.server)!.add(sid)
39
+ }
40
+ }
41
+ }
42
+
43
+ // Error categories
44
+ for (const [cat, count] of Object.entries(s.tool_error_categories ?? {})) {
45
+ errorCategories[cat] = (errorCategories[cat] ?? 0) + count
46
+ totalErrors += count
47
+ }
48
+ }
49
+
50
+ // ── Build ToolSummary list ─────────────────────────────────────────────────
51
+ const tools: ToolSummary[] = [...toolTotals.entries()]
52
+ .map(([name, total_calls]) => ({
53
+ name,
54
+ category: categorizeTool(name),
55
+ total_calls,
56
+ session_count: toolSessionCount.get(name)?.size ?? 0,
57
+ error_count: 0,
58
+ }))
59
+ .sort((a, b) => b.total_calls - a.total_calls)
60
+
61
+ const totalToolCalls = tools.reduce((s, t) => s + t.total_calls, 0)
62
+
63
+ // ── MCP server summaries ───────────────────────────────────────────────────
64
+ const mcp_servers: McpServerSummary[] = [...mcpServerCalls.entries()]
65
+ .map(([server_name, toolMap]) => {
66
+ const toolArr = [...toolMap.entries()]
67
+ .map(([name, calls]) => ({ name, calls }))
68
+ .sort((a, b) => b.calls - a.calls)
69
+ const total_calls = toolArr.reduce((s, t) => s + t.calls, 0)
70
+ return {
71
+ server_name,
72
+ tools: toolArr,
73
+ total_calls,
74
+ session_count: mcpServerSessions.get(server_name)?.size ?? 0,
75
+ }
76
+ })
77
+ .sort((a, b) => b.total_calls - a.total_calls)
78
+
79
+ // ── Feature adoption ──────────────────────────────────────────────────────
80
+ const featureSessions = {
81
+ task_agents: sessions.filter(s => s.uses_task_agent || (s.tool_counts?.Task ?? 0) > 0).length,
82
+ mcp: sessions.filter(s => s.uses_mcp || Object.keys(s.tool_counts ?? {}).some(isMcpTool)).length,
83
+ web_search: sessions.filter(s => s.uses_web_search || (s.tool_counts?.WebSearch ?? 0) > 0).length,
84
+ web_fetch: sessions.filter(s => s.uses_web_fetch || (s.tool_counts?.WebFetch ?? 0) > 0).length,
85
+ plan_mode: sessions.filter(s => (s.tool_counts?.EnterPlanMode ?? 0) > 0).length,
86
+ git_commits: sessions.filter(s => (s.git_commits ?? 0) > 0).length,
87
+ }
88
+
89
+ const feature_adoption: Record<string, { sessions: number; pct: number }> = {}
90
+ for (const [key, count] of Object.entries(featureSessions)) {
91
+ feature_adoption[key] = { sessions: count, pct: totalSessions > 0 ? count / totalSessions : 0 }
92
+ }
93
+
94
+ // ── Version + branch info from JSONL ─────────────────────────────────────
95
+ const versionData = new Map<string, { sessions: Set<string>; dates: string[] }>()
96
+ const branchTurns = new Map<string, number>()
97
+
98
+ const slugs = await listProjectSlugs()
99
+ await Promise.all(
100
+ slugs.map(async (slug) => {
101
+ const files = await listProjectJSONLFiles(slug)
102
+ await Promise.all(
103
+ files.map(async (f) => {
104
+ const sessionId = path.basename(f, '.jsonl')
105
+ let fileVersion: string | undefined
106
+ let fileDate: string | undefined
107
+
108
+ await readJSONLLines(f, (line: AnyLine) => {
109
+ if (!fileVersion && line.version) {
110
+ fileVersion = line.version
111
+ fileDate = line.timestamp
112
+ }
113
+ if (line.gitBranch && line.gitBranch !== 'HEAD') {
114
+ branchTurns.set(line.gitBranch, (branchTurns.get(line.gitBranch) ?? 0) + 1)
115
+ }
116
+ })
117
+
118
+ if (fileVersion) {
119
+ if (!versionData.has(fileVersion)) {
120
+ versionData.set(fileVersion, { sessions: new Set(), dates: [] })
121
+ }
122
+ const vd = versionData.get(fileVersion)!
123
+ vd.sessions.add(sessionId)
124
+ if (fileDate) vd.dates.push(fileDate)
125
+ }
126
+ })
127
+ )
128
+ })
129
+ )
130
+
131
+ const versions: VersionRecord[] = [...versionData.entries()]
132
+ .map(([version, data]) => {
133
+ const sortedDates = data.dates.sort()
134
+ return {
135
+ version,
136
+ session_count: data.sessions.size,
137
+ first_seen: sortedDates[0] ?? '',
138
+ last_seen: sortedDates[sortedDates.length - 1] ?? '',
139
+ }
140
+ })
141
+ .sort((a, b) => b.last_seen.localeCompare(a.last_seen))
142
+
143
+ const branches = [...branchTurns.entries()]
144
+ .map(([branch, turns]) => ({ branch, turns }))
145
+ .sort((a, b) => b.turns - a.turns)
146
+ .slice(0, 15)
147
+
148
+ const result: ToolsAnalytics = {
149
+ tools,
150
+ mcp_servers,
151
+ feature_adoption,
152
+ versions,
153
+ branches,
154
+ error_categories: errorCategories,
155
+ total_tool_calls: totalToolCalls,
156
+ total_errors: totalErrors,
157
+ }
158
+
159
+ return NextResponse.json(result)
160
+ }