library: Grok Build and Grok App can be given hooks (#1790)
The Hooks tab said "Grok App has no hooks magpie can write" and RTK said
"No rtk hook". RTK stays correct for now (rtk init has no Grok agent), but
the hooks message was wrong: the Grok CLI keeps hooks as [[hooks.<Event>]]
array tables in its config.toml, which Grok App reads from agent-home on a
custom route. Hindsight already ships three hooks into both configs.
Add grok and grok-app to hookAgents with a TOML hook spec. A hook is written
as a [[hooks.<Event>]] table with a [[hooks.<Event>.hooks]] child, the same
find/claim/drop logic as a JSON agent's: the block text is recorded entry by
entry, so only a block still exactly as magpie wrote it is ever taken out,
and the user's own blocks around it stay as they are. Portable events map to
Stop / PostToolUse / PreToolUse / UserPromptSubmit / SessionStart; a tool
matcher uses Grok's own tool names (run_terminal_command, search_replace).
Grok Build and Grok App run the one CLI, so a grok:<Event> own event goes to
both (sameHookFamily).
edit gains WriteTOMLFile and SplitLines so the library can round-trip a
config's lines through the same validating write the other TOML editors use.
Verification (branch grokapp-hooks):
- TestHooksGrokConfigTables fails on the pre-change code with a real FAIL
("Grok Build has no hooks magpie can write"); passes with the change.
Broke the matcher map, the drop and the event map by hand; each break is
caught by the test.
- go test ./internal/library ./internal/edit: 811 passed (was 828 before the
two new grok cases and the hookAgents additions).
- gofmt -l clean; go vet on mac, GOOS=linux -tags nogui, and GOOS=windows all
clean; go build, GOOS=linux go build -tags nogui and GOOS=windows go build
all succeed.
- go test -tags nogui ./... has three pre-existing failures on base cdb7b5ff
(internal/gateway TestGrokCallsGiveCodexIntegers, internal/library
TestRTKCheckLatestDoesNotWaitForThePackageManager, internal/proc
TestNoCommandBypassesProc); none is in a file this change touches, and each
reproduces without it.
- Real use: confirmed against the local Grok App 0.2.40 / grok 1.0.55 install
that agent-home/config.toml already carries Hindsight's [[hooks.*]] tables,
so the shape matches what magpie now writes. The GUI Hooks tab is driven by
the backend hookAgents view, which now lists grok and grok-app; the Tauri
window itself was not clicked through.
Reviewed before landing (fu13-pt, on e297a8ab2 + #1889/#1897/#1900/#1989):
- The shape is Grok's own: grok 1.0.50's binary carries its user guide
(10-hooks.md), which reads hooks from ~/.grok/config.toml as
[[hooks.<Event>]] with an optional matcher and an inner hooks array,
the [[hooks.<Event>.hooks]] form accepted; handler fields type, command,
url, timeout, env; run_terminal_command and search_replace are its tool
names (Bash and Edit|Write|MultiEdit are aliases of them).
- A scratch test (not committed) on a config holding a user's inline
`hooks = [ {...} ]` Stop block, a comment, [mcp_servers.x], a user
PreToolUse block and [ui]: add (Stop, PreToolUse on shell), edit the
timeout, remove both. The file parsed as TOML at each step with the
arrays as Grok reads them, and came back byte for byte. A config with a
plain [hooks] table (Stop = [...]) is refused as a problem ("key value
already exists as a Stop, but should be an array table"), file unchanged.
- Drop broken by hand (never drops a block): TestHooksGrokConfigTables and
TestHooksGrokOwnEventBoth both FAIL with the blocks left; restored, pass.
- Not tried: the Grok App window, and a running grok reading the result.
Grok App in shared mode reads ~/.grok, not agent-home, as its MCP row
already does.
This commit is contained in:
@@ -24,7 +24,7 @@ agents RTK, a CLI that cuts shell output down before the model reads it.
|
||||
| Skills a repository added | A check for updates (`CheckSkills`) also asks, for each GitHub repository and ref the library has skills from, GitHub's list of its files (`repoTree`, one API request, free when the ETag still matches). Only when that list has a skill folder beside the installed ones (under `newBase`, their deepest common folder) that the library doesn't have and hasn't offered does `findNew` fetch the repository for the skills' names and descriptions. `SeenSkills` records per `repo@ref` the paths the install picker showed and the ones set aside, so they aren't offered again. The finds live in memory (`newFound`) and reach the page as `View.NewSkills`; `AddNewSkills` gives each to the agents that have its repository's other skills, and `IgnoreNewSkills` sets it aside (`/api/library/skills/{add-new,ignore-new}`). | [`skillnew.go`](../../internal/library/skillnew.go), [`skillcheck.go`](../../internal/library/skillcheck.go) |
|
||||
| Skill groups | The page groups skills by `SkillView.Repo`, the repository each came from (`tracer.repoOf`): its GitHub source, CC Switch's `Origin`, `From`, the skills CLI's lock or the git checkout a linked folder is in. A lock entry of `sourceType: well-known` (a site's kit at its `/.well-known/agent-skills/`) is grouped by its `sourceBaseUrl` as host/path (`wellKnownBase`), not by each skill's own `sourceUrl`: Feishu's lark-* skills are one group and Fish Audio's another, while two kits under one host with different base URLs stay apart. An older entry with no base URL takes the part of its `sourceUrl` before `/.well-known/`, and one with neither is grouped by its `sourceUrl` as before. Such a kit is never fetched from GitHub by Group again, even when it reads like owner/repo (a GitHub owner has no dot), and its heading's link opens the site (#1862, `TestWellKnownKitGrouped`). `From` is written when a repository is probed (installing from it again, `noteFrom`): for a skill with the very same `SKILL.md`, and for one traced to nowhere by a name the repository has when the library has others from there, since a pack added a while ago is mostly older copies edited there since (White Immortal on Discord: 20 of mattpocock/skills' 38). Group again (`RegroupSkills`, `POST /api/library/skills/regroup`) fetches each GitHub repository the skills are traced to and does the same; it fails only when none could be fetched. A skill traced to another repository is never moved. A group's (or part's, or the Select bar's) agent chips count, give and take only the skills magpie decides for each agent: one kept in `~/.agents/skills` is in `SkillView.Always` for the agents that read that folder themselves, so a chip's `agents-some` for such an agent leaves it out, its tooltip and the status after a click say how many it still reads itself, and an agent that reads every one of them itself has a lit, locked chip as the row's is, which sends nothing (`groupChips` in library.js). The heading says how many of its skills are in `~/.agents/skills`. A row's locked chip is lit with a lock on its corner, not greyed like a chip that can't be given the skill (#1862, `skill-group-shared.test.cjs`). Collapse all / Expand all, beside the sort, folds or opens every group the list shows at once (`foldAllButton`): without a filter it sets each group's kept fold (`magpie.libSkillFolds`), as a click on each heading would; while filtering, only the groups the filter shows, till the filter changes (`unfiltered`), leaving the kept folds alone. It reads Collapse all while any shown group is open, is hidden with fewer than two groups (A→Z, or a filter one group matches), leaves a part's own fold as it is and sends nothing (#1862, `skill-fold-all.test.cjs`). | [`skill_from.go`](../../internal/library/skill_from.go), [`library.js`](../../internal/gui/assets/library.js) |
|
||||
| Skill updates | A skill from GitHub (`kind: github`, a market install among them) keeps the commit it was fetched at and `Hash`, the hash of its files as fetched. `CheckSkills` asks GitHub for each one's last commit and keeps the result in memory; `View.CheckDue` says none was checked since magpie started, or not for `checkEvery` (12 hours), and the page then checks by itself as the skills open (#1449). `editState` says a skill was changed here when the library's folder no longer hashes to `Hash` (`.DS_Store` aside), or an agent's copy was edited since its mark and not yet taken in; the view's `edited` says so. `UpdateSkill` refuses such a skill with `*EditedError` unless told to replace it (the page's own Update asks first; the CLI takes `--replace-edits`), and `UpdateSkills`/`UpdateSomeSkills` leave it as it is, in `Unupdated`. A replaced version that was changed, or that can't be told (no `Hash`), is moved to the backups (`keepReplaced`). Skills the skills CLI manages (`npx skills`, `~/.agents/.skill-lock.json`) are only grouped: the CLI updates them (`npx skills update`). A linked folder, a skill imported from an agent and a `From`-only skill have no remote to check; one CC Switch installed (`Origin`) can be updated by hand but isn't checked. | [`skill_changed.go`](../../internal/library/skill_changed.go), [`skillcheck.go`](../../internal/library/skillcheck.go), [`skills.go`](../../internal/library/skills.go) |
|
||||
| Hooks | A `Hook` (#1790) is a command, an event, an optional matcher, a timeout and the agents ticked for it. Its optional `Description` (#2011) says what it is for in any language, since its name is letters, digits, - and _: one line of at most `maxHookDescription` (200) characters, shown under the name; only library.json keeps it, and no agent is given it. Its event is portable (`HookEvents`: turn-end, after-tool, before-tool, prompt, session-start, each under the agent's own name) or an agent's own (`"codex:PermissionRequest"`), which only that agent is given. A portable tool event can be narrowed to shell or edit tools, each agent's own tool names for them. `syncHooks` writes each into the agent's own file and shape (`hookSpecOf`): Claude Code `<claude dir>/settings.json`, Codex `hooks.json` beside its config.toml, Gemini CLI `~/.gemini/settings.json` (timeout in ms), Cursor `~/.cursor/hooks.json` (flat entries, `version: 1`). Every other agent, and an agent in WSL, is refused with why, and the page greys its chip with that reason. The page also says when an agent has every hook turned off (`hooksOff`: Claude Code's `disableAllHooks`, Gemini's `hooksConfig.enabled`, Codex's `[features] hooks`). | [`hooks.go`](../../internal/library/hooks.go) |
|
||||
| Hooks | A `Hook` (#1790) is a command, an event, an optional matcher, a timeout and the agents ticked for it. Its optional `Description` (#2011) says what it is for in any language, since its name is letters, digits, - and _: one line of at most `maxHookDescription` (200) characters, shown under the name; only library.json keeps it, and no agent is given it. Its event is portable (`HookEvents`: turn-end, after-tool, before-tool, prompt, session-start, each under the agent's own name) or an agent's own (`"codex:PermissionRequest"`), which only that agent is given. A portable tool event can be narrowed to shell or edit tools, each agent's own tool names for them. `syncHooks` writes each into the agent's own file and shape (`hookSpecOf`): Claude Code `<claude dir>/settings.json`, Codex `hooks.json` beside its config.toml, Gemini CLI `~/.gemini/settings.json` (timeout in ms), Cursor `~/.cursor/hooks.json` (flat entries, `version: 1`), and Grok Build `~/.grok/config.toml` and Grok App `agent-home/config.toml` as `[[hooks.<Event>]]` array tables with a `[[hooks.<Event>.hooks]]` child. Grok Build and Grok App run the one CLI, so a `grok:<Event>` own event goes to both (`sameHookFamily`). Every other agent, and an agent in WSL, is refused with why, and the page greys its chip with that reason. The page also says when an agent has every hook turned off (`hooksOff`: Claude Code's `disableAllHooks`, Gemini's `hooksConfig.enabled`, Codex's `[features] hooks`). | [`hooks.go`](../../internal/library/hooks.go) |
|
||||
| Backups | Before a change first writes an agent file, `backups` copies it to `BackupDir`, one folder per change. The last `keepBackups` (30) changes are kept. The Backups button at the top of every tab, beside Library folder, opens that folder (`libHead`; Dade on Discord found it at the foot of a long page). | [`backup.go`](../../internal/library/backup.go) |
|
||||
| RTK | `SetRTK` runs rtk's own installer (`rtk init -g …`) for an agent being switched on. For one being switched off, it removes exactly what the installer wrote, using magpie's own code, which works even with rtk gone. `ReadRTK` reads each agent's files to say which have the hook. `rtkSpec.blocked` stops the installer where it would break an agent. `rtkSpec.env` tells the installer the agent's folder where rtk would pick another: Hermes Agent's is `appdir.HermesHome` (`%LOCALAPPDATA%\hermes` on Windows), which rtk is given as `HERMES_HOME`, since rtk 0.51 knows only `$HERMES_HOME` and `~/.hermes`. A detected agent RTK has no hook for at all is still listed, from `rtkNoHook`, with the reason and a switch that can't be turned on (dsh: its hooks can allow or deny a command but not rewrite it, and `rtk init` has no `--agent dsh`; Grok Build and Grok App: `rtk init` has no Grok or Grok App agent, so both are listed with the switch off). | [`rtk.go`](../../internal/library/rtk.go) |
|
||||
|
||||
@@ -58,7 +58,7 @@ agents RTK, a CLI that cuts shell output down before the model reads it.
|
||||
- A carried library (`Collect`) has every file of each skill, its templates and other binaries included, up to `maxCarried` (16 MiB) a file and `maxCarriedAll` (32 MiB) in all, chosen smallest first across the skills (`readSkills`), so every skill's text goes before any big file. The total keeps a sealed backup under the 64 MiB a sync reads: the files are base64 twice in it. What is left out is named in `Left`, and `Put` keeps this computer's copy of such a file in the skill it puts (`keepLeft`). [`carry.go`](../../internal/library/carry.go)
|
||||
- WorkBuddy's servers go in `$WORKBUDDY_CONFIG_DIR/mcp.json` (default `~/.workbuddy`; WorkBuddy AI, the international build, keeps its own in `~/.workbuddy-ai`, #1494), and CodeBuddy Code's go in the first of `.mcp.json`, `mcp.json` and `~/.codebuddy.json` that exists, as `resolveMcpFilePath` reads them (#1266). WorkBuddy connects a server only after the user has switched it on once in its own MCP settings. It keeps that approval in `mcp-approvals.json`, keyed by the command, args and env names or the URL's origin, so changing those asks again. magpie never writes the approval, and the servers page says so, by the build's name, when a server is given to WorkBuddy or WorkBuddy AI.
|
||||
- Alma's servers go in `~/.config/alma/mcp.json` on every system (its home, not its data folder), as its own MCP settings write them: `command`/`args`/`env`, or `url`/`headers` with `transport: "sse"` only for SSE (#1292). Alma reads the file as it starts and when its MCP settings refresh, so a server given to it while it runs reaches it after one of those.
|
||||
- Grok App's independent home (Use on a custom provider, `GROK_HOME` at `agent-home` under its data folder) gets instructions in `AGENTS.md`, MCP servers in `[mcp_servers]` of the same `config.toml` magpie's channel is in, and skills in `skills/`, and it also reads `~/.agents/skills`. Shared mode stays on Grok Build's `~/.grok` row. RTK lists Grok App, and Grok Build, with the switch off: `rtk init` has no Grok agent.
|
||||
- Grok App's independent home (Use on a custom provider, `GROK_HOME` at `agent-home` under its data folder) gets instructions in `AGENTS.md`, MCP servers in `[mcp_servers]` of the same `config.toml` magpie's channel is in, skills in `skills/`, and hooks as `[[hooks.<Event>]]` tables in that config, and it also reads `~/.agents/skills`. Shared mode stays on Grok Build's `~/.grok` row. RTK lists Grok App, and Grok Build, with the switch off: `rtk init` has no Grok agent.
|
||||
- Zed's servers go in `context_servers` of the settings.json magpie sets its model in (`agent.zed`: `~/.config/zed` on macOS, `$XDG_CONFIG_HOME/zed` on Linux, `%APPDATA%\Zed` on Windows, or `$MAGPIE_ZED_CONFIG_DIR`), as `command`/`args`/`env` or `url`/`headers` (`ContextServerSettingsContent`, zed-industries/zed 2c99f547). The file is JSONC: it is edited in place, so the user's comments, other settings and own servers stay, and `enabled`, `remote`, `timeout` and `oauth` in magpie's entry are the user's. Zed speaks streamable HTTP only (its `http.rs` only POSTs), so no SSE. An entry Zed's extensions configure (`settings` and no command or url) is never written over: a server by that name is refused for Zed (`mcpFile.foreign`), and asks for another name. Zed reloads the file as it changes.
|
||||
- An agent with no place for an item is refused by `Takes`, never recorded as given it. The refusal lists the agents here that take that item (`takenBy`), and says where it goes instead (`noPlace`): OpenChamber reads OpenCode's global AGENTS.md, skills folder and opencode.json (its server's `shared.js`), so it gets them from OpenCode; Claude Desktop's chat keeps its instructions in its own settings, with the Claude account, and its Code tab reads Claude Code's. A plugin's agent is refused an item its `agent.library` names no place for, and the refusal names the key its plugin would set.
|
||||
- Removing RTK never uses `rtk init --uninstall`. That command deletes Gemini's `GEMINI.md` whole and removes Claude Code, OpenCode and Cursor together.
|
||||
|
||||
@@ -655,6 +655,17 @@ func writeTOML(path string, lines []string) error {
|
||||
return WriteAtomic(path, data)
|
||||
}
|
||||
|
||||
// WriteTOMLFile writes lines back as a TOML file, validating the result first
|
||||
// so an edit that would leave the document invalid is refused rather than
|
||||
// saved. Line endings follow the file's existing ones (joinLinesLike).
|
||||
func WriteTOMLFile(path string, lines []string) error {
|
||||
return writeTOML(path, lines)
|
||||
}
|
||||
|
||||
// SplitLines splits file text into lines the way the TOML editors here do,
|
||||
// keeping a trailing newline as an empty final element.
|
||||
func SplitLines(s string) []string { return splitLines(s) }
|
||||
|
||||
func validateTOML(data []byte) error {
|
||||
// Check syntax first so EOF errors use the same nil-highlight-safe
|
||||
// diagnostics as reads, before the decoder checks TOML definitions.
|
||||
|
||||
+281
-12
@@ -77,10 +77,44 @@ type hookSpec struct {
|
||||
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
|
||||
toml bool // Grok: hooks are [[hooks.<Event>]] tables in config.toml, not JSON
|
||||
}
|
||||
|
||||
// hookAgents are the agents magpie can give hooks to.
|
||||
var hookAgents = []string{"claude", "codex", "cursor", "gemini"}
|
||||
var hookAgents = []string{"claude", "codex", "cursor", "gemini", "grok", "grok-app"}
|
||||
|
||||
// grokHookEvents are the events the Grok CLI fires (docs/user-guide/10-hooks.md),
|
||||
// shared by Grok Build and the Grok App that runs it. Only the ones magpie
|
||||
// maps a portable event to, plus an agent's own ("grok:Stop"), are offered;
|
||||
// the rest are listed so an own-event hook can name any of them.
|
||||
var grokHookEvents = []string{"SessionStart", "SessionEnd", "UserPromptSubmit", "PreToolUse", "PostToolUse",
|
||||
"PostToolUseFailure", "PermissionDenied", "Stop", "StopFailure", "StopCancelled", "Notification",
|
||||
"SubagentStart", "SubagentStop", "PreCompact", "PostCompact"}
|
||||
|
||||
// grokHookTools is Grok's own tool names for a portable tool matcher. Grok also
|
||||
// reads Claude's names (Bash → run_terminal_command, Edit|Write|MultiEdit →
|
||||
// search_replace), so the shared Claude tools would do; these are its own.
|
||||
var grokHookTools = map[string]string{
|
||||
"shell": "run_terminal_command",
|
||||
"edit": "search_replace",
|
||||
}
|
||||
|
||||
// grokHookSpec is how the Grok CLI keeps hooks: [[hooks.<Event>]] array tables
|
||||
// in its config.toml, each with a [[hooks.<Event>.hooks]] child holding the
|
||||
// command. Grok Build reads ~/.grok/config.toml; Grok App, on a custom route,
|
||||
// reads agent-home/config.toml. Both are the same shape.
|
||||
func grokHookSpec(path string) *hookSpec {
|
||||
return &hookSpec{
|
||||
path: path,
|
||||
events: map[string]string{
|
||||
"turn-end": "Stop", "after-tool": "PostToolUse", "before-tool": "PreToolUse",
|
||||
"prompt": "UserPromptSubmit", "session-start": "SessionStart",
|
||||
},
|
||||
native: grokHookEvents,
|
||||
tools: grokHookTools,
|
||||
toml: true,
|
||||
}
|
||||
}
|
||||
|
||||
// toolEvents are the portable events that take a matcher.
|
||||
var toolEvents = []string{"after-tool", "before-tool"}
|
||||
@@ -142,6 +176,13 @@ func hookSpecOf(t *Target) (*hookSpec, string) {
|
||||
tools: map[string]string{"shell": "Shell", "edit": "Write"},
|
||||
flat: true,
|
||||
}, ""
|
||||
case "grok":
|
||||
// Grok Build: [[hooks.<Event>]] tables in ~/.grok/config.toml
|
||||
return grokHookSpec(filepath.Join(grokDir(), "config.toml")), ""
|
||||
case "grok-app":
|
||||
// Grok App runs the same CLI, on a custom route reading
|
||||
// agent-home/config.toml, the same [[hooks.<Event>]] shape
|
||||
return grokHookSpec(t.MCP.Path), ""
|
||||
}
|
||||
return nil, fmt.Sprintf("%s has no hooks magpie can write", t.Agent.Name)
|
||||
}
|
||||
@@ -149,7 +190,7 @@ func hookSpecOf(t *Target) (*hookSpec, string) {
|
||||
// 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 {
|
||||
if !sameHookFamily(a, agent) {
|
||||
return "", fmt.Errorf("%s is an event of another agent's", ev)
|
||||
}
|
||||
if !slices.Contains(sp.native, ev) {
|
||||
@@ -163,8 +204,8 @@ func (sp *hookSpec) event(agent string, h *Hook) (string, error) {
|
||||
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 {
|
||||
// entry is h as the agent's file holds it, under its event ev.
|
||||
func (sp *hookSpec) entry(h *Hook, ev string) 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
|
||||
@@ -173,6 +214,13 @@ func (sp *hookSpec) entry(h *Hook) json.RawMessage {
|
||||
if sp.ms {
|
||||
timeout *= 1000
|
||||
}
|
||||
if sp.toml {
|
||||
// Grok: a [[hooks.<Event>]] table with a [[hooks.<Event>.hooks]]
|
||||
// child. The block text is what goes in the file and what is
|
||||
// recorded (as a JSON string) so an entry the user changed is
|
||||
// theirs, exactly as with a JSON agent's.
|
||||
return json.RawMessage(grokHookBlock(ev, m, h.Command, timeout))
|
||||
}
|
||||
var v any
|
||||
if sp.flat {
|
||||
v = struct {
|
||||
@@ -199,6 +247,46 @@ func (sp *hookSpec) entry(h *Hook) json.RawMessage {
|
||||
// characters: a line that says what it is for, not a document.
|
||||
const maxHookDescription = 200
|
||||
|
||||
// grokBlockText decodes a Grok hook entry (a JSON string holding the TOML
|
||||
// block) into the block text.
|
||||
func grokBlockText(entry json.RawMessage) (string, bool) {
|
||||
var s string
|
||||
if json.Unmarshal(entry, &s) != nil {
|
||||
return "", false
|
||||
}
|
||||
return s, true
|
||||
}
|
||||
|
||||
// grokHookBlock is one Grok hook as a TOML block: a [[hooks.<Event>]] array
|
||||
// table, its matcher (when any) and a single [[hooks.<Event>.hooks]] child
|
||||
// with the command. Returned as a JSON string so it can sit in HookEntry.Entry
|
||||
// and be compared and moved exactly as a JSON agent's entry is.
|
||||
func grokHookBlock(ev, matcher, command string, timeout int) string {
|
||||
var b strings.Builder
|
||||
b.WriteString("[[hooks." + ev + "]]\n")
|
||||
if matcher != "" {
|
||||
b.WriteString("matcher = " + strconv.Quote(matcher) + "\n")
|
||||
}
|
||||
b.WriteString(" [[hooks." + ev + ".hooks]]\n")
|
||||
b.WriteString(" type = \"command\"\n")
|
||||
b.WriteString(" command = " + strconv.Quote(command) + "\n")
|
||||
if timeout > 0 {
|
||||
b.WriteString(" timeout = " + strconv.Itoa(timeout) + "\n")
|
||||
}
|
||||
s, _ := json.Marshal(b.String())
|
||||
return string(s)
|
||||
}
|
||||
|
||||
// sameHookFamily is whether two agent ids are the same agent for an own
|
||||
// event: Grok Build and Grok App run the one Grok CLI, so an agent's own
|
||||
// ("grok:Notification") event goes to both, as a portable one does.
|
||||
func sameHookFamily(a, b string) bool {
|
||||
if a == b {
|
||||
return true
|
||||
}
|
||||
return (a == "grok" || a == "grok-app") && (b == "grok" || b == "grok-app")
|
||||
}
|
||||
|
||||
func (h *Hook) check() error {
|
||||
if err := checkName("hook", h.Name); err != nil {
|
||||
return err
|
||||
@@ -217,7 +305,7 @@ func (h *Hook) check() error {
|
||||
return fmt.Errorf("no event called %s", h.Event)
|
||||
}
|
||||
for _, x := range h.Agents {
|
||||
if x != a {
|
||||
if !sameHookFamily(x, a) {
|
||||
return fmt.Errorf("%s is %s's own event: only it can be given this hook", ev, a)
|
||||
}
|
||||
}
|
||||
@@ -292,6 +380,144 @@ func hookList(doc []byte, path, ev string) ([]json.RawMessage, error) {
|
||||
return list, nil
|
||||
}
|
||||
|
||||
// grokHookBlocks reads the [[hooks.<ev>]] blocks a Grok config.toml has, each
|
||||
// as the block text it is, so it lines up with what grokHookBlock records and
|
||||
// the same find/claim/drop logic a JSON list uses applies. A file that isn't
|
||||
// valid TOML is an error, never treated as having no hooks.
|
||||
func grokHookBlocks(path, ev string) ([]json.RawMessage, error) {
|
||||
raw, err := edit.Read(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(bytes.TrimSpace(raw)) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
lines := edit.SplitLines(string(raw))
|
||||
header := "[[hooks." + ev + "]]"
|
||||
var blocks []json.RawMessage
|
||||
for i := 0; i < len(lines); i++ {
|
||||
if strings.TrimSpace(lines[i]) != header {
|
||||
continue
|
||||
}
|
||||
j := grokBlockEnd(lines, i)
|
||||
block := strings.Join(lines[i:j], "\n") + "\n"
|
||||
s, _ := json.Marshal(block)
|
||||
blocks = append(blocks, json.RawMessage(s))
|
||||
i = j - 1
|
||||
}
|
||||
return blocks, nil
|
||||
}
|
||||
|
||||
// grokBlockEnd is the line index just past the [[hooks.<ev>]] block starting
|
||||
// at from: its body, including any [[hooks.<ev>.hooks]] child array tables,
|
||||
// up to the next table header of another event, trailing blank lines excluded.
|
||||
func grokBlockEnd(lines []string, from int) int {
|
||||
ev, _ := grokArrayEvent(lines[from])
|
||||
child := "hooks." + ev + "." // a table under this event continues the block
|
||||
j := from + 1
|
||||
for j < len(lines) {
|
||||
s := strings.TrimSpace(lines[j])
|
||||
if isGrokHeader(s) {
|
||||
if name := grokTableName(s); !strings.HasPrefix(name, child) {
|
||||
break
|
||||
}
|
||||
}
|
||||
j++
|
||||
}
|
||||
for j-1 > from && strings.TrimSpace(lines[j-1]) == "" {
|
||||
j--
|
||||
}
|
||||
return j
|
||||
}
|
||||
|
||||
// grokTableName is the dotted table name a [[x.y]] header declares, "" for a
|
||||
// line that isn't one.
|
||||
func grokTableName(line string) string {
|
||||
if ev, ok := grokArrayEvent(line); ok {
|
||||
return "hooks." + ev
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// isGrokHeader is whether a line starts a TOML table ([x] or [[x]]).
|
||||
func isGrokHeader(line string) bool {
|
||||
return strings.HasPrefix(strings.TrimSpace(line), "[")
|
||||
}
|
||||
|
||||
// writeGrokHooks applies the drop and add of Grok hook blocks to the config:
|
||||
// each block whose exact text is dropped is taken out, each added one appended
|
||||
// after the last [[hooks.*]] block (or at the end). Comments and the user's
|
||||
// own blocks around them are left as they are; the result is validated as TOML
|
||||
// before it is written, so a bad state never lands.
|
||||
func writeGrokHooks(path string, drop, add [][]byte) error {
|
||||
raw, err := edit.Read(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
lines := edit.SplitLines(string(raw))
|
||||
dropped := map[string]bool{}
|
||||
for _, d := range drop {
|
||||
dropped[string(d)] = true
|
||||
}
|
||||
var out []string
|
||||
lastHooks := -1 // line count up to and including the last [[hooks.*]] block
|
||||
i := 0
|
||||
for i < len(lines) {
|
||||
// start a block only at a [[hooks.<Event>]] header, never at a
|
||||
// child [[hooks.<Event>.hooks]] (grokArrayEvent returns that as
|
||||
// "Event.hooks"), which belongs to the block above it
|
||||
if ev, ok := grokArrayEvent(lines[i]); ok && ev != "" && !strings.Contains(ev, ".") {
|
||||
j := grokBlockEnd(lines, i)
|
||||
block := strings.Join(lines[i:j], "\n") + "\n"
|
||||
if dropped[block] {
|
||||
for len(out) > 0 && strings.TrimSpace(out[len(out)-1]) == "" {
|
||||
out = out[:len(out)-1] // take the blank line before it too
|
||||
}
|
||||
} else {
|
||||
out = append(out, lines[i:j]...)
|
||||
}
|
||||
lastHooks = len(out)
|
||||
i = j
|
||||
continue
|
||||
}
|
||||
out = append(out, lines[i])
|
||||
i++
|
||||
}
|
||||
for _, a := range add {
|
||||
// the block text ends in "\n"; TrimRight then SplitLines leaves no
|
||||
// trailing empty element to drop
|
||||
blk := edit.SplitLines(strings.TrimRight(string(a), "\n"))
|
||||
if lastHooks > 0 {
|
||||
insert := append([]string{""}, blk...)
|
||||
tail := append([]string{}, out[lastHooks:]...)
|
||||
out = append(append(out[:lastHooks], insert...), tail...)
|
||||
lastHooks += len(insert)
|
||||
} else {
|
||||
if len(out) > 0 && strings.TrimSpace(out[len(out)-1]) != "" {
|
||||
out = append(out, "")
|
||||
}
|
||||
out = append(out, blk...)
|
||||
lastHooks = len(out)
|
||||
}
|
||||
}
|
||||
return edit.WriteTOMLFile(path, out)
|
||||
}
|
||||
|
||||
// grokArrayEvent is the event a [[hooks.<ev>]] or [[hooks.<ev>.hooks]] header
|
||||
// names, or "" for a header of another table. The bool says the line is an
|
||||
// array-table header of the hooks namespace at all.
|
||||
func grokArrayEvent(line string) (string, bool) {
|
||||
s := strings.TrimSpace(line)
|
||||
if !strings.HasPrefix(s, "[[") || !strings.HasSuffix(s, "]]") {
|
||||
return "", false
|
||||
}
|
||||
name := strings.TrimSuffix(strings.TrimPrefix(s, "[["), "]]")
|
||||
if !strings.HasPrefix(name, "hooks.") {
|
||||
return "", false
|
||||
}
|
||||
return strings.TrimPrefix(name, "hooks."), true
|
||||
}
|
||||
|
||||
// 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.
|
||||
@@ -322,17 +548,27 @@ func (l *Library) syncHooks(t *Target, b *backups, res *Result) {
|
||||
res.fail(id, "hooks", err)
|
||||
}
|
||||
}
|
||||
doc, err := readHooksFile(sp.path)
|
||||
if err != nil {
|
||||
failAll(err)
|
||||
return
|
||||
var doc []byte
|
||||
if !sp.toml {
|
||||
d, err := readHooksFile(sp.path)
|
||||
if err != nil {
|
||||
failAll(err)
|
||||
return
|
||||
}
|
||||
doc = d
|
||||
}
|
||||
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)
|
||||
var x []json.RawMessage
|
||||
var err error
|
||||
if sp.toml {
|
||||
x, err = grokHookBlocks(sp.path, ev)
|
||||
} else {
|
||||
x, err = hookList(doc, sp.path, ev)
|
||||
}
|
||||
if err == nil {
|
||||
lists[ev] = x
|
||||
}
|
||||
@@ -355,7 +591,7 @@ func (l *Library) syncHooks(t *Target, b *backups, res *Result) {
|
||||
res.fail(id, "hook:"+h.Name, err)
|
||||
continue
|
||||
}
|
||||
ws = append(ws, &wanted{h: h, ev: ev, entry: sp.entry(h)})
|
||||
ws = append(ws, &wanted{h: h, ev: ev, entry: sp.entry(h, ev)})
|
||||
}
|
||||
claimed := map[string]map[int]bool{} // event → the entries magpie's records found
|
||||
find := func(ev string, entry json.RawMessage) int {
|
||||
@@ -414,6 +650,39 @@ func (l *Library) syncHooks(t *Target, b *backups, res *Result) {
|
||||
a.Hooks = append(kept, unread...)
|
||||
return
|
||||
}
|
||||
if sp.toml {
|
||||
if err := b.keep(id, sp.path); err != nil {
|
||||
failAll(err)
|
||||
return
|
||||
}
|
||||
err := os.MkdirAll(filepath.Dir(sp.path), 0o755)
|
||||
if err == nil {
|
||||
var drops, adds [][]byte
|
||||
// the dropped blocks: the entry text each index in lists holds
|
||||
for ev, idxs := range drop {
|
||||
for _, i := range idxs {
|
||||
if blk, ok := grokBlockText(lists[ev][i]); ok {
|
||||
drops = append(drops, []byte(blk))
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, es := range add {
|
||||
for _, e := range es {
|
||||
if blk, ok := grokBlockText(e); ok {
|
||||
adds = append(adds, []byte(blk))
|
||||
}
|
||||
}
|
||||
}
|
||||
err = writeGrokHooks(sp.path, drops, adds)
|
||||
}
|
||||
if err != nil {
|
||||
failAll(fmt.Errorf("%s: %w", sp.path, err))
|
||||
return
|
||||
}
|
||||
res.changed(id)
|
||||
a.Hooks = append(append(kept, added...), unread...)
|
||||
return
|
||||
}
|
||||
// what each list becomes, and where each entry left in it moves to
|
||||
var set []edit.KV
|
||||
var del []string
|
||||
@@ -779,7 +1048,7 @@ func SomeHooksAgents(names, agents []string, on bool) (*Result, error) {
|
||||
// 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 sameHookFamily(x, a)
|
||||
}
|
||||
return slices.Contains(hookAgents, a)
|
||||
}
|
||||
|
||||
@@ -11,6 +11,141 @@ import (
|
||||
"github.com/tidwall/jsonc"
|
||||
)
|
||||
|
||||
// grokBlocks is the [[hooks.<ev>]] blocks a Grok config.toml has, as raw text.
|
||||
// It reads the file plainly (no new symbols) so the test that uses it still
|
||||
// compiles against the code before this change and fails there with a real
|
||||
// behavior failure, not a compile error.
|
||||
func grokBlocks(t *testing.T, path, ev string) []string {
|
||||
t.Helper()
|
||||
var out []string
|
||||
lines := strings.Split(read(t, path), "\n")
|
||||
header := "[[hooks." + ev + "]]"
|
||||
child := "[[hooks." + ev + "."
|
||||
for i := 0; i < len(lines); i++ {
|
||||
if strings.TrimSpace(lines[i]) != header {
|
||||
continue
|
||||
}
|
||||
// the block runs to the next [[hooks.*]] header of another event,
|
||||
// skipping this event's own child tables ([[hooks.<ev>.hooks]])
|
||||
j := i + 1
|
||||
for j < len(lines) {
|
||||
s := strings.TrimSpace(lines[j])
|
||||
if strings.HasPrefix(s, "[[hooks.") && !strings.HasPrefix(s, child) {
|
||||
break
|
||||
}
|
||||
j++
|
||||
}
|
||||
for j-1 > i && strings.TrimSpace(lines[j-1]) == "" {
|
||||
j--
|
||||
}
|
||||
out = append(out, strings.Join(lines[i:j], "\n")+"\n")
|
||||
i = j - 1
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Grok Build and Grok App keep hooks as [[hooks.<Event>]] tables in their
|
||||
// config.toml. A portable hook lands in each one's own event, with the tool
|
||||
// matcher under Grok's own tool name, beside the user's own blocks, and comes
|
||||
// out of it alone leaving the rest as it was.
|
||||
func TestHooksGrokConfigTables(t *testing.T) {
|
||||
h := sandbox(t)
|
||||
t.Setenv("GROK_APP_HOME", filepath.Join(h, "grok-app-data"))
|
||||
build := filepath.Join(h, ".grok/config.toml")
|
||||
app := filepath.Join(h, "grok-app-data", "agent-home/config.toml")
|
||||
write(t, build, "# my grok config\nmodel = \"grok-4.7\"\n\n[[hooks.Stop]]\n [[hooks.Stop.hooks]]\n type = \"command\"\n command = \"say my own done\"\n")
|
||||
write(t, app, "[models]\ndefault = \"grok-4.7\"\n")
|
||||
|
||||
ok(t)(SaveHook("", Hook{Name: "bark", Event: "turn-end", Command: "curl -s https://api.day.app/KEY/done", Timeout: 10,
|
||||
Agents: []string{"grok", "grok-app"}}))
|
||||
ok(t)(SaveHook("", Hook{Name: "fmt", Event: "after-tool", Matcher: "edit", Command: "prettier --write .",
|
||||
Agents: []string{"grok", "grok-app"}}))
|
||||
|
||||
barkBlk := "[[hooks.Stop]]\n [[hooks.Stop.hooks]]\n type = \"command\"\n command = \"curl -s https://api.day.app/KEY/done\"\n timeout = 10\n"
|
||||
// Grok Build starts with the user's own Stop block; Grok App with none
|
||||
if got := grokBlocks(t, build, "Stop"); len(got) != 2 || got[1] != barkBlk {
|
||||
t.Errorf("grok build Stop: %q", got)
|
||||
}
|
||||
if got := grokBlocks(t, app, "Stop"); len(got) != 1 || got[0] != barkBlk {
|
||||
t.Errorf("grok app Stop: %q", got)
|
||||
}
|
||||
for _, p := range []string{build, app} {
|
||||
if got := grokBlocks(t, p, "PostToolUse"); len(got) != 1 || !strings.Contains(got[0], "matcher = \"search_replace\"") ||
|
||||
!strings.Contains(got[0], "command = \"prettier --write .\"") {
|
||||
t.Errorf("%s PostToolUse: %q", p, got)
|
||||
}
|
||||
}
|
||||
// the user's own Stop block stayed first, the comment kept
|
||||
if s := read(t, build); !strings.HasPrefix(s, "# my grok config\n") || !strings.Contains(s, "say my own done") {
|
||||
t.Errorf("grok build config around the hooks:\n%s", s)
|
||||
}
|
||||
|
||||
v, err := Read(nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var bark HookView
|
||||
for _, hh := range v.Hooks {
|
||||
if hh.Name == "bark" {
|
||||
bark = hh
|
||||
}
|
||||
}
|
||||
if bark.Native["grok"] != "Stop" || bark.Native["grok-app"] != "Stop" {
|
||||
t.Errorf("native events: %+v", bark.Native)
|
||||
}
|
||||
|
||||
ok(t)(RemoveHooks([]string{"bark", "fmt"}))
|
||||
// the user's own Stop block in Grok Build stays; Grok App's is empty again
|
||||
if got := grokBlocks(t, build, "Stop"); len(got) != 1 || !strings.Contains(got[0], "say my own done") {
|
||||
t.Errorf("grok build after removal, the user's own gone: %q", got)
|
||||
}
|
||||
if got := grokBlocks(t, app, "Stop"); len(got) != 0 {
|
||||
t.Errorf("grok app after removal, left: %q", got)
|
||||
}
|
||||
for _, p := range []string{build, app} {
|
||||
if got := grokBlocks(t, p, "PostToolUse"); len(got) != 0 {
|
||||
t.Errorf("%s PostToolUse left: %q", p, got)
|
||||
}
|
||||
}
|
||||
if v, _ := Read(nil); len(v.Hooks) != 0 {
|
||||
t.Errorf("left in the library: %+v", v.Hooks)
|
||||
}
|
||||
}
|
||||
|
||||
// An agent's own event ("grok:Notification") is given to Grok Build and Grok
|
||||
// App together, since they run the one CLI — and an own event of another agent
|
||||
// is still refused for them.
|
||||
func TestHooksGrokOwnEventBoth(t *testing.T) {
|
||||
h := sandbox(t)
|
||||
t.Setenv("GROK_APP_HOME", filepath.Join(h, "grok-app-data"))
|
||||
build := filepath.Join(h, ".grok/config.toml")
|
||||
app := filepath.Join(h, "grok-app-data", "agent-home/config.toml")
|
||||
write(t, build, "model = \"grok-4.7\"\n")
|
||||
write(t, app, "[models]\n")
|
||||
res, err := SaveHook("", Hook{Name: "idle", Event: "grok:Notification", Matcher: "idle_prompt", Command: "notify", Agents: []string{"grok", "grok-app"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(res.Problems) != 0 {
|
||||
t.Errorf("problems: %+v", res.Problems)
|
||||
}
|
||||
for _, p := range []string{build, app} {
|
||||
got := grokBlocks(t, p, "Notification")
|
||||
if len(got) != 1 || !strings.Contains(got[0], "matcher = \"idle_prompt\"") || !strings.Contains(got[0], "command = \"notify\"") {
|
||||
t.Errorf("%s Notification: %q", p, got)
|
||||
}
|
||||
}
|
||||
if _, err := SaveHook("", Hook{Name: "bad", Event: "codex:PermissionRequest", Command: "x", Agents: []string{"grok"}}); err == nil {
|
||||
t.Error("grok accepted Codex's own event")
|
||||
}
|
||||
ok(t)(RemoveHooks([]string{"idle"}))
|
||||
for _, p := range []string{build, app} {
|
||||
if got := grokBlocks(t, p, "Notification"); len(got) != 0 {
|
||||
t.Errorf("%s Notification left: %q", p, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// hooksOf is the list a hooks file has under hooks.<ev>, as JSON.
|
||||
func hooksOf(t *testing.T, path, ev string) []string {
|
||||
t.Helper()
|
||||
|
||||
@@ -51,6 +51,15 @@ type Target struct {
|
||||
|
||||
func home() string { h, _ := os.UserHomeDir(); return h }
|
||||
|
||||
// grokDir is where Grok Build keeps its config.toml: $GROK_HOME, else ~/.grok
|
||||
// (internal/agent/grok.go grokIn).
|
||||
func grokDir() string {
|
||||
if d := appdir.Getenv("GROK_HOME"); d != "" {
|
||||
return d
|
||||
}
|
||||
return filepath.Join(home(), ".grok")
|
||||
}
|
||||
|
||||
func claudeDir() string { return appdir.ClaudeDirIn(home()) }
|
||||
|
||||
// claudeJSON is where Claude Code keeps its user-wide MCP servers: beside
|
||||
|
||||
Reference in New Issue
Block a user