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
fix(claude): keep the model-context opt-in until changed, and let the collector enforce it
Kyle Elliottee888d249741
diff --git a/cli/beacon/cmd/endpoint.go b/cli/beacon/cmd/endpoint.goindex 10de6f05..52f97d38 100644--- a/cli/beacon/cmd/endpoint.go+++ b/cli/beacon/cmd/endpoint.go@@ -4,6 +4,7 @@ import ("encoding/json""fmt""os"+ "strconv""strings""time"@@ -31,7 +32,7 @@ var endpointOpts struct {collectorPath stringincludeRuntimeMetrics boolincludeCodexSpans bool- claudeCaptureModelContext bool+ claudeCaptureModelContext optionalBoolkeepLogs boolkeepConfig boolnoStart bool@@ -91,7 +92,38 @@ var endpointOpts struct {}const claudeCaptureModelContextUsage = "Record context Claude Code gives the model that no other event reports, such as the pages its WebFetch tool fetches. " +- "Turns on Claude Code's API body logs; the collector keeps only that context and drops every body"+ "Turns on Claude Code's API body logs; the collector keeps only that context and drops every body. " ++ "Kept until an install or repair passes --claude-capture-model-context=false"++// optionalBool is a boolean flag that also records whether it was given, for an opt-in that an+// install or repair without the flag must leave as it was.+type optionalBool struct {+ value *bool+}++func (b *optionalBool) Set(s string) error {+ v, err := strconv.ParseBool(s)+ if err != nil {+ return err+ }+ b.value = &v+ return nil+}++func (b *optionalBool) String() string {+ if b == nil || b.value == nil {+ return "unset"+ }+ return strconv.FormatBool(*b.value)+}++func (b *optionalBool) Type() string { return "bool" }++// registerOptionalBool registers b so that the bare flag means true and --flag=false means false.+func registerOptionalBool(cmd *cobra.Command, b *optionalBool, name, usage string) {+ cmd.Flags().Var(b, name, usage)+ cmd.Flags().Lookup(name).NoOptDefVal = "true"+}var endpointCmd = &cobra.Command{Use: "endpoint",@@ -429,7 +461,7 @@ func init() {endpointInstallCmd.Flags().StringVar(&endpointOpts.collectorPath, "collector", "", "Path to a beacon-otelcol binary")endpointInstallCmd.Flags().BoolVar(&endpointOpts.includeRuntimeMetrics, "include-runtime-metrics", false, "Include generic process/runtime OTLP metrics and harness operational metrics (OpenClaw, Copilot CLI) in the runtime JSONL log")endpointInstallCmd.Flags().BoolVar(&endpointOpts.includeCodexSpans, "include-codex-spans", false, "Include high-volume Codex OTLP spans for troubleshooting")- endpointInstallCmd.Flags().BoolVar(&endpointOpts.claudeCaptureModelContext, "claude-capture-model-context", false, claudeCaptureModelContextUsage)+ registerOptionalBool(endpointInstallCmd, &endpointOpts.claudeCaptureModelContext, "claude-capture-model-context", claudeCaptureModelContextUsage)endpointInstallCmd.Flags().BoolVar(&endpointOpts.noStart, "no-start", false, "Write files without starting the collector service")endpointInstallCmd.Flags().BoolVar(&endpointOpts.noBrowser, "no-browser", false, "During interactive setup, print the sign-in URL instead of opening a browser")endpointInstallCmd.Flags().StringVar(&endpointOpts.serviceKind, "service", "", "Service manager to use: auto (default), launchd, systemd, or none for a supervised collector process")@@ -453,7 +485,7 @@ func init() {endpointRepairCmd.Flags().StringVar(&endpointOpts.collectorPath, "collector", "", "Path to a beacon-otelcol binary")endpointRepairCmd.Flags().BoolVar(&endpointOpts.includeRuntimeMetrics, "include-runtime-metrics", false, "Include generic process/runtime OTLP metrics and harness operational metrics (OpenClaw, Copilot CLI) in the runtime JSONL log")endpointRepairCmd.Flags().BoolVar(&endpointOpts.includeCodexSpans, "include-codex-spans", false, "Include high-volume Codex OTLP spans for troubleshooting")- endpointRepairCmd.Flags().BoolVar(&endpointOpts.claudeCaptureModelContext, "claude-capture-model-context", false, claudeCaptureModelContextUsage)+ registerOptionalBool(endpointRepairCmd, &endpointOpts.claudeCaptureModelContext, "claude-capture-model-context", claudeCaptureModelContextUsage)endpointRepairCmd.Flags().BoolVar(&endpointOpts.noStart, "no-start", false, "Write files without starting the collector service")endpointRepairCmd.Flags().StringVar(&endpointOpts.serviceKind, "service", "", "Service manager to use: auto (default), launchd, systemd, or none for a supervised collector process")endpointRepairCmd.Flags().BoolVar(&endpointOpts.dryRun, "dry-run", false, "Print planned actions without changing endpoint files or services")diff --git a/cli/beacon/cmd/endpoint_install.go b/cli/beacon/cmd/endpoint_install.goindex 49402742..fc6d5b22 100644--- a/cli/beacon/cmd/endpoint_install.go+++ b/cli/beacon/cmd/endpoint_install.go@@ -126,7 +126,7 @@ func endpointInstallOptions(selection endpointTargetSelection, serviceKind serviStartService: !endpointOpts.noStart,IncludeRuntimeMetrics: endpointOpts.includeRuntimeMetrics,IncludeCodexSpans: endpointOpts.includeCodexSpans,- ClaudeCaptureModelContext: endpointOpts.claudeCaptureModelContext,+ ClaudeCaptureModelContext: endpointOpts.claudeCaptureModelContext.value,SplunkHEC: splunkHECOptions(),FalconHEC: falconHECOptions(),ServiceKind: serviceKind,diff --git a/cli/beacon/cmd/endpoint_install_harness_test.go b/cli/beacon/cmd/endpoint_install_harness_test.goindex 6dd2d780..5a75559b 100644--- a/cli/beacon/cmd/endpoint_install_harness_test.go+++ b/cli/beacon/cmd/endpoint_install_harness_test.go@@ -97,22 +97,60 @@ func TestEndpointRepairHookOnlyHarnessConfiguresNoOTLPRuntime(t *testing.T) {assertNoOTLPHarnesses(t, "repair --harness omp", opts.Harnesses)}-// Model-context capture has Claude Code export every API body, so it stays off unless the flag asks for-// it, and repair takes it from its own flags like install, so a repair without it turns it off.-func TestEndpointInstallAndRepairCaptureClaudeWebFetchOnlyWhenAsked(t *testing.T) {+// Model-context capture has Claude Code export every API body, so it changes only when the flag says+// so: without it the lifecycle is told nothing and keeps the endpoint's recorded choice, which is+// what the package upgrades and MDM repairs that re-run install rely on.+func TestEndpointInstallAndRepairPassTheModelContextChoiceOnlyWhenGiven(t *testing.T) {for _, repair := range []bool{false, true} {- // The first recorded run restores every endpoint option when the test ends.- endpointOpts.claudeCaptureModelContext = false- if opts := runRecordedEndpointCommand(t, repair, "claude"); opts.ClaudeCaptureModelContext {- t.Fatalf("repair=%t: Model-context capture is on without --claude-capture-model-context", repair)+ for _, tc := range []struct {+ flag string+ want *bool+ }{+ {"", nil},+ {"true", ptrTo(true)},+ {"false", ptrTo(false)},+ } {+ // The first recorded run restores every endpoint option when the test ends.+ endpointOpts.claudeCaptureModelContext = optionalBool{}+ if tc.flag != "" {+ if err := endpointOpts.claudeCaptureModelContext.Set(tc.flag); err != nil {+ t.Fatal(err)+ }+ }+ got := runRecordedEndpointCommand(t, repair, "claude").ClaudeCaptureModelContext+ if (got == nil) != (tc.want == nil) || (got != nil && *got != *tc.want) {+ t.Fatalf("repair=%t flag=%q: lifecycle got %v, want %v", repair, tc.flag, got, tc.want)+ }}- endpointOpts.claudeCaptureModelContext = true- if opts := runRecordedEndpointCommand(t, repair, "claude"); !opts.ClaudeCaptureModelContext {- t.Fatalf("repair=%t: --claude-capture-model-context did not reach the lifecycle", repair)+ }+}++// The bare flag opts in and --claude-capture-model-context=false opts out, on install and repair.+func TestClaudeCaptureModelContextFlagParses(t *testing.T) {+ for _, tc := range []struct {+ args []string+ want string+ }{+ {nil, "unset"},+ {[]string{"--claude-capture-model-context"}, "true"},+ {[]string{"--claude-capture-model-context=false"}, "false"},+ {[]string{"--claude-capture-model-context=true"}, "true"},+ } {+ var value optionalBool+ cmd := &cobra.Command{Use: "install", RunE: func(*cobra.Command, []string) error { return nil }}+ registerOptionalBool(cmd, &value, "claude-capture-model-context", "")+ cmd.SetArgs(tc.args)+ if err := cmd.Execute(); err != nil {+ t.Fatalf("%v: %v", tc.args, err)+ }+ if got := value.String(); got != tc.want {+ t.Fatalf("%v parsed to %s, want %s", tc.args, got, tc.want)}}}+func ptrTo[T any](v T) *T { return &v }+// `--harness ""` is the documented collector-only install (splitHarnessCSV keeps it an empty// list on purpose), so it must configure no runtime at all.func TestEndpointInstallCollectorOnlyHarnessConfiguresNoOTLPRuntime(t *testing.T) {diff --git a/cli/beacon/internal/endpoint/collector/collector.go b/cli/beacon/internal/endpoint/collector/collector.goindex 9a2d3d78..17f46d4f 100644--- a/cli/beacon/internal/endpoint/collector/collector.go+++ b/cli/beacon/internal/endpoint/collector/collector.go@@ -148,6 +148,12 @@ func ConfigYAML(cfg endpointconfig.Config) string {if cfg.Collector.IncludeCodexSpans {codexSpansYAML = " include_codex_spans: true\n"}+ // The processor and the exporters each decide from their own config whether to keep anything+ // from a Claude Code API body, so the opt-in is written to all of them.+ modelContextYAML := ""+ if cfg.ClaudeCaptureModelContext {+ modelContextYAML = " capture_model_context: true\n"+ }return fmt.Sprintf(`receivers:otlp:protocols:@@ -164,7 +170,7 @@ processors:timeout: 5ssend_batch_size: 128claude_api_body:-+%sexporters:beaconjson:path: %q@@ -195,7 +201,7 @@ service:receivers: [otlp]processors: [memory_limiter, batch]exporters: %s-`, cfg.Collector.GRPCPort, cfg.Collector.HTTPPort, cfg.LogPath, runtimeMetricsYAML+codexSpansYAML+splunkExporter+falconExporter, endpointconfig.HealthCheckPort(cfg.Collector), exporters, exporters, exporters)+`, cfg.Collector.GRPCPort, cfg.Collector.HTTPPort, modelContextYAML, cfg.LogPath, runtimeMetricsYAML+codexSpansYAML+modelContextYAML+splunkExporter+falconExporter, endpointconfig.HealthCheckPort(cfg.Collector), exporters, exporters, exporters)}func splunkHECYAML(cfg endpointconfig.Config) string {@@ -243,6 +249,9 @@ func falconHECYAML(cfg endpointconfig.Config) string {if cfg.Collector.IncludeCodexSpans {fmt.Fprintf(&b, " include_codex_spans: true\n")}+ if cfg.ClaudeCaptureModelContext {+ fmt.Fprintf(&b, " capture_model_context: true\n")+ }if falcon.Source != "" {fmt.Fprintf(&b, " source: %q\n", falcon.Source)}diff --git a/cli/beacon/internal/endpoint/collector/collector_test.go b/cli/beacon/internal/endpoint/collector/collector_test.goindex 1190ca70..3b0d33c0 100644--- a/cli/beacon/internal/endpoint/collector/collector_test.go+++ b/cli/beacon/internal/endpoint/collector/collector_test.go@@ -90,6 +90,33 @@ func TestConfigYAMLIncludesCodexSpansOptIn(t *testing.T) {}}+// The processor and each converting exporter decide on their own whether to keep anything from a+// Claude Code API body, so the opt-in reaches all of them or none.+func TestConfigYAMLWritesTheModelContextOptInToEveryComponentThatReadsBodies(t *testing.T) {+ cfg := testConfig(t)+ cfg.Destinations = &endpointconfig.Destinations{FalconHEC: &endpointconfig.FalconHEC{+ Endpoint: "https://cloud.us.humio.com/api/v1/ingest/hec",+ Token: "ingest-token",+ }}+ if yaml := ConfigYAML(cfg); strings.Contains(yaml, "capture_model_context") {+ t.Fatalf("ConfigYAML opted in without the flag:\n%s", yaml)+ }+ cfg.ClaudeCaptureModelContext = true+ yaml := ConfigYAML(cfg)+ for _, want := range []string{+ " claude_api_body:\n capture_model_context: true\n",+ " redact_secrets: true\n capture_model_context: true\n",+ " falcon_hec:\n",+ } {+ if !strings.Contains(yaml, want) {+ t.Fatalf("ConfigYAML missing %q:\n%s", want, yaml)+ }+ }+ if got := strings.Count(yaml, "capture_model_context: true"); got != 3 {+ t.Fatalf("capture_model_context appears %d times, want processor, beaconjson and falcon_hec:\n%s", got, yaml)+ }+}+func TestConfigYAMLIncludesSplunkHECWhenConfigured(t *testing.T) {cfg := testConfig(t)cfg.Destinations = &endpointconfig.Destinations{SplunkHEC: &endpointconfig.SplunkHEC{diff --git a/cli/beacon/internal/endpoint/harness/harness.go b/cli/beacon/internal/endpoint/harness/harness.goindex 05e52654..62d8dee3 100644--- a/cli/beacon/internal/endpoint/harness/harness.go+++ b/cli/beacon/internal/endpoint/harness/harness.go@@ -8,6 +8,7 @@ import ("os/exec""path/filepath""runtime"+ "sort""strings""time"@@ -389,18 +390,7 @@ func ConfigureClaude(opts ConfigureOptions) (string, error) {// identity/arguments needed to reconstruct agent activity from OTel events.env["OTEL_LOG_TOOL_DETAILS"] = "1"env["OTEL_LOG_USER_PROMPTS"] = "1"- // Inline API bodies carry the page WebFetch sends to its summarizer model, the- // only place Claude Code reports it, and also the system prompt and the whole- // conversation. The collector's claude_api_body processor keeps only that context,- // but Claude Code is asked for them only on opt-in. Neither branch overrides 0 or- // file:<dir>; without the opt-in an inline value goes, so opting out works.- rawBodies, configured := env["OTEL_LOG_RAW_API_BODIES"]- switch {- case opts.CaptureModelContext && !configured:- env["OTEL_LOG_RAW_API_BODIES"] = "1"- case !opts.CaptureModelContext && claudeInlineRawBodies(rawBodies):- delete(env, "OTEL_LOG_RAW_API_BODIES")- }+ configureClaudeModelContext(env, opts.CaptureModelContext)settings["env"] = envif err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {return "", err@@ -802,14 +792,55 @@ func commandVersion(path string) string {return strings.TrimSpace(string(out))}-// claudeInlineRawBodies reports whether an OTEL_LOG_RAW_API_BODIES value has Claude Code put-// API bodies inline in its log events, rather than leave them off or write them to files.-func claudeInlineRawBodies(value interface{}) bool {- switch strings.ToLower(strings.TrimSpace(fmt.Sprint(value))) {- case "1", "true":- return true+// claudeModelContextMarker names, in Claude Code's own env block, the settings Beacon wrote for+// --claude-capture-model-context. Install and repair without the opt-in remove those and nothing+// else: a value the user set themselves is theirs, and the collector keeps nothing from the bodies+// it produces unless the endpoint was installed with the opt-in. Claude Code ignores the key.+const claudeModelContextMarker = "BEACON_CLAUDE_MODEL_CONTEXT"++// claudeModelContextValues are the values Beacon writes for --claude-capture-model-context.+var claudeModelContextValues = map[string]string{+ "OTEL_LOG_RAW_API_BODIES": "1",+}++// configureClaudeModelContext sets or removes Beacon's model-context settings in Claude Code's env.+//+// Inline API bodies carry the page WebFetch sends to its summarizer model, the only place Claude+// Code reports it, and also the system prompt and the whole conversation. The collector's+// claude_api_body processor keeps only that context, and only on the opt-in, but Claude Code is+// asked for the bodies only on the opt-in too. The opt-in sets a setting only where none is set, so+// 0, file:<dir> and a user's own 1 are never taken over; without it, a setting Beacon wrote goes+// unless it has been changed since.+func configureClaudeModelContext(env map[string]interface{}, capture bool) {+ owned := map[string]bool{}+ for _, key := range strings.Split(fmt.Sprint(env[claudeModelContextMarker]), ",") {+ if _, known := claudeModelContextValues[key]; known {+ owned[key] = true+ }}- return false+ if capture {+ if _, set := env["OTEL_LOG_RAW_API_BODIES"]; !set {+ env["OTEL_LOG_RAW_API_BODIES"] = claudeModelContextValues["OTEL_LOG_RAW_API_BODIES"]+ owned["OTEL_LOG_RAW_API_BODIES"] = true+ }+ } else {+ for key := range owned {+ if fmt.Sprint(env[key]) == claudeModelContextValues[key] {+ delete(env, key)+ }+ }+ owned = nil+ }+ var keys []string+ for key := range owned {+ keys = append(keys, key)+ }+ if len(keys) == 0 {+ delete(env, claudeModelContextMarker)+ return+ }+ sort.Strings(keys)+ env[claudeModelContextMarker] = strings.Join(keys, ",")}func backup(path string, data []byte) error {diff --git a/cli/beacon/internal/endpoint/harness/harness_test.go b/cli/beacon/internal/endpoint/harness/harness_test.goindex ec040d05..64d1fa7c 100644--- a/cli/beacon/internal/endpoint/harness/harness_test.go+++ b/cli/beacon/internal/endpoint/harness/harness_test.go@@ -125,26 +125,29 @@ func TestConfigureClaudeEnablesPromptLogging(t *testing.T) {}// Model-context capture is opt-in. The opt-in sets inline API bodies only where nothing is set, and-// install without it removes an inline setting, so a repair without the flag turns capture off.-// Neither overrides 0 or file:<dir>.-func TestConfigureClaudeRawBodiesFollowTheWebFetchOptIn(t *testing.T) {+// install without it removes only a setting Beacon wrote, so a repair without the flag turns+// Beacon's capture off and leaves a user's own setting alone. Neither overrides 0 or file:<dir>.+func TestConfigureClaudeRawBodiesFollowTheModelContextOptIn(t *testing.T) {const unset = "<unset>"tests := []struct {- capture bool+ steps []boolbefore, want string}{- {capture: true, before: unset, want: "1"},- {capture: true, before: "1", want: "1"},- {capture: true, before: "0", want: "0"},- {capture: true, before: "file:/private/claude-bodies", want: "file:/private/claude-bodies"},- {capture: false, before: unset, want: unset},- {capture: false, before: "1", want: unset},- {capture: false, before: "true", want: unset},- {capture: false, before: "0", want: "0"},- {capture: false, before: "file:/private/claude-bodies", want: "file:/private/claude-bodies"},+ {steps: []bool{true}, before: unset, want: "1"},+ {steps: []bool{true}, before: "1", want: "1"},+ {steps: []bool{true}, before: "0", want: "0"},+ {steps: []bool{true}, before: "file:/private/claude-bodies", want: "file:/private/claude-bodies"},+ {steps: []bool{false}, before: unset, want: unset},+ {steps: []bool{false}, before: "1", want: "1"},+ {steps: []bool{false}, before: "true", want: "true"},+ {steps: []bool{false}, before: "0", want: "0"},+ {steps: []bool{false}, before: "file:/private/claude-bodies", want: "file:/private/claude-bodies"},+ {steps: []bool{true, false}, before: unset, want: unset},+ {steps: []bool{true, true, false}, before: unset, want: unset},+ {steps: []bool{true, false}, before: "1", want: "1"},}for _, tc := range tests {- t.Run(fmt.Sprintf("capture=%t/%s", tc.capture, tc.before), func(t *testing.T) {+ t.Run(fmt.Sprintf("%v/%s", tc.steps, tc.before), func(t *testing.T) {home := t.TempDir()testenv.SetHome(t, home)path := filepath.Join(home, ".claude", "settings.json")@@ -162,8 +165,8 @@ func TestConfigureClaudeRawBodiesFollowTheWebFetchOptIn(t *testing.T) {if err := os.WriteFile(path, before, 0600); err != nil {t.Fatal(err)}- for range 2 {- if _, err := ConfigureClaude(ConfigureOptions{Endpoint: "http://127.0.0.1:4317", CaptureModelContext: tc.capture}); err != nil {+ for _, capture := range tc.steps {+ if _, err := ConfigureClaude(ConfigureOptions{Endpoint: "http://127.0.0.1:4317", CaptureModelContext: capture}); err != nil {t.Fatal(err)}}@@ -180,7 +183,10 @@ func TestConfigureClaudeRawBodiesFollowTheWebFetchOptIn(t *testing.T) {got = unset}if got != tc.want {- t.Fatalf("OTEL_LOG_RAW_API_BODIES after install and reinstall = %q, want %q", got, tc.want)+ t.Fatalf("OTEL_LOG_RAW_API_BODIES after installs %v = %q, want %q", tc.steps, got, tc.want)+ }+ if marker, set := settings["env"][claudeModelContextMarker]; set && !tc.steps[len(tc.steps)-1] {+ t.Fatalf("%s = %q left behind after an install without the opt-in", claudeModelContextMarker, marker)}})}diff --git a/cli/beacon/internal/endpoint/lifecycle/harness_selection_test.go b/cli/beacon/internal/endpoint/lifecycle/harness_selection_test.goindex 64f0ece1..cb3c2aed 100644--- a/cli/beacon/internal/endpoint/lifecycle/harness_selection_test.go+++ b/cli/beacon/internal/endpoint/lifecycle/harness_selection_test.go@@ -4,6 +4,7 @@ import ("encoding/json""os""path/filepath"+ "strings""testing"endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"@@ -92,9 +93,11 @@ func TestRepairWithExplicitEmptyHarnessesLeavesClaudeAndCodexConfigAlone(t *test}}-// Model-context capture follows the flag of the install or repair that ran last: on with it, off again-// after a repair without it, in Claude Code's settings and in config.json alike.-func TestClaudeWebFetchCaptureFollowsTheLatestInstallOrRepair(t *testing.T) {+// Model-context capture is on after an install with the flag, stays on through a repair that does+// not mention it -- the package upgrades, MDM repairs and self-updates that re-run install -- and is+// off after a repair that turns it off, in Claude Code's settings, config.json and the collector+// config alike.+func TestClaudeModelContextCaptureFollowsTheLastInstallThatChoseIt(t *testing.T) {testenv.RequirePOSIXExecutableFixtures(t)home := t.TempDir()testenv.SetHome(t, home)@@ -135,10 +138,18 @@ func TestClaudeWebFetchCaptureFollowsTheLatestInstallOrRepair(t *testing.T) {if err != nil {t.Fatal(err)}+ collectorConfig, err := os.ReadFile(cfg.Collector.ConfigPath)+ if err != nil {+ t.Fatal(err)+ }+ if inCollector := strings.Contains(string(collectorConfig), "capture_model_context: true"); inCollector != cfg.ClaudeCaptureModelContext {+ t.Fatalf("config.json records %t but the collector config has capture_model_context %t", cfg.ClaudeCaptureModelContext, inCollector)+ }return cfg.ClaudeCaptureModelContext}+ on, off := true, false- opts.ClaudeCaptureModelContext = true+ opts.ClaudeCaptureModelContext = &onif _, err := Install(opts); err != nil {t.Fatalf("Install: %v", err)}@@ -146,11 +157,19 @@ func TestClaudeWebFetchCaptureFollowsTheLatestInstallOrRepair(t *testing.T) {t.Fatalf("after install with the flag: OTEL_LOG_RAW_API_BODIES = %q, recorded = %t; want 1 and true", value, recorded())}- opts.ClaudeCaptureModelContext = false+ opts.ClaudeCaptureModelContext = nil+ if _, err := Repair(opts); err != nil {+ t.Fatalf("Repair: %v", err)+ }+ if value, _ := rawBodies(); value != "1" || !recorded() {+ t.Fatalf("after repair without the flag: OTEL_LOG_RAW_API_BODIES = %q, recorded = %t; want capture still on", value, recorded())+ }++ opts.ClaudeCaptureModelContext = &offif _, err := Repair(opts); err != nil {t.Fatalf("Repair: %v", err)}if value, set := rawBodies(); set || recorded() {- t.Fatalf("after repair without the flag: OTEL_LOG_RAW_API_BODIES = %q (set %t), recorded = %t; want capture off", value, set, recorded())+ t.Fatalf("after repair with the flag false: OTEL_LOG_RAW_API_BODIES = %q (set %t), recorded = %t; want capture off", value, set, recorded())}}diff --git a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go b/cli/beacon/internal/endpoint/lifecycle/lifecycle.goindex 9d166168..08588a12 100644--- a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go+++ b/cli/beacon/internal/endpoint/lifecycle/lifecycle.go@@ -193,12 +193,15 @@ type InstallOptions struct {HTTPPort int// HealthPort is the collector health_check port. Zero derives it from the OTLP ports// (endpointconfig.DeriveHealthCheckPort), which keeps 13133 for the default ports.- HealthPort int- CollectorPath string- StartService bool- IncludeRuntimeMetrics bool- IncludeCodexSpans bool- ClaudeCaptureModelContext bool+ HealthPort int+ CollectorPath string+ StartService bool+ IncludeRuntimeMetrics bool+ IncludeCodexSpans bool+ // ClaudeCaptureModelContext is --claude-capture-model-context. nil keeps the choice the+ // endpoint's config.json records, so an install or repair that does not pass the flag neither+ // opts in nor out.+ ClaudeCaptureModelContext *boolSplunkHEC *endpointconfig.SplunkHECFalconHEC *endpointconfig.FalconHEC// ServiceKind selects the service manager. Empty auto-detects: launchd on macOS,@@ -714,6 +717,14 @@ func Repair(opts InstallOptions) (InstallResult, error) {priorAutoUpdateMode = mode}}+ // The uninstall below removes config.json with the rest of the manifest, so a choice the repair+ // does not make is read before it goes.+ if opts.ClaudeCaptureModelContext == nil {+ if prior, err := endpointconfig.Load(opts.UserMode); err == nil {+ capture := prior.ClaudeCaptureModelContext+ opts.ClaudeCaptureModelContext = &capture+ }+ }_ = Uninstall(repairUninstallOptions(opts))result, err := Install(opts)if err != nil {@@ -891,6 +902,8 @@ func buildConfig(opts InstallOptions) endpointconfig.Config {// managed_ingest block is owned by connect/disconnect, so carry the existing one over.// The same goes for inventory_heartbeat: an operator's `enabled: false` must survive the// package upgrade that re-runs install, or the scheduled job would come back.+ // And the model-context opt-in, unless this install says otherwise: packages, MDM repairs and+ // self-update all re-run install without the flag, and must not opt the endpoint out.if existing, err := endpointconfig.Load(opts.UserMode); err == nil {if existing.ManagedIngest != nil {cfg.ManagedIngest = existing.ManagedIngest@@ -898,6 +911,7 @@ func buildConfig(opts InstallOptions) endpointconfig.Config {if existing.Inventory != nil {cfg.Inventory = existing.Inventory}+ cfg.ClaudeCaptureModelContext = existing.ClaudeCaptureModelContext}if opts.Harnesses != nil {cfg.Harnesses = opts.Harnesses@@ -919,7 +933,9 @@ func buildConfig(opts InstallOptions) endpointconfig.Config {cfg.Collector.BinaryPath = opts.CollectorPathcfg.Collector.IncludeRuntimeMetrics = opts.IncludeRuntimeMetricscfg.Collector.IncludeCodexSpans = opts.IncludeCodexSpans- cfg.ClaudeCaptureModelContext = opts.ClaudeCaptureModelContext+ if opts.ClaudeCaptureModelContext != nil {+ cfg.ClaudeCaptureModelContext = *opts.ClaudeCaptureModelContext+ }if opts.SplunkHEC != nil {if cfg.Destinations == nil {cfg.Destinations = &endpointconfig.Destinations{}diff --git a/collector-builder/exporter/beaconjsonexporter/claudeapibodyprocessor/processor.go b/collector-builder/exporter/beaconjsonexporter/claudeapibodyprocessor/processor.goindex 36cc0e81..bd225e80 100644--- a/collector-builder/exporter/beaconjsonexporter/claudeapibodyprocessor/processor.go+++ b/collector-builder/exporter/beaconjsonexporter/claudeapibodyprocessor/processor.go@@ -21,7 +21,12 @@ import (var componentType = component.MustNewType("claude_api_body")-type Config struct{}+// Config is rendered by `beacon endpoint install`. CaptureModelContext is the+// --claude-capture-model-context opt-in; without it every API body event is dropped, whoever+// turned the bodies on.+type Config struct {+ CaptureModelContext bool `mapstructure:"capture_model_context"`+}func NewFactory() processor.Factory {return processor.NewFactory(@@ -32,20 +37,26 @@ func NewFactory() processor.Factory {}func createLogs(ctx context.Context, set processor.Settings, cfg component.Config, next consumer.Logs) (processor.Logs, error) {- return processorhelper.NewLogs(ctx, set, cfg, next, processLogs,+ capture := cfg.(*Config).CaptureModelContext+ return processorhelper.NewLogs(ctx, set, cfg, next, processLogs(capture),processorhelper.WithCapabilities(consumer.Capabilities{MutatesData: true}))}-func processLogs(_ context.Context, logs plog.Logs) (plog.Logs, error) {- logs.ResourceLogs().RemoveIf(func(resource plog.ResourceLogs) bool {- resource.ScopeLogs().RemoveIf(func(scope plog.ScopeLogs) bool {- scope.LogRecords().RemoveIf(beaconevent.SanitizeClaudeAPIBodyRecord)- return scope.LogRecords().Len() == 0+func processLogs(capture bool) processorhelper.ProcessLogsFunc {+ drop := func(record plog.LogRecord) bool {+ return beaconevent.SanitizeClaudeAPIBodyRecord(record, capture)+ }+ return func(_ context.Context, logs plog.Logs) (plog.Logs, error) {+ logs.ResourceLogs().RemoveIf(func(resource plog.ResourceLogs) bool {+ resource.ScopeLogs().RemoveIf(func(scope plog.ScopeLogs) bool {+ scope.LogRecords().RemoveIf(drop)+ return scope.LogRecords().Len() == 0+ })+ return resource.ScopeLogs().Len() == 0})- return resource.ScopeLogs().Len() == 0- })- if logs.LogRecordCount() == 0 {- return logs, processorhelper.ErrSkipProcessingData+ if logs.LogRecordCount() == 0 {+ return logs, processorhelper.ErrSkipProcessingData+ }+ return logs, nil}- return logs, nil}diff --git a/collector-builder/exporter/beaconjsonexporter/claudeapibodyprocessor/processor_test.go b/collector-builder/exporter/beaconjsonexporter/claudeapibodyprocessor/processor_test.goindex 40f6b662..02936269 100644--- a/collector-builder/exporter/beaconjsonexporter/claudeapibodyprocessor/processor_test.go+++ b/collector-builder/exporter/beaconjsonexporter/claudeapibodyprocessor/processor_test.go@@ -25,7 +25,7 @@ func appendBody(records plog.LogRecordSlice, eventName, querySource, body string// policy: no API body, no body file path, and the summarizer input under its own attribute.func TestProcessorForwardsOnlyTheSummarizerInput(t *testing.T) {sink := new(consumertest.LogsSink)- proc, err := NewFactory().CreateLogs(context.Background(), processortest.NewNopSettings(componentType), &Config{}, sink)+ proc, err := NewFactory().CreateLogs(context.Background(), processortest.NewNopSettings(componentType), &Config{CaptureModelContext: true}, sink)if err != nil {t.Fatal(err)}@@ -71,3 +71,29 @@ func TestProcessorForwardsOnlyTheSummarizerInput(t *testing.T) {t.Fatal("a batch with nothing left in it was forwarded")}}++// The default config is an endpoint installed without --claude-capture-model-context. A user who+// turned Claude Code's bodies on themselves gets nothing past the processor, the page included.+func TestProcessorWithoutTheOptInForwardsNoBody(t *testing.T) {+ sink := new(consumertest.LogsSink)+ proc, err := NewFactory().CreateLogs(context.Background(), processortest.NewNopSettings(componentType), NewFactory().CreateDefaultConfig(), sink)+ if err != nil {+ t.Fatal(err)+ }+ logs := plog.NewLogs()+ records := logs.ResourceLogs().AppendEmpty().ScopeLogs().AppendEmpty().LogRecords()+ appendBody(records, "api_request_body", "web_fetch_apply", summarizerBody)+ prompt := records.AppendEmpty()+ prompt.Body().SetStr("claude_code.user_prompt")++ if err := proc.ConsumeLogs(context.Background(), logs); err != nil {+ t.Fatal(err)+ }+ got := sink.AllLogs()+ if len(got) != 1 || got[0].LogRecordCount() != 1 {+ t.Fatalf("forwarded %d batches, want one holding only the prompt", len(got))+ }+ if body := got[0].ResourceLogs().At(0).ScopeLogs().At(0).LogRecords().At(0).Body().Str(); body != "claude_code.user_prompt" {+ t.Fatalf("forwarded %q, want only the prompt", body)+ }+}diff --git a/collector-builder/exporter/beaconjsonexporter/config.go b/collector-builder/exporter/beaconjsonexporter/config.goindex a31bca80..9ac0d952 100644--- a/collector-builder/exporter/beaconjsonexporter/config.go+++ b/collector-builder/exporter/beaconjsonexporter/config.go@@ -18,6 +18,9 @@ type Config struct {ContentRetention string `mapstructure:"content_retention"` // Deprecated no-op; retained for older collector configs.IncludeRuntimeMetrics bool `mapstructure:"include_runtime_metrics"`IncludeCodexSpans bool `mapstructure:"include_codex_spans"`+ // CaptureModelContext is the --claude-capture-model-context opt-in, the same setting the+ // claude_api_body processor reads; see beaconevent.Options.+ CaptureModelContext bool `mapstructure:"capture_model_context"`}func createDefaultConfig() *Config {diff --git a/collector-builder/exporter/beaconjsonexporter/exporter.go b/collector-builder/exporter/beaconjsonexporter/exporter.goindex 668735c8..80bcd9b7 100644--- a/collector-builder/exporter/beaconjsonexporter/exporter.go+++ b/collector-builder/exporter/beaconjsonexporter/exporter.go@@ -68,6 +68,7 @@ func newExporter(raw component.Config, set exporter.Settings) (*beaconExporter,converter: beaconevent.NewConverter(beaconevent.Options{IncludeRuntimeMetrics: cfg.IncludeRuntimeMetrics,IncludeCodexSpans: cfg.IncludeCodexSpans,+ CaptureModelContext: cfg.CaptureModelContext,}),}, nil}@@ -168,6 +169,7 @@ func (e *beaconExporter) eventConverter() beaconevent.Converter {return beaconevent.NewConverter(beaconevent.Options{IncludeRuntimeMetrics: e.cfg.IncludeRuntimeMetrics,IncludeCodexSpans: e.cfg.IncludeCodexSpans,+ CaptureModelContext: e.cfg.CaptureModelContext,})}diff --git a/collector-builder/exporter/beaconjsonexporter/falconhecexporter/config.go b/collector-builder/exporter/beaconjsonexporter/falconhecexporter/config.goindex 60efaed5..23819097 100644--- a/collector-builder/exporter/beaconjsonexporter/falconhecexporter/config.go+++ b/collector-builder/exporter/beaconjsonexporter/falconhecexporter/config.go@@ -25,6 +25,8 @@ type Config struct {ContentRetention string `mapstructure:"content_retention"` // Deprecated no-op; retained for older collector configs.IncludeRuntimeMetrics bool `mapstructure:"include_runtime_metrics"`IncludeCodexSpans bool `mapstructure:"include_codex_spans"`+ // CaptureModelContext is the --claude-capture-model-context opt-in; see beaconevent.Options.+ CaptureModelContext bool `mapstructure:"capture_model_context"`}func createDefaultConfig() *Config {diff --git a/collector-builder/exporter/beaconjsonexporter/falconhecexporter/exporter.go b/collector-builder/exporter/beaconjsonexporter/falconhecexporter/exporter.goindex 59ffb249..ff2c18cc 100644--- a/collector-builder/exporter/beaconjsonexporter/falconhecexporter/exporter.go+++ b/collector-builder/exporter/beaconjsonexporter/falconhecexporter/exporter.go@@ -62,6 +62,7 @@ func newExporter(raw component.Config, set exporter.Settings) (*falconExporter,converter: beaconevent.NewConverter(beaconevent.Options{IncludeRuntimeMetrics: cfg.IncludeRuntimeMetrics,IncludeCodexSpans: cfg.IncludeCodexSpans,+ CaptureModelContext: cfg.CaptureModelContext,}),}, nil}diff --git a/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/claude_api_body.go b/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/claude_api_body.goindex a95721b3..a4cce07b 100644--- a/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/claude_api_body.go+++ b/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/claude_api_body.go@@ -39,6 +39,11 @@ const (// fetched page, and of that only its user-role text. Every other body event, request or response,// is dropped -- claude_code.api_request already records the call -- and so is a summarizer request// with no text left to keep.+//+// Even the summarizer text is kept only when the endpoint was installed with+// --claude-capture-model-context, which the collector config carries as capture_model_context.+// Claude Code sends bodies whenever OTEL_LOG_RAW_API_BODIES is on, and a user can turn that on+// without asking Beacon to keep anything; without the opt-in, every body event is dropped.func isClaudeAPIBody(eventName string) bool {return eventName == ClaudeAPIRequestBody || eventName == ClaudeAPIResponseBody@@ -63,11 +68,11 @@ func retainedClaudeWebFetchInput(text string, partial bool) claudeWebFetchInput}// takeClaudeAPIBody removes the body, body_ref and summarizer input of a Claude Code API body-// event from attrs, and returns the text Beacon keeps: the summarizer request's user text, or-// nothing. isBody reports whether eventName is a body event at all. A record the claude_api_body-// processor already rewrote carries the text in ClaudeWebFetchInputAttr, so its body is not-// parsed again.-func takeClaudeAPIBody(attrs map[string]interface{}, eventName string) (input claudeWebFetchInput, isBody bool) {+// event from attrs, and returns the text Beacon keeps: the summarizer request's user text when+// capture is on, or nothing. isBody reports whether eventName is a body event at all. A record the+// claude_api_body processor already rewrote carries the text in ClaudeWebFetchInputAttr, so its+// body is not parsed again.+func takeClaudeAPIBody(attrs map[string]interface{}, eventName string, capture bool) (input claudeWebFetchInput, isBody bool) {if !isClaudeAPIBody(eventName) {return claudeWebFetchInput{}, false}@@ -78,7 +83,7 @@ func takeClaudeAPIBody(attrs map[string]interface{}, eventName string) (input clfor _, key := range claudeAPIBodyAttrs {delete(attrs, key)}- if !isClaudeWebFetchSummarizerRequest(eventName, FirstString(attrs, "query_source")) {+ if !capture || !isClaudeWebFetchSummarizerRequest(eventName, FirstString(attrs, "query_source")) {return claudeWebFetchInput{}, true}if input.text != "" {@@ -96,11 +101,11 @@ func takeClaudeAPIBody(attrs map[string]interface{}, eventName string) (input clvar claudeAPIBodyAttrs = []string{"body", "body_ref", ClaudeWebFetchInputAttr, ClaudeWebFetchInputTruncatedAttr, ClaudeWebFetchInputRedactedAttr}// SanitizeClaudeAPIBodyRecord applies the API body policy to a log record in place, and reports-// whether the record is dropped. A kept summarizer request leaves with its text in-// ClaudeWebFetchInputAttr in place of body and body_ref. The claude_api_body processor calls it so-// the policy holds before any exporter sees the record, including ones such as splunk_hec that-// forward OTLP attributes as they arrive.-func SanitizeClaudeAPIBodyRecord(record plog.LogRecord) (drop bool) {+// whether the record is dropped. With capture on, a kept summarizer request leaves with its text in+// ClaudeWebFetchInputAttr in place of body and body_ref; with it off, every body event is dropped.+// The claude_api_body processor calls it so the policy holds before any exporter sees the record,+// including ones such as splunk_hec that forward OTLP attributes as they arrive.+func SanitizeClaudeAPIBodyRecord(record plog.LogRecord, capture bool) (drop bool) {attrs := record.Attributes()eventName := ""if value, ok := attrs.Get("event.name"); ok {@@ -110,7 +115,7 @@ func SanitizeClaudeAPIBodyRecord(record plog.LogRecord) (drop bool) {if !isClaudeAPIBody(name) {return false}- input, _ := takeClaudeAPIBody(AttrsToMap(attrs), name)+ input, _ := takeClaudeAPIBody(AttrsToMap(attrs), name, capture)if input.text == "" {return true}diff --git a/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/claude_api_body_test.go b/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/claude_api_body_test.goindex 46cae569..36d5c07c 100644--- a/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/claude_api_body_test.go+++ b/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/claude_api_body_test.go@@ -37,12 +37,16 @@ func claudeBodyRecord(eventName, querySource, body string) plog.LogRecord {return record}+// captureModelContext is the converter of an endpoint installed with --claude-capture-model-context,+// the only one that keeps anything from an API body.+var captureModelContext = Options{CaptureModelContext: true}+// convertedLog runs record through EventsFromLogs, the path the exporters take, and reports whether// it survived as an event.func convertedLog(record plog.LogRecord) bool {logs := plog.NewLogs()record.CopyTo(logs.ResourceLogs().AppendEmpty().ScopeLogs().AppendEmpty().LogRecords().AppendEmpty())- return len(NewConverter(Options{}).EventsFromLogs(logs)) == 1+ return len(NewConverter(captureModelContext).EventsFromLogs(logs)) == 1}func encodedEvent(t *testing.T, event Event) string {@@ -59,7 +63,7 @@ func TestClaudeWebFetchSummarizerInputIsRecordedAsAWebFetchResult(t *testing.T)if !convertedLog(record) {t.Fatal("the WebFetch summarizer request was dropped")}- event := NewConverter(Options{}).EventFromLog(nil, record)+ event := NewConverter(captureModelContext).EventFromLog(nil, record)if event.Event.Action != "tool.invoked" || event.Event.Category != "tool" {t.Fatalf("event = %s/%s, want tool.invoked/tool", event.Event.Action, event.Event.Category)@@ -127,7 +131,7 @@ func TestClaudeAPIBodiesOtherThanTheSummarizerRequestAreDropped(t *testing.T) {t.Fatal("body event was kept")}// A caller that converts one record directly still gets no body.- encoded := encodedEvent(t, NewConverter(Options{}).EventFromLog(nil, record))+ encoded := encodedEvent(t, NewConverter(captureModelContext).EventFromLog(nil, record))for _, forbidden := range append(privateBodyParts, "private-body", "PARTIAL-PAGE", "PAGE-CANARY", "/private/body.json") {if strings.Contains(encoded, forbidden) {t.Fatalf("converted event leaked %q: %s", forbidden, encoded)@@ -149,7 +153,7 @@ func TestClaudeAPIBodyPolicyIsKeyedOnTheEventName(t *testing.T) {if convertedLog(sdk("sdk")) {t.Fatal("an Agent SDK main-loop body was kept")}- event := NewConverter(Options{}).EventFromLog(nil, sdk(claudeWebFetchApplyQuerySource))+ event := NewConverter(captureModelContext).EventFromLog(nil, sdk(claudeWebFetchApplyQuerySource))if event.Harness.Name != "claude_agent_sdk" {t.Fatalf("harness = %q, want claude_agent_sdk", event.Harness.Name)}@@ -180,7 +184,7 @@ func TestClaudeTruncatedSummarizerBodyKeepsTheReadablePrefix(t *testing.T) {if !convertedLog(record) {t.Fatal("a truncated summarizer request was dropped with its page prefix")}- event := NewConverter(Options{}).EventFromLog(nil, record)+ event := NewConverter(captureModelContext).EventFromLog(nil, record)result, _ := event.GenAI.Tool.Call.Result.(string)if !strings.HasPrefix(result, "Web page content:\n---\nPAGE-START caf") {t.Fatalf("result = %q, want the page prefix", result)@@ -224,10 +228,10 @@ func TestClaudeWebFetchInputIsRedactedAndCappedOnEveryPath(t *testing.T) {if err != nil {t.Fatal(err)}- direct := NewConverter(Options{}).EventFromLog(nil, claudeBodyRecord("api_request_body", claudeWebFetchApplyQuerySource, string(body)))+ direct := NewConverter(captureModelContext).EventFromLog(nil, claudeBodyRecord("api_request_body", claudeWebFetchApplyQuerySource, string(body)))record := claudeBodyRecord("api_request_body", claudeWebFetchApplyQuerySource, string(body))- if SanitizeClaudeAPIBodyRecord(record) {+ if SanitizeClaudeAPIBodyRecord(record, true) {t.Fatal("the processor dropped the summarizer request")}for _, key := range []string{"body", "body_ref"} {@@ -245,7 +249,7 @@ func TestClaudeWebFetchInputIsRedactedAndCappedOnEveryPath(t *testing.T) {t.Fatalf("the processor did not forward %s", key)}}- processed := NewConverter(Options{}).EventFromLog(nil, record)+ processed := NewConverter(captureModelContext).EventFromLog(nil, record)for path, event := range map[string]Event{"direct": direct, "processed": processed} {if result, _ := event.GenAI.Tool.Call.Result.(string); result != forwarded {t.Fatalf("%s: stored result differs from what the processor forwards", path)@@ -259,14 +263,33 @@ func TestClaudeWebFetchInputIsRedactedAndCappedOnEveryPath(t *testing.T) {}}+// A user can turn Claude Code's API bodies on without asking Beacon to keep anything. Without the+// opt-in, even the summarizer request is dropped, by the converter and by the processor.+func TestClaudeAPIBodiesAreDroppedWithoutTheOptIn(t *testing.T) {+ logs := plog.NewLogs()+ claudeBodyRecord("api_request_body", claudeWebFetchApplyQuerySource, summarizerBody).CopyTo(logs.ResourceLogs().AppendEmpty().ScopeLogs().AppendEmpty().LogRecords().AppendEmpty())+ if events := NewConverter(Options{}).EventsFromLogs(logs); len(events) != 0 {+ t.Fatalf("without the opt-in the converter kept %d events, want none", len(events))+ }+ encoded := encodedEvent(t, NewConverter(Options{}).EventFromLog(nil, claudeBodyRecord("api_request_body", claudeWebFetchApplyQuerySource, summarizerBody)))+ if strings.Contains(encoded, "PAGE-CANARY") || strings.Contains(encoded, "/private/body.json") {+ t.Fatalf("a directly converted record leaked the body: %s", encoded)+ }+ processed := claudeBodyRecord("api_request_body", claudeWebFetchApplyQuerySource, summarizerBody)+ processed.Attributes().PutStr(ClaudeWebFetchInputAttr, "PAGE-CANARY")+ if !SanitizeClaudeAPIBodyRecord(processed, false) {+ t.Fatal("without the opt-in the processor kept the summarizer request")+ }+}+func TestSanitizeClaudeAPIBodyRecordDropsOtherBodiesAndLeavesOtherRecords(t *testing.T) {- if !SanitizeClaudeAPIBodyRecord(claudeBodyRecord("api_response_body", "sdk", `{}`)) {+ if !SanitizeClaudeAPIBodyRecord(claudeBodyRecord("api_response_body", "sdk", `{}`), true) {t.Fatal("the processor kept a main-loop body")}other := plog.NewLogRecord()other.Body().SetStr("claude_code.user_prompt")other.Attributes().PutStr("body", "not an API body")- if SanitizeClaudeAPIBodyRecord(other) {+ if SanitizeClaudeAPIBodyRecord(other, false) {t.Fatal("the processor dropped a record that is not an API body")}if value, _ := other.Attributes().Get("body"); value.Str() != "not an API body" {diff --git a/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter.go b/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter.goindex 4cea8ca5..c3b29a52 100644--- a/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter.go+++ b/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter.go@@ -89,6 +89,9 @@ var noisyCodexLogMessages = []string{type Options struct {IncludeRuntimeMetrics boolIncludeCodexSpans bool+ // CaptureModelContext keeps what Beacon records from Claude Code's API bodies. Off, every body+ // event is dropped; see takeClaudeAPIBody.+ CaptureModelContext bool}type Converter struct {@@ -317,7 +320,7 @@ func (c Converter) EventFromLog(resourceAttrs map[string]interface{}, record plofunc (c Converter) eventFromLog(resourceAttrs map[string]interface{}, record plog.LogRecord) (Event, bool) {attrs := MergeMaps(resourceAttrs, AttrsToMap(record.Attributes()))body := record.Body().AsString()- webFetchInput, isAPIBody := takeClaudeAPIBody(attrs, ClaudeLogEventName(attrs, body))+ webFetchInput, isAPIBody := takeClaudeAPIBody(attrs, ClaudeLogEventName(attrs, body), c.opts.CaptureModelContext)ts := Timestamp(record.Timestamp().AsTime())// An action the record states outright is observed by definition; only the fallback has to// account for how it got there.diff --git a/docs/changelog/cli.mdx b/docs/changelog/cli.mdxindex d7ce3042..6f9efa5d 100644--- a/docs/changelog/cli.mdx+++ b/docs/changelog/cli.mdx@@ -16,15 +16,18 @@ Stay up to date with the latest changes to the Agent Beacon CLI.Code's API-body logs, so Beacon can record context Claude Code gives the modelthat no other event reports. The first is the page WebFetch hands its summarizermodel, recorded as a `WebFetch` tool result, which `indirect-injection-in-tool-result`- evaluates. Without the flag, install and repair remove an inline- `OTEL_LOG_RAW_API_BODIES` (`1` or `true`) from `~/.claude/settings.json`; `0`- and `file:<dir>` are left alone. A CI job opts in by setting- `OTEL_LOG_RAW_API_BODIES=1` in its environment.+ evaluates. The choice is kept by later installs, repairs, and package upgrades+ that do not pass the flag; `--claude-capture-model-context=false` turns it off,+ and `BEACON_CLAUDE_CAPTURE_MODEL_CONTEXT` sets it from packages and MDM. Install+ changes only the Claude Code settings it wrote, never one you set yourself. A CI+ job opts in by setting `OTEL_LOG_RAW_API_BODIES=1` in its environment.- **API bodies are filtered before every destination** · A new collectorprocessor, `claude_api_body`, runs ahead of every exporter, Splunk HEC included.- It drops every Claude Code API body except the WebFetch page text, which leaves- redacted and capped at 2048 characters. If you had enabled raw bodies yourself,- they no longer appear in `raw.attributes.body` or reach your SIEM.+ It drops every Claude Code API body, and with the opt-in keeps only the WebFetch+ page text, redacted and capped at 2048 characters. If you had enabled raw bodies+ yourself, they no longer appear in `raw.attributes.body` or reach your SIEM.+ Install stops with an error if the collector binary it would use is too old to+ have the processor.- **`ci exec` keeps your telemetry timing** · A value you set for`OTEL_METRIC_EXPORT_INTERVAL`, `OTEL_BLRP_SCHEDULE_DELAY` or`OTEL_BSP_SCHEDULE_DELAY` now reaches Claude Code. Before, `ci exec` replaced itdiff --git a/docs/cli/endpoint-install.mdx b/docs/cli/endpoint-install.mdxindex daa7235e..dde80732 100644--- a/docs/cli/endpoint-install.mdx+++ b/docs/cli/endpoint-install.mdx@@ -37,7 +37,7 @@ The `claude` harness writes both Claude Code's OpenTelemetry settings and its us| `--dry-run` | Print planned actions without changing endpoint files or services || `--include-runtime-metrics` | Include generic process, runtime, and harness operational OTLP metrics in Beacon JSONL. By default, low-signal metrics such as process CPU, memory, Node.js event loop, V8 heap, GitHub Copilot CLI, and OpenClaw operational metrics are filtered out || `--include-codex-spans` | Include every high-volume Codex OTLP span for troubleshooting. By default, Beacon keeps semantic logs and only the usage-bearing completed turn span |-| `--claude-capture-model-context` | Record context Claude Code gives the model that no other event reports, such as the pages its WebFetch tool fetches. Turns on Claude Code's API-body logs; the collector keeps only that context and drops every body. Off by default; an install without the flag turns it off. See [Claude Code: model context from API bodies](/runtimes/claude-code#model-context-from-api-bodies) |+| `--claude-capture-model-context` | Record context Claude Code gives the model that no other event reports, such as the pages its WebFetch tool fetches. Turns on Claude Code's API-body logs; the collector keeps only that context and drops every body. Off by default. The choice is kept by later installs that do not pass the flag; `--claude-capture-model-context=false` turns it off, and `BEACON_CLAUDE_CAPTURE_MODEL_CONTEXT=1` or `0` does the same for package and MDM installs. See [Claude Code: model context from API bodies](/runtimes/claude-code#model-context-from-api-bodies) || `--splunk-hec-endpoint <url>` | Splunk HEC endpoint URL || `--splunk-hec-token <token>` | Splunk HEC token || `--splunk-index <index>` | Optional Splunk index |diff --git a/docs/cli/endpoint-repair.mdx b/docs/cli/endpoint-repair.mdxindex f73a196e..16fba260 100644--- a/docs/cli/endpoint-repair.mdx+++ b/docs/cli/endpoint-repair.mdx@@ -32,7 +32,7 @@ During repair, Beacon removes the existing managed service before reinstalling i| `--dry-run` | Print planned actions without changing endpoint files or services || `--include-runtime-metrics` | Include generic process, runtime, and harness operational OTLP metrics in Beacon JSONL. By default, low-signal metrics such as process CPU, memory, Node.js event loop, V8 heap, GitHub Copilot CLI, and OpenClaw operational metrics are filtered out || `--include-codex-spans` | Include every high-volume Codex OTLP span for troubleshooting. By default, Beacon keeps semantic logs and only the usage-bearing completed turn span |-| `--claude-capture-model-context` | Record context Claude Code gives the model that no other event reports, such as the pages its WebFetch tool fetches. Pass it on every repair that should keep capture on; a repair without it turns capture off. See [Claude Code: model context from API bodies](/runtimes/claude-code#model-context-from-api-bodies) |+| `--claude-capture-model-context` | Record context Claude Code gives the model that no other event reports, such as the pages its WebFetch tool fetches. A repair without the flag keeps the endpoint's current choice; `--claude-capture-model-context=false` turns capture off. See [Claude Code: model context from API bodies](/runtimes/claude-code#model-context-from-api-bodies) || `--splunk-hec-endpoint <url>` | Splunk HEC endpoint URL || `--splunk-hec-token <token>` | Splunk HEC token || `--splunk-index <index>` | Optional Splunk index |diff --git a/docs/runtimes/claude-code.mdx b/docs/runtimes/claude-code.mdxindex dc200ebb..257b3426 100644--- a/docs/runtimes/claude-code.mdx+++ b/docs/runtimes/claude-code.mdx@@ -78,9 +78,13 @@ Some of what Claude Code gives the model appears in no OTLP event except its APIbeacon endpoint install --claude-capture-model-context```-With the flag, install and repair set `OTEL_LOG_RAW_API_BODIES=1` in `~/.claude/settings.json`, and the choice is recorded as `claude_capture_model_context` in Beacon's `config.json`. Without it, they remove an inline setting (`1` or `true`), so a repair without the flag turns capture off. Neither touches `0` (off) or `file:<dir>` (bodies written to files). `beacon ci exec` does not set the variable; a CI job opts in by setting `OTEL_LOG_RAW_API_BODIES=1` in its own environment.+The choice is recorded as `claude_capture_model_context` in Beacon's `config.json` and kept until an install or repair changes it, so package upgrades, MDM repairs, and self-updates that re-run install without the flag leave it as it was. To turn capture off, pass `--claude-capture-model-context=false`. A package or MDM install can set `BEACON_CLAUDE_CAPTURE_MODEL_CONTEXT=1` or `0` instead of the flag.-Whatever turned the bodies on, the collector filters them in its `claude_api_body` processor. The processor runs before every destination, including the local runtime log, Falcon, and Splunk HEC. It keeps only the context listed below, and drops every other request and response body. The `claude_code.api_request` event already records each model call.+With capture on, install sets `OTEL_LOG_RAW_API_BODIES=1` in `~/.claude/settings.json` if it is unset, and marks the settings it wrote in `BEACON_CLAUDE_MODEL_CONTEXT` in the same `env` block. With capture off, install removes only what that marker names. A value you set yourself, including `0`, `1`, and `file:<dir>` (bodies written to files), is never changed. `beacon ci exec` does not set the variable; a CI job opts in by setting `OTEL_LOG_RAW_API_BODIES=1` in its own environment.++Whatever turned the bodies on, the collector filters them in its `claude_api_body` processor. The processor runs before every destination, including the local runtime log, Falcon, and Splunk HEC. With capture on, it keeps only the context listed below. With capture off, it drops every body, so turning `OTEL_LOG_RAW_API_BODIES` on yourself sends Beacon nothing it keeps. The `claude_code.api_request` event already records each model call.++The generated collector config names the `claude_api_body` processor, which collectors older than this release do not have. Install checks the collector binary it is about to use and stops with an error if the processor is missing, for example when an older `beacon-otelcol` is earlier on `PATH` or passed with `--collector`.#### Fetched web pagesdiff --git a/packaging/linux/install-endpoint.sh b/packaging/linux/install-endpoint.shindex 63c1a705..d5df16d7 100755--- a/packaging/linux/install-endpoint.sh+++ b/packaging/linux/install-endpoint.sh@@ -52,4 +52,10 @@ set -- endpoint install --system \[ "$BEACON_SPLUNK_INSECURE_SKIP_VERIFY" = "1" ] && set -- "$@" --splunk-insecure-skip-verify[ -n "$BEACON_SPLUNK_CA_FILE" ] && set -- "$@" --splunk-ca-file "$BEACON_SPLUNK_CA_FILE"+# Unset leaves the endpoint's recorded choice alone, so a package upgrade neither opts in nor out.+case "${BEACON_CLAUDE_CAPTURE_MODEL_CONTEXT:-}" in+ 1|true|TRUE|yes|YES) set -- "$@" --claude-capture-model-context ;;+ 0|false|FALSE|no|NO) set -- "$@" --claude-capture-model-context=false ;;+esac+exec "$BEACON_BIN" "$@"diff --git a/packaging/macos/fleet/scripts/repair.sh b/packaging/macos/fleet/scripts/repair.shindex d081c83b..cbbf5846 100755--- a/packaging/macos/fleet/scripts/repair.sh+++ b/packaging/macos/fleet/scripts/repair.sh@@ -74,5 +74,14 @@ esacif [ -n "$BEACON_FALCON_CA_FILE" ]; thenset -- "$@" --falcon-ca-file "$BEACON_FALCON_CA_FILE"fi+# Unset leaves the endpoint's recorded choice alone, so a repair neither opts in nor out.+case "${BEACON_CLAUDE_CAPTURE_MODEL_CONTEXT:-}" in+ 1|true|TRUE|yes|YES)+ set -- "$@" --claude-capture-model-context+ ;;+ 0|false|FALSE|no|NO)+ set -- "$@" --claude-capture-model-context=false+ ;;+esacexec "$BEACON_BIN" "$@"diff --git a/packaging/macos/install-endpoint.sh b/packaging/macos/install-endpoint.shindex ef50be6d..80d79200 100755--- a/packaging/macos/install-endpoint.sh+++ b/packaging/macos/install-endpoint.sh@@ -97,5 +97,15 @@ case "$BEACON_NO_START" in;;esac+# Unset leaves the endpoint's recorded choice alone, so a package upgrade neither opts in nor out.+case "${BEACON_CLAUDE_CAPTURE_MODEL_CONTEXT:-}" in+ 1|true|TRUE|yes|YES)+ set -- "$@" --claude-capture-model-context+ ;;+ 0|false|FALSE|no|NO)+ set -- "$@" --claude-capture-model-context=false+ ;;+esac+exec "$BEACON_BIN" "$@"diff --git a/packaging/macos/jamf/scripts/repair.sh b/packaging/macos/jamf/scripts/repair.shindex fc078158..4542571d 100755--- a/packaging/macos/jamf/scripts/repair.sh+++ b/packaging/macos/jamf/scripts/repair.sh@@ -74,5 +74,14 @@ esacif [ -n "$BEACON_FALCON_CA_FILE" ]; thenset -- "$@" --falcon-ca-file "$BEACON_FALCON_CA_FILE"fi+# Unset leaves the endpoint's recorded choice alone, so a repair neither opts in nor out.+case "${BEACON_CLAUDE_CAPTURE_MODEL_CONTEXT:-}" in+ 1|true|TRUE|yes|YES)+ set -- "$@" --claude-capture-model-context+ ;;+ 0|false|FALSE|no|NO)+ set -- "$@" --claude-capture-model-context=false+ ;;+esacexec "$BEACON_BIN" "$@"diff --git a/packaging/windows/install-endpoint.ps1 b/packaging/windows/install-endpoint.ps1index e80491d0..63c0ff62 100644--- a/packaging/windows/install-endpoint.ps1+++ b/packaging/windows/install-endpoint.ps1@@ -55,6 +55,11 @@ if (-not [string]::IsNullOrWhiteSpace($collector)) { $installArgs += @('--collec# install. Passing it explicitly is for a fleet that wants the supervised fallback instead.if (-not [string]::IsNullOrWhiteSpace($service)) { $installArgs += @('--service', $service) }if ($noStart -eq '1') { $installArgs += '--no-start' }+# Unset leaves the endpoint's recorded choice alone, so a package upgrade neither opts in nor out.+switch -Regex (Get-EnvOrDefault 'BEACON_CLAUDE_CAPTURE_MODEL_CONTEXT' '') {+ '^(1|true|yes)$' { $installArgs += '--claude-capture-model-context' }+ '^(0|false|no)$' { $installArgs += '--claude-capture-model-context=false' }+}Write-Output "beacon: installing the system endpoint"& $beaconBin @installArgs