Skip to content

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

Add beacon share and beacon share refresh

Claude2a047b9db41d
diff --git a/CLAUDE.md b/CLAUDE.md
index deddc554..48dea651 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -69,6 +69,7 @@ Supported runtime surfaces today:
- Token usage and runtime-reported cost capture across spans, logs, and metric datapoints, normalized into `gen_ai.usage`, with attribution rollups served by the dashboard token view (`/api/tokens`) and the `beacon token-usage` report command for local and CI logs. Every report row carries three costs (`cli/beacon/internal/tokens/cost.go`): `cost_usd` (runtime-reported, unchanged), `estimated_cost_usd` (list price of every priced token, from `internal/pricing`, computed after dedup and cumulative resolution) and `effective_cost_usd` with `cost_source` (per endpoint/harness/session scope, reported cost wins wholesale when the scope has any; otherwise the estimate; session-less events per event), plus `unpriced_events`/`unpriced_tokens` and a report-level `pricing` block (catalog provenance, per-model key, match, base rates, bands applied, fallbacks, unpriced models). Long-context bands apply only to events `requestScoped` classifies as one model request; it defaults to aggregate, so a new capture path is priced at base rates until it is added there with a test. Lens data (`LensDataV1`) carries no estimate.
- 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.
- 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.
- 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
new file mode 100644
index 00000000..d22b1387
--- /dev/null
+++ b/cli/beacon/cmd/share.go
@@ -0,0 +1,751 @@
+package cmd
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "sort"
+ "strings"
+ "time"
+
+ "github.com/spf13/cobra"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/account"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/lifecycle"
+ "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/gitlink"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/handoff"
+ "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"
+)
+
+// `beacon share` publishes one local agent session as a shared trace on beacon.sh. It is the
+// only part of the CLI that uploads session content on request, so it is explicit about it: the
+// session it picked is named before anything is sent, --print shows the exact payload without a
+// network call, a public share asks first, and the content goes through the same sanitizer the
+// runtime log uses before it is projected into messages (asymptoteobserve.BuildShareMessages).
+//
+// After an upload it records one session.shared event in the session's own timeline, so the local
+// trace list and dashboard show the session as shared. That event is inferred bookkeeping: no
+// harness collected it.
+
+// SessionSharedAction is the runtime-log action recorded after a session is shared or refreshed.
+const SessionSharedAction = "session.shared"
+
+var (
+ shareAccountLoad = account.Load
+ shareHTTPClient = &http.Client{Timeout: 60 * time.Second}
+ shareNow = time.Now
+ shareGetenv = os.Getenv
+ shareIsTTY = func() bool { return isTerminal(os.Stdin) }
+ shareStdin io.Reader = os.Stdin
+ // shareGitRemote reads the remote of the repository a session ran in, best effort.
+ shareGitRemote = gitRemoteForDir
+)
+
+type shareOptions struct {
+ session string
+ sourcePath string
+ cwd string
+ harness string
+ visibility string
+ title string
+ key string
+ authURL string
+ jsonOutput bool
+ list bool
+ print bool
+ dryRun bool
+ yes bool
+ limit int
+ logPath string
+ storeDirs []string
+}
+
+var shareOpts shareOptions
+
+var shareCmd = &cobra.Command{
+ Use: "share",
+ Short: "Share a local agent session as a trace on beacon.sh",
+ Long: `Share one local agent session as a trace on beacon.sh, and print its link.
+
+The session is the most recent one in the current directory unless --session, --source-path or
+--cwd names another; --list shows the candidates. It is read from its runtime's own session store
+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 their
+arguments, commands, file paths and diffs, and tool output, after the same secret redaction and size
+limits 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.
+
+Visibility: direct (the default for a new trace) means anyone with the link; private means only
+you; public lists the trace in Discover for anyone, and asks for confirmation first. Re-sharing
+a session updates the same trace and keeps its visibility unless --visibility is given.
+
+Sharing needs ` + "`beacon login`" + ` (with the traces:write permission) or a Beacon API key in --key or
+BEACON_API_KEY. Nothing is uploaded by hooks or in the background; only this command shares.`,
+ Args: cobra.NoArgs,
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error { return shareJSONErrors(cmd, runShare(cmd)) },
+}
+
+var shareRefreshCmd = &cobra.Command{
+ Use: "refresh [external-id|session-id]",
+ Short: "Upload a shared session's new messages",
+ Long: `Upload the messages a session has gained since it was shared.
+
+The argument is the trace's external id (<runtime>:<session-id>, as ` + "`beacon share --json`" + ` prints
+it) or a session id or unique prefix; without one, the most recent session in the current directory.
+beacon.sh reports the last message it has, and only the messages after it are sent. Re-sending is
+harmless, so a refresh that fails part way can simply be run again. The trace's visibility is not
+changed.`,
+ Args: cobra.MaximumNArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ return shareJSONErrors(cmd, runShareRefresh(cmd, args))
+ },
+}
+
+func init() {
+ rootCmd.AddCommand(shareCmd)
+ shareCmd.AddCommand(shareRefreshCmd)
+ for _, c := range []*cobra.Command{shareCmd, shareRefreshCmd} {
+ f := c.Flags()
+ f.StringVar(&shareOpts.harness, "harness", "auto", "Only sessions of this runtime ("+strings.Join(handoff.RuntimeNames(), ", ")+"), or auto")
+ f.StringVar(&shareOpts.key, "key", "", "Beacon API key (bcn_api_...) to share with instead of your sign-in")
+ f.StringVar(&shareOpts.authURL, "auth-url", "", "Beacon service an API key is sent to (defaults to "+account.DefaultBaseURL+", or "+account.BaseURLEnv+")")
+ f.BoolVar(&shareOpts.jsonOutput, "json", false, "Print the result as JSON")
+ f.StringVar(&shareOpts.logPath, "log-path", "", "Runtime JSONL log to read sessions from and record the share in (default the local runtime log)")
+ f.StringArrayVar(&shareOpts.storeDirs, "store-dir", nil, "Read a runtime's sessions from this directory, as <runtime>=<path> (repeatable)")
+ 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: the session's title or first prompt)")
+ }
+ f := shareCmd.Flags()
+ f.StringVar(&shareOpts.session, "session", "", "Session id, or a unique prefix of at least 6 characters")
+ f.StringVar(&shareOpts.sourcePath, "source-path", "", "The session's file in its runtime's store")
+ f.StringVar(&shareOpts.visibility, "visibility", asymptoteobserve.ShareVisibilityDirect, "Who can view the trace: public, direct (anyone with the link) or private")
+ 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")
+ shareCmd.MarkFlagsMutuallyExclusive("session", "source-path", "cwd")
+}
+
+// shareJSONErrors also reports a failure as {"ok":false,...} on stdout under --json, so a script
+// reading stdout always gets a document.
+func shareJSONErrors(cmd *cobra.Command, err error) error {
+ if err != nil && shareOpts.jsonOutput {
+ _ = json.NewEncoder(cmd.OutOrStdout()).Encode(map[string]any{"ok": false, "error": err.Error()})
+ }
+ return err
+}
+
+type shareResult struct {
+ TraceID string `json:"trace_id"`
+ ExternalID string `json:"external_id"`
+ SharedURL string `json:"shared_url"`
+ Visibility string `json:"visibility"`
+ AgentID string `json:"agent_id"`
+ MessageCount int `json:"message_count"`
+ // Uploaded is how many messages this run sent; on a first share it equals the session's count.
+ Uploaded int `json:"uploaded"`
+}
+
+// sharePayload is what --print shows: the trace metadata of the PUT request and every message the
+// batch requests would carry, in order.
+type sharePayload struct {
+ ExternalID string `json:"external_id"`
+ Trace asymptoteobserve.ShareTraceV1 `json:"trace"`
+ Messages []asymptoteobserve.ShareMessageV1 `json:"messages"`
+}
+
+func (o shareOptions) printOnly() bool { return o.print || o.dryRun }
+
+func runShare(cmd *cobra.Command) error {
+ if err := validateShareFlags(cmd); err != nil {
+ return err
+ }
+ harness, err := shareHarness()
+ if err != nil {
+ return err
+ }
+ if shareOpts.list {
+ return runShareList(cmd, harness)
+ }
+ subject, err := resolveShareSubject(harness, shareOpts.session)
+ if err != nil {
+ return err
+ }
+ payload, err := buildSharePayload(subject)
+ if err != nil {
+ return err
+ }
+ if cmd.Flags().Changed("visibility") {
+ payload.Trace.Visibility = shareOpts.visibility
+ }
+ errOut := cmd.ErrOrStderr()
+ if shareOpts.printOnly() {
+ return writeIndentedJSON(cmd.OutOrStdout(), payload)
+ }
+ if payload.Trace.Visibility == asymptoteobserve.ShareVisibilityPublic && !shareOpts.yes {
+ if err := confirmPublicShare(errOut, subject.session, len(payload.Messages)); err != nil {
+ return err
+ }
+ }
+ client, err := newShareClient()
+ if err != nil {
+ return err
+ }
+ 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))
+ }
+ ctx := commandContext(cmd)
+ trace, err := client.PutTrace(ctx, payload.ExternalID, payload.Trace)
+ if err != nil {
+ return err
+ }
+ uploaded, err := client.PutMessages(ctx, payload.ExternalID, payload.Messages)
+ if err != nil {
+ return fmt.Errorf("the trace was created at %s, but uploading its messages failed (run the same command again to retry): %w", trace.URL, err)
+ }
+ result := shareResult{
+ TraceID: trace.ID,
+ ExternalID: payload.ExternalID,
+ SharedURL: trace.URL,
+ Visibility: trace.Visibility,
+ AgentID: payload.Trace.AgentID,
+ MessageCount: uploaded.MessageCount,
+ Uploaded: len(payload.Messages),
+ }
+ if uploaded.Batches == 0 {
+ result.MessageCount = trace.MessageCount
+ }
+ if err := recordShareEvent(subject.session, result, false); err != nil {
+ fmt.Fprintf(errOut, "warning: the session was shared, but the runtime log was not updated: %v\n", err)
+ }
+ return printShareResult(cmd, result)
+}
+
+func runShareRefresh(cmd *cobra.Command, args []string) error {
+ harness, err := shareHarness()
+ if err != nil {
+ return err
+ }
+ id := ""
+ if len(args) == 1 {
+ id = strings.TrimSpace(args[0])
+ if shareOpts.cwd != "" {
+ return errors.New("pass a session or --cwd, not both")
+ }
+ if h, sessionID, ok := parseShareExternalID(id); ok {
+ if harness != "" && h != harness {
+ return fmt.Errorf("%s is a %s trace, not %s", id, h, harness)
+ }
+ harness, id = h, sessionID
+ } else if strings.Contains(id, ":sha256-") {
+ return fmt.Errorf("%s names a session by a digest of its id; pass the session id instead", id)
+ }
+ }
+ subject, err := resolveShareSubject(harness, id)
+ if err != nil {
+ return err
+ }
+ payload, err := buildSharePayload(subject)
+ if err != nil {
+ return err
+ }
+ if shareOpts.printOnly() {
+ return writeIndentedJSON(cmd.OutOrStdout(), payload)
+ }
+ client, err := newShareClient()
+ if err != nil {
+ return err
+ }
+ ctx := commandContext(cmd)
+ state, found, err := client.GetTrace(ctx, payload.ExternalID)
+ if err != nil {
+ return err
+ }
+ if !found {
+ return fmt.Errorf("%s is not shared yet: run `beacon share --session %s` first", payload.ExternalID, subject.session.ID)
+ }
+ pending := messagesAfter(payload.Messages, state.LastMessageID, state.MaxOrder)
+ trace, err := client.PutTrace(ctx, payload.ExternalID, payload.Trace)
+ if err != nil {
+ return err
+ }
+ uploaded, err := client.PutMessages(ctx, payload.ExternalID, pending)
+ if err != nil {
+ return err
+ }
+ result := shareResult{
+ TraceID: trace.ID,
+ ExternalID: payload.ExternalID,
+ SharedURL: trace.URL,
+ Visibility: trace.Visibility,
+ AgentID: payload.Trace.AgentID,
+ MessageCount: state.MessageCount,
+ Uploaded: len(pending),
+ }
+ if uploaded.Batches > 0 {
+ result.MessageCount = uploaded.MessageCount
+ }
+ if err := recordShareEvent(subject.session, result, true); err != nil {
+ fmt.Fprintf(cmd.ErrOrStderr(), "warning: the trace was refreshed, but the runtime log was not updated: %v\n", err)
+ }
+ return printShareResult(cmd, result)
+}
+
+// messagesAfter returns the messages after the one beacon.sh reported last. With no last id it goes
+// by the order number. When the last id is not in this projection (the session was shared from
+// another source, or its earlier messages changed), it returns everything: an upsert of what the
+// server already has changes nothing.
+func messagesAfter(messages []asymptoteobserve.ShareMessageV1, lastID string, maxOrder int) []asymptoteobserve.ShareMessageV1 {
+ if lastID != "" {
+ for i, m := range messages {
+ if m.ID == lastID {
+ return messages[i+1:]
+ }
+ }
+ }
+ if maxOrder > 0 && maxOrder <= len(messages) && lastID == "" {
+ return messages[maxOrder:]
+ }
+ return messages
+}
+
+func validateShareFlags(cmd *cobra.Command) error {
+ if !asymptoteobserve.ValidShareVisibility(shareOpts.visibility) {
+ return fmt.Errorf("--visibility must be public, direct or private, not %q", shareOpts.visibility)
+ }
+ if shareOpts.list {
+ switch {
+ case shareOpts.session != "" || shareOpts.sourcePath != "":
+ return errors.New("--list shows candidates; combine it with --cwd or --harness, not --session or --source-path")
+ case shareOpts.printOnly():
+ return errors.New("--list and --print cannot be combined")
+ }
+ }
+ if shareOpts.limit < 0 {
+ return errors.New("--limit cannot be negative")
+ }
+ return nil
+}
+
+func shareHarness() (string, error) {
+ value := strings.TrimSpace(shareOpts.harness)
+ if value == "" || strings.EqualFold(value, "auto") {
+ return "", nil
+ }
+ return handoff.ParseHarness(value)
+}
+
+func shareLogPath() string {
+ return lifecycle.ResolveRuntimeLog(true, shareOpts.logPath).EffectiveLogPath
+}
+
+func shareStoreDirs() (handoff.StoreDirs, error) {
+ dirs := handoff.StoreDirs{}
+ for _, entry := range shareOpts.storeDirs {
+ name, dir, ok := strings.Cut(entry, "=")
+ if !ok || strings.TrimSpace(name) == "" || dir == "" {
+ return nil, fmt.Errorf("--store-dir %q: want <runtime>=<path>", entry)
+ }
+ harness, err := handoff.ParseHarness(name)
+ if err != nil {
+ return nil, fmt.Errorf("--store-dir %q: %w", entry, err)
+ }
+ abs, err := filepath.Abs(dir)
+ if err != nil {
+ return nil, err
+ }
+ dirs[harness] = abs
+ }
+ return dirs, nil
+}
+
+// shareDirectory is the directory --cwd names, absolute, or the current one.
+func shareDirectory() (string, error) {
+ dir := strings.TrimSpace(shareOpts.cwd)
+ if dir == "" {
+ dir = "."
+ }
+ abs, err := filepath.Abs(dir)
+ if err != nil {
+ return "", fmt.Errorf("resolve --cwd %s: %w", dir, err)
+ }
+ return abs, nil
+}
+
+// shareSubject is a session to share and, when it came from the runtime log, its events.
+type shareSubject struct {
+ session handoff.Session
+ fromLog bool
+ logEvents []schema.Event
+}
+
+func shareSourceNote(subject shareSubject) string {
+ if subject.fromLog {
+ return " from Beacon's runtime log"
+ }
+ return ""
+}
+
+// resolveShareSubject finds the session to share: by id (prefix ok), by its store file, or as the
+// most recent session in a directory. Stores come first, then the runtime log.
+func resolveShareSubject(harness, id string) (shareSubject, error) {
+ dirs, err := shareStoreDirs()
+ if err != nil {
+ return shareSubject{}, err
+ }
+ sources := handoffSources(dirs)
+ switch {
+ case id != "":
+ session, findErr := handoff.Find(sources, harness, id)
+ if findErr == nil {
+ return shareSubject{session: session}, nil
+ }
+ var notFound *handoff.NotFoundError
+ if !errors.As(findErr, &notFound) {
+ return shareSubject{}, findErr
+ }
+ logPath := shareLogPath()
+ session, events, found, err := handoff.LogSession(logPath, id, harness)
+ if err != nil {
+ return shareSubject{}, fmt.Errorf("read runtime log %s: %w", logPath, err)
+ }
+ if !found || (harness != "" && session.Harness != harness) {
+ return shareSubject{}, fmt.Errorf("%w; not in the runtime log %s either (`beacon share --list` shows what is available)", notFound, logPath)
+ }
+ return shareSubject{session: session, fromLog: true, logEvents: events}, nil
+ case strings.TrimSpace(shareOpts.sourcePath) != "":
+ return resolveShareSourcePath(sources, harness, shareOpts.sourcePath)
+ default:
+ dir, err := shareDirectory()
+ if err != nil {
+ return shareSubject{}, err
+ }
+ candidates, err := shareCandidates(sources, harness, dir, 1)
+ if err != nil {
+ return shareSubject{}, err
+ }
+ if len(candidates) == 0 {
+ return shareSubject{}, fmt.Errorf("no agent session found in %s; pass --session, or --cwd for another directory (`beacon share --list --cwd DIR`)", dir)
+ }
+ // A session of a runtime whose store Beacon reads is read from that store; one the store has
+ // lost since falls back to the log when its events are read (shareEvents).
+ session := candidates[0]
+ if handoff.ReadsStore(session.Harness) {
+ return shareSubject{session: session}, nil
+ }
+ return resolveShareLog(session)
+ }
+}
+
+func resolveShareLog(session handoff.Session) (shareSubject, error) {
+ logPath := shareLogPath()
+ found, events, ok, err := handoff.LogSession(logPath, session.ID, session.Harness)
+ if err != nil {
+ return shareSubject{}, fmt.Errorf("read runtime log %s: %w", logPath, err)
+ }
+ if !ok {
+ return shareSubject{}, fmt.Errorf("%s session %s is not in the runtime log %s", session.Harness, session.ID, logPath)
+ }
+ return shareSubject{session: found, fromLog: true, logEvents: events}, nil
+}
+
+func resolveShareSourcePath(sources []handoff.Source, harness, path string) (shareSubject, error) {
+ abs, err := filepath.Abs(path)
+ if err != nil {
+ return shareSubject{}, err
+ }
+ if _, err := os.Stat(abs); err != nil {
+ return shareSubject{}, fmt.Errorf("--source-path %s: %w", path, err)
+ }
+ resolved, _ := filepath.EvalSymlinks(abs)
+ sessions, listErr := handoff.List(sources, handoff.Filter{Harness: harness, IncludeSubagents: true})
+ for _, session := range sessions {
+ if session.SourcePath == "" {
+ continue
+ }
+ if session.SourcePath == abs || (resolved != "" && evalSymlinks(session.SourcePath) == resolved) {
+ return shareSubject{session: session}, nil
+ }
+ }
+ if listErr != nil {
+ return shareSubject{}, fmt.Errorf("no session store lists %s (some stores could not be read: %v)", path, listErr)
+ }
+ return shareSubject{}, fmt.Errorf("no session store Beacon reads lists %s as a session file", path)
+}
+
+func evalSymlinks(path string) string {
+ resolved, err := filepath.EvalSymlinks(path)
+ if err != nil {
+ return path
+ }
+ return resolved
+}
+
+// shareCandidates lists the sessions in dir, newest first: those in the runtimes' own stores, then
+// sessions only Beacon's runtime log has. A store that cannot be read is skipped; the log still
+// answers for it.
+func shareCandidates(sources []handoff.Source, harness, dir string, limit int) ([]handoff.Session, error) {
+ stored, _ := handoff.List(sources, handoff.Filter{Harness: harness, Directory: dir})
+ logged, logErr := handoff.LogSessions(shareLogPath(), handoff.Filter{Harness: harness, Directory: dir})
+ if logErr != nil && !errors.Is(logErr, os.ErrNotExist) && len(stored) == 0 {
+ return nil, fmt.Errorf("read runtime log: %w", logErr)
+ }
+ seen := map[string]bool{}
+ var out []handoff.Session
+ for _, s := range stored {
+ seen[s.Harness+"\x00"+s.ID] = true
+ out = append(out, s)
+ }
+ for _, s := range logged {
+ if !seen[s.Harness+"\x00"+s.ID] {
+ out = append(out, s)
+ }
+ }
+ sort.SliceStable(out, func(i, j int) bool { return out[i].UpdatedAt.After(out[j].UpdatedAt) })
+ if limit > 0 && len(out) > limit {
+ out = out[:limit]
+ }
+ return out, nil
+}
+
+func runShareList(cmd *cobra.Command, harness string) error {
+ dirs, err := shareStoreDirs()
+ if err != nil {
+ return err
+ }
+ dir, err := shareDirectory()
+ if err != nil {
+ return err
+ }
+ sessions, err := shareCandidates(handoffSources(dirs), harness, dir, shareOpts.limit)
+ if err != nil {
+ return err
+ }
+ out := cmd.OutOrStdout()
+ if shareOpts.jsonOutput {
+ if sessions == nil {
+ sessions = []handoff.Session{}
+ }
+ return json.NewEncoder(out).Encode(map[string]any{"ok": true, "data": map[string]any{"directory": dir, "sessions": sessions}})
+ }
+ printHandoffSessions(out, sessions, shareNow())
+ return nil
+}
+
+// shareEvents reads the subject's events: from its runtime's store, or from the runtime log when the
+// session came from there or its store has lost it since it was listed.
+func shareEvents(subject shareSubject) (shareSubject, []schema.Event, error) {
+ if subject.fromLog {
+ return subject, subject.logEvents, nil
+ }
+ dirs, err := shareStoreDirs()
+ if err != nil {
+ return subject, nil, err
+ }
+ events, err := handoff.Events(handoffSources(dirs), subject.session)
+ if err == nil {
+ return subject, events, nil
+ }
+ if !errors.Is(err, handoff.ErrNotFound) {
+ return subject, nil, fmt.Errorf("read %s session %s: %w", subject.session.Harness, subject.session.ID, err)
+ }
+ logSubject, logErr := resolveShareLog(subject.session)
+ if logErr != nil {
+ return subject, nil, logErr
+ }
+ return logSubject, logSubject.logEvents, nil
+}
+
+func buildSharePayload(subject shareSubject) (sharePayload, error) {
+ subject, events, err := shareEvents(subject)
+ if err != nil {
+ return sharePayload{}, err
+ }
+ session := subject.session
+ sort.SliceStable(events, func(i, j int) bool { return shareEventTime(events[i]).Before(shareEventTime(events[j])) })
+ 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)
+ }
+ trace := asymptoteobserve.ShareMetadataFromEventsWithOptions(events, opts)
+ agent := asymptoteobserve.NormalizeHarnessName(session.Harness)
+ if agent == "" {
+ agent = session.Harness
+ }
+ trace.AgentID = agent
+ trace.SourceSessionID = session.ID
+ 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)
+ }
+ if trace.GitBranch == "" {
+ trace.GitBranch = asymptoteobserve.ShareBranch(session.Branch)
+ }
+ if trace.GitRemoteURL == "" && session.Directory != "" {
+ trace.GitRemoteURL = gitlink.SanitizeRemoteURL(shareGitRemote(session.Directory))
+ if trace.ProjectName == "" || trace.ProjectName == filepath.Base(session.Directory) {
+ if name := strings.TrimSuffix(lastURLSegment(trace.GitRemoteURL), ".git"); name != "" {
+ trace.ProjectName = name
+ }
+ }
+ }
+ if session.Subagent && session.ParentID != "" {
+ trace.RelatedTo = asymptoteobserve.ShareExternalID(session.Harness, session.ParentID)
+ trace.RelationshipType = asymptoteobserve.ShareRelationshipSubagent
+ }
+ // The token aggregator resolves cumulative metric series and live-versus-backfill overlap,
+ // which a plain sum of every event does not. Cost is what runtimes reported, never an estimate.
+ totals := tokens.Aggregate(events, tokens.Options{}).Totals
+ usage := asymptoteobserve.ShareTokenUsageV1{
+ InputTokens: totals.InputTokens,
+ OutputTokens: totals.OutputTokens,
+ CacheReadInputTokens: totals.CacheReadInputTokens,
+ CacheCreationInputTokens: totals.CacheCreationInputTokens,
+ ReasoningOutputTokens: totals.ReasoningOutputTokens,
+ }
+ trace.TokenUsage, trace.CostUSD = nil, nil
+ if !usage.IsZero() {
+ trace.TokenUsage = &usage
+ }
+ if totals.CostUSD > 0 {
+ cost := totals.CostUSD
+ trace.CostUSD = &cost
+ }
+ return sharePayload{
+ ExternalID: asymptoteobserve.ShareExternalID(session.Harness, session.ID),
+ Trace: trace,
+ Messages: messages,
+ }, nil
+}
+
+func shareEventTime(event schema.Event) time.Time {
+ ts, err := schema.ParseTimestamp(event.Timestamp)
+ if err != nil {
+ return time.Time{}
+ }
+ return ts
+}
+
+func lastURLSegment(value string) string {
+ value = strings.TrimRight(value, "/")
+ if i := strings.LastIndexAny(value, "/:"); i >= 0 {
+ return value[i+1:]
+ }
+ return ""
+}
+
+// gitRemoteForDir reads the origin remote of the repository at dir, or "" when there is none. It
+// is a local read of git's config; nothing is fetched.
+func gitRemoteForDir(dir string) string {
+ if info, err := os.Stat(dir); err != nil || !info.IsDir() {
+ return ""
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
+ defer cancel()
+ out, err := exec.CommandContext(ctx, "git", "-C", dir, "config", "--get", "remote.origin.url").Output()
+ if err != nil {
+ return ""
+ }
+ return strings.TrimSpace(string(out))
+}
+
+func confirmPublicShare(errOut io.Writer, session handoff.Session, messages int) error {
+ if !shareIsTTY() || isCIEnvironment() {
+ return errors.New("a public trace is listed for anyone to find; pass --yes to share publicly without a terminal to confirm")
+ }
+ fmt.Fprintf(errOut, "Share %s session %s (%d messages) publicly? Anyone can find and read it in Discover. [y/N] ", session.Harness, session.ID, messages)
+ if !confirmNo(shareStdin) {
+ return errors.New("not shared")
+ }
+ return nil
+}
+
+func newShareClient() (*account.ShareClient, error) {
+ cred, err := account.ResolveShareCredential(account.ResolveShareCredentialOptions{
+ Key: shareOpts.key,
+ BaseURL: shareOpts.authURL,
+ Load: shareAccountLoad,
+ Getenv: shareGetenv,
+ Now: shareNow(),
+ })
+ if err != nil {
+ return nil, err
+ }
+ return account.NewShareClient(cred, shareHTTPClient)
+}
+
+func parseShareExternalID(value string) (harness, sessionID string, ok bool) {
+ name, rest, found := strings.Cut(value, ":")
+ if !found || rest == "" || strings.HasPrefix(rest, "sha256-") || !asymptoteobserve.ValidShareExternalID(value) {
+ return "", "", false
+ }
+ h, err := handoff.ParseHarness(name)
+ if err != nil {
+ return "", "", false
+ }
+ return h, rest, true
+}
+
+// recordShareEvent writes the session.shared event into the session's own timeline, with the
+// sharing fields the trace list reads (shared_url, visibility, shared_at, last_refreshed_at).
+func recordShareEvent(session handoff.Session, result shareResult, refresh bool) error {
+ event := shareRecordEvent(session, result, refresh, shareNow())
+ _, err := writer.AppendEvent(event, writer.Options{Path: shareLogPath(), UserMode: true})
+ return err
+}
+
+func shareRecordEvent(session handoff.Session, result shareResult, refresh bool, now time.Time) schema.Event {
+ verb := "shared"
+ if refresh {
+ verb = "refreshed"
+ }
+ event := schema.NewEvent(schema.NewEventOptions{
+ Action: SessionSharedAction,
+ Category: "session",
+ Severity: schema.SeverityInfo,
+ AgentVersion: version.GetVersion(),
+ Harness: schema.HarnessInfo{Name: session.Harness},
+ Fidelity: asymptoteobserve.FidelityInferred,
+ Message: fmt.Sprintf("session %s to beacon.sh (%s, %d messages)", verb, result.Visibility, result.MessageCount),
+ })
+ event.Timestamp = schema.FormatTimestamp(now)
+ event.Session = &schema.SessionInfo{ID: session.ID, WorkingDirectory: session.Directory}
+ stamp := now.UTC().Format(time.RFC3339)
+ event.Raw = map[string]interface{}{
+ "shared_url": result.SharedURL,
+ "visibility": result.Visibility,
+ "shared_trace_id": result.TraceID,
+ "external_id": result.ExternalID,
+ "last_refreshed_at": stamp,
+ }
+ if !refresh {
+ event.Raw["shared_at"] = stamp
+ }
+ return event
+}
+
+func printShareResult(cmd *cobra.Command, result shareResult) error {
+ out := cmd.OutOrStdout()
+ if shareOpts.jsonOutput {
+ return json.NewEncoder(out).Encode(map[string]any{"ok": true, "data": result})
+ }
+ fmt.Fprintln(out, result.SharedURL)
+ fmt.Fprintf(cmd.ErrOrStderr(), "%s, %d messages (%d sent). External id: %s\n", result.Visibility, result.MessageCount, result.Uploaded, result.ExternalID)
+ return nil
+}
diff --git a/cli/beacon/cmd/share_test.go b/cli/beacon/cmd/share_test.go
new file mode 100644
index 00000000..a197be5e
--- /dev/null
+++ b/cli/beacon/cmd/share_test.go
@@ -0,0 +1,466 @@
+package cmd
+
+import (
+ "bytes"
+ "compress/gzip"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/spf13/pflag"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/account"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/dashboard"
+ "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/testenv"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
+)
+
+const shareTestSession = "5f0c1d2e-aaaa-4bbb-8ccc-000000000001"
+
+// shareEnv isolates one share test: a home, a runtime log, a stub Claude Code store holding one
+// session in projectDir, and seams that fail the test on any network use unless a test opts in.
+type shareEnv struct {
+ home string
+ projectDir string
+ logPath string
+}
+
+func newShareEnv(t *testing.T) *shareEnv {
+ t.Helper()
+ home := t.TempDir()
+ testenv.SetHome(t, home)
+ env := &shareEnv{home: home, projectDir: filepath.Join(home, "src", "app"), logPath: filepath.Join(home, "runtime.jsonl")}
+ if err := os.MkdirAll(env.projectDir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ stubHandoffSources(t, stubHandoffSource{
+ harness: handoff.HarnessClaude,
+ sessions: []handoff.Session{{
+ Harness: handoff.HarnessClaude, ID: shareTestSession, Title: "Fix the login test",
+ Directory: env.projectDir, SourcePath: filepath.Join(home, "store", shareTestSession+".jsonl"),
+ UpdatedAt: time.Now(),
+ }},
+ events: shareFixtureEvents(env.projectDir),
+ })
+ prevLoad, prevClient, prevTTY, prevStdin, prevGetenv, prevRemote := shareAccountLoad, shareHTTPClient, shareIsTTY, shareStdin, shareGetenv, shareGitRemote
+ shareAccountLoad = func() (*account.Session, error) { return nil, account.ErrNotSignedIn }
+ shareHTTPClient = &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
+ t.Errorf("unexpected network request: %s %s", r.Method, r.URL)
+ return nil, errors.New("no network in tests")
+ })}
+ shareIsTTY = func() bool { return false }
+ shareStdin = strings.NewReader("")
+ shareGetenv = func(string) string { return "" }
+ shareGitRemote = func(string) string { return "" }
+ t.Cleanup(func() {
+ shareAccountLoad, shareHTTPClient, shareIsTTY, shareStdin, shareGetenv, shareGitRemote = prevLoad, prevClient, prevTTY, prevStdin, prevGetenv, prevRemote
+ })
+ return env
+}
+
+type roundTripFunc func(*http.Request) (*http.Response, error)
+
+func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
+
+func shareFixtureEvents(dir string) []schema.Event {
+ base := func(ts, action, category string) schema.Event {
+ e := schema.NewEvent(schema.NewEventOptions{Action: action, Category: category, Harness: schema.HarnessInfo{Name: handoff.HarnessClaude, CollectionMethod: schema.CollectionMethodPoll}})
+ e.Timestamp = ts
+ e.Session = &schema.SessionInfo{ID: shareTestSession, WorkingDirectory: dir}
+ return e
+ }
+ prompt := base("2026-10-01T10:00:00.000000000Z", "prompt.submitted", "prompt")
+ prompt.Prompt = &schema.PromptInfo{Text: "Fix the login test in " + dir + "/login_test.go"}
+ call := base("2026-10-01T10:00:01.000000000Z", "tool.invoked", "tool")
+ call.Tool = &schema.ToolInfo{Name: "Bash", Command: "go test ./..."}
+ call.GenAI = &schema.GenAIInfo{Tool: &schema.GenAIToolInfo{Name: "Bash", Call: &schema.GenAIToolCallInfo{ID: "toolu_1", Arguments: map[string]interface{}{"command": "go test ./..."}}}}
+ done := base("2026-10-01T10:00:02.000000000Z", "command.executed", "command")
+ done.Tool = &schema.ToolInfo{Name: "Bash", Command: "go test ./..."}
+ done.Command = &schema.CommandInfo{Command: "go test ./...", Output: "ok"}
+ done.GenAI = &schema.GenAIInfo{Tool: &schema.GenAIToolInfo{Name: "Bash", Call: &schema.GenAIToolCallInfo{ID: "toolu_1"}}}
+ answer := base("2026-10-01T10:00:03.000000000Z", "agent.message", "agent")
+ answer.Model = "claude-sonnet-5-5"
+ answer.GenAI = &schema.GenAIInfo{Output: &schema.GenAIOutputInfo{Messages: asymptoteobserve.TextOutputMessages("Fixed.")}}
+ return []schema.Event{prompt, call, done, answer}
+}
+
+func runShareCommand(t *testing.T, args ...string) (string, string, error) {
+ t.Helper()
+ shareOpts = shareOptions{}
+ for _, cmd := range []*pflag.FlagSet{shareCmd.Flags(), shareRefreshCmd.Flags()} {
+ cmd.VisitAll(func(f *pflag.Flag) {
+ if slice, ok := f.Value.(pflag.SliceValue); ok {
+ _ = slice.Replace(nil)
+ f.Changed = false
+ return
+ }
+ _ = f.Value.Set(f.DefValue)
+ f.Changed = false
+ })
+ }
+ var stdout, stderr bytes.Buffer
+ rootCmd.SetOut(&stdout)
+ rootCmd.SetErr(&stderr)
+ rootCmd.SetArgs(append([]string{"share"}, args...))
+ t.Cleanup(func() {
+ rootCmd.SetOut(nil)
+ rootCmd.SetErr(nil)
+ rootCmd.SetArgs(nil)
+ })
+ err := rootCmd.Execute()
+ return stdout.String(), stderr.String(), err
+}
+
+func TestShareFlagValidation(t *testing.T) {
+ env := newShareEnv(t)
+ for _, tc := range []struct {
+ args []string
+ want string
+ }{
+ {[]string{"--visibility", "everyone"}, "--visibility must be"},
+ {[]string{"--session", "abc", "--cwd", env.projectDir}, "none of the others can be"},
+ {[]string{"--session", "abc", "--source-path", "x"}, "none of the others can be"},
+ {[]string{"--list", "--session", shareTestSession}, "--list shows candidates"},
+ {[]string{"--list", "--print"}, "cannot be combined"},
+ {[]string{"--harness", "notaruntime", "--print"}, "unsupported runtime"},
+ } {
+ _, _, err := runShareCommand(t, append(tc.args, "--log-path", env.logPath)...)
+ if err == nil || !strings.Contains(err.Error(), tc.want) {
+ t.Errorf("share %v: err = %v, want %q", tc.args, err, tc.want)
+ }
+ }
+}
+
+func TestShareDryRunPrintsThePayloadWithoutNetwork(t *testing.T) {
+ env := newShareEnv(t)
+ 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.ExternalID != "claude_code:"+shareTestSession || payload.Trace.AgentID != "claude_code" {
+ t.Fatalf("identity = %q %q", payload.ExternalID, payload.Trace.AgentID)
+ }
+ if payload.Trace.Title != "Fix the login test" || payload.Trace.Visibility != "" || payload.Trace.ProjectName != "app" {
+ t.Fatalf("trace = %+v", payload.Trace)
+ }
+ if len(payload.Messages) != 4 {
+ t.Fatalf("messages = %d: %s", len(payload.Messages), stdout)
+ }
+ if strings.Contains(stdout, env.home) {
+ t.Fatalf("the payload names the local home directory:\n%s", stdout)
+ }
+ if !strings.Contains(stdout, "./login_test.go") {
+ t.Fatalf("the prompt path was not made relative:\n%s", stdout)
+ }
+ if _, err := os.Stat(env.logPath); !os.IsNotExist(err) {
+ t.Fatalf("a dry run wrote the runtime log: %v", err)
+ }
+ // --dry-run is the same, and --session takes a prefix.
+ again, _, err := runShareCommand(t, "--session", shareTestSession[:8], "--dry-run", "--log-path", env.logPath)
+ if err != nil || again != stdout {
+ t.Fatalf("--dry-run --session prefix differs (err %v)", err)
+ }
+}
+
+func TestShareResolvesSessionsBySourcePathAndFromTheLog(t *testing.T) {
+ env := newShareEnv(t)
+ source := filepath.Join(env.home, "store", shareTestSession+".jsonl")
+ if err := os.MkdirAll(filepath.Dir(source), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(source, []byte("{}\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ stdout, _, err := runShareCommand(t, "--source-path", source, "--print", "--log-path", env.logPath)
+ if err != nil || !strings.Contains(stdout, shareTestSession) {
+ t.Fatalf("--source-path: err=%v out=%s", err, stdout)
+ }
+
+ // A Gemini CLI session exists only in the runtime log, in another directory.
+ other := filepath.Join(env.home, "src", "tool")
+ prompt := schema.NewEvent(schema.NewEventOptions{Action: "prompt.submitted", Category: "prompt", Harness: schema.HarnessInfo{Name: "gemini_cli", CollectionMethod: schema.CollectionMethodHook}})
+ prompt.Session = &schema.SessionInfo{ID: "gem-session-1", WorkingDirectory: other}
+ prompt.Prompt = &schema.PromptInfo{Text: "Add a flag"}
+ if _, err := writer.AppendEvent(prompt, writer.Options{Path: env.logPath, UserMode: true}); err != nil {
+ t.Fatal(err)
+ }
+ stdout, _, err = runShareCommand(t, "--cwd", other, "--print", "--log-path", env.logPath)
+ if err != nil {
+ t.Fatalf("--cwd from log: %v", err)
+ }
+ var payload sharePayload
+ if err := json.Unmarshal([]byte(stdout), &payload); err != nil || payload.ExternalID != "gemini_cli:gem-session-1" || len(payload.Messages) != 1 {
+ t.Fatalf("log payload = %+v (err %v)", payload, err)
+ }
+
+ list, _, err := runShareCommand(t, "--list", "--cwd", env.home, "--json", "--log-path", env.logPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var listed struct {
+ OK bool `json:"ok"`
+ Data struct {
+ Sessions []handoff.Session `json:"sessions"`
+ } `json:"data"`
+ }
+ if err := json.Unmarshal([]byte(list), &listed); err != nil || !listed.OK || len(listed.Data.Sessions) != 2 {
+ t.Fatalf("list = %s (err %v)", list, err)
+ }
+
+ _, _, err = runShareCommand(t, "--cwd", filepath.Join(env.home, "empty"), "--print", "--log-path", env.logPath)
+ if err == nil || !strings.Contains(err.Error(), "no agent session found") {
+ t.Fatalf("empty dir: err = %v", err)
+ }
+}
+
+// fakeShareServer is beacon.sh's shared-trace API, in memory.
+type fakeShareServer struct {
+ mu sync.Mutex
+ server *httptest.Server
+ trace *asymptoteobserve.ShareTraceV1
+ messages []asymptoteobserve.ShareMessageV1
+ requests []string
+ auth map[string]bool
+}
+
+func newFakeShareServer(t *testing.T) *fakeShareServer {
+ f := &fakeShareServer{auth: map[string]bool{}}
+ f.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.requests = append(f.requests, r.Method+" "+r.URL.Path)
+ f.auth[r.Header.Get("Authorization")] = true
+ id := strings.TrimPrefix(r.URL.Path, "/v1/traces/")
+ switch {
+ case r.Method == http.MethodPut:
+ var trace asymptoteobserve.ShareTraceV1
+ _ = json.NewDecoder(r.Body).Decode(&trace)
+ created := f.trace == nil
+ if !created && trace.Visibility == "" {
+ trace.Visibility = f.trace.Visibility
+ }
+ if trace.Visibility == "" {
+ trace.Visibility = "direct"
+ }
+ f.trace = &trace
+ fmt.Fprintf(w, `{"id":"k3xabc","external_id":%q,"url":"https://beacon.sh/s/k3xabc","visibility":%q,"message_count":%d,"created":%v}`, id, trace.Visibility, len(f.messages), created)
+ case r.Method == http.MethodPost && strings.HasSuffix(id, "/messages/batch"):
+ zr, err := gzip.NewReader(r.Body)
+ if err != nil {
+ http.Error(w, "want gzip", 400)
+ return
+ }
+ data, _ := io.ReadAll(zr)
+ var batch asymptoteobserve.ShareMessagesBatchV1
+ _ = json.Unmarshal(data, &batch)
+ for _, m := range batch.Messages {
+ replaced := false
+ for i := range f.messages {
+ if f.messages[i].ID == m.ID {
+ f.messages[i], replaced = m, true
+ }
+ }
+ if !replaced {
+ f.messages = append(f.messages, m)
+ }
+ }
+ fmt.Fprintf(w, `{"accepted":%d,"message_count":%d}`, len(batch.Messages), len(f.messages))
+ case r.Method == http.MethodGet:
+ if f.trace == nil {
+ http.NotFound(w, r)
+ return
+ }
+ last, maxOrder := "", 0
+ for _, m := range f.messages {
+ if m.Order > maxOrder {
+ last, maxOrder = m.ID, m.Order
+ }
+ }
+ fmt.Fprintf(w, `{"id":"k3xabc","url":"https://beacon.sh/s/k3xabc","visibility":%q,"message_count":%d,"last_message_id":%q,"max_order":%d}`, f.trace.Visibility, len(f.messages), last, maxOrder)
+ default:
+ http.NotFound(w, r)
+ }
+ }))
+ t.Cleanup(f.server.Close)
+ return f
+}
+
+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 }
+ shareHTTPClient = f.server.Client()
+}
+
+func TestShareUploadsAndRecordsTheShareLocally(t *testing.T) {
+ env := newShareEnv(t)
+ srv := newFakeShareServer(t)
+ srv.signIn(account.ScopeTracesWrite)
+
+ stdout, stderr, err := runShareCommand(t, "--cwd", env.projectDir, "--json", "--log-path", env.logPath)
+ if err != nil {
+ t.Fatalf("share: %v\n%s", err, stderr)
+ }
+ var result struct {
+ OK bool `json:"ok"`
+ Data shareResult `json:"data"`
+ }
+ if err := json.Unmarshal([]byte(stdout), &result); err != nil || !result.OK {
+ t.Fatalf("output = %s (err %v)", stdout, err)
+ }
+ want := shareResult{TraceID: "k3xabc", ExternalID: "claude_code:" + shareTestSession, SharedURL: "https://beacon.sh/s/k3xabc", Visibility: "direct", AgentID: "claude_code", MessageCount: 4, Uploaded: 4}
+ if result.Data != want {
+ t.Fatalf("result = %+v, want %+v", result.Data, want)
+ }
+ if strings.Contains(stdout+stderr, "bcn_cli_secret_token") {
+ t.Fatal("the account token reached the output")
+ }
+ if !srv.auth["Bearer bcn_cli_secret_token"] || len(srv.messages) != 4 || srv.trace.SchemaVersion != asymptoteobserve.ShareSchemaVersion {
+ t.Fatalf("server saw auth=%v messages=%d trace=%+v", srv.auth, len(srv.messages), srv.trace)
+ }
+ if srv.trace.Visibility != "" && srv.trace.Visibility != "direct" {
+ t.Fatalf("visibility sent = %q", srv.trace.Visibility)
+ }
+
+ // The local trace list now shows the session as shared.
+ list, err := dashboard.ReadTraceList(env.logPath, dashboard.TraceQuery{State: "shared"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(list.Traces) != 1 || list.Traces[0].Sharing.URL != "https://beacon.sh/s/k3xabc" || list.Traces[0].Sharing.Visibility != "direct" || list.Traces[0].Sharing.SharedAt == "" {
+ t.Fatalf("shared traces = %+v", list.Traces)
+ }
+ data, err := os.ReadFile(env.logPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var event schema.Event
+ if err := json.Unmarshal(bytes.TrimSpace(data), &event); err != nil {
+ t.Fatal(err)
+ }
+ if event.Event.Action != SessionSharedAction || event.Event.Fidelity != asymptoteobserve.FidelityInferred || event.Harness.CollectionMethod != "" || event.Session.ID != shareTestSession {
+ t.Fatalf("session.shared event = %+v", event)
+ }
+
+ // Sharing again updates the same trace: nothing duplicates and the visibility is kept.
+ if _, _, err := runShareCommand(t, "--cwd", env.projectDir, "--log-path", env.logPath); err != nil {
+ t.Fatal(err)
+ }
+ if len(srv.messages) != 4 {
+ t.Fatalf("re-share duplicated messages: %d", len(srv.messages))
+ }
+
+ // A refresh sends only what the server does not have.
+ srv.mu.Lock()
+ srv.messages = srv.messages[:2]
+ srv.mu.Unlock()
+ stdout, _, err = runShareCommand(t, "refresh", "claude_code:"+shareTestSession, "--json", "--log-path", env.logPath)
+ if err != nil {
+ t.Fatalf("refresh: %v", err)
+ }
+ if err := json.Unmarshal([]byte(stdout), &result); err != nil || result.Data.Uploaded != 2 || result.Data.MessageCount != 4 {
+ t.Fatalf("refresh result = %s (err %v)", stdout, err)
+ }
+}
+
+func TestSharePublicNeedsConfirmation(t *testing.T) {
+ env := newShareEnv(t)
+ srv := newFakeShareServer(t)
+ srv.signIn(account.ScopeTracesWrite)
+
+ _, _, err := runShareCommand(t, "--cwd", env.projectDir, "--visibility", "public", "--log-path", env.logPath)
+ if err == nil || !strings.Contains(err.Error(), "--yes") || len(srv.requests) != 0 {
+ t.Fatalf("non-terminal public share: err = %v, requests = %v", err, srv.requests)
+ }
+
+ shareIsTTY = func() bool { return true }
+ for _, key := range []string{"CI", "CONTINUOUS_INTEGRATION", "GITHUB_ACTIONS", "GITLAB_CI", "BUILDKITE", "JENKINS_URL", "TEAMCITY_VERSION"} {
+ t.Setenv(key, "")
+ }
+ shareStdin = strings.NewReader("n\n")
+ _, stderr, err := runShareCommand(t, "--cwd", env.projectDir, "--visibility", "public", "--log-path", env.logPath)
+ if err == nil || !strings.Contains(stderr, "publicly?") || len(srv.requests) != 0 {
+ t.Fatalf("declined public share: err = %v, requests = %v, stderr = %s", err, srv.requests, stderr)
+ }
+
+ shareStdin = strings.NewReader("y\n")
+ if _, _, err := runShareCommand(t, "--cwd", env.projectDir, "--visibility", "public", "--log-path", env.logPath); err != nil {
+ t.Fatalf("confirmed public share: %v", err)
+ }
+ if srv.trace == nil || srv.trace.Visibility != "public" {
+ t.Fatalf("trace = %+v", srv.trace)
+ }
+
+ shareIsTTY = func() bool { return false }
+ if _, _, err := runShareCommand(t, "--cwd", env.projectDir, "--visibility", "public", "--yes", "--log-path", env.logPath); err != nil {
+ t.Fatalf("--yes public share: %v", err)
+ }
+}
+
+func TestShareNeedsTheTracesWriteScope(t *testing.T) {
+ env := newShareEnv(t)
+ srv := newFakeShareServer(t)
+ srv.signIn(account.ScopeProfileRead, account.ScopeMCPTokenCreate)
+ stdout, _, err := runShareCommand(t, "--cwd", env.projectDir, "--json", "--log-path", env.logPath)
+ if !errors.Is(err, account.ErrTracesWriteScope) || len(srv.requests) != 0 {
+ t.Fatalf("err = %v, requests = %v", err, srv.requests)
+ }
+ if !strings.Contains(stdout, `"ok":false`) || !strings.Contains(stdout, "beacon login") {
+ t.Fatalf("json error = %s", stdout)
+ }
+
+ // An API key stands in for the sign-in.
+ shareGetenv = func(name string) string {
+ if name == account.APIKeyEnv {
+ return "bcn_api_test_key"
+ }
+ return ""
+ }
+ t.Setenv(account.BaseURLEnv, srv.server.URL)
+ if _, _, err := runShareCommand(t, "--cwd", env.projectDir, "--log-path", env.logPath); err != nil {
+ t.Fatalf("share with API key: %v", err)
+ }
+ if !srv.auth["Bearer bcn_api_test_key"] {
+ t.Fatalf("auth = %v", srv.auth)
+ }
+}
+
+func TestShareRefreshParsesExternalIDs(t *testing.T) {
+ cases := map[string]struct {
+ harness, session string
+ ok bool
+ }{
+ "claude_code:abc-123": {handoff.HarnessClaude, "abc-123", true},
+ "codex:rollout:1": {handoff.HarnessCodex, "rollout:1", true},
+ "cursor:sha256-0123456789ab": {"", "", false},
+ "abc-123": {"", "", false},
+ "nope:abc": {"", "", false},
+ }
+ for in, want := range cases {
+ h, s, ok := parseShareExternalID(in)
+ if ok != want.ok || h != want.harness || s != want.session {
+ t.Errorf("parseShareExternalID(%q) = %q %q %v, want %+v", in, h, s, ok, want)
+ }
+ }
+ if got := messagesAfter([]asymptoteobserve.ShareMessageV1{{ID: "a"}, {ID: "b"}, {ID: "c"}}, "b", 2); len(got) != 1 || got[0].ID != "c" {
+ t.Fatalf("messagesAfter = %+v", got)
+ }
+ if got := messagesAfter([]asymptoteobserve.ShareMessageV1{{ID: "a"}, {ID: "b"}}, "zzz", 9); len(got) != 2 {
+ t.Fatalf("unknown last id should resend everything: %+v", got)
+ }
+}
diff --git a/cli/beacon/internal/handoff/runtimelog.go b/cli/beacon/internal/handoff/runtimelog.go
index e8c6ebbc..ecbe853a 100644
--- a/cli/beacon/internal/handoff/runtimelog.go
+++ b/cli/beacon/internal/handoff/runtimelog.go
@@ -1,6 +1,7 @@
package handoff
import (
+ "sort"
"strings"
"time"
@@ -85,3 +86,66 @@ func logSessionForPrefix(logPath, prefix, harness string) (string, error) {
}
return "", &AmbiguousError{ID: prefix, Candidates: candidates}
}
+
+// LogSessions lists the sessions in Beacon's runtime log, newest first, narrowed by filter the way
+// List narrows a store listing: a runtime, a directory the session ran in or below, and a limit. It
+// is how a runtime whose store Beacon does not read, or a session its store no longer has, is found
+// by directory. Title is the session's first prompt, cut to one line.
+func LogSessions(logPath string, filter Filter) ([]Session, error) {
+ within := directoryMatcher(filter.Directory)
+ byKey := map[string]*Session{}
+ var order []string
+ err := dashboard.StreamEvents(logPath, func(event schema.Event) error {
+ if event.Session == nil || strings.TrimSpace(event.Session.ID) == "" {
+ return nil
+ }
+ name := canonicalHarness(asymptoteobserve.NormalizeHarnessName(event.Harness.Name))
+ if name == "" || (filter.Harness != "" && name != filter.Harness) {
+ return nil
+ }
+ key := name + "\x00" + event.Session.ID
+ session := byKey[key]
+ if session == nil {
+ session = &Session{Harness: name, ID: event.Session.ID}
+ byKey[key] = session
+ order = append(order, key)
+ }
+ if session.Directory == "" {
+ session.Directory = strings.TrimSpace(event.Session.WorkingDirectory)
+ }
+ if session.Branch == "" {
+ session.Branch = strings.TrimSpace(event.Branch)
+ }
+ if session.Title == "" && event.Prompt != nil && strings.TrimSpace(event.Prompt.Text) != "" {
+ session.Title = oneLine(event.Prompt.Text)
+ }
+ if ts, err := asymptoteobserve.ParseTimestamp(event.Timestamp); err == nil && ts.After(session.UpdatedAt) {
+ session.UpdatedAt = ts.UTC()
+ }
+ return nil
+ })
+ if err != nil {
+ return nil, err
+ }
+ var sessions []Session
+ for _, key := range order {
+ session := byKey[key]
+ if filter.Directory != "" && (session.Directory == "" || !within(session.Directory)) {
+ continue
+ }
+ sessions = append(sessions, *session)
+ }
+ sort.SliceStable(sessions, func(i, j int) bool {
+ if !sessions[i].UpdatedAt.Equal(sessions[j].UpdatedAt) {
+ return sessions[i].UpdatedAt.After(sessions[j].UpdatedAt)
+ }
+ if sessions[i].Harness != sessions[j].Harness {
+ return sessions[i].Harness < sessions[j].Harness
+ }
+ return sessions[i].ID < sessions[j].ID
+ })
+ if filter.Limit > 0 && len(sessions) > filter.Limit {
+ sessions = sessions[:filter.Limit]
+ }
+ return sessions, nil
+}
diff --git a/cli/beacon/internal/handoff/runtimelog_test.go b/cli/beacon/internal/handoff/runtimelog_test.go
new file mode 100644
index 00000000..a71fcbcf
--- /dev/null
+++ b/cli/beacon/internal/handoff/runtimelog_test.go
@@ -0,0 +1,43 @@
+package handoff
+
+import (
+ "path/filepath"
+ "testing"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer"
+)
+
+func TestLogSessionsListsByDirectoryNewestFirst(t *testing.T) {
+ dir := t.TempDir()
+ logPath := filepath.Join(dir, "runtime.jsonl")
+ write := func(harness, session, cwd, ts, prompt string) {
+ t.Helper()
+ event := schema.NewEvent(schema.NewEventOptions{Action: "prompt.submitted", Category: "prompt", Harness: schema.HarnessInfo{Name: harness}})
+ event.Timestamp = ts
+ event.Session = &schema.SessionInfo{ID: session, WorkingDirectory: cwd}
+ event.Prompt = &schema.PromptInfo{Text: prompt}
+ if _, err := writer.AppendEvent(event, writer.Options{Path: logPath, UserMode: true}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ project := filepath.Join(dir, "app")
+ write("gemini_cli", "g1", project, "2026-10-01T10:00:00.000000000Z", "first\nprompt")
+ write("kiro", "k1", filepath.Join(project, "sub"), "2026-10-01T11:00:00.000000000Z", "second")
+ write("kiro", "k2", filepath.Join(dir, "elsewhere"), "2026-10-01T12:00:00.000000000Z", "third")
+ write("gemini_cli", "g1", project, "2026-10-01T13:00:00.000000000Z", "later")
+
+ sessions, err := LogSessions(logPath, Filter{Directory: project})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(sessions) != 2 || sessions[0].ID != "g1" || sessions[1].ID != "k1" {
+ t.Fatalf("sessions = %+v", sessions)
+ }
+ if sessions[0].Title != "first prompt" || sessions[0].Harness != "gemini_cli" {
+ t.Fatalf("session = %+v", sessions[0])
+ }
+ if only, _ := LogSessions(logPath, Filter{Harness: "kiro", Limit: 1}); len(only) != 1 || only[0].ID != "k2" {
+ t.Fatalf("kiro sessions = %+v", only)
+ }
+}
diff --git a/docs/cli/account-auth.mdx b/docs/cli/account-auth.mdx
index 8ab61b3d..6c5350ea 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}/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`.
+- `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`](/cli/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`, `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/endpoint-traces.mdx b/docs/cli/endpoint-traces.mdx
index e15e8591..9f6782a4 100644
--- a/docs/cli/endpoint-traces.mdx
+++ b/docs/cli/endpoint-traces.mdx
@@ -84,8 +84,8 @@ All commands accept:
|------|-------------|
| `--query <text>`, `-q <text>` | Filter traces by text |
| `--page <n>` | Page number for trace listing. Defaults to `1` |
-| `--state <state>` | Filter by sharing state |
-| `--visibility <visibility>` | Filter by sharing visibility |
+| `--state <state>` | Filter by sharing state: `local_only`, or `shared` for sessions published with [`beacon share`](/cli/share) |
+| `--visibility <visibility>` | Filter by sharing visibility: `private` for local-only traces, or the `public`, `direct` or `private` a shared trace was given |
`search` also accepts:
diff --git a/docs/cli/share.mdx b/docs/cli/share.mdx
new file mode 100644
index 00000000..02d1677a
--- /dev/null
+++ b/docs/cli/share.mdx
@@ -0,0 +1,146 @@
+---
+title: "beacon share"
+description: "Share a local agent session as a trace on beacon.sh"
+---
+
+## Command overview
+
+`beacon share` publishes one local agent session as a shared trace on beacon.sh and prints its link. The trace shows the session's prompts, the agent's answers and reasoning, and every tool call with its result, in order.
+
+```bash title="Command syntax"
+beacon share [--session <id> | --source-path <path> | --cwd <dir>] [flags]
+beacon share --list [--cwd <dir>] [--harness <runtime>]
+beacon share refresh [<external-id> | <session-id>] [flags]
+```
+
+Without a session flag, `beacon share` shares the most recent session that ran in the current directory. It names the session it picked before uploading anything.
+
+```bash title="Share the session you just finished here"
+beacon share
+```
+
+```bash title="See what would be uploaded, without uploading it"
+beacon share --print
+```
+
+Sharing is always something you ask for. Hooks, plugins and background jobs never share a session, and nothing else in Beacon uploads session content to beacon.sh except [Beacon Cloud forwarding](/cli/endpoint-connect) when you connect an endpoint.
+
+## Choosing the session
+
+| Flag | Picks |
+|------|-------|
+| `--session <id>` | The session with this id, or the one session whose id starts with this prefix (at least 6 characters) |
+| `--source-path <path>` | The session stored in this file of its runtime's session store |
+| `--cwd <dir>` | The most recent session that ran in this directory or below it. This is the default, with the current directory |
+| `--harness <runtime>` | Only sessions of this runtime (`claude`, `codex`, `cursor`, ...). `auto`, the default, considers every runtime |
+
+`--session`, `--source-path` and `--cwd` cannot be combined. `--list` shows the candidates instead of sharing, newest first, and takes `--cwd`, `--harness` and `--limit` (default 20, `0` for all).
+
+```bash title="List and pick"
+beacon share --list --cwd ~/src/app
+beacon share --session 5f0c1d2e
+```
+
+Sessions are read the way [`beacon handoff`](/cli/handoff) reads them: from the runtime's own session store when Beacon reads that runtime's store, which keeps the most of each step, and otherwise from Beacon's runtime log. `--store-dir <runtime>=<path>` reads a store from another location, and `--log-path` reads another runtime log.
+
+## What is uploaded
+
+A shared trace is made of messages. Each Beacon event of the session becomes at most one message:
+
+| Event | Message |
+|-------|---------|
+| Prompt | A user message with the prompt text |
+| Assistant text, reasoning | An assistant message with a text or thinking part |
+| Tool invocation | An assistant message with a `tool_call` part: the tool, its kind (`terminal_command`, `read`, `edit`, `write`, `grep`, `glob`, `web_search`, `web_fetch`, `task`, `todo`, `mcp`, ...), its arguments, command, file path and diff |
+| Tool completion | An assistant message with a `tool_result` part: the output, `success` or `error`, the exit code and duration where the runtime reported them |
+| Approval, policy decision, session lifecycle, commit link | A system message with a `system_event` part |
+| Failure that is not a tool's | A system message with an `error` part |
+
+When a runtime reports one tool call twice, before and after it runs, the two become a call and a result that share one call id. A call reported by more than one capture path is written once. Beacon's own bookkeeping (heartbeats, inventory, metric datapoints) is not uploaded.
+
+Before anything leaves the machine:
+
+- Every event goes through the same secret redaction and size limits the runtime log applies.
+- Paths under the session's directory are written relative to it, and your home directory becomes `~`, in file paths, commands, output and diffs.
+- The repository remote (from the session's events, or else the `origin` remote in the session's directory, read locally) is sent without credentials, and the project name is the repository's or the directory's name, never a path. The name of your home directory is not used as a project name.
+- Token usage is the session's total as [`beacon token-usage`](/cli/token-usage) counts it. Cost is sent only when the runtime reported one, never a list-price estimate.
+
+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.
+
+`--print` (or `--dry-run`) prints exactly that payload as JSON, the trace metadata and every message, and sends nothing:
+
+```json
+{
+ "external_id": "claude_code:5f0c1d2e-...",
+ "trace": { "schema_version": "beacon.share.v1", "agent_id": "claude_code", "title": "Fix the login test", "...": "..." },
+ "messages": [ { "id": "...", "order": 1, "role": "user", "text": "...", "parts": [ ... ] } ]
+}
+```
+
+## Visibility
+
+| `--visibility` | Who can view the trace |
+|----------------|------------------------|
+| `direct` | Anyone with the link. It is not listed anywhere. The default for a new trace |
+| `private` | Only you |
+| `public` | Anyone. The trace is listed in Discover |
+
+A public share asks for confirmation. Without a terminal to ask on, it is refused unless you pass `--yes`.
+
+Sharing a session again updates the same trace: each session has one stable external id (`<runtime>:<session-id>`), and every message has a stable id, so nothing is duplicated. A re-share keeps the trace's visibility unless you pass `--visibility`. Change a trace's visibility by sharing it again with `--visibility`, or from the beacon.sh dashboard, where you can also delete it.
+
+## Refresh
+
+`beacon share refresh` uploads only the messages a shared session has gained since it was last uploaded. beacon.sh reports the last message it has, and the messages after it are sent; when that message is not in the session as Beacon reads it now, every message is re-sent, which changes nothing that was already there. The trace's visibility is not changed.
+
+```bash
+beacon share refresh claude_code:5f0c1d2e-aaaa-4bbb-8ccc-000000000001
+beacon share refresh 5f0c1d2e
+beacon share refresh # the most recent session in this directory
+```
+
+## Credentials
+
+`beacon share` uses, in this order:
+
+1. A Beacon API key passed with `--key` (`bcn_api_...`).
+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.
+
+## Local record
+
+After an upload, `beacon share` writes one `session.shared` event to the runtime log, in the session's own timeline. It carries the link, the visibility and when the session was shared (and refreshed), so [`beacon endpoint traces list --state shared`](/cli/endpoint-traces) and the local dashboard show the session as shared. The event is marked `event.fidelity=inferred` and has no collection method, because no runtime reported it. It is not itself uploaded with the trace.
+
+## Output
+
+The link goes to stdout and a summary to stderr. `--json` prints one document:
+
+```json
+{"ok":true,"data":{"trace_id":"k3x...","external_id":"claude_code:5f0c1d2e-...","shared_url":"https://beacon.sh/s/k3x...","visibility":"direct","agent_id":"claude_code","message_count":42,"uploaded":42}}
+```
+
+`uploaded` is how many messages this run sent. On failure, `--json` prints `{"ok":false,"error":"..."}` and the command exits non-zero.
+
+## Flags
+
+| Flag | Description |
+|------|-------------|
+| `--session <id>` | Session id or unique prefix |
+| `--source-path <path>` | The session's file in its runtime's store |
+| `--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) |
+| `--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 |
+| `--limit <n>` | With `--list`, the most sessions to show |
+| `--print`, `--dry-run` | Print the payload and send nothing |
+| `--yes` | Share publicly without asking |
+| `--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 |
+
+`refresh` takes `--harness`, `--cwd`, `--title`, `--key`, `--auth-url`, `--print`, `--json`, `--store-dir` and `--log-path`.
diff --git a/docs/docs.json b/docs/docs.json
index c9f8eeec..edbe81c1 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -372,6 +372,7 @@
]
},
"cli/handoff",
+ "cli/share",
"cli/lenses",
"cli/git",
"cli/token-usage",