Skip to content

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

Share a session as a beacon.trace.v1 trace and refresh by last event

Claudeaafc2ed0bbde
diff --git a/CLAUDE.md b/CLAUDE.md
index ed0adbc7..26236fe0 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 that is a `beacon.trace.v1` trace, the projection the dashboard uses: `BuildShareBundle` (sanitize, scrub, then `TraceEventFromEvent`/`TraceBuilder`), the wire types (`ShareTraceV1` summary body, `ShareEventsBatchV1` of `TraceEventV1`s, `ShareTraceStateV1` with `last_event_id`), `ShareExternalID` (`<harness>:<session-id>`, or a sha256 form), `ShareRelation` and `ShareEventsAfter` live in `pkg/asymptoteobserve/share.go`, and the client in `cli/beacon/internal/account/share.go` (`PUT /v1/traces/{external_id}`, `POST .../events/batch` capped at `ShareMaxEventsPerBatch`, `GET`). The chat view is derived on beacon.sh with `TraceMessages` (`pkg/asymptoteobserve/tracemessages.go`), which pairs a tool invocation and its completion by `tool_call_id` and writes a call reported twice once; messages are never uploaded. Sessions resolve through the handoff registry (store first, then the runtime log). Every event goes through `SanitizeEvent` and session-directory/home paths are rewritten in every projected field before projection, and the shared summary drops the working directory and repository path and names the project by `project.name`. `--print` shows the exact `{external_id, trace, events}` payload with no network, `public` needs confirmation (refused without a terminal unless `--yes`), a re-share upserts by stable event id, and a refresh sends only `ShareEventsAfter` the server's `last_event_id` (re-sending it and any tool call still open). 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
index e4b52d0f..e3b9653e 100644
--- a/cli/beacon/cmd/share.go
+++ b/cli/beacon/cmd/share.go
@@ -30,7 +30,8 @@ import (
// 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).
+// runtime log uses before it is projected into a beacon.trace.v1 trace
+// (asymptoteobserve.BuildShareBundle), the projection the local dashboard shows.
//
// 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
@@ -98,12 +99,13 @@ BEACON_API_KEY. Nothing is uploaded by hooks or in the background; only this com
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.
+ Short: "Upload a shared session's new events",
+ Long: `Upload the events 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
+beacon.sh reports the last event it has, and only the events after it are sent (with that event and
+any tool call still waiting for its result). 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),
@@ -149,24 +151,27 @@ func shareJSONErrors(cmd *cobra.Command, err error) error {
}
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.
+ TraceID string `json:"trace_id"`
+ ExternalID string `json:"external_id"`
+ SharedURL string `json:"shared_url"`
+ Visibility string `json:"visibility"`
+ Harness string `json:"harness"`
+ EventCount int `json:"event_count"`
+ // Uploaded is how many events this run sent; on a first share it equals the trace'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.
+// sharePayload is what --print shows: the external id the requests go to, the body of the PUT
+// request (trace) and every event the batch requests would carry (events), in order.
type sharePayload struct {
- ExternalID string `json:"external_id"`
- Trace asymptoteobserve.ShareTraceV1 `json:"trace"`
- Messages []asymptoteobserve.ShareMessageV1 `json:"messages"`
+ ExternalID string `json:"external_id"`
+ Trace asymptoteobserve.ShareTraceV1 `json:"trace"`
+ Events []asymptoteobserve.TraceEventV1 `json:"events"`
}
+// harness is the normalized runtime name a trace's summary carries.
+func (p sharePayload) harness() string { return p.Trace.Summary.Harness.Name }
+
func (o shareOptions) printOnly() bool { return o.print || o.dryRun }
func runShare(cmd *cobra.Command) error {
@@ -196,7 +201,7 @@ func runShare(cmd *cobra.Command) error {
return writeIndentedJSON(cmd.OutOrStdout(), payload)
}
if payload.Trace.Visibility == asymptoteobserve.ShareVisibilityPublic && !shareOpts.yes {
- if err := confirmPublicShare(errOut, subject.session, len(payload.Messages)); err != nil {
+ if err := confirmPublicShare(errOut, subject.session, len(payload.Events)); err != nil {
return err
}
}
@@ -205,7 +210,7 @@ func runShare(cmd *cobra.Command) error {
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))
+ fmt.Fprintf(errOut, "Sharing %s session %s (%d events)%s.\n", subject.session.Harness, subject.session.ID, len(payload.Events), shareSourceNote(subject))
}
ctx := commandContext(cmd)
if state, found, err := client.GetTrace(ctx, payload.ExternalID); err != nil {
@@ -223,21 +228,21 @@ func runShare(cmd *cobra.Command) error {
if err != nil {
return err
}
- uploaded, err := client.PutMessages(ctx, payload.ExternalID, payload.Messages)
+ uploaded, err := client.PostEvents(ctx, payload.ExternalID, asymptoteobserve.ShareEventsBatchV1{Events: payload.Events})
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)
+ return fmt.Errorf("the trace was created at %s, but uploading its events 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),
+ TraceID: trace.ID,
+ ExternalID: payload.ExternalID,
+ SharedURL: trace.URL,
+ Visibility: trace.Visibility,
+ Harness: payload.harness(),
+ EventCount: uploaded.EventCount,
+ Uploaded: len(payload.Events),
}
if uploaded.Batches == 0 {
- result.MessageCount = trace.MessageCount
+ result.EventCount = trace.EventCount
}
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)
@@ -292,26 +297,26 @@ func runShareRefresh(cmd *cobra.Command, args []string) error {
return err
}
keepSharedTitle(cmd, &payload)
- pending := messagesAfter(payload.Messages, state.LastMessageID, state.MaxOrder)
+ pending := asymptoteobserve.ShareEventsAfter(payload.Events, state.LastEventID, state.MaxNumber)
trace, err := client.PutTrace(ctx, payload.ExternalID, payload.Trace)
if err != nil {
return err
}
- uploaded, err := client.PutMessages(ctx, payload.ExternalID, pending)
+ uploaded, err := client.PostEvents(ctx, payload.ExternalID, asymptoteobserve.ShareEventsBatchV1{Events: 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),
+ TraceID: trace.ID,
+ ExternalID: payload.ExternalID,
+ SharedURL: trace.URL,
+ Visibility: trace.Visibility,
+ Harness: payload.harness(),
+ EventCount: state.EventCount,
+ Uploaded: len(pending),
}
if uploaded.Batches > 0 {
- result.MessageCount = uploaded.MessageCount
+ result.EventCount = uploaded.EventCount
}
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)
@@ -319,54 +324,6 @@ func runShareRefresh(cmd *cobra.Command, args []string) error {
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 it returns everything; callers
-// run alignShareSource first, so that happens only for a projection from the same source whose
-// earlier messages changed, where an upsert by id changes nothing.
-func messagesAfter(messages []asymptoteobserve.ShareMessageV1, lastID string, maxOrder int) []asymptoteobserve.ShareMessageV1 {
- end := -1
- if lastID != "" {
- for i, m := range messages {
- if m.ID == lastID {
- end = i
- break
- }
- }
- if end < 0 {
- return messages
- }
- } else if maxOrder > 0 && maxOrder <= len(messages) {
- end = maxOrder - 1
- } else {
- return messages
- }
- // A tool call gains its command, diff or path when its completion arrives, which updates the
- // call message in place. Re-send from the earliest call the server holds without its result,
- // and always the last message it holds; the server upserts by id, so a re-send is harmless.
- return messages[firstOpenCall(messages[:end+1], end):]
-}
-
-// firstOpenCall is the index of the earliest tool_call in uploaded that has no tool_result among
-// them, or fallback when every call is resolved.
-func firstOpenCall(uploaded []asymptoteobserve.ShareMessageV1, fallback int) int {
- resolved := map[string]bool{}
- for _, m := range uploaded {
- for _, part := range m.Parts {
- if result, ok := part.Content.(*asymptoteobserve.ShareToolResultContent); ok && result.CallID != "" {
- resolved[result.CallID] = true
- }
- }
- }
- for i, m := range uploaded {
- for _, part := range m.Parts {
- if call, ok := part.Content.(*asymptoteobserve.ShareToolCallContent); ok && call.CallID != "" && !resolved[call.CallID] {
- return i
- }
- }
- }
- return fallback
-}
-
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)
@@ -430,13 +387,13 @@ func shareDirectory() (string, error) {
return abs, nil
}
-// alignShareSource keeps a re-share or refresh on the source the trace was first built from. Message
-// ids come from event ids, and the same session read from its runtime's store and from Beacon's
-// runtime log has different event ids, so uploading the other source would add a second copy of
-// every message. When the server's last message is not in this projection, the other source is
-// tried; when neither has it, the upload is refused rather than duplicated.
+// alignShareSource keeps a re-share or refresh on the source the trace was first built from. The
+// same session read from its runtime's store and from Beacon's runtime log has different event ids,
+// so uploading the other source would add a second copy of every event. When the server's last
+// event is not in this projection, the other source is tried; when neither has it, the upload is
+// refused rather than duplicated.
func alignShareSource(subject shareSubject, payload sharePayload, state *asymptoteobserve.ShareTraceStateV1) (shareSubject, sharePayload, error) {
- if state == nil || state.LastMessageID == "" || hasShareMessage(payload.Messages, state.LastMessageID) {
+ if state == nil || state.LastEventID == "" || hasShareEvent(payload.Events, state.LastEventID) {
return subject, payload, nil
}
var other shareSubject
@@ -452,11 +409,11 @@ func alignShareSource(subject shareSubject, payload sharePayload, state *asympto
other = logSubject
}
if other.session.ID != "" {
- if otherPayload, err := buildSharePayload(other); err == nil && hasShareMessage(otherPayload.Messages, state.LastMessageID) {
+ if otherPayload, err := buildSharePayload(other); err == nil && hasShareEvent(otherPayload.Events, state.LastEventID) {
return other, otherPayload, nil
}
}
- return subject, payload, fmt.Errorf("%s on beacon.sh was built from a different copy of this session than Beacon can read now (its store and the runtime log name messages differently), so uploading it would duplicate every message; delete the shared trace and share it again to start over", payload.ExternalID)
+ return subject, payload, fmt.Errorf("%s on beacon.sh was built from a different copy of this session than Beacon can read now (its store and the runtime log name events differently), so uploading it would duplicate every event; delete the shared trace and share it again to start over", payload.ExternalID)
}
// keepSharedTitle leaves an existing trace's title alone unless --title names a new one: the
@@ -468,9 +425,9 @@ func keepSharedTitle(cmd *cobra.Command, payload *sharePayload) {
}
}
-func hasShareMessage(messages []asymptoteobserve.ShareMessageV1, id string) bool {
- for _, m := range messages {
- if m.ID == id {
+func hasShareEvent(events []asymptoteobserve.TraceEventV1, id string) bool {
+ for _, e := range events {
+ if e.ID == id {
return true
}
}
@@ -668,63 +625,84 @@ func buildSharePayload(subject shareSubject) (sharePayload, error) {
}
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 {
+ bundle := asymptoteobserve.BuildShareBundle(events, asymptoteobserve.ShareOptions{
+ WorkingDirectory: session.Directory,
+ BeaconVersion: version.GetVersion(),
+ GeneratedAt: shareNow(),
+ })
+ if len(bundle.Events) == 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
+ // Visibility is set only when the person names one, so a re-share keeps the trace's own.
+ trace := asymptoteobserve.NewShareTrace(bundle, "")
+ if trace.Summary.Harness.Name == "" {
+ trace.Summary.Harness.Name = session.Harness
+ }
+ if name := asymptoteobserve.NormalizeHarnessName(trace.Summary.Harness.Name); name != "" {
+ trace.Summary.Harness.Name = name
}
- 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 = asymptoteobserve.ShareRemoteURL(shareGitRemote(session.Directory))
- if trace.ProjectName == "" || trace.ProjectName == filepath.Base(session.Directory) {
- if name := strings.TrimSuffix(lastURLSegment(trace.GitRemoteURL), ".git"); name != "" {
- trace.ProjectName = name
- }
- }
- }
+ shareSummaryFromSession(&trace.Summary, session)
if session.Subagent && session.ParentID != "" {
trace.RelatedTo = asymptoteobserve.ShareExternalID(session.Harness, session.ParentID)
trace.RelationshipType = asymptoteobserve.ShareRelationshipSubagent
+ } else {
+ trace.RelatedTo, trace.RelationshipType = asymptoteobserve.ShareRelation(events)
}
// 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.
+ // which the summary's 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
+ usage := asymptoteobserve.TraceUsageV1{
+ InputTokens: totals.InputTokens,
+ OutputTokens: totals.OutputTokens,
+ CacheReadInputTokens: totals.CacheReadInputTokens,
+ CacheCreationInputTokens: totals.CacheCreationInputTokens,
+ CacheCreation1hInputTokens: totals.CacheCreation1hInputTokens,
+ ReasoningOutputTokens: totals.ReasoningOutputTokens,
+ CostUSD: totals.CostUSD,
+ }
+ trace.Summary.TokenUsage = nil
+ if usage != (asymptoteobserve.TraceUsageV1{}) {
+ trace.Summary.TokenUsage = &usage
}
return sharePayload{
ExternalID: asymptoteobserve.ShareExternalID(session.Harness, session.ID),
Trace: trace,
- Messages: messages,
+ Events: bundle.Events,
}, nil
}
+// shareSummaryFromSession fills what the events did not say from the session listing and the
+// repository it ran in: its branch, its origin remote (credentials removed), and the project's name
+// from that remote when the events named only the directory.
+func shareSummaryFromSession(summary *asymptoteobserve.TraceSummaryV1, session handoff.Session) {
+ repo := summary.Repository
+ if repo == nil {
+ repo = &asymptoteobserve.TraceRepositoryV1{}
+ }
+ if repo.Branch == "" {
+ repo.Branch = asymptoteobserve.ShareBranch(session.Branch)
+ }
+ if repo.RemoteURL == "" && session.Directory != "" {
+ repo.RemoteURL = asymptoteobserve.ShareRemoteURL(shareGitRemote(session.Directory))
+ if summary.Project == nil || summary.Project.Name == filepath.Base(session.Directory) {
+ if name := strings.TrimSuffix(lastURLSegment(repo.RemoteURL), ".git"); name != "" {
+ summary.Project = &asymptoteobserve.TraceProjectV1{Name: name}
+ }
+ }
+ }
+ if *repo == (asymptoteobserve.TraceRepositoryV1{}) {
+ summary.Repository = nil
+ } else {
+ summary.Repository = repo
+ }
+}
+
func shareEventTime(event schema.Event) time.Time {
ts, err := schema.ParseTimestamp(event.Timestamp)
if err != nil {
@@ -756,11 +734,11 @@ func gitRemoteForDir(dir string) string {
return strings.TrimSpace(string(out))
}
-func confirmPublicShare(errOut io.Writer, session handoff.Session, messages int) error {
+func confirmPublicShare(errOut io.Writer, session handoff.Session, events 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)
+ fmt.Fprintf(errOut, "Share %s session %s (%d events) publicly? Anyone can find and read it in Discover. [y/N] ", session.Harness, session.ID, events)
if !confirmNo(shareStdin) {
return errors.New("not shared")
}
@@ -813,7 +791,7 @@ func shareRecordEvent(session handoff.Session, result shareResult, refresh bool,
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),
+ Message: fmt.Sprintf("session %s to beacon.sh (%s, %d events)", verb, result.Visibility, result.EventCount),
})
event.Timestamp = schema.FormatTimestamp(now)
event.Session = &schema.SessionInfo{ID: session.ID, WorkingDirectory: session.Directory}
@@ -837,6 +815,6 @@ func printShareResult(cmd *cobra.Command, result shareResult) error {
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)
+ fmt.Fprintf(cmd.ErrOrStderr(), "%s, %d events (%d sent). External id: %s\n", result.Visibility, result.EventCount, result.Uploaded, result.ExternalID)
return nil
}
diff --git a/cli/beacon/cmd/share_test.go b/cli/beacon/cmd/share_test.go
index d2ce7e8c..28c9434d 100644
--- a/cli/beacon/cmd/share_test.go
+++ b/cli/beacon/cmd/share_test.go
@@ -153,14 +153,24 @@ func TestShareDryRunPrintsThePayloadWithoutNetwork(t *testing.T) {
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.ExternalID != "claude_code:"+shareTestSession || payload.Trace.Summary.Harness.Name != "claude_code" {
+ t.Fatalf("identity = %q %q", payload.ExternalID, payload.Trace.Summary.Harness.Name)
}
- if payload.Trace.Title != "Fix the login test" || payload.Trace.Visibility != "" || payload.Trace.ProjectName != "app" {
+ if payload.Trace.SchemaVersion != asymptoteobserve.TraceSchemaVersion || payload.Trace.Title != "Fix the login test" || payload.Trace.Visibility != "" ||
+ payload.Trace.Summary.Project == nil || payload.Trace.Summary.Project.Name != "app" {
t.Fatalf("trace = %+v", payload.Trace)
}
- if len(payload.Messages) != 4 {
- t.Fatalf("messages = %d: %s", len(payload.Messages), stdout)
+ if len(payload.Events) != 4 {
+ t.Fatalf("events = %d: %s", len(payload.Events), stdout)
+ }
+ for i, event := range payload.Events {
+ if event.Number != i+1 || event.ID == "" {
+ t.Fatalf("event %d = %+v", i, event)
+ }
+ }
+ var raw map[string]json.RawMessage
+ if err := json.Unmarshal([]byte(stdout), &raw); err != nil || raw["trace"] == nil || raw["events"] == nil {
+ t.Fatalf("payload keys = %v (err %v)", raw, err)
}
if strings.Contains(stdout, env.home) {
t.Fatalf("the payload names the local home directory:\n%s", stdout)
@@ -173,8 +183,16 @@ func TestShareDryRunPrintsThePayloadWithoutNetwork(t *testing.T) {
}
// --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)
+ var second sharePayload
+ if err != nil || json.Unmarshal([]byte(again), &second) != nil {
+ t.Fatalf("--dry-run --session prefix: %v\n%s", err, again)
+ }
+ // Only the generation time differs between two runs.
+ payload.Trace.Provenance.GeneratedAt, second.Trace.Provenance.GeneratedAt = "", ""
+ first, _ := json.Marshal(payload)
+ repeat, _ := json.Marshal(second)
+ if string(first) != string(repeat) {
+ t.Fatalf("--dry-run --session prefix differs:\n%s\n%s", first, repeat)
}
}
@@ -205,7 +223,7 @@ func TestShareResolvesSessionsBySourcePathAndFromTheLog(t *testing.T) {
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 {
+ if err := json.Unmarshal([]byte(stdout), &payload); err != nil || payload.ExternalID != "gemini_cli:gem-session-1" || len(payload.Events) != 1 {
t.Fatalf("log payload = %+v (err %v)", payload, err)
}
@@ -234,7 +252,7 @@ type fakeShareServer struct {
mu sync.Mutex
server *httptest.Server
trace *asymptoteobserve.ShareTraceV1
- messages []asymptoteobserve.ShareMessageV1
+ events []asymptoteobserve.TraceEventV1
requests []string
auth map[string]bool
}
@@ -262,40 +280,40 @@ func newFakeShareServer(t *testing.T) *fakeShareServer {
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"):
+ fmt.Fprintf(w, `{"id":"k3xabc","external_id":%q,"url":"https://beacon.sh/s/k3xabc","visibility":%q,"event_count":%d,"created":%v}`, id, trace.Visibility, len(f.events), created)
+ case r.Method == http.MethodPost && strings.HasSuffix(id, "/events/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
+ var batch asymptoteobserve.ShareEventsBatchV1
_ = json.Unmarshal(data, &batch)
- for _, m := range batch.Messages {
+ for _, e := range batch.Events {
replaced := false
- for i := range f.messages {
- if f.messages[i].ID == m.ID {
- f.messages[i], replaced = m, true
+ for i := range f.events {
+ if f.events[i].ID == e.ID {
+ f.events[i], replaced = e, true
}
}
if !replaced {
- f.messages = append(f.messages, m)
+ f.events = append(f.events, e)
}
}
- fmt.Fprintf(w, `{"accepted":%d,"message_count":%d}`, len(batch.Messages), len(f.messages))
+ fmt.Fprintf(w, `{"upserted":%d,"event_count":%d}`, len(batch.Events), len(f.events))
case r.Method == http.MethodGet:
if f.trace == nil {
http.NotFound(w, r)
return
}
- last, maxOrder := "", 0
- for _, m := range f.messages {
- if m.Order > maxOrder {
- last, maxOrder = m.ID, m.Order
+ last, maxNumber := "", 0
+ for _, e := range f.events {
+ if e.Number > maxNumber {
+ last, maxNumber = e.ID, e.Number
}
}
- 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)
+ fmt.Fprintf(w, `{"id":"k3xabc","url":"https://beacon.sh/s/k3xabc","visibility":%q,"event_count":%d,"last_event_id":%q,"max_number":%d}`, f.trace.Visibility, len(f.events), last, maxNumber)
default:
http.NotFound(w, r)
}
@@ -326,15 +344,15 @@ 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", Harness: "claude_code", EventCount: 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.auth["Bearer bcn_cli_secret_token"] || len(srv.events) != 4 || srv.trace.SchemaVersion != asymptoteobserve.TraceSchemaVersion {
+ t.Fatalf("server saw auth=%v events=%d trace=%+v", srv.auth, len(srv.events), srv.trace)
}
if srv.trace.Visibility != "" && srv.trace.Visibility != "direct" {
t.Fatalf("visibility sent = %q", srv.trace.Visibility)
@@ -364,20 +382,20 @@ func TestShareUploadsAndRecordsTheShareLocally(t *testing.T) {
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))
+ if len(srv.events) != 4 {
+ t.Fatalf("re-share duplicated events: %d", len(srv.events))
}
// A refresh sends what the server does not have, plus the call it holds without a result
// (the prompt and the Bash call are on the server; the call is re-sent with its result).
srv.mu.Lock()
- srv.messages = srv.messages[:2]
+ srv.events = srv.events[: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 != 3 || result.Data.MessageCount != 4 {
+ if err := json.Unmarshal([]byte(stdout), &result); err != nil || result.Data.Uploaded != 3 || result.Data.EventCount != 4 {
t.Fatalf("refresh result = %s (err %v)", stdout, err)
}
}
@@ -461,27 +479,6 @@ func TestShareRefreshParsesExternalIDs(t *testing.T) {
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) != 2 || got[0].ID != "b" {
- t.Fatalf("messagesAfter should resend the last uploaded message: %+v", got)
- }
- // A call uploaded before its result arrived is re-sent so the completion's command and diff
- // reach the server.
- call := func(id, callID string) asymptoteobserve.ShareMessageV1 {
- return asymptoteobserve.ShareMessageV1{ID: id, Parts: []asymptoteobserve.SharePartV1{{Type: asymptoteobserve.SharePartToolCall, Content: &asymptoteobserve.ShareToolCallContent{CallID: callID}}}}
- }
- result := func(id, callID string) asymptoteobserve.ShareMessageV1 {
- return asymptoteobserve.ShareMessageV1{ID: id, Parts: []asymptoteobserve.SharePartV1{{Type: asymptoteobserve.SharePartToolResult, Content: &asymptoteobserve.ShareToolResultContent{CallID: callID}}}}
- }
- msgs := []asymptoteobserve.ShareMessageV1{call("c1", "t1"), result("r1", "t1"), call("c2", "t2"), {ID: "text"}, result("r2", "t2"), {ID: "later"}}
- if got := messagesAfter(msgs, "text", 0); len(got) != 4 || got[0].ID != "c2" {
- t.Fatalf("open call not re-sent: %+v", got)
- }
- if got := messagesAfter(msgs, "r2", 0); len(got) != 2 || got[0].ID != "r2" {
- t.Fatalf("resolved calls should not be re-sent: %+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)
- }
}
func TestShareLeavesALocalGitRemoteOut(t *testing.T) {
@@ -496,13 +493,13 @@ func TestShareLeavesALocalGitRemoteOut(t *testing.T) {
if err := json.Unmarshal([]byte(stdout), &payload); err != nil {
t.Fatal(err)
}
- if payload.Trace.GitRemoteURL != "" || strings.Contains(stdout, env.home) {
+ if payload.Trace.Summary.Repository != nil || strings.Contains(stdout, env.home) {
t.Fatalf("remote %q leaked into the payload: %+v", remote, payload.Trace)
}
}
shareGitRemote = func(string) string { return "https://[email protected]/acme/app.git" }
stdout, _, err := runShareCommand(t, "--cwd", env.projectDir, "--print", "--log-path", env.logPath)
- if err != nil || !strings.Contains(stdout, `"git_remote_url": "https://github.com/acme/app.git"`) {
+ if err != nil || !strings.Contains(stdout, `"remote_url": "https://github.com/acme/app.git"`) {
t.Fatalf("network remote: err=%v\n%s", err, stdout)
}
}
@@ -531,11 +528,11 @@ func TestShareRefreshRefusesToDuplicateFromAnotherSource(t *testing.T) {
}
}
_, _, err := runShareCommand(t, "refresh", "claude_code:"+shareTestSession, "--log-path", env.logPath)
- if err == nil || !strings.Contains(err.Error(), "duplicate every message") {
+ if err == nil || !strings.Contains(err.Error(), "duplicate every event") {
t.Fatalf("refresh err = %v", err)
}
- if len(srv.messages) != 4 {
- t.Fatalf("server holds %d messages after a refused refresh", len(srv.messages))
+ if len(srv.events) != 4 {
+ t.Fatalf("server holds %d events after a refused refresh", len(srv.events))
}
}
@@ -595,12 +592,38 @@ func TestShareAlignSwitchesFromTheLogToTheStore(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- state := &asymptoteobserve.ShareTraceStateV1{LastMessageID: stored.Messages[len(stored.Messages)-1].ID}
+ state := &asymptoteobserve.ShareTraceStateV1{LastEventID: stored.Events[len(stored.Events)-1].ID}
subject, payload, err := alignShareSource(logSubject, logPayload, state)
if err != nil {
t.Fatalf("align: %v", err)
}
- if subject.fromLog || !hasShareMessage(payload.Messages, state.LastMessageID) {
+ if subject.fromLog || !hasShareEvent(payload.Events, state.LastEventID) {
t.Fatalf("did not switch to the store copy: fromLog=%v", subject.fromLog)
}
}
+
+func TestSharePayloadRelatesAHandoff(t *testing.T) {
+ env := newShareEnv(t)
+ events := shareFixtureEvents(env.projectDir)
+ handoffEvent := events[0]
+ handoffEvent.Event.Action = "session.handoff"
+ handoffEvent.Event.Category = "session"
+ handoffEvent.Prompt = nil
+ handoffEvent.Handoff = &schema.HandoffInfo{SourceHarness: "codex", SourceSessionID: "rollout-1"}
+ stubHandoffSources(t, stubHandoffSource{
+ harness: handoff.HarnessClaude,
+ sessions: []handoff.Session{{Harness: handoff.HarnessClaude, ID: shareTestSession, Directory: env.projectDir, UpdatedAt: time.Now()}},
+ events: append([]schema.Event{handoffEvent}, events...),
+ })
+ stdout, _, err := runShareCommand(t, "--cwd", env.projectDir, "--print", "--log-path", env.logPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var payload sharePayload
+ if err := json.Unmarshal([]byte(stdout), &payload); err != nil {
+ t.Fatal(err)
+ }
+ if payload.Trace.RelatedTo != asymptoteobserve.ShareExternalID("codex", "rollout-1") || payload.Trace.RelationshipType != asymptoteobserve.ShareRelationshipHandoff {
+ t.Fatalf("relation = %q %q", payload.Trace.RelatedTo, payload.Trace.RelationshipType)
+ }
+}
diff --git a/docs/cli/share.mdx b/docs/cli/share.mdx
index 02d1677a..8293e2b4 100644
--- a/docs/cli/share.mdx
+++ b/docs/cli/share.mdx
@@ -45,35 +45,36 @@ Sessions are read the way [`beacon handoff`](/cli/handoff) reads them: from the
## What is uploaded
-A shared trace is made of messages. Each Beacon event of the session becomes at most one message:
+A shared trace is a `beacon.trace.v1` trace: the same projection of the session's Beacon events that the local [dashboard](/cli/dashboard) and [lenses](/concepts/lenses) read. It has two parts:
-| 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 |
+- A **summary**: the runtime and its version, the session id, the title, when the session started and ended, the models, token usage, the project name and repository, and how much content was retained.
+- The **events**, in order. Each Beacon event of the session becomes one trace event with a stable `id`, its `number`, `timestamp`, `type` (`user_message`, `agent_message`, `agent_reasoning`, `tool_call`, `tool_result`, `command`, `file`, `mcp`, `approval`, `token_usage`, `session`, `error`, ...) and the fields that event carried: prompt or answer text, the tool with its arguments and result, the command with its exit code and output, the file path and diff, the MCP server and tool, the approval or policy decision, the model and token usage, and the `tool_call_id` and `prompt_id` that tie a call to its result and an action to its prompt.
-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.
+beacon.sh derives the chat view from those events: a tool invocation and its completion become one call and its result, and a call reported by more than one capture path is shown once. Lenses run on a shared trace with the same data they get locally. Beacon's own bookkeeping and status telemetry (heartbeats, inventory, metric datapoints without token usage, the `session.shared` record) 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.
+- The session's working directory and the repository path are left out of the summary. 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 `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.
+- A session started from a [handoff](/cli/handoff) names the session it continues (`related_to`, with `relationship_type` `handoff`), and a subagent's session names its parent's (`subagent`), by their external ids.
- 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:
+`--print` (or `--dry-run`) prints exactly that payload as JSON and sends nothing: the external id the requests go to, `trace` (the body of `PUT /v1/traces/{external_id}`) and `events` (every event the `POST /v1/traces/{external_id}/events/batch` requests would carry, at most 1,000 per request):
```json
{
"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": [ ... ] } ]
+ "trace": {
+ "schema_version": "beacon.trace.v1",
+ "summary": { "harness": { "name": "claude_code" }, "project": { "name": "app" }, "...": "..." },
+ "title": "Fix the login test",
+ "source": "cli",
+ "provenance": { "source": "cli", "generated_at": "...", "beacon_version": "..." }
+ },
+ "events": [ { "id": "...", "number": 1, "timestamp": "...", "type": "user_message", "action": "prompt.submitted", "content": { "text": "...", "...": "..." } } ]
}
```
@@ -87,11 +88,11 @@ beacon.sh redacts every string again on its side. Redaction catches common crede
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.
+Sharing a session again updates the same trace: each session has one stable external id (`<runtime>:<session-id>`), and every event has a stable id (its Beacon `event.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.
+`beacon share refresh` uploads only the events a shared session has gained since it was last uploaded. beacon.sh reports the last event it has, and the events after it are sent, together with that event and everything from the earliest tool call it holds without a result. When that event is not in the session as Beacon reads it now, every event is re-sent, which changes nothing that was already there. The trace's summary is updated; its visibility is not changed.
```bash
beacon share refresh claude_code:5f0c1d2e-aaaa-4bbb-8ccc-000000000001
@@ -118,10 +119,10 @@ 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","harness":"claude_code","event_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.
+`event_count` is how many events the trace holds on beacon.sh, and `uploaded` how many this run sent. On failure, `--json` prints `{"ok":false,"error":"..."}` and the command exits non-zero.
## Flags