package server import ( "fmt" "strings" "time" "git.a-wan.net/alan/pipelines/internal/protocol" ) // chatShellSharePrompt is the ordinary prompt chat_shell_share queues: the // command, where it ran, how it ended and a bounded tail of the plain-text // rendering of its output (no terminal escape sequences). It is the only path // by which an operator command reaches the agent. func chatShellSharePrompt(record protocol.ChatShellRunRecord) string { text := record.Text if text == "" { text = chatShellPlainText(record.Output) } shown := text if len(shown) > protocol.ChatShellRunShareOutput { shown = shown[runeStartAfter([]byte(shown), len(shown)-protocol.ChatShellRunShareOutput):] } var b strings.Builder fmt.Fprintf(&b, "I ran this shell command in %s:\n\n", record.Directory) fence := chatShellFence(record.Command) fmt.Fprintf(&b, "%ssh\n$ %s\n%s\n\n", fence, record.Command, fence) fmt.Fprintf(&b, "%s.\n\n", chatShellOutcome(record)) if strings.TrimSpace(shown) == "" { b.WriteString("It printed no output.") return b.String() } if len(shown) < len(text) || record.OutputStart > 0 { fmt.Fprintf(&b, "Output (the last %s of the %s it wrote, as plain text):\n\n", chatShellBytes(int64(len(shown))), chatShellBytes(record.OutputBytes)) } else { b.WriteString("Output:\n\n") } fence = chatShellFence(shown) fmt.Fprintf(&b, "%stext\n%s\n%s", fence, strings.TrimRight(shown, "\n"), fence) return b.String() } // chatShellOutcome describes how a run ended, in the card's own words. func chatShellOutcome(record protocol.ChatShellRunRecord) string { took := (time.Duration(record.DurationMS) * time.Millisecond).Round(time.Millisecond) switch record.Status { case protocol.ChatShellRunStopped: return fmt.Sprintf("I stopped it after %s", took) case protocol.ChatShellRunInterrupted: return "It was interrupted when the server stopped" case protocol.ChatShellRunFailed: return "It failed: " + record.Error } if record.Signal != "" { return fmt.Sprintf("It was killed by %s after %s", record.Signal, took) } if record.ExitCode != nil { return fmt.Sprintf("It exited with status %d after %s", *record.ExitCode, took) } return "It ended" } // chatShellFence is a Markdown code fence longer than any backtick run in text. func chatShellFence(text string) string { longest, run := 0, 0 for _, r := range text { if r == '`' { run++ longest = max(longest, run) } else { run = 0 } } return strings.Repeat("`", max(3, longest+1)) } func chatShellBytes(n int64) string { switch { case n >= 1<<20: return fmt.Sprintf("%.1f MiB", float64(n)/(1<<20)) case n >= 1<<10: return fmt.Sprintf("%.1f KiB", float64(n)/(1<<10)) } return fmt.Sprintf("%d bytes", n) }