Skip to content

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

16.6 KB
Raw Blame
package asymptoteobserve

import (
	"crypto/sha1"
	"encoding/hex"
	"encoding/json"
	"io"
	"math"
	"strconv"
	"strings"
	"unicode/utf8"
)

// ToolCallIDKeys are the names a runtime uses for the identifier it assigns to
// one tool invocation, in the order Beacon prefers them.
//
// Every supported runtime already emits this value -- Claude Code as
// tool_use_id, Codex and OpenCode as call_id, Cline as callId -- and until this
// list existed Beacon dropped all of them into raw, because the promotion list
// held only the canonical OTel name that no runtime actually writes. It is the
// one field that links a tool call to its result, an approval to the execution
// it approved, and a hook event to the OTLP event for the same action, so it is
// promoted to gen_ai.tool.call.id on every capture path from this single list.
//
// Order matters: the canonical names come first so an explicitly mapped value
// always beats a runtime-native one, and the runtime-native names follow in no
// significant order because no payload carries two of them.
var ToolCallIDKeys = []string{
	"gen_ai.tool.call.id",
	"beacon.gen_ai.tool.call.id",
	"tool_use_id",
	"toolUseId",
	"tool_call_id",
	"toolCallId",
	"call_id",
	"callId",
	"callID",
	// Cursor's server-side OpenTelemetry export names a Grok Bot MCP tool call and computer-use
	// session by this key. It is the only place Beacon learns the id, because Grok Bot runs on
	// a Cursor-hosted computer and has no hook path that would carry a runtime-native spelling.
	"cursor.grok_bot.tool_call.id",
}

// PromptIDKeys are the names a runtime uses for the identifier it assigns to one
// user prompt and all the work done for it, until the next prompt -- what a
// person would call a turn. They are promoted to prompt.id on every capture
// path from this single list, the way ToolCallIDKeys is promoted to
// gen_ai.tool.call.id.
//
// OpenTelemetry's GenAI conventions define no attribute for this, so the field
// takes the name the runtimes themselves use: Claude Code's prompt.id, which it
// documents as correlating "a user prompt with all subsequent events until the
// next prompt", and which Gemini CLI spells prompt_id with the same meaning.
//
// A spelling belongs here only when the runtime's value means exactly that.
// Each entry names the runtime that writes it and the evidence:
//
//   - prompt.id: Claude Code OTLP events. The same UUID is written as promptId
//     on the transcript's prompt and tool-result entries.
//   - promptId: Claude Code session transcripts.
//   - prompt_id: Gemini CLI OTLP events.
//   - turn.id: Codex OTLP turn spans.
//   - turn_id: Codex hooks ("the active Codex turn id" on every turn-scoped
//     hook), Muse Code hooks, and Kimi Code hooks, where it is a number.
//   - generation_id: Cursor hooks ("the current generation that changes with
//     every user message"; conversation_id is the session).
//
// GitHub Copilot's turn ids are deliberately absent: Copilot opens a new turn
// for each model call inside one prompt, so its turn id is finer than a prompt.
//
// Canonical names come first so an explicitly mapped value always beats a
// runtime-native one; no payload carries two of the native names.
var PromptIDKeys = []string{
	"prompt.id",
	"beacon.prompt.id",
	"promptId",
	"prompt_id",
	"turn.id",
	"turn_id",
	"generation_id",
}

// PromptIDFrom reads the first prompt identifier in m under PromptIDKeys.
//
// Strings are trimmed. Integral numbers are accepted and rendered in base 10,
// because Kimi Code numbers its turns and a decoded JSON payload holds that as
// a float64. Anything else -- a fractional number, an object, a bool -- is not
// an identifier and is skipped.
func PromptIDFrom(m map[string]interface{}) string {
	for _, key := range PromptIDKeys {
		if id := identifierString(m[key]); id != "" {
			return id
		}
	}
	return ""
}

func identifierString(value interface{}) string {
	switch typed := value.(type) {
	case string:
		return strings.TrimSpace(typed)
	case float64:
		if typed == math.Trunc(typed) && !math.IsInf(typed, 0) && math.Abs(typed) < 1<<53 {
			return strconv.FormatInt(int64(typed), 10)
		}
	case int:
		return strconv.Itoa(typed)
	case int64:
		return strconv.FormatInt(typed, 10)
	case json.Number:
		if n, err := typed.Int64(); err == nil {
			return strconv.FormatInt(n, 10)
		}
	}
	return ""
}

// SetPromptID records the prompt an event belongs to, keeping any prompt text
// already on it. An empty id leaves the event alone.
func SetPromptID(event *Event, id string) {
	id = strings.TrimSpace(id)
	if event == nil || id == "" {
		return
	}
	if event.Prompt == nil {
		event.Prompt = &PromptInfo{}
	}
	event.Prompt.ID = id
}

// PromptID returns the prompt identifier recorded on an event.
func PromptID(event *Event) string {
	if event == nil || event.Prompt == nil {
		return ""
	}
	return strings.TrimSpace(event.Prompt.ID)
}

// eventIDNamespace is the fixed UUID namespace every Beacon event ID is derived
// under, so the same event derives the same UUID in any process and any
// release. It is an arbitrary constant, not a secret, and must never change:
// changing it renames every event ID Beacon has ever written.
var eventIDNamespace = [16]byte{
	0x1f, 0x4b, 0x2c, 0x8e, 0x6d, 0x3a, 0x5a, 0x7c,
	0x9b, 0x61, 0x3f, 0x0d, 0x5e, 0x8c, 0x2a, 0x14,
}

// EventIDForLine derives the deterministic identity of one serialized endpoint
// event whose event.id has not been set yet.
//
// Deterministic means the same event derives the same ID every time, in either
// capture path and in any later run. That is what makes an event addressable:
// re-reading a log, merging two reports of one action, or uploading a trace
// twice can all name the same event rather than guessing at it by position.
//
// Two identities are possible and the event decides which it gets:
//
//   - When the runtime named the action itself -- a tool call ID plus a
//     resolvable target -- the ID is derived from session, action, target and
//     call ID alone. Timestamps and content are deliberately excluded, so the
//     hook report and the OTLP report of one real action derive one ID even
//     though they are written seconds apart with different fields.
//   - Otherwise the ID is a digest of the event itself, which is unique to the
//     extent the event is. Two events that agree on every recorded byte,
//     including the timestamp, are indistinguishable in the log and get one ID;
//     a per-session sequence number would separate them, and when events carry
//     one this derivation picks it up for free.
//
// The writer does not suppress duplicates on this field. Equality under the
// content digest means "nothing recorded tells these apart", which is a weaker
// claim than "this is the same action" and not one to drop an event over. The
// call ID carries that claim, and duplicate suppression keys on it directly.
//
// line must be the event's JSON with event.id absent; passing a line that
// already carries one derives an ID for a different event than the caller
// meant, so callers marshal with the field empty and fill it afterwards.
func EventIDForLine(line []byte) string {
	var event map[string]interface{}
	if err := json.Unmarshal(line, &event); err != nil {
		// An event Beacon cannot parse is still an event Beacon is about to
		// write, so it gets a content identity rather than no identity.
		return eventUUID("content", string(line))
	}
	action := nestedString(event, "event", "action")
	callID := nestedString(event, "gen_ai", "tool", "call", "id")
	target := dedupeTarget(action, event)
	if callID != "" && target != "" {
		return eventUUID("call", strings.Join([]string{
			nestedString(event, "session", "id"),
			strings.ToLower(strings.TrimSpace(action)),
			target,
			callID,
		}, "\x00"))
	}
	return eventUUID("content", string(line))
}

// EventID is EventIDForLine over event serialized with event.id absent, without the round trip
// where it can be avoided. EventIDForLine parses the line back into a map to find the action, call
// id and target, which costs more than writing the line did; most events a call-keyed identity
// names (tool calls and results) are named by session, action, target and call id alone, and those
// fields are read from the struct here, as the serialized form would present them: invalid UTF-8
// replaced by U+FFFD byte by byte, and surrounding space trimmed. Any other event is marshaled
// and digested as EventIDForLine digests it.
//
// An event that does not serialize has no line to name; it gets a call identity when it has one
// and the empty string otherwise.
func EventID(event Event) string {
	action := jsonFieldString(event.Event.Action)
	var callID, session string
	if g := event.GenAI; g != nil && g.Tool != nil && g.Tool.Call != nil {
		callID = jsonFieldString(g.Tool.Call.ID)
	}
	if callID != "" {
		if target := eventDedupeTarget(action, &event); target != "" {
			if event.Session != nil {
				session = jsonFieldString(event.Session.ID)
			}
			return eventUUID("call", session+"\x00"+strings.ToLower(action)+"\x00"+target+"\x00"+callID)
		}
	}
	event.Event.ID = ""
	line, err := json.Marshal(event)
	if err != nil {
		return ""
	}
	return eventUUID("content", string(line))
}

// jsonFieldString is a string field as EventIDForLine reads it back from the serialized event.
// encoding/json writes each byte of invalid UTF-8 as U+FFFD, and nestedString trims.
func jsonFieldString(s string) string {
	if !utf8.ValidString(s) {
		var b strings.Builder
		b.Grow(len(s) + 8)
		for i := 0; i < len(s); {
			r, n := utf8.DecodeRuneInString(s[i:])
			if r == utf8.RuneError && n == 1 {
				b.WriteRune(utf8.RuneError)
			} else {
				b.WriteString(s[i : i+n])
			}
			i += n
		}
		s = b.String()
	}
	return strings.TrimSpace(s)
}

// eventDedupeTarget is dedupeTarget over the struct. action is already trimmed.
func eventDedupeTarget(action string, event *Event) string {
	str := jsonFieldString
	switch strings.ToLower(action) {
	case "mcp.tool_invoked":
		var server, tool, toolName string
		if event.MCP != nil {
			server, tool = str(event.MCP.Server), str(event.MCP.Tool)
		}
		if event.Tool != nil {
			toolName = str(event.Tool.Name)
		}
		return canonicalTarget("mcp", server, firstNonEmptyString(tool, toolName, str(event.Message)))
	case "command.executed":
		var command, toolCommand string
		if event.Command != nil {
			command = str(event.Command.Command)
		}
		if event.Tool != nil {
			toolCommand = str(event.Tool.Command)
		}
		return canonicalLiteralTarget("command", command, toolCommand)
	case "file.read", "file.modified":
		var path string
		if event.File != nil {
			path = str(event.File.Path)
		}
		return canonicalLiteralTarget("file", path)
	case "tool.completed":
		return canonicalTarget("tool.completed", str(event.Model), str(event.Message))
	case "tool.invoked", "tool.failed":
		var name, path string
		if event.Tool != nil {
			name, path = str(event.Tool.Name), str(event.Tool.Path)
		}
		return canonicalTarget("tool", name, path, str(event.Message))
	}
	return ""
}

// eventUUID renders a name under eventIDNamespace as an RFC 4122 version 5
// UUID. The kind prefix keeps the two identity modes in separate value spaces,
// so a content digest can never collide with a call identity.
//
// SHA-1 is what version 5 specifies. It is used here as a namespaced identifier
// function over data Beacon just wrote, never as a security boundary.
//
// The parts are streamed into the hash rather than concatenated into a sized
// buffer first. name is a whole serialized event, so sizing an allocation from
// its length is a computation on a value the event's own content decides -- and
// there is no reason to hold a second copy of the event in memory to hash it.
func eventUUID(kind, name string) string {
	digest := sha1.New()
	// hash.Hash.Write is documented never to return an error.
	digest.Write(eventIDNamespace[:])
	io.WriteString(digest, kind)
	io.WriteString(digest, name)
	var sum [sha1.Size]byte
	id := digest.Sum(sum[:0])[:16]
	id[6] = (id[6] & 0x0f) | 0x50 // version 5
	id[8] = (id[8] & 0x3f) | 0x80 // RFC 4122 variant
	var out [36]byte
	hex.Encode(out[0:8], id[0:4])
	out[8] = '-'
	hex.Encode(out[9:13], id[4:6])
	out[13] = '-'
	hex.Encode(out[14:18], id[6:8])
	out[18] = '-'
	hex.Encode(out[19:23], id[8:10])
	out[23] = '-'
	hex.Encode(out[24:36], id[10:16])
	return string(out[:])
}

// DerivedTraceIDForSession is the trace identity used by non-OTLP collection paths.
//
// OTLP spans already arrive with a provider trace id. Hook, plugin and poll paths usually do not,
// but they do carry the runtime session id that the dashboard already uses as the trace grouping
// key. Writing that grouping key into event.trace makes the event self-describing for consumers
// that do not know Beacon's dashboard fallback rules.
func DerivedTraceIDForSession(harnessName, sessionID string) string {
	sessionID = strings.TrimSpace(sessionID)
	if sessionID == "" {
		return ""
	}
	harness := NormalizeHarnessName(harnessName)
	if harness == "" {
		harness = strings.TrimSpace(harnessName)
	}
	if harness == "" {
		return "session:" + sessionID
	}
	return "session:" + harness + ":" + sessionID
}

// AttachDerivedTrace fills event.trace from the stable identities Beacon already promotes.
// Existing trace fields, such as OTLP trace/span ids, always win.
func AttachDerivedTrace(event *Event) {
	if event == nil || event.Session == nil {
		return
	}
	traceID := ""
	if event.Trace != nil {
		traceID = strings.TrimSpace(event.Trace.ID)
	}
	if traceID == "" {
		traceID = DerivedTraceIDForSession(event.Harness.Name, event.Session.ID)
	}
	if traceID == "" {
		return
	}
	if event.Trace == nil {
		event.Trace = &TraceInfo{}
	}
	if strings.TrimSpace(event.Trace.ID) == "" {
		event.Trace.ID = traceID
	}
	if strings.TrimSpace(event.Trace.SpanID) == "" {
		event.Trace.SpanID = ToolCallID(event)
	}
}

// ToolCallID returns the promoted runtime identifier for one tool invocation.
func ToolCallID(event *Event) string {
	if event == nil || event.GenAI == nil || event.GenAI.Tool == nil || event.GenAI.Tool.Call == nil {
		return ""
	}
	return strings.TrimSpace(event.GenAI.Tool.Call.ID)
}

// ContextUsedKeys and ContextLimitKeys are the names a runtime uses for how full the model's
// context was on a call, and for the window it was measured against.
//
// Promoted to gen_ai.context on every capture path from these lists, for the reason ToolCallIDKeys
// exists: a promotion list holding only a canonical name no runtime writes drops every real value
// into raw. A new runtime adds its spelling here rather than growing a branch in a mapper.
//
// Both must be present before either is promoted, which is not the usual alias-list rule and is
// deliberate. "input_tokens" is the name Qwen Code gives the context measure, and it is also the
// name half the ecosystem gives a genuine additive usage count -- so the key alone cannot say which
// it is. A reported context limit alongside it is what distinguishes a payload describing how full
// the window is from one reporting what a call spent. Without that pairing this list would quietly
// reclassify other runtimes' spend as context.
//
// The distinction matters because gen_ai.usage is additive and every report sums it, while context
// size is a level at one moment. Qwen is the case that proves it: its Stop payload's input_tokens
// is the prompt for that turn, which already contains every prior turn, so summing inflates a
// session by roughly the square of its length. The same number read as context occupancy is exact
// and useful -- 110100 of a 262144 window.
//
// Canonical names first, so an explicitly mapped value beats a runtime-native one.
var ContextUsedKeys = []string{
	"gen_ai.context.used_tokens",
	"beacon.gen_ai.context.used_tokens",
	// Qwen Code's Stop payload. Its sibling context_usage is this value divided by the limit, so
	// it is derivable and stays in raw rather than being stored twice in different units.
	"input_tokens",
	// Cursor's preCompact payload. Unambiguous on its own -- unlike input_tokens, nothing in the
	// ecosystem uses this name for an additive count -- but it still only promotes alongside a
	// limit, because the pairing rule is a property of the list rather than of any one key.
	"context_tokens",
}

// ContextLimitKeys names the context window a runtime reported for a call. A reported window beats
// the local model table in cli/beacon/internal/tokens, because it reflects the tier actually in
// force rather than the default for the model name. Its presence is also what licenses reading a
// used-token count from an ambiguous key; see ContextUsedKeys.
var ContextLimitKeys = []string{
	"gen_ai.context.limit_tokens",
	"beacon.gen_ai.context.limit_tokens",
	// Qwen Code's Stop payload.
	"context_limit",
	// Cursor's preCompact payload. Its context_usage_percent is this over the used count, so it
	// stays in raw for the reason Qwen's context_usage does.
	"context_window_size",
}