@withgateway/sdk 0.1.13 → 0.1.14

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/dist/cli.js ADDED
@@ -0,0 +1,1303 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __esm = (fn, res) => function __init() {
10
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
+ };
12
+ var __export = (target, all) => {
13
+ for (var name in all)
14
+ __defProp(target, name, { get: all[name], enumerable: true });
15
+ };
16
+ var __copyProps = (to, from, except, desc) => {
17
+ if (from && typeof from === "object" || typeof from === "function") {
18
+ for (let key of __getOwnPropNames(from))
19
+ if (!__hasOwnProp.call(to, key) && key !== except)
20
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
21
+ }
22
+ return to;
23
+ };
24
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
25
+ // If the importer is in node compatibility mode or this is not an ESM
26
+ // file that has been converted to a CommonJS file using a Babel-
27
+ // compatible transform (i.e. "__esModule" has not been set), then set
28
+ // "default" to the CommonJS "module.exports" for node compatibility.
29
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
30
+ mod
31
+ ));
32
+
33
+ // src/worlds/session.ts
34
+ var session_exports = {};
35
+ __export(session_exports, {
36
+ WorldSession: () => WorldSession,
37
+ WorldSessionCallError: () => WorldSessionCallError,
38
+ WorldSessionTimeout: () => WorldSessionTimeout,
39
+ attachSession: () => attachSession,
40
+ openSession: () => openSession,
41
+ runSessions: () => runSessions,
42
+ schemaFromSignature: () => schemaFromSignature
43
+ });
44
+ function schemaFromSignature(spec) {
45
+ const inside = /\(([\s\S]*)\)\s*$/.exec(spec.signature.trim())?.[1] ?? "";
46
+ const properties = {};
47
+ const required = [];
48
+ const params = [];
49
+ let depth = 0;
50
+ let current = "";
51
+ for (const ch of inside) {
52
+ if ("([{".includes(ch)) depth++;
53
+ if (")]}".includes(ch)) depth--;
54
+ if (ch === "," && depth === 0) {
55
+ params.push(current);
56
+ current = "";
57
+ } else current += ch;
58
+ }
59
+ if (current.trim()) params.push(current);
60
+ for (const raw of params) {
61
+ const param = raw.trim();
62
+ if (!param || param.startsWith("*") || param === "self") continue;
63
+ const eq = param.indexOf("=");
64
+ const name = (eq === -1 ? param : param.slice(0, eq)).split(":")[0].trim();
65
+ if (!name) continue;
66
+ if (eq === -1) {
67
+ properties[name] = { type: "string" };
68
+ required.push(name);
69
+ continue;
70
+ }
71
+ const value = param.slice(eq + 1).trim();
72
+ if (/^-?\d+(\.\d+)?$/.test(value)) properties[name] = { type: "number" };
73
+ else if (value === "True" || value === "False")
74
+ properties[name] = { type: "boolean" };
75
+ else properties[name] = { type: "string" };
76
+ }
77
+ return {
78
+ type: "function",
79
+ function: {
80
+ name: spec.name,
81
+ description: spec.doc ?? spec.name,
82
+ parameters: { type: "object", properties, required }
83
+ }
84
+ };
85
+ }
86
+ async function attachSession(sessionId, options = {}) {
87
+ const state = await apiRequest(
88
+ options,
89
+ "GET",
90
+ `/api/public/world-sessions/${encodeURIComponent(sessionId)}`
91
+ );
92
+ return new WorldSession(sessionId, state, options);
93
+ }
94
+ async function openSession(slugOrRef, task, opts = {}) {
95
+ const options = opts.options ?? {};
96
+ const at = slugOrRef.indexOf("@");
97
+ const slug = at === -1 ? slugOrRef : slugOrRef.slice(0, at);
98
+ const state = await apiRequest(
99
+ options,
100
+ "POST",
101
+ "/api/public/world-sessions",
102
+ {
103
+ ...opts.versionId ? { versionId: opts.versionId } : { slug },
104
+ task,
105
+ ...opts.reuseWarm === void 0 ? {} : { reuseWarm: opts.reuseWarm }
106
+ }
107
+ );
108
+ return new WorldSession(state.sessionId, state, options);
109
+ }
110
+ async function runSessions(opts) {
111
+ const options = opts.options ?? {};
112
+ const concurrency = Math.max(1, opts.concurrency ?? 3);
113
+ let tasks = opts.tasks;
114
+ let versionId = opts.versionId;
115
+ if (!tasks || !versionId) {
116
+ const { openWorld: openWorld2 } = await Promise.resolve().then(() => (init_worlds(), worlds_exports));
117
+ const world = await openWorld2(opts.world, options);
118
+ tasks = tasks ?? world.tasks.map((t) => t.name);
119
+ versionId = versionId ?? world.version.versionId;
120
+ }
121
+ const results = [];
122
+ let next = 0;
123
+ await Promise.all(
124
+ Array.from({ length: Math.min(concurrency, tasks.length) }, async () => {
125
+ while (next < tasks.length) {
126
+ const task = tasks[next++];
127
+ let session = null;
128
+ try {
129
+ session = await openSession(opts.world, task, {
130
+ versionId,
131
+ options
132
+ });
133
+ await session.ready();
134
+ const toolkit = await session.toolkit();
135
+ await opts.agent({
136
+ session,
137
+ toolkit,
138
+ instruction: session.instruction ?? task,
139
+ task
140
+ });
141
+ const graded = await session.grade();
142
+ const result = {
143
+ task,
144
+ sessionId: session.sessionId,
145
+ reward: graded.reward,
146
+ rewards: graded.rewards
147
+ };
148
+ results.push(result);
149
+ opts.onResult?.(result);
150
+ } catch (error) {
151
+ const result = {
152
+ task,
153
+ sessionId: session?.sessionId ?? "",
154
+ reward: 0,
155
+ rewards: {},
156
+ // An Error with an empty message would read as "no error" to any
157
+ // caller checking truthiness; name the type instead.
158
+ error: (error instanceof Error ? error.message : String(error)) || (error instanceof Error ? error.name : "Unknown error")
159
+ };
160
+ results.push(result);
161
+ opts.onResult?.(result);
162
+ } finally {
163
+ await session?.close({ keepWarm: opts.keepWarm ?? true }).catch(() => void 0);
164
+ }
165
+ }
166
+ })
167
+ );
168
+ const mean = results.reduce((sum, r) => sum + (r.reward ?? 0), 0) / (results.length || 1);
169
+ return {
170
+ results: results.sort((a, b) => a.task.localeCompare(b.task)),
171
+ mean,
172
+ passed: opts.failUnder === void 0 ? true : mean >= opts.failUnder
173
+ };
174
+ }
175
+ var READY_TIMEOUT_MS, READY_POLL_MS, CALL_TIMEOUT_MS, CALL_POLL_MS, sleep, WorldSessionTimeout, WorldSessionCallError, WorldSession;
176
+ var init_session = __esm({
177
+ "src/worlds/session.ts"() {
178
+ "use strict";
179
+ init_worlds();
180
+ READY_TIMEOUT_MS = 10 * 6e4;
181
+ READY_POLL_MS = 2e3;
182
+ CALL_TIMEOUT_MS = 3 * 6e4;
183
+ CALL_POLL_MS = 400;
184
+ sleep = (ms) => new Promise((r) => setTimeout(r, ms));
185
+ WorldSessionTimeout = class extends Error {
186
+ };
187
+ WorldSessionCallError = class extends Error {
188
+ };
189
+ WorldSession = class {
190
+ constructor(sessionId, state, options) {
191
+ this.sessionId = sessionId;
192
+ this.state = state;
193
+ this.options = options;
194
+ }
195
+ get task() {
196
+ return this.state.taskName;
197
+ }
198
+ /** What this task asks for — the bundle's own instruction.md. */
199
+ get instruction() {
200
+ return this.state.instruction ?? null;
201
+ }
202
+ get versionId() {
203
+ return this.state.versionId;
204
+ }
205
+ /** The session's latest platform state (one request, no waiting). */
206
+ async status() {
207
+ const fresh = await apiRequest(
208
+ this.options,
209
+ "GET",
210
+ `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}`
211
+ );
212
+ this.state = {
213
+ instruction: this.state.instruction,
214
+ tools: this.state.tools,
215
+ ...fresh
216
+ };
217
+ return this.state;
218
+ }
219
+ /**
220
+ * Wait until the container is warm — meaning the process inside it has
221
+ * asked the platform for work, not merely that a job was accepted.
222
+ */
223
+ async ready(opts = {}) {
224
+ const deadline = Date.now() + (opts.timeoutMs ?? READY_TIMEOUT_MS);
225
+ for (; ; ) {
226
+ const state = await this.status();
227
+ if (state.ready) return state;
228
+ if (state.state === "FAILED" || state.state === "STOPPED")
229
+ throw new WorldSessionCallError(
230
+ `World session ${state.state.toLowerCase()} before it was ready.`
231
+ );
232
+ if (Date.now() > deadline)
233
+ throw new WorldSessionTimeout(
234
+ `World session still ${state.state} after ${Math.round((opts.timeoutMs ?? READY_TIMEOUT_MS) / 1e3)}s.`
235
+ );
236
+ await sleep(READY_POLL_MS);
237
+ }
238
+ }
239
+ /** Enqueue one interaction and wait for the container's answer. */
240
+ async exchange(body, timeoutMs = CALL_TIMEOUT_MS) {
241
+ const { callId } = await apiRequest(
242
+ this.options,
243
+ "POST",
244
+ `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/calls`,
245
+ body
246
+ );
247
+ const deadline = Date.now() + timeoutMs;
248
+ for (; ; ) {
249
+ const call = await apiRequest(
250
+ this.options,
251
+ "GET",
252
+ `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/calls/${encodeURIComponent(callId)}`
253
+ );
254
+ if (call.done) {
255
+ if (call.error) throw new WorldSessionCallError(call.error);
256
+ return call.result;
257
+ }
258
+ if (Date.now() > deadline)
259
+ throw new WorldSessionTimeout(
260
+ `Call ${callId} still ${call.state} after ${Math.round(timeoutMs / 1e3)}s \u2014 the container may have died.`
261
+ );
262
+ await sleep(CALL_POLL_MS);
263
+ }
264
+ }
265
+ /**
266
+ * Run one of the world's tools INSIDE the container. The arguments and the
267
+ * result are the world's own contract — this layer neither validates nor
268
+ * reshapes them, so a tool error reads exactly as it would in a hosted run.
269
+ */
270
+ async call(tool, args = {}, opts = {}) {
271
+ return this.exchange({ kind: "call", tool, args }, opts.timeoutMs);
272
+ }
273
+ /**
274
+ * THE WORLD'S TOOLS, READY TO HAND TO A MODEL. Schemas come from the
275
+ * world's own signatures and implementations call into this session, so a
276
+ * caller never writes — and never has to re-sync — a tool map of their own:
277
+ *
278
+ * const { schemas, impls } = await session.toolkit();
279
+ * await runMyAgent(impls, schemas, session.instruction);
280
+ *
281
+ * A tool added to the world shows up here on the next run; a tool renamed
282
+ * in the world renames here too, instead of failing at call time against a
283
+ * hand-written map that still remembers the old name.
284
+ */
285
+ async toolkit() {
286
+ let specs = this.state.tools;
287
+ if (!specs) specs = (await this.status()).tools ?? [];
288
+ const impls = {};
289
+ for (const spec of specs) {
290
+ impls[spec.name] = (args = {}) => this.call(spec.name, args);
291
+ }
292
+ return { schemas: specs.map(schemaFromSignature), impls, specs };
293
+ }
294
+ /** Run the task's grader against the container's END STATE. */
295
+ async grade(opts = {}) {
296
+ const raw = await this.exchange(
297
+ { kind: "grade" },
298
+ opts.timeoutMs
299
+ );
300
+ const record = raw && typeof raw === "object" ? raw : {};
301
+ const rewards = {};
302
+ for (const [key, value] of Object.entries(record)) {
303
+ if (key !== "reward" && typeof value === "number") rewards[key] = value;
304
+ }
305
+ return {
306
+ reward: typeof record.reward === "number" ? record.reward : null,
307
+ rewards,
308
+ raw
309
+ };
310
+ }
311
+ /**
312
+ * End the session. `keepWarm` hands the container back to the pool instead
313
+ * of tearing it down, so the next session for the same task starts warm —
314
+ * the pooled instance still obeys the fleet's idle TTL and pinning.
315
+ */
316
+ async close(opts = {}) {
317
+ return apiRequest(
318
+ this.options,
319
+ "DELETE",
320
+ `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}`,
321
+ { keepWarm: opts.keepWarm ?? false }
322
+ );
323
+ }
324
+ };
325
+ }
326
+ });
327
+
328
+ // src/worlds/index.ts
329
+ var worlds_exports = {};
330
+ __export(worlds_exports, {
331
+ WorldSession: () => WorldSession,
332
+ WorldSessionCallError: () => WorldSessionCallError,
333
+ WorldSessionTimeout: () => WorldSessionTimeout,
334
+ WorldSet: () => WorldSet,
335
+ WorldTask: () => WorldTask,
336
+ apiRequest: () => apiRequest,
337
+ attachSession: () => attachSession,
338
+ deleteEnvSecret: () => deleteEnvSecret,
339
+ detectProvenance: () => detectProvenance,
340
+ getRun: () => getRun,
341
+ listEnvSecretKeys: () => listEnvSecretKeys,
342
+ listRunConfigs: () => listRunConfigs,
343
+ openSession: () => openSession,
344
+ openWorld: () => openWorld,
345
+ runSessions: () => runSessions,
346
+ schemaFromSignature: () => schemaFromSignature,
347
+ setEnvSecret: () => setEnvSecret,
348
+ waitForRun: () => waitForRun
349
+ });
350
+ function resolveEnv(options) {
351
+ const host = options.host ?? process.env.GATEWAY_HOST ?? "https://withgateway.ai";
352
+ const publicKey = options.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;
353
+ const secretKey = options.secretKey ?? process.env.GATEWAY_SECRET_KEY;
354
+ if (!publicKey || !secretKey) {
355
+ throw new Error(
356
+ "Gateway keys missing: set GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY (or pass publicKey/secretKey)."
357
+ );
358
+ }
359
+ return { host: host.replace(/\/+$/, ""), publicKey, secretKey };
360
+ }
361
+ async function apiRequest(options, method, path2, body) {
362
+ const { host, publicKey, secretKey } = resolveEnv(options);
363
+ const res = await fetch(`${host}${path2}`, {
364
+ method,
365
+ headers: {
366
+ "content-type": "application/json",
367
+ authorization: "Basic " + Buffer.from(`${publicKey}:${secretKey}`).toString("base64")
368
+ },
369
+ ...body === void 0 ? {} : { body: JSON.stringify(body) }
370
+ });
371
+ const text = await res.text();
372
+ if (!res.ok) {
373
+ throw new Error(
374
+ `${method} ${path2} -> ${res.status}: ${text.slice(0, 400)}`
375
+ );
376
+ }
377
+ return JSON.parse(text);
378
+ }
379
+ async function setEnvSecret(slug, key, value, options = {}) {
380
+ return apiRequest(
381
+ options,
382
+ "PUT",
383
+ "/api/public/benchmark-containers/secrets",
384
+ {
385
+ slug,
386
+ key,
387
+ value
388
+ }
389
+ );
390
+ }
391
+ async function listEnvSecretKeys(slug, options = {}) {
392
+ const res = await apiRequest(
393
+ options,
394
+ "GET",
395
+ `/api/public/benchmark-containers/secrets?slug=${encodeURIComponent(slug)}`
396
+ );
397
+ return res.secrets;
398
+ }
399
+ async function deleteEnvSecret(slug, key, options = {}) {
400
+ await apiRequest(
401
+ options,
402
+ "DELETE",
403
+ "/api/public/benchmark-containers/secrets",
404
+ {
405
+ slug,
406
+ key
407
+ }
408
+ );
409
+ }
410
+ async function listRunConfigs(options = {}) {
411
+ const res = await apiRequest(
412
+ options,
413
+ "GET",
414
+ "/api/public/benchmark-containers/run-configs"
415
+ );
416
+ return res.runConfigs;
417
+ }
418
+ async function getRun(runId, options = {}) {
419
+ return apiRequest(
420
+ options,
421
+ "GET",
422
+ `/api/public/benchmark-containers/runs/${encodeURIComponent(runId)}`
423
+ );
424
+ }
425
+ async function waitForRun(runId, opts = {}) {
426
+ const deadline = Date.now() + (opts.timeoutMinutes ?? 45) * 6e4;
427
+ for (; ; ) {
428
+ const run = await getRun(runId, opts.options ?? {});
429
+ if (run.terminal) return run;
430
+ if (Date.now() > deadline)
431
+ throw new Error(
432
+ `Run ${runId} still ${run.status} after the wait timeout.`
433
+ );
434
+ opts.onTick?.(run);
435
+ await new Promise(
436
+ (resolve2) => setTimeout(resolve2, (opts.intervalSeconds ?? 20) * 1e3)
437
+ );
438
+ }
439
+ }
440
+ function detectProvenance() {
441
+ const env = globalThis.process?.env ?? {};
442
+ const out = {};
443
+ const ref = env.GITHUB_HEAD_REF || env.GITHUB_REF_NAME;
444
+ if (ref) out.branch = ref;
445
+ if (env.GITHUB_SHA) out.commit = env.GITHUB_SHA;
446
+ const server = env.GITHUB_SERVER_URL ?? "https://github.com";
447
+ if (env.GITHUB_REPOSITORY) out.repoUrl = `${server}/${env.GITHUB_REPOSITORY}`;
448
+ if (env.GITHUB_ACTOR) {
449
+ out.actor = {
450
+ kind: "ci",
451
+ id: env.GITHUB_ACTOR,
452
+ name: env.GITHUB_ACTOR,
453
+ // GitHub serves every account's avatar at /<login>.png.
454
+ imageUrl: `${server}/${env.GITHUB_ACTOR}.png`
455
+ };
456
+ }
457
+ if (!out.branch || !out.commit) {
458
+ try {
459
+ const { execFileSync } = require("child_process");
460
+ const git = (args) => execFileSync("git", args, {
461
+ encoding: "utf-8",
462
+ stdio: ["ignore", "pipe", "ignore"]
463
+ }).toString().trim();
464
+ out.branch = out.branch ?? git(["rev-parse", "--abbrev-ref", "HEAD"]);
465
+ out.commit = out.commit ?? git(["rev-parse", "HEAD"]);
466
+ if (!out.repoUrl) {
467
+ const remote = git(["config", "--get", "remote.origin.url"]);
468
+ if (remote) out.repoUrl = remote.replace(/\.git$/, "");
469
+ }
470
+ if (!out.actor) {
471
+ const name = git(["config", "--get", "user.name"]);
472
+ if (name) out.actor = { kind: "user", name };
473
+ }
474
+ } catch {
475
+ }
476
+ }
477
+ return out;
478
+ }
479
+ async function openWorld(slugRef, options = {}) {
480
+ const at = slugRef.indexOf("@");
481
+ const slug = at === -1 ? slugRef : slugRef.slice(0, at);
482
+ const ref = at === -1 ? null : slugRef.slice(at + 1);
483
+ const version = await apiRequest(options, "POST", "/api/public/benchmark-containers/resolve-version", {
484
+ slug,
485
+ ...ref ? { ref } : {}
486
+ });
487
+ const world = new WorldSet(
488
+ slugRef,
489
+ slug,
490
+ ref,
491
+ {
492
+ versionId: version.versionId,
493
+ semanticVersion: version.semanticVersion ?? null,
494
+ contentHash: version.contentHash,
495
+ state: version.state
496
+ },
497
+ [],
498
+ options
499
+ );
500
+ for (const name of version.taskNames ?? []) {
501
+ const variant = /^[a-z0-9]+-([a-z0-9]+)-/.exec(name)?.[1] ?? null;
502
+ world.tasks.push(new WorldTask(world, name, variant));
503
+ }
504
+ return world;
505
+ }
506
+ var WorldTask, WorldSet;
507
+ var init_worlds = __esm({
508
+ "src/worlds/index.ts"() {
509
+ "use strict";
510
+ init_session();
511
+ WorldTask = class {
512
+ constructor(world, name, variant) {
513
+ this.world = world;
514
+ this.name = name;
515
+ this.variant = variant;
516
+ }
517
+ };
518
+ WorldSet = class {
519
+ constructor(slugRef, slug, ref, version, tasks, options) {
520
+ this.slugRef = slugRef;
521
+ this.slug = slug;
522
+ this.ref = ref;
523
+ this.version = version;
524
+ this.tasks = tasks;
525
+ this.options = options;
526
+ }
527
+ task(variant) {
528
+ const hit = this.tasks.find(
529
+ (t) => t.variant === variant || t.name.includes(variant)
530
+ );
531
+ if (!hit) {
532
+ const known = this.tasks.map((t) => t.variant ?? t.name).join(", ");
533
+ throw new Error(`no task matches ${variant}; have: ${known}`);
534
+ }
535
+ return hit;
536
+ }
537
+ /**
538
+ * Open a LIVE session against one of this world's tasks: the platform boots
539
+ * (or reuses) a warm container, and your agent calls its tools through the
540
+ * platform. See worlds/session.ts.
541
+ */
542
+ async open(task, opts = {}) {
543
+ const { openSession: openSession2 } = await Promise.resolve().then(() => (init_session(), session_exports));
544
+ return openSession2(this.slug, task, {
545
+ versionId: this.version.versionId,
546
+ reuseWarm: opts.reuseWarm,
547
+ options: this.options
548
+ });
549
+ }
550
+ /**
551
+ * Start a HOSTED run of a run config against this world — the platform
552
+ * executes the (Python) world in parallel containers per the config's
553
+ * `parallelism` and files one graded run per model. Returns those runs.
554
+ */
555
+ async dispatch(runConfigId, opts = {}) {
556
+ const provenance = opts.provenance ?? detectProvenance();
557
+ return apiRequest(
558
+ this.options,
559
+ "POST",
560
+ "/api/public/benchmark-containers/run-configs/dispatch",
561
+ {
562
+ runConfigId,
563
+ ...opts.containerId ? { containerId: opts.containerId } : {},
564
+ versionId: opts.versionId ?? this.version.versionId,
565
+ ...provenance
566
+ }
567
+ );
568
+ }
569
+ };
570
+ }
571
+ });
572
+
573
+ // src/cli.ts
574
+ init_worlds();
575
+
576
+ // src/worlds/hub.ts
577
+ var import_node_crypto = require("crypto");
578
+ var import_node_zlib = require("zlib");
579
+ var fs = __toESM(require("fs"));
580
+ var path = __toESM(require("path"));
581
+ init_worlds();
582
+ var DEFAULT_BRANCH = "main";
583
+ var META_RELPATH = path.join(".gateway", ".env-metadata.json");
584
+ var SKIP_DIRS = /* @__PURE__ */ new Set([
585
+ ".git",
586
+ "__pycache__",
587
+ "node_modules",
588
+ ".venv",
589
+ ".mypy_cache",
590
+ "dist",
591
+ "build",
592
+ "outputs"
593
+ ]);
594
+ var ROOT_EXCLUDED_DIRS = /* @__PURE__ */ new Set(["dist", "build", "outputs", "__pycache__"]);
595
+ function isExcludedDirComponent(component) {
596
+ return component.startsWith(".") || ROOT_EXCLUDED_DIRS.has(component) || component.endsWith(".egg-info");
597
+ }
598
+ function isIncludedInContentHash(relPath, includeAllRootFiles) {
599
+ const parts = relPath.split("/");
600
+ const name = parts[parts.length - 1];
601
+ const dirParts = parts.slice(0, -1);
602
+ if (name.startsWith(".")) return false;
603
+ if (parts.includes("__pycache__")) return false;
604
+ if (dirParts.length === 0) {
605
+ return includeAllRootFiles || name === "README.md" || name === "pyproject.toml" || name === "gateway-env.toml" || name.endsWith(".py");
606
+ }
607
+ return !dirParts.some(isExcludedDirComponent);
608
+ }
609
+ function collectArchiveRelPaths(dir) {
610
+ if (fs.existsSync(path.join(dir, ".gitignore"))) {
611
+ throw new Error(
612
+ "This bundle has a root .gitignore, which the Python CLI honors via gitignore_parser. Reimplementing that imperfectly here would silently produce a different content hash, so the TS CLI refuses. Remove the .gitignore (or bake its effect into the tree) and retry."
613
+ );
614
+ }
615
+ const out = [];
616
+ const includeAllRootFiles = fs.existsSync(path.join(dir, "gateway-env.toml"));
617
+ const walk = (rel) => {
618
+ const abs = rel ? path.join(dir, rel) : dir;
619
+ for (const entry of fs.readdirSync(abs, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
620
+ const childRel = rel ? `${rel}/${entry.name}` : entry.name;
621
+ if (entry.isDirectory()) {
622
+ if (!isExcludedDirComponent(entry.name)) walk(childRel);
623
+ } else if (entry.isFile()) {
624
+ if (isIncludedInContentHash(childRel, includeAllRootFiles)) {
625
+ out.push(childRel);
626
+ }
627
+ }
628
+ }
629
+ };
630
+ walk("");
631
+ return out.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
632
+ }
633
+ function computeContentHash(dir) {
634
+ const hasher = (0, import_node_crypto.createHash)("sha256");
635
+ for (const relPath of collectArchiveRelPaths(dir)) {
636
+ hasher.update(Buffer.from(`file:${relPath}`, "utf-8"));
637
+ hasher.update(fs.readFileSync(path.join(dir, relPath)));
638
+ }
639
+ return hasher.digest("hex");
640
+ }
641
+ function octal(value, length) {
642
+ return Buffer.from(value.toString(8).padStart(length - 1, "0") + "\0", "ascii");
643
+ }
644
+ function tarHeader(name, size) {
645
+ const header = Buffer.alloc(512);
646
+ header.write(name, 0, 100, "utf-8");
647
+ octal(420, 8).copy(header, 100);
648
+ octal(0, 8).copy(header, 108);
649
+ octal(0, 8).copy(header, 116);
650
+ octal(size, 12).copy(header, 124);
651
+ octal(0, 12).copy(header, 136);
652
+ header.write(" ", 148, "ascii");
653
+ header.write("0", 156, "ascii");
654
+ header.write("ustar", 257, "ascii");
655
+ header.write("00", 263, "ascii");
656
+ let sum = 0;
657
+ for (const byte of header) sum += byte;
658
+ header.write(sum.toString(8).padStart(6, "0") + "\0 ", 148, "ascii");
659
+ return header;
660
+ }
661
+ function tarMember(name, payload) {
662
+ const parts = [];
663
+ const nameBytes = Buffer.byteLength(name, "utf-8");
664
+ if (nameBytes > 100) {
665
+ const body = Buffer.from(name + "\0", "utf-8");
666
+ const lHeader = tarHeader("././@LongLink", body.length);
667
+ lHeader.write("L", 156, "ascii");
668
+ let sum = 0;
669
+ lHeader.write(" ", 148, "ascii");
670
+ for (const byte of lHeader) sum += byte;
671
+ lHeader.write(sum.toString(8).padStart(6, "0") + "\0 ", 148, "ascii");
672
+ parts.push(lHeader, body);
673
+ const pad2 = body.length % 512 === 0 ? 0 : 512 - body.length % 512;
674
+ if (pad2) parts.push(Buffer.alloc(pad2));
675
+ parts.push(tarHeader(name.slice(0, 100), payload.length));
676
+ } else {
677
+ parts.push(tarHeader(name, payload.length));
678
+ }
679
+ parts.push(payload);
680
+ const pad = payload.length % 512 === 0 ? 0 : 512 - payload.length % 512;
681
+ if (pad) parts.push(Buffer.alloc(pad));
682
+ return parts;
683
+ }
684
+ function buildSourceTarball(dir) {
685
+ const parts = [];
686
+ for (const relPath of collectArchiveRelPaths(dir)) {
687
+ parts.push(...tarMember(relPath, fs.readFileSync(path.join(dir, relPath))));
688
+ }
689
+ parts.push(Buffer.alloc(1024));
690
+ return (0, import_node_zlib.gzipSync)(Buffer.concat(parts), { level: 9 });
691
+ }
692
+ function readLocalMeta(dir) {
693
+ try {
694
+ const raw = fs.readFileSync(path.join(dir, META_RELPATH), "utf-8");
695
+ const parsed = JSON.parse(raw);
696
+ return parsed && typeof parsed === "object" ? parsed : null;
697
+ } catch {
698
+ return null;
699
+ }
700
+ }
701
+ function writeLocalMeta(dir, meta) {
702
+ fs.mkdirSync(path.join(dir, ".gateway"), { recursive: true });
703
+ fs.writeFileSync(path.join(dir, META_RELPATH), JSON.stringify(meta, null, 2));
704
+ }
705
+ function snapshotTreeHashes(dir) {
706
+ const out = {};
707
+ for (const relPath of collectArchiveRelPaths(dir)) {
708
+ out[relPath] = (0, import_node_crypto.createHash)("sha256").update(fs.readFileSync(path.join(dir, relPath))).digest("hex");
709
+ }
710
+ return out;
711
+ }
712
+ function localTreeState(dir) {
713
+ const meta = readLocalMeta(dir);
714
+ const base = meta?.baseFiles;
715
+ if (!base || typeof base !== "object") {
716
+ return { meta, dirty: [], clean: false };
717
+ }
718
+ const now = snapshotTreeHashes(dir);
719
+ const dirty = /* @__PURE__ */ new Set();
720
+ for (const [p, h] of Object.entries(now)) if (base[p] !== h) dirty.add(p);
721
+ for (const p of Object.keys(base)) if (!(p in now)) dirty.add(p);
722
+ return { meta, dirty: [...dirty].sort(), clean: dirty.size === 0 };
723
+ }
724
+ var sha256b64 = (data) => (0, import_node_crypto.createHash)("sha256").update(data).digest("base64");
725
+ function readPyproject(dir) {
726
+ try {
727
+ const text = fs.readFileSync(path.join(dir, "pyproject.toml"), "utf-8");
728
+ const section = /\[project\]([\s\S]*?)(\n\[|$)/.exec(text)?.[1] ?? "";
729
+ const name = /\bname\s*=\s*"([^"]+)"/.exec(section)?.[1];
730
+ const version = /\bversion\s*=\s*"([^"]+)"/.exec(section)?.[1];
731
+ return { name, version };
732
+ } catch {
733
+ return {};
734
+ }
735
+ }
736
+ function buildFileManifest(dir) {
737
+ const entries = [];
738
+ const walk = (rel) => {
739
+ const abs = rel ? path.join(dir, rel) : dir;
740
+ for (const entry of fs.readdirSync(abs, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
741
+ const childRel = rel ? `${rel}/${entry.name}` : entry.name;
742
+ if (entry.isDirectory()) {
743
+ if (!SKIP_DIRS.has(entry.name) && !entry.name.endsWith(".egg-info")) {
744
+ walk(childRel);
745
+ }
746
+ } else if (entry.isFile()) {
747
+ const payload = fs.readFileSync(path.join(dir, childRel));
748
+ entries.push({
749
+ path: childRel,
750
+ isDirectory: false,
751
+ size: payload.length,
752
+ sha256: (0, import_node_crypto.createHash)("sha256").update(payload).digest("hex")
753
+ });
754
+ }
755
+ }
756
+ };
757
+ walk("");
758
+ return entries;
759
+ }
760
+ async function putObject(url, data, shaB64) {
761
+ const resp = await fetch(url, {
762
+ method: "PUT",
763
+ headers: {
764
+ "Content-Type": "application/gzip",
765
+ "x-amz-checksum-sha256": shaB64
766
+ },
767
+ body: new Uint8Array(data)
768
+ });
769
+ if (!resp.ok) {
770
+ throw new Error(`object PUT -> ${resp.status}: ${(await resp.text()).slice(0, 300)}`);
771
+ }
772
+ }
773
+ async function push(dir, opts = {}) {
774
+ const options = opts.options ?? {};
775
+ if (!fs.statSync(dir).isDirectory()) throw new Error(`Not a directory: ${dir}`);
776
+ const localMeta = readLocalMeta(dir) ?? {};
777
+ const branch = opts.branch ?? localMeta.branch ?? DEFAULT_BRANCH;
778
+ const baseVersionId = localMeta.versionId ?? null;
779
+ const contentHash = computeContentHash(dir);
780
+ const pyproject = readPyproject(dir);
781
+ const slug = opts.slug ?? pyproject.name ?? path.basename(path.resolve(dir));
782
+ const resolve2 = await apiRequest(
783
+ options,
784
+ "POST",
785
+ "/api/public/benchmark-containers/resolve",
786
+ { slug, name: pyproject.name ?? slug }
787
+ );
788
+ const tarball = buildSourceTarball(dir);
789
+ const bundleSha256 = sha256b64(tarball);
790
+ const version = await apiRequest(options, "POST", "/api/public/benchmark-containers/versions", {
791
+ containerId: resolve2.containerId,
792
+ contentHash,
793
+ bundleSha256,
794
+ bundleSizeBytes: tarball.length,
795
+ ...pyproject.version ? { semanticVersion: pyproject.version } : {},
796
+ pyprojectMeta: pyproject,
797
+ fileManifest: buildFileManifest(dir),
798
+ branch,
799
+ baseVersionId,
800
+ ...opts.force ? { force: true } : {},
801
+ ...opts.message ? { changeReason: opts.message } : {},
802
+ ...opts.author ? { author: opts.author } : {}
803
+ });
804
+ if (version.uploadUrl) await putObject(version.uploadUrl, tarball, bundleSha256);
805
+ await apiRequest(
806
+ options,
807
+ "POST",
808
+ `/api/public/benchmark-containers/versions/${version.versionId}/finalize`,
809
+ { branch, baseVersionId, ...opts.force ? { force: true } : {} }
810
+ );
811
+ writeLocalMeta(dir, {
812
+ ...localMeta,
813
+ slug,
814
+ ref: branch,
815
+ branch,
816
+ versionId: version.versionId,
817
+ contentHash,
818
+ semanticVersion: pyproject.version,
819
+ forkedFromVersionId: baseVersionId,
820
+ baseFiles: snapshotTreeHashes(dir)
821
+ });
822
+ return { slug, versionId: version.versionId, contentHash, branch };
823
+ }
824
+ function extractBundle(bundle, dir) {
825
+ const tar = (0, import_node_zlib.gunzipSync)(bundle);
826
+ let offset = 0;
827
+ let longName = null;
828
+ let written = 0;
829
+ while (offset + 512 <= tar.length) {
830
+ const header = tar.subarray(offset, offset + 512);
831
+ offset += 512;
832
+ if (header.every((b) => b === 0)) break;
833
+ const rawName = header.subarray(0, 100).toString("utf-8").replace(/\0.*$/, "");
834
+ const size = parseInt(header.subarray(124, 136).toString("ascii").replace(/\0.*$/, "").trim(), 8) || 0;
835
+ const typeflag = header.subarray(156, 157).toString("ascii");
836
+ const body = tar.subarray(offset, offset + size);
837
+ offset += size + (size % 512 === 0 ? 0 : 512 - size % 512);
838
+ if (typeflag === "L") {
839
+ longName = body.toString("utf-8").replace(/\0.*$/, "");
840
+ continue;
841
+ }
842
+ const name = (longName ?? rawName).replace(/^\.\//, "");
843
+ longName = null;
844
+ if (typeflag !== "0" && typeflag !== "") continue;
845
+ if (name.startsWith("/") || name.split("/").includes("..")) continue;
846
+ const target = path.join(dir, name);
847
+ fs.mkdirSync(path.dirname(target), { recursive: true });
848
+ fs.writeFileSync(target, body);
849
+ written++;
850
+ }
851
+ return written;
852
+ }
853
+ async function pull(slugRef, target, options = {}) {
854
+ const at = slugRef.indexOf("@");
855
+ const slug = at === -1 ? slugRef : slugRef.slice(0, at);
856
+ const ref = at === -1 ? "latest" : slugRef.slice(at + 1);
857
+ const details = await apiRequest(options, "POST", "/api/public/benchmark-containers/resolve-version", {
858
+ slug,
859
+ ref
860
+ });
861
+ if (!details.downloadUrl) {
862
+ throw new Error(`${slug}@${ref} resolved but has no uploaded bundle`);
863
+ }
864
+ let dir = target ?? path.join(process.cwd(), slug);
865
+ if (!target) {
866
+ let i = 1;
867
+ const base = dir;
868
+ while (fs.existsSync(dir)) dir = `${base}-${i++}`;
869
+ }
870
+ fs.mkdirSync(dir, { recursive: true });
871
+ const resp = await fetch(details.downloadUrl);
872
+ if (!resp.ok) throw new Error(`bundle download -> ${resp.status}`);
873
+ const bundle = Buffer.from(await resp.arrayBuffer());
874
+ if (details.bundleSha256 && sha256b64(bundle) !== details.bundleSha256) {
875
+ throw new Error(
876
+ `bundle integrity check failed for ${slug}@${ref}: downloaded sha256 != recorded bundleSha256`
877
+ );
878
+ }
879
+ const files = extractBundle(bundle, dir);
880
+ const branch = ref === "latest" || /^\d|^[0-9a-f]{8,}$/.test(ref) ? DEFAULT_BRANCH : ref;
881
+ writeLocalMeta(dir, {
882
+ slug,
883
+ ref,
884
+ branch,
885
+ versionId: details.versionId,
886
+ contentHash: details.contentHash,
887
+ semanticVersion: details.semanticVersion ?? void 0,
888
+ baseFiles: snapshotTreeHashes(dir)
889
+ });
890
+ return { slug, dir, versionId: details.versionId, files };
891
+ }
892
+ async function propose(dir, opts) {
893
+ const meta = readLocalMeta(dir);
894
+ if (!meta?.slug || !meta.baseFiles) {
895
+ throw new Error("This dir has no pull/push base \u2014 run pull first, then edit, then propose.");
896
+ }
897
+ const state = localTreeState(dir);
898
+ if (state.clean) throw new Error("Nothing to propose \u2014 the tree matches its base.");
899
+ const changes = state.dirty.map((relPath) => {
900
+ const abs = path.join(dir, relPath);
901
+ if (!fs.existsSync(abs)) return { path: relPath, action: "delete" };
902
+ return {
903
+ path: relPath,
904
+ action: "write",
905
+ newContent: fs.readFileSync(abs, "utf-8")
906
+ };
907
+ });
908
+ const res = await apiRequest(
909
+ opts.options ?? {},
910
+ "POST",
911
+ "/api/public/benchmark-containers/proposals",
912
+ {
913
+ slug: meta.slug,
914
+ title: opts.title,
915
+ changeReason: opts.reason,
916
+ baseVersionId: meta.versionId,
917
+ ...opts.targetBranch ? { targetBranch: opts.targetBranch } : {},
918
+ changes
919
+ }
920
+ );
921
+ return res;
922
+ }
923
+ async function createRef(slug, name, kind, versionId, options = {}) {
924
+ return apiRequest(options, "POST", "/api/public/benchmark-containers/refs", {
925
+ slug,
926
+ name,
927
+ kind,
928
+ ...versionId ? { versionId } : {}
929
+ });
930
+ }
931
+
932
+ // src/cli.ts
933
+ function parseArgv(argv) {
934
+ const positional = [];
935
+ const flags = {};
936
+ for (let i = 0; i < argv.length; i++) {
937
+ const arg = argv[i];
938
+ if (arg.startsWith("--")) {
939
+ const key = arg.slice(2);
940
+ const next = argv[i + 1];
941
+ if (next !== void 0 && !next.startsWith("--")) {
942
+ flags[key] = next;
943
+ i++;
944
+ } else {
945
+ flags[key] = true;
946
+ }
947
+ } else {
948
+ positional.push(arg);
949
+ }
950
+ }
951
+ return { positional, flags };
952
+ }
953
+ function str(flags, key) {
954
+ const value = flags[key];
955
+ return typeof value === "string" ? value : void 0;
956
+ }
957
+ function fail(message) {
958
+ console.error(message);
959
+ process.exit(2);
960
+ }
961
+ var PYTHON_ONLY = /* @__PURE__ */ new Set(["eval"]);
962
+ var HELP = `gateway bench <command> \u2014 worlds from TypeScript
963
+
964
+ resolve <slug[@ref]> pinned version + task count
965
+ tasks <slug[@ref]> the task list
966
+ dispatch <runConfigId> [--container-id X] [--version-id Y]
967
+ run <runId> [--wait] [--timeout-min N] status, score, per-task rewards
968
+ run-configs list
969
+ run-configs create --name N --models a,b [--parallelism K] [--tasks t1,t2] [--agent A] [--auto-run-on-push] [--id existing]
970
+ run-configs delete --id X
971
+ secrets set --env <slug> --key K [--value V] (omit --value to read stdin)
972
+ secrets list --env <slug>
973
+ secrets unset --env <slug> --key K
974
+ refs <slug> branches and tags
975
+ log <slug> [--branch B] [--limit N] version history
976
+ proposals <slug> [--status open|applied|dismissed]
977
+
978
+ pull <slug[@ref]> [--dir D] materialize a working dir
979
+ push [dir] [--slug S] [--branch B] [--force] [--message M]
980
+ checkout <slug@ref> --dir D re-aim an existing working dir
981
+ status [dir] clean/dirty vs base + hash check
982
+ branch <slug> <name> [--version-id V] create a branch
983
+ tag <slug> <name> [--version-id V] create a tag
984
+ propose [dir] --title T --reason R [--target-branch B]
985
+
986
+ eval (local engine runs) is Python-only \u2014 run hosted via 'dispatch'.
987
+
988
+ Auth: GATEWAY_HOST, GATEWAY_PUBLIC_KEY, GATEWAY_SECRET_KEY.`;
989
+ async function readStdin() {
990
+ const chunks = [];
991
+ for await (const chunk of process.stdin) chunks.push(chunk);
992
+ return Buffer.concat(chunks).toString("utf-8").trim();
993
+ }
994
+ async function main() {
995
+ const [group, command, ...rest] = process.argv.slice(2);
996
+ if (!group || group === "help" || group === "--help") {
997
+ console.log(HELP);
998
+ return 0;
999
+ }
1000
+ if (group !== "bench") {
1001
+ fail(
1002
+ `Unknown command group '${group}' \u2014 this CLI covers 'gateway bench'. Run 'gateway help'.`
1003
+ );
1004
+ }
1005
+ if (!command) fail(HELP);
1006
+ if (PYTHON_ONLY.has(command)) {
1007
+ fail(
1008
+ `'gateway bench eval' runs the world locally on the PYTHON engines (verifiers/harbor) \u2014 it cannot exist in a JS process.
1009
+ Run hosted instead: gateway bench dispatch <runConfigId> \u2014 same worlds, graded on the platform.`
1010
+ );
1011
+ }
1012
+ const { positional, flags } = parseArgv(rest);
1013
+ switch (command) {
1014
+ case "resolve": {
1015
+ const slugRef = positional[0] ?? fail("usage: gateway bench resolve <slug[@ref]>");
1016
+ const world = await openWorld(slugRef);
1017
+ console.log(
1018
+ `${world.slug}@${world.ref ?? "latest"}: ${world.version.semanticVersion ?? "-"} (${world.version.contentHash.slice(0, 12)}) \xB7 ${world.version.state ?? "?"} \xB7 ${world.tasks.length} tasks`
1019
+ );
1020
+ console.log(`versionId: ${world.version.versionId}`);
1021
+ return 0;
1022
+ }
1023
+ case "tasks": {
1024
+ const slugRef = positional[0] ?? fail("usage: gateway bench tasks <slug[@ref]>");
1025
+ const world = await openWorld(slugRef);
1026
+ if (world.tasks.length === 0) {
1027
+ console.log("No task manifest served for this version.");
1028
+ return 0;
1029
+ }
1030
+ for (const task of world.tasks) {
1031
+ console.log(`${task.name}${task.variant ? ` (${task.variant})` : ""}`);
1032
+ }
1033
+ return 0;
1034
+ }
1035
+ case "dispatch": {
1036
+ const runConfigId = positional[0] ?? fail("usage: gateway bench dispatch <runConfigId>");
1037
+ const body = { runConfigId };
1038
+ const containerId = str(flags, "container-id");
1039
+ const versionId = str(flags, "version-id");
1040
+ if (containerId) body.containerId = containerId;
1041
+ if (versionId) body.versionId = versionId;
1042
+ const result = await apiRequest(
1043
+ {},
1044
+ "POST",
1045
+ "/api/public/benchmark-containers/run-configs/dispatch",
1046
+ body
1047
+ );
1048
+ for (const run of result.runs) {
1049
+ console.log(
1050
+ `${run.model}: ${run.ok ? "dispatched" : `FAILED: ${run.error}`} run=${run.runId}`
1051
+ );
1052
+ }
1053
+ console.log(`-> ${result.versionLabel}`);
1054
+ return result.runs.every((r) => r.ok) ? 0 : 1;
1055
+ }
1056
+ case "run": {
1057
+ const runId = positional[0] ?? fail("usage: gateway bench run <runId> [--wait]");
1058
+ const report = flags.wait ? await waitForRun(runId, {
1059
+ timeoutMinutes: Number(str(flags, "timeout-min") ?? 45),
1060
+ onTick: (r) => console.error(
1061
+ `\u2026${r.status.toLowerCase()} (${r.shardsCompleted ?? 0}/${r.parallelism} shards)`
1062
+ )
1063
+ }) : await getRun(runId);
1064
+ console.log(
1065
+ `${report.id} ${report.status}${report.score !== null ? ` score=${report.score.toFixed(3)}` : ""} (${report.model ?? "?"} \xB7 ${report.versionLabel ?? "?"} \xB7 x${report.parallelism})`
1066
+ );
1067
+ for (const sample of report.samples) {
1068
+ const subs = Object.entries(sample.rewards).filter(([, v]) => typeof v === "number").map(([k, v]) => `${k}=${v.toFixed(2)}`).join(" ");
1069
+ console.log(
1070
+ ` ${(sample.reward ?? 0).toFixed(2)} ${sample.task ?? "?"}${subs ? ` [${subs}]` : ""}`
1071
+ );
1072
+ }
1073
+ if (report.summary) console.log(` ${report.summary}`);
1074
+ return report.terminal && report.status.toUpperCase() === "COMPLETED" ? 0 : 1;
1075
+ }
1076
+ case "run-configs": {
1077
+ const action = positional[0] ?? "list";
1078
+ if (action === "list") {
1079
+ const rows = await listRunConfigs();
1080
+ if (rows.length === 0) {
1081
+ console.log("No run configs in this project.");
1082
+ return 0;
1083
+ }
1084
+ for (const row2 of rows) {
1085
+ const extras = [
1086
+ row2.parallelism > 1 ? `x${row2.parallelism} containers` : null,
1087
+ row2.autoRunOnPush ? "auto-on-push" : null
1088
+ ].filter(Boolean);
1089
+ console.log(
1090
+ `${row2.id} ${row2.name} (${row2.models.join(", ") || "no models"})${extras.length ? ` [${extras.join(", ")}]` : ""}`
1091
+ );
1092
+ }
1093
+ return 0;
1094
+ }
1095
+ if (action === "delete") {
1096
+ const id2 = str(flags, "id") ?? fail("--id is required for delete");
1097
+ await apiRequest(
1098
+ {},
1099
+ "DELETE",
1100
+ "/api/public/benchmark-containers/run-configs",
1101
+ { id: id2 }
1102
+ );
1103
+ console.log(`Deleted ${id2}.`);
1104
+ return 0;
1105
+ }
1106
+ if (action !== "create")
1107
+ fail("run-configs actions: list | create | delete");
1108
+ const name = str(flags, "name") ?? fail("--name is required for create");
1109
+ const models = (str(flags, "models") ?? fail("--models is required for create")).split(",").map((m) => m.trim()).filter(Boolean);
1110
+ const body = { name, models };
1111
+ const parallelism = str(flags, "parallelism");
1112
+ if (parallelism) body.parallelism = Number(parallelism);
1113
+ const agent = str(flags, "agent");
1114
+ if (agent) body.agent = agent;
1115
+ const tasks = str(flags, "tasks");
1116
+ if (tasks)
1117
+ body.taskNames = tasks.split(",").map((t) => t.trim()).filter(Boolean);
1118
+ if (flags["auto-run-on-push"]) body.autoRunOnPush = true;
1119
+ const id = str(flags, "id");
1120
+ if (id) body.id = id;
1121
+ const row = await apiRequest({}, "POST", "/api/public/benchmark-containers/run-configs", body);
1122
+ console.log(`${row.id} ${row.name} (${row.models.join(", ")})`);
1123
+ return 0;
1124
+ }
1125
+ case "secrets": {
1126
+ const action = positional[0] ?? fail("secrets actions: set | list | unset");
1127
+ const env = str(flags, "env") ?? fail("--env <world slug> is required");
1128
+ if (action === "list") {
1129
+ const rows = await listEnvSecretKeys(env);
1130
+ if (rows.length === 0) {
1131
+ console.log(`No secrets on ${env}.`);
1132
+ return 0;
1133
+ }
1134
+ for (const row of rows)
1135
+ console.log(`${row.key} (rotated ${row.updatedAt})`);
1136
+ return 0;
1137
+ }
1138
+ const key = str(flags, "key") ?? fail(`--key is required for ${action}`);
1139
+ if (action === "unset") {
1140
+ await deleteEnvSecret(env, key);
1141
+ console.log(`Deleted ${key} from ${env}.`);
1142
+ return 0;
1143
+ }
1144
+ if (action !== "set") fail("secrets actions: set | list | unset");
1145
+ const value = str(flags, "value") ?? await readStdin();
1146
+ if (!value)
1147
+ fail("empty value \u2014 nothing stored (pass --value or pipe stdin)");
1148
+ const res = await setEnvSecret(env, key, value);
1149
+ console.log(
1150
+ `${res.created ? "Added" : "Rotated"} ${key} on ${env} \u2014 next hosted run receives it.`
1151
+ );
1152
+ return 0;
1153
+ }
1154
+ case "refs": {
1155
+ const slug = positional[0] ?? fail("usage: gateway bench refs <slug>");
1156
+ const res = await apiRequest(
1157
+ {},
1158
+ "GET",
1159
+ `/api/public/benchmark-containers/refs?slug=${encodeURIComponent(slug)}`
1160
+ );
1161
+ for (const ref of res.refs) {
1162
+ console.log(
1163
+ `${ref.kind === "tag" ? "tag " : "branch"} ${ref.name} ${ref.semanticVersion ?? "-"} (${ref.contentHash?.slice(0, 12) ?? "?"}) ${ref.state ?? ""}`
1164
+ );
1165
+ }
1166
+ return 0;
1167
+ }
1168
+ case "log": {
1169
+ const slug = positional[0] ?? fail("usage: gateway bench log <slug>");
1170
+ const params = new URLSearchParams({ slug });
1171
+ const branch = str(flags, "branch");
1172
+ if (branch) params.set("branch", branch);
1173
+ const limit = str(flags, "limit");
1174
+ if (limit) params.set("limit", limit);
1175
+ const res = await apiRequest(
1176
+ {},
1177
+ "GET",
1178
+ `/api/public/benchmark-containers/log?${params.toString()}`
1179
+ );
1180
+ console.log(`branch: ${res.branch}`);
1181
+ for (const entry of res.entries) {
1182
+ console.log(
1183
+ `${entry.contentHash.slice(0, 12)} ${entry.semanticVersion ?? "-"} ${entry.state}${entry.author ? ` by ${entry.author}` : ""}${entry.changeReason ? ` \u2014 ${entry.changeReason}` : ""}`
1184
+ );
1185
+ }
1186
+ return 0;
1187
+ }
1188
+ case "proposals": {
1189
+ const slug = positional[0] ?? fail("usage: gateway bench proposals <slug>");
1190
+ const params = new URLSearchParams({ slug });
1191
+ const status = str(flags, "status");
1192
+ if (status) params.set("status", status);
1193
+ const res = await apiRequest(
1194
+ {},
1195
+ "GET",
1196
+ `/api/public/benchmark-containers/proposals?${params.toString()}`
1197
+ );
1198
+ if (res.proposals.length === 0) {
1199
+ console.log("No proposals.");
1200
+ return 0;
1201
+ }
1202
+ for (const proposal of res.proposals) {
1203
+ console.log(
1204
+ `${proposal.id} [${proposal.status}] ${proposal.title ?? ""}`
1205
+ );
1206
+ }
1207
+ return 0;
1208
+ }
1209
+ case "pull": {
1210
+ const slugRef = positional[0] ?? fail("usage: gateway bench pull <slug[@ref]> [--dir D]");
1211
+ const res = await pull(slugRef, str(flags, "dir"));
1212
+ console.log(
1213
+ `Pulled ${res.slug} -> ${res.dir} (${res.files} files, version ${res.versionId})`
1214
+ );
1215
+ return 0;
1216
+ }
1217
+ case "checkout": {
1218
+ const slugRef = positional[0] ?? fail("usage: gateway bench checkout <slug@ref> --dir D");
1219
+ const dir = str(flags, "dir") ?? fail("--dir is required for checkout (the working dir to re-aim)");
1220
+ const res = await pull(slugRef, dir);
1221
+ console.log(
1222
+ `Checked out ${slugRef} into ${res.dir} (${res.files} files)`
1223
+ );
1224
+ return 0;
1225
+ }
1226
+ case "push": {
1227
+ const dir = positional[0] ?? ".";
1228
+ const res = await push(dir, {
1229
+ slug: str(flags, "slug"),
1230
+ branch: str(flags, "branch"),
1231
+ force: Boolean(flags.force),
1232
+ message: str(flags, "message"),
1233
+ author: str(flags, "author")
1234
+ });
1235
+ console.log(
1236
+ `Pushed ${res.slug}@${res.branch}: version ${res.versionId} (${res.contentHash.slice(0, 12)})`
1237
+ );
1238
+ return 0;
1239
+ }
1240
+ case "status": {
1241
+ const dir = positional[0] ?? ".";
1242
+ const state = localTreeState(dir);
1243
+ if (!state.meta) {
1244
+ console.log(
1245
+ "Ad-hoc dir: no pull/push base recorded (.gateway missing)."
1246
+ );
1247
+ return 0;
1248
+ }
1249
+ console.log(
1250
+ `base: ${state.meta.slug}@${state.meta.branch ?? "?"} version ${state.meta.versionId ?? "?"}`
1251
+ );
1252
+ const localHash = computeContentHash(dir);
1253
+ const baseHash = state.meta.contentHash;
1254
+ console.log(
1255
+ `content hash: ${localHash.slice(0, 12)} ${localHash === baseHash ? "== base (hash-verified)" : `!= base ${String(baseHash).slice(0, 12)}`}`
1256
+ );
1257
+ if (state.clean) {
1258
+ console.log("clean \u2014 tree matches its base.");
1259
+ return 0;
1260
+ }
1261
+ console.log(`dirty (${state.dirty.length}):`);
1262
+ for (const p of state.dirty.slice(0, 40)) console.log(` ${p}`);
1263
+ return 0;
1264
+ }
1265
+ case "branch":
1266
+ case "tag": {
1267
+ const slug = positional[0] ?? fail(`usage: gateway bench ${command} <slug> <name>`);
1268
+ const name = positional[1] ?? fail(`usage: gateway bench ${command} <slug> <name>`);
1269
+ const ref = await createRef(
1270
+ slug,
1271
+ name,
1272
+ command,
1273
+ str(flags, "version-id")
1274
+ );
1275
+ console.log(`${ref.kind} ${ref.name} -> ${ref.versionId}`);
1276
+ return 0;
1277
+ }
1278
+ case "propose": {
1279
+ const dir = positional[0] ?? ".";
1280
+ const title = str(flags, "title") ?? fail("--title is required");
1281
+ const reason = str(flags, "reason") ?? fail("--reason is required");
1282
+ const res = await propose(dir, {
1283
+ title,
1284
+ reason,
1285
+ targetBranch: str(flags, "target-branch")
1286
+ });
1287
+ console.log(`Proposal ${res.proposalId} opened.`);
1288
+ return 0;
1289
+ }
1290
+ default:
1291
+ fail(`Unknown command 'bench ${command}'.
1292
+
1293
+ ${HELP}`);
1294
+ }
1295
+ }
1296
+ main().then(
1297
+ (code) => process.exit(code),
1298
+ (error) => {
1299
+ console.error(error instanceof Error ? error.message : String(error));
1300
+ process.exit(1);
1301
+ }
1302
+ );
1303
+ //# sourceMappingURL=cli.js.map