Skip to content

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

fix(handoff): cancel unconfirmed detached launches and carry store paths

Claude2f5b86aabc10
diff --git a/CLAUDE.md b/CLAUDE.md
index ac08eb09..3a4cdf8f 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -69,7 +69,7 @@ Supported runtime surfaces today:
- A local-only dashboard served by `beacon endpoint dashboard`, bound to loopback by default and backed by the runtime JSONL log.
- 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, over `https://` only (plain http just for loopback, no redirect off https), size-capped, and verified first when `--sha256` is given. A small frozen baseline is embedded so `scan` works before any rules are installed, and it stays active alongside the store: a store rule replaces a baseline rule only by id (`rulestore.LoadActiveSkipping`), so installing one rule never silently switches the baseline off; only `--rules <dir>` runs a directory alone.
-- 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 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. By default the runtime runs in the calling terminal; `--launch auto|new-terminal|tmux` (`internal/handoff/detached.go`) instead writes a one-time `launch-<id>.json` specification (0600, expires after five minutes) beside the briefs, opens a terminal surface (cmux or Terminal.app, Windows Terminal or PowerShell, a Linux terminal emulator, or a detached tmux session) running the hidden `beacon handoff _launch --spec`, and waits up to 15 s for it to confirm the runtime started, removing the specification on a timeout so a late terminal starts nothing. Content is never put on the terminal's command line, and only the store-locating path variables in `carriedEnvNames`, never credentials, are carried into the specification. 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`, with the workflow guides in `docs/sharing/` kept in sync). 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, except the opted-in pre-push sharing below. From a Metadata-only endpoint the share payload goes through `asymptoteobserve.StripToMetadata` (the same fields the Vector metadata transform removes, applied after event ids are derived) and drops the derived title. 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; a child runtime inherits them, so without `--harness` they are refused, naming both sessions, when the named session ran outside this directory and its parents or another runtime worked here more recently: `shareEnvContradiction`), then the active-session record (only when the entry was seen at least as recently as the directory's newest session, since OTLP-only and poll runtimes never write it), then the directory's most recent session. The record is `pkg/asymptoteobserve/activesession` (`~/.beacon/endpoint/active-sessions.json`, 0600 under 0700, atomic and locked, at most 256 entries, 14-day prune, an unchanged entry rewritten at most once a minute), written by the hook logger after every endpoint event with a session id, working directory and harness; it holds identifiers and paths only, never content, and hooks write it silently and never touch the network for it. Hook tests point `BEACON_ACTIVE_SESSIONS_FILE` at a temp file in `TestMain`. Auto-share (`beacon share auto enable|disable|status`, `cli/beacon/cmd/share_auto.go`, settings in `pkg/asymptoteobserve/shareauto`) is server-side publishing: when it applies to a session's working directory, the hook logger writes ONE local `session.share_requested` event per session (`event.fidelity=inferred`, `share.visibility`; deduplicated under the active-session record's lock) and Beacon Cloud forwarding ships it; beacon.sh builds and refreshes the trace with the same `BuildShareBundle` projection and `ShareExternalID`. Hooks never upload. The user file `~/.beacon/endpoint/share.json` (0600, CLI-written) holds the user-wide switch, three-state (unset, on, or off as a kill switch over every project; `auto.state`, with `auto.enabled` kept in step so older files read) and per-project choices by path, which a user-wide enable or disable never rewrites; a project marker `<repo>/.beacon/share.json` may disable on its own (and an off marker wins over the user's entry for the same directory; the closest directory with an entry or marker decides) but enables only when the user's file trusts that project, with the user's visibility, so a cloned repository can never publish someone's sessions. `ForHook` costs one failed read when nothing is enabled. Hook tests point `BEACON_SHARE_SETTINGS_FILE` at a temp file. The share projection and `handoff.LogSessions` recency skip `session.share_requested`.
- Commit-to-session links via `beacon git setup|status|remove|link|notes` (`cli/beacon/internal/gitlink`, `cli/beacon/cmd/git*.go`; docs in `docs/cli/git.mdx`). A link is a `beacon:<harness>/<session-id>` line in a git note under `refs/notes/beacon`; it carries identifiers only, never content, because notes can be pushed. Which sessions to link is inferred from the local runtime log: a session is linked when, between the parent commit and the commit (at least two hours, at most 24), it wrote a file the commit changes (for a merge, only files that differ from every parent, so a clean merge or pull links nothing). Evidence is file write events, write-type `file.operation`s, plainly readable shell targets, and `apply_patch` envelopes; reads never count. Note updates are a compare-and-swap on the notes ref through a private `refs/notes/beacon-tx/` working ref, and every existing note line, a teammate's or a person's, is kept verbatim. `setup` installs post-commit (links HEAD in the foreground with a 3 s budget, silent, never fails the commit, skips rebase/cherry-pick/revert) and post-rewrite (normalizes the note git concatenates on amend) as standalone `beacon-<hook>` scripts called from a marked block inserted after the shebang of the repository's own hook; only shell hooks are edited, `core.hooksPath` is refused without `--hooks-path`, and `notes.rewriteRef` carries links through amend and rebase. `BEACON_GIT_HOOKS=0` disables the hooks for one command. Every link a run adds is also written to the runtime log as one `session.commit_linked` event in the linked session's timeline (`event.fidelity=inferred`, no collection method), with commit id, branch and credential-stripped remote in the OTel-shaped `vcs` block and overlap counts in `vcs.attribution`; the event deliberately carries no file, command or tool fields so it can never become attribution evidence. Sharing is opt-in (`setup --share-notes`, off by default): a non-destructive fetch refspec `+refs/notes/beacon:refs/notes/beacon-remotes/<remote>` so git's own fetch brings teammates' links into a read-only tracking ref that `beacon git notes` unions with the local one (never force-fetch into `refs/notes/beacon`: it would destroy unpushed links), and a pre-push hook that fetches, merges with `cat_sort_uniq` through the same CAS, and pushes only the notes ref with `--no-verify`, within a 10 s budget and never failing the push. That pre-push hook is the only Beacon git hook that touches the network, and only during a push the person started; `beacon git notes push|fetch` do the same by hand. A note line may carry the session's share URL as its first trailing field (`beacon:<harness>/<id> <url>`; an identifier, not content): `gitlink.ValidShareURL` admits only https URLs on beacon.sh or the configured Beacon host (`AllowShareHost`, fed by `gitAllowShareHosts`), on write and on read, and `MergeNote`/`ParseNote` prefer the line with the URL over the bare one. Post-commit and `link` take URLs only from local `session.shared` events (`localShareURLs`). `setup --share-sessions [--share-visibility]` (implies `--share-notes`; stored as `beacon.shareSessions`/`beacon.shareVisibility` in local git config; public needs confirmation or `--yes`) makes the pre-push hook, which now receives git's stdin, share sessions linked to pushed commits that have no URL (at most 100 commits/10 sessions, silent without credentials, never failing the push; the budget is enforced by the clock: the share phase runs in a goroutine delivering URLs to a collector, the hook takes what it holds after the 6 s upload budget and abandons the rest, then writes notes and pushes the notes ref with what remains of the hook's 10 s, never less than 1 s and 3 s, so only the main path ever writes notes) through `shareUpload` (`cmd/share_upload.go`: `alignShareSource` + `ShareEventsAfter`), then write the URLs into the notes before pushing them. `beacon share --follow [--interval]` (`cmd/share_follow.go`) polls the session locally, uploads through `shareUpload` only when the fingerprint of the projected trace events changed (the events only: the trace body carries its build time), stops at `session.ended` or Ctrl+C (`shareFollowWait`/`shareFollowSignals` are the test seams), and records `session.shared` after each upload, later ones as refreshes that keep the share date; `docs/cli/share.mdx` carries the API-key CI walkthrough with GitHub Actions and GitLab CI examples. Local views show sharing read-only: the trace summary (`traceFold`, which wraps `asymptoteobserve.TraceBuilder` with the local-only `traceStaleness`, and the history through `traceAggregateState`, derivation version 12) and the dashboard's `SessionRecord.Sharing` mark a shared session `stale` when an event `asymptoteobserve.ShareProjects` accepts (the one definition of what a share publishes) and that is not the share's own (`shareActivity`) is newer than what its last `session.shared` record covered (`shared_through`), and carry `asymptoteobserve.ShareRefreshCommand` for the reader to copy; the session list/page, `beacon traces` TUI and plain list display them, and nothing in them shares.
- 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.
diff --git a/cli/beacon/internal/handoff/detached.go b/cli/beacon/internal/handoff/detached.go
index 2a8fe93f..b454d255 100644
--- a/cli/beacon/internal/handoff/detached.go
+++ b/cli/beacon/internal/handoff/detached.go
@@ -57,6 +57,27 @@ type launchSpec struct {
StatusPath string `json:"status_path"`
CleanupPaths []string `json:"cleanup_paths,omitempty"`
ExpiresAt time.Time `json:"expires_at"`
+ // CarriedEnv holds the caller's values of carriedEnvNames. A new terminal starts from its own
+ // environment, not the caller's, so without them a runtime could look for its session store in
+ // a different place. The plan's own Env still wins over them.
+ CarriedEnv map[string]string `json:"carried_env,omitempty"`
+}
+
+// carriedEnvNames are the variables that locate a runtime's configuration and session store. They
+// hold paths, never credentials, so they may be written to the launch specification.
+var carriedEnvNames = []string{
+ "CLAUDE_CONFIG_DIR",
+ "CODEX_HOME",
+ "COPILOT_HOME",
+ "CURSOR_CONFIG_DIR",
+ "DSH_HOME",
+ "GEMINI_CLI_HOME",
+ "HERMES_HOME",
+ "KIRO_HOME",
+ "PI_CODING_AGENT_DIR",
+ "XDG_CONFIG_HOME",
+ "XDG_DATA_HOME",
+ "XDG_STATE_HOME",
}
type launchStatus struct {
@@ -121,6 +142,7 @@ func LaunchDetached(plan Plan, opts DetachedOptions) (DetachedResult, error) {
Plan: plan,
StatusPath: files.statusPath,
ExpiresAt: opts.Now().Add(5 * time.Minute).UTC(),
+ CarriedEnv: carriedEnv(opts.Getenv),
}
if command.needsScript {
spec.CleanupPaths = append(spec.CleanupPaths, files.scriptPath)
@@ -147,7 +169,10 @@ func LaunchDetached(plan Plan, opts DetachedOptions) (DetachedResult, error) {
}
status, err := waitLaunchStatus(files.statusPath, opts)
if err != nil {
- return DetachedResult{}, fmt.Errorf("%s opened but the target runtime did not confirm startup: %w (launch spec: %s)", command.name, err, files.specPath)
+ // Remove the specification so a terminal that opens late finds nothing to run: the caller
+ // is told the launch failed and may retry, which must not start the runtime twice.
+ cleanup()
+ return DetachedResult{}, fmt.Errorf("%s opened but the target runtime did not confirm startup: %w; the launch was cancelled", command.name, err)
}
_ = os.Remove(files.statusPath)
if status.State != "started" {
@@ -162,6 +187,19 @@ func LaunchDetached(plan Plan, opts DetachedOptions) (DetachedResult, error) {
}, nil
}
+func carriedEnv(getenv func(string) string) map[string]string {
+ var env map[string]string
+ for _, name := range carriedEnvNames {
+ if value := getenv(name); value != "" {
+ if env == nil {
+ env = map[string]string{}
+ }
+ env[name] = value
+ }
+ }
+ return env
+}
+
func normalizeDetachedOptions(opts DetachedOptions) DetachedOptions {
if opts.GOOS == "" {
opts.GOOS = runtime.GOOS
@@ -304,13 +342,16 @@ func terminalLauncher(plan Plan, files detachedFiles, opts DetachedOptions) (lau
mode: LaunchModeNewTerminal,
name: "Terminal.app",
executable: open,
- args: []string{"-n", "-a", "Terminal.app", files.scriptPath},
+ args: []string{"-a", "Terminal.app", files.scriptPath},
needsScript: true,
}, nil
case "windows":
if wt, err := opts.LookPath("wt.exe"); err == nil {
- args := []string{"-w", "new", "new-tab", "--startingDirectory", plan.Dir, opts.BeaconExecutable}
- args = append(args, runnerArgs...)
+ // wt splits its command line into subcommands at every ";", so a literal one is escaped.
+ args := []string{"-w", "new", "new-tab", "--startingDirectory", escapeWindowsTerminal(plan.Dir), escapeWindowsTerminal(opts.BeaconExecutable)}
+ for _, arg := range runnerArgs {
+ args = append(args, escapeWindowsTerminal(arg))
+ }
return launcherCommand{mode: LaunchModeNewTerminal, name: "Windows Terminal", executable: wt, args: args}, nil
}
for _, name := range []string{"powershell.exe", "pwsh.exe", "pwsh"} {
@@ -343,6 +384,10 @@ func terminalLauncher(plan Plan, files detachedFiles, opts DetachedOptions) (lau
}
}
+func escapeWindowsTerminal(arg string) string {
+ return strings.ReplaceAll(arg, ";", `\;`)
+}
+
func cmuxLauncher(files detachedFiles, opts DetachedOptions) (launcherCommand, bool) {
socketPath := strings.TrimSpace(opts.Getenv("CMUX_SOCKET_PATH"))
if socketPath == "" {
@@ -421,7 +466,7 @@ func linuxTerminalArgs(kind, dir, beaconExecutable string, runnerArgs []string)
case "alacritty":
return append([]string{"--working-directory", dir, "-e"}, command...), nil
case "foot":
- return append([]string{"--cwd=" + dir}, command...), nil
+ return append([]string{"--working-directory=" + dir}, command...), nil
case "x-terminal-emulator", "xterm":
return append([]string{"-e"}, command...), nil
default:
@@ -513,6 +558,18 @@ func RunLaunchSpec(path string, stdin io.Reader, stdout, stderr io.Writer) (int,
for _, cleanup := range spec.CleanupPaths {
_ = os.Remove(cleanup)
}
+ if len(spec.CarriedEnv) > 0 {
+ env := make(map[string]string, len(spec.CarriedEnv)+len(spec.Plan.Env))
+ for name, value := range spec.CarriedEnv {
+ if !overridden(name, spec.Plan.Env) {
+ env[name] = value
+ }
+ }
+ for name, value := range spec.Plan.Env {
+ env[name] = value
+ }
+ spec.Plan.Env = env
+ }
started := func() error {
return writeLaunchStatus(spec.StatusPath, launchStatus{State: "started"})
}
diff --git a/cli/beacon/internal/handoff/detached_test.go b/cli/beacon/internal/handoff/detached_test.go
index 79a09866..3ee282d5 100644
--- a/cli/beacon/internal/handoff/detached_test.go
+++ b/cli/beacon/internal/handoff/detached_test.go
@@ -259,16 +259,65 @@ func TestLaunchDetachedReportsAnUnconfirmedTerminal(t *testing.T) {
Sleep: func(time.Duration) {},
StartupTimeout: 2 * time.Second,
})
- if err == nil || !strings.Contains(err.Error(), "did not confirm startup") || !strings.Contains(err.Error(), "launch spec:") {
+ if err == nil || !strings.Contains(err.Error(), "did not confirm startup") || !strings.Contains(err.Error(), "cancelled") {
t.Fatalf("err = %v", err)
}
+ // A terminal that opens after the caller gave up must find nothing to run.
+ if leftover, _ := filepath.Glob(filepath.Join(dir, "launch-*")); len(leftover) != 0 {
+ t.Fatalf("launch files left behind: %v", leftover)
+ }
+}
+
+func TestLaunchDetachedCarriesStoreLocatingEnvironment(t *testing.T) {
+ dir := t.TempDir()
+ env := map[string]string{"CODEX_HOME": "/home/me/.codex-work", "ANTHROPIC_API_KEY": "secret"}
+ var carried map[string]string
+ _, err := LaunchDetached(Plan{Executable: "/bin/codex", Dir: dir}, DetachedOptions{
+ Mode: LaunchModeTmux,
+ BeaconExecutable: "/opt/beacon/bin/beacon",
+ SpecDir: dir,
+ GOOS: "linux",
+ Getenv: func(name string) string { return env[name] },
+ LookPath: func(string) (string, error) { return "/usr/bin/tmux", nil },
+ Start: func(*exec.Cmd) error {
+ specs, _ := filepath.Glob(filepath.Join(dir, "launch-*[0-9a-f].json"))
+ if len(specs) != 1 {
+ return fmt.Errorf("specs = %v", specs)
+ }
+ spec, err := readLaunchSpec(specs[0])
+ if err != nil {
+ return err
+ }
+ carried = spec.CarriedEnv
+ return writeLaunchStatus(spec.StatusPath, launchStatus{State: "started"})
+ },
+ Sleep: func(time.Duration) {},
+ })
+ if err != nil {
+ t.Fatalf("LaunchDetached: %v", err)
+ }
+ if !reflect.DeepEqual(carried, map[string]string{"CODEX_HOME": "/home/me/.codex-work"}) {
+ t.Fatalf("carried env = %v", carried)
+ }
+}
+
+func TestWindowsTerminalEscapesSemicolons(t *testing.T) {
+ files := detachedFiles{id: "0123456789abcdef01234567", specPath: `C:\Users\a;b\handoffs\launch.json`}
+ command, err := terminalLauncher(Plan{Dir: `C:\work;x`}, files, normalizeDetachedOptions(detachedTestOptions("windows", "wt.exe")))
+ if err != nil {
+ t.Fatal(err)
+ }
+ joined := strings.Join(command.args, " ")
+ if !strings.Contains(joined, `C:\work\;x`) || !strings.Contains(joined, `a\;b`) {
+ t.Fatalf("args = %q", command.args)
+ }
}
func TestRunLaunchSpecStartsTheExactPlanAndConsumesPrivateFiles(t *testing.T) {
testenv.RequirePOSIXExecutableFixtures(t)
dir := t.TempDir()
script := filepath.Join(dir, "agent")
- if err := os.WriteFile(script, []byte("#!/bin/sh\nprintf '%s|%s' \"$1\" \"$HANDOFF_MODE\"\n"), 0o700); err != nil {
+ if err := os.WriteFile(script, []byte("#!/bin/sh\nprintf '%s|%s|%s' \"$1\" \"$HANDOFF_MODE\" \"$CODEX_HOME\"\n"), 0o700); err != nil {
t.Fatal(err)
}
specPath := filepath.Join(dir, "launch.json")
@@ -288,6 +337,8 @@ func TestRunLaunchSpecStartsTheExactPlanAndConsumesPrivateFiles(t *testing.T) {
StatusPath: statusPath,
CleanupPaths: []string{cleanupPath},
ExpiresAt: time.Now().Add(time.Minute),
+ // The plan's own Env wins over a carried value.
+ CarriedEnv: map[string]string{"CODEX_HOME": "/carried/codex", "HANDOFF_MODE": "carried"},
}
if err := writeLaunchSpec(specPath, spec); err != nil {
t.Fatal(err)
@@ -297,7 +348,7 @@ func TestRunLaunchSpecStartsTheExactPlanAndConsumesPrivateFiles(t *testing.T) {
if err != nil || code != 0 {
t.Fatalf("RunLaunchSpec = %d, %v", code, err)
}
- if stdout.String() != "argument with spaces|safe" {
+ if stdout.String() != "argument with spaces|safe|/carried/codex" {
t.Fatalf("stdout = %q", stdout.String())
}
for _, path := range []string{specPath, cleanupPath} {
diff --git a/docs/cli/handoff.mdx b/docs/cli/handoff.mdx
index 56b58c51..bae7e870 100644
--- a/docs/cli/handoff.mdx
+++ b/docs/cli/handoff.mdx
@@ -220,6 +220,16 @@ Detached launches use a private, expiring `0600` specification under
`~/.beacon/endpoint/handoffs`. The new terminal runs a hidden Beacon trampoline that consumes the
specification, starts the exact approval-safe argument vector, and confirms startup to the calling
process. Prompt or brief content is never interpolated into a terminal-launch shell command.
+If the runtime does not confirm startup within 15 seconds, Beacon removes the specification and
+reports the launch as cancelled, so a terminal that opens late starts nothing and a retry cannot
+start the runtime twice.
+
+A new terminal starts from its own environment rather than the calling process's. Beacon carries
+the variables that locate a runtime's configuration and sessions (`CLAUDE_CONFIG_DIR`,
+`CODEX_HOME`, `COPILOT_HOME`, `CURSOR_CONFIG_DIR`, `DSH_HOME`, `GEMINI_CLI_HOME`, `HERMES_HOME`,
+`KIRO_HOME`, `PI_CODING_AGENT_DIR` and `XDG_CONFIG_HOME`/`XDG_DATA_HOME`/`XDG_STATE_HOME`) into
+the specification. It never writes other variables there, so credentials such as API keys must be
+available in the new terminal's own environment, for example from your shell profile.
The runtime starts in the session's recorded directory. If that directory no longer exists, Beacon
stops rather than starting somewhere else; pass `--cwd` to choose a directory. Beacon prints the