| 1 |
package clnkrapp |
| 2 |
|
| 3 |
import ( |
| 4 |
"encoding/json" |
| 5 |
"fmt" |
| 6 |
"io" |
| 7 |
"strings" |
| 8 |
|
| 9 |
"github.com/clnkr-ai/clnkr" |
| 10 |
) |
| 11 |
|
| 12 |
type JSONLCommand struct { |
| 13 |
Type string `json:"type"` |
| 14 |
Text string `json:"text,omitempty"` |
| 15 |
Mode string `json:"mode,omitempty"` |
| 16 |
} |
| 17 |
|
| 18 |
func DecodeJSONLCommand(line []byte) (JSONLCommand, error) { |
| 19 |
var command JSONLCommand |
| 20 |
if err := json.Unmarshal(line, &command); err != nil { |
| 21 |
return JSONLCommand{}, fmt.Errorf("decode JSONL command: %w", err) |
| 22 |
} |
| 23 |
switch command.Type { |
| 24 |
case "prompt": |
| 25 |
if strings.TrimSpace(command.Text) == "" { |
| 26 |
return JSONLCommand{}, fmt.Errorf("JSONL prompt text is required") |
| 27 |
} |
| 28 |
switch command.Mode { |
| 29 |
case PromptModeApproval, PromptModeFullSend: |
| 30 |
return command, nil |
| 31 |
default: |
| 32 |
return JSONLCommand{}, fmt.Errorf("unknown JSONL prompt mode %q", command.Mode) |
| 33 |
} |
| 34 |
case "reply", "shutdown": |
| 35 |
return command, nil |
| 36 |
case "compact": |
| 37 |
var m map[string]any |
| 38 |
if err := json.Unmarshal(line, &m); err != nil { |
| 39 |
return JSONLCommand{}, fmt.Errorf("decode JSONL command: %w", err) |
| 40 |
} |
| 41 |
if len(m) != 1 || m["type"] != "compact" { |
| 42 |
return JSONLCommand{}, fmt.Errorf("JSONL compact supports only {\"type\":\"compact\"}") |
| 43 |
} |
| 44 |
return command, nil |
| 45 |
default: |
| 46 |
return JSONLCommand{}, fmt.Errorf("unknown JSONL command type %q", command.Type) |
| 47 |
} |
| 48 |
} |
| 49 |
|
| 50 |
func WriteJSONL(w io.Writer, event any) error { |
| 51 |
if event, ok := event.(clnkr.Event); ok { |
| 52 |
return WriteEventLog(w, event) |
| 53 |
} |
| 54 |
switch event := event.(type) { |
| 55 |
case EventClarificationRequest: |
| 56 |
return writeEvent(w, "clarify", map[string]string{"question": event.Question}) |
| 57 |
case EventApprovalRequest: |
| 58 |
return writeEvent( |
| 59 |
w, |
| 60 |
"approval_request", |
| 61 |
map[string]any{"prompt": event.Prompt, "commands": event.Commands}, |
| 62 |
) |
| 63 |
case EventDone: |
| 64 |
return writeEvent(w, "done", map[string]string{"summary": event.Summary}) |
| 65 |
case EventCompacted: |
| 66 |
return writeEvent(w, "compacted", map[string]int{ |
| 67 |
"compacted_messages": event.Stats.CompactedMessages, |
| 68 |
"kept_messages": event.Stats.KeptMessages, |
| 69 |
}) |
| 70 |
case EventError: |
| 71 |
message := "" |
| 72 |
if event.Err != nil { |
| 73 |
message = event.Err.Error() |
| 74 |
} |
| 75 |
return writeEvent(w, "error", map[string]string{"message": message}) |
| 76 |
default: |
| 77 |
return fmt.Errorf("write JSONL: unsupported event %T", event) |
| 78 |
} |
| 79 |
} |