mirror of
https://github.com/donlucasx/xscapes.git
synced 2026-10-20 08:43:32 +02:00
The companion test for the near pose OFF skipped whenever Near was not zero, and unset XSCAPES_NEAR has meant rung 2 since 2026-09-11, so it skipped every run; it sets the pose off itself now. The test harness scrubs XSCAPES_HOOKLOG and XSCAPES_EVENTLOG as it scrubs HOME and TRACE, so no test can append to the logs of whoever runs the suite inside a scape. A StopFailure flagged is_interrupt is the user's Esc and becomes an Interrupt, as PostToolUseFailure's flag already did, instead of a worried owl. The installer test skips rather than fails on a box whose Go lives in /usr/bin. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
821 lines
27 KiB
Go
821 lines
27 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"io"
|
|
"net/url"
|
|
"os"
|
|
"path/filepath"
|
|
"regexp"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/donlucasx/xscapes/internal/envx"
|
|
"github.com/donlucasx/xscapes/internal/event"
|
|
"github.com/donlucasx/xscapes/internal/spend"
|
|
)
|
|
|
|
// hookPayload is the subset of Claude Code's hook input we read. The full
|
|
// schema is recorded in notes/claude-hooks-verified.md, extracted from the
|
|
// binary itself rather than from documentation.
|
|
//
|
|
// Everything is optional on purpose. This struct is fed by a program that
|
|
// ships new hook events regularly; a missing field must produce a quieter
|
|
// scene, never an error and never a crash inside the agent's turn.
|
|
type hookPayload struct {
|
|
Event string `json:"hook_event_name"`
|
|
Session string `json:"session_id"`
|
|
CWD string `json:"cwd"`
|
|
// Transcript is the session's JSONL, which every hook names; the spend
|
|
// counter is summed off it (internal/spend).
|
|
Transcript string `json:"transcript_path"`
|
|
AgentID string `json:"agent_id"`
|
|
AgentType string `json:"agent_type"`
|
|
|
|
ToolName string `json:"tool_name"`
|
|
ToolInput json.RawMessage `json:"tool_input"`
|
|
ToolUseID string `json:"tool_use_id"`
|
|
DurationM int64 `json:"duration_ms"`
|
|
|
|
// Kimi Code CLI (0.39) sends the same event names as Claude Code with
|
|
// two keys spelled differently: the call id and the subagent's name.
|
|
// Read off the binary's embedded source, not observed (s35).
|
|
ToolCallID string `json:"tool_call_id"`
|
|
AgentName string `json:"agent_name"`
|
|
|
|
// Hermes Agent (0.14) sends snake_case events of its own, and carries
|
|
// everything past the tool fields under "extra" (agent/shell_hooks.py).
|
|
Extra json.RawMessage `json:"extra"`
|
|
|
|
NotificationType string `json:"notification_type"`
|
|
Message string `json:"message"`
|
|
|
|
// Error is a string from Claude Code and an OBJECT {code, message} from
|
|
// Kimi Code CLI (measured 2026-09-17); errorText reads either.
|
|
Error json.RawMessage `json:"error"`
|
|
IsInterrupt bool `json:"is_interrupt"`
|
|
|
|
LastAssistant string `json:"last_assistant_message"`
|
|
// Prompt is a string from Claude Code and, on Kimi's UserPromptSubmit,
|
|
// an ARRAY of parts [{type: "text", text}] (measured); promptText reads
|
|
// either. As a string field the array failed to parse and the prompt
|
|
// reached the sand with no words.
|
|
Prompt json.RawMessage `json:"prompt"`
|
|
Source string `json:"source"`
|
|
Reason string `json:"reason"`
|
|
Trigger string `json:"trigger"`
|
|
// Decision is PermissionResult's verdict on Kimi ("approved" or
|
|
// "denied"); Claude Code has no such event.
|
|
Decision string `json:"decision"`
|
|
|
|
// Src names whose hooks these are ("claude", "kimi", "hermes"). It comes
|
|
// from the installed command's own argument, never from the payload, so
|
|
// an agent cannot claim to be another one.
|
|
Src string `json:"-"`
|
|
}
|
|
|
|
// promptText is the prompt as one string, whichever shape carried it.
|
|
func (p hookPayload) promptText() string {
|
|
if len(p.Prompt) == 0 {
|
|
return ""
|
|
}
|
|
var s string
|
|
if json.Unmarshal(p.Prompt, &s) == nil {
|
|
return s
|
|
}
|
|
var parts []struct {
|
|
Type string `json:"type"`
|
|
Text string `json:"text"`
|
|
}
|
|
if json.Unmarshal(p.Prompt, &parts) != nil {
|
|
return ""
|
|
}
|
|
var b strings.Builder
|
|
for _, part := range parts {
|
|
if part.Type == "text" && part.Text != "" {
|
|
if b.Len() > 0 {
|
|
b.WriteByte(' ')
|
|
}
|
|
b.WriteString(part.Text)
|
|
}
|
|
}
|
|
return b.String()
|
|
}
|
|
|
|
// errorText is the error's first line, whichever shape carried it.
|
|
func (p hookPayload) errorText() string {
|
|
if len(p.Error) == 0 {
|
|
return ""
|
|
}
|
|
var s string
|
|
if json.Unmarshal(p.Error, &s) == nil {
|
|
return firstLine(s)
|
|
}
|
|
var o struct {
|
|
Message string `json:"message"`
|
|
Code string `json:"code"`
|
|
}
|
|
if json.Unmarshal(p.Error, &o) != nil {
|
|
return ""
|
|
}
|
|
if o.Message != "" {
|
|
return firstLine(o.Message)
|
|
}
|
|
return o.Code
|
|
}
|
|
|
|
// firstQuestion is what AskUserQuestion is asking, for the balloon.
|
|
func firstQuestion(raw json.RawMessage) string {
|
|
var in struct {
|
|
Questions []struct {
|
|
Question string `json:"question"`
|
|
} `json:"questions"`
|
|
}
|
|
if json.Unmarshal(raw, &in) != nil || len(in.Questions) == 0 {
|
|
return ""
|
|
}
|
|
return firstLine(in.Questions[0].Question)
|
|
}
|
|
|
|
// logRaw appends one line to the hook log: when, whose hooks, the command's
|
|
// own arguments, and the payload exactly as it came (as JSON when it is
|
|
// JSON, as a string when it is not, never dropped). Errors are swallowed:
|
|
// the log is a diagnostic and must never fail the agent's turn.
|
|
func logRaw(path, src string, args []string, raw []byte) {
|
|
_ = os.MkdirAll(filepath.Dir(path), 0o700)
|
|
f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
|
|
if err != nil {
|
|
return
|
|
}
|
|
defer f.Close()
|
|
var payload interface{}
|
|
if json.Valid(raw) {
|
|
payload = json.RawMessage(raw)
|
|
} else {
|
|
payload = string(raw)
|
|
}
|
|
line, err := json.Marshal(map[string]interface{}{
|
|
"ts": time.Now().UnixMilli(), "src": src, "argv": args, "payload": payload,
|
|
})
|
|
if err != nil {
|
|
return
|
|
}
|
|
_, _ = f.Write(append(line, '\n'))
|
|
}
|
|
|
|
// needsYouTypes are the notification types that mean a human is actually being
|
|
// asked for something.
|
|
//
|
|
// This is an ALLOW list, and the direction matters. A deny list ("everything
|
|
// except idle_prompt") fails open: the day Claude Code adds a new chatty
|
|
// notification type, the cat starts knocking for it. An allow list fails
|
|
// closed -- a new type is silently ignored until we decide it deserves the
|
|
// bubble, which is the harmless direction to be wrong in.
|
|
var needsYouTypes = map[string]bool{
|
|
"permission_prompt": true,
|
|
"worker_permission_prompt": true,
|
|
"agent_needs_input": true,
|
|
"elicitation_dialog": true,
|
|
"elicitation_url_dialog": true,
|
|
}
|
|
|
|
// maxPayload bounds what we read from a hook. A PostToolUse carrying the full
|
|
// output of a build can be far larger than anything we want to parse.
|
|
const maxPayload = 1 << 20
|
|
|
|
// salvage pulls the flat scalar fields out of a payload that would not parse.
|
|
// Deliberately dumb: it only recognises `"key": "value"` and `"key": number`
|
|
// at any depth, which is enough because every field here is unique by name and
|
|
// appears before the bulky ones.
|
|
func salvage(b []byte, p *hookPayload) {
|
|
str := func(key string) string {
|
|
m := regexp.MustCompile(`"` + key + `"\s*:\s*"((?:[^"\\]|\\.)*)"`).FindSubmatch(b)
|
|
if m == nil {
|
|
return ""
|
|
}
|
|
var out string
|
|
if json.Unmarshal(append(append([]byte{'"'}, m[1]...), '"'), &out) != nil {
|
|
return ""
|
|
}
|
|
return out
|
|
}
|
|
num := func(key string) int64 {
|
|
m := regexp.MustCompile(`"` + key + `"\s*:\s*(-?[0-9]+)`).FindSubmatch(b)
|
|
if m == nil {
|
|
return 0
|
|
}
|
|
var out int64
|
|
if json.Unmarshal(m[1], &out) != nil {
|
|
return 0
|
|
}
|
|
return out
|
|
}
|
|
if p.Event == "" {
|
|
p.Event = str("hook_event_name")
|
|
}
|
|
if p.Session == "" {
|
|
p.Session = str("session_id")
|
|
}
|
|
if p.Transcript == "" {
|
|
p.Transcript = str("transcript_path")
|
|
}
|
|
if p.ToolName == "" {
|
|
p.ToolName = str("tool_name")
|
|
}
|
|
if p.ToolUseID == "" {
|
|
p.ToolUseID = str("tool_use_id")
|
|
}
|
|
if p.AgentID == "" {
|
|
p.AgentID = str("agent_id")
|
|
}
|
|
if p.NotificationType == "" {
|
|
p.NotificationType = str("notification_type")
|
|
}
|
|
if p.DurationM == 0 {
|
|
p.DurationM = num("duration_ms")
|
|
}
|
|
}
|
|
|
|
// runHook is the adapter. It reads one hook payload on stdin, emits zero or
|
|
// more protocol events, and exits 0.
|
|
//
|
|
// Three rules govern everything here, all of them about not damaging the thing
|
|
// we are decorating:
|
|
//
|
|
// - Never write to stdout. On UserPromptSubmit and SessionStart a hook's
|
|
// stdout is fed to the model as context, so a stray print would inject
|
|
// text into the agent's conversation.
|
|
// - Never exit non-zero. A non-zero hook shows stderr to the user, and on
|
|
// some events blocks the turn.
|
|
// - Never take long. This runs on every tool call.
|
|
func runHook(args []string) {
|
|
// Whatever happens below -- a wedged filesystem, a socket that will not
|
|
// answer, a panic -- this process is gone in 250ms and the agent never
|
|
// notices. It is the only guarantee here that does not depend on the
|
|
// rest of the code being correct.
|
|
watchdog := time.AfterFunc(250*time.Millisecond, func() { os.Exit(0) })
|
|
defer watchdog.Stop()
|
|
defer func() { recover() }()
|
|
|
|
b, rerr := io.ReadAll(io.LimitReader(os.Stdin, maxPayload))
|
|
if rerr != nil {
|
|
b = nil
|
|
}
|
|
src := hookSrc(args)
|
|
// XSCAPES_HOOKLOG=<file>: every raw payload, as received, one JSON line
|
|
// each. The instrument for an adapter question -- what does this agent
|
|
// actually fire, in what order -- read off a live run instead of a probe.
|
|
path := logPath(envx.Lookup("HOOKLOG"), "hooks.jsonl")
|
|
if path != "" {
|
|
logRaw(path, src, args, b)
|
|
}
|
|
var socket, spooled, failed int
|
|
for _, e := range hookTranslate(args, b) {
|
|
switch via, err := event.Emit(e); {
|
|
case err != nil:
|
|
failed++
|
|
case via:
|
|
socket++
|
|
default:
|
|
spooled++
|
|
}
|
|
}
|
|
if path != "" {
|
|
logOutcome(path, src, args, socket, spooled, failed)
|
|
}
|
|
}
|
|
|
|
// logOutcome is the hook log's second line for a payload: what became of
|
|
// it. A hook log with six SubagentStarts and a scape with no owlets (his
|
|
// swarm, 2026-09-17) could not say which side lost them; this says whether
|
|
// each left the hook at all, and by which door.
|
|
func logOutcome(path, src string, args []string, socket, spooled, failed int) {
|
|
f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
|
|
if err != nil {
|
|
return
|
|
}
|
|
defer f.Close()
|
|
line, err := json.Marshal(map[string]interface{}{
|
|
"ts": time.Now().UnixMilli(), "src": src, "argv": args,
|
|
"emitted": map[string]int{"socket": socket, "spool": spooled, "failed": failed},
|
|
})
|
|
if err != nil {
|
|
return
|
|
}
|
|
_, _ = f.Write(append(line, '\n'))
|
|
}
|
|
|
|
// hookSrc is whose hooks these are: `xscapes hook <Event> [agent]`, the
|
|
// installer having written which agent's hooks they are, because Kimi's
|
|
// event names are Claude Code's. It never comes from the payload, so an
|
|
// agent cannot claim to be another one.
|
|
func hookSrc(args []string) string {
|
|
if len(args) > 1 && args[1] != "" {
|
|
return args[1]
|
|
}
|
|
return "claude"
|
|
}
|
|
|
|
// hookTranslate is the hook command's whole translation, as a function of
|
|
// what it was given: the raw payload and its own arguments. runHook feeds
|
|
// it stdin; a replay feeds it a hook log, so what a live run produced can
|
|
// be folded again through the same code (kimilog_replay_test.go).
|
|
func hookTranslate(args []string, b []byte) []event.Event {
|
|
var p hookPayload
|
|
if len(b) > 0 && json.Unmarshal(b, &p) != nil {
|
|
// The payload did not parse -- almost always because a big
|
|
// tool_response pushed it past the cap and the read cut it
|
|
// mid-object. Dropping it whole is the expensive failure: the
|
|
// tool_use_id goes with it, so the matching tool_start is never
|
|
// closed and the sea stays up forever. The scalar fields we need
|
|
// sit near the front, ahead of the payload that made it big.
|
|
salvage(b, &p)
|
|
}
|
|
if p.Event == "" && len(args) > 0 {
|
|
// The installed command names the event too, so a payload we could
|
|
// not parse still produces the right kind of event.
|
|
p.Event = args[0]
|
|
}
|
|
src := hookSrc(args)
|
|
if p.Session == "" {
|
|
p.Session = event.SessionFromEnv()
|
|
}
|
|
p.Src = src
|
|
// Kimi's hooks carry no transcript path; its session directory stands in
|
|
// for one (internal/spend/kimi.go), resolved on every event because the
|
|
// index that names it is written a moment after SessionStart.
|
|
if src == "kimi" && p.Transcript == "" {
|
|
p.Transcript = spend.KimiSessionDir(p.Session)
|
|
}
|
|
// Kimi spells two keys differently; fold them in so translate reads one
|
|
// shape.
|
|
if p.ToolUseID == "" {
|
|
p.ToolUseID = p.ToolCallID
|
|
}
|
|
if p.AgentID == "" && p.AgentName != "" {
|
|
p.AgentID = p.AgentName
|
|
}
|
|
if p.AgentType == "" {
|
|
p.AgentType = p.AgentName
|
|
}
|
|
var out []event.Event
|
|
for _, e := range translate(p) {
|
|
e.Session = p.Session
|
|
e.Src = src
|
|
e.Transcript = p.Transcript
|
|
if e.Agent == "" {
|
|
e.Agent = p.AgentID
|
|
}
|
|
if e.AgentType == "" {
|
|
e.AgentType = p.AgentType
|
|
}
|
|
out = append(out, e)
|
|
}
|
|
return out
|
|
}
|
|
|
|
// hermesExtra is what Hermes puts under "extra": every keyword argument the
|
|
// hook was fired with, minus the tool fields. Names from
|
|
// website/docs/user-guide/features/hooks.md in the installed checkout (0.14).
|
|
type hermesExtra struct {
|
|
UserMessage string `json:"user_message"`
|
|
AssistantResponse string `json:"assistant_response"`
|
|
DurationMS int64 `json:"duration_ms"`
|
|
ChildRole string `json:"child_role"`
|
|
ChildStatus string `json:"child_status"`
|
|
ChildSessionID string `json:"child_session_id"`
|
|
Command string `json:"command"`
|
|
Reason string `json:"reason"`
|
|
}
|
|
|
|
func (p hookPayload) hermes() hermesExtra {
|
|
var x hermesExtra
|
|
if len(p.Extra) > 0 {
|
|
_ = json.Unmarshal(p.Extra, &x)
|
|
}
|
|
return x
|
|
}
|
|
|
|
// translate maps one hook payload to protocol events.
|
|
func translate(p hookPayload) []event.Event {
|
|
switch p.Event {
|
|
|
|
case "SessionStart":
|
|
_ = event.SetCurrent(p.Session)
|
|
// Source rides along so the reducer can tell a new conversation from
|
|
// an auto-compaction re-announcing the same one mid-turn.
|
|
return []event.Event{{Kind: event.SessionStart, Text: p.Source}}
|
|
|
|
case "SessionEnd":
|
|
return []event.Event{{Kind: event.SessionEnd, Text: p.Reason}}
|
|
|
|
case "UserPromptSubmit":
|
|
return []event.Event{{Kind: event.Prompt, Text: p.promptText()}}
|
|
|
|
case "PreToolUse":
|
|
op, target := classify(p.ToolName, p.ToolInput)
|
|
start := event.Event{
|
|
Kind: event.ToolStart, Op: op, Tool: p.ToolName,
|
|
Target: target, ID: p.ToolUseID,
|
|
}
|
|
// Kimi's question to the user is a plain tool call and fires no
|
|
// Notification (measured 2026-09-17), so the tool starting IS the
|
|
// ask. After the start, because a tool starting clears the balloon.
|
|
if p.Src == "kimi" && p.ToolName == "AskUserQuestion" {
|
|
return []event.Event{start, {Kind: event.NeedsInput, Text: firstQuestion(p.ToolInput)}}
|
|
}
|
|
return []event.Event{start}
|
|
|
|
case "PostToolUse":
|
|
op, target := classify(p.ToolName, p.ToolInput)
|
|
e := event.Event{
|
|
Kind: event.ToolEnd, Op: op, Tool: p.ToolName,
|
|
Target: target, ID: p.ToolUseID, MS: p.DurationM,
|
|
}
|
|
// A checklist is its own channel, not a flavour of tool use, so it gets
|
|
// its own event rather than counts bolted onto this one. The protocol
|
|
// has carried `todo` with n/of since the beginning and nothing has ever
|
|
// emitted it: TodoWrite was classified as an op and stopped there, so
|
|
// the reducer's Todo case could only ever be reached by hand from
|
|
// `xscapes emit`. Two halves of one feature that were never joined.
|
|
if done, total, ok := todoCounts(p.ToolName, p.ToolInput); ok {
|
|
return []event.Event{e, {Kind: event.Todo, N: done, Of: total}}
|
|
}
|
|
// A question answered is the answer: the tool completing means the
|
|
// user replied, so the ask comes down now and not at the next tool
|
|
// start (his 2026-09-17 run: 19 s of a stale balloon after he had
|
|
// answered). A no-op when no ask is up.
|
|
if p.ToolName == "AskUserQuestion" {
|
|
return []event.Event{e, {Kind: event.Answered, Text: "answered"}}
|
|
}
|
|
return []event.Event{e}
|
|
|
|
case "PostToolUseFailure":
|
|
op, target := classify(p.ToolName, p.ToolInput)
|
|
// An interrupt is the user pressing escape. Treating that as a
|
|
// failure would put the cat in the worried pose every time Lucas
|
|
// changes his mind, which is both wrong and the fastest way to
|
|
// teach someone to ignore the signal.
|
|
kind := event.Error
|
|
if p.IsInterrupt {
|
|
kind = event.ToolEnd
|
|
}
|
|
return []event.Event{{
|
|
Kind: kind, Op: op, Tool: p.ToolName, Target: target,
|
|
ID: p.ToolUseID, MS: p.DurationM, Detail: p.errorText(),
|
|
}}
|
|
|
|
case "PermissionRequest":
|
|
op, target := classify(p.ToolName, p.ToolInput)
|
|
return []event.Event{{
|
|
Kind: event.NeedsInput, Op: op, Tool: p.ToolName, Target: target,
|
|
Text: "allow " + p.ToolName + "?",
|
|
}}
|
|
|
|
case "PermissionResult":
|
|
// Kimi's word that the approval was answered, either way: the ask
|
|
// comes down now, not at the next tool start or the turn's end.
|
|
return []event.Event{{Kind: event.Answered, Text: p.Decision}}
|
|
|
|
case "Notification":
|
|
// The whole 60-second-nag problem, solved by reading a field.
|
|
// idle_prompt IS the nag: 2,220 of them at exactly sixty seconds
|
|
// after Stop in the measured log. It is not in the allow list, so
|
|
// it lands here and is dropped.
|
|
switch {
|
|
case needsYouTypes[p.NotificationType]:
|
|
return []event.Event{{Kind: event.NeedsInput, Text: firstLine(p.Message)}}
|
|
case p.NotificationType == "agent_completed":
|
|
return []event.Event{{Kind: event.Done, Text: firstLine(p.Message)}}
|
|
}
|
|
return nil
|
|
|
|
case "Stop":
|
|
return []event.Event{{Kind: event.Done, Text: firstLine(p.LastAssistant)}}
|
|
|
|
case "SubagentStart":
|
|
return []event.Event{{
|
|
Kind: event.SubStart, Op: event.OpSub,
|
|
Agent: p.AgentID, AgentType: p.AgentType,
|
|
}}
|
|
|
|
case "SubagentStop":
|
|
return []event.Event{{
|
|
Kind: event.SubEnd, Op: event.OpSub,
|
|
Agent: p.AgentID, AgentType: p.AgentType,
|
|
}}
|
|
|
|
case "PreCompact":
|
|
return []event.Event{{Kind: event.Compact, Text: p.Trigger}}
|
|
|
|
// Kimi Code CLI. Its event list is Claude Code's plus a few; the ones
|
|
// that mean something here:
|
|
case "StopFailure":
|
|
// The turn ended in a failure of the agent itself (a provider error,
|
|
// a model that would not answer): the companion worries, and the
|
|
// sand says why. Interrupt is the user pressing escape and stays
|
|
// silent, as PostToolUseFailure's is_interrupt does; the flag is
|
|
// checked here too, or an Esc would be a worried owl.
|
|
if p.IsInterrupt {
|
|
return []event.Event{{Kind: event.Interrupt}}
|
|
}
|
|
return []event.Event{{Kind: event.Error, Detail: p.errorText()}}
|
|
|
|
case "Interrupt":
|
|
// Esc. Kimi fires this IN PLACE OF Stop (measured), so without it
|
|
// the turn would stay open until TurnSilence. Quiet, his ruling of
|
|
// 2026-09-17: the person who pressed the key is already here.
|
|
return []event.Event{{Kind: event.Interrupt, Text: p.Reason}}
|
|
|
|
// Hermes Agent. pre_llm_call and post_llm_call fire ONCE PER TURN
|
|
// (hooks.md: "before the tool-calling loop" / "after the tool-calling
|
|
// loop completes"), which is what makes them the prompt and the done.
|
|
case "on_session_start":
|
|
_ = event.SetCurrent(p.Session)
|
|
return []event.Event{{Kind: event.SessionStart, Text: "startup"}}
|
|
case "on_session_reset":
|
|
_ = event.SetCurrent(p.Session)
|
|
return []event.Event{{Kind: event.SessionStart, Text: "clear"}}
|
|
case "on_session_end", "on_session_finalize":
|
|
return []event.Event{{Kind: event.SessionEnd}}
|
|
case "pre_llm_call":
|
|
return []event.Event{{Kind: event.Prompt, Text: firstLine(p.hermes().UserMessage)}}
|
|
case "post_llm_call":
|
|
return []event.Event{{Kind: event.Done, Text: firstLine(p.hermes().AssistantResponse)}}
|
|
case "pre_tool_call":
|
|
op, target := classify(p.ToolName, p.ToolInput)
|
|
return []event.Event{{Kind: event.ToolStart, Op: op, Tool: p.ToolName, Target: target}}
|
|
case "post_tool_call":
|
|
op, target := classify(p.ToolName, p.ToolInput)
|
|
return []event.Event{{Kind: event.ToolEnd, Op: op, Tool: p.ToolName, Target: target, MS: p.hermes().DurationMS}}
|
|
case "pre_approval_request":
|
|
op, target := classify(p.ToolName, p.ToolInput)
|
|
return []event.Event{{Kind: event.NeedsInput, Op: op, Tool: p.ToolName, Target: target, Text: "allow " + p.ToolName + "?"}}
|
|
case "subagent_stop":
|
|
// Hermes has no subagent START event, only this. A litter that
|
|
// never gets a start never shows, so the stop is announced as a
|
|
// start and an end together: the reducer's dwell (KittenDwell)
|
|
// keeps the arrival on screen for a minute, which is the same
|
|
// treatment a subagent that lived seven seconds gets from Claude.
|
|
x := p.hermes()
|
|
id := x.ChildSessionID
|
|
if id == "" {
|
|
id = x.ChildRole
|
|
}
|
|
return []event.Event{
|
|
{Kind: event.SubStart, Op: event.OpSub, Agent: id, AgentType: x.ChildRole},
|
|
{Kind: event.SubEnd, Op: event.OpSub, Agent: id, AgentType: x.ChildRole},
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// todoCounts reads a TodoWrite call and reports how much of the list is done.
|
|
//
|
|
// ⚠ The payload shape here is INFERRED, not measured. notes/claude-hooks-verified.md
|
|
// covers every hook this program uses and says nothing about TodoWrite's
|
|
// tool_input, because in 13,682 recorded tool events and every transcript since
|
|
// the hook was installed, TodoWrite has been called exactly zero times. So this
|
|
// is written to fail quiet rather than fail wrong: an unrecognised shape
|
|
// reports ok=false and the sky shows nothing, which is the same as today.
|
|
//
|
|
// It counts "completed" and treats everything else as outstanding, so a status
|
|
// value nobody anticipated lands on "not done" rather than on "done".
|
|
func todoCounts(tool string, in json.RawMessage) (done, total int, ok bool) {
|
|
if (tool != "TodoWrite" && tool != "TodoList") || len(in) == 0 {
|
|
return 0, 0, false
|
|
}
|
|
var p struct {
|
|
Todos []struct {
|
|
Status string `json:"status"`
|
|
} `json:"todos"`
|
|
}
|
|
if err := json.Unmarshal(in, &p); err != nil || len(p.Todos) == 0 {
|
|
return 0, 0, false
|
|
}
|
|
for _, t := range p.Todos {
|
|
// Claude Code says "completed"; Kimi's TodoList says "done".
|
|
if strings.EqualFold(t.Status, "completed") || strings.EqualFold(t.Status, "done") {
|
|
done++
|
|
}
|
|
}
|
|
return done, len(p.Todos), true
|
|
}
|
|
|
|
// toolInput is the handful of tool_input keys that name a subject. Claude Code
|
|
// tools are not uniform about it, so this is a union rather than a per-tool
|
|
// table -- a new tool with a file_path gets a sensible sand line for free.
|
|
type toolInput struct {
|
|
FilePath string `json:"file_path"`
|
|
Path string `json:"path"`
|
|
NotebookP string `json:"notebook_path"`
|
|
Pattern string `json:"pattern"`
|
|
Command string `json:"command"`
|
|
URL string `json:"url"`
|
|
Query string `json:"query"`
|
|
Description string `json:"description"`
|
|
SubagentTyp string `json:"subagent_type"`
|
|
Prompt string `json:"prompt"`
|
|
// Questions is AskUserQuestion's input, Claude Code's and Kimi's alike.
|
|
Questions []struct {
|
|
Question string `json:"question"`
|
|
} `json:"questions"`
|
|
}
|
|
|
|
// classify puts a tool into one of the coarse ops and finds its subject.
|
|
//
|
|
// This is not the per-tool taxonomy the brief killed: nothing downstream keys
|
|
// a *visual* off the op. It exists so the sand can say "read" rather than
|
|
// "Read", and so the reducer can tell a shell command from a file read when
|
|
// deciding how long the water stays up.
|
|
func classify(tool string, raw json.RawMessage) (event.Op, string) {
|
|
var in toolInput
|
|
if len(raw) > 0 {
|
|
_ = json.Unmarshal(raw, &in)
|
|
}
|
|
|
|
subject := func() string {
|
|
switch {
|
|
case in.FilePath != "":
|
|
return shorten(in.FilePath)
|
|
case in.NotebookP != "":
|
|
return shorten(in.NotebookP)
|
|
case in.Path != "":
|
|
return shorten(in.Path)
|
|
case in.Pattern != "":
|
|
return in.Pattern
|
|
case in.URL != "":
|
|
return safeURL(in.URL)
|
|
case in.Query != "":
|
|
return in.Query
|
|
}
|
|
return ""
|
|
}
|
|
|
|
switch tool {
|
|
case "Read", "NotebookRead":
|
|
return event.OpRead, subject()
|
|
case "Write":
|
|
return event.OpWrite, subject()
|
|
case "Edit", "NotebookEdit", "MultiEdit":
|
|
return event.OpEdit, subject()
|
|
case "Grep", "Glob", "LS":
|
|
return event.OpSearch, subject()
|
|
case "Bash", "BashOutput", "KillShell":
|
|
// The command, not its arguments. A shell line is the one tool input
|
|
// that routinely contains a secret, and this string is written to a
|
|
// file and painted on a screen.
|
|
return event.OpShell, program(in.Command)
|
|
case "WebFetch":
|
|
return event.OpWeb, safeURL(in.URL)
|
|
case "WebSearch":
|
|
// A search query is the user's words, not a credential, but it is also
|
|
// not something to write across the beach in full.
|
|
return event.OpWeb, trimTo(in.Query, 40)
|
|
case "Agent", "Task", "AgentSwarm":
|
|
// Kimi's AgentSwarm starts one sub-agent per item (its schema: "Each
|
|
// item launches one new subagent"; seven in his first swarm).
|
|
s := in.SubagentTyp
|
|
if s == "" {
|
|
s = firstLine(in.Description)
|
|
}
|
|
return event.OpSub, s
|
|
case "TodoWrite", "TodoList":
|
|
return event.OpTodo, ""
|
|
case "AskUserQuestion":
|
|
if len(in.Questions) > 0 {
|
|
return event.OpOther, trimTo(firstLine(in.Questions[0].Question), 40)
|
|
}
|
|
return event.OpOther, ""
|
|
}
|
|
if strings.HasPrefix(tool, "mcp__") {
|
|
return event.OpMCP, strings.TrimPrefix(tool, "mcp__")
|
|
}
|
|
// Hermes Agent's tools (tools/*.py in the installed checkout). The
|
|
// input key names are inferred from the tool names, unverified against a
|
|
// live payload; a miss costs the subject, never the verb.
|
|
switch tool {
|
|
case "read_file":
|
|
return event.OpRead, subject()
|
|
case "write_file":
|
|
return event.OpWrite, subject()
|
|
case "patch":
|
|
return event.OpEdit, subject()
|
|
case "search_files", "session_search":
|
|
return event.OpSearch, subject()
|
|
case "terminal", "process":
|
|
return event.OpShell, program(in.Command)
|
|
case "web_search", "x_search":
|
|
return event.OpWeb, trimTo(in.Query, 40)
|
|
case "web_extract":
|
|
return event.OpWeb, safeURL(in.URL)
|
|
case "delegate_task", "mixture_of_agents":
|
|
return event.OpSub, firstLine(in.Description)
|
|
case "todo":
|
|
return event.OpTodo, ""
|
|
}
|
|
return event.OpOther, subject()
|
|
}
|
|
|
|
// shorten makes a path readable in a beach's worth of columns: relative to the
|
|
// working directory when it is under it, and ~ for home.
|
|
func shorten(p string) string {
|
|
if wd, err := os.Getwd(); err == nil {
|
|
if rel, err := filepath.Rel(wd, p); err == nil && !strings.HasPrefix(rel, "..") {
|
|
return rel
|
|
}
|
|
}
|
|
if home, err := os.UserHomeDir(); err == nil && strings.HasPrefix(p, home) {
|
|
return "~" + strings.TrimPrefix(p, home)
|
|
}
|
|
return p
|
|
}
|
|
|
|
// program extracts the command name from a shell line and nothing else.
|
|
// `psql "postgresql://user:password@host"` must reach the sand as `psql`.
|
|
//
|
|
// The first token is NOT the program often enough to matter: the single most
|
|
// common way a secret appears literally in a shell line is the leading
|
|
// assignment form, `PGPASSWORD=hunter2 psql ...`, and taking token zero
|
|
// published it verbatim. Leading assignments, and the wrappers that usually
|
|
// carry them, are skipped rather than truncated -- half a secret is a secret.
|
|
func program(cmd string) string {
|
|
for _, tok := range strings.Fields(cmd) {
|
|
if isAssignment(tok) {
|
|
continue
|
|
}
|
|
switch tok {
|
|
case "sudo", "env", "command", "nohup", "time", "exec", "doas":
|
|
continue
|
|
}
|
|
if i := strings.LastIndex(tok, "/"); i >= 0 && i+1 < len(tok) {
|
|
tok = tok[i+1:]
|
|
}
|
|
if len(tok) > 24 {
|
|
tok = tok[:24]
|
|
}
|
|
return tok
|
|
}
|
|
// Nothing but assignments and wrappers. Naming the shape is safe; naming
|
|
// the variable is not, because the name is often the giveaway.
|
|
if strings.TrimSpace(cmd) != "" {
|
|
return "env"
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// isAssignment reports whether tok is a leading NAME=VALUE.
|
|
func isAssignment(tok string) bool {
|
|
i := strings.IndexByte(tok, '=')
|
|
if i <= 0 {
|
|
return false
|
|
}
|
|
for j, r := range tok[:i] {
|
|
ok := r == '_' || (r >= 'A' && r <= 'Z') || (r >= 'a' && r <= 'z') || (j > 0 && r >= '0' && r <= '9')
|
|
if !ok {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
// safeURL keeps enough of a URL to say where the agent went and drops
|
|
// everything that carries a credential: the query string (access tokens live
|
|
// there), the fragment, and any userinfo. It is also the more legible line.
|
|
func safeURL(raw string) string {
|
|
u, err := url.Parse(raw)
|
|
if err != nil || u.Host == "" {
|
|
// Not parseable as a URL: keep the scheme-ish head only.
|
|
if i := strings.IndexAny(raw, "?#"); i >= 0 {
|
|
raw = raw[:i]
|
|
}
|
|
return trimTo(raw, 60)
|
|
}
|
|
out := u.Host
|
|
if p := strings.TrimPrefix(u.Path, "/"); p != "" {
|
|
if i := strings.IndexByte(p, '/'); i >= 0 {
|
|
p = p[:i]
|
|
}
|
|
out += "/" + p
|
|
}
|
|
return trimTo(out, 60)
|
|
}
|
|
|
|
func trimTo(s string, n int) string {
|
|
if len([]rune(s)) <= n {
|
|
return s
|
|
}
|
|
return string([]rune(s)[:n-1]) + "…"
|
|
}
|
|
|
|
func firstLine(s string) string {
|
|
s = strings.TrimSpace(s)
|
|
if i := strings.IndexAny(s, "\r\n"); i >= 0 {
|
|
s = s[:i]
|
|
}
|
|
if len([]rune(s)) > 120 {
|
|
s = string([]rune(s)[:119]) + "…"
|
|
}
|
|
return s
|
|
}
|