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
Add optional, off-by-default policy provider seam to the hook path
Claude9b9d0d9b650b
diff --git a/CLAUDE.md b/CLAUDE.mdindex 06a3529d..82b5f109 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -37,6 +37,7 @@ Supported runtime surfaces today:- A local-only dashboard served by `beacon endpoint dashboard`, bound to loopback by default and backed by the runtime JSONL log.- Token usage and runtime-reported cost capture across spans, logs, and metric datapoints, normalized into `gen_ai.usage`, with attribution rollups served by the dashboard token view (`/api/tokens`) and the `beacon token-usage` report command for local and CI logs.- Local threat detection via `beacon scan`, which runs the open Threat Rules format (`spec/threat-rules`; CEL match conditions over the endpoint event schema, with embedded conformance fixtures) over the runtime JSONL. The engine (`pkg/asymptoteobserve/threatrules`) ships in the binary; the rule corpus is external data loaded from a local store (`~/.beacon/endpoint/rules`) managed by `beacon rules`, so the corpus can grow without enlarging the binary. `scan` is read-only and offline; only the explicit, user-initiated `beacon rules pull <url>` reaches the network. A small frozen baseline is embedded so `scan` works before any rules are installed.+- An optional, off-by-default policy seam in the hook path (`cli/beacon-hooks/internal/policy`) governed by the stable contract in `pkg/asymptoteobserve/policycontract`. When `BEACON_POLICY_PROVIDER` names an executable, the `pre-tool` and `permission-request` hooks send it a JSON request describing the imminent tool call and honor an allow/deny response, returning the runtime's native deny shape and `policy.enforcement=enforce` telemetry on a deny. The seam is inert when unset and fail-open on any error (timeout, non-zero exit, malformed output), so the open build ships no enforcement of its own; all audit/enforce decision logic lives in the external provider. `rules/agent-control/agent-permission-bypass-spawn` is the open detect twin that flags the same pattern in `beacon scan`.Current non-goals unless explicitly requested:diff --git a/cli/beacon-hooks/cmd/permission_request.go b/cli/beacon-hooks/cmd/permission_request.goindex fe06b76b..e4d074ab 100644--- a/cli/beacon-hooks/cmd/permission_request.go+++ b/cli/beacon-hooks/cmd/permission_request.go@@ -4,6 +4,7 @@ import ("github.com/spf13/cobra""github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/logging"+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/policycontract")var permissionRequestCmd = &cobra.Command{@@ -38,6 +39,11 @@ func runPermissionRequest(cmd *cobra.Command, args []string) {logger = logging.NewLoggerForPlatform("permission-request", platformFlag)}+ if deny, denied := enforcePolicy(logger, input, sessionID, policycontract.PhasePermissionRequest); denied {+ outputJSON(deny)+ return+ }+if isDevinLikePlatform(platformFlag) {emitPreToolDecision(logger, input, sessionID, "approval.allowed", "approve", "Permission request approved")outputJSON(devinApproveResponse)diff --git a/cli/beacon-hooks/cmd/policy.go b/cli/beacon-hooks/cmd/policy.gonew file mode 100644index 00000000..1a7ff044--- /dev/null+++ b/cli/beacon-hooks/cmd/policy.go@@ -0,0 +1,175 @@+package cmd++import (+ "context"+ "encoding/json"+ "strings"++ "github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/logging"+ "github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/policy"+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/policycontract"+)++// policyCandidate describes the imminent tool call. The same fields feed both the+// provider request event and, on a deny, the denial telemetry event.+type policyCandidate struct {+ action string+ category string+ fields map[string]interface{}+}++// enforcePolicy consults the configured policy provider for the imminent tool+// call. If the provider denies and the current platform has a deny response+// shape, it records denial telemetry and returns that response plus true.+// Otherwise it returns nil, false and the caller proceeds with the normal allow+// flow. It is a no-op (nil, false) when no provider is configured.+func enforcePolicy(logger *logging.Logger, input map[string]interface{}, sessionID string, phase policycontract.Phase) (map[string]interface{}, bool) {+ if !policy.Enabled() {+ return nil, false+ }+ candidate := newPolicyCandidate(input, sessionID)+ resp := policy.Evaluate(context.Background(), policy.Request{+ Phase: phase,+ Platform: platformFlag,+ Event: candidate.event(),+ })+ if !resp.Denied() {+ return nil, false+ }+ reason := strings.TrimSpace(resp.Reason)+ if reason == "" {+ reason = "Tool call denied by policy provider"+ }+ deny := policyDenyResponse(phase, reason)+ if deny == nil {+ // Platform has no deny shape: honor "unknown platform -> allow".+ return nil, false+ }+ emitPolicyDenied(logger, input, candidate, resp, reason)+ return deny, true+}++// newPolicyCandidate builds the candidate from hook input the same way the+// telemetry path does (session + tool fields), plus a top-level command fallback+// for runtimes (e.g. Cursor shell hooks) that carry the command outside tool input.+func newPolicyCandidate(input map[string]interface{}, sessionID string) policyCandidate {+ toolName := getFirstStr(input, "tool_name", "toolName")+ if platformFlag == "antigravity" {+ toolName = antigravityToolName(input)+ }+ toolInput := resolveToolInput(input)+ hookEvent := getFirstStr(input, "hook_event_name", "hookEventName")++ fields := sessionFields(sessionID, input)+ for key, value := range toolFields(toolName, toolInput) {+ fields[key] = value+ }+ if _, ok := fields["command"]; !ok {+ if command := getFirstStr(input, "command"); command != "" {+ fields["command"] = map[string]interface{}{"command": command}+ }+ }++ action := actionForTool(hookEvent, toolName)+ // A command-bearing call with no more specific action is a command execution.+ if action == "tool.invoked" {+ if _, ok := fields["command"]; ok {+ action = "command.executed"+ }+ }+ return policyCandidate{action: action, category: categoryForAction(action), fields: fields}+}++func categoryForAction(action string) string {+ switch {+ case strings.HasPrefix(action, "command."):+ return "command"+ case strings.HasPrefix(action, "file."):+ return "file"+ case strings.HasPrefix(action, "mcp."):+ return "mcp"+ case strings.HasPrefix(action, "approval.") || strings.HasPrefix(action, "policy."):+ return "approval"+ default:+ return "tool"+ }+}++// event builds the asymptoteobserve.Event sent to the provider via a JSON+// round-trip of the same field map the telemetry writer uses, so the provider+// sees the same shape it would match in the runtime JSONL.+func (c policyCandidate) event() asymptoteobserve.Event {+ envelope := map[string]interface{}{+ "vendor": "beacon",+ "product": "endpoint-agent",+ "schema_version": "1.0",+ "event": map[string]interface{}{+ "kind": "agent_runtime",+ "action": c.action,+ "category": c.category,+ },+ "harness": map[string]interface{}{"name": platformFlag},+ }+ for key, value := range c.fields {+ envelope[key] = value+ }+ var ev asymptoteobserve.Event+ data, err := json.Marshal(envelope)+ if err != nil {+ return ev+ }+ _ = json.Unmarshal(data, &ev)+ return ev+}++// emitPolicyDenied records the denial as endpoint telemetry, carrying+// policy.enforcement=enforce / policy.decision=deny and the matching approval+// fields.+func emitPolicyDenied(logger *logging.Logger, input map[string]interface{}, c policyCandidate, resp policycontract.Response, reason string) {+ fields := c.fields+ fields["approval"] = map[string]interface{}{+ "required": true,+ "decision": "deny",+ "reason": reason,+ }+ policyField := map[string]interface{}{+ "enforcement": "enforce",+ "decision": "deny",+ "reason": reason,+ }+ if resp.RuleID != "" {+ policyField["id"] = resp.RuleID+ }+ fields["policy"] = policyField++ severity := strings.TrimSpace(resp.Severity)+ if severity == "" {+ severity = "high"+ }+ emitHookEvent(logger, "approval.denied", "approval", severity, reason, input, fields)+}++// policyDenyResponse returns the runtime-specific hook response that denies the+// tool call. A nil return means the platform has no confirmed deny shape for this+// phase, so the caller allows (unknown platform -> allow).+func policyDenyResponse(phase policycontract.Phase, reason string) map[string]interface{} {+ switch {+ case platformFlag == "cursor":+ return map[string]interface{}{"permission": "deny"}+ case isDevinLikePlatform(platformFlag):+ return map[string]interface{}{"decision": "reject"}+ case platformFlag == "antigravity" || platformFlag == "grok":+ return map[string]interface{}{"decision": "deny"}+ case platformFlag == "claude" && phase == policycontract.PhasePreTool:+ return map[string]interface{}{+ "hookSpecificOutput": map[string]interface{}{+ "hookEventName": "PreToolUse",+ "permissionDecision": "deny",+ "permissionDecisionReason": reason,+ },+ }+ default:+ return nil+ }+}diff --git a/cli/beacon-hooks/cmd/policy_test.go b/cli/beacon-hooks/cmd/policy_test.gonew file mode 100644index 00000000..387c78aa--- /dev/null+++ b/cli/beacon-hooks/cmd/policy_test.go@@ -0,0 +1,130 @@+package cmd++import (+ "os"+ "path/filepath"+ "runtime"+ "testing"++ "github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/policy"+)++// writeProvider writes an executable shell script that ignores stdin and prints a+// fixed JSON response, then points BEACON_POLICY_PROVIDER at it. Skips on Windows,+// which has no /bin/sh.+func writeProvider(t *testing.T, responseJSON string) {+ t.Helper()+ if runtime.GOOS == "windows" {+ t.Skip("provider script requires a POSIX shell")+ }+ path := filepath.Join(t.TempDir(), "provider.sh")+ script := "#!/bin/sh\ncat >/dev/null\nprintf '%s' '" + responseJSON + "'\n"+ if err := os.WriteFile(path, []byte(script), 0o755); err != nil {+ t.Fatalf("write provider: %v", err)+ }+ t.Setenv(policy.ProviderEnv, path)+}++func setupPolicyTest(t *testing.T, platform, responseJSON string) string {+ t.Helper()+ setupHookConfigDirs(t)+ platformFlag = platform+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)+ writeProvider(t, responseJSON)+ return logPath+}++const denyResponse = `{"decision":"deny","reason":"blocked by test","rule_id":"agent-permission-bypass-spawn","severity":"high","mode":"enforce"}`++func assertDenialEvent(t *testing.T, logPath string) {+ t.Helper()+ event := lastEndpointEvent(t, logPath)+ if action := event["event"].(map[string]interface{})["action"]; action != "approval.denied" {+ t.Fatalf("event.action = %q, want approval.denied", action)+ }+ pol, ok := event["policy"].(map[string]interface{})+ if !ok {+ t.Fatalf("policy field missing: %#v", event)+ }+ if pol["decision"] != "deny" || pol["enforcement"] != "enforce" {+ t.Fatalf("policy = %#v, want decision=deny enforcement=enforce", pol)+ }+ if pol["id"] != "agent-permission-bypass-spawn" {+ t.Fatalf("policy.id = %v, want rule id propagated", pol["id"])+ }+ approval, ok := event["approval"].(map[string]interface{})+ if !ok || approval["decision"] != "deny" {+ t.Fatalf("approval = %#v, want decision=deny", event["approval"])+ }+}++func TestPreToolPolicyDenyCursor(t *testing.T) {+ logPath := setupPolicyTest(t, "cursor", denyResponse)+ out := runHookWithInput(t, runPreTool, map[string]interface{}{+ "conversation_id": "conv-1",+ "command": "claude --dangerously-skip-permissions -p go",+ })+ if out["permission"] != "deny" {+ t.Fatalf("cursor deny response = %#v, want permission=deny", out)+ }+ assertDenialEvent(t, logPath)+}++func TestPreToolPolicyDenyClaude(t *testing.T) {+ logPath := setupPolicyTest(t, "claude", denyResponse)+ out := runHookWithInput(t, runPreTool, map[string]interface{}{+ "session_id": "s-claude",+ "tool_name": "Bash",+ "tool_input": map[string]interface{}{"command": "codex --full-auto"},+ })+ hso, ok := out["hookSpecificOutput"].(map[string]interface{})+ if !ok {+ t.Fatalf("claude deny response = %#v, want hookSpecificOutput", out)+ }+ if hso["permissionDecision"] != "deny" || hso["permissionDecisionReason"] != "blocked by test" {+ t.Fatalf("hookSpecificOutput = %#v, want deny + reason", hso)+ }+ assertDenialEvent(t, logPath)+}++func TestPreToolPolicyDenyDevin(t *testing.T) {+ logPath := setupPolicyTest(t, "devin", denyResponse)+ out := runHookWithInput(t, runPreTool, map[string]interface{}{+ "session_id": "s-devin",+ "tool_name": "exec",+ "tool_input": map[string]interface{}{"command": "goose --yolo"},+ })+ if out["decision"] != "reject" {+ t.Fatalf("devin deny response = %#v, want decision=reject", out)+ }+ assertDenialEvent(t, logPath)+}++func TestPreToolPolicyAllowProceedsNormally(t *testing.T) {+ logPath := setupPolicyTest(t, "cursor", `{"decision":"allow"}`)+ out := runHookWithInput(t, runPreTool, map[string]interface{}{+ "conversation_id": "conv-allow",+ "command": "ls -la",+ })+ if out["permission"] != "allow" {+ t.Fatalf("allow response = %#v, want permission=allow", out)+ }+ event := lastEndpointEvent(t, logPath)+ if action := event["event"].(map[string]interface{})["action"]; action == "approval.denied" {+ t.Fatalf("provider allowed but a denial was emitted: %#v", event)+ }+}++func TestPermissionRequestPolicyDenyDevin(t *testing.T) {+ logPath := setupPolicyTest(t, "devin", denyResponse)+ out := runHookWithInput(t, runPermissionRequest, map[string]interface{}{+ "session_id": "s-devin-perm",+ "tool_name": "exec",+ "tool_input": map[string]interface{}{"command": "claude --dangerously-skip-permissions"},+ })+ if out["decision"] != "reject" {+ t.Fatalf("devin permission-request deny = %#v, want decision=reject", out)+ }+ assertDenialEvent(t, logPath)+}diff --git a/cli/beacon-hooks/cmd/pre_tool.go b/cli/beacon-hooks/cmd/pre_tool.goindex 1fb91ec3..a58e6218 100644--- a/cli/beacon-hooks/cmd/pre_tool.go+++ b/cli/beacon-hooks/cmd/pre_tool.go@@ -11,6 +11,7 @@ import ("github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/logging""github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/state"+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/policycontract")var preToolCmd = &cobra.Command{@@ -44,6 +45,10 @@ func runPreTool(cmd *cobra.Command, args []string) {}logger.Debug("Pre-tool observed")+ if deny, denied := enforcePolicy(logger, input, sessionID, policycontract.PhasePreTool); denied {+ outputJSON(deny)+ return+ }if platformFlag == "cursor" && emitCursorPreHook(logger, input, sessionID) {maybeUploadCursorCloudTelemetry(logger)} else if platformFlag == "antigravity" {diff --git a/cli/beacon-hooks/internal/policy/policy.go b/cli/beacon-hooks/internal/policy/policy.gonew file mode 100644index 00000000..6a0afb40--- /dev/null+++ b/cli/beacon-hooks/internal/policy/policy.go@@ -0,0 +1,89 @@+// Package policy is the hook-side client for the Beacon policy seam. It consults+// an external provider named by BEACON_POLICY_PROVIDER for an allow/deny decision+// on an imminent tool call. It contains no enforcement decision logic of its own —+// it only asks and honors.+//+// The client is inert when no provider is configured, and fail-open on every+// error path (missing provider, marshal failure, exec failure, timeout, non-zero+// exit, malformed output), so the open Beacon build never blocks a tool call by+// default.+package policy++import (+ "bytes"+ "context"+ "encoding/json"+ "os"+ "os/exec"+ "strings"+ "time"++ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/policycontract"+)++// ProviderEnv names the executable consulted for policy decisions. When unset or+// empty, the seam is disabled.+const ProviderEnv = "BEACON_POLICY_PROVIDER"++// Timeout bounds how long a hook waits for a provider decision before failing+// open. It is a package variable so tests can shorten it.+var Timeout = 2 * time.Second++// execCommandContext is overridable in tests.+var execCommandContext = exec.CommandContext++// Request carries everything the client needs to consult the provider.+type Request struct {+ Phase policycontract.Phase+ Platform string+ Event asymptoteobserve.Event+}++// Enabled reports whether a provider is configured. Hooks use this to skip all+// candidate-building work on the default (no-provider) path.+func Enabled() bool {+ return strings.TrimSpace(os.Getenv(ProviderEnv)) != ""+}++// Evaluate consults the configured provider and returns its response. It is+// fail-open: on any error or when no provider is configured it returns an allow+// response.+func Evaluate(ctx context.Context, req Request) policycontract.Response {+ allow := policycontract.Response{Decision: policycontract.DecisionAllow}++ provider := strings.TrimSpace(os.Getenv(ProviderEnv))+ if provider == "" {+ return allow+ }++ payload, err := json.Marshal(policycontract.Request{+ Version: policycontract.Version,+ Phase: req.Phase,+ Platform: req.Platform,+ Event: req.Event,+ })+ if err != nil {+ return allow+ }++ ctx, cancel := context.WithTimeout(ctx, Timeout)+ defer cancel()++ cmd := execCommandContext(ctx, provider)+ cmd.Stdin = bytes.NewReader(payload)+ var stdout bytes.Buffer+ cmd.Stdout = &stdout+ if err := cmd.Run(); err != nil {+ return allow+ }++ var resp policycontract.Response+ if err := json.Unmarshal(bytes.TrimSpace(stdout.Bytes()), &resp); err != nil {+ return allow+ }+ if !resp.Denied() {+ return allow+ }+ return resp+}diff --git a/cli/beacon-hooks/internal/policy/policy_test.go b/cli/beacon-hooks/internal/policy/policy_test.gonew file mode 100644index 00000000..11bb53c8--- /dev/null+++ b/cli/beacon-hooks/internal/policy/policy_test.go@@ -0,0 +1,120 @@+package policy++import (+ "context"+ "os"+ "os/exec"+ "testing"+ "time"++ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/policycontract"+)++// fakeProvider points execCommandContext at this test binary running+// TestHelperProcess with the given behavior, so the client's exec path is+// exercised without an external binary.+func fakeProvider(t *testing.T, behavior string) {+ t.Helper()+ orig := execCommandContext+ execCommandContext = func(ctx context.Context, name string, args ...string) *exec.Cmd {+ cs := append([]string{"-test.run=TestHelperProcess", "--", name}, args...)+ cmd := exec.CommandContext(ctx, os.Args[0], cs...)+ cmd.Env = append(os.Environ(), "GO_WANT_HELPER_PROCESS=1", "HELPER_BEHAVIOR="+behavior)+ return cmd+ }+ t.Cleanup(func() { execCommandContext = orig })+}++func sampleRequest() Request {+ return Request{+ Phase: policycontract.PhasePreTool,+ Platform: "claude",+ Event: asymptoteobserve.Event{+ Event: asymptoteobserve.EventInfo{Action: "command.executed", Category: "command"},+ Command: &asymptoteobserve.CommandInfo{Command: "claude --dangerously-skip-permissions"},+ },+ }+}++func TestEvaluateNoProviderAllows(t *testing.T) {+ os.Unsetenv(ProviderEnv)+ if Enabled() {+ t.Fatal("Enabled() should be false with no provider")+ }+ if got := Evaluate(context.Background(), sampleRequest()); got.Denied() {+ t.Fatalf("expected allow with no provider, got %+v", got)+ }+}++func TestEvaluateProviderDenies(t *testing.T) {+ t.Setenv(ProviderEnv, "fake")+ fakeProvider(t, "deny")+ got := Evaluate(context.Background(), sampleRequest())+ if !got.Denied() {+ t.Fatalf("expected deny, got %+v", got)+ }+ if got.RuleID != "test-rule" || got.Reason != "blocked" {+ t.Fatalf("deny fields not propagated: %+v", got)+ }+}++func TestEvaluateProviderAllows(t *testing.T) {+ t.Setenv(ProviderEnv, "fake")+ fakeProvider(t, "allow")+ if got := Evaluate(context.Background(), sampleRequest()); got.Denied() {+ t.Fatalf("expected allow, got %+v", got)+ }+}++func TestEvaluateFailsOpenOnError(t *testing.T) {+ for _, behavior := range []string{"exit-error", "garbage"} {+ t.Run(behavior, func(t *testing.T) {+ t.Setenv(ProviderEnv, "fake")+ fakeProvider(t, behavior)+ if got := Evaluate(context.Background(), sampleRequest()); got.Denied() {+ t.Fatalf("expected fail-open allow for %q, got %+v", behavior, got)+ }+ })+ }+}++func TestEvaluateFailsOpenOnTimeout(t *testing.T) {+ t.Setenv(ProviderEnv, "fake")+ fakeProvider(t, "sleep")+ orig := Timeout+ Timeout = 100 * time.Millisecond+ t.Cleanup(func() { Timeout = orig })++ start := time.Now()+ got := Evaluate(context.Background(), sampleRequest())+ if got.Denied() {+ t.Fatalf("expected fail-open allow on timeout, got %+v", got)+ }+ if elapsed := time.Since(start); elapsed > 2*time.Second {+ t.Fatalf("timeout not enforced, took %s", elapsed)+ }+}++// TestHelperProcess is not a real test: it is the fake provider invoked by+// fakeProvider via the test binary.+func TestHelperProcess(t *testing.T) {+ if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" {+ return+ }+ switch os.Getenv("HELPER_BEHAVIOR") {+ case "deny":+ os.Stdout.WriteString(`{"decision":"deny","reason":"blocked","rule_id":"test-rule","severity":"high","mode":"enforce"}`)+ case "allow":+ os.Stdout.WriteString(`{"decision":"allow"}`)+ case "garbage":+ os.Stdout.WriteString("not json at all")+ case "exit-error":+ os.Stdout.WriteString(`{"decision":"deny"}`) // output ignored because exit is non-zero+ os.Exit(3)+ case "sleep":+ time.Sleep(3 * time.Second)+ os.Stdout.WriteString(`{"decision":"deny"}`)+ }+ os.Exit(0)+}diff --git a/pkg/asymptoteobserve/policycontract/README.md b/pkg/asymptoteobserve/policycontract/README.mdnew file mode 100644index 00000000..c5c40d08--- /dev/null+++ b/pkg/asymptoteobserve/policycontract/README.md@@ -0,0 +1,70 @@+# Beacon policy provider contract++This package defines the stable, versioned boundary between a Beacon hook and an+external **policy provider** — an executable that decides whether to allow or deny+a tool call an agent runtime is about to make.++It is the public seam that lets anyone plug enforcement into Beacon without Beacon+shipping any enforcement of its own. The open Beacon build only ever **asks and+honors**: it is inert when no provider is configured and **fail-open** on any+error.++## How it works++1. A hook (`beacon-hooks pre-tool` / `permission-request`) reads the environment+ variable `BEACON_POLICY_PROVIDER`. If it is unset, the seam does nothing and+ the tool call proceeds as before.+2. If set, it is the path to a provider executable. The hook writes a single JSON+ [`Request`](./policycontract.go) to the provider's **stdin**.+3. The provider writes a single JSON [`Response`](./policycontract.go) to its+ **stdout** and exits.+4. If the response decision is `deny`, the hook returns the runtime's+ platform-specific deny shape and records `policy.enforcement=enforce` /+ `policy.decision=deny` telemetry. Anything else — including a timeout,+ non-zero exit, or malformed output — is treated as **allow**.++The request `event` is a Beacon endpoint `Event` describing the imminent tool+call, using the same field names as the runtime JSONL log and the open Threat+Rules schema (`spec/threat-rules/FIELDS.md`), so a provider can match it with the+same rule format `beacon scan` uses.++`schema.json` is the JSON Schema for the request and response objects.++## Request++```json+{+ "version": "1",+ "phase": "pre-tool",+ "platform": "claude",+ "event": {+ "vendor": "beacon",+ "product": "endpoint-agent",+ "schema_version": "1.0",+ "event": { "kind": "agent_runtime", "action": "command.executed", "category": "command" },+ "command": { "command": "claude --dangerously-skip-permissions -p \"...\"" },+ "session": { "id": "abc123" }+ }+}+```++## Response++```json+{ "decision": "deny", "reason": "permission-bypass spawn blocked", "rule_id": "agent-permission-bypass-spawn", "severity": "high", "mode": "enforce" }+```++## Minimal provider++Any language works; it just needs to read stdin and write a JSON object to+stdout. A trivial allow-all provider in shell:++```sh+#!/bin/sh+cat >/dev/null # consume the request+printf '{"decision":"allow"}\n'+```++A reference provider that denies permission-bypass spawns lives in+[`refprovider`](./refprovider); build it and point `BEACON_POLICY_PROVIDER` at the+binary to see the seam in action.diff --git a/pkg/asymptoteobserve/policycontract/policycontract.go b/pkg/asymptoteobserve/policycontract/policycontract.gonew file mode 100644index 00000000..062be4c0--- /dev/null+++ b/pkg/asymptoteobserve/policycontract/policycontract.go@@ -0,0 +1,71 @@+// Package policycontract defines the stable, versioned wire contract between a+// Beacon hook (the asker) and an external policy provider (the decider).+//+// The provider is an executable named by the BEACON_POLICY_PROVIDER environment+// variable. Before a hook allows a tool call, it writes a single JSON Request to+// the provider's stdin and reads a single JSON Response from stdout. The provider+// decides allow vs deny; the hook only asks and honors.+//+// The seam is inert when no provider is configured, and fail-open on any error+// (missing provider, timeout, non-zero exit, malformed output) — so the open+// Beacon build ships no enforcement behavior of its own. Both audit and enforce+// behavior live entirely in whatever provider an operator chooses to install.+//+// This package contains only data types: it is safe to import from any module+// (the hooks, the public CLI, or a third-party provider) without pulling in+// runtime behavior.+package policycontract++import "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"++// Version is the contract version carried in every Request. Providers should+// treat an unrecognized version conservatively (typically by allowing).+const Version = "1"++// Phase identifies which hook is consulting the provider.+type Phase string++const (+ // PhasePreTool is a pre-tool-use consultation: a tool call is about to run.+ PhasePreTool Phase = "pre-tool"+ // PhasePermissionRequest is an explicit permission/approval decision request.+ PhasePermissionRequest Phase = "permission-request"+)++// Decision is the provider's verdict.+type Decision string++const (+ DecisionAllow Decision = "allow"+ DecisionDeny Decision = "deny"+)++// Request is written to the provider's stdin as a single JSON object. Event is a+// Beacon endpoint Event describing the imminent tool call (its action, command,+// file, tool, session, and so on) using the same field names the runtime JSONL+// log uses, so a provider can match it with the open Threat Rules format.+type Request struct {+ Version string `json:"version"`+ Phase Phase `json:"phase"`+ Platform string `json:"platform"`+ Event asymptoteobserve.Event `json:"event"`+}++// Response is read from the provider's stdout as a single JSON object. Only+// Decision is required. An empty or unrecognized Decision is treated as allow.+//+// - Reason: human-readable explanation surfaced to the runtime and telemetry.+// - RuleID: identifier of the provider rule that produced the decision.+// - Severity: provider-reported severity (e.g. low/medium/high/critical).+// - Mode: provider-reported posture (e.g. "audit" or "enforce").+type Response struct {+ Decision Decision `json:"decision"`+ Reason string `json:"reason,omitempty"`+ RuleID string `json:"rule_id,omitempty"`+ Severity string `json:"severity,omitempty"`+ Mode string `json:"mode,omitempty"`+}++// Denied reports whether the response explicitly denies the action. Any value+// other than an explicit "deny" is treated as allow (fail-open).+func (r Response) Denied() bool { return r.Decision == DecisionDeny }diff --git a/pkg/asymptoteobserve/policycontract/policycontract_test.go b/pkg/asymptoteobserve/policycontract/policycontract_test.gonew file mode 100644index 00000000..b07fc90b--- /dev/null+++ b/pkg/asymptoteobserve/policycontract/policycontract_test.go@@ -0,0 +1,66 @@+package policycontract++import (+ _ "embed"+ "encoding/json"+ "testing"++ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"+)++//go:embed schema.json+var schemaJSON []byte++func TestSchemaIsValidJSON(t *testing.T) {+ if !json.Valid(schemaJSON) {+ t.Fatal("schema.json is not valid JSON")+ }+}++func TestRequestRoundTrip(t *testing.T) {+ req := Request{+ Version: Version,+ Phase: PhasePreTool,+ Platform: "claude",+ Event: asymptoteobserve.Event{+ Event: asymptoteobserve.EventInfo{Action: "command.executed", Category: "command"},+ Command: &asymptoteobserve.CommandInfo{Command: "claude --dangerously-skip-permissions"},+ },+ }+ data, err := json.Marshal(req)+ if err != nil {+ t.Fatalf("marshal: %v", err)+ }+ var got Request+ if err := json.Unmarshal(data, &got); err != nil {+ t.Fatalf("unmarshal: %v", err)+ }+ if got.Version != Version || got.Phase != PhasePreTool || got.Platform != "claude" {+ t.Fatalf("envelope round trip mismatch: %+v", got)+ }+ if got.Event.Command == nil || got.Event.Command.Command != req.Event.Command.Command {+ t.Fatalf("event round trip mismatch: %+v", got.Event)+ }+}++func TestResponseDenied(t *testing.T) {+ cases := []struct {+ raw string+ deny bool+ }{+ {`{"decision":"deny","reason":"nope","rule_id":"r1","severity":"high","mode":"enforce"}`, true},+ {`{"decision":"allow"}`, false},+ {`{"decision":""}`, false},+ {`{"decision":"DENY"}`, false}, // case-sensitive: only exact "deny" denies+ {`{}`, false},+ }+ for _, c := range cases {+ var resp Response+ if err := json.Unmarshal([]byte(c.raw), &resp); err != nil {+ t.Fatalf("unmarshal %q: %v", c.raw, err)+ }+ if got := resp.Denied(); got != c.deny {+ t.Fatalf("Denied(%q) = %v, want %v", c.raw, got, c.deny)+ }+ }+}diff --git a/pkg/asymptoteobserve/policycontract/refprovider/main.go b/pkg/asymptoteobserve/policycontract/refprovider/main.gonew file mode 100644index 00000000..69228314--- /dev/null+++ b/pkg/asymptoteobserve/policycontract/refprovider/main.go@@ -0,0 +1,53 @@+// Command refprovider is a reference Beacon policy provider. It demonstrates the+// BEACON_POLICY_PROVIDER contract: read a policycontract.Request from stdin, write+// a policycontract.Response to stdout.+//+// This reference denies a single pattern — spawning an AI agent runtime with its+// permission/approval gate disabled (the open detect-twin's enforce counterpart) —+// and allows everything else. It is intentionally tiny and dependency-light so it+// can be copied as a starting point for a real provider. It is not installed by+// the Beacon build and has no effect unless an operator points+// BEACON_POLICY_PROVIDER at it.+package main++import (+ "encoding/json"+ "os"+ "regexp"++ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/policycontract"+)++// agentRuntime matches a known agent CLI invoked as a command head.+var agentRuntime = regexp.MustCompile(`(?i)(^|[;&|]|&&|\|\||\bsudo\s+|\benv\s+|\bnpx\s+)\s*(claude|codex|cursor-agent|aider|goose|opencode|gemini)\b`)++// bypassFlag matches a flag that disables the runtime's permission/approval gate.+var bypassFlag = regexp.MustCompile(`(?i)(--dangerously-skip-permissions|--dangerously-bypass-approvals-and-sandbox|--permission-mode[ =]+bypasspermissions|--sandbox[ =]+danger-full-access|--ask-for-approval[ =]+never|--full-auto|--yolo|(^|\s)-a[ =]+never\b|--force\b)`)++func main() {+ resp := decide(os.Stdin)+ _ = json.NewEncoder(os.Stdout).Encode(resp)+}++func decide(r *os.File) policycontract.Response {+ allow := policycontract.Response{Decision: policycontract.DecisionAllow}++ var req policycontract.Request+ if err := json.NewDecoder(r).Decode(&req); err != nil {+ return allow // fail-open: a provider that cannot parse should not block+ }+ if req.Event.Command == nil {+ return allow+ }+ command := req.Event.Command.Command+ if agentRuntime.MatchString(command) && bypassFlag.MatchString(command) {+ return policycontract.Response{+ Decision: policycontract.DecisionDeny,+ Reason: "AI agent runtime spawned with its permission/approval gate disabled",+ RuleID: "agent-permission-bypass-spawn",+ Severity: "high",+ Mode: "enforce",+ }+ }+ return allow+}diff --git a/pkg/asymptoteobserve/policycontract/schema.json b/pkg/asymptoteobserve/policycontract/schema.jsonnew file mode 100644index 00000000..d9b4aff1--- /dev/null+++ b/pkg/asymptoteobserve/policycontract/schema.json@@ -0,0 +1,59 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": "https://asymptote.sh/schemas/beacon/policy-provider/v1.json",+ "title": "Beacon policy provider contract (v1)",+ "description": "Wire contract between a Beacon hook and an external policy provider named by BEACON_POLICY_PROVIDER. The hook writes a Request to the provider's stdin and reads a Response from its stdout.",+ "$defs": {+ "request": {+ "type": "object",+ "required": ["version", "phase", "platform", "event"],+ "properties": {+ "version": {+ "type": "string",+ "const": "1",+ "description": "Contract version."+ },+ "phase": {+ "type": "string",+ "enum": ["pre-tool", "permission-request"],+ "description": "Which hook is consulting the provider."+ },+ "platform": {+ "type": "string",+ "description": "Agent runtime platform (e.g. claude, cursor, devin)."+ },+ "event": {+ "type": "object",+ "description": "Beacon endpoint Event describing the imminent tool call. Uses the same field names as the runtime JSONL log and the open Threat Rules schema."+ }+ }+ },+ "response": {+ "type": "object",+ "required": ["decision"],+ "properties": {+ "decision": {+ "type": "string",+ "enum": ["allow", "deny"],+ "description": "Verdict. Any value other than \"deny\" is treated as allow (fail-open)."+ },+ "reason": {+ "type": "string",+ "description": "Human-readable explanation surfaced to the runtime and telemetry."+ },+ "rule_id": {+ "type": "string",+ "description": "Identifier of the provider rule that produced the decision."+ },+ "severity": {+ "type": "string",+ "description": "Provider-reported severity (e.g. low, medium, high, critical)."+ },+ "mode": {+ "type": "string",+ "description": "Provider-reported posture (e.g. audit, enforce)."+ }+ }+ }+ }+}