From ac73c8dcd8df1613377ba08579b21468c29c90dd Mon Sep 17 00:00:00 2001 From: ksp2000 Date: Fri, 18 Sep 2026 16:15:11 +0530 Subject: [PATCH] fix: extract Copilot skill calls from chatSessions and OTel spans (#1480) Copilot calls parsed from VS Code chatSessions and the OTel agent-traces store never carried the structured skill name, so the skills breakdown stayed empty for every period while the Skill tool itself showed up under tools. Pull the skill name out of the tool call arguments on both paths, and bump the Copilot parse version and the status snapshot render version so warm caches re-derive once instead of serving the old empty breakdown. Costs, token counts and daily totals are unchanged for every provider. --- src/providers/copilot.ts | 53 ++++++++++++++++++---- src/session-cache.ts | 5 ++- src/status-snapshot-semantic.ts | 5 ++- tests/providers/copilot.test.ts | 80 +++++++++++++++++++++++++++++++++ 4 files changed, 133 insertions(+), 10 deletions(-) diff --git a/src/providers/copilot.ts b/src/providers/copilot.ts index 05e23146..6d87665d 100644 --- a/src/providers/copilot.ts +++ b/src/providers/copilot.ts @@ -591,18 +591,39 @@ function modelFromChatSessionRequest(req: ChatSessionRequest, metadata: Record): string[] { +function extractStructuredSkill(raw: unknown): string | null { + const payload = typeof raw === 'string' + ? (() => { + try { + return JSON.parse(raw) as unknown + } catch { + return null + } + })() + : raw + if (!isRecord(payload)) return null + const skill = payload['skill'] + return typeof skill === 'string' && skill.trim() ? skill.trim() : null +} + +function extractChatSessionTools(metadata: Record): { tools: string[]; skills: string[] } { const rounds = metadata['toolCallRounds'] - if (!Array.isArray(rounds)) return [] + if (!Array.isArray(rounds)) return { tools: [], skills: [] } const names = new Set() + const skills = new Set() const addName = (raw: unknown): void => { if (typeof raw === 'string' && raw.trim()) names.add(normalizeTool(raw)) } const addFromRecord = (record: Record): void => { - addName(record['toolName']) - addName(record['name']) - addName(record['tool']) + for (const key of ['toolName', 'name', 'tool']) { + const raw = record[key] + addName(raw) + if (typeof raw !== 'string' || normalizeTool(raw) !== 'Skill') continue + const skill = extractStructuredSkill(record['arguments']) + ?? extractStructuredSkill(record['input']) + if (skill) skills.add(skill) + } } for (const round of rounds) { @@ -622,7 +643,7 @@ function extractChatSessionTools(metadata: Record): string[] { } } - return [...names] + return { tools: [...names], skills: [...skills] } } /** @@ -1121,6 +1142,8 @@ function createChatSessionParser( const costUSD = calculateCost(model, inputTokens, outputTokens, 0, 0, 0) const timestamp = timestampToISO(rawReq['timestamp']) || sessionCreatedAt + const extracted = extractChatSessionTools(metadata) + yield { provider: 'copilot', sessionId, @@ -1134,8 +1157,9 @@ function createChatSessionParser( reasoningTokens: 0, webSearchRequests: 0, costUSD, - tools: extractChatSessionTools(metadata), + tools: extracted.tools, bashCommands: [], + skills: extracted.skills.length > 0 ? extracted.skills : undefined, timestamp, speed: 'standard' as const, deduplicationKey: dedupKey, @@ -1846,6 +1870,7 @@ function createOtelParser( // subagent's own chat spans, so attributing the agent name per-trace // labels exactly the subagent's calls. const toolsByTrace = new Map() + const skillsByTrace = new Map() const bashByTrace = new Map() const subagentsByTrace = new Map() const chatSpanIds: string[] = [] @@ -1865,10 +1890,20 @@ function createOtelParser( const attrs = loadSpanAttributesFromTable(db, span.span_id) const rawToolName = attrs['gen_ai.tool.name'] as string | undefined if (rawToolName) { + const normalizedTool = normalizeTool(rawToolName) const existing = toolsByTrace.get(span.trace_id) ?? [] - existing.push(normalizeTool(rawToolName)) + existing.push(normalizedTool) toolsByTrace.set(span.trace_id, existing) + if (normalizedTool === 'Skill') { + const skill = extractStructuredSkill(attrs['gen_ai.tool.call.arguments']) + if (skill) { + const skills = skillsByTrace.get(span.trace_id) ?? [] + skills.push(skill) + skillsByTrace.set(span.trace_id, skills) + } + } + // For shell tools, extract command names via the OTEL-specific // normaliser (handles the full multi-line scripts the OTEL store // records; see extractOtelBashCommands). @@ -1936,6 +1971,7 @@ function createOtelParser( } const tools = toolsByTrace.get(spanMetadata.trace_id) ?? [] + const skills = skillsByTrace.get(spanMetadata.trace_id) ?? [] const bashCommands = bashByTrace.get(spanMetadata.trace_id) ?? [] const subagentTypes = subagentsByTrace.get(spanMetadata.trace_id) const timestamp = epochToISO(spanMetadata.start_time_ms) @@ -1965,6 +2001,7 @@ function createOtelParser( costUSD, tools, bashCommands, + skills: skills.length > 0 ? skills : undefined, subagentTypes: subagentTypes && subagentTypes.length > 0 ? subagentTypes : undefined, timestamp, speed: 'standard' as const, diff --git a/src/session-cache.ts b/src/session-cache.ts index 658ffae4..c748d4c8 100644 --- a/src/session-cache.ts +++ b/src/session-cache.ts @@ -387,7 +387,10 @@ export const PROVIDER_PARSE_VERSIONS: Record = { // it identifies the request, and moving it would leave the cached output-0 // copy beside the new row - so only this bump re-parses a v2 cache into the // corrected shape. - copilot: 'cli-shutdown-cost-v1-skills-source-provenance-v1-session-store-v3', + // chatsession-otel-skills-v1: structured Skill calls are now extracted from + // VS Code chatSessions and OTel execute_tool spans. Cached calls lack those + // fields, so force one re-parse before serving period breakdowns. + copilot: 'cli-shutdown-cost-v1-skills-source-provenance-v1-session-store-v3-chatsession-otel-skills-v1', // authoritative-usage-v4: persist one Grok session call from top-level // authoritative totals, use modelUsage only for priced attribution, clamp // reasoning per record, and label mixed sessions estimated. diff --git a/src/status-snapshot-semantic.ts b/src/status-snapshot-semantic.ts index 5515c97f..0f4a4c88 100644 --- a/src/status-snapshot-semantic.ts +++ b/src/status-snapshot-semantic.ts @@ -31,7 +31,10 @@ import { DAILY_CACHE_VERSION } from './daily-cache.js' /// treated as a miss (one real recompute per query), then the fresh record /// is served; daily/session caches are separate version domains and are /// not touched. -export const STATUS_SNAPSHOT_RENDER_VERSION = 9 +// v10: current.skills is rebuilt from the newly reparsed Copilot +// chatSessions/OTel calls; older snapshots can contain stale or empty skill +// breakdowns for otherwise identical period queries. +export const STATUS_SNAPSHOT_RENDER_VERSION = 10 /// The semantic key recorded on every status snapshot. A snapshot whose stored /// key differs (an older render revision, or a different daily-cache version) diff --git a/tests/providers/copilot.test.ts b/tests/providers/copilot.test.ts index 62dc4451..6abc5d7c 100644 --- a/tests/providers/copilot.test.ts +++ b/tests/providers/copilot.test.ts @@ -1100,6 +1100,53 @@ describe('copilot provider - chatSessions parsing', () => { expect(calls[0]!.costUSD).toBeGreaterThan(0) }) + it('extracts structured skill calls without inferring from prompt text', async () => { + const filePath = join(tmpDir, 'skill.jsonl') + await createChatSessionFile(filePath, [ + { kind: 0, v: { version: 3, creationDate: 1780157113020, sessionId: 'chat-skill', requests: [] } }, + { kind: 2, k: ['requests'], v: [chatSessionSampleRequest({ + result: { + metadata: { + promptTokens: 100, + outputTokens: 20, + resolvedModel: 'claude-sonnet-4-6', + renderedUserMessage: [{ type: 1, text: 'Follow instructions in #prompt:SKILL.md' }], + toolCallRounds: [{ + toolCalls: [{ name: 'skill', arguments: { skill: 'ponytail' } }], + }], + }, + }, + })] }, + ]) + + const calls = await collectCalls({ path: filePath, project: 'myproject', provider: 'copilot', sourceType: 'chatsession' }) + + expect(calls).toHaveLength(1) + expect(calls[0]!.tools).toEqual(['Skill']) + expect(calls[0]!.skills).toEqual(['ponytail']) + }) + + it('keeps every tool name a round record carries', async () => { + const filePath = join(tmpDir, 'multi-tool.jsonl') + await createChatSessionFile(filePath, [ + { kind: 0, v: { version: 3, creationDate: 1780157113020, sessionId: 'chat-multi', requests: [] } }, + { kind: 2, k: ['requests'], v: [chatSessionSampleRequest({ + result: { + metadata: { + promptTokens: 100, + outputTokens: 20, + resolvedModel: 'claude-sonnet-4-6', + toolCallRounds: [{ toolCalls: [{ name: 'read_file', tool: 'bash' }] }], + }, + }, + })] }, + ]) + + const calls = await collectCalls({ path: filePath, project: 'myproject', provider: 'copilot', sourceType: 'chatsession' }) + + expect(calls[0]!.tools).toEqual(['Read', 'Bash']) + }) + it('returns no calls for an empty reconstructed requests array', async () => { const filePath = join(tmpDir, 'empty.jsonl') await createChatSessionFile(filePath, [ @@ -1653,6 +1700,39 @@ describe('copilot provider - OTel cache token parsing', () => { expect(calls[0]!.cacheReadInputTokens).toBe(10000) }) + it('extracts structured skill calls from execute_tool spans', async () => { + if (!isSqliteAvailable()) return + + createOtelDb(dbPath) + insertSpan(dbPath, { + spanId: 'span-skill-chat', traceId: 'trace-skill', operationName: 'chat', startTimeMs: 1000, + attrs: { + 'gen_ai.conversation.id': 'conv-skill', + 'gen_ai.response.model': 'gpt-4.1', + 'gen_ai.usage.input_tokens': 100, + 'gen_ai.usage.output_tokens': 20, + }, + }) + insertSpan(dbPath, { + spanId: 'span-skill-tool', traceId: 'trace-skill', operationName: 'execute_tool', startTimeMs: 1100, + attrs: { + 'gen_ai.tool.name': 'skill', + 'gen_ai.tool.call.arguments': JSON.stringify({ skill: 'ponytail' }), + }, + }) + + const provider = createCopilotProvider('/nonexistent/jsonl', '/nonexistent/ws') + const sources = await provider.discoverSessions() + const src = sources.find(s => s.path.startsWith(dbPath)) + expect(src).toBeDefined() + + const calls = await collectCalls(src!) + + expect(calls).toHaveLength(1) + expect(calls[0]!.tools).toContain('Skill') + expect(calls[0]!.skills).toEqual(['ponytail']) + }) + it('skips OTel spans with zero input and output tokens', async () => { if (!isSqliteAvailable()) return