The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu
Go agent-ai-cliagent-harnessesagent-securitybrowser-extensionciclaude-codecloudcodexcursordetection-engineeringjevknowledge-basememorymobile-device-managementobservabilitysecuritysecurity-information-and-event-managementsecurity-toolstelemetrytraces
handoff: let a runtime's command set or remove environment variables
Claudeb990fcf5c249
diff --git a/cli/beacon/cmd/handoff_resume.go b/cli/beacon/cmd/handoff_resume.goindex 5ecd330a..f877babf 100644--- a/cli/beacon/cmd/handoff_resume.go+++ b/cli/beacon/cmd/handoff_resume.go@@ -9,6 +9,7 @@ import ("os""os/exec""path/filepath"+ "sort""strings""github.com/spf13/cobra"@@ -150,9 +151,30 @@ func describeHandoffPlan(w io.Writer, plan handoff.Plan) {fmt.Fprintf(w, " brief: %s\n", plan.BriefPath)fmt.Fprintf(w, " directory: %s\n", plan.Dir)}+ if env := describeHandoffEnv(plan.Env); env != "" {+ fmt.Fprintf(w, " env: %s\n", env)+ }fmt.Fprintf(w, " command: %s\n", shellCommand(append([]string{plan.Executable}, plan.Args...)...))}+// describeHandoffEnv lists what the runtime's environment differs by, in name order.+func describeHandoffEnv(env map[string]string) string {+ names := make([]string, 0, len(env))+ for name := range env {+ names = append(names, name)+ }+ sort.Strings(names)+ parts := make([]string, 0, len(names))+ for _, name := range names {+ if env[name] == "" {+ parts = append(parts, "unset "+name)+ } else {+ parts = append(parts, name+"="+env[name])+ }+ }+ return strings.Join(parts, ", ")+}+func confirmHandoff(in io.Reader, w io.Writer) bool {fmt.Fprint(w, "Continue? [Y/n] ")line, err := bufio.NewReader(in).ReadString('\n')diff --git a/cli/beacon/cmd/handoff_test.go b/cli/beacon/cmd/handoff_test.goindex a8f76824..b193e800 100644--- a/cli/beacon/cmd/handoff_test.go+++ b/cli/beacon/cmd/handoff_test.go@@ -512,3 +512,19 @@ func TestHandoffExportFindsALogSessionByPrefix(t *testing.T) {t.Fatalf("export by prefix = %v\n%s", err, out)}}++func TestDescribeHandoffPlanShowsTheEnvironment(t *testing.T) {+ var out bytes.Buffer+ describeHandoffPlan(&out, handoff.Plan{+ Mode: handoff.ModeNative, Source: handoff.Session{Harness: handoff.HarnessClaude, ID: "s-1"},+ Executable: "/bin/agent", Dir: "/work", Env: map[string]string{"MODE": "approve", "ALLOW_ALL": ""},+ })+ if !strings.Contains(out.String(), " env: unset ALLOW_ALL, MODE=approve\n") {+ t.Fatalf("plan = %q", out.String())+ }+ out.Reset()+ describeHandoffPlan(&out, handoff.Plan{Mode: handoff.ModeNative, Source: handoff.Session{Harness: handoff.HarnessClaude, ID: "s-1"}, Executable: "/bin/claude"})+ if strings.Contains(out.String(), "env:") {+ t.Fatalf("a plan with no overrides shows no env line: %q", out.String())+ }+}diff --git a/cli/beacon/internal/handoff/envname_other.go b/cli/beacon/internal/handoff/envname_other.gonew file mode 100644index 00000000..db617e75--- /dev/null+++ b/cli/beacon/internal/handoff/envname_other.go@@ -0,0 +1,5 @@+//go:build !windows++package handoff++func envNameEqual(a, b string) bool { return a == b }diff --git a/cli/beacon/internal/handoff/envname_windows.go b/cli/beacon/internal/handoff/envname_windows.gonew file mode 100644index 00000000..95dce0d1--- /dev/null+++ b/cli/beacon/internal/handoff/envname_windows.go@@ -0,0 +1,5 @@+package handoff++import "strings"++func envNameEqual(a, b string) bool { return strings.EqualFold(a, b) }diff --git a/cli/beacon/internal/handoff/launch.go b/cli/beacon/internal/handoff/launch.goindex eebb1cdc..f6c0fc45 100644--- a/cli/beacon/internal/handoff/launch.go+++ b/cli/beacon/internal/handoff/launch.go@@ -6,6 +6,8 @@ import ("os""os/exec""os/signal"+ "sort"+ "strings")// Launch runs the plan's runtime in the current terminal and waits for it, returning its exit@@ -15,7 +17,7 @@ func Launch(plan Plan, stdin io.Reader, stdout, stderr io.Writer) (int, error) {cmd := exec.Command(plan.Executable, plan.Args...)cmd.Dir = plan.Dircmd.Stdin, cmd.Stdout, cmd.Stderr = stdin, stdout, stderr- cmd.Env = os.Environ()+ cmd.Env = launchEnv(os.Environ(), plan.Env)interrupts := make(chan os.Signal, 1)signal.Notify(interrupts, os.Interrupt)@@ -31,3 +33,38 @@ func Launch(plan Plan, stdin io.Reader, stdout, stderr io.Writer) (int, error) {}return 0, nil}++// launchEnv applies the plan's overrides to environ. A name is matched as the platform matches it:+// case-insensitively on Windows.+func launchEnv(environ []string, overrides map[string]string) []string {+ if len(overrides) == 0 {+ return environ+ }+ env := make([]string, 0, len(environ)+len(overrides))+ for _, entry := range environ {+ name, _, _ := strings.Cut(entry, "=")+ if !overridden(name, overrides) {+ env = append(env, entry)+ }+ }+ names := make([]string, 0, len(overrides))+ for name := range overrides {+ names = append(names, name)+ }+ sort.Strings(names)+ for _, name := range names {+ if value := overrides[name]; value != "" {+ env = append(env, name+"="+value)+ }+ }+ return env+}++func overridden(name string, overrides map[string]string) bool {+ for candidate := range overrides {+ if envNameEqual(name, candidate) {+ return true+ }+ }+ return false+}diff --git a/cli/beacon/internal/handoff/resume.go b/cli/beacon/internal/handoff/resume.goindex 81e40d36..2b30824d 100644--- a/cli/beacon/internal/handoff/resume.go+++ b/cli/beacon/internal/handoff/resume.go@@ -38,6 +38,9 @@ type Plan struct {Dir string `json:"dir"`// BriefPath is where the brief for a new session is written. It is empty for a native resume.BriefPath string `json:"brief_path,omitempty"`+ // Env is what the runtime's environment differs by: a variable set to a value is set, one set+ // to "" is removed.+ Env map[string]string `json:"env,omitempty"`}// PlanOptions steer how a session is picked up.@@ -83,6 +86,12 @@ func PlanResume(session Session, opts PlanOptions) (Plan, error) {return Plan{}, fmt.Errorf("%w: %s (%s was not found on PATH)", ErrRuntimeNotInstalled, RuntimeLabel(target), targetCommand.Executable)}plan.Executable = executable+ if len(targetCommand.Env) > 0 {+ plan.Env = make(map[string]string, len(targetCommand.Env))+ for name, value := range targetCommand.Env {+ plan.Env[name] = value+ }+ }reason := nativeBlocker(session, target, opts)if reason == "" {plan.Mode, plan.Args = ModeNative, nativeArgs(targetCommand, session)diff --git a/cli/beacon/internal/handoff/resume_test.go b/cli/beacon/internal/handoff/resume_test.goindex 17fdbb09..8bd9f29c 100644--- a/cli/beacon/internal/handoff/resume_test.go+++ b/cli/beacon/internal/handoff/resume_test.go@@ -275,3 +275,71 @@ func TestLaunchReportsAMissingExecutable(t *testing.T) {t.Fatalf("Launch = %d, %v", code, err)}}++func TestLaunchEnvSetsAndRemovesVariables(t *testing.T) {+ environ := []string{"PATH=/bin", "ALLOW_ALL=true", "MODE=auto", "KEEP=1"}+ got := launchEnv(environ, map[string]string{"ALLOW_ALL": "", "MODE": "approve", "NEW": "x"})+ want := []string{"PATH=/bin", "KEEP=1", "MODE=approve", "NEW=x"}+ if !reflect.DeepEqual(got, want) {+ t.Fatalf("env = %q, want %q", got, want)+ }+ if got := launchEnv(environ, nil); !reflect.DeepEqual(got, environ) {+ t.Fatalf("no overrides changed the environment: %q", got)+ }+}++// withRuntime registers a runtime for the length of a test.+func withRuntime(t *testing.T, r Runtime) {+ t.Helper()+ prev := runtimes+ runtimes = append(append([]Runtime{}, runtimes...), r)+ t.Cleanup(func() { runtimes = prev })+}++func TestPlanResumeCarriesTheRuntimesEnvironment(t *testing.T) {+ withRuntime(t, Runtime{Harness: "test_agent", Label: "Test Agent", Command: &runtimeCommand{+ Executable: "test-agent",+ Resume: func(s Session) ([]string, bool) { return []string{"--resume", s.ID}, true },+ NewSession: func(prompt string) []string { return []string{prompt} },+ Env: map[string]string{"TEST_AGENT_MODE": "approve", "TEST_AGENT_ALLOW_ALL": ""},+ }})+ session := resumableSession(t, "test_agent", "s-1")+ plan, err := PlanResume(session, PlanOptions{LookPath: installed("test-agent")})+ if err != nil {+ t.Fatalf("PlanResume: %v", err)+ }+ want := map[string]string{"TEST_AGENT_MODE": "approve", "TEST_AGENT_ALLOW_ALL": ""}+ if !reflect.DeepEqual(plan.Env, want) {+ t.Fatalf("env = %v, want %v", plan.Env, want)+ }+ // The plan holds a copy: changing it cannot change what the next plan gets.+ plan.Env["TEST_AGENT_MODE"] = "yolo"+ again, _ := PlanResume(session, PlanOptions{LookPath: installed("test-agent")})+ if again.Env["TEST_AGENT_MODE"] != "approve" {+ t.Fatal("a plan's environment must not alias the registry's")+ }++ claude, err := PlanResume(resumableSession(t, HarnessClaude, "s-2"), PlanOptions{LookPath: allRuntimes})+ if err != nil || claude.Env != nil {+ t.Fatalf("a runtime with no overrides plans none: %v %v", claude.Env, err)+ }+}++func TestLaunchAppliesThePlansEnvironment(t *testing.T) {+ testenv.RequirePOSIXExecutableFixtures(t)+ script := filepath.Join(t.TempDir(), "fake-agent")+ writeFixture(t, script, "#!/bin/sh\necho \"mode=$TEST_AGENT_MODE allow=${TEST_AGENT_ALLOW_ALL-unset}\"\n")+ if err := os.Chmod(script, 0o755); err != nil {+ t.Fatal(err)+ }+ t.Setenv("TEST_AGENT_MODE", "auto")+ t.Setenv("TEST_AGENT_ALLOW_ALL", "true")+ var stdout strings.Builder+ plan := Plan{Executable: script, Dir: t.TempDir(), Env: map[string]string{"TEST_AGENT_MODE": "approve", "TEST_AGENT_ALLOW_ALL": ""}}+ if _, err := Launch(plan, nil, &stdout, nil); err != nil {+ t.Fatal(err)+ }+ if got := strings.TrimSpace(stdout.String()); got != "mode=approve allow=unset" {+ t.Fatalf("runtime saw %q", got)+ }+}diff --git a/cli/beacon/internal/handoff/runtimes.go b/cli/beacon/internal/handoff/runtimes.goindex 46a42f50..4fe83608 100644--- a/cli/beacon/internal/handoff/runtimes.go+++ b/cli/beacon/internal/handoff/runtimes.go@@ -38,6 +38,9 @@ type runtimeCommand struct {// NewSession returns the arguments that start an interactive session with prompt as its first// message.NewSession func(prompt string) []string+ // Env overrides the runtime's environment: a variable set to a value is set, one set to "" is+ // removed. It holds switches only, never credentials, because the plan prints it.+ Env map[string]string}// Harness names, as the endpoint event schema spells them.diff --git a/docs/cli/handoff.mdx b/docs/cli/handoff.mdxindex a4da50a8..fccb325c 100644--- a/docs/cli/handoff.mdx+++ b/docs/cli/handoff.mdx@@ -128,7 +128,7 @@ The runtime runs in this terminal, in the session's recorded directory. If that| `--new` | Start a new session from a brief even when the session could be reopened. || `--cwd` | Directory to start the runtime in. || `--print` | Show the plan and command without writing a brief or launching anything. |-| `--json` | With `--print`, describe the plan as JSON (`mode`, `reason`, `target`, `executable`, `args`, `dir`, `brief_path`). |+| `--json` | With `--print`, describe the plan as JSON (`mode`, `reason`, `target`, `executable`, `args`, `env`, `dir`, `brief_path`). || `--yes` | Launch without asking. || `--output-dir`, `--log-path`, `--harness`, `--store-dir`, and the `--*-dir` flags | As for `export`. |