/** * Runtime-side utilities for recording model trajectories: the glue between raw * LLM/provider call sites and whichever trajectory-logger service is registered * (`services/trajectories`). Owns the LLM-call detail/purpose taxonomy, the * strict-mode guards that fail fast when a generative call happens outside a * trajectory step, and the wrappers that open child steps around actions, * providers, evaluators, and spawned sub-agents. * * `recordLlmCall` is the canonical entry point for raw SDK/fetch generation: it * times `fn`, derives the response text, and emits an llm-call entry against the * active step. Opt-in request scopes can also attest a pinned instruction on * those final provider inputs before quota is spent, returning only hashes and * counts. `withStandaloneTrajectory` / `withActionStep` / `withProviderStep` / * `withEvaluatorStep` establish the trajectory context those calls attach to; * `resolveTrajectoryLogger` picks the best-scoring logger service by capability. * * Also builds the context-object trajectory export (JSON-sanitized, cycle-safe) * and holds the process-global registry of trajectory `source` tags excluded * from training/optimization datasets. Strict enforcement is gated on * `ELIZA_TRAJECTORY_STRICT`; embeddings, tokenizers, and speech/media models are * exempt from the generative-call guards. */ import type { ContextEvent, ContextObject } from "./runtime/context-object.js"; import type { TrajectoryProviderAttribution } from "./runtime/trajectory-provider-attribution.js"; import type { TrajectorySkillInvocationRecord } from "./services/trajectory-types.js"; import type { ActionResult } from "./types/components.js"; import type { IAgentRuntime } from "./types/runtime.js"; import { type ContextObjectTrajectoryExport, type JsonValue, type Trajectory } from "./types/trajectory-export.js"; export type TrajectoryFinalStatus = "completed" | "error" | "timeout" | "terminated"; export declare const TRAJECTORY_LLM_PURPOSES: readonly ["planner", "action", "provider", "evaluator", "background", "external_llm", "optimizer"]; export type TrajectoryLlmPurpose = (typeof TRAJECTORY_LLM_PURPOSES)[number]; export type TrajectoryLlmCallDetails = { runId?: string; roomId?: string; messageId?: string; executionTraceId?: string; model: string; modelVersion?: string; modelType?: string; provider?: string; systemPrompt: string; userPrompt: string; prompt?: string; messages?: unknown[]; tools?: unknown; toolChoice?: unknown; output?: unknown; responseSchema?: unknown; providerOptions?: unknown; response: string; toolCalls?: unknown[]; finishReason?: string; providerMetadata?: unknown; reasoning?: string; temperature?: number; maxTokens?: number; maxTokensOmitted?: boolean; /** * High-level model-call category. Prefer the canonical taxonomy in * {@link TRAJECTORY_LLM_PURPOSES}; custom strings remain accepted for * compatibility with older trajectory rows. */ purpose: string; /** * Precise call-site label, e.g. `runtime.useModel`, `ai.generateText`, * or `openai.chat.completions.create`. */ actionType?: string; latencyMs?: number; promptTokens?: number; completionTokens?: number; cacheReadInputTokens?: number; cacheCreationInputTokens?: number; reasoningTokens?: number; providerOrder?: string[]; providerAttributions?: TrajectoryProviderAttribution[]; }; export type TrajectoryProviderAccessParams = { stepId: string; providerName: string; startedAt?: number; endedAt?: number; durationMs?: number; overlapsWith?: Array<{ providerName: string; overlapMs: number; }>; data: Record; sha256?: string; tokenCount?: number; position?: number; spanStart?: number; spanEnd?: number; purpose: string; query?: Record; runId?: string; roomId?: string; messageId?: string; executionTraceId?: string; }; export type TrajectoryProviderAccessLogger = { logProviderAccess: (params: TrajectoryProviderAccessParams) => void; }; export type TrajectoryRuntimeLlmCallParams = { stepId: string; modelSlot?: string; runId?: string; roomId?: string; messageId?: string; executionTraceId?: string; providerOrder?: string[]; providerAttributions?: TrajectoryProviderAttribution[]; } & TrajectoryLlmCallDetails; export type TrajectoryRuntimeLlmCallLogger = { logLlmCall: (params: TrajectoryRuntimeLlmCallParams) => void; }; /** * Caller-supplied portion of {@link TrajectoryLlmCallDetails} for * {@link recordLlmCall}. The helper measures `latencyMs` itself and * derives `response` from the function's return value. */ export type RecordLlmCallDetails = Omit & { /** Optional override for the recorded response string. */ response?: string; }; /** * Content-free proof that every final provider input in one request contained * an expected instruction exactly once. The raw instruction exists only in * the request-scoped collector and is never returned in this summary. */ export interface LlmInputSubstringAttestation { schemaVersion: 1; expectedSha256: string; modelCallCount: number; matchingCallCount: number; totalOccurrences: number; exactOncePerModelCall: boolean; modelTypeCallCounts: Record; } /** * Trajectory-shaped input for context-object export: either a slice of the * canonical {@link Trajectory} type or a loosely-typed detail/DB row * (`Record` metadata/metrics) used by trajectory services. */ export type ContextObjectTrajectoryExportTrajectoryInput = Partial> | { trajectoryId?: string; agentId?: string; source?: string; status?: string; startTime?: number; endTime?: number; durationMs?: number; metadata?: Record; metrics?: Record; }; export type ContextObjectTrajectoryExportInput = { trajectory?: ContextObjectTrajectoryExportTrajectoryInput | null; contextObject?: ContextObject | null; events?: readonly ContextEvent[]; trajectoryId?: string; agentId?: string; contextObjectId?: string; createdAt?: number; source?: string; metadata?: Record; metrics?: Record; }; export declare function extractContextObjectFromTrajectory(trajectory: unknown): ContextObject | null; export declare function extractContextEventsFromTrajectory(trajectory: unknown): ContextEvent[] | null; export declare function buildContextObjectTrajectoryExport(input: ContextObjectTrajectoryExportInput): ContextObjectTrajectoryExport; export declare function serializeContextObjectTrajectoryExport(input: ContextObjectTrajectoryExportInput, space?: number): string; type TrajectoryStartOptions = { source?: string; metadata?: Record; }; type TrajectoryStepState = { timestamp: number; agentBalance?: number; agentPoints?: number; agentPnL?: number; openPositions?: number; kind?: "llm" | "action" | "evaluator"; parentStepId?: string; evaluatorName?: string; }; type TrajectoryStepKindLike = "llm" | "action"; export type TrajectoryAnnotateParams = { stepId: string; kind?: TrajectoryStepKindLike; script?: string; childSteps?: string[]; appendChildSteps?: string[]; usedSkills?: string[]; /** * Per-skill invocation records with arguments, result, duration, success, and invocation * identity. */ appendSkillInvocations?: TrajectorySkillInvocationRecord[]; }; type TrajectoryLoggerLike = { isEnabled?: () => boolean; startTrajectory?: (agentId: string, options?: TrajectoryStartOptions) => Promise | string; startStep?: (trajectoryId: string, state: TrajectoryStepState) => string; completeStep?: (trajectoryId: string, stepId: string, action: { actionType: string; actionName: string; parameters: Record; success: boolean; result?: Record; error?: string; }) => void; endTrajectory?: (stepIdOrTrajectoryId: string, status?: TrajectoryFinalStatus, finalMetrics?: Record) => Promise | void; releaseTrajectoryOwnership?: (stepIdOrTrajectoryId: string) => void; flushWriteQueue?: (trajectoryId: string) => Promise | void; applyReward?: (params: { trajectoryId: string; idempotencyKey: string; reward: number; component: string; }) => Promise; logLlmCall?: (params: { stepId: string; } & TrajectoryLlmCallDetails) => void; /** * Optional. When implemented (DatabaseTrajectoryLogger does), lets a caller * extend an existing step row with the new schema fields (kind, script, * childSteps, usedSkills) without depending directly on @elizaos/agent. */ annotateStep?: (params: TrajectoryAnnotateParams) => Promise | void; }; type StandaloneTrajectoryOptions = { /** Defer capture writes until an actual model invocation in this task. */ deferUntilModelCall?: boolean; source: string; metadata?: Record; successStatus?: TrajectoryFinalStatus; errorStatus?: Exclude; }; type TrajectoryLlmGuardContext = { model?: string; modelType?: string; purpose?: string; actionType?: string; }; /** * Verify one final provider attempt against the active request scope. * * Provider retry loops call this before every transport attempt with the same * details object. Every attempt is rechecked, while the returned summary counts * that stable object once so its model-call totals retain logical-call parity * with usage telemetry. */ export declare function attestLlmInputSubstring(details: RecordLlmCallDetails): void; /** * Run one request under exact final-model-input attestation. * * Each nested {@link recordLlmCall} must carry the expected text exactly once * across its actual wire-bearing system/messages or system/prompt surfaces. * A mismatch throws before the provider callback runs, and a request that * reaches no model boundary fails when the scope closes. */ export declare function runWithLlmInputSubstringAttestation(expectedText: string, fn: () => Promise | T): Promise<{ result: T; attestation: LlmInputSubstringAttestation; }>; export declare function isTrajectoryStrictModeEnabled(): boolean; export declare function normalizeTrajectoryLlmPurpose(value: string | null | undefined, fallback?: TrajectoryLlmPurpose): TrajectoryLlmPurpose; /** * Return true for model slots that are expected to produce generative LLM * output. Embeddings, tokenizers, and speech/transcription/media models are * intentionally excluded from strict trajectory enforcement. */ export declare function isLlmGenerationModelType(modelType: unknown): boolean; /** * Strict-mode assertion for any generative LLM call. In normal mode this * returns immediately. With `ELIZA_TRAJECTORY_STRICT=1`, it throws unless a * trajectory step is active. */ export declare function assertActiveTrajectoryForLlmCall(context?: TrajectoryLlmGuardContext): string | null; /** * Strict-mode assertion for low-level raw SDK/fetch shims. Use this in tests * or thin adapters that cannot directly call {@link recordLlmCall}; canonical * raw generation call sites should still wrap the SDK call in * {@link recordLlmCall}. */ export declare function assertRecordedLlmCall(context?: TrajectoryLlmGuardContext): void; /** * Mutable per-call recording state. Exported so callers can hold the live * reference and read `.recorded` at the actual suppression decision point. */ export type ModelCallRecordingState = { recorded: boolean; }; /** * Open a request-local recording scope around a single `useModel()` call. * * Returns the live mutable store so the caller can read `.recorded` at the * actual decision point — which may be AFTER streaming completes. * * For deferred-streaming providers (e.g. plugin-xai grok.ts), the handler * returns a TextStreamResult immediately, but `recordLlmCall` only resolves * when the stream is fully consumed. The mutable store reflects late-arriving * marks because `markProviderRecordedCall` mutates the same object reference. * * Each call gets its own store via AsyncLocalStorage semantics, so concurrent * `useModel()` calls cannot suppress one another. */ export declare function runWithModelCallRecordingScope(fn: () => Promise | T): Promise<{ result: T; recordingState: ModelCallRecordingState; }>; /** * Re-enter the recording scope for a given recordingState, typically to * consume a deferred stream whose provider finalizer calls * `markProviderRecordedCall()`. Async generators do not retain * AsyncLocalStorage context from their creation, so we must re-establish the * scope around stream consumption. */ export declare function runInModelCallRecordingScope(recordingState: ModelCallRecordingState, fn: () => T | Promise): T | Promise; /** * Mark the current model call as already recorded by the provider-level wire * recorder. Called from `logActiveTrajectoryLlmCall` (the single chokepoint * for all provider trajectory logging) when the log succeeds. */ export declare function markProviderRecordedCall(): void; /** * Returns `true` when the current model call has already been recorded by the * provider-level wire recorder, so the generic `useModel` fallback can skip. */ export declare function isProviderRecordedCall(): boolean; /** * The most capable registered trajectory logger. Runs on every model call, so * it scores candidates in place; a candidate seen twice scores the same and * never displaces the first (strictly-greater wins). */ export declare function resolveTrajectoryLogger(runtime: IAgentRuntime): TrajectoryLoggerLike | null; /** * Start the active scope's deferred child step (see `withProviderStep`) at its * first model capture, so the call is recorded on that child, not the parent. */ export declare function activateDeferredChildStep(): void; /** * Before invoking a model provider, start the deferred child step and activate * an inherited task capture. The task capture is never activated at the * synchronous sink. */ export declare function ensureTaskTrajectory(): Promise; export declare function withStandaloneTrajectory(runtime: IAgentRuntime | null | undefined, options: StandaloneTrajectoryOptions, callback: () => Promise | T): Promise; /** * Annotate a trajectory step via whichever trajectory logger service is * registered on the runtime. Returns true when an annotate-capable service * was found and called; false when no compatible service exists or it is * disabled. Errors from the underlying service are propagated. */ export declare function annotateActiveTrajectoryStep(runtime: IAgentRuntime | null | undefined, params: TrajectoryAnnotateParams): Promise; export declare function logActiveTrajectoryLlmCall(runtime: IAgentRuntime | null | undefined, details: TrajectoryLlmCallDetails): boolean; export declare function recordLlmCall(runtime: IAgentRuntime | null | undefined, details: RecordLlmCallDetails, fn: () => Promise | T): Promise; /** * Wrap an action handler invocation in a child trajectory step linked to the * currently-active parent step. Model calls inside `fn` are recorded against * the new child step rather than the parent. * * Transparent: when no trajectory is active, `fn` runs unchanged and no * step is created. */ export declare function withActionStep(runtime: IAgentRuntime | null | undefined, actionName: string, fn: () => Promise | T, options?: { parameters?: Record; projectResult?: (result: T) => ActionResult; }): Promise; /** * Same as {@link withActionStep} but for provider rendering. */ export declare function withProviderStep(runtime: IAgentRuntime | null | undefined, providerName: string, fn: () => Promise | T): Promise; /** * Same as {@link withActionStep} but for evaluator turns. The child lifecycle * carries evaluator identity before nested model calls are captured, so reloads * do not need to infer ownership from prompt purpose. */ export declare function withEvaluatorStep(runtime: IAgentRuntime | null | undefined, evaluatorName: string, fn: () => Promise | T): Promise; export type SpawnTrajectoryHandle = { /** The currently-active step id at spawn time, if any. */ parentStepId: string | undefined; /** * Annotate the parent step with a freshly-known child step id (e.g. one * the spawned coding agent reports back over the bridge). No-op when no * parent step was active at spawn time. */ linkChild: (childStepId: string) => Promise; }; /** * Helper for spawn paths (orchestrator / app-control / workbench coding agents) * that produces a parent-stepId-aware handle. The fn is run inside the current * trajectory context so any inline LLM calls during the spawn dispatch are * still parent-attributed; the returned handle lets the caller link * later-discovered child step ids back onto the parent. */ export declare function spawnWithTrajectoryLink(runtime: IAgentRuntime | null | undefined, _options: { source?: string; metadata?: Record; } | undefined, fn: (handle: SpawnTrajectoryHandle) => Promise | T): Promise; /** * Single source-of-truth registry for trajectory "source" tags whose * trajectories must be excluded from training / optimization datasets. * * Bench-eval harnesses, optimizer self-judge calls, etc. register themselves * once at module load: * * registerTrajectorySource("plugin-action-bench", {excludeFromTraining: true}); * * Then any pipeline that reads trajectories before training (the privacy * filter / nightly export / on-demand orchestrator) checks * `isExcludedFromTraining(row.source)` and drops the row. */ type TrajectorySourceMeta = { excludeFromTraining: boolean; }; export declare function registerTrajectorySource(name: string, opts: TrajectorySourceMeta): void; export declare function isExcludedFromTraining(sourceName: string | null | undefined): boolean; export {};