trajectory

package
v2.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 15, 2026 License: MIT Imports: 27 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package trajectory derives causal evaluation steps from self-contained run records.

Index

Constants

View Source
const SchemaVersion = "loom.trajectory.v1"

SchemaVersion identifies the trajectory document's field and meaning contract.

Variables

View Source
var (
	// ErrNotTerminal means the requested run or one of its linked children is unsealed.
	ErrNotTerminal = errors.New("trajectory: run is not terminal")
)

Functions

func EncodeDocument

func EncodeDocument(t *Trajectory) ([]byte, error)

EncodeDocument encodes one trajectory using the canonical callrecord codec.

func EncodeSessionDocument

func EncodeSessionDocument(s Session) ([]byte, error)

EncodeSessionDocument encodes a caller-ordered session using the canonical codec.

func Schema

func Schema() []byte

Schema returns the embedded JSON Schema 2020-12 for trajectory documents.

Types

type AnswerStep

type AnswerStep struct {
	Kind    index.EntryKind `json:"kind"`
	InputID string          `json:"input_id,omitzero"`
	Content json.RawMessage `json:"content"`
}

AnswerStep preserves a complete clarification or typed-input answer. Content is a JSON string for clarification text or the exact stored JSON payload for typed input. It is encoded as a readable value, never base64. Invalid UTF-8 in clarification text is replaced with U+FFFD.

type Document

type Document struct {
	Schema     string      `json:"schema"`
	Trajectory *Trajectory `json:"trajectory,omitzero"`
	Session    Session     `json:"session,omitzero"`
}

Document wraps exactly one trajectory or session in a versioned JSON envelope.

type Format

type Format string

Format selects the human-readable rendering syntax.

const (
	// FormatText renders plain text with two-space child indentation.
	FormatText Format = "text"
	// FormatMarkdown renders nested lists, fenced JSON and safely fenced plain text.
	FormatMarkdown Format = "markdown"
)

type Limits

type Limits struct {
	MaxValueBytes int
	MaxSteps      int
	MaxDepth      int
}

Limits bounds individual rendered values, steps per run and child nesting. Each zero field disables that limit. The root run has depth zero.

func DefaultLimits

func DefaultLimits() Limits

DefaultLimits returns a 4096-byte value limit, 200 steps per run and depth 4.

type ModelStep

type ModelStep struct {
	Key           runstore.CallKey             `json:"key"`
	Class         runrecord.CallClass          `json:"class"`
	Activity      callrecord.ActivityKind      `json:"activity"`
	Step          int                          `json:"step"`
	Model         string                       `json:"model"`
	ModelID       string                       `json:"model_id"`
	Usage         model.TokenUsage             `json:"usage"`
	Latency       time.Duration                `json:"latency"`
	Error         *callrecord.CallError        `json:"error,omitzero"`
	Facts         *contextmeasure.RequestFacts `json:"facts,omitzero"`
	Chosen        []model.ToolCall             `json:"chosen"`
	SystemHash    runstore.Hash                `json:"system_hash"`
	ToolsHash     runstore.Hash                `json:"tools_hash"`
	RequestDigest runstore.Hash                `json:"request_digest"`
	Prompts       []prompt.PromptRef           `json:"prompts"`
}

ModelStep preserves one recorded invocation, including abandoned and open calls.

type ObservedEvent

type ObservedEvent struct {
	Type      hooks.EventType `json:"type"`
	EventKey  string          `json:"event_key"`
	Timestamp time.Time       `json:"timestamp"`
	Payload   rawjson.Message `json:"payload"`
}

ObservedEvent preserves a selected run-log payload without numeric coercion. Its containing Step owns the verification flag.

type Options

type Options struct {
	// Output, when present, supplies Final even if that field is nil.
	// It applies only to the requested run, not its linked children.
	Output *api.RunOutput `json:"output,omitzero"`
	// EventsUnverified marks observed steps and status as unverified.
	// Record-derived model, tool and answer steps remain verified.
	EventsUnverified bool `json:"events_unverified"`
}

Options supplies a caller's final output and observer-event trust boundary.

type RenderOptions

type RenderOptions struct {
	Format
	Limits
}

RenderOptions configures human-readable rendering; the zero format is text.

type Session

type Session []*Trajectory

Session preserves trajectories in the caller's run order.

func (Session) Marshal

func (s Session) Marshal() ([]byte, error)

Marshal returns deterministic JSON without changing the caller's run order.

func (Session) Render

func (s Session) Render(opts RenderOptions) string

Render returns runs in the session's caller-supplied order. It intentionally fails fast by panicking on nil Session or Children elements or unsupported final message Part types.

type Step

type Step struct {
	Kind     StepKind        `json:"kind"`
	Step     int             `json:"step"`
	EntryID  index.MessageID `json:"entry_id,omitzero"`
	Verified bool            `json:"verified"`
	Model    *ModelStep      `json:"model,omitzero"`
	Tool     *ToolStep       `json:"tool,omitzero"`
	Event    *ObservedEvent  `json:"event,omitzero"`
	Answer   *AnswerStep     `json:"answer,omitzero"`
}

Step is one model call, tool call, stored answer or observed event. Step is the planner schedule number; EntryID is zero for non-entry steps. Exactly one of Model, Tool, Event and Answer is populated.

type StepKind

type StepKind string

StepKind identifies the populated member of a Step.

const (
	// StepModel identifies a recorded model invocation.
	StepModel StepKind = "model"
	// StepTool identifies a stored tool invocation and its result.
	StepTool StepKind = "tool"
	// StepAwait identifies an observed await prompt.
	StepAwait StepKind = "await"
	// StepAnswer identifies a stored answer or observed tool authorization.
	StepAnswer StepKind = "answer"
	// StepEvent identifies another selected observer event.
	StepEvent StepKind = "event"
)

type ToolStep

type ToolStep struct {
	Name             tools.Ident        `json:"name"`
	ToolCallID       string             `json:"tool_call_id"`
	ParentToolCallID string             `json:"parent_tool_call_id,omitzero"`
	Arguments        rawjson.Message    `json:"arguments"`
	Result           rawjson.Message    `json:"result"`
	Bounds           *agent.Bounds      `json:"bounds,omitzero"`
	Error            *planner.ToolError `json:"error,omitzero"`
	Duration         time.Duration      `json:"duration"`
	Children         []*Trajectory      `json:"children"`
}

ToolStep joins an original stored call to its full result and linked children. Arguments are the planner's stored arguments before server injection. Result is absent when no result has been recorded. Children follow their owning call in canonical child-link order, regardless of completion order.

type Totals

type Totals struct {
	TokensByModel     map[string]model.TokenUsage `json:"tokens_by_model"`
	ModelCallsByClass map[runrecord.CallClass]int `json:"model_calls_by_class"`
	ModelCalls        int                         `json:"model_calls"`
	AdoptedModelCalls int                         `json:"adopted_model_calls"`
	ToolCalls         int                         `json:"tool_calls"`
	FailedToolCalls   int                         `json:"failed_tool_calls"`
	RepeatedToolCalls int                         `json:"repeated_tool_calls"`
	WallTime          time.Duration               `json:"wall_time"`
}

Totals counts only this run's recorded calls; children have their own totals. RepeatedToolCalls counts calls after the first with identical name and key-sorted arguments. WallTime spans first to last record-event timestamp.

type Trajectory

type Trajectory struct {
	// Pos and Prev preserve optional session continuation identity.
	Pos  int     `json:"pos,omitzero"`
	Prev *string `json:"prev,omitzero"`

	// TraceID optionally correlates the run with caller-owned distributed tracing.
	TraceID        string         `json:"trace_id,omitempty"`
	RunID          string         `json:"run_id"`
	SessionID      string         `json:"session_id"`
	AgentID        agent.Ident    `json:"agent_id"`
	Steps          []Step         `json:"steps"`
	Final          *model.Message `json:"final"`
	Status         string         `json:"status"`
	StatusVerified bool           `json:"status_verified"`
	Totals         Totals         `json:"totals"`
}

Trajectory contains one sealed run's causal steps and run-local totals.

func Build

func Build(rec *runrecord.RunRecord, runID string, opts Options) (*Trajectory, error)

Build derives a sealed run and its linked children from rec alone, without store access. It rejects inconsistent call/result joins and missing child records. Output overrides only the requested run's final answer; child answers come from records.

func (*Trajectory) Marshal

func (t *Trajectory) Marshal() ([]byte, error)

Marshal returns deterministic JSON with nanosecond durations and sorted objects.

func (*Trajectory) Render

func (t *Trajectory) Render(opts RenderOptions) string

Render returns the run's causal steps, linked children, final answer and totals. It intentionally fails fast by panicking on a nil trajectory, nil Children elements or unsupported final message Part types.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL