mirror of
https://github.com/donlucasx/xscapes.git
synced 2026-10-20 08:43:32 +02:00
The two words run the agent inside the scape as `xscapes claude` does. The first outside tester's agent hand-wrote twelve [[hooks]] entries into Kimi's config, each calling `xscapes hook <Event>` with no marker; installed over them, every event would fire twice and a doubled SubagentStart is two kittens for one sub-agent. The installer now refuses such a file and says why; it removes nothing it did not write. PermissionResult and Interrupt join the Kimi block. README: one install line, then one line per agent; Adapter 3 rewritten on the measurements. The page's Install section, his ruling: the install line, then four small captioned boxes (Claude Code, Kimi Code CLI, Hermes Agent, anything else) and a coming-soon line. Looked at on desktop and phone. Site rebuilt. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
353 lines
12 KiB
Go
353 lines
12 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"flag"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"os/exec"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/donlucasx/xscapes/internal/event"
|
|
"github.com/donlucasx/xscapes/internal/notify"
|
|
)
|
|
|
|
// dispatch handles the subcommands. They are checked before flag.Parse so that
|
|
// `xscapes emit tool_start -tool Read` can have its own flag set without
|
|
// colliding with the renderer's twenty demo flags.
|
|
//
|
|
// Returns true if it handled the call.
|
|
func dispatch(args []string) bool {
|
|
if len(args) == 0 || strings.HasPrefix(args[0], "-") {
|
|
return false
|
|
}
|
|
switch args[0] {
|
|
case "hook":
|
|
runHook(args[1:])
|
|
case "emit":
|
|
runEmit(args[1:])
|
|
case "statusline":
|
|
runStatusline(args[1:])
|
|
case "install":
|
|
runInstall(args[1:])
|
|
case "uninstall":
|
|
runUninstall(args[1:])
|
|
case "replay":
|
|
runReplay(args[1:])
|
|
case "notify":
|
|
runNotify(args[1:])
|
|
case "claude":
|
|
runClaude(args[1:])
|
|
case "kimi", "hermes":
|
|
// The same thing `xscapes claude` is: the agent on top, the scape
|
|
// underneath, its hooks bound as they announce the session.
|
|
runInside(args[1:], args[0])
|
|
case "inside":
|
|
runInside(args[1:], "")
|
|
case "shades":
|
|
runShades(args[1:])
|
|
case "tune":
|
|
runTune(args[1:])
|
|
case "companion":
|
|
os.Exit(cmdCompanion(args[1:]))
|
|
case "scape":
|
|
os.Exit(cmdScape(args[1:]))
|
|
case "help", "-h", "--help":
|
|
usage(os.Stderr)
|
|
default:
|
|
fmt.Fprintf(os.Stderr, "xscapes: unknown command %q\n\n", args[0])
|
|
usage(os.Stderr)
|
|
os.Exit(2)
|
|
}
|
|
return true
|
|
}
|
|
|
|
func usage(w io.Writer) {
|
|
fmt.Fprint(w, `xscapes — a thinking screen for terminal agents
|
|
|
|
xscapes claude run Claude Code INSIDE the scape, in this window
|
|
xscapes claude -beside the older layout: agent in its own tmux pane
|
|
xscapes shades one frame three ways, to judge the 256 smoothing here
|
|
xscapes tune fold real recordings through the reducer and report
|
|
xscapes companion show or set the companion (cat, crab)
|
|
xscapes scape show or set the scape (shore, vista); a running scape switches live
|
|
xscapes inside <cmd> host any command inside the scape
|
|
xscapes render one frame
|
|
xscapes -live run the scape in this terminal
|
|
|
|
xscapes install claude add the hooks to Claude Code (prints a plan; --apply to write)
|
|
xscapes install kimi the same for Kimi Code CLI (~/.kimi-code/config.toml)
|
|
xscapes install hermes the same for Hermes Agent (~/.hermes/config.yaml)
|
|
xscapes uninstall claude|kimi|hermes
|
|
xscapes kimi run Kimi Code CLI inside the scape (after 'install kimi')
|
|
xscapes hermes run Hermes Agent inside the scape (after 'install hermes')
|
|
xscapes emit <kind> send one event by hand (for testing)
|
|
xscapes replay <file> feed a recorded event log to a running scape
|
|
xscapes notify [kind] play the knock sounds (ask, done, worried, or all three)
|
|
xscapes hook [Event] adapter; reads a Claude Code hook payload on stdin
|
|
xscapes statusline adapter for the context moon; chains to your statusline
|
|
|
|
Run 'xscapes help' for the renderer's twenty demo flags as well.
|
|
`)
|
|
}
|
|
|
|
// runEmit sends one event from the command line. This is the whole reason the
|
|
// protocol is a protocol: you can drive the scene without an agent at all,
|
|
// which is how it gets tested and how a third adapter gets written.
|
|
func runEmit(args []string) {
|
|
fs := flag.NewFlagSet("emit", flag.ExitOnError)
|
|
var (
|
|
tool = fs.String("tool", "", "tool name")
|
|
op = fs.String("op", "", "op: read|write|edit|search|shell|web|subagent|todo|mcp")
|
|
target = fs.String("target", "", "file or subject")
|
|
detail = fs.String("detail", "", "short result")
|
|
text = fs.String("text", "", "message text")
|
|
id = fs.String("id", "", "correlation id for tool_start/tool_end")
|
|
agent = fs.String("agent", "", "subagent id")
|
|
ms = fs.Int64("ms", 0, "duration in milliseconds")
|
|
frac = fs.Float64("frac", -1, "0..1 reading (context used)")
|
|
n = fs.Int("n", 0, "todos done, for `emit todo`")
|
|
of = fs.Int("of", 0, "todos in total, for `emit todo`")
|
|
session = fs.String("session", "", "session id (default: $CLAUDE_CODE_SESSION_ID, else current)")
|
|
quiet = fs.Bool("q", false, "print nothing")
|
|
)
|
|
// The kind comes first and Go's flag package stops parsing at the first
|
|
// non-flag argument, so `emit tool_start -tool Read` -- the form printed
|
|
// in the help and the README -- silently dropped every flag and emitted an
|
|
// empty event. Split the kind off before parsing.
|
|
if len(args) == 0 || strings.HasPrefix(args[0], "-") {
|
|
fmt.Fprintln(os.Stderr, "xscapes emit: need a kind, e.g. `xscapes emit tool_start -tool Read`")
|
|
os.Exit(2)
|
|
}
|
|
kind := args[0]
|
|
// REJECT AN UNDEFINED KIND, his ruling of 2026-09-12: "fix it".
|
|
//
|
|
// Without this the word went to the socket, the reducer dropped it, and
|
|
// this command printed "sent ask to session ..." -- a success message for
|
|
// a delivery of nothing. `ask` is the obvious guess, because `xscapes
|
|
// notify ask` takes exactly that word, and three of them are in his log.
|
|
if !event.Known(event.Kind(kind)) {
|
|
fmt.Fprintf(os.Stderr, "xscapes emit: %q is not an event kind.\nkinds: %s\n",
|
|
kind, strings.Join(event.KindNames(), ", "))
|
|
if alt := emitDidYouMean(kind); alt != "" {
|
|
fmt.Fprintf(os.Stderr, "did you mean %q?\n", alt)
|
|
}
|
|
os.Exit(2)
|
|
}
|
|
fs.Parse(args[1:])
|
|
|
|
sess := *session
|
|
if sess == "" {
|
|
sess = event.SessionFromEnv()
|
|
}
|
|
if sess == "" {
|
|
sess = event.Current()
|
|
}
|
|
|
|
e := event.Event{
|
|
Kind: event.Kind(kind), Session: sess, Src: "manual",
|
|
Tool: *tool, Op: event.Op(*op), Target: *target, Detail: *detail,
|
|
Text: *text, ID: *id, Agent: *agent, MS: *ms,
|
|
N: *n, Of: *of,
|
|
}
|
|
if *frac >= 0 {
|
|
f := *frac
|
|
e.Frac = &f
|
|
}
|
|
|
|
viaSock, err := event.Emit(e)
|
|
if *quiet {
|
|
return
|
|
}
|
|
switch {
|
|
case err != nil:
|
|
fmt.Fprintln(os.Stderr, "xscapes:", err)
|
|
os.Exit(1)
|
|
case viaSock:
|
|
fmt.Printf("sent %s to session %s\n", e.Kind, event.Short(sess))
|
|
default:
|
|
// Say so plainly. "It went to the spool" is the difference between
|
|
// "no scape is running" and "the scape is broken", and guessing
|
|
// wrong wastes an afternoon.
|
|
fmt.Printf("spooled %s for session %s (no scape listening)\n", e.Kind, event.Short(sess))
|
|
}
|
|
}
|
|
|
|
// statuslineInput is the part of Claude Code's statusline payload we want.
|
|
//
|
|
// The moon has no other source: no hook payload carries context remaining, and
|
|
// summing the transcript's usage means dividing by a context window we would
|
|
// have to hardcode -- which is measurably wrong on this machine, where the
|
|
// model in use has a 1M window and the obvious constant is 200k.
|
|
// used_percentage is computed by Claude Code against the real window size.
|
|
type statuslineInput struct {
|
|
Context struct {
|
|
UsedPercentage *float64 `json:"used_percentage"`
|
|
WindowSize int `json:"context_window_size"`
|
|
} `json:"context_window"`
|
|
Session string `json:"session_id"`
|
|
}
|
|
|
|
// statuslineEvent turns a statusline payload into the context event, with the
|
|
// model's window riding along. ⚠ NOT the spend: the payload's "total" token
|
|
// fields are the tokens in the window from the most recent response (its
|
|
// docs, read 2026-09-16), which is the moon's variable in another coat; the
|
|
// session's spend is summed off the transcript (internal/spend). Not ok when
|
|
// the payload has no reading.
|
|
func statuslineEvent(in []byte) (event.Event, bool) {
|
|
var s statuslineInput
|
|
if json.Unmarshal(in, &s) != nil || s.Context.UsedPercentage == nil {
|
|
return event.Event{}, false
|
|
}
|
|
sess := s.Session
|
|
if sess == "" {
|
|
sess = event.SessionFromEnv()
|
|
}
|
|
f := *s.Context.UsedPercentage / 100
|
|
return event.Event{
|
|
Kind: event.Context, Session: sess, Src: "claude", Frac: &f,
|
|
Window: s.Context.WindowSize,
|
|
}, true
|
|
}
|
|
|
|
// runStatusline is a pass-through: it reads the statusline payload, emits the
|
|
// context reading, then runs whatever statusline command the user already had
|
|
// and forwards its output verbatim.
|
|
//
|
|
// Chaining rather than replacing is not politeness. Lucas has a statusline he
|
|
// wrote; a tool that silently takes it over to drive a decoration has made a
|
|
// bad trade on his behalf.
|
|
func runStatusline(args []string) {
|
|
defer func() { recover() }()
|
|
|
|
in, _ := io.ReadAll(io.LimitReader(os.Stdin, 1<<20))
|
|
|
|
if e, ok := statuslineEvent(in); ok {
|
|
_, _ = event.Emit(e)
|
|
}
|
|
|
|
// Strip the `--` separator. Without this the chain execs "--" and the
|
|
// user's statusline vanishes -- and the instruction install prints tells
|
|
// them to write exactly that, so following our own documentation deleted
|
|
// the thing we promised to preserve.
|
|
if len(args) > 0 && args[0] == "--" {
|
|
args = args[1:]
|
|
}
|
|
if len(args) == 0 {
|
|
return
|
|
}
|
|
cmd := exec.Command(args[0], args[1:]...)
|
|
cmd.Stdin = bytes.NewReader(in)
|
|
cmd.Stdout = os.Stdout
|
|
cmd.Stderr = os.Stderr
|
|
if err := cmd.Run(); err != nil {
|
|
// stdout here IS the statusline, so a silent failure leaves a blank
|
|
// bar and no clue why. Say something short in the space it owns.
|
|
fmt.Printf("xscapes: statusline chain failed: %v", err)
|
|
}
|
|
}
|
|
|
|
// runNotify plays the knocks on demand. The scape itself is silent unless it
|
|
// is following a real session -- the demo cycles through every state on a
|
|
// timer and would otherwise chime at the user forever -- so this is how the
|
|
// sounds get heard and judged.
|
|
func runNotify(args []string) {
|
|
p := notify.New()
|
|
fmt.Printf("player: %s\n", p.Describe())
|
|
|
|
kinds := []notify.Kind{notify.Ask, notify.Done, notify.Worried}
|
|
if len(args) > 0 {
|
|
switch args[0] {
|
|
case "ask", "needs_input":
|
|
kinds = []notify.Kind{notify.Ask}
|
|
case "done", "finish":
|
|
kinds = []notify.Kind{notify.Done}
|
|
case "worried", "broken":
|
|
kinds = []notify.Kind{notify.Worried}
|
|
default:
|
|
fmt.Fprintf(os.Stderr, "xscapes notify: unknown kind %q (ask, done, worried)\n", args[0])
|
|
os.Exit(2)
|
|
}
|
|
}
|
|
for i, k := range kinds {
|
|
if i > 0 {
|
|
time.Sleep(1400 * time.Millisecond) // let the first finish
|
|
}
|
|
fmt.Printf(" %s\n", k)
|
|
p.Play(k)
|
|
}
|
|
// Play starts the player and returns; exiting immediately would kill it.
|
|
time.Sleep(1400 * time.Millisecond)
|
|
}
|
|
|
|
// runReplay feeds a recorded log back through the bus, which is how the
|
|
// constants in internal/reduce get tuned against a real session instead of
|
|
// against a guess about one.
|
|
func runReplay(args []string) {
|
|
fs := flag.NewFlagSet("replay", flag.ExitOnError)
|
|
speed := fs.Float64("speed", 1, "playback speed multiplier")
|
|
session := fs.String("session", "", "session to replay into")
|
|
fs.Parse(args)
|
|
|
|
if fs.NArg() < 1 {
|
|
fmt.Fprintln(os.Stderr, "xscapes replay: need a file")
|
|
os.Exit(2)
|
|
}
|
|
b, err := os.ReadFile(fs.Arg(0))
|
|
if err != nil {
|
|
fmt.Fprintln(os.Stderr, "xscapes:", err)
|
|
os.Exit(1)
|
|
}
|
|
sess := *session
|
|
if sess == "" {
|
|
sess = event.SessionFromEnv()
|
|
}
|
|
if sess == "" {
|
|
sess = event.Current()
|
|
}
|
|
|
|
var prev int64
|
|
n := 0
|
|
for _, line := range bytes.Split(b, []byte("\n")) {
|
|
if len(bytes.TrimSpace(line)) == 0 {
|
|
continue
|
|
}
|
|
e, err := event.Decode(line)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
if prev > 0 && e.TS > prev && *speed > 0 {
|
|
d := time.Duration(float64(e.TS-prev)/(*speed)) * time.Millisecond
|
|
if d > 5*time.Second {
|
|
d = 5 * time.Second
|
|
}
|
|
time.Sleep(d)
|
|
}
|
|
prev = e.TS
|
|
e.Session, e.TS = sess, 0
|
|
_, _ = event.Emit(e)
|
|
n++
|
|
}
|
|
fmt.Printf("replayed %d events\n", n)
|
|
}
|
|
|
|
// emitDidYouMean catches the two words a person actually types. They are not
|
|
// guesses: `ask` is what `xscapes notify` calls the same moment, and `finish`
|
|
// is the other half of that pair.
|
|
func emitDidYouMean(kind string) string {
|
|
switch strings.ToLower(kind) {
|
|
case "ask", "needs-input", "needsinput", "permission":
|
|
return string(event.NeedsInput)
|
|
case "finish", "complete", "finished":
|
|
return string(event.Done)
|
|
case "start", "session":
|
|
return string(event.SessionStart)
|
|
case "sub", "subagent":
|
|
return string(event.SubStart)
|
|
}
|
|
return ""
|
|
}
|