Skip to content

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

Share the session an agent runs inside with beacon share --current

Claudec3fc84a42d9b
diff --git a/CLAUDE.md b/CLAUDE.md
index 48dea651..60a3fc80 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -69,7 +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.
+- 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`.
- 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-hooks/cmd/active_session_test.go b/cli/beacon-hooks/cmd/active_session_test.go
new file mode 100644
index 00000000..6b990392
--- /dev/null
+++ b/cli/beacon-hooks/cmd/active_session_test.go
@@ -0,0 +1,86 @@
+package cmd
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/activesession"
+)
+
+func TestSessionStartRecordsTheActiveSession(t *testing.T) {
+ setupHookConfigDirs(t)
+ platformFlag = "claude"
+ t.Cleanup(func() { platformFlag = "claude" })
+ dir := t.TempDir()
+ t.Setenv("BEACON_ENDPOINT_MODE", "1")
+ t.Setenv("BEACON_ENDPOINT_LOG", filepath.Join(dir, "runtime.jsonl"))
+ record := filepath.Join(dir, "endpoint", activesession.FileName)
+ t.Setenv(activesession.PathEnv, record)
+
+ runHookWithInput(t, runSessionStart, map[string]interface{}{
+ "hook_event_name": "SessionStart",
+ "session_id": "11111111-2222-3333-4444-555555555555",
+ "cwd": "/work/project",
+ })
+ got, ok := activesession.Lookup(record, "claude_code", "/work/project", 0, time.Now())
+ if !ok || got.SessionID != "11111111-2222-3333-4444-555555555555" {
+ t.Fatalf("active session = %+v, %v", got, ok)
+ }
+}
+
+func TestSessionStartExportsTheSessionToClaudeEnvFile(t *testing.T) {
+ setupHookConfigDirs(t)
+ platformFlag = "claude"
+ t.Cleanup(func() { platformFlag = "claude" })
+ dir := t.TempDir()
+ t.Setenv("BEACON_ENDPOINT_MODE", "1")
+ t.Setenv("BEACON_ENDPOINT_LOG", filepath.Join(dir, "runtime.jsonl"))
+ envFile := filepath.Join(dir, "claude-env.sh")
+ if err := os.WriteFile(envFile, []byte("export NODE_ENV=production\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ t.Setenv("CLAUDE_ENV_FILE", envFile)
+
+ runHookWithInput(t, runSessionStart, map[string]interface{}{
+ "hook_event_name": "SessionStart",
+ "session_id": "abc-123",
+ "cwd": "/work/project",
+ })
+ data, _ := os.ReadFile(envFile)
+ want := "export NODE_ENV=production\nexport BEACON_SESSION_ID=abc-123\nexport BEACON_HARNESS=claude_code\n"
+ if string(data) != want {
+ t.Fatalf("env file = %q, want %q", data, want)
+ }
+
+ // A session id that is not a plain identifier is never written into shell code.
+ runHookWithInput(t, runSessionStart, map[string]interface{}{
+ "hook_event_name": "SessionStart",
+ "session_id": "x; rm -rf ~",
+ "cwd": "/work/project",
+ })
+ if after, _ := os.ReadFile(envFile); string(after) != want {
+ t.Fatalf("unsafe id written: %q", after)
+ }
+}
+
+func TestSessionStartLeavesClaudeEnvFileAloneOnOtherRuntimes(t *testing.T) {
+ setupHookConfigDirs(t)
+ platformFlag = "qwen"
+ t.Cleanup(func() { platformFlag = "claude" })
+ dir := t.TempDir()
+ t.Setenv("BEACON_ENDPOINT_MODE", "1")
+ t.Setenv("BEACON_ENDPOINT_LOG", filepath.Join(dir, "runtime.jsonl"))
+ envFile := filepath.Join(dir, "claude-env.sh")
+ t.Setenv("CLAUDE_ENV_FILE", envFile)
+
+ runHookWithInput(t, runSessionStart, map[string]interface{}{
+ "hook_event_name": "SessionStart",
+ "session_id": "q-1",
+ "cwd": "/work/project",
+ })
+ if _, err := os.Stat(envFile); !os.IsNotExist(err) {
+ t.Fatalf("env file written on qwen: %v", err)
+ }
+}
diff --git a/cli/beacon-hooks/cmd/main_test.go b/cli/beacon-hooks/cmd/main_test.go
new file mode 100644
index 00000000..6e11e486
--- /dev/null
+++ b/cli/beacon-hooks/cmd/main_test.go
@@ -0,0 +1,24 @@
+package cmd
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/activesession"
+)
+
+// TestMain keeps the active-session record every endpoint event updates out of the real home
+// directory; tests that check it point BEACON_ACTIVE_SESSIONS_FILE somewhere of their own.
+func TestMain(m *testing.M) {
+ dir, err := os.MkdirTemp("", "beacon-hooks-active-")
+ if err != nil {
+ panic(err)
+ }
+ os.Setenv(activesession.PathEnv, filepath.Join(dir, activesession.FileName))
+ // A suite run from inside a Claude Code session must not append to that session's env file.
+ os.Unsetenv("CLAUDE_ENV_FILE")
+ code := m.Run()
+ os.RemoveAll(dir)
+ os.Exit(code)
+}
diff --git a/cli/beacon-hooks/cmd/session_start.go b/cli/beacon-hooks/cmd/session_start.go
index ab8b4047..d0fbbbb4 100644
--- a/cli/beacon-hooks/cmd/session_start.go
+++ b/cli/beacon-hooks/cmd/session_start.go
@@ -2,6 +2,9 @@ package cmd
import (
"fmt"
+ "os"
+ "regexp"
+ "strings"
"github.com/spf13/cobra"
@@ -9,6 +12,7 @@ import (
"github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/config"
"github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/logging"
"github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/state"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
)
var sessionStartCmd = &cobra.Command{
@@ -69,5 +73,39 @@ func runSessionStart(cmd *cobra.Command, args []string) {
logger.Info("Session initialized", "session_id", sessionID, "platform", platformFlag)
emitHookEvent(logger, "session.started", "session", "info", "Agent session started", input, sessionFields(sessionID, input))
+ if err := exportClaudeSessionEnv(sessionID); err != nil {
+ logger.Warn("Failed to export the session id to CLAUDE_ENV_FILE", "error", err.Error())
+ }
outputJSON(emptyResponse)
}
+
+// claudeEnvSessionID is the shape of session id written to CLAUDE_ENV_FILE. The file is run as shell
+// code before every Bash command, so anything outside this set is refused rather than quoted.
+var claudeEnvSessionID = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$`)
+
+// exportClaudeSessionEnv appends BEACON_SESSION_ID and BEACON_HARNESS to the file Claude Code names
+// in CLAUDE_ENV_FILE, so the shell commands an agent runs later in the session -- `beacon share
+// --current` among them -- know which session they belong to.
+//
+// Claude Code documents CLAUDE_ENV_FILE for SessionStart hooks only: the hook appends `export`
+// lines and Claude Code runs the file before each Bash command. Appending keeps what other hooks
+// wrote, and a later SessionStart (a /clear starts a new session) appends a newer value that
+// overrides the earlier one. Other runtimes and a missing variable leave everything untouched.
+func exportClaudeSessionEnv(sessionID string) error {
+ if asymptoteobserve.NormalizeHarnessName(platformFlag) != "claude_code" {
+ return nil
+ }
+ path := strings.TrimSpace(os.Getenv("CLAUDE_ENV_FILE"))
+ if path == "" || !claudeEnvSessionID.MatchString(sessionID) {
+ return nil
+ }
+ f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
+ if err != nil {
+ return err
+ }
+ _, werr := fmt.Fprintf(f, "export BEACON_SESSION_ID=%s\nexport BEACON_HARNESS=claude_code\n", sessionID)
+ if cerr := f.Close(); werr == nil {
+ werr = cerr
+ }
+ return werr
+}
diff --git a/cli/beacon-hooks/internal/logging/logging.go b/cli/beacon-hooks/internal/logging/logging.go
index 9d2e70e5..1529db5a 100644
--- a/cli/beacon-hooks/internal/logging/logging.go
+++ b/cli/beacon-hooks/internal/logging/logging.go
@@ -15,6 +15,7 @@ import (
"github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/config"
"github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/activesession"
"github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/filelock"
)
@@ -136,9 +137,30 @@ func (l *Logger) EndpointEventWithFidelity(action, category, severity, message,
reportEndpointWriteFailure(os.Stderr, l.platform, path, err)
return err
}
+ recordActiveSession(event)
return nil
}
+// recordActiveSession notes the event's session as the one its runtime is running in its working
+// directory, for `beacon share --current`. It is a local file write and never fails the hook: the
+// record is a convenience, the event above is what matters. Nothing here touches the network.
+func recordActiveSession(event map[string]interface{}) {
+ session, _ := event["session"].(map[string]interface{})
+ harness, _ := event["harness"].(map[string]interface{})
+ if session == nil || harness == nil {
+ return
+ }
+ id, _ := session["id"].(string)
+ dir, _ := session["working_directory"].(string)
+ name, _ := harness["name"].(string)
+ if id == "" || dir == "" || name == "" {
+ return
+ }
+ // Silent on failure: stderr is shown to the person on some runtimes, and a missing record
+ // only means `beacon share --current` falls back to the newest session in the directory.
+ _ = activesession.Record(activesession.DefaultPath(), name, id, dir, time.Now())
+}
+
// reportedWriteFailures remembers which runtime log paths this process has already explained a
// write failure for, so the explanation is printed once per path rather than once per event. One
// hook invocation can emit several events -- a post-tool hook records the tool result, the file
diff --git a/cli/beacon-hooks/internal/logging/main_test.go b/cli/beacon-hooks/internal/logging/main_test.go
new file mode 100644
index 00000000..3005f2f7
--- /dev/null
+++ b/cli/beacon-hooks/internal/logging/main_test.go
@@ -0,0 +1,22 @@
+package logging
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/activesession"
+)
+
+// TestMain keeps the active-session record every endpoint event updates out of the real home
+// directory; tests that check it point BEACON_ACTIVE_SESSIONS_FILE somewhere of their own.
+func TestMain(m *testing.M) {
+ dir, err := os.MkdirTemp("", "beacon-hooks-active-")
+ if err != nil {
+ panic(err)
+ }
+ os.Setenv(activesession.PathEnv, filepath.Join(dir, activesession.FileName))
+ code := m.Run()
+ os.RemoveAll(dir)
+ os.Exit(code)
+}
diff --git a/cli/beacon/cmd/share.go b/cli/beacon/cmd/share.go
index d22b1387..f41eaf34 100644
--- a/cli/beacon/cmd/share.go
+++ b/cli/beacon/cmd/share.go
@@ -25,6 +25,7 @@ import (
"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"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/activesession"
)
// `beacon share` publishes one local agent session as a shared trace on beacon.sh. It is the
@@ -49,8 +50,22 @@ var (
shareStdin io.Reader = os.Stdin
// shareGitRemote reads the remote of the repository a session ran in, best effort.
shareGitRemote = gitRemoteForDir
+ // shareActiveSessionsPath is the hooks' record of each runtime's current session per directory.
+ shareActiveSessionsPath = activesession.DefaultPath
)
+// Environment a runtime's shell commands carry to name the session they run in. Beacon's Claude
+// Code SessionStart hook writes both into CLAUDE_ENV_FILE; any other launcher may set them too.
+const (
+ shareSessionEnv = "BEACON_SESSION_ID"
+ shareHarnessEnv = "BEACON_HARNESS"
+)
+
+// shareActiveMaxAge is how recently a hook must have seen a session for --current to take it from
+// the active-session record. An agent that is running reports on every tool call, so a day is
+// generous; anything older is more likely a session that has since ended.
+const shareActiveMaxAge = 24 * time.Hour
+
type shareOptions struct {
session string
sourcePath string
@@ -61,6 +76,7 @@ type shareOptions struct {
key string
authURL string
jsonOutput bool
+ current bool
list bool
print bool
dryRun bool
@@ -77,8 +93,11 @@ var shareCmd = &cobra.Command{
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
+With no selector (or --current) the session is the one this command runs inside: the session
+named by BEACON_SESSION_ID (and BEACON_HARNESS), which Beacon's Claude Code hook exports to the
+agent's shell; otherwise the session a Beacon hook last saw in this directory; otherwise the most
+recent session in this directory. --harness narrows every step to one runtime. --session,
+--source-path or --cwd names another session; --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
@@ -103,7 +122,8 @@ var shareRefreshCmd = &cobra.Command{
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.
+it) or a session id or unique prefix; without one, the session it runs inside, found the way
+` + "`beacon share --current`" + ` finds it.
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.`,
@@ -134,10 +154,11 @@ func init() {
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.current, "current", false, "Share the session this command runs inside (the default with no other selector)")
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")
+ shareCmd.MarkFlagsMutuallyExclusive("session", "source-path", "cwd", "current")
}
// shareJSONErrors also reports a failure as {"ok":false,...} on stdout under --json, so a script
@@ -158,6 +179,8 @@ type shareResult struct {
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"`
+ // SelectedBy says how the session was chosen: session, source_path, env, active or recent.
+ SelectedBy string `json:"selected_by,omitempty"`
}
// sharePayload is what --print shows: the trace metadata of the PUT request and every message the
@@ -225,6 +248,7 @@ func runShare(cmd *cobra.Command) error {
AgentID: payload.Trace.AgentID,
MessageCount: uploaded.MessageCount,
Uploaded: len(payload.Messages),
+ SelectedBy: subject.selectedBy,
}
if uploaded.Batches == 0 {
result.MessageCount = trace.MessageCount
@@ -295,6 +319,7 @@ func runShareRefresh(cmd *cobra.Command, args []string) error {
AgentID: payload.Trace.AgentID,
MessageCount: state.MessageCount,
Uploaded: len(pending),
+ SelectedBy: subject.selectedBy,
}
if uploaded.Batches > 0 {
result.MessageCount = uploaded.MessageCount
@@ -329,8 +354,8 @@ func validateShareFlags(cmd *cobra.Command) error {
}
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.session != "" || shareOpts.sourcePath != "" || shareOpts.current:
+ 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")
}
@@ -391,6 +416,8 @@ type shareSubject struct {
session handoff.Session
fromLog bool
logEvents []schema.Event
+ // selectedBy says how the session was chosen (see shareResult.SelectedBy).
+ selectedBy string
}
func shareSourceNote(subject shareSubject) string {
@@ -410,45 +437,93 @@ func resolveShareSubject(harness, id string) (shareSubject, error) {
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
+ subject, err := resolveShareID(sources, harness, id)
+ subject.selectedBy = "session"
+ return subject, err
case strings.TrimSpace(shareOpts.sourcePath) != "":
- return resolveShareSourcePath(sources, harness, shareOpts.sourcePath)
+ subject, err := resolveShareSourcePath(sources, harness, shareOpts.sourcePath)
+ subject.selectedBy = "source_path"
+ return subject, err
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)
+ return resolveShareCurrent(sources, harness)
+ }
+}
+
+// resolveShareID finds a session by id or unique prefix: in the runtimes' stores, then in the
+// runtime log.
+func resolveShareID(sources []handoff.Source, harness, id string) (shareSubject, error) {
+ 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
+}
+
+// resolveShareCurrent finds the session this command runs inside, in order:
+//
+// 1. BEACON_SESSION_ID (with BEACON_HARNESS), which the Claude Code hook exports to the agent's
+// shell. Skipped under --cwd, which names another directory, and when --harness names another
+// runtime (a Codex started from a Claude Code shell inherits Claude's variables). An id that is
+// set but cannot be found is an error rather than a reason to share some other session.
+// 2. The session a Beacon hook last saw in the directory, from the active-session record.
+// 3. The most recent session in the directory.
+func resolveShareCurrent(sources []handoff.Source, harness string) (shareSubject, error) {
+ dir, err := shareDirectory()
+ if err != nil {
+ return shareSubject{}, err
+ }
+ if strings.TrimSpace(shareOpts.cwd) == "" {
+ if id := strings.TrimSpace(shareGetenv(shareSessionEnv)); id != "" {
+ envHarness, herr := handoff.ParseHarness(shareGetenv(shareHarnessEnv))
+ if herr == nil && (harness == "" || envHarness == "" || envHarness == harness) {
+ if envHarness == "" {
+ envHarness = harness
+ }
+ subject, err := resolveShareID(sources, envHarness, id)
+ if err != nil {
+ return shareSubject{}, fmt.Errorf("%s=%s names this session, but it cannot be read yet: %w", shareSessionEnv, id, err)
+ }
+ subject.selectedBy = "env"
+ return subject, nil
+ }
}
- // 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
+ }
+ if entryHarness, entryID, ok := shareActiveSession(dir, harness); ok {
+ // A record whose session cannot be read (a runtime Beacon reads only from the log, whose
+ // events have rotated away) falls through to the directory's most recent session.
+ if subject, err := resolveShareID(sources, entryHarness, entryID); err == nil {
+ subject.selectedBy = "active"
+ return subject, nil
}
- return resolveShareLog(session)
}
+ candidates, err := shareCandidates(sources, harness, dir, 1)
+ if err != nil {
+ return shareSubject{}, err
+ }
+ if len(candidates) == 0 {
+ return shareSubject{}, shareNoSessionError(sources, harness, 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, selectedBy: "recent"}, nil
+ }
+ subject, err := resolveShareLog(session)
+ subject.selectedBy = "recent"
+ return subject, err
}
func resolveShareLog(session handoff.Session) (shareSubject, error) {
@@ -495,6 +570,57 @@ func evalSymlinks(path string) string {
return resolved
}
+// shareActiveSession is the session a Beacon hook last saw in dir, limited to harness when it is
+// set, from the active-session record. Entries older than shareActiveMaxAge are ignored.
+func shareActiveSession(dir, harness string) (entryHarness, sessionID string, ok bool) {
+ entries, err := activesession.Read(shareActiveSessionsPath())
+ if err != nil {
+ return "", "", false
+ }
+ dir = activesession.CleanDir(dir)
+ now := shareNow()
+ for _, e := range entries {
+ if e.WorkingDirectory != dir || now.Sub(e.LastSeen) > shareActiveMaxAge {
+ continue
+ }
+ name, err := handoff.ParseHarness(e.Harness)
+ if err != nil || (harness != "" && name != harness) {
+ continue
+ }
+ return name, e.SessionID, true
+ }
+ return "", "", false
+}
+
+// shareNoSessionError explains that nothing ran in dir and names the most recent sessions anywhere,
+// so the next command can name one.
+func shareNoSessionError(sources []handoff.Source, harness, dir string) error {
+ msg := fmt.Sprintf("no agent session found in %s", dir)
+ stored, _ := handoff.List(sources, handoff.Filter{Harness: harness, Limit: 5})
+ logged, _ := handoff.LogSessions(shareLogPath(), handoff.Filter{Harness: harness, Limit: 5})
+ seen := map[string]bool{}
+ var all []handoff.Session
+ for _, s := range append(stored, logged...) {
+ if key := s.Harness + "\x00" + s.ID; !seen[key] {
+ seen[key] = true
+ all = append(all, s)
+ }
+ }
+ sort.SliceStable(all, func(i, j int) bool { return all[i].UpdatedAt.After(all[j].UpdatedAt) })
+ if len(all) > 5 {
+ all = all[:5]
+ }
+ if len(all) == 0 {
+ return errors.New(msg + "; Beacon has no sessions recorded yet (is `beacon endpoint install` set up for this runtime?)")
+ }
+ var b strings.Builder
+ b.WriteString(msg + "; recent sessions elsewhere (pass one with --session, or use --cwd DIR):")
+ for _, s := range all {
+ fmt.Fprintf(&b, "\n %s %s %s", s.Harness, s.ID, s.Directory)
+ }
+ return errors.New(b.String())
+}
+
// 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.
diff --git a/cli/beacon/cmd/share_current_test.go b/cli/beacon/cmd/share_current_test.go
new file mode 100644
index 00000000..c4754912
--- /dev/null
+++ b/cli/beacon/cmd/share_current_test.go
@@ -0,0 +1,134 @@
+package cmd
+
+import (
+ "encoding/json"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "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/pkg/asymptoteobserve/activesession"
+)
+
+// shareCurrentEnv adds a second, older Claude Code session and a Gemini CLI session (log only) in
+// the project directory, so each resolution step can be told apart from "most recent".
+func shareCurrentEnv(t *testing.T) *shareEnv {
+ t.Helper()
+ env := newShareEnv(t)
+ recordPath := filepath.Join(env.home, "active.json")
+ prev := shareActiveSessionsPath
+ shareActiveSessionsPath = func() string { return recordPath }
+ t.Cleanup(func() { shareActiveSessionsPath = prev })
+ gem := schema.NewEvent(schema.NewEventOptions{Action: "prompt.submitted", Category: "prompt", Harness: schema.HarnessInfo{Name: "gemini_cli", CollectionMethod: schema.CollectionMethodHook}})
+ gem.Timestamp = schema.FormatTimestamp(time.Now().Add(-time.Hour))
+ gem.Session = &schema.SessionInfo{ID: "gem-session-1", WorkingDirectory: env.projectDir}
+ gem.Prompt = &schema.PromptInfo{Text: "Add a flag"}
+ if _, err := writer.AppendEvent(gem, writer.Options{Path: env.logPath, UserMode: true}); err != nil {
+ t.Fatal(err)
+ }
+ return env
+}
+
+func sharePrintedExternalID(t *testing.T, stdout string) string {
+ t.Helper()
+ var payload sharePayload
+ if err := json.Unmarshal([]byte(stdout), &payload); err != nil {
+ t.Fatalf("payload is not JSON: %v\n%s", err, stdout)
+ }
+ return payload.ExternalID
+}
+
+func TestShareCurrentPrefersTheSessionEnvironment(t *testing.T) {
+ env := shareCurrentEnv(t)
+ t.Chdir(env.projectDir)
+ shareGetenv = func(key string) string {
+ switch key {
+ case shareSessionEnv:
+ return "gem-session-1"
+ case shareHarnessEnv:
+ return "gemini_cli"
+ }
+ return ""
+ }
+ stdout, _, err := runShareCommand(t, "--print", "--log-path", env.logPath)
+ if err != nil {
+ t.Fatalf("share: %v", err)
+ }
+ if got := sharePrintedExternalID(t, stdout); got != "gemini_cli:gem-session-1" {
+ t.Fatalf("external id = %q, want the env session", got)
+ }
+
+ // --harness naming another runtime ignores inherited variables.
+ stdout, _, err = runShareCommand(t, "--current", "--harness", "claude", "--print", "--log-path", env.logPath)
+ if err != nil {
+ t.Fatalf("share --harness claude: %v", err)
+ }
+ if got := sharePrintedExternalID(t, stdout); got != "claude_code:"+shareTestSession {
+ t.Fatalf("external id = %q, want the claude session", got)
+ }
+
+ // An env id that cannot be found is an error, never some other session.
+ shareGetenv = func(key string) string {
+ if key == shareSessionEnv {
+ return "missing-session"
+ }
+ return ""
+ }
+ if _, _, err := runShareCommand(t, "--current", "--print", "--log-path", env.logPath); err == nil || !strings.Contains(err.Error(), "BEACON_SESSION_ID=missing-session") {
+ t.Fatalf("missing env session: err = %v", err)
+ }
+}
+
+func TestShareCurrentUsesTheActiveSessionRecord(t *testing.T) {
+ env := shareCurrentEnv(t)
+ t.Chdir(env.projectDir)
+ // The Claude session is the most recent; the hook last saw Gemini here.
+ if err := activesession.Record(shareActiveSessionsPath(), "gemini_cli", "gem-session-1", env.projectDir, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ stdout, _, err := runShareCommand(t, "--current", "--print", "--log-path", env.logPath)
+ if err != nil {
+ t.Fatalf("share --current: %v", err)
+ }
+ if got := sharePrintedExternalID(t, stdout); got != "gemini_cli:gem-session-1" {
+ t.Fatalf("external id = %q, want the active session", got)
+ }
+ // A --harness hint passes over another runtime's entry.
+ stdout, _, err = runShareCommand(t, "--harness", "claude_code", "--print", "--log-path", env.logPath)
+ if err != nil {
+ t.Fatalf("share --harness: %v", err)
+ }
+ if got := sharePrintedExternalID(t, stdout); got != "claude_code:"+shareTestSession {
+ t.Fatalf("external id = %q", got)
+ }
+ // A stale entry is ignored.
+ shareNow = func() time.Time { return time.Now().Add(48 * time.Hour) }
+ t.Cleanup(func() { shareNow = time.Now })
+ stdout, _, err = runShareCommand(t, "--print", "--log-path", env.logPath)
+ if err != nil {
+ t.Fatalf("share: %v", err)
+ }
+ if got := sharePrintedExternalID(t, stdout); got != "claude_code:"+shareTestSession {
+ t.Fatalf("stale record used: %q", got)
+ }
+}
+
+func TestShareCurrentNamesCandidatesWhenNothingRanHere(t *testing.T) {
+ env := shareCurrentEnv(t)
+ empty := t.TempDir()
+ t.Chdir(empty)
+ _, _, err := runShareCommand(t, "--current", "--print", "--log-path", env.logPath)
+ if err == nil {
+ t.Fatal("want an error")
+ }
+ for _, want := range []string{"no agent session found", shareTestSession, "gem-session-1", "--session"} {
+ if !strings.Contains(err.Error(), want) {
+ t.Errorf("error %q lacks %q", err, want)
+ }
+ }
+ if _, _, err := runShareCommand(t, "--current", "--session", shareTestSession, "--print"); err == nil {
+ t.Fatal("--current with --session accepted")
+ }
+}
diff --git a/cli/beacon/cmd/share_test.go b/cli/beacon/cmd/share_test.go
index a197be5e..90fc86e2 100644
--- a/cli/beacon/cmd/share_test.go
+++ b/cli/beacon/cmd/share_test.go
@@ -323,7 +323,7 @@ func TestShareUploadsAndRecordsTheShareLocally(t *testing.T) {
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}
+ want := shareResult{TraceID: "k3xabc", ExternalID: "claude_code:" + shareTestSession, SharedURL: "https://beacon.sh/s/k3xabc", Visibility: "direct", AgentID: "claude_code", MessageCount: 4, Uploaded: 4, SelectedBy: "recent"}
if result.Data != want {
t.Fatalf("result = %+v, want %+v", result.Data, want)
}
diff --git a/docs/cli/share.mdx b/docs/cli/share.mdx
index 02d1677a..748a9d93 100644
--- a/docs/cli/share.mdx
+++ b/docs/cli/share.mdx
@@ -8,17 +8,21 @@ description: "Share a local agent session as a trace on beacon.sh"
`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 [--current | --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.
+Without a session flag, `beacon share` shares the session it runs inside (see [Sharing this session](#sharing-this-session)), and otherwise 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="From inside an agent: share this session"
+beacon share --current --harness claude_code --json
+```
+
```bash title="See what would be uploaded, without uploading it"
beacon share --print
```
@@ -29,12 +33,13 @@ Sharing is always something you ask for. Hooks, plugins and background jobs neve
| Flag | Picks |
|------|-------|
+| `--current` | The session this command runs inside. The default when no other selector is given |
| `--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).
+`--current`, `--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
@@ -43,6 +48,16 @@ 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.
+## Sharing this session
+
+An agent asked to "share this session" runs `beacon share` from its own shell, where it does not know its session id. `--current`, which is also what `beacon share` does with no selector, finds it in this order:
+
+1. **`BEACON_SESSION_ID`** (with `BEACON_HARNESS`). Beacon's Claude Code `SessionStart` hook appends `export BEACON_SESSION_ID=<id>` and `export BEACON_HARNESS=claude_code` to the file Claude Code names in `CLAUDE_ENV_FILE`, which Claude Code runs before each shell command of the session, so every command the agent runs carries its session id. Any other launcher may set the two variables too. The step is skipped under `--cwd`, and when `--harness` names another runtime, because a runtime started from a Claude Code shell inherits Claude Code's variables. An id that is set but cannot be read is an error, never a reason to share another session.
+2. **The active-session record.** Every Beacon hook notes, per runtime and working directory, the session it last saw, in `~/.beacon/endpoint/active-sessions.json` (0600 under a 0700 directory). The record holds session ids, runtime names, directories and times, never content, and nothing in it leaves the machine. It keeps at most 256 entries and drops any not seen for 14 days; `--current` uses an entry seen within the last day.
+3. **The most recent session** that ran in the directory.
+
+`--harness` narrows every step to one runtime, which matters when two runtimes worked in the same directory. When nothing ran in the directory, the error names the most recent sessions elsewhere so one can be passed with `--session`. `--json` reports how the session was chosen in `selected_by`: `env`, `active`, `recent`, `session` or `source_path`.
+
## What is uploaded
A shared trace is made of messages. Each Beacon event of the session becomes at most one message:
@@ -96,7 +111,7 @@ Sharing a session again updates the same trace: each session has one stable exte
```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
+beacon share refresh # this session, found like --current
```
## Credentials
@@ -118,7 +133,7 @@ After an upload, `beacon share` writes one `session.shared` event to the runtime
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}}
+{"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,"selected_by":"env"}}
```
`uploaded` is how many messages this run sent. On failure, `--json` prints `{"ok":false,"error":"..."}` and the command exits non-zero.
@@ -127,6 +142,7 @@ The link goes to stdout and a summary to stderr. `--json` prints one document:
| Flag | Description |
|------|-------------|
+| `--current` | The session this command runs inside (default with no other selector) |
| `--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) |
diff --git a/docs/runtimes/claude-code.mdx b/docs/runtimes/claude-code.mdx
index c3299a86..9218dcef 100644
--- a/docs/runtimes/claude-code.mdx
+++ b/docs/runtimes/claude-code.mdx
@@ -135,6 +135,8 @@ Managed-ingest privacy is a separate forwarding policy and does not switch off l
Claude Code hooks cover `SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `Stop`, `SubagentStart`, `SubagentStop`, `PermissionRequest`, and `SessionEnd`. Pre-tool matching includes common Claude tools such as `Bash`, `Edit`, `Write`, `MultiEdit`, `Read`, `Glob`, `Grep`, `WebFetch`, `WebSearch`, `Agent`, and `mcp__.*`.
+The `SessionStart` hook also appends `export BEACON_SESSION_ID=<id>` and `export BEACON_HARNESS=claude_code` to the file Claude Code names in `CLAUDE_ENV_FILE`, so the shell commands of the session know which session they belong to and [`beacon share --current`](/cli/share#sharing-this-session) can share it. Nothing else is written there, and an id that is not a plain identifier is never written.
+
The `PostToolUse` hook records an MCP tool's result on its live `mcp.tool_invoked` event, in `gen_ai.tool.call.result.content`. Claude Code rewrites the server's result before the hook sees it: an image stays an image, and text, audio, embedded resources and resource links arrive as text blocks, with audio and binary resources as notes naming the file Claude Code saved them to. Beacon stores an image as its media type, decoded size and SHA-256 rather than its bytes. Detection rules match the text blocks.
## Normalized OTLP events
diff --git a/pkg/asymptoteobserve/activesession/activesession.go b/pkg/asymptoteobserve/activesession/activesession.go
new file mode 100644
index 00000000..99e7b02c
--- /dev/null
+++ b/pkg/asymptoteobserve/activesession/activesession.go
@@ -0,0 +1,230 @@
+// Package activesession records, per runtime and working directory, the agent session a hook saw
+// last, so `beacon share --current` can name "this session" from inside an agent without being told
+// its id.
+//
+// The record is a small local file, `~/.beacon/endpoint/active-sessions.json` (0600 under a 0700
+// directory). The hook adapter writes it as a side effect of writing an event; the CLI only reads
+// it. It never leaves the machine and it holds identifiers and paths only -- a session id, a
+// harness name, a working directory and a timestamp -- never content.
+//
+// Writes are cheap enough for the hook path: the file is bounded (MaxEntries), stale entries are
+// pruned on every write (MaxAge), an entry that has not changed is only rewritten once its
+// timestamp is RefreshInterval old, and every write is an atomic rename under an advisory lock.
+package activesession
+
+import (
+ "encoding/json"
+ "errors"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/filelock"
+)
+
+const (
+ // FileName is the record's name under the endpoint base directory.
+ FileName = "active-sessions.json"
+ // PathEnv overrides where the record lives (tests, unusual homes).
+ PathEnv = "BEACON_ACTIVE_SESSIONS_FILE"
+ // MaxEntries bounds the record; the oldest entries go first.
+ MaxEntries = 256
+ // MaxAge is how long an entry is kept after it was last seen.
+ MaxAge = 14 * 24 * time.Hour
+ // RefreshInterval is how stale an unchanged entry's timestamp may get before it is rewritten.
+ RefreshInterval = time.Minute
+
+ schemaVersion = "beacon.active_sessions.v1"
+)
+
+// Entry is the session a runtime last reported in one working directory.
+type Entry struct {
+ Harness string `json:"harness"`
+ SessionID string `json:"session_id"`
+ WorkingDirectory string `json:"working_directory"`
+ LastSeen time.Time `json:"last_seen"`
+}
+
+type document struct {
+ SchemaVersion string `json:"schema_version"`
+ Sessions []Entry `json:"sessions"`
+}
+
+// DefaultPath is BEACON_ACTIVE_SESSIONS_FILE, or ~/.beacon/endpoint/active-sessions.json.
+func DefaultPath() string {
+ if p := strings.TrimSpace(os.Getenv(PathEnv)); p != "" {
+ return p
+ }
+ home, err := os.UserHomeDir()
+ if err != nil || home == "" {
+ return ""
+ }
+ return filepath.Join(home, ".beacon", "endpoint", FileName)
+}
+
+// CleanDir is the form working directories are compared in.
+func CleanDir(dir string) string {
+ dir = strings.TrimSpace(dir)
+ if dir == "" {
+ return ""
+ }
+ return filepath.Clean(dir)
+}
+
+func entryKey(harness, dir string) string { return harness + "\x00" + dir }
+
+// Read returns every entry in the record at path, newest first. A missing or unreadable record
+// reads as empty.
+func Read(path string) ([]Entry, error) {
+ doc, err := load(path)
+ if err != nil {
+ return nil, err
+ }
+ out := append([]Entry(nil), doc.Sessions...)
+ sort.SliceStable(out, func(i, j int) bool { return out[i].LastSeen.After(out[j].LastSeen) })
+ return out, nil
+}
+
+// Lookup returns the newest entry for dir, limited to harness when it is not empty, that was seen
+// within maxAge (0 for MaxAge).
+func Lookup(path, harness, dir string, maxAge time.Duration, now time.Time) (Entry, bool) {
+ entries, err := Read(path)
+ if err != nil {
+ return Entry{}, false
+ }
+ if maxAge <= 0 {
+ maxAge = MaxAge
+ }
+ dir = CleanDir(dir)
+ for _, e := range entries {
+ if e.WorkingDirectory != dir || (harness != "" && e.Harness != harness) {
+ continue
+ }
+ if now.Sub(e.LastSeen) > maxAge {
+ continue
+ }
+ return e, true
+ }
+ return Entry{}, false
+}
+
+// Record notes that harness reported session in dir at now. It is a no-op when any of the three is
+// empty, and rewrites the file only when the entry changed or its timestamp is RefreshInterval old.
+func Record(path, harness, session, dir string, now time.Time) error {
+ harness, session, dir = strings.TrimSpace(harness), strings.TrimSpace(session), CleanDir(dir)
+ if path == "" || harness == "" || session == "" || dir == "" {
+ return nil
+ }
+ return update(path, now, func(doc *document) bool {
+ for i, e := range doc.Sessions {
+ if entryKey(e.Harness, e.WorkingDirectory) != entryKey(harness, dir) {
+ continue
+ }
+ if e.SessionID == session && now.Sub(e.LastSeen) < RefreshInterval {
+ return false
+ }
+ doc.Sessions[i].SessionID = session
+ doc.Sessions[i].LastSeen = now.UTC()
+ return true
+ }
+ doc.Sessions = append(doc.Sessions, Entry{Harness: harness, SessionID: session, WorkingDirectory: dir, LastSeen: now.UTC()})
+ return true
+ })
+}
+
+func load(path string) (document, error) {
+ doc := document{SchemaVersion: schemaVersion}
+ if path == "" {
+ return doc, nil
+ }
+ data, err := os.ReadFile(path)
+ if err != nil {
+ if errors.Is(err, os.ErrNotExist) {
+ return doc, nil
+ }
+ return doc, err
+ }
+ if len(data) == 0 {
+ return doc, nil
+ }
+ if err := json.Unmarshal(data, &doc); err != nil {
+ // A damaged record is replaced rather than trusted; it holds nothing that cannot be
+ // rebuilt by the next hook.
+ return document{SchemaVersion: schemaVersion}, nil
+ }
+ doc.SchemaVersion = schemaVersion
+ return doc, nil
+}
+
+func update(path string, now time.Time, mutate func(*document) bool) error {
+ dir := filepath.Dir(path)
+ if err := os.MkdirAll(dir, 0o700); err != nil {
+ return err
+ }
+ lockFile, err := os.OpenFile(path+".lock", os.O_CREATE|os.O_RDWR, 0o600)
+ if err != nil {
+ return err
+ }
+ defer lockFile.Close()
+ lock, err := filelock.Exclusive(lockFile)
+ if err != nil {
+ return err
+ }
+ defer lock.Release()
+
+ doc, err := load(path)
+ if err != nil {
+ return err
+ }
+ changed := mutate(&doc)
+ if prune(&doc, now) {
+ changed = true
+ }
+ if !changed {
+ return nil
+ }
+ data, err := json.MarshalIndent(doc, "", " ")
+ if err != nil {
+ return err
+ }
+ tmp, err := os.CreateTemp(dir, "."+FileName+".*.tmp")
+ if err != nil {
+ return err
+ }
+ tmpName := tmp.Name()
+ defer os.Remove(tmpName)
+ if err := tmp.Chmod(0o600); err != nil {
+ tmp.Close()
+ return err
+ }
+ if _, err := tmp.Write(append(data, '\n')); err != nil {
+ tmp.Close()
+ return err
+ }
+ if err := tmp.Close(); err != nil {
+ return err
+ }
+ return os.Rename(tmpName, path)
+}
+
+// prune drops entries older than MaxAge and trims both lists to their bounds, oldest first.
+func prune(doc *document, now time.Time) bool {
+ changed := false
+ kept := doc.Sessions[:0]
+ for _, e := range doc.Sessions {
+ if now.Sub(e.LastSeen) <= MaxAge {
+ kept = append(kept, e)
+ } else {
+ changed = true
+ }
+ }
+ doc.Sessions = kept
+ if len(doc.Sessions) > MaxEntries {
+ sort.SliceStable(doc.Sessions, func(i, j int) bool { return doc.Sessions[i].LastSeen.After(doc.Sessions[j].LastSeen) })
+ doc.Sessions = doc.Sessions[:MaxEntries]
+ changed = true
+ }
+ return changed
+}
diff --git a/pkg/asymptoteobserve/activesession/activesession_test.go b/pkg/asymptoteobserve/activesession/activesession_test.go
new file mode 100644
index 00000000..666fb3e1
--- /dev/null
+++ b/pkg/asymptoteobserve/activesession/activesession_test.go
@@ -0,0 +1,125 @@
+package activesession
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "runtime"
+ "testing"
+ "time"
+)
+
+func TestRecordAndLookup(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "endpoint", FileName)
+ now := time.Date(2026, 10, 1, 12, 0, 0, 0, time.UTC)
+ if err := Record(path, "claude_code", "s1", "/work/repo/", now); err != nil {
+ t.Fatal(err)
+ }
+ if err := Record(path, "codex_cli", "c1", "/work/repo", now.Add(time.Second)); err != nil {
+ t.Fatal(err)
+ }
+ got, ok := Lookup(path, "", "/work/repo", 0, now.Add(2*time.Second))
+ if !ok || got.SessionID != "c1" {
+ t.Fatalf("newest in dir = %+v, %v", got, ok)
+ }
+ got, ok = Lookup(path, "claude_code", "/work/repo", 0, now.Add(2*time.Second))
+ if !ok || got.SessionID != "s1" {
+ t.Fatalf("claude in dir = %+v, %v", got, ok)
+ }
+ if _, ok := Lookup(path, "", "/work/other", 0, now); ok {
+ t.Fatal("other directory matched")
+ }
+ if _, ok := Lookup(path, "", "/work/repo", time.Hour, now.Add(2*time.Hour)); ok {
+ t.Fatal("stale entry matched")
+ }
+ // A new session in the same directory replaces the old one for that runtime.
+ if err := Record(path, "claude_code", "s2", "/work/repo", now.Add(3*time.Second)); err != nil {
+ t.Fatal(err)
+ }
+ entries, _ := Read(path)
+ if len(entries) != 2 || entries[0].SessionID != "s2" {
+ t.Fatalf("entries = %+v", entries)
+ }
+ if runtime.GOOS != "windows" {
+ info, err := os.Stat(path)
+ if err != nil || info.Mode().Perm() != 0o600 {
+ t.Fatalf("mode = %v, %v", info.Mode(), err)
+ }
+ dir, _ := os.Stat(filepath.Dir(path))
+ if dir.Mode().Perm() != 0o700 {
+ t.Fatalf("dir mode = %v", dir.Mode())
+ }
+ }
+}
+
+func TestRecordSkipsUnchangedWritesAndIgnoresEmptyFields(t *testing.T) {
+ path := filepath.Join(t.TempDir(), FileName)
+ now := time.Date(2026, 10, 1, 12, 0, 0, 0, time.UTC)
+ for _, args := range [][3]string{{"", "s", "/d"}, {"h", "", "/d"}, {"h", "s", ""}} {
+ if err := Record(path, args[0], args[1], args[2], now); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if _, err := os.Stat(path); !os.IsNotExist(err) {
+ t.Fatalf("record written for empty fields: %v", err)
+ }
+ if err := Record(path, "h", "s", "/d", now); err != nil {
+ t.Fatal(err)
+ }
+ before, _ := os.ReadFile(path)
+ if err := Record(path, "h", "s", "/d", now.Add(10*time.Second)); err != nil {
+ t.Fatal(err)
+ }
+ after, _ := os.ReadFile(path)
+ if string(before) != string(after) {
+ t.Fatal("unchanged entry rewritten inside the refresh interval")
+ }
+ if err := Record(path, "h", "s", "/d", now.Add(2*RefreshInterval)); err != nil {
+ t.Fatal(err)
+ }
+ entries, _ := Read(path)
+ if !entries[0].LastSeen.Equal(now.Add(2 * RefreshInterval)) {
+ t.Fatalf("last seen not refreshed: %v", entries[0].LastSeen)
+ }
+}
+
+func TestRecordPrunesAndBounds(t *testing.T) {
+ path := filepath.Join(t.TempDir(), FileName)
+ start := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
+ if err := Record(path, "h", "old", "/old", start); err != nil {
+ t.Fatal(err)
+ }
+ now := start.Add(MaxAge + time.Hour)
+ for i := 0; i < MaxEntries+10; i++ {
+ if err := Record(path, "h", "s", filepath.Join("/d", string(rune('a'+i%26)), time.Duration(i).String()), now.Add(time.Duration(i)*time.Second)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ entries, _ := Read(path)
+ if len(entries) != MaxEntries {
+ t.Fatalf("len = %d", len(entries))
+ }
+ for _, e := range entries {
+ if e.SessionID == "old" {
+ t.Fatal("stale entry kept")
+ }
+ }
+}
+
+func TestDamagedRecordIsReplaced(t *testing.T) {
+ path := filepath.Join(t.TempDir(), FileName)
+ if err := os.WriteFile(path, []byte("{not json"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if entries, err := Read(path); err != nil || len(entries) != 0 {
+ t.Fatalf("damaged read = %v, %v", entries, err)
+ }
+ if err := Record(path, "h", "s", "/d", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ var doc map[string]any
+ data, _ := os.ReadFile(path)
+ if err := json.Unmarshal(data, &doc); err != nil || doc["schema_version"] != schemaVersion {
+ t.Fatalf("doc = %s", data)
+ }
+}