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 the traces:write scope and the shared-trace API client
Claude515a1f58d537
diff --git a/CLAUDE.md b/CLAUDE.mdindex 6e9afc92..deddc554 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -26,7 +26,7 @@ Do not recreate or depend on removed `asymptote` mirror trees. Keep new work foc- 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 default. The public Beacon build must not require a hosted account, remote policy fetch, hosted dashboard, or external network dependency during normal hook execution, and hooks themselves never touch the network.-- `beacon login` is the account-identity channel for interactive users and is required by the interactive `beacon endpoint install` wizard. It uses browser PKCE against beacon.sh and stores the scoped CLI token only in `~/.beacon/auth/session.json` (0600 under a 0700 directory). Signing in alone never starts forwarding. User-mode `beacon endpoint connect` may send that token once to `POST /api/cli/enroll/account` to authorize minting a separate device ingest key, and `beacon mcp token create` may send it to `POST /api/cli/mcp/tokens` (scope `mcp:token:create`, listed on the sign-in page) to mint a personal MCP token that is printed once to stdout and never written to a file; never copy the account token into endpoint config, Vector, hook environments, logs, or command output. System/root/package/MDM/CI/piped-stdin/dry-run installs stay noninteractive and account-free.+- `beacon login` is the account-identity channel for interactive users and is required by the interactive `beacon endpoint install` wizard. It uses browser PKCE against beacon.sh and stores the scoped CLI token only in `~/.beacon/auth/session.json` (0600 under a 0700 directory). Signing in alone never starts forwarding. User-mode `beacon endpoint connect` may send that token once to `POST /api/cli/enroll/account` to authorize minting a separate device ingest key, and `beacon mcp token create` may send it to `POST /api/cli/mcp/tokens` (scope `mcp:token:create`, listed on the sign-in page) to mint a personal MCP token that is printed once to stdout and never written to a file, and `beacon share` may send it (scope `traces:write`, also on the sign-in page) to `PUT /v1/traces/{external_id}`, `POST /v1/traces/{external_id}/messages/batch` and `GET /v1/traces/{external_id}` on the session's own base URL to upload a shared trace the person chose to publish (`cli/beacon/internal/account/share.go`; a `bcn_api_` API key from `--key` or `BEACON_API_KEY` may stand in for it, precedence `--key`, then a current sign-in carrying the scope, then the environment). These are explicit, user-initiated requests with redirects refused; hooks, plugins and background jobs never make them. Never copy the account token into endpoint config, Vector, hook environments, logs, or command output. System/root/package/MDM/CI/piped-stdin/dry-run installs stay noninteractive and account-free.- Beacon Cloud forwarding (`cli/beacon/internal/endpoint/asymptote`, `beacon endpoint connect`, `beacon endpoint asymptote`) is Vector-shaped: Beacon writes local JSONL, Vector ships runtime lines only from the connection point forward and reads inventory from the beginning to establish the endpoint's current baseline, plus the one bounded exception of the session backfill (below), and the `bcn_device_*` key stays only in `<BaseDir>/asymptote/vector-secrets.json` via Vector's secret backend. The onboarding wizard preselects Beacon Cloud, and confirming it connects this endpoint in the same command once the local install has succeeded; an endpoint that is already enrolled is never re-enrolled, because enrollment rotates the device key. Standard mode ships locally sanitized retained content; metadata-only uses local Vector transforms to remove prompts, responses, reasoning, tool arguments/results, command output, raw fields, diffs, inventory content, and MCP definitions before buffering/upload. Keep the ingest URL `https://`, the wire contract aligned with `beacon-ingest` (`/v1/ingest/{runtime,inventory}` and `/v1/ingest/health`), and do not add another endpoint network channel. The cloud-sandbox shuttle is the bounded exception: only with `BEACON_ORIGIN=cloud`, it can upload new runtime lines to GCS, S3, or the same Beacon ingest contract because no Vector/service manager/browser/persistent disk exists there.- Session backfill (`cli/beacon/cmd/endpoint_backfill.go`; docs in `docs/cli/endpoint-install.mdx#session-backfill` and `docs/cli/endpoint-connect.mdx#session-backfill`): after every successful install (user or system mode), every session-store collector runs once with `CollectOptions.Since` (30 days; `sessionwindow.Recent` keeps those sessions, newest first, and never touches the cursors of the rest) and a shared `writer.Budget` (24 MiB, at most 12 MiB per runtime through `Budget.Sub`; a refused append returns `writer.ErrBudgetSpent`, the collector stops with cursors past only what was written, and a manual sync reads the rest). A new session-store collector takes both fields and joins `endpointBackfillRunners`. Every connect, first or re-connect, user or system, runs the same sweep before enrollment (skipped when install just ran it) and, before the forwarder starts, `asymptote.StageBackfill` copies the window's `harness.collection_method=poll` lines into `cloud-backfill.jsonl` beside the runtime log, which the `beacon_backfill` Vector source (fingerprinted `device_and_inode`, so each atomically restaged copy is a new file) reads from the beginning into the runtime sink through the same privacy transform. Live hook/OTLP/plugin history before the connection point stays local. Re-connects restage, so a resend of already-shipped lines is expected and rests on the deterministic `event.id`; a privacy-mode change clears the checkpoints and the restage renames the new-mode copy over the old one (kept until then so the copy is always a new inode; deleted instead when nothing restages), and `disconnect` removes it. System mode runs the collectors under `withUserHome` for the active console user (`activeConsoleUser`), with cursors under the system base directory, and reports a skip when nobody is logged in. The wizard's confirm screen names the upload (`WizardOptions.BackfillDays`). Dry-run, `--no-backfill` and `BEACON_BACKFILL=0` skip all of it; the cmd tests run with `BEACON_BACKFILL=0` set in `TestMain`.- `beacon endpoint install` has a full-screen onboarding wizard on interactive user TTYs. It signs in, preselects Beacon Cloud, requires an explicit choice to opt out to Local, and asks Managed users to choose Standard or Metadata-only privacy. Signing in alone still moves no telemetry. Confirming Beacon Cloud does: the confirm screen states that it installs Beacon and starts forwarding, and names what the selected privacy mode sends, so that screen is the consent point. The managed destination is recorded only after enrollment succeeds, so a failed enrollment leaves a working local install, prints `beacon endpoint connect` as the retry, and re-offers the question on the next install. The onboarding record is written only after `lifecycle.Install` returns, because a profile written first left a failed install looking onboarded and silently skipped the wizard on the retry. Explicit `install --connect` is unchanged. The wizard is skipped for system/root/CI/piped-stdin/dry-run or `BEACON_ONBOARDING=0`; those unattended paths must never gain an account or browser dependency. Legacy `BEACON_ONBOARDING_EMAIL`/`USAGE` submissions remain only for fleet compatibility. After the destination, the wizard shows an agent tools screen; every row is preselected (opt-out, space toggles). Beacon Cloud MCP is offered only with Beacon Cloud and runs the `beacon mcp connect` flow (`connectCloudMCP` with `yes`, OAuth, detected harnesses) only after the endpoint is connected (or already was), via `finishCloudSetup`; a failed enrollment skips it and names the retry. The Beacon Agent Skills are offered for either destination and installed user-wide into `~/.agents/skills` and, when Claude Code is set up, `~/.claude/skills` (`cli/beacon/internal/agentskills`, `beacon skills install|uninstall`; a `.beacon-managed` marker decides what Beacon may replace or remove; install and repair refresh only copies Beacon already wrote). Both run after `lifecycle.Install` returns and warn rather than fail. The answers are recorded as `onboarding.cloud_mcp`/`agent_skills`. Implementation lives in `cli/beacon/internal/onboarding`, `cli/beacon/cmd/endpoint_onboarding.go`, `cli/beacon/cmd/endpoint_install.go` and `cli/beacon/cmd/agent_tools.go`; keep `docs/cli/endpoint-onboarding.mdx` and `docs/cli/skills.mdx` in sync.diff --git a/cli/beacon/internal/account/login.go b/cli/beacon/internal/account/login.goindex e9d2a7ce..5b4dcc18 100644--- a/cli/beacon/internal/account/login.go+++ b/cli/beacon/internal/account/login.go@@ -38,10 +38,13 @@ const (// tokens (`beacon mcp token create`). The sign-in page lists it, and beacon.sh// 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.+ ScopeTracesWrite = "traces:write")// LoginScopes are the permissions every `beacon login` asks for.-var LoginScopes = []string{ScopeProfileRead, ScopeDeviceEnroll, ScopeMCPTokenCreate}+var LoginScopes = []string{ScopeProfileRead, ScopeDeviceEnroll, ScopeMCPTokenCreate, ScopeTracesWrite}type LoginOptions struct {BaseURL stringdiff --git a/cli/beacon/internal/account/login_test.go b/cli/beacon/internal/account/login_test.goindex bcea318b..c90c1ee4 100644--- a/cli/beacon/internal/account/login_test.go+++ b/cli/beacon/internal/account/login_test.go@@ -137,7 +137,7 @@ func TestLoginUsesPKCEAndReturnsPrivateSession(t *testing.T) {t.Fatalf("client payload = %#v", client)}scopes := service.init["scopes"].([]any)- if len(scopes) != 3 || scopes[0] != ScopeProfileRead || scopes[1] != ScopeDeviceEnroll || scopes[2] != ScopeMCPTokenCreate {+ if len(scopes) != 4 || scopes[0] != ScopeProfileRead || scopes[1] != ScopeDeviceEnroll || scopes[2] != ScopeMCPTokenCreate || scopes[3] != ScopeTracesWrite {t.Fatalf("requested scopes = %#v", scopes)}if service.exchange["state"] != service.init["state"] || service.exchange["exchange_code"] != "code-123" || service.exchange["code_verifier"] == "" {diff --git a/cli/beacon/internal/account/share.go b/cli/beacon/internal/account/share.gonew file mode 100644index 00000000..129d1aef--- /dev/null+++ b/cli/beacon/internal/account/share.go@@ -0,0 +1,398 @@+package account++import (+ "bytes"+ "compress/gzip"+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "net/http"+ "net/url"+ "strings"+ "time"++ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"+)++// Shared traces: `beacon share` uploads one session's messages to beacon.sh with+// `PUT /v1/traces/{external_id}`, `POST /v1/traces/{external_id}/messages/batch` and reads its own+// trace back with `GET /v1/traces/{external_id}`. These are explicit, user-initiated requests; no+// hook or background job ever makes them.+//+// 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.++const (+ // TracesPath is the prefix of the shared-trace write API.+ TracesPath = "/v1/traces/"+ // APIKeyEnv names the environment variable an API key is read from when there is no --key and no+ // usable sign-in.+ APIKeyEnv = "BEACON_API_KEY"+ // APIKeyPrefix starts every Beacon API key.+ APIKeyPrefix = "bcn_api_"++ // ShareMaxBatchBytes bounds one batch body before compression. beacon.sh accepts 8 MiB; the+ // margin covers the batch envelope and JSON escaping differences.+ ShareMaxBatchBytes = 6 << 20+ // shareMaxResponseBytes bounds what is read of any response.+ shareMaxResponseBytes = 1 << 20+)++// Where a share credential came from.+const (+ CredentialSourceFlag = "flag"+ CredentialSourceLogin = "login"+ CredentialSourceEnv = "env"+)++// ErrTracesWriteScope means the signed-in session cannot share traces: it was issued before+// `beacon login` asked for ScopeTracesWrite, or beacon.sh refused that scope.+var ErrTracesWriteScope = errors.New("this Beacon sign-in cannot share traces: run `beacon login` again")++// ErrNoShareCredential means there is neither an API key nor a sign-in to share with.+var ErrNoShareCredential = errors.New("not signed in to Beacon: run `beacon login`, or pass an API key with --key or " + APIKeyEnv)++// ShareCredential is the bearer credential a ShareClient sends and the base URL it belongs to.+// Token is never printed or logged; String hides it.+type ShareCredential struct {+ BaseURL string+ Token string+ // Source is CredentialSourceFlag, CredentialSourceLogin or CredentialSourceEnv.+ Source string+ // User is the signed-in user for a login credential; empty for an API key.+ User User+}++// String describes the credential without its secret.+func (c ShareCredential) String() string {+ switch c.Source {+ case CredentialSourceLogin:+ return "Beacon sign-in " + c.User.Email+ case CredentialSourceFlag:+ return "API key from --key"+ case CredentialSourceEnv:+ return "API key from " + APIKeyEnv+ }+ return "credential"+}++// GoString keeps %#v from printing the token.+func (c ShareCredential) GoString() string { return "account.ShareCredential{" + c.String() + "}" }++// ResolveShareCredentialOptions are the inputs ResolveShareCredential chooses between.+type ResolveShareCredentialOptions struct {+ // Key is the --key flag.+ Key string+ // BaseURL is the --base-url flag; an API key is sent to ResolveBaseURL(BaseURL).+ BaseURL string+ // Load reads the stored sign-in; nil means Load.+ Load func() (*Session, error)+ // Getenv reads the environment; nil means no environment.+ Getenv func(string) string+ Now time.Time+}++// ResolveShareCredential picks the credential to share with: --key first, then a stored sign-in that+// is current and carries ScopeTracesWrite, then BEACON_API_KEY. When none is usable the error says+// why the sign-in could not be used, since that is what most people have.+func ResolveShareCredential(opts ResolveShareCredentialOptions) (ShareCredential, error) {+ if opts.Now.IsZero() {+ opts.Now = time.Now()+ }+ if key := strings.TrimSpace(opts.Key); key != "" {+ return apiKeyCredential(key, opts.BaseURL, CredentialSourceFlag, "--key")+ }+ load := opts.Load+ if load == nil {+ load = Load+ }+ session, loadErr := load()+ var loginErr error+ switch {+ case errors.Is(loadErr, ErrNotSignedIn):+ loginErr = ErrNoShareCredential+ case loadErr != nil:+ loginErr = loadErr+ case session.Expired(opts.Now):+ loginErr = errors.New("Beacon sign-in expired: run `beacon login` again")+ case !hasScope(session.Scopes, ScopeTracesWrite):+ loginErr = ErrTracesWriteScope+ default:+ return ShareCredential{BaseURL: strings.TrimRight(session.BaseURL, "/"), Token: session.AccessToken, Source: CredentialSourceLogin, User: session.User}, nil+ }+ if opts.Getenv != nil {+ if key := strings.TrimSpace(opts.Getenv(APIKeyEnv)); key != "" {+ return apiKeyCredential(key, opts.BaseURL, CredentialSourceEnv, APIKeyEnv)+ }+ }+ return ShareCredential{}, loginErr+}++func apiKeyCredential(key, baseURL, source, origin string) (ShareCredential, error) {+ if !strings.HasPrefix(key, APIKeyPrefix) || len(key) == len(APIKeyPrefix) || strings.ContainsAny(key, " \t\r\n") {+ // The value is deliberately not echoed: it may be a secret pasted into the wrong flag.+ return ShareCredential{}, fmt.Errorf("%s is not a Beacon API key (they start with %s)", origin, APIKeyPrefix)+ }+ return ShareCredential{BaseURL: ResolveBaseURL(baseURL), Token: key, Source: source}, nil+}++// ShareClient talks to the shared-trace write API.+type ShareClient struct {+ cred ShareCredential+ http *http.Client+}++// NewShareClient checks the credential and its base URL 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")+ }+ if strings.TrimSpace(cred.Token) == "" {+ return nil, ErrNoShareCredential+ }+ if client == nil {+ client = &http.Client{Timeout: defaultTimeout}+ }+ // A redirect would resend the credential somewhere else.+ clientCopy := *client+ clientCopy.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }+ return &ShareClient{cred: cred, http: &clientCopy}, nil+}++// BaseURL is the service the client sends to.+func (c *ShareClient) BaseURL() string { return c.cred.BaseURL }++// PutTrace creates or updates a trace's metadata.+func (c *ShareClient) PutTrace(ctx context.Context, externalID string, trace asymptoteobserve.ShareTraceV1) (*asymptoteobserve.ShareTraceResultV1, error) {+ if trace.SchemaVersion == "" {+ trace.SchemaVersion = asymptoteobserve.ShareSchemaVersion+ }+ if strings.TrimSpace(trace.AgentID) == "" {+ return nil, errors.New("a shared trace needs an agent id")+ }+ if trace.Visibility != "" && !asymptoteobserve.ValidShareVisibility(trace.Visibility) {+ return nil, fmt.Errorf("unknown visibility %q", trace.Visibility)+ }+ body, err := json.Marshal(trace)+ if err != nil {+ return nil, err+ }+ payload, status, err := c.do(ctx, http.MethodPut, externalID, "", body, false)+ if err != nil {+ return nil, err+ }+ if err := c.statusError("share trace", status, payload); err != nil {+ return nil, err+ }+ var result asymptoteobserve.ShareTraceResultV1+ if err := json.Unmarshal(payload, &result); err != nil {+ return nil, fmt.Errorf("parse share response: %w", err)+ }+ if result.ID == "" {+ return nil, errors.New("share response did not include a trace id")+ }+ return &result, nil+}++// PutMessagesResult sums the batches PutMessages sent.+type PutMessagesResult struct {+ Batches int `json:"batches"`+ Accepted int `json:"accepted"`+ // MessageCount is the trace's total after the last batch, as beacon.sh reported it.+ MessageCount int `json:"message_count"`+}++// PutMessages upserts messages in batches of at most ShareMaxMessagesPerBatch messages and+// ShareMaxBatchBytes bytes, each gzip-compressed. Re-sending a message is idempotent, so a failed+// run can simply be repeated. An empty list sends nothing.+func (c *ShareClient) PutMessages(ctx context.Context, externalID string, messages []asymptoteobserve.ShareMessageV1) (PutMessagesResult, error) {+ var result PutMessagesResult+ batches, err := ShareBatches(messages, asymptoteobserve.ShareMaxMessagesPerBatch, ShareMaxBatchBytes)+ if err != nil {+ return result, err+ }+ for _, batch := range batches {+ payload, status, err := c.do(ctx, http.MethodPost, externalID, "/messages/batch", batch.Body, true)+ if err != nil {+ return result, err+ }+ if err := c.statusError("upload messages", status, payload); err != nil {+ return result, err+ }+ var accepted asymptoteobserve.ShareBatchResultV1+ if err := json.Unmarshal(payload, &accepted); err != nil {+ return result, fmt.Errorf("parse batch response: %w", err)+ }+ result.Batches+++ result.Accepted += accepted.Accepted+ result.MessageCount = accepted.MessageCount+ }+ return result, nil+}++// GetTrace reads the owner's view of a trace. found is false when beacon.sh has no such trace for+// this credential.+func (c *ShareClient) GetTrace(ctx context.Context, externalID string) (*asymptoteobserve.ShareTraceStateV1, bool, error) {+ payload, status, err := c.do(ctx, http.MethodGet, externalID, "", nil, false)+ if err != nil {+ return nil, false, err+ }+ if status == http.StatusNotFound {+ return nil, false, nil+ }+ if err := c.statusError("read shared trace", status, payload); err != nil {+ return nil, false, err+ }+ var state asymptoteobserve.ShareTraceStateV1+ if err := json.Unmarshal(payload, &state); err != nil {+ return nil, false, fmt.Errorf("parse shared trace: %w", err)+ }+ return &state, true, nil+}++// ShareBatch is one batch request body and how many messages it carries.+type ShareBatch struct {+ Body []byte+ Messages int+}++// ShareBatches splits messages into batch bodies of at most maxMessages messages and maxBytes+// bytes. A single message larger than maxBytes is refused rather than sent to be rejected.+func ShareBatches(messages []asymptoteobserve.ShareMessageV1, maxMessages, maxBytes int) ([]ShareBatch, error) {+ const envelope = len(`{"messages":[]}`)+ var batches []ShareBatch+ var current [][]byte+ size := envelope+ flush := func() {+ if len(current) == 0 {+ return+ }+ body := make([]byte, 0, size)+ body = append(body, `{"messages":[`...)+ for i, m := range current {+ if i > 0 {+ body = append(body, ',')+ }+ body = append(body, m...)+ }+ body = append(body, `]}`...)+ batches = append(batches, ShareBatch{Body: body, Messages: len(current)})+ current, size = nil, envelope+ }+ for _, message := range messages {+ encoded, err := json.Marshal(message)+ if err != nil {+ return nil, err+ }+ if envelope+len(encoded) > maxBytes {+ return nil, fmt.Errorf("message %s is %d bytes, more than one batch may carry", message.ID, len(encoded))+ }+ extra := len(encoded)+ if len(current) > 0 {+ extra++ // the comma+ }+ if len(current) >= maxMessages || size+extra > maxBytes {+ flush()+ extra = len(encoded)+ }+ current = append(current, encoded)+ size += extra+ }+ flush()+ return batches, nil+}++func (c *ShareClient) do(ctx context.Context, method, externalID, suffix string, body []byte, compress bool) ([]byte, int, error) {+ if !asymptoteobserve.ValidShareExternalID(externalID) {+ return nil, 0, fmt.Errorf("invalid external id %q", externalID)+ }+ target := c.cred.BaseURL + TracesPath + url.PathEscape(externalID) + suffix+ var reader io.Reader+ encoding := ""+ if body != nil {+ if compress {+ var buf bytes.Buffer+ zw := gzip.NewWriter(&buf)+ if _, err := zw.Write(body); err != nil {+ return nil, 0, err+ }+ if err := zw.Close(); err != nil {+ return nil, 0, err+ }+ reader = &buf+ encoding = "gzip"+ } else {+ reader = bytes.NewReader(body)+ }+ }+ req, err := http.NewRequestWithContext(ctx, method, target, reader)+ if err != nil {+ return nil, 0, err+ }+ req.Header.Set("Authorization", "Bearer "+c.cred.Token)+ req.Header.Set("Accept", "application/json")+ req.Header.Set("User-Agent", CLIClientName)+ if body != nil {+ req.Header.Set("Content-Type", "application/json")+ }+ if encoding != "" {+ req.Header.Set("Content-Encoding", encoding)+ }+ resp, err := c.http.Do(req)+ if err != nil {+ return nil, 0, fmt.Errorf("%s %s: %w", method, c.cred.BaseURL+TracesPath+"…", scrubURLError(err))+ }+ defer resp.Body.Close()+ payload, err := io.ReadAll(io.LimitReader(resp.Body, shareMaxResponseBytes))+ if err != nil {+ 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 payload, resp.StatusCode, nil+}++// scrubURLError drops the request URL a *url.Error carries; the cause is what matters, and the URL+// is already in the message.+func scrubURLError(err error) error {+ var urlErr *url.Error+ if errors.As(err, &urlErr) {+ return urlErr.Err+ }+ return err+}++func (c *ShareClient) statusError(what string, status int, payload []byte) error {+ if status >= 200 && status <= 299 {+ return nil+ }+ var failure struct {+ Detail string `json:"detail"`+ Error string `json:"error"`+ }+ _ = json.Unmarshal(payload, &failure)+ detail := firstNonEmpty(failure.Detail, failure.Error, fmt.Sprintf("HTTP %d", status))+ detail = strings.ReplaceAll(detail, c.cred.Token, "[REDACTED]")+ switch status {+ case http.StatusUnauthorized:+ if c.cred.Source == CredentialSourceLogin {+ return fmt.Errorf("Beacon rejected the sign-in (%s): run `beacon login` again", detail)+ }+ return fmt.Errorf("Beacon rejected the %s (%s)", c.cred, detail)+ case http.StatusForbidden:+ if c.cred.Source == CredentialSourceLogin {+ return ErrTracesWriteScope+ }+ 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)+ 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)+}diff --git a/cli/beacon/internal/account/share_test.go b/cli/beacon/internal/account/share_test.gonew file mode 100644index 00000000..6b125647--- /dev/null+++ b/cli/beacon/internal/account/share_test.go@@ -0,0 +1,300 @@+package account++import (+ "compress/gzip"+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync"+ "testing"+ "time"++ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"+)++const shareTestToken = "bcn_cli_share_secret"++func shareCred(baseURL string) ShareCredential {+ return ShareCredential{BaseURL: baseURL, Token: shareTestToken, Source: CredentialSourceLogin, User: User{ID: "u", Email: "[email protected]"}}+}++func TestResolveShareCredentialPrecedence(t *testing.T) {+ now := time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC)+ good := &Session{BaseURL: "https://beacon.sh", AccessToken: "bcn_cli_x", Scopes: []string{ScopeTracesWrite}, User: User{ID: "u", Email: "e@x"}, ExpiresAt: now.Add(time.Hour)}+ stale := &Session{BaseURL: "https://beacon.sh", AccessToken: "bcn_cli_x", Scopes: []string{ScopeProfileRead}, User: User{ID: "u", Email: "e@x"}}+ expired := &Session{BaseURL: "https://beacon.sh", AccessToken: "bcn_cli_x", Scopes: []string{ScopeTracesWrite}, User: User{ID: "u", Email: "e@x"}, ExpiresAt: now.Add(-time.Hour)}+ load := func(s *Session, err error) func() (*Session, error) {+ return func() (*Session, error) { return s, err }+ }+ env := func(value string) func(string) string {+ return func(name string) string {+ if name == APIKeyEnv {+ return value+ }+ return ""+ }+ }+ cases := []struct {+ name string+ opts ResolveShareCredentialOptions+ wantSource string+ wantErr error+ errText string+ }{+ {"flag beats login", ResolveShareCredentialOptions{Key: "bcn_api_flag", Load: load(good, nil), Getenv: env("bcn_api_env")}, CredentialSourceFlag, nil, ""},+ {"login beats env", ResolveShareCredentialOptions{Load: load(good, nil), Getenv: env("bcn_api_env")}, CredentialSourceLogin, nil, ""},+ {"env when signed out", ResolveShareCredentialOptions{Load: load(nil, ErrNotSignedIn), Getenv: env("bcn_api_env")}, CredentialSourceEnv, nil, ""},+ {"env when the login lacks the scope", ResolveShareCredentialOptions{Load: load(stale, nil), Getenv: env("bcn_api_env")}, CredentialSourceEnv, nil, ""},+ {"older login without env", ResolveShareCredentialOptions{Load: load(stale, nil), Getenv: env("")}, "", ErrTracesWriteScope, ""},+ {"expired login", ResolveShareCredentialOptions{Load: load(expired, nil)}, "", nil, "expired"},+ {"nothing", ResolveShareCredentialOptions{Load: load(nil, ErrNotSignedIn)}, "", ErrNoShareCredential, ""},+ {"bad key", ResolveShareCredentialOptions{Key: "sk-something", Load: load(good, nil)}, "", nil, "not a Beacon API key"},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ tc.opts.Now = now+ cred, err := ResolveShareCredential(tc.opts)+ switch {+ case tc.wantErr != nil:+ if !errors.Is(err, tc.wantErr) {+ t.Fatalf("err = %v, want %v", err, tc.wantErr)+ }+ return+ case tc.errText != "":+ if err == nil || !strings.Contains(err.Error(), tc.errText) {+ t.Fatalf("err = %v, want %q", err, tc.errText)+ }+ if strings.Contains(err.Error(), "sk-something") {+ t.Fatalf("the rejected key was echoed: %v", err)+ }+ return+ case err != nil:+ t.Fatalf("err = %v", err)+ }+ if cred.Source != tc.wantSource {+ t.Fatalf("source = %q, want %q", cred.Source, tc.wantSource)+ }+ if strings.Contains(fmt.Sprintf("%v %+v %#v %s", cred, cred, cred, cred), cred.Token) {+ t.Fatal("formatting a credential prints its token")+ }+ })+ }+}++func TestShareClientRefusesInsecureURL(t *testing.T) {+ if _, err := NewShareClient(ShareCredential{BaseURL: "http://beacon.example.com", Token: "x"}, nil); err == nil {+ t.Fatal("expected an error for a non-loopback http URL")+ }+}++type shareServer struct {+ mu sync.Mutex+ server *httptest.Server+ auth []string+ batches [][]asymptoteobserve.ShareMessageV1+ encoding []string+ trace *asymptoteobserve.ShareTraceV1+ paths []string+}++func newShareServer(t *testing.T) *shareServer {+ s := &shareServer{}+ s.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ s.mu.Lock()+ defer s.mu.Unlock()+ s.auth = append(s.auth, r.Header.Get("Authorization"))+ s.paths = append(s.paths, r.Method+" "+r.URL.EscapedPath())+ switch {+ case r.Method == http.MethodPut && r.URL.Path == "/v1/traces/claude_code:abc":+ var trace asymptoteobserve.ShareTraceV1+ if err := json.NewDecoder(r.Body).Decode(&trace); err != nil {+ http.Error(w, err.Error(), 400)+ return+ }+ s.trace = &trace+ w.WriteHeader(http.StatusCreated)+ fmt.Fprint(w, `{"id":"k3x","external_id":"claude_code:abc","url":"https://beacon.sh/s/k3x","visibility":"direct","message_count":0,"created":true}`)+ case r.Method == http.MethodPost && r.URL.Path == "/v1/traces/claude_code:abc/messages/batch":+ s.encoding = append(s.encoding, r.Header.Get("Content-Encoding"))+ var body io.Reader = r.Body+ if r.Header.Get("Content-Encoding") == "gzip" {+ zr, err := gzip.NewReader(r.Body)+ if err != nil {+ http.Error(w, err.Error(), 400)+ return+ }+ body = zr+ }+ var batch asymptoteobserve.ShareMessagesBatchV1+ if err := json.NewDecoder(body).Decode(&batch); err != nil {+ http.Error(w, err.Error(), 400)+ return+ }+ s.batches = append(s.batches, batch.Messages)+ total := 0+ for _, b := range s.batches {+ total += len(b)+ }+ fmt.Fprintf(w, `{"accepted":%d,"message_count":%d}`, len(batch.Messages), total)+ case r.Method == http.MethodGet && r.URL.Path == "/v1/traces/claude_code:abc":+ fmt.Fprint(w, `{"id":"k3x","url":"https://beacon.sh/s/k3x","visibility":"direct","message_count":2,"last_message_id":"m2","max_order":2}`)+ default:+ http.Error(w, `{"detail":"no such trace"}`, http.StatusNotFound)+ }+ }))+ t.Cleanup(s.server.Close)+ return s+}++func messagesN(n int, textBytes int) []asymptoteobserve.ShareMessageV1 {+ out := make([]asymptoteobserve.ShareMessageV1, n)+ for i := range out {+ out[i] = asymptoteobserve.ShareMessageV1{+ ID: fmt.Sprintf("m%d", i+1), Order: i + 1, Role: "user", Timestamp: "2026-10-01T00:00:00Z",+ Text: strings.Repeat("x", textBytes),+ Parts: []asymptoteobserve.SharePartV1{{Type: "text", Order: 1, Content: asymptoteobserve.ShareTextContent{Text: "x"}}},+ }+ }+ return out+}++func TestShareClientPutGetAndBatches(t *testing.T) {+ s := newShareServer(t)+ client, err := NewShareClient(shareCred(s.server.URL), s.server.Client())+ if err != nil {+ t.Fatal(err)+ }+ ctx := context.Background()+ result, err := client.PutTrace(ctx, "claude_code:abc", asymptoteobserve.ShareTraceV1{AgentID: "claude_code", Visibility: "direct"})+ if err != nil {+ t.Fatalf("PutTrace: %v", err)+ }+ if result.ID != "k3x" || !result.Created || s.trace.SchemaVersion != asymptoteobserve.ShareSchemaVersion {+ t.Fatalf("result = %+v trace = %+v", result, s.trace)+ }++ put, err := client.PutMessages(ctx, "claude_code:abc", messagesN(2500, 10))+ if err != nil {+ t.Fatalf("PutMessages: %v", err)+ }+ if put.Batches != 3 || put.Accepted != 2500 || put.MessageCount != 2500 {+ t.Fatalf("put = %+v", put)+ }+ if len(s.batches[0]) != 1000 || len(s.batches[2]) != 500 || s.batches[2][499].ID != "m2500" {+ t.Fatalf("batch sizes = %d %d %d", len(s.batches[0]), len(s.batches[1]), len(s.batches[2]))+ }+ for _, encoding := range s.encoding {+ if encoding != "gzip" {+ t.Fatalf("batch sent with Content-Encoding %q", encoding)+ }+ }++ state, found, err := client.GetTrace(ctx, "claude_code:abc")+ if err != nil || !found || state.LastMessageID != "m2" || state.MaxOrder != 2 {+ t.Fatalf("GetTrace = %+v %v %v", state, found, err)+ }+ if _, found, err := client.GetTrace(ctx, "claude_code:missing"); err != nil || found {+ t.Fatalf("missing trace: found=%v err=%v", found, err)+ }+ for _, auth := range s.auth {+ if auth != "Bearer "+shareTestToken {+ t.Fatalf("authorization = %q", auth)+ }+ }+ if _, err := client.PutMessages(ctx, "bad id!", messagesN(1, 1)); err == nil {+ t.Fatal("expected an invalid external id to be refused")+ }+}++func TestShareBatchesHonorTheByteLimit(t *testing.T) {+ batches, err := ShareBatches(messagesN(10, 1000), 1000, 3500)+ if err != nil {+ t.Fatal(err)+ }+ total := 0+ for _, b := range batches {+ if len(b.Body) > 3500 {+ t.Fatalf("batch of %d bytes exceeds the limit", len(b.Body))+ }+ var decoded asymptoteobserve.ShareMessagesBatchV1+ if err := json.Unmarshal(b.Body, &decoded); err != nil || len(decoded.Messages) != b.Messages {+ t.Fatalf("batch does not decode: %v", err)+ }+ total += b.Messages+ }+ if total != 10 || len(batches) < 4 {+ t.Fatalf("batches = %d, messages = %d", len(batches), total)+ }+ if _, err := ShareBatches(messagesN(1, 5000), 1000, 3500); err == nil {+ t.Fatal("expected an oversized message to be refused")+ }+ if batches, err := ShareBatches(nil, 1000, 3500); err != nil || len(batches) != 0 {+ t.Fatalf("empty input = %v %v", batches, err)+ }+}++func TestShareClientRefusesRedirects(t *testing.T) {+ var followed bool+ target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { followed = true }))+ defer target.Close()+ redirect := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ http.Redirect(w, r, target.URL+r.URL.Path, http.StatusTemporaryRedirect)+ }))+ defer redirect.Close()+ client, err := NewShareClient(shareCred(redirect.URL), redirect.Client())+ if err != nil {+ t.Fatal(err)+ }+ _, err = client.PutTrace(context.Background(), "claude_code:abc", asymptoteobserve.ShareTraceV1{AgentID: "claude_code"})+ if err == nil || !strings.Contains(err.Error(), "redirect") {+ t.Fatalf("err = %v", err)+ }+ if followed {+ t.Fatal("the redirect was followed with the credential")+ }+}++func TestShareClientMapsAuthFailures(t *testing.T) {+ for _, tc := range []struct {+ status int+ source string+ want string+ is error+ }{+ {http.StatusUnauthorized, CredentialSourceLogin, "run `beacon login` again", nil},+ {http.StatusForbidden, CredentialSourceLogin, "", ErrTracesWriteScope},+ {http.StatusUnauthorized, CredentialSourceFlag, "rejected the API key from --key", nil},+ {http.StatusForbidden, CredentialSourceEnv, "needs the traces:write scope", nil},+ } {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(tc.status)+ // A server echoing the credential back must not get it into the error.+ fmt.Fprintf(w, `{"detail":"bad token %s"}`, shareTestToken)+ }))+ cred := shareCred(server.URL)+ cred.Source = tc.source+ client, err := NewShareClient(cred, server.Client())+ if err != nil {+ t.Fatal(err)+ }+ _, err = client.PutTrace(context.Background(), "claude_code:abc", asymptoteobserve.ShareTraceV1{AgentID: "claude_code"})+ server.Close()+ if err == nil {+ t.Fatalf("%d/%s: expected an error", tc.status, tc.source)+ }+ if tc.is != nil && !errors.Is(err, tc.is) {+ t.Fatalf("%d/%s: err = %v, want %v", tc.status, tc.source, err, tc.is)+ }+ if tc.want != "" && !strings.Contains(err.Error(), tc.want) {+ t.Fatalf("%d/%s: err = %v, want %q", tc.status, tc.source, err, tc.want)+ }+ if strings.Contains(err.Error(), shareTestToken) {+ t.Fatalf("%d/%s: the token reached the error: %v", tc.status, tc.source, err)+ }+ }+}diff --git a/docs/cli/account-auth.mdx b/docs/cli/account-auth.mdxindex debe302e..8ab61b3d 100644--- a/docs/cli/account-auth.mdx+++ b/docs/cli/account-auth.mdx@@ -98,9 +98,10 @@ 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}/messages/batch` and `GET /v1/traces/{external_id}` create, fill and read back a shared trace for `beacon share`, with the access token (or a `bcn_api_` API key) as a Bearer credential. They require `traces:write`.- `POST /api/cli/auth/revoke` accepts the access token as a Bearer credential and revokes it.-`beacon login` requests `profile:read`, `device:enroll` and `mcp:token:create`. 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. A session from an older `beacon login` lacks `mcp:token:create`; run `beacon login` again to create MCP tokens from the CLI.+`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.For that enrollment, `beacon endpoint connect` sends the machine description to`POST /api/cli/enroll/account` with the CLI access token. The response uses the