mux-sesh 2.0.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.
@@ -0,0 +1,278 @@
1
+ import { spawn } from 'bun'
2
+ import { readdir, readFile } from 'fs/promises'
3
+ import { join } from 'path'
4
+ import { SESSION_STORAGE, MESSAGE_STORAGE } from './constants'
5
+ import { getLastMessageTokens } from './tokens'
6
+ import type { OpencodeStats } from './types'
7
+
8
+ export async function getTmuxSessionDirectory(sessionName: string): Promise<string> {
9
+ try {
10
+ const proc = spawn(['tmux', 'display-message', '-t', sessionName, '-p', '#{pane_current_path}'])
11
+ const output = await new Response(proc.stdout).text()
12
+ return output.trim()
13
+ } catch (error) {
14
+ console.error('Failed to get tmux session directory:', error)
15
+ return ''
16
+ }
17
+ }
18
+
19
+ export async function getMessageCount(sessionID: string): Promise<number> {
20
+ try {
21
+ if (!sessionID) return 0
22
+
23
+ const messageDir = join(MESSAGE_STORAGE, sessionID)
24
+ const messageFiles = await readdir(messageDir).catch(() => [])
25
+
26
+ return messageFiles.filter(file => file.endsWith('.json')).length
27
+ } catch (error) {
28
+ console.error('Failed to get message count:', error)
29
+ return 0
30
+ }
31
+ }
32
+
33
+ export async function getAggregatedMessageCount(directory: string): Promise<number> {
34
+ try {
35
+ const projectDirs = await readdir(SESSION_STORAGE)
36
+ let totalMessages = 0
37
+
38
+ for (const projectID of projectDirs) {
39
+ const projectPath = join(SESSION_STORAGE, projectID)
40
+
41
+ try {
42
+ const sessionFiles = await readdir(projectPath)
43
+
44
+ for (const sessionFile of sessionFiles) {
45
+ if (!sessionFile.endsWith('.json')) continue
46
+
47
+ const sessionPath = join(projectPath, sessionFile)
48
+ const content = await readFile(sessionPath, 'utf-8')
49
+ const sessionData = JSON.parse(content)
50
+
51
+ if (sessionData.directory === directory) {
52
+ totalMessages += await getMessageCount(sessionData.id)
53
+ }
54
+ }
55
+ } catch (err) {
56
+ continue
57
+ }
58
+ }
59
+
60
+ return totalMessages
61
+ } catch (error) {
62
+ console.error('Failed to get aggregated message count:', error)
63
+ return 0
64
+ }
65
+ }
66
+
67
+ export async function getActiveOpencodeSession(directory: string): Promise<OpencodeStats | null> {
68
+ try {
69
+ const projectDirs = await readdir(SESSION_STORAGE)
70
+ const now = Date.now()
71
+ const fiveMinutesAgo = now - 5 * 60 * 1000
72
+
73
+ let mostRecentActive: OpencodeStats | null = null
74
+ let latestTime = 0
75
+
76
+ for (const projectID of projectDirs) {
77
+ const projectPath = join(SESSION_STORAGE, projectID)
78
+
79
+ try {
80
+ const sessionFiles = await readdir(projectPath)
81
+
82
+ for (const sessionFile of sessionFiles) {
83
+ if (!sessionFile.endsWith('.json')) continue
84
+
85
+ const sessionPath = join(projectPath, sessionFile)
86
+ const content = await readFile(sessionPath, 'utf-8')
87
+ const sessionData = JSON.parse(content)
88
+
89
+ if (sessionData.directory === directory) {
90
+ const updatedAt = sessionData.time?.updated || sessionData.time?.created || 0
91
+
92
+ if (updatedAt >= fiveMinutesAgo && updatedAt > latestTime) {
93
+ latestTime = updatedAt
94
+ const lastMessageData = await getLastMessageTokens(sessionData.id)
95
+ mostRecentActive = {
96
+ sessionID: sessionData.id,
97
+ title: sessionData.title,
98
+ projectID,
99
+ directory: sessionData.directory,
100
+ messageCount: await getMessageCount(sessionData.id),
101
+ filesModified: sessionData.summary?.files || 0,
102
+ additions: sessionData.summary?.additions || 0,
103
+ deletions: sessionData.summary?.deletions || 0,
104
+ createdAt: sessionData.time?.created,
105
+ updatedAt: sessionData.time?.updated,
106
+ lastMessageTokens: lastMessageData?.lastMessageTokens,
107
+ contextLimit: lastMessageData?.contextLimit,
108
+ sessionTotalCost: lastMessageData?.totalCost,
109
+ }
110
+ }
111
+ }
112
+ }
113
+ } catch (err) {
114
+ continue
115
+ }
116
+ }
117
+
118
+ return mostRecentActive
119
+ } catch (error) {
120
+ console.error('Failed to get active OpenCode session:', error)
121
+ return null
122
+ }
123
+ }
124
+
125
+ export async function getAggregatedOpencodeStats(directory: string): Promise<OpencodeStats | null> {
126
+ try {
127
+ const projectDirs = await readdir(SESSION_STORAGE)
128
+
129
+ let totalSessions = 0
130
+ let totalFiles = 0
131
+ let totalAdditions = 0
132
+ let totalDeletions = 0
133
+ let oldestTime = Date.now()
134
+ let newestTime = 0
135
+ let mostRecentSession: any = null
136
+
137
+ for (const projectID of projectDirs) {
138
+ const projectPath = join(SESSION_STORAGE, projectID)
139
+
140
+ try {
141
+ const sessionFiles = await readdir(projectPath)
142
+
143
+ for (const sessionFile of sessionFiles) {
144
+ if (!sessionFile.endsWith('.json')) continue
145
+
146
+ const sessionPath = join(projectPath, sessionFile)
147
+ const content = await readFile(sessionPath, 'utf-8')
148
+ const sessionData = JSON.parse(content)
149
+
150
+ if (sessionData.directory === directory) {
151
+ totalSessions++
152
+ totalFiles += sessionData.summary?.files || 0
153
+ totalAdditions += sessionData.summary?.additions || 0
154
+ totalDeletions += sessionData.summary?.deletions || 0
155
+
156
+ const createdAt = sessionData.time?.created || 0
157
+ const updatedAt = sessionData.time?.updated || sessionData.time?.created || 0
158
+
159
+ if (createdAt < oldestTime) oldestTime = createdAt
160
+ if (updatedAt > newestTime) {
161
+ newestTime = updatedAt
162
+ mostRecentSession = sessionData
163
+ }
164
+ }
165
+ }
166
+ } catch (err) {
167
+ continue
168
+ }
169
+ }
170
+
171
+ if (totalSessions === 0) return null
172
+
173
+ return {
174
+ title: `Global OpenCode Sessions (${totalSessions} total)`,
175
+ directory,
176
+ messageCount: await getAggregatedMessageCount(directory),
177
+ filesModified: totalFiles,
178
+ additions: totalAdditions,
179
+ deletions: totalDeletions,
180
+ createdAt: oldestTime,
181
+ updatedAt: newestTime,
182
+ sessionCount: totalSessions,
183
+ mostRecentTitle: mostRecentSession?.title || 'Unknown',
184
+ }
185
+ } catch (error) {
186
+ console.error('Failed to get aggregated OpenCode stats:', error)
187
+ return null
188
+ }
189
+ }
190
+
191
+ export async function getMostRecentSessionForDirectory(
192
+ directory: string
193
+ ): Promise<OpencodeStats | null> {
194
+ try {
195
+ const projectDirs = await readdir(SESSION_STORAGE)
196
+
197
+ let mostRecent: OpencodeStats | null = null
198
+ let latestTime = 0
199
+
200
+ for (const projectID of projectDirs) {
201
+ const projectPath = join(SESSION_STORAGE, projectID)
202
+
203
+ try {
204
+ const sessionFiles = await readdir(projectPath)
205
+
206
+ for (const sessionFile of sessionFiles) {
207
+ if (!sessionFile.endsWith('.json')) continue
208
+
209
+ const sessionPath = join(projectPath, sessionFile)
210
+ const content = await readFile(sessionPath, 'utf-8')
211
+ const sessionData = JSON.parse(content)
212
+
213
+ if (sessionData.directory === directory) {
214
+ const updatedAt = sessionData.time?.updated || sessionData.time?.created || 0
215
+
216
+ if (updatedAt > latestTime) {
217
+ latestTime = updatedAt
218
+ const lastMessageData = await getLastMessageTokens(sessionData.id)
219
+ mostRecent = {
220
+ sessionID: sessionData.id,
221
+ title: sessionData.title,
222
+ projectID,
223
+ directory: sessionData.directory,
224
+ messageCount: await getMessageCount(sessionData.id),
225
+ filesModified: sessionData.summary?.files || 0,
226
+ additions: sessionData.summary?.additions || 0,
227
+ deletions: sessionData.summary?.deletions || 0,
228
+ createdAt: sessionData.time?.created,
229
+ updatedAt: sessionData.time?.updated,
230
+ lastMessageTokens: lastMessageData?.lastMessageTokens,
231
+ contextLimit: lastMessageData?.contextLimit,
232
+ sessionTotalCost: lastMessageData?.totalCost,
233
+ }
234
+ }
235
+ }
236
+ }
237
+ } catch (err) {
238
+ continue
239
+ }
240
+ }
241
+
242
+ return mostRecent
243
+ } catch (error) {
244
+ console.error('Failed to get most recent session for directory:', error)
245
+ return null
246
+ }
247
+ }
248
+
249
+ export async function getDetailedSessionStats(sessionID: string): Promise<OpencodeStats | null> {
250
+ try {
251
+ const proc = spawn(['opencode', 'export', sessionID])
252
+ const output = await new Response(proc.stdout).text()
253
+
254
+ const jsonStart = output.indexOf('{')
255
+ if (jsonStart === -1) return null
256
+
257
+ const jsonData = output.slice(jsonStart)
258
+ const data = JSON.parse(jsonData)
259
+
260
+ const messageCount = data.messages?.length || 0
261
+
262
+ return {
263
+ sessionID: data.info?.id,
264
+ title: data.info?.title,
265
+ projectID: data.info?.projectID,
266
+ directory: data.info?.directory,
267
+ messageCount,
268
+ filesModified: data.info?.summary?.files || 0,
269
+ additions: data.info?.summary?.additions || 0,
270
+ deletions: data.info?.summary?.deletions || 0,
271
+ createdAt: data.info?.time?.created,
272
+ updatedAt: data.info?.time?.updated,
273
+ }
274
+ } catch (error) {
275
+ console.error('Failed to get detailed session stats:', error)
276
+ return null
277
+ }
278
+ }
@@ -0,0 +1,34 @@
1
+ import {
2
+ getTmuxSessionDirectory,
3
+ getActiveOpencodeSession,
4
+ getAggregatedOpencodeStats,
5
+ getMostRecentSessionForDirectory,
6
+ } from './session'
7
+ import type { OpencodeStats } from './types'
8
+
9
+ export async function getOpencodeSessionStats(
10
+ tmuxSessionName: string
11
+ ): Promise<OpencodeStats | null> {
12
+ try {
13
+ const tmuxDirectory = await getTmuxSessionDirectory(tmuxSessionName)
14
+ if (!tmuxDirectory) {
15
+ console.error('Could not determine tmux session directory')
16
+ return null
17
+ }
18
+
19
+ const activeSession = await getActiveOpencodeSession(tmuxDirectory)
20
+ if (activeSession) {
21
+ return activeSession
22
+ }
23
+
24
+ const homeDir = process.env.HOME || '/home/ghost'
25
+ if (tmuxDirectory === homeDir) {
26
+ return await getAggregatedOpencodeStats(tmuxDirectory)
27
+ }
28
+
29
+ return await getMostRecentSessionForDirectory(tmuxDirectory)
30
+ } catch (error) {
31
+ console.error('Failed to get OpenCode session stats:', error)
32
+ return null
33
+ }
34
+ }
@@ -0,0 +1,143 @@
1
+ import { spawn } from 'bun'
2
+ import { readdir, readFile } from 'fs/promises'
3
+ import { join } from 'path'
4
+ import { MESSAGE_STORAGE } from './constants'
5
+
6
+ export async function getModelContextLimit(modelID: string, providerID: string): Promise<number> {
7
+ try {
8
+ const proc = spawn(['opencode', 'models', providerID, '--verbose'])
9
+ const output = await new Response(proc.stdout).text()
10
+
11
+ const lines = output.split('\n')
12
+ let inTargetModel = false
13
+ let jsonBuffer = ''
14
+
15
+ for (let i = 0; i < lines.length; i++) {
16
+ const line = lines[i]
17
+
18
+ if (line === `${providerID}/${modelID}`) {
19
+ inTargetModel = true
20
+ jsonBuffer = ''
21
+ continue
22
+ }
23
+
24
+ if (inTargetModel) {
25
+ if (line.match(/^[a-z]+\//)) {
26
+ break
27
+ }
28
+ jsonBuffer += line + '\n'
29
+ }
30
+ }
31
+
32
+ if (jsonBuffer) {
33
+ const modelData = JSON.parse(jsonBuffer)
34
+ if (modelData.limit?.context) {
35
+ return modelData.limit.context
36
+ }
37
+ }
38
+
39
+ if (modelID.includes('claude-sonnet-4')) return 1000000 // Sonnet 4.x has 1M
40
+ if (modelID.includes('claude-opus-4')) return 200000
41
+ if (modelID.includes('claude-3')) return 200000
42
+ if (modelID.includes('gpt-4o')) return 128000
43
+ if (modelID.includes('gpt-4')) return 128000
44
+
45
+ return 200000
46
+ } catch (error) {
47
+ console.error('Failed to get model context limit:', error)
48
+
49
+ if (modelID.includes('claude-sonnet-4')) return 1000000
50
+ if (modelID.includes('claude')) return 200000
51
+ if (modelID.includes('gpt-4')) return 128000
52
+ return 200000
53
+ }
54
+ }
55
+
56
+ export async function getLastMessageTokens(sessionID: string): Promise<{
57
+ lastMessageTokens: number
58
+ contextLimit: number
59
+ totalCost: number
60
+ modelID?: string
61
+ providerID?: string
62
+ } | null> {
63
+ try {
64
+ if (!sessionID) return null
65
+
66
+ const messageDir = join(MESSAGE_STORAGE, sessionID)
67
+ const messageFiles = await readdir(messageDir).catch(() => [])
68
+
69
+ const messagesWithTime: Array<{ file: string; message: any; created: number }> = []
70
+
71
+ for (const file of messageFiles) {
72
+ if (!file.endsWith('.json')) continue
73
+
74
+ try {
75
+ const content = await readFile(join(messageDir, file), 'utf-8')
76
+ const message = JSON.parse(content)
77
+ messagesWithTime.push({
78
+ file,
79
+ message,
80
+ created: message.time?.created || 0,
81
+ })
82
+ } catch (err) {
83
+ continue
84
+ }
85
+ }
86
+
87
+ // Sort by time.created (chronological order)
88
+ messagesWithTime.sort((a, b) => a.created - b.created)
89
+
90
+ let totalCost = 0
91
+ let lastAssistantMessage: any = null
92
+
93
+ // Find last assistant message and calculate cumulative cost
94
+ for (const item of messagesWithTime) {
95
+ const message = item.message
96
+
97
+ if (message.role === 'assistant') {
98
+ totalCost += message.cost || 0
99
+
100
+ // Keep track of last assistant message with output > 0
101
+ if (message.tokens && message.tokens.output > 0) {
102
+ lastAssistantMessage = message
103
+ }
104
+ }
105
+ }
106
+
107
+ if (!lastAssistantMessage || !lastAssistantMessage.tokens) return null
108
+
109
+ const tokens = lastAssistantMessage.tokens
110
+ const lastMessageTotal =
111
+ (tokens.input || 0) +
112
+ (tokens.output || 0) +
113
+ (tokens.reasoning || 0) +
114
+ (tokens.cache?.read || 0) +
115
+ (tokens.cache?.write || 0)
116
+
117
+ // Get model context limit dynamically
118
+ const contextLimit = await getModelContextLimit(
119
+ lastAssistantMessage.modelID,
120
+ lastAssistantMessage.providerID
121
+ )
122
+
123
+ return {
124
+ lastMessageTokens: lastMessageTotal,
125
+ contextLimit,
126
+ totalCost,
127
+ modelID: lastAssistantMessage.modelID,
128
+ providerID: lastAssistantMessage.providerID,
129
+ }
130
+ } catch (error) {
131
+ console.error('Failed to get last message tokens:', error)
132
+ return null
133
+ }
134
+ }
135
+
136
+ export function estimateSessionCost(inputTokens: number, outputTokens: number): string {
137
+ const inputCost = (inputTokens / 1_000_000) * 3
138
+ const outputCost = (outputTokens / 1_000_000) * 15
139
+ const total = inputCost + outputCost
140
+
141
+ if (total < 0.01) return '<$0.01'
142
+ return `$${total.toFixed(2)}`
143
+ }
@@ -0,0 +1,33 @@
1
+ export interface OpencodeStats {
2
+ // Per-session stats
3
+ sessionID?: string
4
+ title?: string
5
+ projectID?: string
6
+ directory?: string
7
+ messageCount?: number
8
+ filesModified?: number
9
+ additions?: number
10
+ deletions?: number
11
+ createdAt?: number
12
+ updatedAt?: number
13
+
14
+ // Global stats
15
+ totalSessions?: number
16
+ totalMessages?: number
17
+ totalCost?: string
18
+ costPerDay?: string
19
+ inputTokens?: string
20
+ outputTokens?: string
21
+ cacheRead?: string
22
+ cacheWrite?: string
23
+ topTools?: Array<{ name: string; count: number; percentage: string }>
24
+
25
+ // Aggregated stats (for home directory sessions)
26
+ sessionCount?: number
27
+ mostRecentTitle?: string
28
+
29
+ // Current session live stats (last message)
30
+ lastMessageTokens?: number
31
+ contextLimit?: number
32
+ sessionTotalCost?: number
33
+ }
@@ -0,0 +1,148 @@
1
+ import type { Item, SearchResult, FuzzyMatch } from '../types'
2
+
3
+ /**
4
+ * Performs fuzzy matching and returns match positions and score
5
+ * Similar to fzf/telescope matching algorithm
6
+ */
7
+ export function fuzzyMatch(text: string, query: string): FuzzyMatch | null {
8
+ if (!query) return { score: 0, indices: [] }
9
+
10
+ const textLower = text.toLowerCase()
11
+ const queryLower = query.toLowerCase()
12
+
13
+ // Track matched character positions
14
+ const indices: number[] = []
15
+ let textIndex = 0
16
+ let queryIndex = 0
17
+
18
+ // Find all query characters in order
19
+ while (queryIndex < queryLower.length && textIndex < textLower.length) {
20
+ if (textLower[textIndex] === queryLower[queryIndex]) {
21
+ indices.push(textIndex)
22
+ queryIndex++
23
+ }
24
+ textIndex++
25
+ }
26
+
27
+ // If we didn't match all characters, no match
28
+ if (queryIndex !== queryLower.length) {
29
+ return null
30
+ }
31
+
32
+ // Calculate score based on match quality
33
+ let score = 100
34
+
35
+ // Bonus for exact match
36
+ if (text.toLowerCase() === query.toLowerCase()) {
37
+ score += 10000
38
+ }
39
+
40
+ // Bonus for match at start
41
+ if (indices[0] === 0) {
42
+ score += 1000
43
+ }
44
+
45
+ // Bonus for consecutive characters
46
+ let consecutiveBonus = 0
47
+ for (let i = 1; i < indices.length; i++) {
48
+ if (indices[i] === indices[i - 1] + 1) {
49
+ consecutiveBonus += 50
50
+ }
51
+ }
52
+ score += consecutiveBonus
53
+
54
+ // Bonus for matches after word boundaries (-, _, ., space, /)
55
+ let boundaryBonus = 0
56
+ for (const idx of indices) {
57
+ if (idx > 0) {
58
+ const prevChar = text[idx - 1]
59
+ if (['-', '_', '.', ' ', '/'].includes(prevChar)) {
60
+ boundaryBonus += 30
61
+ }
62
+ }
63
+ }
64
+ score += boundaryBonus
65
+
66
+ // Bonus for case-sensitive exact character matches
67
+ let caseBonus = 0
68
+ for (const idx of indices) {
69
+ if (text[idx] === query[indices.indexOf(idx)]) {
70
+ caseBonus += 10
71
+ }
72
+ }
73
+ score += caseBonus
74
+
75
+ // Penalty for early gaps (characters not matched at the beginning)
76
+ const firstMatchPos = indices[0]
77
+ score -= firstMatchPos * 5
78
+
79
+ // Penalty for length of text (shorter matches are better)
80
+ score -= text.length * 2
81
+
82
+ // Bonus for matching a higher percentage of the text
83
+ const matchPercentage = indices.length / text.length
84
+ score += matchPercentage * 100
85
+
86
+ return { score, indices }
87
+ }
88
+
89
+ export function calculateSearchScore(item: Item, query: string): number {
90
+ const queryTrimmed = query.trim()
91
+ if (queryTrimmed === '') return 1
92
+
93
+ let bestScore = 0
94
+ let hasMatch = false
95
+
96
+ // Try fuzzy matching on title
97
+ const titleMatch = fuzzyMatch(item.title, queryTrimmed)
98
+ if (titleMatch && titleMatch.score > 0) {
99
+ ;(item as any).titleMatchIndices = titleMatch.indices
100
+ bestScore = Math.max(bestScore, titleMatch.score)
101
+ hasMatch = true
102
+ } else {
103
+ delete (item as any).titleMatchIndices
104
+ }
105
+
106
+ // Try fuzzy matching on description
107
+ if (item.desc) {
108
+ const descMatch = fuzzyMatch(item.desc, queryTrimmed)
109
+ if (descMatch && descMatch.score > 0) {
110
+ ;(item as any).descMatchIndices = descMatch.indices
111
+ // Use the better score - prefer title matches slightly
112
+ bestScore = Math.max(bestScore, descMatch.score * 0.8)
113
+ hasMatch = true
114
+ } else {
115
+ delete (item as any).descMatchIndices
116
+ }
117
+ }
118
+
119
+ return hasMatch ? bestScore : 0
120
+ }
121
+
122
+ /**
123
+ * Clears match indices from items
124
+ */
125
+ export function clearMatchIndices(items: Item[]): void {
126
+ items.forEach(item => {
127
+ delete (item as any).titleMatchIndices
128
+ delete (item as any).descMatchIndices
129
+ })
130
+ }
131
+
132
+ export function filterAndSortItems(items: Item[], query: string): Item[] {
133
+ if (!query.trim()) {
134
+ // Clear any previous match indices
135
+ clearMatchIndices(items)
136
+ return items
137
+ }
138
+
139
+ const scored: SearchResult[] = items
140
+ .map(item => ({
141
+ item,
142
+ score: calculateSearchScore(item, query),
143
+ }))
144
+ .filter(({ score }) => score > 0)
145
+ .sort((a, b) => b.score - a.score)
146
+
147
+ return scored.map(({ item }) => item)
148
+ }
@@ -0,0 +1,46 @@
1
+ export const colors = {
2
+ primary: '#f38ba8',
3
+ active: '#a6e3a1',
4
+ inactive: '#6c7086',
5
+ text: '#cdd6f4',
6
+ border: '#89b4fa',
7
+ background: '#1e1e2e',
8
+ backgroundAlt: '#313244',
9
+ key: '#f9e2af',
10
+ action: '#cba6f7',
11
+ separator: '#585b70',
12
+ program: '#fab387',
13
+ fileTree: '#94e2d5',
14
+ }
15
+
16
+ export const sessionListStyle = {
17
+ border: true,
18
+ borderStyle: 'rounded' as const,
19
+ borderColor: colors.border,
20
+ padding: 0.3,
21
+ width: 65,
22
+ height: 38,
23
+ }
24
+
25
+ export const sessionListStyleFull = {
26
+ ...sessionListStyle,
27
+ width: 110,
28
+ }
29
+
30
+ export const detailPanelStyle = {
31
+ border: true,
32
+ borderStyle: 'rounded' as const,
33
+ borderColor: colors.border,
34
+ padding: 0.3,
35
+ width: 65,
36
+ height: 38,
37
+ }
38
+
39
+ export const selectedStyle = {
40
+ fg: colors.text,
41
+ backgroundColor: colors.backgroundAlt,
42
+ }
43
+
44
+ export const normalStyle = {
45
+ fg: colors.text,
46
+ }