mux-sesh 1.3.7 → 1.4.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.
- package/README.md +2 -2
- package/package.json +1 -1
- package/src/app.tsx +44 -37
- package/src/handlers/actions.ts +6 -5
- package/src/handlers/keyboard.ts +5 -2
- package/src/index.tsx +9 -0
- package/src/opencode/constants.ts +2 -0
- package/src/opencode/parser.ts +23 -47
- package/src/opencode/session.ts +120 -236
- package/src/opencode/sqlite.ts +432 -0
- package/src/opencode/stats.ts +10 -19
- package/src/opencode/tokens.ts +68 -95
- package/src/types/index.ts +7 -1
- package/src/ui/OpencodeStatsPanel.tsx +101 -81
- package/src/util/shutdown.ts +75 -0
|
@@ -0,0 +1,432 @@
|
|
|
1
|
+
import { Database } from 'bun:sqlite'
|
|
2
|
+
import { readdir, stat } from 'fs/promises'
|
|
3
|
+
import { join } from 'path'
|
|
4
|
+
import { OPENCODE_DATA_DIR, OPENCODE_DATABASE_PATH } from './constants'
|
|
5
|
+
|
|
6
|
+
export interface OpencodeSessionRow {
|
|
7
|
+
sessionID: string
|
|
8
|
+
projectID: string
|
|
9
|
+
directory: string
|
|
10
|
+
title: string
|
|
11
|
+
filesModified: number | null
|
|
12
|
+
additions: number | null
|
|
13
|
+
deletions: number | null
|
|
14
|
+
createdAt: number
|
|
15
|
+
updatedAt: number
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface OpencodeDirectoryAggregateRow {
|
|
19
|
+
sessionCount: number
|
|
20
|
+
filesModified: number
|
|
21
|
+
additions: number
|
|
22
|
+
deletions: number
|
|
23
|
+
createdAt: number
|
|
24
|
+
updatedAt: number
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface OpencodeAssistantMessageData {
|
|
28
|
+
modelID?: string
|
|
29
|
+
providerID?: string
|
|
30
|
+
tokens: {
|
|
31
|
+
input: number
|
|
32
|
+
output: number
|
|
33
|
+
reasoning: number
|
|
34
|
+
cacheRead: number
|
|
35
|
+
cacheWrite: number
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface OpencodeGlobalStatsRow {
|
|
40
|
+
totalSessions: number
|
|
41
|
+
totalMessages: number
|
|
42
|
+
totalCost: number
|
|
43
|
+
inputTokens: number
|
|
44
|
+
outputTokens: number
|
|
45
|
+
cacheRead: number
|
|
46
|
+
cacheWrite: number
|
|
47
|
+
oldestCreatedAt: number | null
|
|
48
|
+
newestUpdatedAt: number | null
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
interface DatabaseCandidate {
|
|
52
|
+
path: string
|
|
53
|
+
modifiedAt: number
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
interface SessionAggregateRow {
|
|
57
|
+
messageCount: number
|
|
58
|
+
totalCost: number
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
interface SessionTitleRow {
|
|
62
|
+
title: string
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
interface AssistantMessageDataRow {
|
|
66
|
+
data: string
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
interface GlobalSessionAggregateRow {
|
|
70
|
+
totalSessions: number
|
|
71
|
+
oldestCreatedAt: number | null
|
|
72
|
+
newestUpdatedAt: number | null
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
interface GlobalMessageAggregateRow {
|
|
76
|
+
totalMessages: number
|
|
77
|
+
totalCost: number
|
|
78
|
+
inputTokens: number
|
|
79
|
+
outputTokens: number
|
|
80
|
+
cacheRead: number
|
|
81
|
+
cacheWrite: number
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
let cachedDatabasePath: string | null = null
|
|
85
|
+
let cachedDatabase: Database | null = null
|
|
86
|
+
|
|
87
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
88
|
+
return typeof value === 'object' && value !== null
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function readNumber(value: unknown): number | undefined {
|
|
92
|
+
return typeof value === 'number' && Number.isFinite(value) ? value : undefined
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function readString(value: unknown): string | undefined {
|
|
96
|
+
return typeof value === 'string' && value.length > 0 ? value : undefined
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function parseAssistantMessageData(raw: string, sessionID: string): OpencodeAssistantMessageData {
|
|
100
|
+
const parsed: unknown = JSON.parse(raw)
|
|
101
|
+
if (!isRecord(parsed)) {
|
|
102
|
+
throw new Error(`Invalid OpenCode message payload for session '${sessionID}'`)
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const tokensValue = isRecord(parsed.tokens) ? parsed.tokens : null
|
|
106
|
+
const cacheValue = tokensValue && isRecord(tokensValue.cache) ? tokensValue.cache : null
|
|
107
|
+
|
|
108
|
+
return {
|
|
109
|
+
modelID: readString(parsed.modelID),
|
|
110
|
+
providerID: readString(parsed.providerID),
|
|
111
|
+
tokens: {
|
|
112
|
+
input: readNumber(tokensValue?.input) ?? 0,
|
|
113
|
+
output: readNumber(tokensValue?.output) ?? 0,
|
|
114
|
+
reasoning: readNumber(tokensValue?.reasoning) ?? 0,
|
|
115
|
+
cacheRead: readNumber(cacheValue?.read) ?? 0,
|
|
116
|
+
cacheWrite: readNumber(cacheValue?.write) ?? 0,
|
|
117
|
+
},
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function createDatabase(databasePath: string): Database {
|
|
122
|
+
return new Database(databasePath, { readonly: true, strict: true })
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async function getDatabaseCandidates(): Promise<DatabaseCandidate[]> {
|
|
126
|
+
const entries = await readdir(OPENCODE_DATA_DIR).catch(() => [])
|
|
127
|
+
const candidates = await Promise.all(
|
|
128
|
+
entries
|
|
129
|
+
.filter(entry => entry === 'opencode.db' || /^opencode-.+\.db$/.test(entry))
|
|
130
|
+
.map(async entry => {
|
|
131
|
+
const candidatePath = join(OPENCODE_DATA_DIR, entry)
|
|
132
|
+
const details = await stat(candidatePath)
|
|
133
|
+
return {
|
|
134
|
+
path: candidatePath,
|
|
135
|
+
modifiedAt: details.mtimeMs,
|
|
136
|
+
}
|
|
137
|
+
})
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
return candidates.sort((left, right) => right.modifiedAt - left.modifiedAt)
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export async function findOpencodeDatabasePath(): Promise<string | null> {
|
|
144
|
+
if (await Bun.file(OPENCODE_DATABASE_PATH).exists()) {
|
|
145
|
+
return OPENCODE_DATABASE_PATH
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const [candidate] = await getDatabaseCandidates()
|
|
149
|
+
return candidate?.path ?? null
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export async function getOpencodeDatabasePath(): Promise<string> {
|
|
153
|
+
const databasePath = await findOpencodeDatabasePath()
|
|
154
|
+
if (!databasePath) {
|
|
155
|
+
throw new Error(`OpenCode database not found in '${OPENCODE_DATA_DIR}'`)
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
return databasePath
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
async function withDatabase<T>(callback: (database: Database) => T): Promise<T> {
|
|
162
|
+
const databasePath = await getOpencodeDatabasePath()
|
|
163
|
+
|
|
164
|
+
if (!cachedDatabase || cachedDatabasePath !== databasePath) {
|
|
165
|
+
cachedDatabase?.close()
|
|
166
|
+
cachedDatabase = createDatabase(databasePath)
|
|
167
|
+
cachedDatabasePath = databasePath
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
return callback(cachedDatabase)
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function getSessionRow(
|
|
174
|
+
database: Database,
|
|
175
|
+
directory: string,
|
|
176
|
+
activeSince?: number
|
|
177
|
+
): OpencodeSessionRow | null {
|
|
178
|
+
if (activeSince !== undefined) {
|
|
179
|
+
const statement = database.query<OpencodeSessionRow, [string, number]>(`
|
|
180
|
+
SELECT
|
|
181
|
+
id AS sessionID,
|
|
182
|
+
project_id AS projectID,
|
|
183
|
+
directory,
|
|
184
|
+
title,
|
|
185
|
+
summary_files AS filesModified,
|
|
186
|
+
summary_additions AS additions,
|
|
187
|
+
summary_deletions AS deletions,
|
|
188
|
+
time_created AS createdAt,
|
|
189
|
+
time_updated AS updatedAt
|
|
190
|
+
FROM session
|
|
191
|
+
WHERE directory = ?1
|
|
192
|
+
AND COALESCE(time_updated, time_created) >= ?2
|
|
193
|
+
ORDER BY COALESCE(time_updated, time_created) DESC, id DESC
|
|
194
|
+
LIMIT 1
|
|
195
|
+
`)
|
|
196
|
+
|
|
197
|
+
return statement.get(directory, activeSince) ?? null
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
const statement = database.query<OpencodeSessionRow, [string]>(`
|
|
201
|
+
SELECT
|
|
202
|
+
id AS sessionID,
|
|
203
|
+
project_id AS projectID,
|
|
204
|
+
directory,
|
|
205
|
+
title,
|
|
206
|
+
summary_files AS filesModified,
|
|
207
|
+
summary_additions AS additions,
|
|
208
|
+
summary_deletions AS deletions,
|
|
209
|
+
time_created AS createdAt,
|
|
210
|
+
time_updated AS updatedAt
|
|
211
|
+
FROM session
|
|
212
|
+
WHERE directory = ?1
|
|
213
|
+
ORDER BY COALESCE(time_updated, time_created) DESC, id DESC
|
|
214
|
+
LIMIT 1
|
|
215
|
+
`)
|
|
216
|
+
|
|
217
|
+
return statement.get(directory) ?? null
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function getMessageAggregate(database: Database, sessionID: string): SessionAggregateRow {
|
|
221
|
+
const statement = database.query<SessionAggregateRow, [string]>(`
|
|
222
|
+
SELECT
|
|
223
|
+
COUNT(*) AS messageCount,
|
|
224
|
+
COALESCE(
|
|
225
|
+
SUM(
|
|
226
|
+
CASE
|
|
227
|
+
WHEN json_extract(data, '$.role') = 'assistant'
|
|
228
|
+
THEN COALESCE(json_extract(data, '$.cost'), 0)
|
|
229
|
+
ELSE 0
|
|
230
|
+
END
|
|
231
|
+
),
|
|
232
|
+
0
|
|
233
|
+
) AS totalCost
|
|
234
|
+
FROM message
|
|
235
|
+
WHERE session_id = ?1
|
|
236
|
+
`)
|
|
237
|
+
|
|
238
|
+
return statement.get(sessionID) ?? { messageCount: 0, totalCost: 0 }
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
export function getActiveSessionRowFromDatabase(
|
|
242
|
+
database: Database,
|
|
243
|
+
directory: string,
|
|
244
|
+
activeSince: number
|
|
245
|
+
): OpencodeSessionRow | null {
|
|
246
|
+
return getSessionRow(database, directory, activeSince)
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
export async function getActiveSessionRow(
|
|
250
|
+
directory: string,
|
|
251
|
+
activeSince: number
|
|
252
|
+
): Promise<OpencodeSessionRow | null> {
|
|
253
|
+
return withDatabase(database => getActiveSessionRowFromDatabase(database, directory, activeSince))
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
export function getMostRecentSessionRowFromDatabase(
|
|
257
|
+
database: Database,
|
|
258
|
+
directory: string
|
|
259
|
+
): OpencodeSessionRow | null {
|
|
260
|
+
return getSessionRow(database, directory)
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
export async function getMostRecentSessionRow(directory: string): Promise<OpencodeSessionRow | null> {
|
|
264
|
+
return withDatabase(database => getMostRecentSessionRowFromDatabase(database, directory))
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
export function getDirectoryAggregateFromDatabase(
|
|
268
|
+
database: Database,
|
|
269
|
+
directory: string
|
|
270
|
+
): OpencodeDirectoryAggregateRow | null {
|
|
271
|
+
const statement = database.query<OpencodeDirectoryAggregateRow, [string]>(`
|
|
272
|
+
SELECT
|
|
273
|
+
COUNT(*) AS sessionCount,
|
|
274
|
+
COALESCE(SUM(summary_files), 0) AS filesModified,
|
|
275
|
+
COALESCE(SUM(summary_additions), 0) AS additions,
|
|
276
|
+
COALESCE(SUM(summary_deletions), 0) AS deletions,
|
|
277
|
+
MIN(time_created) AS createdAt,
|
|
278
|
+
MAX(COALESCE(time_updated, time_created)) AS updatedAt
|
|
279
|
+
FROM session
|
|
280
|
+
WHERE directory = ?1
|
|
281
|
+
`)
|
|
282
|
+
|
|
283
|
+
const row = statement.get(directory)
|
|
284
|
+
if (!row || row.sessionCount === 0) {
|
|
285
|
+
return null
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
return row
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
export async function getDirectoryAggregate(
|
|
292
|
+
directory: string
|
|
293
|
+
): Promise<OpencodeDirectoryAggregateRow | null> {
|
|
294
|
+
return withDatabase(database => getDirectoryAggregateFromDatabase(database, directory))
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
export function getMostRecentSessionTitleForDirectoryFromDatabase(
|
|
298
|
+
database: Database,
|
|
299
|
+
directory: string
|
|
300
|
+
): string | null {
|
|
301
|
+
const statement = database.query<SessionTitleRow, [string]>(`
|
|
302
|
+
SELECT title
|
|
303
|
+
FROM session
|
|
304
|
+
WHERE directory = ?1
|
|
305
|
+
ORDER BY COALESCE(time_updated, time_created) DESC, id DESC
|
|
306
|
+
LIMIT 1
|
|
307
|
+
`)
|
|
308
|
+
|
|
309
|
+
return statement.get(directory)?.title ?? null
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
export async function getMostRecentSessionTitleForDirectory(directory: string): Promise<string | null> {
|
|
313
|
+
return withDatabase(database => getMostRecentSessionTitleForDirectoryFromDatabase(database, directory))
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
export function getMessageCountBySessionFromDatabase(database: Database, sessionID: string): number {
|
|
317
|
+
return getMessageAggregate(database, sessionID).messageCount
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
export async function getMessageCountBySession(sessionID: string): Promise<number> {
|
|
321
|
+
return withDatabase(database => getMessageCountBySessionFromDatabase(database, sessionID))
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
export function getMessageCountByDirectoryFromDatabase(database: Database, directory: string): number {
|
|
325
|
+
const statement = database.query<{ messageCount: number }, [string]>(`
|
|
326
|
+
SELECT COUNT(m.id) AS messageCount
|
|
327
|
+
FROM message m
|
|
328
|
+
INNER JOIN session s ON s.id = m.session_id
|
|
329
|
+
WHERE s.directory = ?1
|
|
330
|
+
`)
|
|
331
|
+
|
|
332
|
+
return statement.get(directory)?.messageCount ?? 0
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
export async function getMessageCountByDirectory(directory: string): Promise<number> {
|
|
336
|
+
return withDatabase(database => getMessageCountByDirectoryFromDatabase(database, directory))
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
export function getAssistantCostTotalBySessionFromDatabase(database: Database, sessionID: string): number {
|
|
340
|
+
return getMessageAggregate(database, sessionID).totalCost
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
export async function getAssistantCostTotalBySession(sessionID: string): Promise<number> {
|
|
344
|
+
return withDatabase(database => getAssistantCostTotalBySessionFromDatabase(database, sessionID))
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
export function getLastAssistantMessageDataFromDatabase(
|
|
348
|
+
database: Database,
|
|
349
|
+
sessionID: string
|
|
350
|
+
): OpencodeAssistantMessageData | null {
|
|
351
|
+
const statement = database.query<AssistantMessageDataRow, [string]>(`
|
|
352
|
+
SELECT data
|
|
353
|
+
FROM message
|
|
354
|
+
WHERE session_id = ?1
|
|
355
|
+
AND json_extract(data, '$.role') = 'assistant'
|
|
356
|
+
AND COALESCE(json_extract(data, '$.tokens.output'), 0) > 0
|
|
357
|
+
ORDER BY time_created DESC, id DESC
|
|
358
|
+
LIMIT 1
|
|
359
|
+
`)
|
|
360
|
+
|
|
361
|
+
const row = statement.get(sessionID)
|
|
362
|
+
if (!row) {
|
|
363
|
+
return null
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
return parseAssistantMessageData(row.data, sessionID)
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
export async function getLastAssistantMessageData(
|
|
370
|
+
sessionID: string
|
|
371
|
+
): Promise<OpencodeAssistantMessageData | null> {
|
|
372
|
+
return withDatabase(database => getLastAssistantMessageDataFromDatabase(database, sessionID))
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
export function getGlobalStatsFromDatabase(database: Database): OpencodeGlobalStatsRow {
|
|
376
|
+
const sessionStatement = database.query<GlobalSessionAggregateRow, []>(`
|
|
377
|
+
SELECT
|
|
378
|
+
COUNT(*) AS totalSessions,
|
|
379
|
+
MIN(time_created) AS oldestCreatedAt,
|
|
380
|
+
MAX(COALESCE(time_updated, time_created)) AS newestUpdatedAt
|
|
381
|
+
FROM session
|
|
382
|
+
`)
|
|
383
|
+
const messageStatement = database.query<GlobalMessageAggregateRow, []>(`
|
|
384
|
+
SELECT
|
|
385
|
+
COUNT(*) AS totalMessages,
|
|
386
|
+
COALESCE(
|
|
387
|
+
SUM(
|
|
388
|
+
CASE
|
|
389
|
+
WHEN json_extract(data, '$.role') = 'assistant'
|
|
390
|
+
THEN COALESCE(json_extract(data, '$.cost'), 0)
|
|
391
|
+
ELSE 0
|
|
392
|
+
END
|
|
393
|
+
),
|
|
394
|
+
0
|
|
395
|
+
) AS totalCost,
|
|
396
|
+
COALESCE(SUM(COALESCE(json_extract(data, '$.tokens.input'), 0)), 0) AS inputTokens,
|
|
397
|
+
COALESCE(SUM(COALESCE(json_extract(data, '$.tokens.output'), 0)), 0) AS outputTokens,
|
|
398
|
+
COALESCE(SUM(COALESCE(json_extract(data, '$.tokens.cache.read'), 0)), 0) AS cacheRead,
|
|
399
|
+
COALESCE(SUM(COALESCE(json_extract(data, '$.tokens.cache.write'), 0)), 0) AS cacheWrite
|
|
400
|
+
FROM message
|
|
401
|
+
`)
|
|
402
|
+
|
|
403
|
+
const sessionRow = sessionStatement.get() ?? {
|
|
404
|
+
totalSessions: 0,
|
|
405
|
+
oldestCreatedAt: null,
|
|
406
|
+
newestUpdatedAt: null,
|
|
407
|
+
}
|
|
408
|
+
const messageRow = messageStatement.get() ?? {
|
|
409
|
+
totalMessages: 0,
|
|
410
|
+
totalCost: 0,
|
|
411
|
+
inputTokens: 0,
|
|
412
|
+
outputTokens: 0,
|
|
413
|
+
cacheRead: 0,
|
|
414
|
+
cacheWrite: 0,
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
return {
|
|
418
|
+
totalSessions: sessionRow.totalSessions,
|
|
419
|
+
totalMessages: messageRow.totalMessages,
|
|
420
|
+
totalCost: messageRow.totalCost,
|
|
421
|
+
inputTokens: messageRow.inputTokens,
|
|
422
|
+
outputTokens: messageRow.outputTokens,
|
|
423
|
+
cacheRead: messageRow.cacheRead,
|
|
424
|
+
cacheWrite: messageRow.cacheWrite,
|
|
425
|
+
oldestCreatedAt: sessionRow.oldestCreatedAt,
|
|
426
|
+
newestUpdatedAt: sessionRow.newestUpdatedAt,
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
export async function getGlobalStats(): Promise<OpencodeGlobalStatsRow> {
|
|
431
|
+
return withDatabase(database => getGlobalStatsFromDatabase(database))
|
|
432
|
+
}
|
package/src/opencode/stats.ts
CHANGED
|
@@ -9,26 +9,17 @@ import type { OpencodeStats } from './types'
|
|
|
9
9
|
export async function getOpencodeSessionStats(
|
|
10
10
|
tmuxSessionName: string
|
|
11
11
|
): Promise<OpencodeStats | null> {
|
|
12
|
-
|
|
13
|
-
const tmuxDirectory = await getTmuxSessionDirectory(tmuxSessionName)
|
|
14
|
-
if (!tmuxDirectory) {
|
|
15
|
-
console.error('Could not determine tmux session directory')
|
|
16
|
-
return null
|
|
17
|
-
}
|
|
12
|
+
const tmuxDirectory = await getTmuxSessionDirectory(tmuxSessionName)
|
|
18
13
|
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
const homeDir = process.env.HOME || '/home/ghost'
|
|
25
|
-
if (tmuxDirectory === homeDir) {
|
|
26
|
-
return await getAggregatedOpencodeStats(tmuxDirectory)
|
|
27
|
-
}
|
|
14
|
+
const activeSession = await getActiveOpencodeSession(tmuxDirectory)
|
|
15
|
+
if (activeSession) {
|
|
16
|
+
return activeSession
|
|
17
|
+
}
|
|
28
18
|
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
return null
|
|
19
|
+
const homeDir = process.env.HOME || '/home/ghost'
|
|
20
|
+
if (tmuxDirectory === homeDir) {
|
|
21
|
+
return getAggregatedOpencodeStats(tmuxDirectory)
|
|
33
22
|
}
|
|
23
|
+
|
|
24
|
+
return getMostRecentSessionForDirectory(tmuxDirectory)
|
|
34
25
|
}
|
package/src/opencode/tokens.ts
CHANGED
|
@@ -1,56 +1,73 @@
|
|
|
1
1
|
import { spawn } from 'bun'
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
|
|
2
|
+
import { getAssistantCostTotalBySession, getLastAssistantMessageData } from './sqlite'
|
|
3
|
+
|
|
4
|
+
const modelContextLimitCache = new Map<string, number>()
|
|
5
|
+
|
|
6
|
+
function getModelCacheKey(modelID: string, providerID: string): string {
|
|
7
|
+
return `${providerID}:${modelID}`
|
|
8
|
+
}
|
|
5
9
|
|
|
6
10
|
export async function getModelContextLimit(modelID: string, providerID: string): Promise<number> {
|
|
11
|
+
const cacheKey = getModelCacheKey(modelID, providerID)
|
|
12
|
+
const cachedLimit = modelContextLimitCache.get(cacheKey)
|
|
13
|
+
if (cachedLimit !== undefined) {
|
|
14
|
+
return cachedLimit
|
|
15
|
+
}
|
|
16
|
+
|
|
7
17
|
try {
|
|
8
18
|
const proc = spawn(['opencode', 'models', providerID, '--verbose'])
|
|
9
19
|
const output = await new Response(proc.stdout).text()
|
|
20
|
+
await proc.exited
|
|
21
|
+
|
|
22
|
+
if (proc.exitCode !== 0) {
|
|
23
|
+
throw new Error(`opencode models exited with code ${proc.exitCode}`)
|
|
24
|
+
}
|
|
10
25
|
|
|
11
26
|
const lines = output.split('\n')
|
|
12
27
|
let inTargetModel = false
|
|
13
28
|
let jsonBuffer = ''
|
|
14
29
|
|
|
15
|
-
for (
|
|
16
|
-
const line = lines[i]
|
|
17
|
-
|
|
30
|
+
for (const line of lines) {
|
|
18
31
|
if (line === `${providerID}/${modelID}`) {
|
|
19
32
|
inTargetModel = true
|
|
20
33
|
jsonBuffer = ''
|
|
21
34
|
continue
|
|
22
35
|
}
|
|
23
36
|
|
|
24
|
-
if (inTargetModel) {
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
37
|
+
if (!inTargetModel) {
|
|
38
|
+
continue
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
if (/^[a-z0-9-]+\//i.test(line)) {
|
|
42
|
+
break
|
|
29
43
|
}
|
|
44
|
+
|
|
45
|
+
jsonBuffer += `${line}\n`
|
|
30
46
|
}
|
|
31
47
|
|
|
32
48
|
if (jsonBuffer) {
|
|
33
|
-
const modelData = JSON.parse(jsonBuffer)
|
|
34
|
-
|
|
35
|
-
|
|
49
|
+
const modelData = JSON.parse(jsonBuffer) as { limit?: { context?: number } }
|
|
50
|
+
const contextLimit = modelData.limit?.context
|
|
51
|
+
if (typeof contextLimit === 'number' && Number.isFinite(contextLimit)) {
|
|
52
|
+
modelContextLimitCache.set(cacheKey, contextLimit)
|
|
53
|
+
return contextLimit
|
|
36
54
|
}
|
|
37
55
|
}
|
|
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
56
|
} catch (error) {
|
|
47
57
|
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
58
|
}
|
|
59
|
+
|
|
60
|
+
const fallbackLimit = getFallbackContextLimit(modelID)
|
|
61
|
+
modelContextLimitCache.set(cacheKey, fallbackLimit)
|
|
62
|
+
return fallbackLimit
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function getFallbackContextLimit(modelID: string): number {
|
|
66
|
+
if (modelID.includes('claude-sonnet-4')) return 1000000
|
|
67
|
+
if (modelID.includes('claude')) return 200000
|
|
68
|
+
if (modelID.includes('gpt-4o')) return 128000
|
|
69
|
+
if (modelID.includes('gpt-4')) return 128000
|
|
70
|
+
return 200000
|
|
54
71
|
}
|
|
55
72
|
|
|
56
73
|
export async function getLastMessageTokens(sessionID: string): Promise<{
|
|
@@ -60,77 +77,33 @@ export async function getLastMessageTokens(sessionID: string): Promise<{
|
|
|
60
77
|
modelID?: string
|
|
61
78
|
providerID?: string
|
|
62
79
|
} | null> {
|
|
63
|
-
|
|
64
|
-
|
|
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
|
-
}
|
|
80
|
+
if (!sessionID) {
|
|
81
|
+
return null
|
|
82
|
+
}
|
|
106
83
|
|
|
107
|
-
|
|
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)
|
|
84
|
+
const lastAssistantMessage = await getLastAssistantMessageData(sessionID)
|
|
85
|
+
if (!lastAssistantMessage) {
|
|
132
86
|
return null
|
|
133
87
|
}
|
|
88
|
+
|
|
89
|
+
const totalCost = await getAssistantCostTotalBySession(sessionID)
|
|
90
|
+
const contextLimit =
|
|
91
|
+
lastAssistantMessage.modelID && lastAssistantMessage.providerID
|
|
92
|
+
? await getModelContextLimit(lastAssistantMessage.modelID, lastAssistantMessage.providerID)
|
|
93
|
+
: 200000
|
|
94
|
+
|
|
95
|
+
return {
|
|
96
|
+
lastMessageTokens:
|
|
97
|
+
lastAssistantMessage.tokens.input +
|
|
98
|
+
lastAssistantMessage.tokens.output +
|
|
99
|
+
lastAssistantMessage.tokens.reasoning +
|
|
100
|
+
lastAssistantMessage.tokens.cacheRead +
|
|
101
|
+
lastAssistantMessage.tokens.cacheWrite,
|
|
102
|
+
contextLimit,
|
|
103
|
+
totalCost,
|
|
104
|
+
modelID: lastAssistantMessage.modelID,
|
|
105
|
+
providerID: lastAssistantMessage.providerID,
|
|
106
|
+
}
|
|
134
107
|
}
|
|
135
108
|
|
|
136
109
|
export function estimateSessionCost(inputTokens: number, outputTokens: number): string {
|
package/src/types/index.ts
CHANGED
|
@@ -33,6 +33,12 @@ export interface OpencodeSessionStats {
|
|
|
33
33
|
sessionTotalCost?: number
|
|
34
34
|
}
|
|
35
35
|
|
|
36
|
+
export type OpencodeStatsState =
|
|
37
|
+
| { status: 'loading' }
|
|
38
|
+
| { status: 'ready'; stats: OpencodeSessionStats }
|
|
39
|
+
| { status: 'missing'; message: string }
|
|
40
|
+
| { status: 'error'; message: string }
|
|
41
|
+
|
|
36
42
|
export interface Item {
|
|
37
43
|
title: string
|
|
38
44
|
desc: string
|
|
@@ -42,7 +48,7 @@ export interface Item {
|
|
|
42
48
|
windowCount?: string
|
|
43
49
|
createdAt?: number
|
|
44
50
|
lastActivity?: number
|
|
45
|
-
|
|
51
|
+
opencodeState?: OpencodeStatsState
|
|
46
52
|
}
|
|
47
53
|
|
|
48
54
|
export interface Config {
|