mirror of
https://github.com/donlucasx/xscapes.git
synced 2026-10-20 08:43:32 +02:00
His ask: "can we add the token spent counter? Maybe it can be a simple number on the top right of the xscape? should we do it xxxx/1M? can xscapes automatically detect the max context window?" The figure comes off the agent's transcript (internal/spend): every assistant line carries the API's usage, a streamed message repeats it once per content block (six times, measured), so a response counts once per message id; subagents' transcripts under the session's directory count too. Claude Code's status payload carries only the WINDOW's tokens from the last response and a dollar figure, per its docs, so the statusline event now carries the window size alone (parked) and the hook forwards the transcript path. The frame loop polls the tally every two seconds, bytes past the last offset only. This session's own transcript: 22.77M tokens over 79 responses, cache reads 97% of it, which is why "/1M" would mislead: the spend passes the window many times over, and the window's fill is the moon's channel already. No denominator. drawTokens, both scapes: row one, one cell in from the right, the balloon's darkened ground, the readout's dim ink; "23M tokens" from 60 columns, the bare number from 40, nothing under the shore's floor (the star-touch sweep at 30x8 went 54 -> 56 with even four cells reserved). Placed stars keep off its cells: the shore re-throws only the darts that land there, so every other star stays where it was (the golden constellation holds); the vista moves such a star one row down. A falling star shows through it: over the arrival sweep 2,232 of 26,694 flights (8.4%) cross the counter's cells on row 1, and blocking them cost his flight floors (88.6 -> 84.3%), so the label yields a cell to a star on it for the frame or two it is there. Hidden under the vista's floor, where the owl's box holds the corner. Tests: TestFormatTokens (four characters at every magnitude; 999,999 is "1.0M"), TestNoPlacedStarSitsUnderTheSpendCounter, TestNoVistaStarSitsUnderTheSpendCounter, TestTheSpendCounterSitsTopRightInEveryScape (both scapes, four sizes, four hours, at least 100 luma over the ground), TestTheTallyCountsEachResponseOnce, TestTheStatuslineCarriesTheWindow. frames.compose is shared by the live frame and the tests. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
347 lines
11 KiB
Go
347 lines
11 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 "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 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 ""
|
|
}
|