Skip to content

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

Add beacon share --follow and document sharing from CI

Claude71af5abb7397
diff --git a/CLAUDE.md b/CLAUDE.md
index f881655d..dcce2146 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -70,7 +70,7 @@ Supported runtime surfaces today:
- Local threat detection via `beacon scan`, which runs the open Threat Rules format (`spec/threat-rules`; CEL match conditions over the endpoint event schema, with embedded conformance fixtures) over the runtime JSONL. The engine (`pkg/asymptoteobserve/threatrules`) ships in the binary; the rule corpus is external data loaded from a local store (`~/.beacon/endpoint/rules`) managed by `beacon rules`, so the corpus can grow without enlarging the binary. `scan` is read-only and offline; only the explicit, user-initiated `beacon rules pull <url>` reaches the network. A small frozen baseline is embedded so `scan` works before any rules are installed.
- Session handoff via `beacon handoff list|export|resume` (`cli/beacon/internal/handoff`, `cli/beacon/cmd/handoff*.go`; docs in `docs/cli/handoff.mdx` and `docs/concepts/session-handoff.mdx`). Every runtime is one entry in the registry in `cli/beacon/internal/handoff/runtimes.go`: its session source, the names it answers to, and the commands that reopen it or start it from a brief; `TestRegistryIsConsistent` checks the entries. Handoff reads the session stores of Claude Code, Codex CLI, OpenCode, Cline, Pi, Prime Agent, Factory Droid, GitHub Copilot CLI, Hermes Agent, DeepSeek Harness, fx, Grok Build, OpenClaw Gateway and Cursor read-only and never touches the network. Oh My Pi, Gemini CLI, Qwen Code, Kiro, Antigravity CLI, Devin CLI, Muse Code, OpenHands and goose have no store Beacon reads: their sessions come from the runtime log, and they take a brief as the target of `--agent`. `resume` reopens a session natively with its runtime's own command when it can, and otherwise writes a brief to `~/.beacon/endpoint/handoffs` (0700/0600) and starts a new session pointed at it. DeepSeek Harness cannot be started, and Hermes Agent and fx only reopen their own sessions, so their sessions continue in another runtime. fx, Grok Build and Cursor find a session by the directory they run in, so they are reopened natively only in the session's own directory. The brief is passed by absolute path, never inlined on a command line. Every launch keeps the runtime's approvals on: Beacon never passes a flag that turns them off, names the approval mode that asks where a CLI takes one (Cline always gets `--auto-approve false`, because Cline defaults to approving every tool call), and removes or overrides environment switches that would approve everything (`COPILOT_ALLOW_ALL`, `COPILOT_PLAN_THEN_AUTOPILOT`, `HERMES_YOLO_MODE`, `GOOSE_MODE`); `--print` shows them under `env`. Briefs run every event through `SanitizeEvent`, and quoted content goes in fences longer than any backtick run it contains, with inline fields reduced to one line, so quoted content cannot forge brief structure. A new session's first prompt ends with the `[beacon-handoff from=<harness> session=<id>]` marker (`pkg/asymptoteobserve/handoff.go`). The hook and plugin prompt paths and the session-store mappers record a `session.handoff` event with `handoff.{source_harness,source_session_id}` when they see it; that is an observed claim, not a verified identity.
- Session sharing via `beacon share` and `beacon share refresh` (`cli/beacon/cmd/share.go`; docs in `docs/cli/share.mdx`). It publishes one session the person names (or the most recent in a directory) to beacon.sh as a shared trace under the `beacon.share.v1` contract: the types, `ShareExternalID` (`<harness>:<session-id>`, or a sha256 form) and the event-to-message projection `BuildShareMessages` live in `pkg/asymptoteobserve/share.go`, and the client in `cli/beacon/internal/account/share.go`. Sessions resolve through the handoff registry (store first, then the runtime log). Every event goes through `SanitizeEvent` and session-directory/home paths are rewritten before projection; a tool invocation and its completion become a `tool_call` and a `tool_result` message sharing one callId, and a call reported twice is written once. `--print` shows the exact payload with no network, `public` needs confirmation (refused without a terminal unless `--yes`), and a re-share upserts by stable message id. After an upload it writes one `session.shared` event (`event.fidelity=inferred`, no collection method) carrying `shared_url`, `visibility`, `shared_at`/`last_refreshed_at` in raw, which the trace list reads as the sharing state; the projection skips that event. It never runs from hooks or in the background. With no selector (or `--current`) it shares the session it runs inside: `BEACON_SESSION_ID`/`BEACON_HARNESS` (the Claude Code SessionStart hook appends both as `export` lines to `$CLAUDE_ENV_FILE`, plain identifiers only), then the active-session record, then the directory's most recent session. The record is `pkg/asymptoteobserve/activesession` (`~/.beacon/endpoint/active-sessions.json`, 0600 under 0700, atomic and locked, at most 256 entries, 14-day prune, an unchanged entry rewritten at most once a minute), written by the hook logger after every endpoint event with a session id, working directory and harness; it holds identifiers and paths only, never content, and hooks write it silently and never touch the network for it. Hook tests point `BEACON_ACTIVE_SESSIONS_FILE` at a temp file in `TestMain`. Auto-share (`beacon share auto enable|disable|status`, `cli/beacon/cmd/share_auto.go`, settings in `pkg/asymptoteobserve/shareauto`) is server-side publishing: when it applies to a session's working directory, the hook logger writes ONE local `session.share_requested` event per session (`event.fidelity=inferred`, `share.visibility`; deduplicated under the active-session record's lock) and Beacon Cloud forwarding ships it; beacon.sh builds and refreshes the trace with the same `ShareExternalID`. Hooks never upload. The user file `~/.beacon/endpoint/share.json` (0600, CLI-written) holds the user-wide switch and per-project choices by path; a project marker `<repo>/.beacon/share.json` may disable on its own but enables only when the user's file trusts that project, with the user's visibility, so a cloned repository can never publish someone's sessions. `ForHook` costs one failed read when nothing is enabled. Hook tests point `BEACON_SHARE_SETTINGS_FILE` at a temp file. The share projection and `handoff.LogSessions` recency skip `session.share_requested`.
-- Commit-to-session links via `beacon git setup|status|remove|link|notes` (`cli/beacon/internal/gitlink`, `cli/beacon/cmd/git*.go`; docs in `docs/cli/git.mdx`). A link is a `beacon:<harness>/<session-id>` line in a git note under `refs/notes/beacon`; it carries identifiers only, never content, because notes can be pushed. Which sessions to link is inferred from the local runtime log: a session is linked when, between the parent commit and the commit (at least two hours, at most 24), it wrote a file the commit changes (for a merge, only files that differ from every parent, so a clean merge or pull links nothing). Evidence is file write events, write-type `file.operation`s, plainly readable shell targets, and `apply_patch` envelopes; reads never count. Note updates are a compare-and-swap on the notes ref through a private `refs/notes/beacon-tx/` working ref, and every existing note line, a teammate's or a person's, is kept verbatim. `setup` installs post-commit (links HEAD in the foreground with a 3 s budget, silent, never fails the commit, skips rebase/cherry-pick/revert) and post-rewrite (normalizes the note git concatenates on amend) as standalone `beacon-<hook>` scripts called from a marked block inserted after the shebang of the repository's own hook; only shell hooks are edited, `core.hooksPath` is refused without `--hooks-path`, and `notes.rewriteRef` carries links through amend and rebase. `BEACON_GIT_HOOKS=0` disables the hooks for one command. Every link a run adds is also written to the runtime log as one `session.commit_linked` event in the linked session's timeline (`event.fidelity=inferred`, no collection method), with commit id, branch and credential-stripped remote in the OTel-shaped `vcs` block and overlap counts in `vcs.attribution`; the event deliberately carries no file, command or tool fields so it can never become attribution evidence. Sharing is opt-in (`setup --share-notes`, off by default): a non-destructive fetch refspec `+refs/notes/beacon:refs/notes/beacon-remotes/<remote>` so git's own fetch brings teammates' links into a read-only tracking ref that `beacon git notes` unions with the local one (never force-fetch into `refs/notes/beacon`: it would destroy unpushed links), and a pre-push hook that fetches, merges with `cat_sort_uniq` through the same CAS, and pushes only the notes ref with `--no-verify`, within a 10 s budget and never failing the push. That pre-push hook is the only Beacon git hook that touches the network, and only during a push the person started; `beacon git notes push|fetch` do the same by hand. A note line may carry the session's share URL as its first trailing field (`beacon:<harness>/<id> <url>`; an identifier, not content): `gitlink.ValidShareURL` admits only https URLs on beacon.sh or the configured Beacon host (`AllowShareHost`, fed by `gitAllowShareHosts`), on write and on read, and `MergeNote`/`ParseNote` prefer the line with the URL over the bare one. Post-commit and `link` take URLs only from local `session.shared` events (`localShareURLs`). `setup --share-sessions [--share-visibility]` (implies `--share-notes`; stored as `beacon.shareSessions`/`beacon.shareVisibility` in local git config; public needs confirmation or `--yes`) makes the pre-push hook, which now receives git's stdin, share sessions linked to pushed commits that have no URL (at most 100 commits/10 sessions, inside the 10 s budget less 3 s kept for the notes push, silent without credentials, never failing the push) through `shareUpload` (`cmd/share_upload.go`: `alignShareSource` + `messagesAfter`), then write the URLs into the notes before pushing them.
+- Commit-to-session links via `beacon git setup|status|remove|link|notes` (`cli/beacon/internal/gitlink`, `cli/beacon/cmd/git*.go`; docs in `docs/cli/git.mdx`). A link is a `beacon:<harness>/<session-id>` line in a git note under `refs/notes/beacon`; it carries identifiers only, never content, because notes can be pushed. Which sessions to link is inferred from the local runtime log: a session is linked when, between the parent commit and the commit (at least two hours, at most 24), it wrote a file the commit changes (for a merge, only files that differ from every parent, so a clean merge or pull links nothing). Evidence is file write events, write-type `file.operation`s, plainly readable shell targets, and `apply_patch` envelopes; reads never count. Note updates are a compare-and-swap on the notes ref through a private `refs/notes/beacon-tx/` working ref, and every existing note line, a teammate's or a person's, is kept verbatim. `setup` installs post-commit (links HEAD in the foreground with a 3 s budget, silent, never fails the commit, skips rebase/cherry-pick/revert) and post-rewrite (normalizes the note git concatenates on amend) as standalone `beacon-<hook>` scripts called from a marked block inserted after the shebang of the repository's own hook; only shell hooks are edited, `core.hooksPath` is refused without `--hooks-path`, and `notes.rewriteRef` carries links through amend and rebase. `BEACON_GIT_HOOKS=0` disables the hooks for one command. Every link a run adds is also written to the runtime log as one `session.commit_linked` event in the linked session's timeline (`event.fidelity=inferred`, no collection method), with commit id, branch and credential-stripped remote in the OTel-shaped `vcs` block and overlap counts in `vcs.attribution`; the event deliberately carries no file, command or tool fields so it can never become attribution evidence. Sharing is opt-in (`setup --share-notes`, off by default): a non-destructive fetch refspec `+refs/notes/beacon:refs/notes/beacon-remotes/<remote>` so git's own fetch brings teammates' links into a read-only tracking ref that `beacon git notes` unions with the local one (never force-fetch into `refs/notes/beacon`: it would destroy unpushed links), and a pre-push hook that fetches, merges with `cat_sort_uniq` through the same CAS, and pushes only the notes ref with `--no-verify`, within a 10 s budget and never failing the push. That pre-push hook is the only Beacon git hook that touches the network, and only during a push the person started; `beacon git notes push|fetch` do the same by hand. A note line may carry the session's share URL as its first trailing field (`beacon:<harness>/<id> <url>`; an identifier, not content): `gitlink.ValidShareURL` admits only https URLs on beacon.sh or the configured Beacon host (`AllowShareHost`, fed by `gitAllowShareHosts`), on write and on read, and `MergeNote`/`ParseNote` prefer the line with the URL over the bare one. Post-commit and `link` take URLs only from local `session.shared` events (`localShareURLs`). `setup --share-sessions [--share-visibility]` (implies `--share-notes`; stored as `beacon.shareSessions`/`beacon.shareVisibility` in local git config; public needs confirmation or `--yes`) makes the pre-push hook, which now receives git's stdin, share sessions linked to pushed commits that have no URL (at most 100 commits/10 sessions, inside the 10 s budget less 3 s kept for the notes push, silent without credentials, never failing the push) through `shareUpload` (`cmd/share_upload.go`: `alignShareSource` + `messagesAfter`), then write the URLs into the notes before pushing them. `beacon share --follow [--interval]` (`cmd/share_follow.go`) polls the session locally, uploads through `shareUpload` only when the projected messages' fingerprint changed, stops at `session.ended` or Ctrl+C (`shareFollowWait`/`shareFollowSignals` are the test seams), and records `session.shared` once at the start and once at the end; `docs/cli/share.mdx` carries the API-key CI walkthrough with GitHub Actions and GitLab CI examples.
- Beacon Cloud MCP registration via `beacon mcp connect|disconnect|status` (`cli/beacon/internal/mcpconnect`, `cli/beacon/cmd/mcp_connect.go`; docs in `docs/cli/mcp-connect.mdx`). It registers the Beacon Cloud MCP server as `beacon-managed`, a different name from the local stdio server `beacon`, in the user-level config of Claude Code, Codex CLI, Cursor, VS Code, Gemini CLI and OpenCode. It prints manual steps for runtimes without confirmed MCP OAuth support. OAuth is the default and writes only the URL; `--token-env` writes a reference to an environment variable in each harness's own syntax, never a value. `connect` never reads or copies the account token and never writes a token; minting one is the separate, explicit `beacon mcp token create`. It is explicit and interactive: never run by an unattended install; the onboarding wizard runs it only after the person chose Beacon Cloud and left "Beacon Cloud MCP" selected (that screen is the confirmation), and otherwise the install only suggests it. It is refused as root, and refused in CI or without a terminal unless `--yes` is given. Its one network request is the RFC 9728 resource-metadata check of the URL, which `--dry-run` skips. Configs are edited like the Kimi Code writer: never re-serialized, spliced as text, parsed back and compared before an atomic replace, backed up first. What was written is recorded in `~/.beacon/mcp/connections.json`, and `disconnect` removes only entries recorded there that still point at the recorded URL. `cmd/mcp_connect_e2e_test.go` runs the real harness CLIs when they are installed; re-run it when a harness changes its MCP config format.
- An optional, off-by-default policy seam in the hook path (`cli/beacon-hooks/internal/policy`) governed by the stable contract in `pkg/asymptoteobserve/policycontract`. When `BEACON_POLICY_PROVIDER` names an executable, the `pre-tool` and `permission-request` hooks send it a JSON request describing the imminent tool call and honor an allow/deny response, returning the runtime's native deny shape and `policy.enforcement=enforce` telemetry on a deny. The seam is inert when unset and fail-open on any error (timeout, non-zero exit, malformed output), so the open build ships no enforcement of its own; all audit/enforce decision logic lives in the external provider. `rules/agent-control/agent-permission-bypass-spawn.rule.yaml` is the open detect twin that flags the same pattern in `beacon scan`.
diff --git a/cli/beacon/cmd/share.go b/cli/beacon/cmd/share.go
index c85af78d..50513896 100644
--- a/cli/beacon/cmd/share.go
+++ b/cli/beacon/cmd/share.go
@@ -37,6 +37,9 @@ import (
// trace list and dashboard show the session as shared. That event is inferred bookkeeping: no
// harness collected it.
+// errShareNothingYet is a session with no messages to share yet. --follow waits for some.
+var errShareNothingYet = errors.New("has nothing to share yet")
+
// SessionSharedAction is the runtime-log action recorded after a session is shared or refreshed.
const SessionSharedAction = "session.shared"
@@ -75,6 +78,8 @@ type shareOptions struct {
key string
authURL string
jsonOutput bool
+ follow bool
+ interval time.Duration
current bool
list bool
print bool
@@ -158,6 +163,8 @@ func init() {
f.BoolVar(&shareOpts.list, "list", false, "List the sessions that could be shared, newest first, and share nothing")
f.IntVar(&shareOpts.limit, "limit", 20, "With --list, the most sessions to show (0 for all)")
f.BoolVar(&shareOpts.yes, "yes", false, "Share publicly without asking")
+ f.BoolVar(&shareOpts.follow, "follow", false, "Keep uploading the session's new messages until it ends or Ctrl+C")
+ f.DurationVar(&shareOpts.interval, "interval", shareFollowDefaultInterval, "With --follow, how often to check the session for new messages")
shareCmd.MarkFlagsMutuallyExclusive("session", "source-path", "cwd", "current")
}
@@ -209,7 +216,7 @@ func runShare(cmd *cobra.Command) error {
return err
}
payload, err := buildSharePayload(subject)
- if err != nil {
+ if err != nil && !(shareOpts.follow && errors.Is(err, errShareNothingYet)) {
return err
}
if cmd.Flags().Changed("visibility") {
@@ -228,6 +235,13 @@ func runShare(cmd *cobra.Command) error {
if err != nil {
return err
}
+ if shareOpts.follow {
+ visibility := ""
+ if cmd.Flags().Changed("visibility") {
+ visibility = shareOpts.visibility
+ }
+ return runShareFollow(cmd, client, subject, visibility)
+ }
if !shareOpts.jsonOutput {
fmt.Fprintf(errOut, "Sharing %s session %s (%d messages)%s.\n", subject.session.Harness, subject.session.ID, len(payload.Messages), shareSourceNote(subject))
}
@@ -403,8 +417,13 @@ func validateShareFlags(cmd *cobra.Command) error {
return errors.New("--list shows candidates; combine it with --cwd or --harness, not --session, --source-path or --current")
case shareOpts.printOnly():
return errors.New("--list and --print cannot be combined")
+ case shareOpts.follow:
+ return errors.New("--list and --follow cannot be combined")
}
}
+ if shareOpts.follow && shareOpts.printOnly() {
+ return errors.New("--follow uploads; it cannot be combined with --print")
+ }
if shareOpts.limit < 0 {
return errors.New("--limit cannot be negative")
}
@@ -798,7 +817,7 @@ func buildSharePayload(subject shareSubject) (sharePayload, error) {
opts := asymptoteobserve.ShareOptions{WorkingDirectory: session.Directory}
messages := asymptoteobserve.BuildShareMessagesWithOptions(events, opts)
if len(messages) == 0 {
- return sharePayload{}, fmt.Errorf("%s session %s has nothing to share yet", session.Harness, session.ID)
+ return sharePayload{}, fmt.Errorf("%s session %s %w", session.Harness, session.ID, errShareNothingYet)
}
trace := asymptoteobserve.ShareMetadataFromEventsWithOptions(events, opts)
agent := asymptoteobserve.NormalizeHarnessName(session.Harness)
diff --git a/cli/beacon/cmd/share_follow.go b/cli/beacon/cmd/share_follow.go
new file mode 100644
index 00000000..cf9a38e7
--- /dev/null
+++ b/cli/beacon/cmd/share_follow.go
@@ -0,0 +1,173 @@
+package cmd
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "os/signal"
+ "syscall"
+ "time"
+
+ "github.com/spf13/cobra"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/account"
+)
+
+// `beacon share --follow` keeps a shared trace current while its session runs: it re-reads the
+// session every --interval and uploads what changed, until the session records its end or the
+// command is interrupted. Each poll is local; a request is made only when the session's messages
+// changed since the last upload, and it goes through shareUpload, the same align-and-resume path
+// as `beacon share refresh`.
+
+const (
+ shareFollowDefaultInterval = 10 * time.Second
+ shareFollowMinInterval = time.Second
+)
+
+var (
+ // shareFollowWait sleeps between polls; tests replace it to drive the loop without a clock.
+ shareFollowWait = func(ctx context.Context, d time.Duration) error {
+ timer := time.NewTimer(d)
+ defer timer.Stop()
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-timer.C:
+ return nil
+ }
+ }
+ // shareFollowSignals wires Ctrl+C and SIGTERM to the follow loop's context.
+ shareFollowSignals = func(ctx context.Context) (context.Context, context.CancelFunc) {
+ return signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM)
+ }
+)
+
+// shareFollowUpdate is one upload --follow made; --json prints one per line.
+type shareFollowUpdate struct {
+ shareResult
+ Final bool `json:"final,omitempty"`
+ // Ended is true when the session recorded its end.
+ Ended bool `json:"ended,omitempty"`
+}
+
+func runShareFollow(cmd *cobra.Command, client *account.ShareClient, subject shareSubject, visibility string) error {
+ interval := shareOpts.interval
+ if interval < shareFollowMinInterval {
+ interval = shareFollowMinInterval
+ }
+ ctx, stop := shareFollowSignals(commandContext(cmd))
+ defer stop()
+ out, errOut := cmd.OutOrStdout(), cmd.ErrOrStderr()
+ if !shareOpts.jsonOutput {
+ fmt.Fprintf(errOut, "Following %s session %s, uploading new messages every %s. Ctrl+C stops.\n", subject.session.Harness, subject.session.ID, interval)
+ }
+ var (
+ lastPrint string
+ last shareResult
+ uploads int
+ ended bool
+ )
+ for {
+ if subject.fromLog {
+ // A session read from the runtime log is re-read each time; one from a store is read
+ // fresh by buildSharePayload anyway.
+ if fresh, err := resolveShareLog(subject.session); err == nil {
+ fresh.selectedBy = subject.selectedBy
+ subject = fresh
+ }
+ }
+ fingerprint, end, err := shareFollowState(subject)
+ ended = end
+ if err == nil && fingerprint != lastPrint {
+ opts := shareUploadOptions{Record: uploads == 0}
+ if uploads == 0 {
+ opts.Visibility = visibility
+ }
+ result, aligned, upErr := shareUpload(ctx, client, subject, opts)
+ switch {
+ case upErr == nil:
+ subject, last, lastPrint = aligned, result, fingerprint
+ uploads++
+ if err := printShareFollow(out, errOut, result, uploads == 1, false, ended); err != nil {
+ return err
+ }
+ case ctx.Err() != nil:
+ // Interrupted mid-upload; the loop ends below.
+ case uploads == 0:
+ return upErr
+ default:
+ // beacon.sh or the network failed after the first upload: say so and retry on the
+ // next poll, since the next upload resends whatever this one lacked.
+ fmt.Fprintf(errOut, "warning: upload failed, retrying in %s: %v\n", interval, upErr)
+ }
+ } else if err != nil && uploads == 0 && !errors.Is(err, errShareNothingYet) {
+ return err
+ }
+ if ended || ctx.Err() != nil {
+ break
+ }
+ if shareFollowWait(ctx, interval) != nil {
+ break
+ }
+ }
+ if uploads == 0 {
+ if ctx.Err() != nil {
+ return errors.New("stopped before the session had anything to share")
+ }
+ return fmt.Errorf("%s session %s has nothing to share", subject.session.Harness, subject.session.ID)
+ }
+ if uploads > 1 {
+ if err := recordShareEvent(subject.session, last, true); err != nil {
+ fmt.Fprintf(errOut, "warning: the runtime log was not updated: %v\n", err)
+ }
+ }
+ return printShareFollow(out, errOut, last, false, true, ended)
+}
+
+// shareFollowState is a fingerprint of the session's messages as they would be uploaded now, and
+// whether the session recorded its end.
+func shareFollowState(subject shareSubject) (string, bool, error) {
+ _, events, err := shareEvents(subject)
+ if err != nil {
+ return "", false, err
+ }
+ ended := false
+ for _, e := range events {
+ if e.Event.Action == "session.ended" {
+ ended = true
+ }
+ }
+ payload, err := buildSharePayload(subject)
+ if err != nil {
+ return "", ended, err
+ }
+ data, err := json.Marshal(payload)
+ if err != nil {
+ return "", ended, err
+ }
+ sum := sha256.Sum256(data)
+ return hex.EncodeToString(sum[:]), ended, nil
+}
+
+func printShareFollow(out, errOut io.Writer, result shareResult, first, final, ended bool) error {
+ if shareOpts.jsonOutput {
+ return json.NewEncoder(out).Encode(map[string]any{"ok": true, "data": shareFollowUpdate{shareResult: result, Final: final, Ended: ended}})
+ }
+ switch {
+ case first:
+ fmt.Fprintln(out, result.SharedURL)
+ fmt.Fprintf(errOut, "%s, %d messages. External id: %s\n", result.Visibility, result.MessageCount, result.ExternalID)
+ case final && ended:
+ fmt.Fprintf(errOut, "The session ended; %s holds %d messages.\n", result.SharedURL, result.MessageCount)
+ case final:
+ fmt.Fprintf(errOut, "Stopped following; %s holds %d messages.\n", result.SharedURL, result.MessageCount)
+ default:
+ fmt.Fprintf(errOut, "Uploaded %d message(s); %d in total.\n", result.Uploaded, result.MessageCount)
+ }
+ return nil
+}
diff --git a/cli/beacon/cmd/share_follow_test.go b/cli/beacon/cmd/share_follow_test.go
new file mode 100644
index 00000000..2c1c97c5
--- /dev/null
+++ b/cli/beacon/cmd/share_follow_test.go
@@ -0,0 +1,161 @@
+package cmd
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "os"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/account"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/handoff"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
+)
+
+// growingSource is a Claude Code store whose one session gains events while --follow runs.
+type growingSource struct {
+ mu sync.Mutex
+ session handoff.Session
+ events []schema.Event
+}
+
+func (g *growingSource) Harness() string { return handoff.HarnessClaude }
+func (g *growingSource) List() ([]handoff.Session, error) {
+ return []handoff.Session{g.session}, nil
+}
+func (g *growingSource) Events(handoff.Session) ([]schema.Event, error) {
+ g.mu.Lock()
+ defer g.mu.Unlock()
+ return append([]schema.Event(nil), g.events...), nil
+}
+func (g *growingSource) add(e schema.Event) {
+ g.mu.Lock()
+ g.events = append(g.events, e)
+ g.mu.Unlock()
+}
+
+func followEvent(dir, ts, action string) schema.Event {
+ e := schema.NewEvent(schema.NewEventOptions{Action: action, Category: "agent", Harness: schema.HarnessInfo{Name: handoff.HarnessClaude, CollectionMethod: schema.CollectionMethodPoll}})
+ e.Timestamp = ts
+ e.Session = &schema.SessionInfo{ID: shareTestSession, WorkingDirectory: dir}
+ return e
+}
+
+func TestShareFollowUploadsNewMessagesUntilTheSessionEnds(t *testing.T) {
+ env := newShareEnv(t)
+ src := &growingSource{
+ session: handoff.Session{Harness: handoff.HarnessClaude, ID: shareTestSession, Directory: env.projectDir, UpdatedAt: time.Now()},
+ events: shareFixtureEvents(env.projectDir),
+ }
+ stubHandoffSources(t, src)
+ srv := newFakeShareServer(t)
+ srv.signIn(account.ScopeTracesWrite)
+
+ // The fake clock: each wait is one poll. Polls 1 and 3 add to the session, poll 2 adds
+ // nothing (no request may be made for it), and poll 4 records the session's end.
+ polls := 0
+ requestsAt := map[int]int{}
+ prevWait := shareFollowWait
+ shareFollowWait = func(ctx context.Context, d time.Duration) error {
+ if d != 2*time.Second {
+ t.Errorf("interval = %s", d)
+ }
+ polls++
+ srv.mu.Lock()
+ requestsAt[polls] = len(srv.requests)
+ srv.mu.Unlock()
+ switch polls {
+ case 1:
+ m := followEvent(env.projectDir, "2026-10-01T10:01:00.000000000Z", "agent.message")
+ m.GenAI = &schema.GenAIInfo{Output: &schema.GenAIOutputInfo{Messages: asymptoteobserve.TextOutputMessages("Second answer.")}}
+ src.add(m)
+ case 3:
+ p := followEvent(env.projectDir, "2026-10-01T10:02:00.000000000Z", "prompt.submitted")
+ p.Event.Category = "prompt"
+ p.Prompt = &schema.PromptInfo{Text: "One more thing"}
+ src.add(p)
+ case 4:
+ src.add(followEvent(env.projectDir, "2026-10-01T10:03:00.000000000Z", "session.ended"))
+ case 10:
+ return errors.New("the loop did not stop at the session's end")
+ }
+ return nil
+ }
+ t.Cleanup(func() { shareFollowWait = prevWait })
+
+ stdout, stderr, err := runShareCommand(t, "--follow", "--interval", "2s", "--json", "--cwd", env.projectDir, "--log-path", env.logPath)
+ if err != nil {
+ t.Fatalf("follow: %v\n%s", err, stderr)
+ }
+ if polls != 4 {
+ t.Fatalf("polls = %d, want 4", polls)
+ }
+ srv.mu.Lock()
+ if requestsAt[3] != requestsAt[2] {
+ t.Errorf("an unchanged poll made requests: %v", srv.requests[requestsAt[2]:requestsAt[3]])
+ }
+ messages := len(srv.messages)
+ srv.mu.Unlock()
+ // The fixture's four, the second answer, the new prompt, and the session's end.
+ if messages != 7 {
+ t.Fatalf("server has %d messages, want 7", messages)
+ }
+ lines := strings.Split(strings.TrimSpace(stdout), "\n")
+ var final struct {
+ OK bool `json:"ok"`
+ Data shareFollowUpdate `json:"data"`
+ }
+ if err := json.Unmarshal([]byte(lines[len(lines)-1]), &final); err != nil || !final.Data.Final || !final.Data.Ended || final.Data.SharedURL != "https://beacon.sh/s/k3xabc" {
+ t.Fatalf("last line %q (%v)", lines[len(lines)-1], err)
+ }
+ if n := len(shareEventsIn(t, env.logPath)); n != 2 {
+ t.Fatalf("session.shared events = %d, want one for the share and one at the end", n)
+ }
+}
+
+func TestShareFollowStopsOnInterrupt(t *testing.T) {
+ env := newShareEnv(t)
+ srv := newFakeShareServer(t)
+ srv.signIn(account.ScopeTracesWrite)
+ prevWait, prevSignals := shareFollowWait, shareFollowSignals
+ var cancel context.CancelFunc
+ shareFollowSignals = func(ctx context.Context) (context.Context, context.CancelFunc) {
+ ctx, cancel = context.WithCancel(ctx)
+ return ctx, cancel
+ }
+ shareFollowWait = func(ctx context.Context, d time.Duration) error {
+ cancel() // Ctrl+C during the first wait
+ return ctx.Err()
+ }
+ t.Cleanup(func() { shareFollowWait, shareFollowSignals = prevWait, prevSignals })
+ stdout, stderr, err := runShareCommand(t, "--follow", "--cwd", env.projectDir, "--log-path", env.logPath)
+ if err != nil {
+ t.Fatalf("follow: %v", err)
+ }
+ if !strings.HasPrefix(stdout, "https://beacon.sh/s/k3xabc") || !strings.Contains(stderr, "Stopped following") {
+ t.Fatalf("stdout=%q stderr=%q", stdout, stderr)
+ }
+ if _, _, err := runShareCommand(t, "--follow", "--print"); err == nil {
+ t.Fatal("--follow --print accepted")
+ }
+}
+
+func shareEventsIn(t *testing.T, logPath string) []schema.Event {
+ t.Helper()
+ data, err := os.ReadFile(logPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var out []schema.Event
+ for _, line := range strings.Split(strings.TrimSpace(string(data)), "\n") {
+ var e schema.Event
+ if json.Unmarshal([]byte(line), &e) == nil && e.Event.Action == SessionSharedAction {
+ out = append(out, e)
+ }
+ }
+ return out
+}
diff --git a/docs/cli/share.mdx b/docs/cli/share.mdx
index fcbb419c..6e0a26d1 100644
--- a/docs/cli/share.mdx
+++ b/docs/cli/share.mdx
@@ -11,6 +11,7 @@ description: "Share a local agent session as a trace on beacon.sh"
beacon share [--current | --session <id> | --source-path <path> | --cwd <dir>] [flags]
beacon share --list [--cwd <dir>] [--harness <runtime>]
beacon share refresh [<external-id> | <session-id>] [flags]
+beacon share --follow [--interval 10s] [selector flags]
beacon share auto enable [--visibility direct|private|public] [--project <dir>] [--yes]
beacon share auto disable [--project <dir>]
beacon share auto status [--project <dir>]
@@ -117,6 +118,17 @@ beacon share refresh 5f0c1d2e
beacon share refresh # this session, found like --current
```
+## Follow a running session
+
+`--follow` keeps the trace current while the session runs. It shares the session, then checks it again every `--interval` (default `10s`, at least `1s`) and uploads what changed, until the session records its end (`session.ended`) or you press Ctrl+C. A check is a local read; a request is made only when the session's messages changed, and it sends only what beacon.sh lacks, the same way `refresh` does. A failed upload after the first is reported and retried on the next check.
+
+```bash
+beacon share --follow # this session, until it ends
+beacon share --follow --session 5f0c1d2e --interval 30s
+```
+
+`--follow` waits for a session that has nothing to share yet. The link is printed after the first upload; with `--json`, each upload prints one JSON document per line, and the last carries `"final":true` (and `"ended":true` when the session ended). The runtime log gets one `session.shared` event when the trace is first shared and one when following stops. `--follow` cannot be combined with `--print` or `--list`.
+
## Auto-share
`beacon share auto enable` publishes new sessions without running `beacon share` each time. It works through [Beacon Cloud forwarding](/cli/endpoint-connect), never from the hooks over the network:
@@ -146,7 +158,100 @@ The `session.share_requested` event is marked `event.fidelity=inferred` because
2. Your [`beacon login`](/cli/account-auth) sign-in, when it carries the `traces:write` permission.
3. A Beacon API key in `BEACON_API_KEY`.
-A sign-in from an older `beacon login` lacks `traces:write`; run `beacon login` again. 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.
+A sign-in from an older `beacon login` lacks `traces:write`; run `beacon login` again.
+
+### API keys for CI and other headless machines
+
+Where nobody can run `beacon login` (CI runners, containers, scheduled jobs), use a Beacon API key:
+
+1. On beacon.sh, create an API key with the `traces:write` permission. It starts with `bcn_api_`.
+2. Store it as a secret in your CI system, for example a GitHub Actions secret or a masked GitLab CI/CD variable named `BEACON_API_KEY`.
+3. Expose it to the step that runs `beacon share` as the `BEACON_API_KEY` environment variable. Prefer the variable to `--key`, which puts the key on the command line where process listings can see it.
+4. Run `beacon share` in the same job as the agent, after it: the session is read from the runner's own disk.
+
+With 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.
+
+## CI examples
+
+These 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.
+
+### GitHub Actions
+
+```yaml title=".github/workflows/agent.yml"
+name: Agent
+on:
+ pull_request:
+ workflow_dispatch:
+
+jobs:
+ agent:
+ runs-on: ubuntu-latest
+ permissions:
+ contents: read
+ pull-requests: write
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Install Beacon
+ run: curl -fsSL https://github.com/asymptote-labs/agent-beacon/releases/latest/download/install.sh | bash
+
+ - name: Run the agent
+ env:
+ ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
+ run: npx -y @anthropic-ai/claude-code --print "Fix the failing test and explain the change"
+
+ - name: Share the agent session
+ id: share
+ if: always()
+ env:
+ BEACON_API_KEY: ${{ secrets.BEACON_API_KEY }}
+ run: |
+ out="$(beacon share --cwd . --harness auto --json)" || { echo "$out"; exit 0; }
+ url="$(printf '%s' "$out" | jq -r '.data.shared_url')"
+ echo "url=$url" >> "$GITHUB_OUTPUT"
+ echo "### Agent session" >> "$GITHUB_STEP_SUMMARY"
+ echo "$url" >> "$GITHUB_STEP_SUMMARY"
+
+ - name: Link the session on the pull request
+ if: github.event_name == 'pull_request' && steps.share.outputs.url != ''
+ uses: actions/github-script@v7
+ env:
+ SHARE_URL: ${{ steps.share.outputs.url }}
+ with:
+ script: |
+ await github.rest.issues.createComment({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ issue_number: context.issue.number,
+ body: `Agent session: ${process.env.SHARE_URL}`,
+ });
+```
+
+The URL reaches the script through an environment variable rather than being written into the script, so nothing in the share output can change what the script runs. Sharing failures leave the job green (`exit 0`); drop that to make a missing trace fail the build. To watch the session live, start `beacon share --follow --harness claude_code &` in the step before the agent instead.
+
+### GitLab CI
+
+```yaml title=".gitlab-ci.yml"
+agent:
+ image: node:22
+ variables:
+ # BEACON_API_KEY and ANTHROPIC_API_KEY are masked CI/CD variables.
+ GIT_DEPTH: "0"
+ before_script:
+ - apt-get update -qq && apt-get install -y -qq jq sudo
+ - curl -fsSL https://github.com/asymptote-labs/agent-beacon/releases/latest/download/install.sh | bash
+ script:
+ - npx -y @anthropic-ai/claude-code --print "Fix the failing test and explain the change"
+ after_script:
+ - beacon share --cwd "$CI_PROJECT_DIR" --harness auto --json | tee beacon-share.json || true
+ - echo "Agent session: $(jq -r '.data.shared_url // empty' beacon-share.json)"
+ artifacts:
+ when: always
+ paths:
+ - beacon-share.json
+```
+
+`after_script` runs in the same job even when the agent fails, so the session is still on disk.
## Local record
@@ -179,6 +284,8 @@ The link goes to stdout and a summary to stderr. `--json` prints one document:
| `--limit <n>` | With `--list`, the most sessions to show |
| `--print`, `--dry-run` | Print the payload and send nothing |
| `--yes` | Share publicly without asking |
+| `--follow` | Keep uploading new messages until the session ends or Ctrl+C |
+| `--interval <duration>` | With `--follow`, how often to check the session (default `10s`) |
| `--json` | Print the result as JSON |
| `--store-dir <runtime>=<path>` | Read a runtime's sessions from this directory (repeatable) |
| `--log-path <path>` | Runtime log to read from and record the share in |