-
Notifications
You must be signed in to change notification settings - Fork 512
Expand file tree
/
Copy pathcommandcode.go
More file actions
344 lines (316 loc) · 7.57 KB
/
Copy pathcommandcode.go
File metadata and controls
344 lines (316 loc) · 7.57 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
package parser
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/tidwall/gjson"
)
type commandCodeMeta struct {
Title string `json:"title"`
UserRenamed bool `json:"userRenamed"`
ProjectPath string `json:"projectPath"`
Cwd string `json:"cwd"`
}
// parseSession parses a Command Code JSONL transcript.
func (p *commandCodeProvider) parseSession(
path, machine string,
) (*ParsedSession, []ParsedMessage, error) {
info, err := os.Stat(path)
if err != nil {
return nil, nil, fmt.Errorf("stat %s: %w", path, err)
}
f, err := os.Open(path)
if err != nil {
return nil, nil, fmt.Errorf("open %s: %w", path, err)
}
defer f.Close()
lr := newLineReader(f, maxLineSize)
var (
sessionID string
cwd string
gitBranch string
firstMessage string
startedAt time.Time
endedAt time.Time
ordinal int
userCount int
malformedLines int
messages []ParsedMessage
)
for {
line, ok := lr.next()
if !ok {
break
}
if !gjson.Valid(line) {
malformedLines++
continue
}
root := gjson.Parse(line)
if sessionID == "" {
sessionID = root.Get("sessionId").Str
}
if cwd == "" {
cwd = commandCodeCwd(root)
}
if gitBranch == "" {
gitBranch = root.Get("gitBranch").Str
}
ts := parseTimestamp(root.Get("timestamp").Str)
if !ts.IsZero() {
if startedAt.IsZero() || ts.Before(startedAt) {
startedAt = ts
}
if endedAt.IsZero() || ts.After(endedAt) {
endedAt = ts
}
}
role := root.Get("role").Str
content := root.Get("content")
text, thinking, hasThinking, hasToolUse, toolCalls, toolResults :=
extractCommandCodeContent(content)
text = strings.TrimSpace(text)
switch role {
case "user":
if text == "" && len(toolResults) == 0 {
continue
}
if firstMessage == "" && text != "" {
firstMessage = truncate(
strings.ReplaceAll(text, "\n", " "),
300,
)
}
messages = append(messages, ParsedMessage{
Ordinal: ordinal,
Role: RoleUser,
Content: text,
ThinkingText: thinking,
Timestamp: ts,
HasThinking: hasThinking,
HasToolUse: hasToolUse,
ContentLength: len(text),
ToolCalls: toolCalls,
ToolResults: toolResults,
})
ordinal++
if text != "" {
userCount++
}
case "assistant":
if text == "" && !hasThinking &&
len(toolCalls) == 0 && len(toolResults) == 0 {
continue
}
messages = append(messages, ParsedMessage{
Ordinal: ordinal,
Role: RoleAssistant,
Content: text,
ThinkingText: thinking,
Timestamp: ts,
HasThinking: hasThinking,
HasToolUse: hasToolUse,
ContentLength: len(text),
ToolCalls: toolCalls,
ToolResults: toolResults,
})
ordinal++
case "tool":
if len(toolResults) == 0 {
continue
}
messages = append(messages, ParsedMessage{
Ordinal: ordinal,
Role: RoleUser,
Timestamp: ts,
ContentLength: 0,
ToolResults: toolResults,
})
ordinal++
}
}
if err := lr.Err(); err != nil {
return nil, nil, fmt.Errorf("reading command-code %s: %w", path, err)
}
if len(messages) == 0 {
return nil, nil, nil
}
meta := loadCommandCodeMeta(path)
if meta != nil {
if cwd == "" {
cwd = commandCodeFirstNonEmpty(meta.Cwd, meta.ProjectPath)
}
if firstMessage == "" {
firstMessage = meta.Title
}
}
if sessionID == "" {
sessionID = strings.TrimSuffix(filepath.Base(path), ".jsonl")
}
project := ExtractProjectFromCwd(cwd)
if project == "" {
project = NormalizeName(filepath.Base(filepath.Dir(path)))
}
sessionName := ""
if meta != nil {
sessionName = meta.Title
}
sess := &ParsedSession{
ID: "commandcode:" + sessionID,
Project: project,
Machine: machine,
Agent: AgentCommandCode,
Cwd: cwd,
GitBranch: gitBranch,
SourceVersion: "2",
MalformedLines: malformedLines,
FirstMessage: firstMessage,
SessionName: sessionName,
StartedAt: startedAt,
EndedAt: endedAt,
MessageCount: len(messages),
UserMessageCount: userCount,
File: FileInfo{
Path: path,
Size: info.Size(),
Mtime: info.ModTime().UnixNano(),
},
}
return sess, messages, nil
}
func loadCommandCodeMeta(path string) *commandCodeMeta {
metaPath := strings.TrimSuffix(path, ".jsonl") + ".meta.json"
data, err := os.ReadFile(metaPath)
if err != nil {
return nil
}
var meta commandCodeMeta
if err := json.Unmarshal(data, &meta); err != nil {
return nil
}
return &meta
}
func commandCodeCwd(root gjson.Result) string {
for _, key := range []string{
"metadata.cwd",
"metadata.projectPath",
"metadata.context.cwd",
"cwd",
} {
if v := root.Get(key).Str; v != "" {
return v
}
}
return ""
}
func extractCommandCodeContent(
content gjson.Result,
) (string, string, bool, bool, []ParsedToolCall, []ParsedToolResult) {
if content.Type == gjson.String {
return content.Str, "", false, false, nil, nil
}
if !content.IsArray() {
return "", "", false, false, nil, nil
}
var (
textParts []string
thinkingParts []string
toolCalls []ParsedToolCall
toolResults []ParsedToolResult
hasThinking bool
hasToolUse bool
)
content.ForEach(func(_, block gjson.Result) bool {
switch block.Get("type").Str {
case "text":
if text := block.Get("text").Str; text != "" {
textParts = append(textParts, text)
}
case "reasoning", "thinking":
thinking := commandCodeFirstNonEmpty(
block.Get("text").Str,
block.Get("thinking").Str,
)
if thinking != "" {
hasThinking = true
thinkingParts = append(thinkingParts, thinking)
}
case "tool-call", "tool_use":
toolName := commandCodeFirstNonEmpty(
block.Get("toolName").Str,
block.Get("name").Str,
)
if toolName == "" {
return true
}
hasToolUse = true
input := block.Get("input")
inputJSON := input.Raw
if inputJSON == "" {
inputJSON = "{}"
}
toolCalls = append(toolCalls, ParsedToolCall{
ToolUseID: blockID(block, "toolCallId", "id"),
ToolName: toolName,
Category: NormalizeToolCategory(toolName),
InputJSON: inputJSON,
})
case "tool-result", "tool_result":
toolUseID := blockID(block, "toolCallId", "tool_use_id")
contentRaw, contentLen := commandCodeToolResultContent(block)
if toolUseID == "" || contentRaw == "" {
return true
}
toolResults = append(toolResults, ParsedToolResult{
ToolUseID: toolUseID,
ContentLength: contentLen,
ContentRaw: contentRaw,
})
}
return true
})
return strings.Join(textParts, "\n"),
strings.Join(thinkingParts, "\n\n"),
hasThinking, hasToolUse, toolCalls, toolResults
}
func commandCodeToolResultContent(block gjson.Result) (string, int) {
output := block.Get("output")
if !output.Exists() {
output = block.Get("content")
}
if output.Exists() {
if output.IsObject() {
if value := output.Get("value"); value.Exists() &&
value.Type == gjson.String {
return strconv.Quote(value.Str), len(value.Str)
}
}
return output.Raw, toolResultContentLength(output)
}
for _, key := range []string{"text", "error", "value"} {
if text := block.Get(key).Str; text != "" {
return strconv.Quote(text), len(text)
}
}
return "", 0
}
func blockID(block gjson.Result, keys ...string) string {
for _, key := range keys {
if value := block.Get(key).Str; value != "" {
return value
}
}
return ""
}
func commandCodeFirstNonEmpty(values ...string) string {
for _, value := range values {
if value != "" {
return value
}
}
return ""
}