package library import ( "bytes" "encoding/json" "errors" "fmt" "os" "path/filepath" "regexp" "slices" "strconv" "strings" "github.com/pelletier/go-toml/v2" "github.com/tidwall/gjson" "github.com/tidwall/jsonc" "github.com/yetone/magpie/internal/edit" ) // Hooks (#1790) are commands an agent runs at a point of its turn: when // it ends (a phone notification), after it edits a file (a formatter). // One is kept once and written into each agent ticked for it, in that // agent's own file and shape: // // Claude Code /settings.json hooks.: [{matcher, hooks: [{type, command, timeout}]}] // Codex /hooks.json the same shape // Gemini CLI ~/.gemini/settings.json the same shape, timeout in ms // Cursor ~/.cursor/hooks.json hooks.: [{command, timeout, matcher}], version 1 // // A portable event ("turn-end") is the same moment in each agent, under // each one's own name; an agent's own event ("codex:PermissionRequest") // is given to that agent alone. What magpie wrote is recorded entry by // entry (Applied.Hooks), and only an entry still exactly as magpie wrote // it is ever taken out: one the user changed is theirs from then on, and // the user's own hooks around it stay as they are. // Hook is a command the agents ticked for it run at Event. type Hook struct { Name string `json:"name"` // Event is a portable event (HookEvents), or an agent's own, // ":" as that agent names it Event string `json:"event"` // Matcher narrows a tool event to some tools: for a portable event // "shell" or "edit" (each agent's own tool names for them), for an // agent's own event the agent's own matcher; "" is every tool Matcher string `json:"matcher,omitempty"` Command string `json:"command"` Timeout int `json:"timeout,omitempty"` // seconds; 0 is the agent's own Agents []string `json:"agents"` } // HookEntry is one entry magpie wrote into an agent's hooks: the hook it // is of, the agent's event it is under, and the entry exactly as written. type HookEntry struct { Name string `json:"name"` Event string `json:"event"` Entry json.RawMessage `json:"entry"` } // HookEvents are the portable events, in the order the page offers them. var HookEvents = []string{"turn-end", "after-tool", "before-tool", "prompt", "session-start"} // HookTools are the kinds of tools a portable tool event can be narrowed to. var HookTools = []string{"shell", "edit"} // hookSpec is how one agent keeps its hooks. type hookSpec struct { path string events map[string]string // portable → the agent's own native []string // every event the agent has tools map[string]string // shell, edit → the agent's matcher for them flat bool // Cursor: an entry is the command itself, not a group of them ms bool // Gemini: timeouts in milliseconds } // hookAgents are the agents magpie can give hooks to. var hookAgents = []string{"claude", "codex", "cursor", "gemini"} // toolEvents are the portable events that take a matcher. var toolEvents = []string{"after-tool", "before-tool"} // hookSpecOf is how t keeps its hooks, or why magpie can't give it any. func hookSpecOf(t *Target) (*hookSpec, string) { if t.Agent.WSL != "" { return nil, fmt.Sprintf("magpie gives hooks only to agents on this computer, not yet to %s in WSL", t.Agent.Name) } switch t.Agent.ID { case "claude": return &hookSpec{ path: filepath.Join(claudeDir(), "settings.json"), events: map[string]string{"turn-end": "Stop", "after-tool": "PostToolUse", "before-tool": "PreToolUse", "prompt": "UserPromptSubmit", "session-start": "SessionStart"}, native: []string{"PreToolUse", "PostToolUse", "PostToolUseFailure", "PermissionRequest", "Notification", "UserPromptSubmit", "Stop", "SubagentStart", "SubagentStop", "PreCompact", "SessionStart", "SessionEnd"}, tools: map[string]string{"shell": "Bash", "edit": "Edit|Write|MultiEdit"}, }, "" case "codex": // codex-rs/hooks: hooks.json beside config.toml, whose events are // HookEventName's return &hookSpec{ path: filepath.Join(codexDir(), "hooks.json"), events: map[string]string{"turn-end": "Stop", "after-tool": "PostToolUse", "before-tool": "PreToolUse", "prompt": "UserPromptSubmit", "session-start": "SessionStart"}, native: []string{"PreToolUse", "PermissionRequest", "PostToolUse", "PreCompact", "PostCompact", "SessionStart", "SessionEnd", "UserPromptSubmit", "SubagentStart", "SubagentStop", "Stop", "Interrupt"}, tools: map[string]string{"shell": "Bash", "edit": "apply_patch"}, }, "" case "gemini": // gemini-cli packages/core/src/hooks/types.ts, HookEventName return &hookSpec{ path: filepath.Join(home(), ".gemini", "settings.json"), events: map[string]string{"turn-end": "AfterAgent", "after-tool": "AfterTool", "before-tool": "BeforeTool", "prompt": "BeforeAgent", "session-start": "SessionStart"}, native: []string{"BeforeTool", "AfterTool", "BeforeAgent", "AfterAgent", "Notification", "SessionStart", "SessionEnd", "PreCompress", "BeforeModel", "AfterModel", "BeforeToolSelection"}, tools: map[string]string{"shell": "run_shell_command", "edit": "write_file|replace"}, ms: true, }, "" case "cursor": return &hookSpec{ path: filepath.Join(home(), ".cursor", "hooks.json"), events: map[string]string{"turn-end": "stop", "after-tool": "postToolUse", "before-tool": "preToolUse", "prompt": "beforeSubmitPrompt", "session-start": "sessionStart"}, native: []string{"beforeShellExecution", "afterShellExecution", "beforeMCPExecution", "afterMCPExecution", "beforeReadFile", "afterFileEdit", "beforeSubmitPrompt", "stop", "afterAgentResponse", "afterAgentThought", "sessionStart", "sessionEnd", "preToolUse", "postToolUse", "postToolUseFailure", "subagentStart", "subagentStop", "preCompact"}, tools: map[string]string{"shell": "Shell", "edit": "Write"}, flat: true, }, "" } return nil, fmt.Sprintf("%s has no hooks magpie can write", t.Agent.Name) } // event is the agent's own name for h's event, or why it has none. func (sp *hookSpec) event(agent string, h *Hook) (string, error) { if a, ev, ok := strings.Cut(h.Event, ":"); ok { if a != agent { return "", fmt.Errorf("%s is an event of another agent's", ev) } if !slices.Contains(sp.native, ev) { return "", fmt.Errorf("it has no event called %s", ev) } return ev, nil } if ev := sp.events[h.Event]; ev != "" { return ev, nil } return "", fmt.Errorf("no event called %s", h.Event) } // entry is h as the agent's file holds it, under event ev. func (sp *hookSpec) entry(h *Hook) json.RawMessage { m := h.Matcher if !strings.Contains(h.Event, ":") { m = sp.tools[h.Matcher] // "" for none, and for an event that takes no matcher } timeout := h.Timeout if sp.ms { timeout *= 1000 } var v any if sp.flat { v = struct { Command string `json:"command"` Timeout int `json:"timeout,omitempty"` Matcher string `json:"matcher,omitempty"` }{h.Command, timeout, m} } else { type cmd struct { Type string `json:"type"` Command string `json:"command"` Timeout int `json:"timeout,omitempty"` } v = struct { Matcher string `json:"matcher,omitempty"` Hooks []cmd `json:"hooks"` }{m, []cmd{{"command", h.Command, timeout}}} } b, _ := json.Marshal(v) return b } func (h *Hook) check() error { if err := checkName("hook", h.Name); err != nil { return err } if strings.TrimSpace(h.Command) == "" { return errors.New("a hook needs a command to run") } if h.Timeout < 0 || h.Timeout > 86400 { return errors.New("a hook's timeout is between 0 (the agent's own) and 86400 seconds") } if a, ev, ok := strings.Cut(h.Event, ":"); ok { if !slices.Contains(hookAgents, a) || ev == "" { return fmt.Errorf("no event called %s", h.Event) } for _, x := range h.Agents { if x != a { return fmt.Errorf("%s is %s's own event: only it can be given this hook", ev, a) } } return nil } if !slices.Contains(HookEvents, h.Event) { return fmt.Errorf("no event called %s", h.Event) } if h.Matcher != "" && (!slices.Contains(toolEvents, h.Event) || !slices.Contains(HookTools, h.Matcher)) { return fmt.Errorf("%s can't be narrowed to %s", h.Event, h.Matcher) } return nil } func (l *Library) hook(name string) *Hook { for _, h := range l.Hooks { if h.Name == name { return h } } return nil } // canonical is a JSON value written one way, its keys sorted, for two // entries to be told the same however each was spaced. func canonical(raw []byte) string { var v any d := json.NewDecoder(bytes.NewReader(raw)) d.UseNumber() if d.Decode(&v) != nil { return string(raw) } b, _ := json.Marshal(v) return string(b) } // readHooksFile is an agent's hooks file as JSON, "" for one not there. One // that can't be read, or isn't JSON, is an error: what it holds is unknown, // never nothing to keep. func readHooksFile(path string) ([]byte, error) { raw, err := edit.Read(path) if err != nil { return nil, err } raw = edit.TrimBOM(raw) if len(bytes.TrimSpace(raw)) == 0 { return nil, nil } j := jsonc.ToJSON(raw) if !json.Valid(j) { return nil, fmt.Errorf("%s isn't JSON magpie can read: it is left as it is", path) } if !gjson.ParseBytes(j).IsObject() { return nil, fmt.Errorf("%s isn't a JSON object: it is left as it is", path) } return j, nil } // hookList is the list the file has under hooks.. func hookList(doc []byte, path, ev string) ([]json.RawMessage, error) { r := gjson.GetBytes(doc, "hooks."+ev) if !r.Exists() { return nil, nil } if !r.IsArray() { return nil, fmt.Errorf("%s: hooks.%s isn't a list", path, ev) } var list []json.RawMessage if err := json.Unmarshal([]byte(r.Raw), &list); err != nil { return nil, fmt.Errorf("%s: hooks.%s: %w", path, ev, err) } return list, nil } // syncHooks writes into t the hooks the library gives it and takes out the // ones it no longer does: only entries exactly as magpie wrote them, the // user's own hooks, before and after them, left where they are. func (l *Library) syncHooks(t *Target, b *backups, res *Result) { id := t.Agent.ID a := l.applied(id) var want []*Hook for _, h := range l.Hooks { if slices.Contains(h.Agents, id) { want = append(want, h) } } if len(a.Hooks) == 0 && len(want) == 0 { return } sp, why := hookSpecOf(t) if sp == nil { for _, h := range want { res.fail(id, "hook:"+h.Name, errors.New(why)) } return } failAll := func(err error) { for _, h := range want { res.fail(id, "hook:"+h.Name, err) } if len(want) == 0 { res.fail(id, "hooks", err) } } doc, err := readHooksFile(sp.path) if err != nil { failAll(err) return } lists := map[string][]json.RawMessage{} listOf := func(ev string) ([]json.RawMessage, error) { if x, ok := lists[ev]; ok { return x, nil } x, err := hookList(doc, sp.path, ev) if err == nil { lists[ev] = x } return x, err } type wanted struct { h *Hook ev string entry json.RawMessage done bool } var ws []*wanted for _, h := range want { ev, err := sp.event(id, h) if err != nil { res.fail(id, "hook:"+h.Name, err) continue } if _, err := listOf(ev); err != nil { res.fail(id, "hook:"+h.Name, err) continue } ws = append(ws, &wanted{h: h, ev: ev, entry: sp.entry(h)}) } claimed := map[string]map[int]bool{} // event → the entries magpie's records found find := func(ev string, entry json.RawMessage) int { c := canonical(entry) for i, e := range lists[ev] { if !claimed[ev][i] && canonical(e) == c { return i } } return -1 } claim := func(ev string, i int) { if claimed[ev] == nil { claimed[ev] = map[int]bool{} } claimed[ev][i] = true } var kept []HookEntry drop := map[string][]int{} // event → the entries to take out var unread []HookEntry // records of an event whose list can't be read now for _, rec := range a.Hooks { if _, err := listOf(rec.Event); err != nil { res.fail(id, "hook:"+rec.Name, err) unread = append(unread, rec) continue } i := find(rec.Event, rec.Entry) if i < 0 { continue // gone, or changed by the user: theirs now } claim(rec.Event, i) if j := slices.IndexFunc(ws, func(w *wanted) bool { return !w.done && w.h.Name == rec.Name && w.ev == rec.Event && canonical(w.entry) == canonical(rec.Entry) }); j >= 0 { ws[j].done = true kept = append(kept, rec) continue } drop[rec.Event] = append(drop[rec.Event], i) } add := map[string][]json.RawMessage{} var added []HookEntry for _, w := range ws { if w.done { continue } // the same entry of the user's own already runs: it isn't written // twice, nor taken as magpie's if i := find(w.ev, w.entry); i >= 0 { continue } add[w.ev] = append(add[w.ev], w.entry) added = append(added, HookEntry{Name: w.h.Name, Event: w.ev, Entry: w.entry}) } if len(drop) == 0 && len(add) == 0 { a.Hooks = append(kept, unread...) return } // what each list becomes, and where each entry left in it moves to var set []edit.KV var del []string moved := map[string]map[int]int{} // event → old index → new, -1 for one taken out for _, ev := range slices.Sorted(func(yield func(string) bool) { seen := map[string]bool{} for k := range drop { if !seen[k] && !yield(k) { return } seen[k] = true } for k := range add { if !seen[k] && !yield(k) { return } seen[k] = true } }) { old := lists[ev] m := map[int]int{} var next []json.RawMessage for i, e := range old { if slices.Contains(drop[ev], i) { m[i] = -1 continue } m[i] = len(next) next = append(next, e) } next = append(next, add[ev]...) moved[ev] = m if len(next) == 0 { del = append(del, "hooks."+ev) } else { set = append(set, edit.KV{Path: "hooks." + ev, Value: next}) } } if err := b.keep(id, sp.path); err != nil { failAll(err) return } // Codex trusts a hook by where it is (codex-rs/hooks: hook_key, the // file's path, the event, the group's and the handler's index): an // entry taken out from before the user's own would leave their trust // on the wrong ones, so it is moved with them var rekey func() error if id == "codex" && len(drop) > 0 { cfg := filepath.Join(codexDir(), "config.toml") f, err := codexRekey(cfg, sp.path, moved) if err != nil { failAll(err) return } if f != nil { if err := b.keep(id, cfg); err != nil { failAll(err) return } rekey = f } } raw := doc if raw == nil { raw = []byte("{}\n") } else if orig, err := edit.Read(sp.path); err == nil { raw = orig // its comments and spacing, as the user has them } if sp.flat && !gjson.GetBytes(jsonc.ToJSON(edit.TrimBOM(raw)), "version").Exists() { set = append(set, edit.KV{Path: "version", Value: 1}) } out, err := edit.PatchJSON(raw, set, del) if err == nil && len(del) > 0 && len(set) == 0 { // a hooks object left empty by magpie goes with what it held if h := gjson.GetBytes(jsonc.ToJSON(edit.TrimBOM(out)), "hooks"); h.IsObject() && len(h.Map()) == 0 { out, err = edit.PatchJSON(out, nil, []string{"hooks"}) } } if err == nil { err = os.MkdirAll(filepath.Dir(sp.path), 0o755) } if err == nil { err = edit.WriteAtomic(sp.path, out) } if err != nil { failAll(fmt.Errorf("%s: %w", sp.path, err)) return } res.changed(id) if rekey != nil { if err := rekey(); err != nil { res.fail(id, "hooks", fmt.Errorf("the hooks are written, but Codex's trust of the ones after them couldn't be moved: review them in Codex's /hooks (%w)", err)) } } a.Hooks = append(append(kept, added...), unread...) } // codexState is a [hooks.state.""] header line in Codex's config.toml. var codexState = regexp.MustCompile(`^(\s*\[\s*hooks\s*\.\s*state\s*\.\s*)("(?:[^"\\]|\\.)*"|'[^']*')(\s*\].*)$`) // codexStateKey splits a hook's trust key: the file's path, the event's // label, the group's index and the handler's. func codexStateKey(k string) (path, label string, group, handler int, ok bool) { parts := strings.Split(k, ":") if len(parts) < 4 { return "", "", 0, 0, false } n := len(parts) g, err1 := strconv.Atoi(parts[n-2]) h, err2 := strconv.Atoi(parts[n-1]) if err1 != nil || err2 != nil { return "", "", 0, 0, false } return strings.Join(parts[:n-3], ":"), parts[n-3], g, h, true } // snake is an event's label in Codex's trust keys (hook_event_key_label): // PreToolUse is pre_tool_use. func snake(ev string) string { var b strings.Builder for i, r := range ev { if r >= 'A' && r <= 'Z' { if i > 0 { b.WriteByte('_') } r += 'a' - 'A' } b.WriteRune(r) } return b.String() } // samePath is whether two paths are the same file. func samePath(a, b string) bool { if filepath.Clean(a) == filepath.Clean(b) { return true } ra, err1 := filepath.EvalSymlinks(filepath.Dir(a)) rb, err2 := filepath.EvalSymlinks(filepath.Dir(b)) return err1 == nil && err2 == nil && filepath.Base(a) == filepath.Base(b) && ra == rb } // codexRekey is what moves Codex's trust records of hooks.json's groups // along with them (moved: event → old index → new, -1 for one taken out), // or nil when none needs moving. A record kept in some other spelling than // a [hooks.state."…"] table of its own can't be moved: that is an error, // and nothing is written. func codexRekey(cfg, hooksPath string, moved map[string]map[int]int) (func() error, error) { raw, err := edit.Read(cfg) if err != nil { return nil, err } if len(bytes.TrimSpace(raw)) == 0 { return nil, nil } var whole struct { Hooks struct { State map[string]any `toml:"state"` } `toml:"hooks"` } if err := toml.Unmarshal(raw, &whole); err != nil { return nil, fmt.Errorf("%s: %w", cfg, err) } labels := map[string]map[int]int{} for ev, m := range moved { labels[snake(ev)] = m } // to is where the record keyed k goes: ok false for one that stays to := func(k string) (string, bool) { p, label, g, h, ok := codexStateKey(k) if !ok || !samePath(p, hooksPath) { return "", false } m := labels[label] if m == nil { return "", false } n, in := m[g] if !in { // a record of a group past the end of the list, whose place // an entry magpie adds takes: it goes return "", g >= len(m) } if n == g { return "", false } if n < 0 { return "", true } return fmt.Sprintf("%s:%s:%d:%d", p, label, n, h), true } need := map[string]bool{} for k := range whole.Hooks.State { if _, ok := to(k); ok { need[k] = true } } if len(need) == 0 { return nil, nil } lines := strings.SplitAfter(string(raw), "\n") type span struct { from, to int key string m []string } var spans []span for i, ln := range lines { m := codexState.FindStringSubmatch(strings.TrimRight(ln, "\r\n")) if m == nil { continue } q := m[2] var k string if q[0] == '\'' { k = q[1 : len(q)-1] } else if u, err := strconv.Unquote(q); err == nil { k = u } else { continue } end := len(lines) for j := i + 1; j < len(lines); j++ { if s := strings.TrimSpace(lines[j]); strings.HasPrefix(s, "[") { end = j break } } spans = append(spans, span{i, end, k, m}) } for k := range need { if !slices.ContainsFunc(spans, func(s span) bool { return s.key == k }) { return nil, fmt.Errorf("%s keeps Codex's trust of %s in a way magpie can't move: take the hook out in Codex's /hooks instead", cfg, k) } } return func() error { var out strings.Builder at := 0 for _, s := range spans { if !need[s.key] { continue } out.WriteString(strings.Join(lines[at:s.from], "")) at = s.to nk, _ := to(s.key) if nk == "" { continue // its group is gone, and its record with it } // the key's end, :