/** Generic trajectory contracts and value projection. File persistence is assistant-owned. */ import { type ToolDiagnosticTextRedactor } from "../security/tool-diagnostics.js"; import type { RecordedStageKind } from "../services/trajectory-semantic-stage.js"; import type { EvaluationResult } from "../types/components.js"; import type { ChatMessage, GenerateTextResult, ToolChoice } from "../types/model.js"; import { type TrajectoryProviderAttribution } from "./trajectory-provider-attribution.js"; export { RECORDED_STAGE_KINDS, type RecordedStageKind, } from "../services/trajectory-semantic-stage.js"; export interface RecordedUsage { promptTokens?: number; completionTokens?: number; cacheReadInputTokens?: number; cacheCreationInputTokens?: number; reasoningTokens?: number; totalTokens?: number; } export interface RecordedToolCall { id?: string; name?: string; args?: Record; } export interface RecordedModelCall { modelType: string; modelName?: string; provider?: string; prompt?: string; messages?: ChatMessage[] | unknown[]; tools?: unknown; toolChoice?: ToolChoice | unknown; providerOptions?: unknown; response: string; /** Complete private/visible provider content parts, separate from user-facing text. */ responseContent?: GenerateTextResult["content"]; toolCalls?: RecordedToolCall[]; usage?: RecordedUsage; finishReason?: string; /** * USD cost of this LLM call computed from the price table identified by * `priceTableId`. Local-inference providers (Ollama / LM Studio / * llama.cpp) record a real `0` — not "missing". The recorder emits a * warning log when a hosted-provider model has no price entry and omits the * field so unknown spend cannot be mistaken for free inference. */ costUsd?: number; /** Price-table snapshot identifier used to compute costUsd. */ priceTableId?: string; /** Provider order selected for the composeState call that fed this model input. */ providerOrder?: string[]; /** * Hash-first provider contributions. No provider text is duplicated: when * `spanStart`/`spanEnd` are present they index into the flattened form of the * persisted `messages` (`flattenTrajectoryMessages(messages)`), derived once * at read time — consumers slice that to verify exact provenance rather than a * second stored copy of the prompt. */ providerAttributions?: TrajectoryProviderAttribution[]; } /** Loss marker in persisted trajectory rows. */ export interface RecordedTruncationMarker { field: "input" | "output" | "error" | "args" | "result"; originalBytes: number; capBytes: number; } export interface RecordedToolStage { name: string; args: Record; result: unknown; success: boolean; durationMs: number; /** * The model-facing tool description the planner was shown for this action — * i.e. the exposed `ToolDefinition.description`, which is the action's * `routingHint` (its "use when / do NOT use when" guidance) prepended to the * compressed description. Captured so a trajectory reviewer or training * pipeline can see WHAT the action was for — and judge whether the planner * had enough to disambiguate it — directly from the execution record, without * cross-referencing the preceding planner stage's `model.tools`. */ description?: string; error?: string; /** Complete action-handler input, encoded as JSON when possible. */ input?: string; /** * Captured action-handler output (the full result the action returned, * not just the planner-shaped summary). */ output?: string; /** * Captured action-handler error text. * Mirrors `error` for free-text reads; structured `error` above is kept * for backwards compatibility with existing readers. */ errorText?: string; /** Loss markers in imported rows; captures preserve complete input. */ truncated?: RecordedTruncationMarker[]; } /** * Per-stage retrieval entry captured when measurement mode is on. One * entry per (action, stage) pair, recorded BEFORE reciprocal-rank-fusion * so the funnel analyzer can see what each individual stage produced. */ export interface RecordedRetrievalStageEntry { actionName: string; score: number; rank: number; } /** * Per-stage retrieval scores captured under `ELIZA_RETRIEVAL_MEASUREMENT=1`. * Default `undefined` — no perf cost in production unless the env var is * explicitly enabled. */ export interface RecordedRetrievalPerStageScores { exact: RecordedRetrievalStageEntry[]; regex: RecordedRetrievalStageEntry[]; keyword: RecordedRetrievalStageEntry[]; bm25: RecordedRetrievalStageEntry[]; embedding: RecordedRetrievalStageEntry[]; contextMatch: RecordedRetrievalStageEntry[]; } /** * Snapshot of the tool-search / action-retrieval phase. Logged once per * planner turn before the LLM call so reviewers can see which actions * were considered, the retrieval scores, and which tier each landed in. */ export interface RecordedToolSearchStage { query: { text: string; tokens?: string[]; candidateActions?: string[]; parentActionHints?: string[]; }; results: Array<{ name: string; score: number; rank: number; rrfScore?: number; matchedBy?: string[]; stageScores?: Record; }>; tier: { tierA: string[]; tierB: string[]; omitted: number; }; durationMs: number; fallback?: string; /** * Per-stage retrieval funnel. Populated only when the retrieval call * ran with measurement mode on (`ELIZA_RETRIEVAL_MEASUREMENT=1`). */ perStageScores?: RecordedRetrievalPerStageScores; /** * Top-K fused (RRF) results. Mirrors `results` but exposes the raw * `rrfScore` field directly so downstream analyzers don't need to * unify the two shapes. Populated only under measurement mode. */ fusedTopK?: Array<{ actionName: string; rrfScore: number; rank: number; }>; /** * Actions the planner ultimately invoked this turn. Recorded by the * caller after the planner loop resolves — the retrieval call itself * does not know which results were selected. */ selectedActions?: string[]; /** * Ground-truth actions for this scenario, when available. Sourced from * the scenario manifest by the benchmark harness; never inferred from * the trajectory. */ correctActions?: string[]; } export interface RecordedEvaluationStage extends EvaluationResult { protocolFailure?: true; [key: string]: unknown; } /** * Snapshot of the facts/relationships extraction stage. Logged whenever * Stage 1 emits a non-empty `extract` and the dedup/persist pass runs in * parallel with the planner. Lets reviewers see (a) what the model thought * was worth keeping vs. dropping, and (b) what actually persisted. */ export interface RecordedFactsAndRelationshipsStage { candidates: { facts: string[]; relationships: Array<{ subject: string; predicate: string; object: string; }>; }; kept: { facts: string[]; relationships: Array<{ subject: string; predicate: string; object: string; }>; }; written: { facts: number; relationships: number; }; thought: string; /** Mirrors the gated evaluation stage: a deterministic gate answered without a model call. */ llmCallSkipped?: boolean; reason?: string; } export interface RecordedCacheStage { segmentHashes: string[]; prefixHash: string; diffFromPriorStage?: { added: number; unchanged: number; removed: number; }; } export interface RecordedStage { stageId: string; kind: RecordedStageKind; iteration?: number; retryIdx?: number; parentStageId?: string; startedAt: number; endedAt: number; latencyMs: number; model?: RecordedModelCall; tool?: RecordedToolStage; toolSearch?: RecordedToolSearchStage; evaluation?: RecordedEvaluationStage; cache?: RecordedCacheStage; factsAndRelationships?: RecordedFactsAndRelationshipsStage; } export interface RecordedTrajectoryMetrics { totalLatencyMs: number; totalPromptTokens: number; totalCompletionTokens: number; totalCacheReadTokens: number; totalCacheCreationTokens: number; totalReasoningTokens?: number; totalCostUsd: number; plannerIterations: number; toolCallsExecuted: number; toolCallFailures: number; toolSearchCount: number; evaluatorFailures: number; finalDecision?: "FINISH" | "CONTINUE" | "max_iterations" | "error"; } export interface RecordedTrajectory { trajectoryId: string; agentId: string; roomId?: string; runId?: string; scenarioId?: string; traceId?: string; taskId?: string; sessionId?: string; parentStepId?: string; codingActionProfile?: { kind: "pi"; includeWorktree: boolean; }; rootMessage: { id: string; text: string; sender?: string; }; startedAt: number; endedAt?: number; status: "running" | "finished" | "errored"; stages: RecordedStage[]; metrics: RecordedTrajectoryMetrics; } export interface StartTrajectoryInput { agentId: string; roomId?: string; rootMessage: { id: string; text: string; sender?: string; }; runId?: string; scenarioId?: string; traceId?: string; taskId?: string; sessionId?: string; parentStepId?: string; /** Normalized trusted coding policy selected for this recorded turn. */ codingActionProfile?: { kind: "pi"; includeWorktree: boolean; }; } export interface ListTrajectoriesOptions { agentId?: string; since?: number; limit?: number; } export interface TrajectoryRecorder { startTrajectory(input: StartTrajectoryInput): string; recordStage(trajectoryId: string, stage: RecordedStage): Promise; endTrajectory(trajectoryId: string, status: "finished" | "errored"): Promise; load(trajectoryId: string): Promise; list(opts?: ListTrajectoriesOptions): Promise; } export interface RecorderLogger { warn?: (context: unknown, message?: string) => void; debug?: (context: unknown, message?: string) => void; error?: (context: unknown, message?: string) => void; } /** Uses the shared trajectory-persistence gate for file recording. */ export declare function isTrajectoryRecordingEnabled(): boolean; export declare function cloneTrajectoryValue(value: T): T; /** * Encode an arbitrary value to a JSON string for trajectory persistence. * Strings pass through unchanged; everything else is sanitized (handles * Error, Date, bigint, circular refs) and serialized. */ export declare function encodeTrajectoryFieldValue(value: unknown): string; export interface ToolStageIOInput { input?: unknown; output?: unknown; error?: unknown; } export interface ToolStageIOCapture { input?: string; output?: string; errorText?: string; } /** * Encode complete action input/output/error for a tool stage. The result is * suitable for assignment into a `RecordedToolStage`. Fields that are * `undefined` after encoding are omitted so the on-disk schema stays * minimal for steps that have nothing to capture. */ export declare function captureToolStageIO(args: ToolStageIOInput): ToolStageIOCapture; /** * Final-persistence projection of tool-call diagnostics for one recorded * stage. Every recordStage caller (planner, sub-planner, evaluator, message * handler, and any future generic caller) is protected here rather than at * its own call site: tool arguments, tool result/error, captured tool I/O, * and model-stage tool-call arguments are projected through the composed * redaction before the stage reaches disk. Mutates the (already cloned) stage * in place. Model prompt/message text is projected as well; when message bytes * change, provider-attribution offsets are dropped through the canonical * fallback so they never index text different from the persisted messages. */ export declare function projectRecordedStageToolDiagnostics(stage: RecordedStage, redactText: ToolDiagnosticTextRedactor): void; export interface FinalizeTrajectoryRecordingOptions { recorder: TrajectoryRecorder; trajectoryId: string; status: "finished" | "errored"; logger?: RecorderLogger; reportError?: (scope: string, error: unknown, context?: Record) => void; } /** * Lifecycle guard: every started trajectory must reach a terminal status. * * Writes the terminal status without depending on optional background work. * Callers record already-settled stages before entering this boundary; a * diagnostic task may never keep a completed turn visibly `running`. */ export declare function finalizeTrajectoryRecording(opts: FinalizeTrajectoryRecordingOptions): Promise;