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 prime session sync
Justin D'Souza5811a8147295
diff --git a/cli/beacon/cmd/endpoint_prime.go b/cli/beacon/cmd/endpoint_prime.gonew file mode 100644index 00000000..9cdc5fcc--- /dev/null+++ b/cli/beacon/cmd/endpoint_prime.go@@ -0,0 +1,240 @@+package cmd++import (+ "context"+ "encoding/json"+ "fmt"+ "path/filepath"+ "strings"+ "time"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/lifecycle"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/primesession"+ "github.com/spf13/cobra"+)++var endpointPrimeCmd = &cobra.Command{+ Use: "prime",+ Short: "Collect telemetry from Prime Agent session files",+ Long: `Collect endpoint telemetry from Prime Agent's local session store.++Prime Agent has a live Beacon extension for hook-time telemetry. This command is+the complementary poll path: it reads committed JSONL transcripts under+~/.prime/agent/sessions and converts records that were not already synced into+endpoint events. Every event is marked harness.collection_method=poll, because+Beacon is reading what Prime Agent wrote after the fact rather than observing the+agent as it works.`,+}++var endpointPrimeSyncCmd = &cobra.Command{+ Use: "sync",+ Short: "Read new Prime Agent session records into the runtime log",+ SilenceUsage: true,+ RunE: runEndpointPrimeSync,+}++var endpointPrimeStatusCmd = &cobra.Command{+ Use: "status",+ Short: "Show Prime Agent sessions and how much Beacon has collected",+ SilenceUsage: true,+ RunE: runEndpointPrimeStatus,+}++var endpointPrimeOpts struct {+ sessionsDir string+ artifactsDir string+ statePath string+ logPath string+ print bool+ watch bool+ interval time.Duration+}++func init() {+ endpointCmd.AddCommand(endpointPrimeCmd)+ endpointPrimeCmd.AddCommand(endpointPrimeSyncCmd)+ endpointPrimeCmd.AddCommand(endpointPrimeStatusCmd)++ for _, c := range []*cobra.Command{endpointPrimeSyncCmd, endpointPrimeStatusCmd} {+ f := c.Flags()+ f.StringVar(&endpointPrimeOpts.sessionsDir, "sessions-dir", "", "Prime Agent sessions directory (default ~/.prime/agent/sessions)")+ f.StringVar(&endpointPrimeOpts.artifactsDir, "artifacts-dir", "", "Prime Agent session artifacts directory (default ~/.prime/agent/session-artifacts)")+ f.StringVar(&endpointPrimeOpts.statePath, "state", "", "Collector cursor file (default ~/.beacon/endpoint/state/prime.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 := endpointPrimeSyncCmd.Flags()+ sync.StringVar(&endpointPrimeOpts.logPath, "log-path", "", "Runtime JSONL log path (default resolved endpoint log)")+ sync.BoolVar(&endpointPrimeOpts.print, "print", false, "Print mapped events as JSON without writing them or advancing the cursor (dry run)")+ sync.BoolVar(&endpointPrimeOpts.watch, "watch", false, "Sweep continuously on --interval (default: one sweep then exit)")+ sync.DurationVar(&endpointPrimeOpts.interval, "interval", time.Minute, "Sweep interval for --watch")+}++func runEndpointPrimeSync(cmd *cobra.Command, args []string) error {+ userMode := endpointUserMode()+ opts := primesession.CollectOptions{+ SessionsDir: endpointPrimeOpts.sessionsDir,+ ArtifactsDir: endpointPrimeOpts.artifactsDir,+ Print: endpointPrimeOpts.print,+ Out: cmd.OutOrStdout(),+ Write: !endpointPrimeOpts.print,+ UserMode: userMode,+ }+ if !endpointPrimeOpts.print {+ opts.StatePath = resolvePrimeStatePath(endpointPrimeOpts.statePath, userMode)+ opts.LogPath = lifecycle.ResolveRuntimeLog(userMode, endpointPrimeOpts.logPath).EffectiveLogPath+ }++ ctx := cmd.Context()+ if ctx == nil {+ ctx = context.Background()+ }+ if endpointPrimeOpts.watch && !endpointPrimeOpts.print {+ return watchPrime(ctx, cmd, opts)+ }+ summary, err := primesession.CollectOnce(opts)+ reportPrimeSweep(cmd, summary)+ return err+}++func watchPrime(ctx context.Context, cmd *cobra.Command, opts primesession.CollectOptions) error {+ interval := endpointPrimeOpts.interval+ if interval < 5*time.Second {+ interval = 5 * time.Second+ }+ for {+ summary, err := primesession.CollectOnce(opts)+ if err != nil {+ fmt.Fprintf(cmd.ErrOrStderr(), "Prime Agent sync error: %v\n", err)+ }+ reportPrimeSweep(cmd, summary)+ select {+ case <-ctx.Done():+ return nil+ case <-time.After(interval):+ }+ }+}++func reportPrimeSweep(cmd *cobra.Command, summary primesession.Summary) {+ if endpointPrimeOpts.print {+ return+ }+ if endpointOpts.jsonOutput {+ _ = json.NewEncoder(cmd.OutOrStdout()).Encode(summary)+ return+ }+ fmt.Fprintf(cmd.OutOrStdout(), "Prime Agent 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 Prime Agent session logs\n", summary.MalformedLines)+ }+}++type primeSessionStatus struct {+ SessionID string `json:"session_id"`+ SourcePath string `json:"source_path"`+ Kind string `json:"kind"`+ Workspace string `json:"workspace,omitempty"`+ CollectedLine int `json:"collected_line"`+ Collected bool `json:"collected"`+ SizeBytes int64 `json:"size_bytes"`+ UpdatedAt string `json:"updated_at,omitempty"`+}++type primeStatusReport struct {+ SessionsDir string `json:"sessions_dir"`+ ArtifactsDir string `json:"artifacts_dir"`+ Present bool `json:"present"`+ StatePath string `json:"state_path,omitempty"`+ Sessions []primeSessionStatus `json:"sessions"`+}++func runEndpointPrimeStatus(cmd *cobra.Command, args []string) error {+ store, err := primesession.NewStore(endpointPrimeOpts.sessionsDir, endpointPrimeOpts.artifactsDir)+ if err != nil {+ return err+ }+ statePath := resolvePrimeStatePath(endpointPrimeOpts.statePath, endpointUserMode())+ state, err := primesession.LoadState(statePath)+ if err != nil {+ return err+ }+ refs, err := store.List()+ if err != nil {+ return err+ }+ report := primeStatusReport{+ SessionsDir: store.SessionsDir,+ ArtifactsDir: store.ArtifactsDir,+ Present: store.Exists(),+ StatePath: statePath,+ Sessions: make([]primeSessionStatus, 0, len(refs)),+ }+ for _, ref := range refs {+ cursor := state.Files[primeStatusKey(ref.Path)]+ status := primeSessionStatus{+ SessionID: ref.ID,+ SourcePath: ref.Path,+ Kind: ref.Kind,+ Workspace: stringFromMap(ref.Header, "cwd"),+ SizeBytes: ref.SizeBytes,+ }+ if ref.ModTimeMS > 0 {+ status.UpdatedAt = time.UnixMilli(ref.ModTimeMS).UTC().Format(time.RFC3339)+ }+ if cursor != nil {+ status.CollectedLine = cursor.LastLine+ status.Collected = cursor.ModTimeMS == ref.ModTimeMS && cursor.SizeBytes == ref.SizeBytes+ }+ 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, "Prime Agent sessions: none (%s does not exist)\n", report.SessionsDir)+ return nil+ }+ fmt.Fprintf(out, "Prime Agent 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 %s\n",+ session.SessionID, state, session.CollectedLine, strings.TrimSpace(session.Workspace))+ }+ return nil+}++func resolvePrimeStatePath(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, "prime-state.json")+ }+ }+ return primesession.DefaultStatePath()+}++func primeStatusKey(path string) string {+ if abs, err := filepath.Abs(path); err == nil {+ return abs+ }+ return path+}++func stringFromMap(values map[string]interface{}, key string) string {+ if values == nil {+ return ""+ }+ value, _ := values[key].(string)+ return value+}diff --git a/cli/beacon/internal/primesession/collect.go b/cli/beacon/internal/primesession/collect.gonew file mode 100644index 00000000..bb3baf26--- /dev/null+++ b/cli/beacon/internal/primesession/collect.go@@ -0,0 +1,134 @@+package primesession++import (+ "encoding/json"+ "errors"+ "fmt"+ "io"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer"+)++type CollectOptions struct {+ SessionsDir string+ ArtifactsDir string+ StatePath string+ Write bool+ LogPath string+ UserMode bool+ Print bool+ Out io.Writer+}++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"`+}++func CollectOnce(opts CollectOptions) (summary Summary, err error) {+ store, err := NewStore(opts.SessionsDir, opts.ArtifactsDir)+ if err != nil {+ return summary, err+ }+ refs, err := store.List()+ if err != nil {+ return summary, err+ }+ 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 Prime Agent collector state: %w", saveErr)+ }+ }()++ var errs []error+ for _, ref := range refs {+ changed, collectErr := collectFile(store, ref, state, opts, &summary)+ if collectErr != nil {+ summary.Errors+++ errs = append(errs, fmt.Errorf("Prime Agent session %s: %w", ref.Path, collectErr))+ continue+ }+ if changed {+ summary.SessionsChanged+++ }+ }+ if len(errs) > 0 {+ return summary, errors.Join(errs...)+ }+ return summary, nil+}++func collectFile(store *Store, ref SessionRef, state *State, opts CollectOptions, summary *Summary) (bool, error) {+ cursor := state.cursor(ref.Path)+ if cursor.LastLine > 0 && cursor.ModTimeMS == ref.ModTimeMS && cursor.SizeBytes == ref.SizeBytes {+ return false, nil+ }+ entries, stats, err := store.Read(ref)+ summary.MalformedLines += stats.Malformed+ if err != nil {+ return false, err+ }+ parent := firstNonEmpty(stringValue(ref.Header["parentSession"]), cursor.SubagentOf)+ mapped := MapSession(ref, entries, MapOptions{+ MinLine: cursor.LastLine,+ SkipStarted: cursor.Started,+ SubagentOf: parent,+ })+ if len(mapped) == 0 {+ advance(cursor, ref, stats.MaxLine, parent)+ return false, nil+ }+ for i, item := range mapped {+ if err := emit(item.Event, opts); err != nil {+ if i > 0 {+ advance(cursor, ref, mapped[i-1].SourceLine, parent)+ }+ return true, err+ }+ summary.EventsEmitted+++ if item.Event.Event.Action == "session.started" {+ cursor.Started = true+ }+ }+ advance(cursor, ref, stats.MaxLine, parent)+ return true, nil+}++func advance(cursor *Cursor, ref SessionRef, line int, parent string) {+ if line > cursor.LastLine {+ cursor.LastLine = line+ }+ cursor.ModTimeMS = ref.ModTimeMS+ cursor.SizeBytes = ref.SizeBytes+ cursor.SubagentOf = parent+}++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/primesession/collect_test.go b/cli/beacon/internal/primesession/collect_test.gonew file mode 100644index 00000000..944e4597--- /dev/null+++ b/cli/beacon/internal/primesession/collect_test.go@@ -0,0 +1,64 @@+package primesession++import (+ "bytes"+ "os"+ "path/filepath"+ "strings"+ "testing"+)++func TestCollectOncePrintsAndAdvancesCursor(t *testing.T) {+ dir := t.TempDir()+ sessions := filepath.Join(dir, "sessions")+ if err := os.MkdirAll(sessions, 0o755); err != nil {+ t.Fatal(err)+ }+ sessionPath := filepath.Join(sessions, "session-1.jsonl")+ writePrimeJSONL(t, sessionPath, []string{+ `{"type":"session","id":"session-1","cwd":"/work/project"}`,+ `{"type":"message","message":{"role":"user","content":[{"text":"hello"}]}}`,+ })+ statePath := filepath.Join(dir, "state.json")+ var out bytes.Buffer+ summary, err := CollectOnce(CollectOptions{+ SessionsDir: sessions,+ StatePath: statePath,+ Print: true,+ Out: &out,+ })+ if err != nil {+ t.Fatal(err)+ }+ if summary.Sessions != 1 || summary.SessionsChanged != 1 || summary.EventsEmitted != 2 {+ t.Fatalf("summary = %#v", summary)+ }+ if got := out.String(); !strings.Contains(got, `"action":"session.started"`) || !strings.Contains(got, `"action":"prompt.submitted"`) {+ t.Fatalf("output did not include expected events:\n%s", got)+ }++ out.Reset()+ summary, err = CollectOnce(CollectOptions{+ SessionsDir: sessions,+ StatePath: statePath,+ Print: true,+ Out: &out,+ })+ if err != nil {+ t.Fatal(err)+ }+ if summary.EventsEmitted != 0 || summary.SessionsChanged != 0 {+ t.Fatalf("second summary = %#v", summary)+ }+ if out.Len() != 0 {+ t.Fatalf("second output = %q", out.String())+ }+}++func writePrimeJSONL(t *testing.T, path string, lines []string) {+ t.Helper()+ data := strings.Join(lines, "\n") + "\n"+ if err := os.WriteFile(path, []byte(data), 0o644); err != nil {+ t.Fatal(err)+ }+}diff --git a/cli/beacon/internal/primesession/mapper.go b/cli/beacon/internal/primesession/mapper.gonew file mode 100644index 00000000..8947217c--- /dev/null+++ b/cli/beacon/internal/primesession/mapper.go@@ -0,0 +1,505 @@+package primesession++import (+ "crypto/sha1"+ "encoding/hex"+ "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"+)++const Harness = "prime_agent"++type MappedEvent struct {+ SourceLine int+ Event schema.Event+}++type MapOptions struct {+ MinLine int+ SkipStarted bool+ SubagentOf string+}++func MapSession(ref SessionRef, entries []Entry, opts MapOptions) []MappedEvent {+ m := &mapper{+ ref: ref,+ opts: opts,+ model: stringValue(ref.Header["model"]),+ calls: map[string]toolCallState{},+ }+ m.sessionID = firstNonEmpty(stringValue(ref.Header["id"]), ref.ID)+ m.cwd = stringValue(ref.Header["cwd"])+ if git, ok := ref.Header["git"].(map[string]interface{}); ok {+ m.repository = stringValue(git["repoUrl"])+ m.branch = stringValue(git["branch"])+ }+ if !opts.SkipStarted {+ m.emitSessionStarted()+ }+ for i := range entries {+ m.consume(entries[i])+ }+ return m.out+}++type toolCallState struct {+ ID string+ Name string+ Args map[string]interface{}+ Timestamp time.Time+}++type mapper struct {+ ref SessionRef+ opts MapOptions+ out []MappedEvent++ sessionID string+ cwd string+ model string+ repository string+ branch string+ calls map[string]toolCallState+}++func (m *mapper) consume(entry Entry) {+ data := entry.Data+ typ := strings.ToLower(stringValue(data["type"]))+ timestamp := timestampValue(firstNonNil(data["timestamp"], refTimestamp(m.ref)))+ emit := entry.Line > m.opts.MinLine++ switch typ {+ case "session":+ if id := stringValue(data["id"]); id != "" {+ m.sessionID = id+ }+ if cwd := stringValue(data["cwd"]); cwd != "" {+ m.cwd = cwd+ }+ case "model_change":+ if model := stringValue(data["modelId"]); model != "" {+ m.model = model+ if emit {+ ev := m.base(timestamp, "session.context", "session", schema.SeverityInfo, "Prime Agent model changed")+ ev.Raw = m.raw(map[string]interface{}{"change": "model_change", "model_id": model})+ m.append(entry.Line, "model_change", ev)+ }+ }+ case "compaction":+ if emit {+ ev := m.base(timestamp, "session.compacting", "session", schema.SeverityInfo, "Prime Agent compacted session history")+ ev.Raw = m.raw(compactionRaw(data))+ m.append(entry.Line, "compaction", ev)+ }+ case "custom":+ if stringValue(data["customType"]) == "prime-agent.refinement" && emit {+ ev := m.base(timestamp, "session.context", "session", schema.SeverityInfo, "Prime Agent refinement state updated")+ ev.Raw = m.raw(map[string]interface{}{"custom_type": "prime-agent.refinement", "data": data["data"]})+ m.append(entry.Line, "refinement", ev)+ }+ case "custom_message":+ if emit {+ ev := m.base(timestamp, "agent.message", "session", schema.SeverityInfo, "Prime Agent custom message")+ ev.Raw = m.raw(map[string]interface{}{"custom_message": data})+ m.append(entry.Line, "custom_message", ev)+ }+ case "message":+ message, _ := data["message"].(map[string]interface{})+ if message == nil {+ return+ }+ m.consumeMessage(entry.Line, message, timestamp, emit)+ }+}++func (m *mapper) consumeMessage(line int, message map[string]interface{}, fallback time.Time, emit bool) {+ role := strings.ToLower(stringValue(message["role"]))+ timestamp := timestampValue(firstNonNil(message["timestamp"], fallback))+ switch role {+ case "user":+ for i, text := range texts(message["content"]) {+ if emit {+ m.emitPrompt(line, i, timestamp, text)+ }+ }+ case "assistant":+ if model := firstNonEmpty(stringValue(message["model"]), stringValue(message["modelId"])); model != "" {+ m.model = model+ }+ content, _ := message["content"].([]interface{})+ for i, part := range content {+ m.consumeAssistantPart(line, i, timestamp, part, emit)+ }+ case "toolresult", "tool_result", "tool":+ callID := firstNonEmpty(stringValue(message["toolCallId"]), stringValue(message["callId"]), fmt.Sprintf("line-%d", line))+ if emit {+ m.emitToolResult(line, timestamp, callID, message)+ }+ case "error":+ if emit {+ ev := m.base(timestamp, "agent.error", "session", schema.SeverityHigh, "Prime Agent error")+ text := firstNonEmpty(stringValue(message["errorMessage"]), strings.Join(texts(message["content"]), "\n"), "Unknown error")+ ev.Error = &schema.ErrorInfo{Type: "runtime_error"}+ ev.Content = asymptoteobserve.RetainedContent(text, asymptoteobserve.DefaultStringLimit)+ ev.Raw = m.raw(map[string]interface{}{"error_message": text})+ m.append(line, "error", ev)+ }+ }+}++func (m *mapper) consumeAssistantPart(line, index int, timestamp time.Time, part interface{}, emit bool) {+ item, _ := part.(map[string]interface{})+ if item == nil {+ return+ }+ kind := strings.ToLower(stringValue(item["type"]))+ switch kind {+ case "thinking":+ text := firstNonEmpty(stringValue(item["thinking"]), stringValue(item["text"]))+ if emit && text != "" {+ ev := m.base(timestamp, "agent.reasoning", "reasoning", schema.SeverityInfo, "Prime Agent reasoning")+ ev.GenAI = ensureGenAI(ev.GenAI)+ ev.GenAI.Output = &schema.GenAIOutputInfo{Messages: []interface{}{map[string]interface{}{+ "role": "assistant",+ "parts": []interface{}{map[string]interface{}{"type": "reasoning", "content": text}},+ }}}+ ev.Content = asymptoteobserve.RetainedContent(text, asymptoteobserve.DefaultStringLimit)+ m.append(line, fmt.Sprintf("assistant.%d.thinking", index), ev)+ }+ case "text":+ text := stringValue(item["text"])+ if emit && text != "" {+ ev := m.base(timestamp, "agent.message", "session", schema.SeverityInfo, "Prime Agent agent message")+ ev.GenAI = ensureGenAI(ev.GenAI)+ ev.GenAI.Output = &schema.GenAIOutputInfo{Messages: asymptoteobserve.TextOutputMessages(text)}+ ev.Content = asymptoteobserve.RetainedContent(text, asymptoteobserve.DefaultRawStringLimit)+ m.append(line, fmt.Sprintf("assistant.%d.text", index), ev)+ }+ case "toolcall", "tool_call":+ callID := firstNonEmpty(stringValue(item["id"]), fmt.Sprintf("line-%d-call-%d", line, index))+ name := firstNonEmpty(stringValue(item["name"]), "unknown")+ args, _ := item["arguments"].(map[string]interface{})+ if args == nil {+ args = map[string]interface{}{}+ }+ m.calls[callID] = toolCallState{ID: callID, Name: name, Args: args, Timestamp: timestamp}+ if emit {+ ev := m.base(timestamp, "tool.invoked", "tool", schema.SeverityInfo, "Prime Agent tool invoked")+ m.applyToolCall(&ev, m.calls[callID])+ m.append(line, fmt.Sprintf("assistant.%d.tool_call", index), ev)+ }+ }+}++func (m *mapper) emitSessionStarted() {+ ts := timestampValue(firstNonNil(m.ref.Header["timestamp"], refTimestamp(m.ref)))+ ev := m.base(ts, "session.started", "session", schema.SeverityInfo, "Prime Agent session started")+ raw := map[string]interface{}{"source_path": m.ref.Path, "source_kind": m.ref.Kind}+ if parent := stringValue(m.ref.Header["parentSession"]); parent != "" {+ raw["parent_session"] = parent+ }+ ev.Raw = m.raw(raw)+ m.append(0, "session.started", ev)+}++func (m *mapper) emitPrompt(line, index int, timestamp time.Time, text string) {+ ev := m.base(timestamp, "prompt.submitted", "prompt", schema.SeverityInfo, "Prime Agent prompt submitted")+ ev.Prompt = &schema.PromptInfo{Text: text}+ ev.Content = asymptoteobserve.RetainedContent(text, asymptoteobserve.DefaultStringLimit)+ ev.GenAI = ensureGenAI(ev.GenAI)+ ev.GenAI.Input = &schema.GenAIInputInfo{Messages: asymptoteobserve.TextInputMessages(text)}+ m.append(line, fmt.Sprintf("user.%d", index), ev)+}++func (m *mapper) emitToolResult(line int, timestamp time.Time, callID string, message map[string]interface{}) {+ state := m.calls[callID]+ if state.ID == "" {+ state = toolCallState{ID: callID, Name: firstNonEmpty(stringValue(message["toolName"]), "unknown")}+ }+ output := strings.Join(texts(message["content"]), "\n")+ failed := boolValue(message["isError"]) || strings.EqualFold(stringValue(childMap(message["details"])["status"]), "error")+ action, category, severity := "tool.completed", "tool", schema.SeverityInfo+ if failed {+ action, severity = "tool.failed", schema.SeverityHigh+ }+ if isCommandTool(state.Name, state.Args) && !failed {+ action, category = "command.executed", "command"+ }+ ev := m.base(timestamp, action, category, severity, "Prime Agent tool result")+ if failed {+ ev.Error = &schema.ErrorInfo{Type: "tool_error"}+ }+ m.applyToolCall(&ev, state)+ if category == "command" {+ ev.Command = &schema.CommandInfo{Command: commandFor(state.Name, state.Args), Output: output}+ }+ if output != "" {+ if ev.Command != nil {+ ev.Command.Output = output+ }+ if ev.Content == nil {+ ev.Content = asymptoteobserve.RetainedContent(output, asymptoteobserve.DefaultStringLimit)+ }+ }+ raw := map[string]interface{}{"tool_result": message}+ if strings.EqualFold(state.Name, "ipython") {+ raw["python"] = true+ }+ ev.Raw = m.raw(raw)+ m.append(line, "tool_result", ev)++ for i, attachment := range attachments(message) {+ fileEvent := m.base(timestamp, "file.read", "file", schema.SeverityInfo, "Prime Agent context attachment")+ fileEvent.File = &schema.FileInfo{Path: attachment.path, Operation: "read", Language: strings.TrimPrefix(filepath.Ext(attachment.path), ".")}+ fileEvent.Raw = m.raw(map[string]interface{}{"attachment_mime_type": attachment.mimeType, "tool_call_id": callID})+ m.append(line, fmt.Sprintf("attachment.%d", i), fileEvent)+ }+}++func (m *mapper) applyToolCall(ev *schema.Event, call toolCallState) {+ ev.Tool = &schema.ToolInfo{Name: call.Name}+ if command := commandFor(call.Name, call.Args); command != "" {+ ev.Tool.Command = command+ ev.Command = &schema.CommandInfo{Command: command}+ ev.Content = asymptoteobserve.RetainedContent(command, asymptoteobserve.DefaultStringLimit)+ }+ if path := stringArg(call.Args, "path", "file_path", "target_path"); path != "" {+ ev.Tool.Path = path+ ev.File = &schema.FileInfo{Path: path, Language: strings.TrimPrefix(filepath.Ext(path), ".")}+ }+ ev.GenAI = ensureGenAI(ev.GenAI)+ ev.GenAI.Operation = &schema.GenAIOperationInfo{Name: "execute_tool"}+ ev.GenAI.Tool = &schema.GenAIToolInfo{Name: call.Name, Call: &schema.GenAIToolCallInfo{ID: call.ID, Arguments: call.Args}}+ if strings.EqualFold(call.Name, "ipython") {+ ev.Raw = m.raw(map[string]interface{}{"python": true})+ }+}++func (m *mapper) base(timestamp time.Time, action, category string, severity schema.Severity, message string) schema.Event {+ ev := schema.NewEvent(schema.NewEventOptions{+ Action: action,+ Category: category,+ Severity: severity,+ Fidelity: schema.FidelityObserved,+ Message: message,+ Origin: schema.OriginLocal,+ Harness: schema.HarnessInfo{+ Name: Harness,+ CollectionMethod: schema.CollectionMethodPoll,+ },+ })+ ev.Timestamp = schema.FormatTimestamp(timestamp)+ ev.Session = &schema.SessionInfo{ID: m.sessionID, WorkingDirectory: m.cwd}+ if m.model != "" {+ ev.Model = asymptoteobserve.NormalizeModelName(m.model)+ }+ if m.repository != "" {+ ev.Repository = m.repository+ }+ if m.branch != "" {+ ev.Branch = m.branch+ }+ return ev+}++func (m *mapper) raw(fields map[string]interface{}) map[string]interface{} {+ if fields == nil {+ fields = map[string]interface{}{}+ }+ if m.ref.Path != "" {+ fields["source_path"] = m.ref.Path+ }+ if m.opts.SubagentOf != "" {+ fields["parent_session"] = m.opts.SubagentOf+ }+ return map[string]interface{}{"prime": fields}+}++func (m *mapper) append(line int, suffix string, ev schema.Event) {+ ev.Event.ID = primeEventID(fmt.Sprintf("%s:%s:%d:%s", m.sessionID, m.ref.Path, line, suffix))+ m.out = append(m.out, MappedEvent{SourceLine: line, Event: ev})+}++func isCommandTool(name string, args map[string]interface{}) bool {+ return strings.EqualFold(name, "ipython") || strings.EqualFold(name, "bash") || commandFor(name, args) != ""+}++func commandFor(name string, args map[string]interface{}) string {+ if strings.EqualFold(name, "ipython") {+ return stringArg(args, "code")+ }+ if strings.EqualFold(name, "bash") {+ return stringArg(args, "command")+ }+ return stringArg(args, "command", "cmd")+}++func ensureGenAI(genAI *schema.GenAIInfo) *schema.GenAIInfo {+ if genAI == nil {+ return &schema.GenAIInfo{}+ }+ return genAI+}++func compactionRaw(data map[string]interface{}) map[string]interface{} {+ out := map[string]interface{}{"source_event_type": "compaction"}+ for _, key := range []string{"summary", "firstKeptEntryId", "tokensBefore", "details", "fromHook"} {+ if value, ok := data[key]; ok {+ out[key] = value+ }+ }+ return out+}++type attachment struct {+ path string+ mimeType string+}++func attachments(message map[string]interface{}) []attachment {+ details := childMap(message["details"])+ raw, _ := details["attachments"].([]interface{})+ var out []attachment+ for _, item := range raw {+ m, _ := item.(map[string]interface{})+ path := stringValue(m["path"])+ if path == "" {+ continue+ }+ out = append(out, attachment{path: path, mimeType: stringValue(m["mimeType"])})+ }+ return out+}++func childMap(value interface{}) map[string]interface{} {+ m, _ := value.(map[string]interface{})+ if m == nil {+ return map[string]interface{}{}+ }+ return m+}++func texts(value interface{}) []string {+ switch v := value.(type) {+ case string:+ if strings.TrimSpace(v) == "" {+ return nil+ }+ return []string{v}+ case []interface{}:+ var out []string+ for _, item := range v {+ if s, ok := item.(string); ok {+ if strings.TrimSpace(s) != "" {+ out = append(out, s)+ }+ continue+ }+ m, _ := item.(map[string]interface{})+ if text := stringValue(m["text"]); text != "" {+ out = append(out, text)+ }+ }+ return out+ default:+ return nil+ }+}++func stringArg(args map[string]interface{}, keys ...string) string {+ for _, key := range keys {+ if value := stringValue(args[key]); value != "" {+ return value+ }+ }+ return ""+}++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 stringValue(value interface{}) string {+ if value == nil {+ return ""+ }+ if text, ok := value.(string); ok {+ return strings.TrimSpace(text)+ }+ return ""+}++func boolValue(value interface{}) bool {+ v, _ := value.(bool)+ return v+}++func timestampValue(value interface{}) time.Time {+ switch v := value.(type) {+ case time.Time:+ return v+ case float64:+ if v > 1_000_000_000_000 {+ return time.UnixMilli(int64(v)).UTC()+ }+ return time.Unix(int64(v), 0).UTC()+ case int64:+ if v > 1_000_000_000_000 {+ return time.UnixMilli(v).UTC()+ }+ return time.Unix(v, 0).UTC()+ case string:+ if t, err := time.Parse(time.RFC3339Nano, v); err == nil {+ return t.UTC()+ }+ if t, err := schema.ParseTimestamp(v); err == nil {+ return t.UTC()+ }+ }+ return time.Now().UTC()+}++func refTimestamp(ref SessionRef) time.Time {+ if ref.ModTimeMS > 0 {+ return time.UnixMilli(ref.ModTimeMS).UTC()+ }+ return time.Now().UTC()+}++var primeIDNamespace = [16]byte{+ 0x8f, 0x89, 0x37, 0x12, 0xbb, 0x46, 0x46, 0xce,+ 0xb5, 0xe2, 0x17, 0x96, 0xed, 0x3c, 0xab, 0x11,+}++func primeEventID(coordinate string) string {+ digest := sha1.New()+ digest.Write(primeIDNamespace[:])+ io.WriteString(digest, coordinate)+ 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/primesession/mapper_test.go b/cli/beacon/internal/primesession/mapper_test.gonew file mode 100644index 00000000..e58e0cd2--- /dev/null+++ b/cli/beacon/internal/primesession/mapper_test.go@@ -0,0 +1,109 @@+package primesession++import "testing"++func TestMapSessionPrimeTranscript(t *testing.T) {+ ref := SessionRef{+ ID: "session-1",+ Path: "/tmp/session-1.jsonl",+ Kind: "session",+ Header: map[string]interface{}{+ "type": "session",+ "id": "session-1",+ "cwd": "/work/project",+ "git": map[string]interface{}{+ "repoUrl": "https://example.test/repo.git",+ "branch": "main",+ },+ },+ }+ entries := []Entry{+ {Line: 1, Data: ref.Header},+ {Line: 2, Data: map[string]interface{}{"type": "message", "timestamp": "2026-09-19T01:00:00Z", "message": map[string]interface{}{+ "role": "user", "content": []interface{}{map[string]interface{}{"text": "inspect the repo"}},+ }}},+ {Line: 3, Data: map[string]interface{}{"type": "message", "timestamp": "2026-09-19T01:00:01Z", "message": map[string]interface{}{+ "role": "assistant",+ "content": []interface{}{+ map[string]interface{}{"type": "thinking", "thinking": "Need to inspect files"},+ map[string]interface{}{"type": "text", "text": "I will look."},+ map[string]interface{}{"type": "tool_call", "id": "call-1", "name": "ipython", "arguments": map[string]interface{}{"code": "bash('ls')"}},+ },+ }}},+ {Line: 4, Data: map[string]interface{}{"type": "message", "timestamp": "2026-09-19T01:00:02Z", "message": map[string]interface{}{+ "role": "tool_result", "toolCallId": "call-1", "toolName": "ipython", "content": []interface{}{map[string]interface{}{"text": "README.md"}},+ "details": map[string]interface{}{"attachments": []interface{}{map[string]interface{}{"path": "/work/project/README.md", "mimeType": "text/markdown"}}},+ }}},+ {Line: 5, Data: map[string]interface{}{"type": "compaction", "timestamp": "2026-09-19T01:00:03Z", "summary": "kept recent work"}},+ {Line: 6, Data: map[string]interface{}{"type": "custom", "customType": "prime-agent.refinement", "timestamp": "2026-09-19T01:00:04Z", "data": map[string]interface{}{"summary": "state updated"}}},+ }++ mapped := MapSession(ref, entries, MapOptions{})+ actions := actionsOf(mapped)+ want := []string{+ "session.started",+ "prompt.submitted",+ "agent.reasoning",+ "agent.message",+ "tool.invoked",+ "command.executed",+ "file.read",+ "session.compacting",+ "session.context",+ }+ if len(actions) != len(want) {+ t.Fatalf("actions length = %d, want %d: %#v", len(actions), len(want), actions)+ }+ for i := range want {+ if actions[i] != want[i] {+ t.Fatalf("actions[%d] = %q, want %q; all=%#v", i, actions[i], want[i], actions)+ }+ }+ command := mapped[5].Event.Command+ if command == nil || command.Command != "bash('ls')" || command.Output != "README.md" {+ t.Fatalf("command event = %#v", command)+ }+ if mapped[0].Event.Harness.Name != Harness || mapped[0].Event.Harness.CollectionMethod != "poll" {+ t.Fatalf("harness = %#v", mapped[0].Event.Harness)+ }+ if mapped[0].Event.Repository != "https://example.test/repo.git" || mapped[0].Event.Branch != "main" {+ t.Fatalf("repo fields = %q %q", mapped[0].Event.Repository, mapped[0].Event.Branch)+ }+ for _, item := range mapped {+ if item.Event.Event.ID == "" {+ t.Fatalf("event %s missing deterministic id", item.Event.Event.Action)+ }+ }+}++func TestMapSessionUsesPriorToolCallStateForNewResult(t *testing.T) {+ ref := SessionRef{ID: "session-1", Path: "/tmp/session-1.jsonl", Header: map[string]interface{}{"type": "session", "id": "session-1"}}+ entries := []Entry{+ {Line: 1, Data: ref.Header},+ {Line: 2, Data: map[string]interface{}{"type": "message", "message": map[string]interface{}{+ "role": "assistant",+ "content": []interface{}{map[string]interface{}{"type": "tool_call", "id": "call-1", "name": "ipython", "arguments": map[string]interface{}{"code": "print('hi')"}}},+ }}},+ {Line: 3, Data: map[string]interface{}{"type": "message", "message": map[string]interface{}{+ "role": "tool_result", "toolCallId": "call-1", "content": []interface{}{map[string]interface{}{"text": "hi"}},+ }}},+ }+ mapped := MapSession(ref, entries, MapOptions{MinLine: 2, SkipStarted: true})+ if len(mapped) != 1 {+ t.Fatalf("mapped %d events, want 1: %#v", len(mapped), actionsOf(mapped))+ }+ if mapped[0].Event.Event.Action != "command.executed" {+ t.Fatalf("action = %q", mapped[0].Event.Event.Action)+ }+ if mapped[0].Event.Command == nil || mapped[0].Event.Command.Command != "print('hi')" {+ t.Fatalf("command = %#v", mapped[0].Event.Command)+ }+}++func actionsOf(items []MappedEvent) []string {+ out := make([]string, 0, len(items))+ for _, item := range items {+ out = append(out, item.Event.Event.Action)+ }+ return out+}diff --git a/cli/beacon/internal/primesession/state.go b/cli/beacon/internal/primesession/state.gonew file mode 100644index 00000000..9c1ba2a9--- /dev/null+++ b/cli/beacon/internal/primesession/state.go@@ -0,0 +1,95 @@+package primesession++import (+ "encoding/json"+ "errors"+ "fmt"+ "os"+ "path/filepath"+ "strings"+)++const StateVersion = 1++type Cursor struct {+ LastLine int `json:"last_line"`+ Started bool `json:"started"`+ ModTimeMS int64 `json:"mod_time_ms,omitempty"`+ SizeBytes int64 `json:"size_bytes,omitempty"`+ SubagentOf string `json:"subagent_of,omitempty"`+}++type State struct {+ Version int `json:"version"`+ Files map[string]*Cursor `json:"files"`+}++func LoadState(path string) (*State, error) {+ state := &State{Version: StateVersion, Files: 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 Prime Agent collector state %s: %w", path, err)+ }+ if stored.Version != StateVersion || stored.Files == nil {+ return state, nil+ }+ state.Files = stored.Files+ 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(path string) *Cursor {+ if s.Files == nil {+ s.Files = map[string]*Cursor{}+ }+ key := stateKey(path)+ cursor := s.Files[key]+ if cursor == nil {+ cursor = &Cursor{}+ s.Files[key] = cursor+ }+ return cursor+}++func stateKey(path string) string {+ if abs, err := filepath.Abs(path); err == nil {+ return abs+ }+ return path+}++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", "prime.json")+}diff --git a/cli/beacon/internal/primesession/store.go b/cli/beacon/internal/primesession/store.gonew file mode 100644index 00000000..a696b203--- /dev/null+++ b/cli/beacon/internal/primesession/store.go@@ -0,0 +1,230 @@+package primesession++import (+ "bufio"+ "encoding/json"+ "errors"+ "fmt"+ "io/fs"+ "os"+ "path/filepath"+ "sort"+ "strings"+)++const (+ maxSessionFiles = 15000+ maxLineBytes = 10 * 1024 * 1024++ primeAgentDirEnv = "PRIME_AGENT_CODING_AGENT_DIR"+)++// Store reads Prime Agent's durable session store.+type Store struct {+ SessionsDir string+ ArtifactsDir string+}++// SessionRef is one Prime Agent JSONL transcript.+type SessionRef struct {+ ID string+ Path string+ Kind string+ ModTimeMS int64+ SizeBytes int64+ Header map[string]interface{}+}++// Entry is one decoded line from a Prime Agent transcript.+type Entry struct {+ Line int+ Data map[string]interface{}+}++type ReadStats struct {+ Malformed int+ MaxLine int+}++func NewStore(sessionsDir, artifactsDir string) (*Store, error) {+ if strings.TrimSpace(sessionsDir) == "" {+ def, err := DefaultSessionsDir()+ if err != nil {+ return nil, err+ }+ sessionsDir = def+ }+ if strings.TrimSpace(artifactsDir) == "" {+ def, err := DefaultArtifactsDir()+ if err != nil {+ return nil, err+ }+ artifactsDir = def+ }+ return &Store{SessionsDir: sessionsDir, ArtifactsDir: artifactsDir}, nil+}++func DefaultSessionsDir() (string, error) {+ agentDir, err := defaultAgentDir()+ if err != nil {+ return "", err+ }+ return filepath.Join(agentDir, "sessions"), nil+}++func DefaultArtifactsDir() (string, error) {+ agentDir, err := defaultAgentDir()+ if err != nil {+ return "", err+ }+ return filepath.Join(agentDir, "session-artifacts"), nil+}++func defaultAgentDir() (string, error) {+ home, err := os.UserHomeDir()+ if err != nil {+ return "", fmt.Errorf("resolve home directory: %w", err)+ }+ if override := strings.TrimSpace(os.Getenv(primeAgentDirEnv)); override != "" {+ return expandTilde(override, home), nil+ }+ if strings.TrimSpace(home) == "" {+ return "", errors.New("home directory is empty")+ }+ return filepath.Join(home, ".prime", "agent"), nil+}++func expandTilde(path, home string) string {+ if path == "~" {+ return home+ }+ if strings.HasPrefix(path, "~/") || strings.HasPrefix(path, `~\`) {+ return filepath.Join(home, filepath.FromSlash(path[2:]))+ }+ return path+}++func (s *Store) Exists() bool {+ return dirExists(s.SessionsDir) || dirExists(s.ArtifactsDir)+}++func dirExists(path string) bool {+ info, err := os.Stat(path)+ return err == nil && info.IsDir()+}++func (s *Store) List() ([]SessionRef, error) {+ var refs []SessionRef+ for _, root := range []struct {+ path string+ kind string+ }{+ {s.SessionsDir, "session"},+ {s.ArtifactsDir, "artifact"},+ } {+ items, err := listJSONL(root.path)+ if err != nil {+ return nil, err+ }+ for _, path := range items {+ info, err := os.Stat(path)+ if err != nil || info.IsDir() {+ continue+ }+ header := readHeader(path)+ id := stringValue(header["id"])+ if id == "" {+ id = strings.TrimSuffix(filepath.Base(path), filepath.Ext(path))+ }+ refs = append(refs, SessionRef{+ ID: id,+ Path: path,+ Kind: root.kind,+ ModTimeMS: info.ModTime().UnixMilli(),+ SizeBytes: info.Size(),+ Header: header,+ })+ }+ }+ sort.SliceStable(refs, func(i, j int) bool {+ if refs[i].ModTimeMS != refs[j].ModTimeMS {+ return refs[i].ModTimeMS < refs[j].ModTimeMS+ }+ return refs[i].Path < refs[j].Path+ })+ return refs, nil+}++func listJSONL(root string) ([]string, error) {+ if !dirExists(root) {+ return nil, nil+ }+ var out []string+ err := filepath.WalkDir(root, func(path string, entry fs.DirEntry, err error) error {+ if err != nil {+ return nil+ }+ if len(out) >= maxSessionFiles {+ return filepath.SkipAll+ }+ if entry.IsDir() {+ return nil+ }+ if entry.Type().IsRegular() && strings.EqualFold(filepath.Ext(entry.Name()), ".jsonl") {+ out = append(out, path)+ }+ return nil+ })+ return out, err+}++func readHeader(path string) map[string]interface{} {+ file, err := os.Open(path)+ if err != nil {+ return nil+ }+ defer file.Close()+ scanner := bufio.NewScanner(file)+ scanner.Buffer(make([]byte, 0, 64*1024), maxLineBytes)+ for scanner.Scan() {+ line := strings.TrimSpace(scanner.Text())+ if line == "" {+ continue+ }+ var item map[string]interface{}+ if json.Unmarshal([]byte(line), &item) == nil && strings.EqualFold(stringValue(item["type"]), "session") {+ return item+ }+ return nil+ }+ return nil+}++func (s *Store) Read(ref SessionRef) ([]Entry, ReadStats, error) {+ file, err := os.Open(ref.Path)+ if err != nil {+ return nil, ReadStats{}, err+ }+ defer file.Close()+ scanner := bufio.NewScanner(file)+ scanner.Buffer(make([]byte, 0, 64*1024), maxLineBytes)+ var entries []Entry+ stats := ReadStats{}+ for scanner.Scan() {+ stats.MaxLine+++ line := strings.TrimSpace(scanner.Text())+ if line == "" {+ continue+ }+ var item map[string]interface{}+ if err := json.Unmarshal([]byte(line), &item); err != nil {+ stats.Malformed+++ continue+ }+ entries = append(entries, Entry{Line: stats.MaxLine, Data: item})+ }+ if err := scanner.Err(); err != nil {+ return entries, stats, err+ }+ return entries, stats, nil+}diff --git a/docs/runtimes/prime-agent.mdx b/docs/runtimes/prime-agent.mdxindex cd2af866..6616cefd 100644--- a/docs/runtimes/prime-agent.mdx+++ b/docs/runtimes/prime-agent.mdx@@ -11,7 +11,15 @@ Asymptote supports [Prime Agent](https://github.com/PrimeIntellect-ai/prime-agenPrime Agent is a hard fork of [pi-mono](https://github.com/badlogic/pi-mono), as [Oh My Pi](/runtimes/oh-my-pi) and [Senpi](/runtimes/senpi) are. All four are supported separately and recorded under their own harness names, because they are separately installed products that one machine can run side by side.</Note>-Prime Agent fits neither of Asymptote's two usual integration shapes. It has no hooks configuration file to merge a managed hook block into, and no OpenTelemetry export to point at the local collector. Its documented observation surface is the TypeScript extension API it inherited from Pi, so the integration is extension-shaped: one Asymptote-owned extension file forwards runtime events to `beacon-hooks`, the same shape as the [Pi](/runtimes/pi), [Oh My Pi](/runtimes/oh-my-pi), [OpenCode](/cli/supported-runtimes-opencode) and [Cline](/cli/supported-runtimes-cline) integrations.+Prime Agent fits neither of Asymptote's two usual live integration shapes. It has no hooks configuration file to merge a managed hook block into, and no OpenTelemetry export to point at the local collector. Its documented observation surface is the TypeScript extension API it inherited from Pi, so the live integration is extension-shaped: one Asymptote-owned extension file forwards runtime events to `beacon-hooks`, the same shape as the [Pi](/runtimes/pi), [Oh My Pi](/runtimes/oh-my-pi), [OpenCode](/cli/supported-runtimes-opencode) and [Cline](/cli/supported-runtimes-cline) integrations.++Asymptote can also read Prime Agent's committed JSONL session store after the fact:++```bash+beacon endpoint prime sync+```++That poll path is local and offline, checkpointed by file and line number, and marks every event `harness.collection_method=poll`. It complements the extension rather than replacing it: the extension sees live tool details as Prime runs, while the poll path can backfill sessions that happened before the extension was installed or sessions where the extension was not loaded.```bashbeacon endpoint hooks install --harness prime@@ -52,7 +60,7 @@ The project path keeps the `agent` segment. Prime Agent's config directory nameAsymptote identifies its own extension file by the marker `beacon-managed-prime-extension:v1`. The version suffix is part of the contract with the extension source: it is what lets a repair recognize a stale file instead of leaving it in place. A `beacon.ts` without the marker belongs to somebody else, so install will not overwrite it and discovery does not report it as Asymptote telemetry. The marker is distinct from Pi's and Oh My Pi's, so a file found at any of the three paths is attributed to the runtime that actually loads it.-Prime Agent has no OpenTelemetry export for Asymptote to configure, so there is no OTLP path for this runtime.+Prime Agent has no OpenTelemetry export for Asymptote to configure, so there is no OTLP path for this runtime. The poll path reads JSONL transcripts from `~/.prime/agent/sessions` and subagent artifacts from `~/.prime/agent/session-artifacts`; if `PRIME_AGENT_CODING_AGENT_DIR` is set, Asymptote reads `sessions` and `session-artifacts` below that directory, matching the runtime's user-level agent directory override. The cursor lives in Asymptote state, not in Prime Agent's directory.## Discovery and status@@ -98,6 +106,7 @@ Install writes one file and refuses to touch a `beacon.ts` it did not write, so| Runtime discovery | Supported through executable and `~/.prime/agent` detection, managed extension path, and telemetry status || Harness attribution | Supported. `prime`, `prime_agent`, `prime-agent`, `primeagent`, `prime_cli`, `prime-cli`, `prime_intellect`, and `prime-intellect` all normalize to `prime_agent` || Extension install, status, uninstall, and repair | Supported |+| Session-store sync | Supported through `beacon endpoint prime sync`, with `--print`, `--watch`, `--sessions-dir`, and `--artifacts-dir` || Session lifecycle | Supported. `session.started` and `session.ended`, carrying why the session started or stopped — a fork and a resume both produce a session with history behind it || Prompts | Supported. `prompt.submitted`, with whether the input was typed, delivered over RPC, or injected by another extension || Tool use | Supported. `tool.invoked` before execution, then `tool.completed` or `tool.failed` |@@ -125,6 +134,7 @@ The extension itself sends nothing over the network. It spawns the local `beacon- **No per-cell exit code.** A Python cell does not have one. The runtime reports a `status` of `ok`, `error`, or `aborted`, which Beacon records verbatim; deriving a `0`/`1` from it would put a shell's vocabulary on something that is not a shell. An interrupted cell is recorded as aborted rather than failed, so a Ctrl+C does not read as an agent error.- **No enforcement.** As with every other runtime, enforcement stays behind the optional, off-by-default policy provider seam (`BEACON_POLICY_PROVIDER`), which is not wired to Prime Agent. Its blocking `tool_call` handler makes it a viable target for that seam later.- **Streaming events are not collected.** The extension subscribes to seven of Prime Agent's event types and ignores the rest — provider request and response internals, streaming message updates, compaction, refinement and tree-navigation signals, and TUI plumbing. Assistant output is recorded once when a message finalizes rather than token by token, so Beacon stays out of the streaming path.+- **Poll sync is after-the-fact.** `beacon endpoint prime sync` can recover committed prompts, assistant messages and reasoning, tool calls and results, context attachments, errors, compactions, refinement state updates, and subagent artifact files from Prime Agent's JSONL store. It cannot block or delay anything, and it does not have every live extension context field. Use it as backfill or scheduled catch-up, not as an enforcement surface.- **`.agents` and other hosts.** Prime Agent's extension directory is its own (`.prime/agent/extensions`), not a shared one, so unlike [goose](/runtimes/goose) there is no ambiguity about which runtime ran the extension.## Deployment notes