gunk-dev/the-valley

codex.go

sourced9f7bacd171bmain's published tip history
1.7 KiB
1package stream
2
3import "encoding/json"
4
5// NormalizeLine adapts Codex and agy JSONL events to the event shapes Klaus already
6// consumes. Original logs are retained unchanged for diagnosis.
7func NormalizeLine(line []byte) []byte {
8 var ev struct {
9 Type string `json:"type"`
10 ThreadID string `json:"thread_id"`
11 Item struct {
12 Type string `json:"type"`
13 Text string `json:"text"`
14 Command string `json:"command"`
15 Output string `json:"aggregated_output"`
16 } `json:"item"`
17 Error struct {
18 Message string `json:"message"`
19 } `json:"error"`
20 }
21 if json.Unmarshal(line, &ev) != nil {
22 return normalizeAgy(line)
23 }
24 var out any
25 switch ev.Type {
26 case "thread.started":
27 out = map[string]any{"type": "system", "subtype": "init", "session_id": ev.ThreadID, "model": "codex"}
28 case "item.completed":
29 switch ev.Item.Type {
30 case "agent_message":
31 out = map[string]any{"type": "assistant", "message": map[string]any{"content": []any{map[string]any{"type": "text", "text": ev.Item.Text}}}}
32 case "command_execution":
33 out = map[string]any{"type": "tool_result", "content": ev.Item.Output}
34 }
35 case "item.started":
36 if ev.Item.Type == "command_execution" {
37 out = map[string]any{"type": "assistant", "message": map[string]any{"content": []any{map[string]any{"type": "tool_use", "name": "Bash", "input": map[string]any{"command": ev.Item.Command}}}}}
38 }
39 case "turn.completed":
40 out = map[string]any{"type": "result", "subtype": "success"}
41 case "turn.failed":
42 out = map[string]any{"type": "result", "subtype": "error_during_execution", "is_error": true, "errors": []string{ev.Error.Message}}
43 }
44 if out == nil {
45 return normalizeAgy(line)
46 }
47 data, err := json.Marshal(out)
48 if err != nil {
49 return normalizeAgy(line)
50 }
51 return data
52}