@withgateway/sdk 0.1.14 → 0.1.17
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 +475 -271
- package/dist/cli.js.map +1 -1
- package/dist/cli.mjs +471 -267
- package/dist/cli.mjs.map +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +627 -59
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +602 -58
- package/dist/index.mjs.map +1 -1
- package/dist/tracing/index.js +1 -1
- package/dist/tracing/index.js.map +1 -1
- package/dist/tracing/index.mjs +1 -1
- package/dist/tracing/index.mjs.map +1 -1
- package/dist/worlds/index.d.mts +132 -1
- package/dist/worlds/index.d.ts +132 -1
- package/dist/worlds/index.js +560 -6
- package/dist/worlds/index.js.map +1 -1
- package/dist/worlds/index.mjs +550 -6
- package/dist/worlds/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/cli.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/worlds/session.ts","../src/worlds/index.ts","../src/cli.ts","../src/worlds/hub.ts"],"sourcesContent":["import { apiRequest, type WorldsClientOptions } from \"./index\";\n\n/**\n * LIVE WORLD SESSIONS from TypeScript: your agent, the platform's container.\n *\n * The other two ways of running a world each give up something. Pulling the\n * bundle and executing it locally tests your agent against a COPY — your\n * python, your sqlite, your machine's idea of the environment. Dispatching a\n * hosted run gives you the real container but runs the platform's agent\n * inside it, so your agent never touches the world.\n *\n * A session is both: the platform boots the task's container and holds it\n * warm, and every `call()` here executes inside THAT container. Your agent\n * stays where it is — this file is just the wire.\n *\n * const world = await openWorld(\"revenue-ops-sim@main\");\n * const session = await openSession(world.slug, \"revops-mara-dedupe-contacts\");\n * await session.ready(); // wait for the container\n * await session.call(\"crm_search\", { entity: \"deals\" });\n * const { reward, rewards } = await session.grade();\n * await session.close({ keepWarm: true }); // hand it back to the pool\n *\n * Every call is a row on the platform before it is an effect in a container,\n * so the episode is on the record — and the platform traces the session\n * itself, which is why these sessions show up under Sessions without the\n * caller instrumenting anything.\n */\n\nexport type WorldToolSpec = {\n name: string;\n /** The world's own signature, e.g. `crm_search(q=None, entity=\"deals\")`. */\n signature: string;\n doc: string | null;\n};\n\n/** What a model needs to call a world: the schemas to advertise, and the\n * implementations that run them in the container. */\nexport type WorldToolkit = {\n /** OpenAI-shaped tool definitions, derived from the world's signatures. */\n schemas: {\n type: \"function\";\n function: {\n name: string;\n description: string;\n parameters: Record<string, unknown>;\n };\n }[];\n /** name -> implementation, each one a call into THIS session. */\n impls: Record<string, (args: Record<string, unknown>) => Promise<unknown>>;\n specs: WorldToolSpec[];\n};\n\nexport type WorldSessionState = {\n sessionId: string;\n state: string;\n ready: boolean;\n versionId: string;\n contentHash: string;\n taskName: string | null;\n /** The task's objective — present when the session was opened (not on a\n * bare status read), so a client never needs the bundle on disk. */\n instruction?: string | null;\n /** The tools this task serves. */\n tools?: WorldToolSpec[];\n};\n\nexport type GradeResult = {\n reward: number | null;\n rewards: Record<string, number>;\n raw: unknown;\n};\n\n/** How long `ready()` waits, and how often it asks. */\nconst READY_TIMEOUT_MS = 10 * 60_000;\nconst READY_POLL_MS = 2_000;\n/** How long one call may take end to end (container claim + execution). */\nconst CALL_TIMEOUT_MS = 3 * 60_000;\nconst CALL_POLL_MS = 400;\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\n/**\n * Turn a world's Python signature into a JSON schema the model can call.\n *\n * `crm_update_deal(id, stage=None, owner=None, amount=None)` becomes an\n * object with `id` required and the rest optional. Types are read from the\n * DEFAULTS the world declares — a numeric default means a number, a boolean\n * default a boolean — because that is the only type information a signature\n * actually carries. Everything else is a string, which is what a tool CLI\n * receives anyway.\n */\nexport function schemaFromSignature(spec: WorldToolSpec): {\n type: \"function\";\n function: {\n name: string;\n description: string;\n parameters: Record<string, unknown>;\n };\n} {\n const inside = /\\(([\\s\\S]*)\\)\\s*$/.exec(spec.signature.trim())?.[1] ?? \"\";\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n // Split on top-level commas only: a default like `{\"a\": 1}` has its own.\n const params: string[] = [];\n let depth = 0;\n let current = \"\";\n for (const ch of inside) {\n if (\"([{\".includes(ch)) depth++;\n if (\")]}\".includes(ch)) depth--;\n if (ch === \",\" && depth === 0) {\n params.push(current);\n current = \"\";\n } else current += ch;\n }\n if (current.trim()) params.push(current);\n\n for (const raw of params) {\n const param = raw.trim();\n if (!param || param.startsWith(\"*\") || param === \"self\") continue;\n const eq = param.indexOf(\"=\");\n const name = (eq === -1 ? param : param.slice(0, eq)).split(\":\")[0].trim();\n if (!name) continue;\n if (eq === -1) {\n properties[name] = { type: \"string\" };\n required.push(name);\n continue;\n }\n const value = param.slice(eq + 1).trim();\n if (/^-?\\d+(\\.\\d+)?$/.test(value)) properties[name] = { type: \"number\" };\n else if (value === \"True\" || value === \"False\")\n properties[name] = { type: \"boolean\" };\n else properties[name] = { type: \"string\" };\n }\n return {\n type: \"function\",\n function: {\n name: spec.name,\n description: spec.doc ?? spec.name,\n parameters: { type: \"object\", properties, required },\n },\n };\n}\n\nexport class WorldSessionTimeout extends Error {}\nexport class WorldSessionCallError extends Error {}\n\nexport class WorldSession {\n constructor(\n readonly sessionId: string,\n private state: WorldSessionState,\n private readonly options: WorldsClientOptions,\n ) {}\n\n get task(): string | null {\n return this.state.taskName;\n }\n\n /** What this task asks for — the bundle's own instruction.md. */\n get instruction(): string | null {\n return this.state.instruction ?? null;\n }\n\n get versionId(): string {\n return this.state.versionId;\n }\n\n /** The session's latest platform state (one request, no waiting). */\n async status(): Promise<WorldSessionState> {\n const fresh = await apiRequest<WorldSessionState>(\n this.options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}`,\n );\n // A status read does not carry the objective; keep the one we opened with.\n this.state = {\n instruction: this.state.instruction,\n tools: this.state.tools,\n ...fresh,\n };\n return this.state;\n }\n\n /**\n * Wait until the container is warm — meaning the process inside it has\n * asked the platform for work, not merely that a job was accepted.\n */\n async ready(opts: { timeoutMs?: number } = {}): Promise<WorldSessionState> {\n const deadline = Date.now() + (opts.timeoutMs ?? READY_TIMEOUT_MS);\n for (;;) {\n const state = await this.status();\n if (state.ready) return state;\n if (state.state === \"FAILED\" || state.state === \"STOPPED\")\n throw new WorldSessionCallError(\n `World session ${state.state.toLowerCase()} before it was ready.`,\n );\n if (Date.now() > deadline)\n throw new WorldSessionTimeout(\n `World session still ${state.state} after ${Math.round((opts.timeoutMs ?? READY_TIMEOUT_MS) / 1000)}s.`,\n );\n await sleep(READY_POLL_MS);\n }\n }\n\n /** Enqueue one interaction and wait for the container's answer. */\n private async exchange(\n body: { kind?: \"call\" | \"grade\" | \"close\"; tool?: string; args?: unknown },\n timeoutMs = CALL_TIMEOUT_MS,\n ): Promise<unknown> {\n const { callId } = await apiRequest<{ callId: string; seq: number }>(\n this.options,\n \"POST\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/calls`,\n body,\n );\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n const call = await apiRequest<{\n done: boolean;\n state: string;\n result: unknown;\n error: string | null;\n }>(\n this.options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/calls/${encodeURIComponent(callId)}`,\n );\n if (call.done) {\n if (call.error) throw new WorldSessionCallError(call.error);\n return call.result;\n }\n if (Date.now() > deadline)\n throw new WorldSessionTimeout(\n `Call ${callId} still ${call.state} after ${Math.round(timeoutMs / 1000)}s — the container may have died.`,\n );\n await sleep(CALL_POLL_MS);\n }\n }\n\n /**\n * Run one of the world's tools INSIDE the container. The arguments and the\n * result are the world's own contract — this layer neither validates nor\n * reshapes them, so a tool error reads exactly as it would in a hosted run.\n */\n async call(\n tool: string,\n args: Record<string, unknown> = {},\n opts: { timeoutMs?: number } = {},\n ): Promise<unknown> {\n return this.exchange({ kind: \"call\", tool, args }, opts.timeoutMs);\n }\n\n /**\n * THE WORLD'S TOOLS, READY TO HAND TO A MODEL. Schemas come from the\n * world's own signatures and implementations call into this session, so a\n * caller never writes — and never has to re-sync — a tool map of their own:\n *\n * const { schemas, impls } = await session.toolkit();\n * await runMyAgent(impls, schemas, session.instruction);\n *\n * A tool added to the world shows up here on the next run; a tool renamed\n * in the world renames here too, instead of failing at call time against a\n * hand-written map that still remembers the old name.\n */\n async toolkit(): Promise<WorldToolkit> {\n let specs = this.state.tools;\n if (!specs) specs = (await this.status()).tools ?? [];\n const impls: WorldToolkit[\"impls\"] = {};\n for (const spec of specs) {\n impls[spec.name] = (args: Record<string, unknown> = {}) =>\n this.call(spec.name, args);\n }\n return { schemas: specs.map(schemaFromSignature), impls, specs };\n }\n\n /** Run the task's grader against the container's END STATE. */\n async grade(opts: { timeoutMs?: number } = {}): Promise<GradeResult> {\n const raw = (await this.exchange(\n { kind: \"grade\" },\n opts.timeoutMs,\n )) as Record<string, unknown> | null;\n const record = raw && typeof raw === \"object\" ? raw : {};\n const rewards: Record<string, number> = {};\n for (const [key, value] of Object.entries(record)) {\n if (key !== \"reward\" && typeof value === \"number\") rewards[key] = value;\n }\n return {\n reward: typeof record.reward === \"number\" ? record.reward : null,\n rewards,\n raw,\n };\n }\n\n /**\n * End the session. `keepWarm` hands the container back to the pool instead\n * of tearing it down, so the next session for the same task starts warm —\n * the pooled instance still obeys the fleet's idle TTL and pinning.\n */\n async close(opts: { keepWarm?: boolean } = {}): Promise<{ state: string }> {\n return apiRequest(\n this.options,\n \"DELETE\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}`,\n { keepWarm: opts.keepWarm ?? false },\n );\n }\n}\n\n/**\n * Attach to a session that already exists — resuming after a crash, or\n * driving a session someone else opened (a container started by hand on a\n * self-hosted install, a session opened by CI and handed to a developer).\n */\nexport async function attachSession(\n sessionId: string,\n options: WorldsClientOptions = {},\n): Promise<WorldSession> {\n const state = await apiRequest<WorldSessionState>(\n options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(sessionId)}`,\n );\n return new WorldSession(sessionId, state, options);\n}\n\n/**\n * Open a live session against one task of a world. Returns as soon as the\n * platform has accepted it — call `ready()` to wait for the container.\n */\nexport async function openSession(\n slugOrRef: string,\n task: string,\n opts: {\n versionId?: string;\n reuseWarm?: boolean;\n options?: WorldsClientOptions;\n } = {},\n): Promise<WorldSession> {\n const options = opts.options ?? {};\n const at = slugOrRef.indexOf(\"@\");\n const slug = at === -1 ? slugOrRef : slugOrRef.slice(0, at);\n const state = await apiRequest<WorldSessionState & { reusedWarm: boolean }>(\n options,\n \"POST\",\n \"/api/public/world-sessions\",\n {\n ...(opts.versionId ? { versionId: opts.versionId } : { slug }),\n task,\n ...(opts.reuseWarm === undefined ? {} : { reuseWarm: opts.reuseWarm }),\n },\n );\n return new WorldSession(state.sessionId, state, options);\n}\n\n// ── running many tasks at once ───────────────────────────────────────────────\n\nexport type SessionRunResult = {\n task: string;\n sessionId: string;\n reward: number | null;\n rewards: Record<string, number>;\n /** Set when the task threw instead of grading. */\n error?: string;\n};\n\nexport type SessionRunReport = {\n results: SessionRunResult[];\n /** Mean reward over every task, counting failures as 0. */\n mean: number;\n /** True when `mean >= failUnder` (or no gate was set). */\n passed: boolean;\n};\n\n/**\n * RUN MANY TASKS IN PARALLEL, one warm container each.\n *\n * Parallelism against live worlds is the normal case — a suite is a dozen\n * tasks and each needs its own container, because two agents sharing one\n * world state would corrupt both episodes. Every caller was writing the same\n * pool, the same per-task open/ready/toolkit/grade/close, and the same\n * \"don't let one failure kill the run\" logic, so it belongs here:\n *\n * const report = await runSessions({\n * world: \"revenue-ops-sim@main\",\n * tasks, // default: every task in the world\n * concurrency: 4,\n * failUnder: 0.7,\n * agent: async ({ toolkit, instruction }) =>\n * myAgent(toolkit.impls, toolkit.schemas, instruction),\n * });\n *\n * The handler gets a ready session with its toolkit already bound; grading,\n * closing (warm) and aggregation are handled. A task that throws scores 0\n * and records why — the tasks that passed keep their results.\n */\nexport async function runSessions(opts: {\n world: string;\n tasks?: string[];\n concurrency?: number;\n failUnder?: number;\n /** Pin every session to one version (default: the world's head). */\n versionId?: string;\n /** Hand the containers back warm for the next run (default: true). */\n keepWarm?: boolean;\n agent: (ctx: {\n session: WorldSession;\n toolkit: WorldToolkit;\n instruction: string;\n task: string;\n }) => Promise<unknown>;\n onResult?: (result: SessionRunResult) => void;\n options?: WorldsClientOptions;\n}): Promise<SessionRunReport> {\n const options = opts.options ?? {};\n const concurrency = Math.max(1, opts.concurrency ?? 3);\n\n let tasks = opts.tasks;\n let versionId = opts.versionId;\n if (!tasks || !versionId) {\n // One resolve for the whole run: every session pins the SAME version, so\n // a push mid-suite cannot split the results across two worlds.\n const { openWorld } = await import(\"./index\");\n const world = await openWorld(opts.world, options);\n tasks = tasks ?? world.tasks.map((t) => t.name);\n versionId = versionId ?? world.version.versionId;\n }\n\n const results: SessionRunResult[] = [];\n let next = 0;\n await Promise.all(\n Array.from({ length: Math.min(concurrency, tasks.length) }, async () => {\n while (next < tasks!.length) {\n const task = tasks![next++];\n let session: WorldSession | null = null;\n try {\n session = await openSession(opts.world, task, {\n versionId,\n options,\n });\n await session.ready();\n const toolkit = await session.toolkit();\n await opts.agent({\n session,\n toolkit,\n instruction: session.instruction ?? task,\n task,\n });\n const graded = await session.grade();\n const result: SessionRunResult = {\n task,\n sessionId: session.sessionId,\n reward: graded.reward,\n rewards: graded.rewards,\n };\n results.push(result);\n opts.onResult?.(result);\n } catch (error) {\n const result: SessionRunResult = {\n task,\n sessionId: session?.sessionId ?? \"\",\n reward: 0,\n rewards: {},\n // An Error with an empty message would read as \"no error\" to any\n // caller checking truthiness; name the type instead.\n error:\n (error instanceof Error ? error.message : String(error)) ||\n (error instanceof Error ? error.name : \"Unknown error\"),\n };\n results.push(result);\n opts.onResult?.(result);\n } finally {\n // Always give the container back — a leaked session bills until the\n // fleet's idle TTL reaps it.\n await session\n ?.close({ keepWarm: opts.keepWarm ?? true })\n .catch(() => undefined);\n }\n }\n }),\n );\n\n const mean =\n results.reduce((sum, r) => sum + (r.reward ?? 0), 0) /\n (results.length || 1);\n return {\n results: results.sort((a, b) => a.task.localeCompare(b.task)),\n mean,\n passed: opts.failUnder === undefined ? true : mean >= opts.failUnder,\n };\n}\n","/**\n * Worlds from TypeScript: identity, tasks, and HOSTED execution.\n *\n * The same three-level model as the Python SDK — WorldSet → Task — with one\n * deliberate difference: a world's tools are Python modules, so TypeScript\n * does not materialize task environments in-process. What a TS agent\n * codebase needs is exactly what this module provides: resolve a world ref\n * to its pinned version, read its task list, and dispatch HOSTED runs\n * (parallelism included) that execute the world server-side and file graded,\n * version-pinned rollouts. Local in-process execution stays a Python\n * capability by design, not by omission.\n */\n\nexport type WorldsClientOptions = {\n host?: string;\n publicKey?: string;\n secretKey?: string;\n};\n\nexport type ResolvedWorldVersion = {\n versionId: string;\n semanticVersion: string | null;\n contentHash: string;\n state?: string;\n};\n\nexport type WorldTaskInfo = {\n name: string;\n variant: string | null;\n};\n\nexport type DispatchedRun = {\n model: string;\n runId: string;\n ok: boolean;\n error?: string;\n};\n\nfunction resolveEnv(options: WorldsClientOptions) {\n const host =\n options.host ?? process.env.GATEWAY_HOST ?? \"https://withgateway.ai\";\n const publicKey = options.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;\n const secretKey = options.secretKey ?? process.env.GATEWAY_SECRET_KEY;\n if (!publicKey || !secretKey) {\n throw new Error(\n \"Gateway keys missing: set GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY \" +\n \"(or pass publicKey/secretKey).\",\n );\n }\n return { host: host.replace(/\\/+$/, \"\"), publicKey, secretKey };\n}\n\n/** Authenticated JSON request against the platform API — the primitive the\n * worlds helpers and the TS CLI share. */\nexport async function apiRequest<T>(\n options: WorldsClientOptions,\n method: \"GET\" | \"POST\" | \"PUT\" | \"DELETE\",\n path: string,\n body?: unknown,\n): Promise<T> {\n const { host, publicKey, secretKey } = resolveEnv(options);\n const res = await fetch(`${host}${path}`, {\n method,\n headers: {\n \"content-type\": \"application/json\",\n authorization:\n \"Basic \" + Buffer.from(`${publicKey}:${secretKey}`).toString(\"base64\"),\n },\n ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n });\n const text = await res.text();\n if (!res.ok) {\n throw new Error(\n `${method} ${path} -> ${res.status}: ${text.slice(0, 400)}`,\n );\n }\n return JSON.parse(text) as T;\n}\n\n/** Set (or rotate) one environment secret — write-only: no API returns it. */\nexport async function setEnvSecret(\n slug: string,\n key: string,\n value: string,\n options: WorldsClientOptions = {},\n): Promise<{ key: string; created: boolean }> {\n return apiRequest(\n options,\n \"PUT\",\n \"/api/public/benchmark-containers/secrets\",\n {\n slug,\n key,\n value,\n },\n );\n}\n\n/** Keys and rotation timestamps only — never values. */\nexport async function listEnvSecretKeys(\n slug: string,\n options: WorldsClientOptions = {},\n): Promise<{ key: string; updatedAt: string }[]> {\n const res = await apiRequest<{\n secrets: { key: string; updatedAt: string }[];\n }>(\n options,\n \"GET\",\n `/api/public/benchmark-containers/secrets?slug=${encodeURIComponent(slug)}`,\n );\n return res.secrets;\n}\n\nexport async function deleteEnvSecret(\n slug: string,\n key: string,\n options: WorldsClientOptions = {},\n): Promise<void> {\n await apiRequest(\n options,\n \"DELETE\",\n \"/api/public/benchmark-containers/secrets\",\n {\n slug,\n key,\n },\n );\n}\n\nexport type RunConfigSummary = {\n id: string;\n name: string;\n runType: string;\n createdAt: string;\n models: string[];\n parallelism: number;\n autoRunOnPush: boolean;\n agent: string | null;\n};\n\n/** Run configs in the project. CI resolves by NAME and dispatches by id. */\nexport async function listRunConfigs(\n options: WorldsClientOptions = {},\n): Promise<RunConfigSummary[]> {\n const res = await apiRequest<{ runConfigs: RunConfigSummary[] }>(\n options,\n \"GET\",\n \"/api/public/benchmark-containers/run-configs\",\n );\n return res.runConfigs;\n}\n\nexport type RunReport = {\n id: string;\n status: string;\n terminal: boolean;\n score: number | null;\n summary: string | null;\n model: string | null;\n versionLabel: string | null;\n parallelism: number;\n shardsCompleted: number | null;\n evaluations: { id: string; status: string; avgReward: number | null }[];\n samples: {\n task: string | null;\n reward: number | null;\n rewards: Record<string, unknown>;\n sessionId: string | null;\n }[];\n};\n\n/** The read half of dispatch: status, score, per-shard evaluations, and\n * per-task rewards — everything a CI gate needs. */\nexport async function getRun(\n runId: string,\n options: WorldsClientOptions = {},\n): Promise<RunReport> {\n return apiRequest(\n options,\n \"GET\",\n `/api/public/benchmark-containers/runs/${encodeURIComponent(runId)}`,\n );\n}\n\n/** Poll a run to terminal (default every 20s, up to `timeoutMinutes`). */\nexport async function waitForRun(\n runId: string,\n opts: {\n timeoutMinutes?: number;\n intervalSeconds?: number;\n onTick?: (run: RunReport) => void;\n options?: WorldsClientOptions;\n } = {},\n): Promise<RunReport> {\n const deadline = Date.now() + (opts.timeoutMinutes ?? 45) * 60_000;\n for (;;) {\n const run = await getRun(runId, opts.options ?? {});\n if (run.terminal) return run;\n if (Date.now() > deadline)\n throw new Error(\n `Run ${runId} still ${run.status} after the wait timeout.`,\n );\n opts.onTick?.(run);\n await new Promise((resolve) =>\n setTimeout(resolve, (opts.intervalSeconds ?? 20) * 1000),\n );\n }\n}\n\nexport type RunProvenance = {\n branch?: string;\n commit?: string;\n repoUrl?: string;\n actor?: { id?: string; name?: string; imageUrl?: string; kind?: string };\n};\n\n/**\n * Where a dispatch comes from, DETECTED rather than configured: the CI\n * checkout's branch/commit/actor under GitHub Actions, else the developer's\n * own git checkout. A run nobody can trace to a branch is a score with no\n * code attached, so every dispatch carries this unless overridden.\n */\nexport function detectProvenance(): RunProvenance {\n const env =\n (globalThis as { process?: { env?: Record<string, string | undefined> } })\n .process?.env ?? {};\n const out: RunProvenance = {};\n const ref = env.GITHUB_HEAD_REF || env.GITHUB_REF_NAME;\n if (ref) out.branch = ref;\n if (env.GITHUB_SHA) out.commit = env.GITHUB_SHA;\n const server = env.GITHUB_SERVER_URL ?? \"https://github.com\";\n if (env.GITHUB_REPOSITORY) out.repoUrl = `${server}/${env.GITHUB_REPOSITORY}`;\n if (env.GITHUB_ACTOR) {\n out.actor = {\n kind: \"ci\",\n id: env.GITHUB_ACTOR,\n name: env.GITHUB_ACTOR,\n // GitHub serves every account's avatar at /<login>.png.\n imageUrl: `${server}/${env.GITHUB_ACTOR}.png`,\n };\n }\n if (!out.branch || !out.commit) {\n try {\n const { execFileSync } =\n require(\"node:child_process\") as typeof import(\"node:child_process\");\n const git = (args: string[]) =>\n execFileSync(\"git\", args, {\n encoding: \"utf-8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n })\n .toString()\n .trim();\n out.branch = out.branch ?? git([\"rev-parse\", \"--abbrev-ref\", \"HEAD\"]);\n out.commit = out.commit ?? git([\"rev-parse\", \"HEAD\"]);\n if (!out.repoUrl) {\n const remote = git([\"config\", \"--get\", \"remote.origin.url\"]);\n if (remote) out.repoUrl = remote.replace(/\\.git$/, \"\");\n }\n if (!out.actor) {\n const name = git([\"config\", \"--get\", \"user.name\"]);\n if (name) out.actor = { kind: \"user\", name };\n }\n } catch {\n // No git here — dispatch without provenance rather than failing.\n }\n }\n return out;\n}\n\n/** One scenario of a world, as data. */\nexport class WorldTask {\n constructor(\n readonly world: WorldSet,\n readonly name: string,\n readonly variant: string | null,\n ) {}\n}\n\n/**\n * THE world, from a TS process: pinned identity + its tasks + hosted runs.\n *\n * const world = await openWorld(\"google-drive-sim@main\");\n * console.log(world.version.semanticVersion, world.tasks.length);\n * const runs = await world.dispatch(runConfigId);\n */\nexport class WorldSet {\n constructor(\n readonly slugRef: string,\n readonly slug: string,\n readonly ref: string | null,\n readonly version: ResolvedWorldVersion,\n public tasks: WorldTask[],\n private readonly options: WorldsClientOptions,\n ) {}\n\n task(variant: string): WorldTask {\n const hit = this.tasks.find(\n (t) => t.variant === variant || t.name.includes(variant),\n );\n if (!hit) {\n const known = this.tasks.map((t) => t.variant ?? t.name).join(\", \");\n throw new Error(`no task matches ${variant}; have: ${known}`);\n }\n return hit;\n }\n\n /**\n * Open a LIVE session against one of this world's tasks: the platform boots\n * (or reuses) a warm container, and your agent calls its tools through the\n * platform. See worlds/session.ts.\n */\n async open(\n task: string,\n opts: { reuseWarm?: boolean } = {},\n ): Promise<import(\"./session\").WorldSession> {\n const { openSession } = await import(\"./session\");\n return openSession(this.slug, task, {\n versionId: this.version.versionId,\n reuseWarm: opts.reuseWarm,\n options: this.options,\n });\n }\n\n /**\n * Start a HOSTED run of a run config against this world — the platform\n * executes the (Python) world in parallel containers per the config's\n * `parallelism` and files one graded run per model. Returns those runs.\n */\n async dispatch(\n runConfigId: string,\n opts: {\n containerId?: string;\n versionId?: string;\n /** Override the auto-detected branch/commit/actor. */\n provenance?: RunProvenance;\n } = {},\n ): Promise<{ versionLabel: string; runs: DispatchedRun[] }> {\n const provenance = opts.provenance ?? detectProvenance();\n return apiRequest(\n this.options,\n \"POST\",\n \"/api/public/benchmark-containers/run-configs/dispatch\",\n {\n runConfigId,\n ...(opts.containerId ? { containerId: opts.containerId } : {}),\n versionId: opts.versionId ?? this.version.versionId,\n ...provenance,\n },\n );\n }\n}\n\n/**\n * Resolve `slug` / `slug@branch|tag|semver|hash` to its pinned version and\n * task list. The task list comes from the version's file manifest\n * (`tasks/<name>/task.toml`), so it needs no bundle download.\n */\nexport async function openWorld(\n slugRef: string,\n options: WorldsClientOptions = {},\n): Promise<WorldSet> {\n const at = slugRef.indexOf(\"@\");\n const slug = at === -1 ? slugRef : slugRef.slice(0, at);\n const ref = at === -1 ? null : slugRef.slice(at + 1);\n\n const version = await apiRequest<\n ResolvedWorldVersion & { taskNames?: string[] }\n >(options, \"POST\", \"/api/public/benchmark-containers/resolve-version\", {\n slug,\n ...(ref ? { ref } : {}),\n });\n\n const world = new WorldSet(\n slugRef,\n slug,\n ref,\n {\n versionId: version.versionId,\n semanticVersion: version.semanticVersion ?? null,\n contentHash: version.contentHash,\n state: version.state,\n },\n [],\n options,\n );\n for (const name of version.taskNames ?? []) {\n const variant = /^[a-z0-9]+-([a-z0-9]+)-/.exec(name)?.[1] ?? null;\n world.tasks.push(new WorldTask(world, name, variant));\n }\n return world;\n}\n\n// The session surface completes the worlds module, so `@withgateway/sdk/worlds`\n// carries both halves: running a world locally, and driving one the platform\n// hosts. (session.ts imports apiRequest from here; the cycle is function-level\n// only, and the build below is what proves it resolves.)\nexport * from \"./session\";\n","#!/usr/bin/env node\n/**\n * The TypeScript `gateway` CLI — full command parity with the Python CLI's\n * `bench` family, including the working-dir workflows (push/pull/checkout/\n * status/branch/tag/propose — see worlds/hub.ts and its LOCKSTEP WARNING on\n * the content hash). The one Python-only command is `eval`: it runs the\n * world locally on the Python engines, which a JS process cannot host —\n * hosted runs via `dispatch` are the equivalent.\n *\n * Auth: GATEWAY_HOST + GATEWAY_PUBLIC_KEY + GATEWAY_SECRET_KEY, same env as\n * the library.\n */\nimport {\n apiRequest,\n deleteEnvSecret,\n getRun,\n listEnvSecretKeys,\n listRunConfigs,\n openWorld,\n setEnvSecret,\n waitForRun,\n} from \"./worlds/index\";\nimport {\n computeContentHash,\n createRef,\n localTreeState,\n propose,\n pull,\n push,\n} from \"./worlds/hub\";\n\ntype Flags = Record<string, string | boolean>;\n\nfunction parseArgv(argv: string[]): { positional: string[]; flags: Flags } {\n const positional: string[] = [];\n const flags: Flags = {};\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i];\n if (arg.startsWith(\"--\")) {\n const key = arg.slice(2);\n const next = argv[i + 1];\n if (next !== undefined && !next.startsWith(\"--\")) {\n flags[key] = next;\n i++;\n } else {\n flags[key] = true;\n }\n } else {\n positional.push(arg);\n }\n }\n return { positional, flags };\n}\n\nfunction str(flags: Flags, key: string): string | undefined {\n const value = flags[key];\n return typeof value === \"string\" ? value : undefined;\n}\n\nfunction fail(message: string): never {\n console.error(message);\n process.exit(2);\n}\n\nconst PYTHON_ONLY = new Set([\"eval\"]);\n\nconst HELP = `gateway bench <command> — worlds from TypeScript\n\n resolve <slug[@ref]> pinned version + task count\n tasks <slug[@ref]> the task list\n dispatch <runConfigId> [--container-id X] [--version-id Y]\n run <runId> [--wait] [--timeout-min N] status, score, per-task rewards\n run-configs list\n run-configs create --name N --models a,b [--parallelism K] [--tasks t1,t2] [--agent A] [--auto-run-on-push] [--id existing]\n run-configs delete --id X\n secrets set --env <slug> --key K [--value V] (omit --value to read stdin)\n secrets list --env <slug>\n secrets unset --env <slug> --key K\n refs <slug> branches and tags\n log <slug> [--branch B] [--limit N] version history\n proposals <slug> [--status open|applied|dismissed]\n\n pull <slug[@ref]> [--dir D] materialize a working dir\n push [dir] [--slug S] [--branch B] [--force] [--message M]\n checkout <slug@ref> --dir D re-aim an existing working dir\n status [dir] clean/dirty vs base + hash check\n branch <slug> <name> [--version-id V] create a branch\n tag <slug> <name> [--version-id V] create a tag\n propose [dir] --title T --reason R [--target-branch B]\n\n eval (local engine runs) is Python-only — run hosted via 'dispatch'.\n\nAuth: GATEWAY_HOST, GATEWAY_PUBLIC_KEY, GATEWAY_SECRET_KEY.`;\n\nasync function readStdin(): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) chunks.push(chunk as Buffer);\n return Buffer.concat(chunks).toString(\"utf-8\").trim();\n}\n\nasync function main(): Promise<number> {\n const [group, command, ...rest] = process.argv.slice(2);\n if (!group || group === \"help\" || group === \"--help\") {\n console.log(HELP);\n return 0;\n }\n if (group !== \"bench\") {\n fail(\n `Unknown command group '${group}' — this CLI covers 'gateway bench'. Run 'gateway help'.`,\n );\n }\n if (!command) fail(HELP);\n if (PYTHON_ONLY.has(command)) {\n fail(\n `'gateway bench eval' runs the world locally on the PYTHON engines (verifiers/harbor) — it cannot exist in a JS process.\\n` +\n `Run hosted instead: gateway bench dispatch <runConfigId> — same worlds, graded on the platform.`,\n );\n }\n\n const { positional, flags } = parseArgv(rest);\n\n switch (command) {\n case \"resolve\": {\n const slugRef =\n positional[0] ?? fail(\"usage: gateway bench resolve <slug[@ref]>\");\n const world = await openWorld(slugRef);\n console.log(\n `${world.slug}@${world.ref ?? \"latest\"}: ${world.version.semanticVersion ?? \"-\"} ` +\n `(${world.version.contentHash.slice(0, 12)}) · ${world.version.state ?? \"?\"} · ${world.tasks.length} tasks`,\n );\n console.log(`versionId: ${world.version.versionId}`);\n return 0;\n }\n case \"tasks\": {\n const slugRef =\n positional[0] ?? fail(\"usage: gateway bench tasks <slug[@ref]>\");\n const world = await openWorld(slugRef);\n if (world.tasks.length === 0) {\n console.log(\"No task manifest served for this version.\");\n return 0;\n }\n for (const task of world.tasks) {\n console.log(`${task.name}${task.variant ? ` (${task.variant})` : \"\"}`);\n }\n return 0;\n }\n case \"dispatch\": {\n const runConfigId =\n positional[0] ?? fail(\"usage: gateway bench dispatch <runConfigId>\");\n const body: Record<string, string> = { runConfigId };\n const containerId = str(flags, \"container-id\");\n const versionId = str(flags, \"version-id\");\n if (containerId) body.containerId = containerId;\n if (versionId) body.versionId = versionId;\n const result = await apiRequest<{\n versionLabel: string;\n runs: { model: string; runId: string; ok: boolean; error?: string }[];\n }>(\n {},\n \"POST\",\n \"/api/public/benchmark-containers/run-configs/dispatch\",\n body,\n );\n for (const run of result.runs) {\n console.log(\n `${run.model}: ${run.ok ? \"dispatched\" : `FAILED: ${run.error}`} run=${run.runId}`,\n );\n }\n console.log(`-> ${result.versionLabel}`);\n return result.runs.every((r) => r.ok) ? 0 : 1;\n }\n case \"run\": {\n const runId =\n positional[0] ?? fail(\"usage: gateway bench run <runId> [--wait]\");\n const report = flags.wait\n ? await waitForRun(runId, {\n timeoutMinutes: Number(str(flags, \"timeout-min\") ?? 45),\n onTick: (r) =>\n console.error(\n `…${r.status.toLowerCase()} (${r.shardsCompleted ?? 0}/${r.parallelism} shards)`,\n ),\n })\n : await getRun(runId);\n console.log(\n `${report.id} ${report.status}${report.score !== null ? ` score=${report.score.toFixed(3)}` : \"\"}` +\n ` (${report.model ?? \"?\"} · ${report.versionLabel ?? \"?\"} · x${report.parallelism})`,\n );\n for (const sample of report.samples) {\n const subs = Object.entries(sample.rewards)\n .filter(([, v]) => typeof v === \"number\")\n .map(([k, v]) => `${k}=${(v as number).toFixed(2)}`)\n .join(\" \");\n console.log(\n ` ${(sample.reward ?? 0).toFixed(2)} ${sample.task ?? \"?\"}${subs ? ` [${subs}]` : \"\"}`,\n );\n }\n if (report.summary) console.log(` ${report.summary}`);\n return report.terminal && report.status.toUpperCase() === \"COMPLETED\"\n ? 0\n : 1;\n }\n case \"run-configs\": {\n const action = positional[0] ?? \"list\";\n if (action === \"list\") {\n const rows = await listRunConfigs();\n if (rows.length === 0) {\n console.log(\"No run configs in this project.\");\n return 0;\n }\n for (const row of rows) {\n const extras = [\n row.parallelism > 1 ? `x${row.parallelism} containers` : null,\n row.autoRunOnPush ? \"auto-on-push\" : null,\n ].filter(Boolean);\n console.log(\n `${row.id} ${row.name} (${row.models.join(\", \") || \"no models\"})${extras.length ? ` [${extras.join(\", \")}]` : \"\"}`,\n );\n }\n return 0;\n }\n if (action === \"delete\") {\n const id = str(flags, \"id\") ?? fail(\"--id is required for delete\");\n await apiRequest(\n {},\n \"DELETE\",\n \"/api/public/benchmark-containers/run-configs\",\n { id },\n );\n console.log(`Deleted ${id}.`);\n return 0;\n }\n if (action !== \"create\")\n fail(\"run-configs actions: list | create | delete\");\n const name = str(flags, \"name\") ?? fail(\"--name is required for create\");\n const models = (\n str(flags, \"models\") ?? fail(\"--models is required for create\")\n )\n .split(\",\")\n .map((m) => m.trim())\n .filter(Boolean);\n const body: Record<string, unknown> = { name, models };\n const parallelism = str(flags, \"parallelism\");\n if (parallelism) body.parallelism = Number(parallelism);\n const agent = str(flags, \"agent\");\n if (agent) body.agent = agent;\n const tasks = str(flags, \"tasks\");\n if (tasks)\n body.taskNames = tasks\n .split(\",\")\n .map((t) => t.trim())\n .filter(Boolean);\n if (flags[\"auto-run-on-push\"]) body.autoRunOnPush = true;\n const id = str(flags, \"id\");\n if (id) body.id = id;\n const row = await apiRequest<{\n id: string;\n name: string;\n models: string[];\n }>({}, \"POST\", \"/api/public/benchmark-containers/run-configs\", body);\n console.log(`${row.id} ${row.name} (${row.models.join(\", \")})`);\n return 0;\n }\n case \"secrets\": {\n const action =\n positional[0] ?? fail(\"secrets actions: set | list | unset\");\n const env = str(flags, \"env\") ?? fail(\"--env <world slug> is required\");\n if (action === \"list\") {\n const rows = await listEnvSecretKeys(env);\n if (rows.length === 0) {\n console.log(`No secrets on ${env}.`);\n return 0;\n }\n for (const row of rows)\n console.log(`${row.key} (rotated ${row.updatedAt})`);\n return 0;\n }\n const key = str(flags, \"key\") ?? fail(`--key is required for ${action}`);\n if (action === \"unset\") {\n await deleteEnvSecret(env, key);\n console.log(`Deleted ${key} from ${env}.`);\n return 0;\n }\n if (action !== \"set\") fail(\"secrets actions: set | list | unset\");\n const value = str(flags, \"value\") ?? (await readStdin());\n if (!value)\n fail(\"empty value — nothing stored (pass --value or pipe stdin)\");\n const res = await setEnvSecret(env, key, value);\n console.log(\n `${res.created ? \"Added\" : \"Rotated\"} ${key} on ${env} — next hosted run receives it.`,\n );\n return 0;\n }\n case \"refs\": {\n const slug = positional[0] ?? fail(\"usage: gateway bench refs <slug>\");\n const res = await apiRequest<{\n refs: {\n name: string;\n kind: string;\n semanticVersion: string | null;\n contentHash: string | null;\n state: string | null;\n }[];\n }>(\n {},\n \"GET\",\n `/api/public/benchmark-containers/refs?slug=${encodeURIComponent(slug)}`,\n );\n for (const ref of res.refs) {\n console.log(\n `${ref.kind === \"tag\" ? \"tag \" : \"branch\"} ${ref.name} ${ref.semanticVersion ?? \"-\"} (${ref.contentHash?.slice(0, 12) ?? \"?\"}) ${ref.state ?? \"\"}`,\n );\n }\n return 0;\n }\n case \"log\": {\n const slug = positional[0] ?? fail(\"usage: gateway bench log <slug>\");\n const params = new URLSearchParams({ slug });\n const branch = str(flags, \"branch\");\n if (branch) params.set(\"branch\", branch);\n const limit = str(flags, \"limit\");\n if (limit) params.set(\"limit\", limit);\n const res = await apiRequest<{\n branch: string;\n entries: {\n versionId: string;\n contentHash: string;\n semanticVersion: string | null;\n state: string;\n author: string | null;\n changeReason: string | null;\n }[];\n }>(\n {},\n \"GET\",\n `/api/public/benchmark-containers/log?${params.toString()}`,\n );\n console.log(`branch: ${res.branch}`);\n for (const entry of res.entries) {\n console.log(\n `${entry.contentHash.slice(0, 12)} ${entry.semanticVersion ?? \"-\"} ${entry.state}` +\n `${entry.author ? ` by ${entry.author}` : \"\"}${entry.changeReason ? ` — ${entry.changeReason}` : \"\"}`,\n );\n }\n return 0;\n }\n case \"proposals\": {\n const slug =\n positional[0] ?? fail(\"usage: gateway bench proposals <slug>\");\n const params = new URLSearchParams({ slug });\n const status = str(flags, \"status\");\n if (status) params.set(\"status\", status);\n const res = await apiRequest<{\n proposals: {\n id: string;\n title?: string | null;\n status: string;\n createdAt?: string;\n }[];\n }>(\n {},\n \"GET\",\n `/api/public/benchmark-containers/proposals?${params.toString()}`,\n );\n if (res.proposals.length === 0) {\n console.log(\"No proposals.\");\n return 0;\n }\n for (const proposal of res.proposals) {\n console.log(\n `${proposal.id} [${proposal.status}] ${proposal.title ?? \"\"}`,\n );\n }\n return 0;\n }\n case \"pull\": {\n const slugRef =\n positional[0] ??\n fail(\"usage: gateway bench pull <slug[@ref]> [--dir D]\");\n const res = await pull(slugRef, str(flags, \"dir\"));\n console.log(\n `Pulled ${res.slug} -> ${res.dir} (${res.files} files, version ${res.versionId})`,\n );\n return 0;\n }\n case \"checkout\": {\n const slugRef =\n positional[0] ??\n fail(\"usage: gateway bench checkout <slug@ref> --dir D\");\n const dir =\n str(flags, \"dir\") ??\n fail(\"--dir is required for checkout (the working dir to re-aim)\");\n const res = await pull(slugRef, dir);\n console.log(\n `Checked out ${slugRef} into ${res.dir} (${res.files} files)`,\n );\n return 0;\n }\n case \"push\": {\n const dir = positional[0] ?? \".\";\n const res = await push(dir, {\n slug: str(flags, \"slug\"),\n branch: str(flags, \"branch\"),\n force: Boolean(flags.force),\n message: str(flags, \"message\"),\n author: str(flags, \"author\"),\n });\n console.log(\n `Pushed ${res.slug}@${res.branch}: version ${res.versionId} (${res.contentHash.slice(0, 12)})`,\n );\n return 0;\n }\n case \"status\": {\n const dir = positional[0] ?? \".\";\n const state = localTreeState(dir);\n if (!state.meta) {\n console.log(\n \"Ad-hoc dir: no pull/push base recorded (.gateway missing).\",\n );\n return 0;\n }\n console.log(\n `base: ${state.meta.slug}@${state.meta.branch ?? \"?\"} version ${state.meta.versionId ?? \"?\"}`,\n );\n const localHash = computeContentHash(dir);\n const baseHash = state.meta.contentHash;\n console.log(\n `content hash: ${localHash.slice(0, 12)} ${localHash === baseHash ? \"== base (hash-verified)\" : `!= base ${String(baseHash).slice(0, 12)}`}`,\n );\n if (state.clean) {\n console.log(\"clean — tree matches its base.\");\n return 0;\n }\n console.log(`dirty (${state.dirty.length}):`);\n for (const p of state.dirty.slice(0, 40)) console.log(` ${p}`);\n return 0;\n }\n case \"branch\":\n case \"tag\": {\n const slug =\n positional[0] ?? fail(`usage: gateway bench ${command} <slug> <name>`);\n const name =\n positional[1] ?? fail(`usage: gateway bench ${command} <slug> <name>`);\n const ref = await createRef(\n slug,\n name,\n command as \"branch\" | \"tag\",\n str(flags, \"version-id\"),\n );\n console.log(`${ref.kind} ${ref.name} -> ${ref.versionId}`);\n return 0;\n }\n case \"propose\": {\n const dir = positional[0] ?? \".\";\n const title = str(flags, \"title\") ?? fail(\"--title is required\");\n const reason = str(flags, \"reason\") ?? fail(\"--reason is required\");\n const res = await propose(dir, {\n title,\n reason,\n targetBranch: str(flags, \"target-branch\"),\n });\n console.log(`Proposal ${res.proposalId} opened.`);\n return 0;\n }\n default:\n fail(`Unknown command 'bench ${command}'.\\n\\n${HELP}`);\n }\n}\n\nmain().then(\n (code) => process.exit(code),\n (error) => {\n console.error(error instanceof Error ? error.message : String(error));\n process.exit(1);\n },\n);\n","import { createHash } from \"node:crypto\";\nimport { gzipSync, gunzipSync } from \"node:zlib\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\n\n/**\n * The working-dir half of the TS CLI: push / pull / checkout / status /\n * branch / tag / propose — a faithful port of the Python client\n * (`gatewaysdk/benchmark_hub/client.py` + `_archive.py`).\n *\n * LOCKSTEP WARNING — the content hash is the version's identity and is\n * byte-compatible with Prime Intellect. It now has FOUR implementations that\n * must stay identical: worker `environmentAgent/tar.ts`, web\n * `benchmark-hub/server/benchmarkContentHash.ts`, Python `_archive.py`, and\n * this file. This one is a line-for-line port of the WEB TypeScript\n * implementation (same language, same crypto) — if the rule ever changes,\n * change all four or push identity splits by client.\n *\n * One deliberate refusal, same policy as the web upload path: a bundle with\n * a ROOT `.gitignore` is refused rather than mis-hashed — the Python CLI\n * honors it via `gitignore_parser`, and an imperfect reimplementation here\n * would produce a wrong, Prime-incompatible hash silently.\n */\n\nexport const DEFAULT_BRANCH = \"main\";\nconst META_RELPATH = path.join(\".gateway\", \".env-metadata.json\");\nconst SKIP_DIRS = new Set([\n \".git\",\n \"__pycache__\",\n \"node_modules\",\n \".venv\",\n \".mypy_cache\",\n \"dist\",\n \"build\",\n \"outputs\",\n]);\nconst ROOT_EXCLUDED_DIRS = new Set([\"dist\", \"build\", \"outputs\", \"__pycache__\"]);\n\n// ── content-hash rules (port of web benchmarkContentHash.ts) ───────────────\n\nfunction isExcludedDirComponent(component: string): boolean {\n return (\n component.startsWith(\".\") ||\n ROOT_EXCLUDED_DIRS.has(component) ||\n component.endsWith(\".egg-info\")\n );\n}\n\nexport function isIncludedInContentHash(\n relPath: string,\n includeAllRootFiles: boolean,\n): boolean {\n const parts = relPath.split(\"/\");\n const name = parts[parts.length - 1];\n const dirParts = parts.slice(0, -1);\n if (name.startsWith(\".\")) return false;\n if (parts.includes(\"__pycache__\")) return false;\n if (dirParts.length === 0) {\n return (\n includeAllRootFiles ||\n name === \"README.md\" ||\n name === \"pyproject.toml\" ||\n name === \"gateway-env.toml\" ||\n name.endsWith(\".py\")\n );\n }\n return !dirParts.some(isExcludedDirComponent);\n}\n\n/** The archive-visible files of a working dir, as sorted relpaths. Throws on\n * a root .gitignore (see the header). */\nexport function collectArchiveRelPaths(dir: string): string[] {\n if (fs.existsSync(path.join(dir, \".gitignore\"))) {\n throw new Error(\n \"This bundle has a root .gitignore, which the Python CLI honors via \" +\n \"gitignore_parser. Reimplementing that imperfectly here would \" +\n \"silently produce a different content hash, so the TS CLI refuses. \" +\n \"Remove the .gitignore (or bake its effect into the tree) and retry.\",\n );\n }\n const out: string[] = [];\n const includeAllRootFiles = fs.existsSync(path.join(dir, \"gateway-env.toml\"));\n const walk = (rel: string) => {\n const abs = rel ? path.join(dir, rel) : dir;\n for (const entry of fs.readdirSync(abs, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {\n const childRel = rel ? `${rel}/${entry.name}` : entry.name;\n if (entry.isDirectory()) {\n if (!isExcludedDirComponent(entry.name)) walk(childRel);\n } else if (entry.isFile()) {\n if (isIncludedInContentHash(childRel, includeAllRootFiles)) {\n out.push(childRel);\n }\n }\n }\n };\n walk(\"\");\n return out.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));\n}\n\nexport function computeContentHash(dir: string): string {\n const hasher = createHash(\"sha256\");\n for (const relPath of collectArchiveRelPaths(dir)) {\n hasher.update(Buffer.from(`file:${relPath}`, \"utf-8\"));\n hasher.update(fs.readFileSync(path.join(dir, relPath)));\n }\n return hasher.digest(\"hex\");\n}\n\n// ── deterministic tar.gz writer ─────────────────────────────────────────────\n\nfunction octal(value: number, length: number): Buffer {\n return Buffer.from(value.toString(8).padStart(length - 1, \"0\") + \"\\0\", \"ascii\");\n}\n\nfunction tarHeader(name: string, size: number): Buffer {\n const header = Buffer.alloc(512);\n header.write(name, 0, 100, \"utf-8\");\n octal(0o644, 8).copy(header, 100); // mode\n octal(0, 8).copy(header, 108); // uid\n octal(0, 8).copy(header, 116); // gid\n octal(size, 12).copy(header, 124);\n octal(0, 12).copy(header, 136); // mtime = 0 (deterministic)\n header.write(\" \", 148, \"ascii\"); // checksum placeholder = spaces\n header.write(\"0\", 156, \"ascii\"); // regular file\n header.write(\"ustar\", 257, \"ascii\");\n header.write(\"00\", 263, \"ascii\");\n let sum = 0;\n for (const byte of header) sum += byte;\n header.write(sum.toString(8).padStart(6, \"0\") + \"\\0 \", 148, \"ascii\");\n return header;\n}\n\nfunction tarMember(name: string, payload: Buffer): Buffer[] {\n const parts: Buffer[] = [];\n const nameBytes = Buffer.byteLength(name, \"utf-8\");\n if (nameBytes > 100) {\n // GNU long name: an 'L' member whose body is the real name.\n const body = Buffer.from(name + \"\\0\", \"utf-8\");\n const lHeader = tarHeader(\"././@LongLink\", body.length);\n lHeader.write(\"L\", 156, \"ascii\");\n let sum = 0;\n lHeader.write(\" \", 148, \"ascii\");\n for (const byte of lHeader) sum += byte;\n lHeader.write(sum.toString(8).padStart(6, \"0\") + \"\\0 \", 148, \"ascii\");\n parts.push(lHeader, body);\n const pad = body.length % 512 === 0 ? 0 : 512 - (body.length % 512);\n if (pad) parts.push(Buffer.alloc(pad));\n parts.push(tarHeader(name.slice(0, 100), payload.length));\n } else {\n parts.push(tarHeader(name, payload.length));\n }\n parts.push(payload);\n const pad = payload.length % 512 === 0 ? 0 : 512 - (payload.length % 512);\n if (pad) parts.push(Buffer.alloc(pad));\n return parts;\n}\n\n/** A deterministic .tar.gz of the source files (node's gzip stamps no mtime,\n * matching the Python's mtime=0 gzip). */\nexport function buildSourceTarball(dir: string): Buffer {\n const parts: Buffer[] = [];\n for (const relPath of collectArchiveRelPaths(dir)) {\n parts.push(...tarMember(relPath, fs.readFileSync(path.join(dir, relPath))));\n }\n parts.push(Buffer.alloc(1024)); // end-of-archive\n return gzipSync(Buffer.concat(parts), { level: 9 });\n}\n\n// ── local metadata (.gateway/.env-metadata.json) ────────────────────────────\n\nexport type LocalMeta = Record<string, unknown> & {\n slug?: string;\n branch?: string;\n versionId?: string;\n contentHash?: string;\n baseFiles?: Record<string, string>;\n};\n\nexport function readLocalMeta(dir: string): LocalMeta | null {\n try {\n const raw = fs.readFileSync(path.join(dir, META_RELPATH), \"utf-8\");\n const parsed = JSON.parse(raw);\n return parsed && typeof parsed === \"object\" ? (parsed as LocalMeta) : null;\n } catch {\n return null;\n }\n}\n\nexport function writeLocalMeta(dir: string, meta: LocalMeta): void {\n fs.mkdirSync(path.join(dir, \".gateway\"), { recursive: true });\n fs.writeFileSync(path.join(dir, META_RELPATH), JSON.stringify(meta, null, 2));\n}\n\nexport function snapshotTreeHashes(dir: string): Record<string, string> {\n const out: Record<string, string> = {};\n for (const relPath of collectArchiveRelPaths(dir)) {\n out[relPath] = createHash(\"sha256\")\n .update(fs.readFileSync(path.join(dir, relPath)))\n .digest(\"hex\");\n }\n return out;\n}\n\nexport function localTreeState(dir: string): {\n meta: LocalMeta | null;\n dirty: string[];\n clean: boolean;\n} {\n const meta = readLocalMeta(dir);\n const base = meta?.baseFiles;\n if (!base || typeof base !== \"object\") {\n return { meta, dirty: [], clean: false };\n }\n const now = snapshotTreeHashes(dir);\n const dirty = new Set<string>();\n for (const [p, h] of Object.entries(now)) if (base[p] !== h) dirty.add(p);\n for (const p of Object.keys(base)) if (!(p in now)) dirty.add(p);\n return { meta, dirty: [...dirty].sort(), clean: dirty.size === 0 };\n}\n\n// ── protocol helpers ─────────────────────────────────────────────────────────\n\nconst sha256b64 = (data: Buffer) =>\n createHash(\"sha256\").update(data).digest(\"base64\");\n\nfunction readPyproject(dir: string): { name?: string; version?: string } {\n try {\n const text = fs.readFileSync(path.join(dir, \"pyproject.toml\"), \"utf-8\");\n // Minimal [project] reads — name and version only, quoted single-line form.\n const section = /\\[project\\]([\\s\\S]*?)(\\n\\[|$)/.exec(text)?.[1] ?? \"\";\n const name = /\\bname\\s*=\\s*\"([^\"]+)\"/.exec(section)?.[1];\n const version = /\\bversion\\s*=\\s*\"([^\"]+)\"/.exec(section)?.[1];\n return { name, version };\n } catch {\n return {};\n }\n}\n\nfunction buildFileManifest(\n dir: string,\n): { path: string; isDirectory: boolean; size: number; sha256: string }[] {\n const entries: { path: string; isDirectory: boolean; size: number; sha256: string }[] = [];\n const walk = (rel: string) => {\n const abs = rel ? path.join(dir, rel) : dir;\n for (const entry of fs.readdirSync(abs, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {\n const childRel = rel ? `${rel}/${entry.name}` : entry.name;\n if (entry.isDirectory()) {\n if (!SKIP_DIRS.has(entry.name) && !entry.name.endsWith(\".egg-info\")) {\n walk(childRel);\n }\n } else if (entry.isFile()) {\n const payload = fs.readFileSync(path.join(dir, childRel));\n entries.push({\n path: childRel,\n isDirectory: false,\n size: payload.length,\n sha256: createHash(\"sha256\").update(payload).digest(\"hex\"),\n });\n }\n }\n };\n walk(\"\");\n return entries;\n}\n\nasync function putObject(url: string, data: Buffer, shaB64: string): Promise<void> {\n const resp = await fetch(url, {\n method: \"PUT\",\n headers: {\n \"Content-Type\": \"application/gzip\",\n \"x-amz-checksum-sha256\": shaB64,\n },\n body: new Uint8Array(data),\n });\n if (!resp.ok) {\n throw new Error(`object PUT -> ${resp.status}: ${(await resp.text()).slice(0, 300)}`);\n }\n}\n\n// ── the workflows ────────────────────────────────────────────────────────────\n\nexport async function push(\n dir: string,\n opts: {\n slug?: string;\n branch?: string;\n force?: boolean;\n message?: string;\n author?: string;\n options?: WorldsClientOptions;\n } = {},\n): Promise<{ slug: string; versionId: string; contentHash: string; branch: string }> {\n const options = opts.options ?? {};\n if (!fs.statSync(dir).isDirectory()) throw new Error(`Not a directory: ${dir}`);\n const localMeta = readLocalMeta(dir) ?? {};\n const branch = opts.branch ?? (localMeta.branch as string | undefined) ?? DEFAULT_BRANCH;\n const baseVersionId = localMeta.versionId ?? null;\n\n const contentHash = computeContentHash(dir);\n const pyproject = readPyproject(dir);\n const slug = opts.slug ?? pyproject.name ?? path.basename(path.resolve(dir));\n\n const resolve = await apiRequest<{ containerId: string }>(\n options,\n \"POST\",\n \"/api/public/benchmark-containers/resolve\",\n { slug, name: pyproject.name ?? slug },\n );\n\n const tarball = buildSourceTarball(dir);\n const bundleSha256 = sha256b64(tarball);\n\n const version = await apiRequest<{\n versionId: string;\n uploadUrl?: string;\n }>(options, \"POST\", \"/api/public/benchmark-containers/versions\", {\n containerId: resolve.containerId,\n contentHash,\n bundleSha256,\n bundleSizeBytes: tarball.length,\n ...(pyproject.version ? { semanticVersion: pyproject.version } : {}),\n pyprojectMeta: pyproject,\n fileManifest: buildFileManifest(dir),\n branch,\n baseVersionId,\n ...(opts.force ? { force: true } : {}),\n ...(opts.message ? { changeReason: opts.message } : {}),\n ...(opts.author ? { author: opts.author } : {}),\n });\n\n if (version.uploadUrl) await putObject(version.uploadUrl, tarball, bundleSha256);\n\n await apiRequest(\n options,\n \"POST\",\n `/api/public/benchmark-containers/versions/${version.versionId}/finalize`,\n { branch, baseVersionId, ...(opts.force ? { force: true } : {}) },\n );\n\n writeLocalMeta(dir, {\n ...localMeta,\n slug,\n ref: branch,\n branch,\n versionId: version.versionId,\n contentHash,\n semanticVersion: pyproject.version,\n forkedFromVersionId: baseVersionId,\n baseFiles: snapshotTreeHashes(dir),\n });\n return { slug, versionId: version.versionId, contentHash, branch };\n}\n\n/** Extract a downloaded bundle into `dir` (paths sanitized). */\nfunction extractBundle(bundle: Buffer, dir: string): number {\n const tar = gunzipSync(bundle);\n let offset = 0;\n let longName: string | null = null;\n let written = 0;\n while (offset + 512 <= tar.length) {\n const header = tar.subarray(offset, offset + 512);\n offset += 512;\n if (header.every((b) => b === 0)) break;\n const rawName = header.subarray(0, 100).toString(\"utf-8\").replace(/\\0.*$/, \"\");\n const size = parseInt(header.subarray(124, 136).toString(\"ascii\").replace(/\\0.*$/, \"\").trim(), 8) || 0;\n const typeflag = header.subarray(156, 157).toString(\"ascii\");\n const body = tar.subarray(offset, offset + size);\n offset += size + (size % 512 === 0 ? 0 : 512 - (size % 512));\n if (typeflag === \"L\") {\n longName = body.toString(\"utf-8\").replace(/\\0.*$/, \"\");\n continue;\n }\n const name = (longName ?? rawName).replace(/^\\.\\//, \"\");\n longName = null;\n if (typeflag !== \"0\" && typeflag !== \"\") continue;\n // Safe extract: no absolute paths, no traversal.\n if (name.startsWith(\"/\") || name.split(\"/\").includes(\"..\")) continue;\n const target = path.join(dir, name);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n fs.writeFileSync(target, body);\n written++;\n }\n return written;\n}\n\nexport async function pull(\n slugRef: string,\n target?: string,\n options: WorldsClientOptions = {},\n): Promise<{ slug: string; dir: string; versionId: string; files: number }> {\n const at = slugRef.indexOf(\"@\");\n const slug = at === -1 ? slugRef : slugRef.slice(0, at);\n const ref = at === -1 ? \"latest\" : slugRef.slice(at + 1);\n\n const details = await apiRequest<{\n versionId: string;\n contentHash: string;\n semanticVersion?: string | null;\n downloadUrl?: string;\n bundleSha256?: string;\n }>(options, \"POST\", \"/api/public/benchmark-containers/resolve-version\", {\n slug,\n ref,\n });\n if (!details.downloadUrl) {\n throw new Error(`${slug}@${ref} resolved but has no uploaded bundle`);\n }\n\n let dir = target ?? path.join(process.cwd(), slug);\n if (!target) {\n let i = 1;\n const base = dir;\n while (fs.existsSync(dir)) dir = `${base}-${i++}`;\n }\n fs.mkdirSync(dir, { recursive: true });\n\n const resp = await fetch(details.downloadUrl);\n if (!resp.ok) throw new Error(`bundle download -> ${resp.status}`);\n const bundle = Buffer.from(await resp.arrayBuffer());\n if (details.bundleSha256 && sha256b64(bundle) !== details.bundleSha256) {\n throw new Error(\n `bundle integrity check failed for ${slug}@${ref}: downloaded sha256 != recorded bundleSha256`,\n );\n }\n\n const files = extractBundle(bundle, dir);\n const branch = ref === \"latest\" || /^\\d|^[0-9a-f]{8,}$/.test(ref) ? DEFAULT_BRANCH : ref;\n writeLocalMeta(dir, {\n slug,\n ref,\n branch,\n versionId: details.versionId,\n contentHash: details.contentHash,\n semanticVersion: details.semanticVersion ?? undefined,\n baseFiles: snapshotTreeHashes(dir),\n });\n return { slug, dir, versionId: details.versionId, files };\n}\n\nexport async function propose(\n dir: string,\n opts: { title: string; reason: string; targetBranch?: string; options?: WorldsClientOptions },\n): Promise<{ proposalId: string }> {\n const meta = readLocalMeta(dir);\n if (!meta?.slug || !meta.baseFiles) {\n throw new Error(\"This dir has no pull/push base — run pull first, then edit, then propose.\");\n }\n const state = localTreeState(dir);\n if (state.clean) throw new Error(\"Nothing to propose — the tree matches its base.\");\n const changes = state.dirty.map((relPath) => {\n const abs = path.join(dir, relPath);\n if (!fs.existsSync(abs)) return { path: relPath, action: \"delete\" as const };\n return {\n path: relPath,\n action: \"write\" as const,\n newContent: fs.readFileSync(abs, \"utf-8\"),\n };\n });\n const res = await apiRequest<{ proposalId: string }>(\n opts.options ?? {},\n \"POST\",\n \"/api/public/benchmark-containers/proposals\",\n {\n slug: meta.slug,\n title: opts.title,\n changeReason: opts.reason,\n baseVersionId: meta.versionId,\n ...(opts.targetBranch ? { targetBranch: opts.targetBranch } : {}),\n changes,\n },\n );\n return res;\n}\n\nexport async function createRef(\n slug: string,\n name: string,\n kind: \"branch\" | \"tag\",\n versionId?: string,\n options: WorldsClientOptions = {},\n): Promise<{ name: string; kind: string; versionId: string }> {\n return apiRequest(options, \"POST\", \"/api/public/benchmark-containers/refs\", {\n slug,\n name,\n kind,\n ...(versionId ? { versionId } : {}),\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA2FO,SAAS,oBAAoB,MAOlC;AACA,QAAM,SAAS,oBAAoB,KAAK,KAAK,UAAU,KAAK,CAAC,IAAI,CAAC,KAAK;AACvE,QAAM,aAAsC,CAAC;AAC7C,QAAM,WAAqB,CAAC;AAE5B,QAAM,SAAmB,CAAC;AAC1B,MAAI,QAAQ;AACZ,MAAI,UAAU;AACd,aAAW,MAAM,QAAQ;AACvB,QAAI,MAAM,SAAS,EAAE,EAAG;AACxB,QAAI,MAAM,SAAS,EAAE,EAAG;AACxB,QAAI,OAAO,OAAO,UAAU,GAAG;AAC7B,aAAO,KAAK,OAAO;AACnB,gBAAU;AAAA,IACZ,MAAO,YAAW;AAAA,EACpB;AACA,MAAI,QAAQ,KAAK,EAAG,QAAO,KAAK,OAAO;AAEvC,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AAClE,YAAM,MAAM,MAAM,QAAQ,KAAK;AAAA,QAC7B;AAAA,QACA;AAAA,QACA,cAAc,IAAI,OAAO,eAAe;AAAA,MAC1C,CAAC;AACD,cAAQ,IAAI,YAAY,IAAI,UAAU,UAAU;AAChD,aAAO;AAAA,IACT;AAAA,IACA;AACE,WAAK,0BAA0B,OAAO;AAAA;AAAA,EAAS,IAAI,EAAE;AAAA,EACzD;AACF;AAEA,KAAK,EAAE;AAAA,EACL,CAAC,SAAS,QAAQ,KAAK,IAAI;AAAA,EAC3B,CAAC,UAAU;AACT,YAAQ,MAAM,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AACpE,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF;","names":["openWorld","path","resolve","openSession","pad","resolve","row","id"]}
|
|
1
|
+
{"version":3,"sources":["../src/worlds/session.ts","../src/worlds/hub.ts","../src/worlds/validate.ts","../src/worlds/index.ts","../src/cli.ts"],"sourcesContent":["import { apiRequest, type WorldsClientOptions } from \"./index\";\n\n/**\n * LIVE WORLD SESSIONS from TypeScript: your agent, the platform's container.\n *\n * The other two ways of running a world each give up something. Pulling the\n * bundle and executing it locally tests your agent against a COPY — your\n * python, your sqlite, your machine's idea of the environment. Dispatching a\n * hosted run gives you the real container but runs the platform's agent\n * inside it, so your agent never touches the world.\n *\n * A session is both: the platform boots the task's container and holds it\n * warm, and every `call()` here executes inside THAT container. Your agent\n * stays where it is — this file is just the wire.\n *\n * const world = await openWorld(\"revenue-ops-sim@main\");\n * const session = await openSession(world.slug, \"revops-mara-dedupe-contacts\");\n * await session.ready(); // wait for the container\n * await session.call(\"crm_search\", { entity: \"deals\" });\n * const { reward, rewards } = await session.grade();\n * await session.close({ keepWarm: true }); // hand it back to the pool\n *\n * Every call is a row on the platform before it is an effect in a container,\n * so the episode is on the record — and the platform traces the session\n * itself, which is why these sessions show up under Sessions without the\n * caller instrumenting anything.\n */\n\nexport type WorldToolSpec = {\n name: string;\n /** The world's own signature, e.g. `crm_search(q=None, entity=\"deals\")`. */\n signature: string;\n doc: string | null;\n};\n\n/** What a model needs to call a world: the schemas to advertise, and the\n * implementations that run them in the container. */\nexport type WorldToolkit = {\n /** OpenAI-shaped tool definitions, derived from the world's signatures. */\n schemas: {\n type: \"function\";\n function: {\n name: string;\n description: string;\n parameters: Record<string, unknown>;\n };\n }[];\n /** name -> implementation, each one a call into THIS session. */\n impls: Record<string, (args: Record<string, unknown>) => Promise<unknown>>;\n specs: WorldToolSpec[];\n};\n\nexport type WorldSessionState = {\n sessionId: string;\n state: string;\n ready: boolean;\n versionId: string;\n contentHash: string;\n taskName: string | null;\n /** The task's objective — present when the session was opened (not on a\n * bare status read), so a client never needs the bundle on disk. */\n instruction?: string | null;\n /** The tools this task serves. */\n tools?: WorldToolSpec[];\n};\n\nexport type GradeResult = {\n reward: number | null;\n rewards: Record<string, number>;\n raw: unknown;\n};\n\n/** How long `ready()` waits, and how often it asks. */\nconst READY_TIMEOUT_MS = 10 * 60_000;\nconst READY_POLL_MS = 2_000;\n/** How long one call may take end to end (container claim + execution). */\nconst CALL_TIMEOUT_MS = 3 * 60_000;\nconst CALL_POLL_MS = 400;\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\n/**\n * Turn a world's Python signature into a JSON schema the model can call.\n *\n * `crm_update_deal(id, stage=None, owner=None, amount=None)` becomes an\n * object with `id` required and the rest optional. Types are read from the\n * DEFAULTS the world declares — a numeric default means a number, a boolean\n * default a boolean — because that is the only type information a signature\n * actually carries. Everything else is a string, which is what a tool CLI\n * receives anyway.\n */\nexport function schemaFromSignature(spec: WorldToolSpec): {\n type: \"function\";\n function: {\n name: string;\n description: string;\n parameters: Record<string, unknown>;\n };\n} {\n const inside = /\\(([\\s\\S]*)\\)\\s*$/.exec(spec.signature.trim())?.[1] ?? \"\";\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n // Split on top-level commas only: a default like `{\"a\": 1}` has its own.\n const params: string[] = [];\n let depth = 0;\n let current = \"\";\n for (const ch of inside) {\n if (\"([{\".includes(ch)) depth++;\n if (\")]}\".includes(ch)) depth--;\n if (ch === \",\" && depth === 0) {\n params.push(current);\n current = \"\";\n } else current += ch;\n }\n if (current.trim()) params.push(current);\n\n for (const raw of params) {\n const param = raw.trim();\n if (!param || param.startsWith(\"*\") || param === \"self\") continue;\n const eq = param.indexOf(\"=\");\n const name = (eq === -1 ? param : param.slice(0, eq)).split(\":\")[0].trim();\n if (!name) continue;\n if (eq === -1) {\n properties[name] = { type: \"string\" };\n required.push(name);\n continue;\n }\n const value = param.slice(eq + 1).trim();\n if (/^-?\\d+(\\.\\d+)?$/.test(value)) properties[name] = { type: \"number\" };\n else if (value === \"True\" || value === \"False\")\n properties[name] = { type: \"boolean\" };\n else properties[name] = { type: \"string\" };\n }\n return {\n type: \"function\",\n function: {\n name: spec.name,\n description: spec.doc ?? spec.name,\n parameters: { type: \"object\", properties, required },\n },\n };\n}\n\nexport class WorldSessionTimeout extends Error {}\nexport class WorldSessionCallError extends Error {}\n\nexport class WorldSession {\n constructor(\n readonly sessionId: string,\n private state: WorldSessionState,\n private readonly options: WorldsClientOptions,\n ) {}\n\n get task(): string | null {\n return this.state.taskName;\n }\n\n /** What this task asks for — the bundle's own instruction.md. */\n get instruction(): string | null {\n return this.state.instruction ?? null;\n }\n\n get versionId(): string {\n return this.state.versionId;\n }\n\n /** The session's latest platform state (one request, no waiting). */\n async status(): Promise<WorldSessionState> {\n const fresh = await apiRequest<WorldSessionState>(\n this.options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}`,\n );\n // A status read does not carry the objective; keep the one we opened with.\n this.state = {\n instruction: this.state.instruction,\n tools: this.state.tools,\n ...fresh,\n };\n return this.state;\n }\n\n /**\n * Wait until the container is warm — meaning the process inside it has\n * asked the platform for work, not merely that a job was accepted.\n */\n async ready(opts: { timeoutMs?: number } = {}): Promise<WorldSessionState> {\n const deadline = Date.now() + (opts.timeoutMs ?? READY_TIMEOUT_MS);\n for (;;) {\n const state = await this.status();\n if (state.ready) return state;\n if (state.state === \"FAILED\" || state.state === \"STOPPED\")\n throw new WorldSessionCallError(\n `World session ${state.state.toLowerCase()} before it was ready.`,\n );\n if (Date.now() > deadline)\n throw new WorldSessionTimeout(\n `World session still ${state.state} after ${Math.round((opts.timeoutMs ?? READY_TIMEOUT_MS) / 1000)}s.`,\n );\n await sleep(READY_POLL_MS);\n }\n }\n\n /** Enqueue one interaction and wait for the container's answer. */\n private async exchange(\n body: { kind?: \"call\" | \"grade\" | \"close\"; tool?: string; args?: unknown },\n timeoutMs = CALL_TIMEOUT_MS,\n ): Promise<unknown> {\n const { callId } = await apiRequest<{ callId: string; seq: number }>(\n this.options,\n \"POST\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/calls`,\n body,\n );\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n const call = await apiRequest<{\n done: boolean;\n state: string;\n result: unknown;\n error: string | null;\n }>(\n this.options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/calls/${encodeURIComponent(callId)}`,\n );\n if (call.done) {\n if (call.error) throw new WorldSessionCallError(call.error);\n return call.result;\n }\n if (Date.now() > deadline)\n throw new WorldSessionTimeout(\n `Call ${callId} still ${call.state} after ${Math.round(timeoutMs / 1000)}s — the container may have died.`,\n );\n await sleep(CALL_POLL_MS);\n }\n }\n\n /**\n * Run one of the world's tools INSIDE the container. The arguments and the\n * result are the world's own contract — this layer neither validates nor\n * reshapes them, so a tool error reads exactly as it would in a hosted run.\n */\n async call(\n tool: string,\n args: Record<string, unknown> = {},\n opts: { timeoutMs?: number } = {},\n ): Promise<unknown> {\n return this.exchange({ kind: \"call\", tool, args }, opts.timeoutMs);\n }\n\n /**\n * THE WORLD'S TOOLS, READY TO HAND TO A MODEL. Schemas come from the\n * world's own signatures and implementations call into this session, so a\n * caller never writes — and never has to re-sync — a tool map of their own:\n *\n * const { schemas, impls } = await session.toolkit();\n * await runMyAgent(impls, schemas, session.instruction);\n *\n * A tool added to the world shows up here on the next run; a tool renamed\n * in the world renames here too, instead of failing at call time against a\n * hand-written map that still remembers the old name.\n */\n async toolkit(): Promise<WorldToolkit> {\n let specs = this.state.tools;\n if (!specs) specs = (await this.status()).tools ?? [];\n const impls: WorldToolkit[\"impls\"] = {};\n for (const spec of specs) {\n impls[spec.name] = (args: Record<string, unknown> = {}) =>\n this.call(spec.name, args);\n }\n return { schemas: specs.map(schemaFromSignature), impls, specs };\n }\n\n /** Run the task's grader against the container's END STATE. */\n async grade(opts: { timeoutMs?: number } = {}): Promise<GradeResult> {\n const raw = (await this.exchange(\n { kind: \"grade\" },\n opts.timeoutMs,\n )) as Record<string, unknown> | null;\n const record = raw && typeof raw === \"object\" ? raw : {};\n const rewards: Record<string, number> = {};\n for (const [key, value] of Object.entries(record)) {\n if (key !== \"reward\" && typeof value === \"number\") rewards[key] = value;\n }\n return {\n reward: typeof record.reward === \"number\" ? record.reward : null,\n rewards,\n raw,\n };\n }\n\n /**\n * End the session. `keepWarm` hands the container back to the pool instead\n * of tearing it down, so the next session for the same task starts warm —\n * the pooled instance still obeys the fleet's idle TTL and pinning.\n */\n async close(opts: { keepWarm?: boolean } = {}): Promise<{ state: string }> {\n return apiRequest(\n this.options,\n \"DELETE\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}`,\n { keepWarm: opts.keepWarm ?? false },\n );\n }\n}\n\n/**\n * Attach to a session that already exists — resuming after a crash, or\n * driving a session someone else opened (a container started by hand on a\n * self-hosted install, a session opened by CI and handed to a developer).\n */\nexport async function attachSession(\n sessionId: string,\n options: WorldsClientOptions = {},\n): Promise<WorldSession> {\n const state = await apiRequest<WorldSessionState>(\n options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(sessionId)}`,\n );\n return new WorldSession(sessionId, state, options);\n}\n\n/**\n * Open a live session against one task of a world. Returns as soon as the\n * platform has accepted it — call `ready()` to wait for the container.\n */\nexport async function openSession(\n slugOrRef: string,\n task: string,\n opts: {\n versionId?: string;\n reuseWarm?: boolean;\n options?: WorldsClientOptions;\n } = {},\n): Promise<WorldSession> {\n const options = opts.options ?? {};\n const at = slugOrRef.indexOf(\"@\");\n const slug = at === -1 ? slugOrRef : slugOrRef.slice(0, at);\n const state = await apiRequest<WorldSessionState & { reusedWarm: boolean }>(\n options,\n \"POST\",\n \"/api/public/world-sessions\",\n {\n ...(opts.versionId ? { versionId: opts.versionId } : { slug }),\n task,\n ...(opts.reuseWarm === undefined ? {} : { reuseWarm: opts.reuseWarm }),\n },\n );\n return new WorldSession(state.sessionId, state, options);\n}\n\n// ── running many tasks at once ───────────────────────────────────────────────\n\nexport type SessionRunResult = {\n task: string;\n sessionId: string;\n reward: number | null;\n rewards: Record<string, number>;\n /** Set when the task threw instead of grading. */\n error?: string;\n};\n\nexport type SessionRunReport = {\n results: SessionRunResult[];\n /** Mean reward over every task, counting failures as 0. */\n mean: number;\n /** True when `mean >= failUnder` (or no gate was set). */\n passed: boolean;\n};\n\n/**\n * RUN MANY TASKS IN PARALLEL, one warm container each.\n *\n * Parallelism against live worlds is the normal case — a suite is a dozen\n * tasks and each needs its own container, because two agents sharing one\n * world state would corrupt both episodes. Every caller was writing the same\n * pool, the same per-task open/ready/toolkit/grade/close, and the same\n * \"don't let one failure kill the run\" logic, so it belongs here:\n *\n * const report = await runSessions({\n * world: \"revenue-ops-sim@main\",\n * tasks, // default: every task in the world\n * concurrency: 4,\n * failUnder: 0.7,\n * agent: async ({ toolkit, instruction }) =>\n * myAgent(toolkit.impls, toolkit.schemas, instruction),\n * });\n *\n * The handler gets a ready session with its toolkit already bound; grading,\n * closing (warm) and aggregation are handled. A task that throws scores 0\n * and records why — the tasks that passed keep their results.\n */\nexport async function runSessions(opts: {\n world: string;\n tasks?: string[];\n concurrency?: number;\n failUnder?: number;\n /** Pin every session to one version (default: the world's head). */\n versionId?: string;\n /** Hand the containers back warm for the next run (default: true). */\n keepWarm?: boolean;\n agent: (ctx: {\n session: WorldSession;\n toolkit: WorldToolkit;\n instruction: string;\n task: string;\n }) => Promise<unknown>;\n onResult?: (result: SessionRunResult) => void;\n options?: WorldsClientOptions;\n}): Promise<SessionRunReport> {\n const options = opts.options ?? {};\n const concurrency = Math.max(1, opts.concurrency ?? 3);\n\n let tasks = opts.tasks;\n let versionId = opts.versionId;\n if (!tasks || !versionId) {\n // One resolve for the whole run: every session pins the SAME version, so\n // a push mid-suite cannot split the results across two worlds.\n const { openWorld } = await import(\"./index\");\n const world = await openWorld(opts.world, options);\n tasks = tasks ?? world.tasks.map((t) => t.name);\n versionId = versionId ?? world.version.versionId;\n }\n\n const results: SessionRunResult[] = [];\n let next = 0;\n await Promise.all(\n Array.from({ length: Math.min(concurrency, tasks.length) }, async () => {\n while (next < tasks!.length) {\n const task = tasks![next++];\n let session: WorldSession | null = null;\n try {\n session = await openSession(opts.world, task, {\n versionId,\n options,\n });\n await session.ready();\n const toolkit = await session.toolkit();\n await opts.agent({\n session,\n toolkit,\n instruction: session.instruction ?? task,\n task,\n });\n const graded = await session.grade();\n const result: SessionRunResult = {\n task,\n sessionId: session.sessionId,\n reward: graded.reward,\n rewards: graded.rewards,\n };\n results.push(result);\n opts.onResult?.(result);\n } catch (error) {\n const result: SessionRunResult = {\n task,\n sessionId: session?.sessionId ?? \"\",\n reward: 0,\n rewards: {},\n // An Error with an empty message would read as \"no error\" to any\n // caller checking truthiness; name the type instead.\n error:\n (error instanceof Error ? error.message : String(error)) ||\n (error instanceof Error ? error.name : \"Unknown error\"),\n };\n results.push(result);\n opts.onResult?.(result);\n } finally {\n // Always give the container back — a leaked session bills until the\n // fleet's idle TTL reaps it.\n await session\n ?.close({ keepWarm: opts.keepWarm ?? true })\n .catch(() => undefined);\n }\n }\n }),\n );\n\n const mean =\n results.reduce((sum, r) => sum + (r.reward ?? 0), 0) /\n (results.length || 1);\n return {\n results: results.sort((a, b) => a.task.localeCompare(b.task)),\n mean,\n passed: opts.failUnder === undefined ? true : mean >= opts.failUnder,\n };\n}\n","import { createHash } from \"node:crypto\";\nimport { gzipSync, gunzipSync } from \"node:zlib\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\n\n/**\n * The working-dir half of the TS CLI: push / pull / checkout / status /\n * branch / tag / propose — a faithful port of the Python client\n * (`gatewaysdk/benchmark_hub/client.py` + `_archive.py`).\n *\n * LOCKSTEP WARNING — the content hash is the version's identity and is\n * byte-compatible with Prime Intellect. It now has FOUR implementations that\n * must stay identical: worker `environmentAgent/tar.ts`, web\n * `benchmark-hub/server/benchmarkContentHash.ts`, Python `_archive.py`, and\n * this file. This one is a line-for-line port of the WEB TypeScript\n * implementation (same language, same crypto) — if the rule ever changes,\n * change all four or push identity splits by client.\n *\n * One deliberate refusal, same policy as the web upload path: a bundle with\n * a ROOT `.gitignore` is refused rather than mis-hashed — the Python CLI\n * honors it via `gitignore_parser`, and an imperfect reimplementation here\n * would produce a wrong, Prime-incompatible hash silently.\n */\n\nexport const DEFAULT_BRANCH = \"main\";\nconst META_RELPATH = path.join(\".gateway\", \".env-metadata.json\");\nconst SKIP_DIRS = new Set([\n \".git\",\n \"__pycache__\",\n \"node_modules\",\n \".venv\",\n \".mypy_cache\",\n \"dist\",\n \"build\",\n \"outputs\",\n]);\nconst ROOT_EXCLUDED_DIRS = new Set([\"dist\", \"build\", \"outputs\", \"__pycache__\"]);\n\n// ── content-hash rules (port of web benchmarkContentHash.ts) ───────────────\n\nfunction isExcludedDirComponent(component: string): boolean {\n return (\n component.startsWith(\".\") ||\n ROOT_EXCLUDED_DIRS.has(component) ||\n component.endsWith(\".egg-info\")\n );\n}\n\nexport function isIncludedInContentHash(\n relPath: string,\n includeAllRootFiles: boolean,\n): boolean {\n const parts = relPath.split(\"/\");\n const name = parts[parts.length - 1];\n const dirParts = parts.slice(0, -1);\n if (name.startsWith(\".\")) return false;\n if (parts.includes(\"__pycache__\")) return false;\n if (dirParts.length === 0) {\n return (\n includeAllRootFiles ||\n name === \"README.md\" ||\n name === \"pyproject.toml\" ||\n name === \"gateway-env.toml\" ||\n name.endsWith(\".py\")\n );\n }\n return !dirParts.some(isExcludedDirComponent);\n}\n\n/** The archive-visible files of a working dir, as sorted relpaths. Throws on\n * a root .gitignore (see the header). */\nexport function collectArchiveRelPaths(dir: string): string[] {\n if (fs.existsSync(path.join(dir, \".gitignore\"))) {\n throw new Error(\n \"This bundle has a root .gitignore, which the Python CLI honors via \" +\n \"gitignore_parser. Reimplementing that imperfectly here would \" +\n \"silently produce a different content hash, so the TS CLI refuses. \" +\n \"Remove the .gitignore (or bake its effect into the tree) and retry.\",\n );\n }\n const out: string[] = [];\n const includeAllRootFiles = fs.existsSync(path.join(dir, \"gateway-env.toml\"));\n const walk = (rel: string) => {\n const abs = rel ? path.join(dir, rel) : dir;\n for (const entry of fs.readdirSync(abs, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {\n const childRel = rel ? `${rel}/${entry.name}` : entry.name;\n if (entry.isDirectory()) {\n if (!isExcludedDirComponent(entry.name)) walk(childRel);\n } else if (entry.isFile()) {\n if (isIncludedInContentHash(childRel, includeAllRootFiles)) {\n out.push(childRel);\n }\n }\n }\n };\n walk(\"\");\n return out.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));\n}\n\nexport function computeContentHash(dir: string): string {\n const hasher = createHash(\"sha256\");\n for (const relPath of collectArchiveRelPaths(dir)) {\n hasher.update(Buffer.from(`file:${relPath}`, \"utf-8\"));\n hasher.update(fs.readFileSync(path.join(dir, relPath)));\n }\n return hasher.digest(\"hex\");\n}\n\n// ── deterministic tar.gz writer ─────────────────────────────────────────────\n\nfunction octal(value: number, length: number): Buffer {\n return Buffer.from(value.toString(8).padStart(length - 1, \"0\") + \"\\0\", \"ascii\");\n}\n\nfunction tarHeader(name: string, size: number): Buffer {\n const header = Buffer.alloc(512);\n header.write(name, 0, 100, \"utf-8\");\n octal(0o644, 8).copy(header, 100); // mode\n octal(0, 8).copy(header, 108); // uid\n octal(0, 8).copy(header, 116); // gid\n octal(size, 12).copy(header, 124);\n octal(0, 12).copy(header, 136); // mtime = 0 (deterministic)\n header.write(\" \", 148, \"ascii\"); // checksum placeholder = spaces\n header.write(\"0\", 156, \"ascii\"); // regular file\n header.write(\"ustar\", 257, \"ascii\");\n header.write(\"00\", 263, \"ascii\");\n let sum = 0;\n for (const byte of header) sum += byte;\n header.write(sum.toString(8).padStart(6, \"0\") + \"\\0 \", 148, \"ascii\");\n return header;\n}\n\nfunction tarMember(name: string, payload: Buffer): Buffer[] {\n const parts: Buffer[] = [];\n const nameBytes = Buffer.byteLength(name, \"utf-8\");\n if (nameBytes > 100) {\n // GNU long name: an 'L' member whose body is the real name.\n const body = Buffer.from(name + \"\\0\", \"utf-8\");\n const lHeader = tarHeader(\"././@LongLink\", body.length);\n lHeader.write(\"L\", 156, \"ascii\");\n let sum = 0;\n lHeader.write(\" \", 148, \"ascii\");\n for (const byte of lHeader) sum += byte;\n lHeader.write(sum.toString(8).padStart(6, \"0\") + \"\\0 \", 148, \"ascii\");\n parts.push(lHeader, body);\n const pad = body.length % 512 === 0 ? 0 : 512 - (body.length % 512);\n if (pad) parts.push(Buffer.alloc(pad));\n parts.push(tarHeader(name.slice(0, 100), payload.length));\n } else {\n parts.push(tarHeader(name, payload.length));\n }\n parts.push(payload);\n const pad = payload.length % 512 === 0 ? 0 : 512 - (payload.length % 512);\n if (pad) parts.push(Buffer.alloc(pad));\n return parts;\n}\n\n/** A deterministic .tar.gz of the source files (node's gzip stamps no mtime,\n * matching the Python's mtime=0 gzip). */\nexport function buildSourceTarball(dir: string): Buffer {\n const parts: Buffer[] = [];\n for (const relPath of collectArchiveRelPaths(dir)) {\n parts.push(...tarMember(relPath, fs.readFileSync(path.join(dir, relPath))));\n }\n parts.push(Buffer.alloc(1024)); // end-of-archive\n return gzipSync(Buffer.concat(parts), { level: 9 });\n}\n\n// ── local metadata (.gateway/.env-metadata.json) ────────────────────────────\n\nexport type LocalMeta = Record<string, unknown> & {\n slug?: string;\n branch?: string;\n versionId?: string;\n contentHash?: string;\n baseFiles?: Record<string, string>;\n};\n\nexport function readLocalMeta(dir: string): LocalMeta | null {\n try {\n const raw = fs.readFileSync(path.join(dir, META_RELPATH), \"utf-8\");\n const parsed = JSON.parse(raw);\n return parsed && typeof parsed === \"object\" ? (parsed as LocalMeta) : null;\n } catch {\n return null;\n }\n}\n\nexport function writeLocalMeta(dir: string, meta: LocalMeta): void {\n fs.mkdirSync(path.join(dir, \".gateway\"), { recursive: true });\n fs.writeFileSync(path.join(dir, META_RELPATH), JSON.stringify(meta, null, 2));\n}\n\nexport function snapshotTreeHashes(dir: string): Record<string, string> {\n const out: Record<string, string> = {};\n for (const relPath of collectArchiveRelPaths(dir)) {\n out[relPath] = createHash(\"sha256\")\n .update(fs.readFileSync(path.join(dir, relPath)))\n .digest(\"hex\");\n }\n return out;\n}\n\nexport function localTreeState(dir: string): {\n meta: LocalMeta | null;\n dirty: string[];\n clean: boolean;\n} {\n const meta = readLocalMeta(dir);\n const base = meta?.baseFiles;\n if (!base || typeof base !== \"object\") {\n return { meta, dirty: [], clean: false };\n }\n const now = snapshotTreeHashes(dir);\n const dirty = new Set<string>();\n for (const [p, h] of Object.entries(now)) if (base[p] !== h) dirty.add(p);\n for (const p of Object.keys(base)) if (!(p in now)) dirty.add(p);\n return { meta, dirty: [...dirty].sort(), clean: dirty.size === 0 };\n}\n\n// ── protocol helpers ─────────────────────────────────────────────────────────\n\nconst sha256b64 = (data: Buffer) =>\n createHash(\"sha256\").update(data).digest(\"base64\");\n\nfunction readPyproject(dir: string): { name?: string; version?: string } {\n try {\n const text = fs.readFileSync(path.join(dir, \"pyproject.toml\"), \"utf-8\");\n // Minimal [project] reads — name and version only, quoted single-line form.\n const section = /\\[project\\]([\\s\\S]*?)(\\n\\[|$)/.exec(text)?.[1] ?? \"\";\n const name = /\\bname\\s*=\\s*\"([^\"]+)\"/.exec(section)?.[1];\n const version = /\\bversion\\s*=\\s*\"([^\"]+)\"/.exec(section)?.[1];\n return { name, version };\n } catch {\n return {};\n }\n}\n\nfunction buildFileManifest(\n dir: string,\n): { path: string; isDirectory: boolean; size: number; sha256: string }[] {\n const entries: { path: string; isDirectory: boolean; size: number; sha256: string }[] = [];\n const walk = (rel: string) => {\n const abs = rel ? path.join(dir, rel) : dir;\n for (const entry of fs.readdirSync(abs, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {\n const childRel = rel ? `${rel}/${entry.name}` : entry.name;\n if (entry.isDirectory()) {\n if (!SKIP_DIRS.has(entry.name) && !entry.name.endsWith(\".egg-info\")) {\n walk(childRel);\n }\n } else if (entry.isFile()) {\n const payload = fs.readFileSync(path.join(dir, childRel));\n entries.push({\n path: childRel,\n isDirectory: false,\n size: payload.length,\n sha256: createHash(\"sha256\").update(payload).digest(\"hex\"),\n });\n }\n }\n };\n walk(\"\");\n return entries;\n}\n\nasync function putObject(url: string, data: Buffer, shaB64: string): Promise<void> {\n const resp = await fetch(url, {\n method: \"PUT\",\n headers: {\n \"Content-Type\": \"application/gzip\",\n \"x-amz-checksum-sha256\": shaB64,\n },\n body: new Uint8Array(data),\n });\n if (!resp.ok) {\n throw new Error(`object PUT -> ${resp.status}: ${(await resp.text()).slice(0, 300)}`);\n }\n}\n\n// ── the workflows ────────────────────────────────────────────────────────────\n\nexport async function push(\n dir: string,\n opts: {\n slug?: string;\n branch?: string;\n force?: boolean;\n message?: string;\n author?: string;\n options?: WorldsClientOptions;\n } = {},\n): Promise<{ slug: string; versionId: string; contentHash: string; branch: string }> {\n const options = opts.options ?? {};\n if (!fs.statSync(dir).isDirectory()) throw new Error(`Not a directory: ${dir}`);\n const localMeta = readLocalMeta(dir) ?? {};\n const branch = opts.branch ?? (localMeta.branch as string | undefined) ?? DEFAULT_BRANCH;\n const baseVersionId = localMeta.versionId ?? null;\n\n const contentHash = computeContentHash(dir);\n const pyproject = readPyproject(dir);\n const slug = opts.slug ?? pyproject.name ?? path.basename(path.resolve(dir));\n\n const resolve = await apiRequest<{ containerId: string }>(\n options,\n \"POST\",\n \"/api/public/benchmark-containers/resolve\",\n { slug, name: pyproject.name ?? slug },\n );\n\n const tarball = buildSourceTarball(dir);\n const bundleSha256 = sha256b64(tarball);\n\n const version = await apiRequest<{\n versionId: string;\n uploadUrl?: string;\n }>(options, \"POST\", \"/api/public/benchmark-containers/versions\", {\n containerId: resolve.containerId,\n contentHash,\n bundleSha256,\n bundleSizeBytes: tarball.length,\n ...(pyproject.version ? { semanticVersion: pyproject.version } : {}),\n pyprojectMeta: pyproject,\n fileManifest: buildFileManifest(dir),\n branch,\n baseVersionId,\n ...(opts.force ? { force: true } : {}),\n ...(opts.message ? { changeReason: opts.message } : {}),\n ...(opts.author ? { author: opts.author } : {}),\n });\n\n if (version.uploadUrl) await putObject(version.uploadUrl, tarball, bundleSha256);\n\n await apiRequest(\n options,\n \"POST\",\n `/api/public/benchmark-containers/versions/${version.versionId}/finalize`,\n { branch, baseVersionId, ...(opts.force ? { force: true } : {}) },\n );\n\n writeLocalMeta(dir, {\n ...localMeta,\n slug,\n ref: branch,\n branch,\n versionId: version.versionId,\n contentHash,\n semanticVersion: pyproject.version,\n forkedFromVersionId: baseVersionId,\n baseFiles: snapshotTreeHashes(dir),\n });\n return { slug, versionId: version.versionId, contentHash, branch };\n}\n\n/** Extract a downloaded bundle into `dir` (paths sanitized). */\nfunction extractBundle(bundle: Buffer, dir: string): number {\n const tar = gunzipSync(bundle);\n let offset = 0;\n let longName: string | null = null;\n let written = 0;\n while (offset + 512 <= tar.length) {\n const header = tar.subarray(offset, offset + 512);\n offset += 512;\n if (header.every((b) => b === 0)) break;\n const rawName = header.subarray(0, 100).toString(\"utf-8\").replace(/\\0.*$/, \"\");\n const size = parseInt(header.subarray(124, 136).toString(\"ascii\").replace(/\\0.*$/, \"\").trim(), 8) || 0;\n const typeflag = header.subarray(156, 157).toString(\"ascii\");\n const body = tar.subarray(offset, offset + size);\n offset += size + (size % 512 === 0 ? 0 : 512 - (size % 512));\n if (typeflag === \"L\") {\n longName = body.toString(\"utf-8\").replace(/\\0.*$/, \"\");\n continue;\n }\n const name = (longName ?? rawName).replace(/^\\.\\//, \"\");\n longName = null;\n if (typeflag !== \"0\" && typeflag !== \"\") continue;\n // Safe extract: no absolute paths, no traversal.\n if (name.startsWith(\"/\") || name.split(\"/\").includes(\"..\")) continue;\n const target = path.join(dir, name);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n fs.writeFileSync(target, body);\n written++;\n }\n return written;\n}\n\nexport async function pull(\n slugRef: string,\n target?: string,\n options: WorldsClientOptions = {},\n): Promise<{ slug: string; dir: string; versionId: string; files: number }> {\n const at = slugRef.indexOf(\"@\");\n const slug = at === -1 ? slugRef : slugRef.slice(0, at);\n const ref = at === -1 ? \"latest\" : slugRef.slice(at + 1);\n\n const details = await apiRequest<{\n versionId: string;\n contentHash: string;\n semanticVersion?: string | null;\n downloadUrl?: string;\n bundleSha256?: string;\n }>(options, \"POST\", \"/api/public/benchmark-containers/resolve-version\", {\n slug,\n ref,\n });\n if (!details.downloadUrl) {\n throw new Error(`${slug}@${ref} resolved but has no uploaded bundle`);\n }\n\n let dir = target ?? path.join(process.cwd(), slug);\n if (!target) {\n let i = 1;\n const base = dir;\n while (fs.existsSync(dir)) dir = `${base}-${i++}`;\n }\n fs.mkdirSync(dir, { recursive: true });\n\n const resp = await fetch(details.downloadUrl);\n if (!resp.ok) throw new Error(`bundle download -> ${resp.status}`);\n const bundle = Buffer.from(await resp.arrayBuffer());\n if (details.bundleSha256 && sha256b64(bundle) !== details.bundleSha256) {\n throw new Error(\n `bundle integrity check failed for ${slug}@${ref}: downloaded sha256 != recorded bundleSha256`,\n );\n }\n\n const files = extractBundle(bundle, dir);\n const branch = ref === \"latest\" || /^\\d|^[0-9a-f]{8,}$/.test(ref) ? DEFAULT_BRANCH : ref;\n writeLocalMeta(dir, {\n slug,\n ref,\n branch,\n versionId: details.versionId,\n contentHash: details.contentHash,\n semanticVersion: details.semanticVersion ?? undefined,\n baseFiles: snapshotTreeHashes(dir),\n });\n return { slug, dir, versionId: details.versionId, files };\n}\n\nexport async function propose(\n dir: string,\n opts: { title: string; reason: string; targetBranch?: string; options?: WorldsClientOptions },\n): Promise<{ proposalId: string }> {\n const meta = readLocalMeta(dir);\n if (!meta?.slug || !meta.baseFiles) {\n throw new Error(\"This dir has no pull/push base — run pull first, then edit, then propose.\");\n }\n const state = localTreeState(dir);\n if (state.clean) throw new Error(\"Nothing to propose — the tree matches its base.\");\n const changes = state.dirty.map((relPath) => {\n const abs = path.join(dir, relPath);\n if (!fs.existsSync(abs)) return { path: relPath, action: \"delete\" as const };\n return {\n path: relPath,\n action: \"write\" as const,\n newContent: fs.readFileSync(abs, \"utf-8\"),\n };\n });\n const res = await apiRequest<{ proposalId: string }>(\n opts.options ?? {},\n \"POST\",\n \"/api/public/benchmark-containers/proposals\",\n {\n slug: meta.slug,\n title: opts.title,\n changeReason: opts.reason,\n baseVersionId: meta.versionId,\n ...(opts.targetBranch ? { targetBranch: opts.targetBranch } : {}),\n changes,\n },\n );\n return res;\n}\n\nexport async function createRef(\n slug: string,\n name: string,\n kind: \"branch\" | \"tag\",\n versionId?: string,\n options: WorldsClientOptions = {},\n): Promise<{ name: string; kind: string; versionId: string }> {\n return apiRequest(options, \"POST\", \"/api/public/benchmark-containers/refs\", {\n slug,\n name,\n kind,\n ...(versionId ? { versionId } : {}),\n });\n}\n","/**\n * PR validation: push the checkout's world source, run it, gate on the graded\n * result — one composed call, because CI should not have to re-derive the\n * choreography from primitives.\n *\n * The differentiating property, stated so it stays true: validation runs the\n * PULL REQUEST'S OWN world source. The push files the checkout as a version on\n * the PR's branch (content-hash dedup makes re-runs cheap), the dispatch pins\n * that version, and the platform resolves the branch back to its open PR — so\n * the run page names the PR and the PR comment names the run. Nothing here\n * validates a standing deployment while pretending to validate the change.\n */\n\nimport {\n apiRequest,\n detectProvenance,\n listRunConfigs,\n waitForRun,\n type RunReport,\n type WorldsClientOptions,\n} from \"./index\";\nimport { push } from \"./hub\";\n\nexport type ValidatedRun = {\n model: string;\n runId: string;\n report: RunReport | null;\n /** Why this run fails the gate, or null when it passes. */\n failure: string | null;\n};\n\nexport type ValidateReport = {\n ok: boolean;\n slug: string;\n branch: string;\n versionId: string;\n contentHash: string;\n runConfig: { id: string; name: string };\n runs: ValidatedRun[];\n /** A PR-comment-ready summary of the whole validation. */\n markdown: string;\n};\n\nfunction fmtScore(score: number | null): string {\n return score === null ? \"no score\" : score.toFixed(3);\n}\n\nfunction buildMarkdown(\n report: Omit<ValidateReport, \"markdown\">,\n minScore: number | null,\n): string {\n const lines: string[] = [];\n lines.push(\n `### World validation ${report.ok ? \"passed\" : \"failed\"} — \\`${report.slug}@${report.branch}\\``,\n );\n lines.push(\"\");\n lines.push(\n `Ran the pull request's own world source (version \\`${report.contentHash.slice(0, 12)}\\`) ` +\n `through run config **${report.runConfig.name}**` +\n (minScore !== null ? `, gating at score ≥ ${minScore}.` : \".\"),\n );\n lines.push(\"\");\n lines.push(\"| Model | Status | Score | Run |\");\n lines.push(\"| --- | --- | ---: | --- |\");\n for (const run of report.runs) {\n const r = run.report;\n const link = r?.url ? `[open](${r.url})` : \"—\";\n const status = run.failure\n ? `❌ ${run.failure}`\n : `✅ ${r?.status ?? \"COMPLETED\"}`;\n lines.push(\n `| \\`${run.model}\\` | ${status} | ${fmtScore(r?.score ?? null)} | ${link} |`,\n );\n }\n const taskRows = report.runs.flatMap((run) =>\n (run.report?.samples ?? []).map((sample) => ({\n model: run.model,\n task: sample.task ?? \"?\",\n reward: sample.reward,\n })),\n );\n if (taskRows.length > 0 && taskRows.length <= 40) {\n lines.push(\"\");\n lines.push(\"<details><summary>Per-task rewards</summary>\");\n lines.push(\"\");\n lines.push(\"| Task | Model | Reward |\");\n lines.push(\"| --- | --- | ---: |\");\n for (const row of taskRows) {\n lines.push(\n `| ${row.task} | \\`${row.model}\\` | ${row.reward === null ? \"no score\" : row.reward.toFixed(2)} |`,\n );\n }\n lines.push(\"\");\n lines.push(\"</details>\");\n }\n return lines.join(\"\\n\");\n}\n\n/**\n * Push `dir` on the current (or given) branch, dispatch the named run config\n * against the pushed version, wait for every run, and gate.\n *\n * The gate: every dispatch accepted, every run terminal COMPLETED, and — when\n * `minScore` is set — every run's score meets it. A run with NO score fails a\n * score gate rather than passing it: null is \"not scored\", never 0 and never\n * fine.\n */\nexport async function validateWorld(\n dir: string,\n opts: {\n slug?: string;\n runConfig: string;\n branch?: string;\n minScore?: number | null;\n timeoutMinutes?: number;\n onProgress?: (line: string) => void;\n options?: WorldsClientOptions;\n },\n): Promise<ValidateReport> {\n const options = opts.options ?? {};\n const progress = opts.onProgress ?? (() => {});\n const minScore = opts.minScore ?? null;\n\n const provenance = detectProvenance();\n const branch = opts.branch ?? provenance.branch;\n if (!branch)\n throw new Error(\n \"No branch to validate on: pass --branch or run inside a git checkout / GitHub Actions.\",\n );\n\n progress(`pushing ${dir} as ${opts.slug ?? \"(pyproject name)\"}@${branch}…`);\n const pushed = await push(dir, {\n slug: opts.slug,\n branch,\n message: `PR validation push (${provenance.commit?.slice(0, 12) ?? \"local\"})`,\n ...(provenance.actor?.name ? { author: provenance.actor.name } : {}),\n options,\n });\n progress(`pushed version ${pushed.versionId} (${pushed.contentHash.slice(0, 12)})`);\n\n // Resolve the run config by name (the stable handle CI configures) or id.\n const configs = await listRunConfigs(options);\n const runConfig =\n configs.find((c) => c.id === opts.runConfig) ??\n configs.find((c) => c.name === opts.runConfig);\n if (!runConfig) {\n const known = configs.map((c) => c.name).join(\", \") || \"(none)\";\n throw new Error(\n `Run config \"${opts.runConfig}\" not found in this project. Have: ${known}`,\n );\n }\n\n progress(`dispatching run config \"${runConfig.name}\" (${runConfig.models.join(\", \")})…`);\n const dispatched = await apiRequest<{\n versionLabel: string;\n runs: { model: string; runId: string; ok: boolean; error?: string }[];\n }>(options, \"POST\", \"/api/public/benchmark-containers/run-configs/dispatch\", {\n runConfigId: runConfig.id,\n versionId: pushed.versionId,\n ...provenance,\n });\n\n // The run's platform page. New deployments return it on the run report\n // (`url`); against an older deployment we build the same page from the\n // evaluation id, because a PR comment that cannot link the run defeats\n // the point of the comment.\n const host = (\n options.host ??\n process.env.GATEWAY_HOST ??\n \"https://withgateway.ai\"\n ).replace(/\\/+$/, \"\");\n let projectId: string | null = null;\n try {\n const projects = await apiRequest<{ data?: { id?: string }[] }>(\n options,\n \"GET\",\n \"/api/public/projects\",\n );\n projectId = projects.data?.[0]?.id ?? null;\n } catch {\n projectId = null;\n }\n const fallbackUrl = (report: RunReport): string | null => {\n if (report.url) return report.url;\n const evaluationId = report.evaluations[0]?.id;\n return projectId && evaluationId\n ? `${host}/project/${projectId}/environment/runs/${encodeURIComponent(evaluationId)}`\n : null;\n };\n\n const runs: ValidatedRun[] = [];\n for (const run of dispatched.runs) {\n if (!run.ok) {\n runs.push({\n model: run.model,\n runId: run.runId,\n report: null,\n failure: `dispatch failed: ${run.error ?? \"unknown error\"}`,\n });\n continue;\n }\n progress(`waiting on ${run.model} (run ${run.runId})…`);\n let report: RunReport | null = null;\n let failure: string | null = null;\n try {\n report = await waitForRun(run.runId, {\n timeoutMinutes: opts.timeoutMinutes ?? 45,\n options,\n onTick: (r) =>\n progress(\n `…${run.model}: ${r.status.toLowerCase()} (${r.shardsCompleted ?? 0}/${r.parallelism} shards)`,\n ),\n });\n report = { ...report, url: fallbackUrl(report) };\n if (report.status.toUpperCase() !== \"COMPLETED\") {\n failure = report.status;\n } else if (minScore !== null) {\n if (report.score === null) failure = \"completed without a score\";\n else if (report.score < minScore)\n failure = `score ${fmtScore(report.score)} < ${minScore}`;\n }\n } catch (error) {\n failure = error instanceof Error ? error.message : String(error);\n }\n runs.push({ model: run.model, runId: run.runId, report, failure });\n }\n\n const base = {\n ok: runs.length > 0 && runs.every((r) => r.failure === null),\n slug: pushed.slug,\n branch,\n versionId: pushed.versionId,\n contentHash: pushed.contentHash,\n runConfig: { id: runConfig.id, name: runConfig.name },\n runs,\n };\n return { ...base, markdown: buildMarkdown(base, minScore) };\n}\n","/**\n * Worlds from TypeScript: identity, tasks, and HOSTED execution.\n *\n * The same three-level model as the Python SDK — WorldSet → Task — with one\n * deliberate difference: a world's tools are Python modules, so TypeScript\n * does not materialize task environments in-process. What a TS agent\n * codebase needs is exactly what this module provides: resolve a world ref\n * to its pinned version, read its task list, and dispatch HOSTED runs\n * (parallelism included) that execute the world server-side and file graded,\n * version-pinned rollouts. Local in-process execution stays a Python\n * capability by design, not by omission.\n */\n\nexport type WorldsClientOptions = {\n host?: string;\n publicKey?: string;\n secretKey?: string;\n};\n\nexport type ResolvedWorldVersion = {\n versionId: string;\n semanticVersion: string | null;\n contentHash: string;\n state?: string;\n};\n\nexport type WorldTaskInfo = {\n name: string;\n variant: string | null;\n};\n\nexport type DispatchedRun = {\n model: string;\n runId: string;\n ok: boolean;\n error?: string;\n};\n\nfunction resolveEnv(options: WorldsClientOptions) {\n const host =\n options.host ?? process.env.GATEWAY_HOST ?? \"https://withgateway.ai\";\n const publicKey = options.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;\n const secretKey = options.secretKey ?? process.env.GATEWAY_SECRET_KEY;\n if (!publicKey || !secretKey) {\n throw new Error(\n \"Gateway keys missing: set GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY \" +\n \"(or pass publicKey/secretKey).\",\n );\n }\n return { host: host.replace(/\\/+$/, \"\"), publicKey, secretKey };\n}\n\n/** Authenticated JSON request against the platform API — the primitive the\n * worlds helpers and the TS CLI share. */\nexport async function apiRequest<T>(\n options: WorldsClientOptions,\n method: \"GET\" | \"POST\" | \"PUT\" | \"DELETE\",\n path: string,\n body?: unknown,\n): Promise<T> {\n const { host, publicKey, secretKey } = resolveEnv(options);\n const res = await fetch(`${host}${path}`, {\n method,\n headers: {\n \"content-type\": \"application/json\",\n authorization:\n \"Basic \" + Buffer.from(`${publicKey}:${secretKey}`).toString(\"base64\"),\n },\n ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n });\n const text = await res.text();\n if (!res.ok) {\n throw new Error(\n `${method} ${path} -> ${res.status}: ${text.slice(0, 400)}`,\n );\n }\n return JSON.parse(text) as T;\n}\n\n/** Set (or rotate) one environment secret — write-only: no API returns it. */\nexport async function setEnvSecret(\n slug: string,\n key: string,\n value: string,\n options: WorldsClientOptions = {},\n): Promise<{ key: string; created: boolean }> {\n return apiRequest(\n options,\n \"PUT\",\n \"/api/public/benchmark-containers/secrets\",\n {\n slug,\n key,\n value,\n },\n );\n}\n\n/** Keys and rotation timestamps only — never values. */\nexport async function listEnvSecretKeys(\n slug: string,\n options: WorldsClientOptions = {},\n): Promise<{ key: string; updatedAt: string }[]> {\n const res = await apiRequest<{\n secrets: { key: string; updatedAt: string }[];\n }>(\n options,\n \"GET\",\n `/api/public/benchmark-containers/secrets?slug=${encodeURIComponent(slug)}`,\n );\n return res.secrets;\n}\n\nexport async function deleteEnvSecret(\n slug: string,\n key: string,\n options: WorldsClientOptions = {},\n): Promise<void> {\n await apiRequest(\n options,\n \"DELETE\",\n \"/api/public/benchmark-containers/secrets\",\n {\n slug,\n key,\n },\n );\n}\n\nexport type RunConfigSummary = {\n id: string;\n name: string;\n runType: string;\n createdAt: string;\n models: string[];\n parallelism: number;\n autoRunOnPush: boolean;\n agent: string | null;\n};\n\n/** Run configs in the project. CI resolves by NAME and dispatches by id. */\nexport async function listRunConfigs(\n options: WorldsClientOptions = {},\n): Promise<RunConfigSummary[]> {\n const res = await apiRequest<{ runConfigs: RunConfigSummary[] }>(\n options,\n \"GET\",\n \"/api/public/benchmark-containers/run-configs\",\n );\n return res.runConfigs;\n}\n\nexport type RunReport = {\n id: string;\n status: string;\n terminal: boolean;\n score: number | null;\n summary: string | null;\n model: string | null;\n versionLabel: string | null;\n parallelism: number;\n shardsCompleted: number | null;\n /** The run's page on the platform — what a PR comment should link. */\n url: string | null;\n evaluations: {\n id: string;\n status: string;\n avgReward: number | null;\n url: string | null;\n }[];\n samples: {\n task: string | null;\n reward: number | null;\n rewards: Record<string, unknown>;\n sessionId: string | null;\n }[];\n};\n\n/** The read half of dispatch: status, score, per-shard evaluations, and\n * per-task rewards — everything a CI gate needs. */\nexport async function getRun(\n runId: string,\n options: WorldsClientOptions = {},\n): Promise<RunReport> {\n return apiRequest(\n options,\n \"GET\",\n `/api/public/benchmark-containers/runs/${encodeURIComponent(runId)}`,\n );\n}\n\n/** Poll a run to terminal (default every 20s, up to `timeoutMinutes`). */\nexport async function waitForRun(\n runId: string,\n opts: {\n timeoutMinutes?: number;\n intervalSeconds?: number;\n onTick?: (run: RunReport) => void;\n options?: WorldsClientOptions;\n } = {},\n): Promise<RunReport> {\n const deadline = Date.now() + (opts.timeoutMinutes ?? 45) * 60_000;\n for (;;) {\n const run = await getRun(runId, opts.options ?? {});\n if (run.terminal) return run;\n if (Date.now() > deadline)\n throw new Error(\n `Run ${runId} still ${run.status} after the wait timeout.`,\n );\n opts.onTick?.(run);\n await new Promise((resolve) =>\n setTimeout(resolve, (opts.intervalSeconds ?? 20) * 1000),\n );\n }\n}\n\nexport type RunProvenance = {\n branch?: string;\n commit?: string;\n repoUrl?: string;\n actor?: { id?: string; name?: string; imageUrl?: string; kind?: string };\n};\n\n/**\n * Where a dispatch comes from, DETECTED rather than configured: the CI\n * checkout's branch/commit/actor under GitHub Actions, else the developer's\n * own git checkout. A run nobody can trace to a branch is a score with no\n * code attached, so every dispatch carries this unless overridden.\n */\nexport function detectProvenance(): RunProvenance {\n const env =\n (globalThis as { process?: { env?: Record<string, string | undefined> } })\n .process?.env ?? {};\n const out: RunProvenance = {};\n const ref = env.GITHUB_HEAD_REF || env.GITHUB_REF_NAME;\n if (ref) out.branch = ref;\n if (env.GITHUB_SHA) out.commit = env.GITHUB_SHA;\n const server = env.GITHUB_SERVER_URL ?? \"https://github.com\";\n if (env.GITHUB_REPOSITORY) out.repoUrl = `${server}/${env.GITHUB_REPOSITORY}`;\n if (env.GITHUB_ACTOR) {\n out.actor = {\n kind: \"ci\",\n id: env.GITHUB_ACTOR,\n name: env.GITHUB_ACTOR,\n // GitHub serves every account's avatar at /<login>.png.\n imageUrl: `${server}/${env.GITHUB_ACTOR}.png`,\n };\n }\n if (!out.branch || !out.commit) {\n try {\n const { execFileSync } =\n require(\"node:child_process\") as typeof import(\"node:child_process\");\n const git = (args: string[]) =>\n execFileSync(\"git\", args, {\n encoding: \"utf-8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n })\n .toString()\n .trim();\n out.branch = out.branch ?? git([\"rev-parse\", \"--abbrev-ref\", \"HEAD\"]);\n out.commit = out.commit ?? git([\"rev-parse\", \"HEAD\"]);\n if (!out.repoUrl) {\n const remote = git([\"config\", \"--get\", \"remote.origin.url\"]);\n if (remote) out.repoUrl = remote.replace(/\\.git$/, \"\");\n }\n if (!out.actor) {\n const name = git([\"config\", \"--get\", \"user.name\"]);\n if (name) out.actor = { kind: \"user\", name };\n }\n } catch {\n // No git here — dispatch without provenance rather than failing.\n }\n }\n return out;\n}\n\n/** One scenario of a world, as data. */\nexport class WorldTask {\n constructor(\n readonly world: WorldSet,\n readonly name: string,\n readonly variant: string | null,\n ) {}\n}\n\n/**\n * THE world, from a TS process: pinned identity + its tasks + hosted runs.\n *\n * const world = await openWorld(\"google-drive-sim@main\");\n * console.log(world.version.semanticVersion, world.tasks.length);\n * const runs = await world.dispatch(runConfigId);\n */\nexport class WorldSet {\n constructor(\n readonly slugRef: string,\n readonly slug: string,\n readonly ref: string | null,\n readonly version: ResolvedWorldVersion,\n public tasks: WorldTask[],\n private readonly options: WorldsClientOptions,\n ) {}\n\n task(variant: string): WorldTask {\n const hit = this.tasks.find(\n (t) => t.variant === variant || t.name.includes(variant),\n );\n if (!hit) {\n const known = this.tasks.map((t) => t.variant ?? t.name).join(\", \");\n throw new Error(`no task matches ${variant}; have: ${known}`);\n }\n return hit;\n }\n\n /**\n * Open a LIVE session against one of this world's tasks: the platform boots\n * (or reuses) a warm container, and your agent calls its tools through the\n * platform. See worlds/session.ts.\n */\n async open(\n task: string,\n opts: { reuseWarm?: boolean } = {},\n ): Promise<import(\"./session\").WorldSession> {\n const { openSession } = await import(\"./session\");\n return openSession(this.slug, task, {\n versionId: this.version.versionId,\n reuseWarm: opts.reuseWarm,\n options: this.options,\n });\n }\n\n /**\n * Start a HOSTED run of a run config against this world — the platform\n * executes the (Python) world in parallel containers per the config's\n * `parallelism` and files one graded run per model. Returns those runs.\n */\n async dispatch(\n runConfigId: string,\n opts: {\n containerId?: string;\n versionId?: string;\n /** Override the auto-detected branch/commit/actor. */\n provenance?: RunProvenance;\n } = {},\n ): Promise<{ versionLabel: string; runs: DispatchedRun[] }> {\n const provenance = opts.provenance ?? detectProvenance();\n return apiRequest(\n this.options,\n \"POST\",\n \"/api/public/benchmark-containers/run-configs/dispatch\",\n {\n runConfigId,\n ...(opts.containerId ? { containerId: opts.containerId } : {}),\n versionId: opts.versionId ?? this.version.versionId,\n ...provenance,\n },\n );\n }\n}\n\n/**\n * Resolve `slug` / `slug@branch|tag|semver|hash` to its pinned version and\n * task list. The task list comes from the version's file manifest\n * (`tasks/<name>/task.toml`), so it needs no bundle download.\n */\nexport async function openWorld(\n slugRef: string,\n options: WorldsClientOptions = {},\n): Promise<WorldSet> {\n const at = slugRef.indexOf(\"@\");\n const slug = at === -1 ? slugRef : slugRef.slice(0, at);\n const ref = at === -1 ? null : slugRef.slice(at + 1);\n\n const version = await apiRequest<\n ResolvedWorldVersion & { taskNames?: string[] }\n >(options, \"POST\", \"/api/public/benchmark-containers/resolve-version\", {\n slug,\n ...(ref ? { ref } : {}),\n });\n\n const world = new WorldSet(\n slugRef,\n slug,\n ref,\n {\n versionId: version.versionId,\n semanticVersion: version.semanticVersion ?? null,\n contentHash: version.contentHash,\n state: version.state,\n },\n [],\n options,\n );\n for (const name of version.taskNames ?? []) {\n const variant = /^[a-z0-9]+-([a-z0-9]+)-/.exec(name)?.[1] ?? null;\n world.tasks.push(new WorldTask(world, name, variant));\n }\n return world;\n}\n\n// The session surface completes the worlds module, so `@withgateway/sdk/worlds`\n// carries both halves: running a world locally, and driving one the platform\n// hosts. (session.ts imports apiRequest from here; the cycle is function-level\n// only, and the build below is what proves it resolves.)\nexport * from \"./session\";\n\n// The hub half: push, pull, propose and the content-hash primitives the CLI\n// runs on. These were reachable only from inside the package, so a consumer\n// could drive a world but never publish one.\nexport * from \"./hub\";\n\n// PR validation: push-dispatch-wait-gate as one composed call, for CI.\nexport * from \"./validate\";\n","#!/usr/bin/env node\n/**\n * The TypeScript `gateway` CLI — full command parity with the Python CLI's\n * `bench` family, including the working-dir workflows (push/pull/checkout/\n * status/branch/tag/propose — see worlds/hub.ts and its LOCKSTEP WARNING on\n * the content hash). The one Python-only command is `eval`: it runs the\n * world locally on the Python engines, which a JS process cannot host —\n * hosted runs via `dispatch` are the equivalent.\n *\n * Auth: GATEWAY_HOST + GATEWAY_PUBLIC_KEY + GATEWAY_SECRET_KEY, same env as\n * the library.\n */\nimport * as fs from \"node:fs\";\n\nimport {\n apiRequest,\n deleteEnvSecret,\n getRun,\n listEnvSecretKeys,\n listRunConfigs,\n openWorld,\n setEnvSecret,\n waitForRun,\n} from \"./worlds/index\";\nimport {\n computeContentHash,\n createRef,\n localTreeState,\n propose,\n pull,\n push,\n} from \"./worlds/hub\";\nimport { validateWorld } from \"./worlds/validate\";\n\ntype Flags = Record<string, string | boolean>;\n\nfunction parseArgv(argv: string[]): { positional: string[]; flags: Flags } {\n const positional: string[] = [];\n const flags: Flags = {};\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i];\n if (arg.startsWith(\"--\")) {\n const key = arg.slice(2);\n const next = argv[i + 1];\n if (next !== undefined && !next.startsWith(\"--\")) {\n flags[key] = next;\n i++;\n } else {\n flags[key] = true;\n }\n } else {\n positional.push(arg);\n }\n }\n return { positional, flags };\n}\n\nfunction str(flags: Flags, key: string): string | undefined {\n const value = flags[key];\n return typeof value === \"string\" ? value : undefined;\n}\n\nfunction fail(message: string): never {\n console.error(message);\n process.exit(2);\n}\n\nconst PYTHON_ONLY = new Set([\"eval\"]);\n\nconst HELP = `gateway bench <command> — worlds from TypeScript\n\n resolve <slug[@ref]> pinned version + task count\n tasks <slug[@ref]> the task list\n dispatch <runConfigId> [--container-id X] [--version-id Y]\n run <runId> [--wait] [--timeout-min N] status, score, per-task rewards\n run-configs list\n run-configs create --name N --models a,b [--parallelism K] [--tasks t1,t2] [--agent A] [--auto-run-on-push] [--id existing]\n run-configs delete --id X\n secrets set --env <slug> --key K [--value V] (omit --value to read stdin)\n secrets list --env <slug>\n secrets unset --env <slug> --key K\n refs <slug> branches and tags\n log <slug> [--branch B] [--limit N] version history\n proposals <slug> [--status open|applied|dismissed]\n\n pull <slug[@ref]> [--dir D] materialize a working dir\n push [dir] [--slug S] [--branch B] [--force] [--message M]\n validate [dir] --run-config NAME [--slug S] [--branch B] [--min-score X]\n [--summary-file F] [--timeout-min N]\n push this checkout, run it, gate — the PR-validation entry\n checkout <slug@ref> --dir D re-aim an existing working dir\n status [dir] clean/dirty vs base + hash check\n branch <slug> <name> [--version-id V] create a branch\n tag <slug> <name> [--version-id V] create a tag\n propose [dir] --title T --reason R [--target-branch B]\n\n eval (local engine runs) is Python-only — run hosted via 'dispatch'.\n\nAuth: GATEWAY_HOST, GATEWAY_PUBLIC_KEY, GATEWAY_SECRET_KEY.`;\n\nasync function readStdin(): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) chunks.push(chunk as Buffer);\n return Buffer.concat(chunks).toString(\"utf-8\").trim();\n}\n\nasync function main(): Promise<number> {\n const [group, command, ...rest] = process.argv.slice(2);\n if (!group || group === \"help\" || group === \"--help\") {\n console.log(HELP);\n return 0;\n }\n if (group !== \"bench\") {\n fail(\n `Unknown command group '${group}' — this CLI covers 'gateway bench'. Run 'gateway help'.`,\n );\n }\n if (!command) fail(HELP);\n if (PYTHON_ONLY.has(command)) {\n fail(\n `'gateway bench eval' runs the world locally on the PYTHON engines (verifiers/harbor) — it cannot exist in a JS process.\\n` +\n `Run hosted instead: gateway bench dispatch <runConfigId> — same worlds, graded on the platform.`,\n );\n }\n\n const { positional, flags } = parseArgv(rest);\n\n switch (command) {\n case \"resolve\": {\n const slugRef =\n positional[0] ?? fail(\"usage: gateway bench resolve <slug[@ref]>\");\n const world = await openWorld(slugRef);\n console.log(\n `${world.slug}@${world.ref ?? \"latest\"}: ${world.version.semanticVersion ?? \"-\"} ` +\n `(${world.version.contentHash.slice(0, 12)}) · ${world.version.state ?? \"?\"} · ${world.tasks.length} tasks`,\n );\n console.log(`versionId: ${world.version.versionId}`);\n return 0;\n }\n case \"tasks\": {\n const slugRef =\n positional[0] ?? fail(\"usage: gateway bench tasks <slug[@ref]>\");\n const world = await openWorld(slugRef);\n if (world.tasks.length === 0) {\n console.log(\"No task manifest served for this version.\");\n return 0;\n }\n for (const task of world.tasks) {\n console.log(`${task.name}${task.variant ? ` (${task.variant})` : \"\"}`);\n }\n return 0;\n }\n case \"dispatch\": {\n const runConfigId =\n positional[0] ?? fail(\"usage: gateway bench dispatch <runConfigId>\");\n const body: Record<string, string> = { runConfigId };\n const containerId = str(flags, \"container-id\");\n const versionId = str(flags, \"version-id\");\n if (containerId) body.containerId = containerId;\n if (versionId) body.versionId = versionId;\n const result = await apiRequest<{\n versionLabel: string;\n runs: { model: string; runId: string; ok: boolean; error?: string }[];\n }>(\n {},\n \"POST\",\n \"/api/public/benchmark-containers/run-configs/dispatch\",\n body,\n );\n for (const run of result.runs) {\n console.log(\n `${run.model}: ${run.ok ? \"dispatched\" : `FAILED: ${run.error}`} run=${run.runId}`,\n );\n }\n console.log(`-> ${result.versionLabel}`);\n return result.runs.every((r) => r.ok) ? 0 : 1;\n }\n case \"run\": {\n const runId =\n positional[0] ?? fail(\"usage: gateway bench run <runId> [--wait]\");\n const report = flags.wait\n ? await waitForRun(runId, {\n timeoutMinutes: Number(str(flags, \"timeout-min\") ?? 45),\n onTick: (r) =>\n console.error(\n `…${r.status.toLowerCase()} (${r.shardsCompleted ?? 0}/${r.parallelism} shards)`,\n ),\n })\n : await getRun(runId);\n console.log(\n `${report.id} ${report.status}${report.score !== null ? ` score=${report.score.toFixed(3)}` : \"\"}` +\n ` (${report.model ?? \"?\"} · ${report.versionLabel ?? \"?\"} · x${report.parallelism})`,\n );\n for (const sample of report.samples) {\n const subs = Object.entries(sample.rewards)\n .filter(([, v]) => typeof v === \"number\")\n .map(([k, v]) => `${k}=${(v as number).toFixed(2)}`)\n .join(\" \");\n console.log(\n ` ${(sample.reward ?? 0).toFixed(2)} ${sample.task ?? \"?\"}${subs ? ` [${subs}]` : \"\"}`,\n );\n }\n if (report.summary) console.log(` ${report.summary}`);\n return report.terminal && report.status.toUpperCase() === \"COMPLETED\"\n ? 0\n : 1;\n }\n case \"run-configs\": {\n const action = positional[0] ?? \"list\";\n if (action === \"list\") {\n const rows = await listRunConfigs();\n if (rows.length === 0) {\n console.log(\"No run configs in this project.\");\n return 0;\n }\n for (const row of rows) {\n const extras = [\n row.parallelism > 1 ? `x${row.parallelism} containers` : null,\n row.autoRunOnPush ? \"auto-on-push\" : null,\n ].filter(Boolean);\n console.log(\n `${row.id} ${row.name} (${row.models.join(\", \") || \"no models\"})${extras.length ? ` [${extras.join(\", \")}]` : \"\"}`,\n );\n }\n return 0;\n }\n if (action === \"delete\") {\n const id = str(flags, \"id\") ?? fail(\"--id is required for delete\");\n await apiRequest(\n {},\n \"DELETE\",\n \"/api/public/benchmark-containers/run-configs\",\n { id },\n );\n console.log(`Deleted ${id}.`);\n return 0;\n }\n if (action !== \"create\")\n fail(\"run-configs actions: list | create | delete\");\n const name = str(flags, \"name\") ?? fail(\"--name is required for create\");\n const models = (\n str(flags, \"models\") ?? fail(\"--models is required for create\")\n )\n .split(\",\")\n .map((m) => m.trim())\n .filter(Boolean);\n const body: Record<string, unknown> = { name, models };\n const parallelism = str(flags, \"parallelism\");\n if (parallelism) body.parallelism = Number(parallelism);\n const agent = str(flags, \"agent\");\n if (agent) body.agent = agent;\n const tasks = str(flags, \"tasks\");\n if (tasks)\n body.taskNames = tasks\n .split(\",\")\n .map((t) => t.trim())\n .filter(Boolean);\n if (flags[\"auto-run-on-push\"]) body.autoRunOnPush = true;\n const id = str(flags, \"id\");\n if (id) body.id = id;\n const row = await apiRequest<{\n id: string;\n name: string;\n models: string[];\n }>({}, \"POST\", \"/api/public/benchmark-containers/run-configs\", body);\n console.log(`${row.id} ${row.name} (${row.models.join(\", \")})`);\n return 0;\n }\n case \"secrets\": {\n const action =\n positional[0] ?? fail(\"secrets actions: set | list | unset\");\n const env = str(flags, \"env\") ?? fail(\"--env <world slug> is required\");\n if (action === \"list\") {\n const rows = await listEnvSecretKeys(env);\n if (rows.length === 0) {\n console.log(`No secrets on ${env}.`);\n return 0;\n }\n for (const row of rows)\n console.log(`${row.key} (rotated ${row.updatedAt})`);\n return 0;\n }\n const key = str(flags, \"key\") ?? fail(`--key is required for ${action}`);\n if (action === \"unset\") {\n await deleteEnvSecret(env, key);\n console.log(`Deleted ${key} from ${env}.`);\n return 0;\n }\n if (action !== \"set\") fail(\"secrets actions: set | list | unset\");\n const value = str(flags, \"value\") ?? (await readStdin());\n if (!value)\n fail(\"empty value — nothing stored (pass --value or pipe stdin)\");\n const res = await setEnvSecret(env, key, value);\n console.log(\n `${res.created ? \"Added\" : \"Rotated\"} ${key} on ${env} — next hosted run receives it.`,\n );\n return 0;\n }\n case \"refs\": {\n const slug = positional[0] ?? fail(\"usage: gateway bench refs <slug>\");\n const res = await apiRequest<{\n refs: {\n name: string;\n kind: string;\n semanticVersion: string | null;\n contentHash: string | null;\n state: string | null;\n }[];\n }>(\n {},\n \"GET\",\n `/api/public/benchmark-containers/refs?slug=${encodeURIComponent(slug)}`,\n );\n for (const ref of res.refs) {\n console.log(\n `${ref.kind === \"tag\" ? \"tag \" : \"branch\"} ${ref.name} ${ref.semanticVersion ?? \"-\"} (${ref.contentHash?.slice(0, 12) ?? \"?\"}) ${ref.state ?? \"\"}`,\n );\n }\n return 0;\n }\n case \"log\": {\n const slug = positional[0] ?? fail(\"usage: gateway bench log <slug>\");\n const params = new URLSearchParams({ slug });\n const branch = str(flags, \"branch\");\n if (branch) params.set(\"branch\", branch);\n const limit = str(flags, \"limit\");\n if (limit) params.set(\"limit\", limit);\n const res = await apiRequest<{\n branch: string;\n entries: {\n versionId: string;\n contentHash: string;\n semanticVersion: string | null;\n state: string;\n author: string | null;\n changeReason: string | null;\n }[];\n }>(\n {},\n \"GET\",\n `/api/public/benchmark-containers/log?${params.toString()}`,\n );\n console.log(`branch: ${res.branch}`);\n for (const entry of res.entries) {\n console.log(\n `${entry.contentHash.slice(0, 12)} ${entry.semanticVersion ?? \"-\"} ${entry.state}` +\n `${entry.author ? ` by ${entry.author}` : \"\"}${entry.changeReason ? ` — ${entry.changeReason}` : \"\"}`,\n );\n }\n return 0;\n }\n case \"proposals\": {\n const slug =\n positional[0] ?? fail(\"usage: gateway bench proposals <slug>\");\n const params = new URLSearchParams({ slug });\n const status = str(flags, \"status\");\n if (status) params.set(\"status\", status);\n const res = await apiRequest<{\n proposals: {\n id: string;\n title?: string | null;\n status: string;\n createdAt?: string;\n }[];\n }>(\n {},\n \"GET\",\n `/api/public/benchmark-containers/proposals?${params.toString()}`,\n );\n if (res.proposals.length === 0) {\n console.log(\"No proposals.\");\n return 0;\n }\n for (const proposal of res.proposals) {\n console.log(\n `${proposal.id} [${proposal.status}] ${proposal.title ?? \"\"}`,\n );\n }\n return 0;\n }\n case \"pull\": {\n const slugRef =\n positional[0] ??\n fail(\"usage: gateway bench pull <slug[@ref]> [--dir D]\");\n const res = await pull(slugRef, str(flags, \"dir\"));\n console.log(\n `Pulled ${res.slug} -> ${res.dir} (${res.files} files, version ${res.versionId})`,\n );\n return 0;\n }\n case \"checkout\": {\n const slugRef =\n positional[0] ??\n fail(\"usage: gateway bench checkout <slug@ref> --dir D\");\n const dir =\n str(flags, \"dir\") ??\n fail(\"--dir is required for checkout (the working dir to re-aim)\");\n const res = await pull(slugRef, dir);\n console.log(\n `Checked out ${slugRef} into ${res.dir} (${res.files} files)`,\n );\n return 0;\n }\n case \"push\": {\n const dir = positional[0] ?? \".\";\n const res = await push(dir, {\n slug: str(flags, \"slug\"),\n branch: str(flags, \"branch\"),\n force: Boolean(flags.force),\n message: str(flags, \"message\"),\n author: str(flags, \"author\"),\n });\n console.log(\n `Pushed ${res.slug}@${res.branch}: version ${res.versionId} (${res.contentHash.slice(0, 12)})`,\n );\n return 0;\n }\n case \"validate\": {\n // The CI entry: push THIS checkout's world source on the PR's branch,\n // run it, gate on the graded result. Exit code is the check.\n const dir = positional[0] ?? \".\";\n const runConfig =\n str(flags, \"run-config\") ??\n fail(\n \"usage: gateway bench validate [dir] --run-config NAME [--slug S] [--branch B] [--min-score X] [--summary-file F] [--timeout-min N]\",\n );\n const minScoreRaw = str(flags, \"min-score\");\n const report = await validateWorld(dir, {\n slug: str(flags, \"slug\"),\n runConfig,\n branch: str(flags, \"branch\"),\n minScore: minScoreRaw === undefined ? null : Number(minScoreRaw),\n timeoutMinutes: Number(str(flags, \"timeout-min\") ?? 45),\n onProgress: (line) => console.error(line),\n });\n for (const run of report.runs) {\n console.log(\n `${run.model}: ${run.failure ? `FAIL — ${run.failure}` : \"pass\"}` +\n `${run.report?.score != null ? ` score=${run.report.score.toFixed(3)}` : \"\"}` +\n `${run.report?.url ? ` ${run.report.url}` : \"\"}`,\n );\n }\n // The markdown lands wherever the caller wants to publish it: a file\n // for a PR comment, and the step summary when GitHub provides one.\n const summaryFile = str(flags, \"summary-file\");\n if (summaryFile) fs.writeFileSync(summaryFile, report.markdown + \"\\n\");\n const stepSummary = process.env.GITHUB_STEP_SUMMARY;\n if (stepSummary) fs.appendFileSync(stepSummary, report.markdown + \"\\n\");\n console.log(report.ok ? \"validation passed\" : \"validation FAILED\");\n return report.ok ? 0 : 1;\n }\n case \"status\": {\n const dir = positional[0] ?? \".\";\n const state = localTreeState(dir);\n if (!state.meta) {\n console.log(\n \"Ad-hoc dir: no pull/push base recorded (.gateway missing).\",\n );\n return 0;\n }\n console.log(\n `base: ${state.meta.slug}@${state.meta.branch ?? \"?\"} version ${state.meta.versionId ?? \"?\"}`,\n );\n const localHash = computeContentHash(dir);\n const baseHash = state.meta.contentHash;\n console.log(\n `content hash: ${localHash.slice(0, 12)} ${localHash === baseHash ? \"== base (hash-verified)\" : `!= base ${String(baseHash).slice(0, 12)}`}`,\n );\n if (state.clean) {\n console.log(\"clean — tree matches its base.\");\n return 0;\n }\n console.log(`dirty (${state.dirty.length}):`);\n for (const p of state.dirty.slice(0, 40)) console.log(` ${p}`);\n return 0;\n }\n case \"branch\":\n case \"tag\": {\n const slug =\n positional[0] ?? fail(`usage: gateway bench ${command} <slug> <name>`);\n const name =\n positional[1] ?? fail(`usage: gateway bench ${command} <slug> <name>`);\n const ref = await createRef(\n slug,\n name,\n command as \"branch\" | \"tag\",\n str(flags, \"version-id\"),\n );\n console.log(`${ref.kind} ${ref.name} -> ${ref.versionId}`);\n return 0;\n }\n case \"propose\": {\n const dir = positional[0] ?? \".\";\n const title = str(flags, \"title\") ?? fail(\"--title is required\");\n const reason = str(flags, \"reason\") ?? fail(\"--reason is required\");\n const res = await propose(dir, {\n title,\n reason,\n targetBranch: str(flags, \"target-branch\"),\n });\n console.log(`Proposal ${res.proposalId} opened.`);\n return 0;\n }\n default:\n fail(`Unknown command 'bench ${command}'.\\n\\n${HELP}`);\n }\n}\n\nmain().then(\n (code) => process.exit(code),\n (error) => {\n console.error(error instanceof Error ? error.message : String(error));\n process.exit(1);\n },\n);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA2FO,SAAS,oBAAoB,MAOlC;AACA,QAAM,SAAS,oBAAoB,KAAK,KAAK,UAAU,KAAK,CAAC,IAAI,CAAC,KAAK;AACvE,QAAM,aAAsC,CAAC;AAC7C,QAAM,WAAqB,CAAC;AAE5B,QAAM,SAAmB,CAAC;AAC1B,MAAI,QAAQ;AACZ,MAAI,UAAU;AACd,aAAW,MAAM,QAAQ;AACvB,QAAI,MAAM,SAAS,E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D,cAAQ,IAAI,YAAY,IAAI,UAAU,UAAU;AAChD,aAAO;AAAA,IACT;AAAA,IACA;AACE,WAAK,0BAA0B,OAAO;AAAA;AAAA,EAAS,IAAI,EAAE;AAAA,EACzD;AACF;AAEA,KAAK,EAAE;AAAA,EACL,CAAC,SAAS,QAAQ,KAAK,IAAI;AAAA,EAC3B,CAAC,UAAU;AACT,YAAQ,MAAM,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AACpE,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF;","names":["openWorld","pad","resolve","path","resolve","openSession","fs","row","id"]}
|
package/dist/index.d.mts
CHANGED
|
@@ -7,7 +7,7 @@ export { GatewayAgentDescriptor, GatewaySecurity, GatewaySecurityConfig, Gateway
|
|
|
7
7
|
export { DEFAULT_TIMEOUT_SECONDS, ENV_GATEWAY_HOST, ENV_GATEWAY_PUBLIC_KEY, ENV_GATEWAY_SECRET_KEY, LoadSessionOptions, SessionLoadError, SessionObservation, SessionRecording, SessionTrace, basicAuthHeader, loadSession, sessionObservationFromApi, sessions } from './sessions/index.mjs';
|
|
8
8
|
export { UserEvent, UserEventOptions, UserProfile, UserProfileError, UserProfileUpdate, UsersClient, UsersClientConfig, UsersClientFromEnvConfig, users } from './users/index.mjs';
|
|
9
9
|
export { AGENT_ID_KEY, SUCCESS_METRIC_NAME_KEY, SUCCESS_SIGNAL_KEY, ScoreDataType, ScoreError, ScoreOptions, ScoresClient, ScoresClientConfig, ScoresClientFromEnvConfig, SuccessOptions, currentTraceId, scores, success } from './scores/index.mjs';
|
|
10
|
-
export { DispatchedRun, GradeResult, ResolvedWorldVersion, RunConfigSummary, RunProvenance, RunReport, SessionRunReport, SessionRunResult, WorldSession, WorldSessionCallError, WorldSessionState, WorldSessionTimeout, WorldSet, WorldTask, WorldTaskInfo, WorldToolSpec, WorldToolkit, WorldsClientOptions, apiRequest, attachSession, deleteEnvSecret, detectProvenance, getRun, listEnvSecretKeys, listRunConfigs, openSession, openWorld, runSessions, schemaFromSignature, setEnvSecret, waitForRun } from './worlds/index.mjs';
|
|
10
|
+
export { DEFAULT_BRANCH, DispatchedRun, GradeResult, LocalMeta, ResolvedWorldVersion, RunConfigSummary, RunProvenance, RunReport, SessionRunReport, SessionRunResult, ValidateReport, ValidatedRun, WorldSession, WorldSessionCallError, WorldSessionState, WorldSessionTimeout, WorldSet, WorldTask, WorldTaskInfo, WorldToolSpec, WorldToolkit, WorldsClientOptions, apiRequest, attachSession, buildSourceTarball, collectArchiveRelPaths, computeContentHash, createRef, deleteEnvSecret, detectProvenance, getRun, isIncludedInContentHash, listEnvSecretKeys, listRunConfigs, localTreeState, openSession, openWorld, propose, pull, push, readLocalMeta, runSessions, schemaFromSignature, setEnvSecret, snapshotTreeHashes, validateWorld, waitForRun, writeLocalMeta } from './worlds/index.mjs';
|
|
11
11
|
import { _ as _tracingModule } from './index-B5HUQQDE.mjs';
|
|
12
12
|
export { I as IdentifyOptions, i as identify, r as resolveUserId } from './index-B5HUQQDE.mjs';
|
|
13
13
|
import 'async_hooks';
|
package/dist/index.d.ts
CHANGED
|
@@ -7,7 +7,7 @@ export { GatewayAgentDescriptor, GatewaySecurity, GatewaySecurityConfig, Gateway
|
|
|
7
7
|
export { DEFAULT_TIMEOUT_SECONDS, ENV_GATEWAY_HOST, ENV_GATEWAY_PUBLIC_KEY, ENV_GATEWAY_SECRET_KEY, LoadSessionOptions, SessionLoadError, SessionObservation, SessionRecording, SessionTrace, basicAuthHeader, loadSession, sessionObservationFromApi, sessions } from './sessions/index.js';
|
|
8
8
|
export { UserEvent, UserEventOptions, UserProfile, UserProfileError, UserProfileUpdate, UsersClient, UsersClientConfig, UsersClientFromEnvConfig, users } from './users/index.js';
|
|
9
9
|
export { AGENT_ID_KEY, SUCCESS_METRIC_NAME_KEY, SUCCESS_SIGNAL_KEY, ScoreDataType, ScoreError, ScoreOptions, ScoresClient, ScoresClientConfig, ScoresClientFromEnvConfig, SuccessOptions, currentTraceId, scores, success } from './scores/index.js';
|
|
10
|
-
export { DispatchedRun, GradeResult, ResolvedWorldVersion, RunConfigSummary, RunProvenance, RunReport, SessionRunReport, SessionRunResult, WorldSession, WorldSessionCallError, WorldSessionState, WorldSessionTimeout, WorldSet, WorldTask, WorldTaskInfo, WorldToolSpec, WorldToolkit, WorldsClientOptions, apiRequest, attachSession, deleteEnvSecret, detectProvenance, getRun, listEnvSecretKeys, listRunConfigs, openSession, openWorld, runSessions, schemaFromSignature, setEnvSecret, waitForRun } from './worlds/index.js';
|
|
10
|
+
export { DEFAULT_BRANCH, DispatchedRun, GradeResult, LocalMeta, ResolvedWorldVersion, RunConfigSummary, RunProvenance, RunReport, SessionRunReport, SessionRunResult, ValidateReport, ValidatedRun, WorldSession, WorldSessionCallError, WorldSessionState, WorldSessionTimeout, WorldSet, WorldTask, WorldTaskInfo, WorldToolSpec, WorldToolkit, WorldsClientOptions, apiRequest, attachSession, buildSourceTarball, collectArchiveRelPaths, computeContentHash, createRef, deleteEnvSecret, detectProvenance, getRun, isIncludedInContentHash, listEnvSecretKeys, listRunConfigs, localTreeState, openSession, openWorld, propose, pull, push, readLocalMeta, runSessions, schemaFromSignature, setEnvSecret, snapshotTreeHashes, validateWorld, waitForRun, writeLocalMeta } from './worlds/index.js';
|
|
11
11
|
import { _ as _tracingModule } from './index-Dpo-t8iO.js';
|
|
12
12
|
export { I as IdentifyOptions, i as identify, r as resolveUserId } from './index-Dpo-t8iO.js';
|
|
13
13
|
import 'async_hooks';
|