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