Debian Codegraph @

internal/core/transcript/command.go

raw
1 package transcript
2
3 import (
4 "encoding/json"
5 "regexp"
6 "strconv"
7 "strings"
8 )
9
10 const commandStreamBudget = 64 * 1024
11
12 var salientPattern = regexp.MustCompile(
13 `(?i)(error|failed|failure|panic|exception|traceback|fatal|undefined|cannot|no such file|permission denied|denied|timeout|killed|segmentation fault|failures|expected|actual|assertion|FAIL|FAILED|--- FAIL|:[0-9]+:)`,
14 )
15
16 // FormatCommandResult renders a command result as structured shell output.
17 func FormatCommandResult(result CommandResult) string {
18 outcome := normalizedOutcome(result.Outcome, result.ExitCode)
19 diagnostic := outcome.Type != CommandOutcomeExit ||
20 outcome.ExitCode != nil && *outcome.ExitCode != 0
21 stdout, stdoutMeta := compressCommandStream(
22 "stdout",
23 result.Stdout,
24 diagnostic && result.Stderr == "",
25 )
26 stderr, stderrMeta := compressCommandStream("stderr", result.Stderr, diagnostic)
27 payload := map[string]any{"stdout": stdout, "stderr": stderr, "outcome": outcome}
28 if result.Command != "" {
29 payload["command"] = result.Command
30 }
31 if len(result.Feedback.ChangedFiles) > 0 || result.Feedback.Diff != "" {
32 payload["feedback"] = result.Feedback
33 }
34 if strings.TrimSpace(result.Guidance) != "" {
35 payload["guidance"] = result.Guidance
36 }
37 if stdoutMeta != nil || stderrMeta != nil {
38 payload["observation"] = map[string]any{
39 "source": "clnkr",
40 "version": 1,
41 "stdout": stdoutMeta,
42 "stderr": stderrMeta,
43 }
44 }
45 body, _ := json.Marshal(payload)
46 return string(body)
47 }
48
49 func compressCommandStream(name, stream string, salient bool) (string, map[string]any) {
50 if len(stream) <= commandStreamBudget {
51 return stream, nil
52 }
53 marker := "[clnkr: " + name + " compressed; original " + strconv.Itoa(
54 len(stream),
55 ) + " bytes, omitted bytes recorded in observation metadata]\n"
56 keep := max(0, commandStreamBudget-len(marker)-len("\n[head]\n\n[tail]\n\n[salient]\n"))
57 head, tail := keep/3, keep/3
58 middle := salientLines(stream[head:len(stream)-tail], keep-head-tail, salient)
59 shown := marker + "[head]\n" + stream[:head]
60 if middle != "" {
61 shown += "\n[salient]\n" + middle
62 }
63 shown += "\n[tail]\n" + stream[len(stream)-tail:]
64 shown = strings.ToValidUTF8(shown, "")
65 return shown, map[string]any{
66 "original_bytes": len(stream),
67 "shown_bytes": len(shown),
68 "omitted_bytes": len(stream) - head - tail - len(middle),
69 "mode": "compressed",
70 }
71 }
72
73 func salientLines(stream string, budget int, ok bool) string {
74 var out string
75 seen := map[string]bool{}
76 for _, line := range strings.SplitAfter(stream, "\n") {
77 if ok && salientPattern.MatchString(line) && !seen[line] && len(out)+len(line) <= budget {
78 seen[line], out = true, out+line
79 }
80 }
81 return out
82 }
83
84 func FormatDeniedCommandResult(reply string) string {
85 stderr := "Command was not run because the user denied approval."
86 if trimmed := strings.TrimSpace(reply); trimmed != "" {
87 stderr += "\nUser guidance: " + trimmed
88 }
89 return FormatCommandResult(
90 CommandResult{Stderr: stderr, Outcome: CommandOutcome{Type: CommandOutcomeDenied}},
91 )
92 }
93
94 func FormatSkippedCommandResult(reason string) string {
95 switch reason = strings.TrimSpace(reason); reason {
96 case "max steps":
97 return FormatCommandResult(
98 CommandResult{
99 Stderr: "Command was not run because the step limit was reached.",
100 Outcome: CommandOutcome{Type: CommandOutcomeSkipped, Reason: "max_steps"},
101 },
102 )
103 case "previous command failed":
104 return FormatCommandResult(
105 CommandResult{
106 Stderr: "Command was not run because a previous command failed.",
107 Outcome: CommandOutcome{
108 Type: CommandOutcomeSkipped,
109 Reason: "previous_command_failed",
110 },
111 },
112 )
113 case "":
114 return FormatCommandResult(
115 CommandResult{
116 Stderr: "Command was not run.",
117 Outcome: CommandOutcome{Type: CommandOutcomeSkipped, Reason: "skipped"},
118 },
119 )
120 default:
121 return FormatCommandResult(
122 CommandResult{
123 Stderr: "Command was not run.\nReason: " + reason,
124 Outcome: CommandOutcome{Type: CommandOutcomeSkipped, Reason: "skipped"},
125 },
126 )
127 }
128 }
129
130 func normalizedOutcome(outcome CommandOutcome, fallbackExitCode int) CommandOutcome {
131 if outcome.Type == "" {
132 return CommandOutcome{Type: CommandOutcomeExit, ExitCode: &fallbackExitCode}
133 }
134 if outcome.Type == CommandOutcomeExit && outcome.ExitCode == nil {
135 code := fallbackExitCode
136 outcome.ExitCode = &code
137 }
138 return outcome
139 }