-
Notifications
You must be signed in to change notification settings - Fork 33
feat: add hook for OpenClaw #155
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
jy-tan
wants to merge
2
commits into
main
Choose a base branch
from
hook-openclaw
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,144 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "encoding/json" | ||
| "fmt" | ||
| "io" | ||
| "os" | ||
|
|
||
| "github.com/Use-Tusk/fence/internal/toolcall" | ||
| ) | ||
|
|
||
| // openclawPreToolUseMode is invoked by the @use-tusk/openclaw-fence plugin. | ||
| // Wire protocol: JSON envelope on stdin, JSON response on stdout, empty | ||
| // stdout = allow. | ||
| const openclawPreToolUseMode = "--openclaw-pre-tool-use" | ||
|
|
||
| type openclawPreToolUseEvent struct { | ||
| HookEventName string `json:"hook_event_name"` | ||
| ToolName string `json:"tool_name"` | ||
| ToolInput map[string]any `json:"tool_input"` | ||
| CWD string `json:"cwd,omitempty"` | ||
| } | ||
|
|
||
| // openclawPreToolUseResponse is the deny shape the plugin reads. We only | ||
| // emit denies; allow is signalled by empty stdout. | ||
| type openclawPreToolUseResponse struct { | ||
| Decision string `json:"decision"` | ||
| Reason string `json:"reason,omitempty"` | ||
| } | ||
|
|
||
| func runOpenclawPreToolUseMode() error { | ||
| return runOpenclawPreToolUse(os.Stdin, os.Stdout, os.Args[2:]) | ||
| } | ||
|
|
||
| func runOpenclawPreToolUse(stdin io.Reader, stdout io.Writer, extraFenceArgs []string) error { | ||
| response, changed, err := buildOpenclawPreToolUseResponse(stdin, extraFenceArgs) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| if !changed { | ||
| return nil | ||
| } | ||
| _, err = fmt.Fprintln(stdout, string(response)) | ||
| return err | ||
| } | ||
|
|
||
| // buildOpenclawPreToolUseResponse decodes the envelope, evaluates against | ||
| // the dispatch table, and emits a deny on block. changed=false on allow / | ||
| // skip / non-before_tool_call event. | ||
| func buildOpenclawPreToolUseResponse(stdin io.Reader, extraFenceArgs []string) ([]byte, bool, error) { | ||
| var event openclawPreToolUseEvent | ||
| decoder := json.NewDecoder(stdin) | ||
| decoder.UseNumber() | ||
| if err := decoder.Decode(&event); err != nil { | ||
| return nil, false, fmt.Errorf("failed to decode OpenClaw hook JSON: %w", err) | ||
| } | ||
|
|
||
| if event.HookEventName != "" && event.HookEventName != "before_tool_call" { | ||
| return nil, false, nil | ||
| } | ||
|
|
||
| hookOptions, err := parseHookFenceOptionsArgs(extraFenceArgs) | ||
| if err != nil { | ||
| return nil, false, err | ||
| } | ||
|
|
||
| cwd := extractHookCommandCWD(event.ToolInput, event.CWD) | ||
| activeConfig, err := loadActiveConfigAudit(cwd, hookOptions.SettingsPath, hookOptions.TemplateName) | ||
| if err != nil { | ||
| return nil, false, err | ||
| } | ||
|
|
||
| evaluator := &toolcall.Evaluator{ | ||
| Table: openclawDispatchTable, | ||
| Config: activeConfig.Config, | ||
| } | ||
|
|
||
| decision := evaluator.Evaluate(toolcall.ToolCall{ | ||
| ToolName: event.ToolName, | ||
| Params: event.ToolInput, | ||
| CWD: cwd, | ||
| }) | ||
|
|
||
| if decision.Outcome != toolcall.OutcomeDeny { | ||
| return nil, false, nil | ||
| } | ||
|
|
||
| response := openclawPreToolUseResponse{ | ||
| Decision: "deny", | ||
| Reason: openclawDenyMessage(event.ToolName, decision), | ||
| } | ||
| data, err := json.Marshal(response) | ||
| if err != nil { | ||
| return nil, false, fmt.Errorf("failed to encode OpenClaw hook response: %w", err) | ||
| } | ||
| return data, true, nil | ||
| } | ||
|
|
||
| // openclawDenyMessage formats a deny reason. The plugin echoes this into | ||
| // the agent's tool-result stream so the LLM can recover with a different call. | ||
| func openclawDenyMessage(toolName string, decision toolcall.Decision) string { | ||
| if decision.Reason != "" { | ||
| return fmt.Sprintf("blocked by Fence policy (%s): %s", toolName, decision.Reason) | ||
| } | ||
| if decision.MatchedRule != "" { | ||
| return fmt.Sprintf("blocked by Fence policy (%s): %s matches %q", toolName, decision.Domain, decision.MatchedRule) | ||
| } | ||
| return fmt.Sprintf("blocked by Fence policy (%s)", toolName) | ||
| } | ||
|
|
||
| // openclawDispatchTable maps OpenClaw tool names (from | ||
| // src/agents/tool-catalog.ts) to their policy domain. Keep curated: only | ||
| // tools whose primary risk maps to one of Fence's existing config domains. | ||
| // Tools needing their own policy vocabulary (channel sends, MCP, subagent | ||
| // spawning, image/media generation) wait for that vocabulary to land. | ||
| // | ||
| // "bash" is here because external agents may emit it before OpenClaw's | ||
| // normalizeToolName collapses it to "exec". | ||
| var openclawDispatchTable = toolcall.Table{ | ||
| "exec": { | ||
| Domain: toolcall.DomainCommand, | ||
| Extract: toolcall.StringExtractor("command"), | ||
| }, | ||
| "bash": { | ||
| Domain: toolcall.DomainCommand, | ||
| Extract: toolcall.StringExtractor("command"), | ||
| }, | ||
| "write": { | ||
| Domain: toolcall.DomainFilesystemWrite, | ||
| Extract: toolcall.StringExtractor("path"), | ||
| }, | ||
| "edit": { | ||
| Domain: toolcall.DomainFilesystemWrite, | ||
| Extract: toolcall.StringExtractor("path"), | ||
| }, | ||
| "apply_patch": { | ||
| Domain: toolcall.DomainFilesystemWrite, | ||
| Extract: toolcall.StringExtractor("path"), | ||
| }, | ||
| "web_fetch": { | ||
| Domain: toolcall.DomainNetworkURL, | ||
| Extract: toolcall.StringExtractor("url"), | ||
| }, | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,59 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "errors" | ||
| "fmt" | ||
| "io" | ||
| "strings" | ||
|
|
||
| "github.com/Use-Tusk/fence/internal/sandbox" | ||
| ) | ||
|
|
||
| // openclawPluginPackageName is the published plugin; shared between tests | ||
| // and the print helper. | ||
| const openclawPluginPackageName = "@use-tusk/openclaw-fence" | ||
|
|
||
| // OpenClaw's plugin manager is imperative, so Fence editing the config | ||
| // file would only be half the work - the package still has to be fetched. | ||
| // We delegate to `openclaw plugins install` instead of coupling Fence to | ||
| // OpenClaw's CLI. | ||
| var ( | ||
| errOpenclawUseImperativeInstall = errors.New( | ||
| "`fence hooks install --openclaw` is not supported because OpenClaw uses an imperative plugin manager; " + | ||
| "run `openclaw plugins install " + openclawPluginPackageName + "` instead, then restart the gateway " + | ||
| "(see `fence hooks print --openclaw` for the full instructions)", | ||
| ) | ||
| errOpenclawUseImperativeUninstall = errors.New( | ||
| "`fence hooks uninstall --openclaw` is not supported; " + | ||
| "run `openclaw plugins remove openclaw-fence` instead", | ||
|
cubic-dev-ai[bot] marked this conversation as resolved.
Outdated
|
||
| ) | ||
| ) | ||
|
|
||
| // writeOpenclawHooksGuidance prints the install one-liner, plus optional | ||
| // settings/template advice. Print-only by design - the install itself | ||
| // stays on the OpenClaw side. | ||
| func writeOpenclawHooksGuidance(w io.Writer, hookOptions hookFenceOptions) error { | ||
| var b strings.Builder | ||
| b.WriteString("# OpenClaw uses an imperative plugin manager.\n") | ||
| b.WriteString("# Run:\n") | ||
| fmt.Fprintf(&b, "openclaw plugins install %s\n", openclawPluginPackageName) | ||
| b.WriteString("openclaw gateway restart\n") | ||
|
|
||
| if hookOptions.SettingsPath != "" || hookOptions.TemplateName != "" { | ||
| b.WriteString("\n") | ||
| b.WriteString("# To pin a Fence config or template, set plugin options after install:\n") | ||
| b.WriteString("# (in your OpenClaw config under plugins.entries.openclaw-fence.config)\n") | ||
| if hookOptions.SettingsPath != "" { | ||
| fmt.Fprintf(&b, "# settingsPath: %s\n", sandbox.ShellQuote([]string{hookOptions.SettingsPath})) | ||
| } | ||
| if hookOptions.TemplateName != "" { | ||
| fmt.Fprintf(&b, "# template: %s\n", hookOptions.TemplateName) | ||
| } | ||
| } else { | ||
| b.WriteString("\n") | ||
| b.WriteString("# Recommended: also pin the bundled `openclaw` template:\n") | ||
| b.WriteString("# plugins.entries.openclaw-fence.config.template: openclaw\n") | ||
| } | ||
| _, err := io.WriteString(w, b.String()) | ||
| return err | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.