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
share: reach api.beacon.sh, respect Metadata-only privacy, redact Beacon CLI tokens and AWS secrets
shukieshah02b198921fa2
diff --git a/cli/beacon/cmd/history_env_test.go b/cli/beacon/cmd/history_env_test.goindex b1e11df0..7490de74 100644--- a/cli/beacon/cmd/history_env_test.go+++ b/cli/beacon/cmd/history_env_test.go@@ -6,13 +6,17 @@ import ("path/filepath""testing"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/account"endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config")// Every test in this package runs with the local history pointed at a path that does not exist, so// a command under test never reads or writes a developer's real ~/.beacon/endpoint/history.db, and// with the session backfill off, so an install under test never sweeps a real agent session store-// that a runtime-specific environment variable points outside the test's home.+// that a runtime-specific environment variable points outside the test's home. The share commands+// also see an endpoint that is not connected to Beacon Cloud, whatever the machine's own (user or+// system) enrollment and privacy mode, and no BEACON_API_URL, so neither changes what a test sends+// or where; a test that needs a connection sets shareAutoCloud itself.func TestMain(m *testing.M) {dir, err := os.MkdirTemp("", "beacon-cmd-test")if err != nil {@@ -24,6 +28,8 @@ func TestMain(m *testing.M) {// A wizard install under test that reaches the end of a Beacon Cloud connect must not open// the developer's browser; tests that check the opening stub this themselves.onboardingOpenDashboard = func(string) error { return nil }+ _ = os.Unsetenv(account.APIURLEnv)+ shareAutoCloud = func() (bool, string) { return false, "" }code := m.Run()_ = os.RemoveAll(dir)os.Exit(code)diff --git a/cli/beacon/cmd/share.go b/cli/beacon/cmd/share.goindex 6aa7521f..9d49d118 100644--- a/cli/beacon/cmd/share.go+++ b/cli/beacon/cmd/share.go@@ -21,6 +21,7 @@ import ("github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/handoff"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/managedprivacy""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/tokens""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/version""github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"@@ -105,7 +106,10 @@ when Beacon reads that runtime's store, and from Beacon's runtime log otherwise.What is uploaded: the session's prompts, assistant text and reasoning, tool calls with theirarguments, commands, file paths and diffs, and tool output, after the same secret redaction and sizelimits the runtime log applies. Paths are rewritten relative to the session's directory, and the-home directory becomes ~. Use --print to see exactly what would be sent without sending it.+home directory becomes ~. When this endpoint forwards to Beacon Cloud in Metadata-only mode, the+share leaves out what forwarding leaves out: prompts, answers, reasoning, tool arguments and results,+command output, diffs and the derived title. Use --print to see exactly what would be sent without+sending it.Visibility: direct (the default for a new trace) means anyone with the link; private means onlyyou; public lists the trace in Discover for anyone, and asks for confirmation first. Re-sharing@@ -153,7 +157,7 @@ func init() {f.StringVar(&shareOpts.cwd, "cwd", "", "Use the most recent session that ran in this directory (default: the current directory)")f.BoolVar(&shareOpts.print, "print", false, "Print the payload that would be uploaded and send nothing")f.BoolVar(&shareOpts.dryRun, "dry-run", false, "Same as --print")- f.StringVar(&shareOpts.title, "title", "", "Title for the shared trace (default for a new trace: the session's title or first prompt; an existing trace keeps its title)")+ f.StringVar(&shareOpts.title, "title", "", "Title for the shared trace (default for a new trace: the session's title or first prompt, or none in Metadata-only mode; an existing trace keeps its title)")}f := shareCmd.Flags()f.StringVar(&shareOpts.session, "session", "", "Session id, or a unique prefix of at least 6 characters")@@ -900,6 +904,14 @@ func shareHasProjectable(events []schema.Event) bool {return false}+// shareMetadataOnly reports whether this endpoint forwards to Beacon Cloud in Metadata-only mode+// (user or system mode). A share from it then leaves out what forwarding leaves out, so publishing a+// session never sends more than the endpoint's privacy mode allows.+func shareMetadataOnly() bool {+ connected, mode := shareAutoCloud()+ return connected && mode == managedprivacy.MetadataOnly+}+func buildSharePayload(subject shareSubject) (sharePayload, error) {subject, events, err := shareEvents(subject)if err != nil {@@ -907,10 +919,12 @@ func buildSharePayload(subject shareSubject) (sharePayload, error) {}session := subject.sessionsort.SliceStable(events, func(i, j int) bool { return shareEventTime(events[i]).Before(shareEventTime(events[j])) })+ metadataOnly := shareMetadataOnly()bundle := asymptoteobserve.BuildShareBundle(events, asymptoteobserve.ShareOptions{WorkingDirectory: session.Directory,BeaconVersion: version.GetVersion(),GeneratedAt: shareNow(),+ MetadataOnly: metadataOnly,})if len(bundle.Events) == 0 {return sharePayload{}, fmt.Errorf("%s session %s %w", session.Harness, session.ID, errShareNothingYet)@@ -923,10 +937,17 @@ func buildSharePayload(subject shareSubject) (sharePayload, error) {if name := asymptoteobserve.NormalizeHarnessName(trace.Summary.Harness.Name); name != "" {trace.Summary.Harness.Name = name}- if title := strings.TrimSpace(shareOpts.title); title != "" {- trace.Title = asymptoteobserve.ShareTitle(title)- } else if title := asymptoteobserve.ShareTitle(session.Title); title != "" {- trace.Title = asymptoteobserve.RedactString(title)+ switch {+ case strings.TrimSpace(shareOpts.title) != "":+ trace.Title = asymptoteobserve.ShareTitle(shareOpts.title)+ case metadataOnly:+ // Most runtimes title a session with its first prompt, which Metadata-only keeps off the+ // trace like every other prompt. Only a title the person typed is sent.+ trace.Title = ""+ default:+ if title := asymptoteobserve.ShareTitle(session.Title); title != "" {+ trace.Title = asymptoteobserve.RedactString(title)+ }}shareSummaryFromSession(&trace.Summary, session)if session.Subagent && session.ParentID != "" {diff --git a/cli/beacon/cmd/share_test.go b/cli/beacon/cmd/share_test.goindex 490b9a07..289ef573 100644--- a/cli/beacon/cmd/share_test.go+++ b/cli/beacon/cmd/share_test.go@@ -24,6 +24,7 @@ import ("github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/handoff"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/managedprivacy""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv""github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve")@@ -316,7 +317,7 @@ func newFakeShareServer(t *testing.T) *fakeShareServer {fmt.Fprintf(w, `{"upserted":%d,"event_count":%d}`, len(batch.Events), len(f.events))case r.Method == http.MethodGet:if f.trace == nil {- http.NotFound(w, r)+ writeShareAPINotFound(w)return}last, maxNumber := "", 0@@ -327,13 +328,20 @@ func newFakeShareServer(t *testing.T) *fakeShareServer {}fmt.Fprintf(w, `{"id":"k3xabc","url":"https://beacon.sh/s/k3xabc","visibility":%q,"event_count":%d,"last_event_id":%q,"max_number":%d,"created_at":%q}`, f.trace.Visibility, len(f.events), last, maxNumber, f.created)default:- http.NotFound(w, r)+ writeShareAPINotFound(w)}}))t.Cleanup(f.server.Close)return f}+// writeShareAPINotFound answers as beacon.sh's API does for a trace it does not have: a JSON 404.+func writeShareAPINotFound(w http.ResponseWriter) {+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusNotFound)+ fmt.Fprintln(w, `{"error":"trace not found","detail":"trace not found"}`)+}+func (f *fakeShareServer) signIn(scopes ...string) {session := &account.Session{BaseURL: f.server.URL, AccessToken: "bcn_cli_secret_token", TokenType: "Bearer", User: account.User{ID: "u1", Email: "[email protected]"}, Scopes: scopes}shareAccountLoad = func() (*account.Session, error) { return session, nil }@@ -822,3 +830,97 @@ func TestShareAgainKeepsTheShareDate(t *testing.T) {t.Fatalf("second record = %q %+v", second.Message, second.Raw)}}++// An endpoint that forwards to Beacon Cloud in Metadata-only mode shares no more than forwarding+// sends: no prompt, answer, output or derived title, and the same event ids a full share uses.+func TestShareFromAMetadataOnlyEndpointLeavesContentOut(t *testing.T) {+ env := newShareEnv(t)+ full, _, err := runShareCommand(t, "--cwd", env.projectDir, "--print", "--log-path", env.logPath)+ if err != nil {+ t.Fatalf("share --print: %v", err)+ }+ var fullPayload sharePayload+ if err := json.Unmarshal([]byte(full), &fullPayload); err != nil {+ t.Fatal(err)+ }++ prev := shareAutoCloud+ shareAutoCloud = func() (bool, string) { return true, managedprivacy.MetadataOnly }+ t.Cleanup(func() { shareAutoCloud = prev })+ stdout, _, err := runShareCommand(t, "--cwd", env.projectDir, "--print", "--log-path", env.logPath)+ if err != nil {+ t.Fatalf("share --print: %v", err)+ }+ var payload sharePayload+ if err := json.Unmarshal([]byte(stdout), &payload); err != nil {+ t.Fatalf("payload is not JSON: %v\n%s", err, stdout)+ }+ if payload.Trace.Title != "" {+ t.Fatalf("title = %q, want none: the session's title is its first prompt", payload.Trace.Title)+ }+ for _, content := range []string{"Fix the login test", "login_test.go", "Fixed.", `"output"`, `"arguments"`} {+ if strings.Contains(stdout, content) {+ t.Errorf("the metadata-only payload carries %q:\n%s", content, stdout)+ }+ }+ if len(payload.Events) != len(fullPayload.Events) {+ t.Fatalf("events = %d, a full share has %d", len(payload.Events), len(fullPayload.Events))+ }+ for i, event := range payload.Events {+ if event.ID != fullPayload.Events[i].ID {+ t.Errorf("event %d id = %s, a full share names it %s", i, event.ID, fullPayload.Events[i].ID)+ }+ if event.Content != nil && event.Content.Text != "" {+ t.Errorf("event %d carries text %q", i, event.Content.Text)+ }+ }+ if !strings.Contains(stdout, "go test ./...") {+ t.Errorf("the command line, which Metadata-only keeps, is missing:\n%s", stdout)+ }++ // A title the person typed is theirs to send.+ stdout, _, err = runShareCommand(t, "--cwd", env.projectDir, "--print", "--title", "Login fix", "--log-path", env.logPath)+ if err != nil || json.Unmarshal([]byte(stdout), &payload) != nil || payload.Trace.Title != "Login fix" {+ t.Fatalf("--title: err=%v title=%q", err, payload.Trace.Title)+ }++ // Standard forwarding shares the content, as before.+ shareAutoCloud = func() (bool, string) { return true, managedprivacy.Standard }+ stdout, _, err = runShareCommand(t, "--cwd", env.projectDir, "--print", "--log-path", env.logPath)+ if err != nil || json.Unmarshal([]byte(stdout), &payload) != nil || payload.Trace.Title != "Fix the login test" || !strings.Contains(stdout, "Fixed.") {+ t.Fatalf("standard: err=%v title=%q\n%s", err, payload.Trace.Title, stdout)+ }+}++// A service with no trace API at the URL used answers with a web 404 page. The share stops there+// with that error instead of reading it as "not shared yet" and going on to create the trace.+func TestShareStopsWhenTheServiceHasNoTraceAPI(t *testing.T) {+ env := newShareEnv(t)+ var mu sync.Mutex+ var requests []string+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ mu.Lock()+ requests = append(requests, r.Method+" "+r.URL.Path)+ mu.Unlock()+ w.Header().Set("Content-Type", "text/html; charset=utf-8")+ w.WriteHeader(http.StatusNotFound)+ fmt.Fprint(w, "<!DOCTYPE html><html><body>404: This page could not be found.</body></html>")+ }))+ t.Cleanup(server.Close)+ session := &account.Session{BaseURL: server.URL, AccessToken: "bcn_cli_secret_token", TokenType: "Bearer", User: account.User{ID: "u1", Email: "[email protected]"}, Scopes: []string{account.ScopeTracesWrite}}+ shareAccountLoad = func() (*account.Session, error) { return session, nil }+ shareHTTPClient = server.Client()++ _, _, err := runShareCommand(t, "--cwd", env.projectDir, "--log-path", env.logPath)+ if err == nil || !strings.Contains(err.Error(), server.URL+" has no trace API (HTTP 404: endpoint not found)") {+ t.Fatalf("err = %v", err)+ }+ mu.Lock()+ defer mu.Unlock()+ if len(requests) != 1 || requests[0] != "GET /v1/traces/claude_code:"+shareTestSession {+ t.Fatalf("requests = %v, want only the read", requests)+ }+ if _, err := os.Stat(env.logPath); !os.IsNotExist(err) {+ t.Fatalf("a failed share recorded itself in the runtime log: %v", err)+ }+}diff --git a/cli/beacon/internal/account/login.go b/cli/beacon/internal/account/login.goindex 5b4dcc18..74a06f1e 100644--- a/cli/beacon/internal/account/login.go+++ b/cli/beacon/internal/account/login.go@@ -39,7 +39,8 @@ const (// approves the sign-in only when the permissions it showed match these.ScopeMCPTokenCreate = "mcp:token:create"// ScopeTracesWrite lets the account token upload shared traces (`beacon share`) to- // /v1/traces on beacon.sh. A session from an older `beacon login` lacks it.+ // /v1/traces on the sign-in's API (api.beacon.sh for a beacon.sh sign-in; see+ // ShareAPIBaseURL). A session from an older `beacon login` lacks it.ScopeTracesWrite = "traces:write")diff --git a/cli/beacon/internal/account/share.go b/cli/beacon/internal/account/share.goindex d17690f0..9d786777 100644--- a/cli/beacon/internal/account/share.go+++ b/cli/beacon/internal/account/share.go@@ -10,6 +10,7 @@ import ("io""net/http""net/url"+ "os""strings""time"@@ -24,8 +25,9 @@ import (//// They authorize with the signed-in CLI token when it carries ScopeTracesWrite, or with a Beacon API// key (bcn_api_...) that carries the same scope. Either credential goes only in the Authorization-// header of these requests, to the base URL it belongs to, and redirects are refused so it can never-// be resent somewhere else.+// header of these requests, to the API of the service it belongs to (ShareAPIBaseURL: beacon.sh+// serves its API from api.beacon.sh), and redirects are refused so it can never be resent somewhere+// else.const (// TracesPath is the prefix of the shared-trace write API.@@ -35,6 +37,11 @@ const (APIKeyEnv = "BEACON_API_KEY"// APIKeyPrefix starts every Beacon API key.APIKeyPrefix = "bcn_api_"+ // APIURLEnv names the environment variable that says where the shared-trace API is, for a+ // service whose API is neither at its sign-in URL nor at the host ShareAPIBaseURL knows for it.+ APIURLEnv = "BEACON_API_URL"+ // DefaultAPIURL is the API of DefaultBaseURL. The beacon.sh web host does not serve /v1.+ DefaultAPIURL = "https://api.beacon.sh"// ShareMaxBatchBytes bounds one batch body before compression. beacon.sh accepts 8 MiB; the// margin covers the batch envelope and JSON escaping differences.@@ -159,17 +166,45 @@ func apiKeyCredential(key, baseURL, source, origin string) (ShareCredential, errreturn ShareCredential{BaseURL: ResolveBaseURL(baseURL), Token: key, Source: source}, nil}+// ShareAPIBaseURL is where the shared-trace API of the service at baseURL lives: the URL in+// BEACON_API_URL when it is set, https://api.beacon.sh for beacon.sh (whose web host answers /v1 with+// its own HTML 404 page), and otherwise baseURL itself, as a self-hosted or local service serves+// both. getenv may be nil.+func ShareAPIBaseURL(baseURL string, getenv func(string) string) string {+ if getenv != nil {+ if override := strings.TrimRight(strings.TrimSpace(getenv(APIURLEnv)), "/"); override != "" {+ return override+ }+ }+ base := strings.TrimRight(strings.TrimSpace(baseURL), "/")+ if u, err := url.Parse(base); err == nil && strings.EqualFold(u.Scheme, "https") {+ switch strings.ToLower(u.Hostname()) {+ case "beacon.sh", "www.beacon.sh":+ return DefaultAPIURL+ }+ }+ return base+}+// ShareClient talks to the shared-trace write API.type ShareClient struct {cred ShareCredential- http *http.Client+ // apiBase is where the requests go: ShareAPIBaseURL of the credential's base URL, which stays+ // the service that issued the credential.+ apiBase string+ http *http.Client}-// NewShareClient checks the credential and its base URL before anything is sent. client may be nil.+// NewShareClient checks the credential, its base URL and the API it is sent to before anything is+// sent. client may be nil.func NewShareClient(cred ShareCredential, client *http.Client) (*ShareClient, error) {if !secureURL(cred.BaseURL) {return nil, errors.New("refusing to send the Beacon credential to an insecure URL")}+ apiBase := ShareAPIBaseURL(cred.BaseURL, os.Getenv)+ if !secureURL(apiBase) {+ return nil, fmt.Errorf("refusing to send the Beacon credential to an insecure URL (%s)", APIURLEnv)+ }if strings.TrimSpace(cred.Token) == "" {return nil, ErrNoShareCredential}@@ -179,11 +214,11 @@ func NewShareClient(cred ShareCredential, client *http.Client) (*ShareClient, er// A redirect would resend the credential somewhere else.clientCopy := *clientclientCopy.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }- return &ShareClient{cred: cred, http: &clientCopy}, nil+ return &ShareClient{cred: cred, apiBase: apiBase, http: &clientCopy}, nil}-// BaseURL is the service the client sends to.-func (c *ShareClient) BaseURL() string { return c.cred.BaseURL }+// BaseURL is the API the client sends its requests to (ShareAPIBaseURL).+func (c *ShareClient) BaseURL() string { return c.apiBase }// PutTrace creates or updates a trace's summary and sharing settings.func (c *ShareClient) PutTrace(ctx context.Context, externalID string, trace asymptoteobserve.ShareTraceV1) (*asymptoteobserve.ShareTraceResultV1, error) {@@ -263,7 +298,9 @@ func (c *ShareClient) GetTrace(ctx context.Context, externalID string) (*asymptoif err != nil {return nil, false, err}- if status == http.StatusNotFound {+ // Only the API's own JSON answer means the trace is not there yet. A 404 page from a host with no+ // trace API is an error: creating the trace there next would fail the same way.+ if status == http.StatusNotFound && jsonBody(payload) {return nil, false, nil}if err := c.statusError("read shared trace", status, payload); err != nil {@@ -332,7 +369,7 @@ func (c *ShareClient) do(ctx context.Context, method, externalID, suffix string,if !asymptoteobserve.ValidShareExternalID(externalID) {return nil, 0, fmt.Errorf("invalid external id %q", externalID)}- target := c.cred.BaseURL + TracesPath + url.PathEscape(externalID) + suffix+ target := c.apiBase + TracesPath + url.PathEscape(externalID) + suffixvar reader io.Readerencoding := ""if body != nil {@@ -366,7 +403,7 @@ func (c *ShareClient) do(ctx context.Context, method, externalID, suffix string,}resp, err := c.http.Do(req)if err != nil {- return nil, 0, fmt.Errorf("%s %s: %w", method, c.cred.BaseURL+TracesPath+"…", scrubURLError(err))+ return nil, 0, fmt.Errorf("%s %s: %w", method, c.apiBase+TracesPath+"…", scrubURLError(err))}defer resp.Body.Close()payload, err := io.ReadAll(io.LimitReader(resp.Body, shareMaxResponseBytes))@@ -374,7 +411,7 @@ func (c *ShareClient) do(ctx context.Context, method, externalID, suffix string,return nil, 0, err}if resp.StatusCode >= 300 && resp.StatusCode < 400 {- return nil, resp.StatusCode, fmt.Errorf("beacon.sh answered with a redirect (HTTP %d); not following it with the credential", resp.StatusCode)+ return nil, resp.StatusCode, fmt.Errorf("%s answered with a redirect (HTTP %d); not following it with the credential", c.apiBase, resp.StatusCode)}return payload, resp.StatusCode, nil}@@ -412,9 +449,19 @@ func (c *ShareClient) statusError(what string, status int, payload []byte) error}return fmt.Errorf("the %s cannot share traces: it needs the %s scope (%s)", c.cred, ScopeTracesWrite, detail)case http.StatusNotFound:- return fmt.Errorf("%s: the trace does not exist on %s (%s)", what, c.cred.BaseURL, detail)+ if !jsonBody(payload) {+ return fmt.Errorf("%s: %s has no trace API (HTTP 404: endpoint not found)", what, c.apiBase)+ }+ return fmt.Errorf("%s: the trace does not exist on %s (%s)", what, c.apiBase, detail)case http.StatusRequestEntityTooLarge:return fmt.Errorf("%s: beacon.sh refused the request as too large (%s)", what, detail)}return fmt.Errorf("%s: %s", what, detail)}++// jsonBody reports whether a response body is JSON, as every answer of the trace API is. A web+// host's 404 page is HTML.+func jsonBody(payload []byte) bool {+ payload = bytes.TrimSpace(payload)+ return len(payload) > 0 && json.Valid(payload)+}diff --git a/cli/beacon/internal/account/share_test.go b/cli/beacon/internal/account/share_test.goindex 7028b9f3..aad41ceb 100644--- a/cli/beacon/internal/account/share_test.go+++ b/cli/beacon/internal/account/share_test.go@@ -9,6 +9,7 @@ import ("io""net/http""net/http/httptest"+ "os""strings""sync""testing"@@ -19,6 +20,13 @@ import (const shareTestToken = "bcn_cli_share_secret"+// The share client reads BEACON_API_URL. A developer's own setting must not send these tests'+// requests anywhere but their test servers.+func TestMain(m *testing.M) {+ _ = os.Unsetenv(APIURLEnv)+ os.Exit(m.Run())+}+func shareCred(baseURL string) ShareCredential {return ShareCredential{BaseURL: baseURL, Token: shareTestToken, Source: CredentialSourceLogin, User: User{ID: "u", Email: "[email protected]"}}}@@ -311,6 +319,103 @@ func TestShareClientMapsAuthFailures(t *testing.T) {}}+// beacon.sh serves its web app, not /v1: a sign-in there shares through api.beacon.sh. Other+// services keep their own base URL, and BEACON_API_URL names the API outright.+func TestShareAPIBaseURL(t *testing.T) {+ for _, tc := range []struct{ base, env, want string }{+ {"https://beacon.sh", "", DefaultAPIURL},+ {"https://beacon.sh/", "", DefaultAPIURL},+ {"https://www.beacon.sh", "", DefaultAPIURL},+ {"https://BEACON.SH", "", DefaultAPIURL},+ {"https://beacon.example.com", "", "https://beacon.example.com"},+ {"http://127.0.0.1:8787/", "", "http://127.0.0.1:8787"},+ {"https://beacon.sh", " https://api.staging.example.com/ ", "https://api.staging.example.com"},+ {"http://127.0.0.1:8787", "https://api.example.com", "https://api.example.com"},+ } {+ getenv := func(name string) string {+ if name == APIURLEnv {+ return tc.env+ }+ return ""+ }+ if got := ShareAPIBaseURL(tc.base, getenv); got != tc.want {+ t.Errorf("ShareAPIBaseURL(%q, %s=%q) = %q, want %q", tc.base, APIURLEnv, tc.env, got, tc.want)+ }+ }+ if got := ShareAPIBaseURL("https://beacon.sh", nil); got != DefaultAPIURL {+ t.Errorf("ShareAPIBaseURL with no environment = %q", got)+ }+}++type shareRoundTripFunc func(*http.Request) (*http.Response, error)++func (f shareRoundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }++func TestShareClientSendsABeaconShSignInToTheAPIHost(t *testing.T) {+ var requested []string+ httpClient := &http.Client{Transport: shareRoundTripFunc(func(r *http.Request) (*http.Response, error) {+ requested = append(requested, r.Method+" "+r.URL.String())+ body := `{"id":"k3x","url":"https://beacon.sh/s/k3x","visibility":"direct","event_count":0,"last_event_id":"","max_number":0}`+ return &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": {"application/json"}}, Body: io.NopCloser(strings.NewReader(body)), Request: r}, nil+ })}+ client, err := NewShareClient(shareCred("https://beacon.sh"), httpClient)+ if err != nil {+ t.Fatal(err)+ }+ if client.BaseURL() != DefaultAPIURL {+ t.Fatalf("BaseURL = %q, want %q", client.BaseURL(), DefaultAPIURL)+ }+ if _, found, err := client.GetTrace(context.Background(), "claude_code:abc"); err != nil || !found {+ t.Fatalf("GetTrace: found=%v err=%v", found, err)+ }+ if len(requested) != 1 || requested[0] != "GET https://api.beacon.sh/v1/traces/claude_code:abc" {+ t.Fatalf("requests = %v", requested)+ }+}++func TestShareClientTakesTheAPIFromTheEnvironment(t *testing.T) {+ s := newShareServer(t)+ t.Setenv(APIURLEnv, s.server.URL+"/")+ client, err := NewShareClient(shareCred("https://beacon.sh"), s.server.Client())+ if err != nil {+ t.Fatal(err)+ }+ if _, found, err := client.GetTrace(context.Background(), "claude_code:abc"); err != nil || !found {+ t.Fatalf("GetTrace: found=%v err=%v", found, err)+ }+ if len(s.paths) != 1 || s.paths[0] != "GET /v1/traces/claude_code:abc" {+ t.Fatalf("requests = %v", s.paths)+ }++ t.Setenv(APIURLEnv, "http://api.example.com")+ if _, err := NewShareClient(shareCred("https://beacon.sh"), nil); err == nil || !strings.Contains(err.Error(), "insecure") {+ t.Fatalf("an http %s was accepted: %v", APIURLEnv, err)+ }+}++// A host with no trace API answers with its own HTML 404 page. That is not "the trace does not exist+// yet": GetTrace reports it, so the caller never goes on to create the trace there.+func TestShareClientReportsAHostWithNoTraceAPI(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "text/html; charset=utf-8")+ w.WriteHeader(http.StatusNotFound)+ fmt.Fprint(w, "<!DOCTYPE html><html><head><title>404: This page could not be found.</title></head><body>404</body></html>")+ }))+ defer server.Close()+ client, err := NewShareClient(shareCred(server.URL), server.Client())+ if err != nil {+ t.Fatal(err)+ }+ want := server.URL + " has no trace API (HTTP 404: endpoint not found)"+ state, found, err := client.GetTrace(context.Background(), "claude_code:abc")+ if err == nil || found || state != nil || !strings.Contains(err.Error(), want) {+ t.Fatalf("GetTrace = %+v found=%v err=%v, want %q", state, found, err, want)+ }+ if _, err := client.PutTrace(context.Background(), "claude_code:abc", shareTrace("direct")); err == nil || !strings.Contains(err.Error(), want) {+ t.Fatalf("PutTrace err = %v, want %q", err, want)+ }+}+func TestShareClientRefusesAnotherSchema(t *testing.T) {client, err := NewShareClient(shareCred("https://beacon.example.com"), nil)if err != nil {diff --git a/cli/beacon/internal/endpoint/asymptote/metadata_fields_test.go b/cli/beacon/internal/endpoint/asymptote/metadata_fields_test.goindex 3c5acbf3..4be1bdd3 100644--- a/cli/beacon/internal/endpoint/asymptote/metadata_fields_test.go+++ b/cli/beacon/internal/endpoint/asymptote/metadata_fields_test.go@@ -14,6 +14,7 @@ import ("github.com/pelletier/go-toml/v2""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve")// metadataOnlyRemoved is every event field Metadata-only forwarding removes: free text, documents,@@ -272,6 +273,55 @@ func sentinelEvent(t reflect.Type, prefix string) map[string]interface{} {func metadataSentinel(path string) string { return "SENTINEL:" + path + ":END" }+// metadataSentinelLeaks lists the content fields whose sentinel is still in an event's JSON and the+// metadata fields whose sentinel is gone.+func metadataSentinelLeaks(transformed string) (leaked, missing []string) {+ for _, leaf := range eventLeaves(reflect.TypeOf(schema.Event{}), "") {+ if !leaf.Text || leaf.Path == "content.retention" {+ continue // Metadata-only rewrites retention to "metadata"+ }+ present := strings.Contains(transformed, metadataSentinel(leaf.Path))+ if removedByMetadataOnly(leaf.Path) && present {+ leaked = append(leaked, leaf.Path)+ }+ if !removedByMetadataOnly(leaf.Path) && !present {+ missing = append(missing, leaf.Path)+ }+ }+ sort.Strings(leaked)+ sort.Strings(missing)+ return leaked, missing+}++// StripToMetadata is the Go twin of the Metadata-only transform, used where Beacon publishes an+// endpoint's events itself (`beacon share`). On an event with every field set, it removes exactly+// the fields the transform removes and keeps every other one.+func TestStripToMetadataRemovesExactlyWhatTheTransformRemoves(t *testing.T) {+ data, err := json.Marshal(sentinelEvent(reflect.TypeOf(schema.Event{}), ""))+ if err != nil {+ t.Fatal(err)+ }+ var event schema.Event+ if err := json.Unmarshal(data, &event); err != nil {+ t.Fatal(err)+ }+ asymptoteobserve.StripToMetadata(&event)+ stripped, err := json.Marshal(event)+ if err != nil {+ t.Fatal(err)+ }+ leaked, missing := metadataSentinelLeaks(string(stripped))+ if len(leaked) > 0 {+ t.Errorf("StripToMetadata kept content fields %v: add each to StripToMetadata along with its del() in the transform\n%s", leaked, stripped)+ }+ if len(missing) > 0 {+ t.Errorf("StripToMetadata removed metadata fields %v:\n%s", missing, stripped)+ }+ if event.Content == nil || event.Content.Retention != schema.ContentRetentionMetadata || event.Content.Included || !event.Content.Redacted {+ t.Errorf("content marker = %+v, want metadata retention", event.Content)+ }+}+// Runs the Metadata-only transform with Vector's own VRL runtime on an event with every field set,// and checks that every content field is gone and every metadata field is still there.func TestMetadataTransformRemovesEveryContentFieldWithVector(t *testing.T) {@@ -313,21 +363,7 @@ func TestMetadataTransformRemovesEveryContentFieldWithVector(t *testing.T) {if err := json.Unmarshal([]byte(transformed), &parsed); err != nil {t.Fatalf("transformed event is not an event: %v\n%s", err, transformed)}- var missing, leaked []string- for _, leaf := range eventLeaves(reflect.TypeOf(schema.Event{}), "") {- if !leaf.Text || leaf.Path == "content.retention" {- continue // the transform rewrites retention to "metadata"- }- present := strings.Contains(transformed, metadataSentinel(leaf.Path))- if removedByMetadataOnly(leaf.Path) && present {- leaked = append(leaked, leaf.Path)- }- if !removedByMetadataOnly(leaf.Path) && !present {- missing = append(missing, leaf.Path)- }- }- sort.Strings(leaked)- sort.Strings(missing)+ leaked, missing := metadataSentinelLeaks(transformed)if len(leaked) > 0 {t.Errorf("Metadata-only forwarded content fields %v:\n%s", leaked, transformed)}diff --git a/docs/changelog/cli.mdx b/docs/changelog/cli.mdxindex 650d3c3d..38cea81e 100644--- a/docs/changelog/cli.mdx+++ b/docs/changelog/cli.mdx@@ -12,6 +12,9 @@ Stay up to date with the latest changes to the Agent Beacon CLI.## October 2026- **Setup ends at the dashboard** · Confirming Beacon Cloud in the `beacon endpoint install` wizard used to end on some forty lines of file paths, connect details, an MCP table and per-runtime steps, and nothing pointed to the hosted dashboard. It now ends on four lines: the account, device and privacy mode; the session backfill; the dashboard URL; and where Beacon Cloud MCP was added. Beacon then opens the dashboard in your browser, except with `--no-browser`, over SSH, or on Linux without a display. The sign-in wait screen now also asks you to open the URL in the browser where you are signed in to beacon.sh, and cancelling the wizard says that nothing was installed and how to start again. `beacon endpoint connect` and `beacon mcp connect` print the same output as before. See [Onboarding](/cli/endpoint-onboarding#when-setup-finishes).+- **`beacon share` reaches beacon.sh's API** · Sharing sent its requests to `https://beacon.sh/v1/traces`, which the beacon.sh web host does not serve, so every share from a beacon.sh sign-in or key failed with "the trace does not exist on https://beacon.sh (HTTP 404)". A beacon.sh credential now shares through `https://api.beacon.sh`, and `BEACON_API_URL` names another API host. A 404 that is a web page rather than the API's own reply now stops the share with `<url> has no trace API (HTTP 404: endpoint not found)` instead of being read as a trace that does not exist yet. See [Where the requests go](/cli/share#where-the-requests-go).+- **Sharing follows Metadata-only privacy** · On an endpoint that forwards to Beacon Cloud in Metadata-only mode, `beacon share`, `refresh`, `--follow` and the git pre-push hook uploaded the session's prompts, answers, command output and diffs anyway. They now leave out exactly what forwarding leaves out, and take no title from the session, whose title is usually its first prompt; `--title` still sets one. Event ids are unchanged, so re-sharing upserts the same events. See [Metadata-only endpoints](/cli/share#metadata-only-endpoints).+- **Redaction catches Beacon's sign-in token and AWS secret keys beside their key id** · Redaction already removed `bcn_api_`, `bcn_device_`, `bcn_mcp_` and `bcn_enfdev_` keys. It now also removes the `beacon login` token (`bcn_cli_…`), MCP refresh tokens (`bcn_mcprt_…`) and the sign-in's `bcn_code_…`, `bcn_client_…` and `bcn_exchange_…` values, and the 40-character AWS secret key that follows an `AKIA…` or `ASIA…` key id, as in a credentials CSV. Both used to reach the log and Beacon Cloud unredacted. See [What is redacted](/security/retention-redaction#what-is-redacted).- **Self-update installs only Beacon-signed packages, over https** · The macOS self-updater took the Apple team a package must be signed by from `update-manifest.json`, which is unsigned, matched it as a substring of the signature output, and skipped the check when the manifest named no team. Whoever could rewrite the manifest could have any notarized package installed as root. The team is now built into `beacon` (Asymptote Labs, `3A98D35XJR`) and must match the package's installer signer exactly, for self-update and the enterprise edition install alike. The manifest and the package must also be fetched over `https`, plain `http` only to a loopback mirror and never through a redirect, so a `managed.json` that names an `http://` update URL on another host stops updating until it is changed to `https`.- **The Jamf hook repair script no longer hands the console user root** · `jamf/claude/common/repair-hooks.sh` runs as root. It granted the console user permission to add and delete entries in `/var/log/beacon-agent`, which let them replace the runtime log with a link that the root collector then opened, and it ran `chown -R` on `~/.beacon` as root, which a planted hard link turned into ownership of a root-run binary. The directory grant is gone, and the script now removes every grant that adds or deletes entries there, including ones earlier runs gave a previous console user and the one the Jamf guide's snippet used to add. It creates and fixes up `~/.beacon` as the user, refuses a symlinked directory, and moves aside one the user does not own. The Jamf guide explains how to remove the old grant by hand.- **The scheduled inventory job follows every moved runtime directory** · The job starts without your shell's environment, so a per-user install or repair records the variables that move a runtime's user directory into it. It recorded `CODEX_HOME`, `HERMES_HOME`, `CLINE_DIR`, `GEMINI_CLI_HOME` and `CLAUDE_CONFIG_DIR`, and now also `KIRO_HOME`, `KIMI_CODE_HOME`, `DSH_HOME`, `OH_PERSISTENCE_DIR`, `OPENCLAW_STATE_DIR`, `XDG_CONFIG_HOME` (Muse, and VS Code on Linux), `PI_CODING_AGENT_DIR`, `OMO_CODING_AGENT_DIR`, `SENPI_CODING_AGENT_DIR`, `PRIME_AGENT_CODING_AGENT_DIR`, and Oh My Pi's `PI_CONFIG_DIR`, `OMP_PROFILE` and `PI_PROFILE`. With one of these set only in your shell, the job used to inventory the default directory while the runtime read the moved one. See [Inventory heartbeats](/cli/endpoint-inventory#inventory-heartbeats).diff --git a/docs/cli/account-auth.mdx b/docs/cli/account-auth.mdxindex 178c5292..9da77247 100644--- a/docs/cli/account-auth.mdx+++ b/docs/cli/account-auth.mdx@@ -98,7 +98,7 @@ The CLI uses the versioned `2026-09-01` grant contract:- `GET /cli/auth?state=...&port=...&scopes=...` authenticates the person, lists every requested scope (space-separated in `scopes`), and redirects to the loopback callback with `state` and a one-time `exchange_code`.- `POST /api/cli/auth/exchange` accepts the exchange code, state, and PKCE verifier. It returns a scoped access token, expiry, user identity, organization memberships, and optional active organization.- `POST /api/cli/mcp/tokens` accepts `{"name": ..., "expires_in_days": ...}` with the access token as a Bearer credential and returns a personal Beacon Cloud MCP token (`token`, `access_token` metadata, `mcp_url`). It requires `mcp:token:create`.-- `PUT /v1/traces/{external_id}`, `POST /v1/traces/{external_id}/events/batch` and `GET /v1/traces/{external_id}` create a shared trace from its `beacon.trace.v1` summary, upsert its trace events, and read it back (with the id of the last event held) for [`beacon share`](/cli/share) (and for the git pre-push hook, only after you opt in with [`beacon git setup --share-sessions`](/cli/git#sharing-sessions-on-push)), with the access token (or a `bcn_api_` API key) as a Bearer credential. They require `traces:write`.+- `PUT /v1/traces/{external_id}`, `POST /v1/traces/{external_id}/events/batch` and `GET /v1/traces/{external_id}` create a shared trace from its `beacon.trace.v1` summary, upsert its trace events, and read it back (with the id of the last event held) for [`beacon share`](/cli/share) (and for the git pre-push hook, only after you opt in with [`beacon git setup --share-sessions`](/cli/git#sharing-sessions-on-push)), with the access token (or a `bcn_api_` API key) as a Bearer credential. They require `traces:write`. For a beacon.sh sign-in they go to `https://api.beacon.sh`; see [where the requests go](/cli/share#where-the-requests-go).- `POST /api/cli/auth/revoke` accepts the access token as a Bearer credential and revokes it.`beacon login` requests `profile:read`, `device:enroll`, `mcp:token:create` and `traces:write`. A later `beacon endpoint connect` can use `device:enroll` to mint a device-specific ingest key without treating the account token as an ingest credential, and `beacon mcp token create` uses `mcp:token:create` to mint a personal MCP token. beacon.sh approves the sign-in only when the permissions its page showed match the ones the CLI registered, so a crafted link cannot hide one. `beacon share` uses `traces:write` to upload a session you choose to share. A session from an older `beacon login` lacks `mcp:token:create` or `traces:write`; run `beacon login` again to create MCP tokens or share traces from the CLI.diff --git a/docs/cli/share.mdx b/docs/cli/share.mdxindex b7823859..e1981c44 100644--- a/docs/cli/share.mdx+++ b/docs/cli/share.mdx@@ -83,6 +83,10 @@ Before anything leaves the machine:beacon.sh redacts every string again on its side. Redaction catches common credential shapes, not everything sensitive, so read `--print` before sharing a session that touched secrets.+### Metadata-only endpoints++When this machine forwards to [Beacon Cloud](/cli/endpoint-connect) in Metadata-only privacy mode (user or system mode), `beacon share` leaves out what forwarding leaves out, so a share never sends more than the endpoint's privacy mode allows. The trace keeps the session's shape: event types and order, tool and command names, command lines, file paths, MCP servers and tools, approval and policy decisions, models, token usage and the ids that tie events together. It has no prompt text, answers or reasoning, tool arguments or results, command output, diffs, raw payloads, or approval and policy reasons. The title is not taken from the session either, because most runtimes title a session with its first prompt; pass `--title` to give the trace one. Event ids are the same in both modes, so sharing a session again with `beacon share` after the endpoint switched to Metadata-only upserts the events already on beacon.sh rather than adding copies; `refresh` sends only the newer ones. This applies to `beacon share`, `refresh`, `--follow` and the git pre-push hook. Run `--print` to see the result.+`--print` (or `--dry-run`) prints exactly that payload as JSON and sends nothing: the external id the requests go to, `trace` (the body of `PUT /v1/traces/{external_id}`) and `events` (every event the `POST /v1/traces/{external_id}/events/batch` requests would carry, at most 1,000 per request):```json@@ -174,6 +178,10 @@ Where nobody can run `beacon login` (CI runners, containers, scheduled jobs), usWith no sign-in on the machine, `BEACON_API_KEY` is used. On a machine that also has a sign-in carrying `traces:write`, the sign-in wins unless you pass `--key`. A key for a self-hosted Beacon service goes with `BEACON_AUTH_URL` (or `--auth-url`) set to that service. An API key is sent to beacon.sh, or to `--auth-url` / `BEACON_AUTH_URL` when set. Either credential goes only in the request's `Authorization` header, redirects are refused, and neither is printed.+### Where the requests go++beacon.sh serves its API from `https://api.beacon.sh`, so a beacon.sh sign-in or key sends the three trace requests there. Any other service gets them at its own URL (the one you signed in to, or `--auth-url` / `BEACON_AUTH_URL`). `BEACON_API_URL` names the API outright, for a service whose API is on another host; it must be `https://`, or `http://` on loopback. When the host answers with a web page's 404 instead of the API's own reply, `beacon share` stops with `<url> has no trace API (HTTP 404: endpoint not found)` and creates nothing.+## CI examplesThese run an agent and share its session in the same job. Claude Code and Codex CLI keep their sessions in stores `beacon share` reads directly, so nothing else needs to be installed. For a runtime whose sessions Beacon reads only from its runtime log, start [Beacon CI telemetry](/cli/ci-start) before the agent and pass the CI log with `--log-path`. Without a terminal, `--visibility public` needs `--yes`; the default, `direct`, makes the trace viewable by anyone with the link.@@ -280,7 +288,7 @@ The link goes to stdout and a summary to stderr. `--json` prints one document:| `--cwd <dir>` | Most recent session in this directory (default: current directory) || `--harness <runtime>` | Only this runtime's sessions, or `auto` (default) || `--visibility <level>` | `public`, `direct` (default for a new trace) or `private` |-| `--title <text>` | Title for the trace (default: the session's title or first prompt) |+| `--title <text>` | Title for the trace (default: the session's title or first prompt; none in Metadata-only mode) || `--key <key>` | Beacon API key to share with || `--auth-url <url>` | Service an API key is sent to || `--list` | List candidate sessions and share nothing |diff --git a/docs/security/retention-redaction.mdx b/docs/security/retention-redaction.mdxindex 18f1bc80..c453ce82 100644--- a/docs/security/retention-redaction.mdx+++ b/docs/security/retention-redaction.mdx@@ -27,9 +27,10 @@ Redaction runs on retained text (prompts, command output, diffs, tool arguments| Authorization headers and flags | `Authorization: Bearer …`, `Authorization: Basic …`, `--password …`, `--token=…` || URL credentials | the password in `postgres://user:…@host`, `https://x-access-token:…@github.com` || Private keys | PEM and OpenSSH `PRIVATE KEY` blocks, including a block cut off before its end line |-| Recognizable tokens (the public type prefix stays, as in `ghp_[REDACTED]`) | Anthropic and OpenAI `sk-…`, AWS `AKIA…`/`ASIA…`, GitHub `ghp_…`/`github_pat_…`, GitLab `glpat-…`, Slack `xox…-`, Stripe `sk_live_…`, Google `AIza…`, npm, Hugging Face, Beacon `bcn_…` keys, and JWTs |+| Recognizable tokens (the public type prefix stays, as in `ghp_[REDACTED]`) | Anthropic and OpenAI `sk-…`, AWS `AKIA…`/`ASIA…`, GitHub `ghp_…`/`github_pat_…`, GitLab `glpat-…`, Slack `xox…-`, Stripe `sk_live_…`, Google `AIza…`, npm, Hugging Face, Beacon keys and tokens (`bcn_api_…`, `bcn_device_…`, `bcn_enfdev_…`, `bcn_mcp_…`, `bcn_mcprt_…`, and the `beacon login` token `bcn_cli_…` with its `bcn_code_…`, `bcn_client_…` and `bcn_exchange_…` values), and JWTs |+| An AWS secret key beside its key id | the 40-character secret that follows an `AKIA…` or `ASIA…` key id within a few spaces, commas, colons, pipes or quotes, as in a credentials CSV (`AKIA…,wJalr…`) or a table |-Redaction is pattern-based. A credential with no label and no recognizable shape, such as a bare random password, is not detected, so treat retained content as sensitive. Metadata-only forwarding is the control for keeping content off Beacon Cloud entirely.+Redaction is pattern-based. A credential with no label and no recognizable shape, such as a bare random password, is not detected, so treat retained content as sensitive. Metadata-only forwarding is the control for keeping content off Beacon Cloud entirely, and [`beacon share`](/cli/share#metadata-only-endpoints) follows it: a Metadata-only endpoint shares no content either.## Prompt event examplediff --git a/docs/sharing/api-key.mdx b/docs/sharing/api-key.mdxindex 64d45639..73255417 100644--- a/docs/sharing/api-key.mdx+++ b/docs/sharing/api-key.mdx@@ -22,7 +22,7 @@ beacon share --cwd . --jsonNo `beacon login` is needed. Prefer the environment variable to `--key`, which puts the key on the command line where process listings can see it.-`beacon share` uses the first credential available: `--key`, then a `beacon login` sign-in carrying `traces:write`, then `BEACON_API_KEY`. On a machine that is also signed in, pass `--key` to use the key. The key is sent only in the request's `Authorization` header to beacon.sh, redirects are refused, and it is never printed. For a self-hosted Beacon service, set `BEACON_AUTH_URL` (or `--auth-url`) to that service.+`beacon share` uses the first credential available: `--key`, then a `beacon login` sign-in carrying `traces:write`, then `BEACON_API_KEY`. On a machine that is also signed in, pass `--key` to use the key. The key is sent only in the request's `Authorization` header to beacon.sh's API (`api.beacon.sh`), redirects are refused, and it is never printed. For a self-hosted Beacon service, set `BEACON_AUTH_URL` (or `--auth-url`) to that service, and `BEACON_API_URL` too if its API is on another host.## Run the share in the agent's jobdiff --git a/docs/sharing/index.mdx b/docs/sharing/index.mdxindex 40c93eef..ac5536b3 100644--- a/docs/sharing/index.mdx+++ b/docs/sharing/index.mdx@@ -58,6 +58,7 @@ Every workflow publishes the same thing: a `beacon.trace.v1` trace built from th- Paths under the session's directory are written relative to it, and your home directory becomes `~`.- The working directory and repository path are left out. The project is named by the repository's or directory's name, and the remote is sent without credentials.- Cost is sent only when the runtime reported one, never a list-price estimate.+- On a machine that forwards to Beacon Cloud in Metadata-only mode, prompts, answers, reasoning, tool arguments and output, diffs and the derived title are left out, as forwarding leaves them out. See [Metadata-only endpoints](/cli/share#metadata-only-endpoints).beacon.sh redacts every string again on its side. Redaction catches common credential shapes, not everything sensitive, so run `beacon share --print` to read exactly what would be uploaded before sharing a session that touched secrets. [`beacon share`](/cli/share#what-is-uploaded) has the full details.diff --git a/pkg/asymptoteobserve/metadata_only.go b/pkg/asymptoteobserve/metadata_only.gonew file mode 100644index 00000000..a4018487--- /dev/null+++ b/pkg/asymptoteobserve/metadata_only.go@@ -0,0 +1,108 @@+package asymptoteobserve++import "reflect"++// StripToMetadata removes from ev every field Beacon Cloud's Metadata-only forwarding removes: the+// prompt's text, the message, raw, command output, the file diff, gen_ai input, output and system+// instructions, a tool's description, definitions, call arguments and result, retrieval queries and+// documents, an evaluation's explanation, an agent's description, stop sequences, and approval and+// policy reasons. What stays is the metadata that forwarding keeps: identifiers, names, paths, the+// command line, decisions, model and token usage. A content marker the event carries is rewritten to+// say so (retention metadata, not included, redacted).+//+// It mirrors the beacon_runtime_metadata Vector transform (metadata-transforms.toml in the+// forwarding pack), including which emptied blocks are dropped, so anything else that publishes an+// endpoint's events in Metadata-only mode, such as `beacon share`, sends no more than forwarding+// would. A test in the forwarding pack holds the two to the same list of fields.+//+// Only ev changes: every block it edits is copied first, so another event that shares one of ev's+// pointers keeps its content.+func StripToMetadata(ev *Event) {+ if ev == nil {+ return+ }+ ev.Message = ""+ ev.Raw = nil+ if ev.Prompt != nil {+ // prompt.id names the turn an event belongs to and stays.+ prompt := *ev.Prompt+ prompt.Text = ""+ ev.Prompt = nonZeroOrNil(prompt)+ }+ if ev.Command != nil {+ command := *ev.Command+ command.Output = ""+ ev.Command = &command+ }+ if ev.File != nil {+ file := *ev.File+ file.Diff = ""+ ev.File = &file+ }+ if ev.Approval != nil {+ approval := *ev.Approval+ approval.Reason = ""+ ev.Approval = nonZeroOrNil(approval)+ }+ if ev.Policy != nil {+ policy := *ev.Policy+ policy.Reason = ""+ ev.Policy = nonZeroOrNil(policy)+ }+ if ev.GenAI != nil {+ ev.GenAI = stripGenAIToMetadata(*ev.GenAI)+ }+ if ev.Content != nil {+ content := *ev.Content+ content.Retention = ContentRetentionMetadata+ content.Included = false+ content.Redacted = true+ ev.Content = &content+ }+}++func stripGenAIToMetadata(genAI GenAIInfo) *GenAIInfo {+ genAI.Input = nil+ genAI.Output = nil+ genAI.SystemInstructions = nil+ genAI.SystemInstructionsText = ""+ genAI.Retrieval = nil+ if genAI.Tool != nil {+ tool := *genAI.Tool+ tool.Description = ""+ tool.Definitions = nil+ if tool.Call != nil {+ call := *tool.Call+ call.Arguments = nil+ call.Result = nil+ call.ResultText = ""+ tool.Call = nonZeroOrNil(call)+ }+ genAI.Tool = nonZeroOrNil(tool)+ }+ if genAI.Evaluation != nil {+ evaluation := *genAI.Evaluation+ evaluation.Explanation = ""+ genAI.Evaluation = nonZeroOrNil(evaluation)+ }+ if genAI.Agent != nil {+ agent := *genAI.Agent+ agent.Description = ""+ genAI.Agent = nonZeroOrNil(agent)+ }+ if genAI.Request != nil {+ request := *genAI.Request+ request.StopSequences = nil+ genAI.Request = nonZeroOrNil(request)+ }+ return nonZeroOrNil(genAI)+}++// nonZeroOrNil is a pointer to value, or nil when value is its type's zero value, as the transform+// drops an object it emptied.+func nonZeroOrNil[T any](value T) *T {+ if reflect.ValueOf(value).IsZero() {+ return nil+ }+ return &value+}diff --git a/pkg/asymptoteobserve/metadata_only_test.go b/pkg/asymptoteobserve/metadata_only_test.gonew file mode 100644index 00000000..4f72864c--- /dev/null+++ b/pkg/asymptoteobserve/metadata_only_test.go@@ -0,0 +1,167 @@+package asymptoteobserve++import (+ "encoding/json"+ "strings"+ "testing"+)++// metadataOnlyFixture is an event with every content field StripToMetadata removes set to text+// containing "secret", and metadata beside each.+func metadataOnlyFixture() Event {+ event := shareEventAt("2026-10-01T10:00:00Z", "claude_code", CollectionMethodHook, "command.executed", "command")+ event.Message = "secret message"+ event.Raw = map[string]interface{}{"tool_input": map[string]interface{}{"command": "secret raw"}}+ event.Prompt = &PromptInfo{ID: "p1", Text: "secret prompt"}+ event.Command = &CommandInfo{Command: "go test ./...", ExitCode: intPtr(1), DurationMS: 42, Output: "secret output"}+ event.File = &FileInfo{Path: "main.go", Operation: "modify", DiffHash: "sha256:d", DiffBytes: 11, Diff: "secret diff"}+ event.Approval = &ApprovalInfo{Required: true, Decision: "deny", Reason: "secret approval reason"}+ event.Policy = &PolicyInfo{ID: "pol-1", Decision: "deny", Enforcement: "enforce", Reason: "secret policy reason"}+ event.Content = &ContentInfo{Retention: ContentRetentionFull, Included: true, Hash: "sha256:c", Bytes: 13}+ event.Model = "claude-sonnet-5-5"+ event.GenAI = &GenAIInfo{+ Input: &GenAIInputInfo{Messages: TextInputMessages("secret input")},+ Output: &GenAIOutputInfo{Messages: TextOutputMessages("secret answer")},+ SystemInstructions: SystemInstructionParts("secret system prompt"),+ SystemInstructionsText: "secret system prompt",+ Retrieval: &GenAIRetrievalInfo{QueryText: "secret query", Documents: []interface{}{"secret document"}},+ Tool: &GenAIToolInfo{+ Name: "Bash", Type: "function", Description: "secret tool description", Definitions: []interface{}{"secret definition"},+ Call: &GenAIToolCallInfo{ID: "toolu_1", Arguments: map[string]interface{}{"command": "secret arguments"}, Result: "secret result", ResultText: "secret result"},+ },+ Evaluation: &GenAIEvaluationInfo{Name: "helpfulness", Explanation: "secret explanation"},+ Agent: &GenAIAgentInfo{ID: "a1", Name: "reviewer", Description: "secret agent description"},+ Request: &GenAIRequestInfo{Model: "claude-sonnet-5-5", StopSequences: []string{"secret stop"}},+ Usage: &GenAIUsageInfo{InputTokens: int64Ptr(5), OutputTokens: int64Ptr(7)},+ }+ return event+}++func TestStripToMetadataRemovesContentAndKeepsMetadata(t *testing.T) {+ original := metadataOnlyFixture()+ before, err := json.Marshal(original)+ if err != nil {+ t.Fatal(err)+ }+ stripped := original+ StripToMetadata(&stripped)+ after, err := json.Marshal(stripped)+ if err != nil {+ t.Fatal(err)+ }+ if strings.Contains(string(after), "secret") {+ t.Fatalf("content survived StripToMetadata:\n%s", after)+ }+ // The threat-rules copies of the semconv values are never written, but are content all the same.+ if stripped.GenAI.SystemInstructionsText != "" || stripped.GenAI.Tool.Call.ResultText != "" {+ t.Fatalf("rule-only text kept: %q %q", stripped.GenAI.SystemInstructionsText, stripped.GenAI.Tool.Call.ResultText)+ }+ g := stripped.GenAI+ switch {+ case stripped.Prompt == nil || stripped.Prompt.ID != "p1":+ t.Errorf("prompt = %+v, want its id kept", stripped.Prompt)+ case stripped.Command.Command != "go test ./..." || stripped.Command.ExitCode == nil || *stripped.Command.ExitCode != 1 || stripped.Command.DurationMS != 42:+ t.Errorf("command = %+v", stripped.Command)+ case stripped.File.Path != "main.go" || stripped.File.Operation != "modify" || stripped.File.DiffHash != "sha256:d" || stripped.File.DiffBytes != 11:+ t.Errorf("file = %+v", stripped.File)+ case stripped.Approval.Decision != "deny" || !stripped.Approval.Required || stripped.Policy.ID != "pol-1" || stripped.Policy.Enforcement != "enforce":+ t.Errorf("approval = %+v policy = %+v", stripped.Approval, stripped.Policy)+ case g.Tool.Name != "Bash" || g.Tool.Type != "function" || g.Tool.Call.ID != "toolu_1":+ t.Errorf("tool = %+v call = %+v", g.Tool, g.Tool.Call)+ case g.Evaluation.Name != "helpfulness" || g.Agent.Name != "reviewer" || g.Agent.ID != "a1" || g.Request.Model != "claude-sonnet-5-5":+ t.Errorf("gen_ai = %+v", g)+ case g.Usage == nil || *g.Usage.InputTokens != 5 || *g.Usage.OutputTokens != 7 || stripped.Model != "claude-sonnet-5-5":+ t.Errorf("usage = %+v model = %q", g.Usage, stripped.Model)+ case stripped.Session == nil || stripped.Session.ID != "sess-1" || stripped.Event.Action != "command.executed":+ t.Errorf("identity = %+v %+v", stripped.Session, stripped.Event)+ }+ if c := stripped.Content; c == nil || c.Retention != ContentRetentionMetadata || c.Included || !c.Redacted || c.Hash != "sha256:c" {+ t.Errorf("content marker = %+v", c)+ }+ // The caller's copy shares every pointer with the stripped event and keeps all of it.+ if again, _ := json.Marshal(original); string(again) != string(before) {+ t.Fatalf("StripToMetadata changed another event's blocks:\nbefore %s\nafter %s", before, again)+ }+ if original.GenAI.SystemInstructionsText == "" || original.GenAI.Tool.Call.ResultText == "" {+ t.Fatal("StripToMetadata changed another event's rule-only text")+ }+}++// A block left with nothing in it goes, as the Vector transform deletes an object it emptied; the+// command and file blocks stay, as they do there.+func TestStripToMetadataDropsBlocksItEmptied(t *testing.T) {+ event := Event{+ Prompt: &PromptInfo{Text: "x"},+ Approval: &ApprovalInfo{Reason: "x"},+ Policy: &PolicyInfo{Reason: "x"},+ Command: &CommandInfo{Output: "x"},+ File: &FileInfo{Diff: "x"},+ GenAI: &GenAIInfo{+ Input: &GenAIInputInfo{Messages: TextInputMessages("x")},+ Tool: &GenAIToolInfo{Description: "x", Call: &GenAIToolCallInfo{Arguments: "x"}},+ Evaluation: &GenAIEvaluationInfo{Explanation: "x"},+ Agent: &GenAIAgentInfo{Description: "x"},+ Request: &GenAIRequestInfo{StopSequences: []string{"x"}},+ },+ }+ StripToMetadata(&event)+ if event.Prompt != nil || event.Approval != nil || event.Policy != nil || event.GenAI != nil {+ t.Fatalf("emptied blocks kept: prompt=%+v approval=%+v policy=%+v gen_ai=%+v", event.Prompt, event.Approval, event.Policy, event.GenAI)+ }+ if event.Command == nil || event.File == nil || event.Content != nil {+ t.Fatalf("command=%+v file=%+v content=%+v", event.Command, event.File, event.Content)+ }+ partial := Event{GenAI: &GenAIInfo{Tool: &GenAIToolInfo{Name: "Bash", Call: &GenAIToolCallInfo{Result: "x"}}}}+ StripToMetadata(&partial)+ if partial.GenAI == nil || partial.GenAI.Tool == nil || partial.GenAI.Tool.Name != "Bash" || partial.GenAI.Tool.Call != nil {+ t.Fatalf("gen_ai = %+v", partial.GenAI)+ }+ StripToMetadata(nil)+}++// A Metadata-only share carries no prompt, answer, output, diff, argument, result or reason, and+// names every event exactly as a full share of the same session does.+func TestShareBundleMetadataOnly(t *testing.T) {+ events := shareFieldEvents()+ for i := range events {+ events[i].Event.ID = "" // derived from the content, which the strip must not change+ }+ full := BuildShareBundle(events, shareTestOpts)+ opts := shareTestOpts+ opts.MetadataOnly = true+ meta := BuildShareBundle(events, opts)+ if len(meta.Events) != len(full.Events) || len(meta.Events) == 0 {+ t.Fatalf("events: metadata-only %d, full %d", len(meta.Events), len(full.Events))+ }+ for i := range meta.Events {+ if meta.Events[i].ID != full.Events[i].ID || meta.Events[i].Type != full.Events[i].Type {+ t.Errorf("event %d: metadata-only %s/%s, full %s/%s", i, meta.Events[i].ID, meta.Events[i].Type, full.Events[i].ID, full.Events[i].Type)+ }+ }+ data, err := json.Marshal(meta)+ if err != nil {+ t.Fatal(err)+ }+ // The MCP resource URI is metadata Metadata-only forwarding keeps; the call's arguments and+ // result (a path and the text read from it) are not.+ for _, content := range []string{"todo.md", "No such file", "+++", `"path":"~/secret.txt"`, "from ~/secret.txt", "I changed", "writes to", "is protected", "permission denied", `"cwd"`, `"nested"`} {+ if strings.Contains(string(data), content) {+ t.Errorf("metadata-only bundle carries %q:\n%s", content, data)+ }+ }+ for _, kept := range []string{"cat ~/.config/app.toml", "main.go", "toolu_c", "mcp__fs__read", `"decision":"deny"`} {+ if !strings.Contains(string(data), kept) {+ t.Errorf("metadata-only bundle lost %q:\n%s", kept, data)+ }+ }+ if title := NewShareTrace(meta, "").Title; title != "" {+ t.Errorf("metadata-only title = %q, want none", title)+ }+ if NewShareTrace(full, "").Title == "" {+ t.Error("the full share has no title from its first prompt")+ }+ // The caller's events still carry their content.+ if events[0].Prompt == nil || events[0].Prompt.Text == "" || events[1].Command.Output == "" {+ t.Fatal("BuildShareBundle stripped the caller's events")+ }+}diff --git a/pkg/asymptoteobserve/privacy.go b/pkg/asymptoteobserve/privacy.goindex 2973d2e7..21c98eea 100644--- a/pkg/asymptoteobserve/privacy.go+++ b/pkg/asymptoteobserve/privacy.go@@ -343,17 +343,23 @@ var redactionRules = concatRules([]redactionRule{// and stays (`ghp_[REDACTED]`, `AKIA[REDACTED]`), the way secret scanners report a finding: the// line still says a GitHub token or an AWS key was there, which is what detection rules match on// in the log, and none of the credential is left.- rule(`\b(sk-)[A-Za-z0-9_-]{20,}`, "${1}"+redactedValue, nil, "sk-"), // Anthropic sk-ant-, OpenAI sk-proj- and sk-- rule(`\b(AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}\b`, "${1}"+redactedValue, nil, "AKIA", "ASIA", "ABIA", "ACCA"), // AWS access key id- rule(`\b(gh[pousr]_)[A-Za-z0-9]{30,}`, "${1}"+redactedValue, nil, "ghp_", "gho_", "ghu_", "ghs_", "ghr_"), // GitHub tokens- rule(`\b(github_pat_)[A-Za-z0-9_]{22,}`, "${1}"+redactedValue, nil, "github_pat_"), // GitHub fine-grained tokens- rule(`\b(glpat-)[A-Za-z0-9_-]{20,}`, "${1}"+redactedValue, nil, "glpat-"), // GitLab- rule(`\b(xox[abposr]-)[A-Za-z0-9-]{10,}`, "${1}"+redactedValue, nil, "xox"), // Slack- rule(`\b([rs]k_(?:live|test)_)[A-Za-z0-9]{16,}`, "${1}"+redactedValue, nil, "k_live_", "k_test_"), // Stripe- rule(`\b(AIza)[0-9A-Za-z_-]{35}`, "${1}"+redactedValue, nil, "AIza"), // Google API key- rule(`\b(npm_)[A-Za-z0-9]{36}`, "${1}"+redactedValue, nil, "npm_"), // npm- rule(`\b(hf_)[A-Za-z0-9]{30,}`, "${1}"+redactedValue, nil, "hf_"), // Hugging Face- rule(`\b(bcn_(?:api|device|mcp|enfdev)_)[A-Za-z0-9_-]{8,}`, "${1}"+redactedValue, nil, "bcn_"), // Beacon's own keys+ rule(`\b(sk-)[A-Za-z0-9_-]{20,}`, "${1}"+redactedValue, nil, "sk-"), // Anthropic sk-ant-, OpenAI sk-proj- and sk-+ // An AWS secret access key has no shape of its own, but where it follows its key id within a few+ // separators (a credentials CSV, `aws configure` output, a table, a JSON array) it is the 40+ // characters after them. This runs before the key id rule below replaces the id it keys on.+ rule(`(\b(?:AKIA|ASIA)[A-Z0-9]{16}\b[\s,:|"']{1,8})[A-Za-z0-9/+]{40}([^A-Za-z0-9/+=]|$)`, "${1}"+redactedValue+"${2}", nil, "AKIA", "ASIA"),+ rule(`\b(AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}\b`, "${1}"+redactedValue, nil, "AKIA", "ASIA", "ABIA", "ACCA"), // AWS access key id+ rule(`\b(gh[pousr]_)[A-Za-z0-9]{30,}`, "${1}"+redactedValue, nil, "ghp_", "gho_", "ghu_", "ghs_", "ghr_"), // GitHub tokens+ rule(`\b(github_pat_)[A-Za-z0-9_]{22,}`, "${1}"+redactedValue, nil, "github_pat_"), // GitHub fine-grained tokens+ rule(`\b(glpat-)[A-Za-z0-9_-]{20,}`, "${1}"+redactedValue, nil, "glpat-"), // GitLab+ rule(`\b(xox[abposr]-)[A-Za-z0-9-]{10,}`, "${1}"+redactedValue, nil, "xox"), // Slack+ rule(`\b([rs]k_(?:live|test)_)[A-Za-z0-9]{16,}`, "${1}"+redactedValue, nil, "k_live_", "k_test_"), // Stripe+ rule(`\b(AIza)[0-9A-Za-z_-]{35}`, "${1}"+redactedValue, nil, "AIza"), // Google API key+ rule(`\b(npm_)[A-Za-z0-9]{36}`, "${1}"+redactedValue, nil, "npm_"), // npm+ rule(`\b(hf_)[A-Za-z0-9]{30,}`, "${1}"+redactedValue, nil, "hf_"), // Hugging Face+ // Beacon's own keys and tokens: API keys, device and enforcement keys, MCP tokens and their refresh+ // tokens, and the CLI sign-in's access token, authorization code, client and exchange values.+ rule(`\b(bcn_(?:api|device|mcprt|mcp|enfdev|cli|code|client|exchange)_)[A-Za-z0-9_-]{8,}`, "${1}"+redactedValue, nil, "bcn_"),rule(`\b(eyJ)[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}`, "${1}"+redactedValue, nil, "eyJ"), // JWT})diff --git a/pkg/asymptoteobserve/privacy_gate_test.go b/pkg/asymptoteobserve/privacy_gate_test.goindex 3f924f57..e033fa5c 100644--- a/pkg/asymptoteobserve/privacy_gate_test.go+++ b/pkg/asymptoteobserve/privacy_gate_test.go@@ -18,6 +18,8 @@ var redactGateFragments = []string{"hunter2hunter2", "null", "true", "42", "https://", "postgres://user:", "pw", "@host", "://","sk-", "sk-ant-api03-", "AKIA", "ASIA", "ABCDEFGHIJKLMNOP", "ghp_", "gho_", "ghs_", "github_pat_","glpat-", "xoxb-", "sk_live_", "rk_test_", "AIza", "npm_", "hf_", "bcn_api_", "bcn_device_",+ "bcn_cli_", "bcn_mcprt_", "bcn_code_", "bcn_client_", "bcn_exchange_", "bcn_mcp_", "bcn_enfdev_", "bcn_other_",+ "AKIAIOSFODNN7EXAMPLE", "ASIAIOSFODNN7EXAMPLE", "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", "|", "/", "+","0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJ", "-----BEGIN RSA PRIVATE KEY-----","-----BEGIN PRIVATE KEY-----", "-----END RSA PRIVATE KEY-----", "MIIEvQIBADANBgkqhkiG9w0BAQEFAASC","Proc-Type: 4,ENCRYPTED", "\\n", "[REDACTED]", "ſecret", "toKen", "Key", "İ", "ß", "é", "日本",diff --git a/pkg/asymptoteobserve/privacy_test.go b/pkg/asymptoteobserve/privacy_test.goindex 73808df7..64457a92 100644--- a/pkg/asymptoteobserve/privacy_test.go+++ b/pkg/asymptoteobserve/privacy_test.go@@ -141,6 +141,13 @@ func TestRedactStringRedactsCommonCredentialFormats(t *testing.T) {{"jwt", "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U", "dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U"},{"beacon device key", "bcn_device_abcdefgh_0123456789abcdef", "0123456789abcdef"},{"beacon machine credential", "bcn_enfdev_abcdefgh_0123456789abcdef", "0123456789abcdef"},+ {"beacon cli token", "Authorization header was bcn_cli_Zx9Qw8Er7Ty6Ui5Op4As3Df2 earlier", "Zx9Qw8Er7Ty6Ui5Op4As3Df2"},+ {"beacon mcp refresh token", "refresh with bcn_mcprt_Lk2Jh3Gf4Ds5Aq6Ws7Ed8Rf9", "Lk2Jh3Gf4Ds5Aq6Ws7Ed8Rf9"},+ {"beacon mcp token", "bcn_mcp_Pq1Wo2Ei3Ru4Ty5Yt6Ur7Ie8", "Pq1Wo2Ei3Ru4Ty5Yt6Ur7Ie8"},+ {"beacon authorization code", "callback ?code=x&c=bcn_code_Mn1Bv2Cx3Zl4Kj5Hg6Fd7", "Mn1Bv2Cx3Zl4Kj5Hg6Fd7"},+ {"aws credentials csv", "Access key ID,Secret access key\nAKIAIOSFODNN7EXAMPLE,wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY\n", "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"},+ {"aws key pair", "use AKIAIOSFODNN7EXAMPLE wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY for the bucket", "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"},+ {"aws key pair ending in a slash", `["ASIAIOSFODNN7EXAMPLE", "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKE/"]`, "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKE/"},{"rsa key", "-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEAsecretbody\n-----END RSA PRIVATE KEY-----", "MIIEowIBAAKCAQEAsecretbody"},{"openssh key cut short", "cat ~/.ssh/id_ed25519\n-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEAAAAA", "b3BlbnNzaC1rZXktdjEAAAAA"},}@@ -153,6 +160,22 @@ func TestRedactStringRedactsCommonCredentialFormats(t *testing.T) {}}+// An AWS secret key is recognized only next to its key id, keeps the separators around it, and a+// longer run of key characters there is not taken for one.+func TestRedactStringRedactsAnAWSSecretBesideItsKeyID(t *testing.T) {+ for input, want := range map[string]string{+ "AKIAIOSFODNN7EXAMPLE,wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY\n": "AKIA[REDACTED],[REDACTED]\n",+ "| AKIAIOSFODNN7EXAMPLE | wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY |": "| AKIA[REDACTED] | [REDACTED] |",+ "ASIAIOSFODNN7EXAMPLE wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY": "ASIA[REDACTED] [REDACTED]",+ "AKIAIOSFODNN7EXAMPLE wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEYplus": "AKIA[REDACTED] wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEYplus",+ "commit wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY has no key id beside it": "commit wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY has no key id beside it",+ } {+ if got := RedactString(input); got != want {+ t.Errorf("RedactString(%q) = %q, want %q", input, got, want)+ }+ }+}+// Redaction keeps the label and the structure around a value, and leaves text that only mentions// tokens alone: token counts are the most common numbers in this log.func TestRedactStringKeepsLabelsAndOrdinaryText(t *testing.T) {diff --git a/pkg/asymptoteobserve/share.go b/pkg/asymptoteobserve/share.goindex 1f48044b..2c111780 100644--- a/pkg/asymptoteobserve/share.go+++ b/pkg/asymptoteobserve/share.go@@ -192,6 +192,11 @@ type ShareOptions struct {BeaconVersion string// GeneratedAt is the provenance timestamp; zero means now.GeneratedAt time.Time+ // MetadataOnly removes from every event what Metadata-only forwarding removes (StripToMetadata):+ // prompts, answers, reasoning, tool arguments and results, command output, diffs, raw payloads+ // and reasons. Event ids are derived before, so a trace shared in either mode names its events+ // the same way.+ MetadataOnly bool}// ShareEventsAfter is what a re-share or refresh uploads of a bundle's events, given the last event@@ -284,8 +289,9 @@ func ShareEventID(event Event) string {// session's directory becomes ".", the home directory "~" -- in every field the projection reads:// the message, prompt text, retained assistant output, command line and output, file path and diff,// tool command, path, arguments and result, MCP fields, approval and policy reasons, error, the-// working directory and the repository. Events ShareProjects rejects are left out. The rest are-// ordered by timestamp, then with tool invocations ahead of everything else at one instant (a+// working directory and the repository. With MetadataOnly, every event is then cut down to what+// Metadata-only forwarding keeps (StripToMetadata). Events ShareProjects rejects are left out. The+// rest are ordered by timestamp, then with tool invocations ahead of everything else at one instant (a// pre-tool and a post-tool hook can share a timestamp), then by ID; events that cannot be timed keep// their input order after every timed one. An event that appears twice (the same ID) is carried// once. Each event's ID is ShareEventID, so re-sharing upserts rather than duplicates.@@ -328,6 +334,10 @@ func BuildShareBundle(events []Event, opts ShareOptions) TraceBundleV1 {id := ShareEventID(clone)event := scrub.event(SanitizeEvent(clone, 1<<30))NormalizeTraceEvent(&event)+ if opts.MetadataOnly {+ // After the id and after normalizing, which names a metric datapoint from its message.+ StripToMetadata(&event)+ }te := TraceEventFromEvent(event, id, 0)if te.Tool != nil && te.Tool.Arguments == nil {// A hook keeps the tool's input in raw when the runtime gave it no gen_ai call.