Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(eval): replay-based eval harness driving the real agent loop (P2.3)
Salman Qureshi87aff5f2155a
diff --git a/src/eval/env.ts b/src/eval/env.tsnew file mode 100644index 00000000..d452f9fa--- /dev/null+++ b/src/eval/env.ts@@ -0,0 +1,55 @@+/**+ * Eval environment bootstrap.+ *+ * MUST be the first import of every eval module: several core modules read+ * MERCURY_HOME at import time (permissions.yaml path, config .env loading),+ * so the scratch home has to exist before `../core/agent.js` is evaluated.+ * ES module evaluation follows import order, so `import './env.js'` at the+ * top of runner.ts is enough.+ *+ * Nothing here touches the network or the user's real ~/.mercury.+ */+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++if (!process.env.LOG_LEVEL) process.env.LOG_LEVEL = 'silent';+// The agent reads MERCURY_MAX_STEPS once at import (core/agent.ts). A small+// budget makes step-budget exhaustion cheap to replay; every other scripted+// turn uses far fewer steps than this.+if (!process.env.MERCURY_MAX_STEPS) process.env.MERCURY_MAX_STEPS = '6';++/** Root scratch directory for this process; every harness gets a home under it. */+export const EVAL_ROOT: string = mkdtempSync(join(tmpdir(), 'mercury-eval-'));+// The agent sends its system prompt as a leading system *message* (for+// Anthropic prompt caching) without `allowSystemInMessages: true`, so the AI+// SDK console.warns on every model call. Drop exactly that line here.+const SYSTEM_IN_MESSAGES_WARNING = 'AI SDK Warning: System messages in the prompt';+const originalWarn = console.warn.bind(console);+console.warn = (...args: unknown[]) => {+ if (typeof args[0] === 'string' && args[0].startsWith(SYSTEM_IN_MESSAGES_WARNING)) return;+ originalWarn(...args);+};++if (!process.env.MERCURY_HOME || !process.env.MERCURY_HOME.startsWith(EVAL_ROOT)) {+ process.env.MERCURY_HOME = join(EVAL_ROOT, 'home');+}+mkdirSync(process.env.MERCURY_HOME, { recursive: true });++/**+ * Point MERCURY_HOME at a fresh directory. Sessions, memory, the work+ * ledger, soul files and schedules all resolve `getMercuryHome()` at call+ * time, so each harness gets isolated state (permissions.yaml keeps the+ * first path — it is resolved at import — which is fine: it only holds the+ * default manifest).+ */+export function freshHome(label: string): string {+ mkdirSync(EVAL_ROOT, { recursive: true });+ const dir = mkdtempSync(join(EVAL_ROOT, `${label.replace(/[^a-z0-9-]/gi, '-').toLowerCase()}-`));+ process.env.MERCURY_HOME = dir;+ return dir;+}++export function removeEvalRoot(): void {+ rmSync(EVAL_ROOT, { recursive: true, force: true });+}diff --git a/src/eval/fixture.ts b/src/eval/fixture.tsnew file mode 100644index 00000000..0b29986f--- /dev/null+++ b/src/eval/fixture.ts@@ -0,0 +1,116 @@+/**+ * Replay fixture format (ROADMAP P2.3).+ *+ * A fixture is plain data: the conversation so far, the incoming message,+ * the programming mode, the scripted model steps (text or tool calls with+ * recorded results) and the expectations. The runner drives the REAL agent+ * loop with it — nothing in the loop is mocked except the model and the+ * tool outputs that were recorded.+ */+import type { ChannelType } from '../types/channel.js';++export interface ScriptedUsage {+ inputTokens?: number;+ outputTokens?: number;+ cachedInputTokens?: number;+}++export interface ScriptedToolCall {+ /** Tool name as registered in CapabilityRegistry (write_file, run_command, …). */+ tool: string;+ /** Must satisfy the real tool's input schema — the SDK validates it. */+ input: Record<string, unknown>;+ /**+ * Recorded tool output. When present the real tool is NOT executed and+ * this is returned verbatim; when absent the real tool runs in the+ * scenario's scratch cwd (auto-approved).+ */+ result?: unknown;+}++export type ScriptedStep =+ | { kind: 'text'; text: string; usage?: ScriptedUsage; finishReason?: 'stop' | 'length' }+ | { kind: 'tools'; calls: ScriptedToolCall[]; text?: string; usage?: ScriptedUsage };++export interface ScriptedProviderSpec {+ name: string;+ model?: string;+ /** The first N model calls to this provider throw `failWith`. */+ failFirst?: number;+ failWith?: string;+}++export interface FixtureHistoryEntry {+ role: 'user' | 'assistant';+ content: string;+ /** 'tool-call' seeds a prior-turn tool trace entry (see core/context-window.ts). */+ kind?: 'message' | 'tool-call';+}++export type PauseKind = 'steps' | 'work-not-started' | 'verification-failed';++export interface TurnExpectations {+ /** Number of persistent (delivered) messages, not status notices. */+ deliveredCount?: number;+ finalTextIncludes?: string[];+ finalTextExcludes?: string[];+ /** Must appear in SOME channel event (delivered or notice). */+ anyEventIncludes?: string[];+ /** Must appear in NO channel event. */+ noEventIncludes?: string[];+ providerCalls?: number;+ forcedActionRounds?: number;+ verificationRounds?: number;+ stepBudgetContinuations?: number;+ pause?: PauseKind | null;+ usedProvider?: string;+ /** Tool names that must have been invoked, in order of first use. */+ toolsUsed?: string[];+}++export interface ScenarioTurn {+ message: string;+ /** Scripted model output, consumed one step per model call. */+ steps?: ScriptedStep[];+ /** Supplies a step when the script runs out (e.g. endless tool loops). */+ onExhausted?: (callIndex: number) => ScriptedStep;+ /** Answer the agent gets from `askToContinue` prompts (default false). */+ askToContinue?: boolean;+ timeoutMs?: number;+ expect?: TurnExpectations;+}++export interface ScenarioFixture {+ name: string;+ channel?: {+ /** Default 'telegram' — exercises the messaging TaskSurface. */+ type?: ChannelType;+ /** 'messaging' implements the Telegram-style task/status-card contract. */+ style?: 'messaging' | 'plain';+ /** Streaming delivery (default true, matching the real Telegram default). */+ streaming?: boolean;+ id?: string;+ };+ programmingMode?: 'off' | 'plan' | 'execute';+ /** Default: one provider named 'scripted'. Order = fallback order. */+ providers?: ScriptedProviderSpec[];+ /** Seeded into the bound session before the first turn. */+ history?: FixtureHistoryEntry[];+ turns: ScenarioTurn[];+}++// ── Small builders so fixtures stay readable ────────────────────────────────++export function textStep(text: string, usage?: ScriptedUsage): ScriptedStep {+ return { kind: 'text', text, usage };+}++export function toolStep(calls: ScriptedToolCall[], text?: string, usage?: ScriptedUsage): ScriptedStep {+ return { kind: 'tools', calls, text, usage };+}++export function call(tool: string, input: Record<string, unknown>, result?: unknown): ScriptedToolCall {+ return { tool, input, result };+}++export const DEFAULT_USAGE: Required<ScriptedUsage> = { inputTokens: 120, outputTokens: 40, cachedInputTokens: 0 };diff --git a/src/eval/recording-channel.ts b/src/eval/recording-channel.tsnew file mode 100644index 00000000..997f9900--- /dev/null+++ b/src/eval/recording-channel.ts@@ -0,0 +1,206 @@+/**+ * RecordingChannel — captures everything the agent sends.+ *+ * Two styles:+ * - 'messaging' implements the Telegram-style task contract the agent's+ * TaskSurface duck-types (beginTask/endTask/popDeferredResponse/…): while+ * a task is active, short sends land in a status card (recorded as+ * `notice`, i.e. NOT a persistent message) and streamed answers are+ * deferred until the task ends. That is exactly the behaviour that used to+ * swallow pause banners, so a scenario can assert they are persistent.+ * - 'plain' delivers every send/stream as a persistent message.+ *+ * Every event carries a monotonic timestamp from the harness clock.+ */+import { BaseChannel } from '../channels/base.js';+import type { ChannelMessage, ChannelType } from '../types/channel.js';++export type ChannelEventKind =+ | 'delivered' // persistent message the user sees+ | 'notice' // status-card line (ephemeral on messaging channels)+ | 'deferred' // answer parked until the task ends+ | 'completion' // completion banner (sendCompletion)+ | 'prompt' // askToContinue question+ | 'file'+ | 'typing'+ | 'task-begin'+ | 'task-end';++export interface ChannelEvent {+ kind: ChannelEventKind;+ text: string;+ at: number;+ targetId?: string;+ /** Answer given to a prompt. */+ answer?: boolean;+}++const isStatusNotice = (content: string): boolean =>+ content.startsWith('☿ ') || content.startsWith('⚠') || content.startsWith(' [') || content.length < 200;++export class RecordingChannel extends BaseChannel {+ readonly events: ChannelEvent[] = [];+ /** Answer for askToContinue; set per turn by the runner. */+ continueAnswer = false;+ private readonly active = new Map<string, boolean>();+ private readonly deferred = new Map<string, string>();++ constructor(+ readonly type: ChannelType,+ readonly style: 'messaging' | 'plain',+ private readonly clock: () => number,+ ) {+ super();+ if (style === 'plain') {+ // Strip the messaging contract so TaskSurface picks its plain path.+ for (const name of ['beginTask', 'endTask', 'resetStepCounter', 'popDeferredResponse', 'deferResponse', 'cleanupEphemeralMessages', 'sendCompletion'] as const) {+ Object.defineProperty(this, name, { value: undefined });+ }+ }+ }++ private record(kind: ChannelEventKind, text: string, targetId?: string, extra: Partial<ChannelEvent> = {}): void {+ this.events.push({ kind, text, at: this.clock(), targetId, ...extra });+ }++ /** Simulate an inbound user message (goes through ChannelRegistry → Agent.enqueueMessage). */+ inject(message: ChannelMessage): void {+ this.emit(message);+ }++ async start(): Promise<void> {+ this.ready = true;+ }++ async stop(): Promise<void> {+ this.ready = false;+ }++ async send(content: string, targetId?: string): Promise<void> {+ const key = targetId ?? 'default';+ if (this.style === 'messaging' && this.active.get(key)) {+ if (!content.trim()) return;+ if (isStatusNotice(content)) this.record('notice', content, targetId);+ else {+ this.deferred.set(key, content);+ this.record('deferred', content, targetId);+ }+ return;+ }+ this.record('delivered', content, targetId);+ }++ async sendFile(filePath: string, targetId?: string): Promise<void> {+ this.record('file', filePath, targetId);+ }++ async stream(content: AsyncIterable<string>, targetId?: string): Promise<string> {+ let full = '';+ for await (const chunk of content) full += chunk;+ const key = targetId ?? 'default';+ if (this.style === 'messaging' && this.active.get(key)) {+ this.deferred.set(key, full);+ if (full) this.record('deferred', full, targetId);+ return full;+ }+ if (full) this.record('delivered', full, targetId);+ return full;+ }++ async typing(targetId?: string): Promise<void> {+ this.record('typing', '', targetId);+ }++ async askToContinue(question: string, targetId?: string): Promise<boolean> {+ this.record('prompt', question, targetId, { answer: this.continueAnswer });+ return this.continueAnswer;+ }++ // ── Messaging task contract (see core/task-surface.ts) ─────────────────────++ beginTask(targetId?: string): void {+ const key = targetId ?? 'default';+ this.active.set(key, true);+ this.deferred.delete(key);+ this.record('task-begin', '', targetId);+ }++ endTask(targetId?: string): void {+ const key = targetId ?? 'default';+ if (this.active.get(key)) this.record('task-end', '', targetId);+ this.active.set(key, false);+ }++ resetStepCounter(): void {}++ popDeferredResponse(targetId?: string): string | undefined {+ return this.deferred.get(targetId ?? 'default');+ }++ deferResponse(targetId: string | undefined, content: string): void {+ if (content.trim()) this.deferred.set(targetId ?? 'default', content);+ }++ async cleanupEphemeralMessages(): Promise<void> {}++ async sendCompletion(elapsedMs: number, stepCount: number, targetId?: string): Promise<void> {+ this.endTask(targetId);+ const deferred = this.deferred.get(targetId ?? 'default');+ if (deferred && deferred.trim()) await this.send(deferred, targetId);+ this.deferred.delete(targetId ?? 'default');+ this.record('completion', `Task complete · ${stepCount} steps · ${(elapsedMs / 1000).toFixed(1)}s`, targetId);+ }++ // ── Views ──────────────────────────────────────────────────────────────────++ since(index: number): ChannelEvent[] {+ return this.events.slice(index);+ }+}++/**+ * Minimal stand-in for ChannelRegistry: the real one always registers (and+ * on wake, starts) the Ink CLI channel, which must not render in tests.+ * Implements exactly the surface Agent uses.+ */+export class EvalChannelRegistry {+ private readonly channels = new Map<ChannelType, BaseChannel>();+ private incoming?: (msg: ChannelMessage) => void;++ register(type: ChannelType, channel: BaseChannel): void {+ channel.onMessage((msg) => this.incoming?.(msg));+ this.channels.set(type, channel);+ }++ get(type: ChannelType): BaseChannel | undefined {+ return this.channels.get(type);+ }++ getChannelForMessage(message: ChannelMessage): BaseChannel | undefined {+ return this.channels.get(message.channelType);+ }++ getCliChannel(): undefined {+ return undefined;+ }++ async startAll(): Promise<void> {+ for (const channel of this.channels.values()) await channel.start();+ }++ async stopAll(): Promise<void> {+ for (const channel of this.channels.values()) await channel.stop();+ }++ getActiveChannels(): ChannelType[] {+ return [...this.channels.entries()].filter(([, c]) => c.isReady()).map(([t]) => t);+ }++ getNotificationChannel(): BaseChannel | undefined {+ return this.channels.values().next().value;+ }++ onIncomingMessage(handler: (msg: ChannelMessage) => void): void {+ this.incoming = handler;+ }+}diff --git a/src/eval/runner.ts b/src/eval/runner.tsnew file mode 100644index 00000000..2ae41e16--- /dev/null+++ b/src/eval/runner.ts@@ -0,0 +1,489 @@+/**+ * runScenario — drive the REAL agent loop with a fixture.+ *+ * Construction mirrors src/index.ts (Agent + ProviderRegistry ++ * CapabilityRegistry + SessionRepository + memory stores) with three+ * substitutions only:+ * - providers are ScriptedProviders (MockLanguageModelV3 playback),+ * - the channel is a RecordingChannel behind a minimal channel registry+ * (the real ChannelRegistry always starts the Ink CLI),+ * - tool `execute` returns the fixture's recorded result when one exists.+ * Messages enter through the channel → registry → Agent.enqueueMessage →+ * processQueue → handleMessage, the production path.+ */+import './env.js';+import { freshHome } from './env.js';+import { mkdirSync } from 'node:fs';+import { join } from 'node:path';+import { performance } from 'node:perf_hooks';+import { vi } from 'vitest';+import type { Tool } from 'ai';+import { Agent } from '../core/agent.js';+import { CapabilityRegistry, type ChatCommandContext } from '../capabilities/registry.js';+import { ProviderRegistry } from '../providers/registry.js';+import { Identity } from '../soul/identity.js';+import { ShortTermMemory, LongTermMemory, EpisodicMemory } from '../memory/store.js';+import { TokenBudget } from '../utils/tokens.js';+import { Scheduler } from '../core/scheduler.js';+import { SessionRepository } from '../sessions/repository.js';+import type { SessionMessage } from '../sessions/types.js';+import { getDefaultConfig, type MercuryConfig } from '../utils/config.js';+import { STEPS_PAUSED_BANNER, VERIFICATION_FAILED_BANNER, WORK_NOT_STARTED_BANNER } from '../core/completion-verdict.js';+import type { ChannelMessage, ChannelType } from '../types/channel.js';+import type { ChannelRegistry } from '../channels/registry.js';+import type { PauseKind, ScenarioFixture, ScenarioTurn, ScriptedProviderSpec, TurnExpectations } from './fixture.js';+import { promptText, ScriptPlayer, type ProviderCallRecord } from './script-player.js';+import { ScriptedProvider } from './scripted-provider.js';+import { EvalChannelRegistry, RecordingChannel, type ChannelEvent } from './recording-channel.js';++export interface ToolCallRecord {+ id: string;+ tool: string;+ input: unknown;+ output: unknown;+ /** true = fixture-recorded output; false = the real tool ran. */+ recorded: boolean;+}++export interface GuardDecisions {+ /** Execute-mode narration guard rounds (toolChoice forced). */+ forcedActionRounds: number;+ wakeUpCalls: number;+ verificationRounds: number;+ stepBudgetContinuations: number;+ /** Model calls the loop forced to start with a tool (toolChoice: required). */+ forcedToolChoiceCalls: number;+ pause: PauseKind | null;+ /** "⚠ provider: … switching to …" / "served by" lines. */+ providerNotices: string[];+}++export interface StepTiming {+ index: number;+ provider: string;+ /** ms since the message was injected. */+ startMs: number;+ /** Until the next model call starts (or delivery): model + tool time. */+ durationMs: number;+ error?: string;+}++export interface PhaseTimings {+ /** Inject → first provider call: history, memory, prompt build. */+ promptBuildMs: number;+ steps: StepTiming[];+ /** Last model call start → final persistent delivery. */+ deliveryMs: number;+ totalMs: number;+}++export interface TurnResult {+ message: string;+ /** Last persistent message of the turn (answer, pause or failure). */+ finalText: string;+ /** Persistent messages, in order. */+ delivered: string[];+ /** Status-card / ephemeral lines. */+ notices: string[];+ events: ChannelEvent[];+ prompts: Array<{ question: string; answer?: boolean }>;+ providerCalls: ProviderCallRecord[];+ toolCalls: ToolCallRecord[];+ guard: GuardDecisions;+ timings: PhaseTimings;+ /** Session entries written during this turn. */+ sessionEntries: SessionMessage[];+ tokens: { input: number; output: number; cached: number };+ usedProvider: string | null;+ traceId: string | null;+ scriptExhausted: boolean;+ /** Expectation failures (empty = pass). */+ failures: string[];+}++export interface ScenarioResult {+ name: string;+ turns: TurnResult[];+ failures: string[];+ /** Kept for post-hoc inspection (e.g. renderTrace); disposed already. */+ sessions: SessionRepository;+ workDir: string;+}++export interface RunOptions {+ /** Fake setTimeout/setInterval for the run (default true): heartbeats, the+ * memory guard, stall watchdog and provider deadlines never fire mid-turn. */+ fakeTimers?: boolean;+}++const DEFAULT_TURN_TIMEOUT_MS = 15_000;+const clock = (): number => performance.now();++class EvalCapabilityRegistry extends CapabilityRegistry {+ player?: ScriptPlayer;+ readonly toolLog: ToolCallRecord[] = [];+ private readonly wrapped = new WeakMap<Tool, Tool>();++ private wrapAll(tools: Record<string, Tool>): Record<string, Tool> {+ const out: Record<string, Tool> = {};+ for (const [name, base] of Object.entries(tools)) out[name] = this.wrap(name, base);+ return out;+ }++ private wrap(name: string, base: Tool): Tool {+ const cached = this.wrapped.get(base);+ if (cached) return cached;+ const realExecute = base.execute;+ const wrapped = {+ ...base,+ execute: async (input: unknown, options: { toolCallId: string }) => {+ const scripted = this.player?.recordedResult(options.toolCallId);+ if (scripted && scripted.result !== undefined) {+ this.toolLog.push({ id: options.toolCallId, tool: name, input, output: scripted.result, recorded: true });+ return scripted.result;+ }+ const output = realExecute ? await (realExecute as any)(input, options) : undefined;+ this.toolLog.push({ id: options.toolCallId, tool: name, input, output, recorded: false });+ return output;+ },+ } as Tool;+ this.wrapped.set(base, wrapped);+ return wrapped;+ }++ override getTools(): Record<string, Tool> {+ return this.wrapAll(super.getTools());+ }++ override getPlanTools(): Record<string, Tool> {+ return this.wrapAll(super.getPlanTools());+ }+}++function buildConfig(providers: ScriptedProviderSpec[]): MercuryConfig {+ const config = getDefaultConfig();+ // Never let a developer's env keys register a live provider.+ for (const value of Object.values(config.providers)) {+ if (value && typeof value === 'object' && 'enabled' in value) (value as { enabled: boolean }).enabled = false;+ }+ (config.providers as { default: string }).default = providers[0].name;+ config.cloud.enabled = false;+ config.channels.telegram.streaming = true;+ config.tokens.dailyBudget = 100_000_000;+ return config;+}++function chatCommandContext(config: MercuryConfig, budget: TokenBudget, caps: CapabilityRegistry): ChatCommandContext {+ return {+ toolNames: () => caps.getToolNames(),+ skillNames: () => [],+ config: () => config,+ tokenBudget: () => budget,+ manual: () => 'Mercury eval manual',+ memorySummary: () => ({ total: 0 } as any),+ memoryRecent: () => [],+ memorySearch: () => [],+ memorySetLearningPaused: () => {},+ memoryClear: () => 0,+ memoryGetSubconscious: () => [],+ memoryIsShareLearning: () => false,+ memorySetShareLearning: () => {},+ };+}++const MARKERS = {+ forcedActionRounds: '[SYSTEM: EXECUTE-MODE GUARD]',+ wakeUpCalls: '[SYSTEM: WAKE-UP CALL]',+ verificationRounds: '[SYSTEM: EXECUTE-MODE VERIFICATION]',+ stepBudgetContinuations: '[SYSTEM: STEP BUDGET]',+} as const;++function countOccurrences(haystack: string, needle: string): number {+ let count = 0;+ for (let i = haystack.indexOf(needle); i !== -1; i = haystack.indexOf(needle, i + needle.length)) count++;+ return count;+}++function pauseKind(delivered: string[]): PauseKind | null {+ for (const text of [...delivered].reverse()) {+ if (text.includes(STEPS_PAUSED_BANNER)) return 'steps';+ if (text.includes(WORK_NOT_STARTED_BANNER)) return 'work-not-started';+ if (text.includes(VERIFICATION_FAILED_BANNER)) return 'verification-failed';+ }+ return null;+}++export class EvalHarness {+ readonly channel: RecordingChannel;+ readonly providers: ScriptedProvider[];+ readonly workDir: string;+ private seq = 0;++ private constructor(+ readonly fixture: ScenarioFixture,+ readonly agent: Agent,+ readonly sessions: SessionRepository,+ readonly capabilities: EvalCapabilityRegistry,+ readonly providerRegistry: ProviderRegistry,+ readonly player: ScriptPlayer,+ channel: RecordingChannel,+ providers: ScriptedProvider[],+ workDir: string,+ private readonly fake: boolean,+ ) {+ this.channel = channel;+ this.providers = providers;+ this.workDir = workDir;+ capabilities.player = this.player;+ }++ get channelType(): ChannelType {+ return this.channel.type;+ }++ get channelId(): string {+ return this.fixture.channel?.id ?? 'eval-chat';+ }++ static async create(fixture: ScenarioFixture, options: RunOptions = {}): Promise<EvalHarness> {+ const fake = options.fakeTimers !== false;+ if (fake) vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval'] });+ const home = freshHome(fixture.name);+ const workDir = join(home, 'work');+ mkdirSync(workDir, { recursive: true });++ const specs = fixture.providers?.length ? fixture.providers : [{ name: 'scripted' }];+ const config = buildConfig(specs);+ const player = new ScriptPlayer(clock);+ const providerRegistry = await ProviderRegistry.create(config);+ const scripted = specs.map((spec) => new ScriptedProvider(spec, player));+ for (const p of scripted) providerRegistry.set(p.name, p);+ providerRegistry.setDefault(specs[0].name);++ const tokenBudget = new TokenBudget(config);+ const scheduler = new Scheduler(config);+ const sessions = new SessionRepository();+ const capabilities = new EvalCapabilityRegistry(undefined, scheduler, tokenBudget);+ capabilities.registerAll();+ capabilities.setCwd(workDir);+ capabilities.permissions.addTempScope(workDir, true, true);+ capabilities.permissions.setAutoApproveAll(true);+ capabilities.setChatCommandContext(chatCommandContext(config, tokenBudget, capabilities));++ const type = fixture.channel?.type ?? 'telegram';+ const channel = new RecordingChannel(type, fixture.channel?.style ?? 'messaging', clock);+ const registry = new EvalChannelRegistry();+ registry.register(type, channel);+ if (fixture.channel?.streaming === false) config.channels.telegram.streaming = false;++ const agent = new Agent(+ config,+ providerRegistry,+ new Identity(),+ new ShortTermMemory(config),+ new LongTermMemory(config),+ new EpisodicMemory(config),+ null,+ registry as unknown as ChannelRegistry,+ tokenBudget,+ capabilities,+ scheduler,+ sessions,+ );+ const mode = fixture.programmingMode ?? 'off';+ if (mode === 'execute') agent.programmingMode.setExecute();+ else if (mode === 'plan') agent.programmingMode.setPlan();++ await agent.birth();+ await agent.wake();++ const harness = new EvalHarness(fixture, agent, sessions, capabilities, providerRegistry, player, channel, scripted, workDir, fake);+ harness.seedHistory();+ return harness;+ }++ private seedHistory(): void {+ const history = this.fixture.history ?? [];+ if (history.length === 0) return;+ const session = this.sessions.getOrCreateBound(this.channelType, this.channelId);+ for (const entry of history) {+ this.sessions.appendMessage(session.id, { role: entry.role, kind: entry.kind ?? 'message', content: entry.content });+ }+ }++ private sessionMessages(): SessionMessage[] {+ return this.sessions.getByBinding(this.channelType, this.channelId)?.messages ?? [];+ }++ async runTurn(turn: ScenarioTurn): Promise<TurnResult> {+ this.player.load(turn);+ this.capabilities.toolLog.length = 0;+ this.channel.continueAnswer = turn.askToContinue ?? false;+ const eventStart = this.channel.events.length;+ const sessionStart = this.sessionMessages().length;+ const msg: ChannelMessage = {+ id: `eval-${this.fixture.name}-${++this.seq}`,+ channelId: this.channelId,+ channelType: this.channelType,+ senderId: 'eval-user',+ content: turn.message,+ timestamp: Date.now(),+ };++ const t0 = clock();+ this.channel.inject(msg);+ await this.waitForIdle(turn.timeoutMs ?? DEFAULT_TURN_TIMEOUT_MS, eventStart);+ const tEnd = clock();++ const events = this.channel.since(eventStart);+ const delivered = events.filter((e) => e.kind === 'delivered').map((e) => e.text);+ const notices = events.filter((e) => e.kind === 'notice').map((e) => e.text);+ const calls = [...this.player.calls];+ const sessionEntries = this.sessionMessages().slice(sessionStart);+ const answer = [...sessionEntries].reverse().find((m) => m.role === 'assistant' && m.kind === 'message');+ const meta = (answer?.metadata ?? {}) as Record<string, unknown>;++ const allPrompts = calls.map((c) => promptText(c.prompt));+ const markerCount = (marker: string) => Math.max(0, ...allPrompts.map((p) => countOccurrences(p, marker)));+ const lastDelivery = [...events].reverse().find((e) => e.kind === 'delivered' || e.kind === 'completion');+ const steps: StepTiming[] = calls.map((c, i) => ({+ index: c.index,+ provider: c.provider,+ startMs: c.startedAt - t0,+ durationMs: (i + 1 < calls.length ? calls[i + 1].startedAt : (lastDelivery?.at ?? tEnd)) - c.startedAt,+ ...(c.error ? { error: c.error } : {}),+ }));+ const lastCall = calls.at(-1);+ const traceMatch = delivered.join('\n').match(/\/trace ([a-z0-9]+)/i);++ const result: TurnResult = {+ message: turn.message,+ finalText: delivered.at(-1) ?? '',+ delivered,+ notices,+ events,+ prompts: events.filter((e) => e.kind === 'prompt').map((e) => ({ question: e.text, answer: e.answer })),+ providerCalls: calls,+ toolCalls: [...this.capabilities.toolLog],+ guard: {+ forcedActionRounds: markerCount(MARKERS.forcedActionRounds),+ wakeUpCalls: markerCount(MARKERS.wakeUpCalls),+ verificationRounds: markerCount(MARKERS.verificationRounds),+ stepBudgetContinuations: markerCount(MARKERS.stepBudgetContinuations),+ forcedToolChoiceCalls: calls.filter((c) => (c.toolChoice as { type?: string } | undefined)?.type === 'required').length,+ pause: pauseKind(delivered),+ providerNotices: events.filter((e) => e.text.startsWith('⚠') && /switching to|served by|no fallback/.test(e.text)).map((e) => e.text),+ },+ timings: {+ promptBuildMs: calls.length > 0 ? calls[0].startedAt - t0 : 0,+ steps,+ deliveryMs: lastCall && lastDelivery ? lastDelivery.at - lastCall.startedAt : 0,+ totalMs: tEnd - t0,+ },+ sessionEntries,+ tokens: {+ input: typeof meta.inputTokens === 'number' ? meta.inputTokens : 0,+ output: typeof meta.outputTokens === 'number' ? meta.outputTokens : 0,+ cached: typeof meta.cachedInputTokens === 'number' ? meta.cachedInputTokens : 0,+ },+ usedProvider: typeof meta.provider === 'string' ? meta.provider : (calls.filter((c) => !c.error).at(-1)?.provider ?? null),+ traceId: typeof meta.traceId === 'string' ? meta.traceId : (traceMatch?.[1] ?? null),+ scriptExhausted: this.player.exhausted,+ failures: [],+ };+ result.failures = checkExpectations(result, turn.expect);+ return result;+ }++ /**+ * handleMessage flips the lifecycle to 'thinking' synchronously inside+ * enqueueMessage, and back to 'idle' when the turn (including delivery)+ * is over. Yield with setImmediate (never faked) until it settles.+ * Hook wanted in agent.ts: a public `whenIdle()` / turn-complete event —+ * see the P2.3 report.+ */+ private async waitForIdle(timeoutMs: number, eventStart: number): Promise<void> {+ const deadline = clock() + timeoutMs;+ const tick = () => new Promise<void>((resolve) => setImmediate(resolve));+ let settled = 0;+ while (settled < 25) {+ await tick();+ if (this.fake) vi.advanceTimersByTime(0); // zero-delay timers only (setTimeout(fn, 0))+ settled = this.agent.lifecycle.is('idle') ? settled + 1 : 0;+ if (clock() > deadline) {+ const tail = this.channel.since(eventStart).map((e) => `${e.kind}: ${e.text.slice(0, 120)}`).join('\n');+ throw new Error(`Turn did not finish within ${timeoutMs}ms (state ${this.agent.lifecycle.getState()}).\n${tail}`);+ }+ }+ }++ /** Model-input text of provider call `index` of the last turn. */+ promptOf(index: number): string {+ const record = this.player.calls[index];+ return record ? promptText(record.prompt) : '';+ }++ async dispose(): Promise<void> {+ try {+ this.agent.cancelActiveWork('eval finished');+ await this.agent.sleep();+ } finally {+ if (this.fake) vi.useRealTimers();+ }+ }+}++export function checkExpectations(result: TurnResult, expect: TurnExpectations | undefined): string[] {+ if (!expect) return [];+ const failures: string[] = [];+ const all = result.events.map((e) => e.text);+ const fail = (what: string) => failures.push(`[${result.message.slice(0, 40)}] ${what}`);+ if (expect.deliveredCount !== undefined && result.delivered.length !== expect.deliveredCount) {+ fail(`delivered ${result.delivered.length} messages, expected ${expect.deliveredCount}: ${JSON.stringify(result.delivered)}`);+ }+ for (const s of expect.finalTextIncludes ?? []) if (!result.finalText.includes(s)) fail(`final text lacks ${JSON.stringify(s)}: ${JSON.stringify(result.finalText)}`);+ for (const s of expect.finalTextExcludes ?? []) if (result.finalText.includes(s)) fail(`final text contains ${JSON.stringify(s)}`);+ for (const s of expect.anyEventIncludes ?? []) if (!all.some((t) => t.includes(s))) fail(`no channel event contains ${JSON.stringify(s)}`);+ for (const s of expect.noEventIncludes ?? []) {+ const hit = all.find((t) => t.toLowerCase().includes(s.toLowerCase()));+ if (hit) fail(`channel event contains ${JSON.stringify(s)}: ${JSON.stringify(hit.slice(0, 160))}`);+ }+ if (expect.providerCalls !== undefined && result.providerCalls.length !== expect.providerCalls) {+ fail(`${result.providerCalls.length} provider calls, expected ${expect.providerCalls}`);+ }+ if (expect.forcedActionRounds !== undefined && result.guard.forcedActionRounds !== expect.forcedActionRounds) {+ fail(`${result.guard.forcedActionRounds} forced action rounds, expected ${expect.forcedActionRounds}`);+ }+ if (expect.verificationRounds !== undefined && result.guard.verificationRounds !== expect.verificationRounds) {+ fail(`${result.guard.verificationRounds} verification rounds, expected ${expect.verificationRounds}`);+ }+ if (expect.stepBudgetContinuations !== undefined && result.guard.stepBudgetContinuations !== expect.stepBudgetContinuations) {+ fail(`${result.guard.stepBudgetContinuations} step-budget continuations, expected ${expect.stepBudgetContinuations}`);+ }+ if (expect.pause !== undefined && result.guard.pause !== expect.pause) fail(`pause ${result.guard.pause}, expected ${expect.pause}`);+ if (expect.usedProvider !== undefined && result.usedProvider !== expect.usedProvider) fail(`served by ${result.usedProvider}, expected ${expect.usedProvider}`);+ if (expect.toolsUsed) {+ const used = [...new Set(result.toolCalls.map((t) => t.tool))];+ if (JSON.stringify(used) !== JSON.stringify(expect.toolsUsed)) fail(`tools ${JSON.stringify(used)}, expected ${JSON.stringify(expect.toolsUsed)}`);+ }+ if (result.scriptExhausted) fail('the agent made more model calls than the script provides');+ return failures;+}++/** Run every turn of a fixture against a fresh agent. */+export async function runScenario(fixture: ScenarioFixture, options: RunOptions = {}): Promise<ScenarioResult> {+ const harness = await EvalHarness.create(fixture, options);+ const turns: TurnResult[] = [];+ try {+ for (const turn of fixture.turns) turns.push(await harness.runTurn(turn));+ } finally {+ await harness.dispose();+ }+ return {+ name: fixture.name,+ turns,+ failures: turns.flatMap((t) => t.failures),+ sessions: harness.sessions,+ workDir: harness.workDir,+ };+}diff --git a/src/eval/script-player.ts b/src/eval/script-player.tsnew file mode 100644index 00000000..70be3b3a--- /dev/null+++ b/src/eval/script-player.ts@@ -0,0 +1,111 @@+/**+ * ScriptPlayer — hands scripted steps to whichever provider the agent calls+ * and records every model call (prompt, tool choice, timing) so tests can+ * inspect exactly what the loop sent and when.+ */+import type { LanguageModelV3CallOptions, LanguageModelV3Prompt } from '@ai-sdk/provider';+import type { ScenarioTurn, ScriptedStep, ScriptedToolCall } from './fixture.js';++export interface ProviderCallRecord {+ index: number;+ provider: string;+ model: string;+ mode: 'stream' | 'generate';+ startedAt: number;+ endedAt?: number;+ prompt: LanguageModelV3Prompt;+ toolChoice?: unknown;+ toolNames: string[];+ step?: ScriptedStep;+ error?: string;+ /** Tool call ids this step emitted (stable: eval-c<call>-<n>). */+ toolCallIds: string[];+}++export class ScriptPlayer {+ readonly calls: ProviderCallRecord[] = [];+ /** True when a model call found no scripted step left (and no onExhausted). */+ exhausted = false;+ private steps: ScriptedStep[] = [];+ private cursor = 0;+ private onExhausted?: (callIndex: number) => ScriptedStep;+ private readonly recorded = new Map<string, ScriptedToolCall>();++ constructor(private readonly clock: () => number) {}++ load(turn: ScenarioTurn): void {+ this.steps = [...(turn.steps ?? [])];+ this.cursor = 0;+ this.onExhausted = turn.onExhausted;+ this.exhausted = false;+ this.calls.length = 0;+ this.recorded.clear();+ }++ remaining(): number {+ return this.steps.length - this.cursor;+ }++ begin(provider: string, model: string, mode: 'stream' | 'generate', options: LanguageModelV3CallOptions): ProviderCallRecord {+ const record: ProviderCallRecord = {+ index: this.calls.length,+ provider,+ model,+ mode,+ startedAt: this.clock(),+ prompt: options.prompt,+ toolChoice: options.toolChoice,+ toolNames: (options.tools ?? []).map((t) => t.name),+ toolCallIds: [],+ };+ this.calls.push(record);+ return record;+ }++ end(record: ProviderCallRecord): void {+ if (record.endedAt === undefined) record.endedAt = this.clock();+ }++ /** Take the next scripted step for model call `record`. */+ nextStep(record: ProviderCallRecord): ScriptedStep {+ let step: ScriptedStep;+ if (this.cursor < this.steps.length) {+ step = this.steps[this.cursor++];+ } else if (this.onExhausted) {+ step = this.onExhausted(record.index);+ } else {+ this.exhausted = true;+ step = { kind: 'text', text: 'Script exhausted: no more scripted steps for this turn.' };+ }+ record.step = step;+ if (step.kind === 'tools') {+ step.calls.forEach((tc, i) => {+ const id = `eval-c${record.index}-${i}`;+ record.toolCallIds.push(id);+ this.recorded.set(id, tc);+ });+ }+ return step;+ }++ recordedResult(toolCallId: string): ScriptedToolCall | undefined {+ return this.recorded.get(toolCallId);+ }+}++/** Flatten a V3 prompt to searchable text (system + every message part). */+export function promptText(prompt: LanguageModelV3Prompt): string {+ const out: string[] = [];+ for (const message of prompt) {+ if (typeof message.content === 'string') {+ out.push(`[${message.role}] ${message.content}`);+ continue;+ }+ for (const part of message.content as unknown as Array<Record<string, unknown>>) {+ if (typeof part.text === 'string') out.push(`[${message.role}] ${part.text}`);+ else if (part.type === 'tool-call') out.push(`[${message.role}] tool-call ${String(part.toolName)} ${JSON.stringify(part.input)}`);+ else if (part.type === 'tool-result') out.push(`[${message.role}] tool-result ${String(part.toolName)} ${JSON.stringify(part.output)}`);+ }+ }+ return out.join('\n');+}diff --git a/src/eval/scripted-provider.ts b/src/eval/scripted-provider.tsnew file mode 100644index 00000000..da3a7120--- /dev/null+++ b/src/eval/scripted-provider.ts@@ -0,0 +1,134 @@+/**+ * ScriptedProvider — a real BaseProvider whose model instance is a+ * MockLanguageModelV3 playing back the fixture's steps through the+ * ScriptPlayer. The agent loop cannot tell it from a live provider: it goes+ * through ProviderRegistry, the fallback iterator, streamText/generateText,+ * tool-call parsing and the SDK's multi-step loop exactly as in production.+ */+import { MockLanguageModelV3 } from 'ai/test';+import type {+ LanguageModelV3CallOptions,+ LanguageModelV3Content,+ LanguageModelV3FinishReason,+ LanguageModelV3StreamPart,+ LanguageModelV3Usage,+} from '@ai-sdk/provider';+import { BaseProvider, type LLMResponse, type LLMStreamChunk } from '../providers/base.js';+import { DEFAULT_USAGE, type ScriptedProviderSpec, type ScriptedStep, type ScriptedUsage } from './fixture.js';+import type { ScriptPlayer } from './script-player.js';++function toUsage(usage: ScriptedUsage | undefined): LanguageModelV3Usage {+ const input = usage?.inputTokens ?? DEFAULT_USAGE.inputTokens;+ const output = usage?.outputTokens ?? DEFAULT_USAGE.outputTokens;+ const cached = usage?.cachedInputTokens ?? DEFAULT_USAGE.cachedInputTokens;+ return {+ inputTokens: { total: input, noCache: input - cached, cacheRead: cached, cacheWrite: 0 },+ outputTokens: { total: output, text: output, reasoning: 0 },+ };+}++function finishOf(step: ScriptedStep): LanguageModelV3FinishReason {+ if (step.kind === 'tools') return { unified: 'tool-calls', raw: 'tool_use' };+ return step.finishReason === 'length' ? { unified: 'length', raw: 'max_tokens' } : { unified: 'stop', raw: 'end_turn' };+}++function contentOf(step: ScriptedStep, toolCallIds: string[]): LanguageModelV3Content[] {+ const content: LanguageModelV3Content[] = [];+ if (step.text) content.push({ type: 'text', text: step.text });+ if (step.kind === 'tools') {+ step.calls.forEach((tc, i) => {+ content.push({ type: 'tool-call', toolCallId: toolCallIds[i], toolName: tc.tool, input: JSON.stringify(tc.input) });+ });+ }+ return content;+}++export class ScriptedProvider extends BaseProvider {+ readonly name: string;+ readonly model: string;+ /** Model calls this provider received (including failed ones). */+ callCount = 0;+ private readonly failFirst: number;+ private readonly failWith: string;+ private readonly instance: MockLanguageModelV3;++ constructor(spec: ScriptedProviderSpec, private readonly player: ScriptPlayer) {+ const model = spec.model ?? `${spec.name}-model`;+ super({ name: spec.name, apiKey: 'eval', baseUrl: 'eval://', model, enabled: true });+ this.name = spec.name;+ this.model = model;+ this.failFirst = spec.failFirst ?? 0;+ this.failWith = spec.failWith ?? `${spec.name}: scripted outage (503 Service Unavailable)`;+ this.instance = new MockLanguageModelV3({+ provider: `eval.${spec.name}`,+ modelId: model,+ doStream: async (options) => this.doStream(options),+ doGenerate: async (options) => this.doGenerate(options),+ });+ }++ private maybeFail(options: LanguageModelV3CallOptions, mode: 'stream' | 'generate'): ReturnType<ScriptPlayer['begin']> {+ this.callCount++;+ const record = this.player.begin(this.name, this.model, mode, options);+ if (this.callCount <= this.failFirst) {+ record.error = this.failWith;+ this.player.end(record);+ throw new Error(this.failWith);+ }+ return record;+ }++ private async doStream(options: LanguageModelV3CallOptions) {+ const record = this.maybeFail(options, 'stream');+ const step = this.player.nextStep(record);+ const parts: LanguageModelV3StreamPart[] = [{ type: 'stream-start', warnings: [] }];+ if (step.text) {+ parts.push({ type: 'text-start', id: 't0' });+ parts.push({ type: 'text-delta', id: 't0', delta: step.text });+ parts.push({ type: 'text-end', id: 't0' });+ }+ for (const part of contentOf(step, record.toolCallIds)) {+ if (part.type === 'tool-call') parts.push(part);+ }+ parts.push({ type: 'finish', usage: toUsage(step.usage), finishReason: finishOf(step) });+ const player = this.player;+ const stream = new ReadableStream<LanguageModelV3StreamPart>({+ start(controller) {+ for (const part of parts) controller.enqueue(part);+ controller.close();+ player.end(record);+ },+ });+ return { stream };+ }++ private async doGenerate(options: LanguageModelV3CallOptions) {+ const record = this.maybeFail(options, 'generate');+ const step = this.player.nextStep(record);+ this.player.end(record);+ return {+ content: contentOf(step, record.toolCallIds),+ finishReason: finishOf(step),+ usage: toUsage(step.usage),+ warnings: [],+ };+ }++ getModelInstance(): MockLanguageModelV3 {+ return this.instance;+ }++ isAvailable(): boolean {+ return true;+ }++ // The direct helpers are only used by side paths (session titles, status+ // verbs); the eval never scripts them, so they answer deterministically.+ async generateText(): Promise<LLMResponse> {+ return { text: 'Eval', inputTokens: 0, outputTokens: 0, totalTokens: 0, model: this.model, provider: this.name };+ }++ async *streamText(): AsyncIterable<LLMStreamChunk> {+ yield { text: 'Eval', done: true };+ }+}