@datagrok/grokky 1.0.4 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/skills/deploy-grokky/SKILL.md +193 -0
- package/.grokignore +2 -0
- package/.turbo/turbo-build.log +24 -0
- package/.vscode/settings.json +16 -0
- package/CHANGELOG.md +151 -8
- package/CLAUDE.md +284 -0
- package/CREDITS.md +173 -0
- package/LICENSE.md +16 -0
- package/README.md +24 -0
- package/bdd/bdd.config.json +1 -0
- package/bdd/bindings/elements.ts +9 -0
- package/bdd/bindings/steps.ts +787 -0
- package/bdd/features/ai-panel/platform-work.feature +63 -0
- package/bdd/features/ai-panel/session.feature +69 -0
- package/bdd/features/ai-panel/table-work.feature +99 -0
- package/bdd/generated/ai-panel/platform-work.test.ts +103 -0
- package/bdd/generated/ai-panel/session.test.ts +100 -0
- package/bdd/generated/ai-panel/table-work.test.ts +150 -0
- package/bdd/package.json +1 -0
- package/bdd/tsconfig.json +13 -0
- package/css/ai.css +637 -49
- package/dist/package-test.js +4 -1707
- package/dist/package-test.js.map +1 -1
- package/dist/package.js +742 -92317
- package/dist/package.js.map +1 -1
- package/dockerfiles/claude-runtime/.dockerignore +1 -0
- package/{.eslintrc.json → dockerfiles/claude-runtime/.eslintrc.json} +7 -16
- package/dockerfiles/claude-runtime/Dockerfile +73 -13
- package/dockerfiles/claude-runtime/agent/grokky_agent/__init__.py +0 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/__main__.py +80 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/browser_tools.py +180 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/config.py +26 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/formats.py +155 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/guard.py +87 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/hermes.py +212 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/hermes.yaml +45 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/hermes_plugin/__init__.py +8 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/hermes_plugin/plugin.yaml +3 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/protocol.py +174 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/__init__.py +21 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/anthropic.py +21 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/azure.py +46 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/base.py +127 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/bedrock.py +46 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/custom.py +40 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/databricks.py +54 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/openai_platform.py +41 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/openrouter.py +46 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/session.py +471 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/skills.py +44 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/structured.py +40 -0
- package/dockerfiles/claude-runtime/container.json +2 -2
- package/dockerfiles/claude-runtime/entrypoint.sh +20 -0
- package/dockerfiles/claude-runtime/package-lock.json +1721 -306
- package/dockerfiles/claude-runtime/package.json +20 -5
- package/dockerfiles/claude-runtime/plugin/.claude-plugin/plugin.json +5 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-calc-column/SKILL.md +92 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-chem-data/SKILL.md +250 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-chem-toolkit/SKILL.md +395 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-df-and-columns/SKILL.md +454 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-entities/SKILL.md +38 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-exec/SKILL.md +209 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-filtering/SKILL.md +185 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-grid-customization/SKILL.md +270 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-projects/SKILL.md +100 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-selection/SKILL.md +344 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-undo/SKILL.md +78 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-viewers/SKILL.md +303 -0
- package/dockerfiles/claude-runtime/pyproject.toml +18 -0
- package/dockerfiles/claude-runtime/src/agent/pool.ts +411 -0
- package/dockerfiles/claude-runtime/src/agent/turn.ts +153 -0
- package/dockerfiles/claude-runtime/src/constants.ts +20 -0
- package/dockerfiles/claude-runtime/src/credentials.ts +45 -0
- package/dockerfiles/claude-runtime/src/grounding.ts +104 -0
- package/dockerfiles/claude-runtime/src/help-index.ts +118 -0
- package/dockerfiles/claude-runtime/src/privileges.ts +8 -0
- package/dockerfiles/claude-runtime/src/prompts.ts +211 -0
- package/dockerfiles/claude-runtime/src/server.ts +134 -234
- package/dockerfiles/claude-runtime/src/session.ts +328 -0
- package/dockerfiles/claude-runtime/src/shared-api-client.ts +112 -0
- package/dockerfiles/claude-runtime/src/stream-filter.ts +80 -0
- package/dockerfiles/claude-runtime/src/sync/home-files.ts +80 -0
- package/dockerfiles/claude-runtime/src/sync/orchestrator.ts +214 -0
- package/dockerfiles/claude-runtime/src/sync/packages.ts +145 -0
- package/dockerfiles/claude-runtime/src/sync/shared-connections.ts +87 -0
- package/dockerfiles/claude-runtime/src/sync/workspace.ts +68 -0
- package/dockerfiles/claude-runtime/src/tasks.ts +124 -0
- package/dockerfiles/claude-runtime/src/tool-summary.ts +66 -0
- package/dockerfiles/claude-runtime/src/types.ts +142 -23
- package/dockerfiles/claude-runtime/src/user/installed-packages.ts +17 -0
- package/dockerfiles/claude-runtime/src/user/staged-workspace.ts +80 -0
- package/dockerfiles/claude-runtime/src/user/user-dir.ts +108 -0
- package/dockerfiles/claude-runtime/src/verify.ts +136 -0
- package/dockerfiles/claude-runtime/src/watchdog.ts +115 -0
- package/dockerfiles/claude-runtime/test/credentials.test.js +43 -0
- package/dockerfiles/claude-runtime/test/grounding.test.js +191 -0
- package/dockerfiles/claude-runtime/test/help-index.test.js +115 -0
- package/dockerfiles/claude-runtime/test/plugin-skills.test.js +57 -0
- package/dockerfiles/claude-runtime/test/prompts.test.js +62 -0
- package/dockerfiles/claude-runtime/test/reaper.test.js +60 -0
- package/dockerfiles/claude-runtime/test/stream-filter.test.js +132 -0
- package/dockerfiles/claude-runtime/test/tasks.test.js +74 -0
- package/dockerfiles/claude-runtime/test/user-dir.test.js +71 -0
- package/dockerfiles/claude-runtime/test/verify.test.js +187 -0
- package/dockerfiles/claude-runtime/test/watchdog.test.js +43 -0
- package/dockerfiles/mcp-server/.eslintrc.json +39 -0
- package/dockerfiles/mcp-server/Dockerfile +10 -2
- package/dockerfiles/mcp-server/package-lock.json +1743 -98
- package/dockerfiles/mcp-server/package.json +27 -5
- package/dockerfiles/mcp-server/src/api-client.ts +123 -66
- package/dockerfiles/mcp-server/src/format.ts +51 -0
- package/dockerfiles/mcp-server/src/index.ts +44 -113
- package/dockerfiles/mcp-server/src/ops.ts +325 -0
- package/dockerfiles/mcp-server/src/shared-api-client.ts +81 -0
- package/dockerfiles/mcp-server/test/format.test.js +62 -0
- package/dockerfiles/mcp-server/test/ops.test.js +84 -0
- package/dockerfiles/mcp-server/test/shared-api-client.test.js +35 -0
- package/dockerfiles/queue/Dockerfile +2 -0
- package/dockerfiles/queue/container.json +7 -0
- package/docs/AUDIT-2026-08-03.md +1064 -0
- package/docs/BENCHMARK.md +292 -0
- package/docs/CLAUDE_CODE_FLOW.md +746 -0
- package/docs/EXAMPLES.md +82 -0
- package/docs/FEATURES.md +71 -0
- package/docs/IMPLEMENTATION.md +128 -0
- package/docs/LATENCY.md +170 -0
- package/docs/VISION.md +36 -0
- package/files/benchmark/suite.yaml +404 -0
- package/files/scripts/process-cro-results.md +14 -0
- package/files/suggestions.yaml +344 -0
- package/package.json +39 -97
- package/src/ai/ai-window.ts +157 -0
- package/src/ai/benchmark/benchmark.ts +737 -0
- package/src/ai/db-view-functions.ts +56 -0
- package/src/ai/engine.ts +98 -0
- package/src/ai/gemma-engine.ts +81 -0
- package/src/ai/panel.ts +1385 -0
- package/src/ai/prompt-suggestions.ts +209 -0
- package/src/ai/search/combined-search.ts +244 -0
- package/src/{llm-utils → ai/search}/query-matching.ts +46 -167
- package/src/{llm-utils → ai}/storage.ts +0 -1
- package/src/ai/table-tools.ts +145 -0
- package/src/ai/ui.ts +720 -0
- package/src/ai/usage-limiter.ts +105 -0
- package/src/ai/view-tools.ts +352 -0
- package/src/claude/ai-feature.ts +16 -0
- package/src/claude/exec-blocks.ts +176 -0
- package/src/claude/queue-task.ts +84 -0
- package/src/claude/runtime-client.ts +310 -0
- package/src/claude/turn-log.ts +114 -0
- package/src/claude/undoable.ts +105 -0
- package/src/{llm-utils → db}/db-index-tools.ts +24 -32
- package/src/db/sql-tools.ts +336 -0
- package/src/depr/LLM-client.ts +251 -0
- package/src/depr/ai-panel.ts +174 -0
- package/src/depr/chatgpt-assistant.ts +257 -0
- package/src/depr/creds.ts +30 -0
- package/src/depr/deepwikiclient.ts +118 -0
- package/src/depr/indexes/dg-repository-index.ts +266 -0
- package/src/depr/interfaces.ts +170 -0
- package/src/depr/is-help-request.ts +39 -0
- package/src/depr/prompt-engine.ts +52 -0
- package/src/depr/rendering-tools.ts +103 -0
- package/src/depr/script-tools.ts +785 -0
- package/src/depr/tableview-tools.ts +746 -0
- package/src/depr/viewers-ai.ts +67 -0
- package/src/package-api.ts +87 -28
- package/src/package-test.ts +1 -0
- package/src/package.g.ts +98 -48
- package/src/package.ts +211 -157
- package/src/polyfills.ts +12 -0
- package/src/utils.ts +128 -0
- package/tsconfig.json +8 -70
- package/webpack.config.js +3 -49
- package/.eslintignore +0 -2
- package/src/ai-panel.ts +0 -174
- package/src/claude-code/claude-panel.ts +0 -34
- package/src/claude-code/claude-runtime-client.ts +0 -148
- package/src/llm-utils/LLM-client.ts +0 -251
- package/src/llm-utils/combined-search.ts +0 -162
- package/src/llm-utils/creds.ts +0 -30
- package/src/llm-utils/deepwikiclient.ts +0 -118
- package/src/llm-utils/indexes/dg-repository-index.ts +0 -266
- package/src/llm-utils/panel.ts +0 -866
- package/src/llm-utils/script-tools.ts +0 -784
- package/src/llm-utils/sql-tools.ts +0 -840
- package/src/llm-utils/tableview-tools.ts +0 -704
- package/src/llm-utils/ui.ts +0 -315
- package/src/prompt-engine/chatgpt-assistant.ts +0 -257
- package/src/prompt-engine/interfaces.ts +0 -170
- package/src/prompt-engine/prompt-engine.ts +0 -52
- package/src/prompt-engine/rendering-tools.ts +0 -103
- package/src/prompts/is-help-request.ts +0 -26
- package/src/viewers-ai.ts +0 -67
- /package/src/{llm-utils → db}/indexes/biologics-index.ts +0 -0
- /package/src/{llm-utils → db}/indexes/chembl-index.ts +0 -0
- /package/src/{llm-utils → db}/query-meta-utils.ts +0 -0
- /package/src/{llm-utils/depr → depr}/AI-API-providers/openai-chat-completions-provider.ts +0 -0
- /package/src/{llm-utils/depr → depr}/AI-API-providers/openai-responses-provider.ts +0 -0
- /package/src/{llm-utils/depr → depr}/AI-API-providers/types.ts +0 -0
- /package/src/{llm-utils/depr → depr}/depr.ts +0 -0
- /package/src/{llm-utils/depr → depr}/embeddings.ts +0 -0
- /package/src/{llm-utils/depr → depr}/sql-utils.ts +0 -0
|
@@ -0,0 +1,737 @@
|
|
|
1
|
+
// Grokky latency/accuracy benchmark harness — see docs/BENCHMARK.md.
|
|
2
|
+
//
|
|
3
|
+
// Drives the golden prompt suite (files/benchmark/suite.yaml) through the SAME runtime path the
|
|
4
|
+
// panel uses (workspace context + view tools + real datagrok-exec/verify round-trips), times each
|
|
5
|
+
// turn client-side (TTFT / total / tool round-trips), reads the server-side token/cost metrics the
|
|
6
|
+
// runtime forwards on `final`, scores each prompt (deterministic assert + a judge on the runtime's
|
|
7
|
+
// model), and downloads a JSON + Markdown report tagged with a config label so runs are
|
|
8
|
+
// comparable across latency levers.
|
|
9
|
+
|
|
10
|
+
import * as grok from 'datagrok-api/grok';
|
|
11
|
+
import * as DG from 'datagrok-api/dg';
|
|
12
|
+
import * as jsyaml from 'js-yaml';
|
|
13
|
+
|
|
14
|
+
import {_package} from '../../package';
|
|
15
|
+
import {ClaudeRuntimeClient, TurnServerMetrics} from '../../claude/runtime-client';
|
|
16
|
+
import {viewFunctionTools} from '../view-tools';
|
|
17
|
+
import {executeSingleBlock, runVerification, buildWorkspaceContext} from '../../claude/exec-blocks';
|
|
18
|
+
import {AiFeature} from '../../claude/ai-feature';
|
|
19
|
+
|
|
20
|
+
interface SuitePrompt {
|
|
21
|
+
category: string;
|
|
22
|
+
prompt: string;
|
|
23
|
+
table?: string;
|
|
24
|
+
assert?: string;
|
|
25
|
+
rubric?: string;
|
|
26
|
+
/** Drives the per-difficulty rollup, so a comparison can be read per tier. */
|
|
27
|
+
difficulty?: 'trivial' | 'standard' | 'hard';
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
interface RepTurn {
|
|
31
|
+
ok: boolean;
|
|
32
|
+
ttftMs: number | null;
|
|
33
|
+
totalMs: number | null;
|
|
34
|
+
toolRoundTrips: number;
|
|
35
|
+
/** Bare tool names in call order — lets asserts check WHICH path a turn took. */
|
|
36
|
+
tools: string[];
|
|
37
|
+
ctxChars: number;
|
|
38
|
+
toolDefCount: number;
|
|
39
|
+
server: TurnServerMetrics | null;
|
|
40
|
+
assertPass: boolean | null;
|
|
41
|
+
/** The runtime's own "could not confirm this action took effect" flag. */
|
|
42
|
+
unverified: boolean;
|
|
43
|
+
content: string;
|
|
44
|
+
error?: string;
|
|
45
|
+
/** Set when an assert expression itself threw — distinguishes a broken assert from a model failure. */
|
|
46
|
+
assertError?: string;
|
|
47
|
+
/** Compact description of the workspace when an assert failed, so the report says what the model
|
|
48
|
+
* actually did rather than only that it was wrong. */
|
|
49
|
+
failState?: string;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
interface Stats {n: number; median: number | null; mean: number | null; min: number | null; max: number | null; p90: number | null; std: number | null}
|
|
53
|
+
interface JudgeResult {pass: boolean; score: number; reason: string}
|
|
54
|
+
|
|
55
|
+
interface PromptResult {
|
|
56
|
+
category: string;
|
|
57
|
+
prompt: string;
|
|
58
|
+
difficulty: 'trivial' | 'standard' | 'hard';
|
|
59
|
+
reps: number;
|
|
60
|
+
okCount: number;
|
|
61
|
+
/** Union of tool names seen across reps — the cheap-vs-strong path discriminator. */
|
|
62
|
+
toolsUsed: string[];
|
|
63
|
+
unverifiedRate: number;
|
|
64
|
+
ttftMs: Stats;
|
|
65
|
+
totalMs: Stats;
|
|
66
|
+
toolRoundTrips: Stats;
|
|
67
|
+
inputTokens: Stats;
|
|
68
|
+
outputTokens: Stats;
|
|
69
|
+
cacheReadTokens: Stats;
|
|
70
|
+
costUsd: Stats;
|
|
71
|
+
ctxChars: number;
|
|
72
|
+
toolDefCount: number;
|
|
73
|
+
assertPassRate: number | null;
|
|
74
|
+
judge: JudgeResult | null;
|
|
75
|
+
accuracyPass: boolean | null;
|
|
76
|
+
/** Workspace state from the first failing rep — what the model actually left behind. */
|
|
77
|
+
failState?: string;
|
|
78
|
+
errors: string[];
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
interface BenchReport {label: string; when: string; reps: number; hasTokens: boolean;
|
|
82
|
+
/** The `only` filter this arm ran with, so a slice is never mistaken for a full run. */
|
|
83
|
+
only?: string;
|
|
84
|
+
results: PromptResult[]}
|
|
85
|
+
|
|
86
|
+
// A hard prompt (substructure search, multi-table chemistry) legitimately runs past two minutes.
|
|
87
|
+
// Timing it out scores a slow turn as a *wrong* one, which conflates latency with correctness —
|
|
88
|
+
// the two axes this harness exists to separate. Latency is still measured; only the cutoff moves.
|
|
89
|
+
const TURN_TIMEOUT_MS: Record<string, number> = {trivial: 120000, standard: 120000, hard: 240000};
|
|
90
|
+
const turnTimeout = (difficulty?: string): number => TURN_TIMEOUT_MS[difficulty ?? 'standard'] ?? 120000;
|
|
91
|
+
// A UI FilterGroup filter applies asynchronously — `t.filter` updates a frame or two after
|
|
92
|
+
// updateOrAdd (see the datagrok-filtering skill). Asserts run synchronously right after `final`,
|
|
93
|
+
// so without this settle window every filter assertion is a race.
|
|
94
|
+
const ASSERT_SETTLE_MS = 400;
|
|
95
|
+
// A judge that merely didn't refuse is not a pass; require real confidence in the answer.
|
|
96
|
+
const JUDGE_SCORE_FLOOR = 0.7;
|
|
97
|
+
// An on-demand container can take a minute or two to pull, start and index help before it answers.
|
|
98
|
+
const READY_ATTEMPTS = 10;
|
|
99
|
+
const READY_RETRY_MS = 15000;
|
|
100
|
+
const BENCH_DIR = 'System:AppData/Grokky/benchmarks';
|
|
101
|
+
const delay = (ms: number): Promise<void> => new Promise((r) => window.setTimeout(r, ms));
|
|
102
|
+
const sanitizeLabel = (label: string): string => (label || 'run').replace(/[^\w.-]/g, '_');
|
|
103
|
+
const benchPath = (label: string): string => `${BENCH_DIR}/benchmark-${sanitizeLabel(label)}.json`;
|
|
104
|
+
const openTableViews = (): DG.TableView[] => Array.from(grok.shell.tableViews);
|
|
105
|
+
|
|
106
|
+
// ---- Suite + demo tables ---------------------------------------------------------------
|
|
107
|
+
|
|
108
|
+
async function loadSuite(): Promise<SuitePrompt[]> {
|
|
109
|
+
const text = await _package.files.readAsText('benchmark/suite.yaml');
|
|
110
|
+
return (jsyaml.load(text) as SuitePrompt[]).filter((p) => p && p.prompt);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Narrows the suite to a comma-separated list of categories, difficulties, or prompt substrings.
|
|
114
|
+
* A full arm is 44 prompts x reps x ~20 s, so validating a suite change — or probing one tier —
|
|
115
|
+
* needs a way to run a slice without paying for the whole thing. */
|
|
116
|
+
function filterSuite(suite: SuitePrompt[], only?: string): SuitePrompt[] {
|
|
117
|
+
const terms = (only ?? '').split(',').map((s) => s.trim().toLowerCase()).filter(Boolean);
|
|
118
|
+
if (!terms.length) return suite;
|
|
119
|
+
return suite.filter((p) => terms.some((term) =>
|
|
120
|
+
p.category.toLowerCase() === term || (p.difficulty ?? 'standard').toLowerCase() === term ||
|
|
121
|
+
p.prompt.toLowerCase().indexOf(term) >= 0));
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const csvCache = new Map<string, DG.DataFrame>();
|
|
125
|
+
|
|
126
|
+
async function freshTable(name: string): Promise<DG.DataFrame> {
|
|
127
|
+
if (name === 'randomWalk')
|
|
128
|
+
return grok.data.demo.randomWalk();
|
|
129
|
+
if (!csvCache.has(name))
|
|
130
|
+
csvCache.set(name, await grok.dapi.files.readCsv(`System:DemoFiles/${name}.csv`));
|
|
131
|
+
return csvCache.get(name)!.clone();
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// ---- One measured turn — mirrors runClaudeStreaming() but headless -----------------------
|
|
135
|
+
|
|
136
|
+
async function runTurn(client: ClaudeRuntimeClient, prompt: string, view: DG.ViewBase | null,
|
|
137
|
+
systemPromptMode?: string, difficulty?: string): Promise<RepTurn> {
|
|
138
|
+
// A bare turn declares no tools: the readiness probe must not be gated, graded or tool-driven.
|
|
139
|
+
const viewTools = systemPromptMode === 'none' ? {defs: [], runners: new Map()} : viewFunctionTools();
|
|
140
|
+
const ctx = view ? buildWorkspaceContext() : '';
|
|
141
|
+
const full = ctx ? ctx + '\n---\n\n' + prompt : prompt;
|
|
142
|
+
const sid = `${AiFeature.Benchmark}-${Date.now()}-${Math.floor(Math.random() * 1e6)}`;
|
|
143
|
+
const targetView = view ?? grok.shell.v;
|
|
144
|
+
|
|
145
|
+
return new Promise<RepTurn>((resolve) => {
|
|
146
|
+
const subs: {unsubscribe: () => void}[] = [];
|
|
147
|
+
const cleanup = () => subs.forEach((s) => s.unsubscribe());
|
|
148
|
+
const forSession = (subj: any, fn: (e: any) => void) =>
|
|
149
|
+
subs.push(subj.subscribe((e: any) => {if (e.sessionId === sid) fn(e);}));
|
|
150
|
+
|
|
151
|
+
let tSend = 0;
|
|
152
|
+
let ttftMs: number | null = null;
|
|
153
|
+
let toolRoundTrips = 0;
|
|
154
|
+
const tools: string[] = [];
|
|
155
|
+
let accumulated = '';
|
|
156
|
+
let done = false;
|
|
157
|
+
|
|
158
|
+
const finish = (extra: Partial<RepTurn>) => {
|
|
159
|
+
if (done) return;
|
|
160
|
+
done = true;
|
|
161
|
+
window.clearTimeout(timer);
|
|
162
|
+
cleanup();
|
|
163
|
+
resolve({
|
|
164
|
+
ok: !extra.error, ttftMs, totalMs: tSend ? performance.now() - tSend : null,
|
|
165
|
+
toolRoundTrips, tools, ctxChars: full.length, toolDefCount: viewTools.defs.length,
|
|
166
|
+
server: null, assertPass: null, unverified: false, content: accumulated, ...extra,
|
|
167
|
+
});
|
|
168
|
+
};
|
|
169
|
+
|
|
170
|
+
const timer = window.setTimeout(() => {
|
|
171
|
+
client.abort(sid);
|
|
172
|
+
finish({error: 'turn timed out'});
|
|
173
|
+
}, turnTimeout(difficulty));
|
|
174
|
+
|
|
175
|
+
forSession(client.onChunk, (e) => {
|
|
176
|
+
if (ttftMs === null) ttftMs = performance.now() - tSend;
|
|
177
|
+
accumulated += e.content;
|
|
178
|
+
});
|
|
179
|
+
forSession(client.onToolActivity, (e) => {
|
|
180
|
+
toolRoundTrips++;
|
|
181
|
+
if (e.name) tools.push(e.name);
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
forSession(client.onInputRequest, async (e) => {
|
|
185
|
+
// Faithful round-trips so multi-tool turns don't stall (the runtime blocks on these).
|
|
186
|
+
if (e.toolName === 'datagrok_exec') {
|
|
187
|
+
const {value, error} = await executeSingleBlock(e.input.code ?? '', targetView, 0);
|
|
188
|
+
let result: any = error ?
|
|
189
|
+
{success: false, error: error.error} :
|
|
190
|
+
{success: true, ...(value != null ? {returnValue: value} : {})};
|
|
191
|
+
if (!error && e.input.verify?.assertion) {
|
|
192
|
+
const v = await runVerification(e.input.verify.assertion, targetView);
|
|
193
|
+
result = {...result, verified: {passed: v.passed,
|
|
194
|
+
...(v.observed !== undefined ? {observed: v.observed} : {}), ...(v.error ? {error: v.error} : {})}};
|
|
195
|
+
}
|
|
196
|
+
client.respondToInput(sid, e.requestId, result);
|
|
197
|
+
} else if (e.toolName === 'datagrok_verify') {
|
|
198
|
+
const {passed, observed, error} = await runVerification(e.input.assertion ?? '', targetView);
|
|
199
|
+
client.respondToInput(sid, e.requestId,
|
|
200
|
+
{passed, ...(observed !== undefined ? {observed} : {}), ...(error ? {error} : {})});
|
|
201
|
+
} else if (e.toolName === 'datagrok_show_entities')
|
|
202
|
+
client.respondToInput(sid, e.requestId, {success: true});
|
|
203
|
+
else {
|
|
204
|
+
const runner = viewTools.runners.get(e.toolName);
|
|
205
|
+
if (runner) {
|
|
206
|
+
try {
|
|
207
|
+
const result = await runner(e.input ?? {});
|
|
208
|
+
client.respondToInput(sid, e.requestId, result === undefined ? {success: true} : result);
|
|
209
|
+
} catch (err: any) {
|
|
210
|
+
client.respondToInput(sid, e.requestId, {success: false, error: err.message});
|
|
211
|
+
}
|
|
212
|
+
} else // AskUserQuestion / unknown — can't answer headlessly; unblock with an empty answer.
|
|
213
|
+
client.respondToInput(sid, e.requestId, {answers: {}});
|
|
214
|
+
}
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
forSession(client.onFinal, (e) => {
|
|
218
|
+
const content = e.revision === 'replaced' ? e.content : (accumulated || e.content);
|
|
219
|
+
// A turn that streamed nothing, called nothing and reported no usage did not happen — the
|
|
220
|
+
// runtime was still starting. Scoring that as a model failure is how a cold container turns
|
|
221
|
+
// into a red row that looks like a regression.
|
|
222
|
+
const empty = !content && !tools.length && !e.metrics;
|
|
223
|
+
finish({server: e.metrics ?? null, unverified: !!e.unverified, content,
|
|
224
|
+
...(empty ? {error: 'empty turn — runtime not ready'} : {})});
|
|
225
|
+
});
|
|
226
|
+
forSession(client.onError, (e) => finish({error: e.message}));
|
|
227
|
+
|
|
228
|
+
tSend = performance.now();
|
|
229
|
+
try {
|
|
230
|
+
client.send(sid, full, {
|
|
231
|
+
...(viewTools.defs.length ? {clientTools: viewTools.defs} : {}),
|
|
232
|
+
...(systemPromptMode ? {systemPromptMode} : {}),
|
|
233
|
+
});
|
|
234
|
+
} catch (err: any) {
|
|
235
|
+
finish({error: err.message});
|
|
236
|
+
}
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// ---- Deterministic assert + fast-model judge --------------------------------------------
|
|
241
|
+
|
|
242
|
+
/** Runs one assert expression. Returns the verdict plus the error text when the expression
|
|
243
|
+
* itself threw — a broken assert must be distinguishable from a model failure, not silently false.
|
|
244
|
+
* The body is async so assertions may `await`; previously `await` was a syntax error (silent false)
|
|
245
|
+
* and an async IIFE returned a truthy Promise (a guaranteed false positive). */
|
|
246
|
+
async function evalAssert(expr: string, view: DG.ViewBase | null, t: DG.DataFrame | null,
|
|
247
|
+
before: any, opened: number, tools: string[], openedViews: DG.TableView[],
|
|
248
|
+
): Promise<{pass: boolean, error?: string}> {
|
|
249
|
+
try {
|
|
250
|
+
// eslint-disable-next-line no-new-func
|
|
251
|
+
const fn = new Function('grok', 'DG', 'view', 't', 'before', 'opened', 'tools', 'openedViews',
|
|
252
|
+
`return (async () => (${expr}))();`);
|
|
253
|
+
return {pass: !!await fn(grok, DG, view, t, before, opened, tools, openedViews)};
|
|
254
|
+
} catch (e: any) {
|
|
255
|
+
const error = `assert threw: ${e?.message ?? e}`;
|
|
256
|
+
console.warn('benchmark:', error, expr);
|
|
257
|
+
return {pass: false, error};
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** What the workspace looked like when an assert failed. Without this a failing row only says
|
|
262
|
+
* "wrong", and every investigation turns into guessing whether the assert or the model was at
|
|
263
|
+
* fault — which is how a benchmark ends up blaming the model for its own bugs. Kept short: enough
|
|
264
|
+
* to tell a mis-bound viewer from a missing one, not a full dump. */
|
|
265
|
+
function describeState(view: DG.ViewBase | null, t: DG.DataFrame | null, before: any): string {
|
|
266
|
+
const parts: string[] = [];
|
|
267
|
+
try {
|
|
268
|
+
const tv = view as DG.TableView | null;
|
|
269
|
+
if (tv?.viewers) {
|
|
270
|
+
const viewers = Array.from(tv.viewers).filter((v) => v.type !== DG.VIEWER.GRID).map((v) => {
|
|
271
|
+
// Only the column-binding props matter here, and only the ones that are set — a full
|
|
272
|
+
// property dump would bury the one field that is usually wrong.
|
|
273
|
+
const bound = ['xColumnName', 'yColumnName', 'valueColumnName', 'splitColumnName',
|
|
274
|
+
'category1ColumnName', 'colorColumnName', 'categoryColumnNames']
|
|
275
|
+
.map((p) => {
|
|
276
|
+
try {
|
|
277
|
+
const val = (v.props as any)[p];
|
|
278
|
+
return val == null || (Array.isArray(val) && !val.length) ? null : `${p}=${val}`;
|
|
279
|
+
} catch {
|
|
280
|
+
return null;
|
|
281
|
+
}
|
|
282
|
+
}).filter(Boolean);
|
|
283
|
+
return `${v.type}(${bound.join(', ') || 'no columns bound'})`;
|
|
284
|
+
});
|
|
285
|
+
parts.push(`viewers: ${viewers.length ? viewers.join(' · ') : 'none beyond the grid'}`);
|
|
286
|
+
}
|
|
287
|
+
if (t) {
|
|
288
|
+
const added = t.columns.names().filter((n: string) => before.cols.indexOf(n) < 0);
|
|
289
|
+
const removed = before.cols.filter((n: string) => !t.columns.contains(n));
|
|
290
|
+
if (added.length) parts.push(`added cols: ${added.join(', ')}`);
|
|
291
|
+
if (removed.length) parts.push(`removed cols: ${removed.join(', ')}`);
|
|
292
|
+
parts.push(`rows ${t.rowCount}/${before.rowCount}, filtered-in ${t.filter.trueCount}, selected ${t.selection.trueCount}`);
|
|
293
|
+
if (tv?.grid) {
|
|
294
|
+
const hidden = t.columns.names().filter((n: string) => {
|
|
295
|
+
try {
|
|
296
|
+
return tv.grid.col(n)?.visible === false;
|
|
297
|
+
} catch {
|
|
298
|
+
return false;
|
|
299
|
+
}
|
|
300
|
+
});
|
|
301
|
+
if (hidden.length) parts.push(`grid-hidden: ${hidden.join(', ')}`);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
} catch (e: any) {
|
|
305
|
+
parts.push(`(state capture failed: ${e?.message ?? e})`);
|
|
306
|
+
}
|
|
307
|
+
return parts.join(' | ');
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
const JUDGE_SCHEMA = {
|
|
311
|
+
type: 'object',
|
|
312
|
+
properties: {pass: {type: 'boolean'}, score: {type: 'number'}, reason: {type: 'string'}},
|
|
313
|
+
required: ['pass', 'score'],
|
|
314
|
+
};
|
|
315
|
+
|
|
316
|
+
async function judge(client: ClaudeRuntimeClient, prompt: string, answer: string, rubric: string): Promise<JudgeResult> {
|
|
317
|
+
const jp = `You are grading an AI assistant's answer against a rubric. Be strict but fair.\n\n` +
|
|
318
|
+
`USER PROMPT:\n${prompt}\n\nASSISTANT ANSWER:\n${answer || '(empty)'}\n\nRUBRIC:\n${rubric}\n\n` +
|
|
319
|
+
`Return pass (boolean), score (0..1), and a one-line reason.`;
|
|
320
|
+
// One retry: a judge call that times out (the runtime watchdog can kill a wedged agent) must not
|
|
321
|
+
// flip a correct answer to failed on transient grounds.
|
|
322
|
+
for (let attempt = 0; ; attempt++) {
|
|
323
|
+
try {
|
|
324
|
+
const r = await client.query(jp, {outputSchema: JUDGE_SCHEMA, systemPromptMode: 'none', feature: AiFeature.Benchmark});
|
|
325
|
+
return {pass: !!r.pass, score: typeof r.score === 'number' ? r.score : (r.pass ? 1 : 0), reason: r.reason ?? ''};
|
|
326
|
+
} catch (e: any) {
|
|
327
|
+
if (attempt >= 1)
|
|
328
|
+
return {pass: false, score: 0, reason: `judge failed: ${e.message}`};
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// ---- Stats ------------------------------------------------------------------------------
|
|
334
|
+
|
|
335
|
+
function stats(values: (number | null | undefined)[]): Stats {
|
|
336
|
+
const xs = values.filter((v): v is number => typeof v === 'number' && !isNaN(v)).sort((a, b) => a - b);
|
|
337
|
+
const n = xs.length;
|
|
338
|
+
if (!n) return {n: 0, median: null, mean: null, min: null, max: null, p90: null, std: null};
|
|
339
|
+
const at = (q: number) => xs[Math.min(n - 1, Math.max(0, Math.round(q * (n - 1))))];
|
|
340
|
+
const mean = xs.reduce((s, v) => s + v, 0) / n;
|
|
341
|
+
const variance = xs.reduce((s, v) => s + (v - mean) * (v - mean), 0) / n;
|
|
342
|
+
return {n, median: at(0.5), mean, min: xs[0], max: xs[n - 1], p90: at(0.9), std: Math.sqrt(variance)};
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
// ---- Orchestration ----------------------------------------------------------------------
|
|
346
|
+
|
|
347
|
+
async function runPrompt(client: ClaudeRuntimeClient, p: SuitePrompt, reps: number): Promise<PromptResult> {
|
|
348
|
+
const turns: RepTurn[] = [];
|
|
349
|
+
for (let i = 0; i < reps; i++) {
|
|
350
|
+
const preViews = openTableViews();
|
|
351
|
+
let view: DG.TableView | null = null;
|
|
352
|
+
try {
|
|
353
|
+
if (p.table) {
|
|
354
|
+
view = grok.shell.addTableView(await freshTable(p.table));
|
|
355
|
+
await delay(120);
|
|
356
|
+
}
|
|
357
|
+
const t = view ? view.dataFrame : null;
|
|
358
|
+
const before = {
|
|
359
|
+
cols: t ? t.columns.names() : [],
|
|
360
|
+
rowCount: t ? t.rowCount : 0,
|
|
361
|
+
viewers: view ? Array.from(view.viewers).length : 0,
|
|
362
|
+
tableViews: openTableViews().length,
|
|
363
|
+
};
|
|
364
|
+
const turn = await runTurn(client, p.prompt, view, undefined, p.difficulty);
|
|
365
|
+
if (turn.ok && p.assert) {
|
|
366
|
+
await delay(ASSERT_SETTLE_MS); // let async filter/viewer updates land before reading state
|
|
367
|
+
const after = openTableViews();
|
|
368
|
+
const openedViews = after.filter((v) => preViews.indexOf(v) < 0 && v !== view);
|
|
369
|
+
const {pass, error} = await evalAssert(p.assert, view, t, before,
|
|
370
|
+
after.length - before.tableViews, turn.tools, openedViews);
|
|
371
|
+
turn.assertPass = pass;
|
|
372
|
+
if (error) turn.assertError = error;
|
|
373
|
+
if (!pass) turn.failState = describeState(view, t, before);
|
|
374
|
+
}
|
|
375
|
+
turns.push(turn);
|
|
376
|
+
} catch (e: any) {
|
|
377
|
+
turns.push({ok: false, ttftMs: null, totalMs: null, toolRoundTrips: 0, tools: [], ctxChars: 0,
|
|
378
|
+
toolDefCount: 0, server: null, assertPass: null, unverified: false, content: '', error: e.message});
|
|
379
|
+
} finally {
|
|
380
|
+
// Close the bench table and anything the assistant opened, so reps stay isolated.
|
|
381
|
+
for (const v of openTableViews())
|
|
382
|
+
if (preViews.indexOf(v) < 0) try {v.close();} catch {}
|
|
383
|
+
await delay(60);
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
const ok = turns.filter((t) => t.ok);
|
|
388
|
+
const assertTurns = turns.filter((t) => t.assertPass !== null);
|
|
389
|
+
const assertPassRate = assertTurns.length ? assertTurns.filter((t) => t.assertPass).length / assertTurns.length : null;
|
|
390
|
+
// Judge every rep that produced text, not just the last one: latency is measured at n=reps, so
|
|
391
|
+
// scoring at n=1 let the same defect flip pass/fail between runs.
|
|
392
|
+
const judged = p.rubric ?
|
|
393
|
+
(await Promise.all(ok.filter((t) => t.content).map((t) => judge(client, p.prompt, t.content, p.rubric!)))) : [];
|
|
394
|
+
const judgeRes: JudgeResult | null = judged.length ? {
|
|
395
|
+
pass: judged.filter((j) => j.pass && j.score >= JUDGE_SCORE_FLOOR).length > judged.length / 2,
|
|
396
|
+
score: judged.reduce((s, j) => s + j.score, 0) / judged.length,
|
|
397
|
+
reason: judged.map((j) => j.reason).find((r) => r) ?? '',
|
|
398
|
+
} : null;
|
|
399
|
+
// A prompt that failed every rep is a FAILURE, not "unscored". Leaving it null dropped it from
|
|
400
|
+
// the denominator, which is how a 19-prompt run reported "16/18".
|
|
401
|
+
const accuracyPass = ok.length === 0 ? false :
|
|
402
|
+
assertPassRate !== null ? assertPassRate >= 0.5 :
|
|
403
|
+
judgeRes ? judgeRes.pass : null;
|
|
404
|
+
|
|
405
|
+
return {
|
|
406
|
+
category: p.category, prompt: p.prompt,
|
|
407
|
+
difficulty: p.difficulty ?? 'standard',
|
|
408
|
+
reps, okCount: ok.length,
|
|
409
|
+
toolsUsed: Array.from(new Set(turns.flatMap((t) => t.tools))),
|
|
410
|
+
unverifiedRate: ok.length ? ok.filter((t) => t.unverified).length / ok.length : 0,
|
|
411
|
+
ttftMs: stats(ok.map((t) => t.ttftMs)),
|
|
412
|
+
totalMs: stats(ok.map((t) => t.totalMs)),
|
|
413
|
+
toolRoundTrips: stats(ok.map((t) => t.toolRoundTrips)),
|
|
414
|
+
inputTokens: stats(ok.map((t) => t.server?.inputTokens ?? null)),
|
|
415
|
+
outputTokens: stats(ok.map((t) => t.server?.outputTokens ?? null)),
|
|
416
|
+
cacheReadTokens: stats(ok.map((t) => t.server?.cacheReadTokens ?? null)),
|
|
417
|
+
costUsd: stats(ok.map((t) => t.server?.costUsd ?? null)),
|
|
418
|
+
ctxChars: ok[0]?.ctxChars ?? 0,
|
|
419
|
+
toolDefCount: ok[0]?.toolDefCount ?? 0,
|
|
420
|
+
assertPassRate, judge: judgeRes, accuracyPass,
|
|
421
|
+
...(turns.find((t) => t.failState)?.failState ? {failState: turns.find((t) => t.failState)!.failState} : {}),
|
|
422
|
+
errors: [
|
|
423
|
+
...turns.filter((t) => t.error).map((t) => t.error!),
|
|
424
|
+
...turns.filter((t) => t.assertError).map((t) => t.assertError!),
|
|
425
|
+
],
|
|
426
|
+
};
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
// ---- Report -----------------------------------------------------------------------------
|
|
430
|
+
|
|
431
|
+
const r1 = (v: number | null) => v == null ? '—' : (Math.round(v * 10) / 10).toString();
|
|
432
|
+
const r0 = (v: number | null) => v == null ? '—' : Math.round(v).toString();
|
|
433
|
+
const usd = (v: number | null) => v == null ? '—' : '$' + v.toFixed(4);
|
|
434
|
+
/** Null when no prompt has a cost: the runtime prices no call of a model its price list lacks. */
|
|
435
|
+
const costSum = (rs: PromptResult[]) => rs.some((r) => r.costUsd.median != null) ?
|
|
436
|
+
rs.reduce((s, r) => s + (r.costUsd.median ?? 0), 0) : null;
|
|
437
|
+
|
|
438
|
+
/** One rollup row over an arbitrary slice of the results — shared by the difficulty and
|
|
439
|
+
* category tables so the two can never drift in how they aggregate. */
|
|
440
|
+
function rollupRow(name: string, rs: PromptResult[], hasTokens: boolean): string {
|
|
441
|
+
const sc = rs.filter((r) => r.accuracyPass !== null);
|
|
442
|
+
const passed = sc.filter((r) => r.accuracyPass).length;
|
|
443
|
+
const cells = [name, `${rs.length}`,
|
|
444
|
+
r0(stats(rs.map((r) => r.totalMs.median)).median),
|
|
445
|
+
r1(stats(rs.map((r) => r.toolRoundTrips.median)).median),
|
|
446
|
+
`${passed}/${sc.length}` + (sc.length ? ` (${Math.round(100 * passed / sc.length)}%)` : '')];
|
|
447
|
+
if (hasTokens) cells.push(usd(costSum(rs)));
|
|
448
|
+
return '| ' + cells.join(' | ') + ' |';
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
function rollupTable(title: string, groups: [string, PromptResult[]][], hasTokens: boolean): string[] {
|
|
452
|
+
const cols = ['', 'n', 'Median ms', 'Tools', 'Accuracy', ...(hasTokens ? ['Cost'] : [])];
|
|
453
|
+
const lines = ['## ' + title, '', '| ' + cols.join(' | ') + ' |', '|' + cols.map(() => '---').join('|') + '|'];
|
|
454
|
+
for (const [name, rs] of groups) lines.push(rollupRow(name, rs, hasTokens));
|
|
455
|
+
lines.push('');
|
|
456
|
+
return lines;
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
function buildMarkdown(label: string, when: string, reps: number, results: PromptResult[],
|
|
460
|
+
hasTokens: boolean, only?: string): string {
|
|
461
|
+
const scored = results.filter((r) => r.accuracyPass !== null);
|
|
462
|
+
const passed = scored.filter((r) => r.accuracyPass).length;
|
|
463
|
+
const totalMed = stats(results.map((r) => r.totalMs.median));
|
|
464
|
+
const ttftMed = stats(results.map((r) => r.ttftMs.median));
|
|
465
|
+
const cost = costSum(results);
|
|
466
|
+
|
|
467
|
+
const lines: string[] = [];
|
|
468
|
+
lines.push(`# Grokky benchmark — \`${label}\``);
|
|
469
|
+
lines.push('');
|
|
470
|
+
lines.push(`| | |`);
|
|
471
|
+
lines.push(`|---|---|`);
|
|
472
|
+
lines.push(`| **When** | ${when} |`);
|
|
473
|
+
lines.push(`| **Prompts × reps** | ${results.length} × ${reps} = ${results.length * reps} turns |`);
|
|
474
|
+
if (only) lines.push(`| **Suite filter** | \`${only}\` — ⚠️ partial run, not comparable to a full arm |`);
|
|
475
|
+
lines.push(`| **Accuracy** | **${passed}/${scored.length}**` +
|
|
476
|
+
(scored.length ? ` (${Math.round(100 * passed / scored.length)}%)` : '') + ` |`);
|
|
477
|
+
lines.push(`| **Median turn** | ${r0(totalMed.median)} ms |`);
|
|
478
|
+
lines.push(`| **Median TTFT** | ${r0(ttftMed.median)} ms |`);
|
|
479
|
+
if (hasTokens) {
|
|
480
|
+
lines.push(`| **Cost** | ${usd(cost)} total` +
|
|
481
|
+
(passed && cost != null ? ` · ${usd(cost / passed)} per passed prompt` : '') + ` |`);
|
|
482
|
+
} else
|
|
483
|
+
lines.push(`| **Cost** | ⚠️ unavailable — no turn reported usage metrics |`);
|
|
484
|
+
lines.push('');
|
|
485
|
+
|
|
486
|
+
// Per-difficulty rollup: a blended number hides where a configuration actually differs. This
|
|
487
|
+
// is what showed a cheap tier taking 8 tool round-trips on prompts the strong tier does in 1.
|
|
488
|
+
const tiers = (['trivial', 'standard', 'hard'] as const).filter((d) => results.some((r) => r.difficulty === d));
|
|
489
|
+
if (tiers.length > 1)
|
|
490
|
+
lines.push(...rollupTable('By difficulty', tiers.map((d) => [d, results.filter((r) => r.difficulty === d)]), hasTokens));
|
|
491
|
+
|
|
492
|
+
const cats = Array.from(new Set(results.map((r) => r.category))).sort();
|
|
493
|
+
if (cats.length > 1)
|
|
494
|
+
lines.push(...rollupTable('By category', cats.map((c) => [c, results.filter((r) => r.category === c)]), hasTokens));
|
|
495
|
+
|
|
496
|
+
lines.push('## Per prompt');
|
|
497
|
+
lines.push('');
|
|
498
|
+
const cols = hasTokens ?
|
|
499
|
+
['Category', 'Diff', 'Prompt', 'n', 'TTFT ms', 'Total ms', 'In tok', 'Out tok', 'Cache rd', 'Cost', 'Tools', 'Acc'] :
|
|
500
|
+
['Category', 'Diff', 'Prompt', 'n', 'TTFT ms', 'Total ms', 'Tools', 'Acc'];
|
|
501
|
+
lines.push('| ' + cols.join(' | ') + ' |');
|
|
502
|
+
lines.push('|' + cols.map(() => '---').join('|') + '|');
|
|
503
|
+
for (const r of results) {
|
|
504
|
+
const prompt = r.prompt.length > 48 ? r.prompt.slice(0, 47) + '…' : r.prompt;
|
|
505
|
+
// Show the raw rate, not a bare tick: 2-of-3 and 3-of-3 are different signals, and the
|
|
506
|
+
// threshold alone hid flaky prompts.
|
|
507
|
+
const rate = r.assertPassRate !== null ? ` ${Math.round(100 * r.assertPassRate)}%` :
|
|
508
|
+
r.judge ? ` ${r.judge.score.toFixed(2)}` : '';
|
|
509
|
+
const acc = r.accuracyPass == null ? '—' : `${r.accuracyPass ? '✅' : '❌'}${rate}`;
|
|
510
|
+
const base = [r.category, r.difficulty, prompt, `${r.okCount}/${r.reps}`,
|
|
511
|
+
r0(r.ttftMs.median), r0(r.totalMs.median)];
|
|
512
|
+
const row = hasTokens ?
|
|
513
|
+
[...base, r0(r.inputTokens.median), r0(r.outputTokens.median), r0(r.cacheReadTokens.median),
|
|
514
|
+
usd(r.costUsd.median), r1(r.toolRoundTrips.median), acc] :
|
|
515
|
+
[...base, r1(r.toolRoundTrips.median), acc];
|
|
516
|
+
lines.push('| ' + row.join(' | ') + ' |');
|
|
517
|
+
}
|
|
518
|
+
lines.push('');
|
|
519
|
+
lines.push('_Values are per-prompt medians across reps. TTFT = time to first streamed token; ' +
|
|
520
|
+
'Total = send→final wall-clock; Tools = tool round-trips/turn. Acc shows the assert pass ' +
|
|
521
|
+
'rate across reps, or the mean judge score._');
|
|
522
|
+
|
|
523
|
+
// A red cell in the table above says *that* something failed; this says *what*, which is the
|
|
524
|
+
// difference between a report you can act on and one you have to re-run to understand.
|
|
525
|
+
const failed = results.filter((r) => r.accuracyPass === false);
|
|
526
|
+
if (failed.length) {
|
|
527
|
+
lines.push('');
|
|
528
|
+
lines.push(`## ❌ Failures (${failed.length})`);
|
|
529
|
+
lines.push('');
|
|
530
|
+
for (const r of failed) {
|
|
531
|
+
const why = r.okCount === 0 ? `every rep errored — ${r.errors[0] ?? 'no detail'}` :
|
|
532
|
+
r.assertPassRate !== null ? `assert passed ${Math.round(100 * r.assertPassRate)}% of reps` :
|
|
533
|
+
r.judge ? `judge ${r.judge.score.toFixed(2)} — ${r.judge.reason}` : 'unscored';
|
|
534
|
+
lines.push(`- **${r.category}/${r.difficulty}** \`${r.prompt}\``);
|
|
535
|
+
lines.push(` - ${why}`);
|
|
536
|
+
if (r.failState) lines.push(` - left: ${r.failState}`);
|
|
537
|
+
if (r.toolsUsed.length) lines.push(` - tools: ${r.toolsUsed.join(' → ')}`);
|
|
538
|
+
const errs = Array.from(new Set(r.errors)).slice(0, 2);
|
|
539
|
+
for (const e of errs) lines.push(` - \`${e.slice(0, 200)}\``);
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
// Kept separate from failures on purpose: an assert that throws is *my* bug, and counting it as
|
|
544
|
+
// a model failure is how a harness quietly reports progress it never made.
|
|
545
|
+
const broken = results.filter((r) => r.errors.some((e) => e.startsWith('assert threw')));
|
|
546
|
+
if (broken.length) {
|
|
547
|
+
lines.push('');
|
|
548
|
+
lines.push('## ⚠️ Broken assertions (harness bug, not a model failure)');
|
|
549
|
+
lines.push('');
|
|
550
|
+
for (const r of broken)
|
|
551
|
+
lines.push(`- \`${r.prompt.slice(0, 60)}\` — ${r.errors.find((e) => e.startsWith('assert threw'))}`);
|
|
552
|
+
}
|
|
553
|
+
return lines.join('\n');
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
function downloadText(filename: string, text: string): void {
|
|
557
|
+
const blob = new Blob([text], {type: 'application/octet-stream'});
|
|
558
|
+
const url = URL.createObjectURL(blob);
|
|
559
|
+
const a = document.createElement('a');
|
|
560
|
+
a.href = url;
|
|
561
|
+
a.download = filename;
|
|
562
|
+
document.body.appendChild(a);
|
|
563
|
+
a.click();
|
|
564
|
+
window.setTimeout(() => {document.body.removeChild(a); URL.revokeObjectURL(url);}, 0);
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
/** Runs the benchmark suite on the runtime's configured model and downloads a `benchmark-<label>.{json,md}`
|
|
568
|
+
* report; to compare models, run one arm per model, each labelled after it. */
|
|
569
|
+
export async function runBenchmark(label: string, reps: number, only?: string): Promise<string> {
|
|
570
|
+
label = sanitizeLabel(label);
|
|
571
|
+
reps = reps && reps > 0 ? Math.floor(reps) : 3;
|
|
572
|
+
const client = ClaudeRuntimeClient.getInstance();
|
|
573
|
+
await client.ensureConnected();
|
|
574
|
+
const all = await loadSuite();
|
|
575
|
+
const suite = filterSuite(all, only);
|
|
576
|
+
if (!suite.length)
|
|
577
|
+
return only ? `No suite prompt matches "${only}" (${all.length} in suite).` : 'Benchmark suite is empty.';
|
|
578
|
+
|
|
579
|
+
grok.shell.info(`Benchmark "${label}": ${suite.length} prompts × ${reps} reps — warming up…`);
|
|
580
|
+
// The container is on-demand: `ensureConnected` returns as soon as the socket is up, but the
|
|
581
|
+
// runtime behind it can still be booting and will answer instantly with nothing. Block until a
|
|
582
|
+
// turn actually produces output, or the whole arm scores against a container that isn't there.
|
|
583
|
+
for (let i = 0; i < READY_ATTEMPTS; i++) {
|
|
584
|
+
// systemPromptMode 'none' is essential, not an optimisation: under the full prompt the
|
|
585
|
+
// GroundingGate blocks a content-free probe and sends the model off reading help pages until
|
|
586
|
+
// the turn timeout, so the probe measures the gate rather than whether the runtime is up.
|
|
587
|
+
const probe = await runTurn(client, 'Reply with exactly: READY', null, 'none');
|
|
588
|
+
if (probe.ok && probe.content.trim()) break;
|
|
589
|
+
if (i === READY_ATTEMPTS - 1)
|
|
590
|
+
return `Runtime never became ready (${READY_ATTEMPTS} probes) — is the claude-runtime container up?`;
|
|
591
|
+
grok.shell.info(`Benchmark "${label}": runtime not ready, retrying (${i + 1}/${READY_ATTEMPTS})…`);
|
|
592
|
+
await delay(READY_RETRY_MS);
|
|
593
|
+
}
|
|
594
|
+
// Warm-up turn (discarded) — primes the static-prefix prompt cache with the real system prompt.
|
|
595
|
+
try {
|
|
596
|
+
const w = suite[0];
|
|
597
|
+
const preViews = openTableViews();
|
|
598
|
+
const view = w.table ? grok.shell.addTableView(await freshTable(w.table)) : null;
|
|
599
|
+
await runTurn(client, w.prompt, view);
|
|
600
|
+
for (const v of openTableViews()) if (preViews.indexOf(v) < 0) try {v.close();} catch {}
|
|
601
|
+
} catch (e) {console.warn('benchmark: warm-up failed', e);}
|
|
602
|
+
|
|
603
|
+
const results: PromptResult[] = [];
|
|
604
|
+
for (let i = 0; i < suite.length; i++) {
|
|
605
|
+
grok.shell.info(`Benchmark "${label}": ${i + 1}/${suite.length} — ${suite[i].category}`);
|
|
606
|
+
results.push(await runPrompt(client, suite[i], reps));
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
const hasTokens = results.some((r) => r.inputTokens.n > 0);
|
|
610
|
+
const when = new Date().toISOString();
|
|
611
|
+
const report: BenchReport = {label, when, reps, hasTokens, ...(only ? {only} : {}), results};
|
|
612
|
+
const markdown = buildMarkdown(label, when, reps, results, hasTokens, only);
|
|
613
|
+
downloadText(`benchmark-${label}.json`, JSON.stringify(report, null, 2));
|
|
614
|
+
downloadText(`benchmark-${label}.md`, markdown);
|
|
615
|
+
// Persist server-side too, so compareBenchmarks() can diff runs across configs and a headless
|
|
616
|
+
// runner can retrieve the report without touching the browser's download directory.
|
|
617
|
+
try {
|
|
618
|
+
await grok.dapi.files.writeAsText(benchPath(label), JSON.stringify(report));
|
|
619
|
+
await grok.dapi.files.writeAsText(benchPath(label).replace(/\.json$/, '.md'), markdown);
|
|
620
|
+
} catch (e) {console.warn('benchmark: could not persist report to AppData', e);}
|
|
621
|
+
|
|
622
|
+
const scored = results.filter((r) => r.accuracyPass !== null);
|
|
623
|
+
const passed = scored.filter((r) => r.accuracyPass).length;
|
|
624
|
+
const msg = `Benchmark "${label}" complete — ${suite.length} prompts × ${reps} reps, ` +
|
|
625
|
+
`accuracy ${passed}/${scored.length}. Report downloaded.` +
|
|
626
|
+
(hasTokens ? '' : ' (Token metrics unavailable: no turn reported them.)');
|
|
627
|
+
grok.shell.info(msg);
|
|
628
|
+
return msg;
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
// ---- Compare two runs -------------------------------------------------------------------
|
|
632
|
+
|
|
633
|
+
async function loadReport(label: string): Promise<BenchReport | null> {
|
|
634
|
+
try {
|
|
635
|
+
const path = benchPath(label);
|
|
636
|
+
if (!await grok.dapi.files.exists(path)) return null;
|
|
637
|
+
return JSON.parse(await grok.dapi.files.readAsText(path)) as BenchReport;
|
|
638
|
+
} catch {
|
|
639
|
+
return null;
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
function overall(rep: BenchReport) {
|
|
644
|
+
const scored = rep.results.filter((r) => r.accuracyPass !== null);
|
|
645
|
+
return {
|
|
646
|
+
totalMs: stats(rep.results.map((r) => r.totalMs.median)).median,
|
|
647
|
+
ttftMs: stats(rep.results.map((r) => r.ttftMs.median)).median,
|
|
648
|
+
inputTokens: stats(rep.results.map((r) => r.inputTokens.median)).median,
|
|
649
|
+
costSum: costSum(rep.results),
|
|
650
|
+
accPassed: scored.filter((r) => r.accuracyPass).length,
|
|
651
|
+
accScored: scored.length,
|
|
652
|
+
};
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
const pct = (a: number | null, b: number | null): string =>
|
|
656
|
+
a == null || b == null || a === 0 ? '—' : (b >= a ? '+' : '') + Math.round(100 * (b - a) / a) + '%';
|
|
657
|
+
|
|
658
|
+
/** Compares two or more saved runs (comma-separated labels) into one Markdown report.
|
|
659
|
+
* N-way rather than pairwise because a model-routing question has at least three arms — cheap,
|
|
660
|
+
* strong, and routed — and reading it as two separate diffs hides where routing actually landed.
|
|
661
|
+
* The first label is the reference every change column is measured against. */
|
|
662
|
+
export async function compareBenchmarks(labels: string): Promise<string> {
|
|
663
|
+
const wanted = labels.split(',').map((s) => s.trim()).filter(Boolean);
|
|
664
|
+
if (wanted.length < 2) return 'Give at least two comma-separated run labels to compare.';
|
|
665
|
+
const loaded = await Promise.all(wanted.map(loadReport));
|
|
666
|
+
const missing = wanted.filter((_, i) => !loaded[i]);
|
|
667
|
+
if (missing.length) return `Missing report(s): ${missing.map(sanitizeLabel).join(', ')}`;
|
|
668
|
+
const reps = loaded as BenchReport[];
|
|
669
|
+
const [ref] = reps;
|
|
670
|
+
const os = reps.map(overall);
|
|
671
|
+
|
|
672
|
+
const lines: string[] = [];
|
|
673
|
+
lines.push(`# Benchmark comparison — ${reps.map((r) => '`' + r.label + '`').join(' vs ')}`);
|
|
674
|
+
lines.push('');
|
|
675
|
+
lines.push(`Reference arm: \`${ref.label}\`. Change columns are relative to it; ` +
|
|
676
|
+
`for latency and cost, negative is better.`);
|
|
677
|
+
lines.push('');
|
|
678
|
+
|
|
679
|
+
const head = ['Metric', ...reps.map((r, i) => r.label + (i ? '' : ' (ref)'))];
|
|
680
|
+
lines.push('| ' + head.join(' | ') + ' |');
|
|
681
|
+
lines.push('|' + head.map(() => '---').join('|') + '|');
|
|
682
|
+
const row = (name: string, get: (o: ReturnType<typeof overall>) => number | null, fmt: (v: number | null) => string) =>
|
|
683
|
+
lines.push(`| ${name} | ` + os.map((o, i) =>
|
|
684
|
+
fmt(get(o)) + (i ? ` (${pct(get(os[0]), get(o))})` : '')).join(' | ') + ' |');
|
|
685
|
+
lines.push(`| Accuracy | ` + os.map((o) => `**${o.accPassed}/${o.accScored}**` +
|
|
686
|
+
(o.accScored ? ` (${Math.round(100 * o.accPassed / o.accScored)}%)` : '')).join(' | ') + ' |');
|
|
687
|
+
row('Median turn (ms)', (o) => o.totalMs, r0);
|
|
688
|
+
row('Median TTFT (ms)', (o) => o.ttftMs, r0);
|
|
689
|
+
row('Median input tokens', (o) => o.inputTokens, r0);
|
|
690
|
+
row('Cost (sum of medians)', (o) => o.costSum, usd);
|
|
691
|
+
lines.push('');
|
|
692
|
+
|
|
693
|
+
// Where routing actually landed: a cheap arm is only interesting if it holds accuracy on the
|
|
694
|
+
// easy tiers, so the per-tier accuracy split is the decision-relevant view, not the aggregate.
|
|
695
|
+
const tiers = (['trivial', 'standard', 'hard'] as const)
|
|
696
|
+
.filter((d) => ref.results.some((r) => r.difficulty === d));
|
|
697
|
+
if (tiers.length > 1) {
|
|
698
|
+
lines.push('## Accuracy by difficulty');
|
|
699
|
+
lines.push('');
|
|
700
|
+
lines.push('| Difficulty | ' + reps.map((r) => r.label).join(' | ') + ' |');
|
|
701
|
+
lines.push('|' + ['---', ...reps.map(() => '---')].join('|') + '|');
|
|
702
|
+
for (const d of tiers) {
|
|
703
|
+
lines.push(`| ${d} | ` + reps.map((rep) => {
|
|
704
|
+
const sc = rep.results.filter((r) => r.difficulty === d && r.accuracyPass !== null);
|
|
705
|
+
return `${sc.filter((r) => r.accuracyPass).length}/${sc.length}`;
|
|
706
|
+
}).join(' | ') + ' |');
|
|
707
|
+
}
|
|
708
|
+
lines.push('');
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
// Per-prompt, showing accuracy alongside time: a faster arm that quietly stopped passing a
|
|
712
|
+
// prompt is the failure mode a latency-only table is blind to.
|
|
713
|
+
lines.push('## Per prompt — median turn ms (accuracy)');
|
|
714
|
+
lines.push('');
|
|
715
|
+
lines.push('| Category | Diff | Prompt | ' + reps.map((r) => r.label).join(' | ') + ' |');
|
|
716
|
+
lines.push('|' + ['---', '---', '---', ...reps.map(() => '---')].join('|') + '|');
|
|
717
|
+
const indexes = reps.map((rep) => new Map(rep.results.map((r) => [r.prompt, r])));
|
|
718
|
+
for (const rr of ref.results) {
|
|
719
|
+
const prompt = rr.prompt.length > 46 ? rr.prompt.slice(0, 45) + '…' : rr.prompt;
|
|
720
|
+
const cells = indexes.map((ix) => {
|
|
721
|
+
const r = ix.get(rr.prompt);
|
|
722
|
+
if (!r) return '—';
|
|
723
|
+
const mark = r.accuracyPass == null ? '' : r.accuracyPass ? ' ✅' : ' ❌';
|
|
724
|
+
return `${r0(r.totalMs.median)}${mark}`;
|
|
725
|
+
});
|
|
726
|
+
lines.push(`| ${rr.category} | ${rr.difficulty} | ${prompt} | ` + cells.join(' | ') + ' |');
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
const md = lines.join('\n');
|
|
730
|
+
const name = `benchmark-compare-${wanted.map(sanitizeLabel).join('-vs-')}`;
|
|
731
|
+
downloadText(`${name}.md`, md);
|
|
732
|
+
try {
|
|
733
|
+
await grok.dapi.files.writeAsText(`${BENCH_DIR}/${name}.md`, md);
|
|
734
|
+
} catch (e) {console.warn('benchmark: could not persist comparison to AppData', e);}
|
|
735
|
+
grok.shell.info(`Compared ${wanted.length} runs. Report downloaded.`);
|
|
736
|
+
return md;
|
|
737
|
+
}
|