fix(copilot): parse JetBrains agent sessions from old plugin format (≤1.5.x)

JetBrains Copilot plugin ≤1.5.x (e.g. 1.5.59-243) stores all session turns
inside ONE large binary-framed outer Nitrite document, rather than the
per-turn {"__first__":{"type":"Subgraph",...}} blobs introduced in later
plugins (≥1.12.x, e.g. 1.12.1-251).

In the old format each assistant turn is a UUID-keyed Value entry whose
value field contains a JSON-string-escaped AgentRound record:

  {"<uuid>":{"type":"Value","value":"{\"type\":\"AgentRound\",
    \"data\":\"{...reply...}\"}"}, ...}

The extractResponseText depth-unescape loop already handles this one extra
level of escaping; the only gap was that extractJetBrainsDbTurns never fed
it the outer document — it only scanned for __first__/Subgraph blobs, which
the old plugin never writes.

Add a fallback that activates when the Subgraph scan produces zero turns but
'AgentRound' text is present in the raw file (old-format signal). It locates
the binary-framed outer document (UUID-keyed Value entry, hex matched
case-insensitively so an uppercase UUID does not fall through to $0), extracts
it with matchJsonObject, and passes it to extractResponseText. Because the outer
document holds every turn in one blob, this emits ONE session-level call per
document (all rounds' replies joined): cost/tokens are correct, only the
per-turn call-count granularity is coarser — an accepted tradeoff for legacy
data. MVStore keeps two identical collection copies; seenReplies dedupes them.

The fallback is guarded by turns.length === 0 so new-format sessions (whose
Subgraph scan succeeds) are completely unaffected and never double-counted.

Tests: old-format doc with multiple AgentRound rounds → 1 call whose token
count equals the two non-empty replies joined (the empty tool-call round is
excluded); an uppercase-UUID variant (fails without the case-insensitive
match); and a guard that new-format Subgraph turns are not double-counted.
docs/providers/copilot.md documents the old format and the one-call-per-session
limitation.
This commit is contained in:
Nihal Jain 2026-07-03 18:04:24 +05:30
parent 2916cd988e
commit cd07707363
3 changed files with 181 additions and 0 deletions

View file

@ -1301,6 +1301,78 @@ function extractJetBrainsDbTurns(raw: string): JBDbTurn[] {
turns.push({ replyText, model, errored: false, conversationId, conversationTitle, conversationProject })
}
// ---------------------------------------------------------------------------
// Fallback: old JetBrains Copilot plugin format (≤1.5.x, e.g. 1.5.59-243)
// ---------------------------------------------------------------------------
// In this format ALL session turns are stored inside ONE large outer Nitrite
// document — a binary-framed JSON object with UUID-keyed Value entries — rather
// than the per-turn {"__first__":{"type":"Subgraph",...}} blobs used by newer
// plugins (≥1.12.x). The AgentRound entries sit one escaping level deeper
// inside the outer document's string values, so `extractResponseText`'s
// depth-unescape loop handles extraction correctly once we feed it the right
// chunk. MVStore keeps two identical copies of the collection; `seenReplies`
// deduplicates them automatically.
//
// Detection heuristic: the __first__/Subgraph path produced no turns AND the
// raw file contains bare 'AgentRound' text (meaning old-format data is present).
if (turns.length === 0 && raw.includes('AgentRound')) {
// The outer Nitrite document is preceded by a single binary framing byte
// (0x81 in practice, but any non-printable/non-ASCII byte in MVStore).
// It starts with a UUID-keyed Value entry: {"<uuid>":{"type":"Value",...}}.
// Hex is matched case-insensitively — an uppercase UUID must not cause the
// whole session to fall through to $0 (the exact bug this path fixes).
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
let dm: RegExpExecArray | null
while ((dm = outerDocRe.exec(raw))) {
// Skip the leading binary byte; matchJsonObject starts at the '{'.
const docStart = dm.index + 1
const { chunk, end } = matchJsonObject(raw, docStart)
outerDocRe.lastIndex = end
// Skip documents that contain no AgentRound data (e.g. empty sessions).
if (!chunk.includes('AgentRound')) continue
// Attribute to the conversation whose GUID most recently precedes this doc.
let conversationId = ''
let conversationTitle = ''
let bestPos = -1
for (const c of convById.values()) {
const p = raw.lastIndexOf(c.id, docStart)
if (p > bestPos) {
bestPos = p
conversationId = c.id
conversationTitle = c.title
}
}
// extractResponseText handles the depth-1 unescape needed to surface the
// AgentRound records, then calls extractAgentRoundReplies for each turn.
// Because the outer document holds ALL turns in one blob we get back a
// single joined string; split it on the '\n' join to yield per-turn texts.
const allReplies = extractResponseText(chunk)
if (!allReplies) continue
const conversationProject = inferJetBrainsProject(chunk) ?? ''
const storeModel = findJetBrainsModelToken(chunk)
// extractResponseText joins multiple replies with '\n'. Since individual
// replies can themselves span multiple lines we cannot cleanly split here —
// instead we emit one ParsedProviderCall per outer document (one session).
const dedupeKey = `${conversationId}::${allReplies}`
if (seenReplies.has(dedupeKey)) continue
seenReplies.add(dedupeKey)
turns.push({
replyText: allReplies,
model: storeModel,
errored: false,
conversationId,
conversationTitle,
conversationProject,
})
}
}
// A project derived from ANY turn of a conversation applies to all its turns
// (the files are usually referenced in the first substantive turn only).
const projByConv = new Map<string, string>()