The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu
Go agent-ai-cliagent-harnessesagent-securitybrowser-extensionciclaude-codecloudcodexcursordetection-engineeringjevknowledge-basememorymobile-device-managementobservabilitysecuritysecurity-information-and-event-managementsecurity-toolstelemetrytraces
Map OpenHands hook events in beacon-hooks
Claudedaab6ae58d70
diff --git a/cli/beacon-hooks/cmd/cascade.go b/cli/beacon-hooks/cmd/cascade.goindex a886390b..2a29af1a 100644--- a/cli/beacon-hooks/cmd/cascade.go+++ b/cli/beacon-hooks/cmd/cascade.go@@ -103,7 +103,10 @@ func cascadeEventClassification(actionName, toolName string) (action, category,if strings.Contains(strings.ToLower(toolName), "mcp") {return "mcp.tool_invoked", "mcp", "MCP tool invocation observed"}- return actionForTool(actionName, toolName), "tool", "Tool execution observed"+ // nil arguments: this classifier is reached only after the Cascade-specific action names above+ // have been ruled out, and it has nothing but the tool name at that point. The nil path is the+ // generic name-only behavior actionForTool has always had.+ return actionForTool(actionName, toolName, nil, nil), "tool", "Tool execution observed"}func parseCascadeWriteInput(input map[string]interface{}, logger *logging.Logger) *evaluationParams {diff --git a/cli/beacon-hooks/cmd/endpoint_events.go b/cli/beacon-hooks/cmd/endpoint_events.goindex 9dd2aa14..4885135c 100644--- a/cli/beacon-hooks/cmd/endpoint_events.go+++ b/cli/beacon-hooks/cmd/endpoint_events.go@@ -284,10 +284,13 @@ func toolFieldsWithResponse(toolName string, toolInput, toolResponse map[string]// this list: the first is Gemini CLI's (and so early Qwen Code's) `read_file` parameter, the// second is what `notebook_edit` names its target on both Qwen and Claude. Both are unambiguous// file paths, so reading them costs nothing and their absence costs a `file` field.- if path := firstToolString(toolInput, "file_path", "filePath", "path", "Path", "AbsolutePath", "absolute_path", "notebook_path", "DirectoryPath", "SearchPath", "searchPath"); path != "" {+ // `dir_path` is the snake_case sibling of `DirectoryPath` already in this list: it is what+ // OpenHands' list_directory names its target. Unambiguous, so reading it costs nothing and its+ // absence costs a `file` field on every directory listing.+ if path := firstToolString(toolInput, "file_path", "filePath", "path", "Path", "AbsolutePath", "absolute_path", "notebook_path", "DirectoryPath", "dir_path", "SearchPath", "searchPath"); path != "" {fields["file"] = map[string]interface{}{"path": path,- "operation": fileOperation(toolName),+ "operation": fileOperation(toolName, toolInput),"language": strings.TrimPrefix(filepath.Ext(path), "."),}fields["tool"] = mergeNested(fields["tool"], map[string]interface{}{"path": path})@@ -392,6 +395,13 @@ func mcpToolFields(toolName string, toolInput, toolResponse map[string]interfacemcpResource := firstToolStringAcross(maps, "mcp.resource.uri", "mcp_resource_uri")mcpSession := firstToolStringAcross(maps, "mcp.session.id", "mcp_session_id")hasCascadeServerToolPair := isCascadePlatform(platformFlag) && firstToolStringAcross(maps, "server_name") != "" && firstToolStringAcross(maps, "tool_name") != ""+ // OpenHands calls an MCP tool by whatever name its server gave it, with no prefix and no+ // mcp_* argument, so every signal above misses it and the call would be recorded as an+ // ordinary tool.invoked. Its result says so instead: tool observations are pydantic dumps+ // carrying a `kind` discriminator, and an MCP call returns MCPToolObservation. Keyed on the+ // platform like the Cascade pair above, because `kind` is a key other runtimes use for other+ // things.+ hasOpenHandsMCPObservation := platformFlag == openHandsPlatform && openHandsIsMCPToolCall(toolResponse)server := firstToolStringAcross([]map[string]interface{}{toolInput, toolResponse}, "server", "server_name", "mcp_server", "mcp_server_name", "mcp.server", "mcp.server.name")tool := firstToolStringAcross([]map[string]interface{}{toolInput, toolResponse}, "tool", "tool_name", "function_name", "mcp_tool", "mcp_tool_name", "mcp.tool", "mcp.tool.name", "gen_ai.tool.name")@@ -410,7 +420,7 @@ func mcpToolFields(toolName string, toolInput, toolResponse map[string]interface}}- isMCP := mcpServer != "" || mcpTool != "" || mcpMethod != "" || mcpProtocol != "" || mcpResource != "" || mcpSession != "" || hasCascadeServerToolPair || strings.Contains(strings.ToLower(toolName), "mcp")+ isMCP := mcpServer != "" || mcpTool != "" || mcpMethod != "" || mcpProtocol != "" || mcpResource != "" || mcpSession != "" || hasCascadeServerToolPair || hasOpenHandsMCPObservation || strings.Contains(strings.ToLower(toolName), "mcp")if !isMCP {return nil}@@ -661,12 +671,25 @@ func normalizeToolString(value interface{}) string {return strings.Trim(strings.TrimSpace(str), `"`)}-func fileOperation(toolName string) string {+// fileOperation classifies what a tool did to the file it named.+//+// toolInput is part of the question rather than extra context: a runtime is free to multiplex+// several operations onto one tool name and select between them with an argument, and OpenHands+// does exactly that -- `file_editor` is a read with command="view" and a write with+// command="str_replace". A classifier that only sees the name is wrong on one of those two+// whichever way it answers, so the arguments have to be in reach. Callers with nothing to pass+// give nil.+func fileOperation(toolName string, toolInput map[string]interface{}) string {if platformFlag == "qwen" {if operation := qwenFileOperation(toolName); operation != "" {return operation}}+ if platformFlag == openHandsPlatform {+ if operation := openHandsFileOperation(toolName, toolInput, nil); operation != "" {+ return operation+ }+ }lower := strings.ToLower(toolName)switch {case strings.Contains(lower, "read") || strings.Contains(lower, "view") || strings.Contains(lower, "list") || strings.Contains(lower, "grep") || strings.Contains(lower, "search"):@@ -680,8 +703,18 @@ func fileOperation(toolName string) string {}}-func actionForTool(hookEvent, toolName string) string {+// actionForTool classifies a tool call as an endpoint event action.+//+// toolInput and toolResponse are read for the same reason fileOperation reads the arguments, and+// for one more: on a runtime that does not decorate MCP tool names, the only thing that says a+// call went to an MCP server is the result it came back with. Callers with neither give nil.+func actionForTool(hookEvent, toolName string, toolInput, toolResponse map[string]interface{}) string {lower := strings.ToLower(toolName)+ if platformFlag == openHandsPlatform {+ if action := openHandsToolAction(toolName, toolInput, toolResponse); action != "" {+ return action+ }+ }if platformFlag == "grok" {if hookEvent == "post_tool_use_failure" {return "tool.failed"diff --git a/cli/beacon-hooks/cmd/helpers.go b/cli/beacon-hooks/cmd/helpers.goindex d3e6d950..6b361f49 100644--- a/cli/beacon-hooks/cmd/helpers.go+++ b/cli/beacon-hooks/cmd/helpers.go@@ -272,6 +272,9 @@ func resolveCwd(input map[string]interface{}, platform string) string {}return firstWorkspaceRoot(input, "workspaceRoots", "workspace_roots")}+ if platform == openHandsPlatform {+ return openHandsWorkingDir(input)+ }if isDevinLikePlatform(platform) {if cwd := getFirstStr(input, "cwd", "project_dir", "projectDir"); cwd != "" {return cwddiff --git a/cli/beacon-hooks/cmd/openhands.go b/cli/beacon-hooks/cmd/openhands.gonew file mode 100644index 00000000..30774fad--- /dev/null+++ b/cli/beacon-hooks/cmd/openhands.go@@ -0,0 +1,434 @@+package cmd++import (+ "os"+ "strings"++ "github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/config"+ hookdiff "github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/diff"+ "github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/logging"+)++// OpenHands payload readers and tool taxonomy.+//+// OpenHands documents its hooks format as compatible with Claude Code's, and the six events line+// up one for one with commands this binary already has -- SessionStart, UserPromptSubmit,+// PreToolUse, PostToolUse, Stop, SessionEnd. That is why OpenHands rides the shared commands+// rather than getting a mapper of its own: the shared path already carries the inventory+// heartbeat, log rotation, session state, the policy seam, content retention and the tool call id,+// and a second implementation of those would be the thing that drifts.+//+// What "compatible" does not cover is the envelope's field names, which are the SDK's HookEvent+// model rather than Claude's:+//+// {"event_type": "PreToolUse", "tool_name": "terminal",+// "tool_input": {...}, "tool_response": {...}, "message": "...",+// "session_id": "...", "working_dir": "...", "metadata": {}}+//+// Three of those differ from the Claude spelling the shared readers use: the working directory is+// `working_dir` and not `cwd`, the prompt is `message` and not `prompt`, and the event name is+// `event_type` and not `hook_event_name`. Only the first two are read here; the third is not read+// at all, because Beacon binds each OpenHands event to a distinct subcommand in the hooks file it+// writes, so the command that is running already knows which event it is answering.+//+// `session_id` and `tool_name`/`tool_input`/`tool_response` are spelled exactly as Claude spells+// them, so the shared readers find them with no branch, and there are deliberately none here.+//+// `metadata` is deliberately not retained. It is empty on five of the six events and carries+// `{"reason": "agent_finished"}` on Stop -- a constant the SDK passes at its single call site --+// so keeping the payload under `raw.openhands` the way the Qwen and Muse mappings do would cost+// the whole tool_input and tool_response on every event, file contents included, to preserve one+// value that is the same every time.+//+// tool_input and tool_response are pydantic model dumps rather than free-form JSON, which is what+// makes the mapping below precise: every one carries a `kind` discriminator naming the model+// class, an observation carries `content` as a list of typed parts, and an editor observation+// reports the file's content before and after rather than the edit instruction.++const openHandsPlatform = "openhands"++// openHandsCommandTools are the built-ins that execute a shell command.+//+// One entry, and the generic classifier in actionForTool would reach the same answer for it by+// substring ("terminal"). It is stated anyway because this map is what the OpenHands taxonomy is+// read from: a reader checking whether shell execution is captured should find the answer here,+// not have to work out which generic substring rule happens to fire.+var openHandsCommandTools = map[string]bool{+ "terminal": true,+}++// openHandsFileEditorTools are the built-ins that multiplex several file operations onto one tool+// name, selected by the action's `command` argument.+//+// They need their own set because a name alone cannot classify them. `file_editor` with+// command="view" is a read and with command="str_replace" is a write, and both arrive as the same+// tool_name -- so the generic classifier, which only ever sees the name, is wrong on one of the two+// whichever way it answers. planning_file_editor is the same tool over plan files: its action and+// observation subclass FileEditorAction and FileEditorObservation, so it takes the same commands+// and reports the same fields.+var openHandsFileEditorTools = map[string]bool{+ "file_editor": true,+ "planning_file_editor": true,+}++// openHandsReadTools are the built-ins that read from the filesystem without changing it.+//+// `glob` and `grep` take a `path` that is a directory to search rather than a file that was read.+// Recording that directory under file.path with operation "read" is the same shape Qwen Code's+// `glob` and `grep_search` already produce, and it is the honest one: a search did happen, and the+// directory is what it touched.+var openHandsReadTools = map[string]bool{+ "read_file": true,+ "list_directory": true,+ "glob": true,+ "grep": true,+}++// openHandsEditTools are the built-ins that create or modify a file under a name that says so.+//+// `edit` and `write_file` are the Gemini-compatible tool set OpenHands ships alongside its own+// editor; they are not in the default preset, and they are here because a hook installed once+// receives payloads from whatever tools the agent was configured with. Both report old_content and+// new_content on the observation, so they take the same diff path file_editor does.+//+// `edit` is a short, generic name that an MCP server could also use. That is survivable rather+// than ignored: openHandsToolAction asks whether the observation is an MCP result before it+// consults this map, so a post-tool payload for an MCP `edit` is classified as MCP. A pre-tool+// payload has no observation to ask, so it is classified as a file edit -- which is the same+// exposure the Qwen taxonomy carries for its own `edit`, and it costs a category rather than a+// missing event.+var openHandsEditTools = map[string]bool{+ "apply_patch": true,+ "write_file": true,+ "edit": true,+}++// openHandsMCPObservationKind is the `kind` discriminator on an MCP tool result.+//+// OpenHands does not prefix MCP tool names -- an MCP tool is called by whatever name its server+// gave it -- so the generic MCP detection, which looks for "mcp" in the tool name or for an+// mcp_* argument, sees nothing. The observation is what says so: every tool result is a pydantic+// dump carrying `kind` set to its model class name, and an MCP call returns MCPToolObservation.+//+// Matched exactly rather than by substring because `kind` is a class name from a closed set, not+// free text; a substring rule here would claim any future observation class whose name merely+// contained these letters.+const openHandsMCPObservationKind = "MCPToolObservation"++// openHandsWorkingDir resolves the directory the agent is working in.+//+// The payload field is `working_dir`, which the shared resolveCwd does not read. The environment+// fallback is not redundant with it: the SDK types HookEvent.working_dir as optional and a+// HookManager built without one leaves it null, while the executor always exports+// OPENHANDS_PROJECT_DIR from its own working directory. So the payload is preferred as the more+// specific statement and the variable covers the case where there is no statement at all.+//+// This value is what the git helpers resolve a repository and branch from, and it is written into+// every event as session.working_directory and repository, so an empty result costs three fields+// on every OpenHands event rather than one.+func openHandsWorkingDir(input map[string]interface{}) string {+ if cwd := getFirstStr(input, "working_dir", "workingDir", "cwd"); cwd != "" {+ return cwd+ }+ return strings.TrimSpace(os.Getenv("OPENHANDS_PROJECT_DIR"))+}++// openHandsPrompt reads the submitted prompt text.+//+// `message` is deliberately not added to the shared key list in runPromptSubmit. That list is+// consulted for every hook runtime, and `message` is an ordinary key that carries something other+// than the user's prompt in other runtimes' payloads -- a status line, a tool result, an error --+// so widening the shared list would put one of those into prompt.text for a runtime that has+// nothing to do with OpenHands.+func openHandsPrompt(input map[string]interface{}) string {+ return getFirstStr(input, "message")+}++// openHandsIsMCPToolCall reports whether a tool result came back from an MCP server.+func openHandsIsMCPToolCall(toolResponse map[string]interface{}) bool {+ return firstToolString(toolResponse, "kind") == openHandsMCPObservationKind+}++// openHandsFileEditorCommand reads which operation a file_editor call performed.+//+// Both sides are consulted because they answer at different times: the action carries `command` on+// PreToolUse, where there is no observation yet, and the observation echoes it on PostToolUse. The+// action is preferred so that the two phases classify the same call the same way.+//+// Only ever called for the tools in openHandsFileEditorTools. `command` means something entirely+// different on a terminal action -- it is the shell command -- and reading it for any other tool+// would classify a shell string as an editor operation.+func openHandsFileEditorCommand(toolInput, toolResponse map[string]interface{}) string {+ return strings.ToLower(firstToolStringAcross(+ []map[string]interface{}{toolInput, toolResponse}, "command"))+}++// openHandsToolAction maps an OpenHands tool call onto an endpoint event action, or returns "" to+// let the generic classifier decide.+//+// Returning "" rather than a default is what keeps the tools with no filesystem or shell meaning+// -- think, finish, task_tracker, the browser set, invoke_skill, ask_oracle -- on the shared path,+// where the tool.invoked fallback is already the right answer for them.+//+// MCP is asked first because an MCP tool's name is chosen by whoever wrote the server and can+// collide with any built-in id in the maps below. A tool result that says it came from MCP is a+// statement by the runtime; a name that happens to match is a coincidence.+func openHandsToolAction(toolName string, toolInput, toolResponse map[string]interface{}) string {+ if openHandsIsMCPToolCall(toolResponse) {+ return "mcp.tool_invoked"+ }+ lower := strings.ToLower(strings.TrimSpace(toolName))+ switch {+ case openHandsFileEditorTools[lower]:+ switch openHandsFileEditorCommand(toolInput, toolResponse) {+ case "view":+ return "file.read"+ case "create", "str_replace", "insert", "undo_edit":+ return "file.modified"+ default:+ // A file_editor call whose command did not arrive, or is one this build has not seen.+ // tool.invoked says a tool ran and nothing about what it did to the file, which is+ // exactly what is known. Falling through to the generic classifier instead would let+ // the substring rules answer from the tool's name, and the name is what cannot+ // distinguish a view from a write on this runtime.+ return "tool.invoked"+ }+ case openHandsCommandTools[lower]:+ return "command.executed"+ case openHandsReadTools[lower]:+ return "file.read"+ case openHandsEditTools[lower]:+ return "file.modified"+ default:+ return ""+ }+}++// openHandsFileOperation is the `file.operation` value for an OpenHands tool, or "" to fall+// through to the generic reader.+//+// Separate from openHandsToolAction, as the Qwen pair is, because the two answer different+// questions and disagree in both directions on this runtime. The generic fileOperation matches+// substrings, so `file_editor` reads as an edit whatever command it ran -- a view would carry+// operation "modify" -- while `apply_patch` matches "patch" and gets the right answer by accident.+func openHandsFileOperation(toolName string, toolInput, toolResponse map[string]interface{}) string {+ lower := strings.ToLower(strings.TrimSpace(toolName))+ switch {+ case openHandsFileEditorTools[lower]:+ switch openHandsFileEditorCommand(toolInput, toolResponse) {+ case "view":+ return "read"+ case "create":+ return "create"+ case "str_replace", "insert", "undo_edit":+ return "modify"+ default:+ return ""+ }+ case openHandsReadTools[lower]:+ return "read"+ case lower == "write_file":+ return "create"+ case openHandsEditTools[lower]:+ return "modify"+ default:+ return ""+ }+}++// openHandsToolFailed reports whether a tool result describes a failure.+//+// `is_error` on the observation, and nothing else. In particular not a non-zero exit code: a+// terminal observation reports exit_code separately and leaves is_error false for a command that+// ran and returned non-zero, which is an ordinary outcome the log should record as+// command.executed with the code attached. Reading the code as a failure would replace every+// failing test run and every grep that matched nothing with tool.failed at high severity.+//+// What does set it is the tool itself failing -- a bad argument, a terminal session that could not+// be recovered, an editor that could not read the path.+func openHandsToolFailed(toolResponse map[string]interface{}) bool {+ if toolResponse == nil {+ return false+ }+ switch value := toolResponse["is_error"].(type) {+ case bool:+ return value+ case string:+ return strings.EqualFold(strings.TrimSpace(value), "true")+ default:+ return false+ }+}++// openHandsObservationText joins the text an observation returned to the model.+//+// An observation's `content` is a list of typed parts rather than a string: text parts carry+// `{"type": "text", "text": ...}` and an image part carries urls instead. Only the text is read.+// An image part is skipped rather than described, because the alternative is writing a+// base64 data URL -- often megabytes of it -- into an event field.+func openHandsObservationText(toolResponse map[string]interface{}) string {+ if toolResponse == nil {+ return ""+ }+ parts, ok := toolResponse["content"].([]interface{})+ if !ok {+ return ""+ }+ var out strings.Builder+ for _, part := range parts {+ item, ok := part.(map[string]interface{})+ if !ok {+ continue+ }+ if partType := firstToolString(item, "type"); partType != "" && partType != "text" {+ continue+ }+ text, ok := item["text"].(string)+ if !ok || text == "" {+ continue+ }+ out.WriteString(text)+ }+ return out.String()+}++// applyOpenHandsToolResult attaches what the shared toolFieldsWithResponse cannot reach: the+// operation an editor call performed, and a shell command's exit code and output.+//+// The exit code and output live on the observation rather than in the tool's arguments, which is+// where toolFieldsWithResponse looks for the command itself, so without this a terminal event+// records what was run and nothing about how it went.+func applyOpenHandsToolResult(fields map[string]interface{}, toolName string, toolInput, toolResponse map[string]interface{}) {+ if operation := openHandsFileOperation(toolName, toolInput, toolResponse); operation != "" {+ if file, ok := fields["file"].(map[string]interface{}); ok {+ file["operation"] = operation+ }+ }+ if !openHandsCommandTools[strings.ToLower(strings.TrimSpace(toolName))] {+ return+ }+ command := mutableChild(fields["command"])+ // exit_code is optional on the observation and null while a command is still running or was+ // interrupted, so jsonInt's second result is what separates "absent" from a real 0. Writing a+ // zero for an absent code would report every unfinished command as a clean success.+ if exitCode, ok := jsonInt(toolResponse["exit_code"]); ok {+ command["exit_code"] = exitCode+ }+ if output := openHandsObservationText(toolResponse); output != "" {+ command["output"] = output+ // The retention marker describes the command output specifically, so it is only set when+ // there is output to describe -- and it is not overwritten, because a caller that already+ // retained something (a diff) has the more specific claim.+ if _, exists := fields["content"]; !exists {+ fields["content"] = retainedContentFields(output)+ }+ }+ if len(command) > 0 {+ fields["command"] = command+ }+}++// parseOpenHandsEdits turns one post-tool payload into the file edits it performed.+//+// A slice rather than the single *evaluationParams the Claude path returns, because one+// apply_patch call legitimately rewrites several files and reports them together. Returning only+// the first would record one edit and silently drop the rest, which is worse than recording none:+// the event would assert that a patch touched one file when it touched four.+//+// An empty result is not a failure. It means this payload is not a file edit -- a view, a+// terminal call, a tool whose observation reports no content change -- and the caller falls+// through to the observing path, which still records the tool call.+func parseOpenHandsEdits(input map[string]interface{}, logger *logging.Logger) []*evaluationParams {+ toolName := getFirstStr(input, "tool_name")+ toolInput := resolveToolInput(input)+ toolResponse := resolveToolResponse(input)++ // A failure is not an edit. The editor reports a failed str_replace with the same tool name+ // and the same arguments as a successful one; without this guard a diff would be built from+ // the content of a write that never landed, and the log would assert a file changed when it+ // did not. Same guard, same reason, as the Qwen branch in parseClaudeCopilotInput.+ if openHandsToolFailed(toolResponse) {+ return nil+ }++ lower := strings.ToLower(strings.TrimSpace(toolName))+ switch {+ case lower == "apply_patch":+ return openHandsPatchEdits(input, toolName, toolResponse, logger)+ case openHandsFileEditorTools[lower], openHandsEditTools[lower]:+ if openHandsToolAction(toolName, toolInput, toolResponse) != "file.modified" {+ return nil+ }+ path := firstToolStringAcross(+ []map[string]interface{}{toolResponse, toolInput}, "path", "file_path")+ oldContent := firstToolString(toolResponse, "old_content")+ newContent := firstToolString(toolResponse, "new_content")+ if edit := openHandsContentEdit(input, toolName, path, oldContent, newContent, logger); edit != nil {+ return []*evaluationParams{edit}+ }+ return nil+ default:+ return nil+ }+}++// openHandsPatchEdits reads the per-file changes an apply_patch call committed.+//+// The patch body in the action is not parsed. The observation already reports what was applied,+// keyed by path, with each file's content before and after -- so reading the commit answers with+// what landed on disk, while parsing the request would answer with what was asked for, and the two+// differ whenever the patch applied with fuzz.+func openHandsPatchEdits(input map[string]interface{}, toolName string, toolResponse map[string]interface{}, logger *logging.Logger) []*evaluationParams {+ commit := firstMap(toolResponse, "commit")+ changes := firstMap(commit, "changes")+ if len(changes) == 0 {+ return nil+ }+ var edits []*evaluationParams+ for path, raw := range changes {+ change, ok := raw.(map[string]interface{})+ if !ok {+ continue+ }+ // A rename reports the source path as the key and the destination under move_path. The+ // edit is recorded against the destination, because that is the file that exists+ // afterwards and the one an investigator would look for.+ target := path+ if movePath := firstToolString(change, "move_path"); movePath != "" {+ target = movePath+ }+ edit := openHandsContentEdit(+ input, toolName, target,+ firstToolString(change, "old_content"),+ firstToolString(change, "new_content"),+ logger)+ if edit != nil {+ edits = append(edits, edit)+ }+ }+ return edits+}++// openHandsContentEdit builds one recordable edit from a path and the file's content on either+// side of it, or nil when there is nothing to record.+func openHandsContentEdit(input map[string]interface{}, toolName, path, oldContent, newContent string, logger *logging.Logger) *evaluationParams {+ path = hookdiff.NormalizePath(path)+ if path == "" {+ return nil+ }+ if !config.IsScannableFile(path) {+ logger.Debug("Skipping non-scannable file: " + path)+ return nil+ }+ diffStr := hookdiff.FromContentChange(path, oldContent, newContent)+ if diffStr == "" {+ logger.Debug("Could not construct diff, skipping", "tool_name", toolName, "file_path", path)+ return nil+ }+ return &evaluationParams{+ sessionID: resolveSessionID(input, openHandsPlatform),+ toolName: toolName,+ filePath: path,+ diffStr: diffStr,+ }+}diff --git a/cli/beacon-hooks/cmd/openhands_hooks_test.go b/cli/beacon-hooks/cmd/openhands_hooks_test.gonew file mode 100644index 00000000..10dbdd67--- /dev/null+++ b/cli/beacon-hooks/cmd/openhands_hooks_test.go@@ -0,0 +1,1042 @@+package cmd++import (+ "path/filepath"+ "strings"+ "testing"++ hookconfig "github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/config"+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/policycontract"+)++// OpenHands hook payloads are the SDK's HookEvent model, and the fixtures below are that model's+// serialized shape rather than an approximation of it: `event_type`, `tool_name`, `tool_input`,+// `tool_response`, `message`, `session_id`, `working_dir`, `metadata`, with tool_input and+// tool_response as pydantic dumps carrying a `kind` discriminator.+//+// They matter more than the usual fixture does, because OpenHands is silent about a hook it does+// not like: a hooks.json that fails validation is dropped with a log line the user never sees, and+// a hook that answers with the wrong shape simply has no effect. Nothing in the runtime tells+// Beacon that a mapping stopped working, so these tests are the only thing that would.++func openHandsTestSetup(t *testing.T) string {+ t.Helper()+ setupHookConfigDirs(t)+ platformFlag = openHandsPlatform+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")+ t.Setenv("BEACON_ENDPOINT_MODE", "1")+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)+ // Beacon's own workspace is a git repository, and the fixtures below name directories that are+ // not, so branch resolution would otherwise shell out once per event for an answer no+ // assertion reads.+ t.Setenv("BEACON_DISABLE_GIT_METADATA", "1")+ return logPath+}++// terminalObservation is a TerminalObservation dump: the command echoed back, an exit code, and+// the output as a list of typed content parts rather than a string.+func terminalObservation(command string, exitCode interface{}, output string) map[string]interface{} {+ return map[string]interface{}{+ "kind": "TerminalObservation",+ "content": []interface{}{map[string]interface{}{"type": "text", "text": output}},+ "is_error": false,+ "command": command,+ "exit_code": exitCode,+ "timeout": false,+ "metadata": map[string]interface{}{"exit_code": exitCode, "working_dir": "/workspace"},+ }+}++// fileEditorObservation is a FileEditorObservation dump. old_content and new_content are the+// file's whole contents on either side of the edit, which is what makes an exact diff possible.+func fileEditorObservation(command, path, oldContent, newContent string, prevExist bool) map[string]interface{} {+ return map[string]interface{}{+ "kind": "FileEditorObservation",+ "content": []interface{}{map[string]interface{}{"type": "text", "text": "The file " + path + " has been edited."}},+ "is_error": false,+ "command": command,+ "path": path,+ "prev_exist": prevExist,+ "old_content": oldContent,+ "new_content": newContent,+ }+}++// ---------------------------------------------------------------------------+// Envelope+// ---------------------------------------------------------------------------++// The session id is spelled exactly as Claude spells it, so the default reader finds it with no+// OpenHands branch. Pinned rather than assumed: this is the field every event's session.id comes+// from, and a refactor of the default branch would take OpenHands' session identity with it.+func TestOpenHandsSessionIDComesFromTheSharedReader(t *testing.T) {+ input := map[string]interface{}{+ "event_type": "PreToolUse",+ "session_id": "oh-session-1",+ "working_dir": "/workspace/project",+ }+ if got := resolveSessionID(input, openHandsPlatform); got != "oh-session-1" {+ t.Fatalf("resolveSessionID = %q, want oh-session-1", got)+ }+ // OpenHands hands hooks no transcript: conversation state lives in its own persistence+ // directory and no payload field points at it. Empty is the honest answer, and reading a+ // Claude-shaped transcript_path key that never arrives would read as an oversight.+ sessionID, transcriptPath := resolveSessionIDWithTranscript(input, openHandsPlatform)+ if sessionID != "oh-session-1" {+ t.Fatalf("resolveSessionIDWithTranscript session = %q, want oh-session-1", sessionID)+ }+ if transcriptPath != "" {+ t.Fatalf("resolveSessionIDWithTranscript transcript = %q, want empty", transcriptPath)+ }+}++// working_dir, not cwd. Without the branch this reads empty, and session.working_directory,+// repository and branch all go missing from every OpenHands event.+func TestOpenHandsWorkingDirectoryComesFromWorkingDir(t *testing.T) {+ input := map[string]interface{}{"working_dir": "/workspace/project"}+ if got := resolveCwd(input, openHandsPlatform); got != "/workspace/project" {+ t.Fatalf("resolveCwd = %q, want /workspace/project", got)+ }+ // A payload that used the Claude spelling still resolves, so a hooks.json shared between the+ // two tools does not lose its workspace.+ if got := resolveCwd(map[string]interface{}{"cwd": "/other"}, openHandsPlatform); got != "/other" {+ t.Fatalf("resolveCwd(cwd) = %q, want /other", got)+ }+}++// HookEvent.working_dir is optional and a HookManager built without one leaves it null, while the+// executor always exports OPENHANDS_PROJECT_DIR from its own working directory. The variable is+// the fallback for exactly that case.+func TestOpenHandsWorkingDirectoryFallsBackToTheProjectDirEnv(t *testing.T) {+ t.Setenv("OPENHANDS_PROJECT_DIR", "/workspace/from-env")+ for _, input := range []map[string]interface{}{+ {},+ {"working_dir": nil},+ {"working_dir": ""},+ } {+ if got := resolveCwd(input, openHandsPlatform); got != "/workspace/from-env" {+ t.Fatalf("resolveCwd(%#v) = %q, want the OPENHANDS_PROJECT_DIR fallback", input, got)+ }+ }+ // The payload is the more specific statement and wins when both are present.+ t.Setenv("OPENHANDS_PROJECT_DIR", "/workspace/from-env")+ if got := resolveCwd(map[string]interface{}{"working_dir": "/workspace/from-payload"}, openHandsPlatform); got != "/workspace/from-payload" {+ t.Fatalf("resolveCwd = %q, want the payload to beat the environment", got)+ }+}++// OpenHands gets its own state directory. Sharing Claude's would interleave two runtimes' hook+// logs and let a stale-session sweep for one walk the other's sessions.+func TestOpenHandsHasItsOwnStateDirectory(t *testing.T) {+ setupHookConfigDirs(t)+ stateDir := hookconfig.GetStateDir(openHandsPlatform)+ if stateDir != hookconfig.OpenHandsDir {+ t.Fatalf("GetStateDir(openhands) = %q, want OpenHandsDir %q", stateDir, hookconfig.OpenHandsDir)+ }+ if stateDir == hookconfig.ClaudeDir {+ t.Fatalf("GetStateDir(openhands) = %q, want a directory distinct from Claude's", stateDir)+ }+ if got, want := hookconfig.GetLogFile(openHandsPlatform), filepath.Join(hookconfig.OpenHandsDir, "hooks.log"); got != want {+ t.Fatalf("GetLogFile(openhands) = %q, want %q", got, want)+ }+}++// ---------------------------------------------------------------------------+// Prompt+// ---------------------------------------------------------------------------++func TestOpenHandsPromptComesFromMessage(t *testing.T) {+ logPath := openHandsTestSetup(t)++ out := runHookWithInput(t, runPromptSubmit, map[string]interface{}{+ "event_type": "UserPromptSubmit",+ "session_id": "oh-session-1",+ "working_dir": "/workspace/project",+ "message": "add a health endpoint",+ "metadata": map[string]interface{}{},+ })+ if len(out) != 0 {+ t.Fatalf("prompt-submit response = %#v, want an empty object", out)+ }++ event := lastEndpointEvent(t, logPath)+ if got := leaf(event, "event", "action"); got != "prompt.submitted" {+ t.Fatalf("event.action = %q, want prompt.submitted", got)+ }+ if got := leaf(event, "prompt", "text"); got != "add a health endpoint" {+ t.Fatalf("prompt.text = %q, want the message text", got)+ }+ if got := leaf(event, "harness", "name"); got != "openhands" {+ t.Fatalf("harness.name = %q, want the canonical openhands", got)+ }+ if got := leaf(event, "harness", "collection_method"); got != "hook" {+ t.Fatalf("harness.collection_method = %q, want hook", got)+ }+ if got := leaf(event, "session", "working_directory"); got != "/workspace/project" {+ t.Fatalf("session.working_directory = %q, want /workspace/project", got)+ }+ // The retention marker is what records that the text stored here is the whole prompt rather+ // than a redacted or truncated copy of it.+ if _, ok := event["content"].(map[string]interface{}); !ok {+ t.Fatalf("event carried no content marker for the retained prompt: %#v", event["content"])+ }+}++// `message` is read for OpenHands and must not be added to the shared key list. It is an ordinary+// key that carries something other than a user prompt in other runtimes' payloads, so widening+// the shared list would put a status line or a tool result into prompt.text elsewhere.+func TestOpenHandsMessageKeyIsNotReadForOtherRuntimes(t *testing.T) {+ logPath := openHandsTestSetup(t)+ platformFlag = "claude"++ runHookWithInput(t, runPromptSubmit, map[string]interface{}{+ "hook_event_name": "UserPromptSubmit",+ "session_id": "claude-session",+ "cwd": "/repo",+ "message": "not a prompt on this runtime",+ })++ event := lastEndpointEvent(t, logPath)+ if got := leaf(event, "prompt", "text"); got != "" {+ t.Fatalf("prompt.text = %q, want empty -- `message` must stay an OpenHands-only reader", got)+ }+}++// ---------------------------------------------------------------------------+// Pre-tool+// ---------------------------------------------------------------------------++// OpenHands exposes no approval hook: PreToolUse announces a call the agent is about to make, not+// a question anybody was asked. Recording an approval here would put an operator decision in the+// log that no operator made, which is the call Cline, Pi and fx already settled the same way.+func TestOpenHandsPreToolObservesWithoutSynthesizingAnApproval(t *testing.T) {+ logPath := openHandsTestSetup(t)++ out := runHookWithInput(t, runPreTool, map[string]interface{}{+ "event_type": "PreToolUse",+ "session_id": "oh-session-1",+ "working_dir": "/workspace/project",+ "tool_name": "terminal",+ "tool_input": map[string]interface{}{+ "kind": "TerminalAction", "command": "rm -rf /tmp/data", "is_input": false, "reset": false,+ },+ "metadata": map[string]interface{}{},+ })+ // Anything but an empty object is a claim. OpenHands reads `decision`, `reason`,+ // `additionalContext` and `continue` from a hook's stdout, and shows the raw string on the+ // HookExecutionEvent in the conversation, so a speculative "allow" would be visible to the+ // user as a decision Beacon did not make -- and would start taking effect if OpenHands ever+ // reads that key.+ if len(out) != 0 {+ t.Fatalf("pre-tool response = %#v, want an empty object", out)+ }++ event := lastEndpointEvent(t, logPath)+ if got := leaf(event, "event", "action"); got != "tool.invoked" {+ t.Fatalf("event.action = %q, want tool.invoked", got)+ }+ if got := leaf(event, "event", "category"); got == "approval" {+ t.Fatalf("event.category = approval; OpenHands has no approval hook to report")+ }+ if _, ok := event["approval"]; ok {+ t.Fatalf("event carried an approval block: %#v", event["approval"])+ }+ if got := leaf(event, "command", "command"); got != "rm -rf /tmp/data" {+ t.Fatalf("command.command = %q, want the command the tool is about to run", got)+ }+ if got := leaf(event, "event", "fidelity"); got != "observed" {+ t.Fatalf("event.fidelity = %q, want observed -- OpenHands named this tool call", got)+ }+}++// ---------------------------------------------------------------------------+// Terminal+// ---------------------------------------------------------------------------++func TestOpenHandsTerminalRecordsCommandExitCodeAndOutput(t *testing.T) {+ logPath := openHandsTestSetup(t)++ runHookWithInput(t, runPostTool, map[string]interface{}{+ "event_type": "PostToolUse",+ "session_id": "oh-session-1",+ "working_dir": "/workspace/project",+ "tool_name": "terminal",+ "tool_input": map[string]interface{}{+ "kind": "TerminalAction", "command": "go test ./...", "is_input": false, "reset": false,+ },+ "tool_response": terminalObservation("go test ./...", float64(0), "ok\tbeacon\t0.4s\n"),+ "metadata": map[string]interface{}{},+ })++ event := lastEndpointEvent(t, logPath)+ if got := leaf(event, "event", "action"); got != "command.executed" {+ t.Fatalf("event.action = %q, want command.executed", got)+ }+ if got := leaf(event, "event", "category"); got != "command" {+ t.Fatalf("event.category = %q, want command", got)+ }+ if got := leaf(event, "command", "command"); got != "go test ./..." {+ t.Fatalf("command.command = %q, want the command that ran", got)+ }+ command, _ := event["command"].(map[string]interface{})+ if got, ok := command["exit_code"].(float64); !ok || got != 0 {+ t.Fatalf("command.exit_code = %#v, want 0", command["exit_code"])+ }+ if got := leaf(event, "command", "output"); !strings.Contains(got, "ok\tbeacon") {+ t.Fatalf("command.output = %q, want the observation's text content", got)+ }+ if _, ok := event["content"].(map[string]interface{}); !ok {+ t.Fatalf("event carried no content marker for the retained output: %#v", event["content"])+ }+}++// A non-zero exit is an ordinary outcome, not a tool failure. OpenHands leaves is_error false for+// a command that ran and returned non-zero, and reading the code as a failure would replace every+// failing test run and every grep that matched nothing with tool.failed at high severity.+func TestOpenHandsNonZeroExitStaysACommandExecution(t *testing.T) {+ logPath := openHandsTestSetup(t)++ runHookWithInput(t, runPostTool, map[string]interface{}{+ "event_type": "PostToolUse",+ "session_id": "oh-session-1",+ "working_dir": "/workspace/project",+ "tool_name": "terminal",+ "tool_input": map[string]interface{}{"kind": "TerminalAction", "command": "go test ./..."},+ "tool_response": terminalObservation("go test ./...", float64(1), "FAIL\tbeacon\n"),+ })++ event := lastEndpointEvent(t, logPath)+ if got := leaf(event, "event", "action"); got != "command.executed" {+ t.Fatalf("event.action = %q, want command.executed for a non-zero exit", got)+ }+ command, _ := event["command"].(map[string]interface{})+ if got, ok := command["exit_code"].(float64); !ok || got != 1 {+ t.Fatalf("command.exit_code = %#v, want 1", command["exit_code"])+ }+}++// exit_code is null while a command is still running or was interrupted. Writing a zero for an+// absent code would report every unfinished command as a clean success, so the field is omitted+// instead.+func TestOpenHandsAbsentExitCodeIsNotRecordedAsZero(t *testing.T) {+ logPath := openHandsTestSetup(t)++ runHookWithInput(t, runPostTool, map[string]interface{}{+ "event_type": "PostToolUse",+ "session_id": "oh-session-1",+ "working_dir": "/workspace/project",+ "tool_name": "terminal",+ "tool_input": map[string]interface{}{"kind": "TerminalAction", "command": "npm run dev"},+ "tool_response": terminalObservation("npm run dev", nil, "listening on :3000\n"),+ })++ event := lastEndpointEvent(t, logPath)+ command, _ := event["command"].(map[string]interface{})+ if _, present := command["exit_code"]; present {+ t.Fatalf("command.exit_code = %#v, want the field omitted for a null code", command["exit_code"])+ }+ if got := leaf(event, "command", "output"); got == "" {+ t.Fatalf("command.output was empty; the output survives an absent exit code")+ }+}++// is_error is the tool itself failing -- a bad argument, an unrecoverable terminal session -- and+// it is the only failure signal OpenHands sends: no failure event name, no top-level `error`.+func TestOpenHandsToolErrorIsRecordedAsAFailure(t *testing.T) {+ logPath := openHandsTestSetup(t)++ runHookWithInput(t, runPostTool, map[string]interface{}{+ "event_type": "PostToolUse",+ "session_id": "oh-session-1",+ "working_dir": "/workspace/project",+ "tool_name": "terminal",+ "tool_input": map[string]interface{}{"kind": "TerminalAction", "command": "["},+ "tool_response": map[string]interface{}{+ "kind": "TerminalObservation",+ "content": []interface{}{map[string]interface{}{"type": "text", "text": "tool-argument error"}},+ "is_error": true,+ "command": "[",+ "exit_code": nil,+ },+ })++ event := lastEndpointEvent(t, logPath)+ if got := leaf(event, "event", "action"); got != "tool.failed" {+ t.Fatalf("event.action = %q, want tool.failed", got)+ }+ if got := event["severity"]; got != "high" {+ t.Fatalf("severity = %v, want high", got)+ }+}++// ---------------------------------------------------------------------------+// file_editor+// ---------------------------------------------------------------------------++// file_editor multiplexes five operations onto one tool name, selected by the action's `command`.+// A classifier that only sees the name is wrong on one of view/str_replace whichever way it+// answers, which is misclassification rather than absence: the event is there, the action is+// wrong, and nothing looks broken.+func TestOpenHandsFileEditorViewIsARead(t *testing.T) {+ logPath := openHandsTestSetup(t)++ runHookWithInput(t, runPostTool, map[string]interface{}{+ "event_type": "PostToolUse",+ "session_id": "oh-session-1",+ "working_dir": "/workspace/project",+ "tool_name": "file_editor",+ "tool_input": map[string]interface{}{+ "kind": "FileEditorAction", "command": "view", "path": "/workspace/project/main.go",+ },+ "tool_response": map[string]interface{}{+ "kind": "FileEditorObservation",+ "content": []interface{}{map[string]interface{}{"type": "text", "text": "package main"}},+ "is_error": false,+ "command": "view",+ "path": "/workspace/project/main.go",+ "prev_exist": true,+ },+ })++ event := lastEndpointEvent(t, logPath)+ if got := leaf(event, "event", "action"); got != "file.read" {+ t.Fatalf("event.action = %q, want file.read for command=view", got)+ }+ if got := leaf(event, "file", "operation"); got != "read" {+ t.Fatalf("file.operation = %q, want read", got)+ }+ if got := leaf(event, "file", "path"); got != "/workspace/project/main.go" {+ t.Fatalf("file.path = %q, want the viewed path", got)+ }+ if got := leaf(event, "file", "diff"); got != "" {+ t.Fatalf("file.diff = %q, want no diff for a read", got)+ }+}++func TestOpenHandsFileEditorEditRecordsAnExactDiff(t *testing.T) {+ logPath := openHandsTestSetup(t)++ runHookWithInput(t, runPostTool, map[string]interface{}{+ "event_type": "PostToolUse",+ "session_id": "oh-session-1",+ "working_dir": "/workspace/project",+ "tool_name": "file_editor",+ "tool_input": map[string]interface{}{+ "kind": "FileEditorAction", "command": "str_replace",+ "path": "/workspace/project/main.go", "old_str": "old", "new_str": "new",+ },+ "tool_response": fileEditorObservation("str_replace", "/workspace/project/main.go",+ "package main\n\nfunc old() {}\n", "package main\n\nfunc new() {}\n", true),+ })++ event := lastEndpointEvent(t, logPath)+ if got := leaf(event, "event", "action"); got != "file.modified" {+ t.Fatalf("event.action = %q, want file.modified", got)+ }+ if got := leaf(event, "file", "path"); got != "/workspace/project/main.go" {+ t.Fatalf("file.path = %q, want the edited path", got)+ }+ diff := leaf(event, "file", "diff")+ // The diff comes from the file's content before and after, not from the old_str/new_str the+ // model wrote, so it describes what landed on disk rather than what was requested.+ if !strings.Contains(diff, "-func old() {}") || !strings.Contains(diff, "+func new() {}") {+ t.Fatalf("file.diff = %q, want the before/after content change", diff)+ }+ if leaf(event, "file", "diff_hash") == "" {+ t.Fatalf("file.diff_hash was empty; the hash describes the original diff")+ }+ if got := leaf(event, "session", "id"); got != "oh-session-1" {+ t.Fatalf("session.id = %q, want oh-session-1", got)+ }+ if got := leaf(event, "harness", "name"); got != "openhands" {+ t.Fatalf("harness.name = %q, want openhands", got)+ }+}++func TestOpenHandsFileEditorCreateRecordsANewFileDiff(t *testing.T) {+ logPath := openHandsTestSetup(t)++ runHookWithInput(t, runPostTool, map[string]interface{}{+ "event_type": "PostToolUse",+ "session_id": "oh-session-1",+ "working_dir": "/workspace/project",+ "tool_name": "file_editor",+ "tool_input": map[string]interface{}{+ "kind": "FileEditorAction", "command": "create",+ "path": "/workspace/project/new.py", "file_text": "print('hi')\n",+ },+ "tool_response": fileEditorObservation("create", "/workspace/project/new.py", "", "print('hi')\n", false),+ })++ event := lastEndpointEvent(t, logPath)+ if got := leaf(event, "event", "action"); got != "file.modified" {+ t.Fatalf("event.action = %q, want file.modified", got)+ }+ diff := leaf(event, "file", "diff")+ if !strings.Contains(diff, "@@ -0,0 +1,") || !strings.Contains(diff, "+print('hi')") {+ t.Fatalf("file.diff = %q, want a new-file hunk", diff)+ }+}++// undo_edit reports old_content and new_content like any other edit, so it takes the same path.+func TestOpenHandsFileEditorUndoIsRecordedAsAnEdit(t *testing.T) {+ logPath := openHandsTestSetup(t)++ runHookWithInput(t, runPostTool, map[string]interface{}{+ "event_type": "PostToolUse",+ "session_id": "oh-session-1",+ "working_dir": "/workspace/project",+ "tool_name": "file_editor",+ "tool_input": map[string]interface{}{"kind": "FileEditorAction", "command": "undo_edit", "path": "/workspace/project/main.go"},+ "tool_response": fileEditorObservation("undo_edit", "/workspace/project/main.go",+ "func new() {}\n", "func old() {}\n", true),+ })++ event := lastEndpointEvent(t, logPath)+ if got := leaf(event, "event", "action"); got != "file.modified" {+ t.Fatalf("event.action = %q, want file.modified for undo_edit", got)+ }+ if diff := leaf(event, "file", "diff"); !strings.Contains(diff, "+func old() {}") {+ t.Fatalf("file.diff = %q, want the restored content", diff)+ }+}++// An unchanged file is not an edit. A header with an empty hunk would record that a file changed+// when it did not, so the payload falls through to the observing path instead: the tool call is+// still recorded, with the path, and without a diff that claims something happened.+func TestOpenHandsUnchangedContentRecordsNoDiff(t *testing.T) {+ logPath := openHandsTestSetup(t)++ runHookWithInput(t, runPostTool, map[string]interface{}{+ "event_type": "PostToolUse",+ "session_id": "oh-session-1",+ "working_dir": "/workspace/project",+ "tool_name": "file_editor",+ "tool_input": map[string]interface{}{"kind": "FileEditorAction", "command": "undo_edit", "path": "/workspace/project/main.go"},+ "tool_response": fileEditorObservation("undo_edit", "/workspace/project/main.go",+ "same\n", "same\n", true),+ })++ event := lastEndpointEvent(t, logPath)+ if got := leaf(event, "event", "action"); got != "file.modified" {+ t.Fatalf("event.action = %q, want file.modified -- the call still happened", got)+ }+ if got := leaf(event, "file", "diff"); got != "" {+ t.Fatalf("file.diff = %q, want no diff when the content did not change", got)+ }+}++// A failed edit carries the same tool name and the same arguments as a successful one, so without+// the guard a diff would be built from a write that never landed and the log would assert a file+// changed when it did not.+func TestOpenHandsFailedEditIsNotRecordedAsAnEdit(t *testing.T) {+ logPath := openHandsTestSetup(t)++ runHookWithInput(t, runPostTool, map[string]interface{}{+ "event_type": "PostToolUse",+ "session_id": "oh-session-1",+ "working_dir": "/workspace/project",+ "tool_name": "file_editor",+ "tool_input": map[string]interface{}{+ "kind": "FileEditorAction", "command": "str_replace",+ "path": "/workspace/project/main.go", "old_str": "absent", "new_str": "new",+ },+ "tool_response": map[string]interface{}{+ "kind": "FileEditorObservation",+ "content": []interface{}{map[string]interface{}{"type": "text", "text": "No replacement performed"}},+ "is_error": true,+ "command": "str_replace",+ "path": "/workspace/project/main.go",+ },+ })++ for _, event := range endpointEvents(t, logPath) {+ if got := leaf(event, "event", "action"); got == "file.modified" {+ t.Fatalf("a failed edit was recorded as file.modified: %#v", event)+ }+ }+ event := lastEndpointEvent(t, logPath)+ if got := leaf(event, "event", "action"); got != "tool.failed" {+ t.Fatalf("event.action = %q, want tool.failed", got)+ }+}++// A file_editor call whose command did not arrive says a tool ran and nothing about what it did to+// the file, which is exactly what is known. Falling through to the generic classifier would let+// the substring rules answer from the tool's name, and the name is what cannot distinguish a view+// from a write on this runtime.+func TestOpenHandsFileEditorWithoutACommandIsNotClassifiedAsAnEdit(t *testing.T) {+ setupHookConfigDirs(t)+ platformFlag = openHandsPlatform++ got := actionForTool("PostToolUse", "file_editor",+ map[string]interface{}{"kind": "FileEditorAction", "path": "/workspace/main.go"}, nil)+ if got != "tool.invoked" {+ t.Fatalf("actionForTool(file_editor, no command) = %q, want tool.invoked", got)+ }+}++// planning_file_editor subclasses the same action and observation, so it takes the same commands+// and reports the same fields.+func TestOpenHandsPlanningFileEditorSharesTheEditorTaxonomy(t *testing.T) {+ setupHookConfigDirs(t)+ platformFlag = openHandsPlatform++ for command, want := range map[string]string{"view": "file.read", "create": "file.modified", "str_replace": "file.modified"} {+ toolInput := map[string]interface{}{"kind": "PlanningFileEditorAction", "command": command, "path": "/workspace/plan.md"}+ if got := actionForTool("PostToolUse", "planning_file_editor", toolInput, nil); got != want {+ t.Errorf("actionForTool(planning_file_editor, %s) = %q, want %q", command, got, want)+ }+ }+}++// ---------------------------------------------------------------------------+// apply_patch+// ---------------------------------------------------------------------------++// One apply_patch call commits a change per file and reports them together. Recording only the+// first would assert that a patch touched one file when it touched several.+func TestOpenHandsApplyPatchRecordsEveryChangedFile(t *testing.T) {+ logPath := openHandsTestSetup(t)++ runHookWithInput(t, runPostTool, map[string]interface{}{+ "event_type": "PostToolUse",+ "session_id": "oh-session-1",+ "working_dir": "/workspace/project",+ "tool_name": "apply_patch",+ "tool_input": map[string]interface{}{+ "kind": "ApplyPatchAction",+ "patch": "*** Begin Patch\n*** Update File: a.py\n*** End Patch",+ },+ "tool_response": map[string]interface{}{+ "kind": "ApplyPatchObservation",+ "content": []interface{}{map[string]interface{}{"type": "text", "text": "Applied patch"}},+ "is_error": false,+ "message": "Applied patch",+ "fuzz": float64(0),+ "commit": map[string]interface{}{+ "changes": map[string]interface{}{+ "/workspace/project/a.py": map[string]interface{}{+ "type": "update", "old_content": "x = 1\n", "new_content": "x = 2\n",+ },+ "/workspace/project/b.py": map[string]interface{}{+ "type": "add", "new_content": "y = 3\n",+ },+ },+ },+ },+ })++ events := endpointEvents(t, logPath)+ paths := map[string]string{}+ for _, event := range events {+ if leaf(event, "event", "action") != "file.modified" {+ continue+ }+ paths[leaf(event, "file", "path")] = leaf(event, "file", "diff")+ }+ if len(paths) != 2 {+ t.Fatalf("recorded %d file.modified events, want one per changed file: %#v", len(paths), paths)+ }+ if diff := paths["/workspace/project/a.py"]; !strings.Contains(diff, "-x = 1") || !strings.Contains(diff, "+x = 2") {+ t.Fatalf("a.py diff = %q, want the update", diff)+ }+ if diff := paths["/workspace/project/b.py"]; !strings.Contains(diff, "@@ -0,0 +1,") || !strings.Contains(diff, "+y = 3") {+ t.Fatalf("b.py diff = %q, want a new-file hunk", diff)+ }+}++// A rename keys the change by the source path and names the destination under move_path. The edit+// is recorded against the destination, because that is the file that exists afterwards and the one+// an investigator would look for.+func TestOpenHandsApplyPatchRenameIsRecordedAgainstTheDestination(t *testing.T) {+ logPath := openHandsTestSetup(t)++ runHookWithInput(t, runPostTool, map[string]interface{}{+ "event_type": "PostToolUse",+ "session_id": "oh-session-1",+ "working_dir": "/workspace/project",+ "tool_name": "apply_patch",+ "tool_input": map[string]interface{}{"kind": "ApplyPatchAction", "patch": "*** Begin Patch\n*** End Patch"},+ "tool_response": map[string]interface{}{+ "kind": "ApplyPatchObservation",+ "is_error": false,+ "commit": map[string]interface{}{+ "changes": map[string]interface{}{+ "/workspace/project/old.py": map[string]interface{}{+ "type": "update", "move_path": "/workspace/project/new.py",+ "old_content": "x = 1\n", "new_content": "x = 2\n",+ },+ },+ },+ },+ })++ event := lastEndpointEvent(t, logPath)+ if got := leaf(event, "file", "path"); got != "/workspace/project/new.py" {+ t.Fatalf("file.path = %q, want the destination of the rename", got)+ }+}++func TestOpenHandsFailedApplyPatchIsNotRecordedAsAnEdit(t *testing.T) {+ logPath := openHandsTestSetup(t)++ runHookWithInput(t, runPostTool, map[string]interface{}{+ "event_type": "PostToolUse",+ "session_id": "oh-session-1",+ "working_dir": "/workspace/project",+ "tool_name": "apply_patch",+ "tool_input": map[string]interface{}{"kind": "ApplyPatchAction", "patch": "*** Begin Patch\nbroken"},+ "tool_response": map[string]interface{}{+ "kind": "ApplyPatchObservation",+ "content": []interface{}{map[string]interface{}{"type": "text", "text": "Invalid patch"}},+ "is_error": true,+ },+ })++ for _, event := range endpointEvents(t, logPath) {+ if got := leaf(event, "event", "action"); got == "file.modified" {+ t.Fatalf("a failed patch was recorded as file.modified: %#v", event)+ }+ }+ if got := leaf(lastEndpointEvent(t, logPath), "event", "action"); got != "tool.failed" {+ t.Fatalf("event.action = %q, want tool.failed", got)+ }+}++// ---------------------------------------------------------------------------+// Gemini-compatible tool set+// ---------------------------------------------------------------------------++// write_file and edit are not in the default preset, but a hook installed once receives payloads+// from whatever tools the agent was configured with. Both report old_content and new_content, so+// they take the same diff path file_editor does.+func TestOpenHandsGeminiEditToolsRecordDiffs(t *testing.T) {+ for _, tc := range []struct {+ toolName string+ kind string+ }{+ {"write_file", "WriteFileObservation"},+ {"edit", "EditObservation"},+ } {+ t.Run(tc.toolName, func(t *testing.T) {+ logPath := openHandsTestSetup(t)++ runHookWithInput(t, runPostTool, map[string]interface{}{+ "event_type": "PostToolUse",+ "session_id": "oh-session-1",+ "working_dir": "/workspace/project",+ "tool_name": tc.toolName,+ "tool_input": map[string]interface{}{"file_path": "/workspace/project/app.ts", "content": "b\n"},+ "tool_response": map[string]interface{}{+ "kind": tc.kind,+ "is_error": false,+ "file_path": "/workspace/project/app.ts",+ "is_new_file": false,+ "old_content": "a\n",+ "new_content": "b\n",+ },+ })++ event := lastEndpointEvent(t, logPath)+ if got := leaf(event, "event", "action"); got != "file.modified" {+ t.Fatalf("event.action = %q, want file.modified", got)+ }+ if got := leaf(event, "file", "path"); got != "/workspace/project/app.ts" {+ t.Fatalf("file.path = %q, want the written path", got)+ }+ if diff := leaf(event, "file", "diff"); !strings.Contains(diff, "-a") || !strings.Contains(diff, "+b") {+ t.Fatalf("file.diff = %q, want the content change", diff)+ }+ })+ }+}++// ---------------------------------------------------------------------------+// Taxonomy+// ---------------------------------------------------------------------------++// The read-side built-ins. `glob` and `grep` take a `path` that is a directory to search rather+// than a file that was read; recording it under file.path with operation "read" is the same shape+// Qwen Code's equivalents produce and the honest one -- a search did happen, and that is what it+// touched.+func TestOpenHandsReadToolsAreClassifiedAsFileReads(t *testing.T) {+ setupHookConfigDirs(t)+ platformFlag = openHandsPlatform++ for _, toolName := range []string{"read_file", "list_directory", "glob", "grep"} {+ t.Run(toolName, func(t *testing.T) {+ if got := actionForTool("PostToolUse", toolName, nil, nil); got != "file.read" {+ t.Errorf("actionForTool(%q) = %q, want file.read", toolName, got)+ }+ if got := openHandsFileOperation(toolName, nil, nil); got != "read" {+ t.Errorf("openHandsFileOperation(%q) = %q, want read", toolName, got)+ }+ })+ }+}++// The tools with no filesystem or shell meaning stay on the shared path, where tool.invoked is+// already the right answer. Returning "" from the OpenHands classifier rather than a default is+// what keeps them there.+func TestOpenHandsNonFilesystemToolsFallThroughToTheGenericClassifier(t *testing.T) {+ setupHookConfigDirs(t)+ platformFlag = openHandsPlatform++ for _, toolName := range []string{"think", "finish", "task_tracker", "browser_navigate", "browser_click", "invoke_skill", "ask_oracle"} {+ t.Run(toolName, func(t *testing.T) {+ if got := openHandsToolAction(toolName, nil, nil); got != "" {+ t.Errorf("openHandsToolAction(%q) = %q, want \"\" so the shared classifier decides", toolName, got)+ }+ if got := actionForTool("PostToolUse", toolName, nil, nil); got != "tool.invoked" {+ t.Errorf("actionForTool(%q) = %q, want tool.invoked", toolName, got)+ }+ })+ }+}++// The OpenHands taxonomy must not leak into other runtimes. `file_editor`, `glob` and `grep` are+// plausible tool names elsewhere, and claiming them for every platform would rewrite another+// runtime's recorded actions with no fixture to say what they should become.+func TestOpenHandsTaxonomyIsScopedToTheOpenHandsPlatform(t *testing.T) {+ setupHookConfigDirs(t)+ platformFlag = "claude"++ toolInput := map[string]interface{}{"command": "view", "path": "/repo/main.go"}+ if got := actionForTool("PostToolUse", "file_editor", toolInput, nil); got == "file.read" {+ t.Fatalf("actionForTool(claude, file_editor) = %q; the OpenHands editor taxonomy leaked", got)+ }+ if got := actionForTool("PostToolUse", "glob", nil, nil); got != "tool.invoked" {+ t.Fatalf("actionForTool(claude, glob) = %q, want the claude classification unchanged", got)+ }+}++// ---------------------------------------------------------------------------+// MCP+// ---------------------------------------------------------------------------++// OpenHands calls an MCP tool by whatever name its server gave it, with no prefix and no mcp_*+// argument, so every generic signal misses it and the call would be recorded as an ordinary+// tool.invoked. The observation is what says so: an MCP call returns MCPToolObservation.+func TestOpenHandsMCPToolCallIsRecognizedFromTheObservation(t *testing.T) {+ logPath := openHandsTestSetup(t)++ runHookWithInput(t, runPostTool, map[string]interface{}{+ "event_type": "PostToolUse",+ "session_id": "oh-session-1",+ "working_dir": "/workspace/project",+ "tool_name": "search_issues",+ "tool_input": map[string]interface{}{"query": "is:open"},+ "tool_response": map[string]interface{}{+ "kind": "MCPToolObservation",+ "content": []interface{}{map[string]interface{}{"type": "text", "text": "[Tool 'search_issues' executed.]"}},+ "is_error": false,+ "tool_name": "search_issues",+ },+ })++ event := lastEndpointEvent(t, logPath)+ if got := leaf(event, "event", "action"); got != "mcp.tool_invoked" {+ t.Fatalf("event.action = %q, want mcp.tool_invoked", got)+ }+ if got := leaf(event, "event", "category"); got != "mcp" {+ t.Fatalf("event.category = %q, want mcp", got)+ }+ if got := leaf(event, "mcp", "tool"); got != "search_issues" {+ t.Fatalf("mcp.tool = %q, want the tool the server named", got)+ }+ if got := leaf(event, "mcp", "method", "name"); got != "tools/call" {+ t.Fatalf("mcp.method.name = %q, want tools/call", got)+ }+}++// An MCP tool's name is chosen by whoever wrote the server and can collide with any built-in id,+// so a result that says it came from MCP outranks a name that happens to match.+func TestOpenHandsMCPObservationOutranksACollidingBuiltinName(t *testing.T) {+ setupHookConfigDirs(t)+ platformFlag = openHandsPlatform++ response := map[string]interface{}{"kind": "MCPToolObservation", "tool_name": "edit"}+ if got := openHandsToolAction("edit", map[string]interface{}{"path": "/x.go"}, response); got != "mcp.tool_invoked" {+ t.Fatalf("openHandsToolAction(edit, MCP result) = %q, want mcp.tool_invoked", got)+ }+}++// Matched exactly rather than by substring: `kind` is a class name from a closed set, not free+// text, so a substring rule would claim any future observation class whose name merely contained+// these letters.+func TestOpenHandsMCPDetectionMatchesTheObservationKindExactly(t *testing.T) {+ for _, kind := range []string{"TerminalObservation", "FileEditorObservation", "MCPToolObservationExtended", "mcptoolobservation", ""} {+ if openHandsIsMCPToolCall(map[string]interface{}{"kind": kind}) {+ t.Errorf("openHandsIsMCPToolCall(kind=%q) = true, want false", kind)+ }+ }+ if !openHandsIsMCPToolCall(map[string]interface{}{"kind": "MCPToolObservation"}) {+ t.Fatal("openHandsIsMCPToolCall(MCPToolObservation) = false, want true")+ }+ if openHandsIsMCPToolCall(nil) {+ t.Fatal("openHandsIsMCPToolCall(nil) = true, want false")+ }+}++// ---------------------------------------------------------------------------+// Observation content+// ---------------------------------------------------------------------------++// An observation's content is a list of typed parts. Only text is read: an image part carries a+// base64 data URL, often megabytes of it, and describing it would write that into an event field.+func TestOpenHandsObservationTextReadsOnlyTextParts(t *testing.T) {+ got := openHandsObservationText(map[string]interface{}{+ "content": []interface{}{+ map[string]interface{}{"type": "text", "text": "first\n"},+ map[string]interface{}{"type": "image", "image_urls": []interface{}{"data:image/png;base64,AAAA"}},+ map[string]interface{}{"type": "text", "text": "second\n"},+ },+ })+ if got != "first\nsecond\n" {+ t.Fatalf("openHandsObservationText = %q, want the text parts joined in order", got)+ }+ for _, response := range []map[string]interface{}{nil, {}, {"content": "not a list"}, {"content": []interface{}{"not a part"}}} {+ if got := openHandsObservationText(response); got != "" {+ t.Errorf("openHandsObservationText(%#v) = %q, want empty", response, got)+ }+ }+}++// is_error arrives as a JSON bool; the string spelling is tolerated so a payload that reached this+// command by some other route is still read correctly. Nothing else counts as a failure.+func TestOpenHandsToolFailedReadsOnlyIsError(t *testing.T) {+ for _, response := range []map[string]interface{}{+ {"is_error": true},+ {"is_error": "true"},+ {"is_error": "TRUE"},+ } {+ if !openHandsToolFailed(response) {+ t.Errorf("openHandsToolFailed(%#v) = false, want true", response)+ }+ }+ for _, response := range []map[string]interface{}{+ nil,+ {},+ {"is_error": false},+ {"is_error": "false"},+ {"is_error": nil},+ {"exit_code": float64(1)},+ } {+ if openHandsToolFailed(response) {+ t.Errorf("openHandsToolFailed(%#v) = true, want false", response)+ }+ }+}++// ---------------------------------------------------------------------------+// Session lifecycle+// ---------------------------------------------------------------------------++func TestOpenHandsSessionLifecycleEvents(t *testing.T) {+ logPath := openHandsTestSetup(t)++ runHookWithInput(t, runSessionStart, map[string]interface{}{+ "event_type": "SessionStart",+ "session_id": "oh-session-1",+ "working_dir": "/workspace/project",+ "metadata": map[string]interface{}{},+ })+ if got := leaf(lastEndpointEvent(t, logPath), "event", "action"); got != "session.started" {+ t.Fatalf("event.action = %q, want session.started", got)+ }++ // Stop fires when the agent tries to finish. Its metadata carries reason="agent_finished", a+ // constant the SDK passes at its single call site, which is why the payload is not retained.+ //+ // The event is built through emitHookEvent with the arguments runStop passes it, rather than by+ // running the command: runStop ends the session-bearing path with outputJSONAndExit, and os.Exit+ // in an in-process test aborts the run. The mapping this asserts -- that an OpenHands Stop+ // payload yields a session-bearing tool.completed with the workspace attached -- is exactly what+ // the command performs. Same workaround, same reason, as the Qwen Stop test.+ stopInput := map[string]interface{}{+ "event_type": "Stop",+ "session_id": "oh-session-1",+ "working_dir": "/workspace/project",+ "metadata": map[string]interface{}{"reason": "agent_finished"},+ }+ stopSession, _ := resolveSessionIDWithTranscript(stopInput, platformFlag)+ if stopSession != "oh-session-1" {+ t.Fatalf("stop session id = %q; the mapping under test would not run", stopSession)+ }+ emitHookEvent(newHookLogger("stop", platformFlag, stopSession), "tool.completed", "tool", "info",+ "Agent response completed", stopInput, sessionFields(stopSession, stopInput))+ stopEvent := lastEndpointEvent(t, logPath)+ if got := leaf(stopEvent, "event", "action"); got != "tool.completed" {+ t.Fatalf("event.action = %q, want tool.completed", got)+ }+ if got := leaf(stopEvent, "session", "working_directory"); got != "/workspace/project" {+ t.Fatalf("session.working_directory = %q, want the workspace on the stop event", got)+ }++ runHookWithInput(t, runSessionEnd, map[string]interface{}{+ "event_type": "SessionEnd",+ "session_id": "oh-session-1",+ "working_dir": "/workspace/project",+ "metadata": map[string]interface{}{},+ })+ last := lastEndpointEvent(t, logPath)+ if got := leaf(last, "event", "action"); got != "session.ended" {+ t.Fatalf("event.action = %q, want session.ended", got)+ }+ if got := leaf(last, "session", "working_directory"); got != "/workspace/project" {+ t.Fatalf("session.working_directory = %q, want the workspace on the closing event too", got)+ }+}++// metadata is empty on five of the six events and carries a constant on Stop, so retaining the+// payload the way the Qwen and Muse mappings do would cost the whole tool_input and tool_response+// on every event -- file contents included -- to preserve a value that never varies.+func TestOpenHandsDoesNotRetainTheRawPayload(t *testing.T) {+ logPath := openHandsTestSetup(t)++ runHookWithInput(t, runPostTool, map[string]interface{}{+ "event_type": "PostToolUse",+ "session_id": "oh-session-1",+ "working_dir": "/workspace/project",+ "tool_name": "terminal",+ "tool_input": map[string]interface{}{"kind": "TerminalAction", "command": "ls"},+ "tool_response": terminalObservation("ls", float64(0), "main.go\n"),+ })++ event := lastEndpointEvent(t, logPath)+ if raw, ok := event["raw"].(map[string]interface{}); ok {+ if _, present := raw[openHandsPlatform]; present {+ t.Fatalf("event carried raw.openhands: %#v", raw[openHandsPlatform])+ }+ }+}++// ---------------------------------------------------------------------------+// Policy seam+// ---------------------------------------------------------------------------++// The seam is off by default and fails open, but when a provider does deny, the response has to be+// the shape OpenHands reads or the deny is silently dropped and the tool runs anyway.+//+// The reason is worth sending alongside the decision: OpenHands surfaces it in the conversation as+// the explanation for the block and hands it to the agent as the tool's failure, so without it the+// operator and the model both see a call refused with no account of why.+func TestOpenHandsPolicyDenyCarriesADecisionAndAReason(t *testing.T) {+ origPlatform := platformFlag+ t.Cleanup(func() { platformFlag = origPlatform })+ platformFlag = openHandsPlatform++ for _, phase := range []policycontract.Phase{policycontract.PhasePreTool, policycontract.PhasePermissionRequest} {+ deny := policyDenyResponse("rm -rf is blocked", phase)+ if deny == nil {+ t.Fatalf("policyDenyResponse(%v) = nil; OpenHands has a confirmed deny shape", phase)+ }+ if got, _ := deny["decision"].(string); got != "deny" {+ t.Fatalf("decision = %q, want deny", got)+ }+ if got, _ := deny["reason"].(string); got != "rm -rf is blocked" {+ t.Fatalf("reason = %q, want the provider's reason", got)+ }+ }+}diff --git a/cli/beacon-hooks/cmd/policy.go b/cli/beacon-hooks/cmd/policy.goindex 515ea5d9..6991a401 100644--- a/cli/beacon-hooks/cmd/policy.go+++ b/cli/beacon-hooks/cmd/policy.go@@ -71,7 +71,11 @@ func newPolicyCandidate(input map[string]interface{}, sessionID string) policyCa}}- action := actionForTool(hookEvent, toolName)+ // The candidate describes a call that has not run yet, so there is no result to pass. On a+ // runtime whose MCP calls are only identifiable from their result, an MCP tool therefore+ // reaches the provider as the action its name implies -- stated rather than hidden, and the+ // same limit the telemetry path has on PreToolUse.+ action := actionForTool(hookEvent, toolName, toolInput, nil)// A command-bearing call with no more specific action is a command execution.if action == "tool.invoked" {if _, ok := fields["command"]; ok {@@ -170,6 +174,17 @@ func policyDenyResponse(reason string, phase policycontract.Phase) map[string]inreturn map[string]interface{}{"decision": "reject"}case platformFlag == "antigravity" || platformFlag == "grok":return map[string]interface{}{"decision": "deny"}+ // OpenHands reads the same `decision` key, and also a `reason` that antigravity and grok have+ // no field for. The reason is worth sending: OpenHands surfaces it in the conversation as the+ // explanation for the block and hands it to the agent as the tool's failure, so without it the+ // operator and the model both see a call refused with no account of why.+ //+ // Exit code 2 is the documented alternative to this object, not a requirement alongside it:+ // the executor parses stdout first and a parsed `decision: deny` sets blocked regardless of the+ // code. Beacon exits 0 on every hook path, so saying it in the object is the only shape that+ // works without changing that.+ case platformFlag == openHandsPlatform:+ return map[string]interface{}{"decision": "deny", "reason": reason}// Qwen Code shares Claude Code's deny shape exactly: `hookSpecificOutput.permissionDecision`// with a `permissionDecisionReason`, both required by its PreToolUse contract. The// `hookEventName` stays "PreToolUse" in both phases the seam runs in, matching the existingdiff --git a/cli/beacon-hooks/cmd/post_tool.go b/cli/beacon-hooks/cmd/post_tool.goindex 85bd537c..2c29bacd 100644--- a/cli/beacon-hooks/cmd/post_tool.go+++ b/cli/beacon-hooks/cmd/post_tool.go@@ -67,6 +67,22 @@ func runPostTool(cmd *cobra.Command, args []string) {}// afterFileEdit exposes file-edit metadata and diffs; retention controls raw diff inclusion.params = parseCursorInput(input, logger)+ } else if platformFlag == openHandsPlatform {+ // OpenHands is the one runtime whose single post-tool payload can describe several file+ // edits: one apply_patch call commits a change per file and reports them together, keyed+ // by path. The shared evaluationParams describes one file, so this branch records each+ // edit itself rather than returning a params the loop below would flatten to the first.+ //+ // An empty result means this payload is not a file edit -- a view, a shell command, a tool+ // whose observation reports no content change -- and it falls through to+ // emitPostToolObserved with params still nil, which is where the tool call is recorded.+ if edits := parseOpenHandsEdits(input, logger); len(edits) > 0 {+ for _, edit := range edits {+ recordLocalEdit(edit, input, logger)+ }+ outputJSON(emptyResponse)+ return+ }} else {params = parseClaudeCopilotInput(input, logger)}@@ -369,7 +385,18 @@ func emitPostToolObserved(logger *logging.Logger, input map[string]interface{})emitHookEvent(logger, "tool.failed", "tool", "high", "Tool execution failed", input, fields)return}- action := actionForTool(hookEvent, toolName)+ // OpenHands reports a failure nowhere near the two places checked above: there is no failure+ // event name and no top-level `error`, only `is_error` on the observation. Same predicate the+ // diff path uses, called rather than restated, so the two cannot drift the way the Qwen pair+ // once did.+ if platformFlag == openHandsPlatform {+ applyOpenHandsToolResult(fields, toolName, toolInput, toolResponse)+ if openHandsToolFailed(toolResponse) {+ emitHookEvent(logger, "tool.failed", "tool", "high", "Tool execution failed", input, fields)+ return+ }+ }+ action := actionForTool(hookEvent, toolName, toolInput, toolResponse)category := "tool"if strings.HasPrefix(action, "file.") {category = "file"diff --git a/cli/beacon-hooks/cmd/pre_tool.go b/cli/beacon-hooks/cmd/pre_tool.goindex 129e00ba..08e9f596 100644--- a/cli/beacon-hooks/cmd/pre_tool.go+++ b/cli/beacon-hooks/cmd/pre_tool.go@@ -50,13 +50,20 @@ func runPreTool(cmd *cobra.Command, args []string) {} else if platformFlag == "antigravity" {emitAntigravityPromptFromTranscript(logger, input, sessionID)emitPreToolObserved(logger, input, sessionID)- } else if platformFlag == "claude" || platformFlag == "qwen" || isDevinLikePlatform(platformFlag) || platformFlag == "grok" || platformFlag == "hermes" || platformFlag == "vscode" || platformFlag == "muse" {+ } else if platformFlag == "claude" || platformFlag == "qwen" || isDevinLikePlatform(platformFlag) || platformFlag == "grok" || platformFlag == "hermes" || platformFlag == "vscode" || platformFlag == "muse" || platformFlag == openHandsPlatform {// Muse Code belongs on the observing side rather than with the runtimes whose pre-tool// notification gets turned into a synthesized approval, and the reason is that it has a// real one. Its PermissionRequest event is a separate hook Beacon also subscribes to, so// deriving an approval.allowed from PreToolUse as well would record two approvals for one// tool call -- one of them inferred and describing nothing an operator did -- and put an// invented decision next to a reported one for the same call.+ //+ // OpenHands is on the same side for the opposite reason: it exposes no approval hook at+ // all. PreToolUse is the only pre-tool signal it sends, and it announces a tool call the+ // agent is about to make, not a question anybody was asked -- its own confirmation mode is+ // not surfaced to hooks. Synthesizing approval.allowed from it would put an operator+ // decision in the log that no operator made, which is the call Cline, Pi and fx already+ // settled the same way.emitPreToolObserved(logger, input, sessionID)} else {emitPreToolDecision(logger, input, sessionID, "approval.allowed", "allow", "Pre-tool observed", asymptoteobserve.FidelityInferred)@@ -132,7 +139,14 @@ func preToolResponse() map[string]interface{} {// not a preference: its hook runner rejects a stdout object carrying keys it does not know, so// `{"permission":"allow"}` would not read as a permissive answer -- it would fail the hook run// outright. Emitting nothing speculative is the only shape that leaves a Muse turn untouched.- if platformFlag == "claude" || platformFlag == "qwen" || isDevinLikePlatform(platformFlag) || platformFlag == "hermes" || platformFlag == "vscode" || platformFlag == "muse" {+ // OpenHands is here for the Qwen reason rather than the Muse one. It parses a hook's stdout as+ // JSON and acts on `decision`, `reason`, `additionalContext` and `continue`; a `permission` key+ // is not among them, so `{"permission":"allow"}` is inert on today's build. It is still the+ // wrong thing to send. The string is stored verbatim on the HookExecutionEvent OpenHands shows+ // in the conversation, so it puts a decision Beacon did not make in front of the user -- and if+ // OpenHands ever reads that key, an observing hook would begin approving tool calls on the+ // user's behalf without a line of Beacon changing. An empty object asserts nothing either way.+ if platformFlag == "claude" || platformFlag == "qwen" || isDevinLikePlatform(platformFlag) || platformFlag == "hermes" || platformFlag == "vscode" || platformFlag == "muse" || platformFlag == openHandsPlatform {return emptyResponse}return allowResponsediff --git a/cli/beacon-hooks/cmd/pre_tool_test.go b/cli/beacon-hooks/cmd/pre_tool_test.goindex 46c01fb2..b5752cd1 100644--- a/cli/beacon-hooks/cmd/pre_tool_test.go+++ b/cli/beacon-hooks/cmd/pre_tool_test.go@@ -927,6 +927,7 @@ func setupHookConfigDirs(t *testing.T) {"grok": &hookconfig.GrokDir,"hermes": &hookconfig.HermesDir,"muse": &hookconfig.MuseDir,+ "openhands": &hookconfig.OpenHandsDir,"opencode": &hookconfig.OpenCodeDir,"qwen": &hookconfig.QwenDir,"vscode": &hookconfig.VSCodeDir,diff --git a/cli/beacon-hooks/cmd/prompt_submit.go b/cli/beacon-hooks/cmd/prompt_submit.goindex 08f78970..e87929a0 100644--- a/cli/beacon-hooks/cmd/prompt_submit.go+++ b/cli/beacon-hooks/cmd/prompt_submit.go@@ -42,6 +42,9 @@ func runPromptSubmit(cmd *cobra.Command, args []string) {if isCascadePlatform(platformFlag) {prompt = cascadePrompt(input)}+ if platformFlag == openHandsPlatform {+ prompt = openHandsPrompt(input)+ }hasPrompt := prompt != ""if hasPrompt {fields["prompt"] = map[string]interface{}{"text": prompt}diff --git a/cli/beacon-hooks/cmd/qwen_event_test.go b/cli/beacon-hooks/cmd/qwen_event_test.goindex 2521a03f..fd816302 100644--- a/cli/beacon-hooks/cmd/qwen_event_test.go+++ b/cli/beacon-hooks/cmd/qwen_event_test.go@@ -80,7 +80,7 @@ func TestQwenBuiltInToolsMapOntoTheRightAction(t *testing.T) {"skill": "tool.invoked",} {t.Run(toolName, func(t *testing.T) {- if got := actionForTool("PostToolUse", toolName); got != want {+ if got := actionForTool("PostToolUse", toolName, nil, nil); got != want {t.Errorf("actionForTool(PostToolUse, %q) = %q, want %q", toolName, got, want)}})@@ -98,7 +98,7 @@ func TestQwenTaxonomyDoesNotClaimMCPTools(t *testing.T) {for _, toolName := range []string{"mcp__notion__edit", "mcp__fs__glob", "mcp__github__read_file", "mcp__shell__run_shell_command",} {- if got := actionForTool("PostToolUse", toolName); got != "mcp.tool_invoked" {+ if got := actionForTool("PostToolUse", toolName, nil, nil); got != "mcp.tool_invoked" {t.Errorf("actionForTool(%q) = %q, want mcp.tool_invoked", toolName, got)}if isFileEditTool("qwen", toolName) {@@ -115,7 +115,7 @@ func TestQwenTaxonomyIsScopedToTheQwenPlatform(t *testing.T) {t.Cleanup(func() { platformFlag = origPlatform })platformFlag = "claude"- if got := actionForTool("PostToolUse", "list_directory"); got != "tool.invoked" {+ if got := actionForTool("PostToolUse", "list_directory", nil, nil); got != "tool.invoked" {t.Errorf("actionForTool(claude, list_directory) = %q, want the claude classification unchanged", got)}if isFileEditTool("claude", "replace") {diff --git a/cli/beacon-hooks/cmd/root.go b/cli/beacon-hooks/cmd/root.goindex 6b30069e..f3e7be58 100644--- a/cli/beacon-hooks/cmd/root.go+++ b/cli/beacon-hooks/cmd/root.go@@ -29,8 +29,8 @@ var (var rootCmd = &cobra.Command{Use: "beacon-hooks",- Short: "Beacon hooks for Claude Code, Codex, GitHub Copilot, Cursor, VS Code, Devin, Factory, Grok, Hermes, Antigravity, opencode, Qwen Code, Muse Code, and Cline",- Long: `Beacon hooks binary for Claude Code, Codex, GitHub Copilot, Cursor, VS Code, Devin, Factory, Grok, Hermes, Antigravity, opencode, Qwen Code, Muse Code, and Cline integration.+ Short: "Beacon hooks for Claude Code, Codex, GitHub Copilot, Cursor, VS Code, Devin, Factory, Grok, Hermes, Antigravity, opencode, OpenHands, Qwen Code, Muse Code, and Cline",+ Long: `Beacon hooks binary for Claude Code, Codex, GitHub Copilot, Cursor, VS Code, Devin, Factory, Grok, Hermes, Antigravity, opencode, OpenHands, Qwen Code, Muse Code, and Cline integration.This binary provides hook commands that are called by IDE plugin systemsto evaluate code changes for security violations.@@ -39,7 +39,7 @@ Use --platform to specify the calling platform (default: claude).`,}func init() {- rootCmd.PersistentFlags().StringVar(&platformFlag, "platform", "claude", "Platform context: claude, cline, codex, antigravity, copilot, cursor, vscode, devin, devin-cli, devin-desktop, factory, grok, hermes, muse, opencode, or qwen")+ rootCmd.PersistentFlags().StringVar(&platformFlag, "platform", "claude", "Platform context: claude, cline, codex, antigravity, copilot, cursor, vscode, devin, devin-cli, devin-desktop, factory, grok, hermes, muse, opencode, openhands, or qwen")rootCmd.PersistentFlags().StringVar(&logFlag, "log", "", "Endpoint runtime log to append to (same value as BEACON_ENDPOINT_LOG)")rootCmd.PersistentFlags().StringVar(&configFlag, "config", "", "Endpoint config to read (same value as BEACON_ENDPOINT_CONFIG)")rootCmd.PersistentFlags().StringVar(&cliFlag, "cli", "", "Path to the beacon CLI for inventory heartbeats (same value as BEACON_ENDPOINT_CLI)")diff --git a/cli/beacon-hooks/internal/config/config.go b/cli/beacon-hooks/internal/config/config.goindex 12ed7f8f..670d2e55 100644--- a/cli/beacon-hooks/internal/config/config.go+++ b/cli/beacon-hooks/internal/config/config.go@@ -23,6 +23,7 @@ var (OpenCodeDir = filepath.Join(BeaconDir, "opencode")QwenDir = filepath.Join(BeaconDir, "qwen")MuseDir = filepath.Join(BeaconDir, "muse")+ OpenHandsDir = filepath.Join(BeaconDir, "openhands")ClineDir = filepath.Join(BeaconDir, "cline"))@@ -106,6 +107,8 @@ func GetStateDir(platform string) string {return QwenDircase "muse":return MuseDir+ case "openhands":+ return OpenHandsDircase "cline":return ClineDirdefault:diff --git a/cli/beacon-hooks/internal/diff/diff.go b/cli/beacon-hooks/internal/diff/diff.goindex 1053d7c7..7bcc2de7 100644--- a/cli/beacon-hooks/internal/diff/diff.go+++ b/cli/beacon-hooks/internal/diff/diff.go@@ -343,3 +343,29 @@ func getIntFromMap(m map[string]interface{}, key string, defaultVal int) int {}return defaultVal}++// FromContentChange builds a unified diff from an observation that reports a file's whole content+// before and after an edit, rather than the edit instruction the model wrote.+//+// This is the accurate direction. Every other constructor in this file reconstructs a diff from+// what the model *asked* for -- an old_string/new_string pair, a patch body, a full-file write --+// which is a statement of intent, and the reconstruction is only as right as the assumption that+// the tool did exactly what it was told. A runtime that reports the file's before and after has+// already answered the question, so nothing has to be inferred: an insert at line 40 and a+// str_replace of one occurrence both come back as the same two strings and produce a diff that+// matches what is on disk.+//+// OpenHands is the runtime that exposes it. Its file_editor, write_file and edit observations all+// carry old_content/new_content, and its five editor commands (create, str_replace, insert,+// undo_edit, view) are multiplexed on one tool name, so a name-keyed reconstruction could not tell+// an insert from a replace in the first place.+//+// An unchanged file yields no diff. undo_edit that restores identical content, and a patch entry+// whose two sides match, both arrive here and are not edits; returning a header with an empty hunk+// would record that a file changed when it did not.+func FromContentChange(filePath, oldContent, newContent string) string {+ if filePath == "" || oldContent == newContent {+ return ""+ }+ return fromWriteTool(filePath, newContent, oldContent)+}diff --git a/cli/beacon-hooks/internal/diff/diff_test.go b/cli/beacon-hooks/internal/diff/diff_test.goindex e521091e..9c30207e 100644--- a/cli/beacon-hooks/internal/diff/diff_test.go+++ b/cli/beacon-hooks/internal/diff/diff_test.go@@ -185,3 +185,71 @@ func TestFromToolResponseResolvesAbsolutePathParameter(t *testing.T) {t.Fatalf("diff = %q, want the absolute_path target and its content", got)}}++// FromContentChange is the one constructor here that is given the answer rather than asked to+// infer it, so these cases pin the three shapes an observation can report: a modification, a+// creation, and a deletion.+func TestFromContentChangeBuildsAReplacementDiff(t *testing.T) {+ got := FromContentChange("/workspace/main.go", "package main\n\nfunc old() {}\n", "package main\n\nfunc new() {}\n")+ for _, want := range []string{"--- a/main.go", "+++ b/main.go", "-func old() {}", "+func new() {}"} {+ if !strings.Contains(got, want) {+ t.Errorf("FromContentChange missing %q:\n%s", want, got)+ }+ }+}++func TestFromContentChangeBuildsANewFileDiff(t *testing.T) {+ got := FromContentChange("/workspace/new.py", "", "print('hi')\n")+ if !strings.Contains(got, "@@ -0,0 +1,") {+ t.Errorf("FromContentChange = %q, want a new-file hunk header", got)+ }+ if !strings.Contains(got, "+print('hi')") {+ t.Errorf("FromContentChange = %q, want the added line", got)+ }+ if removed := diffBodyLines(got, "-"); len(removed) != 0 {+ t.Errorf("FromContentChange = %q, want no removed lines for a new file, got %v", got, removed)+ }+}++// diffBodyLines returns the diff's content lines starting with prefix, skipping the ---/+++ file+// headers so that a "+++ b/x" header is not mistaken for an added line.+func diffBodyLines(diff, prefix string) []string {+ var out []string+ for _, line := range strings.Split(diff, "\n") {+ if strings.HasPrefix(line, "---") || strings.HasPrefix(line, "+++") || strings.HasPrefix(line, "@@") {+ continue+ }+ if strings.HasPrefix(line, prefix) {+ out = append(out, line)+ }+ }+ return out+}++func TestFromContentChangeBuildsADeletionDiff(t *testing.T) {+ got := FromContentChange("/workspace/gone.go", "package main\n", "")+ if !strings.Contains(got, "-package main") {+ t.Errorf("FromContentChange = %q, want the removed line", got)+ }+ if added := diffBodyLines(got, "+"); len(added) != 0 {+ t.Errorf("FromContentChange = %q, want no added lines for a deletion, got %v", got, added)+ }+}++// An unchanged file is not an edit. Returning a header with an empty hunk would record that a file+// changed when it did not -- which is the failure this constructor exists to avoid, because a+// runtime that reports before and after can legitimately report them equal (an undo that restores+// identical content, a patch entry whose two sides match).+func TestFromContentChangeReturnsNothingWhenTheContentIsUnchanged(t *testing.T) {+ for _, tc := range []struct{ name, path, oldContent, newContent string }{+ {"identical", "/workspace/main.go", "same\n", "same\n"},+ {"both empty", "/workspace/main.go", "", ""},+ {"no path", "", "a\n", "b\n"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ if got := FromContentChange(tc.path, tc.oldContent, tc.newContent); got != "" {+ t.Errorf("FromContentChange = %q, want empty", got)+ }+ })+ }+}