The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu
Go agent-ai-cliagent-harnessesagent-securitybrowser-extensionciclaude-codecloudcodexcursordetection-engineeringjevknowledge-basememorymobile-device-managementobservabilitysecuritysecurity-information-and-event-managementsecurity-toolstelemetrytraces
add cursor session syncing
Justin D'Souzac514b4263a04
diff --git a/cli/beacon/cmd/endpoint_cursor.go b/cli/beacon/cmd/endpoint_cursor.gonew file mode 100644index 00000000..b308cbff--- /dev/null+++ b/cli/beacon/cmd/endpoint_cursor.go@@ -0,0 +1,223 @@+package cmd++import (+ "context"+ "encoding/json"+ "fmt"+ "path/filepath"+ "strings"+ "time"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/cursorsession"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/lifecycle"+ "github.com/spf13/cobra"+)++// `beacon endpoint cursor` collects telemetry from Cursor's own durable local+// session stores. This supplements Cursor hooks: it can recover sessions that+// happened before Beacon hooks were installed, but it is poll-based and cannot+// hold or deny tool calls.+var endpointCursorCmd = &cobra.Command{+ Use: "cursor",+ Short: "Collect telemetry from Cursor local sessions",+ Long: `Collect endpoint telemetry from Cursor's local session stores.++Cursor keeps Composer conversations in its global VS Code storage database and+agent transcripts under ~/.cursor/projects. Beacon reads those committed local+records and converts them into endpoint events marked harness.collection_method=poll.++Reading is local and offline. Run 'sync' on a schedule, or with --watch, to keep+the runtime log current.`,+}++var endpointCursorSyncCmd = &cobra.Command{+ Use: "sync",+ Short: "Read new Cursor session records into the runtime log",+ SilenceUsage: true,+ RunE: runEndpointCursorSync,+}++var endpointCursorStatusCmd = &cobra.Command{+ Use: "status",+ Short: "Show Cursor local session stores and collection progress",+ SilenceUsage: true,+ RunE: runEndpointCursorStatus,+}++var endpointCursorOpts struct {+ globalDBPath string+ projectsDir string+ statePath string+ logPath string+ print bool+ watch bool+ interval time.Duration+}++func init() {+ endpointCmd.AddCommand(endpointCursorCmd)+ endpointCursorCmd.AddCommand(endpointCursorSyncCmd)+ endpointCursorCmd.AddCommand(endpointCursorStatusCmd)++ for _, c := range []*cobra.Command{endpointCursorSyncCmd, endpointCursorStatusCmd} {+ f := c.Flags()+ f.StringVar(&endpointCursorOpts.globalDBPath, "global-db", "", "Cursor global storage DB path (default OS-specific Cursor state.vscdb)")+ f.StringVar(&endpointCursorOpts.projectsDir, "projects-dir", "", "Cursor projects directory (default ~/.cursor/projects)")+ f.StringVar(&endpointCursorOpts.statePath, "state", "", "Collector cursor file (default ~/.beacon/endpoint/state/cursor-sessions.json)")+ 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 := endpointCursorSyncCmd.Flags()+ sync.StringVar(&endpointCursorOpts.logPath, "log-path", "", "Runtime JSONL log path (default resolved endpoint log)")+ sync.BoolVar(&endpointCursorOpts.print, "print", false, "Print mapped events as JSON without writing them or advancing the cursor (dry run)")+ sync.BoolVar(&endpointCursorOpts.watch, "watch", false, "Sweep continuously on --interval (default: one sweep then exit)")+ sync.DurationVar(&endpointCursorOpts.interval, "interval", time.Minute, "Sweep interval for --watch")+}++func runEndpointCursorSync(cmd *cobra.Command, args []string) error {+ userMode := endpointUserMode()+ opts := cursorsession.CollectOptions{+ GlobalDBPath: endpointCursorOpts.globalDBPath,+ ProjectsDir: endpointCursorOpts.projectsDir,+ Print: endpointCursorOpts.print,+ Out: cmd.OutOrStdout(),+ Write: !endpointCursorOpts.print,+ UserMode: userMode,+ }+ if !endpointCursorOpts.print {+ opts.StatePath = resolveCursorStatePath(endpointCursorOpts.statePath, userMode)+ opts.LogPath = lifecycle.ResolveRuntimeLog(userMode, endpointCursorOpts.logPath).EffectiveLogPath+ }+ ctx := cmd.Context()+ if ctx == nil {+ ctx = context.Background()+ }+ if endpointCursorOpts.watch && !endpointCursorOpts.print {+ return watchCursor(ctx, cmd, opts)+ }+ summary, err := cursorsession.CollectOnce(opts)+ reportCursorSweep(cmd, summary)+ return err+}++func watchCursor(ctx context.Context, cmd *cobra.Command, opts cursorsession.CollectOptions) error {+ interval := endpointCursorOpts.interval+ if interval < 5*time.Second {+ interval = 5 * time.Second+ }+ for {+ summary, err := cursorsession.CollectOnce(opts)+ if err != nil {+ fmt.Fprintf(cmd.ErrOrStderr(), "cursor sync error: %v\n", err)+ }+ reportCursorSweep(cmd, summary)+ select {+ case <-ctx.Done():+ return nil+ case <-time.After(interval):+ }+ }+}++func reportCursorSweep(cmd *cobra.Command, summary cursorsession.Summary) {+ if endpointCursorOpts.print {+ return+ }+ if endpointOpts.jsonOutput {+ _ = json.NewEncoder(cmd.OutOrStdout()).Encode(summary)+ return+ }+ fmt.Fprintf(cmd.OutOrStdout(), "cursor sync: %d traces, %d changed, %d events, %d errors\n",+ summary.Traces, summary.TracesChanged, summary.EventsEmitted, summary.Errors)+}++type cursorStatusRef struct {+ ID string `json:"id"`+ Source string `json:"source"`+ Workspace string `json:"workspace,omitempty"`+ UpdatedAt string `json:"updated_at,omitempty"`+ Collected bool `json:"collected"`+ EventsRead int `json:"events_read"`+ SizeBytes int64 `json:"size_bytes"`+ SourcePath string `json:"source_path,omitempty"`+}++type cursorStatusReport struct {+ GlobalDBPath string `json:"global_db_path"`+ ProjectsDir string `json:"projects_dir"`+ Present bool `json:"present"`+ StatePath string `json:"state_path,omitempty"`+ Traces []cursorStatusRef `json:"traces"`+}++func runEndpointCursorStatus(cmd *cobra.Command, args []string) error {+ store, err := cursorsession.NewStore(endpointCursorOpts.globalDBPath, endpointCursorOpts.projectsDir)+ if err != nil {+ return err+ }+ statePath := resolveCursorStatePath(endpointCursorOpts.statePath, endpointUserMode())+ state, err := cursorsession.LoadState(statePath)+ if err != nil {+ return err+ }+ refs, err := store.List()+ if err != nil {+ return err+ }+ report := cursorStatusReport{+ GlobalDBPath: store.GlobalDBPath,+ ProjectsDir: store.ProjectsDir,+ Present: store.Exists(),+ StatePath: statePath,+ Traces: make([]cursorStatusRef, 0, len(refs)),+ }+ for _, ref := range refs {+ status := cursorStatusRef{+ ID: ref.ID,+ Source: string(ref.Kind),+ Workspace: ref.Workspace,+ SizeBytes: ref.SizeBytes,+ SourcePath: ref.SourcePath,+ }+ if ref.UpdatedAtUnixMS > 0 {+ status.UpdatedAt = time.UnixMilli(ref.UpdatedAtUnixMS).UTC().Format(time.RFC3339)+ }+ records, _ := store.Read(ref)+ status.EventsRead = len(records)+ if cursor := state.Traces[string(ref.Kind)+":"+ref.ID]; cursor != nil {+ status.Collected = cursor.LastOrder >= len(records) && (ref.UpdatedAtUnixMS == 0 || cursor.UpdatedAtMS >= ref.UpdatedAtUnixMS)+ }+ report.Traces = append(report.Traces, status)+ }+ if endpointOpts.jsonOutput {+ return json.NewEncoder(cmd.OutOrStdout()).Encode(report)+ }+ out := cmd.OutOrStdout()+ if !report.Present {+ fmt.Fprintf(out, "cursor sessions: none (%s and %s do not exist)\n", report.GlobalDBPath, report.ProjectsDir)+ return nil+ }+ fmt.Fprintf(out, "cursor sessions: %d traces\n", len(report.Traces))+ for _, trace := range report.Traces {+ state := "pending"+ if trace.Collected {+ state = "collected"+ }+ fmt.Fprintf(out, " %s %s %s %s\n", trace.ID, trace.Source, state, strings.TrimSpace(trace.Workspace))+ }+ return nil+}++func resolveCursorStatePath(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, "cursor-sessions-state.json")+ }+ }+ return cursorsession.DefaultStatePath()+}diff --git a/cli/beacon/go.mod b/cli/beacon/go.modindex 0b0ff14a..b222e590 100644--- a/cli/beacon/go.mod+++ b/cli/beacon/go.mod@@ -6,7 +6,7 @@ require (github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve v0.0.0github.com/pelletier/go-toml/v2 v2.3.1github.com/spf13/cobra v1.8.1- golang.org/x/sys v0.44.0+ golang.org/x/sys v0.47.0golang.org/x/term v0.33.0gopkg.in/yaml.v3 v3.0.1)@@ -17,8 +17,13 @@ require (cel.dev/expr v0.25.1 // indirectgithub.com/antlr4-go/antlr/v4 v4.13.1 // indirectgithub.com/cpuguy83/go-md2man/v2 v2.0.4 // indirect+ github.com/dustin/go-humanize v1.0.1 // indirectgithub.com/google/cel-go v0.30.0 // indirect+ github.com/google/uuid v1.6.0 // indirectgithub.com/inconshreveable/mousetrap v1.1.0 // indirect+ github.com/mattn/go-isatty v0.0.24 // indirect+ github.com/ncruces/go-strftime v1.0.0 // indirect+ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirectgithub.com/russross/blackfriday/v2 v2.1.0 // indirectgithub.com/spf13/pflag v1.0.5 // indirectgo.yaml.in/yaml/v3 v3.0.4 // indirect@@ -27,4 +32,8 @@ require (google.golang.org/genproto/googleapis/api v0.0.0-20240826202546-f6391c0de4c7 // indirectgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20240826202546-f6391c0de4c7 // indirectgoogle.golang.org/protobuf v1.36.10 // indirect+ modernc.org/libc v1.75.7 // indirect+ modernc.org/mathutil v1.7.1 // indirect+ modernc.org/memory v1.12.1 // indirect+ modernc.org/sqlite v1.59.0 // indirect)diff --git a/cli/beacon/go.sum b/cli/beacon/go.sumindex 7350c7dd..fe4e32db 100644--- a/cli/beacon/go.sum+++ b/cli/beacon/go.sum@@ -4,14 +4,24 @@ github.com/antlr4-go/antlr/v4 v4.13.1 h1:SqQKkuVZ+zWkMMNkjy5FZe5mr5WURWnlpmOuzYWgithub.com/antlr4-go/antlr/v4 v4.13.1/go.mod h1:GKmUxMtwp6ZgGwZSva4eWPC5mS6vUAmOABFgjdkM7Nw=github.com/cpuguy83/go-md2man/v2 v2.0.4 h1:wfIWP927BUkWJb2NmU/kNDYIBTh/ziUX91+lVfRxZq4=github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=+github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=+github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=github.com/google/cel-go v0.30.0 h1:ll54AkzKunWkBn9wSoiUXbFZXYZTkdJGNXTBXUoolGo=github.com/google/cel-go v0.30.0/go.mod h1:X0bD6iVNR8pkROSOoHVdgTkzmRcosof7WQqCD6wcMc8=github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=+github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=+github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=+github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=+github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=+github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=+github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=github.com/pelletier/go-toml/v2 v2.3.1 h1:MYEvvGnQjeNkRF1qUuGolNtNExTDwct51yp7olPtrEc=github.com/pelletier/go-toml/v2 v2.3.1/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=+github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=+github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM=@@ -24,6 +34,8 @@ golang.org/x/exp v0.0.0-20240823005443-9b4947da3948 h1:kx6Ds3MlpiUHKj7syVnbp57++golang.org/x/exp v0.0.0-20240823005443-9b4947da3948/go.mod h1:akd2r19cwCdwSwWeIdzYQGa/EZZyqcOdwWiwj5L5eKQ=golang.org/x/sys v0.44.0 h1:ildZl3J4uzeKP07r2F++Op7E9B29JRUy+a27EibtBTQ=golang.org/x/sys v0.44.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=+golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=+golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=golang.org/x/term v0.33.0 h1:NuFncQrRcaRvVmgRkvM3j/F00gWIAlcmlB8ACEKmGIg=golang.org/x/term v0.33.0/go.mod h1:s18+ql9tYWp1IfpV9DmCtQDDSRBUjKaw9M1eAv5UeF0=golang.org/x/text v0.39.0 h1:UbZz4pLOvn600D6Oh6GGEI6VAmndrEBLv8/6BEXzyus=@@ -38,3 +50,11 @@ gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=+modernc.org/libc v1.75.7 h1:o3DTP9/0p9pKmY2WCKQaySW6wIiZhNM7wc2lUoyhfew=+modernc.org/libc v1.75.7/go.mod h1:bO5o2ztHxBb2rjz0PgdHN0sSMw57CgxGFLZ3Qd/QpVQ=+modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=+modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=+modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g=+modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=+modernc.org/sqlite v1.59.0 h1:X1es1GpqBlS/5T+vbM4HLUdaa8OtQx468DF2vrx+38A=+modernc.org/sqlite v1.59.0/go.mod h1:+paeT2A3iPRHkQDwG7oA6Tk0zQd5woMEI8q7orfry8k=diff --git a/cli/beacon/internal/cursorsession/collect.go b/cli/beacon/internal/cursorsession/collect.gonew file mode 100644index 00000000..8efc64dd--- /dev/null+++ b/cli/beacon/internal/cursorsession/collect.go@@ -0,0 +1,198 @@+package cursorsession++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"+)++const StateVersion = 1++type Cursor struct {+ LastOrder int `json:"last_order"`+ UpdatedAtMS int64 `json:"updated_at_ms,omitempty"`+}++type State struct {+ Version int `json:"version"`+ Traces map[string]*Cursor `json:"traces"`+}++func LoadState(path string) (*State, error) {+ state := &State{Version: StateVersion, Traces: map[string]*Cursor{}}+ if strings.TrimSpace(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 Cursor collector state %s: %w", path, err)+ }+ if stored.Version != StateVersion || stored.Traces == nil {+ return state, nil+ }+ return &stored, nil+}++func (s *State) Save(path string) error {+ if strings.TrimSpace(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(ref TraceRef) *Cursor {+ if s.Traces == nil {+ s.Traces = map[string]*Cursor{}+ }+ key := stateKey(ref)+ cursor := s.Traces[key]+ if cursor == nil {+ cursor = &Cursor{}+ s.Traces[key] = cursor+ }+ return cursor+}++func stateKey(ref TraceRef) string {+ return string(ref.Kind) + ":" + ref.ID+}++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", "cursor-sessions.json")+}++type CollectOptions struct {+ GlobalDBPath string+ ProjectsDir string+ StatePath string+ Write bool+ LogPath string+ UserMode bool+ Print bool+ Out io.Writer+}++type Summary struct {+ Traces int `json:"traces"`+ TracesChanged int `json:"traces_changed"`+ EventsEmitted int `json:"events_emitted"`+ Errors int `json:"errors"`+ MalformedItems int `json:"malformed_items"`+}++func CollectOnce(opts CollectOptions) (summary Summary, err error) {+ store, err := NewStore(opts.GlobalDBPath, opts.ProjectsDir)+ if err != nil {+ return summary, err+ }+ refs, err := store.List()+ if err != nil {+ return summary, err+ }+ summary.Traces = len(refs)+ 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 Cursor collector state: %w", saveErr)+ }+ }()++ var errs []error+ for _, ref := range refs {+ changed, collectErr := collectTrace(store, ref, state, opts, &summary)+ if collectErr != nil {+ summary.Errors+++ errs = append(errs, fmt.Errorf("Cursor trace %s: %w", ref.ID, collectErr))+ continue+ }+ if changed {+ summary.TracesChanged+++ }+ }+ if len(errs) > 0 {+ return summary, errors.Join(errs...)+ }+ return summary, nil+}++func collectTrace(store *Store, ref TraceRef, state *State, opts CollectOptions, summary *Summary) (bool, error) {+ cursor := state.cursor(ref)+ if ref.UpdatedAtUnixMS > 0 && ref.UpdatedAtUnixMS <= cursor.UpdatedAtMS {+ return false, nil+ }+ records, err := store.Read(ref)+ if err != nil {+ return false, err+ }+ mapped := MapTrace(ref, records, MapOptions{MinOrder: cursor.LastOrder})+ if len(mapped) == 0 {+ cursor.UpdatedAtMS = ref.UpdatedAtUnixMS+ if len(records) > 0 && records[len(records)-1].Order > cursor.LastOrder {+ cursor.LastOrder = records[len(records)-1].Order+ }+ return false, nil+ }+ for i, item := range mapped {+ if err := emit(item.Event, opts); err != nil {+ if i > 0 {+ cursor.LastOrder = mapped[i-1].SourceOrder+ }+ return true, err+ }+ cursor.LastOrder = item.SourceOrder+ summary.EventsEmitted+++ }+ cursor.UpdatedAtMS = ref.UpdatedAtUnixMS+ return true, nil+}++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+}diff --git a/cli/beacon/internal/cursorsession/collect_test.go b/cli/beacon/internal/cursorsession/collect_test.gonew file mode 100644index 00000000..5fd589a7--- /dev/null+++ b/cli/beacon/internal/cursorsession/collect_test.go@@ -0,0 +1,144 @@+package cursorsession++import (+ "bytes"+ "database/sql"+ "encoding/json"+ "os"+ "path/filepath"+ "strings"+ "testing"+)++func TestCollectGlobalStorageComposer(t *testing.T) {+ dbPath := filepath.Join(t.TempDir(), "state.vscdb")+ writeCursorDB(t, dbPath, map[string]string{+ "composerData:composer-1": `{+ "composerId":"composer-1",+ "name":"Investigate build",+ "createdAt":"2026-09-19T20:00:00Z",+ "lastUpdatedAt":"2026-09-19T20:00:03Z",+ "modelConfig":{"modelName":"gpt-5.5"},+ "fullConversationHeadersOnly":[+ {"bubbleId":"u1","type":1},+ {"bubbleId":"a1","type":2},+ {"bubbleId":"t1","type":2}+ ]+ }`,+ "bubbleId:composer-1:u1": `{"type":1,"text":"run the tests","createdAt":"2026-09-19T20:00:00Z"}`,+ "bubbleId:composer-1:a1": `{"type":2,"text":"Tests are green","createdAt":"2026-09-19T20:00:01Z"}`,+ "bubbleId:composer-1:t1": `{+ "type":2,+ "createdAt":"2026-09-19T20:00:02Z",+ "toolFormerData":{"name":"run_terminal_cmd","params":"{\"command\":\"go test ./...\"}","result":"ok","status":"success"}+ }`,+ })++ var out bytes.Buffer+ summary, err := CollectOnce(CollectOptions{+ GlobalDBPath: dbPath,+ ProjectsDir: filepath.Join(t.TempDir(), "missing-projects"),+ Print: true,+ Out: &out,+ })+ if err != nil {+ t.Fatalf("CollectOnce() error = %v", err)+ }+ if summary.EventsEmitted != 4 {+ t.Fatalf("events emitted = %d, want 4\n%s", summary.EventsEmitted, out.String())+ }+ events := decodeEvents(t, out.String())+ if actions := eventActions(events); strings.Join(actions, ",") != "prompt.submitted,agent.message,tool.invoked,command.executed" {+ t.Fatalf("actions = %v", actions)+ }+ command := events[3]["command"].(map[string]interface{})+ if command["command"] != "go test ./..." {+ t.Fatalf("command = %#v", command)+ }+ if got := nested(events[3], "harness")["collection_method"]; got != "poll" {+ t.Fatalf("collection method = %v, want poll", got)+ }+}++func TestCollectTranscriptJSONL(t *testing.T) {+ root := t.TempDir()+ project := filepath.Join(root, "-tmp-cursor-project", "agent-transcripts")+ if err := os.MkdirAll(project, 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(project, "session-1.jsonl"), []byte(strings.Join([]string{+ `{"type":"user_message","id":"u1","text":"hello","timestamp":"2026-09-19T20:00:00Z"}`,+ `{"type":"message","id":"a1","message":{"role":"assistant","content":[{"type":"reasoning","text":"thinking"},{"type":"text","text":"hi"}],"model":"claude-sonnet-4"},"timestamp":"2026-09-19T20:00:01Z"}`,+ `{"type":"tool_call","id":"c1","toolCall":{"id":"call-1","name":"read_file","args":{"path":"/tmp/a.txt"}},"timestamp":"2026-09-19T20:00:02Z"}`,+ }, "\n")), 0o644); err != nil {+ t.Fatal(err)+ }++ var out bytes.Buffer+ summary, err := CollectOnce(CollectOptions{+ GlobalDBPath: filepath.Join(t.TempDir(), "missing.vscdb"),+ ProjectsDir: root,+ Print: true,+ Out: &out,+ })+ if err != nil {+ t.Fatalf("CollectOnce() error = %v", err)+ }+ if summary.EventsEmitted != 4 {+ t.Fatalf("events emitted = %d, want 4\n%s", summary.EventsEmitted, out.String())+ }+ events := decodeEvents(t, out.String())+ if actions := eventActions(events); strings.Join(actions, ",") != "prompt.submitted,agent.reasoning,agent.message,tool.invoked" {+ t.Fatalf("actions = %v", actions)+ }+ if got := nested(events[1], "gen_ai", "output")["messages"]; got == nil {+ t.Fatalf("reasoning event missing gen_ai output: %#v", events[1])+ }+}++func writeCursorDB(t *testing.T, path string, kv map[string]string) {+ t.Helper()+ db, err := sql.Open("sqlite", path)+ if err != nil {+ t.Fatal(err)+ }+ defer db.Close()+ if _, err := db.Exec(`CREATE TABLE cursorDiskKV (key TEXT PRIMARY KEY, value BLOB)`); err != nil {+ t.Fatal(err)+ }+ for key, value := range kv {+ if _, err := db.Exec(`INSERT INTO cursorDiskKV(key, value) VALUES (?, ?)`, key, []byte(value)); err != nil {+ t.Fatal(err)+ }+ }+}++func decodeEvents(t *testing.T, text string) []map[string]interface{} {+ t.Helper()+ var out []map[string]interface{}+ for _, line := range strings.Split(strings.TrimSpace(text), "\n") {+ var event map[string]interface{}+ if err := json.Unmarshal([]byte(line), &event); err != nil {+ t.Fatalf("decode event: %v\n%s", err, line)+ }+ out = append(out, event)+ }+ return out+}++func eventActions(events []map[string]interface{}) []string {+ out := make([]string, 0, len(events))+ for _, event := range events {+ out = append(out, nested(event, "event")["action"].(string))+ }+ return out+}++func nested(root map[string]interface{}, keys ...string) map[string]interface{} {+ current := root+ for _, key := range keys {+ next, _ := current[key].(map[string]interface{})+ current = next+ }+ return current+}diff --git a/cli/beacon/internal/cursorsession/mapper.go b/cli/beacon/internal/cursorsession/mapper.gonew file mode 100644index 00000000..91862fa8--- /dev/null+++ b/cli/beacon/internal/cursorsession/mapper.go@@ -0,0 +1,324 @@+package cursorsession++import (+ "crypto/sha1"+ "crypto/sha256"+ "encoding/hex"+ "encoding/json"+ "fmt"+ "io"+ "path/filepath"+ "strings"+ "time"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"+)++type MappedEvent struct {+ SourceOrder int+ Event schema.Event+}++type MapOptions struct {+ MinOrder int+}++func MapTrace(ref TraceRef, records []Record, opts MapOptions) []MappedEvent {+ var out []MappedEvent+ for _, record := range records {+ if record.Order <= opts.MinOrder {+ continue+ }+ ev, ok := mapRecord(ref, record)+ if !ok {+ continue+ }+ ev.Event.ID = cursorEventID(fmt.Sprintf("%s:%s:%d:%s:%s", ref.Kind, ref.ID, record.Order, record.NativeID, record.Type))+ out = append(out, MappedEvent{SourceOrder: record.Order, Event: ev})+ }+ return out+}++func mapRecord(ref TraceRef, record Record) (schema.Event, bool) {+ ev := baseEvent(ref, record, "tool.completed", "tool", schema.SeverityInfo, schema.FidelityObserved, "Cursor session event")+ switch record.Type {+ case "user_message":+ if strings.TrimSpace(record.Content) == "" {+ return schema.Event{}, false+ }+ ev.Event.Action = "prompt.submitted"+ ev.Event.Category = "prompt"+ ev.Message = "Cursor prompt submitted"+ ev.Prompt = &schema.PromptInfo{Text: record.Content}+ ev.Content = asymptoteobserve.RetainedContent(record.Content, asymptoteobserve.DefaultStringLimit)+ ev.GenAI = withGenAI(ev.GenAI, func(genAI *schema.GenAIInfo) {+ genAI.Input = &schema.GenAIInputInfo{Messages: asymptoteobserve.TextInputMessages(record.Content)}+ })+ case "agent_text":+ if strings.TrimSpace(record.Content) == "" {+ return schema.Event{}, false+ }+ ev.Event.Action = "agent.message"+ ev.Event.Category = "session"+ ev.Message = "Cursor agent message"+ ev.Content = asymptoteobserve.RetainedContent(record.Content, asymptoteobserve.DefaultRawStringLimit)+ ev.GenAI = withGenAI(ev.GenAI, func(genAI *schema.GenAIInfo) {+ genAI.Output = &schema.GenAIOutputInfo{Messages: asymptoteobserve.TextOutputMessages(record.Content)}+ })+ case "agent_thinking":+ if strings.TrimSpace(record.Content) == "" {+ return schema.Event{}, false+ }+ ev.Event.Action = "agent.reasoning"+ ev.Event.Category = "session"+ ev.Message = "Cursor agent reasoning"+ ev.Content = asymptoteobserve.RetainedContent(record.Content, asymptoteobserve.DefaultStringLimit)+ ev.GenAI = withGenAI(ev.GenAI, func(genAI *schema.GenAIInfo) {+ genAI.Output = &schema.GenAIOutputInfo{Messages: []interface{}{+ map[string]interface{}{+ "role": "assistant",+ "parts": []interface{}{+ map[string]interface{}{"type": "reasoning", "content": record.Content},+ },+ },+ }}+ })+ case "tool_call":+ ev.Event.Action = "tool.invoked"+ ev.Event.Category = "tool"+ ev.Message = "Cursor tool invoked"+ applyTool(&ev, record)+ case "tool_result":+ action, category, message := classifyTool(record)+ ev.Event.Action = action+ ev.Event.Category = category+ ev.Message = message+ applyTool(&ev, record)+ if record.Status == "error" {+ ev.Error = &schema.ErrorInfo{Type: "tool_execution_failed"}+ }+ if action == "command.executed" {+ applyCommand(&ev, record)+ }+ if strings.HasPrefix(action, "file.") {+ applyFile(&ev, record)+ }+ if action == "mcp.tool_invoked" {+ ev.MCP = &schema.MCPInfo{Tool: record.ToolName}+ }+ case "error":+ ev.Event.Action = "tool.failed"+ ev.Event.Category = "tool"+ ev.Severity = schema.SeverityHigh+ ev.Message = firstNonEmpty(record.Content, "Cursor session error")+ ev.Error = &schema.ErrorInfo{Type: "cursor_session_error"}+ case "system_event":+ ev.Event.Action = "session.compacting"+ ev.Event.Category = "session"+ ev.Message = "Cursor compacted session history"+ default:+ return schema.Event{}, false+ }+ raw := map[string]interface{}{+ "source": ref.Kind,+ "source_path": ref.SourcePath,+ "native_id": record.NativeID,+ "order": record.Order,+ }+ if record.Subtype != "" {+ raw["subtype"] = record.Subtype+ }+ if len(record.Data) > 0 {+ raw["data"] = record.Data+ }+ ev.Raw = map[string]interface{}{"cursor": raw}+ return ev, true+}++func baseEvent(ref TraceRef, record Record, action, category string, severity schema.Severity, fidelity, message string) schema.Event {+ ev := schema.NewEvent(schema.NewEventOptions{+ Action: action,+ Category: category,+ Severity: severity,+ Fidelity: fidelity,+ Message: message,+ Origin: schema.OriginLocal,+ Harness: schema.HarnessInfo{+ Name: Harness,+ CollectionMethod: schema.CollectionMethodPoll,+ },+ })+ if record.TimestampMS > 0 {+ ev.Timestamp = schema.FormatTimestamp(time.UnixMilli(record.TimestampMS))+ } else if ref.UpdatedAtUnixMS > 0 {+ ev.Timestamp = schema.FormatTimestamp(time.UnixMilli(ref.UpdatedAtUnixMS))+ }+ ev.Session = &schema.SessionInfo{ID: ref.ID, WorkingDirectory: ref.Workspace}+ if record.Model != "" {+ ev.Model = asymptoteobserve.NormalizeModelName(record.Model)+ }+ return ev+}++func applyTool(ev *schema.Event, record Record) {+ ev.Tool = &schema.ToolInfo{Name: record.ToolName}+ if path := pathFromArgs(record.Args); path != "" {+ ev.Tool.Path = path+ }+ if command := commandFromArgs(record.Args); command != "" {+ ev.Tool.Command = command+ }+ ev.GenAI = withGenAI(ev.GenAI, func(genAI *schema.GenAIInfo) {+ genAI.Operation = &schema.GenAIOperationInfo{Name: "execute_tool"}+ genAI.Tool = &schema.GenAIToolInfo{+ Name: record.ToolName,+ Call: &schema.GenAIToolCallInfo{+ ID: record.CallID,+ Arguments: record.Args,+ },+ }+ if record.Type == "tool_result" && strings.TrimSpace(record.Output) != "" {+ genAI.Tool.Call.Result = record.Output+ }+ })+}++func classifyTool(record Record) (action, category, message string) {+ name := strings.ToLower(record.ToolName)+ switch {+ case strings.HasPrefix(name, "mcp_") || strings.Contains(name, "__"):+ return "mcp.tool_invoked", "mcp", "Cursor MCP tool invoked"+ case commandFromArgs(record.Args) != "" || strings.Contains(name, "terminal") || strings.Contains(name, "command") || strings.Contains(name, "bash") || strings.Contains(name, "shell"):+ return "command.executed", "command", "Cursor command executed"+ case pathFromArgs(record.Args) != "":+ if strings.Contains(name, "read") || strings.Contains(name, "grep") || strings.Contains(name, "search") || strings.Contains(name, "list") {+ return "file.read", "file", "Cursor file read"+ }+ if strings.Contains(name, "write") || strings.Contains(name, "create") {+ return "file.created", "file", "Cursor file created"+ }+ if strings.Contains(name, "edit") || strings.Contains(name, "delete") || strings.Contains(name, "apply") {+ return "file.modified", "file", "Cursor file modified"+ }+ case record.Status == "error":+ return "tool.failed", "tool", "Cursor tool failed"+ }+ return "tool.completed", "tool", "Cursor tool completed"+}++func applyCommand(ev *schema.Event, record Record) {+ info := &schema.CommandInfo{Command: commandFromArgs(record.Args)}+ if strings.TrimSpace(record.Output) != "" {+ info.Output = record.Output+ ev.Content = asymptoteobserve.RetainedContent(record.Output, asymptoteobserve.DefaultStringLimit)+ }+ if record.DurationMS > 0 {+ info.DurationMS = record.DurationMS+ }+ ev.Command = info+}++func applyFile(ev *schema.Event, record Record) {+ path := pathFromArgs(record.Args)+ info := &schema.FileInfo{Path: path, Operation: fileOperation(record)}+ if path != "" {+ info.Language = strings.TrimPrefix(filepath.Ext(path), ".")+ }+ if diff := diffFromArgs(record.Args); diff != "" {+ info.Diff = diff+ info.DiffBytes = len(diff)+ info.DiffHash = sha256Hex(diff)+ ev.Content = asymptoteobserve.RetainedContent(diff, asymptoteobserve.DefaultStringLimit)+ }+ ev.File = info+}++func fileOperation(record Record) string {+ name := strings.ToLower(record.ToolName)+ switch {+ case strings.Contains(name, "read") || strings.Contains(name, "grep") || strings.Contains(name, "search") || strings.Contains(name, "list"):+ return "read"+ case strings.Contains(name, "write") || strings.Contains(name, "create"):+ return "create"+ default:+ return "modify"+ }+}++func pathFromArgs(args map[string]interface{}) string {+ for _, key := range []string{"path", "file_path", "filePath", "targetFile", "target_file", "target_path", "relativeWorkspacePath"} {+ if value, ok := args[key].(string); ok && strings.TrimSpace(value) != "" {+ return value+ }+ }+ return ""+}++func commandFromArgs(args map[string]interface{}) string {+ for _, key := range []string{"command", "cmd", "commandLine"} {+ if value, ok := args[key].(string); ok && strings.TrimSpace(value) != "" {+ return value+ }+ }+ return ""+}++func diffFromArgs(args map[string]interface{}) string {+ oldText, oldOK := args["old_string"].(string)+ newText, newOK := args["new_string"].(string)+ if !oldOK || !newOK {+ return ""+ }+ path := pathFromArgs(args)+ var b strings.Builder+ if path != "" {+ b.WriteString("--- a/")+ b.WriteString(path)+ b.WriteString("\n+++ b/")+ b.WriteString(path)+ b.WriteString("\n")+ }+ b.WriteString("-")+ b.WriteString(strings.ReplaceAll(oldText, "\n", "\n-"))+ b.WriteString("\n+")+ b.WriteString(strings.ReplaceAll(newText, "\n", "\n+"))+ b.WriteString("\n")+ return b.String()+}++func withGenAI(genAI *schema.GenAIInfo, edit func(*schema.GenAIInfo)) *schema.GenAIInfo {+ if genAI == nil {+ genAI = &schema.GenAIInfo{}+ }+ edit(genAI)+ return genAI+}++func sha256Hex(value string) string {+ sum := sha256.Sum256([]byte(value))+ return hex.EncodeToString(sum[:])+}++var cursorIDNamespace = [16]byte{+ 0x50, 0x73, 0x15, 0x64, 0xc6, 0x90, 0x44, 0x0f,+ 0x91, 0x4a, 0x42, 0x31, 0x77, 0xe1, 0x82, 0x9c,+}++func cursorEventID(value string) string {+ digest := sha1.New()+ digest.Write(cursorIDNamespace[:])+ io.WriteString(digest, value)+ 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])+}++func rawJSON(v interface{}) string {+ data, _ := json.Marshal(v)+ return string(data)+}diff --git a/cli/beacon/internal/cursorsession/parse.go b/cli/beacon/internal/cursorsession/parse.gonew file mode 100644index 00000000..ae30201e--- /dev/null+++ b/cli/beacon/internal/cursorsession/parse.go@@ -0,0 +1,741 @@+package cursorsession++import (+ "bufio"+ "bytes"+ "database/sql"+ "encoding/json"+ "fmt"+ "net/url"+ "os"+ "path/filepath"+ "regexp"+ "strconv"+ "strings"+ "time"+)++func composerPreview(c composerData) string {+ for _, value := range []string{c.Name, c.Text, c.RichText} {+ value = strings.TrimSpace(value)+ if value == "" {+ continue+ }+ if strings.HasPrefix(value, "{") {+ if text := richTextPreview(value); text != "" {+ return truncateLine(text, 100)+ }+ }+ return truncateLine(value, 100)+ }+ return "(No title)"+}++func richTextPreview(value string) string {+ var doc map[string]interface{}+ if err := json.Unmarshal([]byte(value), &doc); err != nil {+ return ""+ }+ var parts []string+ var walk func(interface{})+ walk = func(v interface{}) {+ switch typed := v.(type) {+ case map[string]interface{}:+ if text, ok := typed["text"].(string); ok {+ parts = append(parts, text)+ }+ for _, child := range []string{"content", "children"} {+ walk(typed[child])+ }+ case []interface{}:+ for _, item := range typed {+ walk(item)+ }+ }+ }+ walk(doc)+ return strings.TrimSpace(strings.Join(parts, " "))+}++func transcriptPreview(path string) string {+ data, err := os.ReadFile(path)+ if err != nil {+ return "(No preview)"+ }+ for _, rec := range parseTranscriptRecords(data) {+ if text := userTextFromRecord(rec); text != "" {+ return truncateLine(stripUserQueryTags(text), 100)+ }+ }+ return "(No preview)"+}++func parseTranscriptRecords(data []byte) []transcriptRecord {+ trimmed := bytes.TrimSpace(data)+ if len(trimmed) == 0 {+ return nil+ }+ var whole interface{}+ if err := json.Unmarshal(trimmed, &whole); err == nil {+ if records := coerceTranscriptCandidates(whole); records != nil {+ return records+ }+ }+ var out []transcriptRecord+ scanner := bufio.NewScanner(bytes.NewReader(data))+ scanner.Buffer(make([]byte, 0, 64*1024), 16*1024*1024)+ for scanner.Scan() {+ line := strings.TrimSpace(scanner.Text())+ if line == "" {+ continue+ }+ var v interface{}+ if err := json.Unmarshal([]byte(line), &v); err != nil {+ continue+ }+ if rec := asMap(v); rec != nil {+ out = append(out, rec)+ }+ }+ return out+}++func coerceTranscriptCandidates(v interface{}) []transcriptRecord {+ if list, ok := v.([]interface{}); ok {+ out := make([]transcriptRecord, 0, len(list))+ for _, item := range list {+ if rec := asMap(item); rec != nil {+ out = append(out, rec)+ }+ }+ return out+ }+ rec := asMap(v)+ if rec == nil {+ return nil+ }+ for _, key := range []string{"messages", "events", "entries"} {+ if list, ok := rec[key].([]interface{}); ok {+ out := make([]transcriptRecord, 0, len(list))+ for _, item := range list {+ if child := asMap(item); child != nil {+ out = append(out, child)+ }+ }+ return out+ }+ }+ return []transcriptRecord{rec}+}++func appendTranscriptMessage(out *[]Record, pending map[string]Record, msg map[string]interface{}, baseID string, ts int64, fallbackRole, fallbackModel string, order int) int {+ role := normalizeRole(firstNonEmpty(pickString(msg, "role"), fallbackRole))+ model := firstNonEmpty(pickString(msg, "modelId", "model"), fallbackModel)+ if role == "user" {+ if text := messageText(msg); text != "" {+ *out = append(*out, Record{Order: order, NativeID: baseID, Type: "user_message", TimestampMS: ts, Content: stripUserQueryTags(text), Model: model})+ order+++ }+ return order+ }+ if role == "assistant" || role == "agent" {+ reasoning := reasoningTexts(msg)+ for i, thinking := range reasoning {+ if strings.TrimSpace(thinking) == "" {+ continue+ }+ *out = append(*out, Record{Order: order, NativeID: fmt.Sprintf("%s:thinking:%d", baseID, i), Type: "agent_thinking", TimestampMS: ts, Content: thinking, Model: model})+ order+++ }+ if text := messageText(msg); text != "" {+ *out = append(*out, Record{Order: order, NativeID: baseID, Type: "agent_text", TimestampMS: ts, Content: text, Model: model})+ order+++ }+ for _, call := range toolCallsFromMessage(msg) {+ r := transcriptToolCall(call, baseID, ts, order)+ pending[r.CallID] = r+ *out = append(*out, r)+ order+++ }+ return order+ }+ if text := messageText(msg); text != "" {+ *out = append(*out, Record{Order: order, NativeID: baseID, Type: "agent_text", TimestampMS: ts, Content: text, Model: model})+ order+++ }+ return order+}++func reasoningTexts(msg map[string]interface{}) []string {+ var out []string+ if text := pickString(msg, "thinking", "reasoning"); text != "" {+ out = append(out, text)+ }+ for _, block := range normalizeBlocks(msg["content"]) {+ typ := strings.ToLower(firstNonEmpty(pickString(block, "type"), "text"))+ if typ == "thinking" || typ == "reasoning" {+ if text := firstNonEmpty(pickString(block, "thinking", "text"), stringFrom(block["content"])); text != "" {+ out = append(out, text)+ }+ }+ }+ return out+}++func messageText(msg map[string]interface{}) string {+ if text := firstNonEmpty(pickString(msg, "text"), stringFrom(msg["content"]), stringFrom(msg["message"])); text != "" {+ return text+ }+ var parts []string+ for _, block := range normalizeBlocks(msg["content"]) {+ typ := strings.ToLower(firstNonEmpty(pickString(block, "type"), "text"))+ if typ != "text" {+ continue+ }+ if text := firstNonEmpty(pickString(block, "text"), stringFrom(block["content"])); text != "" {+ parts = append(parts, text)+ }+ }+ return strings.TrimSpace(strings.Join(parts, "\n"))+}++func userTextFromRecord(rec transcriptRecord) string {+ typ := strings.ToLower(pickString(rec, "type"))+ role := normalizeRole(pickString(rec, "role"))+ if typ == "user_message" || role == "user" {+ return firstNonEmpty(messageText(rec), stringFrom(rec["message"]))+ }+ if msg := asMap(rec["message"]); msg != nil {+ if normalizeRole(pickString(msg, "role")) == "user" {+ return messageText(msg)+ }+ }+ return ""+}++func toolCallsFromMessage(msg map[string]interface{}) []map[string]interface{} {+ var out []map[string]interface{}+ for _, key := range []string{"toolCalls", "tool_calls"} {+ if list, ok := msg[key].([]interface{}); ok {+ for _, item := range list {+ if call := asMap(item); call != nil {+ out = append(out, call)+ }+ }+ }+ }+ return out+}++func transcriptToolCall(call map[string]interface{}, baseID string, ts int64, order int) Record {+ callID := firstNonEmpty(pickString(call, "id", "toolCallId", "callId"), baseID+":call")+ name := firstNonEmpty(pickString(call, "name", "toolName", "tool"), "unknown_tool")+ args := objectArgs(firstNonNil(call["args"], call["arguments"], call["params"], call["input"]))+ return Record{Order: order, NativeID: baseID + ":tool_call", Type: "tool_call", TimestampMS: ts, CallID: callID, ToolName: name, Args: args}+}++func transcriptToolResult(result map[string]interface{}, baseID string, ts int64, order int, pending map[string]Record) Record {+ callID := firstNonEmpty(pickString(result, "toolCallId", "callId", "id"), baseID+":call")+ name := firstNonEmpty(pickString(result, "toolName", "name", "tool"), pending[callID].ToolName, "unknown_tool")+ args := pending[callID].Args+ output := firstNonEmpty(pickString(result, "output", "result", "content", "text"), stringify(firstNonNil(result["result"], result["data"])))+ status := strings.ToLower(firstNonEmpty(pickString(result, "status"), "success"))+ if status == "failure" || status == "failed" {+ status = "error"+ }+ return Record{Order: order, NativeID: baseID + ":tool_result", Type: "tool_result", TimestampMS: ts, CallID: callID, ToolName: name, Args: args, Output: output, Status: status}+}++func parseTranscriptTimestamp(rec map[string]interface{}, fallback int64) int64 {+ for _, key := range []string{"timestamp", "createdAt", "time"} {+ if ms := millisFrom(rec[key]); ms > 0 {+ return ms+ }+ }+ return fallback+}++func millisFrom(v interface{}) int64 {+ switch typed := v.(type) {+ case float64:+ return int64(typed)+ case int64:+ return typed+ case json.Number:+ n, _ := typed.Int64()+ return n+ case string:+ if typed == "" {+ return 0+ }+ if n, err := strconv.ParseInt(typed, 10, 64); err == nil {+ return n+ }+ if t, err := time.Parse(time.RFC3339Nano, typed); err == nil {+ return t.UnixMilli()+ }+ }+ return 0+}++func formatToolFormerResult(data *toolFormerData) string {+ if data == nil {+ return ""+ }+ if strings.TrimSpace(data.Result) != "" {+ var pretty interface{}+ if err := json.Unmarshal([]byte(data.Result), &pretty); err == nil {+ if encoded, err := json.MarshalIndent(pretty, "", " "); err == nil {+ return string(encoded)+ }+ }+ return data.Result+ }+ if data.AdditionalData != nil && isCursorGrepTool(data.Name) {+ return cursorGrepSummary(data.AdditionalData)+ }+ return ""+}++func cursorGrepSummary(data map[string]interface{}) string {+ var lines []string+ if v, ok := data["totalMatches"].(float64); ok {+ lines = append(lines, fmt.Sprintf("Matches: %.0f", v))+ }+ if v, ok := data["totalFiles"].(float64); ok {+ lines = append(lines, fmt.Sprintf("Files: %.0f", v))+ }+ if pattern, ok := data["pattern"].(string); ok && strings.TrimSpace(pattern) != "" {+ lines = append(lines, "Pattern: "+pattern)+ }+ if path, ok := data["path"].(string); ok && strings.TrimSpace(path) != "" {+ lines = append(lines, "Path: "+path)+ }+ return strings.Join(lines, "\n")+}++func isCursorGrepTool(name string) bool {+ normalized := strings.NewReplacer("-", "", "_", "", " ", "").Replace(strings.ToLower(name))+ return strings.Contains(normalized, "grep") || strings.Contains(normalized, "ripgrep") || (strings.Contains(normalized, "search") && strings.Contains(normalized, "code"))+}++func decodeArgs(params string) map[string]interface{} {+ if strings.TrimSpace(params) == "" {+ return nil+ }+ var out map[string]interface{}+ if err := json.Unmarshal([]byte(params), &out); err != nil {+ return map[string]interface{}{"raw": params}+ }+ return out+}++func objectArgs(v interface{}) map[string]interface{} {+ switch typed := v.(type) {+ case map[string]interface{}:+ return typed+ case string:+ return decodeArgs(typed)+ default:+ if typed == nil {+ return nil+ }+ return map[string]interface{}{"value": typed}+ }+}++func (s *Store) enrichEditFileV2Args(db *sql.DB, args map[string]interface{}, result string) map[string]interface{} {+ if args == nil {+ args = map[string]interface{}{}+ }+ var resultObj map[string]interface{}+ if err := json.Unmarshal([]byte(result), &resultObj); err != nil {+ return args+ }+ beforeID, _ := resultObj["beforeContentId"].(string)+ afterID, _ := resultObj["afterContentId"].(string)+ before := readComposerContent(db, beforeID)+ after := readComposerContent(db, afterID)+ if before == "" || after == "" {+ return args+ }+ if _, ok := args["path"]; !ok {+ if path, ok := args["relativeWorkspacePath"].(string); ok {+ args["path"] = path+ }+ }+ args["old_string"] = truncateForArg(before)+ args["new_string"] = truncateForArg(after)+ return args+}++func readComposerContent(db *sql.DB, id string) string {+ if strings.TrimSpace(id) == "" {+ return ""+ }+ key := id+ if !strings.HasPrefix(key, contentPrefix) {+ key = contentPrefix + key+ }+ var raw []byte+ if err := db.QueryRow(`SELECT value FROM cursorDiskKV WHERE key = ?`, key).Scan(&raw); err != nil {+ return ""+ }+ return string(raw)+}++func truncateForArg(value string) string {+ const limit = 100000+ if len(value) <= limit {+ return value+ }+ return value[:limit]+}++func compactionSummary(c composerData) map[string]interface{} {+ if c.LatestConversationSummary == nil || c.LatestConversationSummary.Summary == nil {+ return nil+ }+ summary := c.LatestConversationSummary.Summary+ if strings.TrimSpace(summary.TruncationLastBubbleIDInclusive) == "" {+ return nil+ }+ out := map[string]interface{}{+ "compacted_through_id": summary.TruncationLastBubbleIDInclusive,+ }+ if v := strings.TrimSpace(c.LatestConversationSummary.LastBubbleID); v != "" {+ out["boundary_message_id"] = v+ }+ if v := strings.TrimSpace(summary.PreviousConversationSummaryBubbleID); v != "" {+ out["previous_compaction_id"] = v+ }+ if v := strings.TrimSpace(summary.ClientShouldStartSendingFromInclusive); v != "" {+ out["retained_from_id"] = v+ }+ if v := strings.TrimSpace(summary.Summary); v != "" {+ out["summary"] = v+ }+ if summary.IncludesToolResults != nil {+ out["summary_includes_tool_results"] = *summary.IncludesToolResults+ }+ return out+}++func (s *Store) resolveComposerWorkspace(db queryRower, id string, composer composerData) string {+ if path := directoryFromContext(composer.Context); path != "" {+ return path+ }+ for i, header := range composer.FullConversationHeadersOnly {+ if i >= 8 {+ break+ }+ bubble, ok := readBubbleFrom(db, id, header.BubbleID)+ if !ok {+ continue+ }+ if path := directoryFromURIs(bubble.WorkspaceURIs); path != "" {+ return path+ }+ if path := directoryFromContext(bubble.Context); path != "" {+ return path+ }+ if path := directoryFromTool(bubble.ToolFormerData); path != "" {+ return path+ }+ }+ return ""+}++type queryRower interface {+ QueryRow(query string, args ...interface{}) *sql.Row+}++func readBubbleFrom(db queryRower, composerID, bubbleID string) (bubbleData, bool) {+ var raw []byte+ err := db.QueryRow(`SELECT value FROM cursorDiskKV WHERE key = ?`, bubblePrefix+composerID+":"+bubbleID).Scan(&raw)+ if err != nil {+ return bubbleData{}, false+ }+ var bubble bubbleData+ if err := json.Unmarshal(raw, &bubble); err != nil {+ return bubbleData{}, false+ }+ return bubble, true+}++func directoryFromContext(ctx map[string]interface{}) string {+ if ctx == nil {+ return ""+ }+ var candidates []interface{}+ for _, key := range []string{"uri", "path"} {+ if ctx[key] != nil {+ candidates = append(candidates, ctx[key])+ }+ }+ for _, key := range []string{"folderSelections", "fileSelections", "terminalFiles"} {+ if list, ok := ctx[key].([]interface{}); ok {+ candidates = append(candidates, list...)+ }+ }+ for _, candidate := range candidates {+ if path := directoryCandidate(candidate); path != "" {+ return path+ }+ }+ return ""+}++func directoryFromURIs(values []string) string {+ for _, value := range values {+ if path := normalizeDirectoryCandidate(value); path != "" {+ return path+ }+ }+ return ""+}++func directoryFromTool(tool *toolFormerData) string {+ if tool == nil || strings.TrimSpace(tool.Params) == "" {+ return ""+ }+ args := decodeArgs(tool.Params)+ for _, key := range []string{"targetFile", "targetDirectory", "filePath", "file_path", "path", "directoryPath", "directory_path", "absolutePath"} {+ if value, ok := args[key].(string); ok && filepath.IsAbs(value) {+ return filepath.Dir(value)+ }+ }+ return ""+}++func directoryCandidate(v interface{}) string {+ if s, ok := v.(string); ok {+ return normalizeDirectoryCandidate(s)+ }+ m := asMap(v)+ if m == nil {+ return ""+ }+ for _, key := range []string{"uri", "path", "filePath"} {+ if value, ok := m[key].(string); ok {+ if path := normalizeDirectoryCandidate(value); path != "" {+ return path+ }+ }+ }+ return ""+}++func normalizeDirectoryCandidate(value string) string {+ value = strings.TrimSpace(value)+ if value == "" {+ return ""+ }+ if strings.HasPrefix(value, "file://") {+ u, err := url.Parse(value)+ if err != nil || u.Scheme != "file" {+ return ""+ }+ value = u.Path+ }+ if !filepath.IsAbs(value) {+ return ""+ }+ if info, err := os.Stat(value); err == nil && !info.IsDir() {+ return filepath.Dir(value)+ }+ return value+}++func resolveDashEncodedProjectDirectory(name string) string {+ parts := strings.FieldsFunc(strings.TrimLeft(name, "-"), func(r rune) bool { return r == '-' })+ if len(parts) == 0 {+ return ""+ }+ seen := map[string]bool{}+ var walk func(root string, idx int) string+ walk = func(root string, idx int) string {+ key := root + "\x00" + strconv.Itoa(idx)+ if seen[key] {+ return ""+ }+ seen[key] = true+ for end := len(parts); end > idx; end-- {+ candidate := filepath.Join(append([]string{root}, parts[idx:end]...)...)+ info, err := os.Stat(candidate)+ if err != nil || !info.IsDir() {+ continue+ }+ if end == len(parts) {+ return candidate+ }+ if nested := walk(candidate, end); nested != "" {+ return nested+ }+ }+ return ""+ }+ if resolved := walk(string(filepath.Separator), 0); resolved != "" {+ return resolved+ }+ return name+}++func stripUserQueryTags(s string) string {+ s = regexp.MustCompile(`(?s)<user_query>\s*(.*?)\s*</user_query>`).ReplaceAllString(s, "$1")+ return strings.TrimSpace(s)+}++func isTranscriptFilename(name string) bool {+ if name == "" || strings.HasPrefix(name, ".") {+ return false+ }+ lower := strings.ToLower(name)+ return strings.HasSuffix(lower, ".json") || strings.HasSuffix(lower, ".jsonl") || filepath.Ext(name) == ""+}++func traceIDFromFilename(name string) string {+ lower := strings.ToLower(name)+ switch {+ case strings.HasSuffix(lower, ".jsonl"):+ return name[:len(name)-6]+ case strings.HasSuffix(lower, ".json"):+ return name[:len(name)-5]+ default:+ return name+ }+}++func normalizeTraceID(id string) string {+ return strings.TrimPrefix(strings.TrimPrefix(strings.TrimPrefix(strings.TrimSpace(id), "transcript:"), "transcript%3A"), "transcript_3A")+}++func birthUnixMS(path string, fallback int64) int64 {+ info, err := os.Stat(path)+ if err != nil {+ return fallback+ }+ if !info.ModTime().IsZero() {+ return info.ModTime().UnixMilli()+ }+ return fallback+}++func asMap(v interface{}) map[string]interface{} {+ if v == nil {+ return nil+ }+ if m, ok := v.(map[string]interface{}); ok {+ return m+ }+ if rec, ok := v.(transcriptRecord); ok {+ return map[string]interface{}(rec)+ }+ return nil+}++func normalizeBlocks(v interface{}) []map[string]interface{} {+ var out []map[string]interface{}+ if list, ok := v.([]interface{}); ok {+ for _, item := range list {+ if m := asMap(item); m != nil {+ out = append(out, m)+ }+ }+ }+ return out+}++func pickString(m map[string]interface{}, keys ...string) string {+ for _, key := range keys {+ if value := stringFrom(m[key]); value != "" {+ return value+ }+ }+ return ""+}++func pickNestedString(m map[string]interface{}, first, second string) string {+ if child := asMap(m[first]); child != nil {+ return pickString(child, second)+ }+ return ""+}++func stringFrom(v interface{}) string {+ switch typed := v.(type) {+ case string:+ return typed+ case fmt.Stringer:+ return typed.String()+ default:+ return ""+ }+}++func stringify(v interface{}) string {+ if v == nil {+ return ""+ }+ if s := stringFrom(v); s != "" {+ return s+ }+ data, err := json.Marshal(v)+ if err != nil {+ return ""+ }+ return string(data)+}++func firstNonNil(values ...interface{}) interface{} {+ for _, value := range values {+ if value != nil {+ return value+ }+ }+ return nil+}++func firstNonEmpty(values ...string) string {+ for _, value := range values {+ if strings.TrimSpace(value) != "" {+ return value+ }+ }+ return ""+}++func normalizeRole(role string) string {+ switch strings.ToLower(strings.TrimSpace(role)) {+ case "human", "user":+ return "user"+ case "assistant", "agent", "ai":+ return "assistant"+ default:+ return strings.ToLower(strings.TrimSpace(role))+ }+}++func truncateLine(value string, limit int) string {+ value = strings.TrimSpace(strings.ReplaceAll(value, "\n", " "))+ if len(value) <= limit {+ return value+ }+ return value[:limit]+}++func shortID(id string) string {+ if len(id) <= 12 {+ return id+ }+ return id[:12]+}++func stringValue(v interface{}) string {+ if s, ok := v.(string); ok {+ return s+ }+ return ""+}++func outPtr(out *[]Record) *[]Record { return out }diff --git a/cli/beacon/internal/cursorsession/store.go b/cli/beacon/internal/cursorsession/store.gonew file mode 100644index 00000000..1e9839e2--- /dev/null+++ b/cli/beacon/internal/cursorsession/store.go@@ -0,0 +1,438 @@+package cursorsession++import (+ "database/sql"+ "encoding/json"+ "errors"+ "fmt"+ "io/fs"+ "net/url"+ "os"+ "path/filepath"+ "runtime"+ "sort"+ "strings"++ _ "modernc.org/sqlite"+)++const (+ composerDataPrefix = "composerData:"+ composerDataEnd = "composerData;"+ bubblePrefix = "bubbleId:"+ contentPrefix = "composer.content."+)++type Store struct {+ GlobalDBPath string+ ProjectsDir string+}++func NewStore(globalDBPath, projectsDir string) (*Store, error) {+ if strings.TrimSpace(globalDBPath) == "" {+ globalDBPath = DefaultGlobalDBPath()+ }+ if strings.TrimSpace(projectsDir) == "" {+ projectsDir = DefaultProjectsDir()+ }+ return &Store{GlobalDBPath: globalDBPath, ProjectsDir: projectsDir}, nil+}++func DefaultGlobalDBPath() string {+ home, err := os.UserHomeDir()+ if err != nil || strings.TrimSpace(home) == "" {+ return ""+ }+ switch runtime.GOOS {+ case "darwin":+ return filepath.Join(home, "Library", "Application Support", "Cursor", "User", "globalStorage", "state.vscdb")+ case "windows":+ if appData := strings.TrimSpace(os.Getenv("APPDATA")); appData != "" {+ return filepath.Join(appData, "Cursor", "User", "globalStorage", "state.vscdb")+ }+ return filepath.Join(home, "AppData", "Roaming", "Cursor", "User", "globalStorage", "state.vscdb")+ default:+ if xdg := strings.TrimSpace(os.Getenv("XDG_CONFIG_HOME")); xdg != "" {+ return filepath.Join(xdg, "Cursor", "User", "globalStorage", "state.vscdb")+ }+ return filepath.Join(home, ".config", "Cursor", "User", "globalStorage", "state.vscdb")+ }+}++func DefaultProjectsDir() string {+ home, err := os.UserHomeDir()+ if err != nil || strings.TrimSpace(home) == "" {+ return ""+ }+ return filepath.Join(home, ".cursor", "projects")+}++func (s *Store) Exists() bool {+ return fileExists(s.GlobalDBPath) || dirExists(s.ProjectsDir)+}++func (s *Store) List() ([]TraceRef, error) {+ var refs []TraceRef+ global, err := s.listGlobalStorage()+ if err != nil {+ return refs, err+ }+ refs = append(refs, global...)+ transcripts, err := s.listTranscripts()+ if err != nil {+ return refs, err+ }+ refs = append(refs, transcripts...)+ sort.SliceStable(refs, func(i, j int) bool {+ if refs[i].UpdatedAtUnixMS != refs[j].UpdatedAtUnixMS {+ return refs[i].UpdatedAtUnixMS < refs[j].UpdatedAtUnixMS+ }+ return refs[i].ID < refs[j].ID+ })+ return refs, nil+}++func (s *Store) listGlobalStorage() ([]TraceRef, error) {+ if !fileExists(s.GlobalDBPath) {+ return nil, nil+ }+ db, err := openSQLiteReadOnly(s.GlobalDBPath)+ if err != nil {+ return nil, fmt.Errorf("open Cursor global storage: %w", err)+ }+ defer db.Close()++ rows, err := db.Query(`SELECT key, value FROM cursorDiskKV WHERE key >= ? AND key < ? AND LENGTH(value) > 10`, composerDataPrefix, composerDataEnd)+ if err != nil {+ return nil, fmt.Errorf("read Cursor composers: %w", err)+ }+ defer rows.Close()++ var refs []TraceRef+ for rows.Next() {+ var key string+ var value []byte+ if err := rows.Scan(&key, &value); err != nil {+ continue+ }+ id := strings.TrimPrefix(key, composerDataPrefix)+ id = normalizeTraceID(id)+ if id == "" {+ continue+ }+ var composer composerData+ if err := json.Unmarshal(value, &composer); err != nil {+ continue+ }+ if len(composer.FullConversationHeadersOnly) == 0 {+ continue+ }+ updated := composer.LastUpdatedAt.Millis+ if updated == 0 {+ updated = composer.CreatedAt.Millis+ }+ preview := composerPreview(composer)+ refs = append(refs, TraceRef{+ ID: id,+ Kind: SourceGlobalStorage,+ SourcePath: "global:" + id,+ Title: firstNonEmpty(composer.Name, preview),+ Preview: preview,+ Workspace: s.resolveComposerWorkspace(db, id, composer),+ UpdatedAtUnixMS: updated,+ CreatedAtUnixMS: composer.CreatedAt.Millis,+ SizeBytes: int64(len(value)),+ })+ }+ return refs, rows.Err()+}++func (s *Store) listTranscripts() ([]TraceRef, error) {+ if !dirExists(s.ProjectsDir) {+ return nil, nil+ }+ projectDirs, err := os.ReadDir(s.ProjectsDir)+ if err != nil {+ if errors.Is(err, fs.ErrNotExist) {+ return nil, nil+ }+ return nil, fmt.Errorf("read Cursor projects directory: %w", err)+ }+ var refs []TraceRef+ for _, project := range projectDirs {+ if !project.IsDir() {+ continue+ }+ projectPath := filepath.Join(s.ProjectsDir, project.Name())+ transcriptDir := filepath.Join(projectPath, "agent-transcripts")+ for _, entry := range listTranscriptFiles(transcriptDir) {+ preview := transcriptPreview(entry.Path)+ refs = append(refs, TraceRef{+ ID: normalizeTraceID(entry.TraceID),+ Kind: SourceTranscript,+ SourcePath: entry.Path,+ Title: firstNonEmpty(preview, "Cursor session "+shortID(entry.TraceID)),+ Preview: preview,+ Workspace: resolveDashEncodedProjectDirectory(project.Name()),+ UpdatedAtUnixMS: entry.Info.ModTime().UnixMilli(),+ CreatedAtUnixMS: birthUnixMS(entry.Path, entry.Info.ModTime().UnixMilli()),+ SizeBytes: entry.Info.Size(),+ RelatedTo: entry.RelatedTo,+ RelationshipType: entry.RelationshipType,+ })+ }+ }+ return refs, nil+}++type transcriptEntry struct {+ TraceID string+ Path string+ Info os.FileInfo+ RelatedTo string+ RelationshipType string+}++func listTranscriptFiles(dir string) []transcriptEntry {+ entries, err := os.ReadDir(dir)+ if err != nil {+ return nil+ }+ var out []transcriptEntry+ for _, entry := range entries {+ path := filepath.Join(dir, entry.Name())+ info, err := entry.Info()+ if err != nil {+ continue+ }+ if info.Mode().IsRegular() && isTranscriptFilename(entry.Name()) {+ out = append(out, transcriptEntry{TraceID: traceIDFromFilename(entry.Name()), Path: path, Info: info})+ continue+ }+ if !entry.IsDir() {+ continue+ }+ children, err := os.ReadDir(path)+ if err == nil {+ for _, child := range children {+ childPath := filepath.Join(path, child.Name())+ childInfo, err := child.Info()+ if err == nil && childInfo.Mode().IsRegular() && isTranscriptFilename(child.Name()) {+ out = append(out, transcriptEntry{TraceID: traceIDFromFilename(child.Name()), Path: childPath, Info: childInfo})+ }+ }+ }+ out = append(out, listSubagentTranscriptEntries(filepath.Join(path, "subagents"), normalizeTraceID(entry.Name()))...)+ }+ return out+}++func listSubagentTranscriptEntries(dir, parentID string) []transcriptEntry {+ entries, err := os.ReadDir(dir)+ if err != nil {+ return nil+ }+ var out []transcriptEntry+ for _, entry := range entries {+ if !isTranscriptFilename(entry.Name()) {+ continue+ }+ path := filepath.Join(dir, entry.Name())+ info, err := entry.Info()+ if err != nil || !info.Mode().IsRegular() {+ continue+ }+ out = append(out, transcriptEntry{+ TraceID: traceIDFromFilename(entry.Name()),+ Path: path,+ Info: info,+ RelatedTo: parentID,+ RelationshipType: "subagent",+ })+ }+ return out+}++func (s *Store) Read(ref TraceRef) ([]Record, error) {+ switch ref.Kind {+ case SourceGlobalStorage:+ return s.readGlobalStorage(ref)+ case SourceTranscript:+ return s.readTranscript(ref)+ default:+ return nil, nil+ }+}++func (s *Store) readGlobalStorage(ref TraceRef) ([]Record, error) {+ db, err := openSQLiteReadOnly(s.GlobalDBPath)+ if err != nil {+ return nil, fmt.Errorf("open Cursor global storage: %w", err)+ }+ defer db.Close()+ id := strings.TrimPrefix(ref.SourcePath, "global:")+ if id == "" {+ id = ref.ID+ }+ var raw []byte+ if err := db.QueryRow(`SELECT value FROM cursorDiskKV WHERE key = ?`, composerDataPrefix+id).Scan(&raw); err != nil {+ return nil, err+ }+ var composer composerData+ if err := json.Unmarshal(raw, &composer); err != nil {+ return nil, err+ }+ records := make([]Record, 0, len(composer.FullConversationHeadersOnly))+ model := ""+ if composer.ModelConfig != nil {+ model = composer.ModelConfig.ModelName+ }+ order := 1+ for _, header := range composer.FullConversationHeadersOnly {+ bubble, ok := readBubble(db, id, header.BubbleID)+ if !ok {+ continue+ }+ ts := bubble.CreatedAt.Millis+ duration := bubble.TurnDurationMS+ switch bubble.Type {+ case 1:+ if strings.TrimSpace(bubble.Text) != "" {+ records = append(records, Record{Order: order, NativeID: header.BubbleID, Type: "user_message", TimestampMS: ts, Content: bubble.Text})+ order+++ }+ case 2:+ for i, block := range bubble.AllThinkingBlocks {+ if strings.TrimSpace(block.Thinking) == "" {+ continue+ }+ records = append(records, Record{Order: order, NativeID: fmt.Sprintf("%s:thinking:%d", header.BubbleID, i), Type: "agent_thinking", TimestampMS: ts, DurationMS: duration, Content: block.Thinking})+ order+++ }+ if bubble.Thinking != nil && strings.TrimSpace(bubble.Thinking.Text) != "" {+ records = append(records, Record{Order: order, NativeID: header.BubbleID + ":thinking", Type: "agent_thinking", TimestampMS: ts, DurationMS: bubble.ThinkingDurationMS, Content: bubble.Thinking.Text})+ order+++ }+ if bubble.ToolFormerData != nil {+ callID := fmt.Sprintf("%s:tool", header.BubbleID)+ args := decodeArgs(bubble.ToolFormerData.Params)+ if bubble.ToolFormerData.Name == "edit_file_v2" {+ args = s.enrichEditFileV2Args(db, args, bubble.ToolFormerData.Result)+ }+ records = append(records, Record{Order: order, NativeID: header.BubbleID + ":tool_call", Type: "tool_call", TimestampMS: ts, DurationMS: duration, CallID: callID, ToolName: firstNonEmpty(bubble.ToolFormerData.Name, "unknown_tool"), Args: args})+ order+++ if output := formatToolFormerResult(bubble.ToolFormerData); output != "" {+ status := "success"+ if bubble.ToolFormerData.Status == "error" {+ status = "error"+ }+ records = append(records, Record{Order: order, NativeID: header.BubbleID + ":tool_result", Type: "tool_result", TimestampMS: ts, DurationMS: duration, CallID: callID, ToolName: firstNonEmpty(bubble.ToolFormerData.Name, "unknown_tool"), Args: args, Output: output, Status: status})+ order+++ }+ } else if strings.TrimSpace(bubble.Text) != "" {+ records = append(records, Record{Order: order, NativeID: header.BubbleID, Type: "agent_text", TimestampMS: ts, DurationMS: duration, Content: bubble.Text, Model: model})+ order+++ }+ if bubble.ErrorDetails != nil && strings.TrimSpace(bubble.ErrorDetails.Message) != "" {+ msg := bubble.ErrorDetails.Message+ if strings.TrimSpace(bubble.ErrorDetails.Title) != "" {+ msg = bubble.ErrorDetails.Title + ": " + msg+ }+ records = append(records, Record{Order: order, NativeID: header.BubbleID + ":error", Type: "error", TimestampMS: ts, DurationMS: duration, Content: msg})+ order+++ }+ }+ }+ if summary := compactionSummary(composer); summary != nil {+ records = append(records, Record{Order: order, NativeID: "compaction:" + stringValue(summary["compacted_through_id"]), Type: "system_event", Subtype: "compaction", TimestampMS: ref.UpdatedAtUnixMS, Data: summary})+ }+ return records, nil+}++func readBubble(db *sql.DB, composerID, bubbleID string) (bubbleData, bool) {+ var raw []byte+ err := db.QueryRow(`SELECT value FROM cursorDiskKV WHERE key = ?`, bubblePrefix+composerID+":"+bubbleID).Scan(&raw)+ if err != nil {+ return bubbleData{}, false+ }+ var bubble bubbleData+ if err := json.Unmarshal(raw, &bubble); err != nil {+ return bubbleData{}, false+ }+ return bubble, true+}++func (s *Store) readTranscript(ref TraceRef) ([]Record, error) {+ data, err := os.ReadFile(ref.SourcePath)+ if err != nil {+ return nil, err+ }+ records := parseTranscriptRecords(data)+ out := make([]Record, 0, len(records))+ order := 1+ pending := map[string]Record{}+ for i, rec := range records {+ ts := parseTranscriptTimestamp(rec, ref.UpdatedAtUnixMS)+ model := firstNonEmpty(pickString(rec, "modelId", "model", "newModel"), pickNestedString(rec, "data", "model"), pickNestedString(rec, "data", "modelId"))+ typ := strings.ToLower(pickString(rec, "type"))+ role := normalizeRole(pickString(rec, "role"))+ baseID := firstNonEmpty(pickString(rec, "id"), fmt.Sprintf("entry-%d", i+1))+ before := len(out)+ switch {+ case typ == "message":+ msg := asMap(rec["message"])+ if msg == nil {+ msg = map[string]interface{}{+ "role": role,+ "text": firstNonEmpty(pickString(rec, "text"), stringFrom(rec["message"])),+ "content": rec["content"],+ "model": model,+ }+ }+ order = appendTranscriptMessage(outPtr(&out), pending, msg, baseID, ts, role, model, order)+ case typ == "user_message":+ msg := map[string]interface{}{"role": "user", "text": firstNonEmpty(pickString(rec, "text"), stringFrom(rec["message"])), "content": rec["content"]}+ order = appendTranscriptMessage(outPtr(&out), pending, msg, baseID, ts, "user", model, order)+ case typ == "tool_call" || typ == "tool_use" || typ == "function_call":+ call := asMap(firstNonNil(rec["toolCall"], rec["functionCall"], rec["data"], rec))+ r := transcriptToolCall(call, baseID, ts, order)+ pending[r.CallID] = r+ out = append(out, r)+ order+++ case typ == "tool_result" || typ == "tool_output" || typ == "function_call_output":+ result := asMap(firstNonNil(rec["toolResult"], rec["functionResult"], rec["data"], rec))+ r := transcriptToolResult(result, baseID, ts, order, pending)+ out = append(out, r)+ order+++ }+ if len(out) == before && role != "" {+ order = appendTranscriptMessage(outPtr(&out), pending, rec, baseID, ts, role, model, order)+ }+ }+ return out, nil+}++func openSQLiteReadOnly(path string) (*sql.DB, error) {+ u := url.URL{Scheme: "file", Path: path}+ q := u.Query()+ q.Set("mode", "ro")+ q.Set("_pragma", "busy_timeout(1000)")+ u.RawQuery = q.Encode()+ return sql.Open("sqlite", u.String())+}++func fileExists(path string) bool {+ if strings.TrimSpace(path) == "" {+ return false+ }+ info, err := os.Stat(path)+ return err == nil && info.Mode().IsRegular()+}++func dirExists(path string) bool {+ if strings.TrimSpace(path) == "" {+ return false+ }+ info, err := os.Stat(path)+ return err == nil && info.IsDir()+}diff --git a/cli/beacon/internal/cursorsession/types.go b/cli/beacon/internal/cursorsession/types.gonew file mode 100644index 00000000..e8c1d23a--- /dev/null+++ b/cli/beacon/internal/cursorsession/types.go@@ -0,0 +1,152 @@+// Package cursorsession reads Cursor's local conversation stores and converts+// committed session records into Beacon endpoint telemetry.+//+// Cursor has two durable stores that matter here. Recent Composer sessions live+// in the VS Code global storage SQLite database under cursorDiskKV keys such as+// `composerData:<id>` and `bubbleId:<id>:<bubble>`. Cursor Agent transcripts+// are JSON/JSONL files under ~/.cursor/projects/*/agent-transcripts. Both are+// local records written after the fact, so every event produced here is marked+// harness.collection_method=poll.+package cursorsession++import (+ "encoding/json"+ "time"+)++const Harness = "cursor"++type SourceKind string++const (+ SourceGlobalStorage SourceKind = "global_storage"+ SourceTranscript SourceKind = "agent_transcript"+)++type TraceRef struct {+ ID string+ Kind SourceKind+ SourcePath string+ Title string+ Preview string+ Workspace string+ UpdatedAtUnixMS int64+ CreatedAtUnixMS int64+ SizeBytes int64+ RelationshipType string+ RelatedTo string+}++type Record struct {+ Order int+ NativeID string+ Type string+ Subtype string+ TimestampMS int64+ DurationMS int64+ Content string+ Model string+ CallID string+ ToolName string+ Args map[string]interface{}+ Output string+ Status string+ Data map[string]interface{}+}++type composerData struct {+ ComposerID string `json:"composerId"`+ Name string `json:"name"`+ Text string `json:"text"`+ RichText string `json:"richText"`+ CreatedAt jsonTimeOrNumber `json:"createdAt"`+ LastUpdatedAt jsonTimeOrNumber `json:"lastUpdatedAt"`+ FullConversationHeadersOnly []conversationHeader `json:"fullConversationHeadersOnly"`+ ModelConfig *composerModelConfig `json:"modelConfig"`+ Context map[string]interface{} `json:"context"`+ LatestConversationSummary *latestConversationState `json:"latestConversationSummary"`+ SubagentComposerIDs []string `json:"subagentComposerIds"`+}++type composerModelConfig struct {+ ModelName string `json:"modelName"`+}++type conversationHeader struct {+ BubbleID string `json:"bubbleId"`+ Type int `json:"type"`+}++type bubbleData struct {+ Type int `json:"type"`+ Text string `json:"text"`+ CreatedAt jsonTimeOrNumber `json:"createdAt"`+ TurnDurationMS int64 `json:"turnDurationMs"`+ ServerBubbleID string `json:"serverBubbleId"`+ WorkspaceURIs []string `json:"workspaceUris"`+ Context map[string]interface{} `json:"context"`+ ConversationState string `json:"conversationState"`+ Thinking *struct {+ Text string `json:"text"`+ } `json:"thinking"`+ ThinkingDurationMS int64 `json:"thinkingDurationMs"`+ AllThinkingBlocks []struct {+ Thinking string `json:"thinking"`+ } `json:"allThinkingBlocks"`+ ToolFormerData *toolFormerData `json:"toolFormerData"`+ ErrorDetails *struct {+ Title string `json:"title"`+ Message string `json:"message"`+ } `json:"errorDetails"`+}++type toolFormerData struct {+ Name string `json:"name"`+ Params string `json:"params"`+ Result string `json:"result"`+ Status string `json:"status"`+ AdditionalData map[string]interface{} `json:"additionalData"`+}++type latestConversationState struct {+ LastBubbleID string `json:"lastBubbleId"`+ Summary *conversationSummary `json:"summary"`+}++type conversationSummary struct {+ TruncationLastBubbleIDInclusive string `json:"truncationLastBubbleIdInclusive"`+ PreviousConversationSummaryBubbleID string `json:"previousConversationSummaryBubbleId"`+ ClientShouldStartSendingFromInclusive string `json:"clientShouldStartSendingFromInclusiveBubbleId"`+ Summary string `json:"summary"`+ IncludesToolResults *bool `json:"includesToolResults"`+}++type transcriptRecord map[string]interface{}++type jsonTimeOrNumber struct {+ Millis int64+}++func (t *jsonTimeOrNumber) UnmarshalJSON(data []byte) error {+ var n float64+ if err := json.Unmarshal(data, &n); err == nil {+ t.Millis = int64(n)+ return nil+ }+ var s string+ if err := json.Unmarshal(data, &s); err != nil {+ return err+ }+ if s == "" {+ return nil+ }+ if parsed, err := time.Parse(time.RFC3339Nano, s); err == nil {+ t.Millis = parsed.UnixMilli()+ return nil+ }+ if parsed, err := time.Parse("2006-01-02 15:04:05.999999999 -0700 MST", s); err == nil {+ t.Millis = parsed.UnixMilli()+ return nil+ }+ return nil+}