Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

fix(cursor): record the agent's reply from afterAgentResponse

Claude64b11bbb7835
diff --git a/cli/beacon-hooks/cmd/agent_response.go b/cli/beacon-hooks/cmd/agent_response.go
new file mode 100644
index 00000000..b635e5d9
--- /dev/null
+++ b/cli/beacon-hooks/cmd/agent_response.go
@@ -0,0 +1,38 @@
+package cmd
+
+import (
+ "github.com/spf13/cobra"
+)
+
+var agentResponseCmd = &cobra.Command{
+ Use: "agent-response",
+ Short: "Record the agent's reply for local endpoint telemetry",
+ Long: `afterAgentResponse hook - triggered when the agent finishes an assistant message.
+Records the reply text as local endpoint telemetry.`,
+ Run: runAgentResponse,
+}
+
+func init() {
+ rootCmd.AddCommand(agentResponseCmd)
+}
+
+// runAgentResponse is Cursor's afterAgentResponse hook. Cursor documents one event-specific field,
+// `text`, holding the assistant's reply; without this hook a live Cursor session recorded the
+// reasoning (afterAgentThought) and every tool call but not what the agent answered.
+//
+// `text` is read only for Cursor. It is a generic key, and on another runtime's payload it could be
+// the prompt or a tool's output; a reply recorded from the wrong field would be a fabricated
+// message in a security log.
+func runAgentResponse(cmd *cobra.Command, args []string) {
+ input, err := readStdinJSON()
+ if err != nil {
+ outputJSON(hookNoopResponse())
+ return
+ }
+ if platformFlag == "cursor" {
+ sessionID := resolveSessionID(input, platformFlag)
+ logger := newHookLogger("agent-response", platformFlag, sessionID)
+ emitAssistantMessage(logger, input, sessionFields(sessionID, input), getFirstStr(input, "text"))
+ }
+ outputJSON(hookNoopResponse())
+}
diff --git a/cli/beacon-hooks/cmd/agent_response_test.go b/cli/beacon-hooks/cmd/agent_response_test.go
new file mode 100644
index 00000000..9f610464
--- /dev/null
+++ b/cli/beacon-hooks/cmd/agent_response_test.go
@@ -0,0 +1,109 @@
+package cmd
+
+import (
+ "encoding/json"
+ "strings"
+ "testing"
+
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
+)
+
+// cursorAfterAgentResponse is Cursor's documented afterAgentResponse input: the common hook fields
+// plus `text`, the assistant's reply.
+func cursorAfterAgentResponse(text interface{}) map[string]interface{} {
+ payload := map[string]interface{}{
+ "hook_event_name": "afterAgentResponse",
+ "conversation_id": "conv-reply",
+ "generation_id": "gen-9",
+ "model": "claude-opus-5-5",
+ "cursor_version": "3.1.0",
+ "workspace_roots": []interface{}{"/repo"},
+ "user_email": nil,
+ "transcript_path": nil,
+ }
+ if text != nil {
+ payload["text"] = text
+ }
+ return payload
+}
+
+// Cursor reports the reply on afterAgentResponse and nowhere else on its hooks. The hook records it
+// as agent.message, with Cursor's turn (generation_id) as prompt.id, so the reply sits in the same
+// turn as the prompt and reasoning the other Cursor hooks record.
+func TestCursorAgentResponseRecordsTheReply(t *testing.T) {
+ reply := "The build was failing because `go.sum` was stale. I ran `go mod tidy`."
+ logPath, stdout := runHookProcess(t, cursorAfterAgentResponse(reply), "--platform", "cursor", "agent-response")
+
+ var answer map[string]interface{}
+ if err := json.Unmarshal(stdout, &answer); err != nil || answer["continue"] != true {
+ t.Fatalf("stdout = %q, want Cursor's {\"continue\":true} no-op", stdout)
+ }
+ events := endpointEvents(t, logPath)
+ if len(events) != 1 {
+ t.Fatalf("wrote %d events, want only the reply: %#v", len(events), events)
+ }
+ message := events[0]
+ if got := leaf(message, "event", "action"); got != "agent.message" {
+ t.Fatalf("event.action = %q, want agent.message", got)
+ }
+ if got := outputText(t, message); got != reply {
+ t.Fatalf("reply = %q, want %q", got, reply)
+ }
+ for _, check := range []struct {
+ path []string
+ want string
+ }{
+ {[]string{"harness", "name"}, "cursor"},
+ {[]string{"harness", "collection_method"}, "hook"},
+ {[]string{"session", "id"}, "conv-reply"},
+ {[]string{"prompt", "id"}, "gen-9"},
+ {[]string{"model"}, "claude-opus-5-5"},
+ } {
+ if got := leaf(message, check.path...); got != check.want {
+ t.Errorf("%s = %q, want %q", strings.Join(check.path, "."), got, check.want)
+ }
+ }
+
+ var texts []string
+ for _, m := range chatView(t, logPath) {
+ if m.Kind == asymptoteobserve.TraceMessageKindAssistant {
+ texts = append(texts, m.Text)
+ }
+ }
+ if len(texts) != 1 || texts[0] != reply {
+ t.Fatalf("chat view assistant text = %q, want the reply", texts)
+ }
+}
+
+// No text, no message -- and still Cursor's no-op answer, so the hook never stalls the agent.
+func TestCursorAgentResponseWithoutTextWritesNothing(t *testing.T) {
+ for name, value := range map[string]interface{}{"absent": nil, "empty": "", "blank": "\n "} {
+ t.Run(name, func(t *testing.T) {
+ logPath, stdout := runHookProcess(t, cursorAfterAgentResponse(value), "--platform", "cursor", "agent-response")
+ if !strings.Contains(string(stdout), `"continue":true`) {
+ t.Fatalf("stdout = %q, want the cursor no-op", stdout)
+ }
+ if events := endpointEventsIfAny(t, logPath); len(events) != 0 {
+ t.Fatalf("wrote %d events with no reply: %#v", len(events), events)
+ }
+ })
+ }
+}
+
+// `text` is generic; it is the reply only on Cursor's afterAgentResponse. Another runtime's
+// payload routed here records nothing.
+func TestAgentResponseReadsTextOnlyForCursor(t *testing.T) {
+ payload := map[string]interface{}{"session_id": "s-1", "cwd": "/repo", "text": "a prompt, not a reply"}
+ logPath, _ := runHookProcess(t, payload, "--platform", "qwen", "agent-response")
+ if events := endpointEventsIfAny(t, logPath); len(events) != 0 {
+ t.Fatalf("recorded %d events under --platform qwen: %#v", len(events), events)
+ }
+}
+
+// The payload is recognized as Cursor's even when the hook command carries no --platform flag, the
+// same as every other Cursor hook event.
+func TestAfterAgentResponseIsACursorPayload(t *testing.T) {
+ if !looksLikeCursorPayload(map[string]interface{}{"hook_event_name": "afterAgentResponse"}) {
+ t.Fatal("afterAgentResponse is not recognized as a Cursor hook event")
+ }
+}
diff --git a/cli/beacon-hooks/cmd/helpers.go b/cli/beacon-hooks/cmd/helpers.go
index 4ff5adfa..1879acc7 100644
--- a/cli/beacon-hooks/cmd/helpers.go
+++ b/cli/beacon-hooks/cmd/helpers.go
@@ -83,7 +83,7 @@ func looksLikeCursorPayload(input map[string]interface{}) bool {
return true
}
switch getFirstStr(input, "hook_event_name", "hookEventName") {
- case "beforeSubmitPrompt", "beforeShellExecution", "afterShellExecution", "beforeReadFile", "afterFileEdit", "afterAgentThought", "postToolUse", "postToolUseFailure", "preCompact", "subagentStart", "subagentStop":
+ case "beforeSubmitPrompt", "beforeShellExecution", "afterShellExecution", "beforeReadFile", "afterFileEdit", "afterAgentThought", "afterAgentResponse", "postToolUse", "postToolUseFailure", "preCompact", "subagentStart", "subagentStop":
return true
default:
return false
diff --git a/cli/beacon/internal/endpoint/hooks/cursor.go b/cli/beacon/internal/endpoint/hooks/cursor.go
index 9cefb63e..589b5881 100644
--- a/cli/beacon/internal/endpoint/hooks/cursor.go
+++ b/cli/beacon/internal/endpoint/hooks/cursor.go
@@ -96,6 +96,7 @@ func installCursorHooksJSON(path, binaryPath, logPath, configPath string) error
"beforeSubmitPrompt": {Command: commandPrefix + " prompt-submit", Timeout: 30},
"preToolUse": {Command: commandPrefix + " pre-tool", Matcher: "Write|Edit|MultiEdit|Shell|MCP"},
"afterAgentThought": {Command: commandPrefix + " agent-thought"},
+ "afterAgentResponse": {Command: commandPrefix + " agent-response"},
"afterFileEdit": {Command: commandPrefix + " post-tool"},
"postToolUse": {Command: commandPrefix + " post-tool"},
"postToolUseFailure": {Command: commandPrefix + " post-tool"},
diff --git a/cli/beacon/internal/endpoint/hooks/cursor_test.go b/cli/beacon/internal/endpoint/hooks/cursor_test.go
index 92925818..9c8b3d23 100644
--- a/cli/beacon/internal/endpoint/hooks/cursor_test.go
+++ b/cli/beacon/internal/endpoint/hooks/cursor_test.go
@@ -43,6 +43,43 @@ func TestInstallCursorHooksJSONPreservesNonBeaconHooks(t *testing.T) {
if !strings.Contains(text, `"afterAgentThought"`) || !strings.Contains(text, "agent-thought") {
t.Fatalf("afterAgentThought reasoning hook was not installed: %s", text)
}
+ var parsed struct {
+ Hooks map[string][]HookRef `json:"hooks"`
+ }
+ if err := json.Unmarshal(data, &parsed); err != nil {
+ t.Fatal(err)
+ }
+ responses := parsed.Hooks["afterAgentResponse"]
+ if len(responses) != 1 || !strings.HasSuffix(responses[0].Command, " agent-response") || !strings.Contains(responses[0].Command, "--platform cursor") {
+ t.Fatalf("afterAgentResponse hooks = %#v, want one Beacon agent-response command", responses)
+ }
+}
+
+func TestInstallCursorHooksJSONAgentResponseIsIdempotentAndRemovable(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "hooks.json")
+ existing := `{"version":1,"hooks":{"afterAgentResponse":[{"command":"echo mine"}]}}`
+ if err := os.WriteFile(path, []byte(existing), 0644); err != nil {
+ t.Fatal(err)
+ }
+ for i := 0; i < 2; i++ {
+ if err := installCursorHooksJSON(path, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", ""); err != nil {
+ t.Fatal(err)
+ }
+ }
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if n := strings.Count(string(data), " agent-response"); n != 1 {
+ t.Fatalf("agent-response installed %d times after two installs, want 1: %s", n, data)
+ }
+ if _, err := removeEndpointHooks(path); err != nil {
+ t.Fatal(err)
+ }
+ data, _ = os.ReadFile(path)
+ if strings.Contains(string(data), "agent-response") || !strings.Contains(string(data), "echo mine") {
+ t.Fatalf("uninstall should remove only Beacon's afterAgentResponse hook: %s", data)
+ }
}
func TestRemoveEndpointHooksPreservesOtherHooks(t *testing.T) {
diff --git a/docs/runtimes/cursor.mdx b/docs/runtimes/cursor.mdx
index 06610416..19dfe189 100644
--- a/docs/runtimes/cursor.mdx
+++ b/docs/runtimes/cursor.mdx
@@ -60,6 +60,7 @@ beacon endpoint hooks install --harness cursor --level project
| Turn identity | Supported. Cursor's `generation_id`, which changes with every user message, is promoted to `prompt.id` on hook events |
| Command, tool, and file telemetry | Supported for tool, shell command, MCP-like, approval, and file edit payloads where Cursor exposes them; Cursor Cloud support is limited to Cursor's [cloud-supported command hooks](https://cursor.com/docs/hooks#cloud-agent-support). |
| Pre-tool answer | `preToolUse`, `beforeShellExecution` and `beforeReadFile` answer `{"permission":"allow"}`, because Cursor's hooks reference does not make `permission` optional and blocks an action whose hook response does not match the schema. Cursor enforces only a hook's `deny`: an `allow` does not override your allowlist or approval mode, so a command Cursor would ask about still asks. A deny from a `BEACON_POLICY_PROVIDER` policy provider returns `{"permission":"deny"}` |
+| Agent responses | Supported for local Cursor through `afterAgentResponse` hooks. Each finished assistant message is recorded as an `agent.message` event with the reply text in `gen_ai.output.messages` (a `text` part) and a `content` marker, in the same turn (`prompt.id`) as the prompt that produced it. Cursor Cloud does not install this hook. `beacon endpoint cursor sync` also recovers committed assistant text |
| Agent reasoning telemetry | Supported for local Cursor through `afterAgentThought` hooks. Each completed thinking block is recorded as an `agent.reasoning` event carrying the reasoning text in the OpenTelemetry GenAI output-messages shape (`gen_ai.output.messages` with a `reasoning` part), plus a `content` marker with the original text's hash and byte count. Reasoning is only available for models/modes where Cursor exposes visible thinking text. |
| Repository and branch context | Events include the workspace path as `repository`, and `branch` is resolved from the workspace's local git checkout (`.git/HEAD`) when Cursor does not supply one; disable local git resolution with `BEACON_DISABLE_GIT_METADATA=1`. |
| Token usage and cost | Not collected. No Cursor hook payload carries a token count or a cost. |