-
Notifications
You must be signed in to change notification settings - Fork 519
Expand file tree
/
Copy pathcopilot.go
More file actions
455 lines (408 loc) · 11.5 KB
/
Copy pathcopilot.go
File metadata and controls
455 lines (408 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
package parser
import (
"fmt"
"os"
"path/filepath"
"slices"
"strings"
"time"
"github.com/tidwall/gjson"
)
// Copilot JSONL event types.
const (
copilotEventSessionStart = "session.start"
copilotEventUserMessage = "user.message"
copilotEventAssistantMsg = "assistant.message"
copilotEventToolComplete = "tool.execution_complete"
copilotEventAssistantReason = "assistant.reasoning"
copilotEventModelChange = "session.model_change"
copilotEventSessionShutdown = "session.shutdown"
)
// copilotSessionBuilder accumulates state while scanning a
// Copilot JSONL session file line by line.
type copilotSessionBuilder struct {
messages []ParsedMessage
usageEvents []ParsedUsageEvent
firstMessage string
startedAt time.Time
endedAt time.Time
sessionID string
project string
ordinal int
currentModel string
}
func newCopilotSessionBuilder() *copilotSessionBuilder {
return &copilotSessionBuilder{
project: "unknown",
}
}
// processLine handles a single non-empty, valid JSON line.
func (b *copilotSessionBuilder) processLine(line string) {
ts := parseTimestamp(gjson.Get(line, "timestamp").Str)
if !ts.IsZero() {
if b.startedAt.IsZero() {
b.startedAt = ts
}
b.endedAt = ts
}
data := gjson.Get(line, "data")
switch gjson.Get(line, "type").Str {
case copilotEventSessionStart:
b.handleSessionStart(data)
case copilotEventUserMessage:
b.handleUserMessage(data, ts)
case copilotEventAssistantMsg:
b.handleAssistantMessage(data, ts)
case copilotEventToolComplete:
b.handleToolComplete(data, ts)
case copilotEventAssistantReason:
b.handleAssistantReasoning()
case copilotEventModelChange:
if v := data.Get("newModel"); v.Exists() {
b.currentModel = normalizeCopilotModel(v.Str)
}
case copilotEventSessionShutdown:
b.handleShutdown(data, ts)
}
}
func (b *copilotSessionBuilder) handleSessionStart(
data gjson.Result,
) {
if id := data.Get("sessionId").Str; id != "" {
b.sessionID = id
}
cwd := data.Get("context.cwd").Str
branch := data.Get("context.branch").Str
if cwd != "" {
if p := ExtractProjectFromCwdWithBranch(
cwd, branch,
); p != "" {
b.project = p
}
}
}
func (b *copilotSessionBuilder) handleUserMessage(
data gjson.Result, ts time.Time,
) {
content := strings.TrimSpace(data.Get("content").Str)
if content == "" {
return
}
if isCopilotSyntheticSkillMessage(data, content) {
return
}
if b.firstMessage == "" {
b.firstMessage = truncate(
strings.ReplaceAll(content, "\n", " "), 300,
)
}
b.messages = append(b.messages, ParsedMessage{
Ordinal: b.ordinal,
Role: RoleUser,
Content: content,
Timestamp: ts,
ContentLength: len(content),
})
b.ordinal++
}
func isCopilotSyntheticSkillMessage(
data gjson.Result, content string,
) bool {
source := strings.TrimSpace(data.Get("source").Str)
if strings.HasPrefix(source, "skill-") {
return true
}
return strings.HasPrefix(content, "<skill-context")
}
func (b *copilotSessionBuilder) handleAssistantMessage(
data gjson.Result, ts time.Time,
) {
content := strings.TrimSpace(data.Get("content").Str)
reasoningText := strings.TrimSpace(data.Get("reasoningText").Str)
hasThinking := reasoningText != ""
var toolCalls []ParsedToolCall
data.Get("toolRequests").ForEach(
func(_, req gjson.Result) bool {
name := req.Get("name").Str
if name == "" {
return true
}
args := req.Get("arguments")
inputJSON := args.Str
if args.Type != gjson.String && args.Raw != "" {
inputJSON = args.Raw
}
toolCalls = append(toolCalls, ParsedToolCall{
ToolUseID: req.Get("toolCallId").Str,
ToolName: name,
Category: NormalizeToolCategory(name),
InputJSON: inputJSON,
})
return true
},
)
hasToolUse := len(toolCalls) > 0
// Build display content for tool calls.
displayContent := content
if hasToolUse && content == "" {
displayContent = formatCopilotToolCalls(toolCalls)
}
// Prepend thinking block when reasoning text is present.
if hasThinking {
thinkBlock := "[Thinking]\n" + reasoningText + "\n[/Thinking]"
if displayContent != "" {
displayContent = thinkBlock + "\n\n" + displayContent
} else {
displayContent = thinkBlock
}
}
if displayContent == "" && !hasToolUse {
return
}
outputTokens := int(data.Get("outputTokens").Int())
hasOutputTokens := data.Get("outputTokens").Exists()
b.messages = append(b.messages, ParsedMessage{
Ordinal: b.ordinal,
Role: RoleAssistant,
Content: displayContent,
Timestamp: ts,
HasThinking: hasThinking,
HasToolUse: hasToolUse,
ContentLength: len(displayContent),
ToolCalls: toolCalls,
Model: b.currentModel,
OutputTokens: outputTokens,
HasOutputTokens: hasOutputTokens,
})
b.ordinal++
}
func (b *copilotSessionBuilder) handleToolComplete(
data gjson.Result, ts time.Time,
) {
toolCallID := data.Get("toolCallId").Str
if toolCallID == "" {
return
}
r := data.Get("result")
content := r.Str
if r.Type != gjson.String && r.Raw != "" {
content = r.Raw
}
contentLen := len(content)
// Emit a tool-result-only user message for pairing.
b.messages = append(b.messages, ParsedMessage{
Ordinal: b.ordinal,
Role: RoleUser,
Timestamp: ts,
ContentLength: contentLen,
ToolResults: []ParsedToolResult{{
ToolUseID: toolCallID,
ContentLength: contentLen,
}},
})
b.ordinal++
}
func (b *copilotSessionBuilder) handleAssistantReasoning() {
// Mark the most recent assistant message as having
// thinking, if one exists.
for i, v := range slices.Backward(b.messages) {
if v.Role == RoleAssistant {
b.messages[i].HasThinking = true
return
}
}
}
// handleShutdown extracts per-model token usage from the
// session.shutdown event's modelMetrics field.
func (b *copilotSessionBuilder) handleShutdown(
data gjson.Result, ts time.Time,
) {
occurredAt := timeString(ts, b.startedAt)
data.Get("modelMetrics").ForEach(
func(modelKey, metrics gjson.Result) bool {
usage := metrics.Get("usage")
totalInput := int(usage.Get("inputTokens").Int())
cacheRead := int(usage.Get("cacheReadTokens").Int())
cacheWrite := int(usage.Get("cacheWriteTokens").Int())
output := int(usage.Get("outputTokens").Int())
reasoning := int(usage.Get("reasoningTokens").Int())
// Fresh input = total - cache_read - cache_write.
freshInput := max(totalInput-cacheRead-cacheWrite, 0)
if freshInput == 0 && output == 0 &&
cacheRead == 0 && cacheWrite == 0 &&
reasoning == 0 {
return true
}
b.usageEvents = append(b.usageEvents, ParsedUsageEvent{
Source: "shutdown",
Model: normalizeCopilotModel(modelKey.Str),
InputTokens: freshInput,
OutputTokens: output,
CacheCreationInputTokens: cacheWrite,
CacheReadInputTokens: cacheRead,
ReasoningTokens: reasoning,
OccurredAt: occurredAt,
})
return true
},
)
}
func formatCopilotToolCalls(
calls []ParsedToolCall,
) string {
var parts []string
for _, tc := range calls {
parts = append(parts,
formatToolHeader(tc.Category, tc.ToolName))
}
return strings.Join(parts, "\n")
}
// normalizeCopilotModel converts the model identifier used in
// Copilot session events to the form used in the pricing catalog.
// Claude model IDs use dots in version numbers in Copilot events
// (e.g. "claude-sonnet-4.6") but hyphens in the pricing catalog
// (e.g. "claude-sonnet-4-6"). Other model families such as GPT
// already use dots in the catalog (e.g. "gpt-5.4"), so only
// claude-prefixed names are normalized.
func normalizeCopilotModel(model string) string {
if strings.HasPrefix(model, "claude-") {
return strings.ReplaceAll(model, ".", "-")
}
return model
}
// readCopilotWorkspaceName reads the session name from the
// workspace.yaml sibling file in a directory-format session.
// Returns an empty string for flat .jsonl sessions or when
// no name is present.
func readCopilotWorkspaceName(eventsPath string) string {
if filepath.Base(eventsPath) != "events.jsonl" {
return ""
}
yamlPath := filepath.Join(
filepath.Dir(eventsPath), "workspace.yaml",
)
data, err := os.ReadFile(yamlPath)
if err != nil {
return ""
}
for line := range strings.SplitSeq(string(data), "\n") {
after, ok := strings.CutPrefix(line, "name: ")
if !ok {
continue
}
name := strings.TrimSpace(after)
if name != "" {
return truncate(
strings.ReplaceAll(name, "\n", " "), 300,
)
}
}
return ""
}
// parseSession parses a Copilot JSONL session file into the session, messages,
// and usage events the provider consumes. Returns (nil, nil, nil, nil) if the
// file doesn't exist or contains no user/assistant messages. This is the
// provider-owned parse entrypoint; the package-level free function was folded
// onto the provider.
func (p *copilotProvider) parseSession(
path, machine string,
) (*ParsedSession, []ParsedMessage, []ParsedUsageEvent, error) {
info, err := os.Stat(path)
if err != nil {
if os.IsNotExist(err) {
return nil, nil, nil, nil
}
return nil, nil, nil, fmt.Errorf("stat %s: %w", path, err)
}
f, err := os.Open(path)
if err != nil {
return nil, nil, nil, fmt.Errorf("open %s: %w", path, err)
}
defer f.Close()
lr := newLineReader(f, maxLineSize)
b := newCopilotSessionBuilder()
for {
line, ok := lr.next()
if !ok {
break
}
if !gjson.Valid(line) {
continue
}
b.processLine(line)
}
if err := lr.Err(); err != nil {
return nil, nil, nil,
fmt.Errorf("reading copilot %s: %w", path, err)
}
// Filter: require at least one user or assistant message.
hasContent := false
for _, m := range b.messages {
if m.Content != "" {
hasContent = true
break
}
}
if !hasContent {
return nil, nil, nil, nil
}
sessionID := b.sessionID
if sessionID == "" {
sessionID = sessionIDFromPath(path)
}
sessionID = "copilot:" + sessionID
// Prefer the workspace.yaml name (LLM-generated or user-set
// title) over the raw first user message. Falls back to the
// first user message when no name is present.
firstMessage := b.firstMessage
if wsName := readCopilotWorkspaceName(path); wsName != "" {
firstMessage = wsName
}
userCount := 0
for _, m := range b.messages {
if m.Role == RoleUser && m.Content != "" {
userCount++
}
}
sess := &ParsedSession{
ID: sessionID,
Project: b.project,
Machine: machine,
Agent: AgentCopilot,
FirstMessage: firstMessage,
StartedAt: b.startedAt,
EndedAt: b.endedAt,
MessageCount: len(b.messages),
UserMessageCount: userCount,
File: FileInfo{
Path: path,
Size: info.Size(),
Mtime: info.ModTime().UnixNano(),
},
}
accumulateMessageTokenUsage(sess, b.messages)
// Stamp the session ID on usage events (not known until here).
// DedupKey encodes the event's position in the slice so that
// multi-segment sessions (where the same model appears in
// several shutdown events) each get a distinct key.
for i := range b.usageEvents {
b.usageEvents[i].SessionID = sessionID
b.usageEvents[i].DedupKey = fmt.Sprintf(
"shutdown:%s:%s:%d",
sessionID,
b.usageEvents[i].Model,
i,
)
}
return sess, b.messages, b.usageEvents, nil
}
// sessionIDFromPath extracts a session ID from a Copilot
// file path. Handles both bare (<uuid>.jsonl) and directory
// (<uuid>/events.jsonl) layouts.
func sessionIDFromPath(path string) string {
base := filepath.Base(path)
if base == "events.jsonl" {
return filepath.Base(filepath.Dir(path))
}
return strings.TrimSuffix(base, ".jsonl")
}