Files
pipelines/internal/server/chat_shell_share.go
T
alan e6bc57c901 Run operator shell commands in a chat's directory on the server
chat_shell_run starts $SHELL -lc in the chat session's directory in its own
process group, streams merged output to every watcher of the session, keeps a
1 MiB tail and persists each run; chat_shell_stop interrupts the group and
kills it after a grace period. chat_shell_share queues an ordinary prompt
with the command and a bounded output tail.
2026-11-09 15:55:14 +00:00

79 lines
2.4 KiB
Go

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 its output. It is
// the only path by which an operator command reaches the agent.
func chatShellSharePrompt(record protocol.ChatShellRunRecord) string {
output := chatShellRecordTail(record, 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 output.Output == "" {
b.WriteString("It printed no output.")
return b.String()
}
if output.OutputStart > 0 {
fmt.Fprintf(&b, "Output (the last %s of %s):\n\n", chatShellBytes(int64(len(output.Output))), chatShellBytes(output.OutputBytes))
} else {
b.WriteString("Output:\n\n")
}
fence = chatShellFence(output.Output)
text := strings.TrimRight(output.Output, "\n")
fmt.Fprintf(&b, "%stext\n%s\n%s", fence, text, 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)
}