vectorbench 3.0.4 → 3.1.1

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/NOTICE CHANGED
@@ -20,7 +20,7 @@ worker/fonts/DejaVuSans.ttf
20
20
  DejaVu Sans, from the DejaVu fonts (https://dejavu-fonts.github.io/).
21
21
  Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera
22
22
  is a trademark of Bitstream, Inc. DejaVu changes are in the public domain.
23
- Used under the Bitstream Vera Fonts licence; the full terms are in
23
+ Used under the Bitstream Vera Fonts license; the full terms are in
24
24
  worker/fonts/DejaVu-LICENSE.txt, which must travel with the font.
25
25
 
26
26
 
@@ -28,7 +28,7 @@ Not in this repository
28
28
  ----------------------
29
29
 
30
30
  These are fetched when you install, build or deploy, each under its own
31
- licence:
31
+ license:
32
32
 
33
33
  - The npm packages listed in package-lock.json. Two of them end up inside
34
34
  what the site serves: the WebAssembly build of resvg from
@@ -44,6 +44,6 @@ Not licensed
44
44
  ------------
45
45
 
46
46
  The VectorBench name and logo are not licensed under the Apache License or
47
- any other licence (see section 6 of the Apache License). The logo appears in
47
+ any other license (see section 6 of the Apache License). The logo appears in
48
48
  the icon files in public/ and is drawn by src/brand.js. If you run your own
49
49
  copy of the site, give it your own name and icons.
package/README.md CHANGED
@@ -133,10 +133,10 @@ version its drawing was made with.
133
133
  https://huggingface.co/vectorbench, each month's votes 30 days after it
134
134
  ends. The first release is due in mid-December 2026.
135
135
 
136
- ## Licences
136
+ ## Licenses
137
137
 
138
138
  - Code: Apache License 2.0 (`LICENSE`). Third-party files keep their own
139
- licences, listed in `NOTICE`.
139
+ licenses, listed in `NOTICE`.
140
140
  - Prompt texts: Creative Commons Attribution 4.0 (`PROMPTS-LICENSE.md`).
141
141
  - Model drawings: CC0 1.0. Please cite VectorBench when you use them.
142
142
  - The VectorBench name and logo are not licensed. If you run your own copy
package/bench.config.mjs CHANGED
@@ -87,9 +87,9 @@ export const prompts = [
87
87
  // test new models with on X, so a visitor can hold ours against the ones
88
88
  // they've seen. The Xbox 360 controller is the most common of them. Real,
89
89
  // well-known products, checkable against the real thing: the controllers'
90
- // stick and button layout and the colours and symbols on their face
90
+ // stick and button layout and the colors and symbols on their face
91
91
  // buttons; the Game Boy's power light, screen and Start/Select; the
92
- // cube's 3×3 faces, its six colours and the one solved face; the
92
+ // cube's 3×3 faces, its six colors and the one solved face; the
93
93
  // unicorn's single horn and its weight on two hind legs.
94
94
  { id: 'xbox-controller', text: 'An Xbox 360 controller, seen from above' },
95
95
  { id: 'playstation-controller', text: 'A PlayStation 5 DualSense controller, seen from above' },
@@ -259,16 +259,17 @@ export const models = [
259
259
  // criteria chart is drawn from. They follow "What wins votes" in the request
260
260
  // above, split where the sandbox gives a model a separate way to get it right:
261
261
  // measurements and 3D for accuracy, generated repetition for detail, computed
262
- // shading and perceptual colour for light and colour, `check` and `zoom` for
262
+ // shading and perceptual color for light and color, `check` and `zoom` for
263
263
  // a clean finish, `frames` for motion.
264
264
  //
265
- // `id` is permanent (it is stored with each judgment). `when: 'animated'`
266
- // is only asked when at least one of the two SVGs moves.
265
+ // `id` is stored with each judgment, so renaming one takes a migration (as
266
+ // migrations/0033_criterion_color.sql did). `when: 'animated'` is only asked
267
+ // when at least one of the two SVGs moves.
267
268
  export const criteria = [
268
269
  { id: 'request', name: 'Matches the request', short: 'Request', hint: 'Everything asked for is there and right: the subject, what it’s doing, and any number, words or arrangement.' },
269
270
  { id: 'accuracy', name: 'True to the real thing', short: 'Accuracy', hint: 'Proportions, anatomy and mechanics are right, and the parts fit together as they really do.' },
270
271
  { id: 'composition', name: 'Composition', short: 'Composition', hint: 'It fills the frame, reads at a glance, and the setting suits the subject.' },
271
- { id: 'colour', name: 'Colour', short: 'Colour', hint: 'A deliberate palette that suits the subject.' },
272
+ { id: 'color', name: 'Color', short: 'Color', hint: 'A deliberate palette that suits the subject.' },
272
273
  { id: 'light', name: 'Light and depth', short: 'Light and depth', hint: 'Shading, shadows and highlights that make it look solid.' },
273
274
  { id: 'detail', name: 'Detail', short: 'Detail', hint: 'Fine detail and texture that hold up when you enlarge it.' },
274
275
  { id: 'finish', name: 'Clean finish', short: 'Finish', hint: 'Nothing broken: no stray shapes, gaps, bad overlaps or cut-off parts, and any lettering is readable.' },
@@ -15,8 +15,10 @@ const { version } = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8'))
15
15
 
16
16
  const HELP = `vectorbench ${version}: draw VectorBench's prompts with your own model (https://vectorbench.ai)
17
17
 
18
- vectorbench draw --model <id> draw every prompt with one model and zip the drawings to send
19
- (--prompt <id> for one first; \`vectorbench draw --help\` lists the options)
18
+ vectorbench draw --model <id> draw every prompt with one model, on GitHub and on your API key, signed so
19
+ the site can check the model; leaves a zip to send
20
+ (--prompt <id> for one first; --local to draw on this machine, unsigned,
21
+ on a plan or a key; \`vectorbench draw --help\` lists the options)
20
22
  vectorbench doctor check this machine has what a drawing run needs
21
23
  vectorbench prompts list the prompts
22
24
  vectorbench criteria list what voters can judge a pair of drawings on, besides the vote
@@ -7,8 +7,8 @@
7
7
  # Bump the tag when anything here changes; the tag is written to each log.
8
8
  #
9
9
  # 4 (18 November 2026): more to draw with and more to look with. Libraries
10
- # for path booleans, noise, perceptual colour, 3D meshes, graph layout and
11
- # raster-to-vector tracing; Graphviz; SVGO; a shelf of open-licence fonts to
10
+ # for path booleans, noise, perceptual color, 3D meshes, graph layout and
11
+ # raster-to-vector tracing; Graphviz; SVGO; a shelf of open-license fonts to
12
12
  # outline lettering in; and the `zoom`, `compare`, `weigh` and `shrink`
13
13
  # commands (box/tools.py). Most entries were pressed against the 200 KB
14
14
  # limit (120 of the 287 drawn with image 3 were over 180 KB), which `weigh`
@@ -29,7 +29,7 @@
29
29
  # 7 (18 November 2026), from the first harness 2 runs (Haiku 5.5, GPT-6.1
30
30
  # Terra, GPT-6.2 Astra): `vb3d`, a module that renders trimesh meshes as
31
31
  # shaded SVG (hidden surfaces removed, cast shadows, exact outlines and
32
- # crease lines), since no run modelled its subject in 3D although the request
32
+ # crease lines), since no run modeled its subject in 3D although the request
33
33
  # suggests it; OpenCV, which two runs reached for; and `submit drawing.svg`
34
34
  # now works (it was refused for its argument, once at reply 37 of 40); and
35
35
  # /work/README.md, a one-page guide to the commands, import names and vb3d,
@@ -48,16 +48,16 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
48
48
  chromium \
49
49
  # Languages.
50
50
  python3 python3-pip python-is-python3 nodejs \
51
- # Python libraries for geometry, colour, paths and XML.
51
+ # Python libraries for geometry, color, paths and XML.
52
52
  python3-numpy python3-scipy python3-pil python3-lxml python3-shapely \
53
53
  python3-fonttools python3-matplotlib python3-skimage python3-cairosvg \
54
- # Exact maths, and graphs with their layouts.
54
+ # Exact math, and graphs with their layouts.
55
55
  python3-sympy python3-networkx \
56
56
  # Vector and raster tools. Graphviz lays out diagrams (dot -Tsvg).
57
57
  inkscape imagemagick librsvg2-bin potrace libxml2-utils graphviz scour \
58
58
  # Fonts behind the generic families (sans-serif, serif, monospace).
59
59
  fonts-dejavu-core fonts-liberation2 fonts-noto-core fonts-noto-color-emoji \
60
- # Open-licence typefaces to turn lettering into outlines with
60
+ # Open-license typefaces to turn lettering into outlines with
61
61
  # (inkscape --export-text-to-path, or fontTools); fc-list lists them.
62
62
  fonts-dejavu-extra fonts-ebgaramond fonts-lato fonts-open-sans fonts-roboto-unhinted \
63
63
  fonts-cantarell fonts-urw-base35 fonts-texgyre fonts-firacode fonts-inter \
@@ -71,11 +71,11 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
71
71
  skia-pathops \
72
72
  # Smooth noise for organic shapes and texture.
73
73
  opensimplex \
74
- # Perceptual colour: OKLCH mixing, gradients, contrast.
74
+ # Perceptual color: OKLCH mixing, gradients, contrast.
75
75
  coloraide \
76
76
  # 3D meshes and solids to model a subject in, then project to 2D.
77
77
  trimesh manifold3d mapbox-earcut \
78
- # Colour raster-to-vector tracing (potrace does one colour).
78
+ # Color raster-to-vector tracing (potrace does one color).
79
79
  vtracer \
80
80
  # Image processing that models reach for by name (cv2).
81
81
  opencv-python-headless \
package/harness/codex.mjs CHANGED
@@ -335,7 +335,7 @@ const usageOf = (counts = {}) => ({
335
335
  reasoning: counts.reasoningOutputTokens ?? 0,
336
336
  });
337
337
 
338
- /** One request Codex logged, as kept: everything but the conversation, which is summarised. */
338
+ /** One request Codex logged, as kept: everything but the conversation, which is summarized. */
339
339
  export function requestRecord(url, body) {
340
340
  const { input = [], client_metadata, prompt_cache_key, ...settings } = body;
341
341
  return {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vectorbench",
3
- "version": "3.0.4",
3
+ "version": "3.1.1",
4
4
  "description": "Draw VectorBench's SVG prompts with your own model, in the same sandbox as the benchmark at vectorbench.ai",
5
5
  "homepage": "https://vectorbench.ai",
6
6
  "repository": {
@@ -26,6 +26,7 @@
26
26
  "bin/",
27
27
  "bench.config.mjs",
28
28
  "scripts/partner.mjs",
29
+ "scripts/verified.mjs",
29
30
  "scripts/harness.mjs",
30
31
  "scripts/doctor.mjs",
31
32
  "scripts/zip.mjs",
@@ -72,6 +73,10 @@
72
73
  "@cloudflare/puppeteer": "2.0.1",
73
74
  "@fontsource-variable/archivo": "^5.3.0",
74
75
  "@resvg/resvg-wasm": "^2.6.2",
76
+ "@sigstore/bundle": "5.0.1",
77
+ "@sigstore/core": "4.0.2",
78
+ "@sigstore/protobuf-specs": "0.5.2",
79
+ "@sigstore/verify": "4.1.4",
75
80
  "esbuild": "^0.28.2",
76
81
  "postal-mime": "^4.2.1",
77
82
  "wrangler": "4.161.0"
@@ -2,6 +2,12 @@
2
2
  // through the same harness, sandbox and budget as our own drawings, and
3
3
  // leaves a zip to send at https://vectorbench.ai/partners.
4
4
  //
5
+ // Without --local the drawings are made on GitHub's runners, on the partner's
6
+ // own API key, and GitHub signs each one with a record of what was asked
7
+ // (scripts/verified.mjs): the site can then check the model and the reasoning
8
+ // setting instead of taking the sender's word. With --local they are made on
9
+ // this machine, as before, and nothing vouches for them but our review.
10
+ //
5
11
  // npx vectorbench@latest draw --model gpt-6.2-astra no clone needed
6
12
  // npm run partner -- --model gpt-6.2-astra the same, in a clone; a model in bench.config.mjs
7
13
  // npm run partner -- --model gpt-6.2-astra --prompt chessboard one prompt first, to see the cost
@@ -10,6 +16,12 @@
10
16
  // --via <provider> anthropic | openai | gemini | xai | openrouter: whose API answers
11
17
  // --api-model <id> the model's id at that API (default: the --model id)
12
18
  // --effort <level> its highest reasoning setting, up to max
19
+ // --local draw on this machine, unsigned: the only way to use a Claude, ChatGPT
20
+ // or Grok plan instead of an API key. The options below it are for --local.
21
+ // --yes (signed runs) don't ask before making the repository and storing the key
22
+ // --repo <o/name> (signed runs) the public repository of yours to run in (default <you>/vectorbench-runs)
23
+ // --keep-secret (signed runs) leave the key stored as the repository's secret afterwards
24
+ // --collect <run> (signed runs) fetch the drawings of a run that was left to finish
13
25
  // --codex an OpenAI model through the Codex CLI on your ChatGPT plan; the default
14
26
  // when OPENAI_API_KEY isn't set and Codex is installed
15
27
  // --grok-build an xAI model through Grok Build on your Grok plan; the default
@@ -27,16 +39,16 @@
27
39
  // picks up where a stopped run left off: the first answer stands.
28
40
 
29
41
  import { spawnSync } from 'node:child_process';
30
- import { copyFileSync, existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
42
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
31
43
  import { join, relative, resolve } from 'node:path';
32
44
  import { models as lineup, prompts, upcomingModels } from '../bench.config.mjs';
33
45
  import { KEYS } from '../harness/adapters/index.mjs';
34
46
  import { HARNESS } from '../harness/request.mjs';
35
47
  import { IMAGE } from '../harness/sandbox.mjs';
36
48
  import { INSTALLED, PROVIDERS, ROOT, check, findChrome, loadEnv, works } from './doctor.mjs';
49
+ import { collect, runVerified } from './verified.mjs';
37
50
  import { zipFolder } from './zip.mjs';
38
51
 
39
- const SITE = 'https://vectorbench.ai';
40
52
  // How this was called, for the examples it prints: bin/vectorbench.mjs says `vectorbench draw`.
41
53
  const COMMAND = process.env.VB_COMMAND || 'npm run partner --';
42
54
 
@@ -48,14 +60,23 @@ const OPTIONS = ` --model <id> the model to draw with (the only one that
48
60
  --api-model <id> for a model we don't list: its id at that API, if it differs from --model
49
61
  --effort <level> for a model we don't list: its highest reasoning setting, up to max
50
62
  --name <name> for a model we don't list: what to call it
63
+ --dry-run show what would be asked and what is missing, and ask nothing
64
+ --out <dir> where to write
65
+
66
+ The drawings are made on GitHub, on your API key, and signed, so the site can check the model and reasoning setting:
67
+ --yes don't ask before making the repository and storing the key as its secret
68
+ --repo <o/name> the public repository of yours to run in (default <you>/vectorbench-runs)
69
+ --keep-secret leave the key stored as the repository's secret afterwards
70
+ --collect <run> fetch the drawings of a run you left to finish
71
+
72
+ --local draw on this machine instead, unsigned (the only way to use a plan rather than an API key):
51
73
  --codex an OpenAI model through the Codex CLI, on your ChatGPT plan (the default when OPENAI_API_KEY isn't set)
52
74
  --grok-build an xAI model through Grok Build, on your Grok plan (the default when XAI_API_KEY isn't set)
53
75
  --api a Claude model on ANTHROPIC_API_KEY, instead of Claude Code on your Claude plan
54
- --dry-run show what would be asked and what is missing, and ask nothing
55
- --out <dir> where to write
56
76
  --concurrency <n> drawings at once (default 3)`;
57
- const VALUED = ['model', 'prompt', 'via', 'api-model', 'effort', 'name', 'out', 'concurrency'];
58
- const FLAGS = ['codex', 'grok-build', 'api', 'dry-run', 'help'];
77
+ const VALUED = ['model', 'prompt', 'via', 'api-model', 'effort', 'name', 'out', 'concurrency', 'repo', 'collect'];
78
+ const FLAGS = ['codex', 'grok-build', 'api', 'dry-run', 'help', 'local', 'yes', 'keep-secret'];
79
+ const LOCAL_ONLY = ['codex', 'grok-build', 'api', 'concurrency'];
59
80
 
60
81
  // --name=value is the same as --name value.
61
82
  const args = process.argv.slice(2).flatMap((arg) => (/^--[a-z-]+=/.test(arg) ? [arg.slice(0, arg.indexOf('=')), arg.slice(arg.indexOf('=') + 1)] : [arg]));
@@ -82,6 +103,22 @@ for (let i = 0; i < args.length; i++) {
82
103
  }
83
104
  if (option('concurrency') && !/^[1-9]\d*$/.test(option('concurrency'))) stop('--concurrency takes a whole number, 1 or more.');
84
105
 
106
+ const { version: VERSION } = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8'));
107
+ const SITE = 'https://vectorbench.ai';
108
+
109
+ // A run that was left to finish: its drawings, once it has.
110
+ if (option('collect')) {
111
+ if (!/^\d+$/.test(option('collect'))) stop('--collect takes the run\'s number, from its address on GitHub.');
112
+ const login = spawnSync(process.env.GH_BIN || 'gh', ['api', 'user', '--jq', '.login'], { encoding: 'utf8' }).stdout?.trim();
113
+ if (!option('repo') && !login) stop('Sign in to GitHub first (`gh auth login`), or name the repository with --repo <owner/name>.');
114
+ try {
115
+ collect({ repo: option('repo') ?? `${login}/vectorbench-runs`, runId: option('collect'), out: option('out') && resolve(option('out')), command: COMMAND, site: SITE, modelId: option('model') });
116
+ } catch (error) {
117
+ stop(error.message);
118
+ }
119
+ process.exit(0);
120
+ }
121
+
85
122
  /* The model ---------------------------------------------------------------- */
86
123
 
87
124
  const id = option('model');
@@ -106,6 +143,26 @@ for (const p of wantedPrompts) if (!prompts.some((x) => x.id === p)) stop(`There
106
143
  /* What it runs on ---------------------------------------------------------- */
107
144
 
108
145
  const keyName = KEYS[model.via];
146
+ const shown = (path) => relative(process.cwd(), path) || '.';
147
+
148
+ // Signed, on GitHub, unless told to stay here.
149
+ if (!flag('local')) {
150
+ const stray = LOCAL_ONLY.filter((name) => flag(name));
151
+ if (stray.length) stop(`--${stray[0]} is for a run on this machine: add --local. Without it the drawings are made on GitHub, on your API key, and signed.`);
152
+ await runVerified({
153
+ model,
154
+ extra,
155
+ prompts: wantedPrompts,
156
+ keyName,
157
+ out: resolve(option('out') ?? join('vectorbench-drawings', model.id)),
158
+ version: VERSION,
159
+ command: COMMAND,
160
+ flags: { dryRun, yes: flag('yes'), keepSecret: flag('keep-secret'), repo: option('repo') },
161
+ stop,
162
+ site: SITE,
163
+ });
164
+ process.exit(0);
165
+ }
109
166
  // An OpenAI model with no API key goes to the ChatGPT plan when the Codex CLI is here, without being told to.
110
167
  const codexBin = process.env.CODEX_BIN || 'codex';
111
168
  const codex = model.via === 'openai' && (flag('codex') || (!process.env[keyName] && works(codexBin, ['--version'])));
@@ -123,7 +180,6 @@ if (missing.length) {
123
180
 
124
181
  // From a clone the drawings stay in it; run with npx, they land where the command was typed.
125
182
  const OUT = resolve(option('out') ?? (INSTALLED ? join('vectorbench-drawings', model.id) : join(ROOT, 'harness', 'trial-partner', model.id)));
126
- const shown = (path) => relative(process.cwd(), path) || '.';
127
183
  console.log(`${model.name} (${model.model}, effort ${model.effort}) on ${route === 'API' ? `${model.via}'s API, billed to your ${keyName}` : `${route}, on your plan`}: ${wantedPrompts.length} prompt${wantedPrompts.length === 1 ? '' : 's'}, into ${shown(OUT)}/.`);
128
184
 
129
185
  if (!dryRun && !works('docker', ['image', 'inspect', IMAGE])) {
@@ -168,4 +224,5 @@ writeFileSync(ZIP, zipFolder(OUT, 'drawings'));
168
224
  console.log(`
169
225
  Look them over: ${shown(join(OUT, 'index.html'))}
170
226
  Send them: ${SITE}/partners, sign in, choose the model, and drop in ${shown(ZIP)}
227
+ Unsigned: made on this machine, so the site has only your word for the model. Without --local, GitHub draws and signs them.
171
228
  Made with: VectorBench harness ${HARNESS.version} (sandbox ${IMAGE}), ${route === 'API' ? `${model.via} API` : route}, effort ${model.effort}`);
@@ -0,0 +1,336 @@
1
+ // A verified drawing run: the drawings are made on a GitHub-hosted runner by
2
+ // our own workflow (.github/workflows/draw.yml, called from a repository of
3
+ // the partner's), and GitHub signs each drawing with a record of the run. The
4
+ // signature names the workflow and commit that made it, so the model and the
5
+ // reasoning setting in the record are the ones our code asked for: nothing on
6
+ // the partner's machine is in a position to change them.
7
+ //
8
+ // Their API key is stored as a secret of their own repository, encrypted by
9
+ // `gh` before it leaves the machine. It goes from GitHub's runner to the
10
+ // provider's API and nowhere else: not to us, and not into a log.
11
+ //
12
+ // runVerified(...) what `vectorbench draw` does (scripts/partner.mjs):
13
+ // drives the run with the GitHub CLI and leaves one zip
14
+ // node scripts/verified.mjs plan on the runner, first: the prompts to draw ($MODEL, $PROMPTS), as the
15
+ // workflow's matrix; an unknown prompt or a malformed model id ends the run here
16
+ // node scripts/verified.mjs record --out <dir> --model <id> --prompt <id>
17
+ // on the runner, after the harness: writes
18
+ // <dir>/verified/<prompt>.svg and <prompt>.run.json,
19
+ // the two files the workflow signs
20
+ //
21
+ // The zip, for https://vectorbench.ai/partners:
22
+ // drawings/<prompt>.svg the drawing, as the model made it
23
+ // runs/<prompt>.json the record (RECORD_VERSION below)
24
+ // attestations/<prompt>.sigstore.json GitHub's signature over both
25
+
26
+ import { spawnSync } from 'node:child_process';
27
+ import { createHash } from 'node:crypto';
28
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
29
+ import { tmpdir } from 'node:os';
30
+ import { join, relative } from 'node:path';
31
+ import { createInterface } from 'node:readline/promises';
32
+ import { fileURLToPath, pathToFileURL } from 'node:url';
33
+ import { models as lineup, prompts as allPrompts, upcomingModels } from '../bench.config.mjs';
34
+ import { zip } from './zip.mjs';
35
+
36
+ const ROOT = fileURLToPath(new URL('../', import.meta.url));
37
+
38
+ /** The repository whose workflow draws, and the workflow. The site accepts no other signer (worker/attest.js). */
39
+ export const SOURCE = 'vectorbench/vectorbench';
40
+ export const WORKFLOW = '.github/workflows/draw.yml';
41
+ /** The partner's repository the runs happen in, and the file there that calls ours. */
42
+ export const RUNS_REPO = 'vectorbench-runs';
43
+ export const CALLER = '.github/workflows/vectorbench.yml';
44
+ /** Bump when the record's fields change meaning. */
45
+ export const RECORD_VERSION = 1;
46
+
47
+ const sha256 = (data) => createHash('sha256').update(data).digest('hex');
48
+
49
+ /* On the runner ------------------------------------------------------------ */
50
+
51
+ /**
52
+ * The record of one drawing, from the harness's own log of it: what was asked
53
+ * of whom, what answered, and which run on GitHub it was. `env` is the
54
+ * runner's environment (GITHUB_*); `source` is the commit of ours that ran.
55
+ */
56
+ export function record({ log, svg, version, listed = false, env = process.env, source = {} }) {
57
+ return {
58
+ vectorbench: RECORD_VERSION,
59
+ package: version,
60
+ prompt: log.prompt,
61
+ // `listed`: the model is one in bench.config.mjs at this commit, asked the way it says. Any other was
62
+ // described by whoever started the run (--via, --api-model, --effort), and the id is only their name for it.
63
+ model: { id: log.model, via: log.via, apiModel: log.apiModel, effort: log.effort, listed },
64
+ route: log.route,
65
+ baseUrl: log.baseUrl,
66
+ servedModel: log.servedModel ?? null,
67
+ responseIds: log.responseIds ?? [],
68
+ harness: log.harness,
69
+ askedAt: log.askedAt,
70
+ seconds: log.seconds,
71
+ replies: log.replies,
72
+ views: log.views,
73
+ ended: log.ended,
74
+ outcome: log.outcome,
75
+ usage: log.usage ? { input: log.usage.input, cached: log.usage.cached, output: log.usage.output, cost: log.usage.cost ?? null, costIs: log.usage.costIs } : null,
76
+ svgSha256: svg == null ? null : sha256(svg),
77
+ github: {
78
+ repository: env.GITHUB_REPOSITORY ?? null,
79
+ runId: env.GITHUB_RUN_ID ?? null,
80
+ runAttempt: env.GITHUB_RUN_ATTEMPT ?? null,
81
+ workflow: source.ref ?? null,
82
+ commit: source.sha ?? null,
83
+ },
84
+ };
85
+ }
86
+
87
+ /** The workflow's matrix: `prompts=["id", ...]`, from what the caller asked for. */
88
+ export function plan({ model, prompts }) {
89
+ if (!/^[a-z0-9][a-z0-9.-]*$/.test(model ?? '')) throw new Error(`"${model}" can't be a model id: lower-case letters, digits, dots and hyphens.`);
90
+ const known = allPrompts.map((p) => p.id);
91
+ const wanted = (prompts ?? '').split(',').map((id) => id.trim()).filter(Boolean);
92
+ for (const id of wanted) if (!known.includes(id)) throw new Error(`There is no prompt "${id}". The prompts: ${known.join(', ')}.`);
93
+ return `prompts=${JSON.stringify(wanted.length ? known.filter((id) => wanted.includes(id)) : known)}`;
94
+ }
95
+
96
+ function recordCommand(args) {
97
+ const option = (name) => (args.includes(`--${name}`) ? args[args.indexOf(`--${name}`) + 1] : undefined);
98
+ const [out, model, prompt] = ['out', 'model', 'prompt'].map(option);
99
+ if (!out || !model || !prompt) throw new Error('record takes --out <dir> --model <id> --prompt <id>');
100
+ const logFile = join(out, 'log', prompt, `${model}.json`);
101
+ if (!existsSync(logFile)) throw new Error(`There is no log of ${model} drawing ${prompt}: the model was not asked, or the provider did not answer. Nothing to sign.`);
102
+ const log = JSON.parse(readFileSync(logFile, 'utf8'));
103
+ const svgFile = join(out, prompt, `${model}.svg`);
104
+ // The bytes that are signed are the bytes that are sent: the file as the harness wrote it.
105
+ const svg = log.outcome === 'drawn' && existsSync(svgFile) ? readFileSync(svgFile) : null;
106
+ const { version } = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8'));
107
+ const folder = join(out, 'verified');
108
+ mkdirSync(folder, { recursive: true });
109
+ if (svg) writeFileSync(join(folder, `${prompt}.svg`), svg);
110
+ const known = [...lineup, ...upcomingModels].find((m) => m.id === log.model);
111
+ const listed = Boolean(known) && known.via === log.via && known.model === log.apiModel && known.effort === log.effort && log.route === log.via;
112
+ const made = record({ log, svg, version, listed, source: { ref: process.env.VB_WORKFLOW_REF, sha: process.env.VB_WORKFLOW_SHA } });
113
+ writeFileSync(join(folder, `${prompt}.run.json`), JSON.stringify(made, null, 2) + '\n');
114
+ console.log(`${prompt}: ${log.outcome}${svg ? `, sha256 ${made.svgSha256}` : ''}`);
115
+ }
116
+
117
+ /* On the partner's machine -------------------------------------------------- */
118
+
119
+ /** The workflow in the partner's repository: it only calls ours, at the tag of this package's version. */
120
+ export const callerWorkflow = (version) => `# Written by \`vectorbench draw\`. It calls VectorBench's own drawing workflow, which
121
+ # runs on GitHub's runner and signs what it draws: https://vectorbench.ai/partners
122
+ name: VectorBench drawings
123
+ run-name: \${{ inputs.model }}
124
+
125
+ on:
126
+ workflow_dispatch:
127
+ inputs:
128
+ model: { description: 'The model to draw with', required: true, type: string }
129
+ prompts: { description: 'Prompt ids, comma-separated (empty: all)', required: false, type: string, default: '' }
130
+ via: { description: "For a model we don't list: whose API answers", required: false, type: string, default: '' }
131
+ api_model: { description: "For a model we don't list: its id at that API", required: false, type: string, default: '' }
132
+ effort: { description: "For a model we don't list: its highest reasoning setting", required: false, type: string, default: '' }
133
+
134
+ permissions: {}
135
+
136
+ jobs:
137
+ draw:
138
+ permissions:
139
+ contents: read
140
+ id-token: write
141
+ attestations: write
142
+ uses: ${SOURCE}/${WORKFLOW}@v${version}
143
+ with:
144
+ model: \${{ inputs.model }}
145
+ prompts: \${{ inputs.prompts }}
146
+ via: \${{ inputs.via }}
147
+ api_model: \${{ inputs.api_model }}
148
+ effort: \${{ inputs.effort }}
149
+ secrets:
150
+ ANTHROPIC_API_KEY: \${{ secrets.ANTHROPIC_API_KEY }}
151
+ OPENAI_API_KEY: \${{ secrets.OPENAI_API_KEY }}
152
+ GEMINI_API_KEY: \${{ secrets.GEMINI_API_KEY }}
153
+ XAI_API_KEY: \${{ secrets.XAI_API_KEY }}
154
+ OPENROUTER_API_KEY: \${{ secrets.OPENROUTER_API_KEY }}
155
+ `;
156
+
157
+ /**
158
+ * The zip to send, from the folders `gh run download` leaves (one per
159
+ * drawing, each holding <prompt>.svg, <prompt>.run.json and
160
+ * <prompt>.sigstore.json). Returns { zip, drawn, failed }: the prompts with a
161
+ * signed drawing, and those the run recorded without one.
162
+ */
163
+ export function pack(downloaded) {
164
+ const entries = [];
165
+ const drawn = [];
166
+ const failed = [];
167
+ for (const folder of readdirSync(downloaded, { withFileTypes: true }).filter((item) => item.isDirectory()).map((item) => item.name).sort()) {
168
+ const files = readdirSync(join(downloaded, folder));
169
+ const runFile = files.find((name) => name.endsWith('.run.json'));
170
+ if (!runFile) continue;
171
+ const prompt = runFile.slice(0, -'.run.json'.length);
172
+ const bundle = `${prompt}.sigstore.json`;
173
+ if (!files.includes(bundle)) continue;
174
+ if (!files.includes(`${prompt}.svg`)) {
175
+ failed.push(prompt);
176
+ continue;
177
+ }
178
+ drawn.push(prompt);
179
+ entries.push({ name: `drawings/${prompt}.svg`, data: readFileSync(join(downloaded, folder, `${prompt}.svg`)) });
180
+ entries.push({ name: `runs/${prompt}.json`, data: readFileSync(join(downloaded, folder, runFile)) });
181
+ entries.push({ name: `attestations/${bundle}`, data: readFileSync(join(downloaded, folder, bundle)) });
182
+ }
183
+ return { zip: entries.length ? zip(entries) : null, drawn, failed };
184
+ }
185
+
186
+ const GH = () => process.env.GH_BIN || 'gh';
187
+ /** Runs gh and answers { ok, out, err }. `input` goes to its standard input, which is how a key is handed over: never as an argument. */
188
+ function gh(args, { input, show = false } = {}) {
189
+ const ran = spawnSync(GH(), args, { encoding: 'utf8', input, stdio: show ? ['ignore', 'inherit', 'inherit'] : ['pipe', 'pipe', 'pipe'], env: { ...process.env, GH_PROMPT_DISABLED: '1' } });
190
+ return { ok: ran.status === 0, out: (ran.stdout ?? '').trim(), err: (ran.stderr ?? '').trim() };
191
+ }
192
+
193
+ const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
194
+
195
+ /**
196
+ * `vectorbench draw`: has GitHub draw `prompts` with `model` on the partner's
197
+ * own key, and leaves the signed zip in `out`. `stop(message)` ends the
198
+ * command; `flags` are { dryRun, yes, keepSecret }. `extra` is set for a
199
+ * model we don't list ({ via, model, effort }).
200
+ */
201
+ export async function runVerified({ model, extra, prompts, keyName, out, version, command, flags, stop, site }) {
202
+ const shown = (path) => relative(process.cwd(), path) || '.';
203
+ const key = process.env[keyName];
204
+ const problems = [];
205
+ if (!gh(['--version']).ok) problems.push('The GitHub CLI (`gh`): https://cli.github.com. The run happens on GitHub, in a repository of yours.');
206
+ else if (!gh(['auth', 'status', '--hostname', 'github.com']).ok) problems.push('A GitHub sign-in: run `gh auth login -s workflow`.');
207
+ if (!key) problems.push(`${keyName}, in the environment or in a .env file here. It is stored as a secret of your own repository and used only by the run.`);
208
+
209
+ console.log(`${model.name} (${model.model}, effort ${model.effort}) on ${model.via}'s API, billed to your ${keyName}: ${prompts.length} prompt${prompts.length === 1 ? '' : 's'}, drawn on GitHub and signed.`);
210
+ if (problems.length) {
211
+ console.error(`Missing:\n${problems.map((line) => ` - ${line}`).join('\n')}\n\nTo draw on this machine instead, unsigned: ${command} --model ${model.id} --local`);
212
+ if (!flags.dryRun) process.exit(1);
213
+ }
214
+
215
+ const login = problems.length ? '<you>' : gh(['api', 'user', '--jq', '.login']).out;
216
+ const repo = flags.repo ?? `${login}/${RUNS_REPO}`;
217
+ console.log(`
218
+ What this does:
219
+ 1. Uses the public repository ${repo} on GitHub (made if it isn't there), with one workflow that calls ${SOURCE}@v${version}.
220
+ 2. Stores ${keyName} there as an encrypted secret. Only the run can read it; it is deleted when the run ends${flags.keepSecret ? ' (kept, with --keep-secret)' : ''}.
221
+ 3. Starts the run: one job for each prompt, on GitHub's runners. Each asks ${model.model} at effort ${model.effort}, and GitHub signs the drawing with a record of what was asked.
222
+ 4. Downloads the drawings and signatures into ${shown(out)}/.
223
+ The repository is public, so anyone signed in to GitHub can see the run's log and its drawings. Your key is masked in the log.`);
224
+ if (flags.dryRun) return;
225
+
226
+ if (!flags.yes) {
227
+ if (!process.stdin.isTTY) stop(`\nAdd --yes to go ahead without being asked.`);
228
+ const ask = createInterface({ input: process.stdin, output: process.stdout });
229
+ const answer = (await ask.question('\nGo ahead? [y/N] ')).trim().toLowerCase();
230
+ ask.close();
231
+ if (!['y', 'yes'].includes(answer)) stop('Nothing was done.');
232
+ }
233
+
234
+ /* The repository and its workflow. */
235
+ const seen = gh(['repo', 'view', repo, '--json', 'visibility', '--jq', '.visibility']);
236
+ if (!seen.ok) {
237
+ if (flags.repo) stop(`There is no repository ${repo} that this sign-in can see.`);
238
+ const made = gh(['repo', 'create', repo, '--public', '--add-readme', '--description', 'Drawings for VectorBench, made and signed on GitHub (https://vectorbench.ai/partners)']);
239
+ if (!made.ok) stop(`Couldn't make ${repo}: ${made.err}`);
240
+ console.log(`\nMade https://github.com/${repo}.`);
241
+ } else if (seen.out !== 'PUBLIC') {
242
+ stop(`${repo} is private. GitHub signs runs for free only in a public repository: make it public, or name another with --repo <owner/name>.`);
243
+ }
244
+
245
+ const wanted = callerWorkflow(version);
246
+ const current = gh(['api', `repos/${repo}/contents/${CALLER}`, '--jq', '[.sha, .content] | @tsv']);
247
+ const [currentSha, currentContent] = current.ok ? current.out.split('\t') : [];
248
+ if (!current.ok || Buffer.from(currentContent.replaceAll('\\n', ''), 'base64').toString() !== wanted) {
249
+ const put = gh(['api', '-X', 'PUT', `repos/${repo}/contents/${CALLER}`, '-f', `message=VectorBench drawing workflow, v${version}`, '-f', `content=${Buffer.from(wanted).toString('base64')}`, ...(currentSha ? ['-f', `sha=${currentSha}`] : [])]);
250
+ if (!put.ok) stop(/workflow/i.test(put.err) ? `GitHub refused the workflow file: this sign-in may not write workflows. Run \`gh auth refresh -h github.com -s workflow\`, then this command again.` : `Couldn't write ${CALLER} to ${repo}: ${put.err}`);
251
+ }
252
+
253
+ /* The key, the run, and the key's removal whatever happens. */
254
+ const stored = gh(['secret', 'set', keyName, '--repo', repo], { input: key });
255
+ if (!stored.ok) stop(`Couldn't store ${keyName} as a secret of ${repo}: ${stored.err}`);
256
+ const forget = () => {
257
+ if (flags.keepSecret) return;
258
+ const gone = gh(['secret', 'delete', keyName, '--repo', repo]);
259
+ console.log(gone.ok ? `Deleted the secret ${keyName} from ${repo}.` : `Couldn't delete the secret ${keyName} from ${repo} (${gone.err}): delete it at https://github.com/${repo}/settings/secrets/actions`);
260
+ };
261
+ let interrupted = false;
262
+ process.once('SIGINT', () => {
263
+ interrupted = true;
264
+ });
265
+
266
+ let runId;
267
+ try {
268
+ const before = new Date(Date.now() - 5000).toISOString();
269
+ const inputs = { model: model.id, prompts: prompts.length === allPrompts.length ? '' : prompts.join(','), ...(extra && { via: extra.via, api_model: extra.model, effort: extra.effort }) };
270
+ // A workflow file just written takes a moment to be known to Actions.
271
+ let started;
272
+ for (let attempt = 0; attempt < 6; attempt++) {
273
+ started = gh(['workflow', 'run', CALLER.split('/').pop(), '--repo', repo, ...Object.entries(inputs).flatMap(([name, value]) => ['-f', `${name}=${value}`])]);
274
+ if (started.ok) break;
275
+ await sleep(5000);
276
+ }
277
+ if (!started.ok) stop(`Couldn't start the run in ${repo}: ${started.err}`);
278
+ for (let attempt = 0; attempt < 30 && !runId; attempt++) {
279
+ await sleep(2000);
280
+ const listed = gh(['run', 'list', '--repo', repo, '--workflow', CALLER.split('/').pop(), '--event', 'workflow_dispatch', '--limit', '5', '--json', 'databaseId,createdAt']);
281
+ runId = listed.ok ? JSON.parse(listed.out || '[]').find((run) => run.createdAt >= before)?.databaseId : undefined;
282
+ }
283
+ if (!runId) stop(`The run was started, but it isn't listed yet: look at https://github.com/${repo}/actions, and when it is done run \`${command} --collect <run id> --repo ${repo}\`.`);
284
+ console.log(`\nRunning: https://github.com/${repo}/actions/runs/${runId}\nEach drawing has up to an hour. This waits for all of them; if you stop it, collect the drawings later with \`${command} --collect ${runId}\`.\n`);
285
+ gh(['run', 'watch', String(runId), '--repo', repo, '--interval', '30'], { show: true });
286
+ } finally {
287
+ // Stopped by hand, the run goes on with the key it was given: say so rather than pull the key from under it.
288
+ if (interrupted) console.log(`\nStopped waiting. The run goes on, and ${keyName} stays a secret of ${repo} until you run \`${command} --collect ${runId ?? '<run id>'}\`.`);
289
+ else forget();
290
+ }
291
+ if (interrupted) process.exit(130);
292
+ return collect({ repo, runId, out, command, site, modelId: model.id });
293
+ }
294
+
295
+ /** Downloads a finished run's drawings and signatures, and packs the zip. */
296
+ export function collect({ repo, runId, out, command, site, modelId, keyName, flags = {} }) {
297
+ const shown = (path) => relative(process.cwd(), path) || '.';
298
+ const state = gh(['run', 'view', String(runId), '--repo', repo, '--json', 'status,conclusion,displayTitle']);
299
+ if (!state.ok) throw new Error(`There is no run ${runId} in ${repo} that this sign-in can see: ${state.err}`);
300
+ const { status, displayTitle } = JSON.parse(state.out);
301
+ if (status !== 'completed') throw new Error(`Run ${runId} is still going: https://github.com/${repo}/actions/runs/${runId}`);
302
+ if (keyName && !flags.keepSecret) gh(['secret', 'delete', keyName, '--repo', repo]);
303
+
304
+ const scratch = mkdtempSync(join(tmpdir(), 'vectorbench-run-'));
305
+ try {
306
+ const got = gh(['run', 'download', String(runId), '--repo', repo, '--dir', scratch, '--pattern', 'drawing-*']);
307
+ if (!got.ok && !readdirSync(scratch).length) throw new Error(`Run ${runId} left no drawings: its log says why, at https://github.com/${repo}/actions/runs/${runId}`);
308
+ const { zip: packed, drawn, failed } = pack(scratch);
309
+ const id = modelId ?? displayTitle;
310
+ const folder = out ?? join('vectorbench-drawings', id);
311
+ mkdirSync(folder, { recursive: true });
312
+ console.log(`\n${drawn.length} drawn and signed${failed.length ? `; not drawn: ${failed.join(', ')} (the model's answer was not a drawing, and that is its answer)` : ''}.`);
313
+ if (!packed) throw new Error(`Nothing to send. The run: https://github.com/${repo}/actions/runs/${runId}`);
314
+ const file = join(folder, 'vectorbench-verified.zip');
315
+ writeFileSync(file, packed);
316
+ console.log(`
317
+ Send them: ${site}/partners, sign in, choose the model, and drop in ${shown(file)}
318
+ The run: https://github.com/${repo}/actions/runs/${runId}
319
+ The site checks GitHub's signature on each drawing, so the model and reasoning setting shown are the ones the run asked for.`);
320
+ return { file, drawn, failed };
321
+ } finally {
322
+ rmSync(scratch, { recursive: true, force: true });
323
+ }
324
+ }
325
+
326
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
327
+ const [command, ...rest] = process.argv.slice(2);
328
+ try {
329
+ if (command === 'record') recordCommand(rest);
330
+ else if (command === 'plan') console.log(plan({ model: process.env.MODEL, prompts: process.env.PROMPTS }));
331
+ else throw new Error('node scripts/verified.mjs plan | record --out <dir> --model <id> --prompt <id>');
332
+ } catch (error) {
333
+ console.error(error.message);
334
+ process.exit(1);
335
+ }
336
+ }
package/src/model-apis.js CHANGED
@@ -14,12 +14,12 @@
14
14
  export class ProviderError extends Error {
15
15
  /**
16
16
  * `fatal`: nothing sent to this provider will work until something is fixed (key, credit).
17
- * `cancelled`: the person asking gave up; nothing went wrong.
17
+ * `canceled`: the person asking gave up; nothing went wrong.
18
18
  */
19
- constructor(message, { fatal = false, cancelled = false } = {}) {
19
+ constructor(message, { fatal = false, canceled = false } = {}) {
20
20
  super(message);
21
21
  this.fatal = fatal;
22
- this.cancelled = cancelled;
22
+ this.canceled = canceled;
23
23
  }
24
24
  }
25
25
 
@@ -30,14 +30,14 @@ export const RETRIES = 4;
30
30
  // getting on every `timing.pollMs`.
31
31
  export const timing = { pollMs: 10_000, giveUpMs: 90 * 60 * 1000, requestMs: 5 * 60 * 1000 };
32
32
 
33
- const cancelled = () => new ProviderError('Cancelled.', { cancelled: true });
33
+ const canceled = () => new ProviderError('Canceled.', { canceled: true });
34
34
 
35
35
  function sleep(ms, signal) {
36
36
  return new Promise((resolve, reject) => {
37
- if (signal?.aborted) return reject(cancelled());
37
+ if (signal?.aborted) return reject(canceled());
38
38
  const stop = () => {
39
39
  clearTimeout(timer);
40
- reject(cancelled());
40
+ reject(canceled());
41
41
  };
42
42
  const timer = setTimeout(() => {
43
43
  signal?.removeEventListener('abort', stop);
@@ -80,7 +80,7 @@ async function request(method, url, headers, body, { declined = () => false, sig
80
80
  signal: limits.length > 1 ? AbortSignal.any(limits) : limits[0],
81
81
  });
82
82
  } catch (error) {
83
- if (signal?.aborted) throw cancelled();
83
+ if (signal?.aborted) throw canceled();
84
84
  if (attempt < retries) {
85
85
  await sleep(2000 * 2 ** attempt, signal);
86
86
  continue;
@@ -153,7 +153,7 @@ async function eachEvent(response, url, signal, handle) {
153
153
  for await (const event of events(response)) handle(event);
154
154
  } catch (error) {
155
155
  if (error instanceof ProviderError) throw error;
156
- if (signal?.aborted) throw cancelled();
156
+ if (signal?.aborted) throw canceled();
157
157
  throw new ProviderError(`the connection to ${new URL(url).host} dropped before the answer finished (${error.name})`);
158
158
  }
159
159
  }
@@ -184,7 +184,7 @@ async function background(first, { at, headers, running, what, signal, onStatus,
184
184
  try {
185
185
  if (running(data)) data = await waitFor(() => sendJson('GET', at, headers, undefined, { signal, retries, declined }), running, what, { signal, onStatus });
186
186
  } catch (error) {
187
- if (error.cancelled) sendJson('POST', `${at}/cancel`, headers, undefined, { retries: 0 }).catch(() => {});
187
+ if (error.canceled) sendJson('POST', `${at}/cancel`, headers, undefined, { retries: 0 }).catch(() => {});
188
188
  throw error;
189
189
  }
190
190
  await sendJson('DELETE', at, headers, undefined, { retries, declined }).catch(() => {});