chompyy 0.5.0 → 0.7.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 +14 -1
- package/dist/advice.js +98 -1
- package/dist/agentlimits.js +77 -0
- package/dist/agentusage.js +96 -0
- package/dist/approvals.js +129 -0
- package/dist/appstate.js +73 -3
- package/dist/away.js +48 -5
- package/dist/blueprint.js +3 -7
- package/dist/board.js +1 -0
- package/dist/cli.js +343 -18
- package/dist/codexquota.js +106 -0
- package/dist/codexusage.js +10 -0
- package/dist/config.js +2 -0
- package/dist/context.js +30 -0
- package/dist/costs.js +41 -2
- package/dist/demon.js +20 -0
- package/dist/detect.js +38 -6
- package/dist/didwork.js +26 -0
- package/dist/label.js +33 -0
- package/dist/menu.js +17 -0
- package/dist/nightcap.js +72 -0
- package/dist/nudge.js +70 -24
- package/dist/pacing.js +16 -1
- package/dist/punchcard.js +39 -0
- package/dist/questions.js +71 -0
- package/dist/recap.js +74 -0
- package/dist/receipt.js +48 -0
- package/dist/recipe.js +79 -0
- package/dist/savings.js +111 -0
- package/dist/stamps.js +14 -0
- package/dist/suggest.js +15 -5
- package/dist/triggers.js +5 -0
- package/dist/usage.js +21 -1
- package/dist/vendor/codeburn/antigravity.js +309 -0
- package/dist/vendor/codeburn/codex.js +429 -0
- package/dist/vendor/codeburn/copilot.js +292 -0
- package/dist/vendor/codeburn/gemini.js +195 -0
- package/dist/vendor/codeburn/grokbot.js +182 -0
- package/dist/vendor/codeburn/kimi.js +178 -0
- package/dist/vendor/codeburn/shims/chalk.js +14 -0
- package/dist/vendor/codeburn/shims/strip-ansi.js +6 -0
- package/dist/vendor/codeburn/src/act/backup.js +83 -0
- package/dist/vendor/codeburn/src/act/model-defaults.js +151 -0
- package/dist/vendor/codeburn/src/act/types.js +37 -0
- package/dist/vendor/codeburn/src/bash-utils.js +204 -0
- package/dist/vendor/codeburn/src/behavioral-weight.js +47 -0
- package/dist/vendor/codeburn/src/cache-dir.js +26 -0
- package/dist/vendor/codeburn/src/cache-refresh-lock.js +543 -0
- package/dist/vendor/codeburn/src/cache-sweep.js +67 -0
- package/dist/vendor/codeburn/src/classifier.js +209 -0
- package/dist/vendor/codeburn/src/claude-identity.js +223 -0
- package/dist/vendor/codeburn/src/codex-cache.js +377 -0
- package/dist/vendor/codeburn/src/codex-fork-replay.js +232 -0
- package/dist/vendor/codeburn/src/codex-jsonl-fields.js +99 -0
- package/dist/vendor/codeburn/src/codex-session-index.js +113 -0
- package/dist/vendor/codeburn/src/codex-throughput.js +544 -0
- package/dist/vendor/codeburn/src/compare-stats.js +405 -0
- package/dist/vendor/codeburn/src/config.js +145 -0
- package/dist/vendor/codeburn/src/content-utils.js +56 -0
- package/dist/vendor/codeburn/src/context-tree-codex.js +329 -0
- package/dist/vendor/codeburn/src/context-tree.js +664 -0
- package/dist/vendor/codeburn/src/copilot-aiu.js +16 -0
- package/dist/vendor/codeburn/src/currency.js +189 -0
- package/dist/vendor/codeburn/src/cursor-cache.js +238 -0
- package/dist/vendor/codeburn/src/cursor-import.js +402 -0
- package/dist/vendor/codeburn/src/cursor-sync.js +256 -0
- package/dist/vendor/codeburn/src/daily-cache.js +2036 -0
- package/dist/vendor/codeburn/src/data/litellm-snapshot.json +1 -0
- package/dist/vendor/codeburn/src/data/pricing-fallback.json +1 -0
- package/dist/vendor/codeburn/src/day-aggregator.js +327 -0
- package/dist/vendor/codeburn/src/editor-data-dir.js +11 -0
- package/dist/vendor/codeburn/src/fetch-utils.js +18 -0
- package/dist/vendor/codeburn/src/format.js +118 -0
- package/dist/vendor/codeburn/src/fs-utils.js +270 -0
- package/dist/vendor/codeburn/src/git-origin.js +334 -0
- package/dist/vendor/codeburn/src/granular-history.js +328 -0
- package/dist/vendor/codeburn/src/hermes-session-ledger.js +512 -0
- package/dist/vendor/codeburn/src/launcher-homes.js +142 -0
- package/dist/vendor/codeburn/src/live-sessions.js +358 -0
- package/dist/vendor/codeburn/src/math-utils.js +8 -0
- package/dist/vendor/codeburn/src/menubar-json.js +294 -0
- package/dist/vendor/codeburn/src/models.js +1879 -0
- package/dist/vendor/codeburn/src/optimize-one-hour-cache.js +92 -0
- package/dist/vendor/codeburn/src/optimize.js +4110 -0
- package/dist/vendor/codeburn/src/parse-workers.js +219 -0
- package/dist/vendor/codeburn/src/parser.js +6955 -0
- package/dist/vendor/codeburn/src/path-privacy.js +26 -0
- package/dist/vendor/codeburn/src/plans.js +135 -0
- package/dist/vendor/codeburn/src/pr-signals.js +132 -0
- package/dist/vendor/codeburn/src/project-filter-warnings.js +33 -0
- package/dist/vendor/codeburn/src/provider-issues.js +30 -0
- package/dist/vendor/codeburn/src/providers/amp.js +286 -0
- package/dist/vendor/codeburn/src/providers/antigravity.js +1731 -0
- package/dist/vendor/codeburn/src/providers/claude.js +551 -0
- package/dist/vendor/codeburn/src/providers/cline-cli.js +401 -0
- package/dist/vendor/codeburn/src/providers/cline.js +63 -0
- package/dist/vendor/codeburn/src/providers/codebuff.js +336 -0
- package/dist/vendor/codeburn/src/providers/codewhale.js +442 -0
- package/dist/vendor/codeburn/src/providers/codex.js +1720 -0
- package/dist/vendor/codeburn/src/providers/command-code.js +196 -0
- package/dist/vendor/codeburn/src/providers/copilot.js +3278 -0
- package/dist/vendor/codeburn/src/providers/crush.js +226 -0
- package/dist/vendor/codeburn/src/providers/cursor-agent.js +837 -0
- package/dist/vendor/codeburn/src/providers/cursor.js +1163 -0
- package/dist/vendor/codeburn/src/providers/devin.js +569 -0
- package/dist/vendor/codeburn/src/providers/droid.js +324 -0
- package/dist/vendor/codeburn/src/providers/dsh.js +690 -0
- package/dist/vendor/codeburn/src/providers/forge.js +245 -0
- package/dist/vendor/codeburn/src/providers/gemini.js +230 -0
- package/dist/vendor/codeburn/src/providers/goose.js +252 -0
- package/dist/vendor/codeburn/src/providers/grok.js +581 -0
- package/dist/vendor/codeburn/src/providers/grokbot.js +290 -0
- package/dist/vendor/codeburn/src/providers/hermes.js +771 -0
- package/dist/vendor/codeburn/src/providers/ibm-bob.js +53 -0
- package/dist/vendor/codeburn/src/providers/index.js +360 -0
- package/dist/vendor/codeburn/src/providers/kilo-code.js +50 -0
- package/dist/vendor/codeburn/src/providers/kimi.js +363 -0
- package/dist/vendor/codeburn/src/providers/kimicode.js +402 -0
- package/dist/vendor/codeburn/src/providers/kiro.js +1174 -0
- package/dist/vendor/codeburn/src/providers/lingtai-tui.js +372 -0
- package/dist/vendor/codeburn/src/providers/mistral-vibe-unified.js +236 -0
- package/dist/vendor/codeburn/src/providers/mistral-vibe.js +405 -0
- package/dist/vendor/codeburn/src/providers/mux.js +242 -0
- package/dist/vendor/codeburn/src/providers/open-design.js +217 -0
- package/dist/vendor/codeburn/src/providers/openclaude.js +309 -0
- package/dist/vendor/codeburn/src/providers/openclaw.js +442 -0
- package/dist/vendor/codeburn/src/providers/opencode-file-parser.js +131 -0
- package/dist/vendor/codeburn/src/providers/opencode.js +91 -0
- package/dist/vendor/codeburn/src/providers/pi.js +429 -0
- package/dist/vendor/codeburn/src/providers/quickdesk.js +491 -0
- package/dist/vendor/codeburn/src/providers/qwen.js +193 -0
- package/dist/vendor/codeburn/src/providers/session-message.js +118 -0
- package/dist/vendor/codeburn/src/providers/sqlite-session-parser.js +457 -0
- package/dist/vendor/codeburn/src/providers/types.js +5 -0
- package/dist/vendor/codeburn/src/providers/vercel-gateway.js +135 -0
- package/dist/vendor/codeburn/src/providers/vscode-cline-parser.js +212 -0
- package/dist/vendor/codeburn/src/providers/warp.js +575 -0
- package/dist/vendor/codeburn/src/providers/zcode.js +249 -0
- package/dist/vendor/codeburn/src/providers/zed.js +187 -0
- package/dist/vendor/codeburn/src/providers/zerostack.js +139 -0
- package/dist/vendor/codeburn/src/quota/antigravity.js +310 -0
- package/dist/vendor/codeburn/src/quota/claude.js +244 -0
- package/dist/vendor/codeburn/src/quota/cursor.js +301 -0
- package/dist/vendor/codeburn/src/quota/security.js +299 -0
- package/dist/vendor/codeburn/src/quota/types.js +1 -0
- package/dist/vendor/codeburn/src/scan-facts.js +99 -0
- package/dist/vendor/codeburn/src/session-cache.js +3040 -0
- package/dist/vendor/codeburn/src/session-count-label.js +14 -0
- package/dist/vendor/codeburn/src/session-output.js +139 -0
- package/dist/vendor/codeburn/src/session-population.js +30 -0
- package/dist/vendor/codeburn/src/sessions-report.js +1342 -0
- package/dist/vendor/codeburn/src/sqlite.js +528 -0
- package/dist/vendor/codeburn/src/sync/otlp.js +420 -0
- package/dist/vendor/codeburn/src/telemetry-snapshot.js +244 -0
- package/dist/vendor/codeburn/src/token-estimate.js +5 -0
- package/dist/vendor/codeburn/src/types.js +16 -0
- package/dist/vendor/codeburn/src/work-units.js +126 -0
- package/dist/vendor/codeburn/src/workflow-insights.js +228 -0
- package/dist/vendor/codeburn/src/wsl.js +198 -0
- package/dist/vendor/codeburn/src/yield.js +666 -0
- package/dist/wastechecks.js +233 -0
- package/package.json +1 -1
|
@@ -0,0 +1,3278 @@
|
|
|
1
|
+
// @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
|
|
2
|
+
// =============================================================================
|
|
3
|
+
// copilot.ts — Modified CodeBurn Copilot provider
|
|
4
|
+
// =============================================================================
|
|
5
|
+
//
|
|
6
|
+
// WHAT CHANGED:
|
|
7
|
+
// The original provider only reads Copilot's JSONL session-state files from
|
|
8
|
+
// ~/.copilot/session-state/, which only log output tokens. Input tokens,
|
|
9
|
+
// cache-read tokens, and cache-creation tokens are never written there, so
|
|
10
|
+
// CodeBurn underreports Copilot costs by 60-80%.
|
|
11
|
+
//
|
|
12
|
+
// This modified version adds VS Code sources that can carry fuller token
|
|
13
|
+
// data: the OTel SQLite store (agent-traces.db), VS Code core chatSessions
|
|
14
|
+
// journals, and legacy extension transcripts. OTel and chatSessions contain
|
|
15
|
+
// input/output token breakdowns for Copilot Chat users; legacy JSONL remains
|
|
16
|
+
// a fallback when richer sources are absent.
|
|
17
|
+
//
|
|
18
|
+
// HOW TO ENABLE THE OTEL SQLITE STORE:
|
|
19
|
+
// TWO settings must both be enabled in VS Code settings.json:
|
|
20
|
+
//
|
|
21
|
+
// {
|
|
22
|
+
// "github.copilot.chat.otel.enabled": true,
|
|
23
|
+
// "github.copilot.chat.otel.dbSpanExporter.enabled": true
|
|
24
|
+
// }
|
|
25
|
+
//
|
|
26
|
+
// The first enables the OTel pipeline; the second (defaults to false) enables
|
|
27
|
+
// the SQLite span exporter that actually writes agent-traces.db.
|
|
28
|
+
// After changing these settings, restart VS Code — the extension watches for
|
|
29
|
+
// these changes and requires a reload to take effect.
|
|
30
|
+
//
|
|
31
|
+
// Or set the environment variable before launching VS Code:
|
|
32
|
+
//
|
|
33
|
+
// export COPILOT_OTEL_ENABLED=true
|
|
34
|
+
//
|
|
35
|
+
// The DB file is created in VS Code's global storage directory:
|
|
36
|
+
// ~/Library/Application Support/Code/User/globalStorage/github.copilot-chat/agent-traces.db
|
|
37
|
+
//
|
|
38
|
+
// ENVIRONMENT VARIABLES:
|
|
39
|
+
// CODEBURN_COPILOT_OTEL_DB — Override the agent-traces.db path
|
|
40
|
+
// CODEBURN_COPILOT_DISABLE_OTEL=1 — Skip OTel entirely, use only JSONL
|
|
41
|
+
// CODEBURN_COPILOT_WS_STORAGE_DIR — Override VS Code workspaceStorage
|
|
42
|
+
// CODEBURN_COPILOT_GLOBAL_STORAGE_DIR — Override VS Code globalStorage
|
|
43
|
+
// CODEBURN_COPILOT_JETBRAINS_DIR — Override the JetBrains github-copilot root
|
|
44
|
+
// CODEBURN_COPILOT_SESSION_STORE_DB — Override the ~/.copilot/session-store.db path
|
|
45
|
+
//
|
|
46
|
+
// ARCHITECTURE:
|
|
47
|
+
// discoverSessions() returns OTel sessions and legacy JSONL sessions. A VS
|
|
48
|
+
// Code chatSessions journal of a session OTel also recorded is dropped at
|
|
49
|
+
// serve time, so each session counts once. OTel sessions carry the full
|
|
50
|
+
// token breakdown; JSONL sessions only carry output tokens (the original
|
|
51
|
+
// behaviour, as a fallback).
|
|
52
|
+
//
|
|
53
|
+
// LIMITATIONS:
|
|
54
|
+
// - The OTel DB only contains Copilot Chat and Agent mode spans. Inline
|
|
55
|
+
// completions (ghost text) and Agent Host spans are NOT yet written to
|
|
56
|
+
// this DB (see https://github.com/microsoft/vscode/issues/315901).
|
|
57
|
+
// - The DB schema is inferred from the official OTel GenAI semantic
|
|
58
|
+
// conventions and the Copilot Budget extension's approach. If VS Code
|
|
59
|
+
// changes the schema, this parser will need updating.
|
|
60
|
+
// =============================================================================
|
|
61
|
+
import { readdir, stat } from 'fs/promises';
|
|
62
|
+
import { homedir, platform } from 'os';
|
|
63
|
+
import { join, basename, dirname, posix, win32 } from 'path';
|
|
64
|
+
import { existsSync } from 'fs';
|
|
65
|
+
import { getEditorDataDir } from '../editor-data-dir.js';
|
|
66
|
+
import { createHash } from 'crypto';
|
|
67
|
+
import { readSessionFile } from '../fs-utils.js';
|
|
68
|
+
import { calculateCost, modelKeyMatches, ownValue } from '../models.js';
|
|
69
|
+
import { NANO_AIU_PER_CREDIT, creditsToUsd, nanoAiuToCredits } from '../copilot-aiu.js';
|
|
70
|
+
import { extractBashCommands } from '../bash-utils.js';
|
|
71
|
+
import { estimateTokens } from '../context-tree.js';
|
|
72
|
+
const COPILOT_OPENAI_AUTO = 'copilot-openai-auto';
|
|
73
|
+
const COPILOT_ANTHROPIC_AUTO = 'copilot-anthropic-auto';
|
|
74
|
+
const transcriptToolCallModelHints = [
|
|
75
|
+
// Anthropic tool-call ID variants observed in Copilot transcript logs.
|
|
76
|
+
{ prefix: 'toolu_bdrk_', model: COPILOT_ANTHROPIC_AUTO },
|
|
77
|
+
{ prefix: 'toolu_vrtx_', model: COPILOT_ANTHROPIC_AUTO },
|
|
78
|
+
{ prefix: 'tooluse_', model: COPILOT_ANTHROPIC_AUTO },
|
|
79
|
+
{ prefix: 'toolu_', model: COPILOT_ANTHROPIC_AUTO },
|
|
80
|
+
// OpenAI tool-call IDs.
|
|
81
|
+
{ prefix: 'call_', model: COPILOT_OPENAI_AUTO },
|
|
82
|
+
];
|
|
83
|
+
// ---------------------------------------------------------------------------
|
|
84
|
+
// Legacy chat-session JSON format helpers
|
|
85
|
+
// ---------------------------------------------------------------------------
|
|
86
|
+
// Legacy ids arrive as "copilot/claude-sonnet-4.5"; dotted ids price through the aliases in models.ts.
|
|
87
|
+
function stripCopilotPrefix(raw) {
|
|
88
|
+
return raw.replace(/^(?:copilot|github\.copilot-chat)\//, '').trim();
|
|
89
|
+
}
|
|
90
|
+
const CHARS_PER_TOKEN_LEGACY = 4;
|
|
91
|
+
export var ChatCompletionContentPartKind;
|
|
92
|
+
(function (ChatCompletionContentPartKind) {
|
|
93
|
+
ChatCompletionContentPartKind[ChatCompletionContentPartKind["Image"] = 0] = "Image";
|
|
94
|
+
ChatCompletionContentPartKind[ChatCompletionContentPartKind["Text"] = 1] = "Text";
|
|
95
|
+
ChatCompletionContentPartKind[ChatCompletionContentPartKind["Opaque"] = 2] = "Opaque";
|
|
96
|
+
ChatCompletionContentPartKind[ChatCompletionContentPartKind["CacheBreakpoint"] = 3] = "CacheBreakpoint";
|
|
97
|
+
ChatCompletionContentPartKind[ChatCompletionContentPartKind["Document"] = 4] = "Document";
|
|
98
|
+
})(ChatCompletionContentPartKind || (ChatCompletionContentPartKind = {}));
|
|
99
|
+
/**
|
|
100
|
+
* Recursively collect all text strings from a VSCode render-tree node.
|
|
101
|
+
*
|
|
102
|
+
* The render tree stores content as leaf nodes with `type === 2` and a `.text`
|
|
103
|
+
* string at arbitrary nesting depth via `.children[]` arrays. Every tool
|
|
104
|
+
* result (file reads, terminal output, edit confirmations, …) uses this shape,
|
|
105
|
+
* regardless of the root `ctorName` (`tse`, `Wy`, etc.).
|
|
106
|
+
*/
|
|
107
|
+
function extractRenderNodeTexts(node) {
|
|
108
|
+
if (!node || typeof node !== 'object')
|
|
109
|
+
return '';
|
|
110
|
+
let out = '';
|
|
111
|
+
if (node.type === 2 && typeof node.text === 'string') {
|
|
112
|
+
out += node.text;
|
|
113
|
+
}
|
|
114
|
+
if (Array.isArray(node.children)) {
|
|
115
|
+
for (const child of node.children) {
|
|
116
|
+
out += extractRenderNodeTexts(child);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return out;
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Extract text from a toolCallResults entry's content array.
|
|
123
|
+
* Handles two observed shapes:
|
|
124
|
+
* - $mid:21: value is a plain string (terminal output, error messages)
|
|
125
|
+
* - $mid:23: value is an object with a .node render tree (edit confirmations, etc.)
|
|
126
|
+
*/
|
|
127
|
+
function extractToolCallResultContent(results) {
|
|
128
|
+
if (!results)
|
|
129
|
+
return '';
|
|
130
|
+
let out = '';
|
|
131
|
+
for (const result of Object.values(results)) {
|
|
132
|
+
for (const item of result.content ?? []) {
|
|
133
|
+
if (typeof item.value === 'string') {
|
|
134
|
+
out += item.value + '\n';
|
|
135
|
+
}
|
|
136
|
+
else if (item.value && typeof item.value === 'object' && 'node' in item.value) {
|
|
137
|
+
out += extractRenderNodeTexts(item.value.node) + '\n';
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
return out;
|
|
142
|
+
}
|
|
143
|
+
function inferModelFromLegacySession(session) {
|
|
144
|
+
// 1. Try to find the first request that has a non-empty, non-auto modelId
|
|
145
|
+
for (const req of session.requests ?? []) {
|
|
146
|
+
if (req.modelId) {
|
|
147
|
+
const stripped = stripCopilotPrefix(req.modelId);
|
|
148
|
+
if (stripped && stripped !== 'auto' && stripped !== 'copilot-auto' && stripped !== 'unknown') {
|
|
149
|
+
return stripped;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
// 1.5. Look in inputState.selectedModel
|
|
154
|
+
const selectedModel = session.inputState?.selectedModel;
|
|
155
|
+
if (selectedModel) {
|
|
156
|
+
const version = selectedModel.metadata?.version || selectedModel.metadata?.family || selectedModel.identifier;
|
|
157
|
+
if (version) {
|
|
158
|
+
const stripped = stripCopilotPrefix(version);
|
|
159
|
+
if (stripped && stripped !== 'copilot/auto' && stripped !== 'auto' && stripped !== 'copilot-auto') {
|
|
160
|
+
return stripped;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
// 2. Try to find if there are any tool calls or IDs that hint at the model
|
|
165
|
+
for (const req of session.requests ?? []) {
|
|
166
|
+
const rawRounds = req.result?.metadata?.['toolCallRounds'] ??
|
|
167
|
+
(isRecord(req.result) ? req.result['toolCallRounds'] : null);
|
|
168
|
+
const rounds = Array.isArray(rawRounds) ? rawRounds : [];
|
|
169
|
+
for (const round of rounds) {
|
|
170
|
+
for (const tc of round.toolCalls ?? []) {
|
|
171
|
+
const id = tc.id ?? '';
|
|
172
|
+
for (const hint of transcriptToolCallModelHints) {
|
|
173
|
+
if (id.startsWith(hint.prefix)) {
|
|
174
|
+
return hint.model;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
const response = req.response;
|
|
180
|
+
for (const item of response ?? []) {
|
|
181
|
+
if (item && typeof item === 'object') {
|
|
182
|
+
const itemTyped = item;
|
|
183
|
+
const id = itemTyped.toolCallId ?? '';
|
|
184
|
+
for (const hint of transcriptToolCallModelHints) {
|
|
185
|
+
if (id.startsWith(hint.prefix)) {
|
|
186
|
+
return hint.model;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
return 'unknown';
|
|
193
|
+
}
|
|
194
|
+
function extractToolCallResultContentFromParts(response) {
|
|
195
|
+
if (!response)
|
|
196
|
+
return '';
|
|
197
|
+
let out = '';
|
|
198
|
+
for (const item of response) {
|
|
199
|
+
if (!item || typeof item !== 'object')
|
|
200
|
+
continue;
|
|
201
|
+
if (item.kind === 'toolInvocationSerialized') {
|
|
202
|
+
const itemTyped = item;
|
|
203
|
+
const spec = itemTyped.toolSpecificData;
|
|
204
|
+
if (spec) {
|
|
205
|
+
// Handle terminal commands output
|
|
206
|
+
if (spec.terminalCommandOutput && typeof spec.terminalCommandOutput.text === 'string') {
|
|
207
|
+
out += spec.terminalCommandOutput.text + '\n';
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
// Handle resultDetails containing base64 data. Images and other binary
|
|
211
|
+
// outputs are not tokenised as text, so only text payloads count.
|
|
212
|
+
const resultDetails = itemTyped.resultDetails;
|
|
213
|
+
if (resultDetails && typeof resultDetails === 'object') {
|
|
214
|
+
if (resultDetails.output && resultDetails.output.type === 'data' && resultDetails.output.mimeType?.startsWith('text/')) {
|
|
215
|
+
const base64 = resultDetails.output.base64Data;
|
|
216
|
+
if (typeof base64 === 'string') {
|
|
217
|
+
const decoded = Buffer.from(base64, 'base64').toString('utf8');
|
|
218
|
+
out += decoded + '\n';
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
return out;
|
|
225
|
+
}
|
|
226
|
+
// Prefer toolCallRounds over req.response: response also embeds terminal output, which is model input.
|
|
227
|
+
function extractLegacyOutputs(req) {
|
|
228
|
+
let outputText = '';
|
|
229
|
+
let reasoningText = '';
|
|
230
|
+
let recordedReasoningTokens = 0;
|
|
231
|
+
const rounds = req.result?.metadata?.toolCallRounds;
|
|
232
|
+
const response = req.response;
|
|
233
|
+
if (rounds && rounds.length > 0) {
|
|
234
|
+
for (const round of rounds) {
|
|
235
|
+
if (typeof round.response === 'string' && round.response) {
|
|
236
|
+
outputText += round.response + '\n';
|
|
237
|
+
}
|
|
238
|
+
for (const tc of round.toolCalls ?? []) {
|
|
239
|
+
if (typeof tc.arguments === 'string' && tc.arguments) {
|
|
240
|
+
outputText += tc.arguments + '\n';
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
if (numberOrZero(round.thinking?.tokens) > 0) {
|
|
244
|
+
recordedReasoningTokens += round.thinking.tokens;
|
|
245
|
+
}
|
|
246
|
+
else if (round.thinking) {
|
|
247
|
+
const text = round.thinking.text;
|
|
248
|
+
if (typeof text === 'string' && text) {
|
|
249
|
+
reasoningText += text + '\n';
|
|
250
|
+
}
|
|
251
|
+
else if (Array.isArray(text)) {
|
|
252
|
+
reasoningText += text.join('\n') + '\n';
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
else if (response && response.length > 0) {
|
|
258
|
+
// Fallback: extract from response parts
|
|
259
|
+
for (const itemRaw of response) {
|
|
260
|
+
if (!itemRaw || typeof itemRaw !== 'object')
|
|
261
|
+
continue;
|
|
262
|
+
const item = itemRaw;
|
|
263
|
+
// Plain IMarkdownString or item.kind === 'markdownContent' or item.kind === 'markdownVuln'
|
|
264
|
+
if ('value' in item && typeof item.value === 'string' && !('kind' in item)) {
|
|
265
|
+
outputText += item.value + '\n';
|
|
266
|
+
}
|
|
267
|
+
else if ((item.kind === 'markdownContent' || item.kind === 'markdownVuln') && item.content) {
|
|
268
|
+
if (typeof item.content === 'string') {
|
|
269
|
+
outputText += item.content + '\n';
|
|
270
|
+
}
|
|
271
|
+
else if (typeof item.content === 'object' && item.content !== null && 'value' in item.content && typeof item.content.value === 'string') {
|
|
272
|
+
outputText += item.content.value + '\n';
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
else if (item.kind === 'thinking' && item.value) {
|
|
276
|
+
if (typeof item.value === 'string') {
|
|
277
|
+
reasoningText += item.value + '\n';
|
|
278
|
+
}
|
|
279
|
+
else if (Array.isArray(item.value)) {
|
|
280
|
+
reasoningText += item.value.join('\n') + '\n';
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
else if (item.kind === 'textEditGroup') {
|
|
284
|
+
const edits = item.edits;
|
|
285
|
+
if (Array.isArray(edits)) {
|
|
286
|
+
for (const edit of edits) {
|
|
287
|
+
if (Array.isArray(edit)) {
|
|
288
|
+
for (const e of edit) {
|
|
289
|
+
if (e && typeof e === 'object' && 'text' in e && typeof e.text === 'string') {
|
|
290
|
+
outputText += e.text + '\n';
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
else if (edit && typeof edit === 'object' && 'text' in edit && typeof edit.text === 'string') {
|
|
295
|
+
outputText += edit.text + '\n';
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
// invocationMessage strings are model narration in the UI ("Checking terminal output",
|
|
303
|
+
// "Using 'Multi-Replace String'", etc.); short but part of model output.
|
|
304
|
+
for (const item of response ?? []) {
|
|
305
|
+
if (item && typeof item === 'object') {
|
|
306
|
+
const inv = item.invocationMessage;
|
|
307
|
+
if (typeof inv === 'string' && inv) {
|
|
308
|
+
outputText += inv + '\n';
|
|
309
|
+
}
|
|
310
|
+
else if (inv && typeof inv === 'object' && 'value' in inv && typeof inv.value === 'string') {
|
|
311
|
+
outputText += inv.value + '\n';
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
return { outputText, reasoningText, recordedReasoningTokens };
|
|
316
|
+
}
|
|
317
|
+
function extractModelFromRequest(req, session) {
|
|
318
|
+
const result = isRecord(req.result) ? req.result : undefined;
|
|
319
|
+
const metadata = isRecord(result?.['metadata']) ? result?.['metadata'] : undefined;
|
|
320
|
+
// 1. Check resolved model from result metadata
|
|
321
|
+
const resolvedMeta = readString(metadata?.['resolvedModel']) || readString(metadata?.['model']);
|
|
322
|
+
if (resolvedMeta) {
|
|
323
|
+
const stripped = stripCopilotPrefix(resolvedMeta);
|
|
324
|
+
if (stripped && stripped !== 'auto' && stripped !== 'copilot-auto') {
|
|
325
|
+
return stripped;
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
// 2. Check resolved model directly on result
|
|
329
|
+
const resultResolved = readString(result?.['resolvedModel']) || readString(result?.['model']);
|
|
330
|
+
if (resultResolved) {
|
|
331
|
+
const stripped = stripCopilotPrefix(resultResolved);
|
|
332
|
+
if (stripped && stripped !== 'auto' && stripped !== 'copilot-auto') {
|
|
333
|
+
return stripped;
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
// 3. Check response parts for autoModeResolution or model info
|
|
337
|
+
for (const part of req.response ?? []) {
|
|
338
|
+
if (part && typeof part === 'object') {
|
|
339
|
+
const p = part;
|
|
340
|
+
if (p['kind'] === 'autoModeResolution') {
|
|
341
|
+
const resolved = readString(p['resolvedModel']) || readString(p['model']) || readString(p['modelId']);
|
|
342
|
+
if (resolved) {
|
|
343
|
+
const stripped = stripCopilotPrefix(resolved);
|
|
344
|
+
if (stripped && stripped !== 'auto' && stripped !== 'copilot-auto') {
|
|
345
|
+
return stripped;
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
// 4. Check request modelId
|
|
352
|
+
if (req.modelId) {
|
|
353
|
+
const stripped = stripCopilotPrefix(req.modelId);
|
|
354
|
+
if (stripped && stripped !== 'auto' && stripped !== 'copilot-auto') {
|
|
355
|
+
return stripped;
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
// 5. Inferred session model or fallback
|
|
359
|
+
const inferred = inferModelFromLegacySession(session);
|
|
360
|
+
if (inferred && inferred !== 'auto' && inferred !== 'copilot-auto' && inferred !== 'unknown') {
|
|
361
|
+
return inferred;
|
|
362
|
+
}
|
|
363
|
+
return 'unknown';
|
|
364
|
+
}
|
|
365
|
+
// An agent-mode request makes one model call per tool round, but
|
|
366
|
+
// result.metadata.promptTokens/outputTokens describe only the last one.
|
|
367
|
+
// modelTotals sums every round per model. Its inputTokens includes the cached
|
|
368
|
+
// part when it comes from the Copilot engine and excludes it when it comes from
|
|
369
|
+
// the Claude SDK; an input below the cached count can only be the latter.
|
|
370
|
+
function chatSessionModelTotals(raw) {
|
|
371
|
+
if (!Array.isArray(raw))
|
|
372
|
+
return undefined;
|
|
373
|
+
let input = 0;
|
|
374
|
+
let cached = 0;
|
|
375
|
+
let output = 0;
|
|
376
|
+
let found = false;
|
|
377
|
+
for (const entry of raw) {
|
|
378
|
+
if (!isRecord(entry))
|
|
379
|
+
continue;
|
|
380
|
+
found = true;
|
|
381
|
+
input += numberOrZero(entry['inputTokens']);
|
|
382
|
+
cached += numberOrZero(entry['cachedTokens']);
|
|
383
|
+
output += numberOrZero(entry['outputTokens']);
|
|
384
|
+
}
|
|
385
|
+
if (!found)
|
|
386
|
+
return undefined;
|
|
387
|
+
return { inputTokens: input >= cached ? input - cached : input, cacheReadTokens: cached, outputTokens: output };
|
|
388
|
+
}
|
|
389
|
+
// copilotCredits is GitHub's billed total_nano_aiu / 1e9 for the whole request,
|
|
390
|
+
// subagents included, so it prices the request where the last-round prompt
|
|
391
|
+
// tokens cannot.
|
|
392
|
+
function chatSessionNanoAiu(raw) {
|
|
393
|
+
return typeof raw === 'number' && Number.isFinite(raw) && raw >= 0 ? Math.round(raw * NANO_AIU_PER_CREDIT) : undefined;
|
|
394
|
+
}
|
|
395
|
+
function parseLegacyChatSession(session, sessionId, project, seenKeys) {
|
|
396
|
+
if (!session || !Array.isArray(session.requests))
|
|
397
|
+
return [];
|
|
398
|
+
const results = [];
|
|
399
|
+
for (const [reqIndex, req] of session.requests.entries()) {
|
|
400
|
+
const resultObj = isRecord(req.result) ? req.result : null;
|
|
401
|
+
const meta = isRecord(resultObj?.['metadata']) ? resultObj?.['metadata'] : null;
|
|
402
|
+
const usage = isRecord(resultObj?.['usage']) ? resultObj?.['usage'] : null;
|
|
403
|
+
const totals = chatSessionModelTotals(req.modelTotals);
|
|
404
|
+
const nanoAiu = chatSessionNanoAiu(req.copilotCredits);
|
|
405
|
+
// Exact token extraction: check metadata, result, root req, and usage independently
|
|
406
|
+
const exactPromptTokens = totals ? totals.inputTokens : (numberOrZero(meta?.['promptTokens']) ||
|
|
407
|
+
numberOrZero(resultObj?.['promptTokens']) ||
|
|
408
|
+
numberOrZero(req.promptTokens) ||
|
|
409
|
+
numberOrZero(usage?.['promptTokens']) ||
|
|
410
|
+
numberOrZero(usage?.['prompt_tokens']) ||
|
|
411
|
+
undefined);
|
|
412
|
+
// Root completionTokens is summed over every round; metadata holds the last.
|
|
413
|
+
const exactOutputTokens = totals ? totals.outputTokens : (numberOrZero(req.completionTokens) ||
|
|
414
|
+
numberOrZero(meta?.['outputTokens']) ||
|
|
415
|
+
numberOrZero(resultObj?.['outputTokens']) ||
|
|
416
|
+
numberOrZero(req.outputTokens) ||
|
|
417
|
+
numberOrZero(usage?.['completionTokens']) ||
|
|
418
|
+
numberOrZero(usage?.['completion_tokens']) ||
|
|
419
|
+
undefined);
|
|
420
|
+
const exactCacheRead = totals ? totals.cacheReadTokens :
|
|
421
|
+
numberOrZero(meta?.['cacheReadTokens']) ||
|
|
422
|
+
numberOrZero(meta?.['cachedTokens']) ||
|
|
423
|
+
numberOrZero(resultObj?.['cacheReadTokens']) ||
|
|
424
|
+
numberOrZero(resultObj?.['cachedTokens']) ||
|
|
425
|
+
numberOrZero(usage?.['cacheReadTokens']) ||
|
|
426
|
+
numberOrZero(usage?.['cache_read_tokens']) ||
|
|
427
|
+
numberOrZero(usage?.['cachedTokens']) ||
|
|
428
|
+
numberOrZero(usage?.['cached_tokens']) ||
|
|
429
|
+
0;
|
|
430
|
+
const exactCacheCreation = totals ? 0 :
|
|
431
|
+
numberOrZero(meta?.['cacheCreationTokens']) ||
|
|
432
|
+
numberOrZero(meta?.['cacheWriteTokens']) ||
|
|
433
|
+
numberOrZero(resultObj?.['cacheCreationTokens']) ||
|
|
434
|
+
numberOrZero(resultObj?.['cacheWriteTokens']) ||
|
|
435
|
+
numberOrZero(usage?.['cacheCreationTokens']) ||
|
|
436
|
+
numberOrZero(usage?.['cache_creation_tokens']) ||
|
|
437
|
+
numberOrZero(usage?.['cacheWriteTokens']) ||
|
|
438
|
+
numberOrZero(usage?.['cache_write_tokens']) ||
|
|
439
|
+
0;
|
|
440
|
+
const hasExactTokens = exactPromptTokens !== undefined || exactOutputTokens !== undefined;
|
|
441
|
+
const model = extractModelFromRequest(req, session);
|
|
442
|
+
const rawRounds = (meta?.['toolCallRounds'] ?? resultObj?.['toolCallRounds']);
|
|
443
|
+
const extracted = extractChatSessionTools({ toolCallRounds: rawRounds });
|
|
444
|
+
const toolNamesSet = new Set(extracted.tools);
|
|
445
|
+
for (const item of req.response ?? []) {
|
|
446
|
+
const part = item;
|
|
447
|
+
if (part?.kind === 'toolInvocationSerialized' && typeof part.toolId === 'string' && part.toolId.trim()) {
|
|
448
|
+
toolNamesSet.add(normalizeTool(part.toolId.trim()));
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
const tools = [...toolNamesSet];
|
|
452
|
+
const msgText = typeof req.message === 'string' ? req.message : (req.message?.text ?? '');
|
|
453
|
+
const { outputText, reasoningText, recordedReasoningTokens } = extractLegacyOutputs(req);
|
|
454
|
+
let totalInputTokens;
|
|
455
|
+
let outputTokens;
|
|
456
|
+
let cacheReadInputTokens = exactCacheRead;
|
|
457
|
+
let cacheCreationInputTokens = exactCacheCreation;
|
|
458
|
+
let reasoningTokens = 0;
|
|
459
|
+
let isEstimated = false;
|
|
460
|
+
if (hasExactTokens) {
|
|
461
|
+
totalInputTokens = exactPromptTokens ?? 0;
|
|
462
|
+
outputTokens = exactOutputTokens ?? 0;
|
|
463
|
+
isEstimated = false;
|
|
464
|
+
}
|
|
465
|
+
else {
|
|
466
|
+
isEstimated = true;
|
|
467
|
+
// Exact output counts already include reasoning, so thinking is only estimated here.
|
|
468
|
+
reasoningTokens = recordedReasoningTokens + Math.ceil(reasoningText.length / CHARS_PER_TOKEN_LEGACY);
|
|
469
|
+
const globalParts = (meta?.['renderedGlobalContext'] ?? []).filter((p) => isRecord(p) && p.type === ChatCompletionContentPartKind.Text && typeof p.text === 'string');
|
|
470
|
+
const userParts = (meta?.['renderedUserMessage'] ?? []).filter((p) => isRecord(p) && p.type === ChatCompletionContentPartKind.Text && typeof p.text === 'string');
|
|
471
|
+
const globalCacheMarkers = (meta?.['renderedGlobalContext'] ?? []).filter((p) => isRecord(p) && p.type === ChatCompletionContentPartKind.CacheBreakpoint);
|
|
472
|
+
const userCacheMarkers = (meta?.['renderedUserMessage'] ?? []).filter((p) => isRecord(p) && p.type === ChatCompletionContentPartKind.CacheBreakpoint);
|
|
473
|
+
let inputTokens = 0;
|
|
474
|
+
const hasRenderedMetadata = globalParts.length > 0 || userParts.length > 0;
|
|
475
|
+
if (hasRenderedMetadata) {
|
|
476
|
+
const globalText = globalParts.map((p) => p.text).join('\n');
|
|
477
|
+
const userText = userParts.map((p) => p.text).join('\n');
|
|
478
|
+
if (globalCacheMarkers.length > 0 || userCacheMarkers.length > 0) {
|
|
479
|
+
if (globalCacheMarkers.length > 0) {
|
|
480
|
+
cacheReadInputTokens = Math.ceil(globalText.length / CHARS_PER_TOKEN_LEGACY);
|
|
481
|
+
}
|
|
482
|
+
else {
|
|
483
|
+
inputTokens = Math.ceil(globalText.length / CHARS_PER_TOKEN_LEGACY);
|
|
484
|
+
}
|
|
485
|
+
const attachmentText = userText.replace(msgText, '');
|
|
486
|
+
if (userCacheMarkers.length > 0 && attachmentText.length > 0) {
|
|
487
|
+
cacheCreationInputTokens = Math.ceil(attachmentText.length / CHARS_PER_TOKEN_LEGACY);
|
|
488
|
+
}
|
|
489
|
+
else if (userCacheMarkers.length === 0) {
|
|
490
|
+
inputTokens += Math.ceil(userText.length / CHARS_PER_TOKEN_LEGACY);
|
|
491
|
+
inputTokens -= Math.ceil(msgText.length / CHARS_PER_TOKEN_LEGACY);
|
|
492
|
+
}
|
|
493
|
+
inputTokens += Math.ceil(msgText.length / CHARS_PER_TOKEN_LEGACY);
|
|
494
|
+
}
|
|
495
|
+
else {
|
|
496
|
+
inputTokens = Math.ceil((globalText + '\n' + userText).length / CHARS_PER_TOKEN_LEGACY);
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
else {
|
|
500
|
+
inputTokens = Math.ceil(msgText.length / CHARS_PER_TOKEN_LEGACY);
|
|
501
|
+
}
|
|
502
|
+
let toolResultText = extractToolCallResultContent(meta?.['toolCallResults']);
|
|
503
|
+
if (!toolResultText) {
|
|
504
|
+
toolResultText = extractToolCallResultContentFromParts(req.response);
|
|
505
|
+
}
|
|
506
|
+
const toolResultTokens = Math.ceil(toolResultText.length / CHARS_PER_TOKEN_LEGACY);
|
|
507
|
+
totalInputTokens = inputTokens + toolResultTokens;
|
|
508
|
+
// Copilot output counts include reasoning (models.ts
|
|
509
|
+
// REASONING_INCLUDED_IN_OUTPUT), so the estimate does too; reasoningTokens
|
|
510
|
+
// stays as metadata.
|
|
511
|
+
outputTokens = Math.ceil(outputText.length / CHARS_PER_TOKEN_LEGACY) + reasoningTokens;
|
|
512
|
+
if (outputTokens === 0 && totalInputTokens === 0 && cacheCreationInputTokens === 0 && reasoningTokens === 0) {
|
|
513
|
+
continue;
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
const reqId = readString(req.requestId) || `request-${reqIndex}`;
|
|
517
|
+
const dedupKey = `copilot-chatsession:${sessionId}:${reqId}`;
|
|
518
|
+
if (seenKeys.has(dedupKey))
|
|
519
|
+
continue;
|
|
520
|
+
seenKeys.add(dedupKey);
|
|
521
|
+
const costUSD = nanoAiu !== undefined ? creditsToUsd(nanoAiuToCredits(nanoAiu)) : calculateCost(model, totalInputTokens, outputTokens, cacheCreationInputTokens, cacheReadInputTokens, 0);
|
|
522
|
+
const ts = timestampToISO(req.timestamp) || timestampToISO(session.creationDate);
|
|
523
|
+
results.push({
|
|
524
|
+
provider: 'copilot',
|
|
525
|
+
model,
|
|
526
|
+
inputTokens: totalInputTokens,
|
|
527
|
+
outputTokens,
|
|
528
|
+
cacheCreationInputTokens,
|
|
529
|
+
cacheReadInputTokens,
|
|
530
|
+
cachedInputTokens: 0,
|
|
531
|
+
reasoningTokens,
|
|
532
|
+
webSearchRequests: 0,
|
|
533
|
+
costUSD,
|
|
534
|
+
costIsEstimated: isEstimated && nanoAiu === undefined,
|
|
535
|
+
tools,
|
|
536
|
+
bashCommands: extracted.bashCommands,
|
|
537
|
+
skills: extracted.skills.length > 0 ? extracted.skills : undefined,
|
|
538
|
+
timestamp: ts,
|
|
539
|
+
speed: 'standard',
|
|
540
|
+
deduplicationKey: dedupKey,
|
|
541
|
+
userMessage: msgText,
|
|
542
|
+
sessionId,
|
|
543
|
+
project,
|
|
544
|
+
...(nanoAiu !== undefined ? { nanoAiu, costFromBilling: true } : {}),
|
|
545
|
+
});
|
|
546
|
+
}
|
|
547
|
+
return results;
|
|
548
|
+
}
|
|
549
|
+
// ---------------------------------------------------------------------------
|
|
550
|
+
// Model display names (unchanged from original)
|
|
551
|
+
// ---------------------------------------------------------------------------
|
|
552
|
+
const modelDisplayNames = {
|
|
553
|
+
'gpt-4.1-nano': 'GPT-4.1 Nano',
|
|
554
|
+
'gpt-4.1-mini': 'GPT-4.1 Mini',
|
|
555
|
+
'gpt-4.1': 'GPT-4.1',
|
|
556
|
+
'gpt-4o-mini': 'GPT-4o Mini',
|
|
557
|
+
'gpt-4o': 'GPT-4o',
|
|
558
|
+
'gpt-5-mini': 'GPT-5 Mini',
|
|
559
|
+
'gpt-5': 'GPT-5',
|
|
560
|
+
'claude-sonnet-4-5': 'Sonnet 4.5',
|
|
561
|
+
'claude-sonnet-4': 'Sonnet 4',
|
|
562
|
+
'copilot-openai-auto': 'Copilot (OpenAI auto)',
|
|
563
|
+
'copilot-anthropic-auto': 'Copilot (Anthropic auto)',
|
|
564
|
+
};
|
|
565
|
+
// ---------------------------------------------------------------------------
|
|
566
|
+
// Tool name normalisation (unchanged from original, plus OTel tool names)
|
|
567
|
+
// ---------------------------------------------------------------------------
|
|
568
|
+
const toolNameMap = {
|
|
569
|
+
// JSONL session-state tool names
|
|
570
|
+
bash: 'Bash',
|
|
571
|
+
skill: 'Skill',
|
|
572
|
+
read_file: 'Read',
|
|
573
|
+
write_file: 'Edit',
|
|
574
|
+
edit_file: 'Edit',
|
|
575
|
+
delete_file: 'Delete',
|
|
576
|
+
github_repo: 'GitHub',
|
|
577
|
+
web_search: 'WebSearch',
|
|
578
|
+
run_in_terminal: 'Shell',
|
|
579
|
+
// JetBrains Copilot agent tool names (snake_case)
|
|
580
|
+
insert_edit_into_file: 'Edit',
|
|
581
|
+
create_file: 'Edit',
|
|
582
|
+
get_errors: 'Diagnostics',
|
|
583
|
+
file_search: 'Search',
|
|
584
|
+
grep_search: 'Search',
|
|
585
|
+
semantic_search: 'Search',
|
|
586
|
+
list_dir: 'Search',
|
|
587
|
+
fetch_webpage: 'Web',
|
|
588
|
+
// OTel execute_tool span names from Copilot Chat:
|
|
589
|
+
readFile: 'Read',
|
|
590
|
+
writeFile: 'Edit',
|
|
591
|
+
editFile: 'Edit',
|
|
592
|
+
runCommand: 'Shell',
|
|
593
|
+
runInTerminal: 'Shell',
|
|
594
|
+
findFiles: 'Search',
|
|
595
|
+
grepSearch: 'Search',
|
|
596
|
+
codebaseSearch: 'Search',
|
|
597
|
+
getErrors: 'Diagnostics',
|
|
598
|
+
listCodeUsages: 'Search',
|
|
599
|
+
createFile: 'Edit',
|
|
600
|
+
deleteFile: 'Delete',
|
|
601
|
+
renameOrMoveFile: 'Edit',
|
|
602
|
+
fetchWebpage: 'Web',
|
|
603
|
+
};
|
|
604
|
+
/**
|
|
605
|
+
* Normalise a raw tool name to its display form.
|
|
606
|
+
* - Known tools are mapped via toolNameMap.
|
|
607
|
+
* - MCP tools (containing both '-' and '_') are formatted as
|
|
608
|
+
* mcp__server_name__tool_name.
|
|
609
|
+
* - Everything else is returned unchanged.
|
|
610
|
+
*/
|
|
611
|
+
function normalizeTool(rawTool) {
|
|
612
|
+
const mapped = ownValue(toolNameMap, rawTool);
|
|
613
|
+
if (mapped)
|
|
614
|
+
return mapped;
|
|
615
|
+
// MCP tool names follow the pattern: server-name-tool_operand
|
|
616
|
+
// e.g. github-mcp-server-list_issues → mcp__github_mcp_server__list_issues
|
|
617
|
+
const dashIdx = rawTool.lastIndexOf('-');
|
|
618
|
+
if (dashIdx > 0 && rawTool.includes('_')) {
|
|
619
|
+
const server = rawTool.slice(0, dashIdx).replace(/-/g, '_');
|
|
620
|
+
const tool = rawTool.slice(dashIdx + 1);
|
|
621
|
+
return `mcp__${server}__${tool}`;
|
|
622
|
+
}
|
|
623
|
+
return rawTool;
|
|
624
|
+
}
|
|
625
|
+
const modelDisplayEntries = Object.entries(modelDisplayNames).sort((a, b) => b[0].length - a[0].length);
|
|
626
|
+
// Tool names that represent shell/bash execution. When the AI calls one of
|
|
627
|
+
// these, we extract the `arguments.command` string into bashCommands[].
|
|
628
|
+
const BASH_TOOL_NAMES = new Set(['bash', 'run_in_terminal', 'runInTerminal', 'runCommand']);
|
|
629
|
+
// ---------------------------------------------------------------------------
|
|
630
|
+
// Paths
|
|
631
|
+
// ---------------------------------------------------------------------------
|
|
632
|
+
function getCopilotSessionStateDir(override) {
|
|
633
|
+
return override ?? process.env['CODEBURN_COPILOT_SESSION_STATE_DIR'] ?? join(homedir(), '.copilot', 'session-state');
|
|
634
|
+
}
|
|
635
|
+
function getSessionStoreDbPath(override) {
|
|
636
|
+
return override ?? process.env['CODEBURN_COPILOT_SESSION_STORE_DB'] ?? join(homedir(), '.copilot', 'session-store.db');
|
|
637
|
+
}
|
|
638
|
+
/**
|
|
639
|
+
* Locate the agent-traces.db file.
|
|
640
|
+
*
|
|
641
|
+
* Priority:
|
|
642
|
+
* 1. CODEBURN_COPILOT_OTEL_DB env var
|
|
643
|
+
* 2. Platform-specific default VS Code global storage path
|
|
644
|
+
* 3. VSCodium variant paths
|
|
645
|
+
*/
|
|
646
|
+
function getAgentTracesDbPath() {
|
|
647
|
+
// Allow explicit override
|
|
648
|
+
const envOverride = process.env['CODEBURN_COPILOT_OTEL_DB'];
|
|
649
|
+
if (envOverride) {
|
|
650
|
+
return existsSync(envOverride) ? envOverride : null;
|
|
651
|
+
}
|
|
652
|
+
const candidates = getVSCodeGlobalStorageDirs(homedir(), platform())
|
|
653
|
+
.map(dir => join(dir, 'github.copilot-chat', 'agent-traces.db'));
|
|
654
|
+
for (const candidate of candidates) {
|
|
655
|
+
if (existsSync(candidate))
|
|
656
|
+
return candidate;
|
|
657
|
+
}
|
|
658
|
+
return null;
|
|
659
|
+
}
|
|
660
|
+
/**
|
|
661
|
+
* Locate the GitHub Copilot config root used by the JetBrains IDE plugin
|
|
662
|
+
* (IntelliJ IDEA, PyCharm, RubyMine, …). The JetBrains Copilot agent persists
|
|
663
|
+
* chat/agent sessions here — a location none of the VS Code or CLI sources
|
|
664
|
+
* touch, so this is the only way JetBrains-driven Copilot usage becomes
|
|
665
|
+
* visible to CodeBurn.
|
|
666
|
+
*
|
|
667
|
+
* The path mirrors the plugin's own `getXdgConfigPath` logic (observed in the
|
|
668
|
+
* bundled copilot-agent language server):
|
|
669
|
+
* - $XDG_CONFIG_HOME/github-copilot (when set to an absolute path)
|
|
670
|
+
* - macOS / Linux: ~/.config/github-copilot
|
|
671
|
+
* - Windows: %USERPROFILE%\AppData\Local\github-copilot
|
|
672
|
+
*
|
|
673
|
+
* Under this root, each IDE has its own subdir (e.g. `iu` for IntelliJ IDEA
|
|
674
|
+
* Ultimate, `intellij` for the community edition) containing
|
|
675
|
+
* chat-agent-sessions/, chat-sessions/, and chat-edit-sessions/.
|
|
676
|
+
*/
|
|
677
|
+
function getJetBrainsCopilotRoot(override) {
|
|
678
|
+
const envOverride = override ?? process.env['CODEBURN_COPILOT_JETBRAINS_DIR'];
|
|
679
|
+
if (envOverride)
|
|
680
|
+
return envOverride;
|
|
681
|
+
const xdg = process.env['XDG_CONFIG_HOME'];
|
|
682
|
+
if (xdg && (posix.isAbsolute(xdg) || win32.isAbsolute(xdg))) {
|
|
683
|
+
return join(xdg, 'github-copilot');
|
|
684
|
+
}
|
|
685
|
+
if (platform() === 'win32') {
|
|
686
|
+
const local = process.env['LOCALAPPDATA'] ?? join(homedir(), 'AppData', 'Local');
|
|
687
|
+
return join(local, 'github-copilot');
|
|
688
|
+
}
|
|
689
|
+
return join(homedir(), '.config', 'github-copilot');
|
|
690
|
+
}
|
|
691
|
+
// ---------------------------------------------------------------------------
|
|
692
|
+
// Helpers
|
|
693
|
+
// ---------------------------------------------------------------------------
|
|
694
|
+
function parseCwd(yaml) {
|
|
695
|
+
const match = yaml.match(/^cwd:\s*(.+)$/m);
|
|
696
|
+
if (!match?.[1])
|
|
697
|
+
return null;
|
|
698
|
+
let raw = match[1].trim();
|
|
699
|
+
// Strip inline YAML comments (# preceded by optional whitespace)
|
|
700
|
+
raw = raw.replace(/\s*#.*$/, '');
|
|
701
|
+
// Strip surrounding single/double quotes
|
|
702
|
+
raw = raw.replace(/^['"]|['"]$/g, '').trim();
|
|
703
|
+
return raw || null;
|
|
704
|
+
}
|
|
705
|
+
/**
|
|
706
|
+
* Load span attributes from the span_attributes table (key-value pairs).
|
|
707
|
+
* This handles the modern VS Code Copilot Chat schema where attributes
|
|
708
|
+
* are stored as separate key-value rows rather than a JSON blob.
|
|
709
|
+
*/
|
|
710
|
+
function loadSpanAttributesFromTable(db, spanId) {
|
|
711
|
+
try {
|
|
712
|
+
const rows = db.query(`SELECT key, value FROM span_attributes WHERE span_id = ?`, [spanId]);
|
|
713
|
+
const attrs = {};
|
|
714
|
+
for (const row of rows) {
|
|
715
|
+
if (row.key && row.value) {
|
|
716
|
+
try {
|
|
717
|
+
// Try to parse numeric values
|
|
718
|
+
const numValue = Number(row.value);
|
|
719
|
+
attrs[row.key] = Number.isNaN(numValue)
|
|
720
|
+
? row.value
|
|
721
|
+
: numValue;
|
|
722
|
+
}
|
|
723
|
+
catch {
|
|
724
|
+
attrs[row.key] = row.value;
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
return attrs;
|
|
729
|
+
}
|
|
730
|
+
catch {
|
|
731
|
+
return {};
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
/**
|
|
735
|
+
* Convert nanosecond or millisecond epoch to ISO timestamp.
|
|
736
|
+
* The OTel spec uses nanoseconds, but some implementations use milliseconds.
|
|
737
|
+
*/
|
|
738
|
+
function epochToISO(epoch) {
|
|
739
|
+
// Guard malformed rows: new Date(NaN).toISOString() throws. Fall back to the
|
|
740
|
+
// epoch (1970) so a bad timestamp is excluded from period totals, not crashing.
|
|
741
|
+
if (!Number.isFinite(epoch) || epoch <= 0)
|
|
742
|
+
return new Date(0).toISOString();
|
|
743
|
+
// If the value looks like nanoseconds (> 1e15), convert to ms
|
|
744
|
+
const ms = epoch > 1e15 ? Math.floor(epoch / 1e6) : epoch > 1e12 ? epoch : epoch * 1000;
|
|
745
|
+
return new Date(ms).toISOString();
|
|
746
|
+
}
|
|
747
|
+
function timestampToISO(raw) {
|
|
748
|
+
if (typeof raw === 'number' && Number.isFinite(raw) && raw > 0) {
|
|
749
|
+
return epochToISO(raw);
|
|
750
|
+
}
|
|
751
|
+
if (typeof raw !== 'string')
|
|
752
|
+
return '';
|
|
753
|
+
const trimmed = raw.trim();
|
|
754
|
+
if (!trimmed)
|
|
755
|
+
return '';
|
|
756
|
+
if (/^\d+(\.\d+)?$/.test(trimmed)) {
|
|
757
|
+
return epochToISO(Number(trimmed));
|
|
758
|
+
}
|
|
759
|
+
const parsed = Date.parse(trimmed);
|
|
760
|
+
return Number.isNaN(parsed) ? '' : new Date(parsed).toISOString();
|
|
761
|
+
}
|
|
762
|
+
function isRecord(value) {
|
|
763
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
764
|
+
}
|
|
765
|
+
function isReplayContainer(value) {
|
|
766
|
+
return typeof value === 'object' && value !== null;
|
|
767
|
+
}
|
|
768
|
+
function createReplayObject() {
|
|
769
|
+
return Object.create(null);
|
|
770
|
+
}
|
|
771
|
+
const FORBIDDEN_CHAT_JOURNAL_KEYS = new Set(['__proto__', 'prototype', 'constructor']);
|
|
772
|
+
function parseChatJournalPath(rawPath, fallback) {
|
|
773
|
+
const value = rawPath === undefined ? fallback : rawPath;
|
|
774
|
+
if (!Array.isArray(value))
|
|
775
|
+
return null;
|
|
776
|
+
const path = [];
|
|
777
|
+
for (const segment of value) {
|
|
778
|
+
if (typeof segment === 'number') {
|
|
779
|
+
if (!Number.isInteger(segment) || segment < 0)
|
|
780
|
+
return null;
|
|
781
|
+
path.push(segment);
|
|
782
|
+
continue;
|
|
783
|
+
}
|
|
784
|
+
if (typeof segment === 'string') {
|
|
785
|
+
if (FORBIDDEN_CHAT_JOURNAL_KEYS.has(segment))
|
|
786
|
+
return null;
|
|
787
|
+
path.push(segment);
|
|
788
|
+
continue;
|
|
789
|
+
}
|
|
790
|
+
return null;
|
|
791
|
+
}
|
|
792
|
+
return path;
|
|
793
|
+
}
|
|
794
|
+
function getReplayValue(container, segment) {
|
|
795
|
+
return container[String(segment)];
|
|
796
|
+
}
|
|
797
|
+
function setReplayValue(container, segment, value) {
|
|
798
|
+
;
|
|
799
|
+
container[String(segment)] = value;
|
|
800
|
+
}
|
|
801
|
+
function createContainerForNext(segment) {
|
|
802
|
+
return typeof segment === 'number' ? [] : createReplayObject();
|
|
803
|
+
}
|
|
804
|
+
function ensureReplayParent(root, path) {
|
|
805
|
+
let current = root;
|
|
806
|
+
for (let i = 0; i < path.length - 1; i++) {
|
|
807
|
+
const segment = path[i];
|
|
808
|
+
const nextSegment = path[i + 1];
|
|
809
|
+
let child = getReplayValue(current, segment);
|
|
810
|
+
if (!isReplayContainer(child)) {
|
|
811
|
+
const created = createContainerForNext(nextSegment);
|
|
812
|
+
setReplayValue(current, segment, created);
|
|
813
|
+
current = created;
|
|
814
|
+
continue;
|
|
815
|
+
}
|
|
816
|
+
current = child;
|
|
817
|
+
}
|
|
818
|
+
return current;
|
|
819
|
+
}
|
|
820
|
+
function applyChatJournalSet(root, path, value) {
|
|
821
|
+
if (path.length === 0)
|
|
822
|
+
return value;
|
|
823
|
+
const workingRoot = isReplayContainer(root) ? root : createReplayObject();
|
|
824
|
+
const parent = ensureReplayParent(workingRoot, path);
|
|
825
|
+
if (!parent)
|
|
826
|
+
return workingRoot;
|
|
827
|
+
setReplayValue(parent, path[path.length - 1], value);
|
|
828
|
+
return workingRoot;
|
|
829
|
+
}
|
|
830
|
+
function applyChatJournalAppend(root, path, items) {
|
|
831
|
+
const workingRoot = isReplayContainer(root) ? root : createReplayObject();
|
|
832
|
+
if (path.length === 0) {
|
|
833
|
+
if (Array.isArray(workingRoot)) {
|
|
834
|
+
for (const item of items)
|
|
835
|
+
workingRoot.push(item);
|
|
836
|
+
}
|
|
837
|
+
return workingRoot;
|
|
838
|
+
}
|
|
839
|
+
const parent = ensureReplayParent(workingRoot, path);
|
|
840
|
+
if (!parent)
|
|
841
|
+
return workingRoot;
|
|
842
|
+
const last = path[path.length - 1];
|
|
843
|
+
let target = getReplayValue(parent, last);
|
|
844
|
+
const targetArray = Array.isArray(target) ? target : [];
|
|
845
|
+
if (target !== targetArray) {
|
|
846
|
+
setReplayValue(parent, last, targetArray);
|
|
847
|
+
}
|
|
848
|
+
for (const item of items)
|
|
849
|
+
targetArray.push(item);
|
|
850
|
+
return workingRoot;
|
|
851
|
+
}
|
|
852
|
+
function replayChatSessionJournal(content) {
|
|
853
|
+
let root = createReplayObject();
|
|
854
|
+
const lines = content.split('\n').filter((l) => l.trim());
|
|
855
|
+
for (const line of lines) {
|
|
856
|
+
let entry;
|
|
857
|
+
try {
|
|
858
|
+
entry = JSON.parse(line);
|
|
859
|
+
}
|
|
860
|
+
catch {
|
|
861
|
+
continue;
|
|
862
|
+
}
|
|
863
|
+
if (!isRecord(entry))
|
|
864
|
+
continue;
|
|
865
|
+
const kind = entry['kind'];
|
|
866
|
+
if (kind === 0) {
|
|
867
|
+
root = entry['v'];
|
|
868
|
+
continue;
|
|
869
|
+
}
|
|
870
|
+
if (kind === 1) {
|
|
871
|
+
const path = parseChatJournalPath(entry['k']);
|
|
872
|
+
if (!path)
|
|
873
|
+
continue;
|
|
874
|
+
root = applyChatJournalSet(root, path, entry['v']);
|
|
875
|
+
continue;
|
|
876
|
+
}
|
|
877
|
+
if (kind === 2) {
|
|
878
|
+
const hasPath = Object.prototype.hasOwnProperty.call(entry, 'k');
|
|
879
|
+
const path = parseChatJournalPath(hasPath ? entry['k'] : undefined, ['requests']);
|
|
880
|
+
const items = Array.isArray(entry['v']) ? entry['v'] : [];
|
|
881
|
+
if (!path)
|
|
882
|
+
continue;
|
|
883
|
+
root = applyChatJournalAppend(root, path, items);
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
return root;
|
|
887
|
+
}
|
|
888
|
+
function numberOrZero(raw) {
|
|
889
|
+
return typeof raw === 'number' && Number.isFinite(raw) && raw > 0 ? raw : 0;
|
|
890
|
+
}
|
|
891
|
+
function readString(raw) {
|
|
892
|
+
return typeof raw === 'string' ? raw : '';
|
|
893
|
+
}
|
|
894
|
+
// An Auto request without resolvedModel names no priceable model. Unless
|
|
895
|
+
// copilotCredits price it (then its label stays), infer one the way the legacy
|
|
896
|
+
// JSON path does and report the cost as estimated; with nothing to infer from
|
|
897
|
+
// it is 'unknown', which reports as unpriced rather than as a $0 estimate.
|
|
898
|
+
function modelFromChatSessionRequest(req, metadata, session, billed) {
|
|
899
|
+
const resolved = readString(metadata['resolvedModel']);
|
|
900
|
+
if (resolved)
|
|
901
|
+
return { model: resolved, inferred: false };
|
|
902
|
+
const modelId = readString(req['modelId']).replace(/^copilot\//, '');
|
|
903
|
+
if (billed || (modelId !== 'auto' && modelId !== 'copilot-auto'))
|
|
904
|
+
return { model: modelId || 'unknown', inferred: false };
|
|
905
|
+
const inferred = extractModelFromRequest(req, session);
|
|
906
|
+
return { model: inferred, inferred: inferred !== 'unknown' };
|
|
907
|
+
}
|
|
908
|
+
function parseStructuredArguments(raw) {
|
|
909
|
+
const payload = typeof raw === 'string'
|
|
910
|
+
? (() => {
|
|
911
|
+
try {
|
|
912
|
+
return JSON.parse(raw);
|
|
913
|
+
}
|
|
914
|
+
catch {
|
|
915
|
+
return null;
|
|
916
|
+
}
|
|
917
|
+
})()
|
|
918
|
+
: raw;
|
|
919
|
+
return isRecord(payload) ? payload : null;
|
|
920
|
+
}
|
|
921
|
+
function extractStructuredSkill(raw) {
|
|
922
|
+
const payload = parseStructuredArguments(raw);
|
|
923
|
+
if (!payload)
|
|
924
|
+
return null;
|
|
925
|
+
const skill = payload['skill'];
|
|
926
|
+
return typeof skill === 'string' && skill.trim() ? skill.trim() : null;
|
|
927
|
+
}
|
|
928
|
+
function extractChatSessionTools(metadata) {
|
|
929
|
+
const rounds = metadata['toolCallRounds'];
|
|
930
|
+
if (!Array.isArray(rounds))
|
|
931
|
+
return { tools: [], skills: [], bashCommands: [] };
|
|
932
|
+
const names = new Set();
|
|
933
|
+
const skills = new Set();
|
|
934
|
+
const bashCommands = [];
|
|
935
|
+
const addName = (raw) => {
|
|
936
|
+
if (typeof raw === 'string' && raw.trim())
|
|
937
|
+
names.add(normalizeTool(raw));
|
|
938
|
+
};
|
|
939
|
+
const addFromRecord = (record) => {
|
|
940
|
+
const rawNames = ['toolName', 'name', 'tool'].map(key => record[key]);
|
|
941
|
+
for (const raw of rawNames) {
|
|
942
|
+
addName(raw);
|
|
943
|
+
if (typeof raw !== 'string' || normalizeTool(raw) !== 'Skill')
|
|
944
|
+
continue;
|
|
945
|
+
const skill = extractStructuredSkill(record['arguments'])
|
|
946
|
+
?? extractStructuredSkill(record['input']);
|
|
947
|
+
if (skill)
|
|
948
|
+
skills.add(skill);
|
|
949
|
+
}
|
|
950
|
+
if (rawNames.some(raw => typeof raw === 'string' && BASH_TOOL_NAMES.has(raw))) {
|
|
951
|
+
const args = parseStructuredArguments(record['arguments'])
|
|
952
|
+
?? parseStructuredArguments(record['input']);
|
|
953
|
+
const command = args?.['command'];
|
|
954
|
+
if (typeof command === 'string')
|
|
955
|
+
bashCommands.push(...extractBashCommands(command));
|
|
956
|
+
}
|
|
957
|
+
};
|
|
958
|
+
for (const round of rounds) {
|
|
959
|
+
if (!isRecord(round))
|
|
960
|
+
continue;
|
|
961
|
+
addFromRecord(round);
|
|
962
|
+
for (const key of ['tools', 'toolCalls', 'toolRequests']) {
|
|
963
|
+
const entries = round[key];
|
|
964
|
+
if (!Array.isArray(entries))
|
|
965
|
+
continue;
|
|
966
|
+
for (const entry of entries) {
|
|
967
|
+
if (typeof entry === 'string') {
|
|
968
|
+
addName(entry);
|
|
969
|
+
}
|
|
970
|
+
else if (isRecord(entry)) {
|
|
971
|
+
addFromRecord(entry);
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
return { tools: [...names], skills: [...skills], bashCommands };
|
|
977
|
+
}
|
|
978
|
+
/**
|
|
979
|
+
* Extract a shell command string from an OTel execute_tool span's
|
|
980
|
+
* `gen_ai.tool.call.arguments` attribute. The attribute is a JSON-encoded
|
|
981
|
+
* argument object (e.g. `{"command":"ls -la"}`); we pull out the `command`
|
|
982
|
+
* field. Returns null when the attribute is absent or doesn't carry a command,
|
|
983
|
+
* so callers can skip shell-command extraction cleanly.
|
|
984
|
+
*/
|
|
985
|
+
function parseToolCommand(raw) {
|
|
986
|
+
if (typeof raw !== 'string' || !raw.trim())
|
|
987
|
+
return null;
|
|
988
|
+
try {
|
|
989
|
+
const parsed = JSON.parse(raw);
|
|
990
|
+
const command = parsed['command'];
|
|
991
|
+
return typeof command === 'string' ? command : null;
|
|
992
|
+
}
|
|
993
|
+
catch {
|
|
994
|
+
return null;
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
// Shell control-flow keywords. These lead a statement but are not commands, so
|
|
998
|
+
// they must never be reported as bash commands.
|
|
999
|
+
const OTEL_SHELL_KEYWORDS = new Set([
|
|
1000
|
+
'if', 'then', 'else', 'elif', 'fi',
|
|
1001
|
+
'for', 'while', 'until', 'do', 'done',
|
|
1002
|
+
'case', 'esac', 'select', 'function', 'in', 'time', 'coproc',
|
|
1003
|
+
]);
|
|
1004
|
+
/**
|
|
1005
|
+
* Normalise an OTEL shell command before command-name extraction.
|
|
1006
|
+
*
|
|
1007
|
+
* Unlike the Copilot CLI / VS Code JSONL logs — which record a single command
|
|
1008
|
+
* per tool call (e.g. `cd x && python3 y`) — the OTEL store records the FULL
|
|
1009
|
+
* multi-line script the agent ran (heredocs, for/if blocks, newline-separated
|
|
1010
|
+
* statements). The shared extractBashCommands helper only splits on `;`/`&&`/`|`
|
|
1011
|
+
* and has no concept of shell keywords, so those scripts leak control-flow words
|
|
1012
|
+
* (`for`, `do`, `if`, `then`, …) and collapse newline-separated statements.
|
|
1013
|
+
*
|
|
1014
|
+
* Normalising here — rather than in the shared helper — keeps every other
|
|
1015
|
+
* provider's behaviour unchanged. We (1) turn newlines into `;` so each
|
|
1016
|
+
* statement is its own segment, then (2) drop shell control-flow keywords.
|
|
1017
|
+
*/
|
|
1018
|
+
function extractOtelBashCommands(command) {
|
|
1019
|
+
const normalized = command.replace(/\r?\n/g, '; ');
|
|
1020
|
+
return extractBashCommands(normalized).filter(c => !OTEL_SHELL_KEYWORDS.has(c));
|
|
1021
|
+
}
|
|
1022
|
+
// ---------------------------------------------------------------------------
|
|
1023
|
+
// Helpers for JSONL / transcript parsing
|
|
1024
|
+
// ---------------------------------------------------------------------------
|
|
1025
|
+
/**
|
|
1026
|
+
* Safely coerce a raw toolRequests value to an array of ToolRequest.
|
|
1027
|
+
* Non-array values (string, null, undefined) are treated as empty arrays
|
|
1028
|
+
* so that a corrupt event.data doesn't abort the whole file parse loop.
|
|
1029
|
+
*/
|
|
1030
|
+
function coerceToolRequests(raw) {
|
|
1031
|
+
return Array.isArray(raw) ? raw : [];
|
|
1032
|
+
}
|
|
1033
|
+
/**
|
|
1034
|
+
* Infer the model bucket for a VS Code transcript file by counting the
|
|
1035
|
+
* toolCallId prefixes across all assistant messages:
|
|
1036
|
+
* call_* → OpenAI
|
|
1037
|
+
* tooluse_* / toolu_* → Anthropic
|
|
1038
|
+
* The dominant prefix determines the model for the whole session.
|
|
1039
|
+
* Returns '' if no toolCallIds are present.
|
|
1040
|
+
*/
|
|
1041
|
+
function inferTranscriptModel(lines) {
|
|
1042
|
+
let openaiCount = 0;
|
|
1043
|
+
let anthropicCount = 0;
|
|
1044
|
+
for (const line of lines) {
|
|
1045
|
+
try {
|
|
1046
|
+
const event = JSON.parse(line);
|
|
1047
|
+
if (event.type !== 'assistant.message')
|
|
1048
|
+
continue;
|
|
1049
|
+
const data = event.data;
|
|
1050
|
+
const reqs = coerceToolRequests(data.toolRequests);
|
|
1051
|
+
for (const req of reqs) {
|
|
1052
|
+
const id = req.toolCallId;
|
|
1053
|
+
if (typeof id !== 'string')
|
|
1054
|
+
continue;
|
|
1055
|
+
if (id.startsWith('call_'))
|
|
1056
|
+
openaiCount++;
|
|
1057
|
+
else if (/^tooluse_|^toolu_/.test(id))
|
|
1058
|
+
anthropicCount++;
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
catch {
|
|
1062
|
+
continue;
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
if (openaiCount === 0 && anthropicCount === 0)
|
|
1066
|
+
return '';
|
|
1067
|
+
return openaiCount >= anthropicCount ? 'copilot-openai-auto' : 'copilot-anthropic-auto';
|
|
1068
|
+
}
|
|
1069
|
+
// ---------------------------------------------------------------------------
|
|
1070
|
+
// JSONL parser (handles both regular CLI session-state events and the VS Code
|
|
1071
|
+
// transcript format — the same event vocabulary, but transcripts carry no
|
|
1072
|
+
// token counts and no session.shutdown rollup)
|
|
1073
|
+
// ---------------------------------------------------------------------------
|
|
1074
|
+
/**
|
|
1075
|
+
* `isTranscript` comes from discovery (where the file lives), never from
|
|
1076
|
+
* content: the Copilot CLI writes the same session.start producer
|
|
1077
|
+
* ('copilot-agent') that VS Code transcripts carry, so producer sniffing
|
|
1078
|
+
* misread every CLI session as a transcript and dropped its session.shutdown
|
|
1079
|
+
* input/cache rollup (#944).
|
|
1080
|
+
*/
|
|
1081
|
+
function createJsonlParser(source, seenKeys, isTranscript) {
|
|
1082
|
+
return {
|
|
1083
|
+
async *parse() {
|
|
1084
|
+
const content = await readSessionFile(source.path);
|
|
1085
|
+
if (!content)
|
|
1086
|
+
return;
|
|
1087
|
+
// CLI session-state files live at <sessionId>/events.jsonl; transcripts
|
|
1088
|
+
// at transcripts/<sessionId>.jsonl — keying the latter on the parent dir
|
|
1089
|
+
// would collapse every transcript into one "transcripts" session (and
|
|
1090
|
+
// one shared dedup namespace).
|
|
1091
|
+
const sessionId = isTranscript
|
|
1092
|
+
? basename(source.path, '.jsonl')
|
|
1093
|
+
: basename(dirname(source.path));
|
|
1094
|
+
const lines = content.split('\n').filter((l) => l.trim());
|
|
1095
|
+
let currentModel = '';
|
|
1096
|
+
let pendingUserMessage = '';
|
|
1097
|
+
// Subagent attribution. Older CLIs write subagent.selected — sticky
|
|
1098
|
+
// until replaced, never cleared. CLI ≥ ~1.0.7x brackets each run with
|
|
1099
|
+
// started/completed instead; runs can nest or overlap, so completed
|
|
1100
|
+
// removes ONLY its own toolCallId's entry and the label falls back to
|
|
1101
|
+
// the still-active run (or the sticky selected value) rather than
|
|
1102
|
+
// wiping attribution for everything in flight.
|
|
1103
|
+
let selectedSubagentType;
|
|
1104
|
+
const activeSubagents = [];
|
|
1105
|
+
const currentSubagentType = () => activeSubagents[activeSubagents.length - 1]?.name ?? selectedSubagentType;
|
|
1106
|
+
if (isTranscript) {
|
|
1107
|
+
// Tool-call-id prefix inference seeds the model; it must not gate the
|
|
1108
|
+
// whole file, or a transcript carrying explicit model info
|
|
1109
|
+
// (session.model_change / per-message model) but no tool calls would
|
|
1110
|
+
// yield nothing. Messages that still end up modelless are skipped
|
|
1111
|
+
// individually below.
|
|
1112
|
+
currentModel = inferTranscriptModel(lines);
|
|
1113
|
+
}
|
|
1114
|
+
// Shutdown rollups may lack their own timestamp; remember the last
|
|
1115
|
+
// stamped event so the supplementary call is never left with an empty
|
|
1116
|
+
// timestamp, which the date-range filters silently drop.
|
|
1117
|
+
let lastEventTimestamp = '';
|
|
1118
|
+
// Stamp of the most recent SUCCESSFUL session.compaction_complete seen so
|
|
1119
|
+
// far. Carried onto each shutdown leg because a compaction resets the
|
|
1120
|
+
// rollup counters, so the leg only describes requests after this point.
|
|
1121
|
+
let lastCompactionTs = '';
|
|
1122
|
+
// A resumed session appends one session.shutdown PER LEG, each carrying
|
|
1123
|
+
// CUMULATIVE per-model totals. Emitting each rollup whole would need the
|
|
1124
|
+
// cache to update a prior call in place — the durable merge is
|
|
1125
|
+
// append-only by dedup key — so we emit per-leg DELTAS keyed by
|
|
1126
|
+
// occurrence (`:n`): re-parses of a growing file append only the new
|
|
1127
|
+
// leg, and each leg lands on its own timestamp. Discovery only yields
|
|
1128
|
+
// `<sid>/events.jsonl`, so two journals cannot share a session id.
|
|
1129
|
+
const prevShutdownUsage = new Map();
|
|
1130
|
+
const shutdownCountByModel = new Map();
|
|
1131
|
+
// Whether this leg's assistant.message events carried outputTokens. When
|
|
1132
|
+
// none did, the rollup is the only record of output and must carry it.
|
|
1133
|
+
let legHasPerTurnOutput = false;
|
|
1134
|
+
for (const line of lines) {
|
|
1135
|
+
let event;
|
|
1136
|
+
try {
|
|
1137
|
+
event = JSON.parse(line);
|
|
1138
|
+
}
|
|
1139
|
+
catch {
|
|
1140
|
+
continue;
|
|
1141
|
+
}
|
|
1142
|
+
if (typeof event.timestamp === 'string' && event.timestamp)
|
|
1143
|
+
lastEventTimestamp = event.timestamp;
|
|
1144
|
+
if (event.type === 'session.start') {
|
|
1145
|
+
if (!isTranscript) {
|
|
1146
|
+
currentModel = event.data.selectedModel ?? currentModel;
|
|
1147
|
+
}
|
|
1148
|
+
continue;
|
|
1149
|
+
}
|
|
1150
|
+
if (event.type === 'session.model_change') {
|
|
1151
|
+
currentModel = event.data.newModel ?? currentModel;
|
|
1152
|
+
continue;
|
|
1153
|
+
}
|
|
1154
|
+
// In-session compaction RESETS the session.shutdown rollup counters,
|
|
1155
|
+
// so a leg that contains one describes only its post-compaction
|
|
1156
|
+
// requests. Carrying the compaction's stamp onto the leg lets the
|
|
1157
|
+
// serve-time reconciliation start that leg's store-row interval here
|
|
1158
|
+
// instead of at the previous leg, which is the difference between
|
|
1159
|
+
// subtracting only the requests the rollup actually covers and
|
|
1160
|
+
// subtracting the whole pre-compaction conversation from it.
|
|
1161
|
+
// compaction_start is recognized but carries nothing we need: only a
|
|
1162
|
+
// COMPLETE with success:true reset anything (a failed or abandoned
|
|
1163
|
+
// compaction leaves the counters alone).
|
|
1164
|
+
if (event.type === 'session.compaction_complete') {
|
|
1165
|
+
const data = event.data;
|
|
1166
|
+
const ts = typeof event.timestamp === 'string' ? event.timestamp : '';
|
|
1167
|
+
if (data?.success === true && ts && !Number.isNaN(new Date(ts).getTime())) {
|
|
1168
|
+
lastCompactionTs = ts;
|
|
1169
|
+
}
|
|
1170
|
+
continue;
|
|
1171
|
+
}
|
|
1172
|
+
if (event.type === 'session.compaction_start')
|
|
1173
|
+
continue;
|
|
1174
|
+
if (event.type === 'subagent.selected') {
|
|
1175
|
+
selectedSubagentType = event.data.agentName;
|
|
1176
|
+
continue;
|
|
1177
|
+
}
|
|
1178
|
+
if (event.type === 'subagent.started') {
|
|
1179
|
+
const data = event.data;
|
|
1180
|
+
activeSubagents.push({ toolCallId: data.toolCallId ?? '', name: data.agentName });
|
|
1181
|
+
continue;
|
|
1182
|
+
}
|
|
1183
|
+
if (event.type === 'subagent.completed') {
|
|
1184
|
+
const id = event.data.toolCallId ?? '';
|
|
1185
|
+
if (!id) {
|
|
1186
|
+
// ID-less completion (transitional CLIs that key nothing, like
|
|
1187
|
+
// subagent.selected): end the most recently started run; explicit
|
|
1188
|
+
// no-op on an empty stack.
|
|
1189
|
+
activeSubagents.pop();
|
|
1190
|
+
continue;
|
|
1191
|
+
}
|
|
1192
|
+
for (let i = activeSubagents.length - 1; i >= 0; i--) {
|
|
1193
|
+
if (activeSubagents[i].toolCallId === id) {
|
|
1194
|
+
activeSubagents.splice(i, 1);
|
|
1195
|
+
break;
|
|
1196
|
+
}
|
|
1197
|
+
}
|
|
1198
|
+
// A non-empty id that matches nothing refers to a run we never saw
|
|
1199
|
+
// start — leave the active runs alone rather than evicting an
|
|
1200
|
+
// unrelated one.
|
|
1201
|
+
continue;
|
|
1202
|
+
}
|
|
1203
|
+
if (event.type === 'user.message') {
|
|
1204
|
+
pendingUserMessage = event.data.content ?? '';
|
|
1205
|
+
continue;
|
|
1206
|
+
}
|
|
1207
|
+
if (event.type === 'session.shutdown') {
|
|
1208
|
+
// The Copilot CLI writes a per-model token/cost rollup here at
|
|
1209
|
+
// shutdown: the only place a CLI session records input, cache-read
|
|
1210
|
+
// and cache-write tokens (assistant.message events carry output
|
|
1211
|
+
// only). VS Code transcripts never carry this rollup, so this path
|
|
1212
|
+
// is gated to the CLI (non-transcript) format, leaving VS Code,
|
|
1213
|
+
// JetBrains and OTel sources untouched.
|
|
1214
|
+
//
|
|
1215
|
+
// We emit one supplementary call per model PER SHUTDOWN LEG (resumed
|
|
1216
|
+
// sessions write one cumulative rollup per leg; see the delta
|
|
1217
|
+
// tracking above) carrying ONLY the input/cache tokens the per-turn
|
|
1218
|
+
// events lack; output is excluded so the assistant.message output
|
|
1219
|
+
// (and its cost) is not double-counted. Combined with the per-turn
|
|
1220
|
+
// output cost, this yields the full, CLI-measured session cost.
|
|
1221
|
+
// CLI 1.0.8x and the VS Code agent host write no per-turn output,
|
|
1222
|
+
// so for their legs the rollup carries output too.
|
|
1223
|
+
if (isTranscript)
|
|
1224
|
+
continue;
|
|
1225
|
+
// When session-store.db holds per-request usage rows for this
|
|
1226
|
+
// session, those rows are authoritative for input/cache: written
|
|
1227
|
+
// per request instead of only on clean shutdown, and they describe
|
|
1228
|
+
// the SAME tokens this rollup lumps together. That precedence is
|
|
1229
|
+
// enforced at SERVE time, not here: this rollup is always parsed
|
|
1230
|
+
// and cached, and the reconciliation in parseProviderSources
|
|
1231
|
+
// decides per (session, model) — store rows replace the rollup,
|
|
1232
|
+
// with any usage the rollup carried beyond the rows' sum served as
|
|
1233
|
+
// a residual (see reconcileCopilotCalls there). Read-time
|
|
1234
|
+
// precedence over one coherent serve set cannot be raced by
|
|
1235
|
+
// writers between a coverage probe and this parse, and a briefly
|
|
1236
|
+
// unreadable store never blocks this file.
|
|
1237
|
+
const shutdownData = event.data;
|
|
1238
|
+
const modelMetrics = shutdownData.modelMetrics;
|
|
1239
|
+
if (!isRecord(modelMetrics))
|
|
1240
|
+
continue;
|
|
1241
|
+
// Prefer lastEventTimestamp over sessionStartTime. sessionStartTime
|
|
1242
|
+
// is identical for every stampless leg of a resumed session, so
|
|
1243
|
+
// using it for the call timestamp (or, previously, the key) collapsed
|
|
1244
|
+
// those legs onto one date. lastEventTimestamp is the last stamped
|
|
1245
|
+
// event in this journal — distinct per leg when intervening events
|
|
1246
|
+
// are stamped, and still a real time when they are not.
|
|
1247
|
+
//
|
|
1248
|
+
// Fallback order matters for accounting, not just display: this
|
|
1249
|
+
// stamp anchors the leg's interval in the serve-time reconciliation,
|
|
1250
|
+
// which subtracts the store rows written up to it. A shutdown
|
|
1251
|
+
// happens at the END of a leg, so the last event seen is the
|
|
1252
|
+
// nearest true anchor; sessionStartTime is BEFORE every row, and
|
|
1253
|
+
// anchoring there would leave the leg covering nothing and re-mint
|
|
1254
|
+
// its whole usage as a residual beside the rows it duplicates.
|
|
1255
|
+
const shutdownTimestamp = (event.timestamp ?? '') || lastEventTimestamp || timestampToISO(shutdownData.sessionStartTime);
|
|
1256
|
+
for (const [model, metrics] of Object.entries(modelMetrics)) {
|
|
1257
|
+
if (!model || !isRecord(metrics))
|
|
1258
|
+
continue;
|
|
1259
|
+
const usage = metrics['usage'];
|
|
1260
|
+
if (!isRecord(usage))
|
|
1261
|
+
continue;
|
|
1262
|
+
const hasNanoAiu = typeof metrics['totalNanoAiu'] === 'number';
|
|
1263
|
+
const cumulative = {
|
|
1264
|
+
inputTokens: numberOrZero(usage['inputTokens']),
|
|
1265
|
+
outputTokens: numberOrZero(usage['outputTokens']),
|
|
1266
|
+
cacheReadTokens: numberOrZero(usage['cacheReadTokens']),
|
|
1267
|
+
cacheWriteTokens: numberOrZero(usage['cacheWriteTokens']),
|
|
1268
|
+
reasoningTokens: numberOrZero(usage['reasoningTokens']),
|
|
1269
|
+
nanoAiu: numberOrZero(metrics['totalNanoAiu']),
|
|
1270
|
+
};
|
|
1271
|
+
const prevRaw = prevShutdownUsage.get(model);
|
|
1272
|
+
prevShutdownUsage.set(model, cumulative);
|
|
1273
|
+
const n = (shutdownCountByModel.get(model) ?? 0) + 1;
|
|
1274
|
+
shutdownCountByModel.set(model, n);
|
|
1275
|
+
// A cumulative total BELOW the previous rollup means the CLI reset
|
|
1276
|
+
// its counters (a fresh accounting epoch): delta from zero, else
|
|
1277
|
+
// this leg's post-reset usage would be clamped away entirely.
|
|
1278
|
+
// inputTokens is the monotonic sentinel — it is cache-inclusive,
|
|
1279
|
+
// so any usage at all grows it. In-session COMPACTION is a
|
|
1280
|
+
// confirmed reset trigger (CLI 1.0.78: a clean single-process
|
|
1281
|
+
// 107-request session's sole rollup covered exactly its five
|
|
1282
|
+
// post-compaction requests), so rollup-only accounting
|
|
1283
|
+
// undercounts any compacted session — usage between the last
|
|
1284
|
+
// pre-reset rollup and the reset is simply never written here.
|
|
1285
|
+
// Only the per-request session-store rows record it; that is why
|
|
1286
|
+
// they are authoritative for covered sessions.
|
|
1287
|
+
const prev = prevRaw && cumulative.inputTokens < numberOrZero(prevRaw.inputTokens)
|
|
1288
|
+
? undefined
|
|
1289
|
+
: prevRaw;
|
|
1290
|
+
// This leg's contribution: cumulative minus the previous rollup.
|
|
1291
|
+
// The clamp guards any remaining non-monotonic field.
|
|
1292
|
+
const delta = (k) => Math.max(0, cumulative[k] - numberOrZero(prev?.[k]));
|
|
1293
|
+
const outputTokens = legHasPerTurnOutput ? 0 : delta('outputTokens');
|
|
1294
|
+
const nanoAiu = hasNanoAiu
|
|
1295
|
+
? Math.max(0, cumulative.nanoAiu - (prevRaw && cumulative.nanoAiu >= prevRaw.nanoAiu ? prevRaw.nanoAiu : 0))
|
|
1296
|
+
: undefined;
|
|
1297
|
+
const cacheReadTokens = delta('cacheReadTokens');
|
|
1298
|
+
const cacheWriteTokens = delta('cacheWriteTokens');
|
|
1299
|
+
const reasoningTokens = delta('reasoningTokens');
|
|
1300
|
+
// usage.inputTokens is cache-INCLUSIVE (input + cache_read +
|
|
1301
|
+
// cache_write). calculateCost expects the uncached input alone with
|
|
1302
|
+
// cache tokens billed separately, so subtract the cache components.
|
|
1303
|
+
// Clamp at 0 in case a future schema reports input non-inclusively.
|
|
1304
|
+
const inputTokens = Math.max(0, delta('inputTokens') - cacheReadTokens - cacheWriteTokens);
|
|
1305
|
+
// Nothing this call would add over the per-turn events, so skip it
|
|
1306
|
+
// to avoid an empty $0 row.
|
|
1307
|
+
if (inputTokens === 0 && outputTokens === 0 && cacheReadTokens === 0 && cacheWriteTokens === 0 && reasoningTokens === 0 && !nanoAiu)
|
|
1308
|
+
continue;
|
|
1309
|
+
const dedupKey = `copilot:${sessionId}:shutdown:${model}:${n}`;
|
|
1310
|
+
if (seenKeys.has(dedupKey))
|
|
1311
|
+
continue;
|
|
1312
|
+
seenKeys.add(dedupKey);
|
|
1313
|
+
// Tokens are real counts written by the CLI, so this cost is
|
|
1314
|
+
// measured, not char-estimated: costIsEstimated is false.
|
|
1315
|
+
const costUSD = calculateCost(model, inputTokens, outputTokens, cacheWriteTokens, cacheReadTokens, 0);
|
|
1316
|
+
yield {
|
|
1317
|
+
provider: 'copilot',
|
|
1318
|
+
sessionId,
|
|
1319
|
+
model,
|
|
1320
|
+
inputTokens,
|
|
1321
|
+
outputTokens,
|
|
1322
|
+
cacheCreationInputTokens: cacheWriteTokens,
|
|
1323
|
+
cacheReadInputTokens: cacheReadTokens,
|
|
1324
|
+
cachedInputTokens: 0,
|
|
1325
|
+
reasoningTokens,
|
|
1326
|
+
webSearchRequests: 0,
|
|
1327
|
+
costUSD,
|
|
1328
|
+
costIsEstimated: false,
|
|
1329
|
+
tools: [],
|
|
1330
|
+
bashCommands: [],
|
|
1331
|
+
timestamp: shutdownTimestamp,
|
|
1332
|
+
speed: 'standard',
|
|
1333
|
+
deduplicationKey: dedupKey,
|
|
1334
|
+
userMessage: '',
|
|
1335
|
+
...(lastCompactionTs ? { compactedAt: lastCompactionTs } : {}),
|
|
1336
|
+
...(nanoAiu !== undefined ? { nanoAiu } : {}),
|
|
1337
|
+
};
|
|
1338
|
+
}
|
|
1339
|
+
legHasPerTurnOutput = false;
|
|
1340
|
+
continue;
|
|
1341
|
+
}
|
|
1342
|
+
if (event.type === 'assistant.message') {
|
|
1343
|
+
const msgData = event.data;
|
|
1344
|
+
const { messageId, model: msgModel, outputTokens = 0 } = msgData;
|
|
1345
|
+
const hasOutputField = typeof msgData.outputTokens === 'number';
|
|
1346
|
+
if (hasOutputField)
|
|
1347
|
+
legHasPerTurnOutput = true;
|
|
1348
|
+
const rawRequests = msgData.toolRequests;
|
|
1349
|
+
const toolRequests = coerceToolRequests(rawRequests);
|
|
1350
|
+
// model may be carried per-message in newer copilot-agent format
|
|
1351
|
+
if (msgModel)
|
|
1352
|
+
currentModel = msgModel;
|
|
1353
|
+
// Older CLIs: skip zero-token messages. A message with no outputTokens
|
|
1354
|
+
// field still counts as a request; its tokens arrive with the rollup.
|
|
1355
|
+
if (!isTranscript && hasOutputField && outputTokens === 0)
|
|
1356
|
+
continue;
|
|
1357
|
+
if (!currentModel)
|
|
1358
|
+
continue;
|
|
1359
|
+
const dedupKey = `copilot:${sessionId}:${messageId}`;
|
|
1360
|
+
if (seenKeys.has(dedupKey))
|
|
1361
|
+
continue;
|
|
1362
|
+
seenKeys.add(dedupKey);
|
|
1363
|
+
const tools = toolRequests
|
|
1364
|
+
.map((t) => {
|
|
1365
|
+
const raw = typeof t === 'object' && t !== null
|
|
1366
|
+
? (t.name ?? t.toolName)
|
|
1367
|
+
: null;
|
|
1368
|
+
return typeof raw === 'string' ? normalizeTool(raw) : null;
|
|
1369
|
+
})
|
|
1370
|
+
.filter((t) => t !== null);
|
|
1371
|
+
const skills = toolRequests.flatMap((t) => {
|
|
1372
|
+
if (typeof t !== 'object' || t === null)
|
|
1373
|
+
return [];
|
|
1374
|
+
const name = (t.name ?? t.toolName) ?? '';
|
|
1375
|
+
if (name !== 'skill')
|
|
1376
|
+
return [];
|
|
1377
|
+
const skill = t.arguments?.['skill'];
|
|
1378
|
+
return typeof skill === 'string' && skill.trim().length > 0 ? [skill.trim()] : [];
|
|
1379
|
+
});
|
|
1380
|
+
// Extract base command names from bash-type tool requests, routing the
|
|
1381
|
+
// raw command through the shared extractBashCommands helper so chained
|
|
1382
|
+
// commands are normalised the same way as every other provider
|
|
1383
|
+
// (see bash-utils.ts, parser.ts, forge.ts, grok.ts, etc.).
|
|
1384
|
+
const bashCommands = toolRequests.flatMap((t) => {
|
|
1385
|
+
if (typeof t !== 'object' || t === null)
|
|
1386
|
+
return [];
|
|
1387
|
+
const name = (t.name ?? t.toolName) ?? '';
|
|
1388
|
+
if (!BASH_TOOL_NAMES.has(name))
|
|
1389
|
+
return [];
|
|
1390
|
+
const cmd = t.arguments?.['command'];
|
|
1391
|
+
return typeof cmd === 'string' ? extractBashCommands(cmd) : [];
|
|
1392
|
+
});
|
|
1393
|
+
// Copilot JSONL only logs outputTokens; inputTokens are NOT available.
|
|
1394
|
+
// Cost will be lower than actual API cost. This is the original
|
|
1395
|
+
// behaviour — OTel data (below) replaces it when available.
|
|
1396
|
+
const costUSD = calculateCost(currentModel, 0, outputTokens, 0, 0, 0);
|
|
1397
|
+
const subagentType = currentSubagentType();
|
|
1398
|
+
yield {
|
|
1399
|
+
provider: 'copilot',
|
|
1400
|
+
sessionId,
|
|
1401
|
+
model: currentModel,
|
|
1402
|
+
inputTokens: 0,
|
|
1403
|
+
outputTokens,
|
|
1404
|
+
cacheCreationInputTokens: 0,
|
|
1405
|
+
cacheReadInputTokens: 0,
|
|
1406
|
+
cachedInputTokens: 0,
|
|
1407
|
+
reasoningTokens: 0,
|
|
1408
|
+
webSearchRequests: 0,
|
|
1409
|
+
costUSD,
|
|
1410
|
+
// A transcript with no token count has unknown usage, not zero. A
|
|
1411
|
+
// counted output is measured; the shutdown rollup or store rows
|
|
1412
|
+
// carry the input (and, for tokenless CLI messages, the output).
|
|
1413
|
+
...(isTranscript && outputTokens === 0 ? { costIsEstimated: true } : {}),
|
|
1414
|
+
tools,
|
|
1415
|
+
bashCommands,
|
|
1416
|
+
skills: skills.length > 0 ? skills : undefined,
|
|
1417
|
+
subagentTypes: subagentType ? [subagentType] : undefined,
|
|
1418
|
+
timestamp: event.timestamp ?? '',
|
|
1419
|
+
speed: 'standard',
|
|
1420
|
+
deduplicationKey: dedupKey,
|
|
1421
|
+
userMessage: pendingUserMessage,
|
|
1422
|
+
};
|
|
1423
|
+
pendingUserMessage = '';
|
|
1424
|
+
}
|
|
1425
|
+
}
|
|
1426
|
+
},
|
|
1427
|
+
};
|
|
1428
|
+
}
|
|
1429
|
+
function createChatSessionParser(source, seenKeys) {
|
|
1430
|
+
return {
|
|
1431
|
+
async *parse() {
|
|
1432
|
+
const content = await readSessionFile(source.path);
|
|
1433
|
+
if (!content)
|
|
1434
|
+
return;
|
|
1435
|
+
if (source.path.endsWith('.json')) {
|
|
1436
|
+
let session;
|
|
1437
|
+
try {
|
|
1438
|
+
session = JSON.parse(content);
|
|
1439
|
+
}
|
|
1440
|
+
catch {
|
|
1441
|
+
return;
|
|
1442
|
+
}
|
|
1443
|
+
const sessionId = readString(session.sessionId) || basename(source.path, '.json');
|
|
1444
|
+
yield* parseLegacyChatSession(session, sessionId, source.project, seenKeys);
|
|
1445
|
+
return;
|
|
1446
|
+
}
|
|
1447
|
+
const root = replayChatSessionJournal(content);
|
|
1448
|
+
if (!isRecord(root))
|
|
1449
|
+
return;
|
|
1450
|
+
const sessionId = readString(root['sessionId']) || basename(source.path, '.jsonl');
|
|
1451
|
+
const sessionCreatedAt = timestampToISO(root['creationDate']);
|
|
1452
|
+
const requests = Array.isArray(root['requests']) ? root['requests'] : [];
|
|
1453
|
+
for (let index = 0; index < requests.length; index++) {
|
|
1454
|
+
const rawReq = requests[index];
|
|
1455
|
+
if (!isRecord(rawReq))
|
|
1456
|
+
continue;
|
|
1457
|
+
const result = rawReq['result'];
|
|
1458
|
+
const resultRecord = isRecord(result) ? result : null;
|
|
1459
|
+
const rawMetadata = resultRecord?.['metadata'];
|
|
1460
|
+
const metadata = isRecord(rawMetadata) ? rawMetadata : createReplayObject();
|
|
1461
|
+
// VS Code also serializes usage on the request itself, with output
|
|
1462
|
+
// summed over every round. Same precedence as the legacy JSON parser.
|
|
1463
|
+
const totals = chatSessionModelTotals(rawReq['modelTotals']);
|
|
1464
|
+
const nanoAiu = chatSessionNanoAiu(rawReq['copilotCredits']);
|
|
1465
|
+
const inputTokens = totals ? totals.inputTokens : numberOrZero(metadata['promptTokens']) || numberOrZero(rawReq['promptTokens']);
|
|
1466
|
+
const outputTokens = totals ? totals.outputTokens : numberOrZero(rawReq['completionTokens']) || numberOrZero(metadata['outputTokens']);
|
|
1467
|
+
const cacheReadTokens = totals?.cacheReadTokens ?? 0;
|
|
1468
|
+
if (inputTokens === 0 && outputTokens === 0 && cacheReadTokens === 0 && !nanoAiu)
|
|
1469
|
+
continue;
|
|
1470
|
+
const requestId = readString(rawReq['requestId']) || `request-${index}`;
|
|
1471
|
+
const dedupKey = `copilot-chatsession:${sessionId}:${requestId}`;
|
|
1472
|
+
if (seenKeys.has(dedupKey))
|
|
1473
|
+
continue;
|
|
1474
|
+
seenKeys.add(dedupKey);
|
|
1475
|
+
const { model, inferred } = modelFromChatSessionRequest(rawReq, metadata, root, nanoAiu !== undefined);
|
|
1476
|
+
const costUSD = nanoAiu !== undefined
|
|
1477
|
+
? creditsToUsd(nanoAiuToCredits(nanoAiu))
|
|
1478
|
+
: calculateCost(model, inputTokens, outputTokens, 0, cacheReadTokens, 0);
|
|
1479
|
+
const timestamp = timestampToISO(rawReq['timestamp']) || sessionCreatedAt;
|
|
1480
|
+
const userMessage = isRecord(rawReq['message']) ? readString(rawReq['message']['text']) : '';
|
|
1481
|
+
const extracted = extractChatSessionTools(metadata);
|
|
1482
|
+
yield {
|
|
1483
|
+
provider: 'copilot',
|
|
1484
|
+
sessionId,
|
|
1485
|
+
project: source.project,
|
|
1486
|
+
model,
|
|
1487
|
+
inputTokens,
|
|
1488
|
+
outputTokens,
|
|
1489
|
+
cacheCreationInputTokens: 0,
|
|
1490
|
+
cacheReadInputTokens: cacheReadTokens,
|
|
1491
|
+
cachedInputTokens: 0,
|
|
1492
|
+
reasoningTokens: 0,
|
|
1493
|
+
webSearchRequests: 0,
|
|
1494
|
+
costUSD,
|
|
1495
|
+
...(inferred ? { costIsEstimated: true } : {}),
|
|
1496
|
+
tools: extracted.tools,
|
|
1497
|
+
bashCommands: extracted.bashCommands,
|
|
1498
|
+
skills: extracted.skills.length > 0 ? extracted.skills : undefined,
|
|
1499
|
+
timestamp,
|
|
1500
|
+
speed: 'standard',
|
|
1501
|
+
deduplicationKey: dedupKey,
|
|
1502
|
+
userMessage,
|
|
1503
|
+
...(nanoAiu !== undefined ? { nanoAiu, costFromBilling: true } : {}),
|
|
1504
|
+
};
|
|
1505
|
+
}
|
|
1506
|
+
},
|
|
1507
|
+
};
|
|
1508
|
+
}
|
|
1509
|
+
// ---------------------------------------------------------------------------
|
|
1510
|
+
// JetBrains parser (Nitrite .db from ~/.config/github-copilot)
|
|
1511
|
+
// ---------------------------------------------------------------------------
|
|
1512
|
+
//
|
|
1513
|
+
// The JetBrains Copilot plugin stores each chat/agent session in a Nitrite
|
|
1514
|
+
// (H2 MVStore) .db of Java-serialized documents. There is NO token accounting
|
|
1515
|
+
// anywhere in the store, so we estimate output tokens from the assistant reply
|
|
1516
|
+
// text (the same char-count approach CodeBurn already uses for Cursor and
|
|
1517
|
+
// legacy Copilot JSONL). Cost is therefore marked costIsEstimated.
|
|
1518
|
+
//
|
|
1519
|
+
// The model (e.g. "claude-opus-4.5", "gpt-4.1") is not always tagged on each
|
|
1520
|
+
// turn, so we recover it by scanning the raw buffer for a known model token.
|
|
1521
|
+
// Known JetBrains Copilot model tokens, longest-first so we match the most
|
|
1522
|
+
// specific name (e.g. "gpt-4.1-mini" before "gpt-4.1").
|
|
1523
|
+
const JETBRAINS_MODEL_TOKENS = [
|
|
1524
|
+
'claude-opus-4.8',
|
|
1525
|
+
'claude-opus-4.7',
|
|
1526
|
+
'claude-opus-4.6',
|
|
1527
|
+
'claude-opus-4.5',
|
|
1528
|
+
'claude-opus-4.1',
|
|
1529
|
+
'claude-opus-4',
|
|
1530
|
+
'claude-sonnet-4.6',
|
|
1531
|
+
'claude-sonnet-4.5',
|
|
1532
|
+
'claude-sonnet-4',
|
|
1533
|
+
'claude-haiku-4.5',
|
|
1534
|
+
'gpt-5.6-luna',
|
|
1535
|
+
'gpt-5.6-terra',
|
|
1536
|
+
'gpt-5.6',
|
|
1537
|
+
'gpt-5.5',
|
|
1538
|
+
'gpt-5.4-mini',
|
|
1539
|
+
'gpt-5.4',
|
|
1540
|
+
'gpt-5.3-codex',
|
|
1541
|
+
'gpt-5.3',
|
|
1542
|
+
'gpt-5.2',
|
|
1543
|
+
'gpt-5.1',
|
|
1544
|
+
'gpt-5-mini',
|
|
1545
|
+
'gpt-5',
|
|
1546
|
+
'gpt-4.1-mini',
|
|
1547
|
+
'gpt-4.1-nano',
|
|
1548
|
+
'gpt-4.1',
|
|
1549
|
+
'gpt-4o-mini',
|
|
1550
|
+
'gpt-4o',
|
|
1551
|
+
'gemini-2.5-pro',
|
|
1552
|
+
'gemini-2.0-flash',
|
|
1553
|
+
'o3-mini',
|
|
1554
|
+
'o4-mini',
|
|
1555
|
+
'o3',
|
|
1556
|
+
];
|
|
1557
|
+
/**
|
|
1558
|
+
* Normalise a raw JetBrains model token to CodeBurn's canonical model id.
|
|
1559
|
+
* Claude names use dots on disk (claude-opus-4.5) but dashes in the pricing
|
|
1560
|
+
* tables (claude-opus-4-5); GPT/Gemini names are kept verbatim.
|
|
1561
|
+
*/
|
|
1562
|
+
function normalizeJetBrainsModelName(raw) {
|
|
1563
|
+
const t = raw.trim();
|
|
1564
|
+
if (!t)
|
|
1565
|
+
return '';
|
|
1566
|
+
if (t.startsWith('claude-'))
|
|
1567
|
+
return t.replace(/\./g, '-');
|
|
1568
|
+
return t;
|
|
1569
|
+
}
|
|
1570
|
+
/** Match a known model token at an alnum boundary anywhere in a string. */
|
|
1571
|
+
export function findJetBrainsModelToken(s) {
|
|
1572
|
+
for (const token of JETBRAINS_MODEL_TOKENS) {
|
|
1573
|
+
const escaped = token.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
1574
|
+
// "o3" etc. must not match inside words like "iso3166". A dot followed by
|
|
1575
|
+
// a digit is a version continuation and is rejected too: `gpt-5` must not
|
|
1576
|
+
// capture `gpt-5.6-luna`, nor `claude-opus-4` capture `claude-opus-4.8` —
|
|
1577
|
+
// that is a different version (#1530). A bare trailing dot (end of
|
|
1578
|
+
// sentence, file extension) is not a version and stays a boundary.
|
|
1579
|
+
if (new RegExp(`(?<![A-Za-z0-9])${escaped}(?![A-Za-z0-9]|\\.\\d)`).test(s)) {
|
|
1580
|
+
return normalizeJetBrainsModelName(token);
|
|
1581
|
+
}
|
|
1582
|
+
}
|
|
1583
|
+
return '';
|
|
1584
|
+
}
|
|
1585
|
+
/** Recover a model from a raw buffer by scanning for a known token. */
|
|
1586
|
+
function inferJetBrainsModel(raw) {
|
|
1587
|
+
return findJetBrainsModelToken(raw);
|
|
1588
|
+
}
|
|
1589
|
+
/**
|
|
1590
|
+
* Infer the project (repository name) from the file:// URIs a chat referenced.
|
|
1591
|
+
*
|
|
1592
|
+
* The JetBrains store has no workspace/cwd record, and there is no reliable
|
|
1593
|
+
* marker inside a path for where the repo root sits (users nest repos under
|
|
1594
|
+
* arbitrary container dirs). So for each referenced file we walk UP the real
|
|
1595
|
+
* filesystem to the nearest ancestor containing a `.git` entry and use that
|
|
1596
|
+
* directory's basename — the true repo root. This is the one approach that
|
|
1597
|
+
* yields a clean, consistent name (e.g. `my-service`) instead of a deep subdir
|
|
1598
|
+
* or an inconsistent prose-scraped guess.
|
|
1599
|
+
*
|
|
1600
|
+
* Returns undefined when the chat referenced no files or none resolve to a repo
|
|
1601
|
+
* that still exists on disk (caller then falls back to a generic bucket).
|
|
1602
|
+
*/
|
|
1603
|
+
function inferJetBrainsProject(raw) {
|
|
1604
|
+
// Capture referenced absolute paths (original case — we hit the real FS).
|
|
1605
|
+
const re = /file:\/\/(\/[^"\\]+?)(?:\\|")/g;
|
|
1606
|
+
const seen = new Set();
|
|
1607
|
+
let m;
|
|
1608
|
+
while ((m = re.exec(raw))) {
|
|
1609
|
+
// Decode %20 etc. and strip a trailing .rej/.orig suffix noise; keep the dir.
|
|
1610
|
+
let p = m[1];
|
|
1611
|
+
try {
|
|
1612
|
+
p = decodeURIComponent(p);
|
|
1613
|
+
}
|
|
1614
|
+
catch { /* leave as-is */ }
|
|
1615
|
+
const dir = p.slice(0, p.lastIndexOf('/'));
|
|
1616
|
+
// A Windows URL is file:///C:/repo/One.ts, so the captured path carries a
|
|
1617
|
+
// leading slash that is part of the URL, not of the drive path.
|
|
1618
|
+
if (dir.startsWith('/'))
|
|
1619
|
+
seen.add(dir.replace(/^\/(?=[a-zA-Z]:\/)/, ''));
|
|
1620
|
+
}
|
|
1621
|
+
if (seen.size === 0)
|
|
1622
|
+
return undefined;
|
|
1623
|
+
for (const dir of seen) {
|
|
1624
|
+
const repo = findGitRepoRoot(dir);
|
|
1625
|
+
if (repo)
|
|
1626
|
+
return repo;
|
|
1627
|
+
}
|
|
1628
|
+
return undefined;
|
|
1629
|
+
}
|
|
1630
|
+
/** Walk up from `dir` to the nearest ancestor containing `.git`; return its basename. */
|
|
1631
|
+
function findGitRepoRoot(dir) {
|
|
1632
|
+
let cur = dir;
|
|
1633
|
+
// Bound the walk to avoid pathological loops; repos are never this deep.
|
|
1634
|
+
for (let i = 0; i < 40 && cur && cur !== '/'; i++) {
|
|
1635
|
+
if (existsSync(join(cur, '.git'))) {
|
|
1636
|
+
const name = basename(cur);
|
|
1637
|
+
return name || undefined;
|
|
1638
|
+
}
|
|
1639
|
+
const parent = dirname(cur);
|
|
1640
|
+
if (parent === cur)
|
|
1641
|
+
break;
|
|
1642
|
+
cur = parent;
|
|
1643
|
+
}
|
|
1644
|
+
return undefined;
|
|
1645
|
+
}
|
|
1646
|
+
/**
|
|
1647
|
+
* Recover the plugin-recorded project label from a Nitrite .db.
|
|
1648
|
+
*
|
|
1649
|
+
* JetBrains Copilot 1.12+ serialises a `projectName` field on the session doc
|
|
1650
|
+
* (e.g. `my-service`, `codeburn`). It is the plugin's OWN authoritative
|
|
1651
|
+
* label — the JetBrains analogue of the OTel source's
|
|
1652
|
+
* `github.copilot.git.repository` — so it is preferred over the file-path
|
|
1653
|
+
* git-walk heuristic when present.
|
|
1654
|
+
*
|
|
1655
|
+
* The field is a Java-serialized string: the key bytes `projectName` are
|
|
1656
|
+
* followed immediately by TC_STRING framing `0x74 <u16 big-endian length>
|
|
1657
|
+
* <UTF-8 bytes>`. We read exactly `length` bytes (so an embedded newline or
|
|
1658
|
+
* quote can't truncate it) and accept the first occurrence whose value is a
|
|
1659
|
+
* plausible short, printable repo name. Older plugins that don't write the
|
|
1660
|
+
* field simply yield undefined (callers fall back to the git-walk).
|
|
1661
|
+
*
|
|
1662
|
+
* Note: the field lives on the session doc, which the plugin writes into the
|
|
1663
|
+
* `chat-sessions` / `chat-edit-sessions` stores — often NOT the
|
|
1664
|
+
* `chat-agent-sessions` store where the billable turns live. Discovery joins
|
|
1665
|
+
* the two by store id; see resolveJetBrainsProjectNames.
|
|
1666
|
+
*/
|
|
1667
|
+
function extractJetBrainsProjectName(raw) {
|
|
1668
|
+
const re = /projectName\x74([\x00-\xff])([\x00-\xff])/g;
|
|
1669
|
+
let m;
|
|
1670
|
+
while ((m = re.exec(raw))) {
|
|
1671
|
+
const len = (m[1].charCodeAt(0) << 8) | m[2].charCodeAt(0);
|
|
1672
|
+
// Repo names are short; a huge length means we matched a schema/key
|
|
1673
|
+
// occurrence rather than a value-bearing one — skip it.
|
|
1674
|
+
if (len < 1 || len > 128)
|
|
1675
|
+
continue;
|
|
1676
|
+
const start = m.index + m[0].length;
|
|
1677
|
+
// The .db is read as latin1, so re-interpret the length-delimited bytes as
|
|
1678
|
+
// UTF-8 (repo names can contain non-ASCII). Reject only if the decoded value
|
|
1679
|
+
// holds control chars — a sign we matched a non-value occurrence, not a name.
|
|
1680
|
+
const val = Buffer.from(raw.slice(start, start + len), 'latin1').toString('utf8');
|
|
1681
|
+
// eslint-disable-next-line no-control-regex
|
|
1682
|
+
if (val.length > 0 && !/[\x00-\x1f]/.test(val))
|
|
1683
|
+
return val;
|
|
1684
|
+
}
|
|
1685
|
+
return undefined;
|
|
1686
|
+
}
|
|
1687
|
+
/**
|
|
1688
|
+
* Recover the conversation (chat-tab) records from a raw .db buffer. Each is
|
|
1689
|
+
* stored as `$<GUID> … name … value <title> … source copilot`. Returns the
|
|
1690
|
+
* GUID→title map so turns can be grouped back to the tab the user sees.
|
|
1691
|
+
*/
|
|
1692
|
+
function extractJetBrainsConversations(raw) {
|
|
1693
|
+
// A conversation's title EVOLVES as the user chats: it starts as "New Agent
|
|
1694
|
+
// Session", may pass through an auto-generated name, and ends at the final
|
|
1695
|
+
// title shown in the UI. The same `$<GUID> … name … value <title> … source`
|
|
1696
|
+
// record is rewritten each time, so we collect every occurrence per GUID and
|
|
1697
|
+
// keep the LAST meaningful (non-default) one.
|
|
1698
|
+
const DEFAULT_TITLES = new Set(['New Agent Session', 'New Session', 'New Chat']);
|
|
1699
|
+
const byId = new Map();
|
|
1700
|
+
const re = /\$([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})[\s\S]{0,8}name/gi;
|
|
1701
|
+
let m;
|
|
1702
|
+
while ((m = re.exec(raw))) {
|
|
1703
|
+
const id = m[1].toLowerCase();
|
|
1704
|
+
const window = raw.slice(m.index, m.index + 400);
|
|
1705
|
+
// The title is the Java-UTF string between the `value` marker and `source`.
|
|
1706
|
+
const tm = window.match(/value.{1,6}?([\x20-\x7e]{3,80}?)t\x00\x06source/);
|
|
1707
|
+
if (!tm)
|
|
1708
|
+
continue;
|
|
1709
|
+
const title = Buffer.from(tm[1].replace(/^[^A-Za-z0-9]*/, ''), 'latin1').toString('utf8').trim();
|
|
1710
|
+
if (!title)
|
|
1711
|
+
continue;
|
|
1712
|
+
// Keep the latest non-default title; only fall back to a default if no
|
|
1713
|
+
// meaningful title has been seen for this conversation yet.
|
|
1714
|
+
const existing = byId.get(id);
|
|
1715
|
+
if (existing && !DEFAULT_TITLES.has(existing) && DEFAULT_TITLES.has(title))
|
|
1716
|
+
continue;
|
|
1717
|
+
byId.set(id, title);
|
|
1718
|
+
}
|
|
1719
|
+
return [...byId.entries()].map(([id, title]) => ({ id, title }));
|
|
1720
|
+
}
|
|
1721
|
+
/** Brace-match a JSON object starting at `start`, tolerating escaped quotes. */
|
|
1722
|
+
function matchJsonObject(raw, start) {
|
|
1723
|
+
let depth = 0;
|
|
1724
|
+
let inStr = false;
|
|
1725
|
+
let esc = false;
|
|
1726
|
+
let i = start;
|
|
1727
|
+
for (; i < raw.length; i++) {
|
|
1728
|
+
const c = raw[i];
|
|
1729
|
+
if (esc) {
|
|
1730
|
+
esc = false;
|
|
1731
|
+
continue;
|
|
1732
|
+
}
|
|
1733
|
+
if (c === '\\') {
|
|
1734
|
+
esc = true;
|
|
1735
|
+
continue;
|
|
1736
|
+
}
|
|
1737
|
+
if (c === '"') {
|
|
1738
|
+
inStr = !inStr;
|
|
1739
|
+
continue;
|
|
1740
|
+
}
|
|
1741
|
+
if (inStr)
|
|
1742
|
+
continue;
|
|
1743
|
+
if (c === '{')
|
|
1744
|
+
depth++;
|
|
1745
|
+
else if (c === '}') {
|
|
1746
|
+
depth--;
|
|
1747
|
+
if (depth === 0) {
|
|
1748
|
+
i++;
|
|
1749
|
+
break;
|
|
1750
|
+
}
|
|
1751
|
+
}
|
|
1752
|
+
}
|
|
1753
|
+
return { chunk: raw.slice(start, i), end: i };
|
|
1754
|
+
}
|
|
1755
|
+
/**
|
|
1756
|
+
* Recover the assistant reply text from a `__first__`/Subgraph response blob.
|
|
1757
|
+
*
|
|
1758
|
+
* JetBrains Copilot has two turn shapes, both handled here:
|
|
1759
|
+
*
|
|
1760
|
+
* - **Ask mode:** the reply is a `Markdown` record whose `data` is an escaped
|
|
1761
|
+
* JSON document `{"text":"…","annotations":…}`.
|
|
1762
|
+
* - **Agent mode** (e.g. PyCharm agent sessions): the reply is the `reply`
|
|
1763
|
+
* field of an `AgentRound` record `{"roundId":N,"reply":"…","toolCalls":[…]}`.
|
|
1764
|
+
* In agent mode the `Markdown` records hold the USER's prompts, not the
|
|
1765
|
+
* reply, so we must NOT read them — the assistant output is the AgentRound
|
|
1766
|
+
* reply.
|
|
1767
|
+
*
|
|
1768
|
+
* Both are read STRUCTURALLY rather than by fully unescaping the blob (which
|
|
1769
|
+
* would strip the reply's own quotes and make regex extraction ambiguous): we
|
|
1770
|
+
* locate each `data`/`reply` value, read it as a properly-delimited JSON-string
|
|
1771
|
+
* literal (honouring escaping), unescape one level, and `JSON.parse` to reach
|
|
1772
|
+
* the text. We unescape the blob one level at a time and extract at the first
|
|
1773
|
+
* depth that yields text, never accumulating across depths (which would union a
|
|
1774
|
+
* quote-truncated half-unescaped capture with the full one and garble the
|
|
1775
|
+
* reply, inflating the token/cost estimate).
|
|
1776
|
+
*
|
|
1777
|
+
* Steps/error/progress-only blobs (no Markdown text and no AgentRound reply)
|
|
1778
|
+
* yield '' and are billed as $0 upstream.
|
|
1779
|
+
*/
|
|
1780
|
+
function extractResponseText(blob) {
|
|
1781
|
+
let s = blob;
|
|
1782
|
+
for (let depth = 0; depth < 8; depth++) {
|
|
1783
|
+
// Decide the mode by the PRESENCE of an AgentRound record, not by whether it
|
|
1784
|
+
// yielded a reply. In agent mode the Markdown record holds the USER prompt,
|
|
1785
|
+
// so an agent blob whose reply is empty (a failed turn, or a pure tool-call
|
|
1786
|
+
// round) must NOT fall back to Markdown — that would bill the user's prompt
|
|
1787
|
+
// as the assistant's output. Ask-mode blobs have no AgentRound record and
|
|
1788
|
+
// use Markdown. (Verified across every observed store: the two reply shapes
|
|
1789
|
+
// never coexist in one blob, so this mode split is unambiguous.)
|
|
1790
|
+
const isAgentMode = /"type":"AgentRound"/.test(s);
|
|
1791
|
+
if (isAgentMode || /"type":"Markdown"/.test(s)) {
|
|
1792
|
+
const decoded = isAgentMode ? extractAgentRoundReplies(s) : extractMarkdownTexts(s);
|
|
1793
|
+
// The .db is read as latin1 (byte-stable), so multibyte UTF-8 characters
|
|
1794
|
+
// are split into separate code units. Re-interpret as UTF-8 so the char
|
|
1795
|
+
// count (→ token estimate) reflects real content length, not byte count.
|
|
1796
|
+
// decoded may be empty (failed/tool-only agent turn) → '' (billed $0).
|
|
1797
|
+
return Buffer.from(decoded.join('\n').trim(), 'latin1').toString('utf8');
|
|
1798
|
+
}
|
|
1799
|
+
// Not yet at the depth where record markers appear bare — unescape one level
|
|
1800
|
+
// in a single left-to-right pass so `\\` and `\"` resolve together (a
|
|
1801
|
+
// two-pass replace would turn `\\"` into `\"` not `\\` + `"`).
|
|
1802
|
+
const next = s.replace(/\\([\\"])/g, '$1');
|
|
1803
|
+
if (next === s)
|
|
1804
|
+
break;
|
|
1805
|
+
s = next;
|
|
1806
|
+
}
|
|
1807
|
+
return '';
|
|
1808
|
+
}
|
|
1809
|
+
/**
|
|
1810
|
+
* Collect the `text` of every `Markdown` record in `s`, treating each record's
|
|
1811
|
+
* `data` value as a one-level-escaped JSON string parsed structurally (so the
|
|
1812
|
+
* reply's own quotes never truncate it). Returns [] if `s` is not yet at the
|
|
1813
|
+
* right unescape depth (no bare `"type":"Markdown"` with a parseable `data`).
|
|
1814
|
+
* Scoping to Markdown skips `Error` (`message`) and `Steps` records — not
|
|
1815
|
+
* billable output. Revisions repeat a reply, so identical texts are de-duped.
|
|
1816
|
+
*/
|
|
1817
|
+
function extractMarkdownTexts(s) {
|
|
1818
|
+
return extractRecordStrings(s, '"type":"Markdown"', '"data":"', 'text');
|
|
1819
|
+
}
|
|
1820
|
+
/**
|
|
1821
|
+
* Collect the non-empty `reply` of every `AgentRound` record (agent mode). A
|
|
1822
|
+
* single blob can hold several rounds (a multi-turn agent session); each round's
|
|
1823
|
+
* `reply` is the assistant's text for that step (empty on pure tool-call rounds).
|
|
1824
|
+
* Deduped in order.
|
|
1825
|
+
*/
|
|
1826
|
+
function extractAgentRoundReplies(s) {
|
|
1827
|
+
return extractRecordStrings(s, '"type":"AgentRound"', '"data":"', 'reply');
|
|
1828
|
+
}
|
|
1829
|
+
/**
|
|
1830
|
+
* Shared structural reader: for every `<marker>` in `s`, find the following
|
|
1831
|
+
* `<dataKey>` string literal (a one-level-escaped JSON document), parse it, and
|
|
1832
|
+
* collect `doc[field]` when it is a non-empty string. Reading the value as a
|
|
1833
|
+
* delimited literal — not a greedy regex — means the payload's own quotes never
|
|
1834
|
+
* truncate it. Returns [] when `s` is not yet at the depth where the marker
|
|
1835
|
+
* appears bare with a parseable payload. De-dupes in order (the store keeps
|
|
1836
|
+
* byte-copies/revisions of each reply).
|
|
1837
|
+
*/
|
|
1838
|
+
function extractRecordStrings(s, marker, dataKey, field) {
|
|
1839
|
+
const texts = [];
|
|
1840
|
+
const seen = new Set();
|
|
1841
|
+
const re = new RegExp(marker.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g');
|
|
1842
|
+
let m;
|
|
1843
|
+
while ((m = re.exec(s))) {
|
|
1844
|
+
const dk = s.indexOf(dataKey, m.index);
|
|
1845
|
+
if (dk === -1 || dk - m.index > 200)
|
|
1846
|
+
continue;
|
|
1847
|
+
// The value runs from after `<dataKey>` to the first UNescaped quote (an odd
|
|
1848
|
+
// run of preceding backslashes escapes it).
|
|
1849
|
+
const start = dk + dataKey.length;
|
|
1850
|
+
let i = start;
|
|
1851
|
+
for (; i < s.length; i++) {
|
|
1852
|
+
if (s[i] !== '"')
|
|
1853
|
+
continue;
|
|
1854
|
+
let bs = 0;
|
|
1855
|
+
for (let j = i - 1; j >= start && s[j] === '\\'; j--)
|
|
1856
|
+
bs++;
|
|
1857
|
+
if (bs % 2 === 0)
|
|
1858
|
+
break;
|
|
1859
|
+
}
|
|
1860
|
+
const literal = s.slice(start, i);
|
|
1861
|
+
try {
|
|
1862
|
+
// Wrapping in quotes + parsing unescapes exactly one level → the inner
|
|
1863
|
+
// JSON document as a string; parsing THAT reaches { <field>, … }.
|
|
1864
|
+
const doc = JSON.parse(JSON.parse('"' + literal + '"'));
|
|
1865
|
+
const text = typeof doc[field] === 'string' ? doc[field] : '';
|
|
1866
|
+
if (text && !seen.has(text)) {
|
|
1867
|
+
seen.add(text);
|
|
1868
|
+
texts.push(text);
|
|
1869
|
+
}
|
|
1870
|
+
}
|
|
1871
|
+
catch {
|
|
1872
|
+
// Not the right depth (or not a matching record) — skip.
|
|
1873
|
+
}
|
|
1874
|
+
}
|
|
1875
|
+
return texts;
|
|
1876
|
+
}
|
|
1877
|
+
/**
|
|
1878
|
+
* Returns a lookup for the conversation whose GUID most recently appears at or
|
|
1879
|
+
* before an offset in `raw`. One pass collects every occurrence; the scan
|
|
1880
|
+
* steps one char past each match so a GUID-shaped neighbour cannot hide one.
|
|
1881
|
+
*/
|
|
1882
|
+
function jetBrainsConversationAt(raw, convById) {
|
|
1883
|
+
const hits = [];
|
|
1884
|
+
const re = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi;
|
|
1885
|
+
let m;
|
|
1886
|
+
while ((m = re.exec(raw))) {
|
|
1887
|
+
const conv = convById.get(m[0].toLowerCase());
|
|
1888
|
+
if (conv)
|
|
1889
|
+
hits.push({ pos: m.index, conv });
|
|
1890
|
+
re.lastIndex = m.index + 1;
|
|
1891
|
+
}
|
|
1892
|
+
return (pos) => {
|
|
1893
|
+
let lo = 0;
|
|
1894
|
+
let hi = hits.length - 1;
|
|
1895
|
+
let found;
|
|
1896
|
+
while (lo <= hi) {
|
|
1897
|
+
const mid = (lo + hi) >> 1;
|
|
1898
|
+
if (hits[mid].pos <= pos) {
|
|
1899
|
+
found = hits[mid].conv;
|
|
1900
|
+
lo = mid + 1;
|
|
1901
|
+
}
|
|
1902
|
+
else {
|
|
1903
|
+
hi = mid - 1;
|
|
1904
|
+
}
|
|
1905
|
+
}
|
|
1906
|
+
return found;
|
|
1907
|
+
};
|
|
1908
|
+
}
|
|
1909
|
+
/**
|
|
1910
|
+
* Extract assistant turns from a raw (latin1) Nitrite .db buffer. Each turn is
|
|
1911
|
+
* one `{"__first__":{"type":"Subgraph"…}` blob; the per-turn model is recovered
|
|
1912
|
+
* from inside the blob when present, else the whole-store default. Each turn is
|
|
1913
|
+
* grouped back to its owning conversation (chat tab) by the nearest preceding
|
|
1914
|
+
* conversation GUID. Duplicate byte-copies of the same reply (the store keeps
|
|
1915
|
+
* several) are de-duplicated by content, per conversation.
|
|
1916
|
+
*/
|
|
1917
|
+
function extractJetBrainsDbTurns(raw) {
|
|
1918
|
+
const conversations = extractJetBrainsConversations(raw);
|
|
1919
|
+
// Precompute the byte offset of each conversation GUID's full form so a turn
|
|
1920
|
+
// can be attributed to the conversation whose id most recently precedes it.
|
|
1921
|
+
const convById = new Map(conversations.map((c) => [c.id, c]));
|
|
1922
|
+
const conversationAt = jetBrainsConversationAt(raw, convById);
|
|
1923
|
+
const turns = [];
|
|
1924
|
+
const seenReplies = new Set(); // keyed by `${conversationId}::${reply}`
|
|
1925
|
+
const re = /\{"__first__":\{"type":"Subgraph"/g;
|
|
1926
|
+
let m;
|
|
1927
|
+
while ((m = re.exec(raw))) {
|
|
1928
|
+
const { chunk, end } = matchJsonObject(raw, m.index);
|
|
1929
|
+
re.lastIndex = end;
|
|
1930
|
+
// Attribute this turn to the conversation whose GUID last appears before it.
|
|
1931
|
+
const owner = conversationAt(m.index);
|
|
1932
|
+
const conversationId = owner?.id ?? '';
|
|
1933
|
+
const conversationTitle = owner?.title ?? '';
|
|
1934
|
+
const replyText = extractResponseText(chunk);
|
|
1935
|
+
// The files this turn referenced (home-relative common dir) → project label.
|
|
1936
|
+
const conversationProject = inferJetBrainsProject(chunk) ?? '';
|
|
1937
|
+
// A per-turn model token sometimes appears inside the blob.
|
|
1938
|
+
const model = findJetBrainsModelToken(chunk);
|
|
1939
|
+
// A failed turn carries an error status / phrase AND produces no reply text.
|
|
1940
|
+
// Requiring empty text avoids misclassifying a genuine reply that merely
|
|
1941
|
+
// *discusses* an error (e.g. explaining a stack trace) as a failed turn.
|
|
1942
|
+
const hasErrorMarker = /error occurred|"isError":true|\\+"status\\+":\\+"(?:error|failed)\\+"/i.test(chunk);
|
|
1943
|
+
if (hasErrorMarker && !replyText) {
|
|
1944
|
+
turns.push({ replyText: '', model, errored: true, conversationId, conversationTitle, conversationProject });
|
|
1945
|
+
continue;
|
|
1946
|
+
}
|
|
1947
|
+
if (!replyText)
|
|
1948
|
+
continue; // Steps/progress-only blob — no billable output
|
|
1949
|
+
const dedupeKey = `${conversationId}::${replyText}`;
|
|
1950
|
+
if (seenReplies.has(dedupeKey))
|
|
1951
|
+
continue;
|
|
1952
|
+
seenReplies.add(dedupeKey);
|
|
1953
|
+
turns.push({ replyText, model, errored: false, conversationId, conversationTitle, conversationProject });
|
|
1954
|
+
}
|
|
1955
|
+
// ---------------------------------------------------------------------------
|
|
1956
|
+
// Fallback: old JetBrains Copilot plugin format (≤1.5.x, e.g. 1.5.59-243)
|
|
1957
|
+
// ---------------------------------------------------------------------------
|
|
1958
|
+
// In this format ALL session turns are stored inside ONE large outer Nitrite
|
|
1959
|
+
// document — a binary-framed JSON object with UUID-keyed Value entries — rather
|
|
1960
|
+
// than the per-turn {"__first__":{"type":"Subgraph",...}} blobs used by newer
|
|
1961
|
+
// plugins (≥1.12.x). The AgentRound entries sit one escaping level deeper
|
|
1962
|
+
// inside the outer document's string values, so `extractResponseText`'s
|
|
1963
|
+
// depth-unescape loop handles extraction correctly once we feed it the right
|
|
1964
|
+
// chunk. MVStore keeps two identical copies of the collection; `seenReplies`
|
|
1965
|
+
// deduplicates them automatically.
|
|
1966
|
+
//
|
|
1967
|
+
// Detection heuristic: the __first__/Subgraph path produced no turns AND the
|
|
1968
|
+
// raw file contains bare 'AgentRound' text (meaning old-format data is present).
|
|
1969
|
+
if (turns.length === 0 && raw.includes('AgentRound')) {
|
|
1970
|
+
// The outer Nitrite document is preceded by a single binary framing byte
|
|
1971
|
+
// (0x81 in practice, but any non-printable/non-ASCII byte in MVStore).
|
|
1972
|
+
// It starts with a UUID-keyed Value entry: {"<uuid>":{"type":"Value",...}}.
|
|
1973
|
+
// Hex is matched case-insensitively — an uppercase UUID must not cause the
|
|
1974
|
+
// whole session to fall through to $0 (the exact bug this path fixes).
|
|
1975
|
+
const outerDocRe = /[\x00-\x1f\x7f-\xff]\{"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}":\{"type":"Value"/g;
|
|
1976
|
+
let dm;
|
|
1977
|
+
while ((dm = outerDocRe.exec(raw))) {
|
|
1978
|
+
// Skip the leading binary byte; matchJsonObject starts at the '{'.
|
|
1979
|
+
const docStart = dm.index + 1;
|
|
1980
|
+
const { chunk, end } = matchJsonObject(raw, docStart);
|
|
1981
|
+
outerDocRe.lastIndex = end;
|
|
1982
|
+
// Skip documents that contain no AgentRound data (e.g. empty sessions).
|
|
1983
|
+
if (!chunk.includes('AgentRound'))
|
|
1984
|
+
continue;
|
|
1985
|
+
// Attribute to the conversation whose GUID most recently precedes this doc.
|
|
1986
|
+
const owner = conversationAt(docStart);
|
|
1987
|
+
const conversationId = owner?.id ?? '';
|
|
1988
|
+
const conversationTitle = owner?.title ?? '';
|
|
1989
|
+
// extractResponseText handles the depth-1 unescape needed to surface the
|
|
1990
|
+
// AgentRound records, then calls extractAgentRoundReplies for each turn.
|
|
1991
|
+
// Because the outer document holds ALL turns in one blob we get back a
|
|
1992
|
+
// single joined string; split it on the '\n' join to yield per-turn texts.
|
|
1993
|
+
const allReplies = extractResponseText(chunk);
|
|
1994
|
+
if (!allReplies)
|
|
1995
|
+
continue;
|
|
1996
|
+
const conversationProject = inferJetBrainsProject(chunk) ?? '';
|
|
1997
|
+
const storeModel = findJetBrainsModelToken(chunk);
|
|
1998
|
+
// extractResponseText joins multiple replies with '\n'. Since individual
|
|
1999
|
+
// replies can themselves span multiple lines we cannot cleanly split here —
|
|
2000
|
+
// instead we emit one ParsedProviderCall per outer document (one session).
|
|
2001
|
+
const dedupeKey = `${conversationId}::${allReplies}`;
|
|
2002
|
+
if (seenReplies.has(dedupeKey))
|
|
2003
|
+
continue;
|
|
2004
|
+
seenReplies.add(dedupeKey);
|
|
2005
|
+
turns.push({
|
|
2006
|
+
replyText: allReplies,
|
|
2007
|
+
model: storeModel,
|
|
2008
|
+
errored: false,
|
|
2009
|
+
conversationId,
|
|
2010
|
+
conversationTitle,
|
|
2011
|
+
conversationProject,
|
|
2012
|
+
});
|
|
2013
|
+
}
|
|
2014
|
+
}
|
|
2015
|
+
// A project derived from ANY turn of a conversation applies to all its turns
|
|
2016
|
+
// (the files are usually referenced in the first substantive turn only).
|
|
2017
|
+
const projByConv = new Map();
|
|
2018
|
+
for (const t of turns) {
|
|
2019
|
+
if (t.conversationProject && !projByConv.has(t.conversationId)) {
|
|
2020
|
+
projByConv.set(t.conversationId, t.conversationProject);
|
|
2021
|
+
}
|
|
2022
|
+
}
|
|
2023
|
+
for (const t of turns) {
|
|
2024
|
+
if (!t.conversationProject)
|
|
2025
|
+
t.conversationProject = projByConv.get(t.conversationId) ?? '';
|
|
2026
|
+
}
|
|
2027
|
+
return turns;
|
|
2028
|
+
}
|
|
2029
|
+
// ---------------------------------------------------------------------------
|
|
2030
|
+
// JetBrains parser: one ParsedProviderCall per assistant turn in the .db
|
|
2031
|
+
// ---------------------------------------------------------------------------
|
|
2032
|
+
function createJetBrainsParser(source, seenKeys) {
|
|
2033
|
+
return {
|
|
2034
|
+
async *parse() {
|
|
2035
|
+
const sessionId = source.sessionId;
|
|
2036
|
+
// Nitrite .db (the store's authoritative session content). Read as latin1
|
|
2037
|
+
// so byte offsets are stable through the binary MVStore framing.
|
|
2038
|
+
if (source.dbPath) {
|
|
2039
|
+
let dbRaw = null;
|
|
2040
|
+
try {
|
|
2041
|
+
dbRaw = await readSessionFile(source.dbPath, 'latin1');
|
|
2042
|
+
}
|
|
2043
|
+
catch {
|
|
2044
|
+
dbRaw = null;
|
|
2045
|
+
}
|
|
2046
|
+
if (dbRaw) {
|
|
2047
|
+
const storeModel = inferJetBrainsModel(dbRaw);
|
|
2048
|
+
const turns = extractJetBrainsDbTurns(dbRaw);
|
|
2049
|
+
// Dedup keys derive from the reply CONTENT, not the scan position:
|
|
2050
|
+
// copilot is a durable provider (cached turns are never deleted and a
|
|
2051
|
+
// re-parse appends any key it hasn't seen), while MVStore compaction
|
|
2052
|
+
// can rewrite the file with blobs in a different byte order. With
|
|
2053
|
+
// positional keys, a rewrite that puts a new blob ahead of an old one
|
|
2054
|
+
// hands the new turn the old turn's key (skipped as seen) and re-emits
|
|
2055
|
+
// the old turn under a fresh index — double-billing it. The per-hash
|
|
2056
|
+
// counter keeps genuinely repeated replies and errored turns (which
|
|
2057
|
+
// share replyText '') distinct within a conversation.
|
|
2058
|
+
const perContentIndex = new Map();
|
|
2059
|
+
for (const turn of turns) {
|
|
2060
|
+
// One .db holds many chat tabs; group each turn under its own
|
|
2061
|
+
// conversation so the user sees one session per tab, not per file.
|
|
2062
|
+
const convId = turn.conversationId || sessionId;
|
|
2063
|
+
const contentHash = createHash('sha256').update(turn.replyText).digest('hex').slice(0, 12);
|
|
2064
|
+
const nth = (perContentIndex.get(`${convId}:${contentHash}`) ?? 0) + 1;
|
|
2065
|
+
perContentIndex.set(`${convId}:${contentHash}`, nth);
|
|
2066
|
+
const dedupKey = `copilot:jb:${convId}:${contentHash}:${nth}`;
|
|
2067
|
+
if (seenKeys.has(dedupKey))
|
|
2068
|
+
continue;
|
|
2069
|
+
seenKeys.add(dedupKey);
|
|
2070
|
+
// Prefer the per-turn model, else the store default, else a generic
|
|
2071
|
+
// Copilot bucket so a real reply is never mis-priced as free.
|
|
2072
|
+
const model = turn.model || storeModel || 'copilot-anthropic-auto';
|
|
2073
|
+
// Errored turns (failed generation) contribute no billable output.
|
|
2074
|
+
const outputTokens = turn.errored ? 0 : estimateTokens(turn.replyText);
|
|
2075
|
+
const costUSD = outputTokens > 0 ? calculateCost(model, 0, outputTokens, 0, 0, 0) : 0;
|
|
2076
|
+
// Project resolution precedence:
|
|
2077
|
+
// 1. projectName — the plugin's own recorded label (1.12+),
|
|
2078
|
+
// joined across kind dirs by store id. Authoritative.
|
|
2079
|
+
// 2. the git repo root of a file:// path the chat referenced
|
|
2080
|
+
// (older plugins / when projectName is absent).
|
|
2081
|
+
// 3. one honest bucket when neither signal exists.
|
|
2082
|
+
// The conversation TITLE is a chat-thread name, NOT a project, and is
|
|
2083
|
+
// kept out of `project` (it would otherwise pollute By-Project).
|
|
2084
|
+
const project = source.projectName || turn.conversationProject || 'copilot-jetbrains';
|
|
2085
|
+
yield {
|
|
2086
|
+
provider: 'copilot',
|
|
2087
|
+
sessionId: convId,
|
|
2088
|
+
project,
|
|
2089
|
+
model,
|
|
2090
|
+
inputTokens: 0,
|
|
2091
|
+
outputTokens,
|
|
2092
|
+
cacheCreationInputTokens: 0,
|
|
2093
|
+
cacheReadInputTokens: 0,
|
|
2094
|
+
cachedInputTokens: 0,
|
|
2095
|
+
reasoningTokens: 0,
|
|
2096
|
+
webSearchRequests: 0,
|
|
2097
|
+
costUSD,
|
|
2098
|
+
costIsEstimated: true,
|
|
2099
|
+
tools: [],
|
|
2100
|
+
bashCommands: [],
|
|
2101
|
+
timestamp: source.mtime,
|
|
2102
|
+
speed: 'standard',
|
|
2103
|
+
deduplicationKey: dedupKey,
|
|
2104
|
+
// Surface the chat-thread name here (it is the session's label, not
|
|
2105
|
+
// a project) so it remains visible in session-level views.
|
|
2106
|
+
userMessage: turn.conversationTitle,
|
|
2107
|
+
};
|
|
2108
|
+
}
|
|
2109
|
+
}
|
|
2110
|
+
}
|
|
2111
|
+
},
|
|
2112
|
+
};
|
|
2113
|
+
}
|
|
2114
|
+
// ---------------------------------------------------------------------------
|
|
2115
|
+
// OTel SQLite parser — reads agent-traces.db for FULL token data
|
|
2116
|
+
// ---------------------------------------------------------------------------
|
|
2117
|
+
function createOtelParser(source, seenKeys) {
|
|
2118
|
+
return {
|
|
2119
|
+
async *parse() {
|
|
2120
|
+
// Lazy-load the SQLite module (same pattern as Cursor/OpenCode providers)
|
|
2121
|
+
const { openDatabase } = await import('../sqlite.js');
|
|
2122
|
+
// One DB open handles ALL conversations — avoids N opens for N conversations.
|
|
2123
|
+
const db = openDatabase(source.path);
|
|
2124
|
+
try {
|
|
2125
|
+
// ---------------------------------------------------------------
|
|
2126
|
+
// Get all distinct conversations in the DB with their project names.
|
|
2127
|
+
// ---------------------------------------------------------------
|
|
2128
|
+
const conversationRows = db.query(`SELECT DISTINCT
|
|
2129
|
+
sa_conv.value AS conversation_id,
|
|
2130
|
+
sa_repo.value AS project,
|
|
2131
|
+
MIN(s.start_time_ms) AS min_start
|
|
2132
|
+
FROM spans s
|
|
2133
|
+
LEFT JOIN span_attributes sa_conv
|
|
2134
|
+
ON s.span_id = sa_conv.span_id AND sa_conv.key = 'gen_ai.conversation.id'
|
|
2135
|
+
LEFT JOIN span_attributes sa_repo
|
|
2136
|
+
ON s.span_id = sa_repo.span_id AND sa_repo.key = 'github.copilot.git.repository'
|
|
2137
|
+
WHERE sa_conv.value IS NOT NULL
|
|
2138
|
+
GROUP BY sa_conv.value
|
|
2139
|
+
ORDER BY min_start DESC`);
|
|
2140
|
+
for (const convRow of conversationRows) {
|
|
2141
|
+
const conversationId = convRow.conversation_id;
|
|
2142
|
+
if (!conversationId)
|
|
2143
|
+
continue;
|
|
2144
|
+
let project = convRow.project ?? 'copilot-chat';
|
|
2145
|
+
if (project.includes('/')) {
|
|
2146
|
+
project = basename(project.replace(/\.git$/, ''));
|
|
2147
|
+
}
|
|
2148
|
+
// -----------------------------------------------------------
|
|
2149
|
+
// Query all 'chat' spans for this conversation.
|
|
2150
|
+
// -----------------------------------------------------------
|
|
2151
|
+
const spanIdRows = db.query(`SELECT DISTINCT s.span_id, s.trace_id
|
|
2152
|
+
FROM spans s
|
|
2153
|
+
INNER JOIN span_attributes sa
|
|
2154
|
+
ON s.span_id = sa.span_id AND sa.key = 'gen_ai.conversation.id' AND sa.value = ?
|
|
2155
|
+
ORDER BY s.start_time_ms ASC`, [conversationId]);
|
|
2156
|
+
// Collect trace IDs and span IDs belonging to this conversation
|
|
2157
|
+
const traceIds = new Set();
|
|
2158
|
+
for (const row of spanIdRows) {
|
|
2159
|
+
traceIds.add(row.trace_id);
|
|
2160
|
+
}
|
|
2161
|
+
if (traceIds.size === 0) {
|
|
2162
|
+
continue;
|
|
2163
|
+
}
|
|
2164
|
+
// Now query all spans within those traces to find chat and tool spans.
|
|
2165
|
+
// Pull the metadata columns in the same query so we don't re-query the
|
|
2166
|
+
// spans table once per chat span below (avoids an N+1).
|
|
2167
|
+
const traceIdArr = [...traceIds];
|
|
2168
|
+
const tracePlaceholders = traceIdArr.map(() => '?').join(',');
|
|
2169
|
+
if (!convRow.project && source.workspaceBySessionId?.size) {
|
|
2170
|
+
const sessionIds = db.query(`SELECT DISTINCT sa.value FROM spans s
|
|
2171
|
+
JOIN span_attributes sa ON s.span_id = sa.span_id
|
|
2172
|
+
WHERE s.trace_id IN (${tracePlaceholders})
|
|
2173
|
+
AND sa.key IN ('copilot_chat.chat_session_id', 'copilot_chat.parent_chat_session_id')
|
|
2174
|
+
ORDER BY sa.key, sa.value`, traceIdArr).map(r => r.value);
|
|
2175
|
+
for (const id of [conversationId, ...sessionIds]) {
|
|
2176
|
+
const workspace = source.workspaceBySessionId.get(id);
|
|
2177
|
+
if (workspace) {
|
|
2178
|
+
project = workspace;
|
|
2179
|
+
break;
|
|
2180
|
+
}
|
|
2181
|
+
}
|
|
2182
|
+
}
|
|
2183
|
+
const traceSpans = db.query(`SELECT span_id, trace_id, operation_name, start_time_ms, response_model FROM spans WHERE trace_id IN (${tracePlaceholders})`, traceIdArr);
|
|
2184
|
+
// Collect tool names, shell commands and subagent names from the
|
|
2185
|
+
// execute_tool / invoke_agent spans for each trace. These mirror the
|
|
2186
|
+
// metadata the JSONL path captures, so the OTel source stays
|
|
2187
|
+
// equivalent (tools + bashCommands + subagentTypes are all first-class
|
|
2188
|
+
// call metadata per types.ts).
|
|
2189
|
+
//
|
|
2190
|
+
// Subagent attribution: VS Code records a subagent run as an
|
|
2191
|
+
// invoke_agent span carrying copilot_chat.parent_chat_session_id. The
|
|
2192
|
+
// root turn agent (gen_ai.agent.name = 'GitHub Copilot Chat') has NO
|
|
2193
|
+
// parent session and is intentionally excluded, otherwise it would
|
|
2194
|
+
// surface as a bogus 'GitHub Copilot Chat' entry in the agents view.
|
|
2195
|
+
// A subagent's invoke_agent span lives in the same trace as that
|
|
2196
|
+
// subagent's own chat spans, so attributing the agent name per-trace
|
|
2197
|
+
// labels exactly the subagent's calls.
|
|
2198
|
+
const toolsByTrace = new Map();
|
|
2199
|
+
const skillsByTrace = new Map();
|
|
2200
|
+
const bashByTrace = new Map();
|
|
2201
|
+
const subagentsByTrace = new Map();
|
|
2202
|
+
const chatSpanIds = [];
|
|
2203
|
+
const spanMetaById = new Map();
|
|
2204
|
+
for (const span of traceSpans) {
|
|
2205
|
+
const opName = span.operation_name || '';
|
|
2206
|
+
spanMetaById.set(span.span_id, span);
|
|
2207
|
+
if (opName === 'chat') {
|
|
2208
|
+
chatSpanIds.push(span.span_id);
|
|
2209
|
+
continue;
|
|
2210
|
+
}
|
|
2211
|
+
if (opName === 'execute_tool') {
|
|
2212
|
+
// Load tool name from attributes and normalise to display form
|
|
2213
|
+
const attrs = loadSpanAttributesFromTable(db, span.span_id);
|
|
2214
|
+
const rawToolName = attrs['gen_ai.tool.name'];
|
|
2215
|
+
if (rawToolName) {
|
|
2216
|
+
const normalizedTool = normalizeTool(rawToolName);
|
|
2217
|
+
const existing = toolsByTrace.get(span.trace_id) ?? [];
|
|
2218
|
+
existing.push(normalizedTool);
|
|
2219
|
+
toolsByTrace.set(span.trace_id, existing);
|
|
2220
|
+
if (normalizedTool === 'Skill') {
|
|
2221
|
+
const skill = extractStructuredSkill(attrs['gen_ai.tool.call.arguments']);
|
|
2222
|
+
if (skill) {
|
|
2223
|
+
const skills = skillsByTrace.get(span.trace_id) ?? [];
|
|
2224
|
+
skills.push(skill);
|
|
2225
|
+
skillsByTrace.set(span.trace_id, skills);
|
|
2226
|
+
}
|
|
2227
|
+
}
|
|
2228
|
+
// For shell tools, extract command names via the OTEL-specific
|
|
2229
|
+
// normaliser (handles the full multi-line scripts the OTEL store
|
|
2230
|
+
// records; see extractOtelBashCommands).
|
|
2231
|
+
if (BASH_TOOL_NAMES.has(rawToolName)) {
|
|
2232
|
+
const command = parseToolCommand(attrs['gen_ai.tool.call.arguments']);
|
|
2233
|
+
if (command) {
|
|
2234
|
+
const bash = bashByTrace.get(span.trace_id) ?? [];
|
|
2235
|
+
bash.push(...extractOtelBashCommands(command));
|
|
2236
|
+
bashByTrace.set(span.trace_id, bash);
|
|
2237
|
+
}
|
|
2238
|
+
}
|
|
2239
|
+
}
|
|
2240
|
+
continue;
|
|
2241
|
+
}
|
|
2242
|
+
// Genuine subagent invocation: an invoke_agent span with a parent
|
|
2243
|
+
// chat session. The root turn agent ('GitHub Copilot Chat') has no
|
|
2244
|
+
// parent session and is skipped to avoid a bogus agents-view entry.
|
|
2245
|
+
if (opName === 'invoke_agent') {
|
|
2246
|
+
const attrs = loadSpanAttributesFromTable(db, span.span_id);
|
|
2247
|
+
const parentSession = attrs['copilot_chat.parent_chat_session_id'];
|
|
2248
|
+
const agentName = attrs['gen_ai.agent.name'];
|
|
2249
|
+
if (parentSession && agentName) {
|
|
2250
|
+
const subs = subagentsByTrace.get(span.trace_id) ?? [];
|
|
2251
|
+
subs.push(agentName);
|
|
2252
|
+
subagentsByTrace.set(span.trace_id, subs);
|
|
2253
|
+
}
|
|
2254
|
+
}
|
|
2255
|
+
}
|
|
2256
|
+
// Attribute trace-level tool/skill/bash metadata to a single chat
|
|
2257
|
+
// span. execute_tool spans happen ONCE in a trace, not once per chat
|
|
2258
|
+
// span, so re-reading them for every span billed a 5-span trace's one
|
|
2259
|
+
// skill call ~5x turns/cost (and split it across periods when the
|
|
2260
|
+
// trace crossed midnight). Order spans by start time and credit the
|
|
2261
|
+
// first one that actually yields, so the metadata lands on exactly one
|
|
2262
|
+
// call in the trace's opening period. Subagent names stay per-trace:
|
|
2263
|
+
// every chat span in a subagent's trace is genuinely that subagent's
|
|
2264
|
+
// call, so all of them are correctly labelled.
|
|
2265
|
+
chatSpanIds.sort((a, b) => (spanMetaById.get(a)?.start_time_ms ?? 0) - (spanMetaById.get(b)?.start_time_ms ?? 0));
|
|
2266
|
+
const creditedTraces = new Set();
|
|
2267
|
+
// Yield one ParsedProviderCall per chat span
|
|
2268
|
+
for (const spanId of chatSpanIds) {
|
|
2269
|
+
const attrs = loadSpanAttributesFromTable(db, spanId);
|
|
2270
|
+
const spanMetadata = spanMetaById.get(spanId);
|
|
2271
|
+
if (!spanMetadata)
|
|
2272
|
+
continue;
|
|
2273
|
+
const model = attrs['gen_ai.response.model'] ??
|
|
2274
|
+
attrs['gen_ai.request.model'] ??
|
|
2275
|
+
spanMetadata.response_model ??
|
|
2276
|
+
'unknown';
|
|
2277
|
+
const inputTokens = Number(attrs['gen_ai.usage.input_tokens'] ?? 0);
|
|
2278
|
+
const outputTokens = Number(attrs['gen_ai.usage.output_tokens'] ?? 0);
|
|
2279
|
+
const cacheReadTokens = Number(attrs['gen_ai.usage.cache_read.input_tokens'] ?? 0);
|
|
2280
|
+
const cacheCreationTokens = Number(attrs['gen_ai.usage.cache_creation.input_tokens'] ?? 0);
|
|
2281
|
+
if (inputTokens === 0 && outputTokens === 0) {
|
|
2282
|
+
continue;
|
|
2283
|
+
}
|
|
2284
|
+
// Dedup key uses span_id which is globally unique
|
|
2285
|
+
const dedupKey = `copilot-otel:${spanId}`;
|
|
2286
|
+
if (seenKeys.has(dedupKey))
|
|
2287
|
+
continue;
|
|
2288
|
+
seenKeys.add(dedupKey);
|
|
2289
|
+
// Also add a JSONL-style dedupKey pattern so that if the same
|
|
2290
|
+
// interaction appears in both OTel and JSONL, we don't double-count.
|
|
2291
|
+
// We use the turn ID from Copilot attributes if available.
|
|
2292
|
+
const turnId = attrs['github.copilot.chat.turn.id'];
|
|
2293
|
+
if (turnId) {
|
|
2294
|
+
const jsonlDedupKey = `copilot:${conversationId}:${turnId}`;
|
|
2295
|
+
seenKeys.add(jsonlDedupKey);
|
|
2296
|
+
}
|
|
2297
|
+
const ownsTraceMetadata = !creditedTraces.has(spanMetadata.trace_id);
|
|
2298
|
+
if (ownsTraceMetadata)
|
|
2299
|
+
creditedTraces.add(spanMetadata.trace_id);
|
|
2300
|
+
const tools = ownsTraceMetadata ? (toolsByTrace.get(spanMetadata.trace_id) ?? []) : [];
|
|
2301
|
+
const skills = ownsTraceMetadata ? (skillsByTrace.get(spanMetadata.trace_id) ?? []) : [];
|
|
2302
|
+
const bashCommands = ownsTraceMetadata ? (bashByTrace.get(spanMetadata.trace_id) ?? []) : [];
|
|
2303
|
+
const subagentTypes = subagentsByTrace.get(spanMetadata.trace_id);
|
|
2304
|
+
const timestamp = epochToISO(spanMetadata.start_time_ms);
|
|
2305
|
+
// input_tokens is cache-INCLUSIVE. An input below the cached count
|
|
2306
|
+
// can only come from an emitter that excludes it, so it stays as is.
|
|
2307
|
+
const cached = cacheReadTokens + cacheCreationTokens;
|
|
2308
|
+
const uncached = inputTokens >= cached ? inputTokens - cached : inputTokens;
|
|
2309
|
+
// calculateCost with FULL token data — this is the key improvement.
|
|
2310
|
+
const costUSD = calculateCost(model, uncached, outputTokens, cacheCreationTokens, cacheReadTokens, 0 // webSearchRequests — not applicable to OTel spans
|
|
2311
|
+
);
|
|
2312
|
+
yield {
|
|
2313
|
+
provider: 'copilot',
|
|
2314
|
+
sessionId: conversationId,
|
|
2315
|
+
project,
|
|
2316
|
+
model,
|
|
2317
|
+
inputTokens: uncached,
|
|
2318
|
+
outputTokens,
|
|
2319
|
+
cacheCreationInputTokens: cacheCreationTokens,
|
|
2320
|
+
cacheReadInputTokens: cacheReadTokens,
|
|
2321
|
+
cachedInputTokens: 0,
|
|
2322
|
+
reasoningTokens: 0,
|
|
2323
|
+
webSearchRequests: 0,
|
|
2324
|
+
costUSD,
|
|
2325
|
+
tools,
|
|
2326
|
+
bashCommands,
|
|
2327
|
+
skills: skills.length > 0 ? skills : undefined,
|
|
2328
|
+
subagentTypes: subagentTypes && subagentTypes.length > 0 ? subagentTypes : undefined,
|
|
2329
|
+
timestamp,
|
|
2330
|
+
speed: 'standard',
|
|
2331
|
+
deduplicationKey: dedupKey,
|
|
2332
|
+
userMessage: '', // Not available in OTel spans by default
|
|
2333
|
+
};
|
|
2334
|
+
}
|
|
2335
|
+
}
|
|
2336
|
+
}
|
|
2337
|
+
finally {
|
|
2338
|
+
db.close();
|
|
2339
|
+
}
|
|
2340
|
+
},
|
|
2341
|
+
};
|
|
2342
|
+
}
|
|
2343
|
+
// ---------------------------------------------------------------------------
|
|
2344
|
+
// Session-store SQLite parser — per-request usage rows from session-store.db
|
|
2345
|
+
// ---------------------------------------------------------------------------
|
|
2346
|
+
//
|
|
2347
|
+
// The Copilot CLI and the GitHub Copilot desktop app both write
|
|
2348
|
+
// ~/.copilot/session-store.db unconditionally. Its assistant_usage_events
|
|
2349
|
+
// table records one row per API request AS IT HAPPENS, where the
|
|
2350
|
+
// session.shutdown rollup in events.jsonl is written only on clean shutdown
|
|
2351
|
+
// (a crash loses the whole session's input/cache accounting) and lumps a
|
|
2352
|
+
// session leg into one per-model total. The DB rows are therefore
|
|
2353
|
+
// authoritative for input/cache tokens; the serve-time reconciliation in
|
|
2354
|
+
// parseProviderSources replaces the covered (session, model) rollup calls
|
|
2355
|
+
// with the rows plus a residual for anything the rollup carried beyond them.
|
|
2356
|
+
//
|
|
2357
|
+
// Each emitted call carries the row's own output_tokens. Older CLIs ALSO write
|
|
2358
|
+
// per-turn outputTokens on assistant.message, so where a row pairs with a
|
|
2359
|
+
// per-turn call that carries output, the serve-time reconciliation in
|
|
2360
|
+
// parseProviderSources serves the row with output 0 (decided there because
|
|
2361
|
+
// only the full serve set knows both sides). CLI 1.0.8x and ACP hosts write no
|
|
2362
|
+
// per-turn output, and an ACP session often never writes session.shutdown, so
|
|
2363
|
+
// the row is the only record of that output. The `initiator='compaction'` row
|
|
2364
|
+
// never pairs: it has no assistant.message anywhere in events.jsonl.
|
|
2365
|
+
// The per-request billing
|
|
2366
|
+
// metadata (total_nano_aiu, request_multiplier) is captured onto the cached
|
|
2367
|
+
// calls but not priced or displayed — that design is upstream #890; the
|
|
2368
|
+
// throughput/latency columns are deliberately not read yet.
|
|
2369
|
+
// The one REQUIRED usage query, shared verbatim between the discovery probe
|
|
2370
|
+
// and the parser so the two can never diverge on schema: discovery runs it
|
|
2371
|
+
// LIMIT 1 (prepare validates every table and column it touches) before
|
|
2372
|
+
// emitting the source, so a store whose shape the parser cannot read is
|
|
2373
|
+
// classified absent — its sessions keep their shutdown rollups — instead of
|
|
2374
|
+
// surfacing a source that could only ever fail.
|
|
2375
|
+
const SESSION_STORE_USAGE_COLUMNS = `e.id, e.session_id, e.model,
|
|
2376
|
+
e.input_tokens, e.cache_read_tokens, e.cache_write_tokens,
|
|
2377
|
+
e.reasoning_tokens, e.created_at,
|
|
2378
|
+
s.cwd, s.repository, s.created_at AS session_created_at`;
|
|
2379
|
+
const SESSION_STORE_USAGE_FROM = `
|
|
2380
|
+
FROM assistant_usage_events e
|
|
2381
|
+
LEFT JOIN sessions s ON s.id = e.session_id`;
|
|
2382
|
+
const SESSION_STORE_USAGE_SELECT = `SELECT ${SESSION_STORE_USAGE_COLUMNS}${SESSION_STORE_USAGE_FROM}`;
|
|
2383
|
+
// OPTIONAL enrichment: the billing-metadata columns plus `initiator`, tried
|
|
2384
|
+
// first at parse time and never probed at discovery — older CLI stores predate
|
|
2385
|
+
// them, and requiring them would classify a perfectly readable store as
|
|
2386
|
+
// absent. A `no such column` failure falls back to the base select above, so
|
|
2387
|
+
// an old store parses identically, just without the enrichment.
|
|
2388
|
+
//
|
|
2389
|
+
// `initiator` names what caused the request. The one value that changes
|
|
2390
|
+
// accounting is 'compaction': that row is the CLI summarizing its own context,
|
|
2391
|
+
// not a user turn, so it has no assistant.message to pair with and it belongs
|
|
2392
|
+
// to the compaction that resets the shutdown rollup. It is optional in the
|
|
2393
|
+
// strongest sense — on a real 2,509-row store 1,504 rows carried NULL here
|
|
2394
|
+
// (the column exists, the CLI just did not always populate it), so every rule
|
|
2395
|
+
// below prefers the label when present and falls back to the timestamp
|
|
2396
|
+
// geometry when it is not.
|
|
2397
|
+
// Widest first, then narrower, then the discovery-validated base. Each step
|
|
2398
|
+
// drops the newest optional column, so a store that has the billing columns
|
|
2399
|
+
// but not `initiator` keeps its billing metadata instead of falling all the
|
|
2400
|
+
// way back — the columns arrived in different CLI releases and a single
|
|
2401
|
+
// all-or-nothing enrichment would lose the older one.
|
|
2402
|
+
//
|
|
2403
|
+
// `output_tokens` rides on the SAME rung as `initiator`: both arrived after the
|
|
2404
|
+
// billing columns, and a store without them serves rows with output 0, leaving
|
|
2405
|
+
// output to the per-turn calls and the rollup residual as before.
|
|
2406
|
+
const SESSION_STORE_USAGE_SELECTS = [
|
|
2407
|
+
`SELECT ${SESSION_STORE_USAGE_COLUMNS},
|
|
2408
|
+
e.total_nano_aiu, e.request_multiplier, e.initiator, e.output_tokens${SESSION_STORE_USAGE_FROM}`,
|
|
2409
|
+
`SELECT ${SESSION_STORE_USAGE_COLUMNS},
|
|
2410
|
+
e.total_nano_aiu, e.request_multiplier${SESSION_STORE_USAGE_FROM}`,
|
|
2411
|
+
SESSION_STORE_USAGE_SELECT,
|
|
2412
|
+
];
|
|
2413
|
+
// FNV-1a 64-bit over the row's identifying content, base36. Collisions only
|
|
2414
|
+
// matter between two rows sharing the SAME session_id and row id — i.e. a
|
|
2415
|
+
// same-path DB reset that happens to reuse an id — where the content strings
|
|
2416
|
+
// differ; 64 bits keeps even adversarial token tuples from aliasing (32-bit
|
|
2417
|
+
// FNV collisions between plausible tuples are constructible).
|
|
2418
|
+
function fnv1a64(s) {
|
|
2419
|
+
let h = 0xcbf29ce484222325n;
|
|
2420
|
+
const prime = 0x100000001b3n;
|
|
2421
|
+
const mask = 0xffffffffffffffffn;
|
|
2422
|
+
for (let i = 0; i < s.length; i++) {
|
|
2423
|
+
h ^= BigInt(s.charCodeAt(i));
|
|
2424
|
+
h = (h * prime) & mask;
|
|
2425
|
+
}
|
|
2426
|
+
return h.toString(36);
|
|
2427
|
+
}
|
|
2428
|
+
function createSessionStoreParser(source, seenKeys) {
|
|
2429
|
+
return {
|
|
2430
|
+
async *parse() {
|
|
2431
|
+
// Lazy-load the SQLite module (same pattern as the OTel source)
|
|
2432
|
+
const { openDatabase, isSqliteBusyError } = await import('../sqlite.js');
|
|
2433
|
+
// The open sits inside the same classify-and-defer boundary as the
|
|
2434
|
+
// query: discovery validated this store moments ago, so a failure HERE
|
|
2435
|
+
// (EACCES/CANTOPEN/EMFILE race) is transient-shaped — letting it
|
|
2436
|
+
// propagate raw would cache a failed marker at the current fingerprint
|
|
2437
|
+
// and zero the covered sessions until the file next changes.
|
|
2438
|
+
let db;
|
|
2439
|
+
try {
|
|
2440
|
+
db = openDatabase(source.path);
|
|
2441
|
+
}
|
|
2442
|
+
catch (err) {
|
|
2443
|
+
if (isSqliteBusyError(err))
|
|
2444
|
+
throw err;
|
|
2445
|
+
throw Object.assign(new Error('copilot session-store.db unreadable at open; deferring'), { code: 'SQLITE_BUSY' });
|
|
2446
|
+
}
|
|
2447
|
+
try {
|
|
2448
|
+
let rows;
|
|
2449
|
+
try {
|
|
2450
|
+
for (const select of SESSION_STORE_USAGE_SELECTS) {
|
|
2451
|
+
try {
|
|
2452
|
+
rows = db.query(`${select} ORDER BY e.id ASC`);
|
|
2453
|
+
break;
|
|
2454
|
+
}
|
|
2455
|
+
catch (selectErr) {
|
|
2456
|
+
// Only an OPTIONAL column may be missing (older store schema):
|
|
2457
|
+
// step down to the next narrower select. The last entry is the
|
|
2458
|
+
// discovery-validated base, so a `no such column` there is a
|
|
2459
|
+
// real shape change and re-throws with everything else.
|
|
2460
|
+
const msg = selectErr instanceof Error ? selectErr.message : String(selectErr);
|
|
2461
|
+
if (!/no such column/i.test(msg) || select === SESSION_STORE_USAGE_SELECT)
|
|
2462
|
+
throw selectErr;
|
|
2463
|
+
}
|
|
2464
|
+
}
|
|
2465
|
+
if (!rows)
|
|
2466
|
+
throw new Error('copilot session-store.db: no usable select');
|
|
2467
|
+
}
|
|
2468
|
+
catch (err) {
|
|
2469
|
+
// Discovery prepare-validated this exact query moments ago, so any
|
|
2470
|
+
// failure here means the store became unreadable or changed shape
|
|
2471
|
+
// mid-run. Yielding nothing would cache an EMPTY success at this
|
|
2472
|
+
// fingerprint while the covered sessions' rollups stay suppressed
|
|
2473
|
+
// — a silent under-count that persists until the file changes.
|
|
2474
|
+
// Every failure defers instead: parseProviderSources
|
|
2475
|
+
// skips-and-retries on the busy shape without writing the cache.
|
|
2476
|
+
if (isSqliteBusyError(err))
|
|
2477
|
+
throw err;
|
|
2478
|
+
throw Object.assign(new Error('copilot session-store.db unreadable mid-parse; deferring'), { code: 'SQLITE_BUSY' });
|
|
2479
|
+
}
|
|
2480
|
+
// created_at defaults to SQLite's datetime('now') — UTC but
|
|
2481
|
+
// timezone-less ('2026-08-07 17:56:38', or with fractional seconds
|
|
2482
|
+
// under 'subsec'), which Date.parse reads as LOCAL time and would
|
|
2483
|
+
// shift the request onto the wrong day. The CLI writes explicit
|
|
2484
|
+
// ISO-Z strings (audited: every observed row), so this normalizes
|
|
2485
|
+
// only the defensive zoneless shapes to UTC; anything carrying its
|
|
2486
|
+
// own zone/offset passes through untouched.
|
|
2487
|
+
const normalizeTimestamp = (raw) => raw
|
|
2488
|
+
? timestampToISO(/^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(\.\d+)?$/.test(raw)
|
|
2489
|
+
? raw.replace(' ', 'T') + 'Z'
|
|
2490
|
+
: raw)
|
|
2491
|
+
: '';
|
|
2492
|
+
let prevTimestamp = '';
|
|
2493
|
+
for (const row of rows) {
|
|
2494
|
+
if (!row.session_id)
|
|
2495
|
+
continue;
|
|
2496
|
+
// A call with an empty timestamp is invisible to every date-range
|
|
2497
|
+
// filter, so never emit one: fall back from the row's own
|
|
2498
|
+
// created_at to the previous row's timestamp, then to the
|
|
2499
|
+
// session's created_at. The previous row deliberately outranks the
|
|
2500
|
+
// session's own created_at even across sessions — ids are GLOBALLY
|
|
2501
|
+
// insertion-ordered, so the previous row is the nearest earlier
|
|
2502
|
+
// clock reading, while a resumed session's created_at can be days
|
|
2503
|
+
// stale. Both columns carry SQLite defaults, so an empty chain is
|
|
2504
|
+
// unreachable outside a hand-built store; such a row is skipped,
|
|
2505
|
+
// and if that desert covers a whole session its rollup simply
|
|
2506
|
+
// stays unsuppressed at serve time.
|
|
2507
|
+
const timestamp = normalizeTimestamp(row.created_at) ||
|
|
2508
|
+
prevTimestamp ||
|
|
2509
|
+
normalizeTimestamp(row.session_created_at);
|
|
2510
|
+
if (!timestamp)
|
|
2511
|
+
continue;
|
|
2512
|
+
prevTimestamp = timestamp;
|
|
2513
|
+
// TEXT NOT NULL still admits '': a billable row must NEVER be
|
|
2514
|
+
// dropped for an unnameable model — its session's rollup was
|
|
2515
|
+
// suppressed on the promise that every billable row is emitted
|
|
2516
|
+
// (the coverage predicate does not know about models). Price as
|
|
2517
|
+
// 'unknown' instead; the pricing engine reports unknown models at
|
|
2518
|
+
// $0 with a fix-it hint rather than silently losing the tokens.
|
|
2519
|
+
const model = row.model || 'unknown';
|
|
2520
|
+
const cacheReadTokens = numberOrZero(row.cache_read_tokens);
|
|
2521
|
+
const cacheWriteTokens = numberOrZero(row.cache_write_tokens);
|
|
2522
|
+
const reasoningTokens = numberOrZero(row.reasoning_tokens);
|
|
2523
|
+
// input_tokens is cache-INCLUSIVE (input + cache_read + cache_write),
|
|
2524
|
+
// the same convention the shutdown rollup uses — confirmed against
|
|
2525
|
+
// token_details_json, whose tokenType:"input" entries hold exactly
|
|
2526
|
+
// this difference. calculateCost expects the uncached remainder with
|
|
2527
|
+
// cache tokens billed separately, so subtract; clamp guards a future
|
|
2528
|
+
// schema that reports input non-inclusively.
|
|
2529
|
+
const inputTokens = Math.max(0, numberOrZero(row.input_tokens) - cacheReadTokens - cacheWriteTokens);
|
|
2530
|
+
const outputTokens = numberOrZero(row.output_tokens);
|
|
2531
|
+
// Nothing this call would add over the per-turn events, so skip it to
|
|
2532
|
+
// avoid an empty $0 row.
|
|
2533
|
+
if (inputTokens === 0 && cacheReadTokens === 0 && cacheWriteTokens === 0 && reasoningTokens === 0 && outputTokens === 0)
|
|
2534
|
+
continue;
|
|
2535
|
+
// `id` is AUTOINCREMENT: stable across re-parses and never reused
|
|
2536
|
+
// WITHIN one database lifetime — but recreating the DB at the same
|
|
2537
|
+
// path restarts the sequence, and a bare `<sid>:<id>` key would then
|
|
2538
|
+
// make the durable union swallow the new row as "already cached"
|
|
2539
|
+
// while its usage differs. A content discriminator (raw created_at
|
|
2540
|
+
// + token counts + model) makes a genuinely different request under
|
|
2541
|
+
// a reused id a NEW key; a byte-identical re-insert (backup restore,
|
|
2542
|
+
// VACUUM INTO) still collapses to the same key.
|
|
2543
|
+
const dedupKey = `copilot-store:${row.session_id}:${row.id}:${fnv1a64(`${row.created_at ?? ''}|${row.input_tokens ?? ''}|${row.cache_read_tokens ?? ''}|${row.cache_write_tokens ?? ''}|${row.reasoning_tokens ?? ''}|${row.model}`)}`;
|
|
2544
|
+
if (seenKeys.has(dedupKey))
|
|
2545
|
+
continue;
|
|
2546
|
+
seenKeys.add(dedupKey);
|
|
2547
|
+
// One DB spans every project, so the project must ride each call
|
|
2548
|
+
// (the per-source fallback would lump them all together). Prefer
|
|
2549
|
+
// the label discovery derived from the session's own session-state
|
|
2550
|
+
// dir (workspace.yaml cwd — the same one its per-turn output calls
|
|
2551
|
+
// carry, so the session never splits across two projects); the
|
|
2552
|
+
// store's sessions.cwd/repository names only sessions with no
|
|
2553
|
+
// session-state dir on this machine.
|
|
2554
|
+
const project = source.projectsBySessionId?.get(row.session_id) ??
|
|
2555
|
+
(row.cwd
|
|
2556
|
+
? basename(row.cwd)
|
|
2557
|
+
: row.repository
|
|
2558
|
+
? basename(row.repository.replace(/\.git$/, ''))
|
|
2559
|
+
: row.session_id);
|
|
2560
|
+
// Tokens are real per-request counts written by the CLI, so this
|
|
2561
|
+
// cost is measured, not char-estimated. reasoning_tokens rides as
|
|
2562
|
+
// metadata only, never as a cost line: it is a SUBSET of the row's
|
|
2563
|
+
// output_tokens (the row's own token_details_json prices exactly
|
|
2564
|
+
// input/cache_read/cache_write/output, no reasoning entry), and
|
|
2565
|
+
// output — reasoning included — is billed once, on whichever call
|
|
2566
|
+
// owns it (see the header). Pricing reasoning here would double-count.
|
|
2567
|
+
const costUSD = calculateCost(model, inputTokens, outputTokens, cacheWriteTokens, cacheReadTokens, 0);
|
|
2568
|
+
yield {
|
|
2569
|
+
provider: 'copilot',
|
|
2570
|
+
sessionId: row.session_id,
|
|
2571
|
+
project,
|
|
2572
|
+
model,
|
|
2573
|
+
inputTokens,
|
|
2574
|
+
outputTokens,
|
|
2575
|
+
cacheCreationInputTokens: cacheWriteTokens,
|
|
2576
|
+
cacheReadInputTokens: cacheReadTokens,
|
|
2577
|
+
cachedInputTokens: 0,
|
|
2578
|
+
reasoningTokens,
|
|
2579
|
+
webSearchRequests: 0,
|
|
2580
|
+
costUSD,
|
|
2581
|
+
costIsEstimated: false,
|
|
2582
|
+
tools: [],
|
|
2583
|
+
bashCommands: [],
|
|
2584
|
+
timestamp,
|
|
2585
|
+
speed: 'standard',
|
|
2586
|
+
deduplicationKey: dedupKey,
|
|
2587
|
+
userMessage: '',
|
|
2588
|
+
// Billing metadata rides as capture-only fields (deliberately
|
|
2589
|
+
// OUTSIDE the dedup-key content hash: it identifies a charge, not
|
|
2590
|
+
// the request). Omitted when the schema predates the columns.
|
|
2591
|
+
...(typeof row.total_nano_aiu === 'number' ? { nanoAiu: row.total_nano_aiu } : {}),
|
|
2592
|
+
...(typeof row.request_multiplier === 'number' ? { requestMultiplier: row.request_multiplier } : {}),
|
|
2593
|
+
...(row.initiator ? { initiator: row.initiator } : {}),
|
|
2594
|
+
};
|
|
2595
|
+
}
|
|
2596
|
+
}
|
|
2597
|
+
finally {
|
|
2598
|
+
db.close();
|
|
2599
|
+
}
|
|
2600
|
+
},
|
|
2601
|
+
};
|
|
2602
|
+
}
|
|
2603
|
+
function isOtelSource(source) {
|
|
2604
|
+
return source.sourceType === 'otel';
|
|
2605
|
+
}
|
|
2606
|
+
function isChatSessionSource(source) {
|
|
2607
|
+
return source.sourceType === 'chatsession';
|
|
2608
|
+
}
|
|
2609
|
+
function isJetBrainsSource(source) {
|
|
2610
|
+
return source.sourceType === 'jetbrains';
|
|
2611
|
+
}
|
|
2612
|
+
function isTranscriptSource(source) {
|
|
2613
|
+
return source.sourceType === 'transcript';
|
|
2614
|
+
}
|
|
2615
|
+
function isSessionStoreSource(source) {
|
|
2616
|
+
return source.sourceType === 'session-store';
|
|
2617
|
+
}
|
|
2618
|
+
// ---------------------------------------------------------------------------
|
|
2619
|
+
// Session discovery: JSONL (original)
|
|
2620
|
+
// ---------------------------------------------------------------------------
|
|
2621
|
+
async function discoverJsonlSessions(sessionStateDir) {
|
|
2622
|
+
const sources = [];
|
|
2623
|
+
let sessionDirs;
|
|
2624
|
+
try {
|
|
2625
|
+
sessionDirs = await readdir(sessionStateDir);
|
|
2626
|
+
}
|
|
2627
|
+
catch {
|
|
2628
|
+
return sources;
|
|
2629
|
+
}
|
|
2630
|
+
for (const sessionId of sessionDirs) {
|
|
2631
|
+
const eventsPath = join(sessionStateDir, sessionId, 'events.jsonl');
|
|
2632
|
+
const s = await stat(eventsPath).catch(() => null);
|
|
2633
|
+
if (!s?.isFile())
|
|
2634
|
+
continue;
|
|
2635
|
+
let project = sessionId;
|
|
2636
|
+
try {
|
|
2637
|
+
const yaml = await readSessionFile(join(sessionStateDir, sessionId, 'workspace.yaml'));
|
|
2638
|
+
const cwd = parseCwd(yaml ?? '');
|
|
2639
|
+
if (cwd)
|
|
2640
|
+
project = basename(cwd);
|
|
2641
|
+
}
|
|
2642
|
+
catch {
|
|
2643
|
+
// workspace.yaml may not exist
|
|
2644
|
+
}
|
|
2645
|
+
sources.push({
|
|
2646
|
+
path: eventsPath,
|
|
2647
|
+
project,
|
|
2648
|
+
provider: 'copilot',
|
|
2649
|
+
sourceType: 'jsonl',
|
|
2650
|
+
});
|
|
2651
|
+
}
|
|
2652
|
+
return sources;
|
|
2653
|
+
}
|
|
2654
|
+
// ---------------------------------------------------------------------------
|
|
2655
|
+
// Session discovery: OTel SQLite
|
|
2656
|
+
// ---------------------------------------------------------------------------
|
|
2657
|
+
async function discoverOtelSessions(dbPath) {
|
|
2658
|
+
// Verify the DB file exists. Return one source per DB file; the parser
|
|
2659
|
+
// opens the DB once and iterates all conversations in a single DB open,
|
|
2660
|
+
// which is far more efficient than one source (and one DB open) per conversation.
|
|
2661
|
+
try {
|
|
2662
|
+
await stat(dbPath);
|
|
2663
|
+
}
|
|
2664
|
+
catch {
|
|
2665
|
+
return [];
|
|
2666
|
+
}
|
|
2667
|
+
return [{ path: dbPath, project: 'copilot-chat', provider: 'copilot', sourceType: 'otel' }];
|
|
2668
|
+
}
|
|
2669
|
+
// ---------------------------------------------------------------------------
|
|
2670
|
+
// Session discovery: session-store SQLite
|
|
2671
|
+
// ---------------------------------------------------------------------------
|
|
2672
|
+
/**
|
|
2673
|
+
* Probe session-store.db. This decides only whether a store SOURCE exists;
|
|
2674
|
+
* which sessions it covers is decided at serve time from what its parse
|
|
2675
|
+
* actually cached (see reconcileCopilotCalls in parseProviderSources), so
|
|
2676
|
+
* nothing a writer does between this probe and the parse can change
|
|
2677
|
+
* accounting.
|
|
2678
|
+
*
|
|
2679
|
+
* Permanent absence — no file, no sqlite driver, or a schema the parser's
|
|
2680
|
+
* own query cannot prepare against ("no such table": CLI builds before the
|
|
2681
|
+
* store existed; "no such column": a future migration) — returns null: no
|
|
2682
|
+
* source, no suppression, and the shutdown-rollup path carries the sessions
|
|
2683
|
+
* exactly as before.
|
|
2684
|
+
*
|
|
2685
|
+
* EVERY other failure still emits the source. Measured against the real
|
|
2686
|
+
* driver (node:sqlite, WAL store): a write lock never blocks readers and a
|
|
2687
|
+
* hot -wal without its -shm reads fine, so the reachable failures here are
|
|
2688
|
+
* corruption-class — SQLITE_CORRUPT (11), SQLITE_NOTADB (26, e.g. mid
|
|
2689
|
+
* atomic-replace), SQLITE_CANTOPEN (14, deleted after the stat) — plus the
|
|
2690
|
+
* classic busy/locked pair and stat-level EACCES/EIO. None of those prove
|
|
2691
|
+
* the store is gone, so the path must stay discovered: the parse raises the
|
|
2692
|
+
* busy shape parseProviderSources skips-and-retries, previously cached rows
|
|
2693
|
+
* keep serving, and serve-time suppression keeps holding from the cache
|
|
2694
|
+
* instead of flapping the covered sessions' rollups back in.
|
|
2695
|
+
*/
|
|
2696
|
+
async function discoverSessionStoreSource(dbPath) {
|
|
2697
|
+
const source = {
|
|
2698
|
+
path: dbPath,
|
|
2699
|
+
project: 'copilot',
|
|
2700
|
+
provider: 'copilot',
|
|
2701
|
+
sourceType: 'session-store',
|
|
2702
|
+
// The store IS the durable record: while it sits on disk, its cached rows
|
|
2703
|
+
// must never age out (crash-only rows have no rollup to fall back to).
|
|
2704
|
+
// Journal-style sources keep the ordinary durable age-out.
|
|
2705
|
+
retainWhilePresent: true,
|
|
2706
|
+
};
|
|
2707
|
+
try {
|
|
2708
|
+
await stat(dbPath);
|
|
2709
|
+
}
|
|
2710
|
+
catch (err) {
|
|
2711
|
+
const code = err.code;
|
|
2712
|
+
return code === 'ENOENT' || code === 'ENOTDIR' ? null : source;
|
|
2713
|
+
}
|
|
2714
|
+
const { openDatabase, isSqliteAvailable } = await import('../sqlite.js');
|
|
2715
|
+
if (!isSqliteAvailable())
|
|
2716
|
+
return null;
|
|
2717
|
+
try {
|
|
2718
|
+
const db = openDatabase(dbPath);
|
|
2719
|
+
try {
|
|
2720
|
+
db.query(`${SESSION_STORE_USAGE_SELECT} LIMIT 1`);
|
|
2721
|
+
}
|
|
2722
|
+
finally {
|
|
2723
|
+
db.close();
|
|
2724
|
+
}
|
|
2725
|
+
return source;
|
|
2726
|
+
}
|
|
2727
|
+
catch (err) {
|
|
2728
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
2729
|
+
return /no such (table|column)/i.test(message) ? null : source;
|
|
2730
|
+
}
|
|
2731
|
+
}
|
|
2732
|
+
// ---------------------------------------------------------------------------
|
|
2733
|
+
// Session discovery: JetBrains (IntelliJ IDEA, PyCharm, …)
|
|
2734
|
+
// ---------------------------------------------------------------------------
|
|
2735
|
+
// The three JetBrains Copilot session kinds (agent / ask / edit mode). Each
|
|
2736
|
+
// store directory holds a Nitrite .db with that kind's session content.
|
|
2737
|
+
const JETBRAINS_SESSION_KINDS = ['chat-agent-sessions', 'chat-sessions', 'chat-edit-sessions'];
|
|
2738
|
+
// Candidate Nitrite .db filenames per kind, plus a generic fallback.
|
|
2739
|
+
const JETBRAINS_DB_NAMES = {
|
|
2740
|
+
'chat-agent-sessions': 'copilot-agent-sessions-nitrite.db',
|
|
2741
|
+
'chat-sessions': 'copilot-chat-nitrite.db',
|
|
2742
|
+
'chat-edit-sessions': 'copilot-edit-sessions-nitrite.db',
|
|
2743
|
+
};
|
|
2744
|
+
/** Locate the Nitrite .db in a store dir (known name, else any *-nitrite.db). */
|
|
2745
|
+
async function findNitriteDbPath(storeDir, kind) {
|
|
2746
|
+
const known = JETBRAINS_DB_NAMES[kind];
|
|
2747
|
+
if (known) {
|
|
2748
|
+
const p = join(storeDir, known);
|
|
2749
|
+
if ((await stat(p).catch(() => null))?.isFile())
|
|
2750
|
+
return p;
|
|
2751
|
+
}
|
|
2752
|
+
let files;
|
|
2753
|
+
try {
|
|
2754
|
+
files = await readdir(storeDir);
|
|
2755
|
+
}
|
|
2756
|
+
catch {
|
|
2757
|
+
return null;
|
|
2758
|
+
}
|
|
2759
|
+
const db = files.find((f) => f.endsWith('-nitrite.db'));
|
|
2760
|
+
return db ? join(storeDir, db) : null;
|
|
2761
|
+
}
|
|
2762
|
+
/**
|
|
2763
|
+
* Discover JetBrains Copilot sessions under the github-copilot config root.
|
|
2764
|
+
*
|
|
2765
|
+
* Layout: <root>/<ide>/<kind>/<storeId>/copilot-*-nitrite.db
|
|
2766
|
+
* <ide> — per-IDE dir (iu, intellij, PyCharm2025.2, …)
|
|
2767
|
+
* <kind> — one of JETBRAINS_SESSION_KINDS
|
|
2768
|
+
*
|
|
2769
|
+
* Emits one source per store directory that has a Nitrite .db. The store
|
|
2770
|
+
* records no token counts, so the parser estimates output tokens from the
|
|
2771
|
+
* assistant reply text (see createJetBrainsParser).
|
|
2772
|
+
*/
|
|
2773
|
+
async function discoverJetBrainsSessions(root) {
|
|
2774
|
+
const sources = [];
|
|
2775
|
+
let ideDirs;
|
|
2776
|
+
try {
|
|
2777
|
+
ideDirs = await readdir(root);
|
|
2778
|
+
}
|
|
2779
|
+
catch {
|
|
2780
|
+
return sources;
|
|
2781
|
+
}
|
|
2782
|
+
for (const ide of ideDirs) {
|
|
2783
|
+
for (const kind of JETBRAINS_SESSION_KINDS) {
|
|
2784
|
+
const kindDir = join(root, ide, kind);
|
|
2785
|
+
let storeDirs;
|
|
2786
|
+
try {
|
|
2787
|
+
storeDirs = await readdir(kindDir);
|
|
2788
|
+
}
|
|
2789
|
+
catch {
|
|
2790
|
+
continue; // this IDE doesn't have this session kind
|
|
2791
|
+
}
|
|
2792
|
+
for (const storeId of storeDirs) {
|
|
2793
|
+
const storeDir = join(kindDir, storeId);
|
|
2794
|
+
const dbPath = await findNitriteDbPath(storeDir, kind);
|
|
2795
|
+
if (!dbPath)
|
|
2796
|
+
continue;
|
|
2797
|
+
const dbStat = await stat(dbPath).catch(() => null);
|
|
2798
|
+
const mtime = (dbStat?.mtime ?? new Date(0)).toISOString();
|
|
2799
|
+
sources.push({
|
|
2800
|
+
path: dbPath,
|
|
2801
|
+
project: 'copilot-jetbrains',
|
|
2802
|
+
provider: 'copilot',
|
|
2803
|
+
sourceType: 'jetbrains',
|
|
2804
|
+
sessionId: storeId,
|
|
2805
|
+
storeId,
|
|
2806
|
+
dbPath,
|
|
2807
|
+
mtime,
|
|
2808
|
+
});
|
|
2809
|
+
}
|
|
2810
|
+
}
|
|
2811
|
+
}
|
|
2812
|
+
// Join projectName across kinds by store id. The plugin records the label on
|
|
2813
|
+
// the session doc, which usually lands in the chat-sessions/chat-edit-sessions
|
|
2814
|
+
// store — NOT the chat-agent-sessions store where the billable turns live.
|
|
2815
|
+
// Without this join, every current agent session falls to the generic bucket
|
|
2816
|
+
// even though its repo name is sitting one store dir over.
|
|
2817
|
+
await resolveJetBrainsProjectNames(sources);
|
|
2818
|
+
return sources;
|
|
2819
|
+
}
|
|
2820
|
+
/**
|
|
2821
|
+
* Populate each source's `projectName` from whichever store dir (of the same
|
|
2822
|
+
* store id) actually recorded it. Reads each source's .db once; a store whose
|
|
2823
|
+
* own .db lacks the field inherits it from a sibling-kind store with the same
|
|
2824
|
+
* id. Best-effort — read/parse failures leave projectName undefined.
|
|
2825
|
+
*/
|
|
2826
|
+
async function resolveJetBrainsProjectNames(sources) {
|
|
2827
|
+
const byStore = new Map();
|
|
2828
|
+
for (const src of sources) {
|
|
2829
|
+
// Already found this store's name via a sibling-kind source — skip the read.
|
|
2830
|
+
if (!src.dbPath || byStore.has(src.storeId))
|
|
2831
|
+
continue;
|
|
2832
|
+
let raw = null;
|
|
2833
|
+
try {
|
|
2834
|
+
raw = await readSessionFile(src.dbPath, 'latin1');
|
|
2835
|
+
}
|
|
2836
|
+
catch {
|
|
2837
|
+
raw = null;
|
|
2838
|
+
}
|
|
2839
|
+
if (!raw)
|
|
2840
|
+
continue;
|
|
2841
|
+
const name = extractJetBrainsProjectName(raw);
|
|
2842
|
+
if (name)
|
|
2843
|
+
byStore.set(src.storeId, name);
|
|
2844
|
+
}
|
|
2845
|
+
for (const src of sources) {
|
|
2846
|
+
const name = byStore.get(src.storeId);
|
|
2847
|
+
if (name)
|
|
2848
|
+
src.projectName = name;
|
|
2849
|
+
}
|
|
2850
|
+
}
|
|
2851
|
+
// ---------------------------------------------------------------------------
|
|
2852
|
+
// Provider factory
|
|
2853
|
+
// ---------------------------------------------------------------------------
|
|
2854
|
+
/**
|
|
2855
|
+
* Returns the VS Code workspaceStorage directories for all VS Code variants
|
|
2856
|
+
* (Code, Code Insiders, VSCodium) on the given platform. Used to discover
|
|
2857
|
+
* transcript sessions written by the Copilot Chat extension.
|
|
2858
|
+
*
|
|
2859
|
+
* Accepts explicit `home` and `os` arguments for the platform fallback.
|
|
2860
|
+
* APPDATA and XDG_CONFIG_HOME still come from the process environment.
|
|
2861
|
+
*/
|
|
2862
|
+
export function getVSCodeWorkspaceStorageDirs(home, os) {
|
|
2863
|
+
const j = os === 'win32' ? win32.join : posix.join;
|
|
2864
|
+
return ['Code', 'Code - Insiders', 'VSCodium']
|
|
2865
|
+
.map(editor => j(getEditorDataDir(editor, home, os), 'User', 'workspaceStorage'));
|
|
2866
|
+
}
|
|
2867
|
+
export function getVSCodeGlobalStorageDirs(home, os) {
|
|
2868
|
+
const j = os === 'win32' ? win32.join : posix.join;
|
|
2869
|
+
return ['Code', 'Code - Insiders', 'VSCodium']
|
|
2870
|
+
.map(editor => j(getEditorDataDir(editor, home, os), 'User', 'globalStorage'));
|
|
2871
|
+
}
|
|
2872
|
+
// workspace.json holds `folder` (single root) or `workspace` (a multi-root
|
|
2873
|
+
// .code-workspace file); either is a URI, local (file://) or remote
|
|
2874
|
+
// (vscode-remote://wsl%2Bubuntu/...). Untitled multi-root workspaces point at
|
|
2875
|
+
// an internal .../Workspaces/<id>/workspace.json that names nothing.
|
|
2876
|
+
async function readWorkspaceName(wsDir, hashDir) {
|
|
2877
|
+
try {
|
|
2878
|
+
const wsJson = await readSessionFile(join(wsDir, hashDir, 'workspace.json'));
|
|
2879
|
+
if (!wsJson)
|
|
2880
|
+
return null;
|
|
2881
|
+
const data = JSON.parse(wsJson);
|
|
2882
|
+
const uri = typeof data.folder === 'string' ? data.folder : typeof data.workspace === 'string' ? data.workspace : null;
|
|
2883
|
+
if (!uri)
|
|
2884
|
+
return null;
|
|
2885
|
+
const name = decodeURIComponent(basename(uri.replace(/^file:\/\//, '').replace(/\/+$/, '')));
|
|
2886
|
+
if (!name || name === 'workspace.json')
|
|
2887
|
+
return null;
|
|
2888
|
+
return name.replace(/\.code-workspace$/, '') || null;
|
|
2889
|
+
}
|
|
2890
|
+
catch {
|
|
2891
|
+
return null;
|
|
2892
|
+
}
|
|
2893
|
+
}
|
|
2894
|
+
async function resolveWorkspaceProject(wsDir, hashDir) {
|
|
2895
|
+
return (await readWorkspaceName(wsDir, hashDir)) ?? hashDir;
|
|
2896
|
+
}
|
|
2897
|
+
// VS Code chat session id -> workspace name. The session id is the
|
|
2898
|
+
// chatSessions/<id>.jsonl (or legacy .json) file name, and Copilot Chat puts
|
|
2899
|
+
// the same id on its OTel spans as gen_ai.conversation.id and
|
|
2900
|
+
// copilot_chat.chat_session_id. VS Code copies a session file when a
|
|
2901
|
+
// workspace's storage id changes, so an id found in two workspaces goes to the
|
|
2902
|
+
// most recently written copy.
|
|
2903
|
+
async function mapChatSessionWorkspaces(workspaceStorageDirs) {
|
|
2904
|
+
const found = new Map();
|
|
2905
|
+
for (const wsDir of workspaceStorageDirs) {
|
|
2906
|
+
let hashDirs;
|
|
2907
|
+
try {
|
|
2908
|
+
hashDirs = await readdir(wsDir);
|
|
2909
|
+
}
|
|
2910
|
+
catch {
|
|
2911
|
+
continue;
|
|
2912
|
+
}
|
|
2913
|
+
for (const hashDir of hashDirs) {
|
|
2914
|
+
let files;
|
|
2915
|
+
try {
|
|
2916
|
+
files = await readdir(join(wsDir, hashDir, 'chatSessions'));
|
|
2917
|
+
}
|
|
2918
|
+
catch {
|
|
2919
|
+
continue;
|
|
2920
|
+
}
|
|
2921
|
+
const project = await readWorkspaceName(wsDir, hashDir);
|
|
2922
|
+
if (!project)
|
|
2923
|
+
continue;
|
|
2924
|
+
for (const file of files) {
|
|
2925
|
+
const id = file.replace(/\.jsonl?$/, '');
|
|
2926
|
+
if (id === file)
|
|
2927
|
+
continue;
|
|
2928
|
+
const s = await stat(join(wsDir, hashDir, 'chatSessions', file)).catch(() => null);
|
|
2929
|
+
if (!s?.isFile())
|
|
2930
|
+
continue;
|
|
2931
|
+
const prev = found.get(id);
|
|
2932
|
+
if (!prev || s.mtimeMs > prev.mtimeMs)
|
|
2933
|
+
found.set(id, { project, mtimeMs: s.mtimeMs });
|
|
2934
|
+
}
|
|
2935
|
+
}
|
|
2936
|
+
}
|
|
2937
|
+
return new Map([...found].map(([id, v]) => [id, v.project]));
|
|
2938
|
+
}
|
|
2939
|
+
// The VS Code storage a chat session file lives in: the workspaceStorage hash
|
|
2940
|
+
// dir for chatSessions journals and transcripts, the directory itself for
|
|
2941
|
+
// empty-window journals.
|
|
2942
|
+
export function copilotChatStorageKey(path) {
|
|
2943
|
+
const dir = dirname(path);
|
|
2944
|
+
const name = basename(dir);
|
|
2945
|
+
if (name === 'transcripts')
|
|
2946
|
+
return dirname(dirname(dir));
|
|
2947
|
+
return name === 'chatSessions' ? dirname(dir) : dir;
|
|
2948
|
+
}
|
|
2949
|
+
async function hasChatSessionFiles(chatSessionsDir) {
|
|
2950
|
+
let files;
|
|
2951
|
+
try {
|
|
2952
|
+
files = await readdir(chatSessionsDir);
|
|
2953
|
+
}
|
|
2954
|
+
catch {
|
|
2955
|
+
return false;
|
|
2956
|
+
}
|
|
2957
|
+
for (const file of files) {
|
|
2958
|
+
if (!file.endsWith('.jsonl') && !file.endsWith('.json'))
|
|
2959
|
+
continue;
|
|
2960
|
+
const s = await stat(join(chatSessionsDir, file)).catch(() => null);
|
|
2961
|
+
if (s?.isFile())
|
|
2962
|
+
return true;
|
|
2963
|
+
}
|
|
2964
|
+
return false;
|
|
2965
|
+
}
|
|
2966
|
+
// ---------------------------------------------------------------------------
|
|
2967
|
+
// Session discovery: VS Code core chatSessions
|
|
2968
|
+
// ---------------------------------------------------------------------------
|
|
2969
|
+
async function discoverWorkspaceChatSessions(workspaceStorageDirs) {
|
|
2970
|
+
const sources = [];
|
|
2971
|
+
for (const wsDir of workspaceStorageDirs) {
|
|
2972
|
+
let hashDirs;
|
|
2973
|
+
try {
|
|
2974
|
+
hashDirs = await readdir(wsDir);
|
|
2975
|
+
}
|
|
2976
|
+
catch {
|
|
2977
|
+
continue;
|
|
2978
|
+
}
|
|
2979
|
+
for (const hashDir of hashDirs) {
|
|
2980
|
+
const chatSessionsDir = join(wsDir, hashDir, 'chatSessions');
|
|
2981
|
+
let files;
|
|
2982
|
+
try {
|
|
2983
|
+
files = await readdir(chatSessionsDir);
|
|
2984
|
+
}
|
|
2985
|
+
catch {
|
|
2986
|
+
continue;
|
|
2987
|
+
}
|
|
2988
|
+
const project = await resolveWorkspaceProject(wsDir, hashDir);
|
|
2989
|
+
for (const file of files) {
|
|
2990
|
+
if (!file.endsWith('.json') && !file.endsWith('.jsonl'))
|
|
2991
|
+
continue;
|
|
2992
|
+
const path = join(chatSessionsDir, file);
|
|
2993
|
+
const s = await stat(path).catch(() => null);
|
|
2994
|
+
if (!s?.isFile())
|
|
2995
|
+
continue;
|
|
2996
|
+
sources.push({
|
|
2997
|
+
path,
|
|
2998
|
+
project,
|
|
2999
|
+
provider: 'copilot',
|
|
3000
|
+
sourceType: 'chatsession',
|
|
3001
|
+
});
|
|
3002
|
+
}
|
|
3003
|
+
}
|
|
3004
|
+
}
|
|
3005
|
+
return sources;
|
|
3006
|
+
}
|
|
3007
|
+
async function discoverEmptyWindowChatSessions(globalStorageDirs) {
|
|
3008
|
+
const sources = [];
|
|
3009
|
+
for (const globalDir of globalStorageDirs) {
|
|
3010
|
+
const chatSessionsDir = join(globalDir, 'emptyWindowChatSessions');
|
|
3011
|
+
let files;
|
|
3012
|
+
try {
|
|
3013
|
+
files = await readdir(chatSessionsDir);
|
|
3014
|
+
}
|
|
3015
|
+
catch {
|
|
3016
|
+
continue;
|
|
3017
|
+
}
|
|
3018
|
+
for (const file of files) {
|
|
3019
|
+
if (!file.endsWith('.json') && !file.endsWith('.jsonl'))
|
|
3020
|
+
continue;
|
|
3021
|
+
const path = join(chatSessionsDir, file);
|
|
3022
|
+
const s = await stat(path).catch(() => null);
|
|
3023
|
+
if (!s?.isFile())
|
|
3024
|
+
continue;
|
|
3025
|
+
sources.push({
|
|
3026
|
+
path,
|
|
3027
|
+
project: 'copilot-chat',
|
|
3028
|
+
provider: 'copilot',
|
|
3029
|
+
sourceType: 'chatsession',
|
|
3030
|
+
});
|
|
3031
|
+
}
|
|
3032
|
+
}
|
|
3033
|
+
return sources;
|
|
3034
|
+
}
|
|
3035
|
+
// ---------------------------------------------------------------------------
|
|
3036
|
+
// Session discovery: VS Code workspace transcripts
|
|
3037
|
+
// ---------------------------------------------------------------------------
|
|
3038
|
+
/**
|
|
3039
|
+
* Discover Copilot Chat transcript sessions stored in VS Code workspaceStorage.
|
|
3040
|
+
* Structure: {wsDir}/{hash}/GitHub.copilot-chat/transcripts/{session}.jsonl
|
|
3041
|
+
* Project is read from {wsDir}/{hash}/workspace.json (folder URI).
|
|
3042
|
+
*/
|
|
3043
|
+
async function discoverTranscriptSessions(workspaceStorageDirs) {
|
|
3044
|
+
const sources = [];
|
|
3045
|
+
for (const wsDir of workspaceStorageDirs) {
|
|
3046
|
+
let hashDirs;
|
|
3047
|
+
try {
|
|
3048
|
+
hashDirs = await readdir(wsDir);
|
|
3049
|
+
}
|
|
3050
|
+
catch {
|
|
3051
|
+
continue;
|
|
3052
|
+
}
|
|
3053
|
+
for (const hashDir of hashDirs) {
|
|
3054
|
+
const chatSessionsDir = join(wsDir, hashDir, 'chatSessions');
|
|
3055
|
+
if (await hasChatSessionFiles(chatSessionsDir))
|
|
3056
|
+
continue;
|
|
3057
|
+
const transcriptsDir = join(wsDir, hashDir, 'GitHub.copilot-chat', 'transcripts');
|
|
3058
|
+
const project = await resolveWorkspaceProject(wsDir, hashDir);
|
|
3059
|
+
let transcriptFiles;
|
|
3060
|
+
try {
|
|
3061
|
+
transcriptFiles = await readdir(transcriptsDir);
|
|
3062
|
+
}
|
|
3063
|
+
catch {
|
|
3064
|
+
continue;
|
|
3065
|
+
}
|
|
3066
|
+
for (const file of transcriptFiles) {
|
|
3067
|
+
if (!file.endsWith('.jsonl'))
|
|
3068
|
+
continue;
|
|
3069
|
+
const s = await stat(join(transcriptsDir, file)).catch(() => null);
|
|
3070
|
+
if (!s?.isFile())
|
|
3071
|
+
continue;
|
|
3072
|
+
sources.push({
|
|
3073
|
+
path: join(transcriptsDir, file),
|
|
3074
|
+
project,
|
|
3075
|
+
provider: 'copilot',
|
|
3076
|
+
sourceType: 'transcript',
|
|
3077
|
+
});
|
|
3078
|
+
}
|
|
3079
|
+
}
|
|
3080
|
+
}
|
|
3081
|
+
return sources;
|
|
3082
|
+
}
|
|
3083
|
+
export function createCopilotProvider(sessionStateDir, workspaceStorageDir, globalStorageDir, jetbrainsDir, sessionStoreDb) {
|
|
3084
|
+
// jsonlDir is resolved lazily inside discoverSessions so that env-var
|
|
3085
|
+
// overrides set after module load (e.g. in tests) are respected.
|
|
3086
|
+
/**
|
|
3087
|
+
* Returns the workspaceStorage directories to scan for transcript sessions.
|
|
3088
|
+
* When workspaceStorageDir is explicitly provided (e.g. in tests), that single
|
|
3089
|
+
* directory is used. The CODEBURN_COPILOT_WS_STORAGE_DIR env var provides a
|
|
3090
|
+
* single-dir override (useful for tests). Otherwise all platform-default VS
|
|
3091
|
+
* Code variant paths are returned.
|
|
3092
|
+
*/
|
|
3093
|
+
function getWsDirs() {
|
|
3094
|
+
if (workspaceStorageDir !== undefined)
|
|
3095
|
+
return [workspaceStorageDir];
|
|
3096
|
+
const envDir = process.env['CODEBURN_COPILOT_WS_STORAGE_DIR'];
|
|
3097
|
+
if (envDir)
|
|
3098
|
+
return [envDir];
|
|
3099
|
+
return getVSCodeWorkspaceStorageDirs(homedir(), platform());
|
|
3100
|
+
}
|
|
3101
|
+
function getGlobalDirs() {
|
|
3102
|
+
if (globalStorageDir !== undefined)
|
|
3103
|
+
return [globalStorageDir];
|
|
3104
|
+
const envDir = process.env['CODEBURN_COPILOT_GLOBAL_STORAGE_DIR'];
|
|
3105
|
+
if (envDir)
|
|
3106
|
+
return [envDir];
|
|
3107
|
+
return getVSCodeGlobalStorageDirs(homedir(), platform());
|
|
3108
|
+
}
|
|
3109
|
+
return {
|
|
3110
|
+
name: 'copilot',
|
|
3111
|
+
displayName: 'Copilot',
|
|
3112
|
+
durableSources: true,
|
|
3113
|
+
// Every directory discovery scans, resolved the same way. Besides the
|
|
3114
|
+
// doctor, a resident process's root watchers are built from these — a
|
|
3115
|
+
// provider without them is silently invisible to the validated-reuse
|
|
3116
|
+
// "clean" verdict, which would let a memoized complete parse outlive a
|
|
3117
|
+
// store append + lock that a fresh parse would have deferred on. The
|
|
3118
|
+
// store DB contributes its PARENT directory, not the file: SQLite appends
|
|
3119
|
+
// land in -wal/-shm siblings a file watch would miss.
|
|
3120
|
+
async probeRoots() {
|
|
3121
|
+
const roots = new Map();
|
|
3122
|
+
const add = (path, label) => {
|
|
3123
|
+
if (path && !roots.has(path))
|
|
3124
|
+
roots.set(path, { path, label });
|
|
3125
|
+
};
|
|
3126
|
+
add(dirname(getSessionStoreDbPath(sessionStoreDb)), 'session store');
|
|
3127
|
+
add(getCopilotSessionStateDir(sessionStateDir), 'CLI session state');
|
|
3128
|
+
for (const dir of getWsDirs())
|
|
3129
|
+
add(dir, 'VS Code workspaceStorage');
|
|
3130
|
+
for (const dir of getGlobalDirs())
|
|
3131
|
+
add(dir, 'VS Code globalStorage');
|
|
3132
|
+
add(getJetBrainsCopilotRoot(jetbrainsDir), 'JetBrains');
|
|
3133
|
+
const otelDb = getAgentTracesDbPath();
|
|
3134
|
+
if (otelDb)
|
|
3135
|
+
add(dirname(otelDb), 'OTel agent traces');
|
|
3136
|
+
return [...roots.values()];
|
|
3137
|
+
},
|
|
3138
|
+
// Segment-boundary match (#1530): `includes` let a bare `gpt-5` key
|
|
3139
|
+
// capture `gpt-5.5` and `gpt-5.6-luna`. Unknown ids fall through to the
|
|
3140
|
+
// raw id, and the report layer's fallbackRawModelDisplayName then resolves
|
|
3141
|
+
// them with the same global getShortModelName every other provider uses.
|
|
3142
|
+
modelDisplayName(model) {
|
|
3143
|
+
for (const [key, display] of modelDisplayEntries) {
|
|
3144
|
+
if (modelKeyMatches(model, key))
|
|
3145
|
+
return display;
|
|
3146
|
+
}
|
|
3147
|
+
return model;
|
|
3148
|
+
},
|
|
3149
|
+
toolDisplayName(rawTool) {
|
|
3150
|
+
return normalizeTool(rawTool);
|
|
3151
|
+
},
|
|
3152
|
+
async discoverSessions() {
|
|
3153
|
+
const sources = [];
|
|
3154
|
+
let discoveredOtel = false;
|
|
3155
|
+
// 1. Discover OTel sessions (preferred — full token data)
|
|
3156
|
+
const disableOtel = process.env['CODEBURN_COPILOT_DISABLE_OTEL'] === '1';
|
|
3157
|
+
if (!disableOtel) {
|
|
3158
|
+
const dbPath = getAgentTracesDbPath();
|
|
3159
|
+
if (dbPath) {
|
|
3160
|
+
try {
|
|
3161
|
+
const otelSources = await discoverOtelSessions(dbPath);
|
|
3162
|
+
discoveredOtel = otelSources.length > 0;
|
|
3163
|
+
if (discoveredOtel) {
|
|
3164
|
+
const workspaceBySessionId = await mapChatSessionWorkspaces(getWsDirs());
|
|
3165
|
+
for (const otelSource of otelSources)
|
|
3166
|
+
otelSource.workspaceBySessionId = workspaceBySessionId;
|
|
3167
|
+
}
|
|
3168
|
+
sources.push(...otelSources);
|
|
3169
|
+
}
|
|
3170
|
+
catch {
|
|
3171
|
+
// OTel discovery failed — fall through to JSONL
|
|
3172
|
+
}
|
|
3173
|
+
}
|
|
3174
|
+
}
|
|
3175
|
+
// 1b. Discover the CLI / GitHub desktop-app session store. Written per
|
|
3176
|
+
// API request (crash-proof) where the events.jsonl shutdown rollup
|
|
3177
|
+
// exists only after a clean exit, so its rows are authoritative for
|
|
3178
|
+
// input/cache tokens; the serve-time reconciliation
|
|
3179
|
+
// (reconcileCopilotCalls in parseProviderSources) replaces the covered
|
|
3180
|
+
// (session, model) rollups with the served rows plus a residual. True
|
|
3181
|
+
// absence (older CLI schema, no sqlite driver) leaves the rollup path
|
|
3182
|
+
// untouched; an unreadable store still surfaces the source so its
|
|
3183
|
+
// parse defers and cached rows keep serving (see
|
|
3184
|
+
// discoverSessionStoreSource).
|
|
3185
|
+
let storeSource = null;
|
|
3186
|
+
try {
|
|
3187
|
+
storeSource = await discoverSessionStoreSource(getSessionStoreDbPath(sessionStoreDb));
|
|
3188
|
+
}
|
|
3189
|
+
catch {
|
|
3190
|
+
// Unreachable in practice (the probe catches its own errors): a
|
|
3191
|
+
// throw here means the sqlite module itself is unusable, and
|
|
3192
|
+
// rollup-only accounting is then the correct mode — the same
|
|
3193
|
+
// fallback as a missing driver.
|
|
3194
|
+
storeSource = null;
|
|
3195
|
+
}
|
|
3196
|
+
if (storeSource)
|
|
3197
|
+
sources.push(storeSource);
|
|
3198
|
+
// 2. Discover JSONL sessions (fallback — output tokens only)
|
|
3199
|
+
try {
|
|
3200
|
+
const jsonlDir = getCopilotSessionStateDir(sessionStateDir);
|
|
3201
|
+
const jsonlSources = await discoverJsonlSessions(jsonlDir);
|
|
3202
|
+
if (storeSource) {
|
|
3203
|
+
// Same sessionId derivation as createJsonlParser: the CLI keys
|
|
3204
|
+
// session-state dirs and session-store rows by the same id, so the
|
|
3205
|
+
// store parser can attribute each session's rows to the same
|
|
3206
|
+
// project its per-turn output calls carry.
|
|
3207
|
+
storeSource.projectsBySessionId = new Map(jsonlSources.map(src => [basename(dirname(src.path)), src.project]));
|
|
3208
|
+
}
|
|
3209
|
+
sources.push(...jsonlSources);
|
|
3210
|
+
}
|
|
3211
|
+
catch {
|
|
3212
|
+
// JSONL discovery failed
|
|
3213
|
+
}
|
|
3214
|
+
// 3. Discover VS Code core chatSessions journals. A journal request
|
|
3215
|
+
// agent-traces.db also recorded is left out at serve time (parser.ts,
|
|
3216
|
+
// otelTwinKeys); everything OTel never recorded counts from the journal.
|
|
3217
|
+
// Sorted by path: the same session copied into two storages carries the
|
|
3218
|
+
// same dedup keys, and the first parsed copy keeps them, so the lowest
|
|
3219
|
+
// storage path wins whatever order the directories list in.
|
|
3220
|
+
const byPath = (a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
|
|
3221
|
+
const chatSessionSources = [];
|
|
3222
|
+
try {
|
|
3223
|
+
chatSessionSources.push(...await discoverWorkspaceChatSessions(getWsDirs()));
|
|
3224
|
+
}
|
|
3225
|
+
catch {
|
|
3226
|
+
// Workspace chatSessions discovery failed
|
|
3227
|
+
}
|
|
3228
|
+
// 4. Discover VS Code empty-window chatSessions journals
|
|
3229
|
+
try {
|
|
3230
|
+
chatSessionSources.push(...await discoverEmptyWindowChatSessions(getGlobalDirs()));
|
|
3231
|
+
}
|
|
3232
|
+
catch {
|
|
3233
|
+
// Empty-window chatSessions discovery failed
|
|
3234
|
+
}
|
|
3235
|
+
sources.push(...chatSessionSources.sort(byPath));
|
|
3236
|
+
// 5. Discover VS Code workspace transcript sessions
|
|
3237
|
+
try {
|
|
3238
|
+
const transcriptSources = await discoverTranscriptSessions(getWsDirs());
|
|
3239
|
+
sources.push(...transcriptSources.sort(byPath));
|
|
3240
|
+
}
|
|
3241
|
+
catch {
|
|
3242
|
+
// Transcript discovery failed
|
|
3243
|
+
}
|
|
3244
|
+
// 6. Discover JetBrains IDE sessions (IntelliJ, PyCharm, …). These live
|
|
3245
|
+
// in a store none of the VS Code / CLI sources touch, so there is no
|
|
3246
|
+
// overlap to dedupe against; the shared seenKeys set still guards it.
|
|
3247
|
+
try {
|
|
3248
|
+
const jetbrainsSources = await discoverJetBrainsSessions(getJetBrainsCopilotRoot(jetbrainsDir));
|
|
3249
|
+
sources.push(...jetbrainsSources);
|
|
3250
|
+
}
|
|
3251
|
+
catch {
|
|
3252
|
+
// JetBrains discovery failed
|
|
3253
|
+
}
|
|
3254
|
+
return sources;
|
|
3255
|
+
},
|
|
3256
|
+
createSessionParser(source, seenKeys) {
|
|
3257
|
+
// Route to the correct parser based on source type.
|
|
3258
|
+
// The dedup key set (seenKeys) is shared across both parsers,
|
|
3259
|
+
// so if OTel already yielded a span, the JSONL parser will skip
|
|
3260
|
+
// the matching assistant.message (and vice versa).
|
|
3261
|
+
if (isOtelSource(source)) {
|
|
3262
|
+
return createOtelParser(source, seenKeys);
|
|
3263
|
+
}
|
|
3264
|
+
if (isSessionStoreSource(source)) {
|
|
3265
|
+
return createSessionStoreParser(source, seenKeys);
|
|
3266
|
+
}
|
|
3267
|
+
if (isChatSessionSource(source)) {
|
|
3268
|
+
return createChatSessionParser(source, seenKeys);
|
|
3269
|
+
}
|
|
3270
|
+
if (isJetBrainsSource(source)) {
|
|
3271
|
+
return createJetBrainsParser(source, seenKeys);
|
|
3272
|
+
}
|
|
3273
|
+
return createJsonlParser(source, seenKeys, isTranscriptSource(source));
|
|
3274
|
+
},
|
|
3275
|
+
};
|
|
3276
|
+
}
|
|
3277
|
+
// Default export for the provider registry
|
|
3278
|
+
export const copilot = createCopilotProvider();
|