Skip to content

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

add pi sync support

Justin D'Souza8b3432f2807e
diff --git a/cli/beacon/cmd/endpoint_pi.go b/cli/beacon/cmd/endpoint_pi.go
new file mode 100644
index 00000000..85e289e1
--- /dev/null
+++ b/cli/beacon/cmd/endpoint_pi.go
@@ -0,0 +1,225 @@
+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/pisession"
+ "github.com/spf13/cobra"
+)
+
+var endpointPiCmd = &cobra.Command{
+ Use: "pi",
+ Short: "Collect telemetry from Pi session files",
+ Long: `Collect endpoint telemetry from Pi's local session store.
+
+Pi has a live Beacon extension for plugin-time telemetry. This command is the
+complementary poll path: it reads committed JSONL transcripts under
+~/.pi/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 Pi wrote after the fact rather than observing the agent
+as it works.`,
+}
+
+var endpointPiSyncCmd = &cobra.Command{
+ Use: "sync",
+ Short: "Read new Pi session records into the runtime log",
+ SilenceUsage: true,
+ RunE: runEndpointPiSync,
+}
+
+var endpointPiStatusCmd = &cobra.Command{
+ Use: "status",
+ Short: "Show Pi sessions and how much Beacon has collected",
+ SilenceUsage: true,
+ RunE: runEndpointPiStatus,
+}
+
+var endpointPiOpts struct {
+ sessionsDir string
+ statePath string
+ logPath string
+ print bool
+ watch bool
+ interval time.Duration
+}
+
+func init() {
+ endpointCmd.AddCommand(endpointPiCmd)
+ endpointPiCmd.AddCommand(endpointPiSyncCmd)
+ endpointPiCmd.AddCommand(endpointPiStatusCmd)
+
+ for _, c := range []*cobra.Command{endpointPiSyncCmd, endpointPiStatusCmd} {
+ f := c.Flags()
+ f.StringVar(&endpointPiOpts.sessionsDir, "sessions-dir", "", "Pi sessions directory (default ~/.pi/agent/sessions)")
+ f.StringVar(&endpointPiOpts.statePath, "state", "", "Collector cursor file (default ~/.beacon/endpoint/state/pi.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 := endpointPiSyncCmd.Flags()
+ sync.StringVar(&endpointPiOpts.logPath, "log-path", "", "Runtime JSONL log path (default resolved endpoint log)")
+ sync.BoolVar(&endpointPiOpts.print, "print", false, "Print mapped events as JSON without writing them or advancing the cursor (dry run)")
+ sync.BoolVar(&endpointPiOpts.watch, "watch", false, "Sweep continuously on --interval (default: one sweep then exit)")
+ sync.DurationVar(&endpointPiOpts.interval, "interval", time.Minute, "Sweep interval for --watch")
+}
+
+func runEndpointPiSync(cmd *cobra.Command, args []string) error {
+ userMode := endpointUserMode()
+ opts := pisession.CollectOptions{
+ SessionsDir: endpointPiOpts.sessionsDir,
+ Print: endpointPiOpts.print,
+ Out: cmd.OutOrStdout(),
+ Write: !endpointPiOpts.print,
+ UserMode: userMode,
+ }
+ if !endpointPiOpts.print {
+ opts.StatePath = resolvePiStatePath(endpointPiOpts.statePath, userMode)
+ opts.LogPath = lifecycle.ResolveRuntimeLog(userMode, endpointPiOpts.logPath).EffectiveLogPath
+ }
+
+ ctx := cmd.Context()
+ if ctx == nil {
+ ctx = context.Background()
+ }
+ if endpointPiOpts.watch && !endpointPiOpts.print {
+ return watchPi(ctx, cmd, opts)
+ }
+ summary, err := pisession.CollectOnce(opts)
+ reportPiSweep(cmd, summary)
+ return err
+}
+
+func watchPi(ctx context.Context, cmd *cobra.Command, opts pisession.CollectOptions) error {
+ interval := endpointPiOpts.interval
+ if interval < 5*time.Second {
+ interval = 5 * time.Second
+ }
+ for {
+ summary, err := pisession.CollectOnce(opts)
+ if err != nil {
+ fmt.Fprintf(cmd.ErrOrStderr(), "Pi sync error: %v\n", err)
+ }
+ reportPiSweep(cmd, summary)
+ select {
+ case <-ctx.Done():
+ return nil
+ case <-time.After(interval):
+ }
+ }
+}
+
+func reportPiSweep(cmd *cobra.Command, summary pisession.Summary) {
+ if endpointPiOpts.print {
+ return
+ }
+ if endpointOpts.jsonOutput {
+ _ = json.NewEncoder(cmd.OutOrStdout()).Encode(summary)
+ return
+ }
+ fmt.Fprintf(cmd.OutOrStdout(), "Pi 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 Pi session logs\n", summary.MalformedLines)
+ }
+}
+
+type piSessionStatus struct {
+ SessionID string `json:"session_id"`
+ SourcePath string `json:"source_path"`
+ 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 piStatusReport struct {
+ SessionsDir string `json:"sessions_dir"`
+ Present bool `json:"present"`
+ StatePath string `json:"state_path,omitempty"`
+ Sessions []piSessionStatus `json:"sessions"`
+}
+
+func runEndpointPiStatus(cmd *cobra.Command, args []string) error {
+ store, err := pisession.NewStore(endpointPiOpts.sessionsDir)
+ if err != nil {
+ return err
+ }
+ statePath := resolvePiStatePath(endpointPiOpts.statePath, endpointUserMode())
+ state, err := pisession.LoadState(statePath)
+ if err != nil {
+ return err
+ }
+ refs, err := store.List()
+ if err != nil {
+ return err
+ }
+ report := piStatusReport{
+ SessionsDir: store.SessionsDir,
+ Present: store.Exists(),
+ StatePath: statePath,
+ Sessions: make([]piSessionStatus, 0, len(refs)),
+ }
+ for _, ref := range refs {
+ cursor := state.Files[piStatusKey(ref.Path)]
+ status := piSessionStatus{
+ SessionID: ref.ID,
+ SourcePath: ref.Path,
+ 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, "Pi sessions: none (%s does not exist)\n", report.SessionsDir)
+ return nil
+ }
+ fmt.Fprintf(out, "Pi 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 resolvePiStatePath(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, "pi-state.json")
+ }
+ }
+ return pisession.DefaultStatePath()
+}
+
+func piStatusKey(path string) string {
+ if abs, err := filepath.Abs(path); err == nil {
+ return abs
+ }
+ return path
+}
diff --git a/cli/beacon/internal/pisession/collect.go b/cli/beacon/internal/pisession/collect.go
new file mode 100644
index 00000000..5e398006
--- /dev/null
+++ b/cli/beacon/internal/pisession/collect.go
@@ -0,0 +1,130 @@
+package pisession
+
+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
+ 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)
+ 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 Pi 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("Pi 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
+ }
+ mapped := MapSession(ref, entries, MapOptions{
+ MinLine: cursor.LastLine,
+ SkipStarted: cursor.Started,
+ })
+ if len(mapped) == 0 {
+ advance(cursor, ref, stats.MaxLine)
+ 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)
+ }
+ return true, err
+ }
+ summary.EventsEmitted++
+ if item.Event.Event.Action == "session.started" {
+ cursor.Started = true
+ }
+ }
+ advance(cursor, ref, stats.MaxLine)
+ return true, nil
+}
+
+func advance(cursor *Cursor, ref SessionRef, line int) {
+ if line > cursor.LastLine {
+ cursor.LastLine = line
+ }
+ cursor.ModTimeMS = ref.ModTimeMS
+ cursor.SizeBytes = ref.SizeBytes
+}
+
+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/pisession/collect_test.go b/cli/beacon/internal/pisession/collect_test.go
new file mode 100644
index 00000000..fccf7af4
--- /dev/null
+++ b/cli/beacon/internal/pisession/collect_test.go
@@ -0,0 +1,64 @@
+package pisession
+
+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")
+ writePiJSONL(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 writePiJSONL(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/pisession/mapper.go b/cli/beacon/internal/pisession/mapper.go
new file mode 100644
index 00000000..819166ca
--- /dev/null
+++ b/cli/beacon/internal/pisession/mapper.go
@@ -0,0 +1,798 @@
+package pisession
+
+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"
+)
+
+const Harness = "pi_cli"
+
+var toolCallKinds = map[string]bool{
+ "tool_call": true,
+ "tool_use": true,
+ "function_call": true,
+ "toolcall": true,
+}
+
+var toolResultKinds = map[string]bool{
+ "tool_result": true,
+ "tool_output": true,
+ "function_call_output": true,
+ "toolresult": true,
+}
+
+type MappedEvent struct {
+ SourceLine int
+ Event schema.Event
+}
+
+type MapOptions struct {
+ MinLine int
+ SkipStarted bool
+}
+
+func MapSession(ref SessionRef, entries []Entry, opts MapOptions) []MappedEvent {
+ m := &mapper{
+ ref: ref,
+ opts: opts,
+ model: firstNonEmpty(stringValue(ref.Header["model"]), stringValue(ref.Header["modelId"])),
+ 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 {
+ case typ == "session":
+ if id := stringValue(data["id"]); id != "" {
+ m.sessionID = id
+ }
+ if cwd := stringValue(data["cwd"]); cwd != "" {
+ m.cwd = cwd
+ }
+ case typ == "model_change":
+ if model := firstNonEmpty(stringValue(data["modelId"]), stringValue(data["model"])); model != "" {
+ m.model = model
+ if emit {
+ ev := m.base(timestamp, "session.context", "session", schema.SeverityInfo, "Pi model changed")
+ ev.Raw = m.raw(map[string]interface{}{"change": "model_change", "model_id": model})
+ m.append(entry.Line, "model_change", ev)
+ }
+ }
+ case typ == "compaction":
+ if emit {
+ ev := m.base(timestamp, "session.compacting", "session", schema.SeverityInfo, "Pi compacted session history")
+ ev.Raw = m.raw(compactionRaw(data))
+ m.append(entry.Line, "compaction", ev)
+ }
+ case typ == "thinking_level_change":
+ return
+ case typ == "custom":
+ m.consumeCustom(entry.Line, data, timestamp, emit)
+ case typ == "message":
+ message, _ := data["message"].(map[string]interface{})
+ if message == nil {
+ return
+ }
+ m.consumeMessage(entry.Line, message, timestamp, emit)
+ case toolCallKinds[typ]:
+ state := m.toolCallFrom(entry.Line, 0, data, timestamp)
+ m.calls[state.ID] = state
+ if emit {
+ ev := m.base(timestamp, "tool.invoked", "tool", schema.SeverityInfo, "Pi tool invoked")
+ m.applyToolCall(&ev, state)
+ m.append(entry.Line, "tool_call", ev)
+ }
+ case toolResultKinds[typ]:
+ if emit {
+ callID := firstNonEmpty(stringValue(data["toolCallId"]), stringValue(data["callId"]), stringValue(data["id"]), fmt.Sprintf("line-%d", entry.Line))
+ m.emitToolResult(entry.Line, timestamp, callID, data)
+ }
+ case typ == "error":
+ if emit {
+ m.emitError(entry.Line, timestamp, data)
+ }
+ }
+}
+
+func (m *mapper) consumeCustom(line int, data map[string]interface{}, timestamp time.Time, emit bool) {
+ customType := stringValue(data["customType"])
+ if customType != "context:skill_loaded" {
+ return
+ }
+ payload, _ := data["data"].(map[string]interface{})
+ name := stringValue(payload["name"])
+ if !emit || name == "" {
+ return
+ }
+ path := stringValue(payload["path"])
+ callID := firstNonEmpty(stringValue(data["id"]), fmt.Sprintf("line-%d-skill", line))
+ args := map[string]interface{}{"name": name, "source_format": "pi-skill-loaded"}
+ if path != "" {
+ args["path"] = path
+ }
+ state := toolCallState{ID: callID, Name: "skill", Args: args, Timestamp: timestamp}
+ call := m.base(timestamp, "tool.invoked", "tool", schema.SeverityInfo, "Pi skill loaded")
+ m.applyToolCall(&call, state)
+ m.append(line, "skill.loaded.call", call)
+
+ result := m.base(timestamp, "tool.completed", "tool", schema.SeverityInfo, "Pi skill load completed")
+ m.applyToolCall(&result, state)
+ result.Raw = m.raw(map[string]interface{}{"custom_type": customType, "data": data["data"]})
+ m.append(line, "skill.loaded.result", result)
+}
+
+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{})
+ start := len(m.out)
+ for i, part := range content {
+ m.consumeAssistantPart(line, i, timestamp, part, emit)
+ }
+ if emit {
+ m.emitUsage(line, timestamp, message, start)
+ }
+ 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 "bashexecution":
+ if emit {
+ m.emitBashExecution(line, timestamp, message)
+ }
+ case "error":
+ if emit {
+ m.emitError(line, timestamp, message)
+ }
+ }
+}
+
+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 {
+ case kind == "thinking":
+ text := firstNonEmpty(stringValue(item["thinking"]), stringValue(item["text"]), stringValue(item["content"]))
+ if emit && text != "" {
+ ev := m.base(timestamp, "agent.reasoning", "reasoning", schema.SeverityInfo, "Pi 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 kind == "text":
+ text := firstNonEmpty(stringValue(item["text"]), stringValue(item["content"]))
+ if emit && text != "" {
+ ev := m.base(timestamp, "agent.message", "session", schema.SeverityInfo, "Pi 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 toolCallKinds[kind]:
+ state := m.toolCallFrom(line, index, item, timestamp)
+ m.calls[state.ID] = state
+ if emit {
+ ev := m.base(timestamp, "tool.invoked", "tool", schema.SeverityInfo, "Pi tool invoked")
+ m.applyToolCall(&ev, state)
+ m.append(line, fmt.Sprintf("assistant.%d.tool_call", index), ev)
+ }
+ case toolResultKinds[kind]:
+ callID := firstNonEmpty(stringValue(item["callId"]), stringValue(item["toolCallId"]), stringValue(item["id"]), fmt.Sprintf("line-%d-call-%d", line, index))
+ if emit {
+ m.emitToolResult(line, timestamp, callID, item)
+ }
+ }
+}
+
+func (m *mapper) toolCallFrom(line, index int, item map[string]interface{}, timestamp time.Time) toolCallState {
+ nested := firstMap(item["toolCall"], item["functionCall"])
+ callID := firstNonEmpty(
+ stringValue(item["callId"]),
+ stringValue(item["toolCallId"]),
+ stringValue(nested["callId"]),
+ stringValue(nested["id"]),
+ stringValue(item["id"]),
+ fmt.Sprintf("line-%d-call-%d", line, index),
+ )
+ name := firstNonEmpty(
+ stringValue(item["name"]),
+ stringValue(item["toolName"]),
+ stringValue(nested["name"]),
+ stringValue(nested["toolName"]),
+ "unknown",
+ )
+ args := parseArgs(firstNonNil(item["args"], item["input"], item["arguments"], nested["args"], nested["input"], nested["arguments"]))
+ return toolCallState{ID: callID, Name: name, Args: args, Timestamp: timestamp}
+}
+
+func (m *mapper) emitSessionStarted() {
+ ts := timestampValue(firstNonNil(m.ref.Header["timestamp"], refTimestamp(m.ref)))
+ ev := m.base(ts, "session.started", "session", schema.SeverityInfo, "Pi session started")
+ ev.Raw = m.raw(map[string]interface{}{"source_path": m.ref.Path})
+ 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, "Pi 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"]), stringValue(message["name"]), "unknown"),
+ Args: parseArgs(firstNonNil(message["args"], message["input"], message["arguments"])),
+ }
+ }
+ output := extractTextContent(firstNonNil(message["output"], message["result"], message["content"], childMap(message["toolResult"])["output"]))
+ if output == "" {
+ output = "(empty result)"
+ }
+ failed := boolValue(firstNonNil(message["isError"], message["is_error"])) || isErrorStatus(firstNonNil(message["status"], childMap(message["details"])["status"]))
+ action, category, severity := classifyToolResult(state.Name, state.Args, failed)
+ ev := m.base(timestamp, action, category, severity, "Pi 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 category == "file" {
+ m.applyFileResult(&ev, state.Name, message)
+ }
+ if output != "" && output != "(empty result)" {
+ if ev.Command != nil {
+ ev.Command.Output = output
+ }
+ if ev.Content == nil {
+ ev.Content = asymptoteobserve.RetainedContent(output, asymptoteobserve.DefaultStringLimit)
+ }
+ }
+ ev.Raw = m.raw(map[string]interface{}{"tool_result": message})
+ m.append(line, "tool_result", ev)
+}
+
+func (m *mapper) emitBashExecution(line int, timestamp time.Time, message map[string]interface{}) {
+ command := stringValue(message["command"])
+ if command == "" {
+ return
+ }
+ callID := fmt.Sprintf("line-%d-bash", line)
+ state := toolCallState{ID: callID, Name: "bash", Args: map[string]interface{}{"command": command}, Timestamp: timestamp}
+ output := extractTextContent(message["output"])
+ ev := m.base(timestamp, "command.executed", "command", schema.SeverityInfo, "Pi bash command executed")
+ m.applyToolCall(&ev, state)
+ ev.Command = &schema.CommandInfo{Command: command, Output: output}
+ if exitCode, ok := intValue(message["exitCode"]); ok {
+ ev.Command.ExitCode = &exitCode
+ }
+ if boolValue(message["cancelled"]) || (ev.Command.ExitCode != nil && *ev.Command.ExitCode != 0) {
+ ev.Error = &schema.ErrorInfo{Type: "command_failed"}
+ }
+ if output != "" {
+ ev.Content = asymptoteobserve.RetainedContent(output, asymptoteobserve.DefaultStringLimit)
+ }
+ ev.Raw = m.raw(map[string]interface{}{"bash_execution": message})
+ m.append(line, "bash_execution", ev)
+}
+
+func (m *mapper) emitError(line int, timestamp time.Time, data map[string]interface{}) {
+ text := firstNonEmpty(stringValue(data["errorMessage"]), stringValue(data["message"]), strings.Join(texts(data["content"]), "\n"), "Unknown error")
+ ev := m.base(timestamp, "agent.error", "session", schema.SeverityHigh, "Pi 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) emitUsage(line int, timestamp time.Time, message map[string]interface{}, since int) {
+ usage := piUsage(childMap(message["usage"]))
+ if usage == nil {
+ return
+ }
+ for i := len(m.out) - 1; i >= since; i-- {
+ action := m.out[i].Event.Event.Action
+ if action == "agent.message" || action == "agent.reasoning" || action == "tool.invoked" || action == "agent.error" {
+ m.out[i].Event.GenAI = ensureGenAI(m.out[i].Event.GenAI)
+ m.out[i].Event.GenAI.Usage = usage
+ return
+ }
+ }
+ ev := m.base(timestamp, "token.usage", "metric", schema.SeverityInfo, "Pi token usage")
+ ev.GenAI = ensureGenAI(ev.GenAI)
+ ev.GenAI.Usage = usage
+ m.append(line, "usage", ev)
+}
+
+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, Operation: fileOperation(call.Name), Language: strings.TrimPrefix(filepath.Ext(path), ".")}
+ }
+ if server, tool := piMCPServerTool(call.Name); server != "" || tool != "" {
+ ev.MCP = &schema.MCPInfo{Server: server, Tool: tool}
+ }
+ 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}}
+}
+
+func (m *mapper) applyFileResult(ev *schema.Event, name string, message map[string]interface{}) {
+ if ev.File == nil {
+ ev.File = &schema.FileInfo{Operation: fileOperation(name)}
+ }
+ details := childMap(message["details"])
+ diff := firstNonEmpty(stringValue(details["patch"]), stringValue(details["diff"]))
+ if diff != "" {
+ ev.File.Diff = diff
+ ev.File.DiffBytes = len(diff)
+ ev.File.DiffHash = sha256Hex(diff)
+ ev.Content = asymptoteobserve.RetainedContent(diff, asymptoteobserve.DefaultStringLimit)
+ }
+}
+
+func classifyToolResult(name string, args map[string]interface{}, failed bool) (string, string, schema.Severity) {
+ lower := strings.ToLower(name)
+ switch {
+ case lower == "bash" || commandFor(name, args) != "":
+ return "command.executed", "command", schema.SeverityInfo
+ case lower == "read" && stringArg(args, "path", "file_path", "target_path") != "":
+ return "file.read", "file", schema.SeverityInfo
+ case lower == "write" && stringArg(args, "path", "file_path", "target_path") != "":
+ return "file.created", "file", schema.SeverityInfo
+ case lower == "edit" && stringArg(args, "path", "file_path", "target_path") != "":
+ return "file.modified", "file", schema.SeverityInfo
+ case isMCPTool(name):
+ return "mcp.tool_invoked", "mcp", schema.SeverityInfo
+ case failed:
+ return "tool.failed", "tool", schema.SeverityHigh
+ default:
+ return "tool.completed", "tool", schema.SeverityInfo
+ }
+}
+
+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
+ }
+ return map[string]interface{}{"pi": fields}
+}
+
+func (m *mapper) append(line int, suffix string, ev schema.Event) {
+ ev.Event.ID = piEventID(fmt.Sprintf("%s:%s:%d:%s", m.sessionID, m.ref.Path, line, suffix))
+ m.out = append(m.out, MappedEvent{SourceLine: line, Event: ev})
+}
+
+func commandFor(name string, args map[string]interface{}) string {
+ if strings.EqualFold(name, "bash") {
+ return stringArg(args, "command")
+ }
+ return stringArg(args, "command", "cmd")
+}
+
+func fileOperation(name string) string {
+ switch strings.ToLower(name) {
+ case "read":
+ return "read"
+ case "write":
+ return "create"
+ case "edit":
+ return "modify"
+ default:
+ return ""
+ }
+}
+
+func piMCPServerTool(toolName string) (string, string) {
+ rest, ok := strings.CutPrefix(strings.TrimSpace(toolName), "mcp__")
+ if !ok {
+ return "", ""
+ }
+ if server, tool, ok := strings.Cut(rest, "__"); ok && server != "" && tool != "" {
+ return server, tool
+ }
+ server, tool, ok := strings.Cut(rest, "_")
+ if !ok || server == "" || tool == "" {
+ return "", ""
+ }
+ return server, tool
+}
+
+func isMCPTool(name string) bool {
+ server, tool := piMCPServerTool(name)
+ return server != "" || tool != ""
+}
+
+func piUsage(usage map[string]interface{}) *schema.GenAIUsageInfo {
+ if len(usage) == 0 {
+ return nil
+ }
+ out := &schema.GenAIUsageInfo{}
+ if value, ok := int64Value(usage["input"]); ok {
+ out.InputTokens = &value
+ }
+ if value, ok := int64Value(usage["output"]); ok {
+ out.OutputTokens = &value
+ }
+ if value, ok := int64Value(usage["cacheRead"]); ok {
+ out.CacheRead = &schema.GenAIUsageCacheReadInfo{InputTokens: &value}
+ }
+ if value, ok := int64Value(usage["cacheWrite"]); ok {
+ out.CacheCreation = &schema.GenAIUsageCacheCreationInfo{InputTokens: &value}
+ }
+ if value, ok := int64Value(usage["reasoning"]); ok {
+ out.Reasoning = &schema.GenAIUsageReasoningInfo{OutputTokens: &value}
+ }
+ if cost := childMap(usage["cost"]); len(cost) > 0 {
+ if value, ok := floatValue(cost["total"]); ok {
+ out.CostUSD = &value
+ }
+ }
+ if out.InputTokens == nil && out.OutputTokens == nil && out.CacheRead == nil && out.CacheCreation == nil && out.Reasoning == nil && out.CostUSD == nil {
+ return nil
+ }
+ return out
+}
+
+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
+}
+
+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 := firstNonEmpty(stringValue(m["text"]), stringValue(m["content"]), stringValue(m["output"])); text != "" {
+ out = append(out, text)
+ }
+ }
+ return out
+ default:
+ return nil
+ }
+}
+
+func extractTextContent(value interface{}) string {
+ if value == nil {
+ return ""
+ }
+ if text := strings.Join(texts(value), "\n"); text != "" {
+ return text
+ }
+ data, err := json.MarshalIndent(value, "", " ")
+ if err != nil {
+ return fmt.Sprint(value)
+ }
+ if string(data) == "null" {
+ return ""
+ }
+ return string(data)
+}
+
+func childMap(value interface{}) map[string]interface{} {
+ m, _ := value.(map[string]interface{})
+ if m == nil {
+ return map[string]interface{}{}
+ }
+ return m
+}
+
+func firstMap(values ...interface{}) map[string]interface{} {
+ for _, value := range values {
+ if m := childMap(value); len(m) > 0 {
+ return m
+ }
+ }
+ return map[string]interface{}{}
+}
+
+func parseArgs(value interface{}) map[string]interface{} {
+ if m := childMap(value); len(m) > 0 {
+ return m
+ }
+ if text := stringValue(value); text != "" {
+ var out map[string]interface{}
+ if err := json.Unmarshal([]byte(text), &out); err == nil && out != nil {
+ return out
+ }
+ return map[string]interface{}{"raw": text}
+ }
+ if value == nil {
+ return map[string]interface{}{}
+ }
+ return map[string]interface{}{"raw": value}
+}
+
+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 strings.TrimSpace(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 intValue(value interface{}) (int, bool) {
+ switch v := value.(type) {
+ case int:
+ return v, true
+ case int64:
+ return int(v), true
+ case float64:
+ return int(v), true
+ default:
+ return 0, false
+ }
+}
+
+func int64Value(value interface{}) (int64, bool) {
+ switch v := value.(type) {
+ case int64:
+ return v, true
+ case int:
+ return int64(v), true
+ case float64:
+ if v < 0 {
+ return 0, false
+ }
+ return int64(v), true
+ default:
+ return 0, false
+ }
+}
+
+func floatValue(value interface{}) (float64, bool) {
+ switch v := value.(type) {
+ case float64:
+ return v, true
+ case int:
+ return float64(v), true
+ case int64:
+ return float64(v), true
+ default:
+ return 0, false
+ }
+}
+
+func isErrorStatus(value interface{}) bool {
+ status := strings.ToLower(stringValue(value))
+ return status == "error" || status == "failed" || status == "failure"
+}
+
+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 n, ok := floatValueFromString(v); ok {
+ if n > 1_000_000_000_000 {
+ return time.UnixMilli(int64(n)).UTC()
+ }
+ return time.Unix(int64(n), 0).UTC()
+ }
+ 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 floatValueFromString(value string) (float64, bool) {
+ var out float64
+ if _, err := fmt.Sscanf(strings.TrimSpace(value), "%f", &out); err != nil {
+ return 0, false
+ }
+ return out, true
+}
+
+func refTimestamp(ref SessionRef) time.Time {
+ if ref.ModTimeMS > 0 {
+ return time.UnixMilli(ref.ModTimeMS).UTC()
+ }
+ return time.Now().UTC()
+}
+
+func sha256Hex(value string) string {
+ sum := sha256.Sum256([]byte(value))
+ return hex.EncodeToString(sum[:])
+}
+
+var piIDNamespace = [16]byte{
+ 0x30, 0xa5, 0xe5, 0x5d, 0x8e, 0x20, 0x49, 0x24,
+ 0x9f, 0x81, 0x15, 0xb7, 0x59, 0x2a, 0x4f, 0x0d,
+}
+
+func piEventID(coordinate string) string {
+ digest := sha1.New()
+ digest.Write(piIDNamespace[:])
+ 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/pisession/mapper_test.go b/cli/beacon/internal/pisession/mapper_test.go
new file mode 100644
index 00000000..e3905e69
--- /dev/null
+++ b/cli/beacon/internal/pisession/mapper_test.go
@@ -0,0 +1,107 @@
+package pisession
+
+import "testing"
+
+func TestMapSessionPiTranscript(t *testing.T) {
+ ref := SessionRef{
+ ID: "session-1",
+ Path: "/tmp/pi-session-1.jsonl",
+ 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",
+ "usage": map[string]interface{}{
+ "input": 10.0, "output": 5.0, "cacheRead": 2.0, "reasoning": 1.0,
+ "cost": map[string]interface{}{"total": 0.01},
+ },
+ "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": "bash", "arguments": map[string]interface{}{"command": "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": "bash", "content": []interface{}{map[string]interface{}{"text": "README.md"}},
+ }}},
+ {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": "context:skill_loaded", "timestamp": "2026-09-19T01:00:04Z", "data": map[string]interface{}{"name": "share-to-traces", "path": "/work/project/.pi/skills/share/SKILL.md"}}},
+ }
+
+ mapped := MapSession(ref, entries, MapOptions{})
+ actions := actionsOf(mapped)
+ want := []string{
+ "session.started",
+ "prompt.submitted",
+ "agent.reasoning",
+ "agent.message",
+ "tool.invoked",
+ "command.executed",
+ "session.compacting",
+ "tool.invoked",
+ "tool.completed",
+ }
+ 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)
+ }
+ }
+ 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)
+ }
+ command := mapped[5].Event.Command
+ if command == nil || command.Command != "ls" || command.Output != "README.md" {
+ t.Fatalf("command event = %#v", command)
+ }
+ if usage := mapped[4].Event.GenAI.Usage; usage == nil || usage.InputTokens == nil || *usage.InputTokens != 10 {
+ t.Fatalf("usage not attached to last assistant event: %#v", usage)
+ }
+ for _, item := range mapped {
+ if item.Event.Event.ID == "" {
+ t.Fatalf("event %s missing deterministic id", item.Event.Event.Action)
+ }
+ }
+}
+
+func TestMapSessionSupportsTopLevelToolRecords(t *testing.T) {
+ ref := SessionRef{ID: "session-1", Path: "/tmp/pi-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": "tool_call", "id": "call-1", "toolName": "edit", "input": map[string]interface{}{"path": "/work/file.go"}}},
+ {Line: 3, Data: map[string]interface{}{"type": "tool_result", "toolCallId": "call-1", "details": map[string]interface{}{"patch": "--- a/file.go\n+++ b/file.go\n@@\n-old\n+new\n"}}},
+ }
+ mapped := MapSession(ref, entries, MapOptions{})
+ if got := actionsOf(mapped); len(got) != 3 || got[1] != "tool.invoked" || got[2] != "file.modified" {
+ t.Fatalf("actions = %#v", got)
+ }
+ file := mapped[2].Event.File
+ if file == nil || file.Path != "/work/file.go" || file.Diff == "" || file.DiffHash == "" {
+ t.Fatalf("file event = %#v", file)
+ }
+}
+
+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/pisession/state.go b/cli/beacon/internal/pisession/state.go
new file mode 100644
index 00000000..2f5a2bd6
--- /dev/null
+++ b/cli/beacon/internal/pisession/state.go
@@ -0,0 +1,94 @@
+package pisession
+
+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"`
+}
+
+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 Pi 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", "pi.json")
+}
diff --git a/cli/beacon/internal/pisession/store.go b/cli/beacon/internal/pisession/store.go
new file mode 100644
index 00000000..b1832db3
--- /dev/null
+++ b/cli/beacon/internal/pisession/store.go
@@ -0,0 +1,213 @@
+package pisession
+
+import (
+ "bufio"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+)
+
+const (
+ maxSessionFiles = 15000
+ maxLineBytes = 10 * 1024 * 1024
+
+ piAgentDirEnv = "PI_CODING_AGENT_DIR"
+)
+
+// Store reads Pi's durable JSONL session store.
+type Store struct {
+ SessionsDir string
+}
+
+// SessionRef is one Pi JSONL transcript.
+type SessionRef struct {
+ ID string
+ Path string
+ ModTimeMS int64
+ SizeBytes int64
+ Header map[string]interface{}
+}
+
+// Entry is one decoded line from a Pi transcript.
+type Entry struct {
+ Line int
+ Data map[string]interface{}
+}
+
+type ReadStats struct {
+ Malformed int
+ MaxLine int
+}
+
+func NewStore(sessionsDir string) (*Store, error) {
+ if strings.TrimSpace(sessionsDir) == "" {
+ def, err := DefaultSessionsDir()
+ if err != nil {
+ return nil, err
+ }
+ sessionsDir = def
+ }
+ return &Store{SessionsDir: sessionsDir}, nil
+}
+
+func DefaultSessionsDir() (string, error) {
+ agentDir, err := defaultAgentDir()
+ if err != nil {
+ return "", err
+ }
+ return filepath.Join(agentDir, "sessions"), 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(piAgentDirEnv)); override != "" {
+ return expandTilde(override, home), nil
+ }
+ if strings.TrimSpace(home) == "" {
+ return "", errors.New("home directory is empty")
+ }
+ return filepath.Join(home, ".pi", "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 {
+ info, err := os.Stat(s.SessionsDir)
+ return err == nil && info.IsDir()
+}
+
+func (s *Store) List() ([]SessionRef, error) {
+ items, err := listJSONL(s.SessionsDir)
+ if err != nil {
+ return nil, err
+ }
+ refs := make([]SessionRef, 0, len(items))
+ 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 = extractSessionIDFromPath(path)
+ }
+ refs = append(refs, SessionRef{
+ ID: id,
+ Path: path,
+ 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 dirExists(path string) bool {
+ info, err := os.Stat(path)
+ return err == nil && info.IsDir()
+}
+
+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
+}
+
+func extractSessionIDFromPath(path string) string {
+ base := strings.TrimSuffix(filepath.Base(path), filepath.Ext(path))
+ if idx := strings.LastIndex(base, "_"); idx >= 0 && idx+1 < len(base) {
+ return base[idx+1:]
+ }
+ return base
+}
diff --git a/docs/cli/endpoint-pi.mdx b/docs/cli/endpoint-pi.mdx
new file mode 100644
index 00000000..7951afa0
--- /dev/null
+++ b/docs/cli/endpoint-pi.mdx
@@ -0,0 +1,98 @@
+---
+title: "beacon endpoint pi"
+description: "Collect endpoint telemetry from Pi session records"
+---
+
+## Command overview
+
+`beacon endpoint pi` collects telemetry from [Pi](/runtimes/pi) by reading the JSONL session records Pi commits under `~/.pi/agent/sessions` and converting them into Beacon [endpoint events](/concepts/core-concepts#endpoint-event).
+
+```bash title="Command syntax"
+beacon endpoint pi [command]
+```
+
+This is a poll path, not an install step. The managed Pi extension remains the live path for future sessions; `beacon endpoint pi sync` is for historical backfill, scheduled catch-up, or machines where the extension was not loaded.
+
+Every event is marked `harness.collection_method=poll`. Beacon sees what Pi wrote after the fact, so nothing here can hold or deny a tool call.
+
+Reading is local and offline. Nothing this command does reaches the network.
+
+## Commands
+
+| Command | Description |
+|---------|-------------|
+| `beacon endpoint pi sync` | Read new Pi session records into the runtime log |
+| `beacon endpoint pi status` | Show Pi sessions on this machine and how much of each has been collected |
+
+## Flags
+
+Both subcommands accept:
+
+| Flag | Description |
+|------|-------------|
+| `--sessions-dir <path>` | Pi session directory. Defaults to `~/.pi/agent/sessions` |
+| `--state <path>` | Collector cursor file. Defaults to `~/.beacon/endpoint/state/pi.json` |
+| `--json` | Print the result as JSON |
+| `--user` | Use per-user endpoint paths. Enabled by default |
+| `--system` | Use system endpoint paths. The cursor moves beside the system runtime log |
+
+`sync` also accepts:
+
+| Flag | Description |
+|------|-------------|
+| `--log-path <path>` | Runtime JSONL log path. Defaults to the resolved endpoint log |
+| `--print` | Print mapped events as JSON without writing them or advancing the cursor |
+| `--watch` | Sweep continuously on `--interval` instead of sweeping once and exiting |
+| `--interval <duration>` | Sweep interval for `--watch`. Defaults to `1m`, with a 5-second floor |
+
+## Sweeping
+
+```bash title="Sweep once"
+beacon endpoint pi sync
+```
+
+```bash title="Preview without writing anything"
+beacon endpoint pi sync --print
+```
+
+`--print` is a dry run in both directions: it neither writes the runtime log nor advances the cursor, so running it twice shows the same events and running it does not quietly consume the work a later real sweep would do.
+
+```bash title="Sweep continuously"
+beacon endpoint pi sync --watch --interval 5m
+```
+
+Nothing sweeps on its own. Run `sync` under whatever scheduler the platform already uses, or leave `--watch` running.
+
+## Status
+
+```bash title="Show Pi sessions and collection progress"
+beacon endpoint pi status
+```
+
+```text
+Pi sessions: 2 in /Users/you/.pi/agent/sessions
+ session-1 collected line 42 /Users/you/src/app
+ session-2 pending line 0 /Users/you/src/api
+```
+
+## Cursor behavior
+
+The cursor keeps a scheduled sweep from re-appending every session's whole history. It stores the last collected line per session file, plus the file size and modification time for a cheap unchanged check.
+
+| Mode | Default cursor path |
+|------|---------------------|
+| User | `~/.beacon/endpoint/state/pi.json` |
+| System | `pi-state.json` beside the system runtime log |
+
+Re-reading is safe: each event ID is derived from the source file, session id, line number, and event position, so the same Pi record maps to the same event every time.
+
+## Related
+
+<Columns cols={2}>
+ <Card title="Pi" icon="code" href="/runtimes/pi">
+ Telemetry coverage, discovery, and known gaps for the runtime.
+ </Card>
+ <Card title="Hooks" icon="plug" href="/cli/hooks">
+ Install the managed Pi extension for live telemetry.
+ </Card>
+</Columns>
diff --git a/docs/cli/index.mdx b/docs/cli/index.mdx
index 3c193818..d7f58a4e 100644
--- a/docs/cli/index.mdx
+++ b/docs/cli/index.mdx
@@ -169,6 +169,8 @@ Manage the local endpoint agent and inspect supported agent harness telemetry.
| [`beacon endpoint gcs`](/cli/gcs) | Generate Google Cloud Storage forwarding content for Beacon endpoint events. |
| [`beacon endpoint asymptote`](/cli/asymptote) | Generate the Vector forwarding pack for Asymptote managed ingest and write validation events. |
| [`beacon endpoint hooks`](/cli/hooks) | Manage supported hook-based endpoint telemetry. |
+| [`beacon endpoint opencode`](/cli/endpoint-opencode) | Collect endpoint telemetry from OpenCode session records on this machine. |
+| [`beacon endpoint pi`](/cli/endpoint-pi) | Collect endpoint telemetry from Pi session records on this machine. |
| [`beacon endpoint fx`](/cli/endpoint-fx) | Collect endpoint telemetry from fx session records on this machine. |
| [`beacon endpoint integrations openclaw`](/cli/openclaw) | Set up and validate OpenClaw Gateway OTLP export. |
| [`beacon endpoint integrations claude-cowork`](/cli/claude-cowork) | Set up and validate Claude Cowork OTLP export. |
diff --git a/docs/docs.json b/docs/docs.json
index e505c898..b33647ea 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -391,6 +391,8 @@
"cli/endpoint-uninstall",
"cli/endpoint-config",
"cli/endpoint-onboarding",
+ "cli/endpoint-opencode",
+ "cli/endpoint-pi",
"cli/endpoint-fx",
"cli/dashboard",
"cli/wazuh",
diff --git a/docs/runtimes/index.mdx b/docs/runtimes/index.mdx
index 1e3d5633..f953d0f2 100644
--- a/docs/runtimes/index.mdx
+++ b/docs/runtimes/index.mdx
@@ -36,9 +36,9 @@ These integrations are grouped by where the agent runs and how telemetry is coll
| [Kiro](/runtimes/kiro) | Native hooks through a Beacon-owned file in `.kiro/hooks/` | Session start, prompts, pre-tool and post-tool activity, commands with output, file reads and edits, MCP tool calls, failed tools, and the agent's final response. No approval decisions or token usage, because Kiro exposes neither on a hook |
| [Muse Code](/runtimes/muse-code) | Native hooks through a managed hooks file | Session start, prompt, pre-tool, post-tool, permission request, subagent, context compaction, stop, command, and file telemetry |
| [Oh My Pi](/runtimes/oh-my-pi) | Managed extension hooks | Session lifecycle, prompts, tool lifecycle, operator approval decisions, commands including operator `!` and `$` commands, file reads and edits with the unified patch, MCP tool activity, agent reasoning, and token usage |
-| [OpenCode](/runtimes/opencode) | Managed plugin hooks | Chat messages, session events, command execution, permission activity, diffs, and errors |
+| [OpenCode](/runtimes/opencode) | Managed plugin hooks plus optional poll of OpenCode's local session store through `beacon endpoint opencode sync` | Plugin: chat messages, session events, command execution, permission activity, diffs, and errors. Poll: historical prompts, assistant text/reasoning, tool outcomes, commands, file activity with paths, compaction, and token usage where persisted. Approval telemetry comes from the live plugin only |
| [OpenHands](/runtimes/openhands) | Native hooks merged into the repository's own `.openhands/hooks.json` | Session start and end, prompts, pre-tool and post-tool activity, commands with exit codes and output, file reads and edits with exact before/after diffs, MCP tool calls, and failed tools. No approval decisions or token usage, because OpenHands exposes neither on a hook |
-| [Pi](/runtimes/pi) | Managed extension hooks | Session lifecycle, prompts, tool lifecycle, commands including operator `!` commands, file reads and edits with the unified patch, agent reasoning, and token usage |
+| [Pi](/runtimes/pi) | Managed extension hooks plus optional poll of Pi's local session store through `beacon endpoint pi sync` | Extension: session lifecycle, prompts, tool lifecycle, commands including operator `!` commands, file reads and edits with the unified patch, agent reasoning, and token usage. Poll: historical prompts, assistant text/reasoning, tool calls/results, commands, file activity with paths and diffs where persisted, compaction, skill-load records, and token usage. No approval decisions, because Pi exposes none |
| [Prime Agent](/runtimes/prime-agent) | Managed extension hooks | Session lifecycle, prompts, tool lifecycle, commands including each `ipython` kernel cell and operator `!` commands, file edits with the unified patch, agent reasoning, and token usage. No approval decisions, because Prime Agent exposes none; MCP calls are not separately attributed, because it does not expose MCP as agent tools |
| [Qwen Code](/runtimes/qwen-code) | Native hooks | Session, prompt, pre-tool, post-tool, failed tool, permission request, subagent, stop, session-end, command, and file telemetry |
| [Senpi](/runtimes/senpi) | Managed extension hooks | Session lifecycle, prompts, tool lifecycle, commands including operator `!` commands, file reads and edits with the unified patch, agent reasoning, and token usage. The standalone `omo` edition of oh-my-openagent; its OpenCode and Codex CLI editions ride the existing OpenCode and Codex CLI integrations instead. No approval decisions, because Senpi exposes none through its extension API |
@@ -113,11 +113,13 @@ MDM assets, meaning Jamf Pro Extension Attributes, Fleet osquery queries, and Ri
|---------|--------------------------|
| Gemini CLI | Opt in by adding `gemini` to the endpoint harness list, for example `claude,codex,gemini`. Asymptote can then manage `~/.gemini/settings.json` for local OTLP collection. |
| fx (Vercel Labs) | Nothing to configure in fx. Schedule [`beacon endpoint fx sync`](/cli/endpoint-fx) in the logged-in user's context, or leave `--watch` running, so committed sessions keep reaching the runtime log. Nothing sweeps on its own. |
+| OpenCode | Install the managed plugin for live telemetry with `beacon endpoint hooks install --harness opencode`. To backfill committed local sessions, schedule [`beacon endpoint opencode sync`](/cli/endpoint-opencode) in the logged-in user's context or leave `--watch` running. |
+| Pi | Install the managed extension for live telemetry with `beacon endpoint hooks install --harness pi`. To backfill committed local sessions, schedule [`beacon endpoint pi sync`](/cli/endpoint-pi) in the logged-in user's context or leave `--watch` running. |
| GitHub Copilot CLI | Configure launch environment through MDM or customer policy: `COPILOT_OTEL_ENABLED=true` and `OTEL_EXPORTER_OTLP_ENDPOINT=http://127.0.0.1:4318`. Asymptote validates the endpoint but does not edit shell profiles or launch environments. |
| Factory Droid | Configure launch environment with `OTEL_TELEMETRY_ENDPOINT=http://127.0.0.1:4318`. Asymptote discovers the runtime and validates the endpoint but does not edit shell profiles or launch environments. |
| OpenClaw Gateway | Install the managed plugin in the account the gateway runs as with `beacon endpoint hooks install --harness openclaw`, then grant `plugins.entries.beacon-endpoint.hooks.allowConversationAccess` in OpenClaw's own config so token usage is collected. For the gateway's OTLP export, use [`beacon endpoint integrations openclaw`](/cli/openclaw) to print local settings and validate events; Asymptote never writes OpenClaw's config. |
-Install hooks separately in the logged-in user's context when you need richer hook telemetry. This applies to Antigravity CLI, Claude Code, Cline, Codex CLI session-context hooks, Cursor, Devin CLI, Devin Desktop, Factory Droid, Grok Build, Hermes Agent, goose, Muse Code, Oh My Pi, OpenClaw Gateway, OpenCode, OpenHands, Pi, Qwen Code, and the optional VS Code hooks. fx is the exception with no hooks to install: schedule [`beacon endpoint fx sync`](/cli/endpoint-fx) instead.
+Install hooks separately in the logged-in user's context when you need richer hook telemetry. This applies to Antigravity CLI, Claude Code, Cline, Codex CLI session-context hooks, Cursor, Devin CLI, Devin Desktop, Factory Droid, Grok Build, Hermes Agent, goose, Muse Code, Oh My Pi, OpenClaw Gateway, OpenCode, OpenHands, Pi, Qwen Code, and the optional VS Code hooks. Pi and OpenCode also have optional session-store sync commands for backfill. fx is the exception with no hooks to install: schedule [`beacon endpoint fx sync`](/cli/endpoint-fx) instead.
If a system collector is running while the CLI is reading the default per-user log, `beacon endpoint status` and the local dashboard surface a runtime-log source warning so you can tell where OTLP events are being written.
diff --git a/docs/runtimes/pi.mdx b/docs/runtimes/pi.mdx
index 01908985..f8a8c301 100644
--- a/docs/runtimes/pi.mdx
+++ b/docs/runtimes/pi.mdx
@@ -11,12 +11,20 @@ Asymptote supports [Pi](https://pi.dev/) through a managed local extension.
Looking for [Oh My Pi](/runtimes/oh-my-pi) (`omp`), [Prime Agent](/runtimes/prime-agent), or [Senpi](/runtimes/senpi) (`omo`, the standalone edition of oh-my-openagent)? All three are forks of Pi, supported separately and recorded under their own harness names. Unlike Pi, Oh My Pi reports operator approval decisions.
</Note>
-Pi 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 support to point at the local collector. Its documented observation surface is the TypeScript extension API, so the integration is extension-shaped: one Asymptote-owned extension file forwards runtime events to `beacon-hooks`, the same shape as the OpenCode and Cline plugins.
+Pi 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 support to point at the local collector. Its documented observation surface is the TypeScript extension API, so the live integration is extension-shaped: one Asymptote-owned extension file forwards runtime events to `beacon-hooks`, the same shape as the OpenCode and Cline plugins.
```bash
beacon endpoint hooks install --harness pi
```
+Asymptote can also read Pi's committed JSONL session store after the fact:
+
+```bash
+beacon endpoint pi 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 events as Pi runs, while the poll path can backfill sessions that happened before the extension was installed or sessions where the extension was not loaded.
+
## Prerequisites
Before enabling Pi telemetry, make sure:
@@ -38,7 +46,7 @@ User level is the default. A project-level extension is subject to Pi's project-
Asymptote identifies its own extension file by the marker `beacon-managed-pi-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.
-Pi has no OpenTelemetry export for Asymptote to configure, so there is no OTLP path for this runtime.
+Pi has no OpenTelemetry export for Asymptote to configure, so there is no OTLP path for this runtime. The poll path reads JSONL transcripts from `~/.pi/agent/sessions`; if `PI_CODING_AGENT_DIR` is set, Asymptote reads `sessions` below that directory, matching Pi's user-level agent directory override. The cursor lives in Asymptote state, not in Pi's directory.
## Discovery and status
@@ -80,6 +88,7 @@ Install writes one file and refuses to touch a `beacon.ts` it did not write, so
| Runtime discovery | Supported through executable and `~/.pi/agent` detection, managed extension path, and telemetry status |
| Harness attribution | Supported. `pi`, `pi.dev`, `pi_cli`, `pi-cli`, `pi_agent`, `pi-agent`, and `pi agent` all normalize to `pi_cli` |
| Extension install, status, uninstall, and repair | Supported |
+| Session-store sync | Supported through `beacon endpoint pi sync`, with `--print`, `--watch`, and `--sessions-dir` |
| Session lifecycle | Supported. `session.started` and `session.ended`, carrying why the session started or stopped |
| 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` |
@@ -104,6 +113,7 @@ The extension itself sends nothing over the network. It spawns the local `beacon
- **No approval telemetry.** Pi's `tool_call` event lets an extension block a call, but that is an extension deciding rather than an operator being asked. Pi exposes no operator approval decision through the extension API, so Beacon records these as tool activity and writes no approval events for Pi. Cline works the same way for the same reason. Detections in `rules/approval-abuse/` do not fire on Pi activity.
- **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 Pi. Pi's blocking `tool_call` handler makes it a viable target for that seam later.
- **Streaming events are not collected.** The extension subscribes to seven of Pi's event types and ignores the rest, which are provider-request and TUI-rendering internals. 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 pi sync` can recover committed prompts, assistant messages and reasoning, tool calls and results, bash execution records, errors, compactions, skill-load records, and token usage from Pi'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.
- **Project-level installs need Pi's trust prompt.** A `.pi/extensions/beacon.ts` is subject to Pi's project-trust prompt, so a user-level install is the one that works without further interaction.
## Deployment notes