-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopencode.go
More file actions
220 lines (195 loc) · 5.65 KB
/
Copy pathopencode.go
File metadata and controls
220 lines (195 loc) · 5.65 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
package compact
import (
"bytes"
"encoding/json"
"fmt"
"time"
"github.com/GrayCodeAI/trace/cli/textutil"
"github.com/GrayCodeAI/trace/cli/transcript"
)
// --- OpenCode format support ---
//
// OpenCode transcripts are a single JSON object (not JSONL):
//
// {"info":{...},"messages":[{"info":{"role":"user","time":{...}},"parts":[...]}, ...]}
//
// Parts use "type" values: "text", "tool", "step-start", "step-finish".
// Tool parts store the tool name in "tool" (string) and call details in "state".
// isOpenCodeFormat checks whether content is a single JSON object with the
// OpenCode session shape (top-level "info" and "messages" keys).
func isOpenCodeFormat(content []byte) bool {
trimmed := bytes.TrimSpace(content)
if len(trimmed) == 0 || trimmed[0] != '{' {
return false
}
// Quick structural check: unmarshal just enough to detect the keys.
var probe struct {
Info *json.RawMessage `json:"info"`
Messages *json.RawMessage `json:"messages"`
}
if json.Unmarshal(trimmed, &probe) != nil {
return false
}
return probe.Info != nil && probe.Messages != nil
}
// openCodeMessage mirrors the OpenCode message structure for unmarshaling.
type openCodeMessage struct {
Info openCodeMessageInfo `json:"info"`
Parts []map[string]json.RawMessage `json:"parts"`
}
type openCodeMessageInfo struct {
ID string `json:"id"`
Role string `json:"role"`
Time openCodeMsgTime `json:"time"`
Tokens *openCodeMsgToken `json:"tokens"`
}
type openCodeMsgTime struct {
Created int64 `json:"created"`
Completed int64 `json:"completed"`
}
type openCodeMsgToken struct {
Input int `json:"input"`
Output int `json:"output"`
}
// compactOpenCode converts a full OpenCode session JSON into transcript lines.
// opts.StartLine is treated as a message-index offset (not a newline offset)
// because the OpenCode transcript is a single JSON object.
func compactOpenCode(content []byte, opts MetadataFields) ([]byte, error) {
var session struct {
Messages []openCodeMessage `json:"messages"`
}
if err := json.Unmarshal(bytes.TrimSpace(content), &session); err != nil {
return nil, fmt.Errorf("parsing opencode session: %w", err)
}
messages := session.Messages
if opts.StartLine > 0 {
if opts.StartLine >= len(messages) {
return []byte{}, nil
}
messages = messages[opts.StartLine:]
}
base := newTranscriptLine(opts)
var result []byte
for _, msg := range messages {
ts := msToTimestamp(msg.Info.Time.Created)
switch msg.Info.Role {
case transcript.TypeUser:
emitOpenCodeUser(&result, base, msg, ts)
case transcript.TypeAssistant:
emitOpenCodeAssistant(&result, base, msg, ts)
}
}
return result, nil
}
func emitOpenCodeUser(result *[]byte, base transcriptLine, msg openCodeMessage, ts json.RawMessage) {
var blocks []json.RawMessage
for _, part := range msg.Parts {
if unquote(part["type"]) != transcript.ContentTypeText {
continue
}
text := textutil.StripIDEContextTags(unquote(part[transcript.ContentTypeText]))
if text == "" {
continue
}
tb := userTextBlock{Text: text}
if id := part["id"]; id != nil {
_ = json.Unmarshal(id, &tb.ID) //nolint:errcheck // best-effort
}
b, err := json.Marshal(tb)
if err != nil {
continue
}
blocks = append(blocks, b)
}
contentJSON, err := json.Marshal(blocks)
if err != nil {
return
}
line := base
line.Type = transcript.TypeUser
line.TS = ts
line.Content = contentJSON
appendLine(result, line)
}
func emitOpenCodeAssistant(result *[]byte, base transcriptLine, msg openCodeMessage, ts json.RawMessage) {
content := make([]map[string]json.RawMessage, 0, len(msg.Parts))
for _, part := range msg.Parts {
partType := unquote(part["type"])
switch partType {
case transcript.ContentTypeText:
b, err := json.Marshal(transcript.ContentTypeText)
if err != nil {
continue
}
content = append(content, map[string]json.RawMessage{
"type": b,
"text": part[transcript.ContentTypeText],
})
case "tool":
toolBlock := make(map[string]json.RawMessage)
b, err := json.Marshal(transcript.ContentTypeToolUse)
if err != nil {
continue
}
toolBlock["type"] = b
if callID := part["callID"]; callID != nil {
toolBlock["id"] = callID
}
if toolName := part["tool"]; toolName != nil {
toolBlock["name"] = toolName
}
if stateRaw := part["state"]; stateRaw != nil {
var state map[string]json.RawMessage
if json.Unmarshal(stateRaw, &state) == nil {
if inp := state["input"]; inp != nil {
toolBlock["input"] = inp
}
toolBlock["result"] = openCodeToolResult(state)
}
}
content = append(content, toolBlock)
}
}
contentJSON, err := json.Marshal(content)
if err != nil {
return
}
line := base
line.Type = transcript.TypeAssistant
line.TS = ts
line.ID = msg.Info.ID
line.Content = contentJSON
if msg.Info.Tokens != nil {
line.InputTokens = msg.Info.Tokens.Input
line.OutputTokens = msg.Info.Tokens.Output
}
appendLine(result, line)
}
// openCodeToolResult builds the compact {"output":"...","status":"success"|"error"}
// object from an OpenCode tool state map.
func openCodeToolResult(state map[string]json.RawMessage) json.RawMessage {
r := toolResultJSON{
Output: unquote(state["output"]),
Status: "success",
}
if s := unquote(state["status"]); s != "" && s != "completed" {
r.Status = toolResultStatusError
}
b, err := json.Marshal(r)
if err != nil {
return nil
}
return b
}
// msToTimestamp converts a Unix millisecond timestamp to an RFC3339 JSON string.
func msToTimestamp(ms int64) json.RawMessage {
if ms == 0 {
return nil
}
t := time.UnixMilli(ms).UTC()
b, err := json.Marshal(t.Format(time.RFC3339Nano))
if err != nil {
return nil
}
return b
}