File size: 14,278 Bytes
a0ebf39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
import { readFileSync, readdirSync, mkdirSync } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import { parseArgs } from 'util';
import type { EvalScenario, ScenarioRunResult, CheckpointResult, EvalReport } from './types';
import type { Action } from '@/lib/types/action';
import { runAgentLoop, type AgentLoopIterationResult } from '@/lib/chat/agent-loop';
import { EvalStateManager } from './state-manager';
import { initCapture, captureWhiteboard, closeCapture } from './capture';
import { scoreScreenshot } from './scorer';
import { generateReport } from './reporter';
import { createRunDir } from '../shared/run-dir';

// ==================== CLI Args ====================
//
// Required env:
//   EVAL_CHAT_MODEL (or DEFAULT_MODEL)  Model for chat generation
//   EVAL_SCORER_MODEL                   Model for VLM scoring
//
// Usage:
//   EVAL_CHAT_MODEL=<provider:model> \
//   EVAL_SCORER_MODEL=<provider:model> \
//   pnpm eval:whiteboard --scenario physics-force-decomposition

const { values: args } = parseArgs({
  options: {
    scenario: { type: 'string' },
    repeat: { type: 'string', default: '1' },
    'base-url': { type: 'string', default: 'http://localhost:3000' },
    'output-dir': { type: 'string', default: 'eval/whiteboard-layout/results' },
    rescore: { type: 'string' }, // Path to existing run dir — rescore only, no chat
  },
});

const BASE_URL = args['base-url']!;
const CHAT_MODEL_RAW = process.env.EVAL_CHAT_MODEL || process.env.DEFAULT_MODEL;
const SCORER_MODEL_RAW = process.env.EVAL_SCORER_MODEL;
const ENABLE_THINKING =
  process.env.EVAL_ENABLE_THINKING === '1' || process.env.EVAL_ENABLE_THINKING === 'true';
if (!CHAT_MODEL_RAW) {
  console.error(
    'Error: EVAL_CHAT_MODEL (or DEFAULT_MODEL) must be set. Example: EVAL_CHAT_MODEL=openai:gpt-4.1',
  );
  process.exit(1);
}
if (!SCORER_MODEL_RAW) {
  console.error(
    'Error: EVAL_SCORER_MODEL must be set. Example: EVAL_SCORER_MODEL=google:gemini-2.5-flash',
  );
  process.exit(1);
}
const CHAT_MODEL: string = CHAT_MODEL_RAW;
const SCORER_MODEL: string = SCORER_MODEL_RAW;
const REPEAT = parseInt(args.repeat || '1', 10);
const OUTPUT_DIR = args['output-dir']!;
const SCENARIO_FILTER = args.scenario;
const MAX_AGENT_TURNS = 10;

// ==================== Scenario Loading ====================

function loadScenarios(): EvalScenario[] {
  const currentDir =
    typeof __dirname !== 'undefined' ? __dirname : dirname(fileURLToPath(import.meta.url));
  const scenarioDir = join(currentDir, 'scenarios');
  const files = readdirSync(scenarioDir).filter((f) => f.endsWith('.json'));
  const scenarios: EvalScenario[] = [];

  for (const file of files) {
    const scenario: EvalScenario = JSON.parse(readFileSync(join(scenarioDir, file), 'utf-8'));
    if (SCENARIO_FILTER && scenario.id !== SCENARIO_FILTER && !file.includes(SCENARIO_FILTER)) {
      continue;
    }
    scenarios.push(scenario);
  }

  return scenarios;
}

// ==================== Single Scenario Run ====================

async function runScenario(
  scenario: EvalScenario,
  runIndex: number,
  runDir: string,
): Promise<ScenarioRunResult> {
  const model = scenario.model || CHAT_MODEL;
  const checkpoints: CheckpointResult[] = [];

  console.log(`  [run ${runIndex + 1}] Starting...`);

  // Per-scenario sub-directory: runDir/<scenario-id>/
  const scenarioDir = join(runDir, scenario.id);
  mkdirSync(scenarioDir, { recursive: true });

  const stateManager = new EvalStateManager(scenario.initialStoreState);
  const messages: Array<{
    role: string;
    content: string;
    parts?: unknown[];
    metadata?: unknown;
  }> = [];

  // Per-turn wall-clock latency around runAgentLoop. Used to compare cost
  // when toggling EVAL_ENABLE_THINKING.
  const turnDurationsMs: number[] = [];

  try {
    for (let turnIdx = 0; turnIdx < scenario.turns.length; turnIdx++) {
      const turn = scenario.turns[turnIdx];
      console.log(`    Turn ${turnIdx + 1}: "${turn.userMessage.slice(0, 50)}..."`);

      messages.push({
        role: 'user',
        content: turn.userMessage,
        parts: [{ type: 'text', text: turn.userMessage }],
        metadata: { createdAt: Date.now() },
      });

      // Per-iteration state for the eval callbacks
      let iterResult: AgentLoopIterationResult | null = null;
      let currentAgentId: string | null = null;
      let currentMessageId: string | null = null;
      const textParts: string[] = [];
      const actionParts: Array<{ type: string; actionName: string; params: unknown }> = [];
      let cueUserReceived = false;
      // Serial action queue: `wb_*` actions must apply in emission order because
      // ActionEngine.ensureWhiteboardOpen() awaits an internal delay on first
      // call, which would let later actions race ahead and insert elements
      // out of order. We chain each execute() onto the previous one and await
      // the tail in onIterationEnd before the screenshot.
      let actionChain: Promise<void> = Promise.resolve();

      // Use the shared agent loop — same logic as frontend
      const controller = new AbortController();
      const turnStartMs = Date.now();
      await runAgentLoop(
        {
          config: scenario.config,
          apiKey: '', // Server resolves API key from env/YAML
          model,
        },
        {
          getStoreState: () => stateManager.getStoreState(),
          getMessages: () => messages,

          fetchChat: async (body, signal) => {
            // Reset per-iteration accumulators
            currentAgentId = null;
            currentMessageId = null;
            textParts.length = 0;
            actionParts.length = 0;
            cueUserReceived = false;
            iterResult = null;
            actionChain = Promise.resolve();

            // Inject thinking config when EVAL_ENABLE_THINKING is set.
            // The chat route defaults to disabled; this opt-in lets us
            // measure latency / quality tradeoff without changing prod.
            const bodyWithThinking = ENABLE_THINKING
              ? { ...body, thinking: { enabled: true } }
              : body;

            return fetch(`${BASE_URL}/api/chat`, {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify(bodyWithThinking),
              signal,
            });
          },

          onEvent: (event) => {
            switch (event.type) {
              case 'agent_start':
                currentAgentId = event.data.agentId;
                currentMessageId = event.data.messageId;
                break;

              case 'text_delta':
                textParts.push(event.data.content);
                break;

              case 'action': {
                const action: Action = {
                  id: event.data.actionId,
                  type: event.data.actionName,
                  ...event.data.params,
                } as Action;
                // Serialize execution: chain each action onto the previous
                // one so they apply in emission order. We await `actionChain`
                // in onIterationEnd before screenshotting.
                actionChain = actionChain.then(() => stateManager.executeAction(action));
                actionParts.push({
                  type: `action-${event.data.actionName}`,
                  actionName: event.data.actionName,
                  params: event.data.params,
                });
                break;
              }

              case 'cue_user':
                cueUserReceived = true;
                break;

              case 'done':
                iterResult = {
                  directorState: event.data.directorState,
                  totalAgents: event.data.totalAgents,
                  agentHadContent: event.data.agentHadContent ?? true,
                  cueUserReceived,
                };
                break;

              case 'error':
                throw new Error(`API error: ${event.data.message}`);
            }
          },

          onIterationEnd: async () => {
            // Wait for all queued actions to apply to the store before we
            // use its state (message construction, screenshot capture).
            try {
              await actionChain;
            } catch (err) {
              const msg = err instanceof Error ? err.message : String(err);
              console.error(`    Action execution error: ${msg.slice(0, 120)}`);
            }

            // Build assistant message for conversation history
            if (currentMessageId && (textParts.length > 0 || actionParts.length > 0)) {
              const parts: unknown[] = [];
              if (textParts.length > 0) {
                parts.push({ type: 'text', text: textParts.join('') });
              }
              for (const ap of actionParts) {
                parts.push({ ...ap, state: 'result', output: { success: true } });
              }
              messages.push({
                role: 'assistant',
                content: textParts.join(''),
                parts,
                metadata: {
                  senderName: currentAgentId || 'agent',
                  originalRole: 'agent',
                  agentId: currentAgentId,
                  createdAt: Date.now(),
                },
              });
            }

            return iterResult;
          },
        },
        controller.signal,
        MAX_AGENT_TURNS,
      );
      const turnDurationMs = Date.now() - turnStartMs;
      turnDurationsMs.push(turnDurationMs);
      console.log(
        `      [timing] turn ${turnIdx + 1} ran in ${(turnDurationMs / 1000).toFixed(1)}s`,
      );

      // Checkpoint: capture + score
      const isLastTurn = turnIdx === scenario.turns.length - 1;
      const isCheckpoint = turn.checkpoint || isLastTurn;

      if (isCheckpoint) {
        const elements = stateManager.getWhiteboardElements();
        const screenshotFilename = `run${runIndex}_turn${turnIdx}.png`;
        const screenshotPath = await captureWhiteboard(elements, scenarioDir, screenshotFilename);
        console.log(`    Captured: ${screenshotFilename} (${elements.length} elements)`);

        try {
          const score = await scoreScreenshot(screenshotPath, SCORER_MODEL);
          console.log(`    Score: overall=${score.overall}, overlap=${score.overlap.score}`);
          checkpoints.push({ turnIndex: turnIdx, screenshotPath, score, elements });
        } catch (scoreErr) {
          const msg = scoreErr instanceof Error ? scoreErr.message : String(scoreErr);
          console.error(`    Score error (continuing): ${msg.slice(0, 120)}`);
          checkpoints.push({ turnIndex: turnIdx, screenshotPath, score: null, elements });
        }
      }
    }
  } catch (error) {
    const msg = error instanceof Error ? error.message : String(error);
    console.error(`    Error: ${msg}`);
    return { scenarioId: scenario.id, runIndex, model, checkpoints, turnDurationsMs, error: msg };
  } finally {
    stateManager.dispose();
  }

  return { scenarioId: scenario.id, runIndex, model, checkpoints, turnDurationsMs };
}

// ==================== Rescore Mode ====================

async function rescoreRun(runDir: string) {
  console.log('=== Rescore Mode ===');
  console.log(`Scorer: ${SCORER_MODEL}`);
  console.log(`Run dir: ${runDir}`);

  // Read the existing report to get scenario metadata
  const reportPath = join(runDir, 'report.json');
  const oldReport: EvalReport = JSON.parse(readFileSync(reportPath, 'utf-8'));

  const allResults: ScenarioRunResult[] = [];

  for (const oldResult of oldReport.scenarios) {
    console.log(`\nScenario: ${oldResult.scenarioId} (run ${oldResult.runIndex + 1})`);
    const checkpoints: CheckpointResult[] = [];

    for (const oldCp of oldResult.checkpoints) {
      const pngPath = oldCp.screenshotPath;
      console.log(`  Rescoring: ${pngPath}`);

      try {
        const score = await scoreScreenshot(pngPath, SCORER_MODEL);
        console.log(`    Score: overall=${score.overall}, overlap=${score.overlap.score}`);
        checkpoints.push({ ...oldCp, score });
      } catch (scoreErr) {
        const msg = scoreErr instanceof Error ? scoreErr.message : String(scoreErr);
        console.error(`    Score error: ${msg.slice(0, 120)}`);
        checkpoints.push(oldCp); // Keep old score
      }
    }

    allResults.push({ ...oldResult, checkpoints });
  }

  const report: EvalReport = {
    timestamp: new Date().toISOString(),
    model: oldReport.model,
    scenarios: allResults,
  };

  const { json, md } = generateReport(report, runDir);
  console.log(`\nReport saved:`);
  console.log(`  JSON: ${json}`);
  console.log(`  Markdown: ${md}`);
}

// ==================== Main ====================

async function main() {
  // Rescore mode: only re-score existing screenshots
  if (args.rescore) {
    await rescoreRun(args.rescore);
    return;
  }

  console.log('=== Whiteboard Layout Eval ===');
  console.log(`Chat: ${CHAT_MODEL} | Scorer: ${SCORER_MODEL} | Repeats: ${REPEAT}`);
  console.log(`Thinking: ${ENABLE_THINKING ? 'ON' : 'OFF'}`);
  console.log('');

  const scenarios = loadScenarios();
  if (scenarios.length === 0) {
    console.error('No scenarios found. Check eval/whiteboard-layout/scenarios/');
    process.exit(1);
  }
  console.log(`Loaded ${scenarios.length} scenario(s)`);

  const runDir = createRunDir(OUTPUT_DIR, CHAT_MODEL);
  console.log(`Output: ${runDir}`);

  await initCapture(BASE_URL);

  const allResults: ScenarioRunResult[] = [];

  for (const scenario of scenarios) {
    console.log(`\nScenario: ${scenario.name} (${scenario.id})`);
    const repeats = scenario.repeat ?? REPEAT;

    for (let r = 0; r < repeats; r++) {
      const result = await runScenario(scenario, r, runDir);
      allResults.push(result);
    }
  }

  await closeCapture();

  const report: EvalReport = {
    timestamp: new Date().toISOString(),
    model: CHAT_MODEL,
    scenarios: allResults,
  };

  const { json, md } = generateReport(report, runDir);
  console.log(`\nReport saved:`);
  console.log(`  JSON: ${json}`);
  console.log(`  Markdown: ${md}`);
}

main().catch((err) => {
  console.error('Fatal error:', err);
  process.exit(1);
});