Skip to content

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

Add DeepSeek Harness session backfill

Justin D'Souza4d74a93d9310
diff --git a/CLAUDE.md b/CLAUDE.md
index f066f909..1845728d 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -48,7 +48,7 @@ Supported runtime surfaces today:
- OpenHands hooks are merged into the runtime's own `.openhands/hooks.json`. Project scope is the practical default because the loader takes the first hooks file and the CLI/GUI agent server reads the repository file. Approvals, token usage/cost, per-call tool ids, and assistant response text are not exposed or synthesized.
- Kiro uses one Beacon-owned hook file under `.kiro/hooks` or `$KIRO_HOME`/`~/.kiro/hooks`. Its hook stdout is added to agent context on `SessionStart` and `UserPromptSubmit`, so Beacon writes nothing to stdout on Kiro; blocking is exit code 2 with the reason on stderr. Approvals are not exposed or synthesized.
- goose currently has only the adapter: `cli/beacon-hooks/cmd/goose.go` can map a manually written `hooks.json` that invokes `beacon-hooks --platform goose`, but there is no `beacon endpoint hooks install --harness goose`, no `DiscoverGoose`, and no automatic OTLP configuration. Keep README/docs from implying goose is generally installable until those pieces exist. goose uses HTTP OTLP (4318), its blocking hook stdout must be `{"decision":"allow"}` or `{"decision":"block"}`, and it exposes no approval decisions or tool output.
-- DeepSeek Harness (`dsh`) is installed through two user-level files: `$DSH_HOME/beacon-endpoint-hooks.json` and a row in `$DSH_HOME/cordis.patch.yml`; there is no project scope. It rides the Claude-shaped envelope, but `run_code` remains `tool.invoked` because nested commands fire their own hooks.
+- DeepSeek Harness (`dsh`) is installed through two user-level files: `$DSH_HOME/beacon-endpoint-hooks.json` and a row in `$DSH_HOME/cordis.patch.yml`; there is no project scope. It also installs a Beacon-owned local skill at `$DSH_HOME/skills/beacon-endpoint/SKILL.md` and supports native session backfill from `$DSH_HOME/sessions` through `beacon endpoint dsh sync`, which fills assistant text/reasoning, tool failures, and token usage that the hook bridge does not expose. It rides the Claude-shaped envelope on the hook path, but `run_code` remains `tool.invoked` because nested commands fire their own hooks.
- fx (vercel-labs/fx) telemetry read from the session store fx commits under `~/.fx/sessions/`, covering session start, prompts, tool calls, commands with exit codes and output, file reads/creates/edits with diffs, MCP tool calls, agent messages, history compaction, and per-turn token usage plus reported cost. fx exposes no third-party hook, plugin, or OTLP surface -- its lifecycle hooks are compiled into the binary -- so collection is a read of fx's own records, run by `beacon endpoint fx sync`. Every event carries `harness.collection_method=poll`; approvals are not synthesized (fx persists permission feedback text, not a per-call decision, matching the Cline and Pi posture) and no session-end event is invented, since fx sessions are resumable. Implementation lives in `cli/beacon/internal/fxsession` and `cli/beacon/cmd/endpoint_fx.go`.
- Claude Cowork admin-configured OpenTelemetry setup guidance and local validation.
- OpenClaw Gateway uses a Beacon-managed plugin directory plus OpenClaw's own diagnostics OTLP guidance (`beacon endpoint integrations openclaw`). The plugin's `before_tool_call` hook is fail-closed, so the handler dispatches synchronously and returns without awaiting. Conversation hooks, including `llm_output`, require `plugins.entries.beacon-endpoint.hooks.allowConversationAccess`; without it, token and agent-message coverage is partial. Beacon reads OpenClaw JSON/JSON5 config for advice but does not rewrite it.
diff --git a/README.md b/README.md
index 2d0aa1ff..2ea32d94 100644
--- a/README.md
+++ b/README.md
@@ -239,7 +239,7 @@ Beacon supports local agents, browser agents, cloud agents, CI workflows, and ag
| Codex CLI | OTLP + hooks + poll | ✅ | ✅ | ✅ | ✅ | – | ✅ | – | ✅ |
| Codex Desktop | OTLP | ✅ | ✅ | ✅ | ✅ | – | ✅ | – | ✅ |
| Cursor | Hooks + poll | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | – |
-| DeepSeek Harness | Hooks | ✅ | ✅ | ✅ | ✅ | ✅ | – | ✅ | – |
+| DeepSeek Harness | Hooks + poll | ✅ | ✅ | ✅ | ✅ | ✅ | – | ✅ | ✅ |
| Devin CLI | Hooks | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | – |
| Devin Desktop | Hooks | – | ✅ | ✅ | ✅ | ✅ | – | ✅ | – |
| Factory Droid | OTLP + hooks + poll | ✅ | ✅ | ✅ | – | ✅ | ✅ | – | – |
diff --git a/cli/beacon-hooks/cmd/dsh_hooks_test.go b/cli/beacon-hooks/cmd/dsh_hooks_test.go
index fed498f0..221dc60d 100644
--- a/cli/beacon-hooks/cmd/dsh_hooks_test.go
+++ b/cli/beacon-hooks/cmd/dsh_hooks_test.go
@@ -575,6 +575,9 @@ func TestDshWriteProducesADiff(t *testing.T) {
if !containsLine(diff, "+package main") {
t.Fatalf("file.diff = %q, want the written content", diff)
}
+ if got := leaf(event, "raw", "dsh", "tool_input", "content"); got != "package main\n\nfunc main() {}\n" {
+ t.Fatalf("raw.dsh.tool_input.content = %q, want the original write payload", got)
+ }
}
func TestDshEditProducesADiff(t *testing.T) {
diff --git a/cli/beacon-hooks/cmd/post_tool.go b/cli/beacon-hooks/cmd/post_tool.go
index ee598b7f..411cab1f 100644
--- a/cli/beacon-hooks/cmd/post_tool.go
+++ b/cli/beacon-hooks/cmd/post_tool.go
@@ -302,19 +302,22 @@ func recordLocalEdit(params *evaluationParams, input map[string]interface{}, log
// twice -- once here, once from OTLP -- and this is the field that lets the
// writer tell that the two are one edit.
applyToolCallID(fields, input)
- // The same gap costs Qwen its raw payload: emitHookEvent is what attaches it, and it lands on
- // exactly the events this runtime's taxonomy exists to produce, since a successful `write_file`
- // or `edit` is classified `file.modified` and routed here. `permission_mode` has no schema field
- // at all and `tool_use_id` keeps its verbatim spelling only here, so both would survive on
- // failed and non-edit tools and vanish on the successful edits.
+ // The same gap costs runtimes with raw payload retention their raw payload: emitHookEvent is
+ // what attaches it, and it lands on exactly the events these runtimes' taxonomies exist to
+ // produce. Successful Qwen and dsh edits are classified `file.modified` and routed here, so
+ // runtime-native context would survive on failed and non-edit tools and vanish on successful
+ // edits unless this path restores it.
//
- // Scoped to qwen rather than applied to every runtime with a raw convention. grok, hermes and
- // vscode have the same gap on this path, and closing it would change their recorded event shape
- // with no fixture here to say what it should become; that is a stated limit rather than a
- // silent one. TestQwenRawPayloadSurvivesTheFileEditPath is what holds the Qwen half.
+ // Scoped to runtimes with pinned raw payload fixtures rather than applied to every runtime with
+ // a raw convention. grok, hermes and vscode have the same gap on this path, and closing it would
+ // change their recorded event shape with no fixture here to say what it should become; that is
+ // a stated limit rather than a silent one.
if platformFlag == "qwen" {
fields["raw"] = mergeNested(fields["raw"], map[string]interface{}{"qwen": input})
}
+ if platformFlag == "dsh" {
+ fields["raw"] = mergeNested(fields["raw"], map[string]interface{}{"dsh": input})
+ }
logger.EndpointEvent("file.modified", "file", "info", "File edit observed", fields)
}
diff --git a/cli/beacon/README.md b/cli/beacon/README.md
index 9b2c582e..730e719b 100644
--- a/cli/beacon/README.md
+++ b/cli/beacon/README.md
@@ -573,6 +573,8 @@ contract, what leaves the machine, and revocation.
./beacon endpoint hooks install --harness dsh
./beacon endpoint hooks status --harness dsh
+./beacon endpoint dsh status
+./beacon endpoint dsh sync
./beacon endpoint hooks install --harness hermes
./beacon endpoint hooks status --harness hermes
@@ -674,6 +676,14 @@ process-level and a repository has nowhere to mount from, so `--level project` i
refused with that explanation rather than silently becoming a machine-wide
install.
+Beacon also reads DeepSeek Harness' native committed session records from
+`$DSH_HOME/sessions` with `beacon endpoint dsh sync`. That poll path is local
+and offline; it backfills assistant text/reasoning, structured failed-tool
+status, and token usage that the hook bridge does not expose. Hook install also
+writes a Beacon-owned local skill at `$DSH_HOME/skills/beacon-endpoint/SKILL.md`
+so `dsh` can check `beacon endpoint dsh status` and run a workspace-scoped sync
+when asked.
+
The patch file is the user's own, and is edited as a document rather than
rewritten: parsed into a YAML node tree, one self-contained element appended or
removed, re-encoded from the same tree, so comments, quoting and `!!js`
diff --git a/cli/beacon/cmd/endpoint_dsh.go b/cli/beacon/cmd/endpoint_dsh.go
new file mode 100644
index 00000000..8e1f27c1
--- /dev/null
+++ b/cli/beacon/cmd/endpoint_dsh.go
@@ -0,0 +1,272 @@
+package cmd
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/dshsession"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/lifecycle"
+ "github.com/spf13/cobra"
+)
+
+var endpointDshCmd = &cobra.Command{
+ Use: "dsh",
+ Short: "Collect telemetry from DeepSeek Harness sessions",
+ Long: `Collect endpoint telemetry from DeepSeek Harness' native session store.
+
+DeepSeek Harness already persists local session records under $DSH_HOME/sessions
+(default ~/.dsh/sessions). Beacon reads those records after the fact and maps
+them to endpoint events with harness.collection_method=poll. This complements
+the live hook integration: hooks observe current tool activity and optional
+policy decisions, while session sync backfills assistant text, reasoning, tool
+failure status, and token usage that the hook bridge does not expose.`,
+}
+
+var endpointDshSyncCmd = &cobra.Command{
+ Use: "sync",
+ Short: "Read new DeepSeek Harness session records into the runtime log",
+ SilenceUsage: true,
+ RunE: runEndpointDshSync,
+}
+
+var endpointDshStatusCmd = &cobra.Command{
+ Use: "status",
+ Short: "Show DeepSeek Harness sessions and collection progress",
+ SilenceUsage: true,
+ RunE: runEndpointDshStatus,
+}
+
+var endpointDshOpts struct {
+ dshHome string
+ statePath string
+ logPath string
+ print bool
+ watch bool
+ interval time.Duration
+ workspace string
+ sessionID string
+}
+
+func init() {
+ endpointCmd.AddCommand(endpointDshCmd)
+ endpointDshCmd.AddCommand(endpointDshSyncCmd)
+ endpointDshCmd.AddCommand(endpointDshStatusCmd)
+
+ for _, c := range []*cobra.Command{endpointDshSyncCmd, endpointDshStatusCmd} {
+ f := c.Flags()
+ f.StringVar(&endpointDshOpts.dshHome, "dsh-home", "", "DeepSeek Harness home (default $DSH_HOME or ~/.dsh)")
+ f.StringVar(&endpointDshOpts.statePath, "state", "", "Collector cursor file (default ~/.beacon/endpoint/state/dsh.json)")
+ f.StringVar(&endpointDshOpts.workspace, "workspace", "", "Only include sessions whose cwd matches this workspace")
+ f.StringVar(&endpointDshOpts.sessionID, "session-id", "", "Only include one DeepSeek session id")
+ f.BoolVar(&endpointOpts.jsonOutput, "json", false, "Print the result as JSON")
+ f.BoolVar(&endpointOpts.userMode, "user", true, "Use per-user endpoint paths")
+ f.BoolVar(&endpointOpts.systemMode, "system", false, "Use system endpoint paths")
+ }
+
+ sync := endpointDshSyncCmd.Flags()
+ sync.StringVar(&endpointDshOpts.logPath, "log-path", "", "Runtime JSONL log path (default resolved endpoint log)")
+ sync.BoolVar(&endpointDshOpts.print, "print", false, "Print mapped events as JSON without writing them or advancing the cursor")
+ sync.BoolVar(&endpointDshOpts.watch, "watch", false, "Sweep continuously on --interval")
+ sync.DurationVar(&endpointDshOpts.interval, "interval", time.Minute, "Sweep interval for --watch")
+}
+
+func runEndpointDshSync(cmd *cobra.Command, args []string) error {
+ userMode := endpointUserMode()
+ opts := dshsession.CollectOptions{
+ DSHHome: endpointDshOpts.dshHome,
+ Print: endpointDshOpts.print,
+ Out: cmd.OutOrStdout(),
+ Write: !endpointDshOpts.print,
+ UserMode: userMode,
+ Workspace: endpointDshOpts.workspace,
+ SessionID: endpointDshOpts.sessionID,
+ }
+ if !endpointDshOpts.print {
+ opts.StatePath = resolveDshStatePath(endpointDshOpts.statePath, userMode)
+ opts.LogPath = lifecycle.ResolveRuntimeLog(userMode, endpointDshOpts.logPath).EffectiveLogPath
+ }
+ ctx := cmd.Context()
+ if ctx == nil {
+ ctx = context.Background()
+ }
+ if endpointDshOpts.watch && !endpointDshOpts.print {
+ return watchDsh(ctx, cmd, opts)
+ }
+ summary, err := dshsession.CollectOnce(opts)
+ reportDshSweep(cmd, summary)
+ return err
+}
+
+func watchDsh(ctx context.Context, cmd *cobra.Command, opts dshsession.CollectOptions) error {
+ interval := endpointDshOpts.interval
+ if interval < 5*time.Second {
+ interval = 5 * time.Second
+ }
+ for {
+ summary, err := dshsession.CollectOnce(opts)
+ if err != nil {
+ fmt.Fprintf(cmd.ErrOrStderr(), "dsh sync error: %v\n", err)
+ }
+ reportDshSweep(cmd, summary)
+ select {
+ case <-ctx.Done():
+ return nil
+ case <-time.After(interval):
+ }
+ }
+}
+
+func reportDshSweep(cmd *cobra.Command, summary dshsession.Summary) {
+ if endpointDshOpts.print {
+ return
+ }
+ if endpointOpts.jsonOutput {
+ _ = json.NewEncoder(cmd.OutOrStdout()).Encode(summary)
+ return
+ }
+ fmt.Fprintf(cmd.OutOrStdout(), "dsh sync: %d sessions, %d changed, %d events, %d errors\n",
+ summary.Sessions, summary.SessionsChanged, summary.EventsEmitted, summary.Errors)
+ if summary.MalformedLines > 0 {
+ fmt.Fprintf(cmd.OutOrStdout(), " %d unreadable line(s) in DeepSeek session logs\n", summary.MalformedLines)
+ }
+ if summary.PartialSessions > 0 {
+ fmt.Fprintf(cmd.OutOrStdout(), " %d session(s) had a partly written record; it will be read on the next sweep\n", summary.PartialSessions)
+ }
+}
+
+type dshSessionStatus struct {
+ SessionID string `json:"session_id"`
+ Workspace string `json:"workspace,omitempty"`
+ ParentSession string `json:"parent_session,omitempty"`
+ Model string `json:"model,omitempty"`
+ Title string `json:"title,omitempty"`
+ Path string `json:"path"`
+ CollectedLine int `json:"collected_line"`
+ LastLine int `json:"last_line"`
+ Collected bool `json:"collected"`
+ SizeBytes int64 `json:"size_bytes"`
+}
+
+type dshStatusReport struct {
+ DSHHome string `json:"dsh_home"`
+ SessionsDir string `json:"sessions_dir"`
+ Present bool `json:"present"`
+ StatePath string `json:"state_path,omitempty"`
+ Sessions []dshSessionStatus `json:"sessions"`
+}
+
+func runEndpointDshStatus(cmd *cobra.Command, args []string) error {
+ store, err := dshsession.NewStore(endpointDshOpts.dshHome)
+ if err != nil {
+ return err
+ }
+ statePath := resolveDshStatePath(endpointDshOpts.statePath, endpointUserMode())
+ state, err := dshsession.LoadState(statePath)
+ if err != nil {
+ return err
+ }
+ refs, err := store.List()
+ if err != nil {
+ return err
+ }
+ refs = filterDshStatusRefs(refs)
+ report := dshStatusReport{
+ DSHHome: store.DSHHome,
+ SessionsDir: store.SessionsDir,
+ Present: store.Exists(),
+ StatePath: statePath,
+ Sessions: make([]dshSessionStatus, 0, len(refs)),
+ }
+ for _, ref := range refs {
+ records, _, _ := store.Read(ref)
+ status := dshSessionStatus{
+ SessionID: ref.ID,
+ Path: ref.Path,
+ LastLine: lastDshLine(records),
+ SizeBytes: ref.SizeBytes,
+ }
+ if ref.Meta != nil {
+ status.Workspace = ref.Meta.CWD
+ status.ParentSession = ref.Meta.ParentSessionID
+ status.Model = ref.Meta.Model
+ status.Title = ref.Meta.Title
+ }
+ if cursor := state.Sources[ref.Path]; cursor != nil {
+ status.CollectedLine = cursor.LastLine
+ status.Collected = cursor.LastLine >= status.LastLine && cursor.SizeBytes == ref.SizeBytes && !cursor.PartialTail && !cursor.PartialFrame
+ }
+ report.Sessions = append(report.Sessions, status)
+ }
+ if endpointOpts.jsonOutput {
+ return json.NewEncoder(cmd.OutOrStdout()).Encode(report)
+ }
+ out := cmd.OutOrStdout()
+ if !report.Present {
+ fmt.Fprintf(out, "DeepSeek Harness sessions: none (%s does not exist)\n", report.SessionsDir)
+ return nil
+ }
+ fmt.Fprintf(out, "DeepSeek Harness sessions: %d in %s\n", len(report.Sessions), report.SessionsDir)
+ for _, session := range report.Sessions {
+ state := "pending"
+ if session.Collected {
+ state = "collected"
+ }
+ fmt.Fprintf(out, " %s %s line %d/%d %s\n",
+ session.SessionID, state, session.CollectedLine, session.LastLine, strings.TrimSpace(session.Workspace))
+ }
+ return nil
+}
+
+func filterDshStatusRefs(refs []dshsession.SessionRef) []dshsession.SessionRef {
+ opts := dshsession.CollectOptions{Workspace: endpointDshOpts.workspace, SessionID: endpointDshOpts.sessionID}
+ out := refs[:0]
+ sessionID := strings.TrimSpace(opts.SessionID)
+ workspace := strings.TrimSpace(opts.Workspace)
+ if workspace != "" {
+ if abs, err := filepath.Abs(workspace); err == nil {
+ workspace = filepath.Clean(abs)
+ }
+ }
+ for _, ref := range refs {
+ if sessionID != "" && ref.ID != sessionID {
+ continue
+ }
+ if workspace != "" {
+ cwd := ""
+ if ref.Meta != nil {
+ cwd = strings.TrimSpace(ref.Meta.CWD)
+ if abs, err := filepath.Abs(cwd); err == nil {
+ cwd = filepath.Clean(abs)
+ }
+ }
+ if cwd != workspace {
+ continue
+ }
+ }
+ out = append(out, ref)
+ }
+ return out
+}
+
+func lastDshLine(records []dshsession.Record) int {
+ if len(records) == 0 {
+ return 0
+ }
+ return records[len(records)-1].Line
+}
+
+func resolveDshStatePath(override string, userMode bool) string {
+ if strings.TrimSpace(override) != "" {
+ return override
+ }
+ if !userMode {
+ if dir := filepath.Dir(lifecycle.ResolveRuntimeLog(false, "").EffectiveLogPath); dir != "" && dir != "." {
+ return filepath.Join(dir, "dsh-state.json")
+ }
+ }
+ return dshsession.DefaultStatePath()
+}
diff --git a/cli/beacon/go.mod b/cli/beacon/go.mod
index ba2c676b..6d49a537 100644
--- a/cli/beacon/go.mod
+++ b/cli/beacon/go.mod
@@ -30,6 +30,7 @@ require (
github.com/google/cel-go v0.30.0 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
+ github.com/klauspost/compress v1.18.0 // indirect
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
github.com/mattn/go-isatty v0.0.24 // indirect
github.com/mattn/go-localereader v0.0.1 // indirect
diff --git a/cli/beacon/go.sum b/cli/beacon/go.sum
index 570545dc..e493b06e 100644
--- a/cli/beacon/go.sum
+++ b/cli/beacon/go.sum
@@ -34,6 +34,8 @@ github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
+github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
+github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
diff --git a/cli/beacon/internal/dshsession/collect.go b/cli/beacon/internal/dshsession/collect.go
new file mode 100644
index 00000000..cd4f0458
--- /dev/null
+++ b/cli/beacon/internal/dshsession/collect.go
@@ -0,0 +1,278 @@
+package dshsession
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer"
+)
+
+type Cursor struct {
+ LastLine int `json:"last_line"`
+ Started bool `json:"started"`
+ SizeBytes int64 `json:"size_bytes,omitempty"`
+ ModTimeMS int64 `json:"mod_time_ms,omitempty"`
+ Events int `json:"events,omitempty"`
+ PartialTail bool `json:"partial_tail,omitempty"`
+ PartialFrame bool `json:"partial_frame,omitempty"`
+}
+
+type State struct {
+ Version int `json:"version"`
+ Sources map[string]*Cursor `json:"sources"`
+}
+
+type CollectOptions struct {
+ DSHHome string
+ StatePath string
+ Write bool
+ LogPath string
+ UserMode bool
+ Print bool
+ Out io.Writer
+ Workspace string
+ SessionID string
+}
+
+type Summary struct {
+ Sessions int `json:"sessions"`
+ SessionsChanged int `json:"sessions_changed"`
+ EventsEmitted int `json:"events_emitted"`
+ Errors int `json:"errors"`
+ MalformedLines int `json:"malformed_lines"`
+ PartialSessions int `json:"partial_sessions"`
+}
+
+func DefaultStatePath() string {
+ base := filepath.Join(os.TempDir(), "beacon")
+ if home, err := os.UserHomeDir(); err == nil && strings.TrimSpace(home) != "" {
+ base = filepath.Join(home, ".beacon")
+ }
+ return filepath.Join(base, "endpoint", "state", "dsh.json")
+}
+
+func LoadState(path string) (*State, error) {
+ state := &State{Version: StateVersion, Sources: map[string]*Cursor{}}
+ if path == "" {
+ return state, nil
+ }
+ data, err := os.ReadFile(path)
+ if err != nil {
+ if errors.Is(err, os.ErrNotExist) {
+ return state, nil
+ }
+ return nil, err
+ }
+ var stored State
+ if err := json.Unmarshal(data, &stored); err != nil {
+ return nil, fmt.Errorf("read DeepSeek collector state %s: %w", path, err)
+ }
+ if stored.Version != StateVersion || stored.Sources == nil {
+ return state, nil
+ }
+ state.Sources = stored.Sources
+ return state, nil
+}
+
+func (s *State) Save(path string) error {
+ if path == "" {
+ return nil
+ }
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ return err
+ }
+ s.Version = StateVersion
+ data, err := json.MarshalIndent(s, "", " ")
+ if err != nil {
+ return err
+ }
+ tmp := path + ".tmp"
+ if err := os.WriteFile(tmp, data, 0o600); err != nil {
+ return err
+ }
+ return os.Rename(tmp, path)
+}
+
+func (s *State) cursor(source string) *Cursor {
+ if s.Sources == nil {
+ s.Sources = map[string]*Cursor{}
+ }
+ cursor := s.Sources[source]
+ if cursor == nil {
+ cursor = &Cursor{}
+ s.Sources[source] = cursor
+ }
+ return cursor
+}
+
+func CollectOnce(opts CollectOptions) (summary Summary, err error) {
+ store, err := NewStore(opts.DSHHome)
+ if err != nil {
+ return summary, err
+ }
+ refs, err := store.List()
+ if err != nil {
+ return summary, err
+ }
+ refs = filterRefs(refs, opts)
+ summary.Sessions = len(refs)
+ if len(refs) == 0 {
+ return summary, nil
+ }
+ state, err := LoadState(opts.StatePath)
+ if err != nil {
+ return summary, err
+ }
+ defer func() {
+ if saveErr := state.Save(opts.StatePath); saveErr != nil && err == nil {
+ err = fmt.Errorf("save DeepSeek collector state: %w", saveErr)
+ }
+ }()
+ var errs []error
+ for _, ref := range refs {
+ changed, collectErr := collectSession(store, ref, state, opts, &summary)
+ if collectErr != nil {
+ summary.Errors++
+ errs = append(errs, fmt.Errorf("DeepSeek session %s: %w", ref.ID, collectErr))
+ continue
+ }
+ if changed {
+ summary.SessionsChanged++
+ }
+ }
+ if len(errs) > 0 {
+ return summary, errors.Join(errs...)
+ }
+ return summary, nil
+}
+
+func collectSession(store *Store, ref SessionRef, state *State, opts CollectOptions, summary *Summary) (bool, error) {
+ sourceKey := ref.Path
+ cursor := state.cursor(sourceKey)
+ if cursor.ModTimeMS == ref.ModTimeUnixMS && cursor.SizeBytes == ref.SizeBytes && !cursor.PartialTail && !cursor.PartialFrame {
+ return false, nil
+ }
+ if ref.SizeBytes < cursor.SizeBytes {
+ cursor.LastLine = 0
+ cursor.Started = false
+ }
+ records, stats, err := store.Read(ref)
+ summary.MalformedLines += stats.Malformed
+ if stats.PartialTail || stats.PartialFrame {
+ summary.PartialSessions++
+ }
+ if err != nil {
+ return false, err
+ }
+ mapped := MapSession(ref, records, MapOptions{MinLine: cursor.LastLine, SkipSessionStarted: cursor.Started})
+ if len(mapped) == 0 {
+ advanceCursor(cursor, ref, records, stats)
+ return false, nil
+ }
+ for i, item := range mapped {
+ if err := emit(item.Event, opts); err != nil {
+ advanceCursorPartial(cursor, ref, mapped, i)
+ return true, err
+ }
+ summary.EventsEmitted++
+ if item.Event.Event.Action == "session.started" {
+ cursor.Started = true
+ }
+ cursor.Events++
+ }
+ advanceCursor(cursor, ref, records, stats)
+ return true, nil
+}
+
+func advanceCursor(cursor *Cursor, ref SessionRef, records []Record, stats Stats) {
+ if len(records) > 0 {
+ cursor.LastLine = records[len(records)-1].Line
+ }
+ cursor.SizeBytes = ref.SizeBytes
+ cursor.ModTimeMS = ref.ModTimeUnixMS
+ cursor.PartialTail = stats.PartialTail
+ cursor.PartialFrame = stats.PartialFrame
+ for _, record := range records {
+ if record.Kind == "session" && record.Line <= cursor.LastLine {
+ cursor.Started = true
+ break
+ }
+ }
+}
+
+func advanceCursorPartial(cursor *Cursor, ref SessionRef, mapped []MappedEvent, failedIdx int) {
+ var lastLine int
+ for i := 0; i < failedIdx; i++ {
+ if mapped[i].SourceLine > lastLine {
+ lastLine = mapped[i].SourceLine
+ }
+ if mapped[i].Event.Event.Action == "session.started" {
+ cursor.Started = true
+ }
+ }
+ if lastLine > cursor.LastLine {
+ cursor.LastLine = lastLine
+ }
+ cursor.SizeBytes = ref.SizeBytes
+ cursor.ModTimeMS = ref.ModTimeUnixMS
+}
+
+func emit(event schema.Event, opts CollectOptions) error {
+ if opts.Print && opts.Out != nil {
+ data, err := json.Marshal(event)
+ if err != nil {
+ return err
+ }
+ if _, err := opts.Out.Write(append(data, '\n')); err != nil {
+ return err
+ }
+ }
+ if opts.Write {
+ if _, err := writer.AppendEvent(event, writer.Options{Path: opts.LogPath, UserMode: opts.UserMode}); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func filterRefs(refs []SessionRef, opts CollectOptions) []SessionRef {
+ sessionID := strings.TrimSpace(opts.SessionID)
+ workspace := cleanPath(opts.Workspace)
+ if sessionID == "" && workspace == "" {
+ return refs
+ }
+ out := refs[:0]
+ for _, ref := range refs {
+ if sessionID != "" && ref.ID != sessionID {
+ continue
+ }
+ if workspace != "" {
+ cwd := ""
+ if ref.Meta != nil {
+ cwd = cleanPath(ref.Meta.CWD)
+ }
+ if cwd != workspace {
+ continue
+ }
+ }
+ out = append(out, ref)
+ }
+ return out
+}
+
+func cleanPath(path string) string {
+ path = strings.TrimSpace(path)
+ if path == "" {
+ return ""
+ }
+ if abs, err := filepath.Abs(path); err == nil {
+ return filepath.Clean(abs)
+ }
+ return filepath.Clean(path)
+}
diff --git a/cli/beacon/internal/dshsession/collect_test.go b/cli/beacon/internal/dshsession/collect_test.go
new file mode 100644
index 00000000..645dd322
--- /dev/null
+++ b/cli/beacon/internal/dshsession/collect_test.go
@@ -0,0 +1,184 @@
+package dshsession
+
+import (
+ "bytes"
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
+ "github.com/klauspost/compress/zstd"
+)
+
+func TestStoreReadsPlainAndMapsDeepSeekSession(t *testing.T) {
+ root := t.TempDir()
+ sessionDir := filepath.Join(root, "sessions", "s1")
+ writeSession(t, sessionDir, SessionFileJSON,
+ record("session", map[string]interface{}{"id": "s1", "cwd": "/repo"}),
+ record("request/header", map[string]interface{}{"header": map[string]interface{}{"config": map[string]interface{}{"model": "deepseek-chat"}}}),
+ record("user/message", map[string]interface{}{"message": map[string]interface{}{"content": "fix tests"}}),
+ record("assistant/message", map[string]interface{}{"message": map[string]interface{}{
+ "source": map[string]interface{}{"model": "deepseek-chat"},
+ "content": []interface{}{
+ map[string]interface{}{"type": "reasoning", "text": "Need to inspect failure."},
+ map[string]interface{}{"type": "text", "text": "I will run tests."},
+ },
+ "usage": map[string]interface{}{"inputTokens": 11, "outputTokens": 7, "cacheReadTokens": 3, "cacheWriteTokens": 2, "reasoningTokens": 5},
+ }}),
+ record("tool/call", map[string]interface{}{"callId": "call_1", "name": "bash", "arguments": map[string]interface{}{"command": "go test ./..."}}),
+ record("tool/result", map[string]interface{}{"callId": "call_1", "toolName": "bash", "content": "FAIL\n[exit code: 1]"}),
+ record("tool/call", map[string]interface{}{"callId": "call_2", "name": "write", "arguments": map[string]interface{}{"file_path": "/repo/new.go", "content": "package main\n"}}),
+ record("tool/result", map[string]interface{}{"callId": "call_2", "toolName": "write", "content": "permission denied", "isError": true}),
+ )
+
+ store, err := NewStore(root)
+ if err != nil {
+ t.Fatal(err)
+ }
+ refs, err := store.List()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(refs) != 1 || refs[0].ID != "s1" || refs[0].Meta.CWD != "/repo" {
+ t.Fatalf("refs = %+v", refs)
+ }
+ records, stats, err := store.Read(refs[0])
+ if err != nil {
+ t.Fatal(err)
+ }
+ if stats.Decoded != 8 {
+ t.Fatalf("decoded = %d, want 8", stats.Decoded)
+ }
+ mapped := MapSession(refs[0], records, MapOptions{})
+ actions := actions(mapped)
+ for _, want := range []string{"session.started", "prompt.submitted", "agent.reasoning", "agent.message", "token.usage", "command.executed", "tool.failed"} {
+ if !contains(actions, want) {
+ t.Fatalf("actions = %v, missing %s", actions, want)
+ }
+ }
+ command := findAction(t, mapped, "command.executed")
+ if command.Command == nil || command.Command.Command != "go test ./..." {
+ t.Fatalf("command event = %+v", command)
+ }
+ if command.Command.ExitCode == nil || *command.Command.ExitCode != 1 {
+ t.Fatalf("exit code = %+v, want 1", command.Command)
+ }
+ usage := findAction(t, mapped, "token.usage")
+ if usage.GenAI == nil || usage.GenAI.Usage == nil || usage.GenAI.Usage.InputTokens == nil || *usage.GenAI.Usage.InputTokens != 11 {
+ t.Fatalf("usage = %+v", usage.GenAI)
+ }
+ failed := findAction(t, mapped, "tool.failed")
+ if failed.File != nil && failed.File.Diff != "" {
+ t.Fatalf("failed write carried a diff: %+v", failed.File)
+ }
+}
+
+func TestStoreReadsCompleteZstdFramesAndDefersPartialTail(t *testing.T) {
+ root := t.TempDir()
+ sessionDir := filepath.Join(root, "sessions", "z1")
+ full := zstdFrame(t, []byte(record("session", map[string]interface{}{"id": "z1", "cwd": "/repo"})+"\n"))
+ partial := zstdFrame(t, []byte(record("user/message", map[string]interface{}{"message": map[string]interface{}{"content": "later"}})+"\n"))
+ if len(partial) < 8 {
+ t.Fatal("zstd frame unexpectedly short")
+ }
+ writeBytes(t, filepath.Join(sessionDir, SessionFileZstd), append(full, partial[:len(partial)/2]...))
+ store, err := NewStore(root)
+ if err != nil {
+ t.Fatal(err)
+ }
+ refs, err := store.List()
+ if err != nil {
+ t.Fatal(err)
+ }
+ records, stats, err := store.Read(refs[0])
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(records) != 1 || records[0].Kind != "session" {
+ t.Fatalf("records = %+v", records)
+ }
+ if !stats.PartialFrame || !stats.PartialTail {
+ t.Fatalf("stats = %+v, want partial frame/tail", stats)
+ }
+}
+
+func TestCollectPrintDoesNotAdvanceState(t *testing.T) {
+ root := t.TempDir()
+ sessionDir := filepath.Join(root, "sessions", "s-print")
+ writeSession(t, sessionDir, SessionFileJSON,
+ record("session", map[string]interface{}{"id": "s-print", "cwd": "/repo"}),
+ record("user/message", map[string]interface{}{"message": map[string]interface{}{"content": "hello"}}),
+ )
+ statePath := filepath.Join(t.TempDir(), "state.json")
+ var out bytes.Buffer
+ summary, err := CollectOnce(CollectOptions{DSHHome: root, Print: true, Out: &out})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if summary.EventsEmitted != 2 || !strings.Contains(out.String(), `"prompt.submitted"`) {
+ t.Fatalf("summary=%+v out=%s", summary, out.String())
+ }
+ if _, err := os.Stat(statePath); !os.IsNotExist(err) {
+ t.Fatalf("--print wrote state file: %v", err)
+ }
+}
+
+func record(kind string, data map[string]interface{}) string {
+ line, _ := json.Marshal(map[string]interface{}{"type": kind, "time": "2026-09-21T10:00:00Z", "data": data})
+ return string(line)
+}
+
+func writeSession(t *testing.T, dir, name string, lines ...string) {
+ t.Helper()
+ writeBytes(t, filepath.Join(dir, name), []byte(strings.Join(lines, "\n")+"\n"))
+}
+
+func writeBytes(t *testing.T, path string, data []byte) {
+ t.Helper()
+ if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(path, data, 0644); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func zstdFrame(t *testing.T, data []byte) []byte {
+ t.Helper()
+ enc, err := zstd.NewWriter(nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer enc.Close()
+ return enc.EncodeAll(data, nil)
+}
+
+func actions(mapped []MappedEvent) []string {
+ out := make([]string, 0, len(mapped))
+ for _, item := range mapped {
+ out = append(out, item.Event.Event.Action)
+ }
+ return out
+}
+
+func contains(values []string, value string) bool {
+ for _, candidate := range values {
+ if candidate == value {
+ return true
+ }
+ }
+ return false
+}
+
+func findAction(t *testing.T, mapped []MappedEvent, action string) schema.Event {
+ t.Helper()
+ for _, item := range mapped {
+ if item.Event.Event.Action == action {
+ return item.Event
+ }
+ }
+ t.Fatalf("missing action %s in %v", action, actions(mapped))
+ return schema.Event{}
+}
diff --git a/cli/beacon/internal/dshsession/mapper.go b/cli/beacon/internal/dshsession/mapper.go
new file mode 100644
index 00000000..fe9f54a5
--- /dev/null
+++ b/cli/beacon/internal/dshsession/mapper.go
@@ -0,0 +1,682 @@
+package dshsession
+
+import (
+ "crypto/sha1"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+ "io"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
+)
+
+func MapSession(ref SessionRef, records []Record, opts MapOptions) []MappedEvent {
+ m := &mapper{
+ ref: ref,
+ opts: opts,
+ session: sessionMetaFromRef(ref),
+ calls: map[string]toolCall{},
+ lastTime: ref.ModTimeUnixMS,
+ }
+ for _, record := range records {
+ m.consumeContext(record)
+ if record.Line <= opts.MinLine {
+ continue
+ }
+ m.consume(record)
+ }
+ return m.out
+}
+
+type mapper struct {
+ ref SessionRef
+ opts MapOptions
+ session SessionMeta
+ model string
+ calls map[string]toolCall
+ out []MappedEvent
+ lastTime int64
+}
+
+type toolCall struct {
+ ID string
+ Name string
+ Arguments map[string]interface{}
+ Line int
+}
+
+func sessionMetaFromRef(ref SessionRef) SessionMeta {
+ if ref.Meta != nil {
+ return *ref.Meta
+ }
+ return SessionMeta{ID: ref.ID}
+}
+
+func (m *mapper) consumeContext(record Record) {
+ if record.TimeMS > 0 {
+ m.lastTime = record.TimeMS
+ }
+ switch record.Kind {
+ case "session":
+ if id := firstString(record.Data, "id", "sessionId", "session_id"); id != "" {
+ m.session.ID = id
+ }
+ if cwd := firstString(record.Data, "cwd", "workingDirectory", "working_directory"); cwd != "" {
+ m.session.CWD = cwd
+ }
+ if parent := firstString(record.Data, "parentSession", "parent_session", "parentSessionId"); parent != "" {
+ m.session.ParentSessionID = parent
+ }
+ case "request/header":
+ if model := requestHeaderModel(record.Data); model != "" {
+ m.model = model
+ m.session.Model = model
+ }
+ case "session/title":
+ if title := firstString(record.Data, "title"); title != "" {
+ m.session.Title = title
+ }
+ case "assistant/message":
+ if model := assistantModel(record.Data); model != "" {
+ m.model = model
+ }
+ case "tool/call", "tool/code-dispatch-start":
+ call := parseToolCall(record)
+ if call.ID != "" {
+ m.calls[call.ID] = call
+ }
+ }
+}
+
+func (m *mapper) consume(record Record) {
+ m.consumeContext(record)
+ switch record.Kind {
+ case "session":
+ if !m.opts.SkipSessionStarted {
+ m.emitSessionStarted(record)
+ }
+ case "user/message":
+ m.emitPrompt(record)
+ case "assistant/message":
+ m.emitAssistant(record)
+ case "tool/call", "tool/code-dispatch-start":
+ m.emitToolCall(record)
+ case "tool/result", "tool/code-dispatch":
+ m.emitToolResult(record)
+ case "turn/end":
+ m.emitTurnEnd(record)
+ }
+}
+
+func (m *mapper) emitSessionStarted(record Record) {
+ ev := m.base(record, "session.started", "session", schema.SeverityInfo, "DeepSeek Harness session started")
+ ev.Raw = rawDsh(record, map[string]interface{}{"source_path": m.ref.Path})
+ m.append(record, "session.started", ev)
+}
+
+func (m *mapper) emitPrompt(record Record) {
+ text := userMessageText(record.Data)
+ if text == "" {
+ return
+ }
+ ev := m.base(record, "prompt.submitted", "prompt", schema.SeverityInfo, "DeepSeek prompt submitted")
+ ev.Prompt = &schema.PromptInfo{Text: text}
+ ev.Content = asymptoteobserve.RetainedContent(text, asymptoteobserve.DefaultStringLimit)
+ ev.GenAI = withGenAI(ev.GenAI, func(genAI *schema.GenAIInfo) {
+ genAI.Input = &schema.GenAIInputInfo{Messages: asymptoteobserve.TextInputMessages(text)}
+ })
+ ev.Raw = rawDsh(record, nil)
+ m.append(record, "prompt.submitted", ev)
+}
+
+func (m *mapper) emitAssistant(record Record) {
+ model := firstNonEmpty(assistantModel(record.Data), m.model, m.session.Model)
+ for i, part := range assistantParts(record.Data) {
+ switch part.kind {
+ case "reasoning":
+ ev := m.base(record, "agent.reasoning", "agent", schema.SeverityInfo, "DeepSeek assistant reasoning")
+ ev.Model = model
+ ev.GenAI = withGenAI(ev.GenAI, func(genAI *schema.GenAIInfo) {
+ genAI.Output = &schema.GenAIOutputInfo{Messages: []map[string]interface{}{{
+ "role": "assistant",
+ "content": []map[string]string{{"type": "reasoning", "text": part.text}},
+ }}}
+ })
+ ev.Content = asymptoteobserve.RetainedContent(part.text, asymptoteobserve.DefaultRawStringLimit)
+ ev.Raw = rawDsh(record, nil)
+ m.append(record, fmt.Sprintf("assistant.reasoning.%d", i), ev)
+ case "text":
+ ev := m.base(record, "agent.message", "agent", schema.SeverityInfo, "DeepSeek assistant message")
+ ev.Model = model
+ ev.GenAI = withGenAI(ev.GenAI, func(genAI *schema.GenAIInfo) {
+ genAI.Output = &schema.GenAIOutputInfo{Messages: asymptoteobserve.TextOutputMessages(part.text)}
+ })
+ ev.Content = asymptoteobserve.RetainedContent(part.text, asymptoteobserve.DefaultRawStringLimit)
+ ev.Raw = rawDsh(record, nil)
+ m.append(record, fmt.Sprintf("assistant.text.%d", i), ev)
+ }
+ }
+ m.emitUsage(record)
+}
+
+func (m *mapper) emitToolCall(record Record) {
+ call := parseToolCall(record)
+ if call.ID != "" {
+ m.calls[call.ID] = call
+ }
+ if call.Name == "" {
+ return
+ }
+ ev := m.base(record, "tool.invoked", "tool", schema.SeverityInfo, "DeepSeek tool invoked")
+ ev.Tool = &schema.ToolInfo{Name: call.Name}
+ applyCall(&ev, call)
+ ev.Raw = rawDsh(record, nil)
+ m.append(record, "tool.call", ev)
+}
+
+func (m *mapper) emitToolResult(record Record) {
+ result := parseToolResult(record)
+ call := m.calls[result.CallID]
+ if result.Name != "" {
+ call.Name = result.Name
+ }
+ if call.ID == "" {
+ call.ID = result.CallID
+ }
+ if call.Name == "" {
+ return
+ }
+ action, category, severity, message := classifyDsh(call, result)
+ ev := m.base(record, action, category, severity, message)
+ ev.Tool = &schema.ToolInfo{Name: call.Name}
+ applyCall(&ev, call)
+ switch action {
+ case "command.executed":
+ applyCommand(&ev, call, result)
+ case "file.read", "file.modified":
+ applyFile(&ev, call, result)
+ case "mcp.tool_invoked":
+ ev.MCP = mcpInfo(call.Name)
+ }
+ if result.IsError {
+ ev.Error = &schema.ErrorInfo{Type: "tool_execution_failed"}
+ }
+ ev.Raw = rawDsh(record, map[string]interface{}{"tool_result": result.Raw})
+ m.append(record, "tool.result", ev)
+}
+
+func (m *mapper) emitTurnEnd(record Record) {
+ reason := childMap(record.Data, "reason")
+ kind := firstString(reason, "kind", "type")
+ if kind != "error" && kind != "interrupted" {
+ return
+ }
+ ev := m.base(record, "agent.error", "session", schema.SeverityHigh, "DeepSeek turn ended with error")
+ ev.Error = &schema.ErrorInfo{Type: kind}
+ ev.Raw = rawDsh(record, nil)
+ m.append(record, "turn.end."+kind, ev)
+}
+
+func (m *mapper) emitUsage(record Record) {
+ usage := usageFromAssistant(record.Data)
+ if usage == nil {
+ return
+ }
+ ev := m.base(record, "token.usage", "metric", schema.SeverityInfo, "DeepSeek token usage")
+ ev.GenAI = withGenAI(ev.GenAI, func(genAI *schema.GenAIInfo) { genAI.Usage = usage })
+ ev.Model = firstNonEmpty(assistantModel(record.Data), m.model, m.session.Model)
+ ev.Raw = rawDsh(record, map[string]interface{}{"token_source": "assistant_message"})
+ m.append(record, "usage", ev)
+}
+
+func (m *mapper) base(record Record, action, category string, severity schema.Severity, message string) schema.Event {
+ ts := m.lastTime
+ if record.TimeMS > 0 {
+ ts = record.TimeMS
+ }
+ if ts <= 0 {
+ ts = m.ref.ModTimeUnixMS
+ }
+ ev := schema.NewEvent(schema.NewEventOptions{
+ Action: action,
+ Category: category,
+ Severity: severity,
+ Harness: schema.HarnessInfo{
+ Name: Harness,
+ CollectionMethod: schema.CollectionMethodPoll,
+ },
+ Origin: schema.OriginLocal,
+ Fidelity: schema.FidelityObserved,
+ Message: message,
+ })
+ if ts > 0 {
+ ev.Timestamp = schema.FormatTimestamp(time.UnixMilli(ts))
+ }
+ ev.Session = &schema.SessionInfo{ID: firstNonEmpty(m.session.ID, m.ref.ID), WorkingDirectory: m.session.CWD}
+ if m.session.ParentSessionID != "" {
+ ev.Raw = mergeRaw(ev.Raw, map[string]interface{}{"parent_session": m.session.ParentSessionID})
+ }
+ if model := firstNonEmpty(m.model, m.session.Model); model != "" {
+ ev.Model = model
+ }
+ return ev
+}
+
+func (m *mapper) append(record Record, suffix string, ev schema.Event) {
+ dedupID := fmt.Sprintf("%s:%s:%d:%s", m.ref.Path, firstNonEmpty(m.session.ID, m.ref.ID), record.Line, suffix)
+ ev.Event.ID = dshEventID(dedupID)
+ m.out = append(m.out, MappedEvent{SourceLine: record.Line, DedupID: dedupID, Event: ev})
+}
+
+type assistantPart struct {
+ kind string
+ text string
+}
+
+type toolResult struct {
+ CallID string
+ Name string
+ Text string
+ IsError bool
+ Raw interface{}
+}
+
+func parseToolCall(record Record) toolCall {
+ data := unwrap(record.Data, "call", "toolCall", "tool_call")
+ args := argumentsFrom(data)
+ return toolCall{
+ ID: firstString(data, "callId", "callID", "id", "tool_call_id", "tool_use_id"),
+ Name: firstString(data, "name", "toolName", "tool_name"),
+ Arguments: args,
+ Line: record.Line,
+ }
+}
+
+func parseToolResult(record Record) toolResult {
+ data := unwrap(record.Data, "result", "toolResult", "tool_result")
+ callID := firstString(data, "callId", "callID", "id", "tool_call_id", "toolUseId", "tool_use_id")
+ name := firstString(data, "name", "toolName", "tool_name")
+ isError := boolValue(data["isError"]) || boolValue(data["is_error"]) || boolValue(data["error"])
+ text := resultText(data)
+ return toolResult{CallID: callID, Name: name, Text: text, IsError: isError, Raw: data}
+}
+
+func classifyDsh(call toolCall, result toolResult) (action, category string, severity schema.Severity, message string) {
+ name := strings.ToLower(strings.TrimSpace(call.Name))
+ if strings.HasPrefix(name, "mcp__") {
+ return "mcp.tool_invoked", "mcp", schema.SeverityInfo, "DeepSeek MCP tool invoked"
+ }
+ if result.IsError {
+ return "tool.failed", "tool", schema.SeverityHigh, "DeepSeek tool failed"
+ }
+ switch dshToolAction(call.Name, call.Arguments) {
+ case "command.executed":
+ return "command.executed", "command", schema.SeverityInfo, "DeepSeek command executed"
+ case "file.read":
+ return "file.read", "file", schema.SeverityInfo, "DeepSeek file read"
+ case "file.modified":
+ return "file.modified", "file", schema.SeverityInfo, "DeepSeek file modified"
+ default:
+ return "tool.completed", "tool", schema.SeverityInfo, "DeepSeek tool completed"
+ }
+}
+
+func applyCall(ev *schema.Event, call toolCall) {
+ ev.GenAI = withGenAI(ev.GenAI, func(genAI *schema.GenAIInfo) {
+ genAI.Operation = &schema.GenAIOperationInfo{Name: "execute_tool"}
+ genAI.Tool = &schema.GenAIToolInfo{
+ Name: call.Name,
+ Call: &schema.GenAIToolCallInfo{
+ ID: call.ID,
+ Arguments: call.Arguments,
+ },
+ }
+ })
+ if path := firstString(call.Arguments, "path", "file_path", "target_path"); path != "" {
+ ev.Tool.Path = path
+ }
+ if command := commandFromCall(call); command != "" {
+ ev.Tool.Command = command
+ }
+}
+
+func applyCommand(ev *schema.Event, call toolCall, result toolResult) {
+ info := &schema.CommandInfo{Command: commandFromCall(call)}
+ if result.Text != "" {
+ info.Output = result.Text
+ ev.Content = asymptoteobserve.RetainedContent(result.Text, asymptoteobserve.DefaultStringLimit)
+ }
+ if code, ok := dshExitCode(result.Text); ok {
+ info.ExitCode = &code
+ }
+ ev.Command = info
+}
+
+func applyFile(ev *schema.Event, call toolCall, result toolResult) {
+ path := firstString(call.Arguments, "file_path", "path")
+ info := &schema.FileInfo{Path: path, Operation: dshFileOperation(call.Name, call.Arguments)}
+ if path != "" {
+ info.Language = strings.TrimPrefix(filepath.Ext(path), ".")
+ }
+ if diff := diffFromCall(call); diff != "" && !result.IsError {
+ info.Diff = diff
+ info.DiffBytes = len(diff)
+ sum := sha256.Sum256([]byte(diff))
+ info.DiffHash = hex.EncodeToString(sum[:])
+ ev.Content = asymptoteobserve.RetainedContent(diff, asymptoteobserve.DefaultStringLimit)
+ }
+ ev.File = info
+}
+
+func diffFromCall(call toolCall) string {
+ name := strings.ToLower(strings.TrimSpace(call.Name))
+ path := firstString(call.Arguments, "file_path", "path")
+ switch name {
+ case "write":
+ content := firstString(call.Arguments, "content", "file_text")
+ if path != "" && content != "" {
+ return "--- /dev/null\n+++ " + path + "\n+" + strings.ReplaceAll(content, "\n", "\n+") + "\n"
+ }
+ case "edit":
+ oldText := firstString(call.Arguments, "old_string", "old_str")
+ newText := firstString(call.Arguments, "new_string", "new_str")
+ if oldText != "" || newText != "" {
+ return "-" + strings.ReplaceAll(oldText, "\n", "\n-") + "\n+" + strings.ReplaceAll(newText, "\n", "\n+") + "\n"
+ }
+ case "str_replace_editor":
+ op := dshEditorOperation(call.Name, call.Arguments)
+ if op == "create" {
+ content := firstString(call.Arguments, "file_text")
+ if content != "" {
+ return "--- /dev/null\n+++ " + path + "\n+" + strings.ReplaceAll(content, "\n", "\n+") + "\n"
+ }
+ }
+ if op == "str_replace" || op == "insert" {
+ oldText := firstString(call.Arguments, "old_str")
+ newText := firstString(call.Arguments, "new_str", "insert")
+ if oldText != "" || newText != "" {
+ return "-" + strings.ReplaceAll(oldText, "\n", "\n-") + "\n+" + strings.ReplaceAll(newText, "\n", "\n+") + "\n"
+ }
+ }
+ }
+ return ""
+}
+
+func mcpInfo(name string) *schema.MCPInfo {
+ trimmed := strings.TrimPrefix(name, "mcp__")
+ parts := strings.SplitN(trimmed, "__", 2)
+ if len(parts) == 2 {
+ return &schema.MCPInfo{Server: parts[0], Tool: parts[1]}
+ }
+ return &schema.MCPInfo{Tool: name}
+}
+
+func userMessageText(data map[string]interface{}) string {
+ data = unwrap(data, "message")
+ return textValue(firstPresent(data, "text", "content", "message"))
+}
+
+func assistantParts(data map[string]interface{}) []assistantPart {
+ msg := unwrap(data, "message")
+ raw := firstPresent(msg, "content", "parts")
+ var out []assistantPart
+ switch v := raw.(type) {
+ case []interface{}:
+ for _, item := range v {
+ m, _ := item.(map[string]interface{})
+ kind := firstNonEmpty(firstString(m, "type"), "text")
+ if kind == "tool-call" || kind == "tool_call" {
+ continue
+ }
+ text := textValue(firstPresent(m, "text", "content"))
+ if text != "" {
+ out = append(out, assistantPart{kind: normalizePartKind(kind), text: text})
+ }
+ }
+ default:
+ if text := textValue(raw); text != "" {
+ out = append(out, assistantPart{kind: "text", text: text})
+ }
+ }
+ if reasoning := firstString(msg, "reasoning", "reasoningText", "reasoning_content"); reasoning != "" {
+ out = append([]assistantPart{{kind: "reasoning", text: reasoning}}, out...)
+ }
+ return out
+}
+
+func usageFromAssistant(data map[string]interface{}) *schema.GenAIUsageInfo {
+ msg := unwrap(data, "message")
+ u := childMap(firstMap(msg, "usage"), "usage")
+ if len(u) == 0 {
+ u = firstMap(msg, "usage")
+ }
+ if len(u) == 0 {
+ u = firstMap(data, "usage")
+ }
+ usage := &schema.GenAIUsageInfo{}
+ if n, ok := int64Value(firstPresent(u, "inputTokens", "input_tokens", "promptTokens")); ok && n > 0 {
+ usage.InputTokens = &n
+ }
+ if n, ok := int64Value(firstPresent(u, "outputTokens", "output_tokens", "completionTokens")); ok && n > 0 {
+ usage.OutputTokens = &n
+ }
+ if n, ok := int64Value(firstPresent(u, "cacheReadTokens", "cache_read_tokens")); ok && n > 0 {
+ usage.CacheRead = &schema.GenAIUsageCacheReadInfo{InputTokens: &n}
+ }
+ if n, ok := int64Value(firstPresent(u, "cacheWriteTokens", "cache_write_tokens")); ok && n > 0 {
+ usage.CacheCreation = &schema.GenAIUsageCacheCreationInfo{InputTokens: &n}
+ }
+ if n, ok := int64Value(firstPresent(u, "reasoningTokens", "reasoning_tokens")); ok && n > 0 {
+ usage.Reasoning = &schema.GenAIUsageReasoningInfo{OutputTokens: &n}
+ }
+ if usage.InputTokens == nil && usage.OutputTokens == nil && usage.CacheRead == nil && usage.CacheCreation == nil && usage.Reasoning == nil {
+ return nil
+ }
+ return usage
+}
+
+func requestHeaderModel(data map[string]interface{}) string {
+ header := childMap(data, "header")
+ config := childMap(header, "config")
+ return firstString(config, "model")
+}
+
+func assistantModel(data map[string]interface{}) string {
+ msg := unwrap(data, "message")
+ source := childMap(msg, "source")
+ return firstNonEmpty(firstString(source, "model"), firstString(msg, "model"))
+}
+
+func rawDsh(record Record, extra map[string]interface{}) map[string]interface{} {
+ raw := map[string]interface{}{}
+ if len(record.Raw) > 0 {
+ var decoded map[string]interface{}
+ if json.Unmarshal(record.Raw, &decoded) == nil {
+ raw["record"] = decoded
+ }
+ }
+ for k, v := range extra {
+ raw[k] = v
+ }
+ return map[string]interface{}{"dsh": raw}
+}
+
+func mergeRaw(existing map[string]interface{}, fields map[string]interface{}) map[string]interface{} {
+ if len(fields) == 0 {
+ return existing
+ }
+ if existing == nil {
+ existing = map[string]interface{}{}
+ }
+ dsh, _ := existing["dsh"].(map[string]interface{})
+ if dsh == nil {
+ dsh = map[string]interface{}{}
+ }
+ for k, v := range fields {
+ dsh[k] = v
+ }
+ existing["dsh"] = dsh
+ return existing
+}
+
+func withGenAI(genAI *schema.GenAIInfo, edit func(*schema.GenAIInfo)) *schema.GenAIInfo {
+ if genAI == nil {
+ genAI = &schema.GenAIInfo{}
+ }
+ edit(genAI)
+ return genAI
+}
+
+func unwrap(data map[string]interface{}, keys ...string) map[string]interface{} {
+ for _, key := range keys {
+ if child, ok := data[key].(map[string]interface{}); ok {
+ return child
+ }
+ }
+ return data
+}
+
+func argumentsFrom(data map[string]interface{}) map[string]interface{} {
+ if args := firstMap(data, "arguments", "args", "input", "tool_input"); len(args) > 0 {
+ return args
+ }
+ if text := firstString(data, "argumentsJson", "arguments_json"); text != "" {
+ var args map[string]interface{}
+ if json.Unmarshal([]byte(text), &args) == nil {
+ return args
+ }
+ return map[string]interface{}{"value": text}
+ }
+ return map[string]interface{}{}
+}
+
+func resultText(data map[string]interface{}) string {
+ return textValue(firstPresent(data, "text", "output", "content", "result"))
+}
+
+func textValue(value interface{}) string {
+ switch v := value.(type) {
+ case nil:
+ return ""
+ case string:
+ return v
+ case []interface{}:
+ parts := make([]string, 0, len(v))
+ for _, item := range v {
+ if text := textValue(item); text != "" {
+ parts = append(parts, text)
+ }
+ }
+ return strings.Join(parts, "\n")
+ case map[string]interface{}:
+ return firstNonEmpty(firstString(v, "text"), firstString(v, "content"), firstString(v, "value"))
+ default:
+ return fmt.Sprint(v)
+ }
+}
+
+func firstPresent(data map[string]interface{}, keys ...string) interface{} {
+ for _, key := range keys {
+ if value, ok := data[key]; ok {
+ return value
+ }
+ }
+ return nil
+}
+
+func firstMap(data map[string]interface{}, keys ...string) map[string]interface{} {
+ for _, key := range keys {
+ if child, ok := data[key].(map[string]interface{}); ok {
+ return child
+ }
+ }
+ return nil
+}
+
+func childMap(data map[string]interface{}, key string) map[string]interface{} {
+ child, _ := data[key].(map[string]interface{})
+ if child == nil {
+ return map[string]interface{}{}
+ }
+ return child
+}
+
+func firstString(data map[string]interface{}, keys ...string) string {
+ for _, key := range keys {
+ if value, ok := data[key]; ok {
+ if text := strings.TrimSpace(textValue(value)); text != "" {
+ return text
+ }
+ }
+ }
+ return ""
+}
+
+func firstNonEmpty(values ...string) string {
+ for _, value := range values {
+ if strings.TrimSpace(value) != "" {
+ return value
+ }
+ }
+ return ""
+}
+
+func int64Value(value interface{}) (int64, bool) {
+ switch v := value.(type) {
+ case float64:
+ return int64(v), v >= 0
+ case int64:
+ return v, v >= 0
+ case int:
+ return int64(v), v >= 0
+ case string:
+ n, err := strconv.ParseInt(strings.TrimSpace(v), 10, 64)
+ return n, err == nil && n >= 0
+ default:
+ return 0, false
+ }
+}
+
+func boolValue(value interface{}) bool {
+ switch v := value.(type) {
+ case bool:
+ return v
+ case string:
+ return strings.EqualFold(v, "true") || strings.EqualFold(v, "error")
+ default:
+ return false
+ }
+}
+
+func normalizePartKind(kind string) string {
+ switch strings.ToLower(strings.TrimSpace(kind)) {
+ case "reasoning", "thinking":
+ return "reasoning"
+ default:
+ return "text"
+ }
+}
+
+var dshIDNamespace = [16]byte{
+ 0x4d, 0x73, 0x68, 0x21, 0x18, 0xa5, 0x4e, 0x6f,
+ 0x99, 0x0a, 0xdf, 0x82, 0x33, 0x52, 0x1c, 0x0d,
+}
+
+func dshEventID(dedupID string) string {
+ digest := sha1.New()
+ digest.Write(dshIDNamespace[:])
+ io.WriteString(digest, dedupID)
+ var id [16]byte
+ copy(id[:], digest.Sum(nil))
+ id[6] = (id[6] & 0x0f) | 0x50
+ id[8] = (id[8] & 0x3f) | 0x80
+ out := make([]byte, 32)
+ hex.Encode(out, id[:])
+ return fmt.Sprintf("%s-%s-%s-%s-%s", out[0:8], out[8:12], out[12:16], out[16:20], out[20:32])
+}
diff --git a/cli/beacon/internal/dshsession/store.go b/cli/beacon/internal/dshsession/store.go
new file mode 100644
index 00000000..6cb9b79f
--- /dev/null
+++ b/cli/beacon/internal/dshsession/store.go
@@ -0,0 +1,289 @@
+package dshsession
+
+import (
+ "bufio"
+ "bytes"
+ "errors"
+ "fmt"
+ "io"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+
+ "github.com/klauspost/compress/zstd"
+)
+
+type Store struct {
+ DSHHome string
+ SessionsDir string
+}
+
+func DefaultDSHHome() (string, error) {
+ if value := strings.TrimSpace(os.Getenv("DSH_HOME")); value != "" {
+ return value, nil
+ }
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return "", fmt.Errorf("resolve home directory: %w", err)
+ }
+ if strings.TrimSpace(home) == "" {
+ return "", errors.New("home directory is empty")
+ }
+ return filepath.Join(home, ".dsh"), nil
+}
+
+func NewStore(dshHome string) (*Store, error) {
+ root := strings.TrimSpace(dshHome)
+ if root == "" {
+ def, err := DefaultDSHHome()
+ if err != nil {
+ return nil, err
+ }
+ root = def
+ }
+ return &Store{DSHHome: root, SessionsDir: filepath.Join(root, "sessions")}, nil
+}
+
+func (s *Store) Exists() bool {
+ info, err := os.Stat(s.SessionsDir)
+ return err == nil && info.IsDir()
+}
+
+func (s *Store) List() ([]SessionRef, error) {
+ type candidate struct {
+ dir string
+ path string
+ }
+ byDir := map[string]candidate{}
+ dirs := 0
+ files := 0
+ err := filepath.WalkDir(s.SessionsDir, func(path string, d fs.DirEntry, walkErr error) error {
+ if walkErr != nil {
+ return nil
+ }
+ if d.IsDir() {
+ dirs++
+ if dirs > MaxDirectories {
+ return filepath.SkipDir
+ }
+ return nil
+ }
+ files++
+ if files > MaxFiles {
+ return filepath.SkipAll
+ }
+ name := d.Name()
+ if name != SessionFileZstd && name != SessionFileJSON {
+ return nil
+ }
+ dir := filepath.Dir(path)
+ prior, ok := byDir[dir]
+ if !ok || filepath.Base(path) == SessionFileZstd || filepath.Base(prior.path) != SessionFileZstd {
+ byDir[dir] = candidate{dir: dir, path: path}
+ }
+ return nil
+ })
+ if err != nil {
+ if errors.Is(err, fs.ErrNotExist) {
+ return nil, nil
+ }
+ return nil, fmt.Errorf("read DeepSeek sessions directory: %w", err)
+ }
+ refs := make([]SessionRef, 0, len(byDir))
+ for _, item := range byDir {
+ info, err := os.Stat(item.path)
+ if err != nil || info.IsDir() {
+ continue
+ }
+ ref := SessionRef{
+ ID: filepath.Base(item.dir),
+ Path: item.path,
+ Dir: item.dir,
+ DSHHome: s.DSHHome,
+ ModTimeUnixMS: info.ModTime().UnixMilli(),
+ SizeBytes: info.Size(),
+ Compressed: filepath.Base(item.path) == SessionFileZstd,
+ }
+ if meta := s.readMeta(ref); meta != nil {
+ ref.Meta = meta
+ if strings.TrimSpace(meta.ID) != "" {
+ ref.ID = meta.ID
+ }
+ }
+ refs = append(refs, ref)
+ }
+ sort.SliceStable(refs, func(i, j int) bool {
+ if refs[i].ModTimeUnixMS != refs[j].ModTimeUnixMS {
+ return refs[i].ModTimeUnixMS < refs[j].ModTimeUnixMS
+ }
+ return refs[i].Path < refs[j].Path
+ })
+ return refs, nil
+}
+
+func (s *Store) Read(ref SessionRef) ([]Record, Stats, error) {
+ var reader io.Reader
+ var stats Stats
+ data, err := os.ReadFile(ref.Path)
+ if err != nil {
+ return nil, stats, err
+ }
+ if ref.Compressed {
+ plain, partial, err := decodeZstdFrames(data)
+ if err != nil {
+ return nil, stats, err
+ }
+ stats.PartialFrame = partial
+ stats.PartialTail = partial
+ reader = bytes.NewReader(plain)
+ } else {
+ reader = bytes.NewReader(data)
+ }
+ records, lineStats, err := decodeRecords(reader)
+ lineStats.PartialFrame = stats.PartialFrame
+ if lineStats.PartialFrame {
+ lineStats.PartialTail = true
+ }
+ return records, lineStats, err
+}
+
+func (s *Store) readMeta(ref SessionRef) *SessionMeta {
+ records, _, err := s.Read(ref)
+ if err != nil {
+ return nil
+ }
+ meta := &SessionMeta{}
+ for _, record := range records {
+ switch record.Kind {
+ case "session":
+ meta.ID = firstString(record.Data, "id", "sessionId", "session_id")
+ meta.CWD = firstString(record.Data, "cwd", "workingDirectory", "working_directory")
+ meta.ParentSessionID = firstString(record.Data, "parentSession", "parent_session", "parentSessionId")
+ case "session/title":
+ meta.Title = firstString(record.Data, "title")
+ case "request/header":
+ meta.Model = requestHeaderModel(record.Data)
+ }
+ if meta.ID != "" && meta.CWD != "" && meta.Title != "" && meta.Model != "" {
+ break
+ }
+ }
+ if meta.ID == "" && meta.CWD == "" && meta.ParentSessionID == "" && meta.Title == "" && meta.Model == "" {
+ return nil
+ }
+ return meta
+}
+
+func decodeRecords(r io.Reader) ([]Record, Stats, error) {
+ br := bufio.NewReaderSize(r, 64*1024)
+ var records []Record
+ var stats Stats
+ lineNo := 0
+ for {
+ line, partial, oversized, err := readLine(br)
+ if err != nil {
+ if errors.Is(err, io.EOF) {
+ if partial {
+ stats.PartialTail = true
+ }
+ break
+ }
+ return records, stats, err
+ }
+ lineNo++
+ stats.Lines = lineNo
+ if oversized {
+ stats.Malformed++
+ if stats.FirstError == nil {
+ stats.FirstError = fmt.Errorf("dsh session line exceeds %d bytes", MaxLineBytes)
+ }
+ continue
+ }
+ if len(bytes.TrimSpace(line)) == 0 {
+ continue
+ }
+ record, err := decodeRecord(line, lineNo)
+ if err != nil {
+ stats.Malformed++
+ if stats.FirstError == nil {
+ stats.FirstError = err
+ }
+ continue
+ }
+ stats.Decoded++
+ records = append(records, *record)
+ }
+ return records, stats, nil
+}
+
+func readLine(br *bufio.Reader) (line []byte, partial, oversized bool, err error) {
+ var buf []byte
+ for {
+ chunk, readErr := br.ReadSlice('\n')
+ if oversized || len(buf)+len(chunk) > MaxLineBytes {
+ oversized = true
+ buf = nil
+ } else {
+ buf = append(buf, chunk...)
+ }
+ if errors.Is(readErr, bufio.ErrBufferFull) {
+ continue
+ }
+ if errors.Is(readErr, io.EOF) {
+ if oversized {
+ return nil, false, true, nil
+ }
+ if len(buf) > 0 {
+ return buf, true, false, io.EOF
+ }
+ return nil, false, false, io.EOF
+ }
+ if readErr != nil {
+ return nil, false, false, readErr
+ }
+ break
+ }
+ if oversized {
+ return nil, false, true, nil
+ }
+ return bytes.TrimSuffix(bytes.TrimSuffix(buf, []byte("\n")), []byte("\r")), false, false, nil
+}
+
+var zstdMagic = []byte{0x28, 0xb5, 0x2f, 0xfd}
+
+func decodeZstdFrames(data []byte) ([]byte, bool, error) {
+ decoder, err := zstd.NewReader(nil)
+ if err != nil {
+ return nil, false, err
+ }
+ defer decoder.Close()
+ var out bytes.Buffer
+ partial := false
+ offset := 0
+ for offset < len(data) {
+ next := bytes.Index(data[offset:], zstdMagic)
+ if next < 0 {
+ partial = strings.TrimSpace(string(data[offset:])) != ""
+ break
+ }
+ start := offset + next
+ follow := bytes.Index(data[start+len(zstdMagic):], zstdMagic)
+ end := len(data)
+ if follow >= 0 {
+ end = start + len(zstdMagic) + follow
+ }
+ decoded, err := decoder.DecodeAll(data[start:end], nil)
+ if err != nil {
+ if follow < 0 {
+ partial = true
+ break
+ }
+ return nil, partial, fmt.Errorf("decode DeepSeek zstd frame: %w", err)
+ }
+ out.Write(decoded)
+ offset = end
+ }
+ return out.Bytes(), partial, nil
+}
diff --git a/cli/beacon/internal/dshsession/taxonomy.go b/cli/beacon/internal/dshsession/taxonomy.go
new file mode 100644
index 00000000..ad2ae185
--- /dev/null
+++ b/cli/beacon/internal/dshsession/taxonomy.go
@@ -0,0 +1,188 @@
+package dshsession
+
+import (
+ "strconv"
+ "strings"
+)
+
+type dshToolKind int
+
+const (
+ dshToolOther dshToolKind = iota
+ dshToolRead
+ dshToolCreate
+ dshToolModify
+ dshToolShell
+)
+
+var dshToolKinds = map[string]dshToolKind{
+ "read": dshToolRead,
+ "read_image": dshToolRead,
+ "glob": dshToolRead,
+ "grep": dshToolRead,
+
+ "write": dshToolCreate,
+ "edit": dshToolModify,
+ "str_replace_editor": dshToolCreate,
+
+ "bash": dshToolShell,
+ "pwsh": dshToolShell,
+ "terminal_send": dshToolShell,
+
+ "terminal_open": dshToolOther,
+ "terminal_read": dshToolOther,
+ "terminal_list": dshToolOther,
+ "terminal_close": dshToolOther,
+ "terminal_signal": dshToolOther,
+ "job_output": dshToolOther,
+ "job_list": dshToolOther,
+ "job_kill": dshToolOther,
+
+ "run_code": dshToolOther,
+ "ask_user_question": dshToolOther,
+ "exit_plan_mode": dshToolOther,
+ "present": dshToolOther,
+ "plugin_manager": dshToolOther,
+ "lsp": dshToolOther,
+ "ralph": dshToolOther,
+ "skill": dshToolOther,
+ "workflow": dshToolOther,
+ "todo_write": dshToolOther,
+ "web_fetch": dshToolOther,
+ "web_search": dshToolOther,
+ "create_goal": dshToolOther,
+ "get_goal": dshToolOther,
+ "update_goal": dshToolOther,
+ "schedule_create": dshToolOther,
+ "schedule_delete": dshToolOther,
+ "schedule_list": dshToolOther,
+ "subagent": dshToolOther,
+ "list_subagent_models": dshToolOther,
+ "spawn_teammate": dshToolOther,
+ "wait_agent": dshToolOther,
+ "interrupt_agent": dshToolOther,
+ "list_agents": dshToolOther,
+ "send_message": dshToolOther,
+ "team_task_create": dshToolOther,
+ "team_task_get": dshToolOther,
+ "team_task_list": dshToolOther,
+ "team_task_update": dshToolOther,
+ "session_search": dshToolOther,
+ "session_trace": dshToolOther,
+ "session_event_read": dshToolOther,
+ "session_event_search": dshToolOther,
+ "session_event_trace": dshToolOther,
+ "cordis_inspect_list": dshToolOther,
+ "cordis_inspect_query": dshToolOther,
+ "stagehand_act": dshToolOther,
+ "stagehand_extract": dshToolOther,
+ "stagehand_navigate": dshToolOther,
+ "stagehand_observe": dshToolOther,
+ "stagehand_screenshot": dshToolOther,
+ "stagehand_tabs": dshToolOther,
+ "list_mcp_resources": dshToolOther,
+ "list_mcp_resource_templates": dshToolOther,
+ "read_mcp_resource": dshToolOther,
+}
+
+var dshEditorCommands = map[string]bool{
+ "view": true,
+ "create": true,
+ "str_replace": true,
+ "insert": true,
+}
+
+const dshExitCodeMarkerPrefix = "[exit code:"
+
+func dshToolAction(toolName string, toolInput map[string]interface{}) string {
+ kind, known := dshEffectiveToolKind(toolName, toolInput)
+ if !known {
+ return ""
+ }
+ switch kind {
+ case dshToolRead:
+ return "file.read"
+ case dshToolCreate, dshToolModify:
+ return "file.modified"
+ case dshToolShell:
+ return "command.executed"
+ default:
+ return "tool.invoked"
+ }
+}
+
+func dshFileOperation(toolName string, toolInput map[string]interface{}) string {
+ kind, known := dshEffectiveToolKind(toolName, toolInput)
+ if !known {
+ return ""
+ }
+ switch kind {
+ case dshToolRead:
+ return "read"
+ case dshToolCreate:
+ return "create"
+ case dshToolModify:
+ return "modify"
+ default:
+ return ""
+ }
+}
+
+func dshEffectiveToolKind(toolName string, toolInput map[string]interface{}) (dshToolKind, bool) {
+ kind, known := dshToolKinds[strings.ToLower(strings.TrimSpace(toolName))]
+ if !known {
+ return dshToolOther, false
+ }
+ if operation := dshEditorOperation(toolName, toolInput); operation != "" {
+ kind = dshEditorKindForOperation(operation)
+ }
+ return kind, true
+}
+
+func dshEditorOperation(toolName string, toolInput map[string]interface{}) string {
+ if strings.ToLower(strings.TrimSpace(toolName)) != "str_replace_editor" {
+ return ""
+ }
+ value := strings.ToLower(strings.TrimSpace(firstString(toolInput, "command")))
+ if !dshEditorCommands[value] {
+ return ""
+ }
+ return value
+}
+
+func dshEditorKindForOperation(operation string) dshToolKind {
+ switch operation {
+ case "view":
+ return dshToolRead
+ case "create":
+ return dshToolCreate
+ default:
+ return dshToolModify
+ }
+}
+
+func commandFromCall(call toolCall) string {
+ switch strings.ToLower(strings.TrimSpace(call.Name)) {
+ case "terminal_send":
+ return firstString(call.Arguments, "text")
+ default:
+ return firstString(call.Arguments, "command", "cmd")
+ }
+}
+
+func dshExitCode(output string) (int, bool) {
+ index := strings.LastIndex(output, dshExitCodeMarkerPrefix)
+ if index < 0 {
+ return 0, false
+ }
+ rest := output[index+len(dshExitCodeMarkerPrefix):]
+ end := strings.Index(rest, "]")
+ if end < 0 {
+ return 0, false
+ }
+ code, err := strconv.Atoi(strings.TrimSpace(rest[:end]))
+ if err != nil {
+ return 0, false
+ }
+ return code, true
+}
diff --git a/cli/beacon/internal/dshsession/types.go b/cli/beacon/internal/dshsession/types.go
new file mode 100644
index 00000000..e74bfcba
--- /dev/null
+++ b/cli/beacon/internal/dshsession/types.go
@@ -0,0 +1,142 @@
+// Package dshsession reads DeepSeek Harness' native session store and maps it
+// into Beacon endpoint events.
+package dshsession
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "math"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
+)
+
+const (
+ Harness = "deepseek_harness"
+ StateVersion = 1
+
+ SessionFileZstd = "session.jsonl.zstd"
+ SessionFileJSON = "session.jsonl"
+
+ MaxFiles = 15000
+ MaxDirectories = 4000
+ MaxLineBytes = 8 * 1024 * 1024
+)
+
+type Record struct {
+ Line int
+ Kind string
+ TimeMS int64
+ Data map[string]interface{}
+ Raw json.RawMessage
+}
+
+type SessionRef struct {
+ ID string
+ Path string
+ Dir string
+ DSHHome string
+ ModTimeUnixMS int64
+ SizeBytes int64
+ Compressed bool
+ Meta *SessionMeta
+}
+
+type SessionMeta struct {
+ ID string
+ CWD string
+ ParentSessionID string
+ Title string
+ Model string
+}
+
+type Stats struct {
+ Lines int
+ Decoded int
+ Malformed int
+ PartialTail bool
+ PartialFrame bool
+ FirstError error
+}
+
+type MapOptions struct {
+ MinLine int
+ SkipSessionStarted bool
+}
+
+type MappedEvent struct {
+ SourceLine int
+ DedupID string
+ Event schema.Event
+}
+
+type envelope struct {
+ Type string `json:"type"`
+ Time interface{} `json:"time"`
+ CreatedAt interface{} `json:"createdAt"`
+ Data json.RawMessage `json:"data"`
+}
+
+func decodeRecord(line []byte, lineNo int) (*Record, error) {
+ var env envelope
+ if err := json.Unmarshal(line, &env); err != nil {
+ return nil, err
+ }
+ if strings.TrimSpace(env.Type) == "" {
+ return nil, errors.New("dsh record type is empty")
+ }
+ data := map[string]interface{}{}
+ if len(env.Data) > 0 && string(env.Data) != "null" {
+ if err := json.Unmarshal(env.Data, &data); err != nil {
+ return nil, fmt.Errorf("decode dsh record data: %w", err)
+ }
+ }
+ return &Record{
+ Line: lineNo,
+ Kind: env.Type,
+ TimeMS: firstTimeMS(env.Time, env.CreatedAt),
+ Data: data,
+ Raw: append(json.RawMessage(nil), line...),
+ }, nil
+}
+
+func firstTimeMS(values ...interface{}) int64 {
+ for _, value := range values {
+ if ms := timeMS(value); ms > 0 {
+ return ms
+ }
+ }
+ return 0
+}
+
+func timeMS(value interface{}) int64 {
+ switch v := value.(type) {
+ case nil:
+ return 0
+ case float64:
+ if math.IsNaN(v) || math.IsInf(v, 0) || v <= 0 {
+ return 0
+ }
+ if v < 1e12 {
+ return int64(v * 1000)
+ }
+ return int64(v)
+ case string:
+ text := strings.TrimSpace(v)
+ if text == "" {
+ return 0
+ }
+ if n, err := strconv.ParseFloat(text, 64); err == nil {
+ return timeMS(n)
+ }
+ if t, err := time.Parse(time.RFC3339Nano, text); err == nil {
+ return t.UnixMilli()
+ }
+ return 0
+ default:
+ return 0
+ }
+}
diff --git a/cli/beacon/internal/endpoint/harness/dsh.go b/cli/beacon/internal/endpoint/harness/dsh.go
new file mode 100644
index 00000000..668b1d44
--- /dev/null
+++ b/cli/beacon/internal/endpoint/harness/dsh.go
@@ -0,0 +1,84 @@
+package harness
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/dshsession"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/hooks"
+)
+
+func DiscoverDsh() Harness {
+ h := Harness{Name: dshsession.Harness, DisplayName: "DeepSeek Harness", Capability: "hooks+session_log"}
+ detectExecutable(&h, "dsh")
+ store, err := dshsession.NewStore("")
+ if err != nil {
+ h.TelemetryStatus = TelemetryMissing
+ h.Message = "DeepSeek Harness home could not be resolved: " + err.Error()
+ return h
+ }
+ if !h.Detected && dirExists(store.DSHHome) {
+ h.Detected = true
+ }
+ hookStatus := hooks.DshHookStatus(hooks.DshOptions{Level: hooks.LevelUser})
+ if hookStatus.Installed {
+ h.ConfigPath = hookStatus.HooksPath
+ } else {
+ h.ConfigPath = store.SessionsDir
+ }
+ h.TelemetryStatus, h.Message = dshCollectionStatus(hookStatus.Installed, store.SessionsDir)
+ return h
+}
+
+func dshCollectionStatus(hooksInstalled bool, sessionsDir string) (TelemetryStatus, string) {
+ collected, total, err := dshSessionProgress(sessionsDir)
+ if hooksInstalled {
+ msg := "Beacon DeepSeek Harness hooks are configured"
+ if err == nil && total > collected {
+ msg += fmt.Sprintf("; %d of %d native session(s) not backfilled, run `beacon endpoint dsh sync` to collect them", total-collected, total)
+ }
+ return TelemetryEnabled, msg
+ }
+ if err != nil {
+ return TelemetryMisconfigured, "DeepSeek Harness hooks are not installed and the session collector state could not be read: " + err.Error()
+ }
+ switch {
+ case total == 0:
+ return TelemetryDisabled, "DeepSeek Harness endpoint hooks are not installed; run `beacon endpoint hooks install --harness dsh`"
+ case collected == 0:
+ return TelemetryDisabled, fmt.Sprintf("DeepSeek Harness endpoint hooks are not installed and none of %d native session(s) have been collected; run `beacon endpoint hooks install --harness dsh`", total)
+ case collected < total:
+ return TelemetryEnabled, fmt.Sprintf("DeepSeek Harness session telemetry collected for %d of %d session(s); run `beacon endpoint dsh sync` to catch up", collected, total)
+ default:
+ return TelemetryEnabled, fmt.Sprintf("DeepSeek Harness session telemetry collected for all %d session(s)", total)
+ }
+}
+
+func dshSessionProgress(sessionsDir string) (collected, total int, err error) {
+ if info, statErr := os.Stat(sessionsDir); statErr != nil || !info.IsDir() {
+ return 0, 0, nil
+ }
+ store, err := dshsession.NewStore(filepath.Dir(sessionsDir))
+ if err != nil {
+ return 0, 0, err
+ }
+ refs, err := store.List()
+ if err != nil {
+ return 0, 0, err
+ }
+ if len(refs) == 0 {
+ return 0, 0, nil
+ }
+ state, err := dshsession.LoadState(dshsession.DefaultStatePath())
+ if err != nil {
+ return 0, len(refs), err
+ }
+ for _, ref := range refs {
+ cursor := state.Sources[ref.Path]
+ if cursor != nil && cursor.ModTimeMS >= ref.ModTimeUnixMS && cursor.SizeBytes == ref.SizeBytes && cursor.Events > 0 && !cursor.PartialTail && !cursor.PartialFrame {
+ collected++
+ }
+ }
+ return collected, len(refs), nil
+}
diff --git a/cli/beacon/internal/endpoint/harness/harness.go b/cli/beacon/internal/endpoint/harness/harness.go
index 3170f375..68b2c4f2 100644
--- a/cli/beacon/internal/endpoint/harness/harness.go
+++ b/cli/beacon/internal/endpoint/harness/harness.go
@@ -64,6 +64,7 @@ func DiscoverAll() []Harness {
DiscoverPrime(),
DiscoverOmo(),
DiscoverFx(),
+ DiscoverDsh(),
DiscoverQwen(),
DiscoverHermes(),
DiscoverFactory(),
diff --git a/cli/beacon/internal/endpoint/hooks/dsh.go b/cli/beacon/internal/endpoint/hooks/dsh.go
index cf1ff5be..a81ea9f0 100644
--- a/cli/beacon/internal/endpoint/hooks/dsh.go
+++ b/cli/beacon/internal/endpoint/hooks/dsh.go
@@ -77,6 +77,9 @@ const (
// dshHomeDirName is the default Harness home under the user's home directory.
dshHomeDirName = ".dsh"
+
+ dshSkillRelPath = "skills/beacon-endpoint/SKILL.md"
+ dshSkillMarker = "beacon-managed-dsh-skill:v1"
)
// dsh hook timeouts are seconds -- the bridge reads a hook's `timeout` as `timeoutSec`, matching
@@ -180,14 +183,25 @@ func InstallDsh(opts DshOptions) (DshStatus, error) {
if err != nil {
return DshStatus{}, err
}
+ if status.ConfigPath != "" {
+ if err := installDshSkill(filepath.Dir(status.ConfigPath)); err != nil {
+ return DshStatus{}, err
+ }
+ }
return dshStatusFromRuntime(status), nil
}
func UninstallDsh(opts DshOptions) (DshStatus, error) {
+ home, _ := dshHomeDir(Level(opts.Level))
status, err := uninstallRuntimeHooks(dshRuntime, RuntimeOptions(opts))
if err != nil {
return DshStatus{}, err
}
+ if home != "" {
+ if err := removeDshSkill(home); err != nil {
+ return DshStatus{}, err
+ }
+ }
return dshStatusFromRuntime(status), nil
}
@@ -412,3 +426,76 @@ func dshHomeDir(level Level) (string, error) {
return "", fmt.Errorf("unknown hook level %q", level)
}
}
+
+func installDshSkill(home string) error {
+ path := filepath.Join(home, dshSkillRelPath)
+ if data, err := os.ReadFile(path); err == nil {
+ if !strings.Contains(string(data), dshSkillMarker) {
+ return fmt.Errorf("%s already exists and is not Beacon-managed; remove it or choose a different skill name before reinstalling", path)
+ }
+ } else if !os.IsNotExist(err) {
+ return err
+ }
+ if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
+ return err
+ }
+ return os.WriteFile(path, []byte(dshSkillContent()), 0644)
+}
+
+func removeDshSkill(home string) error {
+ path := filepath.Join(home, dshSkillRelPath)
+ data, err := os.ReadFile(path)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return nil
+ }
+ return err
+ }
+ if !strings.Contains(string(data), dshSkillMarker) {
+ return nil
+ }
+ if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
+ return err
+ }
+ _ = os.Remove(filepath.Dir(path))
+ return nil
+}
+
+func dshSkillContent() string {
+ return `---
+name: beacon-endpoint
+description: Keep Beacon's local DeepSeek Harness backfill current for the active session.
+---
+
+# Beacon Endpoint
+
+<!-- ` + dshSkillMarker + ` -->
+
+Use this skill when the user asks about Beacon, endpoint telemetry, local traces, telemetry gaps,
+or whether the current DeepSeek Harness session has been collected by Beacon.
+
+Beacon is local-only endpoint telemetry. This skill does not publish or upload anything.
+
+## Check Status
+
+Run this first:
+
+` + "```bash" + `
+beacon endpoint dsh status --workspace "$PWD" --json
+` + "```" + `
+
+Summarize whether the current workspace has pending DeepSeek session records.
+
+## Sync Current Workspace
+
+When the user asks to collect, backfill, update, or refresh Beacon telemetry for the current
+DeepSeek Harness session, run:
+
+` + "```bash" + `
+beacon endpoint dsh sync --workspace "$PWD"
+` + "```" + `
+
+Use ` + "`--print`" + ` only when the user wants to preview mapped events without writing Beacon's
+runtime log.
+`
+}
diff --git a/cli/beacon/internal/tokens/coverage.go b/cli/beacon/internal/tokens/coverage.go
index 334b5e1b..4122b447 100644
--- a/cli/beacon/internal/tokens/coverage.go
+++ b/cli/beacon/internal/tokens/coverage.go
@@ -83,6 +83,7 @@ var usageExpectation = map[string]struct {
// `beacon endpoint hooks status --harness openclaw` is where that gap is surfaced.
"openclaw_gateway": {ExpectReported, "plugin reports usage per model response when conversation access is granted"},
"vercel_fx": {ExpectReported, "session store carries cumulative usage and cost"},
+ "deepseek_harness": {ExpectReported, "native session backfill reports usage when DeepSeek persists it"},
"asymptote_observe": {ExpectReported, "SDK spans carry semconv usage"},
"gemini_cli": {ExpectGenericOTLP, "only if it emits OTel GenAI semconv usage"},
@@ -113,11 +114,6 @@ var usageExpectation = map[string]struct {
"chatgpt_web": {ExpectNone, "the chat stream reports no token counts"},
"openhands": {ExpectNone, "hook payloads carry no token counts"},
"kiro": {ExpectNone, "hook payloads carry no token counts"},
- // The bridge builds each hook payload from a fixed base plus per-event fields, and no usage
- // count is among them on any of the seven events it supports. dsh does record usage -- in its
- // own session log -- but nothing in the hook surface exposes it, so a DeepSeek Harness session
- // reporting no tokens is correct rather than silent.
- "deepseek_harness": {ExpectNone, "the hook bridge's payloads carry no token counts"},
}
// InstalledConfig is the part of a config-scanner row that install detection reads.
diff --git a/docs/runtimes/deepseek-harness.mdx b/docs/runtimes/deepseek-harness.mdx
index 53931e1b..b6ce8f11 100644
--- a/docs/runtimes/deepseek-harness.mdx
+++ b/docs/runtimes/deepseek-harness.mdx
@@ -5,7 +5,7 @@ description: "Beacon support details for DeepSeek Harness (dsh) endpoint telemet
## Runtime overview
-Beacon supports DeepSeek Harness — DeepSeek's open agent harness, run as `dsh` — through the Claude Code hook bridge DeepSeek ships in the CLI, sent to `beacon-hooks`.
+Beacon supports DeepSeek Harness — DeepSeek's open agent harness, run as `dsh` — through the Claude Code hook bridge DeepSeek ships in the CLI, sent to `beacon-hooks`, plus a local poll of DeepSeek's native session files.
```bash
beacon endpoint hooks install --harness dsh
@@ -53,6 +53,15 @@ The row Beacon adds looks like this:
The home-level patch layer is applied over **every** profile and outranks each profile's own, so one install covers `dsh`, `dsh web`, the ACP server, and the SDK. `configPath` is absolute because the bridge resolves a relative path against the directory the process was launched from, which for an agent runtime is wherever you happened to be standing.
+Beacon also reads committed native session records from `$DSH_HOME/sessions` through:
+
+```bash
+beacon endpoint dsh sync
+beacon endpoint dsh status
+```
+
+The poll path is local and offline. It complements hooks by backfilling persisted assistant text, reasoning, structured tool failures, and token usage that the hook bridge does not expose. Poll events are marked `harness.collection_method=poll`, so they are historical observation only: they cannot approve, deny, hold, or delay a tool call.
+
<Warning>
**There is no project scope.** The bridge's `configPath` is process-level — read once at startup — and per-session discovery of a project-local hooks file is unimplemented in the bridge itself. A repository has nowhere to mount a hook bridge from, so `--level project` is **refused with that explanation** rather than quietly becoming a machine-wide install. DeepSeek Harness is also left out of the project-level `--all` sweep for the same reason.
</Warning>
@@ -99,7 +108,7 @@ beacon endpoint hooks status --harness dsh
Status reports **both** paths, because `installed` is the conjunction of the two files: a hooks file with nothing mounted at it is a file nothing reads, and a mount pointing at a missing hooks file is a bridge that logs a warning and registers nothing. `beacon endpoint inventory` lists both for the same reason, so a half-install is visible as a half-install.
-DeepSeek Harness reports as the `deepseek_harness` harness with capability `hooks`, and every event carries `harness.collection_method=hook`. The bridge is a plugin, but it is DeepSeek's plugin, shipped and versioned with the CLI; what Beacon contributes is command hooks, and the thing that runs on each event is the same `beacon-hooks` binary every other hook runtime runs.
+DeepSeek Harness reports as the `deepseek_harness` harness with capability `hooks+session_log`. Live hook events carry `harness.collection_method=hook`; backfilled native session events carry `harness.collection_method=poll`. The bridge is a plugin, but it is DeepSeek's plugin, shipped and versioned with the CLI; what Beacon contributes is command hooks, and the thing that runs on each hook event is the same `beacon-hooks` binary every other hook runtime runs.
## Install or configuration support
@@ -107,29 +116,32 @@ DeepSeek Harness reports as the `deepseek_harness` harness with capability `hook
beacon endpoint hooks install --harness dsh
beacon endpoint hooks status --harness dsh
beacon endpoint hooks uninstall --harness dsh
+beacon endpoint dsh sync
+beacon endpoint dsh status
```
-Re-running the install rewrites the hooks file wholesale and **repoints** the mount in place rather than adding a second one — so a reinstall after `$DSH_HOME` moved updates the path the bridge reads, and a repair does not end with each event registered twice.
+Re-running the install rewrites the hooks file wholesale, **repoints** the mount in place rather than adding a second one, and installs a Beacon-owned local skill at `$DSH_HOME/skills/beacon-endpoint/SKILL.md`. The skill only teaches `dsh` how to run `beacon endpoint dsh status` and workspace-scoped `beacon endpoint dsh sync`; it does not publish or upload anything.
-Uninstall removes Beacon's hooks file and its one patch element, and leaves your rows and comments alone.
+Uninstall removes Beacon's hooks file, its one patch element, and the Beacon-owned skill when its marker is still present. It leaves your rows, comments, and non-Beacon skills alone.
## Telemetry coverage
| Area | Support |
|------|---------|
-| Runtime discovery | Supported through both files in the Harness home |
+| Runtime discovery | Supported through hook files and native session-store progress in the Harness home |
| Harness attribution | Supported. `dsh`, `dsh_cli`, `dsh-cli`, `dshcli`, `deepseek_harness`, `deepseek-harness`, `deepseekharness`, `deepseek-ai/dsh`, and `@deepseek-ai/dsh` normalize to `deepseek_harness` |
| Hook install, status, uninstall, and repair | Supported at user scope |
-| Session lifecycle | Supported. `session.started` from `SessionStart`, and `tool.completed` from `Stop` |
-| Prompts | Supported. `prompt.submitted` from `UserPromptSubmit` |
-| Tool use | Supported for pre-tool and post-tool activity, with `gen_ai.tool.call.id` from `tool_use_id` |
-| Commands | Supported. `command.executed` with the command, its output, and its exit code |
-| File activity | Supported. `file.read` and `file.modified` with paths, operations, and diffs |
+| Session lifecycle | Supported. Hooks record `session.started` from `SessionStart`, and poll backfill records persisted session starts |
+| Prompts | Supported. Hooks record `prompt.submitted` from `UserPromptSubmit`; poll backfill reads persisted user messages |
+| Assistant text and reasoning | Supported through native session poll |
+| Tool use | Supported for hook pre-tool/post-tool activity and persisted poll tool calls/results, with native call ids promoted to `gen_ai.tool.call.id` |
+| Commands | Supported. Hooks and poll both record `command.executed` with the command, output, and exit code when exposed |
+| File activity | Supported. Hooks and poll record `file.read` and `file.modified` with paths, operations, and diffs where available |
| MCP activity | Supported. Recognized from `mcp__<server>__<tool>`, with the server and tool split out |
| Subagents | Supported. `subagent.started` and `subagent.stopped` |
| Approval decisions | Not collected. See [Known gaps](#known-gaps) |
-| Token usage and cost | Not collected. See [Known gaps](#known-gaps) |
-| Failed tools | Not collected. See [Known gaps](#known-gaps) |
+| Token usage and cost | Token usage is collected from native session poll when persisted. Runtime-reported cost is not currently exposed |
+| Failed tools | Collected from native session poll. Not exposed on the hook bridge |
| Local JSONL and dashboard | Supported |
| MDM deployment | Supported for the endpoint agent. Hooks are installed in the logged-in user's Harness home |
@@ -198,17 +210,17 @@ Enforcement stays behind the optional, off-by-default policy provider seam (`BEA
## Data handling
-DeepSeek Harness content is handled like every other runtime. Prompts, tool arguments, commands, command output, paths, and diffs are retained in local or customer-controlled logs, with local secret redaction and per-string limits applied before writing, and a hash and byte count on each content-bearing event. Events over the 64 KiB limit drop raw and retained content, preserve stable metadata, and set `field_truncated`.
+DeepSeek Harness content is handled like every other runtime. Prompts, assistant text/reasoning from poll, tool arguments, commands, command output, paths, and diffs are retained in local or customer-controlled logs, with local secret redaction and per-string limits applied before writing, and a hash and byte count on each content-bearing event. Events over the 64 KiB limit drop raw and retained content, preserve stable metadata, and set `field_truncated`.
Unlike [Kiro](/runtimes/kiro) and [OpenHands](/runtimes/openhands), Beacon **does** preserve the verbatim payload under `raw.dsh`, as it does for [Qwen Code](/runtimes/qwen-code) and [Muse Code](/runtimes/muse-code). Non-MCP tool arguments reach no endpoint-schema field on any runtime, so on `dsh` this is where `run_code`'s program, a `glob` or `grep` pattern, a `terminal_send` `submit` flag, and `SessionStart`'s `source` survive. The cost is stated rather than hidden: on a `write` the payload repeats the file content the diff already carries. `raw` is the first thing dropped at the size ceiling, so the duplication is bounded and the diff is what survives.
## Known gaps
-- **No approval decisions.** The bridge exposes no `PermissionRequest` event, and Beacon does not synthesize one from `PreToolUse`. Approval rules and dashboards will show nothing for this runtime.
-- **No token usage or cost.** The bridge builds each payload from a fixed base plus per-event fields, and no usage count is among them on any of the seven events. `dsh` does record usage in its own session log; nothing on the hook surface exposes it. DeepSeek Harness activity therefore does not appear in `beacon token-usage` reports or the dashboard token view.
-- **No failed-tool events.** The bridge hands a hook the result's flattened text and nothing else, so a tool that threw is indistinguishable at the hook from one that returned. `tool.failed` is never recorded, and a diff is built from a write's arguments whether or not the write landed. A non-zero shell exit is *not* a tool failure and is recorded as such.
+- **No approval decisions.** The bridge exposes no `PermissionRequest` event, native session records do not represent operator decisions, and Beacon does not synthesize one from `PreToolUse`. Approval rules and dashboards will show nothing for this runtime.
+- **Token usage is poll-only.** The bridge builds each hook payload from a fixed base plus per-event fields, and no usage count is among them on any of the seven events. `beacon endpoint dsh sync` reads usage from native session records when DeepSeek persisted it.
+- **Failed tools are poll-only.** The bridge hands a hook the result's flattened text and nothing else, so a tool that threw is indistinguishable at the hook from one that returned. Native session poll records failed tool results when the session store marks them. A non-zero shell exit is *not* a tool failure and is recorded as a command exit code.
- **No session-end event.** `dsh` has no `SessionEnd`. `Stop` fires when a turn finishes, not when a session ends, so it is recorded as `tool.completed`.
-- **No transcript path.** The bridge always sends `transcript_path` as the empty string: the persistence seam exposes no artifact path, and the default session log is Zstandard-compressed and not readable by a hook script.
+- **No transcript path on hooks.** The bridge always sends `transcript_path` as the empty string. Use `beacon endpoint dsh sync` for the native session-store path.
- **No compaction events.** `PreCompact` and `PostCompact` are among the events the bridge does not support.
- **Subagent detail is thin.** The bridge reports a constant `agent_type` of `general-purpose` and uses the child's session id where Claude Code reports the parent's, so a subagent event cannot be joined to the session that spawned it.
- **No project scope.** See the warning under [Collection path](#collection-path).
@@ -222,6 +234,8 @@ Confirm status, then generate one event and check the log:
```bash
beacon endpoint hooks status --harness dsh
+beacon endpoint dsh status
+beacon endpoint dsh sync
beacon endpoint doctor --system
grep '"name":"deepseek_harness"' ~/.beacon/endpoint/logs/runtime.jsonl | tail -3
```
@@ -235,6 +249,7 @@ If DeepSeek Harness telemetry is missing:
- Preview the composed configuration with `dsh --dump-config` to confirm the bridge row is in the tree the profile mounts.
- Check the startup log under `$DSH_HOME/logs/` for a `hooks-claude-code` warning. A config the bridge cannot read registers **no** hooks and says so only there.
- Restart `dsh` so the updated plugin tree is loaded.
+- Run `beacon endpoint dsh status` to see whether native session records are pending backfill.
## Related
diff --git a/docs/runtimes/index.mdx b/docs/runtimes/index.mdx
index 1f09bf62..fe7baa68 100644
--- a/docs/runtimes/index.mdx
+++ b/docs/runtimes/index.mdx
@@ -25,7 +25,7 @@ These integrations are grouped by where the agent runs and how telemetry is coll
| [Cline](/runtimes/cline) | Managed plugin hooks plus optional poll of Cline's local task/session stores through `beacon endpoint cline sync` | Plugin: prompts, task lifecycle, tool lifecycle, commands, file reads and edits with diffs, MCP activity, and token usage. Poll: historical prompts, assistant messages, reasoning, tool results, commands, files, MCP-shaped activity, and token counts where persisted |
| [Codex CLI](/runtimes/codex-cli) | Local OTLP logs, selective usage trace, endpoint hooks, and poll of `~/.codex/sessions` through `beacon endpoint codex sync` | OTLP/hooks: session, prompt, approval, and tool-result activity plus per-user/session/model turn token usage. Poll: historical prompts, assistant messages, commands, files, tool calls, MCP-shaped activity, and token snapshots where persisted |
| [Cursor](/runtimes/cursor) | Native hooks plus optional poll of Cursor's local session stores through `beacon endpoint cursor sync` | Hooks: prompt, tool, shell command, MCP-like, approval, file edit, reasoning, and context telemetry. Poll: historical Composer and agent-session records from Cursor's global storage database and `~/.cursor/projects` |
-| [DeepSeek Harness](/runtimes/deepseek-harness) | DeepSeek's own Claude Code hook bridge, mounted by a Beacon row in `$DSH_HOME/cordis.patch.yml` at a hooks file Beacon owns | Session start, prompts, pre-tool and post-tool activity, commands with output and exit code, file reads and edits with diffs, MCP tool calls, subagent start and stop, and the turn-closing stop. No approval decisions, token usage, or failed-tool events, because the bridge exposes none of them on a hook |
+| [DeepSeek Harness](/runtimes/deepseek-harness) | DeepSeek's own Claude Code hook bridge, mounted by a Beacon row in `$DSH_HOME/cordis.patch.yml` at a hooks file Beacon owns, plus poll of `$DSH_HOME/sessions` through `beacon endpoint dsh sync` | Hooks: session start, prompts, pre-tool and post-tool activity, commands with output and exit code, file reads and edits with diffs, MCP tool calls, subagent start and stop, and the turn-closing stop. Poll: historical prompts, assistant text/reasoning, tool calls/results, failed tools, command/file/MCP activity, and token usage where persisted. No approval decisions, because neither surface exposes them |
| [Devin CLI](/runtimes/devin) | Native hooks | Session, prompt, pre-tool, post-tool, permission request, stop, session-end, approval, and file telemetry |
| [Devin Desktop](/runtimes/devin-desktop) | Cascade/Windsurf hooks | Prompt, command, MCP tool, file read, and file write telemetry where Desktop exposes Cascade hook payloads |
| [Factory Droid](/runtimes/factory-droid) | OTLP HTTP, optional hooks, and poll of `~/.factory/sessions` through `beacon endpoint factory sync` | OTLP/hooks: session, prompt, write/edit/create tool use, stop, session-end, and available OTLP telemetry. Poll: historical session records committed by Factory |
@@ -116,6 +116,7 @@ MDM assets, meaning Jamf Pro Extension Attributes, Fleet osquery queries, and Ri
| Cursor | Install hooks with `beacon endpoint hooks install --harness cursor`. To backfill committed local sessions, schedule `beacon endpoint cursor sync` in the logged-in user's context or leave `--watch` running. |
| Cline | Install the managed plugin with `beacon endpoint hooks install --harness cline`. To backfill committed local tasks and sessions, schedule `beacon endpoint cline sync` in the logged-in user's context or leave `--watch` running. |
| Codex CLI | `beacon endpoint install` configures local OTLP export. To backfill committed sessions, schedule `beacon endpoint codex sync` in the logged-in user's context or leave `--watch` running. |
+| DeepSeek Harness | Install hooks with `beacon endpoint hooks install --harness dsh`. To backfill committed native sessions, schedule `beacon endpoint dsh sync` in the logged-in user's context or leave `--watch` running. |
| Gemini CLI | Opt in by adding `gemini` to the endpoint harness list, for example `claude,codex,gemini`. Beacon can then manage `~/.gemini/settings.json` for local OTLP collection. |
| fx (Vercel Labs) | Nothing to configure in fx. Schedule [`beacon endpoint fx sync`](/cli/endpoint-fx) in the logged-in user's context, or leave `--watch` running, so committed sessions keep reaching the runtime log. Nothing sweeps on its own. |
| OpenCode | Install the managed plugin for live telemetry with `beacon endpoint hooks install --harness opencode`. To backfill committed local sessions, schedule [`beacon endpoint opencode sync`](/cli/endpoint-opencode) in the logged-in user's context or leave `--watch` running. |