library: hooks reach DeepSeek Harness through its Claude Code hooks plugin (eiyuuzaki2333 on X)

DSH was the one Library agent with no Hooks. Its plugin
@deepseek-ai/dsh-hooks-claude-code runs a Claude Code hooks.json on dsh's
interception points, so a hook given to dsh is written to
$DSH_HOME/magpie-hooks.json (Claude shape, dsh tool names bash|pwsh and
write|edit|str_replace_editor, the events the bridge runs). Each profile gets the
plugin and @deepseek-ai/dsh-hook-protocol installed at dsh's own version
(`dsh plugin --profile <name> add`), then one marked magpie-hooks insert row.
No row is written, and any magpie row is taken out, while the plugin isn't
there (a user removed it, or the install failed): dsh leaves out a row whose
plugin is missing, and a deny hook would then allow everything. A user's own
row for the plugin is left alone and said. Failed installs retry after 10 min.

Not supported by dsh, so left off (named in docs/subsystems/library.md):
subagents, slash commands, rules, env, project MCP/hooks, Claude plugins.

Run:
- real dsh 0.2.2-rc.5 on mote, sandbox HOME, fake model server: bash call
  denied through the bridge with the hook's reason shown to the model;
  without @deepseek-ai/dsh-hook-protocol the row fails to import (hence both
  packages are installed).
- mote: go test ./internal/library ./internal/agent -count=1 ok (before the
  removed-plugin fix); go test ./internal/library -run Hook ok after it;
  GOOS=windows, GOOS=linux and native go vet ./internal/library ok; gofmt -l clean.
- GUI library-hooks, project-hooks, library-rtk-nohook (12 tests, each
  covering en/zh/zh-TW/ja/de at 440px) in chromium and webkit: 12/12 both.
- New tests: TestHooksDsh*, red on the old code (dsh was no hook agent).
  The hooks page is driven by hookAgents, so no GUI change was needed.

Not tried: the full magpie sync against real dsh (full sync not run against
real dsh: the row format was written by hand and loaded by real dsh, the
install is faked in tests); Windows and WSL dsh; a dsh older than 0.2.2-rc.5;
session-start narrowing (dsh's source names unknown). Full suites run after
the tag.
This commit is contained in:
yetone
2026-11-20 05:10:42 +08:00
parent 4ff57b8cbf
commit 8de4669fb6
4 changed files with 460 additions and 2 deletions
File diff suppressed because one or more lines are too long
+244
View File
@@ -0,0 +1,244 @@
package library
// DeepSeek Harness has no hooks file of its own. Its plugin
// @deepseek-ai/dsh-hooks-claude-code runs a Claude Code hooks.json on dsh's
// interception points (session start, prompt, tool before and after, turn
// end, subagents), and a profile loads it through a row its patch list
// inserts:
//
// - insert: # magpie
// - id: magpie-hooks
// name: "@deepseek-ai/dsh-hooks-claude-code"
// config:
// configPath: "<DSH_HOME>/magpie-hooks.json"
//
// magpie keeps its hooks in $DSH_HOME/magpie-hooks.json, in Claude Code's
// shape (hooks.go writes it as it does Claude's), and gives every profile
// that row. The plugin is a profile's own npm package, at the dsh's own
// version (its peer dependencies are pinned to it), so magpie installs it
// with `dsh plugin --profile <name> add` first and writes the row only once
// it is there: a row for a plugin that isn't installed is one dsh warns of
// and leaves out, and a deny hook would then allow what it was set to stop.
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/yetone/magpie/internal/agent"
"github.com/yetone/magpie/internal/proc"
)
const (
dshHooksPkg = "@deepseek-ai/dsh-hooks-claude-code"
dshHooksProtocol = "@deepseek-ai/dsh-hook-protocol"
dshHooksRowID = "magpie-hooks"
)
// dshHookEvents are the events the bridge runs (CLAUDE_EVENTS in
// dsh-hooks-claude-code 0.2.2-rc.5); a hook under another Claude Code event
// is one it never runs.
var dshHookEvents = []string{"SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse", "Stop", "SubagentStart", "SubagentStop"}
// dshHookSpec is how dsh keeps hooks, or why it can't. Its tools are bash,
// pwsh, read, write, edit and str_replace_editor (dsh-agent's tool names),
// and the bridge reads a matcher of names joined by | as exact names.
func dshHookSpec(t *Target) (*hookSpec, string) {
if t.MCP == nil || filepath.Base(t.MCP.Path) != "cordis.patch.yml" {
return nil, "DeepSeek Harness has no profile yet: start dsh once, and hooks can be given to it"
}
return &hookSpec{
path: filepath.Join(t.Agent.Dir, "magpie-hooks.json"),
events: map[string]string{"turn-end": "Stop", "after-tool": "PostToolUse", "before-tool": "PreToolUse",
"prompt": "UserPromptSubmit", "session-start": "SessionStart"},
native: dshHookEvents,
tools: map[string]string{"shell": "bash|pwsh", "edit": "write|edit|str_replace_editor"},
}, ""
}
// dshInstalled is the version of an npm package a profile has, "" when it
// has none.
func dshInstalled(profile, pkg string) string {
b, err := os.ReadFile(filepath.Join(profile, "node_modules", filepath.FromSlash(pkg), "package.json"))
if err != nil {
return ""
}
var v struct {
Version string `json:"version"`
}
json.Unmarshal(b, &v)
return v.Version
}
// dshTool is the version and command of the dsh a; a var for tests.
var dshTool = func(a *agent.Agent) (string, string) { return a.InstalledVersion(), a.BinPath() }
// dshPluginRun runs `dsh <args>` in cwd, a profile's folder, under
// DSH_HOME dir; a var for tests.
var dshPluginRun = func(bin, dir, cwd string, args ...string) (string, error) {
const timeout = 3 * time.Minute
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
cmd := proc.CommandContext(ctx, bin, args...)
cmd.Stdin = nil
cmd.Dir = cwd
cmd.Env = append(os.Environ(), "DSH_HOME="+dir, "PATH="+filepath.Dir(bin)+string(os.PathListSeparator)+os.Getenv("PATH"))
out, err := cmd.CombinedOutput()
text := strings.TrimSpace(string(out))
if err != nil {
if errors.Is(ctx.Err(), context.DeadlineExceeded) {
return text, fmt.Errorf("dsh %s didn't finish in %s", strings.Join(args, " "), timeout)
}
if text == "" {
text = err.Error()
}
return text, fmt.Errorf("dsh %s: %s", strings.Join(args, " "), lastLines(text, 4))
}
return text, nil
}
// dshInstallFailed remembers an install that failed, per profile and
// version, so a sync that runs every few seconds doesn't wait on the
// network again each time.
var (
dshInstallMu sync.Mutex
dshInstallFailed = map[string]time.Time{}
)
const dshInstallRetry = 10 * time.Minute
// dshHooksPlugin brings every profile to what the hooks need: with any
// hook (want), the plugin installed at dsh's version and the row in its
// patch list; with none, the row taken out. A profile that fails is said
// in the error, the others done.
func dshHooksPlugin(t *Target, file string, want bool, keep func(path string) error) error {
dir := t.Agent.Dir
var ver, bin string
if want {
ver, bin = dshTool(t.Agent)
if ver == "" || bin == "" {
return errors.New("DeepSeek Harness's version or command isn't known, so its hooks plugin can't be installed")
}
}
var errs []error
for _, patch := range agent.DshPatchFiles(dir) {
if filepath.Base(patch) != "cordis.patch.yml" {
continue
}
profile := filepath.Dir(patch)
name := filepath.Base(profile)
if !want {
if err := dshDelHooksRow(patch, keep); err != nil {
errs = append(errs, fmt.Errorf("profile %s: %w", name, err))
}
continue
}
if dshInstalled(profile, dshHooksPkg) != ver || dshInstalled(profile, dshHooksProtocol) != ver {
key := profile + "\x00" + ver
dshInstallMu.Lock()
at, failed := dshInstallFailed[key]
dshInstallMu.Unlock()
if failed && time.Since(at) < dshInstallRetry {
errs = append(errs, fmt.Errorf("profile %s: the hooks plugin didn't install a moment ago; trying again later", name))
// a plugin the user removed leaves no row of magpie's behind
if err := dshDelHooksRow(patch, keep); err != nil {
errs = append(errs, fmt.Errorf("profile %s: %w", name, err))
}
continue
}
_, err := dshPluginRun(bin, dir, profile, "plugin", "--profile", name, "add", dshHooksProtocol+"@"+ver, dshHooksPkg+"@"+ver)
if err == nil && (dshInstalled(profile, dshHooksPkg) != ver || dshInstalled(profile, dshHooksProtocol) != ver) {
err = fmt.Errorf("%s isn't installed after its install", dshHooksPkg)
}
dshInstallMu.Lock()
if err != nil {
dshInstallFailed[key] = time.Now()
} else {
delete(dshInstallFailed, key)
}
dshInstallMu.Unlock()
if err != nil {
errs = append(errs, fmt.Errorf("profile %s: %w", name, err))
// the plugin isn't there, so no row of magpie's points at it
if derr := dshDelHooksRow(patch, keep); derr != nil {
errs = append(errs, fmt.Errorf("profile %s: %w", name, derr))
}
continue
}
}
if err := dshPutHooksRow(patch, file, keep); err != nil {
errs = append(errs, fmt.Errorf("profile %s: %w", name, err))
}
}
return errors.Join(errs...)
}
// dshHooksItem is the index of magpie's hooks insert in the list, -1 when
// there is none, and whether a row of the user's loads the same plugin.
func (p *dshPatches) dshHooksItem() (mine int, theirs bool) {
mine = -1
for i, it := range p.items {
switch {
case strings.TrimSpace(it[0]) == dshMark && len(it) > 1 && strings.TrimSpace(it[1]) == "- id: "+dshHooksRowID:
mine = i
case strings.Contains(strings.Join(it, "\n"), dshHooksPkg):
theirs = true
}
}
return mine, theirs
}
func dshPutHooksRow(patch, file string, keep func(string) error) error {
p, err := dshRead(patch)
if err != nil {
return err
}
i, theirs := p.dshHooksItem()
if theirs {
return errors.New("its patch list loads the hooks plugin already, with a config of its own; magpie leaves that one")
}
lines := []string{
dshMark,
" - id: " + dshHooksRowID,
" name: " + dshScalar(dshHooksPkg),
" config:",
" configPath: " + dshScalar(file),
}
if i >= 0 {
if strings.Join(p.items[i], "\n") == strings.Join(lines, "\n") {
return nil
}
p.items[i] = lines
} else {
p.items = append(p.items, lines)
}
if err := keep(patch); err != nil {
return err
}
return p.write(patch)
}
func dshDelHooksRow(patch string, keep func(string) error) error {
p, err := dshRead(patch)
if err != nil {
if os.IsNotExist(err) {
return nil
}
return err
}
i, _ := p.dshHooksItem()
if i < 0 {
return nil
}
p.items = append(p.items[:i], p.items[i+1:]...)
if err := keep(patch); err != nil {
return err
}
return p.write(patch)
}
+204
View File
@@ -0,0 +1,204 @@
package library
import (
"encoding/json"
"errors"
"os"
"path/filepath"
"strings"
"testing"
"github.com/yetone/magpie/internal/agent"
)
// fakeDshPlugins stands in for `dsh plugin add`: it lays the two packages
// down in the profile as pnpm would, at version ver, and counts the runs.
func fakeDshPlugins(t *testing.T, ver string, fail error) *[][]string {
t.Helper()
var runs [][]string
was, wasRun := dshTool, dshPluginRun
dshTool = func(*agent.Agent) (string, string) { return ver, "dsh" }
dshPluginRun = func(bin, dir, cwd string, args ...string) (string, error) {
runs = append(runs, append([]string{cwd}, args...))
if fail != nil {
return "", fail
}
for _, pkg := range []string{dshHooksPkg, dshHooksProtocol} {
b, _ := json.Marshal(map[string]string{"name": pkg, "version": ver})
write(t, filepath.Join(cwd, "node_modules", filepath.FromSlash(pkg), "package.json"), string(b))
}
return "", nil
}
t.Cleanup(func() {
dshTool, dshPluginRun = was, wasRun
dshInstallMu.Lock()
clear(dshInstallFailed)
dshInstallMu.Unlock()
})
return &runs
}
// A hook given to DeepSeek Harness lands in magpie's Claude-shaped hooks
// file under dsh's own tool names, the plugin that runs it is installed in
// every profile at dsh's version, and each profile's patch list gets one
// marked row naming the file. The user's rows stay; taking the last hook
// away takes the row away and leaves the user's rows.
func TestHooksDsh(t *testing.T) {
h := sandbox(t)
web := filepath.Join(h, ".dsh/profiles/web/cordis.patch.yml")
other := filepath.Join(h, ".dsh/profiles/other/cordis.patch.yml")
write(t, web, "- id: some-plugin\n disabled: false\n")
write(t, other, "[]\n")
runs := fakeDshPlugins(t, "0.2.2-rc.5", nil)
ok(t)(SaveHook("", Hook{Name: "guard", Event: "before-tool", Matcher: "shell", Command: "check.sh", Timeout: 5, Agents: []string{"dsh"}}))
ok(t)(SaveHook("", Hook{Name: "fmt", Event: "after-tool", Matcher: "edit", Command: "prettier --write .", Agents: []string{"dsh"}}))
file := filepath.Join(h, ".dsh", "magpie-hooks.json")
var doc struct {
Hooks map[string][]struct {
Matcher string `json:"matcher"`
Hooks []struct {
Type, Command string
Timeout int
}
}
}
if err := json.Unmarshal([]byte(read(t, file)), &doc); err != nil {
t.Fatalf("%v\n%s", err, read(t, file))
}
if g := doc.Hooks["PreToolUse"]; len(g) != 1 || g[0].Matcher != "bash|pwsh" || g[0].Hooks[0].Command != "check.sh" || g[0].Hooks[0].Timeout != 5 {
t.Errorf("PreToolUse: %+v", doc.Hooks["PreToolUse"])
}
if g := doc.Hooks["PostToolUse"]; len(g) != 1 || g[0].Matcher != "write|edit|str_replace_editor" {
t.Errorf("PostToolUse: %+v", doc.Hooks["PostToolUse"])
}
if len(*runs) != 2 {
t.Errorf("the plugin was installed %d times, want once a profile: %v", len(*runs), *runs)
}
row := "- insert: # magpie\n - id: magpie-hooks\n name: \"@deepseek-ai/dsh-hooks-claude-code\"\n config:\n configPath: " + dshScalar(file) + "\n"
for _, p := range []string{web, other} {
if s := read(t, p); strings.Count(s, "id: magpie-hooks\n") != 1 || !strings.Contains(s, row) {
t.Errorf("%s:\n%s", p, s)
}
}
if s := read(t, web); !strings.HasPrefix(s, "- id: some-plugin\n disabled: false\n") {
t.Errorf("the user's row moved:\n%s", s)
}
// a second hook installs nothing again and writes one row still
ok(t)(SaveHook("", Hook{Name: "bark", Event: "turn-end", Command: "notify", Agents: []string{"dsh"}}))
if len(*runs) != 2 || strings.Count(read(t, web), "id: magpie-hooks\n") != 1 {
t.Errorf("runs %d\n%s", len(*runs), read(t, web))
}
ok(t)(RemoveHooks([]string{"guard", "fmt", "bark"}))
if s := read(t, web); strings.Contains(s, "id: magpie-hooks\n") || !strings.Contains(s, "some-plugin") {
t.Errorf("after removing every hook:\n%s", s)
}
if s := read(t, other); strings.Contains(s, "id: magpie-hooks\n") {
t.Errorf("after removing every hook:\n%s", s)
}
}
// With the plugin not installed, no row is written: dsh would warn of the
// row, leave it out, and run no hook, so a deny hook would allow everything.
// The failure is said, and the next sync installs it.
func TestHooksDshNeedsItsPlugin(t *testing.T) {
h := sandbox(t)
web := filepath.Join(h, ".dsh/profiles/web/cordis.patch.yml")
write(t, web, "[]\n")
fakeDshPlugins(t, "0.2.2-rc.5", errors.New("pnpm: no network"))
res, err := SaveHook("", Hook{Name: "guard", Event: "before-tool", Command: "check.sh", Agents: []string{"dsh"}})
if err != nil {
t.Fatal(err)
}
if len(res.Problems) == 0 || !strings.Contains(res.Problems[0].Error, "no network") {
t.Fatalf("problems: %+v", res.Problems)
}
if s := read(t, web); strings.Contains(s, "id: magpie-hooks\n") {
t.Fatalf("a row for a plugin that isn't there:\n%s", s)
}
}
// A plugin of another version than dsh's is installed again: its peer
// dependencies are pinned to dsh's exact version.
func TestHooksDshReinstallsOnVersion(t *testing.T) {
h := sandbox(t)
web := filepath.Join(h, ".dsh/profiles/web/cordis.patch.yml")
write(t, web, "[]\n")
for _, pkg := range []string{dshHooksPkg, dshHooksProtocol} {
write(t, filepath.Join(h, ".dsh/profiles/web/node_modules", filepath.FromSlash(pkg), "package.json"), `{"version":"0.2.1-rc.2"}`)
}
runs := fakeDshPlugins(t, "0.2.2-rc.5", nil)
ok(t)(SaveHook("", Hook{Name: "guard", Event: "before-tool", Command: "check.sh", Agents: []string{"dsh"}}))
if len(*runs) != 1 || !strings.Contains(strings.Join((*runs)[0], " "), dshHooksPkg+"@0.2.2-rc.5") {
t.Fatalf("runs: %v", *runs)
}
}
// A user's own row for the plugin is left as it is.
func TestHooksDshLeavesUsersRow(t *testing.T) {
h := sandbox(t)
web := filepath.Join(h, ".dsh/profiles/web/cordis.patch.yml")
mine := "- insert:\n - id: my-hooks\n name: \"@deepseek-ai/dsh-hooks-claude-code\"\n config:\n configPath: /x/hooks.json\n"
write(t, web, mine)
fakeDshPlugins(t, "0.2.2-rc.5", nil)
res, err := SaveHook("", Hook{Name: "guard", Event: "before-tool", Command: "check.sh", Agents: []string{"dsh"}})
if err != nil {
t.Fatal(err)
}
if len(res.Problems) == 0 {
t.Fatal("no problem said")
}
if s := read(t, web); s != mine {
t.Fatalf("the user's row was changed:\n%s", s)
}
}
// dsh has the Claude Code events its bridge runs and no more: a hook under
// another event is refused, not written where nothing reads it.
func TestHooksDshEvents(t *testing.T) {
h := sandbox(t)
write(t, filepath.Join(h, ".dsh/profiles/web/cordis.patch.yml"), "[]\n")
fakeDshPlugins(t, "0.2.2-rc.5", nil)
res, err := SaveHook("", Hook{Name: "n", Event: "dsh:Notification", Command: "x", Agents: []string{"dsh"}})
if err != nil {
t.Fatal(err)
}
if len(res.Problems) == 0 || !strings.Contains(res.Problems[0].Error, "no event called Notification") {
t.Fatalf("problems: %+v", res.Problems)
}
if read(t, filepath.Join(h, ".dsh", "magpie-hooks.json")) != "" && strings.Contains(read(t, filepath.Join(h, ".dsh", "magpie-hooks.json")), "Notification") {
t.Fatal("written")
}
}
// A user who removes the plugin from a profile finds no row of magpie's left
// pointing at it: the next sync can't install it again, and takes the row out.
func TestHooksDshRemovedPluginLeavesNoRow(t *testing.T) {
h := sandbox(t)
web := filepath.Join(h, ".dsh/profiles/web/cordis.patch.yml")
write(t, web, "- id: some-plugin\n disabled: false\n")
fakeDshPlugins(t, "0.2.2-rc.5", nil)
ok(t)(SaveHook("", Hook{Name: "guard", Event: "before-tool", Command: "check.sh", Agents: []string{"dsh"}}))
if !strings.Contains(read(t, web), "id: magpie-hooks\n") {
t.Fatal("no row to start from")
}
// the user removes the plugin, and the network is down
if err := os.RemoveAll(filepath.Join(h, ".dsh/profiles/web/node_modules")); err != nil {
t.Fatal(err)
}
fakeDshPlugins(t, "0.2.2-rc.5", errors.New("pnpm: no network"))
res, err := SaveHook("guard", Hook{Name: "guard", Event: "before-tool", Command: "check2.sh", Agents: []string{"dsh"}})
if err != nil {
t.Fatal(err)
}
if len(res.Problems) == 0 {
t.Fatal("no problem said")
}
if s := read(t, web); strings.Contains(s, "id: magpie-hooks\n") || !strings.Contains(s, "some-plugin") {
t.Fatalf("a row left pointing at a plugin that isn't there:\n%s", s)
}
}
+10 -1
View File
@@ -30,6 +30,7 @@ import (
// 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
// DeepSeek Harness $DSH_HOME/magpie-hooks.json the Claude Code shape, run by the plugin dsh-hooks-claude-code (dsh_hooks.go)
//
// 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")
@@ -204,7 +205,7 @@ type hookSpec struct {
}
// hookAgents are the agents magpie can give hooks to.
var hookAgents = []string{"claude", "codex", "cursor", "gemini", "grok", "grok-app"}
var hookAgents = []string{"claude", "codex", "cursor", "dsh", "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
@@ -328,6 +329,8 @@ func hookSpecFor(t *Target) (*hookSpec, string) {
// 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), ""
case "dsh":
return dshHookSpec(t)
}
return nil, fmt.Sprintf("%s has no hooks magpie can write", t.Agent.Name)
}
@@ -704,6 +707,12 @@ func (l *Library) syncHooks(t *Target, b *backups, res *Result) {
}
if ok {
a.Hooks = recs
if id == "dsh" {
// dsh runs a hooks file through a plugin its profiles load
if err := dshHooksPlugin(t, sp.path, len(recs) > 0, func(path string) error { return b.keep(id, path) }); err != nil {
res.fail(id, "hooks", err)
}
}
}
}