Skip to content

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

handoff: add OpenClaw Gateway

Claude2e47ea8cc8aa
diff --git a/cli/beacon/internal/handoff/fixtures_test.go b/cli/beacon/internal/handoff/fixtures_test.go
index e9c90e3f..0ea94b32 100644
--- a/cli/beacon/internal/handoff/fixtures_test.go
+++ b/cli/beacon/internal/handoff/fixtures_test.go
@@ -24,7 +24,7 @@ var (
// runtime the fixture leaves at its default reads only the test's HOME.
func isolateRuntimeEnv(t *testing.T) {
t.Helper()
- for _, name := range []string{"PI_CODING_AGENT_DIR", "PRIME_AGENT_CODING_AGENT_DIR"} {
+ for _, name := range []string{"PI_CODING_AGENT_DIR", "PRIME_AGENT_CODING_AGENT_DIR", "OPENCLAW_STATE_DIR"} {
t.Setenv(name, "")
}
}
diff --git a/cli/beacon/internal/handoff/openclaw.go b/cli/beacon/internal/handoff/openclaw.go
new file mode 100644
index 00000000..2db384f5
--- /dev/null
+++ b/cli/beacon/internal/handoff/openclaw.go
@@ -0,0 +1,115 @@
+package handoff
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "strings"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/openclawsession"
+)
+
+// OpenClaw Gateway keeps one transcript store per agent profile, agents/<profile>/sessions/ under
+// its state directory, indexed by a sessions.json that files each transcript under the Gateway
+// session key the conversation is routed by. Transcript ids are unique only within a profile.
+
+type openClawSource struct{ dir string }
+
+func (s *openClawSource) Harness() string { return HarnessOpenClaw }
+
+// store reads dir as OpenClaw's state directory, as `beacon endpoint openclaw sessions sync
+// --openclaw-dir` does. Empty means the default, honouring OPENCLAW_STATE_DIR.
+func (s *openClawSource) store() (*openclawsession.Store, error) {
+ return openclawsession.NewStore(s.dir)
+}
+
+func (s *openClawSource) List() ([]Session, error) {
+ store, err := s.store()
+ if err != nil {
+ return nil, err
+ }
+ if !store.Exists() {
+ return nil, nil
+ }
+ refs, err := store.List()
+ if err != nil {
+ return nil, err
+ }
+ sessions := make([]Session, 0, len(refs))
+ for _, ref := range refs {
+ sessions = append(sessions, Session{
+ Harness: HarnessOpenClaw,
+ ID: ref.ID,
+ Title: openClawTitle(ref),
+ Directory: ref.Directory,
+ SourcePath: ref.SourcePath,
+ Key: openClawSessionKey(ref),
+ UpdatedAt: unixMS(ref.UpdatedAtUnixMS),
+ })
+ }
+ return sessions, nil
+}
+
+func (s *openClawSource) Events(session Session) ([]schema.Event, error) {
+ store, err := s.store()
+ if err != nil {
+ return nil, err
+ }
+ refs, err := store.List()
+ if err != nil {
+ return nil, err
+ }
+ for _, ref := range refs {
+ if ref.ID != session.ID || ref.SourcePath != session.SourcePath {
+ continue
+ }
+ records, err := store.Read(ref)
+ if err != nil {
+ return nil, err
+ }
+ mapped := openclawsession.MapTrace(ref, records, openclawsession.MapOptions{})
+ events := make([]schema.Event, 0, len(mapped))
+ for _, m := range mapped {
+ events = append(events, m.Event)
+ }
+ return events, nil
+ }
+ return nil, errSessionGone(session)
+}
+
+// openClawNoPreview is the title the store gives a transcript with no prompt.
+const openClawNoPreview = "(No preview)"
+
+func openClawTitle(ref openclawsession.TraceRef) string {
+ for _, title := range []string{ref.Title, ref.Preview} {
+ // The store cuts titles at a byte count, which can split a character.
+ if title = oneLine(strings.ToValidUTF8(title, "")); title != "" && title != openClawNoPreview {
+ return title
+ }
+ }
+ return ""
+}
+
+// openClawSessionKey is the Gateway session key that reopens ref, or "" when there is none Beacon
+// can pass on safely. The Gateway qualifies a key with its agent ("agent:<agent>:<rest>"), and an
+// unqualified one is resolved against whichever agent the TUI settles on, so only a key qualified
+// with the profile the transcript is stored under names this conversation.
+func openClawSessionKey(ref openclawsession.TraceRef) string {
+ key := strings.TrimSpace(ref.SessionKey)
+ parts := strings.SplitN(key, ":", 3)
+ if len(parts) != 3 || !strings.EqualFold(parts[0], "agent") || parts[2] == "" {
+ return ""
+ }
+ if !strings.EqualFold(parts[1], ref.Profile) {
+ return ""
+ }
+ return key
+}
+
+// openClawNewSessionKey names the Gateway session a brief starts. Without --session the TUI posts
+// into the agent's shared main session, so every handoff gets a key of its own: the prompt names
+// the brief, whose file name is never reused.
+func openClawNewSessionKey(prompt string) string {
+ sum := sha256.Sum256([]byte(prompt))
+ return "beacon-handoff-" + hex.EncodeToString(sum[:8])
+}
diff --git a/cli/beacon/internal/handoff/openclaw_test.go b/cli/beacon/internal/handoff/openclaw_test.go
new file mode 100644
index 00000000..7804db43
--- /dev/null
+++ b/cli/beacon/internal/handoff/openclaw_test.go
@@ -0,0 +1,230 @@
+package handoff
+
+import (
+ "errors"
+ "path/filepath"
+ "reflect"
+ "regexp"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/openclawsession"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv"
+)
+
+var openClawUpdated = time.Date(2026, 9, 24, 11, 0, 0, 0, time.UTC)
+
+type openClawPaths struct {
+ main, loose, mainShared, workShared string
+}
+
+// openClawFixture lays down an OpenClaw state directory with two agent profiles, each a sessions
+// directory of transcripts and the sessions.json index that files them under Gateway session keys.
+func openClawFixture(t *testing.T) (StoreDirs, openClawPaths) {
+ t.Helper()
+ testenv.SetHome(t, t.TempDir())
+ isolateRuntimeEnv(t)
+ state := filepath.Join(t.TempDir(), "openclaw-state")
+ dirs := StoreDirs{HarnessOpenClaw: state}
+ mainDir := filepath.Join(state, "agents", "main", "sessions")
+ workDir := filepath.Join(state, "agents", "work", "sessions")
+ paths := openClawPaths{
+ main: filepath.Join(mainDir, "oc-sess-1.jsonl"),
+ loose: filepath.Join(mainDir, "oc-loose-2.jsonl"),
+ mainShared: filepath.Join(mainDir, "shared-1.jsonl"),
+ workShared: filepath.Join(workDir, "shared-1.jsonl"),
+ }
+ transcript := func(id, cwd, at, prompt, reply string) string {
+ lines := jsonLine(t, map[string]interface{}{"type": "session", "id": id, "timestamp": at, "cwd": cwd})
+ if prompt != "" {
+ lines += jsonLine(t, map[string]interface{}{"type": "message", "id": "u1", "timestamp": at, "message": map[string]interface{}{
+ "role": "user", "content": []interface{}{map[string]interface{}{"type": "text", "text": prompt}},
+ }})
+ }
+ return lines + jsonLine(t, map[string]interface{}{"type": "message", "id": "a1", "timestamp": at, "message": map[string]interface{}{
+ "role": "assistant", "content": []interface{}{map[string]interface{}{"type": "text", "text": reply}},
+ }})
+ }
+ writeFixture(t, paths.main, transcript("oc-sess-1", "/work/api", "2026-09-24T10:59:00Z", " plan the\nrelease ", "Plan ready."))
+ writeFixture(t, paths.loose, transcript("oc-loose-2", "/work/api", "2026-09-24T08:00:00Z", "", "Heartbeat ok."))
+ // A transcript outside the index is dated by its file.
+ setModTime(t, paths.loose, openClawUpdated.Add(-3*time.Hour))
+ writeFixture(t, paths.mainShared, transcript("shared-1", "/work/memo", "2026-09-24T07:00:00Z", "draft the memo", "Drafted."))
+ writeFixture(t, paths.workShared, transcript("shared-1", "/work/inbox", "2026-09-24T06:00:00Z", "triage the inbox", "Triaged."))
+ writeFixture(t, filepath.Join(mainDir, "sessions.json"), mustJSON(t, map[string]interface{}{
+ "agent:main:main": map[string]interface{}{"sessionId": "oc-sess-1", "sessionFile": "oc-sess-1.jsonl", "updatedAt": openClawUpdated.Format(time.RFC3339), "workspaceDir": "/work/api"},
+ "agent:main:memo": map[string]interface{}{"sessionId": "shared-1", "sessionFile": "shared-1.jsonl", "updatedAt": "2026-09-24T07:00:00Z"},
+ }))
+ // A legacy index key that names no agent.
+ writeFixture(t, filepath.Join(workDir, "sessions.json"), mustJSON(t, map[string]interface{}{
+ "discord:channel:9": map[string]interface{}{"sessionId": "shared-1", "sessionFile": paths.workShared, "updatedAt": "2026-09-24T06:00:00Z"},
+ }))
+ return dirs, paths
+}
+
+func TestListReadsOpenClawSessions(t *testing.T) {
+ dirs, paths := openClawFixture(t)
+ sessions, err := List(DefaultSources(dirs), Filter{Harness: HarnessOpenClaw})
+ if err != nil {
+ t.Fatalf("List: %v", err)
+ }
+ bySource := map[string]Session{}
+ for _, s := range sessions {
+ bySource[s.SourcePath] = s
+ }
+ if len(sessions) != 4 {
+ t.Fatalf("sessions = %v, want 4", sessionKeys(sessions))
+ }
+ want := Session{
+ Harness: HarnessOpenClaw, ID: "oc-sess-1", Title: "plan the release", Directory: "/work/api",
+ SourcePath: paths.main, Key: "agent:main:main", UpdatedAt: openClawUpdated,
+ }
+ if got := bySource[paths.main]; !reflect.DeepEqual(got, want) {
+ t.Fatalf("main session = %+v\nwant %+v", got, want)
+ }
+ // A transcript outside the index has no key, and one with no prompt no title.
+ if loose := bySource[paths.loose]; loose.ID != "oc-loose-2" || loose.Title != "" || loose.Key != "" {
+ t.Fatalf("loose session = %+v", loose)
+ }
+ if s := bySource[paths.mainShared]; s.Key != "agent:main:memo" || s.Title != "draft the memo" {
+ t.Fatalf("main shared session = %+v", s)
+ }
+ // An index key that names no agent is not passed on.
+ if s := bySource[paths.workShared]; s.Key != "" || s.Title != "triage the inbox" || s.Directory != "/work/inbox" {
+ t.Fatalf("work shared session = %+v", s)
+ }
+ if got := sessions[0].ID; got != "oc-sess-1" {
+ t.Fatalf("newest session = %s, want oc-sess-1", got)
+ }
+}
+
+func TestListWithoutAnOpenClawStore(t *testing.T) {
+ testenv.SetHome(t, t.TempDir())
+ isolateRuntimeEnv(t)
+ sessions, err := (&openClawSource{dir: filepath.Join(t.TempDir(), "missing")}).List()
+ if err != nil || sessions != nil {
+ t.Fatalf("List = %v, %v; want nothing", sessions, err)
+ }
+}
+
+func TestOpenClawSessionsBuildABrief(t *testing.T) {
+ dirs, _ := openClawFixture(t)
+ sources := DefaultSources(dirs)
+ // A unique prefix finds the session too.
+ session, err := Find(sources, HarnessOpenClaw, "oc-sess")
+ if err != nil {
+ t.Fatalf("Find: %v", err)
+ }
+ events, err := Events(sources, session)
+ if err != nil {
+ t.Fatalf("Events: %v", err)
+ }
+ brief := BuildBrief(session, events, FromSessionStore, time.Now())
+ if brief.Prompts != 1 || !strings.Contains(brief.FirstRequest, "plan the") {
+ t.Fatalf("brief prompts=%d first=%q", brief.Prompts, brief.FirstRequest)
+ }
+ if !strings.Contains(brief.Render(), "OpenClaw Gateway") {
+ t.Fatalf("the brief should name OpenClaw Gateway:\n%s", brief.Render())
+ }
+}
+
+func TestOpenClawIDsAreUniqueOnlyWithinAProfile(t *testing.T) {
+ dirs, paths := openClawFixture(t)
+ sources := DefaultSources(dirs)
+ var ambiguous *AmbiguousError
+ if _, err := Find(sources, HarnessOpenClaw, "shared-1"); !errors.As(err, &ambiguous) || len(ambiguous.Candidates) != 2 {
+ t.Fatalf("Find = %v, want both profiles' shared-1", err)
+ }
+ for path, prompt := range map[string]string{paths.mainShared: "draft the memo", paths.workShared: "triage the inbox"} {
+ events, err := Events(sources, Session{Harness: HarnessOpenClaw, ID: "shared-1", SourcePath: path})
+ if err != nil {
+ t.Fatalf("Events(%s): %v", path, err)
+ }
+ brief := BuildBrief(Session{Harness: HarnessOpenClaw, ID: "shared-1"}, events, FromSessionStore, time.Now())
+ if brief.FirstRequest != prompt {
+ t.Fatalf("%s first request = %q, want %q", path, brief.FirstRequest, prompt)
+ }
+ }
+}
+
+func TestOpenClawSessionGoneFromItsStore(t *testing.T) {
+ dirs, paths := openClawFixture(t)
+ session := Session{Harness: HarnessOpenClaw, ID: "oc-sess-1", SourcePath: paths.main + ".moved"}
+ if _, err := Events(DefaultSources(dirs), session); !errors.Is(err, ErrNotFound) {
+ t.Fatalf("Events = %v, want ErrNotFound", err)
+ }
+}
+
+func TestPlanResumeReopensAnOpenClawSessionByItsKey(t *testing.T) {
+ session := resumableSession(t, HarnessOpenClaw, "oc-1")
+ session.Key = "agent:main:discord:channel:9"
+ plan, err := PlanResume(session, PlanOptions{LookPath: installed("openclaw")})
+ if err != nil {
+ t.Fatalf("PlanResume: %v", err)
+ }
+ if plan.Mode != ModeNative || plan.Executable != "/bin/openclaw" || !reflect.DeepEqual(plan.Args, []string{"tui", "--session", "agent:main:discord:channel:9"}) {
+ t.Fatalf("plan = %+v", plan)
+ }
+
+ // Without a key the Gateway has no name for the conversation, so it continues from a brief.
+ keyless := session
+ keyless.Key = ""
+ brief := filepath.Join(t.TempDir(), "brief.md")
+ plan, err = PlanResume(keyless, PlanOptions{BriefPath: brief, LookPath: installed("openclaw")})
+ if err != nil {
+ t.Fatalf("PlanResume: %v", err)
+ }
+ prompt := NewSessionPrompt(keyless, brief)
+ if plan.Mode != ModeNewSession || plan.Reason != ReasonNotResumable || !reflect.DeepEqual(plan.Args, []string{"tui", "--session", openClawNewSessionKey(prompt), "--message", prompt}) {
+ t.Fatalf("plan = %+v", plan)
+ }
+ for _, arg := range plan.Args {
+ if arg == "--deliver" {
+ t.Fatal("a handoff must not deliver replies through the Gateway's channels")
+ }
+ }
+
+ gone := session
+ gone.SourcePath = filepath.Join(t.TempDir(), "missing.jsonl")
+ plan, err = PlanResume(gone, PlanOptions{BriefPath: brief, LookPath: installed("openclaw")})
+ if err != nil {
+ t.Fatalf("PlanResume: %v", err)
+ }
+ if plan.Mode != ModeNewSession || plan.Reason != ReasonSessionGone {
+ t.Fatalf("plan = %+v", plan)
+ }
+}
+
+func TestOpenClawNewSessionKeyIsFreshPerBrief(t *testing.T) {
+ session := Session{Harness: HarnessCodex, ID: "019a-thread"}
+ first := openClawNewSessionKey(NewSessionPrompt(session, "/h/codex_cli-019a-thread-20260924T090000.000Z.md"))
+ second := openClawNewSessionKey(NewSessionPrompt(session, "/h/codex_cli-019a-thread-20260924T090000.001Z.md"))
+ if first == second {
+ t.Fatalf("two briefs of one session share the key %s", first)
+ }
+ // Lower case, so the Gateway's key normalisation leaves it as written, and never the shared
+ // main session.
+ if !regexp.MustCompile(`^beacon-handoff-[0-9a-f]{16}$`).MatchString(first) {
+ t.Fatalf("key = %q", first)
+ }
+}
+
+func TestOpenClawSessionKeyNeedsItsOwnAgent(t *testing.T) {
+ for _, tc := range []struct {
+ key, profile, want string
+ }{
+ {"agent:main:main", "main", "agent:main:main"},
+ {"agent:work:discord:channel:9", "work", "agent:work:discord:channel:9"},
+ {"agent:other:main", "main", ""},
+ {"main", "main", ""},
+ {"discord:channel:9", "work", ""},
+ {"agent:main:", "main", ""},
+ {"", "main", ""},
+ } {
+ ref := openclawsession.TraceRef{SessionKey: tc.key, Profile: tc.profile}
+ if got := openClawSessionKey(ref); got != tc.want {
+ t.Errorf("openClawSessionKey(%q in %s) = %q, want %q", tc.key, tc.profile, got, tc.want)
+ }
+ }
+}
diff --git a/cli/beacon/internal/handoff/resume_test.go b/cli/beacon/internal/handoff/resume_test.go
index 54ed8c2d..3a558119 100644
--- a/cli/beacon/internal/handoff/resume_test.go
+++ b/cli/beacon/internal/handoff/resume_test.go
@@ -24,7 +24,7 @@ func installed(names ...string) func(string) (string, error) {
}
}
-var allRuntimes = installed("claude", "codex", "opencode", "cline", "pi", "prime-agent")
+var allRuntimes = installed("claude", "codex", "opencode", "cline", "pi", "prime-agent", "openclaw")
// resumableSession is a session whose directory and session file both exist.
func resumableSession(t *testing.T, harness, id string) Session {
@@ -80,6 +80,8 @@ func TestPlanResumeStartsANewSessionInEachRuntime(t *testing.T) {
{HarnessCline, "cline", []string{"--tui", "--auto-approve", "false"}},
{HarnessPi, "pi", []string{"--"}},
{HarnessPrime, "prime-agent", []string{"--"}},
+ // {key} stands for the fresh Gateway session key the prompt derives.
+ {HarnessOpenClaw, "openclaw", []string{"tui", "--session", "{key}", "--message"}},
} {
t.Run(tc.target, func(t *testing.T) {
source := HarnessCodex
@@ -94,7 +96,12 @@ func TestPlanResumeStartsANewSessionInEachRuntime(t *testing.T) {
if plan.Mode != ModeNewSession || plan.Reason != ReasonOtherRuntime || plan.BriefPath != brief {
t.Fatalf("plan = %+v", plan)
}
- want := append(append([]string{}, tc.prefix...), NewSessionPrompt(session, brief))
+ prompt := NewSessionPrompt(session, brief)
+ var want []string
+ for _, arg := range tc.prefix {
+ want = append(want, strings.ReplaceAll(arg, "{key}", openClawNewSessionKey(prompt)))
+ }
+ want = append(want, prompt)
if plan.Executable != "/bin/"+tc.exe || !reflect.DeepEqual(plan.Args, want) {
t.Fatalf("command = %s %q\nwant /bin/%s %q", plan.Executable, plan.Args, tc.exe, want)
}
diff --git a/cli/beacon/internal/handoff/runtimes.go b/cli/beacon/internal/handoff/runtimes.go
index 76162102..c8ce9f48 100644
--- a/cli/beacon/internal/handoff/runtimes.go
+++ b/cli/beacon/internal/handoff/runtimes.go
@@ -7,6 +7,7 @@ import (
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/claudesession"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/clinesession"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/codexsession"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/openclawsession"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/opencodesession"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/pisession"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/primesession"
@@ -53,6 +54,7 @@ const (
HarnessCline = clinesession.Harness
HarnessPi = pisession.Harness
HarnessPrime = primesession.Harness
+ HarnessOpenClaw = openclawsession.Harness
)
// runtimes lists every runtime handoff supports, in display order.
@@ -149,6 +151,27 @@ var runtimes = []Runtime{
NewSession: func(prompt string) []string { return []string{"--", prompt} },
},
},
+ {
+ Harness: HarnessOpenClaw,
+ Label: "OpenClaw Gateway",
+ Aliases: []string{"openclaw", "openclaw-gateway"},
+ NewSource: func(dir string) Source { return &openClawSource{dir: dir} },
+ // The TUI is a client of the Gateway: it needs the Gateway running, and a conversation lives
+ // on the Gateway under its session key, not its transcript id. --deliver stays off, so
+ // replies are not sent out through the Gateway's chat channels.
+ Command: &runtimeCommand{
+ Executable: "openclaw",
+ Resume: func(s Session) ([]string, bool) {
+ if s.Key == "" {
+ return nil, false
+ }
+ return []string{"tui", "--session", s.Key}, true
+ },
+ NewSession: func(prompt string) []string {
+ return []string{"tui", "--session", openClawNewSessionKey(prompt), "--message", prompt}
+ },
+ },
+ },
}
// Harnesses lists the runtimes handoff supports, in display order.
diff --git a/cli/beacon/internal/handoff/session.go b/cli/beacon/internal/handoff/session.go
index 1c699e89..5ee8ac1a 100644
--- a/cli/beacon/internal/handoff/session.go
+++ b/cli/beacon/internal/handoff/session.go
@@ -25,7 +25,10 @@ type Session struct {
SourcePath string `json:"source_path,omitempty"`
// Store names which of a runtime's stores holds the session when it has more than one, such as
// Cline's CLI sessions and its older task history.
- Store string `json:"store,omitempty"`
+ Store string `json:"store,omitempty"`
+ // Key is the name the runtime's CLI reopens the session by when that is not its id: an OpenClaw
+ // Gateway session key. Empty when the store does not say.
+ Key string `json:"key,omitempty"`
UpdatedAt time.Time `json:"updated_at"`
// Subagent marks a child session a runtime spawned for delegated work. Those are listed only on
// request, because resuming one resumes a fragment of the parent's task.
diff --git a/cli/beacon/internal/openclawsession/handoff_test.go b/cli/beacon/internal/openclawsession/handoff_test.go
new file mode 100644
index 00000000..e514b2c5
--- /dev/null
+++ b/cli/beacon/internal/openclawsession/handoff_test.go
@@ -0,0 +1,53 @@
+package openclawsession
+
+import (
+ "testing"
+
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
+)
+
+func TestMapTraceRecordsAHandoffLink(t *testing.T) {
+ ref := TraceRef{ID: "new-1", Profile: "main", SourcePath: "/state/agents/main/sessions/new-1.jsonl", Directory: "/work"}
+ prompt := "Continue the work.\n\n" + asymptoteobserve.HandoffMarker("claude_code", "src-1")
+ records := []Record{
+ {Order: 1, NativeID: "s0:session", Type: "session_started", Content: "/work"},
+ {Order: 2, NativeID: "u1:user", Type: "user_message", Role: "user", Content: prompt},
+ {Order: 3, NativeID: "u2:user", Type: "user_message", Role: "user", Content: "no marker here"},
+ }
+ mapped := MapTrace(ref, records, MapOptions{})
+ var links []MappedEvent
+ for _, m := range mapped {
+ if m.Event.Event.Action == "session.handoff" {
+ links = append(links, m)
+ }
+ }
+ if len(links) != 1 {
+ t.Fatalf("links = %d, want 1: %+v", len(links), mapped)
+ }
+ link := links[0]
+ if link.SourceOrder != 2 || link.Event.Handoff == nil || link.Event.Handoff.SourceHarness != "claude_code" || link.Event.Handoff.SourceSessionID != "src-1" {
+ t.Fatalf("link = %+v handoff=%+v", link, link.Event.Handoff)
+ }
+ if link.Event.Session == nil || link.Event.Session.ID != "new-1" || link.Event.Session.WorkingDirectory != "/work" {
+ t.Fatalf("link session = %+v", link.Event.Session)
+ }
+ if link.Event.Harness.Name != Harness || link.Event.Harness.CollectionMethod != "poll" || link.Event.Event.Fidelity != "observed" {
+ t.Fatalf("link provenance = %+v %+v", link.Event.Harness, link.Event.Event)
+ }
+ if link.Event.Prompt != nil || link.Event.Content != nil || link.Event.GenAI != nil {
+ t.Fatalf("the link must not repeat the prompt: %+v", link.Event)
+ }
+ ids := map[string]bool{}
+ for _, m := range mapped {
+ if ids[m.Event.Event.ID] {
+ t.Fatalf("duplicate event id %s", m.Event.Event.ID)
+ }
+ ids[m.Event.Event.ID] = true
+ }
+ again := MapTrace(ref, records, MapOptions{})
+ for i := range mapped {
+ if again[i].Event.Event.ID != mapped[i].Event.Event.ID {
+ t.Fatal("event ids must be deterministic, so a second sync never duplicates the link")
+ }
+ }
+}
diff --git a/cli/beacon/internal/openclawsession/mapper.go b/cli/beacon/internal/openclawsession/mapper.go
index 65cfdbcd..58134834 100644
--- a/cli/beacon/internal/openclawsession/mapper.go
+++ b/cli/beacon/internal/openclawsession/mapper.go
@@ -105,6 +105,11 @@ func (m *mapper) emitPrompt(record Record) {
ev.GenAI = &schema.GenAIInfo{Input: &schema.GenAIInputInfo{Messages: asymptoteobserve.TextInputMessages(text)}}
ev.Raw = mergeRaw(ev.Raw, record.Raw)
m.append(record, "prompt", ev)
+ if info, ok := asymptoteobserve.ParseHandoffMarker(text); ok {
+ link := m.base(record, "session.handoff", "session", schema.SeverityInfo, "Session continued from a "+info.SourceHarness+" session")
+ link.Handoff = &info
+ m.append(record, "prompt.handoff", link)
+ }
}
func (m *mapper) emitAgentMessage(record Record) {
diff --git a/cli/beacon/internal/openclawsession/store.go b/cli/beacon/internal/openclawsession/store.go
index 5e9200b4..f91e6cab 100644
--- a/cli/beacon/internal/openclawsession/store.go
+++ b/cli/beacon/internal/openclawsession/store.go
@@ -131,7 +131,7 @@ func (s *Store) readSessionsIndex(root string) []TraceRef {
return nil
}
var refs []TraceRef
- for _, entry := range raw {
+ for key, entry := range raw {
sourcePath := resolveIndexedSourcePath(entry.SessionFile, root)
if entry.SessionID == "" || sourcePath == "" {
continue
@@ -143,6 +143,7 @@ func (s *Store) readSessionsIndex(root string) []TraceRef {
dir := firstNonEmpty(entry.WorkspaceDir, directoryFromAny(entry.SystemPromptReport))
if ref, ok := s.readTraceMetadata(sourcePath, updated, dir); ok {
ref.Profile = profileFromSessionRoot(root)
+ ref.SessionKey = key
refs = append(refs, ref)
}
}
diff --git a/cli/beacon/internal/openclawsession/types.go b/cli/beacon/internal/openclawsession/types.go
index 2f399dec..c26a9910 100644
--- a/cli/beacon/internal/openclawsession/types.go
+++ b/cli/beacon/internal/openclawsession/types.go
@@ -25,6 +25,9 @@ type TraceRef struct {
Directory string
UpdatedAtUnixMS int64
SizeBytes int64
+ // SessionKey is the Gateway session key the sessions.json index files the transcript under,
+ // such as "agent:main:main". Empty for a transcript found outside the index.
+ SessionKey string
}
type SessionIndexEntry struct {
diff --git a/docs/cli/handoff.mdx b/docs/cli/handoff.mdx
index 4b458e2b..c4f9da04 100644
--- a/docs/cli/handoff.mdx
+++ b/docs/cli/handoff.mdx
@@ -25,10 +25,13 @@ Sessions come from each runtime's own local session store, not from Beacon's run
| Cline | `~/.cline/data` | `cline` |
| Pi | `~/.pi/agent/sessions` (or under `PI_CODING_AGENT_DIR`) | `pi` |
| Prime Agent | `~/.prime/agent`, both `sessions` and `session-artifacts` (or `PRIME_AGENT_CODING_AGENT_DIR`) | `prime` |
+| OpenClaw Gateway | `~/.openclaw/agents/<agent>/sessions` for every agent (or under `OPENCLAW_STATE_DIR`) | `openclaw` |
-When a Codex thread has more than one rollout file, `beacon handoff` lists it once, under its newest file. Cline can hold the same task both as a CLI session and in its older task history; the CLI session is the copy that is listed. Cline kanban cards are not sessions and are not listed. Prime Agent subagent transcripts, under `session-artifacts`, are listed as subagents of the session that started them.
+When a Codex thread has more than one rollout file, `beacon handoff` lists it once, under its newest file. Cline can hold the same task both as a CLI session and in its older task history; the CLI session is the copy that is listed. Cline kanban cards are not sessions and are not listed. Prime Agent subagent transcripts, under `session-artifacts`, are listed as subagents of the session that started them. OpenClaw transcript ids are unique only within one agent. When two agents hold the same id, both are listed, and `export` and `resume` report the id as ambiguous rather than pick one.
-`--store-dir <runtime>=<path>` takes the location in the table: for Pi its sessions directory, as `beacon endpoint pi sync --sessions-dir` does, and for Prime Agent the agent directory holding both of its roots.
+OpenClaw Gateway sessions are read from the JSONL transcripts and the `sessions.json` index in each agent's `sessions` directory, as `beacon endpoint openclaw sessions sync` reads them. Recent OpenClaw releases keep live sessions in a per-agent SQLite database and treat that directory as legacy, so sessions that exist only in the database are not listed.
+
+`--store-dir <runtime>=<path>` takes the location in the table: for Pi its sessions directory, as `beacon endpoint pi sync --sessions-dir` does, for Prime Agent the agent directory holding both of its roots, and for OpenClaw Gateway its state directory, as `beacon endpoint openclaw sessions sync --openclaw-dir` does.
## `beacon handoff list`
@@ -43,7 +46,7 @@ beacon handoff list --json
| Flag | Description |
|------|-------------|
-| `--harness` | Only this runtime: `claude`, `codex`, `opencode`, or `cline`. |
+| `--harness` | Only this runtime: `claude`, `codex`, `opencode`, `cline`, `pi`, `prime` or `openclaw`. |
| `--here` | Only sessions that ran in the current directory or below it. |
| `--dir` | Only sessions that ran in this directory or below it. |
| `--subagents` | Include subagent sessions. They are hidden by default, because resuming one resumes a fragment of its parent's task. |
@@ -110,6 +113,7 @@ There are two ways to resume:
| Cline | `cline --tui --auto-approve false --id <id>` |
| Pi | `pi --session <session file>` |
| Prime Agent | `prime-agent --resume <session file>` |
+ | OpenClaw Gateway | `openclaw tui --session <session key>` |
- **Start a new session from a brief.** Otherwise, or with `--agent` naming another runtime or with `--new`, Beacon writes a brief (see `export`) and starts a new session. The first message of that session points at the brief:
@@ -121,18 +125,21 @@ There are two ways to resume:
| Cline | `cline --tui --auto-approve false "<prompt>"` |
| Pi | `pi -- "<prompt>"` |
| Prime Agent | `prime-agent -- "<prompt>"` |
+ | OpenClaw Gateway | `openclaw tui --session beacon-handoff-<hash> --message "<prompt>"` |
The prompt names the brief by its path and asks the agent to read it, then confirm the task before changing anything. The brief is never inlined into the command line, because a command line is visible to every local user through the process table. The prompt ends with a handoff marker (see below).
Claude Code, Cline and Prime Agent subagent sessions, and Cline's older task history, can't be reopened by their CLIs, so they always continue from a brief. A session known only from Beacon's runtime log also continues from a brief, and it needs `--agent` if its own runtime isn't one Beacon can start.
+OpenClaw's TUI is a client of the Gateway, so the Gateway must be running (`openclaw gateway run`, or its installed service) for either command to connect; Beacon does not start it. The Gateway reopens a conversation by its session key, such as `agent:main:main`, not by its transcript id, so an OpenClaw session is reopened natively only when the agent's `sessions.json` files the transcript under a key qualified with that agent (`agent:<agent>:...`); otherwise it continues from a brief. The Gateway answers for that key with whatever conversation it now holds under it: a key it no longer knows can open as an empty conversation. A new session gets a key of its own, `beacon-handoff-` and a hash of its prompt, because without `--session` the TUI would post into the agent's shared main session. Beacon never passes `--deliver`, so replies stay in the TUI and are not sent out through the Gateway's chat channels.
+
Cline approves every tool call by default. Beacon always passes `--auto-approve false`, so a session Beacon starts never gets auto-approval on Beacon's say-so. You can still turn it on inside the Cline TUI.
The runtime runs in this terminal, 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 plan and asks `Continue? [Y/n]` before launching. Without a terminal, it launches only with `--yes`. `beacon handoff resume` exits with the runtime's own exit code.
| Flag | Description |
|------|-------------|
-| `--agent` | Runtime to continue in: `claude`, `codex`, `opencode`, `cline`, `pi` or `prime`. Defaults to the session's own runtime. |
+| `--agent` | Runtime to continue in: `claude`, `codex`, `opencode`, `cline`, `pi`, `prime` or `openclaw`. Defaults to the session's own runtime. |
| `--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. |
@@ -163,7 +170,7 @@ The link event keeps the new session's id, workspace and harness, and leaves the
Two paths record the link:
- **Live hooks.** The prompt hook for Claude Code and the Cline and OpenCode plugins record it as the prompt is sent (`harness.collection_method: hook`).
-- **Session-store sync.** `beacon endpoint claude sync`, `codex sync`, `opencode sync`, `cline sync`, `pi sync` and `prime sync` record it when they read the prompt back from the runtime's store (`harness.collection_method: poll`).
+- **Session-store sync.** `beacon endpoint claude sync`, `codex sync`, `opencode sync`, `cline sync`, `pi sync`, `prime sync` and `openclaw sessions sync` record it when they read the prompt back from the runtime's store (`harness.collection_method: poll`).
Codex CLI prompts reach Beacon over OTLP and through `beacon endpoint codex sync`, not a prompt hook, so a session continued in Codex is linked by the sync. For a runtime that also has a prompt hook or plugin, a sync can record the same link the hook already did; the two carry different `collection_method` values, as every other event those runtimes report through both paths does. A sync's link has a deterministic `event.id`, so syncing again never duplicates it.