-
-
Notifications
You must be signed in to change notification settings - Fork 437
Expand file tree
/
Copy pathrun-benchmark.cjs
More file actions
2811 lines (2566 loc) · 161 KB
/
run-benchmark.cjs
File metadata and controls
2811 lines (2566 loc) · 161 KB
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
/**
* Home Security AI Benchmark Suite
*
* Evaluates LLM and VLM models on home security AI tasks:
* - Context preprocessing (dedup)
* - Topic classification
* - Knowledge distillation
* - Event deduplication (security classifier)
* - Tool use (tool selection & parameter extraction)
* - Chat & JSON compliance
* - VLM scene analysis (optional, requires VLM server)
*
* ## Skill Protocol (when spawned by Aegis)
*
* Aegis → Skill (env vars):
* AEGIS_GATEWAY_URL — LLM gateway URL (e.g. http://localhost:5407)
* AEGIS_VLM_URL — VLM server URL (e.g. http://localhost:5405)
* AEGIS_SKILL_PARAMS — JSON params from skill config
* AEGIS_SKILL_ID — Skill ID
*
* Skill → Aegis (stdout, JSON lines):
* {"event": "ready", "model": "Qwen3.5-4B-Q4_1"}
* {"event": "suite_start", "suite": "Context Preprocessing"}
* {"event": "test_result", "suite": "...", "test": "...", "status": "pass", "timeMs": 123}
* {"event": "suite_end", "suite": "...", "passed": 4, "failed": 0}
* {"event": "complete", "passed": 23, "total": 26, "timeMs": 95000, "reportPath": "..."}
*
* Standalone usage:
* node run-benchmark.cjs [options]
* --gateway URL LLM gateway (fallback if no AEGIS_GATEWAY_URL)
* --vlm URL VLM server (fallback if no AEGIS_VLM_URL)
* --out DIR Results directory (default: ~/.aegis-ai/benchmarks)
* --report Auto-generate HTML report after run
*/
const fs = require('fs');
const path = require('path');
const os = require('os');
const { execSync } = require('child_process');
// ─── Config: Aegis env vars → CLI args → defaults ────────────────────────────
const args = process.argv.slice(2);
function getArg(name, defaultVal) {
const idx = args.indexOf(`--${name}`);
if (idx === -1) return defaultVal;
return args[idx + 1] || defaultVal;
}
// ─── Help ─────────────────────────────────────────────────────────────────────
if (args.includes('--help') || args.includes('-h')) {
console.log(`
Home Security AI Benchmark Suite • DeepCamera / SharpAI
Usage: node scripts/run-benchmark.cjs [options]
Options:
--gateway URL LLM gateway URL (default: http://localhost:5407)
--vlm URL VLM server base URL (disabled if omitted)
--out DIR Results output directory (default: ~/.aegis-ai/benchmarks)
--no-open Don't auto-open report in browser
-h, --help Show this help message
Environment Variables (set by Aegis):
AEGIS_GATEWAY_URL LLM gateway URL
AEGIS_VLM_URL VLM server base URL
AEGIS_SKILL_ID Skill identifier (enables skill mode)
AEGIS_SKILL_PARAMS JSON params from skill config
Tests: 131 total (96 LLM + 35 VLM) across 16 suites
`.trim());
process.exit(0);
}
// Parse skill parameters if running as Aegis skill
let skillParams = {};
try { skillParams = JSON.parse(process.env.AEGIS_SKILL_PARAMS || '{}'); } catch { }
// Aegis provides config via env vars; CLI args are fallback for standalone
const GATEWAY_URL = process.env.AEGIS_GATEWAY_URL || getArg('gateway', 'http://localhost:5407');
const LLM_URL = process.env.AEGIS_LLM_URL || getArg('llm', ''); // Direct llama-server LLM port
const VLM_URL = process.env.AEGIS_VLM_URL || getArg('vlm', '');
const RESULTS_DIR = getArg('out', path.join(os.homedir(), '.aegis-ai', 'benchmarks'));
const IS_SKILL_MODE = !!process.env.AEGIS_SKILL_ID;
const NO_OPEN = args.includes('--no-open') || skillParams.noOpen || false;
// Auto-detect mode: if no VLM URL, default to 'llm' (skip VLM image-analysis tests)
const TEST_MODE = skillParams.mode || (VLM_URL ? 'full' : 'llm');
const IDLE_TIMEOUT_MS = 30000; // Streaming idle timeout — resets on each received token
const FIXTURES_DIR = path.join(__dirname, '..', 'fixtures');
// API type and model info from Aegis (or defaults for standalone)
const LLM_API_TYPE = process.env.AEGIS_LLM_API_TYPE || 'openai';
const LLM_MODEL = process.env.AEGIS_LLM_MODEL || '';
const LLM_API_KEY = process.env.AEGIS_LLM_API_KEY || '';
const LLM_BASE_URL = process.env.AEGIS_LLM_BASE_URL || '';
const VLM_API_TYPE = process.env.AEGIS_VLM_API_TYPE || 'openai-compatible';
const VLM_MODEL = process.env.AEGIS_VLM_MODEL || '';
// ─── OpenAI SDK Clients ──────────────────────────────────────────────────────
const OpenAI = require('openai');
// Resolve LLM base URL — priority: cloud provider → direct llama-server → gateway
const strip = (u) => u.replace(/\/v1\/?$/, '');
const llmBaseUrl = LLM_BASE_URL
? `${strip(LLM_BASE_URL)}/v1`
: LLM_URL
? `${strip(LLM_URL)}/v1`
: `${GATEWAY_URL}/v1`;
const llmClient = new OpenAI({
apiKey: LLM_API_KEY || 'not-needed', // Local servers don't require auth
baseURL: llmBaseUrl,
});
// VLM client — always local llama-server
const vlmClient = VLM_URL ? new OpenAI({
apiKey: 'not-needed',
baseURL: `${strip(VLM_URL)}/v1`,
}) : null;
// ─── Model Family Capabilities Config ────────────────────────────────────────
//
// Different model families require different per-request params to control
// thinking/reasoning behavior. This table centralizes those differences so
// llmCall() can dispatch them automatically.
//
// Fields:
// match — fn(modelName: string) → bool
// apiParams — extra params merged into every chat/completions request
// serverFlags — llama-server startup flags needed for full control
// (documentation only — llmCall is a client and cannot set these)
//
// ┌─────────────────────┬──────────────────────────────┬──────────────────────────────────────────┐
// │ Family │ Per-request param │ llama-server startup flag │
// ├─────────────────────┼──────────────────────────────┼──────────────────────────────────────────┤
// │ Mistral Small 4+ │ reasoning_effort: 'none' │ --reasoning-budget 0 │
// │ Qwen3.5 (thinking) │ (none needed — handled by │ --chat-template-kwargs │
// │ │ /no_think prompt suffix and │ '{"enable_thinking":false}' │
// │ │ 500-token reasoning abort) │ │
// │ GPT / Claude │ (none — cloud API, no local │ N/A │
// │ │ thinking tokens) │ │
// └─────────────────────┴──────────────────────────────┴──────────────────────────────────────────┘
//
// To add a new model family: append an entry to MODEL_FAMILIES.
// The match fn receives the lower-cased model name/filename.
const MODEL_FAMILIES = [
{
name: 'Mistral',
// Covers: Mistral-Small-4, Mistral-*, Magistral-*, Mixtral-*
match: (m) => m.includes('mistral') || m.includes('magistral') || m.includes('mixtral'),
// reasoning_effort=none disables thinking and routes all output to delta.content.
// Supported by both Mistral cloud API and llama-server (forwarded as chat template kwarg).
// Without this Mistral routes ALL output to delta.thinking, causing 30s idle timeouts.
apiParams: { reasoning_effort: 'none' },
serverFlags: '--chat-template-kwargs {"reasoning_effort":"none"} --parallel 1',
},
{
name: 'Nemotron',
// NVIDIA Nemotron-3-Nano (4B, 30B) — rejects temperature < 1.0 with HTTP 400:
// "Unsupported value: 'temperature' does not support 0.1 with this model"
match: (m) => m.includes('nemotron'),
apiParams: {},
minTemperature: 1.0,
},
{
name: 'LFM',
// Liquid LFM2 / LFM2.5 — same temperature restriction as Nemotron
match: (m) => m.includes('lfm'),
apiParams: {},
minTemperature: 1.0,
},
// Qwen3.5 thinking is handled via prompt-level /no_think and the 500-token reasoning
// abort in llmCall — no extra per-request params needed.
{
name: 'GPT-OSS',
// gpt-oss-20b uses <|channel|>analysis/final structure.
// reasoning_effort=none hints the model to minimize analysis (injected into system prompt
// by the chat template). The mlx-server OutputFilter suppresses analysis at token ID level.
match: (m) => m.includes('gpt-oss'),
apiParams: { reasoning_effort: 'none' },
serverFlags: '--chat-template-kwargs {"reasoning_effort":"none"}',
},
];
/**
* Return the matched MODEL_FAMILIES entry for the given model name.
* Returns {} if the model is not in any known family.
*/
function getModelFamily(modelName) {
if (!modelName) return {};
const lower = modelName.toLowerCase();
for (const family of MODEL_FAMILIES) {
if (family.match(lower)) return family;
}
return {};
}
/** Return extra API params for the model (e.g. reasoning_effort for Mistral). */
function getModelApiParams(modelName) {
return getModelFamily(modelName).apiParams || {};
}
// ─── Skill Protocol: JSON lines on stdout, human text on stderr ──────────────
/**
* Emit a JSON-lines event on stdout (parsed by Aegis skill-runtime-manager).
* All structured data goes here so Aegis can react to it.
*/
function emit(event) {
process.stdout.write(JSON.stringify(event) + '\n');
}
/**
* Log human-readable text to stderr (shows in Aegis console tab).
* In standalone mode, also mirrors to stdout for terminal visibility.
*/
function log(msg) {
process.stderr.write(msg + '\n');
}
// ─── Test Framework ───────────────────────────────────────────────────────────
const suites = [];
let currentSuite = null;
function suite(name, fn) {
suites.push({ name, fn, tests: [] });
}
let targetServerParams = {};
try { targetServerParams = JSON.parse(process.env.AEGIS_SERVER_PARAMS || '{}'); } catch { }
const results = {
timestamp: new Date().toISOString(),
gateway: GATEWAY_URL,
vlm: VLM_URL || null,
serverParams: targetServerParams,
system: {},
model: {},
suites: [],
totals: { passed: 0, failed: 0, skipped: 0, total: 0, timeMs: 0 },
tokenTotals: { prompt: 0, completion: 0, total: 0 },
perfTotals: { ttftMs: [], decodeTokensPerSec: [], prefillTokensPerSec: null, serverDecodeTokensPerSec: null },
resourceSamples: [], // GPU/memory snapshots taken after each suite
};
async function llmCall(messages, opts = {}) {
// Select the appropriate OpenAI client (LLM or VLM)
const client = opts.vlm ? vlmClient : llmClient;
if (!client) {
throw new Error(opts.vlm ? 'VLM client not configured' : 'LLM client not configured');
}
const model = opts.model || (opts.vlm ? VLM_MODEL : LLM_MODEL) || undefined;
// For JSON-expected tests, use low temperature + top_p to encourage
// direct JSON output without extended reasoning.
// NOTE: Do NOT inject assistant prefill — Qwen3.5 rejects prefill
// when enable_thinking is active (400 error).
if (opts.expectJSON) {
messages = [...messages];
// Remove any leftover /no_think from messages
messages = messages.map(m => {
if (m.role === 'user' && typeof m.content === 'string' && m.content.endsWith(' /no_think')) {
return { ...m, content: m.content.slice(0, -10) };
}
return m;
});
// Append JSON guidance to last user message for local models
const lastUser = messages.findLastIndex(m => m.role === 'user');
if (lastUser >= 0 && typeof messages[lastUser].content === 'string') {
messages[lastUser] = {
...messages[lastUser],
content: messages[lastUser].content + '\n\nRespond with ONLY valid JSON, no explanation or markdown.',
};
}
}
// Sanitize messages for llama-server compatibility:
// - Replace null content with empty string (llama-server rejects null)
// - Convert tool_calls assistant messages to plain text (llama-server
// doesn't support OpenAI tool_calls format in conversation history)
// - Convert tool result messages to user messages
messages = messages.map(m => {
if (m.role === 'assistant' && m.tool_calls) {
// Convert tool call to text representation
const callDesc = m.tool_calls.map(tc => {
const argStr = typeof tc.function.arguments === 'string'
? tc.function.arguments
: JSON.stringify(tc.function.arguments);
return `[Calling ${tc.function.name}(${argStr})]`;
}).join('\n');
return { role: 'assistant', content: callDesc };
}
if (m.role === 'tool') {
// Convert tool result to user message
return { role: 'user', content: `[Tool result]: ${m.content}` };
}
return {
...m,
...(m.content === null && { content: '' }),
};
});
// Determine the correct max-tokens parameter name:
// - OpenAI cloud (GPT-5.4+): requires 'max_completion_tokens', rejects 'max_tokens'
// - Local llama-server: requires 'max_tokens', may not understand 'max_completion_tokens'
const isCloudApi = !opts.vlm && (LLM_API_TYPE === 'openai' || LLM_BASE_URL.includes('openai.com') || LLM_BASE_URL.includes('api.anthropic'));
// No max_tokens for any API — the streaming loop's 2000-token hard cap is the safety net.
// Sending max_tokens to thinking models (Qwen3.5) starves actual output since
// reasoning_content counts against the limit.
// Lookup model-family-specific config (e.g. reasoning_effort for Mistral,
// minTemperature for Nemotron/LFM2).
// VLM calls skip the LLM family table — VLM models are always local llava-compatible.
const modelFamily = opts.vlm ? {} : getModelFamily(model || LLM_MODEL);
const modelFamilyParams = modelFamily.apiParams || {};
// Resolve temperature: apply model-specific minimum if needed.
// Nemotron and LFM2 reject temperature < 1.0 with HTTP 400.
let temperature = opts.temperature;
if (temperature === undefined && opts.expectJSON) temperature = 0.7;
if (temperature !== undefined && modelFamily.minTemperature !== undefined) {
temperature = Math.max(temperature, modelFamily.minTemperature);
}
// Build request params
const params = {
messages,
stream: true,
// Request token usage in streaming response (only supported by cloud APIs;
// llama-server crashes with "Failed to parse input" when stream_options is present)
...(isCloudApi && { stream_options: { include_usage: true } }),
...(model && { model }),
...(temperature !== undefined && { temperature }),
...(opts.expectJSON && { top_p: 0.8 }),
// For JSON-expected tests on local servers, enable server-side JSON mode
// which activates prefix buffering to strip hallucinated artifacts
...(opts.expectJSON && !isCloudApi && { response_format: { type: 'json_object' } }),
...(opts.tools && { tools: opts.tools }),
// Model-family-specific params (e.g. reasoning_effort:'none' for Mistral).
// These are merged last so they take precedence over defaults.
...modelFamilyParams,
};
// Use an AbortController with idle timeout that resets on each streamed chunk.
const controller = new AbortController();
const idleMs = opts.timeout || IDLE_TIMEOUT_MS;
let idleTimer = setTimeout(() => controller.abort(), idleMs);
const resetIdle = () => { clearTimeout(idleTimer); idleTimer = setTimeout(() => controller.abort(), idleMs); };
// Log prompt being sent
log(`\n 📤 Prompt (${messages.length} messages, params: ${JSON.stringify({maxTokens: opts.maxTokens, expectJSON: !!opts.expectJSON})}):`);
for (const m of messages) {
if (typeof m.content === 'string') {
log(` [${m.role}] ${m.content}`);
} else if (Array.isArray(m.content)) {
// Multi-part content (VLM with images)
for (const part of m.content) {
if (part.type === 'text') {
log(` [${m.role}] ${part.text}`);
} else if (part.type === 'image_url') {
const url = part.image_url?.url || '';
const b64Match = url.match(/^data:([^;]+);base64,(.+)/);
if (b64Match) {
const mimeType = b64Match[1];
const b64Data = b64Match[2];
const sizeKB = Math.round(b64Data.length * 3 / 4 / 1024);
log(` [${m.role}] 🖼️ [Image: ${mimeType}, ~${sizeKB}KB]`);
log(`[IMG:${url}]`);
} else {
log(` [${m.role}] 🖼️ [Image URL: ${url.slice(0, 80)}…]`);
}
}
}
} else {
log(` [${m.role}] ${JSON.stringify(m.content).slice(0, 200)}`);
}
}
const callStartTime = Date.now();
try {
const stream = await client.chat.completions.create(params, {
signal: controller.signal,
});
let content = '';
let reasoningContent = '';
let toolCalls = null;
let model = '';
let usage = {};
let tokenCount = 0;
let tokenBuffer = '';
let firstTokenTime = null; // For TTFT measurement
// For JSON-expected tests: track whether we've seen the start of JSON content.
// Until we see '{' or '[', everything in delta.content is treated as reasoning.
let jsonContentStarted = !opts.expectJSON; // true immediately for non-JSON tests
for await (const chunk of stream) {
resetIdle();
if (chunk.model) model = chunk.model;
const delta = chunk.choices?.[0]?.delta;
if (delta?.content) {
if (jsonContentStarted) {
// Already in content mode — accumulate normally
content += delta.content;
} else {
// JSON test: haven't seen JSON start yet.
// Check if this chunk contains the start of JSON.
// First strip any <think>...</think> blocks.
const cleaned = (content + delta.content)
.replace(/<think>[\s\S]*?<\/think>\s*/gi, '')
.trimStart();
const jsonIdx = cleaned.search(/[{\[]/);
if (jsonIdx >= 0) {
// Found JSON start — split: everything before is reasoning,
// everything from JSON start onwards is content.
jsonContentStarted = true;
const allText = content + delta.content;
// Find the actual position in the raw text
const rawCleaned = allText.replace(/<think>[\s\S]*?<\/think>\s*/gi, '');
const rawJsonIdx = rawCleaned.search(/[{\[]/);
if (rawJsonIdx >= 0) {
const thinkingPart = rawCleaned.slice(0, rawJsonIdx);
const contentPart = rawCleaned.slice(rawJsonIdx);
if (thinkingPart.trim()) reasoningContent += thinkingPart;
content = contentPart;
} else {
content = allText;
}
} else {
// Still no JSON — accumulate as reasoning
reasoningContent += delta.content;
// Keep the raw content in a temp buffer for the split logic above
content += delta.content;
}
}
}
if (delta?.reasoning_content) reasoningContent += delta.reasoning_content;
// Fallback: Mistral Small 4 in llama-server may route thinking tokens through
// `delta.thinking` even when reasoning_effort=none is requested (llama.cpp
// compatibility varies by version). Capture it so the idle timer resets.
if (delta?.thinking) reasoningContent += delta.thinking;
// mlx-lm Python server uses `delta.reasoning` instead of `delta.reasoning_content`
if (delta?.reasoning) reasoningContent += delta.reasoning;
if (delta?.content || delta?.reasoning_content || delta?.thinking || delta?.reasoning) {
tokenCount++;
// Capture TTFT on first content/reasoning token
if (!firstTokenTime) firstTokenTime = Date.now();
// Buffer and log tokens — tag with field source
const isContent = !!delta?.content && jsonContentStarted;
const tok = delta?.content || delta?.reasoning_content || delta?.reasoning || '';
// Tag first token of each field type
if (tokenCount === 1) tokenBuffer += isContent ? '[C] ' : '[R] ';
tokenBuffer += tok;
if (tokenCount % 20 === 0) {
log(tokenBuffer);
tokenBuffer = '';
}
if (tokenCount % 100 === 0) {
log(` … ${tokenCount} tokens (content: ${content.length}c, reasoning: ${reasoningContent.length}c)`);
}
// Smart early abort for JSON-expected tests:
// Allow thinking models (Qwen3.5) up to 500 reasoning tokens before aborting.
// They legitimately need to reason before outputting JSON.
if (opts.expectJSON && !isContent && tokenCount > 500) {
log(` ⚠ Aborting: ${tokenCount} reasoning tokens for JSON test — model is thinking too long`);
controller.abort();
break;
}
// If we have actual JSON content, verify it looks valid
if (opts.expectJSON && jsonContentStarted && content.length >= 50) {
const stripped = content.trimStart();
if (stripped.length >= 50 && !/^\s*[{\[]/.test(stripped)) {
log(` ⚠ Aborting: expected JSON but got: "${stripped.slice(0, 80)}…"`);
controller.abort();
break;
}
}
// Hard cap: abort if token count far exceeds maxTokens
if (opts.maxTokens && tokenCount > opts.maxTokens * 2) {
log(` ⚠ Aborting: ${tokenCount} tokens exceeds ${opts.maxTokens}×2 safety limit`);
controller.abort();
break;
}
// Global safety limit: no benchmark test should ever need >2000 tokens
if (tokenCount > 2000) {
log(` ⚠ Aborting: ${tokenCount} tokens exceeds global 2000-token safety limit`);
controller.abort();
break;
}
}
if (delta?.tool_calls) {
if (!toolCalls) toolCalls = [];
for (const tc of delta.tool_calls) {
const idx = tc.index ?? 0;
if (!toolCalls[idx]) {
toolCalls[idx] = { id: tc.id, type: tc.type || 'function', function: { name: '', arguments: '' } };
}
if (tc.function?.name) toolCalls[idx].function.name += tc.function.name;
if (tc.function?.arguments) {
const chunk = typeof tc.function.arguments === 'string'
? tc.function.arguments
: JSON.stringify(tc.function.arguments);
toolCalls[idx].function.arguments += chunk;
}
}
}
if (chunk.usage) usage = chunk.usage;
}
// Flush remaining token buffer
if (tokenBuffer) log(tokenBuffer);
// If JSON was expected but never found in content, the content is all thinking text.
// Clear it so the reasoning fallback below can extract JSON from reasoningContent.
if (opts.expectJSON && !jsonContentStarted) {
log(` 💭 Model produced ${tokenCount} thinking tokens, no JSON content yet — checking reasoning for JSON`);
content = '';
}
// If the model only produced reasoning_content (thinking) with no content,
// use the reasoning output as the response content for evaluation purposes.
// Try to extract JSON from reasoning if this was a JSON-expected call.
if (!content && reasoningContent) {
// Try to find JSON embedded in the reasoning output
try {
const jsonMatch = reasoningContent.match(/[{\[][\s\S]*[}\]]/);
if (jsonMatch) {
content = jsonMatch[0];
} else {
content = reasoningContent;
}
} catch {
content = reasoningContent;
}
}
// Build per-call token data:
// Prefer server-reported usage; fall back to chunk-counted completion tokens
const promptTokens = usage.prompt_tokens || 0;
const completionTokens = usage.completion_tokens || tokenCount; // tokenCount = chunks with content/reasoning
const totalTokens = usage.total_tokens || (promptTokens + completionTokens);
const callTokens = { prompt: promptTokens, completion: completionTokens, total: totalTokens };
// ─── Performance metrics ───
const callEndTime = Date.now();
const totalElapsedMs = callEndTime - callStartTime;
const ttftMs = firstTokenTime ? (firstTokenTime - callStartTime) : null;
// Decode throughput: tokens generated / time spent generating (after first token)
const decodeMs = firstTokenTime ? (callEndTime - firstTokenTime) : 0;
const decodeTokensPerSec = (decodeMs > 0 && tokenCount > 1)
? ((tokenCount - 1) / (decodeMs / 1000)) // -1 because first token is the TTFT boundary
: null;
const callPerf = {
ttftMs,
decodeTokensPerSec: decodeTokensPerSec ? parseFloat(decodeTokensPerSec.toFixed(1)) : null,
totalElapsedMs,
};
// Track global token totals
results.tokenTotals.prompt += callTokens.prompt;
results.tokenTotals.completion += callTokens.completion;
results.tokenTotals.total += callTokens.total;
// Track per-test tokens (accumulated across multiple llmCall invocations within one test)
if (_currentTestTokens) {
_currentTestTokens.prompt += callTokens.prompt;
_currentTestTokens.completion += callTokens.completion;
_currentTestTokens.total += callTokens.total;
}
// Track per-test perf (accumulated across multiple llmCall invocations within one test)
if (_currentTestPerf) {
if (ttftMs !== null) _currentTestPerf.ttftMs.push(ttftMs);
if (decodeTokensPerSec !== null) _currentTestPerf.decodeTokensPerSec.push(decodeTokensPerSec);
}
// Track global perf totals
if (ttftMs !== null) results.perfTotals.ttftMs.push(ttftMs);
if (decodeTokensPerSec !== null) results.perfTotals.decodeTokensPerSec.push(decodeTokensPerSec);
// Capture model name from first response
// MLX server returns the full filesystem path as model name
// e.g. /Users/simba/.aegis-ai/models/mlx_models/mlx-community/Qwen3.5-9B-8bit
// Strip to just the org/model portion: mlx-community/Qwen3.5-9B-8bit
const cleanName = (n) => {
if (!n || !n.includes('/')) return n;
const parts = n.split('/');
// If it looks like a filesystem path (>3 segments), keep last 2 (org/model)
return parts.length > 3 ? parts.slice(-2).join('/') : n;
};
if (opts.vlm) {
if (!results.model.vlm && model) results.model.vlm = cleanName(model);
} else {
if (!results.model.name && model) results.model.name = cleanName(model);
}
return { content, toolCalls, usage: callTokens, perf: callPerf, model };
} finally {
clearTimeout(idleTimer);
}
}
function stripThink(text) {
// Strip standard <think>...</think> tags
let cleaned = text.replace(/<think>[\s\S]*?<\/think>\s*/gi, '').trim();
// Strip Qwen3.5 'Thinking Process:' blocks (outputs plain text reasoning
// instead of <think> tags when enable_thinking is active)
cleaned = cleaned.replace(/^Thinking Process[:\s]*[\s\S]*?(?=\n\s*[{\[]|\n```|$)/i, '').trim();
// Strip gpt-oss <|channel|>...<|message|> routing tokens
// e.g. "<|channel|>analysis<|message|>We need to decide..." → "We need to decide..."
cleaned = cleaned.replace(/^<\|channel\|>[^<]*<\|message\|>/i, '').trim();
// Strip any remaining <|...|> special tokens (end_turn, etc.)
cleaned = cleaned.replace(/<\|[^|]+\|>/g, '').trim();
return cleaned;
}
function parseJSON(text) {
const cleaned = stripThink(text);
let jsonStr = cleaned;
const codeBlock = cleaned.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
if (codeBlock) {
jsonStr = codeBlock[1];
} else {
// Extract ALL balanced JSON objects/arrays, then pick the largest.
// Some models (gpt-oss) emit an empty `{}` prefix before the real JSON.
const candidates = [];
let searchFrom = 0;
while (searchFrom < cleaned.length) {
const sub = cleaned.slice(searchFrom);
const startOff = sub.search(/[{\[]/);
if (startOff < 0) break;
const startIdx = searchFrom + startOff;
const opener = cleaned[startIdx];
const closer = opener === '{' ? '}' : ']';
let depth = 0, inString = false, escape = false, endIdx = -1;
for (let i = startIdx; i < cleaned.length; i++) {
const ch = cleaned[i];
if (escape) { escape = false; continue; }
if (ch === '\\' && inString) { escape = true; continue; }
if (ch === '"') { inString = !inString; continue; }
if (!inString) {
if (ch === opener) depth++;
else if (ch === closer) { depth--; if (depth === 0) { endIdx = i; break; } }
}
}
if (endIdx >= 0) {
candidates.push(cleaned.slice(startIdx, endIdx + 1));
searchFrom = endIdx + 1;
} else {
break;
}
}
// Prefer the longest candidate (most likely the real response)
if (candidates.length > 0) {
jsonStr = candidates.reduce((a, b) => a.length >= b.length ? a : b);
}
}
// Clean common local model artifacts before parsing:
// - Replace literal "..." or "…" placeholders in arrays/values
// - Replace <any placeholder text> tags (model echoes prompt templates)
jsonStr = jsonStr
.replace(/,\s*\.{3,}\s*(?=[\]},])/g, '') // trailing ..., before ] } or ,
.replace(/\.{3,}/g, '"..."') // standalone ... → string
.replace(/…/g, '"..."') // ellipsis char
.replace(/<[^>]+>/g, '"placeholder"') // <any text> → "placeholder" (multi-word)
.replace(/,\s*([}\]])/g, '$1'); // trailing commas
try {
return JSON.parse(jsonStr.trim());
} catch (firstErr) {
// Aggressive retry: strip all non-JSON artifacts
const aggressive = jsonStr
.replace(/"placeholder"(\s*"placeholder")*/g, '"placeholder"') // collapse repeated placeholders
.replace(/\bplaceholder\b/g, '""') // placeholder → empty string
.replace(/,\s*([}\]])/g, '$1'); // re-clean trailing commas
try {
return JSON.parse(aggressive.trim());
} catch (secondErr) {
// Include raw content in error for diagnostics
throw new Error(`${secondErr.message} | raw(120): "${(text || '').slice(0, 120)}"`);
}
}
}
function assert(condition, msg) {
if (!condition) throw new Error(msg || 'Assertion failed');
}
// ─── Resource Metrics (GPU/MPS + Memory) ─────────────────────────────────────
/**
* Sample GPU (Apple Silicon MPS) utilization and system memory.
* Uses `ioreg` for GPU stats (no sudo needed).
*/
function sampleResourceMetrics() {
const os = require('os');
const sample = {
timestamp: new Date().toISOString(),
sys: {
totalGB: parseFloat((os.totalmem() / 1073741824).toFixed(1)),
freeGB: parseFloat((os.freemem() / 1073741824).toFixed(1)),
usedGB: parseFloat(((os.totalmem() - os.freemem()) / 1073741824).toFixed(1)),
},
process: {
rssMB: parseFloat((process.memoryUsage().rss / 1048576).toFixed(0)),
},
gpu: null,
};
// Apple Silicon GPU via ioreg (macOS only)
if (process.platform === 'darwin') {
try {
const out = execSync('ioreg -r -c AGXAccelerator 2>/dev/null', { encoding: 'utf8', timeout: 3000 });
const m = (key) => { const r = new RegExp('"' + key + '"=(\\d+)'); const match = out.match(r); return match ? parseInt(match[1]) : null; };
const deviceUtil = m('Device Utilization %');
const rendererUtil = m('Renderer Utilization %');
const tilerUtil = m('Tiler Utilization %');
const memUsed = m('In use system memory');
const memAlloc = m('Alloc system memory');
if (deviceUtil !== null) {
sample.gpu = {
util: deviceUtil,
renderer: rendererUtil,
tiler: tilerUtil,
memUsedGB: memUsed ? parseFloat((memUsed / 1073741824).toFixed(1)) : null,
memAllocGB: memAlloc ? parseFloat((memAlloc / 1073741824).toFixed(1)) : null,
};
}
} catch { /* ioreg not available or timed out */ }
}
return sample;
}
/**
* Aggregate resource samples to produce a representative summary.
* Uses PEAK GPU utilization (since point-in-time samples often miss active inference)
* and MAX GPU memory (high-water mark during the benchmark run).
*/
function aggregateResourceSamples(samples) {
if (!samples || samples.length === 0) return null;
const gpuSamples = samples.filter(s => s.gpu);
if (gpuSamples.length === 0) {
// No GPU data — return last sample for sys memory at least
return samples[samples.length - 1];
}
// Find peak GPU utilization sample
const peakGpu = gpuSamples.reduce((best, s) =>
(s.gpu.util > (best.gpu?.util ?? -1)) ? s : best, gpuSamples[0]);
// Find max GPU memory sample
const maxMem = gpuSamples.reduce((best, s) =>
((s.gpu.memUsedGB || 0) > (best.gpu?.memUsedGB || 0)) ? s : best, gpuSamples[0]);
// Use the last sample for system memory (most recent)
const lastSample = samples[samples.length - 1];
return {
...lastSample,
gpu: {
util: peakGpu.gpu.util,
renderer: peakGpu.gpu.renderer,
tiler: peakGpu.gpu.tiler,
memUsedGB: maxMem.gpu.memUsedGB,
memAllocGB: maxMem.gpu.memAllocGB,
},
};
}
// ─── Live progress: intermediate saves + report regeneration ────────────────
let _liveReportOpened = false;
let _runStartedAt = null; // Set when runSuites() begins
let _currentTestName = null; // Set during test execution for live banner
let _currentSuiteIndex = 0; // Current suite index for live progress
let _totalSuites = 0; // Total number of suites
/**
* Save the current (in-progress) results to disk and regenerate the live report.
* Called after each test completes so the browser auto-refreshes with updated data.
*/
function saveLiveProgress(startedAt, suitesCompleted, totalSuites, nextSuiteName, currentTest) {
try {
fs.mkdirSync(RESULTS_DIR, { recursive: true });
// Save current results as a live file (will be overwritten each time)
const liveFile = path.join(RESULTS_DIR, '_live_progress.json');
// Include the in-progress suite so Quality/Vision tabs can render partial data
const liveSuites = [...results.suites];
if (currentSuite && currentSuite.tests.length > 0 && !results.suites.includes(currentSuite)) {
liveSuites.push(currentSuite);
}
const liveResults = {
...results,
suites: liveSuites,
_live: true,
_progress: { suitesCompleted, totalSuites, startedAt, currentTest: currentTest || null },
};
fs.writeFileSync(liveFile, JSON.stringify(liveResults, null, 2));
// Build a temporary index with just the live file
const indexFile = path.join(RESULTS_DIR, 'index.json');
// Compute live performance summary from accumulated data
const ttftArr = [...results.perfTotals.ttftMs];
const decArr = [...results.perfTotals.decodeTokensPerSec];
const livePerfSummary = (ttftArr.length > 0 || decArr.length > 0) ? {
ttft: ttftArr.length > 0 ? {
avgMs: Math.round(ttftArr.reduce((a, b) => a + b, 0) / ttftArr.length),
p50Ms: [...ttftArr].sort((a, b) => a - b)[Math.floor(ttftArr.length * 0.5)],
p95Ms: [...ttftArr].sort((a, b) => a - b)[Math.floor(ttftArr.length * 0.95)],
samples: ttftArr.length,
} : null,
decode: decArr.length > 0 ? {
avgTokensPerSec: parseFloat((decArr.reduce((a, b) => a + b, 0) / decArr.length).toFixed(1)),
samples: decArr.length,
} : null,
server: {
prefillTokensPerSec: results.perfTotals.prefillTokensPerSec,
decodeTokensPerSec: results.perfTotals.serverDecodeTokensPerSec,
},
resource: aggregateResourceSamples(results.resourceSamples),
} : null;
// Preserve previous runs in index for comparison sidebar
let existingIndex = [];
try { existingIndex = JSON.parse(fs.readFileSync(indexFile, 'utf8')).filter(e => e.file !== '_live_progress.json'); } catch { }
const liveEntry = {
file: '_live_progress.json',
model: results.model.name || 'loading...',
vlm: results.model.vlm || null,
timestamp: results.timestamp,
passed: results.totals.passed,
failed: results.totals.failed,
total: results.totals.total,
llmPassed: results.totals.passed, // Simplified for live view
llmTotal: results.totals.total,
vlmPassed: 0, vlmTotal: 0,
timeMs: Date.now() - new Date(startedAt).getTime(),
tokens: results.tokenTotals.total,
perfSummary: livePerfSummary,
};
fs.writeFileSync(indexFile, JSON.stringify([...existingIndex, liveEntry], null, 2));
// Regenerate report in live mode
const reportScript = path.join(__dirname, 'generate-report.cjs');
// Clear require cache to pick up any code changes
delete require.cache[require.resolve(reportScript)];
const { generateReport } = require(reportScript);
const testsCompleted = liveSuites.reduce((n, s) => n + s.tests.length, 0);
const testsTotal = liveSuites.reduce((n, s) => n + s.tests.length, 0) + (currentTest ? 0 : 0);
const reportPath = generateReport(RESULTS_DIR, {
liveMode: true,
liveStatus: {
suitesCompleted,
totalSuites,
currentSuite: currentSuite?.name || nextSuiteName || 'Finishing...',
currentTest: currentTest || null,
testsCompleted,
startedAt,
},
});
// Open browser on first save (so user sees live progress from the start)
if (!_liveReportOpened && !NO_OPEN && reportPath) {
if (IS_SKILL_MODE) {
// Ask Aegis to open in its embedded browser window
emit({ event: 'open_report', reportPath });
log(' 📊 Requested Aegis to open live report');
} else {
// Standalone: open in system browser
try {
const openCmd = process.platform === 'darwin' ? 'open' : 'xdg-open';
execSync(`${openCmd} "${reportPath}"`, { stdio: 'ignore' });
log(' 📊 Live report opened in browser (auto-refreshes every 5s)');
} catch { }
}
_liveReportOpened = true;
}
} catch (err) {
// Non-fatal — live progress is a nice-to-have
log(` ⚠️ Live progress update failed: ${err.message}`);
}
}
async function runSuites() {
_runStartedAt = new Date().toISOString();
_totalSuites = suites.length;
for (let si = 0; si < suites.length; si++) {
const s = suites[si];
_currentSuiteIndex = si;
currentSuite = { name: s.name, tests: [], passed: 0, failed: 0, skipped: 0, timeMs: 0 };
log(`\n${'─'.repeat(60)}`);
log(` ${s.name}`);
log(`${'─'.repeat(60)}`);
emit({ event: 'suite_start', suite: s.name });
await s.fn();
results.suites.push(currentSuite);
results.totals.passed += currentSuite.passed;
results.totals.failed += currentSuite.failed;
results.totals.skipped += currentSuite.skipped;
results.totals.total += currentSuite.tests.length;
emit({ event: 'suite_end', suite: s.name, passed: currentSuite.passed, failed: currentSuite.failed, skipped: currentSuite.skipped, timeMs: currentSuite.timeMs });
// Sample resource metrics (GPU + memory) after each suite
const resourceSample = sampleResourceMetrics();
resourceSample.suite = s.name;
results.resourceSamples.push(resourceSample);
// Scrape server metrics after each suite so live perf cards update
await scrapeServerMetrics();
// Live progress: save after suite (also saved per-test, but suite boundary is a clean checkpoint)
saveLiveProgress(_runStartedAt, si + 1, suites.length, si + 1 < suites.length ? suites[si + 1]?.name : null);
}
}
// ─── Per-test token + perf accumulators (set by test(), read by llmCall) ──────
let _currentTestTokens = null;
let _currentTestPerf = null;
let _vlmTestMeta = null; // VLM fixture metadata (set during VLM tests, read after test() completes)
async function test(name, fn) {
const testResult = { name, status: 'pass', timeMs: 0, detail: '', tokens: { prompt: 0, completion: 0, total: 0 }, perf: {} };
_currentTestTokens = { prompt: 0, completion: 0, total: 0 };
_currentTestPerf = { ttftMs: [], decodeTokensPerSec: [] };
const start = Date.now();
try {
const detail = await fn();
testResult.timeMs = Date.now() - start;
testResult.detail = detail || '';
testResult.tokens = { ..._currentTestTokens };
// Compute aggregate perf for this test (may span multiple llmCall invocations)
testResult.perf = {
ttftMs: _currentTestPerf.ttftMs.length > 0 ? Math.round(_currentTestPerf.ttftMs.reduce((a, b) => a + b, 0) / _currentTestPerf.ttftMs.length) : null,
decodeTokensPerSec: _currentTestPerf.decodeTokensPerSec.length > 0 ? parseFloat((_currentTestPerf.decodeTokensPerSec.reduce((a, b) => a + b, 0) / _currentTestPerf.decodeTokensPerSec.length).toFixed(1)) : null,
};
currentSuite.passed++;
const tokInfo = _currentTestTokens.total > 0 ? `, ${_currentTestTokens.total} tok` : '';
const perfInfo = testResult.perf.ttftMs !== null ? `, TTFT ${testResult.perf.ttftMs}ms` : '';
const tpsInfo = testResult.perf.decodeTokensPerSec !== null ? `, ${testResult.perf.decodeTokensPerSec} tok/s` : '';
log(` ✅ ${name} (${testResult.timeMs}ms${tokInfo}${perfInfo}${tpsInfo})${detail ? ` — ${detail}` : ''}`);
} catch (err) {
testResult.timeMs = Date.now() - start;
testResult.status = 'fail';
testResult.detail = err.message;
testResult.tokens = { ..._currentTestTokens };
testResult.perf = {
ttftMs: _currentTestPerf.ttftMs.length > 0 ? Math.round(_currentTestPerf.ttftMs.reduce((a, b) => a + b, 0) / _currentTestPerf.ttftMs.length) : null,
decodeTokensPerSec: _currentTestPerf.decodeTokensPerSec.length > 0 ? parseFloat((_currentTestPerf.decodeTokensPerSec.reduce((a, b) => a + b, 0) / _currentTestPerf.decodeTokensPerSec.length).toFixed(1)) : null,
};
currentSuite.failed++;
log(` ❌ ${name} (${testResult.timeMs}ms) — ${err.message}`);
}
_currentTestTokens = null;
_currentTestPerf = null;
currentSuite.timeMs += testResult.timeMs;
currentSuite.tests.push(testResult);
emit({ event: 'test_result', suite: currentSuite.name, test: name, status: testResult.status, timeMs: testResult.timeMs, detail: testResult.detail.slice(0, 120), tokens: testResult.tokens, perf: testResult.perf });
// Live progress: save after each test for real-time updates in commander center
if (_runStartedAt) {
_currentTestName = null; // Test just completed
saveLiveProgress(_runStartedAt, _currentSuiteIndex, _totalSuites, null, name);
}
}
function skip(name, reason) {
currentSuite.skipped++;
currentSuite.tests.push({ name, status: 'skip', timeMs: 0, detail: reason });
log(` ⏭️ ${name} — ${reason}`);
emit({ event: 'test_result', suite: currentSuite.name, test: name, status: 'skip', timeMs: 0, detail: reason });
}
// ═══════════════════════════════════════════════════════════════════════════════
// SUITE 1: CONTEXT PREPROCESSING
// ═══════════════════════════════════════════════════════════════════════════════
function buildPreprocessPrompt(messageIndex, userMessage) {
return `You are a context deduplication engine. Given a list of user messages from a conversation, decide which exchanges to KEEP and which are DUPLICATES.
## User Messages (index, timestamp, first 50 words)
${messageIndex.map(m => `[${m.idx}] ${m.ts ? `(${m.ts})` : ''} ${m.text}`).join('\n')}
## New User Question
${userMessage}
## Rules
1. If the user asked the same or very similar question multiple times, keep ONLY the LATEST one
2. Keep messages that are clearly different topics or provide unique context
3. Always keep the last 2 user messages (most recent context)