-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathopencode.ts
More file actions
606 lines (552 loc) · 21 KB
/
Copy pathopencode.ts
File metadata and controls
606 lines (552 loc) · 21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
import type { CanonicalEvent, MetricBag } from '@codetime/shared'
import type { AdapterEnv, AgentAdapter, InstallEntry } from './types.js'
import os from 'node:os'
import path from 'node:path'
import {
AGENT_TIME_SCHEMA_VERSION,
createStableHash,
createWorkspaceId,
} from '@codetime/shared'
import { operationForTool, toolFileActivityType } from '../lib/activity.js'
import { matchesBackfillFilters } from '../lib/backfill.js'
import {
isPlainObject,
numberField,
objectField,
stringField,
stringRefs,
} from '../lib/fields.js'
import { msToIso } from '../lib/jsonl.js'
interface OpenCodeUsage {
tokensInput?: number
tokensOutput?: number
tokensReasoningOutput?: number
tokensCachedInput?: number
tokensCacheReadInput?: number
tokensCacheCreationInput?: number
tokensTotal: number
}
// ── Parser ──
async function parseOpenCodeSessionFile(
dbPath: string,
options: Record<string, unknown> & { _: string[] },
): Promise<CanonicalEvent[]> {
const { DatabaseSync } = await import('node:sqlite')
if (!dbPath.endsWith('.db')) {
return []
}
const db = new DatabaseSync(dbPath, { readOnly: true })
const events: CanonicalEvent[] = []
try {
// Older OpenCode databases predate the `path` column on session.
// Probe schema first and only select columns that exist.
const sessionCols = new Set(
(db.prepare('PRAGMA table_info(session)').all() as Array<{ name: string }>)
.map(row => row.name),
)
const hasDirectory = sessionCols.has('directory')
const hasPath = sessionCols.has('path')
const hasArchived = sessionCols.has('time_archived')
const selectCols = ['id', 'title', 'time_created']
if (hasDirectory) {
selectCols.push('directory')
}
if (hasPath) {
selectCols.push('path')
}
if (hasArchived) {
selectCols.push('time_archived')
}
const sessions = db.prepare(
`SELECT ${selectCols.join(', ')} FROM session WHERE time_created IS NOT NULL ORDER BY time_created`,
).all() as Array<{
id: string
directory?: string | null
path?: string | null
title: string
time_created: number
time_archived?: number | null
}>
for (const session of sessions) {
const sessionId = session.id
const cwd = session.directory || session.path || undefined
const project = cwd ? path.basename(cwd) : undefined
const sessionTs = msToIso(session.time_created)
events.push(baseOpenCodeEvent({
ts: sessionTs,
type: 'session.started',
sessionId,
cwd,
project,
operation: 'session start',
}))
const messages = db.prepare(
'SELECT id, data FROM message WHERE session_id = ? ORDER BY time_created',
).all(sessionId) as Array<{ id: string, data: string }>
let currentTurnId: string | undefined
let turnTs: string | undefined
for (const msg of messages) {
let info: Record<string, unknown>
try {
info = JSON.parse(msg.data)
}
catch {
continue
}
if (!isPlainObject(info)) {
continue
}
const role = stringField(info, 'role')
const timeObj = objectField(info, 'time')
const timeCreated = numberField(timeObj, 'created')
if (!role || !timeCreated) {
continue
}
if (role === 'user') {
currentTurnId = `turn_${createStableHash([sessionId, msg.id]).slice(0, 24)}`
turnTs = msToIso(timeCreated)
const userAgent = stringField(info, 'agent') || 'opencode'
const modelObj = objectField(info, 'model')
const model = modelObj ? stringField(modelObj, 'modelID') : undefined
events.push(baseOpenCodeEvent({
ts: turnTs,
type: 'turn.started',
sessionId,
turnId: currentTurnId,
cwd,
project,
model,
operation: 'turn start',
confidence: 'exact',
}, userAgent))
let promptText = ''
try {
const parts = db.prepare(
'SELECT data FROM part WHERE message_id = ? ORDER BY id',
).all(msg.id) as Array<{ data: string }>
for (const part of parts) {
let pd: Record<string, unknown>
try {
pd = JSON.parse(part.data)
}
catch {
continue
}
if (!isPlainObject(pd)) {
continue
}
if (pd.type === 'text' && !pd.ignored && !pd.synthetic) {
promptText += stringField(pd, 'text') || ''
}
}
}
catch { /* parts may not exist */ }
if (promptText) {
events.push(baseOpenCodeEvent({
ts: turnTs,
type: 'prompt.submitted',
sessionId,
turnId: currentTurnId,
cwd,
project,
model,
operation: 'prompt submitted',
confidence: 'exact',
metrics: { prompts: 1, promptChars: promptText.length },
refs: stringRefs({ promptHash: `sha256:${createStableHash(promptText)}` }),
}, userAgent))
}
}
if (role === 'assistant') {
const model = stringField(info, 'modelID')
const assistantAgent = stringField(info, 'agent') || 'opencode'
const pathObj = objectField(info, 'path')
const assistantCwd = stringField(pathObj, 'cwd') || cwd
const assistantProject = assistantCwd ? path.basename(assistantCwd) : project
const completedTs = numberField(objectField(info, 'time'), 'completed')
const createdTs = timeCreated
const tokens = opencodeUsageFromInfo(info)
const cost = (typeof info.cost === 'number' && info.cost > 0) ? info.cost as number : undefined
// The assistant message's own info.tokens is the authoritative per-message
// usage (this is the only thing ccusage counts — it reads `SELECT ... FROM
// message` and never the part table). Each `step-finish` part ALSO carries a
// tokens object that repeats those same tokens, so emitting model.usage for
// both double-counted the turn (≥2× for a single-step message). Only fall
// back to step-finish tokens when the message carried none of its own.
let messageHadUsage = false
if (tokens) {
messageHadUsage = true
const metrics: MetricBag = {
tokensInput: tokens.tokensInput,
tokensOutput: tokens.tokensOutput,
tokensReasoningOutput: tokens.tokensReasoningOutput,
tokensCachedInput: tokens.tokensCachedInput,
tokensCacheReadInput: tokens.tokensCacheReadInput,
tokensCacheCreationInput: tokens.tokensCacheCreationInput,
tokensTotal: tokens.tokensTotal,
}
if (cost !== undefined) {
metrics.costUsd = cost
}
events.push(baseOpenCodeEvent({
ts: msToIso(completedTs || createdTs),
type: 'model.usage',
sessionId,
turnId: currentTurnId,
cwd: assistantCwd,
project: assistantProject,
model,
operation: 'model usage',
metrics,
}, assistantAgent))
}
try {
const parts = db.prepare(
'SELECT data FROM part WHERE message_id = ? ORDER BY id',
).all(msg.id) as Array<{ data: string }>
for (const part of parts) {
let pd: Record<string, unknown>
try {
pd = JSON.parse(part.data)
}
catch {
continue
}
if (!isPlainObject(pd)) {
continue
}
if (pd.type === 'tool') {
const tool = stringField(pd, 'tool') || 'unknown'
const callId = stringField(pd, 'callID')
const state = objectField(pd, 'state')
const status = stringField(state, 'status')
const stateTime = objectField(state, 'time')
const startMs = numberField(stateTime, 'start') || createdTs
const endMs = numberField(stateTime, 'end')
const stateInput = objectField(state, 'input')
events.push(baseOpenCodeEvent({
ts: msToIso(startMs),
type: 'tool.started',
sessionId,
turnId: currentTurnId,
cwd: assistantCwd,
project: assistantProject,
model,
tool,
operation: `${tool} started`,
metrics: { toolCalls: 1 },
refs: stringRefs({ sourceId: callId }),
}, assistantAgent))
if (status === 'completed' || status === 'error') {
const durationMs = endMs && startMs ? endMs - startMs : undefined
const success = status === 'completed'
events.push(baseOpenCodeEvent({
ts: msToIso(endMs || completedTs || createdTs),
type: success ? 'tool.completed' : 'tool.failed',
sessionId,
turnId: currentTurnId,
cwd: assistantCwd,
project: assistantProject,
model,
tool,
success,
operation: success ? `${tool} completed` : `${tool} failed`,
metrics: { toolDurationMs: durationMs, durationMs },
refs: stringRefs({ sourceId: callId }),
}, assistantAgent))
if (tool === 'bash' || tool === 'Bash') {
const command = stringField(stateInput, 'command')
events.push(baseOpenCodeEvent({
ts: msToIso(endMs || completedTs || createdTs),
type: success ? 'command.completed' : 'command.failed',
sessionId,
turnId: currentTurnId,
cwd: assistantCwd,
project: assistantProject,
model,
tool: 'Bash',
success,
operation: success ? 'command completed' : 'command failed',
metrics: { commandCalls: 1, commandDurationMs: durationMs, durationMs },
refs: stringRefs({
sourceId: callId,
commandHash: command ? `sha256:${createStableHash(String(command))}` : undefined,
}),
}, assistantAgent))
}
const filePath = stringField(stateInput, 'file_path') || stringField(stateInput, 'filePath')
if (filePath) {
events.push(baseOpenCodeEvent({
ts: msToIso(endMs || completedTs || createdTs),
type: toolFileActivityType(tool),
sessionId,
turnId: currentTurnId,
cwd: assistantCwd,
project: assistantProject,
model,
tool,
success,
operation: `${tool} file activity`,
fileActivities: [{
ts: msToIso(endMs || completedTs || createdTs),
path: filePath,
operation: operationForTool(tool),
}],
refs: stringRefs({ sourceId: callId }),
}, assistantAgent))
}
}
}
if (pd.type === 'step-finish' && !messageHadUsage) {
const stepTokens = opencodeUsageFromInfo(pd)
const stepCost = (typeof pd.cost === 'number' && pd.cost > 0) ? pd.cost as number : undefined
if (stepTokens) {
const stepMetrics: MetricBag = {
tokensInput: stepTokens.tokensInput,
tokensOutput: stepTokens.tokensOutput,
tokensReasoningOutput: stepTokens.tokensReasoningOutput,
tokensCachedInput: stepTokens.tokensCachedInput,
tokensCacheReadInput: stepTokens.tokensCacheReadInput,
tokensCacheCreationInput: stepTokens.tokensCacheCreationInput,
tokensTotal: stepTokens.tokensTotal,
}
if (stepCost !== undefined) {
stepMetrics.costUsd = stepCost
}
events.push(baseOpenCodeEvent({
ts: msToIso(completedTs || createdTs),
type: 'model.usage',
sessionId,
turnId: currentTurnId,
cwd: assistantCwd,
project: assistantProject,
model,
operation: 'model usage (step)',
confidence: 'exact',
metrics: stepMetrics,
}, assistantAgent))
}
}
if (pd.type === 'subtask') {
events.push(baseOpenCodeEvent({
ts: msToIso(createdTs),
type: 'subagent.started',
sessionId,
turnId: currentTurnId,
cwd: assistantCwd,
project: assistantProject,
model,
operation: 'subagent started',
agentInstanceId: stringField(pd, 'agent') || stringField(pd, 'description'),
}, assistantAgent))
}
}
}
catch { /* parts may not exist */ }
if (stringField(info, 'finish')) {
const durationMs = completedTs && createdTs ? completedTs - createdTs : undefined
events.push(baseOpenCodeEvent({
ts: msToIso(completedTs || createdTs),
type: 'turn.completed',
sessionId,
turnId: currentTurnId,
cwd: assistantCwd,
project: assistantProject,
model,
operation: 'turn completed',
metrics: { durationMs },
}, assistantAgent))
}
}
}
if (session.time_archived) {
events.push(baseOpenCodeEvent({
ts: msToIso(session.time_archived),
type: 'session.ended',
sessionId,
cwd,
project,
operation: 'session end',
}))
}
}
}
finally {
db.close()
}
return events.filter(event => matchesBackfillFilters(event, options))
}
// ── OpenCode-specific helpers ──
function baseOpenCodeEvent(
event: Omit<CanonicalEvent, 'schemaVersion' | 'source' | 'agent' | 'workspaceId' | 'confidence'>
& { confidence?: CanonicalEvent['confidence'] },
agentName?: string,
): CanonicalEvent {
return {
schemaVersion: AGENT_TIME_SCHEMA_VERSION,
source: 'opencode',
agent: agentName || 'opencode',
workspaceId: createWorkspaceId({ projectName: event.project, repoRoot: event.cwd }),
...event,
}
}
export function opencodeUsageFromInfo(info: Record<string, unknown>): OpenCodeUsage | undefined {
const tokensObj = objectField(info, 'tokens')
if (!tokensObj) {
return undefined
}
const input = Math.max(0, numberField(tokensObj, 'input') || 0)
const output = Math.max(0, numberField(tokensObj, 'output') || 0)
const reasoning = Math.max(0, numberField(tokensObj, 'reasoning') || 0)
const cache = objectField(tokensObj, 'cache')
const cacheRead = Math.max(0, numberField(cache, 'read') || 0)
const cacheWrite = Math.max(0, numberField(cache, 'write') || 0)
const totalInput = input + cacheRead + cacheWrite
// OpenCode reports reasoning separately from output, so fold it into the
// billable output total. tokensReasoningOutput keeps the informational subset.
// The total fallback uses totalInput + billableOutput (NOT + reasoning again)
// to avoid double-counting; numerically equal to the previous expression.
const billableOutput = output + reasoning
const total = Math.max(0, numberField(tokensObj, 'total') || (totalInput + billableOutput))
if (total <= 0) {
return undefined
}
return {
tokensInput: totalInput || undefined,
tokensOutput: billableOutput || undefined,
tokensReasoningOutput: reasoning || undefined,
tokensCachedInput: (cacheRead + cacheWrite) || undefined,
tokensCacheReadInput: cacheRead || undefined,
tokensCacheCreationInput: cacheWrite || undefined,
tokensTotal: total,
}
}
// ── Path resolution ──
// OpenCode follows XDG for its config (~/.config/opencode) and data
// (~/.local/share/opencode), but also reads OPENCODE_CONFIG_DIR for the former.
// Both can move independently — agents, plugins, and history.
function opencodeConfigDir(home: string, env?: AdapterEnv): string {
const override = env?.OPENCODE_CONFIG_DIR
if (override && override.trim()) {
return path.resolve(override)
}
const xdgConfig = env?.XDG_CONFIG_HOME
if (xdgConfig && xdgConfig.trim()) {
return path.join(path.resolve(xdgConfig), 'opencode')
}
return path.join(home, '.config', 'opencode')
}
function opencodeDataCandidates(home: string, env?: AdapterEnv): string[] {
const xdgData = env?.XDG_DATA_HOME
const primary = xdgData && xdgData.trim()
? path.join(path.resolve(xdgData), 'opencode', 'opencode.db')
: path.join(home, '.local', 'share', 'opencode', 'opencode.db')
// Keep the legacy ~/.opencode/opencode.db location as a fallback for older
// installs that haven't migrated to the XDG data dir.
return [primary, path.join(home, '.opencode', 'opencode.db')]
}
// ── Backfill file discovery (special: OpenCode uses SQLite, not JSONL) ──
export async function opencodeBackfillFiles(
sourceRoot?: string,
home: string = os.homedir(),
env?: AdapterEnv,
): Promise<Array<{ path: string, modifiedAt: string }>> {
const { stat } = await import('node:fs/promises')
if (sourceRoot) {
if (!sourceRoot.endsWith('.db')) {
return []
}
const info = await stat(sourceRoot).catch(() => null)
if (!info) {
return []
}
return [{ path: sourceRoot, modifiedAt: info.mtime.toISOString() }]
}
for (const candidatePath of opencodeDataCandidates(home, env)) {
const info = await stat(candidatePath).catch(() => null)
if (info) {
return [{ path: candidatePath, modifiedAt: info.mtime.toISOString() }]
}
}
return []
}
// ── Installation content ──
function opencodePluginContent(): string {
return `// Agent Time plugin for OpenCode
// Generated by codetime.
export const AgentTime = async ({ $, directory }) => {
const report = async (payload) => {
try {
await $\`codetime hook --agent opencode\`.stdin(JSON.stringify(payload)).quiet()
} catch {}
}
return {
"session.created": async (ctx) => {
await report({
hook_event_name: "SessionStart",
session_id: ctx?.id,
cwd: directory
})
},
"session.idle": async (ctx) => {
await report({
hook_event_name: "SessionEnd",
session_id: ctx?.id,
cwd: directory
})
},
"tool.execute.after": async (input) => {
const toolName = input?.tool || "unknown"
const toolCallId = input?.toolCallId
const toolInput = input?.args || input?.input || {}
const command = toolInput?.command
const filePath = toolInput?.file_path || toolInput?.filePath
await report({
hook_event_name: "PostToolUse",
tool_name: toolName,
tool_use_id: toolCallId,
cwd: directory,
tool_input: { command, file_path: filePath }
})
}
}
}
`
}
// ── Adapter factory ──
export function createOpenCodeAdapter(): AgentAdapter {
const PLUGIN_PATH = 'plugins/codetime.mjs'
return {
id: 'opencode',
label: 'OpenCode',
agentName: 'opencode',
kind: 'agent',
detectPath(home: string, env?: AdapterEnv) {
return opencodeConfigDir(home, env)
},
installedPath(home: string, env?: AdapterEnv) {
return path.join(opencodeConfigDir(home, env), PLUGIN_PATH)
},
async isInstalled(home: string, env?: AdapterEnv) {
try {
const { pathExists } = await import('../lib/fs.js')
return await pathExists(path.join(opencodeConfigDir(home, env), PLUGIN_PATH))
|| await pathExists(path.join('.opencode', PLUGIN_PATH))
}
catch {
return false
}
},
installEntries(home: string, env?: AdapterEnv): InstallEntry[] {
return [{
kind: 'file',
path: path.join(opencodeConfigDir(home, env), PLUGIN_PATH),
content: opencodePluginContent(),
}]
},
sourcePaths(home: string, env?: AdapterEnv): string[] {
return opencodeDataCandidates(home, env)
},
parseSessionFile: parseOpenCodeSessionFile,
}
}