@withgateway/sdk 0.1.13 → 0.1.16

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.
@@ -0,0 +1,1120 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __esm = (fn, res) => function __init() {
9
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
+ };
11
+ var __export = (target, all) => {
12
+ for (var name in all)
13
+ __defProp(target, name, { get: all[name], enumerable: true });
14
+ };
15
+ var __copyProps = (to, from, except, desc) => {
16
+ if (from && typeof from === "object" || typeof from === "function") {
17
+ for (let key of __getOwnPropNames(from))
18
+ if (!__hasOwnProp.call(to, key) && key !== except)
19
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
+ }
21
+ return to;
22
+ };
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
+ // If the importer is in node compatibility mode or this is not an ESM
25
+ // file that has been converted to a CommonJS file using a Babel-
26
+ // compatible transform (i.e. "__esModule" has not been set), then set
27
+ // "default" to the CommonJS "module.exports" for node compatibility.
28
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
+ mod
30
+ ));
31
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
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/hub.ts
329
+ function isExcludedDirComponent(component) {
330
+ return component.startsWith(".") || ROOT_EXCLUDED_DIRS.has(component) || component.endsWith(".egg-info");
331
+ }
332
+ function isIncludedInContentHash(relPath, includeAllRootFiles) {
333
+ const parts = relPath.split("/");
334
+ const name = parts[parts.length - 1];
335
+ const dirParts = parts.slice(0, -1);
336
+ if (name.startsWith(".")) return false;
337
+ if (parts.includes("__pycache__")) return false;
338
+ if (dirParts.length === 0) {
339
+ return includeAllRootFiles || name === "README.md" || name === "pyproject.toml" || name === "gateway-env.toml" || name.endsWith(".py");
340
+ }
341
+ return !dirParts.some(isExcludedDirComponent);
342
+ }
343
+ function collectArchiveRelPaths(dir) {
344
+ if (fs.existsSync(path.join(dir, ".gitignore"))) {
345
+ throw new Error(
346
+ "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."
347
+ );
348
+ }
349
+ const out = [];
350
+ const includeAllRootFiles = fs.existsSync(path.join(dir, "gateway-env.toml"));
351
+ const walk = (rel) => {
352
+ const abs = rel ? path.join(dir, rel) : dir;
353
+ for (const entry of fs.readdirSync(abs, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
354
+ const childRel = rel ? `${rel}/${entry.name}` : entry.name;
355
+ if (entry.isDirectory()) {
356
+ if (!isExcludedDirComponent(entry.name)) walk(childRel);
357
+ } else if (entry.isFile()) {
358
+ if (isIncludedInContentHash(childRel, includeAllRootFiles)) {
359
+ out.push(childRel);
360
+ }
361
+ }
362
+ }
363
+ };
364
+ walk("");
365
+ return out.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
366
+ }
367
+ function computeContentHash(dir) {
368
+ const hasher = (0, import_node_crypto.createHash)("sha256");
369
+ for (const relPath of collectArchiveRelPaths(dir)) {
370
+ hasher.update(Buffer.from(`file:${relPath}`, "utf-8"));
371
+ hasher.update(fs.readFileSync(path.join(dir, relPath)));
372
+ }
373
+ return hasher.digest("hex");
374
+ }
375
+ function octal(value, length) {
376
+ return Buffer.from(value.toString(8).padStart(length - 1, "0") + "\0", "ascii");
377
+ }
378
+ function tarHeader(name, size) {
379
+ const header = Buffer.alloc(512);
380
+ header.write(name, 0, 100, "utf-8");
381
+ octal(420, 8).copy(header, 100);
382
+ octal(0, 8).copy(header, 108);
383
+ octal(0, 8).copy(header, 116);
384
+ octal(size, 12).copy(header, 124);
385
+ octal(0, 12).copy(header, 136);
386
+ header.write(" ", 148, "ascii");
387
+ header.write("0", 156, "ascii");
388
+ header.write("ustar", 257, "ascii");
389
+ header.write("00", 263, "ascii");
390
+ let sum = 0;
391
+ for (const byte of header) sum += byte;
392
+ header.write(sum.toString(8).padStart(6, "0") + "\0 ", 148, "ascii");
393
+ return header;
394
+ }
395
+ function tarMember(name, payload) {
396
+ const parts = [];
397
+ const nameBytes = Buffer.byteLength(name, "utf-8");
398
+ if (nameBytes > 100) {
399
+ const body = Buffer.from(name + "\0", "utf-8");
400
+ const lHeader = tarHeader("././@LongLink", body.length);
401
+ lHeader.write("L", 156, "ascii");
402
+ let sum = 0;
403
+ lHeader.write(" ", 148, "ascii");
404
+ for (const byte of lHeader) sum += byte;
405
+ lHeader.write(sum.toString(8).padStart(6, "0") + "\0 ", 148, "ascii");
406
+ parts.push(lHeader, body);
407
+ const pad2 = body.length % 512 === 0 ? 0 : 512 - body.length % 512;
408
+ if (pad2) parts.push(Buffer.alloc(pad2));
409
+ parts.push(tarHeader(name.slice(0, 100), payload.length));
410
+ } else {
411
+ parts.push(tarHeader(name, payload.length));
412
+ }
413
+ parts.push(payload);
414
+ const pad = payload.length % 512 === 0 ? 0 : 512 - payload.length % 512;
415
+ if (pad) parts.push(Buffer.alloc(pad));
416
+ return parts;
417
+ }
418
+ function buildSourceTarball(dir) {
419
+ const parts = [];
420
+ for (const relPath of collectArchiveRelPaths(dir)) {
421
+ parts.push(...tarMember(relPath, fs.readFileSync(path.join(dir, relPath))));
422
+ }
423
+ parts.push(Buffer.alloc(1024));
424
+ return (0, import_node_zlib.gzipSync)(Buffer.concat(parts), { level: 9 });
425
+ }
426
+ function readLocalMeta(dir) {
427
+ try {
428
+ const raw = fs.readFileSync(path.join(dir, META_RELPATH), "utf-8");
429
+ const parsed = JSON.parse(raw);
430
+ return parsed && typeof parsed === "object" ? parsed : null;
431
+ } catch {
432
+ return null;
433
+ }
434
+ }
435
+ function writeLocalMeta(dir, meta) {
436
+ fs.mkdirSync(path.join(dir, ".gateway"), { recursive: true });
437
+ fs.writeFileSync(path.join(dir, META_RELPATH), JSON.stringify(meta, null, 2));
438
+ }
439
+ function snapshotTreeHashes(dir) {
440
+ const out = {};
441
+ for (const relPath of collectArchiveRelPaths(dir)) {
442
+ out[relPath] = (0, import_node_crypto.createHash)("sha256").update(fs.readFileSync(path.join(dir, relPath))).digest("hex");
443
+ }
444
+ return out;
445
+ }
446
+ function localTreeState(dir) {
447
+ const meta = readLocalMeta(dir);
448
+ const base = meta?.baseFiles;
449
+ if (!base || typeof base !== "object") {
450
+ return { meta, dirty: [], clean: false };
451
+ }
452
+ const now = snapshotTreeHashes(dir);
453
+ const dirty = /* @__PURE__ */ new Set();
454
+ for (const [p, h] of Object.entries(now)) if (base[p] !== h) dirty.add(p);
455
+ for (const p of Object.keys(base)) if (!(p in now)) dirty.add(p);
456
+ return { meta, dirty: [...dirty].sort(), clean: dirty.size === 0 };
457
+ }
458
+ function readPyproject(dir) {
459
+ try {
460
+ const text = fs.readFileSync(path.join(dir, "pyproject.toml"), "utf-8");
461
+ const section = /\[project\]([\s\S]*?)(\n\[|$)/.exec(text)?.[1] ?? "";
462
+ const name = /\bname\s*=\s*"([^"]+)"/.exec(section)?.[1];
463
+ const version = /\bversion\s*=\s*"([^"]+)"/.exec(section)?.[1];
464
+ return { name, version };
465
+ } catch {
466
+ return {};
467
+ }
468
+ }
469
+ function buildFileManifest(dir) {
470
+ const entries = [];
471
+ const walk = (rel) => {
472
+ const abs = rel ? path.join(dir, rel) : dir;
473
+ for (const entry of fs.readdirSync(abs, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
474
+ const childRel = rel ? `${rel}/${entry.name}` : entry.name;
475
+ if (entry.isDirectory()) {
476
+ if (!SKIP_DIRS.has(entry.name) && !entry.name.endsWith(".egg-info")) {
477
+ walk(childRel);
478
+ }
479
+ } else if (entry.isFile()) {
480
+ const payload = fs.readFileSync(path.join(dir, childRel));
481
+ entries.push({
482
+ path: childRel,
483
+ isDirectory: false,
484
+ size: payload.length,
485
+ sha256: (0, import_node_crypto.createHash)("sha256").update(payload).digest("hex")
486
+ });
487
+ }
488
+ }
489
+ };
490
+ walk("");
491
+ return entries;
492
+ }
493
+ async function putObject(url, data, shaB64) {
494
+ const resp = await fetch(url, {
495
+ method: "PUT",
496
+ headers: {
497
+ "Content-Type": "application/gzip",
498
+ "x-amz-checksum-sha256": shaB64
499
+ },
500
+ body: new Uint8Array(data)
501
+ });
502
+ if (!resp.ok) {
503
+ throw new Error(`object PUT -> ${resp.status}: ${(await resp.text()).slice(0, 300)}`);
504
+ }
505
+ }
506
+ async function push(dir, opts = {}) {
507
+ const options = opts.options ?? {};
508
+ if (!fs.statSync(dir).isDirectory()) throw new Error(`Not a directory: ${dir}`);
509
+ const localMeta = readLocalMeta(dir) ?? {};
510
+ const branch = opts.branch ?? localMeta.branch ?? DEFAULT_BRANCH;
511
+ const baseVersionId = localMeta.versionId ?? null;
512
+ const contentHash = computeContentHash(dir);
513
+ const pyproject = readPyproject(dir);
514
+ const slug = opts.slug ?? pyproject.name ?? path.basename(path.resolve(dir));
515
+ const resolve2 = await apiRequest(
516
+ options,
517
+ "POST",
518
+ "/api/public/benchmark-containers/resolve",
519
+ { slug, name: pyproject.name ?? slug }
520
+ );
521
+ const tarball = buildSourceTarball(dir);
522
+ const bundleSha256 = sha256b64(tarball);
523
+ const version = await apiRequest(options, "POST", "/api/public/benchmark-containers/versions", {
524
+ containerId: resolve2.containerId,
525
+ contentHash,
526
+ bundleSha256,
527
+ bundleSizeBytes: tarball.length,
528
+ ...pyproject.version ? { semanticVersion: pyproject.version } : {},
529
+ pyprojectMeta: pyproject,
530
+ fileManifest: buildFileManifest(dir),
531
+ branch,
532
+ baseVersionId,
533
+ ...opts.force ? { force: true } : {},
534
+ ...opts.message ? { changeReason: opts.message } : {},
535
+ ...opts.author ? { author: opts.author } : {}
536
+ });
537
+ if (version.uploadUrl) await putObject(version.uploadUrl, tarball, bundleSha256);
538
+ await apiRequest(
539
+ options,
540
+ "POST",
541
+ `/api/public/benchmark-containers/versions/${version.versionId}/finalize`,
542
+ { branch, baseVersionId, ...opts.force ? { force: true } : {} }
543
+ );
544
+ writeLocalMeta(dir, {
545
+ ...localMeta,
546
+ slug,
547
+ ref: branch,
548
+ branch,
549
+ versionId: version.versionId,
550
+ contentHash,
551
+ semanticVersion: pyproject.version,
552
+ forkedFromVersionId: baseVersionId,
553
+ baseFiles: snapshotTreeHashes(dir)
554
+ });
555
+ return { slug, versionId: version.versionId, contentHash, branch };
556
+ }
557
+ function extractBundle(bundle, dir) {
558
+ const tar = (0, import_node_zlib.gunzipSync)(bundle);
559
+ let offset = 0;
560
+ let longName = null;
561
+ let written = 0;
562
+ while (offset + 512 <= tar.length) {
563
+ const header = tar.subarray(offset, offset + 512);
564
+ offset += 512;
565
+ if (header.every((b) => b === 0)) break;
566
+ const rawName = header.subarray(0, 100).toString("utf-8").replace(/\0.*$/, "");
567
+ const size = parseInt(header.subarray(124, 136).toString("ascii").replace(/\0.*$/, "").trim(), 8) || 0;
568
+ const typeflag = header.subarray(156, 157).toString("ascii");
569
+ const body = tar.subarray(offset, offset + size);
570
+ offset += size + (size % 512 === 0 ? 0 : 512 - size % 512);
571
+ if (typeflag === "L") {
572
+ longName = body.toString("utf-8").replace(/\0.*$/, "");
573
+ continue;
574
+ }
575
+ const name = (longName ?? rawName).replace(/^\.\//, "");
576
+ longName = null;
577
+ if (typeflag !== "0" && typeflag !== "") continue;
578
+ if (name.startsWith("/") || name.split("/").includes("..")) continue;
579
+ const target = path.join(dir, name);
580
+ fs.mkdirSync(path.dirname(target), { recursive: true });
581
+ fs.writeFileSync(target, body);
582
+ written++;
583
+ }
584
+ return written;
585
+ }
586
+ async function pull(slugRef, target, options = {}) {
587
+ const at = slugRef.indexOf("@");
588
+ const slug = at === -1 ? slugRef : slugRef.slice(0, at);
589
+ const ref = at === -1 ? "latest" : slugRef.slice(at + 1);
590
+ const details = await apiRequest(options, "POST", "/api/public/benchmark-containers/resolve-version", {
591
+ slug,
592
+ ref
593
+ });
594
+ if (!details.downloadUrl) {
595
+ throw new Error(`${slug}@${ref} resolved but has no uploaded bundle`);
596
+ }
597
+ let dir = target ?? path.join(process.cwd(), slug);
598
+ if (!target) {
599
+ let i = 1;
600
+ const base = dir;
601
+ while (fs.existsSync(dir)) dir = `${base}-${i++}`;
602
+ }
603
+ fs.mkdirSync(dir, { recursive: true });
604
+ const resp = await fetch(details.downloadUrl);
605
+ if (!resp.ok) throw new Error(`bundle download -> ${resp.status}`);
606
+ const bundle = Buffer.from(await resp.arrayBuffer());
607
+ if (details.bundleSha256 && sha256b64(bundle) !== details.bundleSha256) {
608
+ throw new Error(
609
+ `bundle integrity check failed for ${slug}@${ref}: downloaded sha256 != recorded bundleSha256`
610
+ );
611
+ }
612
+ const files = extractBundle(bundle, dir);
613
+ const branch = ref === "latest" || /^\d|^[0-9a-f]{8,}$/.test(ref) ? DEFAULT_BRANCH : ref;
614
+ writeLocalMeta(dir, {
615
+ slug,
616
+ ref,
617
+ branch,
618
+ versionId: details.versionId,
619
+ contentHash: details.contentHash,
620
+ semanticVersion: details.semanticVersion ?? void 0,
621
+ baseFiles: snapshotTreeHashes(dir)
622
+ });
623
+ return { slug, dir, versionId: details.versionId, files };
624
+ }
625
+ async function propose(dir, opts) {
626
+ const meta = readLocalMeta(dir);
627
+ if (!meta?.slug || !meta.baseFiles) {
628
+ throw new Error("This dir has no pull/push base \u2014 run pull first, then edit, then propose.");
629
+ }
630
+ const state = localTreeState(dir);
631
+ if (state.clean) throw new Error("Nothing to propose \u2014 the tree matches its base.");
632
+ const changes = state.dirty.map((relPath) => {
633
+ const abs = path.join(dir, relPath);
634
+ if (!fs.existsSync(abs)) return { path: relPath, action: "delete" };
635
+ return {
636
+ path: relPath,
637
+ action: "write",
638
+ newContent: fs.readFileSync(abs, "utf-8")
639
+ };
640
+ });
641
+ const res = await apiRequest(
642
+ opts.options ?? {},
643
+ "POST",
644
+ "/api/public/benchmark-containers/proposals",
645
+ {
646
+ slug: meta.slug,
647
+ title: opts.title,
648
+ changeReason: opts.reason,
649
+ baseVersionId: meta.versionId,
650
+ ...opts.targetBranch ? { targetBranch: opts.targetBranch } : {},
651
+ changes
652
+ }
653
+ );
654
+ return res;
655
+ }
656
+ async function createRef(slug, name, kind, versionId, options = {}) {
657
+ return apiRequest(options, "POST", "/api/public/benchmark-containers/refs", {
658
+ slug,
659
+ name,
660
+ kind,
661
+ ...versionId ? { versionId } : {}
662
+ });
663
+ }
664
+ var import_node_crypto, import_node_zlib, fs, path, DEFAULT_BRANCH, META_RELPATH, SKIP_DIRS, ROOT_EXCLUDED_DIRS, sha256b64;
665
+ var init_hub = __esm({
666
+ "src/worlds/hub.ts"() {
667
+ "use strict";
668
+ import_node_crypto = require("crypto");
669
+ import_node_zlib = require("zlib");
670
+ fs = __toESM(require("fs"));
671
+ path = __toESM(require("path"));
672
+ init_worlds();
673
+ DEFAULT_BRANCH = "main";
674
+ META_RELPATH = path.join(".gateway", ".env-metadata.json");
675
+ SKIP_DIRS = /* @__PURE__ */ new Set([
676
+ ".git",
677
+ "__pycache__",
678
+ "node_modules",
679
+ ".venv",
680
+ ".mypy_cache",
681
+ "dist",
682
+ "build",
683
+ "outputs"
684
+ ]);
685
+ ROOT_EXCLUDED_DIRS = /* @__PURE__ */ new Set(["dist", "build", "outputs", "__pycache__"]);
686
+ sha256b64 = (data) => (0, import_node_crypto.createHash)("sha256").update(data).digest("base64");
687
+ }
688
+ });
689
+
690
+ // src/worlds/validate.ts
691
+ function fmtScore(score) {
692
+ return score === null ? "no score" : score.toFixed(3);
693
+ }
694
+ function buildMarkdown(report, minScore) {
695
+ const lines = [];
696
+ lines.push(
697
+ `### World validation ${report.ok ? "passed" : "failed"} \u2014 \`${report.slug}@${report.branch}\``
698
+ );
699
+ lines.push("");
700
+ lines.push(
701
+ `Ran the pull request's own world source (version \`${report.contentHash.slice(0, 12)}\`) through run config **${report.runConfig.name}**` + (minScore !== null ? `, gating at score \u2265 ${minScore}.` : ".")
702
+ );
703
+ lines.push("");
704
+ lines.push("| Model | Status | Score | Run |");
705
+ lines.push("| --- | --- | ---: | --- |");
706
+ for (const run of report.runs) {
707
+ const r = run.report;
708
+ const link = r?.url ? `[open](${r.url})` : "\u2014";
709
+ const status = run.failure ? `\u274C ${run.failure}` : `\u2705 ${r?.status ?? "COMPLETED"}`;
710
+ lines.push(
711
+ `| \`${run.model}\` | ${status} | ${fmtScore(r?.score ?? null)} | ${link} |`
712
+ );
713
+ }
714
+ const taskRows = report.runs.flatMap(
715
+ (run) => (run.report?.samples ?? []).map((sample) => ({
716
+ model: run.model,
717
+ task: sample.task ?? "?",
718
+ reward: sample.reward
719
+ }))
720
+ );
721
+ if (taskRows.length > 0 && taskRows.length <= 40) {
722
+ lines.push("");
723
+ lines.push("<details><summary>Per-task rewards</summary>");
724
+ lines.push("");
725
+ lines.push("| Task | Model | Reward |");
726
+ lines.push("| --- | --- | ---: |");
727
+ for (const row of taskRows) {
728
+ lines.push(
729
+ `| ${row.task} | \`${row.model}\` | ${row.reward === null ? "no score" : row.reward.toFixed(2)} |`
730
+ );
731
+ }
732
+ lines.push("");
733
+ lines.push("</details>");
734
+ }
735
+ return lines.join("\n");
736
+ }
737
+ async function validateWorld(dir, opts) {
738
+ const options = opts.options ?? {};
739
+ const progress = opts.onProgress ?? (() => {
740
+ });
741
+ const minScore = opts.minScore ?? null;
742
+ const provenance = detectProvenance();
743
+ const branch = opts.branch ?? provenance.branch;
744
+ if (!branch)
745
+ throw new Error(
746
+ "No branch to validate on: pass --branch or run inside a git checkout / GitHub Actions."
747
+ );
748
+ progress(`pushing ${dir} as ${opts.slug ?? "(pyproject name)"}@${branch}\u2026`);
749
+ const pushed = await push(dir, {
750
+ slug: opts.slug,
751
+ branch,
752
+ message: `PR validation push (${provenance.commit?.slice(0, 12) ?? "local"})`,
753
+ ...provenance.actor?.name ? { author: provenance.actor.name } : {},
754
+ options
755
+ });
756
+ progress(`pushed version ${pushed.versionId} (${pushed.contentHash.slice(0, 12)})`);
757
+ const configs = await listRunConfigs(options);
758
+ const runConfig = configs.find((c) => c.id === opts.runConfig) ?? configs.find((c) => c.name === opts.runConfig);
759
+ if (!runConfig) {
760
+ const known = configs.map((c) => c.name).join(", ") || "(none)";
761
+ throw new Error(
762
+ `Run config "${opts.runConfig}" not found in this project. Have: ${known}`
763
+ );
764
+ }
765
+ progress(`dispatching run config "${runConfig.name}" (${runConfig.models.join(", ")})\u2026`);
766
+ const dispatched = await apiRequest(options, "POST", "/api/public/benchmark-containers/run-configs/dispatch", {
767
+ runConfigId: runConfig.id,
768
+ versionId: pushed.versionId,
769
+ ...provenance
770
+ });
771
+ const runs = [];
772
+ for (const run of dispatched.runs) {
773
+ if (!run.ok) {
774
+ runs.push({
775
+ model: run.model,
776
+ runId: run.runId,
777
+ report: null,
778
+ failure: `dispatch failed: ${run.error ?? "unknown error"}`
779
+ });
780
+ continue;
781
+ }
782
+ progress(`waiting on ${run.model} (run ${run.runId})\u2026`);
783
+ let report = null;
784
+ let failure = null;
785
+ try {
786
+ report = await waitForRun(run.runId, {
787
+ timeoutMinutes: opts.timeoutMinutes ?? 45,
788
+ options,
789
+ onTick: (r) => progress(
790
+ `\u2026${run.model}: ${r.status.toLowerCase()} (${r.shardsCompleted ?? 0}/${r.parallelism} shards)`
791
+ )
792
+ });
793
+ if (report.status.toUpperCase() !== "COMPLETED") {
794
+ failure = report.status;
795
+ } else if (minScore !== null) {
796
+ if (report.score === null) failure = "completed without a score";
797
+ else if (report.score < minScore)
798
+ failure = `score ${fmtScore(report.score)} < ${minScore}`;
799
+ }
800
+ } catch (error) {
801
+ failure = error instanceof Error ? error.message : String(error);
802
+ }
803
+ runs.push({ model: run.model, runId: run.runId, report, failure });
804
+ }
805
+ const base = {
806
+ ok: runs.length > 0 && runs.every((r) => r.failure === null),
807
+ slug: pushed.slug,
808
+ branch,
809
+ versionId: pushed.versionId,
810
+ contentHash: pushed.contentHash,
811
+ runConfig: { id: runConfig.id, name: runConfig.name },
812
+ runs
813
+ };
814
+ return { ...base, markdown: buildMarkdown(base, minScore) };
815
+ }
816
+ var init_validate = __esm({
817
+ "src/worlds/validate.ts"() {
818
+ "use strict";
819
+ init_worlds();
820
+ init_hub();
821
+ }
822
+ });
823
+
824
+ // src/worlds/index.ts
825
+ var worlds_exports = {};
826
+ __export(worlds_exports, {
827
+ DEFAULT_BRANCH: () => DEFAULT_BRANCH,
828
+ WorldSession: () => WorldSession,
829
+ WorldSessionCallError: () => WorldSessionCallError,
830
+ WorldSessionTimeout: () => WorldSessionTimeout,
831
+ WorldSet: () => WorldSet,
832
+ WorldTask: () => WorldTask,
833
+ apiRequest: () => apiRequest,
834
+ attachSession: () => attachSession,
835
+ buildSourceTarball: () => buildSourceTarball,
836
+ collectArchiveRelPaths: () => collectArchiveRelPaths,
837
+ computeContentHash: () => computeContentHash,
838
+ createRef: () => createRef,
839
+ deleteEnvSecret: () => deleteEnvSecret,
840
+ detectProvenance: () => detectProvenance,
841
+ getRun: () => getRun,
842
+ isIncludedInContentHash: () => isIncludedInContentHash,
843
+ listEnvSecretKeys: () => listEnvSecretKeys,
844
+ listRunConfigs: () => listRunConfigs,
845
+ localTreeState: () => localTreeState,
846
+ openSession: () => openSession,
847
+ openWorld: () => openWorld,
848
+ propose: () => propose,
849
+ pull: () => pull,
850
+ push: () => push,
851
+ readLocalMeta: () => readLocalMeta,
852
+ runSessions: () => runSessions,
853
+ schemaFromSignature: () => schemaFromSignature,
854
+ setEnvSecret: () => setEnvSecret,
855
+ snapshotTreeHashes: () => snapshotTreeHashes,
856
+ validateWorld: () => validateWorld,
857
+ waitForRun: () => waitForRun,
858
+ writeLocalMeta: () => writeLocalMeta
859
+ });
860
+ module.exports = __toCommonJS(worlds_exports);
861
+ function resolveEnv(options) {
862
+ const host = options.host ?? process.env.GATEWAY_HOST ?? "https://withgateway.ai";
863
+ const publicKey = options.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;
864
+ const secretKey = options.secretKey ?? process.env.GATEWAY_SECRET_KEY;
865
+ if (!publicKey || !secretKey) {
866
+ throw new Error(
867
+ "Gateway keys missing: set GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY (or pass publicKey/secretKey)."
868
+ );
869
+ }
870
+ return { host: host.replace(/\/+$/, ""), publicKey, secretKey };
871
+ }
872
+ async function apiRequest(options, method, path2, body) {
873
+ const { host, publicKey, secretKey } = resolveEnv(options);
874
+ const res = await fetch(`${host}${path2}`, {
875
+ method,
876
+ headers: {
877
+ "content-type": "application/json",
878
+ authorization: "Basic " + Buffer.from(`${publicKey}:${secretKey}`).toString("base64")
879
+ },
880
+ ...body === void 0 ? {} : { body: JSON.stringify(body) }
881
+ });
882
+ const text = await res.text();
883
+ if (!res.ok) {
884
+ throw new Error(
885
+ `${method} ${path2} -> ${res.status}: ${text.slice(0, 400)}`
886
+ );
887
+ }
888
+ return JSON.parse(text);
889
+ }
890
+ async function setEnvSecret(slug, key, value, options = {}) {
891
+ return apiRequest(
892
+ options,
893
+ "PUT",
894
+ "/api/public/benchmark-containers/secrets",
895
+ {
896
+ slug,
897
+ key,
898
+ value
899
+ }
900
+ );
901
+ }
902
+ async function listEnvSecretKeys(slug, options = {}) {
903
+ const res = await apiRequest(
904
+ options,
905
+ "GET",
906
+ `/api/public/benchmark-containers/secrets?slug=${encodeURIComponent(slug)}`
907
+ );
908
+ return res.secrets;
909
+ }
910
+ async function deleteEnvSecret(slug, key, options = {}) {
911
+ await apiRequest(
912
+ options,
913
+ "DELETE",
914
+ "/api/public/benchmark-containers/secrets",
915
+ {
916
+ slug,
917
+ key
918
+ }
919
+ );
920
+ }
921
+ async function listRunConfigs(options = {}) {
922
+ const res = await apiRequest(
923
+ options,
924
+ "GET",
925
+ "/api/public/benchmark-containers/run-configs"
926
+ );
927
+ return res.runConfigs;
928
+ }
929
+ async function getRun(runId, options = {}) {
930
+ return apiRequest(
931
+ options,
932
+ "GET",
933
+ `/api/public/benchmark-containers/runs/${encodeURIComponent(runId)}`
934
+ );
935
+ }
936
+ async function waitForRun(runId, opts = {}) {
937
+ const deadline = Date.now() + (opts.timeoutMinutes ?? 45) * 6e4;
938
+ for (; ; ) {
939
+ const run = await getRun(runId, opts.options ?? {});
940
+ if (run.terminal) return run;
941
+ if (Date.now() > deadline)
942
+ throw new Error(
943
+ `Run ${runId} still ${run.status} after the wait timeout.`
944
+ );
945
+ opts.onTick?.(run);
946
+ await new Promise(
947
+ (resolve2) => setTimeout(resolve2, (opts.intervalSeconds ?? 20) * 1e3)
948
+ );
949
+ }
950
+ }
951
+ function detectProvenance() {
952
+ const env = globalThis.process?.env ?? {};
953
+ const out = {};
954
+ const ref = env.GITHUB_HEAD_REF || env.GITHUB_REF_NAME;
955
+ if (ref) out.branch = ref;
956
+ if (env.GITHUB_SHA) out.commit = env.GITHUB_SHA;
957
+ const server = env.GITHUB_SERVER_URL ?? "https://github.com";
958
+ if (env.GITHUB_REPOSITORY) out.repoUrl = `${server}/${env.GITHUB_REPOSITORY}`;
959
+ if (env.GITHUB_ACTOR) {
960
+ out.actor = {
961
+ kind: "ci",
962
+ id: env.GITHUB_ACTOR,
963
+ name: env.GITHUB_ACTOR,
964
+ // GitHub serves every account's avatar at /<login>.png.
965
+ imageUrl: `${server}/${env.GITHUB_ACTOR}.png`
966
+ };
967
+ }
968
+ if (!out.branch || !out.commit) {
969
+ try {
970
+ const { execFileSync } = require("child_process");
971
+ const git = (args) => execFileSync("git", args, {
972
+ encoding: "utf-8",
973
+ stdio: ["ignore", "pipe", "ignore"]
974
+ }).toString().trim();
975
+ out.branch = out.branch ?? git(["rev-parse", "--abbrev-ref", "HEAD"]);
976
+ out.commit = out.commit ?? git(["rev-parse", "HEAD"]);
977
+ if (!out.repoUrl) {
978
+ const remote = git(["config", "--get", "remote.origin.url"]);
979
+ if (remote) out.repoUrl = remote.replace(/\.git$/, "");
980
+ }
981
+ if (!out.actor) {
982
+ const name = git(["config", "--get", "user.name"]);
983
+ if (name) out.actor = { kind: "user", name };
984
+ }
985
+ } catch {
986
+ }
987
+ }
988
+ return out;
989
+ }
990
+ async function openWorld(slugRef, options = {}) {
991
+ const at = slugRef.indexOf("@");
992
+ const slug = at === -1 ? slugRef : slugRef.slice(0, at);
993
+ const ref = at === -1 ? null : slugRef.slice(at + 1);
994
+ const version = await apiRequest(options, "POST", "/api/public/benchmark-containers/resolve-version", {
995
+ slug,
996
+ ...ref ? { ref } : {}
997
+ });
998
+ const world = new WorldSet(
999
+ slugRef,
1000
+ slug,
1001
+ ref,
1002
+ {
1003
+ versionId: version.versionId,
1004
+ semanticVersion: version.semanticVersion ?? null,
1005
+ contentHash: version.contentHash,
1006
+ state: version.state
1007
+ },
1008
+ [],
1009
+ options
1010
+ );
1011
+ for (const name of version.taskNames ?? []) {
1012
+ const variant = /^[a-z0-9]+-([a-z0-9]+)-/.exec(name)?.[1] ?? null;
1013
+ world.tasks.push(new WorldTask(world, name, variant));
1014
+ }
1015
+ return world;
1016
+ }
1017
+ var WorldTask, WorldSet;
1018
+ var init_worlds = __esm({
1019
+ "src/worlds/index.ts"() {
1020
+ init_session();
1021
+ init_hub();
1022
+ init_validate();
1023
+ WorldTask = class {
1024
+ constructor(world, name, variant) {
1025
+ this.world = world;
1026
+ this.name = name;
1027
+ this.variant = variant;
1028
+ }
1029
+ };
1030
+ WorldSet = class {
1031
+ constructor(slugRef, slug, ref, version, tasks, options) {
1032
+ this.slugRef = slugRef;
1033
+ this.slug = slug;
1034
+ this.ref = ref;
1035
+ this.version = version;
1036
+ this.tasks = tasks;
1037
+ this.options = options;
1038
+ }
1039
+ task(variant) {
1040
+ const hit = this.tasks.find(
1041
+ (t) => t.variant === variant || t.name.includes(variant)
1042
+ );
1043
+ if (!hit) {
1044
+ const known = this.tasks.map((t) => t.variant ?? t.name).join(", ");
1045
+ throw new Error(`no task matches ${variant}; have: ${known}`);
1046
+ }
1047
+ return hit;
1048
+ }
1049
+ /**
1050
+ * Open a LIVE session against one of this world's tasks: the platform boots
1051
+ * (or reuses) a warm container, and your agent calls its tools through the
1052
+ * platform. See worlds/session.ts.
1053
+ */
1054
+ async open(task, opts = {}) {
1055
+ const { openSession: openSession2 } = await Promise.resolve().then(() => (init_session(), session_exports));
1056
+ return openSession2(this.slug, task, {
1057
+ versionId: this.version.versionId,
1058
+ reuseWarm: opts.reuseWarm,
1059
+ options: this.options
1060
+ });
1061
+ }
1062
+ /**
1063
+ * Start a HOSTED run of a run config against this world — the platform
1064
+ * executes the (Python) world in parallel containers per the config's
1065
+ * `parallelism` and files one graded run per model. Returns those runs.
1066
+ */
1067
+ async dispatch(runConfigId, opts = {}) {
1068
+ const provenance = opts.provenance ?? detectProvenance();
1069
+ return apiRequest(
1070
+ this.options,
1071
+ "POST",
1072
+ "/api/public/benchmark-containers/run-configs/dispatch",
1073
+ {
1074
+ runConfigId,
1075
+ ...opts.containerId ? { containerId: opts.containerId } : {},
1076
+ versionId: opts.versionId ?? this.version.versionId,
1077
+ ...provenance
1078
+ }
1079
+ );
1080
+ }
1081
+ };
1082
+ }
1083
+ });
1084
+ init_worlds();
1085
+ // Annotate the CommonJS export names for ESM import in node:
1086
+ 0 && (module.exports = {
1087
+ DEFAULT_BRANCH,
1088
+ WorldSession,
1089
+ WorldSessionCallError,
1090
+ WorldSessionTimeout,
1091
+ WorldSet,
1092
+ WorldTask,
1093
+ apiRequest,
1094
+ attachSession,
1095
+ buildSourceTarball,
1096
+ collectArchiveRelPaths,
1097
+ computeContentHash,
1098
+ createRef,
1099
+ deleteEnvSecret,
1100
+ detectProvenance,
1101
+ getRun,
1102
+ isIncludedInContentHash,
1103
+ listEnvSecretKeys,
1104
+ listRunConfigs,
1105
+ localTreeState,
1106
+ openSession,
1107
+ openWorld,
1108
+ propose,
1109
+ pull,
1110
+ push,
1111
+ readLocalMeta,
1112
+ runSessions,
1113
+ schemaFromSignature,
1114
+ setEnvSecret,
1115
+ snapshotTreeHashes,
1116
+ validateWorld,
1117
+ waitForRun,
1118
+ writeLocalMeta
1119
+ });
1120
+ //# sourceMappingURL=index.js.map