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 dashboard
Justin D'Souza25f4bb59e092
diff --git a/CLAUDE.md b/CLAUDE.mdindex dc8cf894..1e810fc0 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -8,11 +8,36 @@ Beacon Endpoint Agent is a local-only endpoint telemetry agent for AI runtimes.- `cli/beacon`: public `beacon` CLI and endpoint runtime.- `cli/beacon-hooks`: hook adapter invoked by Cursor and other supported runtimes.-- `collector-builder`: OpenTelemetry Collector distribution scaffold.+- `collector-builder`: OpenTelemetry Collector distribution and Beacon JSONL exporter.- `packaging`: macOS packaging and deployment assets.Do not recreate or depend on removed `asymptote` mirror trees. Keep new work focused on the Beacon paths above.+## Product Posture++- Beacon is visibility-first endpoint telemetry for local AI agent runtimes, not a hosted policy service or general endpoint protection product.+- Preserve the local-only product posture. The public Beacon build should not require a hosted account, remote policy fetch, hosted dashboard, or external network dependency during normal hook execution.+- Do not add dependency vulnerability scanning, OSV/GHSA lookups, package remediation, or other vulnerability-enforcement flows to the public hook path.+- Do not add broad runtime enforcement unless explicitly requested. Current control behavior is limited to hook-native approvals/denials exposed by supported agent runtimes.+- Keep direct destination support scoped to local JSONL/Wazuh unless explicitly requested. Other SIEM/observability systems should consume the local output through customer-managed forwarding.+- Default content retention should remain metadata-only. Prompt text, command output, raw tool inputs, raw OTLP attributes, and raw diffs must be opt-in via explicit retention configuration and must pass through local redaction/size limits where supported.++## Telemetry Scope++Supported runtime surfaces today:++- Claude Code and Codex CLI telemetry configuration through local OpenTelemetry settings.+- Cursor hook telemetry for sessions, prompt submission, tool use, command execution, MCP-like tool activity, approval decisions, and file edits where hook payloads expose those fields.+- Claude Cowork admin-configured OpenTelemetry setup guidance and local validation.+- `beaconjson` OpenTelemetry Collector exporter that converts OTLP logs, traces, metrics, and resource attributes into Beacon endpoint JSONL.+- A local-only dashboard served by `beacon endpoint dashboard`, bound to loopback by default and backed by the runtime JSONL log.++Current non-goals unless explicitly requested:++- Kernel/process monitoring, EDR replacement, shell history scraping, cloud audit ingestion, browser/SaaS telemetry, credential-use attribution, and MCP configuration inventory.+- Direct hosted integrations for Datadog, Splunk, Elastic, Snowflake, Chronicle, Panther, or other SIEM destinations.+- Dependency vulnerability scanning or package security remediation.+## Common CommandsRun tests for the public CLI:@@ -43,13 +68,29 @@ cd cli/beaconmake build```+Run Collector exporter tests:++```bash+cd collector-builder/exporter/beaconjsonexporter+go test ./...+```++Run the local dashboard during manual testing:++```bash+cd cli/beacon+go run . endpoint dashboard --user+```+## Implementation Notes- Prefer deterministic tests that use `t.TempDir()`, `t.Setenv("HOME", ...)`, fake binaries, and free local ports.- Avoid tests that require root, real `launchctl` service changes, Wazuh, a live collector, or external network access.- For macOS-only behavior, gate tests with `runtime.GOOS == "darwin"` or assert the non-Darwin contract explicitly.- Keep endpoint event schema fields stable: `vendor`, `product`, `schema_version`, required event fields, and Wazuh-compatible JSONL output are release contracts.-- Preserve the local-only product posture. The public Beacon build should not require a hosted account or remote policy fetch.+- Preserve optional event fields for agent-native metadata (`session`, `tool`, `file`, `command`, `mcp`, `approval`, `content`, `model`, `repository`, and `branch`) without changing existing required field semantics.+- Prefer metadata-first telemetry. If adding a new signal, include stable identifiers/counts/hashes before considering raw content.+- Keep the dashboard read-only. It should inspect local status and JSONL events but must not mutate endpoint configuration or telemetry.## CI Expectations@@ -58,5 +99,6 @@ CI runs:- `go test ./...` in `cli/beacon`.- `go test -race ./internal/endpoint/...` in `cli/beacon`.- `go test ./...` in `cli/beacon-hooks`.+- `go test ./...` in `collector-builder/exporter/beaconjsonexporter`.- CLI help smoke checks for the public command tree.- macOS packaging script validation via `packaging/macos/test-endpoint-scripts.sh`.diff --git a/README.md b/README.mdindex 4e041eac..26a9a77a 100644--- a/README.md+++ b/README.md@@ -6,6 +6,42 @@ Beacon Endpoint Agent configures local telemetry for tools like Claude Code,Codex CLI, Claude Cowork, and Cursor, then writes Wazuh-compatible JSONL logs.It runs local-only and does not require a Beacon account.+Beacon is visibility-first. The current public build focuses on observing local+agent runtime activity, normalizing it into endpoint events, and leaving+forwarding to existing localfile/Wazuh or customer-managed pipelines.++## What It Captures++Beacon can currently:++- Discover supported local agent runtimes: Claude Code, Codex CLI, Cursor, and+ Claude Cowork.+- Configure Claude Code and Codex CLI to export OpenTelemetry to a localhost+ collector.+- Install Cursor hooks that emit local endpoint events for sessions, prompt+ submission, tool use, command execution, MCP-like tool activity, approval+ decisions, and file edits where Cursor exposes those hook payloads.+- Convert OTLP logs, traces, metrics, and resource attributes into Beacon+ endpoint JSONL with the `beaconjson` collector exporter.+- Write Wazuh-compatible JSONL to a local runtime log.+- Run a local-only dashboard for inspecting runtime inventory, summaries,+ timelines, filters, and event details from the JSONL log.+- Generate Wazuh localfile/rule content for the Beacon event schema.++Beacon records metadata by default. Content retention is configurable with:++- `metadata`: default; no prompt text, raw attributes, command output, or raw+ diffs.+- `redacted`: include configured content fields after local redaction and size+ limits.+- `full`: include configured content fields in local/customer-controlled logs,+ still subject to event size limits.++Beacon does not currently provide kernel/process monitoring, shell history+collection, cloud audit ingestion, browser/SaaS telemetry, credential-use+attribution, MCP configuration inventory, or direct Datadog/Splunk/Elastic/etc.+exporters.+## Quick StartBuild the CLI:@@ -22,6 +58,12 @@ Install in user mode:./beacon endpoint status```+Install with explicit content retention:++```bash+./beacon endpoint install --user --content-retention metadata+```+Print Wazuh config and validate event output:```bash@@ -36,6 +78,13 @@ Optional integrations:./beacon endpoint integrations claude-cowork print-config --user```+Run the local dashboard:++```bash+./beacon endpoint dashboard --user+./beacon endpoint dashboard --user --open+```+Uninstall:```bash@@ -48,6 +97,7 @@ Uninstall:- `beacon endpoint repair`: reapply service/config files and repair telemetry drift.- `beacon endpoint status`: show Collector, service, harness, and diagnostic status.- `beacon endpoint discover`: list supported local AI runtimes.+- `beacon endpoint dashboard`: run a localhost-only dashboard over the runtime JSONL log.- `beacon endpoint hooks`: install, check, or remove hook-based integrations such as Cursor.- `beacon endpoint integrations claude-cowork`: print setup and validate admin-configured Cowork OTLP export.- `beacon endpoint wazuh`: print/install Wazuh content and write a validation event.@@ -57,7 +107,8 @@ Uninstall:- `cli/beacon`: public `beacon` CLI.- `cli/beacon-hooks`: hook adapter invoked by supported agent runtimes.-- `collector-builder`: custom OpenTelemetry Collector distribution scaffold.+- `collector-builder`: custom OpenTelemetry Collector distribution and+ `beaconjson` exporter.- `packaging`: macOS packaging and MDM deployment assets.## Test@@ -69,4 +120,7 @@ go test -race ./internal/endpoint/...cd ../beacon-hooksgo test ./...++cd ../../collector-builder/exporter/beaconjsonexporter+go test ./...```diff --git a/cli/beacon/README.md b/cli/beacon/README.mdindex acb4d495..850cbb47 100644--- a/cli/beacon/README.md+++ b/cli/beacon/README.md@@ -15,9 +15,21 @@ make build./beacon endpoint status --json./beacon endpoint discover --json./beacon endpoint repair --user+./beacon endpoint dashboard --user./beacon endpoint uninstall --user --keep-logs```+## Dashboard++```bash+./beacon endpoint dashboard --user+./beacon endpoint dashboard --user --addr 127.0.0.1:8765+./beacon endpoint dashboard --user --open+```++The dashboard is local-only, binds to loopback, and reads the configured+runtime JSONL log.+## Wazuh```bashdiff --git a/cli/beacon/cmd/endpoint.go b/cli/beacon/cmd/endpoint.goindex c36d96f4..d51c6c08 100644--- a/cli/beacon/cmd/endpoint.go+++ b/cli/beacon/cmd/endpoint.go@@ -9,6 +9,7 @@ import ("github.com/spf13/cobra"endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/dashboard""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/harness"endpointhooks "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/hooks""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/integrations/cowork"@@ -34,6 +35,8 @@ var endpointOpts struct {coworkHeaders stringhookLevel stringcontentRetention string+ dashboardAddr string+ dashboardOpen bool}var endpointCmd = &cobra.Command{@@ -78,6 +81,13 @@ var endpointRepairCmd = &cobra.Command{RunE: runEndpointRepair,}+var endpointDashboardCmd = &cobra.Command{+ Use: "dashboard",+ Short: "Run the local Beacon endpoint dashboard",+ SilenceUsage: true,+ RunE: runEndpointDashboard,+}+var endpointWazuhCmd = &cobra.Command{Use: "wazuh",Short: "Manage Wazuh integration content",@@ -208,6 +218,7 @@ func init() {endpointCmd.AddCommand(endpointDiscoverCmd)endpointCmd.AddCommand(endpointUninstallCmd)endpointCmd.AddCommand(endpointRepairCmd)+ endpointCmd.AddCommand(endpointDashboardCmd)endpointCmd.AddCommand(endpointWazuhCmd)endpointCmd.AddCommand(endpointIntegrationsCmd)endpointCmd.AddCommand(endpointHooksCmd)@@ -238,6 +249,10 @@ func init() {endpointRepairCmd.Flags().IntVar(&endpointOpts.httpPort, "otlp-http-port", endpointconfig.DefaultHTTPPort, "Local OTLP HTTP port")endpointRepairCmd.Flags().StringVar(&endpointOpts.collectorPath, "collector", "", "Path to a beacon-otelcol binary")endpointRepairCmd.Flags().StringVar(&endpointOpts.contentRetention, "content-retention", "metadata", "Content retention mode: metadata, redacted, or full")+ endpointDashboardCmd.Flags().BoolVar(&endpointOpts.userMode, "user", false, "Use per-user endpoint paths instead of system paths")+ endpointDashboardCmd.Flags().StringVar(&endpointOpts.logPath, "log-path", "", "Runtime JSONL log path")+ endpointDashboardCmd.Flags().StringVar(&endpointOpts.dashboardAddr, "addr", dashboard.DefaultAddr, "Local dashboard listen address")+ endpointDashboardCmd.Flags().BoolVar(&endpointOpts.dashboardOpen, "open", false, "Open the dashboard in a browser")endpointDiscoverCmd.Flags().BoolVar(&endpointOpts.jsonOutput, "json", false, "Print discovery as JSON")endpointStatusCmd.Flags().BoolVar(&endpointOpts.jsonOutput, "json", false, "Print status as JSON")@@ -339,6 +354,29 @@ func runEndpointWazuhValidate(cmd *cobra.Command, args []string) error {return nil}+func runEndpointDashboard(cmd *cobra.Command, args []string) error {+ cfg := loadOrDefaultConfig()+ if endpointOpts.dashboardAddr == "" {+ endpointOpts.dashboardAddr = dashboard.DefaultAddr+ }+ if err := dashboard.ValidateLoopbackAddr(endpointOpts.dashboardAddr); err != nil {+ return err+ }+ url := dashboard.URL(endpointOpts.dashboardAddr)+ fmt.Printf("Beacon endpoint dashboard: %s\n", url)+ fmt.Printf("Runtime log: %s\n", cfg.LogPath)+ if endpointOpts.dashboardOpen {+ if err := dashboard.OpenBrowser(url); err != nil {+ return err+ }+ }+ return dashboard.ListenAndServe(dashboard.Options{+ Addr: endpointOpts.dashboardAddr,+ LogPath: cfg.LogPath,+ UserMode: cfg.UserMode,+ })+}+func runEndpointInstall(cmd *cobra.Command, args []string) error {result, err := lifecycle.Install(lifecycle.InstallOptions{UserMode: endpointOpts.userMode,diff --git a/cli/beacon/cmd/endpoint_test.go b/cli/beacon/cmd/endpoint_test.goindex cab3fa9e..cd2b8880 100644--- a/cli/beacon/cmd/endpoint_test.go+++ b/cli/beacon/cmd/endpoint_test.go@@ -14,3 +14,19 @@ func TestSplitCSV(t *testing.T) {}}}++func TestEndpointDashboardCommandRegistered(t *testing.T) {+ cmd, _, err := endpointCmd.Find([]string{"dashboard"})+ if err != nil {+ t.Fatalf("Find dashboard returned error: %v", err)+ }+ if cmd == nil || cmd.Use != "dashboard" {+ t.Fatalf("dashboard command not registered: %#v", cmd)+ }+ if cmd.Flags().Lookup("addr") == nil {+ t.Fatal("dashboard command missing --addr flag")+ }+ if cmd.Flags().Lookup("open") == nil {+ t.Fatal("dashboard command missing --open flag")+ }+}diff --git a/cli/beacon/internal/endpoint/dashboard/events.go b/cli/beacon/internal/endpoint/dashboard/events.gonew file mode 100644index 00000000..359579f3--- /dev/null+++ b/cli/beacon/internal/endpoint/dashboard/events.go@@ -0,0 +1,165 @@+package dashboard++import (+ "bufio"+ "bytes"+ "encoding/json"+ "fmt"+ "os"+ "sort"+ "strings"+ "time"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"+)++const (+ defaultEventLimit = 500+ maxEventLimit = 2000+)++type EventRecord struct {+ ID string `json:"id"`+ Line int `json:"line"`+ Event schema.Event `json:"event"`+ Raw json.RawMessage `json:"raw"`+ Parsed time.Time `json:"parsed_timestamp,omitempty"`+}++type EventQuery struct {+ Limit int+ Since time.Time+ Harness string+ Action string+ Repository string+ Session string+ File string+ Command string+}++type EventResult struct {+ Events []EventRecord `json:"events"`+ TotalMatched int `json:"total_matched"`+ MalformedLines int `json:"malformed_lines"`+ Limit int `json:"limit"`+}++func ReadEvents(path string, query EventQuery) (EventResult, error) {+ limit := normalizeLimit(query.Limit)+ file, err := os.Open(path)+ if err != nil {+ if os.IsNotExist(err) {+ return EventResult{Events: []EventRecord{}, Limit: limit}, nil+ }+ return EventResult{}, err+ }+ defer file.Close()++ result := EventResult{Limit: limit}+ scanner := bufio.NewScanner(file)+ scanner.Buffer(make([]byte, 0, 64*1024), 4*1024*1024)++ lineNo := 0+ for scanner.Scan() {+ lineNo+++ line := bytes.TrimSpace(scanner.Bytes())+ if len(line) == 0 {+ continue+ }+ var event schema.Event+ if err := json.Unmarshal(line, &event); err != nil {+ result.MalformedLines+++ continue+ }+ parsed, _ := time.Parse(time.RFC3339, event.Timestamp)+ record := EventRecord{+ ID: fmt.Sprintf("line-%d", lineNo),+ Line: lineNo,+ Event: event,+ Raw: append(json.RawMessage(nil), line...),+ Parsed: parsed,+ }+ if !matchesQuery(record, query) {+ continue+ }+ result.TotalMatched+++ result.Events = append(result.Events, record)+ if len(result.Events) > limit {+ copy(result.Events, result.Events[1:])+ result.Events = result.Events[:limit]+ }+ }+ if err := scanner.Err(); err != nil {+ return EventResult{}, err+ }++ sort.SliceStable(result.Events, func(i, j int) bool {+ return result.Events[i].Line > result.Events[j].Line+ })+ return result, nil+}++func FindEvent(path, id string) (EventRecord, bool, error) {+ result, err := ReadEvents(path, EventQuery{Limit: maxEventLimit})+ if err != nil {+ return EventRecord{}, false, err+ }+ for _, record := range result.Events {+ if record.ID == id {+ return record, true, nil+ }+ }+ return EventRecord{}, false, nil+}++func normalizeLimit(limit int) int {+ if limit <= 0 {+ return defaultEventLimit+ }+ if limit > maxEventLimit {+ return maxEventLimit+ }+ return limit+}++func matchesQuery(record EventRecord, query EventQuery) bool {+ event := record.Event+ if !query.Since.IsZero() {+ if record.Parsed.IsZero() || record.Parsed.Before(query.Since) {+ return false+ }+ }+ if query.Harness != "" && !strings.EqualFold(event.Harness.Name, query.Harness) {+ return false+ }+ if query.Action != "" && !strings.EqualFold(event.Event.Action, query.Action) {+ return false+ }+ if query.Repository != "" && !containsFold(event.Repository, query.Repository) {+ return false+ }+ if query.Session != "" {+ if event.Session == nil || !containsFold(event.Session.ID, query.Session) {+ return false+ }+ }+ if query.File != "" {+ if event.File == nil || !containsFold(event.File.Path, query.File) {+ return false+ }+ }+ if query.Command != "" {+ if event.Command != nil && containsFold(event.Command.Command, query.Command) {+ return true+ }+ if event.Tool != nil && (containsFold(event.Tool.Name, query.Command) || containsFold(event.Tool.Command, query.Command)) {+ return true+ }+ return false+ }+ return true+}++func containsFold(value, needle string) bool {+ return strings.Contains(strings.ToLower(value), strings.ToLower(needle))+}diff --git a/cli/beacon/internal/endpoint/dashboard/events_test.go b/cli/beacon/internal/endpoint/dashboard/events_test.gonew file mode 100644index 00000000..404a09f3--- /dev/null+++ b/cli/beacon/internal/endpoint/dashboard/events_test.go@@ -0,0 +1,132 @@+package dashboard++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "testing"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"+)++func TestReadEventsSkipsMalformedLinesAndFilters(t *testing.T) {+ path := filepath.Join(t.TempDir(), "runtime.jsonl")+ writeTestLog(t, path,+ testEvent("2026-05-13T01:00:00Z", "cursor", "command.executed", "command", "repo-a"),+ []byte("{not json"),+ testEvent("2026-05-13T01:01:00Z", "cursor", "file.modified", "file", "repo-b"),+ )++ result, err := ReadEvents(path, EventQuery{Action: "command.executed", Limit: 10})+ if err != nil {+ t.Fatalf("ReadEvents returned error: %v", err)+ }+ if result.MalformedLines != 1 {+ t.Fatalf("MalformedLines = %d, want 1", result.MalformedLines)+ }+ if result.TotalMatched != 1 || len(result.Events) != 1 {+ t.Fatalf("matched events = total %d len %d, want 1/1", result.TotalMatched, len(result.Events))+ }+ if result.Events[0].Event.Event.Action != "command.executed" {+ t.Fatalf("unexpected event action: %s", result.Events[0].Event.Event.Action)+ }+}++func TestBuildSummaryAggregatesSignals(t *testing.T) {+ result := EventResult{+ TotalMatched: 2,+ Events: []EventRecord{+ {Event: schema.Event{+ Timestamp: "2026-05-13T01:00:00Z",+ Event: schema.EventInfo{Action: "command.executed", Category: "command"},+ Severity: schema.SeverityInfo,+ Harness: schema.HarnessInfo{Name: "cursor"},+ Session: &schema.SessionInfo{ID: "s1"},+ Command: &schema.CommandInfo{Command: "go test ./..."},+ }},+ {Event: schema.Event{+ Timestamp: "2026-05-13T01:01:00Z",+ Event: schema.EventInfo{Action: "mcp.tool_invoked", Category: "mcp"},+ Severity: schema.SeverityHigh,+ Harness: schema.HarnessInfo{Name: "cursor"},+ Session: &schema.SessionInfo{ID: "s2"},+ MCP: &schema.MCPInfo{Server: "github", Tool: "get_issue"},+ }},+ },+ }++ summary := BuildSummary(result)+ if summary.TotalEvents != 2 || summary.ActiveSessions != 2 {+ t.Fatalf("summary totals = events %d sessions %d, want 2/2", summary.TotalEvents, summary.ActiveSessions)+ }+ if summary.CommandEvents != 1 || summary.MCPEvents != 1 {+ t.Fatalf("signal counts = command %d mcp %d, want 1/1", summary.CommandEvents, summary.MCPEvents)+ }+ if summary.CountsByHarness["cursor"] != 2 {+ t.Fatalf("cursor harness count = %d, want 2", summary.CountsByHarness["cursor"])+ }+}++func TestHandlerEventsEndpoint(t *testing.T) {+ path := filepath.Join(t.TempDir(), "runtime.jsonl")+ writeTestLog(t, path, testEvent("2026-05-13T01:00:00Z", "cursor", "prompt.submitted", "prompt", "repo-a"))++ handler, err := Handler(Options{LogPath: path, UserMode: true})+ if err != nil {+ t.Fatalf("Handler returned error: %v", err)+ }+ req := httptest.NewRequest(http.MethodGet, "/api/events?action=prompt.submitted", nil)+ rec := httptest.NewRecorder()+ handler.ServeHTTP(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String())+ }+ var result EventResult+ if err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if len(result.Events) != 1 {+ t.Fatalf("events len = %d, want 1", len(result.Events))+ }+}++func TestValidateLoopbackAddr(t *testing.T) {+ if err := ValidateLoopbackAddr("127.0.0.1:8765"); err != nil {+ t.Fatalf("loopback address rejected: %v", err)+ }+ if err := ValidateLoopbackAddr("0.0.0.0:8765"); err == nil {+ t.Fatal("expected non-loopback address to be rejected")+ }+}++func writeTestLog(t *testing.T, path string, lines ...[]byte) {+ t.Helper()+ var data []byte+ for _, line := range lines {+ data = append(data, line...)+ data = append(data, '\n')+ }+ if err := os.WriteFile(path, data, 0644); err != nil {+ t.Fatalf("write test log: %v", err)+ }+}++func testEvent(ts, harness, action, category, repo string) []byte {+ event := schema.Event{+ Timestamp: ts,+ Vendor: schema.Vendor,+ Product: schema.Product,+ SchemaVersion: schema.SchemaVersion,+ Event: schema.EventInfo{Kind: "agent_runtime", Action: action, Category: category},+ Severity: schema.SeverityInfo,+ Endpoint: schema.EndpointInfo{OS: "darwin"},+ Harness: schema.HarnessInfo{Name: harness},+ Repository: repo,+ Message: action,+ }+ data, _ := json.Marshal(event)+ return data+}diff --git a/cli/beacon/internal/endpoint/dashboard/server.go b/cli/beacon/internal/endpoint/dashboard/server.gonew file mode 100644index 00000000..e1a9468f--- /dev/null+++ b/cli/beacon/internal/endpoint/dashboard/server.go@@ -0,0 +1,207 @@+package dashboard++import (+ "embed"+ "encoding/json"+ "fmt"+ "io/fs"+ "net"+ "net/http"+ "os/exec"+ "runtime"+ "strconv"+ "time"++ endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/lifecycle"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer"+)++const DefaultAddr = "127.0.0.1:8765"++//go:embed static/*+var staticFiles embed.FS++type Options struct {+ Addr string+ LogPath string+ UserMode bool+}++type StatusResponse struct {+ Version string `json:"version"`+ ConfigPath string `json:"config_path"`+ LogPath string `json:"log_path"`+ ContentRetention endpointconfig.ContentRetention `json:"content_retention"`+ Harnesses interface{} `json:"harnesses"`+ Collector interface{} `json:"collector"`+ Service interface{} `json:"service"`+ Diagnostics interface{} `json:"diagnostics"`+}++func Handler(opts Options) (http.Handler, error) {+ if opts.LogPath == "" {+ opts.LogPath = writer.DefaultPath(opts.UserMode)+ }+ staticRoot, err := fs.Sub(staticFiles, "static")+ if err != nil {+ return nil, err+ }+ mux := http.NewServeMux()+ mux.HandleFunc("/api/status", func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet {+ methodNotAllowed(w)+ return+ }+ status := lifecycle.GetStatus(opts.UserMode, opts.LogPath)+ cfg, err := endpointconfig.Load(opts.UserMode)+ if err != nil {+ cfg = endpointconfig.Default(opts.UserMode, opts.LogPath)+ }+ if opts.LogPath != "" {+ cfg.LogPath = opts.LogPath+ }+ writeJSON(w, StatusResponse{+ Version: status.Version,+ ConfigPath: status.ConfigPath,+ LogPath: status.LogPath,+ ContentRetention: cfg.ContentRetention,+ Harnesses: status.Harnesses,+ Collector: status.Collector,+ Service: status.Service,+ Diagnostics: status.Diagnostics,+ })+ })+ mux.HandleFunc("/api/summary", func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet {+ methodNotAllowed(w)+ return+ }+ events, err := ReadEvents(opts.LogPath, parseQuery(r, maxEventLimit))+ if err != nil {+ writeError(w, http.StatusInternalServerError, err)+ return+ }+ writeJSON(w, BuildSummary(events))+ })+ mux.HandleFunc("/api/events", func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet {+ methodNotAllowed(w)+ return+ }+ events, err := ReadEvents(opts.LogPath, parseQuery(r, defaultEventLimit))+ if err != nil {+ writeError(w, http.StatusInternalServerError, err)+ return+ }+ writeJSON(w, events)+ })+ mux.HandleFunc("/api/event", func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet {+ methodNotAllowed(w)+ return+ }+ id := r.URL.Query().Get("id")+ record, ok, err := FindEvent(opts.LogPath, id)+ if err != nil {+ writeError(w, http.StatusInternalServerError, err)+ return+ }+ if !ok {+ writeError(w, http.StatusNotFound, fmt.Errorf("event not found"))+ return+ }+ writeJSON(w, record)+ })+ mux.Handle("/", http.FileServer(http.FS(staticRoot)))+ return mux, nil+}++func ListenAndServe(opts Options) error {+ if opts.Addr == "" {+ opts.Addr = DefaultAddr+ }+ if err := ValidateLoopbackAddr(opts.Addr); err != nil {+ return err+ }+ handler, err := Handler(opts)+ if err != nil {+ return err+ }+ server := &http.Server{+ Addr: opts.Addr,+ Handler: handler,+ ReadHeaderTimeout: 5 * time.Second,+ }+ return server.ListenAndServe()+}++func ValidateLoopbackAddr(addr string) error {+ host, _, err := net.SplitHostPort(addr)+ if err != nil {+ return err+ }+ ip := net.ParseIP(host)+ if ip == nil || !ip.IsLoopback() {+ return fmt.Errorf("dashboard address must bind to a loopback IP")+ }+ return nil+}++func URL(addr string) string {+ if addr == "" {+ addr = DefaultAddr+ }+ return "http://" + addr+}++func OpenBrowser(url string) error {+ var cmd *exec.Cmd+ switch runtime.GOOS {+ case "darwin":+ cmd = exec.Command("open", url)+ case "windows":+ cmd = exec.Command("rundll32", "url.dll,FileProtocolHandler", url)+ default:+ cmd = exec.Command("xdg-open", url)+ }+ return cmd.Start()+}++func parseQuery(r *http.Request, fallbackLimit int) EventQuery {+ q := r.URL.Query()+ limit, _ := strconv.Atoi(q.Get("limit"))+ if limit == 0 {+ limit = fallbackLimit+ }+ query := EventQuery{+ Limit: limit,+ Harness: q.Get("harness"),+ Action: q.Get("action"),+ Repository: q.Get("repository"),+ Session: q.Get("session"),+ File: q.Get("file"),+ Command: q.Get("command"),+ }+ if since := q.Get("since"); since != "" {+ if parsed, err := time.Parse(time.RFC3339, since); err == nil {+ query.Since = parsed+ }+ }+ return query+}++func writeJSON(w http.ResponseWriter, value interface{}) {+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(value)+}++func writeError(w http.ResponseWriter, status int, err error) {+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(status)+ _ = json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})+}++func methodNotAllowed(w http.ResponseWriter) {+ writeError(w, http.StatusMethodNotAllowed, fmt.Errorf("method not allowed"))+}diff --git a/cli/beacon/internal/endpoint/dashboard/static/app.js b/cli/beacon/internal/endpoint/dashboard/static/app.jsnew file mode 100644index 00000000..7913c2fc--- /dev/null+++ b/cli/beacon/internal/endpoint/dashboard/static/app.js@@ -0,0 +1,133 @@+const state = {+ status: null,+ summary: null,+ events: [],+};++const $ = (selector) => document.querySelector(selector);++async function getJSON(path) {+ const response = await fetch(path);+ if (!response.ok) {+ throw new Error(`${response.status} ${response.statusText}`);+ }+ return response.json();+}++function queryFromFilters() {+ const data = new FormData($("#filters"));+ const params = new URLSearchParams();+ for (const [key, value] of data.entries()) {+ if (value) params.set(key, value);+ }+ return params.toString();+}++async function load() {+ const query = queryFromFilters();+ const suffix = query ? `?${query}` : "";+ const [status, summary, events] = await Promise.all([+ getJSON("/api/status"),+ getJSON(`/api/summary${suffix}`),+ getJSON(`/api/events${suffix}`),+ ]);+ state.status = status;+ state.summary = summary;+ state.events = events.events || [];+ render();+}++function render() {+ $("#log-path").textContent = state.status?.log_path || "Runtime log unavailable";+ $("#retention").textContent = `retention: ${state.status?.content_retention || "metadata"}`;+ renderCards();+ renderHarnesses();+ renderEvents();+}++function renderCards() {+ const cards = [+ ["Events", state.summary?.total_events || 0],+ ["Sessions", state.summary?.active_sessions || 0],+ ["Commands", state.summary?.command_events || 0],+ ["Files", state.summary?.file_events || 0],+ ["MCP", state.summary?.mcp_events || 0],+ ["Approvals", state.summary?.approval_events || 0],+ ["Malformed", state.summary?.malformed_lines || 0],+ ];+ $("#cards").innerHTML = cards+ .map(([label, value]) => `<div class="card"><span class="muted">${escapeHTML(label)}</span><span class="value">${value}</span></div>`)+ .join("");+}++function renderHarnesses() {+ const harnesses = state.status?.harnesses || [];+ $("#harnesses").innerHTML = harnesses+ .map((harness) => `+ <div class="harness">+ <strong>${escapeHTML(harness.display_name || harness.name || "unknown")}</strong>+ <p class="muted">detected: ${Boolean(harness.detected)}</p>+ <p class="muted">telemetry: ${escapeHTML(harness.telemetry_status || "unknown")}</p>+ <p class="muted">${escapeHTML(harness.message || "")}</p>+ </div>+ `)+ .join("");+}++function renderEvents() {+ $("#events").innerHTML = state.events+ .map((record) => {+ const event = record.event || {};+ const info = event.event || {};+ const session = event.session || {};+ const harness = event.harness || {};+ return `+ <tr data-id="${escapeHTML(record.id)}">+ <td>${escapeHTML(event.timestamp || "")}</td>+ <td>${escapeHTML(harness.name || "")}</td>+ <td>${escapeHTML(info.action || "")}</td>+ <td class="severity-${escapeHTML(event.severity || "")}">${escapeHTML(event.severity || "")}</td>+ <td>${escapeHTML(session.id || "")}</td>+ <td>${escapeHTML(event.repository || "")}</td>+ <td>${escapeHTML(event.message || "")}</td>+ </tr>+ `;+ })+ .join("");+ document.querySelectorAll("#events tr").forEach((row) => {+ row.addEventListener("click", () => showEvent(row.dataset.id));+ });+}++async function showEvent(id) {+ const record = await getJSON(`/api/event?id=${encodeURIComponent(id)}`);+ $("#event-json").textContent = JSON.stringify(record.event, null, 2);+ $("#drawer").classList.add("open");+ $("#drawer").setAttribute("aria-hidden", "false");+}++function closeDrawer() {+ $("#drawer").classList.remove("open");+ $("#drawer").setAttribute("aria-hidden", "true");+}++function escapeHTML(value) {+ return String(value)+ .replaceAll("&", "&")+ .replaceAll("<", "<")+ .replaceAll(">", ">")+ .replaceAll('"', """)+ .replaceAll("'", "'");+}++$("#refresh").addEventListener("click", () => load().catch(console.error));+$("#filters").addEventListener("submit", (event) => {+ event.preventDefault();+ load().catch(console.error);+});+$("#close-drawer").addEventListener("click", closeDrawer);++load().catch((err) => {+ $("#events").innerHTML = `<tr><td colspan="7">Failed to load dashboard: ${escapeHTML(err.message)}</td></tr>`;+});+setInterval(() => load().catch(console.error), 10000);diff --git a/cli/beacon/internal/endpoint/dashboard/static/index.html b/cli/beacon/internal/endpoint/dashboard/static/index.htmlnew file mode 100644index 00000000..45b8b584--- /dev/null+++ b/cli/beacon/internal/endpoint/dashboard/static/index.html@@ -0,0 +1,84 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <title>Beacon Endpoint Dashboard</title>+ <link rel="stylesheet" href="/styles.css" />+ </head>+ <body>+ <header class="topbar">+ <div>+ <p class="eyebrow">Local-only</p>+ <h1>Beacon Endpoint Dashboard</h1>+ </div>+ <button id="refresh">Refresh</button>+ </header>++ <main>+ <section class="panel status-panel">+ <div>+ <h2>Endpoint</h2>+ <p id="log-path" class="muted">Loading runtime log...</p>+ </div>+ <div id="retention" class="pill">metadata</div>+ </section>++ <section class="cards" id="cards"></section>++ <section class="panel">+ <div class="section-head">+ <div>+ <h2>Activity Timeline</h2>+ <p class="muted">Prompt, tool, command, MCP, approval, and file events from the local JSONL log.</p>+ </div>+ </div>+ <form id="filters" class="filters">+ <input name="harness" placeholder="Harness" />+ <input name="action" placeholder="Action" />+ <input name="repository" placeholder="Repository" />+ <input name="session" placeholder="Session" />+ <input name="file" placeholder="File path" />+ <input name="command" placeholder="Command or tool" />+ <select name="limit">+ <option value="100">100 events</option>+ <option value="500" selected>500 events</option>+ <option value="1000">1000 events</option>+ </select>+ <button type="submit">Apply</button>+ </form>+ <div class="table-wrap">+ <table>+ <thead>+ <tr>+ <th>Time</th>+ <th>Harness</th>+ <th>Action</th>+ <th>Severity</th>+ <th>Session</th>+ <th>Repository</th>+ <th>Message</th>+ </tr>+ </thead>+ <tbody id="events"></tbody>+ </table>+ </div>+ </section>++ <section class="panel">+ <h2>Runtime Inventory</h2>+ <div id="harnesses" class="harnesses"></div>+ </section>+ </main>++ <aside id="drawer" class="drawer" aria-hidden="true">+ <div class="drawer-head">+ <h2>Event Detail</h2>+ <button id="close-drawer">Close</button>+ </div>+ <pre id="event-json"></pre>+ </aside>++ <script src="/app.js"></script>+ </body>+</html>diff --git a/cli/beacon/internal/endpoint/dashboard/static/styles.css b/cli/beacon/internal/endpoint/dashboard/static/styles.cssnew file mode 100644index 00000000..37ebaf2e--- /dev/null+++ b/cli/beacon/internal/endpoint/dashboard/static/styles.css@@ -0,0 +1,220 @@+:root {+ color-scheme: light dark;+ --bg: #0f172a;+ --panel: #111827;+ --panel-soft: #1f2937;+ --text: #e5e7eb;+ --muted: #9ca3af;+ --line: #374151;+ --accent: #7dd3fc;+ --danger: #fca5a5;+ --warn: #fcd34d;+}++* {+ box-sizing: border-box;+}++body {+ margin: 0;+ background: var(--bg);+ color: var(--text);+ font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;+}++button,+input,+select {+ border: 1px solid var(--line);+ border-radius: 8px;+ background: var(--panel-soft);+ color: var(--text);+ font: inherit;+ padding: 0.6rem 0.75rem;+}++button {+ cursor: pointer;+}++.topbar {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 1.5rem 2rem;+ border-bottom: 1px solid var(--line);+ background: rgba(17, 24, 39, 0.9);+ position: sticky;+ top: 0;+ z-index: 2;+}++h1,+h2,+p {+ margin: 0;+}++h1 {+ font-size: 1.4rem;+}++h2 {+ font-size: 1rem;+}++main {+ display: grid;+ gap: 1rem;+ padding: 1.5rem 2rem 3rem;+}++.eyebrow {+ color: var(--accent);+ font-size: 0.75rem;+ letter-spacing: 0.1em;+ text-transform: uppercase;+ margin-bottom: 0.25rem;+}++.muted {+ color: var(--muted);+ font-size: 0.9rem;+}++.panel,+.card {+ background: var(--panel);+ border: 1px solid var(--line);+ border-radius: 14px;+ padding: 1rem;+}++.status-panel,+.section-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 1rem;+}++.cards {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));+ gap: 1rem;+}++.card .value {+ display: block;+ font-size: 1.8rem;+ font-weight: 700;+ margin-top: 0.35rem;+}++.pill {+ display: inline-flex;+ align-items: center;+ border: 1px solid var(--line);+ border-radius: 999px;+ padding: 0.35rem 0.75rem;+ color: var(--accent);+ background: var(--panel-soft);+ white-space: nowrap;+}++.filters {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));+ gap: 0.75rem;+ margin: 1rem 0;+}++.table-wrap {+ overflow-x: auto;+}++table {+ width: 100%;+ border-collapse: collapse;+}++th,+td {+ border-bottom: 1px solid var(--line);+ padding: 0.7rem;+ text-align: left;+ vertical-align: top;+ font-size: 0.9rem;+}++th {+ color: var(--muted);+ font-weight: 600;+}++tr {+ cursor: pointer;+}++tr:hover {+ background: var(--panel-soft);+}++.severity-high,+.severity-critical {+ color: var(--danger);+}++.severity-medium {+ color: var(--warn);+}++.harnesses {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));+ gap: 0.75rem;+ margin-top: 1rem;+}++.harness {+ border: 1px solid var(--line);+ border-radius: 12px;+ padding: 0.85rem;+ background: var(--panel-soft);+}++.drawer {+ position: fixed;+ top: 0;+ right: 0;+ bottom: 0;+ width: min(680px, 100vw);+ background: #020617;+ border-left: 1px solid var(--line);+ transform: translateX(100%);+ transition: transform 160ms ease;+ z-index: 3;+ display: flex;+ flex-direction: column;+}++.drawer.open {+ transform: translateX(0);+}++.drawer-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 1rem;+ border-bottom: 1px solid var(--line);+}++pre {+ margin: 0;+ padding: 1rem;+ overflow: auto;+ white-space: pre-wrap;+ word-break: break-word;+ font-size: 0.85rem;+}diff --git a/cli/beacon/internal/endpoint/dashboard/summary.go b/cli/beacon/internal/endpoint/dashboard/summary.gonew file mode 100644index 00000000..8895fae5--- /dev/null+++ b/cli/beacon/internal/endpoint/dashboard/summary.go@@ -0,0 +1,74 @@+package dashboard++type Summary struct {+ TotalEvents int `json:"total_events"`+ LastEventTime string `json:"last_event_time,omitempty"`+ ActiveSessions int `json:"active_sessions"`+ MalformedLines int `json:"malformed_lines"`+ CountsByAction map[string]int `json:"counts_by_action"`+ CountsByHarness map[string]int `json:"counts_by_harness"`+ CountsBySeverity map[string]int `json:"counts_by_severity"`+ PromptEvents int `json:"prompt_events"`+ ToolEvents int `json:"tool_events"`+ CommandEvents int `json:"command_events"`+ FileEvents int `json:"file_events"`+ MCPEvents int `json:"mcp_events"`+ ApprovalEvents int `json:"approval_events"`+}++func BuildSummary(result EventResult) Summary {+ summary := Summary{+ TotalEvents: result.TotalMatched,+ MalformedLines: result.MalformedLines,+ CountsByAction: map[string]int{},+ CountsByHarness: map[string]int{},+ CountsBySeverity: map[string]int{},+ }+ sessions := map[string]bool{}+ for _, record := range result.Events {+ event := record.Event+ if summary.LastEventTime == "" || event.Timestamp > summary.LastEventTime {+ summary.LastEventTime = event.Timestamp+ }+ if event.Event.Action != "" {+ summary.CountsByAction[event.Event.Action]+++ }+ if event.Harness.Name != "" {+ summary.CountsByHarness[event.Harness.Name]+++ }+ if event.Severity != "" {+ summary.CountsBySeverity[string(event.Severity)]+++ }+ if event.Session != nil && event.Session.ID != "" {+ sessions[event.Session.ID] = true+ }+ promptEvent := event.Event.Category == "prompt"+ commandEvent := event.Event.Category == "command" || event.Command != nil+ fileEvent := event.Event.Category == "file" || event.File != nil+ mcpEvent := event.Event.Category == "mcp" || event.MCP != nil+ approvalEvent := event.Event.Category == "approval" || event.Approval != nil+ switch event.Event.Category {+ case "prompt":+ summary.PromptEvents+++ case "tool":+ summary.ToolEvents+++ }+ if !promptEvent && event.Event.Action == "prompt.submitted" {+ summary.PromptEvents+++ }+ if commandEvent {+ summary.CommandEvents+++ }+ if fileEvent {+ summary.FileEvents+++ }+ if mcpEvent {+ summary.MCPEvents+++ }+ if approvalEvent {+ summary.ApprovalEvents+++ }+ }+ summary.ActiveSessions = len(sessions)+ return summary+}