Repository navigation
Expand file tree
/
Copy pathclaude.go
More file actions
339 lines (321 loc) · 9.18 KB
/
Copy pathclaude.go
File metadata and controls
339 lines (321 loc) · 9.18 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
package sessions
import (
"bytes"
"encoding/json"
"regexp"
"strings"
"time"
"github.com/tidwall/gjson"
)
// Claude Code writes one line per event: the prompts as "user" lines, each
// block of a reply as an "assistant" line carrying the whole message's
// usage (so a message's later blocks repeat it), and titles of its own.
type ccLine struct {
Type string `json:"type"`
IsMeta bool `json:"isMeta"`
IsSidechain bool `json:"isSidechain"`
Cwd string `json:"cwd"`
SessionID string `json:"sessionId"`
RequestID ccStr `json:"requestId"`
AITitle string `json:"aiTitle"`
CustomTitle string `json:"customTitle"`
Summary string `json:"summary"`
Message struct {
ID string `json:"id"`
Model string `json:"model"`
Content json.RawMessage `json:"content"`
Usage *struct {
Input int `json:"input_tokens"`
Output int `json:"output_tokens"`
CacheRead int `json:"cache_read_input_tokens"`
CacheWrite int `json:"cache_creation_input_tokens"`
Creation *ccCacheCreation `json:"cache_creation"`
} `json:"usage"`
} `json:"message"`
}
var (
ccAssistant = []byte(`"type":"assistant"`)
ccUser = []byte(`"type":"user"`)
ccTitle = []byte(`"type":"ai-title"`)
ccCustom = []byte(`"type":"custom-title"`)
ccSummary = []byte(`"type":"summary"`)
ccCwd = []byte(`"cwd":"`)
)
var (
ccMessage = []byte(`"message":{`)
ccAttach = []byte(`"attachment":{`)
ccRole = []byte(`"role":"`)
ccModel = []byte(`"model":"`)
ccID = []byte(`"id":"`)
ccUsage = []byte(`"usage":{`)
ccSession = []byte(`"sessionId":"`)
ccTop = []byte(`{"type":"`)
)
// claudeLine reads a line, telling from its first bytes what it is: most of
// a long session is tool results and attachments, read for their time
// alone, and a reply's usage is decoded without its content.
func claudeLine(s *state, b []byte, main bool) {
h := b[:min(len(b), 1024)]
if bytes.HasPrefix(h, ccTop) {
// a line of Claude Code's own: a title, a summary, a mode…
switch typeAfter(h, ccTop) {
case "user", "assistant":
// a message laid out type first
case "ai-title", "custom-title", "summary":
claudeFull(s, b, main)
return
default:
s.saw(tsAt(b, true), main)
return
}
}
m, a := bytes.Index(h, ccMessage), bytes.Index(h, ccAttach)
if a >= 0 && (m < 0 || a < m) {
s.saw(tsAt(b, true), main)
ccWhere(s, b)
return
}
if m < 0 {
claudeFull(s, b, main)
return
}
// Claude Code's own order: a reply opens with its model and id, a
// prompt with its role; a message written another way is read whole
msg := h[m+len(ccMessage):]
switch {
case bytes.HasPrefix(msg, ccModel) && typeAfter(msg, ccRole) == "assistant":
at := tsAt(b, true)
s.saw(at, main)
ccWhere(s, b)
ccReply(s, at, msg, b, main)
case bytes.HasPrefix(msg, ccRole) && typeAfter(msg, ccRole) == "user":
if main && !ccToolResult(msg) {
// a prompt, or something Claude Code put in: read whole
claudeFull(s, b, main)
return
}
s.saw(tsAt(b, true), main)
ccWhere(s, b)
default:
claudeFull(s, b, main)
}
}
// ccWhere takes the session's folder and id from the end of a line, while
// they are not known.
func ccWhere(s *state, b []byte) {
if s.Cwd == "" {
s.Cwd = strAt(b, ccCwd)
}
if s.ID == "" {
s.ID = strAt(b, ccSession)
}
}
// strAt is the string after the last key in b.
func strAt(b, key []byte) string {
i := bytes.LastIndex(b, key)
if i < 0 {
return ""
}
rest := b[i+len(key)-1:]
for j := 1; j < len(rest); j++ {
switch rest[j] {
case '\\':
j++
case '"':
var v string
if json.Unmarshal(rest[:j+1], &v) != nil {
return ""
}
return v
}
}
return ""
}
var (
ccContent = []byte(`"content":`)
ccResult1 = []byte(`[{"tool_use_id"`)
ccResult2 = []byte(`[{"type":"tool_result"`)
ccToolUse = []byte(`{"type":"tool_use"`)
)
// ccToolResult tells a user message that is a tool's result from its head.
func ccToolResult(msg []byte) bool {
i := bytes.Index(msg, ccContent)
if i < 0 {
return false
}
c := msg[i+len(ccContent):]
return bytes.HasPrefix(c, ccResult1) || bytes.HasPrefix(c, ccResult2)
}
// ccTools finds Claude Code's tool blocks (type first) and decodes their
// identity without retaining their arguments. Advancing over the whole block
// also prevents a nested tool-shaped object in its input from being counted.
func ccTools(s *state, m *claudeContribution, at time.Time, b []byte) {
for rest := b; ; {
i := bytes.Index(rest, ccToolUse)
if i < 0 {
return
}
var tool struct {
ID, Name string
Input struct{ Skill any }
}
dec := json.NewDecoder(bytes.NewReader(rest[i:]))
if dec.Decode(&tool) != nil {
return
}
rest = rest[i+int(dec.InputOffset()):]
skill, _ := tool.Input.Skill.(string)
if tool.Name != "Skill" {
skill = ""
}
ccTool(s, m, at, tool.ID, tool.Name, skill)
}
}
// ccReply counts a reply's usage: its model and id lead the message, its
// usage follows the content.
func ccReply(s *state, at time.Time, msg, b []byte, main bool) {
model, id := typeAfter(msg, ccModel), typeAfter(msg, ccID)
// Decode just the outer identity: a tool's input may itself contain a
// requestId, which must never become the identity of this response.
identity := gjson.GetBytes(b, "requestId")
request := ""
if identity.Type == gjson.String {
request = identity.String()
}
m := ccUsageState(&s.Claude).message(id, request)
defer s.Claude.finish(m)
i := bytes.LastIndex(b, ccUsage)
if i < 0 {
i = len(b)
}
ccTools(s, m, at, b[:i])
if i == len(b) || model == "<synthetic>" {
return
}
var u struct {
Input int `json:"input_tokens"`
Output int `json:"output_tokens"`
CacheRead int `json:"cache_read_input_tokens"`
CacheWrite int `json:"cache_creation_input_tokens"`
Creation *ccCacheCreation `json:"cache_creation"`
}
if json.NewDecoder(bytes.NewReader(b[i+len(ccUsage)-1:])).Decode(&u) != nil {
return
}
ccCount(s, m, at, model, ccTokens(u.Input, u.Output, u.CacheRead, u.CacheWrite, u.Creation), main)
}
// claudeFull reads a line whole.
func claudeFull(s *state, b []byte, main bool) {
at := tsAt(b, true)
s.saw(at, main)
want := bytes.Contains(b, ccAssistant) ||
main && bytes.Contains(b, ccUser) ||
main && (bytes.Contains(b, ccTitle) || bytes.Contains(b, ccCustom) || bytes.Contains(b, ccSummary)) ||
s.Cwd == "" && bytes.Contains(b, ccCwd)
if !want {
return
}
var l ccLine
if json.Unmarshal(b, &l) != nil {
return
}
if s.Cwd == "" && l.Cwd != "" {
s.Cwd = l.Cwd
}
if s.ID == "" && l.SessionID != "" {
s.ID = l.SessionID
}
switch l.Type {
case "ai-title":
if l.AITitle != "" {
s.Named = title(l.AITitle)
}
case "custom-title":
// named by the user (/rename): before the one Claude Code made
if main && l.CustomTitle != "" {
s.Custom = title(l.CustomTitle)
}
case "summary":
if l.Summary != "" && s.Named == "" {
s.Named = title(l.Summary)
}
case "user":
if main && !l.IsMeta && !l.IsSidechain {
p := ccPrompt(l.Message.Content)
if p != "" {
s.day(dateOf(at)).Prompts++
}
if s.Title == "" {
s.Title = p
if s.Title == "" && s.First == "" {
s.First = untagged(ccText(l.Message.Content))
}
}
}
case "assistant":
m := ccUsageState(&s.Claude).message(l.Message.ID, string(l.RequestID))
defer s.Claude.finish(m)
var blocks []struct {
Type, ID, Name string
Input struct{ Skill any }
}
if json.Unmarshal(l.Message.Content, &blocks) == nil {
for _, c := range blocks {
if c.Type == "tool_use" {
skill, _ := c.Input.Skill.(string)
if c.Name != "Skill" {
skill = ""
}
ccTool(s, m, at, c.ID, c.Name, skill)
}
}
}
u := l.Message.Usage
if u == nil || l.Message.Model == "<synthetic>" {
return
}
ccCount(s, m, at, l.Message.Model, ccTokens(u.Input, u.Output, u.CacheRead, u.CacheWrite, u.Creation), main)
}
}
// ccText is the text of a user message, "" for a tool's result.
func ccText(content json.RawMessage) string {
var text string
if json.Unmarshal(content, &text) != nil {
var blocks []struct{ Type, Text string }
if json.Unmarshal(content, &blocks) != nil {
return ""
}
var parts []string
for _, b := range blocks {
if b.Type == "tool_result" {
return ""
}
if b.Type == "text" && b.Text != "" {
parts = append(parts, b.Text)
}
}
text = strings.Join(parts, " ")
}
return strings.TrimSpace(text)
}
var (
ccCommand = regexp.MustCompile(`<command-name>\s*([^<]*?)\s*</command-name>`)
ccArgs = regexp.MustCompile(`<command-args>\s*([^<]*?)\s*</command-args>`)
)
// ccPrompt is the words of a prompt someone typed, or "" for what Claude
// Code put in the conversation itself (tool results, command output).
func ccPrompt(content json.RawMessage) string {
text := ccText(content)
if m := ccCommand.FindStringSubmatch(text); m != nil {
// a slash command: its name and what was typed after it
cmd := m[1]
if a := ccArgs.FindStringSubmatch(text); a != nil && a[1] != "" {
cmd += " " + a[1]
}
return title(cmd)
}
if text == "" || strings.HasPrefix(text, "<") || strings.HasPrefix(text, "[Request interrupted") || strings.HasPrefix(text, "Caveat:") {
return ""
}
return title(text)
}