Debian Codegraph @

internal/core/transcript/state.go

raw
1 package transcript
2
3 import (
4 "encoding/json"
5 "fmt"
6 "io"
7 "strings"
8 )
9
10 type state struct {
11 Type string `json:"type"`
12 Source string `json:"source"`
13 Cwd string `json:"cwd"`
14 }
15
16 // FormatStateMessage renders the host cwd state object stored in transcripts.
17 func FormatStateMessage(cwd string) string {
18 body, err := json.Marshal(state{
19 Type: "state",
20 Source: "clnkr",
21 Cwd: cwd,
22 })
23 if err != nil {
24 panic(fmt.Sprintf("marshal state message: %v", err))
25 }
26 return string(body)
27 }
28
29 // ExtractLatestCwd returns the latest valid clnkr cwd state from a transcript.
30 func ExtractLatestCwd(messages []Message) (string, bool) {
31 for i := len(messages) - 1; i >= 0; i-- {
32 if messages[i].Role != "user" {
33 continue
34 }
35 if cwd, ok := ExtractStateCwd(messages[i].Content); ok {
36 return cwd, true
37 }
38 }
39 return "", false
40 }
41
42 // ExtractStateCwd parses a single transcript state message.
43 func ExtractStateCwd(content string) (string, bool) {
44 dec := json.NewDecoder(strings.NewReader(content))
45 dec.DisallowUnknownFields()
46 var parsed state
47 if err := dec.Decode(&parsed); err != nil {
48 return "", false
49 }
50 if err := dec.Decode(&struct{}{}); err != io.EOF {
51 return "", false
52 }
53 if parsed.Type != "state" || parsed.Source != "clnkr" || parsed.Cwd == "" {
54 return "", false
55 }
56 return parsed.Cwd, true
57 }