Files
magpie/internal/library/hooks.go
T
yetone e3a497d7a2 library, gui: Hooks are a fifth Library category, kept once and written into each ticked agent's own hooks file (#1790, AllenReder)
What: the Library page has a Hooks tab beside Instructions, MCP, Skills
and RTK. A hook is a command, an event, an optional tool filter, a
timeout and the agents ticked for it. magpie writes it into each agent in
that agent's own file and shape:
  Claude Code  <claude dir>/settings.json   hooks.<Event>[{matcher, hooks[]}]
  Codex        <codex home>/hooks.json       same shape
  Gemini CLI   ~/.gemini/settings.json       same shape, timeout in ms
  Cursor       ~/.cursor/hooks.json          flat entries, version 1
Portable events (turn end, after a tool, before a tool, prompt sent,
session start) map to each agent's own name; "shell"/"edit" map to each
agent's own tool names. An agent's own event (codex:PermissionRequest,
cursor:afterFileEdit, ...) is offered too and given to that agent only.
Rows have agent chips (All first), Select + bar, and Remove all, like
skills and servers. An agent that can't take a hook has its chip greyed
with the reason: every agent but those four ("has no hooks magpie can
write"), an agent in WSL (not yet), and another agent for a native event.
The page also says when an agent has all hooks turned off
(disableAllHooks, hooksConfig.enabled=false, [features] hooks=false).

Why these choices (product call delegated to us): the four agents are
the ones with a documented, file-based command-hook API whose events line
up; others (OpenCode's JS plugins, dsh, ...) have no comparable file, so
they're named as unavailable rather than half-supported. Removal is
exact: Applied.Hooks records each entry as written (canonical JSON), and
only an entry still exactly as written is taken out; one the user edited
is theirs, and their own hooks beside it are never touched. A hooks file
that doesn't parse is a problem, never treated as empty or written over.
Codex keeps trust per hook in config.toml keyed by group position, so
taking a group out re-keys the user's trust for the groups after it
(codexRekey) instead of silently untrusting them. Carried bundles
(backup/WebDAV/S3) don't carry hooks in this first version.

Run:
- go test ./internal/library ./internal/gui (sandbox HOME): pass. New
  hooks_test.go: each agent's shape; the user's edited entry stays and is
  no longer recorded; an unparseable file is left alone and reported;
  Codex trust moves with its groups; native events/unavailable agents;
  hooks-off reported.
- library-hooks.test.cjs: 12/12 in chromium and webkit, at 440px, in en,
  zh, zh-TW, ja, de; against the old library.js it fails (timeouts on the
  missing tab). All 52 new strings translated in the 4 languages.
- library-loading.test.cjs expects the Hooks tab in its tab lists
  (it failed on this change before; 6/6 now).
- Every library-*/skill-* GUI test in chromium and webkit: all pass but
  WebKit timeouts in library-mcp-tool-switch/library-mcp-tools, which fail
  the same on origin/main b0a904bd9 under load (#1609, commented).
- gofmt -l, go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: clean. Full go test ./... at the pre-rebase
  head c1c1a730f: 49 packages ok. After rebasing onto 86b2f4d05:
  library, gui and gateway's Anthropic/Zed tests ok.

Not tried: real Claude Code / Codex / Gemini / Cursor runs firing the
written hooks; the shapes were checked against each agent's source and
docs, not executed.
2026-10-12 22:44:28 +08:00

855 lines
26 KiB
Go

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 <claude dir>/settings.json hooks.<Event>: [{matcher, hooks: [{type, command, timeout}]}]
// Codex <codex home>/hooks.json the same shape
// Gemini CLI ~/.gemini/settings.json the same shape, timeout in ms
// Cursor ~/.cursor/hooks.json hooks.<event>: [{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,
// "<agent>:<Event>" 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.<ev>.
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."<key>"] 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, :<label>:<group>:<handler>, is digits and a
// label alone: it is written over as it is spelled
_, label, g, h, _ := codexStateKey(s.key)
_, _, ng, _, _ := codexStateKey(nk)
oldEnd, newEnd := fmt.Sprintf(":%s:%d:%d", label, g, h), fmt.Sprintf(":%s:%d:%d", label, ng, h)
q := s.m[2]
nq := q[:len(q)-1-len(oldEnd)] + newEnd + q[len(q)-1:]
nl := s.m[1] + nq + s.m[3]
if strings.HasSuffix(lines[s.from], "\r\n") {
nl += "\r\n"
} else if strings.HasSuffix(lines[s.from], "\n") {
nl += "\n"
}
out.WriteString(nl)
out.WriteString(strings.Join(lines[s.from+1:s.to], ""))
}
out.WriteString(strings.Join(lines[at:], ""))
return edit.WriteAtomic(cfg, []byte(out.String()))
}, nil
}
// hooksOff is whether the agent has every hook turned off in its settings,
// for the page to say why one given it doesn't run.
func hooksOff(t *Target, sp *hookSpec) bool {
switch t.Agent.ID {
case "claude":
v, _ := edit.GetJSON(sp.path, "disableAllHooks")
return v == "true"
case "gemini":
v, _ := edit.GetJSON(sp.path, "hooksConfig.enabled")
return v == "false"
case "codex":
f, _ := edit.GetTOMLTable(filepath.Join(codexDir(), "config.toml"), "features")
return f["hooks"] == "false"
}
return false
}
// ---- changes ---------------------------------------------------------------
// SaveHook adds a hook, or replaces the one called old (renaming it). An
// agent it can't be given is left out of it, said in the result.
func SaveHook(old string, h Hook) (*Result, error) {
if err := h.check(); err != nil {
return nil, err
}
return change(func(l *Library) error {
if h.Name != old && l.hook(h.Name) != nil {
return fmt.Errorf("the library already has a hook called %s", h.Name)
}
if old != "" {
i := slices.IndexFunc(l.Hooks, func(x *Hook) bool { return x.Name == old })
if i < 0 {
return fmt.Errorf("no hook called %s", old)
}
l.Hooks = slices.Delete(l.Hooks, i, i+1)
}
h.Agents = orNone(slices.Compact(slices.Sorted(slices.Values(h.Agents))))
l.Hooks = append(l.Hooks, &h)
return nil
})
}
// HookAgents sets which agents get a hook.
func HookAgents(name string, agents []string) (*Result, error) {
return change(func(l *Library) error {
h := l.hook(name)
if h == nil {
return fmt.Errorf("no hook called %s", name)
}
c := *h
c.Agents = agents
if err := c.check(); err != nil {
return err
}
h.Agents = orNone(slices.Compact(slices.Sorted(slices.Values(agents))))
return nil
})
}
// SomeHooksAgents gives the hooks named to the agents, or takes them from
// them, each to the agents that can take it: an agent's own event stays
// that agent's alone.
func SomeHooksAgents(names, agents []string, on bool) (*Result, error) {
if len(names) == 0 {
return nil, errors.New("no hooks to give the agents")
}
if len(agents) == 0 {
return nil, errors.New("no agents to give the hooks to")
}
return change(func(l *Library) error {
for _, name := range names {
if l.hook(name) == nil {
return fmt.Errorf("no hook called %s", name)
}
}
for _, h := range l.Hooks {
if !slices.Contains(names, h.Name) {
continue
}
list := slices.Clone(h.Agents)
for _, a := range agents {
if on && !hookTakes(h, a) {
continue
}
list = set(list, a, on)
}
h.Agents = orNone(list)
}
return nil
})
}
// hookTakes is whether agent a can be given h.
func hookTakes(h *Hook, a string) bool {
if x, _, ok := strings.Cut(h.Event, ":"); ok {
return x == a
}
return slices.Contains(hookAgents, a)
}
// RemoveHooks takes the hooks named out of the library, and what magpie
// wrote of them out of every agent. A name the library hasn't is said in
// Unremoved, the others gone all the same.
func RemoveHooks(names []string) (*Result, error) {
if len(names) == 0 {
return nil, errors.New("no hooks to remove")
}
names = slices.Compact(slices.Sorted(slices.Values(names)))
var failed []Problem
res, err := change(func(l *Library) error {
failed = nil
for _, name := range names {
if l.hook(name) == nil {
failed = append(failed, Problem{What: "hook:" + name, Error: "no hook called " + name})
}
}
if len(failed) == len(names) {
return errors.New(failed[0].Error)
}
l.Hooks = slices.DeleteFunc(l.Hooks, func(h *Hook) bool { return slices.Contains(names, h.Name) })
return nil
})
if res != nil {
res.Unremoved = failed
}
return res, err
}
// ---- the page --------------------------------------------------------------
// HookView is a library hook, and what each agent makes of it.
type HookView struct {
*Hook
// Native is what each agent it can go to calls its event
Native map[string]string `json:"native,omitempty"`
// Problems are the agents it couldn't be given to, and why
Problems map[string]string `json:"problems,omitempty"`
}
// HookAgentView is an agent the Hooks tab lists.
type HookAgentView struct {
ID string `json:"id"`
// File is where its hooks are; No is why magpie can't give it any
File string `json:"file,omitempty"`
No string `json:"no,omitempty"`
// WSL: No is that it runs in WSL, which magpie gives no hooks yet
WSL bool `json:"wsl,omitempty"`
// Off: it has every hook turned off in its settings
Off bool `json:"off,omitempty"`
// Events are its own events, for a hook of its alone
Events []string `json:"events,omitempty"`
}
func (l *Library) hooksView(targets []*Target, of func(string) map[string]string) ([]HookView, []HookAgentView) {
agents := []HookAgentView{}
specs := map[string]*hookSpec{}
for _, t := range targets {
sp, why := hookSpecOf(t)
av := HookAgentView{ID: t.Agent.ID, No: why, WSL: t.Agent.WSL != ""}
if sp != nil {
specs[t.Agent.ID] = sp
av.File, av.Off, av.Events = sp.path, hooksOff(t, sp), sp.native
}
agents = append(agents, av)
}
hooks := []HookView{}
for _, h := range l.Hooks {
c := *h
c.Agents = orNone(c.Agents)
hv := HookView{Hook: &c, Native: map[string]string{}, Problems: of("hook:" + h.Name)}
for id, sp := range specs {
if ev, err := sp.event(id, h); err == nil {
hv.Native[id] = ev
}
}
// an agent ticked that can't take it says why, before any change
for _, av := range agents {
if av.No != "" && slices.Contains(h.Agents, av.ID) {
if hv.Problems == nil {
hv.Problems = map[string]string{}
}
if hv.Problems[av.ID] == "" {
hv.Problems[av.ID] = av.No
}
}
}
hooks = append(hooks, hv)
}
return hooks, agents
}