@withgateway/sdk 0.2.6 → 0.2.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +24 -8
- package/dist/cli.js +15468 -11263
- package/dist/cli.js.map +1 -1
- package/dist/cli.mjs +15233 -11028
- package/dist/cli.mjs.map +1 -1
- package/dist/files/index.d.mts +1 -1
- package/dist/files/index.d.ts +1 -1
- package/dist/files/index.js +291 -40
- package/dist/files/index.js.map +1 -1
- package/dist/files/index.mjs +284 -37
- package/dist/files/index.mjs.map +1 -1
- package/dist/hooks/index.d.mts +1 -1
- package/dist/hooks/index.d.ts +1 -1
- package/dist/hooks/index.js +203 -47
- package/dist/hooks/index.js.map +1 -1
- package/dist/hooks/index.mjs +198 -42
- package/dist/hooks/index.mjs.map +1 -1
- package/dist/{index-BaKu5ZSU.d.mts → index-C3UzD0G3.d.mts} +75 -1
- package/dist/{index-BaKu5ZSU.d.ts → index-C3UzD0G3.d.ts} +75 -1
- package/dist/{index-CLkMr6VG.d.ts → index-D-_4Ibcn.d.ts} +36 -4
- package/dist/{index-CdbmO4aX.d.mts → index-FfK4Nump.d.mts} +36 -4
- package/dist/index.d.mts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +2149 -615
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +2053 -566
- package/dist/index.mjs.map +1 -1
- package/dist/traces/index.js +268 -31
- package/dist/traces/index.js.map +1 -1
- package/dist/traces/index.mjs +262 -28
- package/dist/traces/index.mjs.map +1 -1
- package/dist/tracing/index.js +19 -11
- package/dist/tracing/index.js.map +1 -1
- package/dist/tracing/index.mjs +19 -11
- package/dist/tracing/index.mjs.map +1 -1
- package/dist/worlds/index.d.mts +886 -117
- package/dist/worlds/index.d.ts +886 -117
- package/dist/worlds/index.js +1770 -452
- package/dist/worlds/index.js.map +1 -1
- package/dist/worlds/index.mjs +1752 -434
- package/dist/worlds/index.mjs.map +1 -1
- package/package.json +14 -10
- package/runtime/gatewaysdk/environment/_toml.py +3 -10
- package/runtime/gatewaysdk/environment/_world.py +95 -28
- package/runtime/gatewaysdk/environment/runtime.py +10 -6
- package/runtime/gatewaysdk/environment/schema/__main__.py +35 -0
- package/runtime/gatewaysdk/environment/schema/api.py +19 -23
- package/runtime/gatewaysdk/environment/schema/batch.py +68 -14
- package/runtime/gatewaysdk/environment/schema/bundle_runtime.py +4 -2
- package/runtime/gatewaysdk/environment/schema/cast.py +264 -0
- package/runtime/gatewaysdk/environment/schema/compiler.py +35 -1
- package/runtime/gatewaysdk/environment/schema/conform.py +28 -10
- package/runtime/gatewaysdk/environment/schema/connector.py +59 -14
- package/runtime/gatewaysdk/environment/schema/connectors/custom/handlers.py +38 -1
- package/runtime/gatewaysdk/environment/schema/connectors/google-drive/readers/merge.toml +3 -1
- package/runtime/gatewaysdk/environment/schema/credentials.py +20 -0
- package/runtime/gatewaysdk/environment/schema/csv_rows.py +117 -0
- package/runtime/gatewaysdk/environment/schema/cycles.py +121 -0
- package/runtime/gatewaysdk/environment/schema/data.py +21 -5
- package/runtime/gatewaysdk/environment/schema/grading.py +95 -13
- package/runtime/gatewaysdk/environment/schema/handler_errors.py +44 -0
- package/runtime/gatewaysdk/environment/schema/handler_scan.py +175 -0
- package/runtime/gatewaysdk/environment/schema/host.py +68 -115
- package/runtime/gatewaysdk/environment/schema/host_requests.py +78 -0
- package/runtime/gatewaysdk/environment/schema/host_surfaces.py +12 -0
- package/runtime/gatewaysdk/environment/schema/ingest.py +5 -18
- package/runtime/gatewaysdk/environment/schema/local.py +7 -10
- package/runtime/gatewaysdk/environment/schema/openapi_document.py +322 -0
- package/runtime/gatewaysdk/environment/schema/openapi_import.py +382 -0
- package/runtime/gatewaysdk/environment/schema/openapi_routes.py +441 -0
- package/runtime/gatewaysdk/environment/schema/openapi_schemas.py +629 -0
- package/runtime/gatewaysdk/environment/schema/openapi_source.py +210 -0
- package/runtime/gatewaysdk/environment/schema/platform.py +110 -299
- package/runtime/gatewaysdk/environment/schema/platform_import.py +182 -0
- package/runtime/gatewaysdk/environment/schema/platform_query.py +95 -0
- package/runtime/gatewaysdk/environment/schema/route_bindings.py +176 -0
- package/runtime/gatewaysdk/environment/schema/runtime.py +56 -7
- package/runtime/gatewaysdk/environment/schema/scaffold.py +64 -5
- package/runtime/gatewaysdk/environment/schema/skills/benchmarks-getting-started/SKILL.md +70 -22
- package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/SKILL.md +54 -4
- package/runtime/gatewaysdk/environment/schema/skills/hooks-getting-started/SKILL.md +27 -2
- package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/ROWS.md +62 -0
- package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/SKILL.md +91 -54
- package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/SKILL.md +146 -146
- package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/cli-mcp-map.md +11 -7
- package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/gotchas.md +30 -0
- package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/new-world-sandbox.md +43 -0
- package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/openapi-import.md +90 -0
- package/runtime/gatewaysdk/environment/schema/store.py +15 -6
- package/runtime/gatewaysdk/environment/schema/store_contract.py +119 -0
- package/runtime/gatewaysdk/environment/schema/tasks.py +121 -32
- package/runtime/gatewaysdk/environment/schema/tools_world.py +32 -10
- package/runtime/gatewaysdk/environment/schema/tree_import.py +228 -0
- package/runtime/gatewaysdk/environment/schema/ui.py +18 -2
- package/runtime/gatewaysdk/environment/schema/validation.py +35 -0
- package/runtime/gatewaysdk/environment/schema/verbs.py +8 -2
- package/runtime/gatewaysdk/environment/world.py +42 -3
- package/runtime/gatewaysdk/environment/world_session_contract.py +57 -0
- package/skills/benchmarks-getting-started/SKILL.md +70 -22
- package/skills/connector-schema-authoring/SKILL.md +54 -4
- package/skills/connector-schema-authoring/connector-worlds.md +21 -7
- package/skills/connector-schema-authoring/world-schema.md +144 -83
- package/skills/hooks-getting-started/SKILL.md +27 -2
- package/skills/world-data-ingestion/ROWS.md +62 -0
- package/skills/world-data-ingestion/SKILL.md +91 -54
- package/skills/worlds-getting-started/SKILL.md +146 -146
- package/skills/worlds-getting-started/references/cli-mcp-map.md +11 -7
- package/skills/worlds-getting-started/references/gotchas.md +30 -0
- package/skills/worlds-getting-started/references/new-world-sandbox.md +43 -0
- package/skills/worlds-getting-started/references/openapi-import.md +90 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/worlds/browser.ts","../../src/worlds/session.ts","../../src/worlds/tasks.ts","../../src/worlds/taskSessions.ts","../../src/worlds/evals.ts","../../src/worlds/taskRun.ts","../../src/worlds/worldDir.ts","../../src/worlds/hub.ts","../../src/worlds/validate.ts","../../src/worlds/describe.ts","../../src/cli/platform/worldData/json.ts","../../src/worlds/transforms.ts","../../src/worlds/redaction.ts","../../src/worlds/query.ts","../../src/worlds/migrate.ts","../../src/worlds/ingest.ts","../../src/worlds/sandbox.ts","../../src/worlds/index.ts","../../src/traces/index.ts"],"sourcesContent":["import { schemaFromSignature, type WorldToolkit } from \"./session\";\n\n/**\n * A BROWSER ON A WORLD'S UI — the computer-use half of a live session.\n *\n * A session answers on SURFACES. `tools` is always there (the world's own\n * operations over the rendezvous). An api-type world may also answer on\n * `api` (the service itself), `ui` (its dashboard, over the same state) and\n * `browser` — a headless Chromium the platform runs NEXT TO that UI, which\n * an agent drives through Playwright. This file is the TS client for the\n * last two, call for call with `gatewaysdk/world_browser.py`.\n *\n * const s = await openSession(\"payments-like\", \"refund-dispute\", {\n * surfaces: [\"ui\", \"browser\"],\n * });\n * await s.ready();\n * const b = await s.browser(); // hosted, next to the world\n * await b.goto(); // the UI's entry page\n * await b.click(\"text=Refund\");\n * const tools = computerUseToolkit(b); // the same actions as model tools\n * await b.close();\n *\n * Playwright is an OPTIONAL peer: nothing here imports it until a browser is\n * opened, so sessions that never touch a UI never load it.\n *\n * MODES. `hosted` connects to the session's own browser (a Playwright server\n * the pod exposes over an authenticated websocket). `local` launches Chromium\n * on this machine and points it at the UI — a laptop against a hosted twin,\n * or a test. `auto` prefers hosted. Asking for a mode the session cannot\n * serve throws `WorldSurfaceUnavailable`; there is no silent fallback to a\n * browser other than the one the episode is judged on.\n *\n * OBSERVABILITY. Every action a `WorldBrowser` takes (goto, click, type,\n * press, scroll, back) is reported to the platform as one event — what was\n * done, whether it worked, where the page ended up, and a JPEG of the screen\n * after — through a `BrowserActionRecorder`. Reporting is fire-and-forget\n * and never fails the action; the platform renders it as the session's\n * browser timeline. Text typed into secret-looking fields is redacted before\n * it leaves the process.\n */\n\nexport const SURFACE_KINDS = [\"tools\", \"api\", \"ui\", \"browser\"] as const;\nexport type WorldSurfaceKind = (typeof SURFACE_KINDS)[number];\n\nexport const DEFAULT_VIEWPORT = { width: 1280, height: 800 };\nconst SETTLE_TIMEOUT_MS = 5_000;\nconst SETTLE_QUIET_MS = 150;\nconst SETTLE_POLL_MS = 25;\n\nexport const EVENT_BATCH_SIZE = 10;\nexport const EVENT_FLUSH_INTERVAL_MS = 1_000;\nexport const EVENT_MAX_RETRIES = 3;\nconst EVENT_SCREENSHOT_QUALITY = 60;\nconst EVENT_MAX_STRING = 500;\n\nconst SECRET_KEY =\n /pass(word|wd)?|secret|token|api[-_]?key|authorization|cookie|(^|[-_ #.\\[\"'=])(otp|pin|cvv|ssn)([-_ \\]\"']|$)/i;\nconst SECRET_VALUE =\n /^((sk|pk|ghp|xox[abp])[-_][-_A-Za-z0-9]{8,}|AKIA[0-9A-Z]{12,}|Bearer [-_.A-Za-z0-9]{8,})/;\n\n/** The `surfaces` block of a session descriptor, as the platform sends it. */\nexport type SessionSurfaces = {\n tools: { kind: \"rendezvous\" };\n api?: {\n url: string;\n /** Per-session credential of a World Host session: send it as\n * `Authorization: Bearer <token>` (the header only; a token in the URL is\n * refused). Absent when the world\n * itself answers with its declared auth (a pod or a customer-hosted twin). */\n token?: string;\n };\n ui?: {\n url: string;\n entry: string;\n /** Same-origin prefix the UI proxies to the world API, e.g. `/__world-api`;\n * null when the UI only reaches the API server-side. */\n apiPath?: string | null;\n /** Per-session credential of a World Host UI. A browser navigation cannot\n * carry a header, so the first page load presents it once as `?token=`\n * and the host answers with an HttpOnly cookie. Absent for pod UIs. */\n token?: string;\n };\n browser?: {\n wsUrl: string;\n /** `cdp`: the platform's Chromium relay (any number of agents share one\n * browser, each in its own context). `playwright`: a `run-server` endpoint. */\n protocol: \"cdp\" | \"playwright\";\n viewport: { width: number; height: number };\n };\n};\n\nexport class WorldSurfaceUnavailable extends Error {\n constructor(\n readonly surface: WorldSurfaceKind,\n reason: string,\n ) {\n super(`World surface '${surface}' is unavailable: ${reason}`);\n }\n}\n\nexport function surfaceKinds(s: SessionSurfaces): WorldSurfaceKind[] {\n const kinds: WorldSurfaceKind[] = [\"tools\"];\n if (s.api) kinds.push(\"api\");\n if (s.ui) kinds.push(\"ui\");\n if (s.browser) kinds.push(\"browser\");\n return kinds;\n}\n\nconst UI_TOKEN_QUERY = \"token\";\n\n/** The URL of `path` on a UI surface, carrying the session token when the\n * surface has one. `path` may already have a query string; the token is\n * appended to it. */\nexport function uiUrl(\n ui: NonNullable<SessionSurfaces[\"ui\"]>,\n path: string,\n): string {\n const base = ui.url.replace(/\\/+$/, \"\");\n const rel = path.startsWith(\"/\") ? path : `/${path}`;\n if (!ui.token) return base + rel;\n const [beforeHash, hash] = splitHash(rel);\n const joiner = beforeHash.includes(\"?\") ? \"&\" : \"?\";\n const query = `${UI_TOKEN_QUERY}=${encodeURIComponent(ui.token)}`;\n return base + beforeHash + joiner + query + hash;\n}\n\nexport function uiEntryUrl(ui: NonNullable<SessionSurfaces[\"ui\"]>): string {\n return uiUrl(ui, ui.entry || \"/\");\n}\n\n/** `url` without its `token` query parameter: what may be logged or shown. */\nexport function withoutUiToken(url: string): string {\n const [beforeHash, hash] = splitHash(url);\n const q = beforeHash.indexOf(\"?\");\n if (q < 0) return url;\n const kept = beforeHash\n .slice(q + 1)\n .split(\"&\")\n .filter((pair) => pair !== \"\" && pair.split(\"=\")[0] !== UI_TOKEN_QUERY);\n return (\n beforeHash.slice(0, q) + (kept.length ? `?${kept.join(\"&\")}` : \"\") + hash\n );\n}\n\nfunction splitHash(url: string): [string, string] {\n const h = url.indexOf(\"#\");\n return h < 0 ? [url, \"\"] : [url.slice(0, h), url.slice(h)];\n}\n\n/** The slice of a Playwright `Page` this module drives. */\nexport type BrowserPage = {\n url(): string;\n goto(url: string, opts?: { waitUntil?: \"load\" }): Promise<unknown>;\n click(selector: string): Promise<void>;\n fill(selector: string, value: string): Promise<void>;\n screenshot(opts?: {\n type?: \"png\" | \"jpeg\";\n quality?: number;\n fullPage?: boolean;\n }): Promise<Buffer>;\n innerText(selector: string): Promise<string>;\n content(): Promise<string>;\n goBack(opts?: { waitUntil?: \"load\" }): Promise<unknown>;\n waitForLoadState(state?: \"load\"): Promise<void>;\n waitForTimeout(ms: number): Promise<void>;\n on(\n event: \"request\" | \"requestfinished\" | \"requestfailed\",\n handler: (request: unknown) => void,\n ): unknown;\n title(): Promise<string>;\n keyboard: { press(key: string): Promise<void> };\n mouse: { wheel(dx: number, dy: number): Promise<void> };\n};\n\nexport type BrowserMode = \"auto\" | \"hosted\" | \"local\";\n\n// ── action events ────────────────────────────────────────────────────────────\n\n/** One browser action as the platform ingests it\n * (`POST /world-sessions/{id}/browser-events`). */\nexport type BrowserActionEvent = {\n agentId: string;\n seq: number;\n ts: string;\n action: string;\n args: Record<string, unknown>;\n ok: boolean;\n error: string | null;\n durationMs: number;\n url: string | null;\n title: string | null;\n mode: Exclude<BrowserMode, \"auto\">;\n viewport: { width: number; height: number };\n /** base64 JPEG of the screen after the action; null if it could not be taken. */\n screenshot: string | null;\n};\n\n/** What of an action's arguments may leave the process. Selectors, paths\n * and keys are what a reviewer needs; anything keyed like a credential, or\n * typed into a field whose selector names one, or shaped like a known key,\n * is replaced. Strings are capped, nested values dropped. */\nexport function redactActionArgs(\n action: string,\n args: Record<string, unknown>,\n): Record<string, unknown> {\n const secretField =\n action === \"browser_type\" && SECRET_KEY.test(String(args.selector ?? \"\"));\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(args)) {\n if (value === null || value === undefined) out[key] = null;\n else if (typeof value === \"boolean\" || typeof value === \"number\")\n out[key] = value;\n else if (typeof value === \"string\") {\n if (\n SECRET_KEY.test(key) ||\n SECRET_VALUE.test(value) ||\n (secretField && key === \"text\")\n )\n out[key] = \"[redacted]\";\n else\n out[key] =\n value.length <= EVENT_MAX_STRING\n ? value\n : value.slice(0, EVENT_MAX_STRING) + \"…\";\n } else out[key] = \"[omitted]\";\n }\n return out;\n}\n\n/**\n * Ships browser action events to the platform, off the action's hot path.\n *\n * `post` receives a batch of events (the request body's `events`). Events\n * are numbered here, so ordering survives batching and retries — the\n * platform dedups on `(agentId, seq)`. A batch that keeps failing is dropped\n * with a warning: telemetry must never stall or fail the agent.\n *\n * Numbering is durable across recorders: `nextSeq()` hands out a position\n * within this recorder, and the first send adds the base `resumeFrom`\n * reports — the platform's next free seq for this agent — so an agent id\n * reopened in a later process appends to its timeline instead of colliding\n * with (and being deduplicated against) what it already recorded. The base\n * is fixed once resolved, which keeps retries idempotent.\n */\nexport class BrowserActionRecorder {\n private seq = 0;\n private base: Promise<number> | null = null;\n private queue: BrowserActionEvent[] = [];\n private timer: ReturnType<typeof setTimeout> | null = null;\n private inflight: Promise<void> = Promise.resolve();\n sent = 0;\n dropped = 0;\n\n constructor(\n private readonly post: (events: BrowserActionEvent[]) => Promise<void>,\n readonly agentId: string,\n private readonly opts: {\n /** The platform's next free seq for `agentId`; 0 when not given. */\n resumeFrom?: () => Promise<number>;\n batchSize?: number;\n flushIntervalMs?: number;\n maxRetries?: number;\n sleep?: (ms: number) => Promise<void>;\n warn?: (message: string) => void;\n } = {},\n ) {}\n\n /** This recorder's next position; the wire seq is `resumeFrom() + this`. */\n nextSeq(): number {\n return this.seq++;\n }\n\n private resolveBase(): Promise<number> {\n if (this.base === null) {\n const resolve = this.opts.resumeFrom ?? (async () => 0);\n this.base = resolve().then((n) => {\n if (!Number.isInteger(n) || n < 0)\n throw new Error(\n `browser event base seq must be a non-negative integer, got ${String(n)}`,\n );\n return n;\n });\n // A failed lookup is retried with the batch, not remembered.\n this.base.catch(() => {\n this.base = null;\n });\n }\n return this.base;\n }\n\n record(event: BrowserActionEvent): void {\n this.queue.push(event);\n if (this.queue.length >= (this.opts.batchSize ?? EVENT_BATCH_SIZE)) {\n this.drain();\n } else if (this.timer === null) {\n this.timer = setTimeout(\n () => this.drain(),\n this.opts.flushIntervalMs ?? EVENT_FLUSH_INTERVAL_MS,\n );\n if (typeof this.timer === \"object\" && \"unref\" in this.timer)\n this.timer.unref();\n }\n }\n\n /** Resolve once everything recorded so far has been posted (or dropped). */\n async flush(): Promise<void> {\n this.drain();\n await this.inflight;\n }\n\n async close(): Promise<void> {\n await this.flush();\n }\n\n private drain(): void {\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n if (this.queue.length === 0) return;\n const batch = this.queue;\n this.queue = [];\n this.inflight = this.inflight.then(() => this.send(batch));\n }\n\n private async send(batch: BrowserActionEvent[]): Promise<void> {\n const retries = this.opts.maxRetries ?? EVENT_MAX_RETRIES;\n const sleep =\n this.opts.sleep ??\n ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));\n for (let attempt = 0; attempt < retries; attempt++) {\n try {\n const base = await this.resolveBase();\n await this.post(\n base === 0 ? batch : batch.map((e) => ({ ...e, seq: base + e.seq })),\n );\n this.sent += batch.length;\n return;\n } catch (error) {\n if (attempt + 1 === retries) {\n this.dropped += batch.length;\n (this.opts.warn ?? console.warn)(\n `dropping ${batch.length} browser events after ${attempt + 1} attempts: ${String(error)}`,\n );\n return;\n }\n await sleep(500 * 2 ** attempt);\n }\n }\n }\n}\n\n/**\n * One Playwright page on the session's UI. Thin on purpose — `page` is the\n * real Playwright page for anything this wrapper does not cover.\n */\nexport class WorldBrowser {\n constructor(\n readonly page: BrowserPage,\n readonly ui: SessionSurfaces[\"ui\"] | undefined,\n readonly mode: Exclude<BrowserMode, \"auto\">,\n private readonly teardown: () => Promise<void>,\n readonly viewport: { width: number; height: number } = DEFAULT_VIEWPORT,\n readonly recorder: BrowserActionRecorder | null = null,\n ) {\n page.on(\"request\", () => {\n this.inflight += 1;\n this.lastNetwork = Date.now();\n });\n const done = () => {\n this.inflight = Math.max(0, this.inflight - 1);\n this.lastNetwork = Date.now();\n };\n page.on(\"requestfinished\", done);\n page.on(\"requestfailed\", done);\n }\n\n private inflight = 0;\n private lastNetwork = Date.now();\n\n get agentId(): string | null {\n return this.recorder?.agentId ?? null;\n }\n\n /** Run one action and report it: the event carries what was asked,\n * whether it worked, and the screen after — for failures too, so a\n * reviewer sees what the agent saw when the selector did not match. */\n private async act<T>(\n action: string,\n args: Record<string, unknown>,\n fn: () => Promise<T>,\n ): Promise<T> {\n const recorder = this.recorder;\n if (!recorder) return fn();\n const started = Date.now();\n let ok = true;\n let error: string | null = null;\n try {\n return await fn();\n } catch (err) {\n ok = false;\n error = (\n err instanceof Error ? `${err.name}: ${err.message}` : String(err)\n ).slice(0, 4000);\n throw err;\n } finally {\n recorder.record({\n agentId: recorder.agentId,\n seq: recorder.nextSeq(),\n ts: new Date().toISOString(),\n action,\n args: redactActionArgs(action, args),\n ok,\n error,\n durationMs: Date.now() - started,\n mode: this.mode,\n viewport: { ...this.viewport },\n ...(await this.observeForEvent()),\n });\n }\n }\n\n private async observeForEvent(): Promise<\n Pick<BrowserActionEvent, \"url\" | \"title\" | \"screenshot\">\n > {\n const out: Pick<BrowserActionEvent, \"url\" | \"title\" | \"screenshot\"> = {\n url: null,\n title: null,\n screenshot: null,\n };\n try {\n out.url = this.page.url();\n out.title = await this.page.title();\n const jpeg = await this.page.screenshot({\n type: \"jpeg\",\n quality: EVENT_SCREENSHOT_QUALITY,\n });\n out.screenshot = jpeg.toString(\"base64\");\n } catch {\n // a closed page still gets its event\n }\n return out;\n }\n\n /** Open a UI path (`/customers`), a full URL, or — with no argument — the\n * UI's declared entry page. */\n async goto(pathOrUrl?: string): Promise<string> {\n let target: string;\n if (pathOrUrl === undefined) {\n if (!this.ui)\n throw new WorldSurfaceUnavailable(\n \"ui\",\n \"this session has no UI to navigate to\",\n );\n target = uiEntryUrl(this.ui);\n } else if (/^https?:\\/\\//.test(pathOrUrl)) {\n target = pathOrUrl;\n } else {\n if (!this.ui)\n throw new WorldSurfaceUnavailable(\n \"ui\",\n \"relative paths need a UI surface\",\n );\n target = uiUrl(this.ui, pathOrUrl);\n }\n return this.act(\n \"browser_goto\",\n { path: pathOrUrl ?? null, url: withoutUiToken(target) },\n async () => {\n await this.page.goto(target, { waitUntil: \"load\" });\n await this.settle();\n return this.page.url();\n },\n );\n }\n\n async back(): Promise<string> {\n return this.act(\"browser_back\", {}, async () => {\n await this.page.goBack({ waitUntil: \"load\" });\n await this.settle();\n return this.page.url();\n });\n }\n\n /** Wait for the page to finish reacting to an action. `load` alone is not\n * enough for client-rendered UIs (React et al.): a click returns before the\n * fetch that re-renders the page, so an agent would read stale text.\n * Playwright's `networkidle` is per navigation and resolves at once after\n * the first one, so this tracks requests itself: done when nothing is in\n * flight and the network has been quiet for `SETTLE_QUIET_MS`, bounded so\n * long-polling UIs cannot hang us. */\n private async settle(): Promise<void> {\n await this.page.waitForLoadState(\"load\");\n const deadline = Date.now() + SETTLE_TIMEOUT_MS;\n while (Date.now() < deadline) {\n const quiet = Date.now() - this.lastNetwork >= SETTLE_QUIET_MS;\n if (this.inflight === 0 && quiet) return;\n await this.page.waitForTimeout(SETTLE_POLL_MS);\n }\n }\n\n async click(selector: string): Promise<void> {\n await this.act(\"browser_click\", { selector }, async () => {\n await this.page.click(selector);\n await this.settle();\n });\n }\n\n async type(selector: string, text: string): Promise<void> {\n await this.act(\"browser_type\", { selector, text }, () =>\n this.page.fill(selector, text),\n );\n }\n\n async press(key: string): Promise<void> {\n await this.act(\"browser_press\", { key }, async () => {\n await this.page.keyboard.press(key);\n await this.settle();\n });\n }\n\n async scroll(dy: number): Promise<void> {\n await this.act(\"browser_scroll\", { dy }, () =>\n this.page.mouse.wheel(0, dy),\n );\n }\n\n async screenshot(fullPage = false): Promise<Buffer> {\n return this.page.screenshot({ type: \"png\", fullPage });\n }\n\n async screenshotBase64(fullPage = false): Promise<string> {\n return (await this.screenshot(fullPage)).toString(\"base64\");\n }\n\n async text(selector = \"body\"): Promise<string> {\n return this.page.innerText(selector);\n }\n\n async html(): Promise<string> {\n return this.page.content();\n }\n\n get url(): string {\n return this.page.url();\n }\n\n async title(): Promise<string> {\n return this.page.title();\n }\n\n async close(): Promise<void> {\n try {\n await this.teardown();\n } finally {\n await this.recorder?.close();\n }\n }\n}\n\n/** The Playwright entry points this module needs, so tests can inject a fake. */\nexport type PlaywrightLike = {\n chromium: {\n connect(wsEndpoint: string): Promise<PlaywrightBrowserLike>;\n connectOverCDP(endpointURL: string): Promise<PlaywrightBrowserLike>;\n launch(opts?: { headless?: boolean }): Promise<PlaywrightBrowserLike>;\n };\n};\n\nexport type PlaywrightBrowserLike = {\n newContext(opts?: {\n viewport?: { width: number; height: number };\n }): Promise<{ newPage(): Promise<BrowserPage>; close(): Promise<void> }>;\n close(): Promise<void>;\n};\n\nasync function loadPlaywright(): Promise<PlaywrightLike> {\n try {\n // A string specifier keeps bundlers from resolving the optional peer.\n const name = \"playwright\";\n return (await import(name)) as PlaywrightLike;\n } catch (error) {\n throw new Error(\n \"Driving a world UI needs Playwright: npm install playwright \" +\n \"(and `npx playwright install chromium` for local mode).\",\n { cause: error },\n );\n }\n}\n\nexport function resolveBrowserMode(\n surfaces: SessionSurfaces,\n mode: BrowserMode,\n): Exclude<BrowserMode, \"auto\"> {\n if (!surfaces.ui && !surfaces.browser)\n throw new WorldSurfaceUnavailable(\n \"ui\",\n \"open the session with surfaces: ['ui'] on a world that declares [ui]\",\n );\n const resolved =\n mode === \"auto\" ? (surfaces.browser ? \"hosted\" : \"local\") : mode;\n if (resolved === \"hosted\" && !surfaces.browser)\n throw new WorldSurfaceUnavailable(\n \"browser\",\n \"open the session with surfaces: ['browser'] to get a hosted browser\",\n );\n return resolved;\n}\n\n/** Open a browser on the session's UI in `hosted`, `local` or `auto` mode. */\nexport async function openBrowser(\n surfaces: SessionSurfaces,\n opts: {\n mode?: BrowserMode;\n headless?: boolean;\n playwright?: PlaywrightLike;\n recorder?: BrowserActionRecorder | null;\n } = {},\n): Promise<WorldBrowser> {\n const mode = resolveBrowserMode(surfaces, opts.mode ?? \"auto\");\n const pw = opts.playwright ?? (await loadPlaywright());\n const viewport = surfaces.browser?.viewport ?? DEFAULT_VIEWPORT;\n const browser =\n mode === \"hosted\"\n ? surfaces.browser!.protocol === \"playwright\"\n ? await pw.chromium.connect(surfaces.browser!.wsUrl)\n : await pw.chromium.connectOverCDP(surfaces.browser!.wsUrl)\n : await pw.chromium.launch({ headless: opts.headless ?? true });\n const context = await browser.newContext({ viewport });\n const page = await context.newPage();\n return new WorldBrowser(\n page,\n surfaces.ui,\n mode,\n async () => {\n await context.close();\n await browser.close();\n },\n viewport,\n opts.recorder ?? null,\n );\n}\n\n// ── computer-use tools ───────────────────────────────────────────────────────\n\nexport const COMPUTER_USE_SPECS = [\n {\n name: \"browser_goto\",\n signature: \"browser_goto(path=None)\",\n doc: \"Open a page of the world's UI. `path` is a UI path like /customers, a full URL, or omitted for the entry page. Returns the URL and page text.\",\n },\n {\n name: \"browser_click\",\n signature: \"browser_click(selector)\",\n doc: \"Click an element by Playwright selector (CSS, `text=Refund`, `role=button[name=Save]`). Returns the page text after the click.\",\n },\n {\n name: \"browser_type\",\n signature: \"browser_type(selector, text)\",\n doc: \"Replace the value of an input/textarea found by selector with `text`.\",\n },\n {\n name: \"browser_press\",\n signature: \"browser_press(key)\",\n doc: \"Press a key (Enter, Tab, Escape, ArrowDown, ...). Returns the page text after.\",\n },\n {\n name: \"browser_scroll\",\n signature: \"browser_scroll(dy=600)\",\n doc: \"Scroll the page vertically by `dy` pixels (negative scrolls up).\",\n },\n {\n name: \"browser_screenshot\",\n signature: \"browser_screenshot(full_page=False)\",\n doc: \"Take a PNG screenshot; returns {image_base64, url}.\",\n },\n {\n name: \"browser_read\",\n signature: \"browser_read(selector='body')\",\n doc: \"Return the visible text of an element (default: whole page) plus the URL and title.\",\n },\n {\n name: \"browser_back\",\n signature: \"browser_back()\",\n doc: \"Go back one page in history.\",\n },\n] as const;\n\nconst str = (v: unknown, fallback: string): string =>\n typeof v === \"string\" && v.length > 0 ? v : fallback;\n\n/**\n * The browser as model tools, in the same `WorldToolkit` shape the world's\n * own tools come in — so an agent loop that already dispatches\n * `toolkit().impls` merges `computerUseToolkit(b).impls` and gains a screen\n * without a second dispatch path.\n */\nexport function computerUseToolkit(\n browser: WorldBrowser,\n opts: { maxText?: number } = {},\n): WorldToolkit {\n const maxText = opts.maxText ?? 20_000;\n const observe = async (selector = \"body\") => {\n const text = await browser.text(selector);\n return {\n url: browser.url,\n title: await browser.title(),\n text: text.slice(0, maxText),\n truncated: text.length > maxText,\n };\n };\n\n const impls: WorldToolkit[\"impls\"] = {\n browser_goto: async (a) => {\n await browser.goto(typeof a.path === \"string\" ? a.path : undefined);\n return observe();\n },\n browser_click: async (a) => {\n await browser.click(str(a.selector, \"\"));\n return observe();\n },\n browser_type: async (a) => {\n await browser.type(str(a.selector, \"\"), String(a.text ?? \"\"));\n return { ok: true, url: browser.url };\n },\n browser_press: async (a) => {\n await browser.press(str(a.key, \"Enter\"));\n return observe();\n },\n browser_scroll: async (a) => {\n await browser.scroll(typeof a.dy === \"number\" ? a.dy : 600);\n return { ok: true, url: browser.url };\n },\n browser_screenshot: async (a) => ({\n image_base64: await browser.screenshotBase64(a.full_page === true),\n url: browser.url,\n }),\n browser_read: async (a) => observe(str(a.selector, \"body\")),\n browser_back: async () => {\n await browser.back();\n return observe();\n },\n };\n\n const specs = COMPUTER_USE_SPECS.map((s) => ({ ...s }));\n return {\n schemas: specs.map((spec) => schemaFromSignature(spec)),\n impls,\n specs,\n };\n}\n","import { randomUUID } from \"node:crypto\";\n\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\nimport {\n BrowserActionRecorder,\n SURFACE_KINDS,\n WorldSurfaceUnavailable,\n computerUseToolkit,\n openBrowser,\n uiEntryUrl,\n type BrowserActionEvent,\n type BrowserMode,\n type PlaywrightLike,\n type SessionSurfaces,\n type WorldBrowser,\n type WorldSurfaceKind,\n} from \"./browser\";\nimport type { WorldTaskSummary } from \"./tasks\";\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, { task: \"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 * The task can also be YOURS rather than the bundle's — an instruction, the\n * rows the session starts with and how it is graded, for one end user:\n *\n * const session = await openSession(\"acme-billing@main\", {\n * task: {\n * instruction: \"Mark invoice INV-7 as paid.\",\n * seed: { rows: { invoices: [{ id: \"INV-7\", status: \"open\" }] } },\n * grader: { kind: \"assertions\", checks: [\n * { entity: \"invoices\", where: { id: \"INV-7\", status: \"paid\" } },\n * ] },\n * metadata: { externalUserId: \"u_42\" },\n * },\n * surfaces: [\"api\"],\n * });\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 inputSchema?: Record<string, unknown>;\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\n// ── tasks ────────────────────────────────────────────────────────────────────\n\n/** A JSON scalar: what `where` filters and field predicates compare against. */\nexport type WorldTaskScalar = string | number | boolean | null;\n\n/** The rows a task starts the session with — the `seed()` contract, applied\n * by the host right after it clones the version's snapshot. `append`\n * (default) upserts by primary key onto the base data; `replace` makes the\n * named entities hold exactly these rows. */\nexport type WorldTaskSeed = {\n mode?: \"append\" | \"replace\";\n /** Redaction on the way in: `off` (default) stores the rows as given,\n * `apply` runs the world's `[redact]` policy over them first, `refuse`\n * rejects a row carrying plaintext in a redacted field. */\n redact?: \"off\" | \"apply\" | \"refuse\";\n rows: Record<string, Record<string, unknown>[]>;\n};\n\nexport type WorldTaskFieldOp =\n \"eq\" | \"neq\" | \"in\" | \"gt\" | \"gte\" | \"lt\" | \"lte\" | \"contains\";\n\n/**\n * One declarative check over the session's final rows. `where` selects rows\n * of `entity` by equality (dotted paths reach into nested objects); the\n * assertion says what must hold of the selection:\n *\n * exists (default) / absent at least one row / none\n * count `count` bound on how many\n * all / any `field op value` on every / some selected row\n *\n * A check's `id` names its entry in `rewards`; the task's reward is the\n * weighted share of checks that passed.\n */\nexport type WorldTaskCheck = {\n id?: string;\n weight?: number;\n entity: string;\n where?: Record<string, WorldTaskScalar>;\n assert?: \"exists\" | \"absent\" | \"count\" | \"all\" | \"any\";\n count?: { eq?: number; gte?: number; lte?: number };\n field?: string;\n op?: WorldTaskFieldOp;\n value?: WorldTaskScalar | WorldTaskScalar[];\n};\n\n/** One thing a rubric judge scores in [0, 1]; `id` names its entry in\n * `rewards`, `weight` (default 1) its share of the task's reward. */\nexport type WorldTaskRubricCriterion = {\n id: string;\n description: string;\n weight?: number;\n};\n\n/** A rubric is prose: what a good outcome looks like. The platform (never the\n * host) has a model read the session's final state and its call log against\n * it; the project's default evaluation model judges unless `model` pins one.\n * `grade()` then resolves asynchronously — `pending: true` first, the reward\n * once the judge has answered. */\nexport type WorldTaskRubricGrader = {\n kind: \"rubric\";\n rubric: string;\n criteria?: WorldTaskRubricCriterion[];\n model?: { provider: string; model: string };\n};\n\n/** How a task is graded: checks the host evaluates in-process, a `verify.py`\n * body (state JSON on stdin, last stdout line `{reward, ...}`) run through the\n * host's confined verifier, or a rubric judged by a model on the platform. */\nexport type WorldTaskGrader =\n | { kind: \"assertions\"; checks: WorldTaskCheck[] }\n | { kind: \"python\"; source: string; timeoutSeconds?: number }\n | WorldTaskRubricGrader;\n\n/** A task supplied at open, for one session, instead of a bundled scenario.\n * `instruction` is what the agent is told; without `seed` the session starts\n * on the version's base data, without `grader` `grade()` answers\n * `reward: null`; `tools` is the allow-list of the version's tools the agent\n * may call in this session (unset: all of them; a call outside it is refused\n * and logged); `metadata` is yours (an end-user id, a ticket) and is echoed\n * on the session, never read. Limits: shared/domain/worldTasks.ts. */\nexport type WorldTaskSpec = {\n name?: string;\n instruction: string;\n seed?: WorldTaskSeed;\n grader?: WorldTaskGrader;\n tools?: string[];\n metadata?: Record<string, unknown>;\n /** A MULTI-WORLD task: one session per alias, each on its own world with\n * its own seed, grader and tools (the top-level three are then refused).\n * Brought up together by `openTask` / `gateway worlds task up`; see\n * worlds/taskSessions.ts. */\n worlds?: Record<\n string,\n {\n slug: string;\n /** One of the world's refs; default `main`. */\n ref?: string;\n seed?: WorldTaskSeed;\n grader?: WorldTaskGrader;\n tools?: string[];\n }\n >;\n};\n\n/** A stored task of the project (see worlds/tasks.ts), opened by id; the\n * session runs a copy of one version's spec — the current one by default. */\nexport type WorldTaskIdRef = { id: string; version?: number };\n\n/** What `openSession` takes as the task: a bundled scenario's name, a\n * stored task's `{ id, version? }`, or an inline spec. */\nexport type WorldTaskRef = string | WorldTaskIdRef | WorldTaskSpec;\n\n/** What a session's task is, on every session response. `hash` is the\n * content hash of the spec (inline or stored) — what warm reuse matches on;\n * `id`/`version` name the stored task the session was opened on. */\nexport type WorldSessionTask = {\n source: \"bundled\" | \"inline\" | \"stored\";\n name: string | null;\n hash: string | null;\n id?: string | null;\n version?: number | null;\n metadata: Record<string, unknown>;\n};\n\nexport const isTaskIdRef = (task: WorldTaskRef): task is WorldTaskIdRef =>\n typeof task === \"object\" && task !== null && \"id\" in task;\n\nexport const isTaskSpec = (task: WorldTaskRef): task is WorldTaskSpec =>\n typeof task === \"object\" && task !== null && \"instruction\" in task;\n\n/** The label a task goes by in results: its name, `inline:<hash>` for an\n * unnamed inline task once the platform has hashed it, or the stored task's\n * name (its id until the platform has answered). */\nexport const taskLabel = (\n task: WorldTaskRef,\n info?: WorldSessionTask | null,\n): string => {\n if (typeof task === \"string\") return task;\n if (isTaskIdRef(task)) return info?.name ?? task.id;\n if (task.name) return task.name;\n return info?.hash ? `inline:${info.hash.slice(0, 12)}` : \"inline\";\n};\n\nexport type SeedResult = {\n seeded: number;\n mode: \"append\" | \"replace\";\n entity_counts: Record<string, number>;\n};\n\n/** One row of the session's call log. */\nexport type WorldSessionCall = {\n seq: number;\n kind: string;\n tool: string | null;\n args: unknown;\n result: unknown;\n error: string | null;\n completedAt: string | null;\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 /** Where the task came from and what it is; absent on platforms that\n * predate session tasks, in which case it is derived from `taskName`. */\n task?: WorldSessionTask;\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 /** Where the session answers besides `tools` — see worlds/browser.ts. */\n surfaces?: SessionSurfaces;\n /** Notices about the world's shape (an api bundle is a deprecated layout;\n * schema worlds are the supported shape), with what to run instead. Empty\n * for a schema world; absent on platforms that predate the notice. */\n deprecations?: WorldDeprecation[];\n};\n\n/** One notice a worlds-path answer carries: a deprecated shape or layout\n * and the command that replaces it. A retired shape is refused instead,\n * with the stable message prefix `world_kind_retired:`. */\nexport type WorldDeprecation = {\n code: string;\n message: string;\n replacement: string;\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/** How long a grade the platform's judge finalizes may take: the model's own\n * timeout and retries, plus the worker's queue backoff. Polled slowly. */\nconst JUDGED_GRADE_TIMEOUT_MS = 15 * 60_000;\nconst JUDGED_GRADE_POLL_MS = 2_000;\nconst EXPORT_PAGE = 500;\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\nexport const modelToolName = (name: string): string =>\n name.replace(/[^A-Za-z0-9_-]/g, \"_\").slice(0, 64) || \"tool\";\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 if (spec.inputSchema)\n return {\n type: \"function\",\n function: {\n name: modelToolName(spec.name),\n description: spec.doc ?? spec.name,\n parameters: spec.inputSchema,\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: modelToolName(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 current: WorldSessionState,\n private readonly options: WorldsClientOptions,\n ) {}\n\n /** The task's display name: a bundled scenario's, or the inline spec's\n * `name` (null when the spec was unnamed). Same as `taskName`. */\n get task(): string | null {\n return this.current.taskName;\n }\n\n /** The task's display name: a bundled scenario's, or the inline spec's\n * `name` (null when the spec was unnamed). */\n get taskName(): string | null {\n return this.current.taskName;\n }\n\n /** The platform's notices about the world this session runs on (empty\n * for a schema world). Printed by the CLI on stderr at open. */\n get deprecations(): WorldDeprecation[] {\n return this.current.deprecations ?? [];\n }\n\n /** The task this session runs: bundled scenario, stored task or inline\n * spec, its name, hash and the caller's metadata. */\n get taskInfo(): WorldSessionTask {\n return (\n this.current.task ?? {\n source: \"bundled\",\n name: this.current.taskName,\n hash: null,\n metadata: {},\n }\n );\n }\n\n /** What this task asks for — the bundle's instruction.md, or the inline\n * spec's `instruction`. */\n get instruction(): string | null {\n return this.current.instruction ?? null;\n }\n\n get versionId(): string {\n return this.current.versionId;\n }\n\n /** Whether the session answered ready as of the last state read (the open,\n * a `status()`, or the poll inside `ready()`); no request is made. */\n get isReady(): boolean {\n return this.current.ready;\n }\n\n /** `api` / `ui` / `browser` are present exactly when the world declares\n * them AND the session was opened asking for them. */\n async surfaces(): Promise<SessionSurfaces> {\n if (!this.current.surfaces) await this.status();\n return this.current.surfaces ?? { tools: { kind: \"rendezvous\" } };\n }\n\n /** Base URL of the world's own HTTP API for this session. */\n async api(): Promise<string> {\n const { api } = await this.surfaces();\n if (!api)\n throw new WorldSurfaceUnavailable(\n \"api\",\n \"open the session with surfaces: ['api'] on an api-type world\",\n );\n return api.url;\n }\n\n /** Headers every request to `api()` needs. A World Host session gates its\n * api surface on a per-session token; a pod or hosted twin answers with the\n * world's own declared auth and this is `{}`. */\n async apiHeaders(): Promise<Record<string, string>> {\n const { api } = await this.surfaces();\n return api?.token ? { Authorization: `Bearer ${api.token}` } : {};\n }\n\n /** URL of the world's UI entry page for this session. */\n async ui(): Promise<string> {\n const { ui } = await this.surfaces();\n if (!ui)\n throw new WorldSurfaceUnavailable(\n \"ui\",\n \"open the session with surfaces: ['ui'] on a world that declares [ui]\",\n );\n return uiEntryUrl(ui);\n }\n\n /** A Playwright browser on this session's UI: `hosted` drives the one the\n * platform runs next to the world, `local` launches one here, `auto`\n * prefers hosted. Call `close()` when done.\n *\n * Every action is reported to the platform under `agentId` (default:\n * `GATEWAY_AGENT_ID` or a fresh `agent-<hex>`) so the session page shows\n * this agent's own timeline — several agents may share one session and\n * one hosted browser. `record: false` opts out. */\n async browser(\n opts: {\n mode?: BrowserMode;\n headless?: boolean;\n playwright?: PlaywrightLike;\n agentId?: string;\n record?: boolean;\n } = {},\n ): Promise<WorldBrowser> {\n const { agentId, record = true, ...rest } = opts;\n return openBrowser(await this.surfaces(), {\n ...rest,\n recorder: record ? this.browserRecorder(agentId) : null,\n });\n }\n\n /** The reporter `browser()` uses; exposed for a page you drive yourself. */\n browserRecorder(agentId?: string): BrowserActionRecorder {\n const path = `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/browser-events`;\n const id =\n agentId ??\n process.env.GATEWAY_AGENT_ID ??\n `agent-${randomUUID().replace(/-/g, \"\").slice(0, 8)}`;\n return new BrowserActionRecorder(\n async (events: BrowserActionEvent[]) => {\n await apiRequest(this.options, \"POST\", path, { events });\n },\n id,\n {\n // Continue this agent's timeline where the platform has it, so the\n // same id reopened later never re-numbers from zero.\n resumeFrom: async () => {\n const summary = await apiRequest<{\n agents: { agentId: string; nextSeq: number }[];\n }>(this.options, \"GET\", path);\n return summary.agents.find((a) => a.agentId === id)?.nextSeq ?? 0;\n },\n },\n );\n }\n\n /** Browser actions as model tools, in the same shape as `toolkit()`. */\n computerUseTools(browser: WorldBrowser): WorldToolkit {\n return computerUseToolkit(browser);\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.current = {\n instruction: this.current.instruction,\n tools: this.current.tools,\n surfaces: this.current.surfaces,\n task: this.current.task,\n ...fresh,\n };\n return this.current;\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: {\n kind?: \"call\" | \"grade\" | \"reset\" | \"state\" | \"seed\" | \"close\";\n tool?: string;\n args?: unknown;\n /** Grade only: the agent's report, for a rubric judge. */\n report?: string;\n },\n timeoutMs?: number,\n ): Promise<unknown> {\n const enqueued = await apiRequest<{\n callId: string;\n seq: number;\n /** The platform's worker finalizes this call (a rubric grade). */\n pending?: boolean;\n }>(\n this.options,\n \"POST\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/calls`,\n body,\n );\n const { callId } = enqueued;\n const judged = enqueued.pending === true;\n const budgetMs =\n timeoutMs ?? (judged ? JUDGED_GRADE_TIMEOUT_MS : CALL_TIMEOUT_MS);\n const pollMs = judged ? JUDGED_GRADE_POLL_MS : CALL_POLL_MS;\n const deadline = Date.now() + budgetMs;\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 judged\n ? `Grade ${callId} still ${call.state} after ${Math.round(budgetMs / 1000)}s — the judge has not answered; the platform finalizes the call on its own, read it back with export().`\n : `Call ${callId} still ${call.state} after ${Math.round(budgetMs / 1000)}s — the container may have died.`,\n );\n await sleep(pollMs);\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.current.tools;\n if (!specs) specs = (await this.status()).tools ?? [];\n const impls: WorldToolkit[\"impls\"] = Object.create(null);\n for (const spec of specs) {\n const alias = modelToolName(spec.name);\n if (Object.hasOwn(impls, alias))\n throw new WorldSessionCallError(`Model tool name collision: ${alias}`);\n impls[alias] = (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. Graders answer\n * in one of two shapes: the scalar with named rewards beside it\n * (`{reward, check_a, check_b}`, a task's own `grade.py`), or the named\n * rewards nested under `rewards` (the api, mock-tools and World Host\n * runners). Both land in `rewards`.\n *\n * A rubric grade is finalized by the platform's judge, not the container:\n * the platform answers the enqueue with `pending: true`, and this waits on\n * the judge's budget (15 min) instead of a call's. `timeoutMs` overrides\n * either. `report` is the agent's own account of what it did and found,\n * handed to the judge as its claim beside the evidence (the state and the\n * calls); assertions and python graders ignore it. */\n async grade(\n opts: { timeoutMs?: number; report?: string } = {},\n ): Promise<GradeResult> {\n const raw = (await this.exchange(\n opts.report !== undefined\n ? { kind: \"grade\", report: opts.report }\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 const nested = record.rewards;\n if (nested && typeof nested === \"object\") {\n for (const [key, value] of Object.entries(nested)) {\n if (typeof value === \"number\") rewards[key] = value;\n }\n }\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 * Put rows into the LIVE world through its contract, in one batch:\n * `append` (default) upserts by primary key, `replace` makes the named\n * entities hold exactly these rows. Atomic — a refused row leaves the\n * session unchanged and the error names the entity, row and field.\n */\n async seed(\n rows: Record<string, Record<string, unknown>[]>,\n opts: {\n mode?: \"append\" | \"replace\";\n /** `apply` runs the world's `[redact]` policy over the rows first;\n * `refuse` rejects plaintext in a redacted field; default `off`. */\n redact?: \"off\" | \"apply\" | \"refuse\";\n timeoutMs?: number;\n } = {},\n ): Promise<SeedResult> {\n const mode = opts.mode ?? \"append\";\n const redact = opts.redact ?? \"off\";\n return (await this.exchange(\n {\n kind: \"seed\",\n args: { mode, rows, ...(redact !== \"off\" ? { redact } : {}) },\n },\n opts.timeoutMs,\n )) as SeedResult;\n }\n\n /** Every entity's rows as the world holds them now — the same dump a\n * grader reads. The shape is the world runtime's: a schema world answers\n * `{<entity>: {<key>: row}, snapshot}`, a mock-tools world\n * `{entities: {<entity>: [row]}}`. */\n async state(opts: { timeoutMs?: number } = {}): Promise<unknown> {\n return this.exchange({ kind: \"state\" }, opts.timeoutMs);\n }\n\n /** Back to the opening state: the version's data plus the bundled\n * scenario's or the inline task's seed. Rows written since are gone; the\n * call log stays. */\n async reset(opts: { timeoutMs?: number } = {}): Promise<void> {\n await this.exchange({ kind: \"reset\" }, opts.timeoutMs);\n }\n\n /** The session's call log, oldest first: every tool call, seed, reset,\n * grade with its result — the record of the episode. */\n async export(): Promise<WorldSessionCall[]> {\n const calls: WorldSessionCall[] = [];\n let cursor: string | undefined;\n do {\n const params = new URLSearchParams({ limit: String(EXPORT_PAGE) });\n if (cursor) params.set(\"cursor\", cursor);\n const page = await apiRequest<{\n calls: Record<string, unknown>[];\n nextCursor?: string | null;\n }>(\n this.options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/calls?${params.toString()}`,\n );\n for (const call of page.calls) {\n calls.push({\n seq: Number(call.seq),\n kind: String(call.kind ?? \"call\"),\n tool: typeof call.tool === \"string\" ? call.tool : null,\n args: call.args ?? null,\n result: call.result ?? null,\n error: typeof call.error === \"string\" ? call.error : null,\n completedAt:\n typeof call.completedAt === \"string\" ? call.completedAt : null,\n });\n }\n cursor = page.nextCursor ?? undefined;\n } while (cursor);\n return calls;\n }\n\n /**\n * Promote this session's inline task into a stored task of the project\n * (version 1, pinned to the session's world unless `world` says otherwise),\n * so a task written for one end user can be reused and its grades\n * compared. The session then records the new task's id. A session on a\n * bundled task has nothing to save; one on a stored task is already saved.\n */\n async saveTask(\n opts: { name?: string; world?: string | null; message?: string } = {},\n ): Promise<WorldTaskSummary> {\n const task = await apiRequest<WorldTaskSummary>(\n this.options,\n \"POST\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/task`,\n {\n ...(opts.name !== undefined ? { name: opts.name } : {}),\n ...(opts.world !== undefined ? { world: opts.world } : {}),\n ...(opts.message !== undefined ? { message: opts.message } : {}),\n },\n );\n this.current = {\n ...this.current,\n taskName: task.name,\n task: {\n ...this.taskInfo,\n source: \"stored\",\n name: task.name,\n id: task.id,\n version: task.version,\n },\n };\n return task;\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\nexport type OpenSessionOptions = {\n versionId?: string;\n reuseWarm?: boolean;\n /** More than `tools`: `[\"api\"]`, `[\"ui\"]`, `[\"browser\"]`. The platform\n * refuses (HTTP 400) rather than quietly serving less than asked. */\n surfaces?: WorldSurfaceKind[];\n options?: WorldsClientOptions;\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 *\n * `task` is a bundled scenario's name, a stored task's `{ id, version? }`\n * or an inline `WorldTaskSpec` (the latter two need a host engine world — the\n * platform answers 400 for a pod world). The older positional form\n * `openSession(slug, \"task-name\", opts)` still works.\n */\nexport async function openSession(\n slugOrRef: string,\n task: OpenSessionOptions & { task: WorldTaskRef },\n): Promise<WorldSession>;\nexport async function openSession(\n slugOrRef: string,\n task: WorldTaskRef,\n opts?: OpenSessionOptions,\n): Promise<WorldSession>;\nexport async function openSession(\n slugOrRef: string,\n taskOrOpts: WorldTaskRef | (OpenSessionOptions & { task: WorldTaskRef }),\n positionalOpts: OpenSessionOptions = {},\n): Promise<WorldSession> {\n const { task, ...opts } =\n typeof taskOrOpts === \"object\" && \"task\" in taskOrOpts\n ? taskOrOpts\n : { task: taskOrOpts as WorldTaskRef, ...positionalOpts };\n if (\n task === undefined ||\n task === null ||\n (typeof task === \"string\" && !task) ||\n (isTaskIdRef(task) && !task.id) ||\n (isTaskSpec(task) && !task.instruction) ||\n (typeof task === \"object\" && !isTaskIdRef(task) && !isTaskSpec(task))\n )\n throw new Error(\n \"openSession needs a task: a bundled task name, a stored task { id, version? } or { instruction, seed?, grader?, metadata? }\",\n );\n const options = opts.options ?? {};\n const unknown = (opts.surfaces ?? []).filter(\n (s) => !(SURFACE_KINDS as readonly string[]).includes(s),\n );\n if (unknown.length)\n throw new Error(\n `Unknown world surfaces: ${unknown.join(\", \")}; choose from ${SURFACE_KINDS.join(\", \")}`,\n );\n const at = slugOrRef.indexOf(\"@\");\n const slug = at === -1 ? slugOrRef : slugOrRef.slice(0, at);\n const ref = at === -1 ? \"\" : slugOrRef.slice(at + 1);\n const state = await apiRequest<WorldSessionState & { reusedWarm: boolean }>(\n options,\n \"POST\",\n \"/api/public/world-sessions\",\n {\n ...(opts.versionId\n ? { versionId: opts.versionId }\n : { slug, ...(ref && { ref }) }),\n task,\n ...(opts.reuseWarm === undefined ? {} : { reuseWarm: opts.reuseWarm }),\n ...(opts.surfaces?.length ? { surfaces: opts.surfaces } : {}),\n },\n );\n return new WorldSession(state.sessionId, state, options);\n}\n\n// ── running many tasks at once ───────────────────────────────────────────────\n\nexport type SessionRunResult = {\n /** The task's name, or `inline:<hash>` for an unnamed inline task. */\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 /** Tasks that never graded: the session did not open or become ready, the\n * agent threw, or grading failed. Any failure fails the run — a 0 an agent\n * earned and a session that never opened are not the same result. */\n failed: number;\n /** True when no task failed and `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 /** Bundled task names, stored task refs and/or inline task specs\n * (default: every bundled task in the world). */\n tasks?: WorldTaskRef[];\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 /** The task's label — see `SessionRunResult.task`. */\n task: string;\n /** The task as it was given: a bundled name, a stored ref or the\n * inline spec. */\n taskRef: WorldTaskRef;\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 — and a\n // caller who pinned a version gets THAT version's task list, not the\n // branch tip's.\n const { openWorld, openWorldVersion } = await import(\"./index\");\n const world = versionId\n ? await openWorldVersion(opts.world.split(\"@\", 1)[0]!, versionId, options)\n : 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 taskRef = tasks![next++];\n let task = taskLabel(taskRef);\n let session: WorldSession | null = null;\n try {\n session = await openSession(opts.world, {\n task: taskRef,\n versionId,\n options,\n });\n task = taskLabel(taskRef, session.taskInfo);\n await session.ready();\n const toolkit = await session.toolkit();\n await opts.agent({\n session,\n toolkit,\n instruction:\n session.instruction ??\n (isTaskSpec(taskRef) ? taskRef.instruction : task),\n task,\n taskRef,\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 const failed = results.filter((r) => r.error).length;\n return {\n results: results.sort((a, b) => a.task.localeCompare(b.task)),\n mean,\n failed,\n passed:\n failed === 0 && (opts.failUnder === undefined || mean >= opts.failUnder),\n };\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\nimport type { WorldTaskSpec } from \"./session\";\n\n/**\n * STORED WORLD TASKS: a task spec kept by the project, outside any bundle.\n *\n * An inline task (`openSession(world, { task: { instruction, … } })`) belongs\n * to one session. A stored task is the same spec as a named, versioned\n * project resource: create it once, open as many sessions on it as you like\n * with `{ task: { id } }`, and every grade attributes back to the task and\n * its version. Updating the spec never rewrites history — it appends a\n * version, and a session opened on `{ id, version: 2 }` keeps running v2\n * after v3 exists.\n *\n * const task = await createTask({\n * name: \"refund-late-invoice\",\n * world: \"acme-billing\",\n * spec: { instruction: \"…\", seed: {…}, grader: {…} },\n * });\n * const session = await openSession(\"acme-billing\", { task: { id: task.id } });\n *\n * Tasks are project-scoped: another project's task id is not found (404),\n * never forbidden. `world` pins a task to one world's slug (validated against\n * that world's contract); null leaves it usable with any world.\n */\n\nexport type WorldTaskSummary = {\n id: string;\n name: string;\n world: string | null;\n version: number;\n hash: string;\n spec: WorldTaskSpec;\n createdAt: string;\n updatedAt: string;\n createdBy: string;\n updatedBy: string;\n /** On create, when the task is pinned to a world of a deprecated shape (an\n * api bundle): what to run instead. A retired shape is refused. */\n deprecations?: { code: string; message: string; replacement: string }[];\n};\n\nexport type WorldTaskVersionSummary = {\n version: number;\n hash: string;\n createdAt: string;\n createdBy: string;\n message: string | null;\n};\n\nexport type WorldTaskDetail = WorldTaskSummary & {\n versions: WorldTaskVersionSummary[];\n};\n\nexport type WorldTaskPage = {\n tasks: WorldTaskSummary[];\n meta: { page: number; limit: number; totalItems: number; totalPages: number };\n};\n\nexport type WorldTaskWorldValidation = {\n slug: string;\n ref: string;\n versionId: string;\n ok: boolean;\n checked: \"entities\" | \"none\";\n problems: string[];\n entities: string[] | null;\n};\n\nexport type WorldTaskValidation = {\n taskId: string;\n version: number;\n /** The world version the task was checked against; null for a task with\n * `worlds`, whose versions are per alias under `worlds`. */\n versionId: string | null;\n ok: boolean;\n /** `entities` when the world's contract was read and every seed and check\n * entity was matched against it; `none` when the version has no contract\n * to check (a mock-tools world), in which case `ok` says only that the\n * version exists and is READY; `worlds` for a multi-world task, checked\n * alias by alias against the ref each names. */\n checked: \"entities\" | \"none\" | \"worlds\";\n /** For a multi-world task each problem is prefixed with its alias. */\n problems: string[];\n entities: string[] | null;\n worlds?: Record<string, WorldTaskWorldValidation>;\n};\n\nconst TASKS = \"/api/public/world-tasks\";\nconst taskRoute = (id: string) => `${TASKS}/${encodeURIComponent(id)}`;\n\nconst compact = (body: Record<string, unknown>) =>\n Object.fromEntries(Object.entries(body).filter(([, v]) => v !== undefined));\n\n/** Store a task. `name` defaults to `spec.name`; one of the two is needed. */\nexport async function createTask(\n input: {\n spec: WorldTaskSpec;\n name?: string;\n world?: string | null;\n message?: string;\n },\n options: WorldsClientOptions = {},\n): Promise<WorldTaskSummary> {\n return apiRequest<WorldTaskSummary>(\n options,\n \"POST\",\n TASKS,\n compact({\n spec: input.spec,\n name: input.name,\n world: input.world,\n message: input.message,\n }),\n );\n}\n\n/** Change a task. A new `spec` becomes the next version (the old ones stay\n * readable and openable); `name` and `world` change in place. */\nexport async function updateTask(\n taskId: string,\n input: {\n spec?: WorldTaskSpec;\n name?: string;\n world?: string | null;\n message?: string;\n },\n options: WorldsClientOptions = {},\n): Promise<WorldTaskSummary> {\n if (\n input.spec === undefined &&\n input.name === undefined &&\n input.world === undefined\n )\n throw new Error(\"updateTask: nothing to update — pass spec, name or world\");\n return apiRequest<WorldTaskSummary>(\n options,\n \"PATCH\",\n taskRoute(taskId),\n compact({\n spec: input.spec,\n name: input.name,\n world: input.world,\n message: input.message,\n }),\n );\n}\n\n/** The project's tasks, newest change first. `world` keeps only tasks\n * pinned to that slug; `metadata` keeps tasks whose spec metadata carries\n * every given key/value (`{ externalUserId: \"u_42\" }`). */\nexport async function listTasks(\n filter: {\n world?: string;\n metadata?: Record<string, string>;\n page?: number;\n limit?: number;\n } = {},\n options: WorldsClientOptions = {},\n): Promise<WorldTaskPage> {\n const params = new URLSearchParams();\n if (filter.world) params.set(\"world\", filter.world);\n if (filter.page !== undefined) params.set(\"page\", String(filter.page));\n if (filter.limit !== undefined) params.set(\"limit\", String(filter.limit));\n for (const [key, value] of Object.entries(filter.metadata ?? {}))\n params.set(`metadata.${key}`, value);\n const query = params.toString();\n return apiRequest<WorldTaskPage>(\n options,\n \"GET\",\n query ? `${TASKS}?${query}` : TASKS,\n );\n}\n\n/** One task with its version history; `version` reads that version's spec\n * instead of the current one. */\nexport async function getTask(\n taskId: string,\n opts: { version?: number } = {},\n options: WorldsClientOptions = {},\n): Promise<WorldTaskDetail> {\n const query =\n opts.version === undefined ? \"\" : `?version=${String(opts.version)}`;\n return apiRequest<WorldTaskDetail>(\n options,\n \"GET\",\n `${taskRoute(taskId)}${query}`,\n );\n}\n\n/** Remove a task and every version. Sessions already opened on it keep\n * their copy of the spec. */\nexport async function deleteTask(\n taskId: string,\n options: WorldsClientOptions = {},\n): Promise<{ id: string; name: string }> {\n return apiRequest(options, \"DELETE\", taskRoute(taskId));\n}\n\n/** Check a task against a world version without opening a session: every\n * seed entity and every check's entity must exist in the world's contract.\n * `slug` checks against that world's head, `versionId` against an exact\n * version, neither against the task's own `world` pin. */\nexport async function validateTask(\n taskId: string,\n target: { version?: number; slug?: string; versionId?: string } = {},\n options: WorldsClientOptions = {},\n): Promise<WorldTaskValidation> {\n return apiRequest<WorldTaskValidation>(\n options,\n \"POST\",\n `${taskRoute(taskId)}/validate`,\n compact({\n version: target.version,\n slug: target.slug,\n versionId: target.versionId,\n }),\n );\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\nimport {\n surfaceKinds,\n uiEntryUrl,\n type SessionSurfaces,\n type WorldSurfaceKind,\n} from \"./browser\";\nimport {\n WorldSession,\n attachSession,\n isTaskIdRef,\n type GradeResult,\n type WorldSessionCall,\n type WorldSessionState,\n type WorldTaskIdRef,\n type WorldTaskSpec,\n} from \"./session\";\n\n/**\n * TASKS THAT NEED SEVERAL WORLDS.\n *\n * A task whose spec names `worlds` is one instruction over N hosted worlds\n * — an investigation that reads a breach feed, a threat-intel API and a\n * ticketing system, say. `openTask` brings every one of them up in ONE call\n * and hands back the sessions keyed by the aliases the spec chose:\n *\n * const task = await openTask({ id: \"wt_1\" }, { surfaces: [\"api\"] });\n * await task.ready();\n * const spycloud = task.sessions.spycloud; // a WorldSession\n * await myAgent(task.instruction, task.sessions);\n * const grade = await task.grade(); // per world + aggregate\n * await task.close();\n *\n * The platform opens the sessions (POST /world-task-sessions) and refuses\n * a partial bring-up: if one world fails, the ones that opened are closed\n * and the error names every alias that failed. Everything after — ready,\n * grade, export, close — is one `WorldSession` call per world, fanned out\n * here. `manifest()` is the record `gateway worlds task up` prints, and\n * `attachTask` rebuilds a `TaskSessions` from a stored task's live sessions.\n */\n\nconst TASK_SESSIONS = \"/api/public/world-task-sessions\";\n\n/** The per-world entry of a `WorldTaskSpec.worlds` table. */\nexport type WorldTaskWorld = {\n slug: string;\n ref?: string;\n seed?: WorldTaskSpec[\"seed\"];\n grader?: WorldTaskSpec[\"grader\"];\n tools?: string[];\n};\n\n/** One world's session as the platform answered it at up. */\nexport type TaskWorldSessionState = WorldSessionState & {\n alias: string;\n slug: string;\n ref: string;\n reusedWarm: boolean;\n};\n\n/** What `POST /world-task-sessions` answers. */\nexport type TaskSessionsResponse = {\n taskId: string | null;\n taskVersion: number | null;\n name: string | null;\n hash: string;\n instruction: string;\n sessions: Record<string, TaskWorldSessionState>;\n};\n\n/** One world in the manifest: where it answers, in the shape\n * `gateway worlds session open` prints for a single session. */\nexport type TaskManifestSession = {\n slug: string;\n ref: string | null;\n versionId: string;\n sessionId: string;\n ready: boolean;\n state: string;\n surfaces: WorldSurfaceKind[];\n api?: { url: string; token?: string };\n ui?: { url: string; entry: string; apiPath: string | null };\n browser?: { wsUrl: string; viewport?: unknown };\n};\n\n/** The manifest: every session of the task, keyed by alias. The file\n * `task up --out` writes and `task down|status|grade|export` read. */\nexport type TaskManifest = {\n taskId: string | null;\n taskVersion: number | null;\n name: string | null;\n instruction: string | null;\n sessions: Record<string, TaskManifestSession>;\n};\n\n/** A stored task's live sessions, as `GET /world-task-sessions` lists them. */\nexport type LiveTaskSession = {\n alias: string | null;\n slug: string | null;\n sessionId: string;\n state: string;\n ready: boolean;\n versionId: string;\n taskVersion: number | null;\n createdAt: string;\n};\n\n/** The task's grade: every world's own `GradeResult` under its alias, and\n * the aggregate. `reward` is the mean of the worlds' numeric rewards — null\n * when no world answered one (no grader anywhere, or a judge still\n * pending); a world with no reward is listed under `ungraded`, never\n * counted as 0. `rewards` flattens each world's named rewards as\n * `<alias>.<key>` beside `<alias>` for the world's own reward. */\nexport type TaskGrade = {\n reward: number | null;\n rewards: Record<string, number>;\n worlds: Record<string, GradeResult>;\n ungraded: string[];\n};\n\n/** Every world's call log, keyed by alias. */\nexport type TaskExport = Record<string, WorldSessionCall[]>;\n\nconst manifestSession = (\n s: SessionSurfaces,\n state: {\n sessionId: string;\n ready: boolean;\n state: string;\n versionId: string;\n },\n world: { slug: string; ref: string | null },\n): TaskManifestSession => ({\n slug: world.slug,\n ref: world.ref,\n versionId: state.versionId,\n sessionId: state.sessionId,\n ready: state.ready,\n state: state.state,\n surfaces: surfaceKinds(s),\n ...(s.api\n ? {\n api: { url: s.api.url, ...(s.api.token ? { token: s.api.token } : {}) },\n }\n : {}),\n ...(s.ui\n ? {\n ui: {\n url: s.ui.url,\n entry: uiEntryUrl(s.ui),\n apiPath: s.ui.apiPath ?? null,\n },\n }\n : {}),\n ...(s.browser\n ? { browser: { wsUrl: s.browser.wsUrl, viewport: s.browser.viewport } }\n : {}),\n});\n\n/** Combine per-world grades into the task's. Pure, so the CLI and the tests\n * share it with `TaskSessions.grade()`. */\nexport function aggregateTaskGrade(\n worlds: Record<string, GradeResult>,\n): TaskGrade {\n const rewards: Record<string, number> = {};\n const ungraded: string[] = [];\n const graded: number[] = [];\n for (const [alias, grade] of Object.entries(worlds)) {\n if (typeof grade.reward === \"number\") {\n rewards[alias] = grade.reward;\n graded.push(grade.reward);\n } else ungraded.push(alias);\n for (const [key, value] of Object.entries(grade.rewards))\n rewards[`${alias}.${key}`] = value;\n }\n const reward =\n graded.length > 0\n ? graded.reduce((a, b) => a + b, 0) / graded.length\n : null;\n return { reward, rewards, worlds, ungraded };\n}\n\nexport class TaskSessions {\n constructor(\n /** The stored task's id, or null for a task given as a spec. */\n readonly taskId: string | null,\n readonly taskVersion: number | null,\n readonly name: string | null,\n /** The instruction every world's session shares. */\n readonly instruction: string | null,\n /** One live session per alias, in the spec's order. */\n readonly sessions: Record<string, WorldSession>,\n private readonly worlds: Record<\n string,\n { slug: string; ref: string | null }\n >,\n /** The spec's content hash — set only by `openTask` (the raw platform\n * response carries it); null for a `TaskSessions` rebuilt with\n * `attachManifest`/`attachTask`, which have no spec to hash. */\n readonly hash: string | null = null,\n ) {}\n\n /** This alias's `{slug, ref}` as recorded at open/attach — the world a\n * `TaskRun` filing needs to name, without exposing the whole map. */\n worldRef(alias: string): { slug: string; ref: string | null } {\n return this.worlds[alias] ?? { slug: \"\", ref: null };\n }\n\n /** The aliases, in the spec's order. */\n get aliases(): string[] {\n return Object.keys(this.sessions);\n }\n\n /** The alias's session, or a clear error naming the aliases there are. */\n session(alias: string): WorldSession {\n const session = this.sessions[alias];\n if (!session)\n throw new Error(\n `task has no world '${alias}'; its worlds are ${this.aliases.join(\", \")}`,\n );\n return session;\n }\n\n private async each<T>(\n fn: (session: WorldSession, alias: string) => Promise<T>,\n ): Promise<Record<string, T>> {\n const entries = await Promise.all(\n Object.entries(this.sessions).map(\n async ([alias, session]) => [alias, await fn(session, alias)] as const,\n ),\n );\n return Object.fromEntries(entries);\n }\n\n /** Wait until every world answers ready. A world that never does throws\n * `WorldSessionTimeout` naming it; the others are left up. */\n async ready(opts: { timeoutMs?: number } = {}): Promise<void> {\n await this.each((session) => session.ready(opts));\n }\n\n /** Every world's current state, keyed by alias. */\n async status(): Promise<Record<string, WorldSessionState>> {\n return this.each((session) => session.status());\n }\n\n /** The manifest: where every world answers, keyed by alias. */\n async manifest(): Promise<TaskManifest> {\n const sessions = await this.each(async (session, alias) =>\n manifestSession(\n await session.surfaces(),\n {\n sessionId: session.sessionId,\n ready: session.isReady,\n state: (await session.status()).state,\n versionId: session.versionId,\n },\n this.worlds[alias]!,\n ),\n );\n return {\n taskId: this.taskId,\n taskVersion: this.taskVersion,\n name: this.name,\n instruction: this.instruction,\n sessions,\n };\n }\n\n /** Grade every world and aggregate — see `TaskGrade`. One `report` (the\n * agent's own account of the whole investigation) goes to every world's\n * judge; a world graded by assertions or python ignores it. */\n async grade(\n opts: { timeoutMs?: number; report?: string } = {},\n ): Promise<TaskGrade> {\n return aggregateTaskGrade(\n await this.each((session) => session.grade(opts)),\n );\n }\n\n /** Every world's call log, keyed by alias. */\n async export(): Promise<TaskExport> {\n return this.each((session) => session.export());\n }\n\n /** Close every world. Closes are attempted for all of them even when one\n * fails; the error then names every world that did not close. */\n async close(\n opts: { keepWarm?: boolean } = {},\n ): Promise<Record<string, { state: string }>> {\n const settled = await Promise.allSettled(\n Object.entries(this.sessions).map(\n async ([alias, session]) => [alias, await session.close(opts)] as const,\n ),\n );\n const failed: string[] = [];\n const closed: Record<string, { state: string }> = {};\n settled.forEach((result, i) => {\n const alias = this.aliases[i]!;\n if (result.status === \"fulfilled\") closed[alias] = result.value[1];\n else\n failed.push(\n `${alias}: ${result.reason instanceof Error ? result.reason.message : String(result.reason)}`,\n );\n });\n if (failed.length > 0)\n throw new Error(\n `${failed.length} of ${this.aliases.length} worlds did not close — ${failed.join(\"; \")}`,\n );\n return closed;\n }\n}\n\nexport type OpenTaskOptions = {\n /** With a task id: open that version of the task instead of the current. */\n version?: number;\n /** Asked of every world; the platform refuses (400) rather than serving\n * fewer surfaces than asked, and then nothing is up. */\n surfaces?: WorldSurfaceKind[];\n reuseWarm?: boolean;\n options?: WorldsClientOptions;\n};\n\nfunction fromResponse(\n answer: TaskSessionsResponse,\n options: WorldsClientOptions,\n): TaskSessions {\n const sessions: Record<string, WorldSession> = {};\n const worlds: Record<string, { slug: string; ref: string | null }> = {};\n for (const [alias, state] of Object.entries(answer.sessions)) {\n sessions[alias] = new WorldSession(state.sessionId, state, options);\n worlds[alias] = { slug: state.slug, ref: state.ref };\n }\n return new TaskSessions(\n answer.taskId,\n answer.taskVersion,\n answer.name,\n answer.instruction,\n sessions,\n worlds,\n answer.hash ?? null,\n );\n}\n\n/**\n * Bring every world of a task up. `ref` is a stored task's id, its\n * `{ id, version? }`, or the spec itself (one with `worlds`). Returns as\n * soon as the platform has opened every session — `ready()` waits for the\n * containers. All or nothing: a world that fails to open closes the rest\n * and the error names it.\n */\nexport async function openTask(\n ref: string | WorldTaskIdRef | WorldTaskSpec,\n opts: OpenTaskOptions = {},\n): Promise<TaskSessions> {\n const options = opts.options ?? {};\n const task: WorldTaskIdRef | WorldTaskSpec =\n typeof ref === \"string\"\n ? {\n id: ref,\n ...(opts.version !== undefined ? { version: opts.version } : {}),\n }\n : isTaskIdRef(ref) && opts.version !== undefined\n ? { ...ref, version: opts.version }\n : ref;\n if (isTaskIdRef(task) ? !task.id : !task.instruction)\n throw new Error(\n \"openTask needs a task: a stored task id, { id, version? } or a spec with worlds\",\n );\n if (!isTaskIdRef(task) && !task.worlds)\n throw new Error(\n \"openTask needs a spec that names its worlds; a single-world spec opens with openSession\",\n );\n const answer = await apiRequest<TaskSessionsResponse>(\n options,\n \"POST\",\n TASK_SESSIONS,\n {\n task,\n ...(opts.reuseWarm === undefined ? {} : { reuseWarm: opts.reuseWarm }),\n ...(opts.surfaces?.length ? { surfaces: opts.surfaces } : {}),\n },\n );\n return fromResponse(answer, options);\n}\n\n/** A stored task's live sessions, newest first — every session the project\n * has opened on it that is not stopped or failed. */\nexport async function listTaskSessions(\n taskId: string,\n options: WorldsClientOptions = {},\n): Promise<LiveTaskSession[]> {\n const answer = await apiRequest<{\n taskId: string;\n sessions: LiveTaskSession[];\n }>(options, \"GET\", `${TASK_SESSIONS}?taskId=${encodeURIComponent(taskId)}`);\n return answer.sessions;\n}\n\n/**\n * Attach to the sessions a stored task has up — after a crash, or from a\n * process other than the one that ran `up`. Refuses when an alias is live\n * more than once (two `up`s of the same task): which set is meant is not\n * knowable, so pass the manifest (`attachManifest`) or close the extras.\n */\nexport async function attachTask(\n taskId: string,\n options: WorldsClientOptions = {},\n): Promise<TaskSessions> {\n const live = await listTaskSessions(taskId, options);\n if (live.length === 0)\n throw new Error(\n `task ${taskId} has no live sessions; run \\`task up\\` first`,\n );\n const byAlias = new Map<string, LiveTaskSession[]>();\n for (const session of live) {\n const alias = session.alias ?? session.sessionId;\n byAlias.set(alias, [...(byAlias.get(alias) ?? []), session]);\n }\n const doubled = [...byAlias.entries()].filter(([, rows]) => rows.length > 1);\n if (doubled.length > 0)\n throw new Error(\n `task ${taskId} has more than one live session for ${doubled\n .map(\n ([alias, rows]) =>\n `'${alias}' (${rows.map((r) => r.sessionId).join(\", \")})`,\n )\n .join(\", \")}; pass the manifest from \\`task up\\`, or close the extras`,\n );\n return attachManifest(\n {\n taskId,\n taskVersion: live[0]!.taskVersion,\n name: null,\n instruction: null,\n sessions: Object.fromEntries(\n [...byAlias.entries()].map(([alias, [row]]) => [\n alias,\n {\n slug: row!.slug ?? \"\",\n ref: null,\n versionId: row!.versionId,\n sessionId: row!.sessionId,\n ready: row!.ready,\n state: row!.state,\n surfaces: [\"tools\"] as WorldSurfaceKind[],\n },\n ]),\n ),\n },\n options,\n );\n}\n\n/** Attach to the sessions a manifest names — the file `task up --out`\n * wrote. Each session is read back from the platform, so a closed one is a\n * clear error rather than a stale handle. */\nexport async function attachManifest(\n manifest: TaskManifest,\n options: WorldsClientOptions = {},\n): Promise<TaskSessions> {\n const entries = await Promise.all(\n Object.entries(manifest.sessions).map(\n async ([alias, entry]) =>\n [alias, await attachSession(entry.sessionId, options)] as const,\n ),\n );\n const sessions = Object.fromEntries(entries);\n const instruction =\n manifest.instruction ?? entries[0]?.[1].instruction ?? null;\n return new TaskSessions(\n manifest.taskId,\n manifest.taskVersion,\n manifest.name,\n instruction,\n sessions,\n Object.fromEntries(\n Object.entries(manifest.sessions).map(([alias, entry]) => [\n alias,\n { slug: entry.slug, ref: entry.ref },\n ]),\n ),\n );\n}\n\n/** Whether a parsed JSON value is a task manifest (what `task up` wrote)\n * rather than a task spec. */\nexport function isTaskManifest(value: unknown): value is TaskManifest {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n typeof (value as { sessions?: unknown }).sessions === \"object\" &&\n (value as { sessions?: unknown }).sessions !== null &&\n !(\"instruction\" in value && \"worlds\" in value)\n );\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\n\n/**\n * Create/push/finalize evaluations against the platform — the TS twin of\n * the Python SDK's `GatewayEvalsClient` (gatewaysdk/benchmark_hub/evals.py):\n * create_evaluation -> push_samples -> finalize_evaluation, anchored to an\n * immutable container version so scores stay reproducible across re-pushes.\n *\n * Used by `runTask` (worlds/taskRun.ts) to file a task run's rollout; kept\n * minimal on purpose — no batching, no rollout-session emission — since\n * that is all a task run needs today. Basic auth from the same\n * `WorldsClientOptions` the rest of the worlds client takes.\n */\n\nconst EVALUATIONS = \"/api/public/benchmark-containers/evaluations\";\n\n/** One rollout, in the platform's sample shape. */\nexport type EvalSample = {\n exampleId: string;\n task?: string;\n rolloutIndex?: number;\n prompt?: unknown;\n completion?: unknown;\n reward?: number;\n score?: number;\n correct?: boolean;\n rewards?: Record<string, number>;\n info?: Record<string, unknown>;\n};\n\nexport type CreateEvaluationOptions = {\n model?: string;\n rolloutsPerExample?: number;\n metadata?: Record<string, unknown>;\n};\n\nexport type FinalizeEvaluationOptions = {\n status?: \"COMPLETED\" | \"FAILED\";\n metrics?: Record<string, unknown>;\n};\n\nexport class GatewayEvalsClient {\n constructor(private readonly options: WorldsClientOptions = {}) {}\n\n /** Anchor a new evaluation to `versionId`; returns its id. */\n async createEvaluation(\n versionId: string,\n opts: CreateEvaluationOptions = {},\n ): Promise<string> {\n const body: Record<string, unknown> = { versionId };\n if (opts.model !== undefined) body.model = opts.model;\n if (opts.rolloutsPerExample !== undefined)\n body.rolloutsPerExample = opts.rolloutsPerExample;\n if (opts.metadata !== undefined) body.metadata = opts.metadata;\n const answer = await apiRequest<{ evaluationId: string }>(\n this.options,\n \"POST\",\n EVALUATIONS,\n body,\n );\n return answer.evaluationId;\n }\n\n /** Push one batch of samples; returns how many the platform inserted. */\n async pushSamples(\n evaluationId: string,\n samples: EvalSample[],\n ): Promise<number> {\n const answer = await apiRequest<{ inserted?: number }>(\n this.options,\n \"POST\",\n `${EVALUATIONS}/${encodeURIComponent(evaluationId)}/samples`,\n { samples },\n );\n return answer.inserted ?? samples.length;\n }\n\n /** Close the evaluation out; returns its final status. */\n async finalizeEvaluation(\n evaluationId: string,\n opts: FinalizeEvaluationOptions = {},\n ): Promise<string> {\n const body: Record<string, unknown> = {\n status: opts.status ?? \"COMPLETED\",\n };\n if (opts.metrics !== undefined) body.metrics = opts.metrics;\n const answer = await apiRequest<{ status: string }>(\n this.options,\n \"POST\",\n `${EVALUATIONS}/${encodeURIComponent(evaluationId)}/finalize`,\n body,\n );\n return answer.status;\n }\n}\n","import { randomBytes } from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport type { WorldSurfaceKind } from \"./browser\";\nimport { WorldSurfaceUnavailable } from \"./browser\";\nimport { GatewayEvalsClient, type EvalSample } from \"./evals\";\nimport type { WorldsClientOptions } from \"./index\";\nimport {\n modelToolName,\n schemaFromSignature,\n WorldSession,\n type WorldTaskIdRef,\n type WorldTaskSpec,\n type WorldToolkit,\n type WorldToolSpec,\n} from \"./session\";\nimport {\n openTask,\n TaskSessions,\n type TaskGrade,\n type TaskManifest,\n} from \"./taskSessions\";\n\n/**\n * RUN A TASK END TO END: open, agent, grade, file, close.\n *\n * `runTask` is `gateway worlds task run` in one call: bring every world of a\n * task up, hand the agent a small `TaskRun` (its sessions, a merged\n * toolkit, a place to record notes), grade every world with the agent's own\n * report, file one rollout the same way the Python SDK's `World.run` does\n * for a single in-process world, and close everything down — a run\n * directory on disk is the paper trail (`manifest.json`, `grades.json`,\n * `report.md`, `run.json`). Mirrors `gatewaysdk.world_tasks.run_task`.\n *\n * const summary = await runTask(\"wt_1\", async (run) => {\n * const { url, token } = await run.api(\"spycloud\");\n * // ... call the agent, using run.sessions / run.toolkit() ...\n * return \"found and locked the account\";\n * }, { model: \"claude-sonnet-4-5\" });\n */\n\n/** What the agent callable given to `runTask` is called with: the run's\n * identity, every world's live session, and a place to leave notes that\n * land in the run's `run.json`. */\nexport class TaskRun {\n readonly notes: Record<string, unknown> = {};\n\n constructor(\n readonly runId: string,\n readonly instruction: string,\n readonly model: string,\n readonly sessions: Record<string, WorldSession>,\n readonly manifest: TaskManifest,\n ) {}\n\n /** The alias's session, or a clear error naming the aliases there are. */\n session(alias: string): WorldSession {\n const session = this.sessions[alias];\n if (!session)\n throw new Error(\n `task run has no world '${alias}'; its worlds are ${Object.keys(this.sessions).join(\", \")}`,\n );\n return session;\n }\n\n /** `alias`'s HTTP API. Raises the same error the session itself would\n * when it was not opened with `surfaces: [\"api\"]`. */\n async api(alias: string): Promise<{ url: string; token?: string }> {\n const surfaces = await this.session(alias).surfaces();\n if (!surfaces.api)\n throw new WorldSurfaceUnavailable(\n \"api\",\n `open '${alias}' with surfaces: ['api']`,\n );\n return { url: surfaces.api.url, token: surfaces.api.token };\n }\n\n /** Every world's tools merged into one toolkit, each name prefixed\n * `<alias>.<tool>` so a model can tell which world a call goes to. A\n * world that exposes no tools contributes nothing — there is nothing to\n * merge. */\n async toolkit(): Promise<WorldToolkit> {\n const schemas: WorldToolkit[\"schemas\"] = [];\n const impls: WorldToolkit[\"impls\"] = {};\n const specs: WorldToolSpec[] = [];\n for (const [alias, session] of Object.entries(this.sessions)) {\n const kit = await session.toolkit();\n if (!kit.specs.length) continue;\n for (const spec of kit.specs) {\n const name = `${alias}.${spec.name}`;\n const prefixed: WorldToolSpec = {\n name,\n signature: spec.signature,\n doc: spec.doc,\n inputSchema: spec.inputSchema,\n };\n specs.push(prefixed);\n const schema = schemaFromSignature(prefixed);\n schema.function.name = name;\n schemas.push(schema);\n impls[name] = kit.impls[modelToolName(spec.name)]!;\n }\n }\n return { schemas, impls, specs };\n }\n\n /** Log arbitrary notes into this run's `run.json` (merged; a later call\n * overrides a key an earlier one set). */\n record(notes: Record<string, unknown>): void {\n Object.assign(this.notes, notes);\n }\n}\n\nfunction worldRef(\n live: TaskSessions,\n alias: string,\n): { slug: string; ref: string | null; versionId: string; sessionId: string } {\n const { slug, ref } = live.worldRef(alias);\n const session = live.sessions[alias]!;\n return {\n slug,\n ref,\n versionId: session.versionId,\n sessionId: session.sessionId,\n };\n}\n\n/** File one rollout for a task run, the same create/push/finalize shape\n * `gatewaysdk.world_tasks._file_task_run` uses. */\nasync function fileTaskRun(\n live: TaskSessions,\n runId: string,\n model: string,\n report: string | null,\n grade: TaskGrade,\n agentError: string | null,\n traced: boolean,\n runDir: string,\n options: WorldsClientOptions,\n): Promise<string> {\n const aliases = live.aliases;\n // The platform anchors an evaluation to ONE version today; a multi-world\n // task has no single version, so the first alias stands in and every\n // world's own version travels in `metadata.worlds` instead.\n const anchor = aliases[0]!;\n const worldsMeta = Object.fromEntries(\n aliases.map((alias) => [alias, worldRef(live, alias)]),\n );\n\n const evals = new GatewayEvalsClient(options);\n const evaluationId = await evals.createEvaluation(\n worldRef(live, anchor).versionId,\n {\n model,\n rolloutsPerExample: 1,\n metadata: {\n source: \"worlds-task-run\",\n task: {\n id: live.taskId,\n version: live.taskVersion,\n name: live.name,\n hash: live.hash,\n },\n anchor,\n worlds: worldsMeta,\n runId,\n },\n },\n );\n\n const reward = grade.reward;\n const sample: Record<string, unknown> = {\n exampleId: live.name ?? live.taskId ?? runId,\n task: live.name ?? live.taskId ?? runId,\n rolloutIndex: 0,\n prompt: live.instruction,\n ...(report === null ? {} : { completion: report }),\n rewards: grade.rewards,\n info: {\n sessionId: runId,\n worlds: Object.fromEntries(\n aliases.map((alias) => [\n alias,\n {\n ...worldRef(live, alias),\n reward: grade.worlds[alias]?.reward ?? null,\n },\n ]),\n ),\n ungraded: grade.ungraded,\n traced,\n runDir,\n ...(agentError ? { agentError } : {}),\n },\n };\n if (typeof reward === \"number\") {\n sample.reward = reward;\n sample.score = reward;\n sample.correct = reward >= 1.0;\n }\n await evals.pushSamples(evaluationId, [sample as unknown as EvalSample]);\n await evals.finalizeEvaluation(evaluationId, {\n status: agentError ? \"FAILED\" : \"COMPLETED\",\n metrics: {\n ...(typeof reward === \"number\" ? { avg_reward: reward } : {}),\n reward,\n ...Object.fromEntries(\n Object.entries(grade.rewards).map(([k, v]) => [`rewards.${k}`, v]),\n ),\n },\n });\n return evaluationId;\n}\n\nexport type RunTaskOptions = {\n /** Model label recorded on the filed run. */\n model: string;\n /** Asked of every world besides tools: api, ui, browser. */\n surfaces?: WorldSurfaceKind[];\n /** Directory the run's own `<runId>/` folder is created under. Default `\"runs\"`. */\n outDir?: string;\n /** Initialize tracing when GATEWAY_* credentials are configured. Default `true`. */\n trace?: boolean;\n /** File one rollout when the run ends. Default `true`. */\n file?: boolean;\n /** Leave every session up instead of closing it when the run ends. Default `false`. */\n keepUp?: boolean;\n reuseWarm?: boolean;\n options?: WorldsClientOptions;\n};\n\n/** What `runTask` returns and writes to `<runDir>/run.json`. */\nexport type RunTaskSummary = {\n runId: string;\n taskId: string | null;\n taskVersion: number | null;\n name: string | null;\n instruction: string;\n model: string;\n aliases: string[];\n reward: number | null;\n rewards: Record<string, number>;\n ungraded: string[];\n agentError: string | null;\n report: string | null;\n traced: boolean;\n runDir: string;\n durationSeconds: number;\n notes: Record<string, unknown>;\n filed: boolean;\n evaluationId?: string;\n [extra: string]: unknown;\n};\n\n/** The report an agent callable may return: a string, or an object with an\n * optional string `report` key (any other keys are kept in `run.json` as-is),\n * or nothing. Anything else is an agent error — a number, a bigint or an\n * array is never stringified into a graded completion. */\nexport type TaskRunResult =\n string | { report?: unknown; [key: string]: unknown } | null | undefined;\n\nconst describeValue = (value: unknown): string =>\n Array.isArray(value) ? \"array\" : value === null ? \"null\" : typeof value;\n\nconst RESULT_CONTRACT =\n \"return a string report, an object {report?: string, ...} or nothing\";\n\nfunction reportFromResult(result: TaskRunResult): {\n report: string | null;\n extra: Record<string, unknown>;\n} {\n if (result === undefined || result === null)\n return { report: null, extra: {} };\n if (typeof result === \"string\") return { report: result, extra: {} };\n if (typeof result !== \"object\" || Array.isArray(result))\n throw new Error(\n `agent returned ${describeValue(result)}; ${RESULT_CONTRACT}`,\n );\n const { report, ...extra } = result as Record<string, unknown>;\n if (report === undefined || report === null) return { report: null, extra };\n if (typeof report !== \"string\")\n throw new Error(\n `agent returned a report of type ${describeValue(report)}; ${RESULT_CONTRACT}`,\n );\n return { report, extra };\n}\n\n/**\n * Open every world of a task, run `agent` once against all of them, grade\n * with its report, file one rollout and close — the engine behind `gateway\n * worlds task run`. `agent` is called as `agent(taskRun)` with a `TaskRun`;\n * its return value becomes the report handed to every world's grader.\n *\n * Every step has a flag and a default, nothing implicit: tracing runs when\n * `GATEWAY_*` credentials are configured unless `trace: false`; filing\n * happens unless `file: false`; every session closes unless `keepUp: true`\n * — even when the agent throws, so grading and filing still happen with the\n * error recorded (`run.json.agentError`, the filed evaluation's status\n * FAILED).\n *\n * Writes `<outDir>/<runId>/{manifest,grades,run}.json` (and `report.md`\n * when the agent gave one).\n */\nexport async function runTask(\n ref: string | WorldTaskIdRef | WorldTaskSpec,\n agent: (run: TaskRun) => TaskRunResult | Promise<TaskRunResult>,\n opts: RunTaskOptions,\n): Promise<RunTaskSummary> {\n const runId = `wtr-${randomBytes(6).toString(\"hex\")}`;\n const outDir = opts.outDir ?? \"runs\";\n const runDir = path.join(outDir, runId);\n fs.mkdirSync(runDir, { recursive: true });\n const options = opts.options ?? {};\n\n const live = await openTask(ref, {\n surfaces: opts.surfaces,\n reuseWarm: opts.reuseWarm,\n options,\n });\n const started = Date.now();\n try {\n await live.ready();\n\n let traced = false;\n if (opts.trace !== false) {\n try {\n const { isGatewayConfigured, init } = await import(\"../tracing/init\");\n if (isGatewayConfigured()) {\n init();\n traced = true;\n }\n } catch {\n // Tracing must never sink a run.\n traced = false;\n }\n }\n\n const taskRun = new TaskRun(\n runId,\n live.instruction ?? \"\",\n opts.model,\n live.sessions,\n await live.manifest(),\n );\n\n let agentError: string | null = null;\n let report: string | null = null;\n let extra: Record<string, unknown> = {};\n try {\n const invoke = () => agent(taskRun);\n const result = traced\n ? await (await import(\"../tracing/session\")).withSession(runId, invoke)\n : await invoke();\n ({ report, extra } = reportFromResult(result));\n } catch (error) {\n const message =\n (error instanceof Error ? error.message : String(error)) ||\n \"Unknown error\";\n agentError = message.slice(0, 2000);\n }\n\n const grade =\n report !== null ? await live.grade({ report }) : await live.grade();\n\n fs.writeFileSync(\n path.join(runDir, \"manifest.json\"),\n JSON.stringify(taskRun.manifest, null, 2),\n );\n fs.writeFileSync(\n path.join(runDir, \"grades.json\"),\n JSON.stringify(grade, null, 2),\n );\n if (report) fs.writeFileSync(path.join(runDir, \"report.md\"), report);\n\n const summary: RunTaskSummary = {\n runId,\n taskId: live.taskId,\n taskVersion: live.taskVersion,\n name: live.name,\n instruction: taskRun.instruction,\n model: opts.model,\n aliases: live.aliases,\n reward: grade.reward,\n rewards: grade.rewards,\n ungraded: grade.ungraded,\n agentError,\n report,\n traced,\n runDir,\n durationSeconds: Math.round((Date.now() - started) / 10) / 100,\n notes: taskRun.notes,\n filed: false,\n ...extra,\n };\n\n if (opts.file !== false) {\n summary.evaluationId = await fileTaskRun(\n live,\n runId,\n opts.model,\n report,\n grade,\n agentError,\n traced,\n runDir,\n options,\n );\n summary.filed = true;\n }\n\n fs.writeFileSync(\n path.join(runDir, \"run.json\"),\n JSON.stringify(summary, null, 2),\n );\n return summary;\n } finally {\n if (!opts.keepUp) {\n try {\n await live.close({ keepWarm: false });\n } catch {\n // Every close is best-effort here; a session that would not close\n // is not this function's failure to report — `task down` covers it.\n }\n }\n }\n}\n","/**\n * What a directory IS, decided once for the TS SDK.\n *\n * `WorldDir.open(dir)` is the one detector this package has: the benchmark\n * front door (`classifyTree`, `detectEnvKind`, `harborTaskDirs`,\n * `verifiersPackage` in ../benchmarks) and the hub client (`collectArchiveRelPaths`,\n * `computeContentHash`, the contract-version lookup in ./hub.ts) are facades\n * over it. Twin of `gatewaysdk.environment.world.World` (Python) and\n * `packages/shared/src/world` (the platform); the corpus under\n * `conformance/worlds/` pins all three to the same answers.\n */\nimport { createHash } from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nexport const WORLD_MANIFEST = \"gateway-env.toml\";\nexport const API_BUNDLE_MANIFEST = \"gateway-api-world.toml\";\nexport const BUNDLED_WORLD_PREFIX = \"server/world/\";\nexport const CONNECTOR_SPEC = \"connector.toml\";\nexport const PYPROJECT = \"pyproject.toml\";\nexport const WORLD_SCHEMA_MARKERS = [\"schema/world.json\", \"schema/runtime.json\", \"schema/lock.json\"];\nconst WORLD_ROOT_MARKERS = [CONNECTOR_SPEC, ...WORLD_SCHEMA_MARKERS];\n/** Root markers that widen the archive to every ordinary root file. */\nconst BROAD_ROOT_MARKERS = [WORLD_MANIFEST, API_BUNDLE_MANIFEST];\nconst SKIPPED_DIRS = new Set([\"dist\", \"build\", \"outputs\", \"__pycache__\"]);\n\n/** The runner's kind: what the dispatcher executes a pushed tree as. */\nexport type EnvKind = \"api\" | \"mock-tools\" | \"harbor\" | \"verifiers-v1\" | \"verifiers\";\n\n// The `verifiers.v1` namespace first shipped in verifiers 0.2.0: a v1 package\n// pins verifiers>=0.2 (or ~=0.2 / ==0.2.* / >=1 / ==1.*) in pyproject and/or\n// imports the namespace or subclasses Taskset alongside a v1-style `__all__`.\nconst V1_DEP = /[\"']verifiers\\s*(?:\\[[^\\]]*\\])?\\s*(?:>=|~=|==|>)\\s*(?:0\\.(?:[2-9]\\d*|[1-9]\\d+)|[1-9]\\d*)/;\nconst V1_IMPORT = /^\\s*(?:from\\s+verifiers\\.v1\\s+import\\b|from\\s+verifiers\\s+import\\s+v1\\b|import\\s+verifiers\\.v1\\b)/m;\nconst V1_TASKSET = /class\\s+\\w+\\s*\\(\\s*(?:(?:vf|v1|verifiers(?:\\.v1)?)\\.)?Taskset\\s*[,)]/;\nconst HARBOR_TASK = /^(?:tasks\\/)?([^/]+)\\/task\\.toml$/;\n\nconst skippedDir = (name: string): boolean =>\n name.startsWith(\".\") || SKIPPED_DIRS.has(name) || name.endsWith(\".egg-info\");\n\n/** Python's `sorted()` order for relpaths: code points, not UTF-16 units. */\nconst byCodePoint = (a: string, b: string): number => Buffer.compare(Buffer.from(a, \"utf-8\"), Buffer.from(b, \"utf-8\"));\n\nexport class WorldDir {\n private pathsMemo: string[] | undefined;\n\n private constructor(\n readonly dir: string,\n /** Where the authored world lives: `\"\"` for a world stored as itself,\n * `server/world/` for one stored as its api bundle. */\n readonly worldRoot: \"\" | typeof BUNDLED_WORLD_PREFIX,\n ) {}\n\n static open(dir: string): WorldDir {\n const present = (rel: string) => fs.existsSync(path.join(dir, rel));\n const bundled = present(API_BUNDLE_MANIFEST) && WORLD_ROOT_MARKERS.some((m) => present(BUNDLED_WORLD_PREFIX + m));\n return new WorldDir(dir, bundled ? BUNDLED_WORLD_PREFIX : \"\");\n }\n\n // ── Files ──────────────────────────────────────────────────────────────\n\n has(rel: string): boolean {\n return fs.existsSync(path.join(this.dir, rel));\n }\n\n text(rel: string): string | null {\n try {\n return fs.readFileSync(path.join(this.dir, rel), \"utf-8\");\n } catch {\n return null;\n }\n }\n\n /** A path under the authored world's root. */\n worldPath(rel: string): string {\n return this.worldRoot + rel;\n }\n\n /** Every regular file the archive rules keep (`_archive.py`: no hidden,\n * dist, build, outputs, pycache or egg-info directories), as sorted\n * relpaths. Root files enter only when a Gateway manifest widens the root\n * or they are README.md, pyproject.toml or Python. */\n get archivePaths(): string[] {\n if (this.pathsMemo) return this.pathsMemo;\n const broad = BROAD_ROOT_MARKERS.some((m) => this.has(m));\n const out: string[] = [];\n const walk = (rel: string) => {\n for (const entry of fs.readdirSync(rel ? path.join(this.dir, rel) : this.dir, { withFileTypes: true })) {\n const child = rel ? `${rel}/${entry.name}` : entry.name;\n if (entry.isDirectory()) {\n if (!skippedDir(entry.name)) walk(child);\n } else if (entry.isFile() && !entry.name.startsWith(\".\")) {\n const rootKept = broad || [\"README.md\", PYPROJECT].includes(entry.name) || entry.name.endsWith(\".py\");\n if (rel || rootKept) out.push(child);\n }\n }\n };\n walk(\"\");\n return (this.pathsMemo = out.sort(byCodePoint));\n }\n\n /** A root `.gitignore` is present: the Python SDK honours it when\n * collecting, this package does not reimplement gitignore. */\n get hasRootGitignore(): boolean {\n return this.has(\".gitignore\");\n }\n\n /** SHA-256 over `utf8(\"file:\" + relpath)` + bytes per archive path in\n * sorted order: the version's identity, byte-compatible with\n * `_archive.compute_content_hash` and Prime Intellect. */\n get contentHash(): string {\n const hasher = createHash(\"sha256\");\n for (const rel of this.archivePaths) {\n hasher.update(Buffer.from(`file:${rel}`, \"utf-8\"));\n hasher.update(fs.readFileSync(path.join(this.dir, rel)));\n }\n return hasher.digest(\"hex\");\n }\n\n // ── Markers ────────────────────────────────────────────────────────────\n\n get isApiBundle(): boolean {\n return this.has(API_BUNDLE_MANIFEST);\n }\n\n get hasManifest(): boolean {\n return this.has(this.worldPath(WORLD_MANIFEST));\n }\n\n get hasSchemaMarker(): boolean {\n return WORLD_SCHEMA_MARKERS.some((m) => this.has(this.worldPath(m)));\n }\n\n /** Harbor task dirs, relative to the tree: `tasks/<name>` when a `tasks/`\n * dir holds them, else the root `<name>` dirs. */\n taskDirs(): string[] {\n const names = new Set<string>();\n for (const rel of this.archivePaths) {\n const m = HARBOR_TASK.exec(rel);\n if (m) names.add(rel.startsWith(\"tasks/\") ? `tasks/${m[1]}` : m[1]!);\n }\n const under = [...names].filter((n) => n.startsWith(\"tasks/\"));\n return (under.length ? under : [...names]).sort();\n }\n\n /** The Python package of a verifiers tree (`<pkg>/__init__.py` or\n * `src/<pkg>/__init__.py`), or null. */\n pythonPackage(): { name: string; init: string } | null {\n if (!this.has(PYPROJECT)) return null;\n for (const base of [\"\", \"src/\"]) {\n const init = this.archivePaths.find((rel) => {\n const m = /^([^/]+)\\/__init__\\.py$/.exec(rel.startsWith(base) ? rel.slice(base.length) : \"\");\n return m !== null && m[1] !== \"tests\";\n });\n if (init) return { name: init.slice(base.length).split(\"/\")[0]!, init };\n }\n return null;\n }\n\n /** The package targets the `verifiers.v1` API: read from the root\n * pyproject and every archived Python module. */\n get isVerifiersV1(): boolean {\n for (const rel of this.archivePaths) {\n if (rel !== PYPROJECT && !rel.endsWith(\".py\")) continue;\n const text = this.text(rel);\n if (text === null) continue;\n if (rel === PYPROJECT ? V1_DEP.test(text) : V1_IMPORT.test(text) || (text.includes(\"__all__\") && V1_TASKSET.test(text)))\n return true;\n }\n return false;\n }\n\n // ── The answer ─────────────────────────────────────────────────────────\n\n /** The runner's kind (`detect_env_kind`): api / mock-tools win over\n * everything, a harbor task tree next, then the verifiers API version. */\n get kind(): EnvKind {\n if (this.isApiBundle) return \"api\";\n if (this.has(WORLD_MANIFEST)) return \"mock-tools\";\n if (this.taskDirs().length) return \"harbor\";\n return this.isVerifiersV1 ? \"verifiers-v1\" : \"verifiers\";\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\";\nimport { WorldDir } from \"./worldDir\";\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 * The content hash is the version's identity and is byte-compatible with\n * Prime Intellect: `WorldDir.contentHash` (./worldDir.ts) computes it here,\n * `WorldTree.contentHash` on the platform and `_archive.compute_content_hash`\n * in the Python SDK; the conformance corpus pins the three to the same bytes.\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\");\n\n/** The archive-visible files of a working dir, as sorted relpaths\n * (`WorldDir.archivePaths`). Throws on a root .gitignore (see the header). */\nexport function collectArchiveRelPaths(dir: string): string[] {\n const world = WorldDir.open(dir);\n if (world.hasRootGitignore) {\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 return world.archivePaths;\n}\n\nexport function computeContentHash(dir: string): string {\n collectArchiveRelPaths(dir);\n return WorldDir.open(dir).contentHash;\n}\n\n// ── deterministic tar.gz writer ─────────────────────────────────────────────\n\nfunction octal(value: number, length: number): Buffer {\n return Buffer.from(\n value.toString(8).padStart(length - 1, \"0\") + \"\\0\",\n \"ascii\",\n );\n}\n\n/** The two modes a stored world file can have: the tar (and `pull`) keep\n * only whether a file is executable — `tests/test.sh` in a harbor tree must\n * still run after a round trip. Owner/mtime are cleared for determinism. */\nconst FILE_MODE = 0o644;\nconst EXEC_MODE = 0o755;\n\nexport function archiveMode(mode: number): number {\n return (mode & 0o111) !== 0 ? EXEC_MODE : FILE_MODE;\n}\n\nfunction tarHeader(name: string, size: number, mode = FILE_MODE): Buffer {\n const header = Buffer.alloc(512);\n header.write(name, 0, 100, \"utf-8\");\n octal(mode, 8).copy(header, 100);\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, mode: number): 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, mode));\n } else {\n parts.push(tarHeader(name, payload.length, mode));\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 const abs = path.join(dir, relPath);\n parts.push(\n ...tarMember(\n relPath,\n fs.readFileSync(abs),\n archiveMode(fs.statSync(abs).mode),\n ),\n );\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\n/** The slug a push of `dir` lands on: an explicit one, else the slug the dir\n * was pushed to or pulled from (its `.gateway` meta), else the pyproject\n * name, else the directory's name — so a tracked checkout never creates a\n * second world named after its folder. */\nexport function pushSlug(dir: string, explicit?: string): string {\n return resolvePushSlug(dir, { explicit }).slug;\n}\n\nexport type SlugDeclaration = { source: string; slug: string };\n\nexport type PushSlugResolution = {\n slug: string;\n /** Where the slug came from (`--slug`, `.gateway metadata`, `benchmark.json`, `pyproject.toml`, `directory name`). */\n source: string;\n /** The slug the dir's `.gateway/.env-metadata.json` tracks from an earlier push or pull, if any. */\n tracked: string | null;\n /** What the tree itself declares (a caller's benchmark.json, then pyproject.toml), in precedence order. */\n declared: SlugDeclaration[];\n /** A declaration the tracked slug does not match — set only when the tracked slug won without `--slug`. */\n conflict: SlugDeclaration | null;\n};\n\n/** The platform's collision suffix: `acme-2` minted for a taken `acme`. */\nconst MINTED_SUFFIX = /^-\\d+$/;\n\n/** `pushSlug` with its provenance. `declared` are the caller's own slug sources\n * (e.g. `{ \"benchmark.json\": \"x\" }`), consulted before pyproject. A tracked slug\n * that disagrees with what the tree declares is reported as `conflict` so a\n * front door can refuse: that is how a directory pushed once with `--slug X`\n * silently landed every later push on X while its benchmark.json said Y. The\n * platform's collision suffix (`acme-2` minted for a taken `acme`) is not a\n * conflict; any other difference is (`acme-e2e` for `acme` was the mix-up). */\nexport function resolvePushSlug(\n dir: string,\n opts: { explicit?: string; declared?: Record<string, string | null | undefined> } = {},\n): PushSlugResolution {\n const meta = readLocalMeta(dir);\n const tracked = typeof meta?.slug === \"string\" && meta.slug ? meta.slug : null;\n const declared = Object.entries({ ...(opts.declared ?? {}), \"pyproject.toml\": readPyproject(dir).name })\n .filter((entry): entry is [string, string] => typeof entry[1] === \"string\" && entry[1] !== \"\")\n .map(([source, slug]) => ({ source, slug }));\n const base = { tracked, declared, conflict: null };\n if (opts.explicit) return { ...base, slug: opts.explicit, source: \"--slug\" };\n if (tracked) {\n const minted = (d: SlugDeclaration) => tracked.startsWith(d.slug) && MINTED_SUFFIX.test(tracked.slice(d.slug.length));\n const conflict = declared.find((d) => d.slug !== tracked && !minted(d)) ?? null;\n return { ...base, slug: tracked, source: \".gateway metadata\", conflict };\n }\n const first = declared[0];\n if (first) return { ...base, slug: first.slug, source: first.source };\n return { ...base, slug: path.basename(path.resolve(dir)), source: \"directory name\" };\n}\n\n/** The refusal a front door raises on `PushSlugResolution.conflict`: both slugs, both sources, every way out. */\nexport class PushSlugConflict extends Error {\n constructor(\n public readonly dir: string,\n public readonly tracked: string,\n public readonly declared: SlugDeclaration,\n ) {\n super(\n `${dir} tracks slug \\`${tracked}\\` (${META_RELPATH}, from an earlier push) but its ${declared.source} says \\`${declared.slug}\\`. ` +\n `Nothing was pushed. Pass --slug ${declared.slug} to push there (and retrack the dir), --slug ${tracked} to keep pushing to \\`${tracked}\\`, ` +\n `or delete ${META_RELPATH} to forget the earlier push.`,\n );\n this.name = \"PushSlugConflict\";\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\n/** A schema world's own version: `x-gateway.package.version` of its contract\n * (`schema/world.json`, or `server/world/schema/world.json` in an api bundle).\n * What a connector world has instead of a pyproject, so its versions read\n * \"1.0.0\" rather than \"unversioned\" on the platform. */\nfunction readWorldContractVersion(dir: string): {\n name?: string;\n version?: string;\n} {\n const world = WorldDir.open(dir);\n try {\n const parsed = JSON.parse(\n world.text(world.worldPath(\"schema/world.json\")) ?? \"\",\n ) as {\n \"x-gateway\"?: { package?: { id?: string; version?: string } };\n };\n const pkg = parsed[\"x-gateway\"]?.package;\n if (pkg?.version) return { name: pkg.id, version: pkg.version };\n } catch {\n // not a schema world\n }\n return {};\n}\n\n/** The rows the platform previews for a pushed DRAFT: the archive set, one\n * entry per file the content hash covers, so hash, tarball, manifest and\n * `pull` agree on what the world is. Finalize replaces them with rows\n * derived from the stored bytes. */\nexport function buildFileManifest(\n dir: string,\n): { path: string; isDirectory: boolean; size: number; sha256: string }[] {\n return collectArchiveRelPaths(dir).map((relPath) => {\n const payload = fs.readFileSync(path.join(dir, relPath));\n return {\n path: relPath,\n isDirectory: false,\n size: payload.length,\n sha256: createHash(\"sha256\").update(payload).digest(\"hex\"),\n };\n });\n}\n\nasync function putObject(\n url: string,\n data: Buffer,\n shaB64: string,\n): 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(\n `object PUT -> ${resp.status}: ${(await resp.text()).slice(0, 300)}`,\n );\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 /** Push on top of this version instead of the local meta's base — what a\n * CI checkout (which has no local meta) passes after resolving the\n * branch tip, so re-validating a PR replaces its own previous push\n * instead of 409ing against it. */\n baseVersionId?: string | null;\n /** Container metadata recorded on resolve — the Python CLI's --name,\n * --description, --tag and --visibility. */\n name?: string;\n description?: string;\n tags?: string[];\n visibility?: string;\n /** Pre-built OCI image ref for image/agentic envs (recorded on the version). */\n imageRef?: string;\n options?: WorldsClientOptions;\n } = {},\n): Promise<{\n containerId: string;\n slug: string;\n versionId: string;\n contentHash: string;\n branch: string;\n state: string | null;\n alreadyUploaded: boolean;\n}> {\n const options = opts.options ?? {};\n if (!fs.statSync(dir).isDirectory())\n throw new Error(`Not a directory: ${dir}`);\n const localMeta = readLocalMeta(dir) ?? {};\n const branch =\n opts.branch ?? (localMeta.branch as string | undefined) ?? DEFAULT_BRANCH;\n const baseVersionId = opts.baseVersionId ?? localMeta.versionId ?? null;\n\n const fileManifest = buildFileManifest(dir);\n if (fileManifest.length === 0)\n throw new Error(\n `Nothing to push: ${dir} has no files the archive rules keep (a world root marker, README.md, pyproject.toml, *.py, or any file below a subdirectory).`,\n );\n const contentHash = computeContentHash(dir);\n const pyproject = readPyproject(dir);\n // A connector world carries its version on its contract, not a pyproject.\n const contractVersion = pyproject.version\n ? undefined\n : readWorldContractVersion(dir).version;\n if (contractVersion) pyproject.version = contractVersion;\n // A dir that tracks a world (created, pulled or pushed before) pushes back\n // to THAT world: its recorded slug wins over the package name, so a world\n // created as `acme-f7` is not re-published as pyproject's `acme` — which is\n // how `worlds ci` minted an unsuffixed twin of every suffixed world.\n const slug =\n opts.slug ??\n localMeta.slug ??\n pyproject.name ??\n path.basename(path.resolve(dir));\n\n // Sent twice on purpose: resolve records it on a container it CREATES,\n // finalize refreshes an existing one — only when the push actually lands.\n // An omitted field leaves the container's value alone; an explicit one\n // replaces it, so `\"\"` clears the description and `[]` clears the tags.\n const metadata = {\n ...(opts.name !== undefined ? { name: opts.name } : {}),\n ...(opts.description !== undefined\n ? { description: opts.description }\n : {}),\n ...(opts.tags !== undefined ? { tags: opts.tags } : {}),\n ...(opts.visibility ? { visibility: opts.visibility } : {}),\n };\n const resolve = await apiRequest<{ containerId: string }>(\n options,\n \"POST\",\n \"/api/public/benchmark-containers/resolve\",\n { slug, ...metadata },\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 alreadyUploaded?: boolean;\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,\n branch,\n baseVersionId,\n ...(opts.force ? { force: true } : {}),\n ...(opts.message ? { changeReason: opts.message } : {}),\n ...(opts.author ? { author: opts.author } : {}),\n ...(opts.imageRef ? { imageRef: opts.imageRef } : {}),\n });\n\n if (version.uploadUrl)\n await putObject(version.uploadUrl, tarball, bundleSha256);\n\n const final = await apiRequest<{ state?: string; branch?: string }>(\n options,\n \"POST\",\n `/api/public/benchmark-containers/versions/${version.versionId}/finalize`,\n {\n branch,\n baseVersionId,\n ...(opts.force ? { force: true } : {}),\n ...metadata,\n },\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 {\n containerId: resolve.containerId,\n slug,\n versionId: version.versionId,\n contentHash,\n branch: final.branch ?? branch,\n state: final.state ?? null,\n alreadyUploaded: Boolean(version.alreadyUploaded),\n };\n}\n\n/** Extract a downloaded bundle into `dir` (paths sanitized, executable bit kept). */\nexport function 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\n .subarray(0, 100)\n .toString(\"utf-8\")\n .replace(/\\0.*$/, \"\");\n const size =\n parseInt(\n header.subarray(124, 136).toString(\"ascii\").replace(/\\0.*$/, \"\").trim(),\n 8,\n ) || 0;\n const mode =\n parseInt(\n header.subarray(100, 108).toString(\"ascii\").replace(/\\0.*$/, \"\").trim(),\n 8,\n ) || FILE_MODE;\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, { mode: archiveMode(mode) });\n fs.chmodSync(target, archiveMode(mode));\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 =\n 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: {\n title: string;\n reason: string;\n targetBranch?: string;\n options?: WorldsClientOptions;\n },\n): Promise<{ proposalId: string }> {\n const meta = readLocalMeta(dir);\n if (!meta?.slug || !meta.baseFiles) {\n throw new Error(\n \"This dir has no pull/push base — run pull first, then edit, then propose.\",\n );\n }\n const state = localTreeState(dir);\n if (state.clean)\n 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))\n 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, pushSlug } 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 source?: { repoUrl?: string; commit?: string },\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 // Name the exact source that ran: the commit on GitHub when we know it,\n // always the content hash the platform pinned.\n const commitLink =\n source?.repoUrl && source?.commit\n ? `[\\`${source.commit.slice(0, 12)}\\`](${source.repoUrl}/commit/${source.commit})`\n : null;\n lines.push(\n `Ran the pull request's own world source` +\n (commitLink ? ` (${commitLink} on \\`${report.branch}\\`` : ` (`) +\n `${commitLink ? \", \" : \"\"}pinned as \\`${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 // Every scenario, in the open: a validation whose per-scenario grades hide\n // behind a fold reads as one opaque number. Fold only when the table is\n // genuinely long.\n if (taskRows.length > 0) {\n const fold = taskRows.length > 12;\n lines.push(\"\");\n if (fold) {\n lines.push(\n `<details><summary>Per-scenario rewards (${taskRows.length})</summary>`,\n );\n lines.push(\"\");\n } else {\n lines.push(`**Scenarios (${taskRows.length})**`);\n lines.push(\"\");\n }\n lines.push(\"| Scenario | 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 if (fold) {\n lines.push(\"\");\n lines.push(\"</details>\");\n }\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 const slug = pushSlug(dir, opts.slug);\n progress(`pushing ${dir} as ${slug}@${branch}…`);\n // CI checkouts carry no local push meta, so a re-validation would 409\n // against the branch tip its own previous run created. Validation's\n // semantics are \"this branch's tip BECOMES the PR's source\": resolve the\n // current tip and push on top of it. A branch that does not exist yet\n // resolves to no base, which is a fresh branch — also correct.\n let tipVersionId: string | null = null;\n try {\n const tip = await apiRequest<{ versionId?: string }>(\n options,\n \"POST\",\n \"/api/public/benchmark-containers/resolve-version\",\n { slug, ref: branch },\n );\n tipVersionId = tip.versionId ?? null;\n } catch {\n tipVersionId = null;\n }\n const pushed = await push(dir, {\n slug,\n branch,\n baseVersionId: tipVersionId,\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 {\n ...base,\n markdown: buildMarkdown(base, minScore, {\n repoUrl: provenance.repoUrl,\n commit: provenance.commit,\n }),\n };\n}\n","/**\n * `describeWorld(slug)` — what a world holds and how each field is stored,\n * from `GET /api/public/worlds/{slug}`: the entities (primary key, unique\n * keys, relationships, row count, fields with their `[redact]` policy) and\n * the `[redact]` table itself, so `storedForms(world, field, plaintext)`\n * can compute a lookup value without Python. The CLI twin is\n * `gateway worlds describe <slug>`; for a directory the CLI asks the schema\n * runtime instead and merges the same shape.\n */\n\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\nimport type { RedactPolicy, Redaction } from \"./redaction\";\n\nexport type WorldField = {\n name: string;\n type: string | null;\n required: boolean;\n /** How the store holds it; null means in the clear (queryable by plaintext as given). */\n redaction: Redaction | null;\n};\n\nexport type WorldRelationship = {\n fields: string[];\n target: string;\n on_delete?: string;\n};\n\nexport type WorldEntityMapping = {\n localEntity: string;\n localField: string;\n depEntity: string;\n depField: string;\n /** A closed set, applied left to right before each world's own redaction. */\n transform: string[];\n};\n\nexport type WorldDependency = {\n alias: string;\n dependsOn: { slug: string | null; versionId: string };\n task: string | null;\n tools: string[];\n entities: WorldEntityMapping[];\n};\n\nexport type WorldEntity = {\n name: string;\n primaryKey: string[];\n unique: string[][];\n relationships: WorldRelationship[];\n /** Rows in the head version; null when the platform does not count this kind. */\n rowCount: number | null;\n fields: WorldField[];\n};\n\nexport type WorldDescription = {\n slug: string;\n name: string;\n description: string | null;\n kind: string;\n version: { id: string; contentHash: string; semanticVersion: string | null };\n url: string;\n hostedUrl: string | null;\n tools: { name: string; signature: string; doc: string | null }[];\n taskCount: number;\n links: { tasks: string; sessions: string };\n /** World-to-world links from `[dependencies]`, resolved at commit, with the\n * entity mappings `--across` follows. */\n dependencies?: WorldDependency[];\n entities: WorldEntity[];\n redact: RedactPolicy | null;\n};\n\n/** The world's head version, described. The route reads the head only, so a\n * `slug@ref` is refused rather than silently served as the head. */\nexport async function describeWorld(\n slug: string,\n options: WorldsClientOptions = {},\n): Promise<WorldDescription> {\n if (slug.includes(\"@\"))\n throw new Error(\n `describeWorld reads a world's head version: pass the slug without @ref (got ${slug})`,\n );\n return apiRequest<WorldDescription>(\n options,\n \"GET\",\n `/api/public/worlds/${encodeURIComponent(slug)}`,\n );\n}\n","/**\n * JSON as the Python CLI sees it, so both CLIs write the same bytes.\n *\n * `JSON.parse` + `JSON.stringify` are not enough for parity with\n * `json.loads` + `json.dumps(separators=(\",\", \":\"), ensure_ascii=False)`:\n * JavaScript loses `1.0` vs `1` (Python keeps the float), rounds integers past\n * 2^53, moves integer-like keys to the front of an object, and spells\n * exponents differently (`1e-7` vs `1e-07`). Here a number keeps its source\n * text and its Python type, an object is a Map (insertion order, always), and\n * `dumps` renders exactly what CPython renders.\n */\n\nexport class JsonNumber {\n /** The lexeme as it appeared, e.g. \"1.0\", \"-0\", \"1e21\". */\n constructor(readonly text: string) {}\n /** A float in Python's eyes: a fraction, an exponent, or a non-finite literal. */\n get isFloat(): boolean {\n return /[.eE]/.test(this.text) || /[nN]/.test(this.text);\n }\n get value(): number {\n return Number(this.text);\n }\n}\n\nexport type JsonObject = Map<string, JsonValue>;\nexport type JsonValue = null | boolean | string | JsonNumber | JsonValue[] | JsonObject;\n\nexport class JsonSyntaxError extends Error {}\n\nexport const isObject = (value: JsonValue | undefined): value is JsonObject => value instanceof Map;\n\n// ------------------------------------------------------------------ parsing\n\n/** Parse one JSON text (a line, a row, a document) into the model above.\n * Accepts what `json.loads` accepts, including NaN/Infinity literals. */\nexport function parseJson(text: string): JsonValue {\n const p = new Parser(text);\n p.skipWs();\n const value = p.value();\n p.skipWs();\n if (p.i < text.length) throw new JsonSyntaxError(`Extra data at ${p.i}`);\n return value;\n}\n\nclass Parser {\n i = 0;\n constructor(readonly s: string) {}\n\n skipWs(): void {\n const s = this.s;\n while (this.i < s.length) {\n const c = s.charCodeAt(this.i);\n if (c === 0x20 || c === 0x0a || c === 0x0d || c === 0x09) this.i++;\n else break;\n }\n }\n\n fail(what: string): never {\n throw new JsonSyntaxError(`${what} at ${this.i}`);\n }\n\n value(): JsonValue {\n const s = this.s;\n if (this.i >= s.length) this.fail(\"Expecting value\");\n const c = s[this.i]!;\n if (c === \"{\") return this.object();\n if (c === \"[\") return this.array();\n if (c === '\"') return this.string();\n if (c === \"t\") return this.literal(\"true\", true);\n if (c === \"f\") return this.literal(\"false\", false);\n if (c === \"n\") return this.literal(\"null\", null);\n if (c === \"N\") return this.literal(\"NaN\", new JsonNumber(\"NaN\"));\n if (c === \"I\") return this.literal(\"Infinity\", new JsonNumber(\"Infinity\"));\n return this.number();\n }\n\n literal<T extends JsonValue>(word: string, value: T): T {\n if (!this.s.startsWith(word, this.i)) this.fail(\"Expecting value\");\n this.i += word.length;\n return value;\n }\n\n number(): JsonNumber {\n const s = this.s;\n const start = this.i;\n if (s[this.i] === \"-\") {\n this.i++;\n if (s.startsWith(\"Infinity\", this.i)) {\n this.i += 8;\n return new JsonNumber(\"-Infinity\");\n }\n }\n const intStart = this.i;\n if (s[this.i] === \"0\") this.i++;\n else {\n while (this.i < s.length && isDigit(s.charCodeAt(this.i))) this.i++;\n if (this.i === intStart) this.fail(\"Expecting value\");\n }\n if (s[this.i] === \".\") {\n this.i++;\n const fracStart = this.i;\n while (this.i < s.length && isDigit(s.charCodeAt(this.i))) this.i++;\n if (this.i === fracStart) this.fail(\"Invalid number\");\n }\n if (s[this.i] === \"e\" || s[this.i] === \"E\") {\n this.i++;\n if (s[this.i] === \"+\" || s[this.i] === \"-\") this.i++;\n const expStart = this.i;\n while (this.i < s.length && isDigit(s.charCodeAt(this.i))) this.i++;\n if (this.i === expStart) this.fail(\"Invalid number\");\n }\n return new JsonNumber(s.slice(start, this.i));\n }\n\n string(): string {\n const s = this.s;\n this.i++; // opening quote\n let out = \"\";\n let runStart = this.i;\n for (;;) {\n if (this.i >= s.length) this.fail(\"Unterminated string\");\n const c = s.charCodeAt(this.i);\n if (c === 0x22) {\n out += s.slice(runStart, this.i);\n this.i++;\n return out;\n }\n if (c < 0x20) this.fail(\"Invalid control character\");\n if (c !== 0x5c) {\n this.i++;\n continue;\n }\n out += s.slice(runStart, this.i);\n this.i++;\n const e = s[this.i];\n switch (e) {\n case '\"':\n case \"\\\\\":\n case \"/\":\n out += e;\n break;\n case \"b\":\n out += \"\\b\";\n break;\n case \"f\":\n out += \"\\f\";\n break;\n case \"n\":\n out += \"\\n\";\n break;\n case \"r\":\n out += \"\\r\";\n break;\n case \"t\":\n out += \"\\t\";\n break;\n case \"u\": {\n const hex = s.slice(this.i + 1, this.i + 5);\n if (!/^[0-9a-fA-F]{4}$/.test(hex)) this.fail(\"Invalid \\\\u escape\");\n out += String.fromCharCode(parseInt(hex, 16));\n this.i += 4;\n break;\n }\n default:\n this.fail(\"Invalid escape\");\n }\n this.i++;\n runStart = this.i;\n }\n }\n\n array(): JsonValue[] {\n this.i++;\n const out: JsonValue[] = [];\n this.skipWs();\n if (this.s[this.i] === \"]\") {\n this.i++;\n return out;\n }\n for (;;) {\n this.skipWs();\n out.push(this.value());\n this.skipWs();\n const c = this.s[this.i];\n if (c === \",\") {\n this.i++;\n continue;\n }\n if (c === \"]\") {\n this.i++;\n return out;\n }\n this.fail(\"Expecting ',' delimiter\");\n }\n }\n\n object(): JsonObject {\n this.i++;\n const out: JsonObject = new Map();\n this.skipWs();\n if (this.s[this.i] === \"}\") {\n this.i++;\n return out;\n }\n for (;;) {\n this.skipWs();\n if (this.s[this.i] !== '\"') this.fail(\"Expecting property name enclosed in double quotes\");\n const key = this.string();\n this.skipWs();\n if (this.s[this.i] !== \":\") this.fail(\"Expecting ':' delimiter\");\n this.i++;\n this.skipWs();\n out.set(key, this.value());\n this.skipWs();\n const c = this.s[this.i];\n if (c === \",\") {\n this.i++;\n continue;\n }\n if (c === \"}\") {\n this.i++;\n return out;\n }\n this.fail(\"Expecting ',' delimiter\");\n }\n }\n}\n\nconst isDigit = (c: number): boolean => c >= 0x30 && c <= 0x39;\n\n// ------------------------------------------------------------ serialising\n\n/** `json.dumps(value, separators=(\",\", \":\"), ensure_ascii=False)`, byte for byte. */\nexport function dumps(value: JsonValue): string {\n if (value === null) return \"null\";\n if (value === true) return \"true\";\n if (value === false) return \"false\";\n if (typeof value === \"string\") return JSON.stringify(value);\n if (value instanceof JsonNumber) return numberText(value);\n if (Array.isArray(value)) return \"[\" + value.map(dumps).join(\",\") + \"]\";\n const parts: string[] = [];\n for (const [key, item] of value) parts.push(JSON.stringify(key) + \":\" + dumps(item));\n return \"{\" + parts.join(\",\") + \"}\";\n}\n\n/** How `json.dumps` spells a parsed number: ints verbatim (`-0` becomes `0`),\n * floats through `float.__repr__`, non-finite as NaN/Infinity. */\nexport function numberText(n: JsonNumber): string {\n if (!n.isFloat) return /^-0+$/.test(n.text) ? \"0\" : n.text;\n const value = n.value;\n if (Number.isNaN(value)) return \"NaN\";\n if (value === Infinity) return \"Infinity\";\n if (value === -Infinity) return \"-Infinity\";\n return pyFloatRepr(value);\n}\n\n/** `str(value)` for the values the redaction digest sees: str, int, float, bool. */\nexport function pyStr(value: string | boolean | JsonNumber): string {\n if (typeof value === \"string\") return value;\n if (typeof value === \"boolean\") return value ? \"True\" : \"False\";\n if (!value.isFloat) return numberText(value);\n const v = value.value;\n if (Number.isNaN(v)) return \"nan\";\n if (v === Infinity) return \"inf\";\n if (v === -Infinity) return \"-inf\";\n return pyFloatRepr(v);\n}\n\n/**\n * CPython's `repr(float)`: the shortest digits that round-trip (which\n * JavaScript's `String(x)` also produces), laid out Python's way — a\n * trailing `.0` on integral values, scientific notation only below 1e-4 or\n * from 1e16, and exponents of at least two digits with a sign.\n */\nexport function pyFloatRepr(x: number): string {\n if (x === 0) return Object.is(x, -0) ? \"-0.0\" : \"0.0\";\n const sign = x < 0 ? \"-\" : \"\";\n const js = String(Math.abs(x));\n const [mantissa, exponentPart] = js.split(\"e\");\n let exponent = exponentPart ? Number(exponentPart) : 0;\n const [intPart, fracPart = \"\"] = mantissa!.split(\".\");\n let digits = intPart! + fracPart;\n // decpt: how many digits sit before the decimal point (may be <= 0 or > length).\n let decpt = intPart!.length + exponent;\n const leading = digits.match(/^0*/)![0].length;\n digits = digits.slice(leading);\n decpt -= leading;\n digits = digits.replace(/0+$/, \"\");\n if (digits === \"\") return sign + \"0.0\";\n const sci = decpt - 1;\n if (sci >= -4 && sci < 16) {\n if (decpt <= 0) return sign + \"0.\" + \"0\".repeat(-decpt) + digits;\n if (decpt >= digits.length) return sign + digits + \"0\".repeat(decpt - digits.length) + \".0\";\n return sign + digits.slice(0, decpt) + \".\" + digits.slice(decpt);\n }\n exponent = sci;\n const mag = String(Math.abs(exponent)).padStart(2, \"0\");\n return sign + digits[0] + (digits.length > 1 ? \".\" + digits.slice(1) : \"\") + \"e\" + (exponent < 0 ? \"-\" : \"+\") + mag;\n}\n\n/**\n * Python's `round(x, ndigits)` for the redaction policy: an int is returned\n * unchanged, a float is correctly rounded on its exact binary value with ties\n * to even (`round(0.125, 2) == 0.12`), then re-read as the nearest double.\n */\nexport function pyRound(n: JsonNumber, ndigits: number): JsonNumber {\n if (!n.isFloat) return n;\n const x = n.value;\n if (!Number.isFinite(x)) return n;\n const sign = x < 0 ? -1 : 1;\n const magnitude = Math.abs(x);\n // Every double at or above 2^53 is an integer already.\n if (magnitude >= 9007199254740992) return new JsonNumber(pyFloatRepr(x));\n const { m, k } = exactFraction(magnitude); // magnitude = m / 2^k, m odd (or zero)\n let rounded: number;\n if (k <= ndigits) rounded = magnitude; // exact at this precision\n else if (k !== ndigits + 1) rounded = Number(magnitude.toFixed(ndigits)); // no tie possible: correctly rounded\n else {\n // Exactly k = ndigits + 1 fractional digits, the last one a 5: a tie. Half to even.\n const scaled = m * 5n ** BigInt(k); // magnitude * 10^k, an integer\n let kept = scaled / 10n; // magnitude * 10^ndigits, truncated\n if (kept % 2n === 1n) kept += 1n;\n const text = kept.toString().padStart(ndigits + 1, \"0\");\n rounded = ndigits === 0 ? Number(text) : Number(text.slice(0, -ndigits) + \".\" + text.slice(-ndigits));\n }\n return new JsonNumber(pyFloatRepr(sign * rounded));\n}\n\n/** A finite non-negative double as m / 2^k with m odd (m = 0, k = 0 for zero). */\nfunction exactFraction(x: number): { m: bigint; k: number } {\n if (x === 0) return { m: 0n, k: 0 };\n const view = new DataView(new ArrayBuffer(8));\n view.setFloat64(0, x);\n const bits = view.getBigUint64(0);\n const exponent = Number((bits >> 52n) & 0x7ffn);\n let mantissa = bits & ((1n << 52n) - 1n);\n let e: number;\n if (exponent === 0) e = -1074;\n else {\n mantissa |= 1n << 52n;\n e = exponent - 1075;\n }\n while (mantissa !== 0n && (mantissa & 1n) === 0n) {\n mantissa >>= 1n;\n e += 1;\n }\n if (e >= 0) return { m: mantissa << BigInt(e), k: 0 };\n return { m: mantissa, k: -e };\n}\n","/**\n * Named plaintext transforms for cross-world entity mappings.\n *\n * A mapping between two worlds' fields is rarely a raw equality: SpyCloud\n * keeps `phone` as bare digits where a Torchlight client sends\n * `+1 (559) 779-1433`; one world keys people by `email`, another by\n * `email_username`. A transform normalises the plaintext on BOTH sides of a\n * mapping before `storedForms` salts it under each world's slug, so a\n * cross-world query is answerable from the plaintext alone, with no stored\n * join.\n *\n * The set is closed and named — no expressions, no user code — because any\n * client must reproduce a transform from the manifest by itself. This is the\n * TypeScript twin of the Python runtime's `environment/schema/transforms.py`;\n * the golden vectors in `__tests__/transforms.test.ts` and the Python\n * `tests/environment/test_schema_transforms.py` pin the two to each other,\n * byte for byte.\n *\n * Whitespace, for `trim` and `collapse_ws`, is the ASCII set `\" \\t\\n\\r\\f\\v\"`\n * by definition (Python's `str.split()` and JavaScript's `\\s` disagree at the\n * edges of Unicode; `nfkc` first folds a no-break space into a plain one).\n */\n\nimport { createHash } from \"node:crypto\";\n\nimport { pyFloatRepr } from \"../cli/platform/worldData/json\";\n\nexport type Transform = (value: string) => string;\n\nexport const WHITESPACE = \" \\t\\n\\r\\f\\v\";\nconst WHITESPACE_EDGES = new RegExp(`^[${WHITESPACE}]+|[${WHITESPACE}]+$`, \"g\");\nconst WHITESPACE_RUN = new RegExp(`[${WHITESPACE}]+`, \"g\");\nconst NOT_DIGIT = /[^0-9]/g;\n\nexport const STRIP_PREFIX = \"strip_prefix\";\n\nconst trim = (value: string): string => value.replace(WHITESPACE_EDGES, \"\");\n\nconst emailLocalPart = (value: string): string => {\n const at = value.lastIndexOf(\"@\");\n return at === -1 ? value : value.slice(0, at);\n};\n\nconst emailDomain = (value: string): string => {\n const at = value.lastIndexOf(\"@\");\n return at === -1 ? \"\" : value.slice(at + 1).toLowerCase();\n};\n\nconst stripPrefix =\n (prefix: string): Transform =>\n (value) =>\n value.startsWith(prefix) ? value.slice(prefix.length) : value;\n\nconst hex = (algorithm: \"sha1\" | \"sha256\", value: string): string =>\n createHash(algorithm).update(value, \"utf8\").digest(\"hex\");\n\nconst SIMPLE: Record<string, Transform> = {\n lower: (value) => value.toLowerCase(),\n upper: (value) => value.toUpperCase(),\n trim,\n collapse_ws: (value) => trim(value).replace(WHITESPACE_RUN, \" \"),\n nfkc: (value) => value.normalize(\"NFKC\"),\n digits: (value) => value.replace(NOT_DIGIT, \"\"),\n email_local_part: emailLocalPart,\n email_domain: emailDomain,\n // Vendor-style digests: lowercase hex of the utf-8 bytes, unsalted. This is\n // how SpyCloud accepts a hashed selector (`_digests` in its api_handlers).\n sha1: (value) => hex(\"sha1\", value),\n sha256: (value) => hex(\"sha256\", value),\n};\n\n/** The closed set, as a manifest spells it. `strip_prefix` takes its parameter\n * after a colon; the parameter may hold any character but `,`. */\nexport const TRANSFORMS: readonly string[] = [...Object.keys(SIMPLE), `${STRIP_PREFIX}:<prefix>`];\n\n/** The function a transform name denotes; throws when the name is not in the set. */\nexport function parseTransform(name: string): Transform {\n const simple = Object.prototype.hasOwnProperty.call(SIMPLE, name) ? SIMPLE[name] : undefined;\n if (simple) return simple;\n const colon = name.indexOf(\":\");\n if (colon !== -1) {\n const head = name.slice(0, colon);\n const prefix = name.slice(colon + 1);\n if (head === STRIP_PREFIX && prefix && !prefix.includes(\",\")) return stripPrefix(prefix);\n }\n throw new Error(`Unknown transform '${name}'; choose one of ${TRANSFORMS.join(\", \")}`);\n}\n\n/** `str(value)` as the Python runtime spells a number: an integral number is an\n * int, any other its float repr. */\nconst text = (value: string | number): string => {\n if (typeof value === \"string\") return value;\n return Number.isInteger(value) ? String(value) : pyFloatRepr(value);\n};\n\n/**\n * Compose `chain` left to right over `value`.\n *\n * A number is written as Python's `str()` first, the way `_digest` salts one,\n * so a number keyed on one side and a string on the other transform alike. The\n * whole chain is parsed before any step runs: a bad name at the end refuses\n * the mapping outright rather than after a partial result. An empty chain is\n * the identity.\n */\nexport function applyTransforms(value: string | number, chain: readonly string[]): string {\n const steps = chain.map(parseTransform);\n let out = text(value);\n for (const step of steps) out = step(out);\n return out;\n}\n","/**\n * Stored forms: what a world's store holds for a field given its plaintext.\n *\n * A schema world's `[redact]` table (connector.toml) rewrites named fields\n * before they reach disk — `hash` to a slug-salted sha256, `preserve` to a\n * shape-preserving digest, `round` to fewer decimals, `drop` to nothing. A\n * lookup by plaintext therefore has to compute the same form the store did.\n * This module is the TypeScript twin of the Python runtime's `_digest`,\n * `_shaped`, `redaction_of` and `stored_forms` (environment/schema/connector.py):\n * the rule is `\"sha256:\" + sha256(\"<slug>:<plaintext>\")`, no lowercasing, no\n * trimming, no other salt, and the golden vectors in redaction.test.ts pin the\n * two implementations to each other.\n */\n\nimport { createHash } from \"node:crypto\";\n\nimport { JsonNumber, pyFloatRepr, pyRound } from \"../cli/platform/worldData/json\";\nimport { applyTransforms } from \"./transforms\";\n\n/** The `[redact]` table as `describe` reports it (`connection.redact`, and\n * `redact` on `GET /api/public/worlds/{slug}`). */\nexport type RedactPolicy = {\n /** The digest salt: the connector's slug from connector.toml. It can differ\n * from the platform world slug (`spycloud` vs `spycloud-world`); `storedForms`\n * prefers it and falls back to the world slug only when it is absent. */\n slug?: string;\n hash: string[];\n drop: string[];\n preserve: string[];\n round: Record<string, number>;\n};\n\n/** The policy one field is stored under; null when it is stored in the clear. */\nexport type Redaction = \"hash\" | \"drop\" | \"preserve\" | `round:${number}`;\n\n/**\n * A value as the Python runtime would see it. JavaScript has one number\n * type, so an integral number takes Python's `int` path and any other number\n * its `float` path (`100` is `100`, never `100.0`); integers stay exact within\n * the safe range only.\n */\nexport type Plaintext = string | number;\n\nconst isInt = (value: Plaintext): value is number => typeof value === \"number\" && Number.isInteger(value);\n\n/** `str(value)` for an int or str, `repr(value)` for a float — the text the\n * Python runtime salts and shapes. */\nexport function pyText(value: Plaintext): string {\n if (typeof value === \"string\") return value;\n if (Number.isInteger(value)) return String(value);\n if (Number.isNaN(value)) return \"nan\";\n if (!Number.isFinite(value)) return value > 0 ? \"inf\" : \"-inf\";\n return pyFloatRepr(value);\n}\n\n/** The `hash` form: `\"sha256:\" + sha256(\"<slug>:<plaintext>\")` as hex. */\nexport function hashForm(slug: string, plaintext: Plaintext): string {\n return \"sha256:\" + createHash(\"sha256\").update(`${slug}:${pyText(plaintext)}`, \"utf8\").digest(\"hex\");\n}\n\n/**\n * The `preserve` form, the Python `_shaped`: the same length, every ASCII\n * digit still a digit, every ASCII letter still a letter of the same case,\n * everything else (separators, punctuation, non-ASCII) left in place. The\n * bytes come from sha256 of the seed `\"<slug>:<text>\"`, re-keyed as\n * sha256(digest + seed) once the 32 bytes are spent. A number keeps its type:\n * an int keeps its digit count (a leading zero is replaced), a float is re-read.\n */\nexport function preserveForm(slug: string, plaintext: Plaintext): Plaintext {\n const kind = typeof plaintext === \"string\" ? \"str\" : isInt(plaintext) ? \"int\" : \"float\";\n const shaped = shapeText(slug, pyText(plaintext), kind);\n return kind === \"str\" ? shaped : Number(shaped);\n}\n\n/** The shaping itself, on text: `kind` says which of Python's rules apply\n * (letters are re-lettered for a str only; an int keeps its digit count). */\nexport function shapeText(slug: string, text: string, kind: \"str\" | \"int\" | \"float\"): string {\n const seed = Buffer.from(`${slug}:${text}`, \"utf8\");\n let digest = createHash(\"sha256\").update(seed).digest();\n let cursor = 0;\n const out: string[] = [];\n for (const char of text) {\n if (cursor === digest.length) {\n digest = createHash(\"sha256\").update(Buffer.concat([digest, seed])).digest();\n cursor = 0;\n }\n const byte = digest[cursor]!;\n cursor += 1;\n if (char >= \"0\" && char <= \"9\") out.push(String(byte % 10));\n else if (kind === \"str\" && char >= \"a\" && char <= \"z\") out.push(String.fromCharCode(97 + (byte % 26)));\n else if (kind === \"str\" && char >= \"A\" && char <= \"Z\") out.push(String.fromCharCode(65 + (byte % 26)));\n else out.push(char);\n }\n // An int keeps its digit count; int() would drop a leading zero.\n if (kind === \"int\" && out.length > 1 && out[0] === \"0\") out[0] = String(1 + (digest[0]! % 9));\n return out.join(\"\");\n}\n\n/** The `round` form: Python's `round(value, decimals)` — an int unchanged, a\n * float correctly rounded with ties to even; a string is not a number and\n * passes through as the runtime leaves it. */\nexport function roundForm(plaintext: Plaintext, decimals: number): Plaintext {\n if (typeof plaintext === \"string\" || isInt(plaintext) || !Number.isFinite(plaintext)) return plaintext;\n return pyRound(new JsonNumber(pyFloatRepr(plaintext)), decimals).value;\n}\n\n/**\n * The policy a field of this name falls under, ranked as the runtime applies\n * them (drop, hash, preserve, round). Read without a path: a bare name in the\n * table counts, and so does a dotted path whose last segment is the field.\n */\nexport function redactionOf(redact: RedactPolicy | null | undefined, field: string): Redaction | null {\n if (!redact) return null;\n const named = (names: string[] | undefined) =>\n (names ?? []).some((name) => name === field || name.slice(name.lastIndexOf(\".\") + 1) === field);\n if (named(redact.drop)) return \"drop\";\n if (named(redact.hash)) return \"hash\";\n if (named(redact.preserve)) return \"preserve\";\n const decimals = redact.round?.[field];\n if (typeof decimals === \"number\") return `round:${decimals}`;\n return null;\n}\n\n/**\n * Every value the store may hold for `field` given this plaintext:\n *\n * clear field -> [plaintext]\n * hash -> [\"sha256:<hex>\"]\n * preserve -> [the shape-preserving digest]\n * round -> [round(plaintext, decimals)] for a number, [plaintext] otherwise\n * drop -> [] (the field is not on disk: a documented miss, not an error)\n *\n * `world` is what `describeWorld` / the bridge's `describe` return: the slug\n * is the salt, `redact` the table.\n *\n * `transform` — a cross-world mapping's chain (`./transforms`) — runs over the\n * plaintext FIRST, so `hash` and `preserve` salt the normalised text; omitted\n * (or empty) is today's behaviour, byte for byte.\n */\nexport function storedForms(\n world: { slug: string; redact?: RedactPolicy | null },\n field: string,\n plaintext: Plaintext,\n transform?: readonly string[],\n): Plaintext[] {\n if (transform?.length) plaintext = applyTransforms(plaintext, transform);\n const policy = redactionOf(world.redact, field);\n const salt = world.redact?.slug ?? world.slug;\n if (policy === \"drop\") return [];\n if (policy === \"hash\") return [hashForm(salt, plaintext)];\n if (policy === \"preserve\") return [preserveForm(salt, plaintext)];\n if (policy !== null) return [roundForm(plaintext, world.redact!.round[field]!)];\n return [plaintext];\n}\n","/**\n * `queryRows(slug[@ref], entity, {where, resolve, limit, offset})` — the rows\n * of one entity that match a predicate, from\n * `GET /api/public/worlds/{slug}/data?ref=&entity=&where=&limit=&offset=&resolve=`.\n * `where` is field → value, or field → list of values (any of); values match\n * the STORED form as given. With `resolve: true` the values are plaintext and\n * the runtime maps each to its stored form under the world's `[redact]`\n * policy first (a hashed `email` becomes its slug-salted digest; a dropped\n * field resolves to nothing and matches no row — the answer's `resolved`\n * says so). The CLI twin is `gateway worlds data query <slug> <entity>`.\n *\n * `across: true` runs the same plaintext in every world this one links to\n * whose `[dependencies.<alias>.entities]` mapping covers a `where` field;\n * each linked world recomputes its own stored form (after the mapping's\n * transform) at query time — no join on disk, no shared salt. The answer\n * is then {@link WorldQueryAcrossResult}: one group per world, the root\n * first, and with `compare: true` a parity report saying, per field and\n * per world, `matched`, `no match` or `unmapped`.\n */\n\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\nimport type { Plaintext } from \"./redaction\";\n\nexport type WorldQueryWhere = Record<string, Plaintext | Plaintext[]>;\n\nexport type WorldQueryOptions = {\n where?: WorldQueryWhere;\n /** The `where` values are plaintext: resolve each to its stored form before matching. */\n resolve?: boolean;\n limit?: number;\n offset?: number;\n /** Query the linked worlds too; the answer becomes groups. */\n across?: boolean;\n /** With `across`: add the parity report. */\n compare?: boolean;\n};\n\n/** The options that make `queryRows` answer {@link WorldQueryAcrossResult}. */\nexport type WorldQueryAcrossOptions = WorldQueryOptions & { across: true };\n\nexport type WorldQueryResult = {\n slug: string;\n versionId: string;\n kind: string | null;\n entity: string;\n rows: Record<string, unknown>[];\n /** Rows in this page. */\n count: number;\n /** Rows matching in all; null when the store does not count them. */\n total: number | null;\n limit: number;\n offset: number;\n /** With `resolve`: the stored forms each `where` field was matched against\n * (`[]` for a dropped field, which is why such a query matches nothing). */\n resolved?: Record<string, Plaintext[]>;\n entityCounts: Record<string, number>;\n snapshot: WorldQuerySnapshot | null;\n};\n\nexport type WorldQuerySnapshot = {\n snapshotId: string;\n contractHash: string;\n batchDigest: string;\n bytes: number;\n};\n\n/** One world's page inside an across answer: the root (`alias: null`, no\n * `mapping`) or a linked world with the mappings that carried the root's\n * `where` fields into its own entity. */\nexport type WorldQueryGroup = {\n world: { slug: string; alias: string | null; versionId: string };\n entity: string;\n rows: Record<string, unknown>[];\n count: number;\n total: number | null;\n limit: number;\n offset: number;\n resolved?: Record<string, Plaintext[]>;\n mapping?: { field: string; depField: string; transform: string[] }[];\n};\n\nexport type WorldQueryCompareStatus = \"matched\" | \"no match\" | \"unmapped\";\n\n/** Per `where` field, per world: whether the field reached the world and\n * whether any row matched there; `present`/`absent` list the worlds by slug. */\nexport type WorldQueryCompare = {\n present: string[];\n absent: string[];\n perField: {\n field: string;\n worlds: {\n world: string;\n alias: string | null;\n status: WorldQueryCompareStatus;\n /** `<depEntity>.<depField>` and the transform applied (mapped worlds only). */\n depField?: string;\n transform?: string[];\n }[];\n }[];\n};\n\nexport type WorldQueryAcrossResult = {\n slug: string;\n versionId: string;\n kind: string | null;\n entity: string;\n /** The root world first, then one per linked world that was queried. */\n groups: WorldQueryGroup[];\n compare?: WorldQueryCompare;\n entityCounts: Record<string, number>;\n snapshot: WorldQuerySnapshot | null;\n};\n\n/** The query string the route reads; `where` travels as URL-encoded JSON and\n * `ref` (the `@ref` of `slug@ref`) picks the version. */\nexport function queryRowsSearch(entity: string, opts: WorldQueryOptions = {}, ref?: string): string {\n const search = new URLSearchParams();\n if (ref) search.set(\"ref\", ref);\n search.set(\"entity\", entity);\n if (opts.where && Object.keys(opts.where).length) search.set(\"where\", JSON.stringify(opts.where));\n if (opts.limit !== undefined) search.set(\"limit\", String(opts.limit));\n if (opts.offset !== undefined) search.set(\"offset\", String(opts.offset));\n if (opts.resolve) search.set(\"resolve\", \"true\");\n if (opts.across) search.set(\"across\", \"true\");\n if (opts.compare) search.set(\"compare\", \"true\");\n return `?${search.toString()}`;\n}\n\n/** One version of the world, queried: the main tip for a bare slug, or the\n * version `slug@ref` names (branch, tag, semver pin or hash prefix — the\n * `bench pull` grammar; a ref nothing answers to is the platform's 404, never\n * the head). With `across: true` the answer is the groups shape. */\nexport async function queryRows(\n slug: string,\n entity: string,\n opts: WorldQueryAcrossOptions,\n options?: WorldsClientOptions,\n): Promise<WorldQueryAcrossResult>;\nexport async function queryRows(\n slug: string,\n entity: string,\n opts?: WorldQueryOptions,\n options?: WorldsClientOptions,\n): Promise<WorldQueryResult>;\nexport async function queryRows(\n slugRef: string,\n entity: string,\n opts: WorldQueryOptions = {},\n options: WorldsClientOptions = {},\n): Promise<WorldQueryResult | WorldQueryAcrossResult> {\n const [slug, ref] = slugRef.split(\"@\", 2) as [string, string | undefined];\n if (!slug || ref === \"\") throw new Error(`queryRows needs a slug, optionally slug@ref (got ${slugRef})`);\n if (!entity) throw new Error(\"queryRows needs an entity\");\n if (opts.compare && !opts.across) throw new Error(\"queryRows: compare needs across\");\n return apiRequest<WorldQueryResult | WorldQueryAcrossResult>(\n options,\n \"GET\",\n `/api/public/worlds/${encodeURIComponent(slug)}/data${queryRowsSearch(entity, opts, ref)}`,\n );\n}\n","/**\n * `migrateWorld(slug)` — convert a stored world into a schema world, from\n * `POST /api/public/worlds/{slug}/migrate`; `migrateProjectWorlds()` plans\n * (or migrates) every connector world in the project from\n * `POST /api/public/worlds/migrate`. Dry run by default: the report says\n * what the version is, what the conversion does, or why it cannot; `apply`\n * commits the migrated tree as the next version (\"Migrated to a schema\n * world\"). Targets are the platform's connector worlds; a hand-built world\n * needs `force`. The CLI twin is `gateway worlds migrate`.\n */\n\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\n\nexport type WorldMigrationRefusal = {\n code: string;\n message: string;\n /** Paths the conversion needed and did not find. */\n missing: string[];\n};\n\nexport type WorldMigrationReport = {\n slug: string;\n containerId: string;\n versionId: string;\n /** True when the container was created from a connector template. */\n connectorWorld: boolean;\n /** schema | api-bundle | legacy-tools | harbor | verifiers */\n shape: string;\n target: \"schema\";\n /** True when the world already is a schema world. */\n unchanged: boolean;\n /** The dry-run report, one sentence each. */\n actions: string[];\n /** Files the migrated tree holds; 0 on a refusal. */\n files: number;\n refusal: WorldMigrationRefusal | null;\n /** True when this call committed the migrated tree. */\n applied: boolean;\n version: { id: string; contentHash: string } | null;\n};\n\nexport type MigrateWorldOptions = {\n /** Commit the migrated tree as the next version. Default false: dry run. */\n apply?: boolean;\n /** Migrate a world that was not created from a connector template. */\n force?: boolean;\n};\n\nexport async function migrateWorld(\n slug: string,\n input: MigrateWorldOptions = {},\n options: WorldsClientOptions = {},\n): Promise<WorldMigrationReport> {\n if (slug.includes(\"@\"))\n throw new Error(\n `migrateWorld converts a world's head version: pass the slug without @ref (got ${slug})`,\n );\n return apiRequest<WorldMigrationReport>(\n options,\n \"POST\",\n `/api/public/worlds/${encodeURIComponent(slug)}/migrate`,\n {\n ...(input.apply === undefined ? {} : { apply: input.apply }),\n ...(input.force === undefined ? {} : { force: input.force }),\n },\n );\n}\n\n/** Every connector world in the project, one report each. */\nexport async function migrateProjectWorlds(\n input: { apply?: boolean } = {},\n options: WorldsClientOptions = {},\n): Promise<{ worlds: WorldMigrationReport[]; applied: boolean }> {\n return apiRequest<{ worlds: WorldMigrationReport[]; applied: boolean }>(\n options,\n \"POST\",\n \"/api/public/worlds/migrate\",\n input.apply === undefined ? {} : { apply: input.apply },\n );\n}\n","/**\n * Records into a world's rows — the record contract, an interceptor that\n * writes it, the conversion from TOOL observations, and the door in.\n *\n * A tool's response is not the entity's shape, and nothing here assumes it\n * is. The workflow with real data is: pull the raw tool calls, look at them,\n * then ingest them through the route you declare — {@link ingest} with a\n * `transform` (your own `transform(records) -> {entity: [rows]}`, a function\n * or a script), with a `map` (an `ingest.toml` mapping for shapes that need\n * no code), or with neither, when the world's own `ingest.toml` applies or\n * each record's tool is a connector operation whose result *is* the\n * operation's response body (its `[ingest]` projection in `connector.toml`).\n * Mappings and projections run in the schema runtime (Python, bundled with\n * the CLI or on the platform), never re-implemented here; a transform runs\n * where you are.\n *\n * The record, one JSON object per line:\n *\n * {\"tool\": \"list_users\", \"args\": {\"team\": \"t1\"}, \"result\": {\"users\": [...]},\n * \"at\": \"2026-09-15T10:00:00Z\", \"session\": \"optional\", \"source\": \"optional free text\"}\n *\n * A `gateway worlds session export` line (`{seq, kind, tool, args, result,\n * error, completedAt}`) is accepted as it is. Redaction is optional and OFF\n * by default everywhere here: rows land as the tools returned them unless\n * `redact: \"apply\"` (the world's `[redact]` policy) or `\"refuse\"` is asked for.\n *\n * - {@link captureToolCalls} wraps an agent's tool functions so every real\n * call is recorded — the agent changes nothing.\n * - {@link toolCallsFromObservations} turns a trace's TOOL observations into\n * records (the `--from traces` path of `gateway worlds data ingest`).\n * - {@link ingest} puts records into a world through a transform, a mapping\n * or the operations: a local directory through the bundled runtime, a\n * platform slug through the batch lane. {@link ingestToolCalls} is the same\n * door with neither transform nor mapping of your own.\n */\n\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\n\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\n\nexport type ToolCallRecord = {\n /** The operation name in the world's `connector.toml`. */\n tool: string;\n /** The call's arguments, by name: what `carry_args` reads. */\n args: Record<string, unknown>;\n /** The operation's response body, as the tool returned it. */\n result?: unknown;\n /** ISO time of the call. */\n at?: string;\n /** The session the call belongs to, when there is one. */\n session?: string;\n /** Free text: where the record came from. */\n source?: string;\n /** Set instead of `result` when the call threw; ingest skips it, counted. */\n error?: string;\n};\n\nexport type RedactMode = \"off\" | \"apply\" | \"refuse\";\nexport type IngestMode = \"append\" | \"replace\";\n\n// ---------------------------------------------------------------- the mapping\n\n/** How one entity field is set: an item path, or a table naming exactly one of `from`, `literal`, `template`, `hash`. */\nexport type IngestFieldSpec =\n | string\n | {\n /** Item path (`name`, `customer.id`, `emails[0]`); `$`-paths reach the record: `$tool`, `$at`, `$index`, `$session`, `$source`, `$source.id`, `$source.trace`, `$record.<path>`, `$parent.<path>`. */\n from?: string;\n literal?: string | number | boolean;\n /** `{path}` holes are filled from the item or the record; a hole with no value refuses the record. */\n template?: string;\n /** sha256 of the JSON array of these paths' values; unset when any is missing. */\n hash?: string[];\n /** A chain from the closed transform set, applied to `from` or `template`. */\n transform?: string[];\n /** Used when `from` is missing or null. */\n default?: string | number | boolean;\n /** Coerce the value; a CSV cell is text until this says otherwise. */\n type?: \"string\" | \"integer\" | \"number\" | \"boolean\";\n };\n\nexport type IngestExplode = {\n /** Item path to a list (or one object) of children. */\n path: string;\n entity: string;\n /** child field <- parent ENTITY field (after the parent's mapping). */\n carry?: Record<string, string>;\n fields?: Record<string, IngestFieldSpec>;\n};\n\nexport type IngestSource = {\n /** The tool name (or several), or `\"*\"` for rows and csv records. */\n name: string | string[];\n kind?: \"tool-call\" | \"rows\" | \"csv\";\n /** Path into the record: `result`, `result.data[*]`, `args`, `$record`. */\n select: string;\n /** All must hold on the selected item: a literal, or `{ present: true | false }`. */\n when?: Record<string, string | number | boolean | { present: boolean }>;\n entity: string;\n /** Item path that dates the row for `on_conflict`; default the record's `at`. */\n at?: string;\n fields?: Record<string, IngestFieldSpec>;\n explode?: IngestExplode[];\n};\n\n/** `ingest.toml`, parsed: the grammar the schema runtime's `mapping.py` checks and applies. */\nexport type IngestMapping = {\n ingest?: { on_conflict?: \"latest\" | \"first\"; unmatched?: \"refuse\" | \"skip\" };\n sources: IngestSource[];\n};\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n// ---------------------------------------------------------------- records\n\nexport type ParsedToolCall = {\n /** The record in the contract's shape, when it is a tool call with a result. */\n record: ToolCallRecord | null;\n /** Why a well-formed record carries no rows by design (a `seed` line, a failed call). */\n skip: string | null;\n /** What is wrong with the record. */\n refusal: string | null;\n};\n\n/**\n * One raw record — the contract's shape or a session-export line — judged the\n * way the runtime judges it (`ingest.normalize_record`): the same skips, the\n * same refusals, so a file checked here is what the runtime will accept.\n */\nexport function parseToolCallRecord(raw: unknown): ParsedToolCall {\n const none = { record: null, skip: null };\n if (!isObject(raw)) return { ...none, refusal: \"record is not an object\" };\n const kind = raw.kind;\n if (kind !== undefined && kind !== null && kind !== \"call\") return { record: null, skip: `kind ${String(kind)}`, refusal: null };\n const tool = raw.tool;\n if (typeof tool !== \"string\" || !tool) return { ...none, refusal: \"record has no tool name\" };\n if (raw.error !== undefined && raw.error !== null && raw.error !== \"\") return { record: null, skip: \"call failed\", refusal: null };\n const args = raw.args ?? {};\n if (!isObject(args)) return { ...none, refusal: `args of ${tool} is not an object` };\n if (!(\"result\" in raw)) return { ...none, refusal: `record of ${tool} has no result` };\n const at = raw.at ?? raw.completedAt;\n const record: ToolCallRecord = { tool, args, result: raw.result };\n if (typeof at === \"string\") record.at = at;\n if (typeof raw.session === \"string\") record.session = raw.session;\n if (typeof raw.source === \"string\") record.source = raw.source;\n return { record, skip: null, refusal: null };\n}\n\n/**\n * Raw records from files: JSONL (one object per line) or one JSON array, several\n * files concatenated in order. A line that is not JSON, or not an object, throws\n * naming the file and line. Each record's shape is judged later, per record, so\n * the report can point at the index.\n */\nexport function readToolCallRecords(paths: string[]): unknown[] {\n const records: unknown[] = [];\n for (const file of paths) records.push(...toolCallRecordsIn(fs.readFileSync(file, \"utf8\"), file));\n return records;\n}\n\n/** The records in one text, named `where` in a refusal. */\nexport function toolCallRecordsIn(text: string, where: string): unknown[] {\n const stripped = text.trim();\n if (!stripped) return [];\n if (stripped.startsWith(\"[\")) {\n const listed = JSON.parse(stripped) as unknown;\n if (!Array.isArray(listed)) throw new Error(`${where} is neither a JSON array nor JSON Lines`);\n listed.forEach((item, index) => {\n if (!isObject(item)) throw new Error(`${where}[${index}] is not an object`);\n });\n return listed;\n }\n const records: unknown[] = [];\n const lines = text.split(/\\r?\\n/);\n for (let index = 0; index < lines.length; index++) {\n const line = lines[index]!;\n if (!line.trim()) continue;\n let item: unknown;\n try {\n item = JSON.parse(line);\n } catch {\n throw new Error(`${where}:${index + 1} is not JSON`);\n }\n if (!isObject(item)) throw new Error(`${where}:${index + 1} is not an object`);\n records.push(item);\n }\n return records;\n}\n\n// ---------------------------------------------------------------- capture\n\n/**\n * Where {@link captureToolCalls} writes each record: an array (pushed), a file\n * path (JSONL, one record per line, appended), or a callback (awaited).\n */\nexport type ToolCallSink = ToolCallRecord[] | string | ((record: ToolCallRecord) => unknown | Promise<unknown>);\n\nexport type ToolFunctions = Record<string, (args: Record<string, unknown>) => Promise<unknown>>;\n\nasync function emit(sink: ToolCallSink, record: ToolCallRecord): Promise<void> {\n if (Array.isArray(sink)) {\n sink.push(record);\n return;\n }\n if (typeof sink === \"string\") {\n fs.appendFileSync(sink, JSON.stringify(record) + \"\\n\");\n return;\n }\n if (typeof sink === \"function\") {\n await sink(record);\n return;\n }\n throw new TypeError(\"sink must be an array, a file path, or a function\");\n}\n\n/**\n * Wrap a name → async function map — the shape the Vercel AI SDK's tools and a\n * `WorldToolkit`'s `impls` share — so every call is recorded as a tool-call\n * record into `sink`, and hand back the same map. The agent changes nothing:\n * each wrapped function returns what the original returned, and an error is\n * thrown through untouched (recorded with `error` and no `result`, which\n * ingest skips and counts). Nothing is redacted here; redaction is optional\n * and off by default on the ingest side.\n *\n * const tools = captureToolCalls({ list_users: realVendor.listUsers }, \"calls.jsonl\");\n * await runMyAgent(tools); // real vendor, every call recorded\n * await ingestToolCalls(\"acme-crm\", readToolCallRecords([\"calls.jsonl\"]));\n */\nexport function captureToolCalls<T extends ToolFunctions>(\n tools: T,\n sink: ToolCallSink,\n opts: { session?: string; source?: string } = {},\n): T {\n const wrapped: ToolFunctions = Object.create(null);\n for (const [name, fn] of Object.entries(tools)) {\n wrapped[name] = async (args: Record<string, unknown> = {}) => {\n const record: ToolCallRecord = { tool: name, args, at: new Date().toISOString() };\n if (opts.session) record.session = opts.session;\n if (opts.source) record.source = opts.source;\n let result: unknown;\n try {\n result = await fn(args);\n } catch (error) {\n record.error = error instanceof Error ? error.message || error.name : String(error);\n await emit(sink, record);\n throw error;\n }\n record.result = result;\n await emit(sink, record);\n return result;\n };\n }\n return wrapped as T;\n}\n\n// ---------------------------------------------------------------- observations\n\n/** What a TOOL observation carries, as `GET /api/public/observations` and\n * `GET /api/public/sessions/{id}?includeIO=true` return it. Both routes decode\n * stored JSON text once on the way out (`parseIoAsJson` defaults to true on the\n * v1 route; the session route renders with the same default), so `input` and\n * `output` arrive as the values the tool saw — an object, or a string when the\n * tool really produced text. Nothing here parses them again. */\nexport type ObservationLike = {\n id?: string;\n traceId?: string | null;\n type?: string;\n name?: string | null;\n input?: unknown;\n output?: unknown;\n startTime?: string | Date;\n level?: string;\n statusMessage?: string | null;\n};\n\nexport type ObservationConversion = {\n records: ToolCallRecord[];\n /** TOOL observations whose name is not one of the world's operations, by name. */\n unknownTools: Record<string, number>;\n /** Observations that were not converted, by reason. */\n skipped: Record<string, number>;\n};\n\nconst isoOf = (value: string | Date | undefined): string | undefined =>\n value instanceof Date ? value.toISOString() : typeof value === \"string\" ? value : undefined;\n\n/**\n * TOOL observations → tool-call records: `name` is the tool, `input` the args,\n * `output` the result, `startTime` the time, `trace:<traceId>/<id>` the source.\n * `input`/`output` arrive from the public API already decoded (it parses the\n * stored text once), so they are taken as they are: a string `output` stays a\n * string even when it looks like JSON; an `input` that is not an object leaves\n * `args` empty rather than guessed.\n * Only `type: \"TOOL\"` converts. With `tools` (the world's operation names) an\n * observation for any other tool is counted in `unknownTools`, not converted.\n * An `ERROR`-level observation converts with `error` set, so ingest counts it\n * as a failed call instead of projecting its output.\n */\nexport function toolCallsFromObservations(\n observations: ObservationLike[],\n opts: { tools?: Iterable<string> | null; session?: string; since?: string } = {},\n): ObservationConversion {\n const known = opts.tools ? new Set(opts.tools) : null;\n const sinceMs = opts.since ? Date.parse(opts.since) : NaN;\n const out: ObservationConversion = { records: [], unknownTools: {}, skipped: {} };\n const skip = (reason: string) => {\n out.skipped[reason] = (out.skipped[reason] ?? 0) + 1;\n };\n for (const observation of observations) {\n if (observation.type !== \"TOOL\") {\n skip(`type ${observation.type ?? \"unknown\"}`);\n continue;\n }\n const tool = observation.name;\n if (typeof tool !== \"string\" || !tool) {\n skip(\"no name\");\n continue;\n }\n const at = isoOf(observation.startTime);\n if (!Number.isNaN(sinceMs) && at !== undefined && Date.parse(at) < sinceMs) {\n skip(\"before since\");\n continue;\n }\n if (known && !known.has(tool)) {\n out.unknownTools[tool] = (out.unknownTools[tool] ?? 0) + 1;\n continue;\n }\n const record: ToolCallRecord = { tool, args: isObject(observation.input) ? observation.input : {} };\n if (observation.level === \"ERROR\") record.error = observation.statusMessage || \"ERROR\";\n else record.result = observation.output;\n if (at !== undefined) record.at = at;\n if (opts.session) record.session = opts.session;\n record.source = `trace:${observation.traceId ?? \"?\"}/${observation.id ?? \"?\"}`;\n out.records.push(record);\n }\n return out;\n}\n\n// ---------------------------------------------------------------- the door\n\nexport type IngestRefusal = { index: number | null; tool: string | null; reason: string; pointer?: string };\n\n/** One `[[sources]]` of a mapping in the report. */\nexport type IngestSourceReport = {\n name: string;\n kind: string;\n select: string;\n entity: string;\n records: number;\n items: number;\n rows: Record<string, number>;\n /** Source fields no line of the source reads, with a sample value. */\n unmappedFields: Record<string, string>;\n /** Entity fields the source never sets, per entity. */\n unsetFields: Record<string, string[]>;\n};\n\nexport type IngestToolCallsReport = {\n world: string;\n /** How the rows were produced. */\n via?: \"transform\" | \"map\" | \"operations\" | \"rows\";\n /** `via: \"map\"`: each source's accounting. */\n sources?: IngestSourceReport[];\n /** `via: \"map\"` with `unmatched = \"skip\"`: records no source claimed, by tool name. */\n unmatched?: Record<string, number>;\n /** `via: \"operations\"`: that this was the operation projection, not a mapping. */\n note?: string;\n /** `via: \"transform\"`: what the script wrote to stderr. */\n stderr?: string;\n /** Records given. */\n records: number;\n /** Records that yielded rows. */\n ingested: number;\n /** Records that carried no rows by design, by reason. */\n skipped: Record<string, number>;\n /** What was wrong, per record; with any, nothing was written. */\n refusals: IngestRefusal[];\n /** Rows projected, per entity. */\n rows: Record<string, number>;\n dryRun: boolean;\n redact: RedactMode;\n changed: boolean;\n kind?: string;\n entityCounts?: Record<string, number>;\n /** A slug that was pushed: the batch's final status (`state`, `versionId`, …). */\n batch?: Record<string, unknown>;\n};\n\nexport type IngestToolCallsOptions = WorldsClientOptions & {\n /** Optional, default `\"off\"`: rows land as the tools returned them. */\n redact?: RedactMode;\n /** Project and prove the rows; write and upload nothing. */\n dryRun?: boolean;\n mode?: IngestMode;\n /** Change reason for the version a slug cuts. */\n message?: string;\n};\n\nexport type IngestReport = IngestToolCallsReport;\n\nexport type IngestOptions = IngestToolCallsOptions & {\n /** Your own `transform(records) -> {entity: [rows]}`: a function (run here) or a script path (`.py`, `.ts`, `.mjs`; a subprocess with a time limit and sockets disabled). */\n transform?: string | ((records: unknown[]) => Rows | Promise<Rows>);\n /** An `ingest.toml` mapping: its text, or the parsed table. Exclusive with `transform`. */\n map?: string | IngestMapping;\n /** For a script transform; default 120 000. */\n timeoutMs?: number;\n};\n\ntype Rows = Record<string, Record<string, unknown>[]>;\n\nfunction credentialsOf(options: WorldsClientOptions): { host: string; publicKey: string; secretKey: string } | null {\n const host = (options.host ?? process.env.GATEWAY_HOST ?? \"https://withgateway.ai\").replace(/\\/+$/, \"\");\n const publicKey = options.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;\n const secretKey = options.secretKey ?? process.env.GATEWAY_SECRET_KEY;\n return publicKey && secretKey ? { host, publicKey, secretKey } : null;\n}\n\n/**\n * Records into a world through the route you declare. `world` is a local\n * directory (written in place through the bundled schema runtime) or a\n * platform slug (pulled to a temporary directory, the rows produced and\n * proven there, then pushed through the chunked batch lane as a new version).\n *\n * With `transform` the rows are what your code returns; with `map` (or the\n * world's own `ingest.toml`) what the mapping declares; with neither, each\n * tool-call record's tool resolves to an operation of `connector.toml` and\n * its result goes through that operation's `[ingest]` projection (the report\n * says `via: \"operations\"`). A transform that fails or returns the wrong\n * shape throws. `redact` is optional and defaults to `\"off\"`.\n */\nexport async function ingest(world: string, records: unknown[], options: IngestOptions = {}): Promise<IngestReport> {\n const { ingestLocalToolCalls, importLocalWorldData, checkLocalWorldData } = await import(\"../cli/runtime/data\");\n if (options.transform !== undefined && options.map !== undefined) throw new Error(\"records go through one of transform, map\");\n const redact = options.redact ?? \"off\";\n const mode = options.mode ?? \"append\";\n const dryRun = Boolean(options.dryRun);\n const creds = credentialsOf(options);\n const local = fs.existsSync(world) && fs.statSync(world).isDirectory();\n const map = options.map === undefined ? undefined : options.map;\n\n let rows: Rows | null = null;\n let stderr = \"\";\n if (options.transform !== undefined) {\n const { transformRecords } = await import(\"../cli/platform/worldData/transform\");\n ({ rows, stderr } = await transformRecords(options.transform, records, { timeoutMs: options.timeoutMs }));\n }\n\n if (local) {\n if (rows === null) return reportOf(world, await ingestLocalToolCalls(world, records, { redact, dryRun, mode, map }, creds), redact);\n const landed = dryRun ? await checkLocalWorldData(world, rows, creds, { redact }) : await importLocalWorldData(world, rows, { mode, redact }, creds);\n return transformReport(world, records.length, rows, stderr, { dryRun, redact, changed: !dryRun && landed.changed, kind: landed.kind, entityCounts: landed.entity_counts });\n }\n if (!creds) throw new Error(\"Gateway keys missing: set GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY (or pass publicKey/secretKey).\");\n const { pull } = await import(\"./hub\");\n const slug = world.split(\"@\", 1)[0]!;\n const scratch = fs.mkdtempSync(path.join(os.tmpdir(), \"gateway-ingest-\"));\n try {\n const pulled = await pull(world, path.join(scratch, slug), options);\n // Produced and proven against the pulled contract; the platform's batch\n // lane checks every row again and redacts there, so this pass runs with\n // redaction off and hands the rows on as they were produced.\n let report: IngestReport;\n let projected: Rows;\n if (rows === null) {\n const proven = await ingestLocalToolCalls(pulled.dir, records, { redact: \"off\", dryRun: true, mode, map }, creds);\n report = reportOf(world, proven, redact);\n projected = proven.projected ?? {};\n } else {\n const proven = await checkLocalWorldData(pulled.dir, rows, creds);\n report = transformReport(world, records.length, rows, stderr, { dryRun, redact, changed: false, kind: proven.kind, entityCounts: proven.entity_counts });\n projected = rows;\n }\n report.dryRun = dryRun;\n if (dryRun || report.refusals.length || !Object.keys(projected).length) return report;\n const { pushRows } = await import(\"../cli/platform/worldData/push\");\n const status = await pushRows(creds, slug, projected, { mode, redact, message: options.message });\n report.batch = status;\n report.changed = status.state === \"applied\" || status.state === \"published\";\n if (status.entityCounts) report.entityCounts = status.entityCounts;\n return report;\n } finally {\n fs.rmSync(scratch, { recursive: true, force: true });\n }\n}\n\n/**\n * Tool-call records into a world with neither a transform nor a mapping of\n * your own: the world's `ingest.toml` when it has one, else each record's\n * tool through its operation's `[ingest]` projection (an unknown tool is a\n * refusal naming it and nothing is written). {@link ingest} with the same\n * options.\n */\nexport async function ingestToolCalls(world: string, records: unknown[], options: IngestToolCallsOptions = {}): Promise<IngestToolCallsReport> {\n return ingest(world, records, options);\n}\n\nfunction transformReport(\n world: string,\n records: number,\n rows: Rows,\n stderr: string,\n outcome: { dryRun: boolean; redact: RedactMode; changed: boolean; kind?: string; entityCounts?: Record<string, number> },\n): IngestReport {\n return {\n world,\n via: \"transform\",\n ...(stderr ? { stderr } : {}),\n records,\n ingested: records,\n skipped: {},\n refusals: [],\n rows: Object.fromEntries(Object.entries(rows).map(([entity, listed]) => [entity, listed.length])),\n dryRun: outcome.dryRun,\n redact: outcome.redact,\n changed: outcome.changed,\n ...(outcome.kind ? { kind: outcome.kind } : {}),\n ...(outcome.entityCounts ? { entityCounts: outcome.entityCounts } : {}),\n };\n}\n\nfunction reportOf(\n world: string,\n local: {\n via?: IngestReport[\"via\"];\n sources?: { name: string; kind: string; select: string; entity: string; records: number; items: number; rows: Record<string, number>; unmapped_fields: Record<string, string>; unset_fields: Record<string, string[]> }[];\n unmatched?: Record<string, number>;\n note?: string;\n records: number;\n ingested: number;\n skipped: Record<string, number>;\n refusals: IngestRefusal[];\n rows: Record<string, number>;\n dry_run: boolean;\n changed: boolean;\n kind?: string;\n entity_counts?: Record<string, number>;\n },\n redact: RedactMode,\n): IngestToolCallsReport {\n return {\n world,\n ...(local.via ? { via: local.via } : {}),\n ...(local.sources ? { sources: local.sources.map(({ unmapped_fields, unset_fields, ...rest }) => ({ ...rest, unmappedFields: unmapped_fields, unsetFields: unset_fields })) } : {}),\n ...(local.unmatched ? { unmatched: local.unmatched } : {}),\n ...(local.note ? { note: local.note } : {}),\n records: local.records,\n ingested: local.ingested,\n skipped: local.skipped,\n refusals: local.refusals,\n rows: local.rows,\n dryRun: local.dry_run,\n redact,\n changed: local.changed,\n ...(local.kind ? { kind: local.kind } : {}),\n ...(local.entity_counts ? { entityCounts: local.entity_counts } : {}),\n };\n}\n\n/** The TOOL observations of one session, every trace's, from `GET /api/public/sessions/{id}?includeIO=true`. */\nexport async function sessionToolObservations(sessionId: string, options: WorldsClientOptions = {}): Promise<ObservationLike[]> {\n const session = await apiRequest<{ traces?: { id?: string; observations?: ObservationLike[] }[] }>(\n options,\n \"GET\",\n `/api/public/sessions/${encodeURIComponent(sessionId)}?includeIO=true`,\n );\n const out: ObservationLike[] = [];\n for (const trace of session.traces ?? [])\n for (const observation of trace.observations ?? []) out.push({ traceId: trace.id ?? null, ...observation });\n return out;\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\n\n/**\n * The CLI sandbox: a server-side workspace opened on a READY version of a\n * world (`/workspace/env` in the console agent's sandbox), edited and run\n * there, and committed straight into the version service — the source\n * never lands on the caller's disk. One client under both `gateway worlds\n * sandbox …` and `gateway bench sandbox …`; the Python twin is\n * `gatewaysdk.benchmark_hub.sandbox.WorldSandboxClient`.\n */\n\n/** Mirrors `SandboxSummaryResponse` (web/features/public-api/types/world-sandboxes.ts). */\nexport type SandboxSummary = {\n sandboxId: string;\n slug: string;\n containerId: string;\n /** The version the next commit is validated against; advances on commit. */\n baseVersionId: string;\n status: \"open\" | \"closed\";\n lastCommitVersionId: string | null;\n createdAt: string;\n};\n\nexport type SandboxOpened = SandboxSummary & {\n baseContentHash: string;\n branch: string;\n dataSnapshotId: string | null;\n fileCount: number;\n workdir: string;\n};\n\nexport type SandboxExecResult = {\n exitCode: number;\n stdout: string;\n stderr: string;\n timedOut: boolean;\n truncated: boolean;\n durationMs: number;\n};\n\nexport type SandboxChanges = { added: string[]; modified: string[]; removed: string[] };\n\nexport type SandboxCheckResult = {\n ok: boolean;\n contentHash: string | null;\n noChange: boolean;\n fileCount: number;\n changes: SandboxChanges;\n warnings: string[];\n error: string | null;\n};\n\nexport type SandboxCommitResult = {\n versionId: string;\n contentHash: string;\n branch: string;\n deduped: boolean;\n noChange: boolean;\n changes: SandboxChanges;\n};\n\n/** `slug` or `slug@ref` → the open body; a bare slug opens the latest READY version. */\nexport function parseSlugRef(slugRef: string): { slug: string; ref?: string } {\n const at = slugRef.indexOf(\"@\");\n if (at === -1) return { slug: slugRef };\n return { slug: slugRef.slice(0, at), ref: slugRef.slice(at + 1) };\n}\n\nconst sid = encodeURIComponent;\n\nexport class WorldSandboxClient {\n constructor(private readonly options: WorldsClientOptions = {}) {}\n\n open(target: { slug: string; ref?: string }): Promise<SandboxOpened> {\n return apiRequest(this.options, \"POST\", \"/api/public/benchmark-containers/sandboxes\", target);\n }\n\n status(sandboxId: string): Promise<SandboxSummary> {\n return apiRequest(this.options, \"GET\", `/api/public/benchmark-containers/sandboxes/${sid(sandboxId)}`);\n }\n\n async read(sandboxId: string, filePath: string): Promise<{ path: string; size: number; bytes: Buffer }> {\n const res = await apiRequest<{ path: string; size: number; contentBase64: string }>(\n this.options,\n \"GET\",\n `/api/public/benchmark-containers/sandboxes/${sid(sandboxId)}/file?path=${encodeURIComponent(filePath)}`,\n );\n return { path: res.path, size: res.size, bytes: Buffer.from(res.contentBase64, \"base64\") };\n }\n\n write(sandboxId: string, filePath: string, bytes: Buffer): Promise<{ path: string; size: number }> {\n return apiRequest(this.options, \"PUT\", `/api/public/benchmark-containers/sandboxes/${sid(sandboxId)}/file`, {\n path: filePath,\n contentBase64: bytes.toString(\"base64\"),\n });\n }\n\n exec(\n sandboxId: string,\n input: { command: string; cwd?: string; timeoutMs?: number },\n ): Promise<SandboxExecResult> {\n return apiRequest(this.options, \"POST\", `/api/public/benchmark-containers/sandboxes/${sid(sandboxId)}/exec`, input);\n }\n\n check(sandboxId: string): Promise<SandboxCheckResult> {\n return apiRequest(this.options, \"POST\", `/api/public/benchmark-containers/sandboxes/${sid(sandboxId)}/check`, {});\n }\n\n commit(sandboxId: string, input: { message: string; branch?: string }): Promise<SandboxCommitResult> {\n return apiRequest(this.options, \"POST\", `/api/public/benchmark-containers/sandboxes/${sid(sandboxId)}/commit`, input);\n }\n\n close(sandboxId: string): Promise<SandboxSummary> {\n return apiRequest(this.options, \"DELETE\", `/api/public/benchmark-containers/sandboxes/${sid(sandboxId)}`);\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\nimport type { WorldTaskIdRef } from \"./session\";\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/** A platform answer outside 2xx, its status kept so a caller can act on one\n * code (a 409 on a name already taken) instead of parsing the message. */\nexport class ApiError extends Error {\n constructor(\n public readonly status: number,\n method: string,\n path: string,\n body: string,\n ) {\n super(`${method} ${path} -> ${status}: ${body}`);\n this.name = \"ApiError\";\n }\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\" | \"PATCH\" | \"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) throw new ApiError(res.status, method, path, text.slice(0, 400));\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\n/** What a run config selects for the runner to work through. A config runs\n * EITHER the bundle's own scenarios (`taskNames`, `taskSetDatasetId`) OR the\n * project's stored tasks (`worldTasks`, api worlds only) — never both. A\n * stored task ref without `version` runs the task's current version at\n * dispatch time; with it, that version forever. */\nexport type RunConfigInput = {\n id?: string;\n name: string;\n models: string[];\n parallelism?: number;\n numExamples?: number;\n rolloutsPerExample?: number;\n timeoutMinutes?: number;\n agent?: string;\n taskSetDatasetId?: string | null;\n taskNames?: string[];\n worldTasks?: WorldTaskIdRef[];\n autoRunOnPush?: boolean;\n};\n\n/** Create a run config, or update the one named by `id`. */\nexport async function upsertRunConfig(\n input: RunConfigInput,\n options: WorldsClientOptions = {},\n): Promise<RunConfigSummary> {\n return apiRequest<RunConfigSummary>(\n options,\n \"POST\",\n \"/api/public/benchmark-containers/run-configs\",\n input,\n );\n}\n\n/** `id[@version]` items (comma-separated or an array) → stored task refs;\n * the spelling `bench run-configs create --world-tasks` takes. */\nexport function parseWorldTaskRefs(spec: string | string[]): WorldTaskIdRef[] {\n const items = (Array.isArray(spec) ? spec : spec.split(\",\"))\n .map((s) => s.trim())\n .filter(Boolean);\n return items.map((item) => {\n const at = item.lastIndexOf(\"@\");\n if (at < 0) return { id: item };\n const id = item.slice(0, at);\n const version = Number(item.slice(at + 1));\n if (!id || !Number.isInteger(version) || version < 1)\n throw new Error(\n `stored task ref '${item}' is not <id> or <id>@<version> (version a positive integer)`,\n );\n return { id, version };\n });\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 — a bundled task's\n * name or an inline `WorldTaskSpec`: the platform boots (or reuses) a warm\n * container, and your agent calls its tools through the platform. See\n * worlds/session.ts.\n */\n async open(\n task: import(\"./session\").WorldTaskRef,\n opts: {\n reuseWarm?: boolean;\n surfaces?: import(\"./browser\").WorldSurfaceKind[];\n } = {},\n ): Promise<import(\"./session\").WorldSession> {\n const { openSession } = await import(\"./session\");\n return openSession(this.slug, {\n task,\n versionId: this.version.versionId,\n reuseWarm: opts.reuseWarm,\n surfaces: opts.surfaces,\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 return resolveWorld(slugRef, slug, ref, ref ? { ref } : {}, options);\n}\n\n/**\n * Resolve `slug` at one pinned READY `versionId` — the task list is THAT\n * version's, never the branch tip's. `worlds run|ci --version-id` come\n * through here; a version of another container, a draft or an unknown id\n * is a 404 from the platform, not a silent fall-through to head.\n */\nexport async function openWorldVersion(\n slug: string,\n versionId: string,\n options: WorldsClientOptions = {},\n): Promise<WorldSet> {\n return resolveWorld(\n `${slug}@${versionId}`,\n slug,\n null,\n { versionId },\n options,\n );\n}\n\nasync function resolveWorld(\n slugRef: string,\n slug: string,\n ref: string | null,\n pin: { ref?: string; versionId?: string },\n options: WorldsClientOptions,\n): Promise<WorldSet> {\n const version = await apiRequest<\n ResolvedWorldVersion & { taskNames?: string[] }\n >(options, \"POST\", \"/api/public/benchmark-containers/resolve-version\", {\n slug,\n ...pin,\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// Stored tasks: the task spec as a named, versioned project resource that\n// `openSession(world, { task: { id } })` opens on.\nexport * from \"./tasks\";\n\n// Tasks that need several worlds: `openTask` brings every world a task\n// names up together (or not at all) and hands back the sessions by alias.\nexport * from \"./taskSessions\";\n\n// Run a task end to end: open every world, hand the agent a `TaskRun`,\n// grade with its report, file one rollout and close — `runTask`, the\n// engine behind `gateway worlds task run`.\nexport * from \"./taskRun\";\n\n// The evaluations client `runTask` files a rollout through — create, push\n// samples, finalize. Exposed in case a caller wants to file its own.\nexport * from \"./evals\";\n\n// The computer-use half: surfaces, a Playwright browser on the world's UI,\n// and browser actions as model tools.\nexport * from \"./browser\";\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\n// Discovery: what a world holds and how each field is stored (`describeWorld`),\n// and the stored forms of a plaintext under the world's [redact] table\n// (`storedForms`, `redactionOf`) — the same digest rule as the Python runtime.\nexport * from \"./describe\";\nexport * from \"./redaction\";\nexport * from \"./transforms\";\n\n// Lookup: the rows of one entity matching a predicate (`queryRows`), by\n// stored value or — with `resolve` — by plaintext the runtime maps through\n// the same [redact] table.\nexport * from \"./query\";\n\n// Migration: a stored world into a schema world (`migrateWorld`), dry run by\n// default; the project's connector worlds at once (`migrateProjectWorlds`).\nexport * from \"./migrate\";\n\n// Tool calls into rows: the record contract, `captureToolCalls` (record an\n// agent's real calls), `toolCallsFromObservations` (from a trace) and\n// `ingestToolCalls` (into a directory or a slug). Redaction optional, off by default.\nexport * from \"./ingest\";\n\n// The CLI sandbox: open a READY version in a server-side workspace, edit and\n// run there, check and commit into the version service without the source\n// ever landing on this disk (`gateway worlds|bench sandbox …`).\nexport * from \"./sandbox\";\n","/**\n * Read the project's traces, observations and trace sessions — the public\n * API behind `gateway traces …` and the MCP tools get_trace / get_observations\n * / get_session. Everything here is read-only.\n *\n * GET /api/public/traces?… a page of traces (page 1-based, limit ≤ 100)\n * GET /api/public/traces/{traceId} one trace with its observations and scores\n * GET /api/public/observations?… a page of observations (type, traceId, time window)\n * GET /api/public/sessions?… a page of trace sessions\n * GET /api/public/sessions/{sessionId} one session; includeIO=true attaches every trace's observations\n */\n\nimport { apiRequest, type WorldsClientOptions } from \"../worlds/index\";\n\nexport type TraceFilters = {\n fromTimestamp?: string;\n toTimestamp?: string;\n sessionId?: string;\n userId?: string;\n name?: string;\n tags?: string[];\n environment?: string;\n version?: string;\n release?: string;\n /** `timestamp.asc`, `timestamp.desc` (the default), … */\n orderBy?: string;\n};\n\nexport type ObservationFilters = {\n traceId?: string;\n type?: string;\n name?: string;\n userId?: string;\n level?: string;\n parentObservationId?: string;\n environment?: string;\n version?: string;\n fromStartTime?: string;\n toStartTime?: string;\n};\n\nexport type SessionFilters = { fromTimestamp?: string; toTimestamp?: string; environment?: string };\n\nexport type PageMeta = { page: number; limit: number; totalItems: number; totalPages: number };\nexport type Page<T> = { data: T[]; meta: PageMeta };\n\nexport type Trace = {\n id: string;\n timestamp: string;\n name: string | null;\n sessionId: string | null;\n userId: string | null;\n tags: string[];\n environment?: string;\n [key: string]: unknown;\n};\n\nexport type Observation = {\n id: string;\n traceId: string | null;\n type: string;\n name: string | null;\n startTime: string;\n endTime?: string | null;\n level?: string;\n [key: string]: unknown;\n};\n\nexport type TraceDetail = Trace & { observations: Observation[]; scores: unknown[]; latency?: number; totalCost?: number };\n\nexport type TraceSession = { id: string; createdAt: string; projectId: string; environment: string };\nexport type TraceSessionDetail = TraceSession & { traces: (Trace & { observations?: Observation[] })[] };\n\n/** The platform caps a page at 100. */\nexport const PAGE_LIMIT = 100;\n\ntype Scalar = string | number | boolean | undefined | null;\n\nfunction qs(params: Record<string, Scalar | string[]>): string {\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined || value === null || value === \"\") continue;\n if (Array.isArray(value)) for (const item of value) search.append(key, item);\n else search.set(key, String(value));\n }\n const text = search.toString();\n return text ? `?${text}` : \"\";\n}\n\nexport async function listTraces(\n options: WorldsClientOptions = {},\n filters: TraceFilters = {},\n page: { page?: number; limit?: number; fields?: string } = {},\n): Promise<Page<Trace>> {\n const { tags, ...rest } = filters;\n return apiRequest<Page<Trace>>(options, \"GET\", `/api/public/traces${qs({ ...rest, tags, page: page.page ?? 1, limit: page.limit ?? 50, fields: page.fields })}`);\n}\n\n/** Page through matching traces, newest first unless `orderBy` says otherwise; `max` stops early. */\nexport async function* iterateTraces(\n options: WorldsClientOptions = {},\n filters: TraceFilters = {},\n limits: { max?: number; fields?: string } = {},\n): AsyncGenerator<Trace> {\n yield* paged((page) => listTraces(options, filters, { page, limit: PAGE_LIMIT, fields: limits.fields }), limits.max);\n}\n\n/** One trace with its observations (input/output included) and scores. */\nexport async function getTrace(options: WorldsClientOptions = {}, traceId: string): Promise<TraceDetail> {\n return apiRequest<TraceDetail>(options, \"GET\", `/api/public/traces/${encodeURIComponent(traceId)}`);\n}\n\nexport async function listObservations(\n options: WorldsClientOptions = {},\n filters: ObservationFilters = {},\n page: { page?: number; limit?: number } = {},\n): Promise<Page<Observation>> {\n return apiRequest<Page<Observation>>(options, \"GET\", `/api/public/observations${qs({ ...filters, page: page.page ?? 1, limit: page.limit ?? 50 })}`);\n}\n\nexport async function* iterateObservations(\n options: WorldsClientOptions = {},\n filters: ObservationFilters = {},\n limits: { max?: number } = {},\n): AsyncGenerator<Observation> {\n yield* paged((page) => listObservations(options, filters, { page, limit: PAGE_LIMIT }), limits.max);\n}\n\nexport async function listSessions(\n options: WorldsClientOptions = {},\n filters: SessionFilters = {},\n page: { page?: number; limit?: number } = {},\n): Promise<Page<TraceSession>> {\n return apiRequest<Page<TraceSession>>(options, \"GET\", `/api/public/sessions${qs({ ...filters, page: page.page ?? 1, limit: page.limit ?? 50 })}`);\n}\n\nexport async function* iterateSessions(\n options: WorldsClientOptions = {},\n filters: SessionFilters = {},\n limits: { max?: number } = {},\n): AsyncGenerator<TraceSession> {\n yield* paged((page) => listSessions(options, filters, { page, limit: PAGE_LIMIT }), limits.max);\n}\n\n/** One trace session and its traces; `includeIO` attaches every trace's full observations. */\nexport async function getSession(\n options: WorldsClientOptions = {},\n sessionId: string,\n detail: { includeIO?: boolean } = {},\n): Promise<TraceSessionDetail> {\n return apiRequest<TraceSessionDetail>(options, \"GET\", `/api/public/sessions/${encodeURIComponent(sessionId)}${qs({ includeIO: detail.includeIO ? \"true\" : undefined })}`);\n}\n\nexport type ExportOptions = {\n /** Attach each trace's observations (one GET /traces/{id} per trace). */\n observations?: boolean;\n /** With `observations`: keep only this observation type (TOOL, GENERATION, SPAN, …). */\n type?: string;\n /** Stop after this many traces. */\n max?: number;\n};\n\nexport type ExportSummary = { traces: number; observations: number };\n\n/**\n * Every matching trace as one JSON object handed to `write`, ids and\n * timestamps exactly as the API returns them. With `observations`, each object\n * carries its `observations` array (filtered by `type` when given) and the\n * trace's `scores`, from `GET /traces/{id}`.\n */\nexport async function exportTraces(\n options: WorldsClientOptions = {},\n filters: TraceFilters = {},\n exportOptions: ExportOptions = {},\n write: (record: Record<string, unknown>) => void,\n): Promise<ExportSummary> {\n const summary: ExportSummary = { traces: 0, observations: 0 };\n const wantedType = exportOptions.type?.toUpperCase();\n for await (const trace of iterateTraces(options, filters, { max: exportOptions.max })) {\n let record: Record<string, unknown> = trace;\n if (exportOptions.observations) {\n const detail = await getTrace(options, trace.id);\n const observations = wantedType ? detail.observations.filter((o) => o.type?.toUpperCase() === wantedType) : detail.observations;\n summary.observations += observations.length;\n record = { ...detail, observations };\n }\n summary.traces++;\n write(record);\n }\n return summary;\n}\n\nasync function* paged<T>(fetchPage: (page: number) => Promise<Page<T>>, max?: number): AsyncGenerator<T> {\n let yielded = 0;\n for (let page = 1; ; page++) {\n const answer = await fetchPage(page);\n for (const item of answer.data) {\n if (max !== undefined && yielded >= max) return;\n yielded++;\n yield item;\n }\n const totalPages = answer.meta?.totalPages ?? (answer.data.length < PAGE_LIMIT ? page : page + 1);\n if (!answer.data.length || page >= totalPages) return;\n }\n}\n"],"mappings":";;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,SAAS,kBAAkB;AAA3B,IA4RM,kBAGA,iBAIA;AAnSN;AAAA;AAAA;AAEA;AACA;AAyRA,IAAM,mBAAmB,KAAK;AAG9B,IAAM,kBAAkB,IAAI;AAI5B,IAAM,0BAA0B,KAAK;AAAA;AAAA;;;ACnSrC;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;AACA;AAMA;AAAA;AAAA;;;ACPA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,SAAS,mBAAmB;AAC5B,YAAY,QAAQ;AACpB,YAAY,UAAU;AAFtB;AAAA;AAAA;AAKA;AACA;AAEA;AASA;AAAA;AAAA;;;ACNA,SAAS,kBAAkB;AAC3B,YAAYA,SAAQ;AACpB,YAAYC,WAAU;AAbtB,IAkBa,gBAEA,sBACP;AArBN;AAAA;AAAA;AAkBO,IAAM,iBAAiB;AAEvB,IAAM,uBAAuB,CAAC,qBAAqB,uBAAuB,kBAAkB;AACnG,IAAM,qBAAqB,CAAC,gBAAgB,GAAG,oBAAoB;AAAA;AAAA;;;ACrBnE,SAAS,cAAAC,mBAAkB;AAC3B,SAAS,UAAU,kBAAkB;AACrC,YAAYC,SAAQ;AACpB,YAAYC,WAAU;AAHtB,IAwBM;AAxBN;AAAA;AAAA;AAIA;AACA;AAmBA,IAAM,eAAoB,WAAK,YAAY,oBAAoB;AAAA;AAAA;;;ACxB/D;AAAA;AAAA;AAaA;AAQA;AAAA;AAAA;;;ACrBA;AAAA;AAAA;AAUA;AAAA;AAAA;;;ACVA;AAAA;AAAA;AAAA;AAAA;;;ACuBA,SAAS,cAAAC,mBAAkB;AAvB3B,IA6Ba,YACP,kBACA,gBACA,WAEO,cAEP,MAEA,gBAKA,aAUA,KAGA,QAiBO;AAzEb;AAAA;AAAA;AAyBA;AAIO,IAAM,aAAa;AAC1B,IAAM,mBAAmB,IAAI,OAAO,KAAK,UAAU,OAAO,UAAU,OAAO,GAAG;AAC9E,IAAM,iBAAiB,IAAI,OAAO,IAAI,UAAU,MAAM,GAAG;AACzD,IAAM,YAAY;AAEX,IAAM,eAAe;AAE5B,IAAM,OAAO,CAAC,UAA0B,MAAM,QAAQ,kBAAkB,EAAE;AAE1E,IAAM,iBAAiB,CAAC,UAA0B;AAChD,YAAM,KAAK,MAAM,YAAY,GAAG;AAChC,aAAO,OAAO,KAAK,QAAQ,MAAM,MAAM,GAAG,EAAE;AAAA,IAC9C;AAEA,IAAM,cAAc,CAAC,UAA0B;AAC7C,YAAM,KAAK,MAAM,YAAY,GAAG;AAChC,aAAO,OAAO,KAAK,KAAK,MAAM,MAAM,KAAK,CAAC,EAAE,YAAY;AAAA,IAC1D;AAOA,IAAM,MAAM,CAAC,WAA8B,UACzCA,YAAW,SAAS,EAAE,OAAO,OAAO,MAAM,EAAE,OAAO,KAAK;AAE1D,IAAM,SAAoC;AAAA,MACxC,OAAO,CAAC,UAAU,MAAM,YAAY;AAAA,MACpC,OAAO,CAAC,UAAU,MAAM,YAAY;AAAA,MACpC;AAAA,MACA,aAAa,CAAC,UAAU,KAAK,KAAK,EAAE,QAAQ,gBAAgB,GAAG;AAAA,MAC/D,MAAM,CAAC,UAAU,MAAM,UAAU,MAAM;AAAA,MACvC,QAAQ,CAAC,UAAU,MAAM,QAAQ,WAAW,EAAE;AAAA,MAC9C,kBAAkB;AAAA,MAClB,cAAc;AAAA;AAAA;AAAA,MAGd,MAAM,CAAC,UAAU,IAAI,QAAQ,KAAK;AAAA,MAClC,QAAQ,CAAC,UAAU,IAAI,UAAU,KAAK;AAAA,IACxC;AAIO,IAAM,aAAgC,CAAC,GAAG,OAAO,KAAK,MAAM,GAAG,GAAG,YAAY,WAAW;AAAA;AAAA;;;AC3DhG,SAAS,cAAAC,mBAAkB;AAd3B;AAAA;AAAA;AAgBA;AACA;AAAA;AAAA;;;ACjBA;AAAA;AAAA;AAoBA;AAAA;AAAA;;;ACpBA;AAAA;AAAA;AAWA;AAAA;AAAA;;;ACyBA,YAAYC,SAAQ;AACpB,YAAY,QAAQ;AACpB,YAAYC,WAAU;AAtCtB;AAAA;AAAA;AAwCA;AAAA;AAAA;;;ACxCA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACwCA,SAAS,WAAW,SAA8B;AAChD,QAAM,OACJ,QAAQ,QAAQ,QAAQ,IAAI,gBAAgB;AAC9C,QAAM,YAAY,QAAQ,aAAa,QAAQ,IAAI;AACnD,QAAM,YAAY,QAAQ,aAAa,QAAQ,IAAI;AACnD,MAAI,CAAC,aAAa,CAAC,WAAW;AAC5B,UAAM,IAAI;AAAA,MACR;AAAA,IAEF;AAAA,EACF;AACA,SAAO,EAAE,MAAM,KAAK,QAAQ,QAAQ,EAAE,GAAG,WAAW,UAAU;AAChE;AAkBA,eAAsB,WACpB,SACA,QACAC,OACA,MACY;AACZ,QAAM,EAAE,MAAM,WAAW,UAAU,IAAI,WAAW,OAAO;AACzD,QAAM,MAAM,MAAM,MAAM,GAAG,IAAI,GAAGA,KAAI,IAAI;AAAA,IACxC;AAAA,IACA,SAAS;AAAA,MACP,gBAAgB;AAAA,MAChB,eACE,WAAW,OAAO,KAAK,GAAG,SAAS,IAAI,SAAS,EAAE,EAAE,SAAS,QAAQ;AAAA,IACzE;AAAA,IACA,GAAI,SAAS,SAAY,CAAC,IAAI,EAAE,MAAM,KAAK,UAAU,IAAI,EAAE;AAAA,EAC7D,CAAC;AACD,QAAM,OAAO,MAAM,IAAI,KAAK;AAC5B,MAAI,CAAC,IAAI,GAAI,OAAM,IAAI,SAAS,IAAI,QAAQ,QAAQA,OAAM,KAAK,MAAM,GAAG,GAAG,CAAC;AAC5E,SAAO,KAAK,MAAM,IAAI;AACxB;AAzFA,IAwDa;AAxDb;AAAA;AAAA;AAsfA;AAIA;AAIA;AAKA;AAIA;AAIA;AAKA;AAGA;AAKA;AACA;AACA;AAKA;AAIA;AAKA;AAKA;AArfO,IAAM,WAAN,cAAuB,MAAM;AAAA,MAClC,YACkB,QAChB,QACAA,OACA,MACA;AACA,cAAM,GAAG,MAAM,IAAIA,KAAI,OAAO,MAAM,KAAK,IAAI,EAAE;AAL/B;AAMhB,aAAK,OAAO;AAAA,MACd;AAAA,IACF;AAAA;AAAA;;;ACtDA;AA8DO,IAAM,aAAa;AAI1B,SAAS,GAAG,QAAmD;AAC7D,QAAM,SAAS,IAAI,gBAAgB;AACnC,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,MAAM,GAAG;AACjD,QAAI,UAAU,UAAa,UAAU,QAAQ,UAAU,GAAI;AAC3D,QAAI,MAAM,QAAQ,KAAK,EAAG,YAAW,QAAQ,MAAO,QAAO,OAAO,KAAK,IAAI;AAAA,QACtE,QAAO,IAAI,KAAK,OAAO,KAAK,CAAC;AAAA,EACpC;AACA,QAAM,OAAO,OAAO,SAAS;AAC7B,SAAO,OAAO,IAAI,IAAI,KAAK;AAC7B;AAEA,eAAsB,WACpB,UAA+B,CAAC,GAChC,UAAwB,CAAC,GACzB,OAA2D,CAAC,GACtC;AACtB,QAAM,EAAE,MAAM,GAAG,KAAK,IAAI;AAC1B,SAAO,WAAwB,SAAS,OAAO,qBAAqB,GAAG,EAAE,GAAG,MAAM,MAAM,MAAM,KAAK,QAAQ,GAAG,OAAO,KAAK,SAAS,IAAI,QAAQ,KAAK,OAAO,CAAC,CAAC,EAAE;AACjK;AAGA,gBAAuB,cACrB,UAA+B,CAAC,GAChC,UAAwB,CAAC,GACzB,SAA4C,CAAC,GACtB;AACvB,SAAO,MAAM,CAAC,SAAS,WAAW,SAAS,SAAS,EAAE,MAAM,OAAO,YAAY,QAAQ,OAAO,OAAO,CAAC,GAAG,OAAO,GAAG;AACrH;AAGA,eAAsB,SAAS,UAA+B,CAAC,GAAG,SAAuC;AACvG,SAAO,WAAwB,SAAS,OAAO,sBAAsB,mBAAmB,OAAO,CAAC,EAAE;AACpG;AAEA,eAAsB,iBACpB,UAA+B,CAAC,GAChC,UAA8B,CAAC,GAC/B,OAA0C,CAAC,GACf;AAC5B,SAAO,WAA8B,SAAS,OAAO,2BAA2B,GAAG,EAAE,GAAG,SAAS,MAAM,KAAK,QAAQ,GAAG,OAAO,KAAK,SAAS,GAAG,CAAC,CAAC,EAAE;AACrJ;AAEA,gBAAuB,oBACrB,UAA+B,CAAC,GAChC,UAA8B,CAAC,GAC/B,SAA2B,CAAC,GACC;AAC7B,SAAO,MAAM,CAAC,SAAS,iBAAiB,SAAS,SAAS,EAAE,MAAM,OAAO,WAAW,CAAC,GAAG,OAAO,GAAG;AACpG;AAEA,eAAsB,aACpB,UAA+B,CAAC,GAChC,UAA0B,CAAC,GAC3B,OAA0C,CAAC,GACd;AAC7B,SAAO,WAA+B,SAAS,OAAO,uBAAuB,GAAG,EAAE,GAAG,SAAS,MAAM,KAAK,QAAQ,GAAG,OAAO,KAAK,SAAS,GAAG,CAAC,CAAC,EAAE;AAClJ;AAEA,gBAAuB,gBACrB,UAA+B,CAAC,GAChC,UAA0B,CAAC,GAC3B,SAA2B,CAAC,GACE;AAC9B,SAAO,MAAM,CAAC,SAAS,aAAa,SAAS,SAAS,EAAE,MAAM,OAAO,WAAW,CAAC,GAAG,OAAO,GAAG;AAChG;AAGA,eAAsB,WACpB,UAA+B,CAAC,GAChC,WACA,SAAkC,CAAC,GACN;AAC7B,SAAO,WAA+B,SAAS,OAAO,wBAAwB,mBAAmB,SAAS,CAAC,GAAG,GAAG,EAAE,WAAW,OAAO,YAAY,SAAS,OAAU,CAAC,CAAC,EAAE;AAC1K;AAmBA,eAAsB,aACpB,UAA+B,CAAC,GAChC,UAAwB,CAAC,GACzB,gBAA+B,CAAC,GAChC,OACwB;AACxB,QAAM,UAAyB,EAAE,QAAQ,GAAG,cAAc,EAAE;AAC5D,QAAM,aAAa,cAAc,MAAM,YAAY;AACnD,mBAAiB,SAAS,cAAc,SAAS,SAAS,EAAE,KAAK,cAAc,IAAI,CAAC,GAAG;AACrF,QAAI,SAAkC;AACtC,QAAI,cAAc,cAAc;AAC9B,YAAM,SAAS,MAAM,SAAS,SAAS,MAAM,EAAE;AAC/C,YAAM,eAAe,aAAa,OAAO,aAAa,OAAO,CAAC,MAAM,EAAE,MAAM,YAAY,MAAM,UAAU,IAAI,OAAO;AACnH,cAAQ,gBAAgB,aAAa;AACrC,eAAS,EAAE,GAAG,QAAQ,aAAa;AAAA,IACrC;AACA,YAAQ;AACR,UAAM,MAAM;AAAA,EACd;AACA,SAAO;AACT;AAEA,gBAAgB,MAAS,WAA+C,KAAiC;AACvG,MAAI,UAAU;AACd,WAAS,OAAO,KAAK,QAAQ;AAC3B,UAAM,SAAS,MAAM,UAAU,IAAI;AACnC,eAAW,QAAQ,OAAO,MAAM;AAC9B,UAAI,QAAQ,UAAa,WAAW,IAAK;AACzC;AACA,YAAM;AAAA,IACR;AACA,UAAM,aAAa,OAAO,MAAM,eAAe,OAAO,KAAK,SAAS,aAAa,OAAO,OAAO;AAC/F,QAAI,CAAC,OAAO,KAAK,UAAU,QAAQ,WAAY;AAAA,EACjD;AACF;","names":["fs","path","createHash","fs","path","createHash","createHash","fs","path","path"]}
|
|
1
|
+
{"version":3,"sources":["../../src/worlds/transport.ts","../../src/worlds/browserReconnect.ts","../../src/worlds/browser.ts","../../src/worlds/sessionContract.ts","../../src/worlds/taskRef.ts","../../src/worlds/session.ts","../../src/worlds/sessionList.ts","../../src/worlds/tasks.ts","../../src/worlds/taskSessions.ts","../../src/worlds/evals.ts","../../src/worlds/taskRun.ts","../../src/worlds/checkoutProvenance.ts","../../src/worlds/setRun.ts","../../src/worlds/checkoutTarget.ts","../../src/worlds/worldDir.ts","../../src/worlds/tar.ts","../../src/worlds/hub.ts","../../src/worlds/validate.ts","../../src/worlds/sandbox.ts","../../src/worlds/describe.ts","../../src/cli/platform/worldData/json.ts","../../src/worlds/transforms.ts","../../src/worlds/redaction.ts","../../src/worlds/query.ts","../../src/worlds/migrate.ts","../../src/worlds/ingest.ts","../../src/worlds/editSessions.ts","../../src/worlds/dryRun.ts","../../src/worlds/index.ts","../../src/traces/index.ts"],"sourcesContent":["export const PLATFORM_TIMEOUT_ENV = \"GATEWAY_TIMEOUT_MS\";\n\n/** How long one platform request may go unanswered before it is abandoned; `GATEWAY_TIMEOUT_MS` overrides it. */\nexport const PLATFORM_TIMEOUT_DEFAULT_MS = 120_000;\n\nexport type PlatformEndpoint = { host: string; publicKey: string; secretKey: string };\n\nexport type PlatformMethod = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n\nexport type PlatformReply = { status: number; ok: boolean; text: string };\n\n/** The request budget in force: `GATEWAY_TIMEOUT_MS` when set, else the default. */\nexport function platformTimeoutMs(env: NodeJS.ProcessEnv = process.env): number {\n const raw = env[PLATFORM_TIMEOUT_ENV];\n if (raw === undefined || raw === \"\") return PLATFORM_TIMEOUT_DEFAULT_MS;\n const value = Number(raw);\n if (Number.isInteger(value) && value > 0) return value;\n throw new Error(`${PLATFORM_TIMEOUT_ENV} must be a positive whole number of milliseconds, not \\`${raw}\\`.`);\n}\n\nconst CHECK_HOST = \"Check GATEWAY_HOST (or --host) points at a running platform, then retry.\";\nconst RETRY = \"Retry; if it repeats, check the network between here and the platform.\";\n\nconst CAUSES: Record<string, { reason: string; next: string }> = {\n ECONNREFUSED: { reason: \"connection refused\", next: CHECK_HOST },\n ENOTFOUND: { reason: \"DNS lookup failed\", next: CHECK_HOST },\n EAI_AGAIN: { reason: \"DNS lookup failed\", next: CHECK_HOST },\n ETIMEDOUT: { reason: \"connect timed out\", next: CHECK_HOST },\n UND_ERR_CONNECT_TIMEOUT: { reason: \"connect timed out\", next: CHECK_HOST },\n EHOSTUNREACH: { reason: \"host unreachable\", next: CHECK_HOST },\n ENETUNREACH: { reason: \"network unreachable\", next: RETRY },\n ECONNRESET: { reason: \"connection dropped\", next: RETRY },\n UND_ERR_SOCKET: { reason: \"connection dropped\", next: RETRY },\n EPIPE: { reason: \"connection dropped\", next: RETRY },\n};\n\nconst UNKNOWN_CAUSE = { reason: \"network error\", next: CHECK_HOST };\n\n/** Why a request got no answer, from the socket-level error undici hides under `fetch failed`. */\nexport class TransportCause {\n private constructor(\n readonly reason: string,\n readonly detail: string | null,\n readonly next: string,\n ) {}\n\n static timeout(timeoutMs: number): TransportCause {\n return new TransportCause(\n `timed out after ${timeoutMs / 1000}s`,\n null,\n `Retry; if the platform is slow, raise ${PLATFORM_TIMEOUT_ENV} (milliseconds per request).`,\n );\n }\n\n static of(error: unknown): TransportCause {\n const cause = error instanceof Error && error.cause instanceof Error ? error.cause : undefined;\n const code = cause && \"code\" in cause && typeof cause.code === \"string\" ? cause.code : null;\n const message = cause?.message ?? (error instanceof Error ? error.message : String(error));\n const known = (code && CAUSES[code]) || UNKNOWN_CAUSE;\n return new TransportCause(known.reason, code ? `${code}: ${message}` : message, known.next);\n }\n\n describe(): string {\n return this.detail === null ? this.reason : `${this.reason} (${this.detail})`;\n }\n}\n\n/** A platform request that never got an answer: one line naming the request, the host, the cause and the next step. */\nexport class UnreachableError extends Error {\n constructor(\n readonly host: string,\n readonly method: string,\n readonly route: string,\n readonly failure: TransportCause,\n ) {\n super(`${method} ${route}: no answer from ${host}: ${failure.describe()}. ${failure.next}`);\n this.name = \"UnreachableError\";\n }\n}\n\n/** The one door every CLI and SDK request to the platform goes through: Basic auth with the project key, a per-request timeout, and a transport failure turned into an `UnreachableError`. */\nexport class PlatformTransport {\n constructor(\n private readonly endpoint: PlatformEndpoint,\n private readonly timeoutMs: number = platformTimeoutMs(),\n ) {}\n\n /** A request that legitimately takes longer (a sandbox exec, a world create) waits its own budget; every other one waits the default. */\n budget(ownMs?: number): number {\n return Math.max(ownMs ?? 0, this.timeoutMs);\n }\n\n async send(\n method: PlatformMethod,\n route: string,\n body?: unknown,\n opts: { timeoutMs?: number } = {},\n ): Promise<PlatformReply> {\n const timeoutMs = this.budget(opts.timeoutMs);\n const payload = body === undefined ? {} : { body: JSON.stringify(body) };\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n try {\n const res = await fetch(`${this.endpoint.host}${route}`, {\n method,\n headers: {\n \"content-type\": \"application/json\",\n accept: \"application/json\",\n authorization:\n \"Basic \" + Buffer.from(`${this.endpoint.publicKey}:${this.endpoint.secretKey}`).toString(\"base64\"),\n },\n ...payload,\n signal: controller.signal,\n });\n return { status: res.status, ok: res.ok, text: await res.text() };\n } catch (error) {\n const cause = controller.signal.aborted ? TransportCause.timeout(timeoutMs) : TransportCause.of(error);\n throw new UnreachableError(this.endpoint.host, method, route, cause);\n } finally {\n clearTimeout(timer);\n }\n }\n}\n","import type { BrowserPage, PlaywrightBrowserLike } from \"./browser\";\n\n/**\n * A HOSTED BROWSER THAT COMES BACK. A World Host session's browser is a pool\n * pod; on the `standard` tier it runs on spot capacity and can be reclaimed\n * with two minutes' notice. The browser dies, the world does not, and the\n * platform can put a new browser behind the SAME `surfaces.browser.wsUrl`.\n *\n * `BrowserReconnector` is the client half of that repair: on a lost\n * connection it asks the platform to repair (`POST .../browser-repair`),\n * waits while a browser starts, reconnects to the same address and hands the\n * new connection to its owner to restore the page. It knows nothing of HTTP\n * or Playwright — both come in as collaborators, so tests drive it with\n * fakes. Twin of `gatewaysdk/world_browser_reconnect.py`, call for call.\n */\n\n/** What the platform answers a repair with. `healthy`: the browser is alive,\n * reconnect now. `replaced`: a new, blank browser; reconnect and reopen the\n * page. `starting`: a browser is coming up; ask again in `retryAfterMs`. */\nexport type RepairAnswer = {\n outcome: \"healthy\" | \"replaced\" | \"starting\";\n retryAfterMs: number | null;\n};\n\ntype BrowserContextLike = Awaited<\n ReturnType<PlaywrightBrowserLike[\"newContext\"]>\n>;\n\n/** One live attachment to the session's browser. */\nexport type BrowserConnection = {\n browser: PlaywrightBrowserLike;\n context: BrowserContextLike;\n page: BrowserPage;\n};\n\nexport async function closeConnection(c: BrowserConnection): Promise<void> {\n await c.context.close();\n await c.browser.close();\n}\n\n/** Close a connection whose browser is already gone: it only frees the\n * handle, so a failure is ignored. */\nexport async function releaseConnection(c: BrowserConnection): Promise<void> {\n await closeConnection(c).catch(() => undefined);\n}\n\nexport const RECOVER_BUDGET_MS = 90_000;\nconst BACKOFF_BASE_MS = 1_000;\nconst BACKOFF_CAP_MS = 5_000;\n\n/** What Playwright says when the browser or its connection is gone, as\n * opposed to an action that failed on a live page. Matched case-insensitively\n * against the error message; nothing else triggers a reconnect. */\nexport const BROWSER_GONE_PATTERNS: readonly RegExp[] = [\n /target page, context or browser has been closed/i,\n /\\bbrowser has been (closed|disconnected)\\b/i,\n /\\bbrowser (has )?disconnected\\b/i,\n /\\btarget closed\\b/i,\n /\\bwebsocket is not open\\b/i,\n /\\bconnection closed\\b/i,\n];\n\n/** A failed page load (`net::ERR_INTERNET_DISCONNECTED`,\n * `net::ERR_CONNECTION_CLOSED`) is the world UI's network, not the browser:\n * the browser is alive, and repairing it would throw away a live page. */\nconst PAGE_NETWORK_ERROR = /net::ERR_/i;\n\nexport function isBrowserGone(error: unknown): boolean {\n const message = error instanceof Error ? error.message : String(error);\n if (PAGE_NETWORK_ERROR.test(message)) return false;\n return BROWSER_GONE_PATTERNS.some((p) => p.test(message));\n}\n\nconst REDACTED = \"<redacted>\";\nconst TOKEN_QUERY_VALUE = /([?&]token=)[^&#\\s\"')]*/gi;\n\n/**\n * Takes a session's credentials out of text that leaves the process — an\n * error recorded into the browser timeline, a recovery's reason. A browser\n * error quotes the URL it failed on, and those URLs carry the session: the\n * hosted browser's `wsUrl` (its path is the credential), the UI's token, and\n * any `?token=` a landing URL presents. Each becomes `<redacted>`.\n */\nexport class SecretScrubber {\n private readonly secrets: string[];\n\n constructor(secrets: readonly (string | null | undefined)[]) {\n const known = secrets.filter((s): s is string => Boolean(s));\n // Longest first, so a wsUrl goes whole before a token inside it.\n this.secrets = [\n ...new Set([...known, ...known.map((s) => encodeURIComponent(s))]),\n ].sort((a, b) => b.length - a.length);\n }\n\n scrub(text: string): string {\n const bare = this.secrets.reduce(\n (out, secret) => out.split(secret).join(REDACTED),\n text,\n );\n return bare.replace(TOKEN_QUERY_VALUE, `$1${REDACTED}`);\n }\n}\n\n/** A mutating action (click, type, press, back, scroll) lost its browser.\n * The browser was repaired and the page reopened at `restoredUrl`, but the\n * action is NOT replayed: its input may already have reached the world.\n * `cause` is the error the action failed with. */\nexport class BrowserReconnected extends Error {\n constructor(\n readonly outcome: RecoveryResult[\"outcome\"],\n readonly restoredUrl: string | null,\n cause: unknown,\n ) {\n super(\n `the browser was lost mid-action and reconnected (${outcome}); ` +\n (restoredUrl\n ? `the page was reopened at ${restoredUrl}. `\n : \"it is on a blank page. \") +\n \"The action may or may not have taken effect — look at the page before acting again.\",\n { cause },\n );\n this.name = \"BrowserReconnected\";\n }\n}\n\n/** The session's browser stayed gone for the whole budget. `cause` is the\n * error the action first failed with. */\nexport class BrowserUnrecoverable extends Error {\n constructor(message: string, cause: unknown) {\n super(message, { cause });\n this.name = \"BrowserUnrecoverable\";\n }\n}\n\n/** A repair refusal worth waiting out: no answer at all (the network), the\n * platform's own failure, or a full pool. Anything else (a 404 for a session\n * that is not open with a browser) ends the recovery. */\nfunction refusalIsTransient(error: unknown): boolean {\n const { status, code } = error as { status?: unknown; code?: unknown };\n if (typeof status !== \"number\") return true;\n if (status >= 500) return true;\n return status === 400 && code === \"browser_capacity\";\n}\n\nfunction describe(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\ntype Step =\n | { kind: \"recovered\"; outcome: RecoveryResult[\"outcome\"] }\n | { kind: \"stop\" }\n | { kind: \"wait\"; reason: string; waitMs: number | null };\n\nexport type RecoveryResult = {\n outcome: \"healthy\" | \"replaced\";\n attempts: number;\n};\n\nexport class BrowserReconnector {\n private readonly sleep: (ms: number) => Promise<void>;\n private readonly now: () => number;\n private readonly scrub: (text: string) => string;\n readonly budgetMs: number;\n\n constructor(\n private readonly repair: () => Promise<RepairAnswer>,\n private readonly connect: () => Promise<BrowserConnection>,\n opts: {\n sleep?: (ms: number) => Promise<void>;\n now?: () => number;\n budgetMs?: number;\n /** Takes credentials out of a reason before it is thrown. */\n scrub?: (text: string) => string;\n } = {},\n ) {\n this.sleep =\n opts.sleep ?? ((ms) => new Promise<void>((r) => setTimeout(r, ms)));\n this.now = opts.now ?? Date.now;\n this.budgetMs = opts.budgetMs ?? RECOVER_BUDGET_MS;\n this.scrub = opts.scrub ?? ((text) => text);\n }\n\n /**\n * Repair, reconnect and `restore` until it works or the budget runs out.\n * `restore` receives each new connection (the owner adopts it and reopens\n * its page); a restore that fails counts as a failed reconnect, because the\n * browser may have died again. A repair the platform refuses for good\n * rethrows `cause` untouched.\n */\n async recover(\n cause: unknown,\n restore: (connection: BrowserConnection) => Promise<void>,\n ): Promise<RecoveryResult> {\n const deadline = this.now() + this.budgetMs;\n let reason = describe(cause);\n for (let attempt = 1; ; attempt++) {\n const step = await this.attempt(restore);\n if (step.kind === \"recovered\")\n return { outcome: step.outcome, attempts: attempt };\n if (step.kind === \"stop\") throw cause;\n reason = step.reason;\n const remaining = deadline - this.now();\n if (remaining <= 0) break;\n const backoff = Math.min(\n BACKOFF_BASE_MS * 2 ** (attempt - 1),\n BACKOFF_CAP_MS,\n );\n await this.sleep(Math.min(step.waitMs ?? backoff, remaining));\n }\n throw new BrowserUnrecoverable(\n `the session's browser could not be recovered within ${Math.round(this.budgetMs / 1000)}s: ${this.scrub(reason)}`,\n cause,\n );\n }\n\n private async attempt(\n restore: (connection: BrowserConnection) => Promise<void>,\n ): Promise<Step> {\n let answer: RepairAnswer;\n try {\n answer = await this.repair();\n } catch (error) {\n if (!refusalIsTransient(error)) return { kind: \"stop\" };\n return {\n kind: \"wait\",\n reason: `repair failed: ${describe(error)}`,\n waitMs: null,\n };\n }\n const outcome = answer.outcome;\n if (outcome === \"starting\")\n return {\n kind: \"wait\",\n reason: \"a new browser is still starting\",\n waitMs: answer.retryAfterMs,\n };\n try {\n await restore(await this.connect());\n } catch (error) {\n return {\n kind: \"wait\",\n reason: `reconnect failed: ${describe(error)}`,\n waitMs: null,\n };\n }\n return { kind: \"recovered\", outcome };\n }\n}\n","import { schemaFromSignature, type WorldToolkit } from \"./session\";\nimport {\n BrowserReconnected,\n BrowserReconnector,\n SecretScrubber,\n closeConnection,\n isBrowserGone,\n releaseConnection,\n type BrowserConnection,\n type RecoveryResult,\n type RepairAnswer,\n} from \"./browserReconnect\";\n\n/**\n * A BROWSER ON A WORLD'S UI — the computer-use half of a live session.\n *\n * A session answers on SURFACES. `tools` is always there (the world's own\n * operations over the rendezvous). An api-type world may also answer on\n * `api` (the service itself), `ui` (its dashboard, over the same state) and\n * `browser` — a headless Chromium the platform runs NEXT TO that UI, which\n * an agent drives through Playwright. This file is the TS client for the\n * last two, call for call with `gatewaysdk/world_browser.py`.\n *\n * const s = await openSession(\"payments-like\", \"refund-dispute\", {\n * surfaces: [\"ui\", \"browser\"],\n * });\n * await s.ready();\n * const b = await s.browser(); // hosted, next to the world\n * await b.goto(); // the UI's entry page\n * await b.click(\"text=Refund\");\n * const tools = computerUseToolkit(b); // the same actions as model tools\n * await b.close();\n *\n * Playwright is an OPTIONAL peer: nothing here imports it until a browser is\n * opened, so sessions that never touch a UI never load it.\n *\n * MODES. `hosted` connects to the session's own browser (a Playwright server\n * the pod exposes over an authenticated websocket). `local` launches Chromium\n * on this machine and points it at the UI — a laptop against a hosted twin,\n * or a test. `auto` prefers hosted. Asking for a mode the session cannot\n * serve throws `WorldSurfaceUnavailable`; there is no silent fallback to a\n * browser other than the one the episode is judged on.\n *\n * OBSERVABILITY. Every action a `WorldBrowser` takes (goto, click, type,\n * press, scroll, back) is reported to the platform as one event — what was\n * done, whether it worked, where the page ended up, and a JPEG of the screen\n * after — through a `BrowserActionRecorder`. Reporting is fire-and-forget\n * and never fails the action; the platform renders it as the session's\n * browser timeline. Text typed into secret-looking fields is redacted before\n * it leaves the process.\n *\n * RECONNECT. A World Host browser on the `standard` tier can be reclaimed\n * mid-session. When an action fails because the browser or its connection is\n * gone, a hosted `cdp` browser asks the platform to repair it, reconnects to\n * the same address and reopens the page it was on (see `browserReconnect.ts`).\n * A read or a `goto` then runs once more; a click, type, press, back or scroll\n * is NOT replayed — its input may already have reached the world — and throws\n * `BrowserReconnected` so the agent looks at the page again. Local and\n * `playwright`-protocol browsers never reconnect.\n */\n\nexport const SURFACE_KINDS = [\"tools\", \"api\", \"ui\", \"browser\"] as const;\nexport type WorldSurfaceKind = (typeof SURFACE_KINDS)[number];\n\n/** Capacity behind a World Host session's browser. `standard` runs on spot\n * capacity first (about half the price) and may be reclaimed with two\n * minutes' notice, ending the browser but never the world; `premium` is\n * on-demand and never spot-reclaimed. Unset, the organization's default applies. */\nexport const BROWSER_TIERS = [\"standard\", \"premium\"] as const;\nexport type BrowserTier = (typeof BROWSER_TIERS)[number];\n\n/** Refuse a tier the platform does not know, before any request is sent. */\nexport function assertBrowserTier(value: unknown): asserts value is BrowserTier {\n if ((BROWSER_TIERS as readonly unknown[]).includes(value)) return;\n throw new Error(\n `Unknown browser tier: ${String(value)}; choose from ${BROWSER_TIERS.join(\", \")}`,\n );\n}\n\nexport const DEFAULT_VIEWPORT = { width: 1280, height: 800 };\nconst SETTLE_TIMEOUT_MS = 5_000;\nconst SETTLE_QUIET_MS = 150;\nconst SETTLE_POLL_MS = 25;\n\nexport const EVENT_BATCH_SIZE = 10;\nexport const EVENT_FLUSH_INTERVAL_MS = 1_000;\nexport const EVENT_MAX_RETRIES = 3;\nconst EVENT_SCREENSHOT_QUALITY = 60;\nconst EVENT_MAX_STRING = 500;\n\nconst SECRET_KEY =\n /pass(word|wd)?|secret|token|api[-_]?key|authorization|cookie|(^|[-_ #.\\[\"'=])(otp|pin|cvv|ssn)([-_ \\]\"']|$)/i;\n/** What a call that lost its browser does once the browser is back: a read or\n * a navigation runs again (`retry`); an action that may already have reached\n * the world is not replayed, and the agent is told (`report`). */\ntype OnBrowserLoss = \"retry\" | \"report\";\n\nconst SECRET_VALUE =\n /^((sk|pk|ghp|xox[abp])[-_][-_A-Za-z0-9]{8,}|AKIA[0-9A-Z]{12,}|Bearer [-_.A-Za-z0-9]{8,})/;\n\n/** The `surfaces` block of a session descriptor, as the platform sends it. */\nexport type SessionSurfaces = {\n tools: { kind: \"rendezvous\" };\n api?: {\n url: string;\n /** Per-session credential of a World Host session: send it as\n * `Authorization: Bearer <token>` (the header only; a token in the URL is\n * refused). Absent when the world\n * itself answers with its declared auth (a pod or a customer-hosted twin). */\n token?: string;\n };\n ui?: {\n url: string;\n entry: string;\n /** Same-origin prefix the UI proxies to the world API, e.g. `/__world-api`;\n * null when the UI only reaches the API server-side. */\n apiPath?: string | null;\n /** Per-session credential of a World Host UI. A browser navigation cannot\n * carry a header, so the first page load presents it once as `?token=`\n * and the host answers with an HttpOnly cookie. Absent for pod UIs. */\n token?: string;\n };\n browser?: {\n wsUrl: string;\n /** `cdp`: the platform's Chromium relay (any number of agents share one\n * browser, each in its own context). `playwright`: a `run-server` endpoint. */\n protocol: \"cdp\" | \"playwright\";\n viewport: { width: number; height: number };\n /** The capacity tier the browser runs on; present for World Host sessions. */\n tier?: BrowserTier;\n };\n};\n\nexport class WorldSurfaceUnavailable extends Error {\n constructor(\n readonly surface: WorldSurfaceKind,\n reason: string,\n ) {\n super(`World surface '${surface}' is unavailable: ${reason}`);\n }\n}\n\nexport function surfaceKinds(s: SessionSurfaces): WorldSurfaceKind[] {\n const kinds: WorldSurfaceKind[] = [\"tools\"];\n if (s.api) kinds.push(\"api\");\n if (s.ui) kinds.push(\"ui\");\n if (s.browser) kinds.push(\"browser\");\n return kinds;\n}\n\nconst UI_TOKEN_QUERY = \"token\";\n\n/** The URL of `path` on a UI surface, carrying the session token when the\n * surface has one. `path` may already have a query string; the token is\n * appended to it. */\nexport function uiUrl(\n ui: NonNullable<SessionSurfaces[\"ui\"]>,\n path: string,\n): string {\n const base = ui.url.replace(/\\/+$/, \"\");\n const rel = path.startsWith(\"/\") ? path : `/${path}`;\n if (!ui.token) return base + rel;\n const [beforeHash, hash] = splitHash(rel);\n const joiner = beforeHash.includes(\"?\") ? \"&\" : \"?\";\n const query = `${UI_TOKEN_QUERY}=${encodeURIComponent(ui.token)}`;\n return base + beforeHash + joiner + query + hash;\n}\n\nexport function uiEntryUrl(ui: NonNullable<SessionSurfaces[\"ui\"]>): string {\n return uiUrl(ui, ui.entry || \"/\");\n}\n\n/** `url` without its `token` query parameter: what may be logged or shown. */\nexport function withoutUiToken(url: string): string {\n const [beforeHash, hash] = splitHash(url);\n const q = beforeHash.indexOf(\"?\");\n if (q < 0) return url;\n const kept = beforeHash\n .slice(q + 1)\n .split(\"&\")\n .filter((pair) => pair !== \"\" && pair.split(\"=\")[0] !== UI_TOKEN_QUERY);\n return (\n beforeHash.slice(0, q) + (kept.length ? `?${kept.join(\"&\")}` : \"\") + hash\n );\n}\n\nfunction splitHash(url: string): [string, string] {\n const h = url.indexOf(\"#\");\n return h < 0 ? [url, \"\"] : [url.slice(0, h), url.slice(h)];\n}\n\n/** The slice of a Playwright `Page` this module drives. */\nexport type BrowserPage = {\n url(): string;\n goto(url: string, opts?: { waitUntil?: \"load\" }): Promise<unknown>;\n click(selector: string): Promise<void>;\n fill(selector: string, value: string): Promise<void>;\n screenshot(opts?: {\n type?: \"png\" | \"jpeg\";\n quality?: number;\n fullPage?: boolean;\n }): Promise<Buffer>;\n innerText(selector: string): Promise<string>;\n content(): Promise<string>;\n goBack(opts?: { waitUntil?: \"load\" }): Promise<unknown>;\n waitForLoadState(state?: \"load\"): Promise<void>;\n waitForTimeout(ms: number): Promise<void>;\n on(\n event: \"request\" | \"requestfinished\" | \"requestfailed\",\n handler: (request: unknown) => void,\n ): unknown;\n title(): Promise<string>;\n keyboard: { press(key: string): Promise<void> };\n mouse: { wheel(dx: number, dy: number): Promise<void> };\n};\n\nexport type BrowserMode = \"auto\" | \"hosted\" | \"local\";\n\n// ── action events ────────────────────────────────────────────────────────────\n\n/** One browser action as the platform ingests it\n * (`POST /world-sessions/{id}/browser-events`). */\nexport type BrowserActionEvent = {\n agentId: string;\n seq: number;\n ts: string;\n action: string;\n args: Record<string, unknown>;\n ok: boolean;\n error: string | null;\n durationMs: number;\n url: string | null;\n title: string | null;\n mode: Exclude<BrowserMode, \"auto\">;\n viewport: { width: number; height: number };\n /** base64 JPEG of the screen after the action; null if it could not be taken. */\n screenshot: string | null;\n};\n\n/** What of an action's arguments may leave the process. Selectors, paths\n * and keys are what a reviewer needs; anything keyed like a credential, or\n * typed into a field whose selector names one, or shaped like a known key,\n * is replaced. Strings are capped, nested values dropped. */\nexport function redactActionArgs(\n action: string,\n args: Record<string, unknown>,\n): Record<string, unknown> {\n const secretField =\n action === \"browser_type\" && SECRET_KEY.test(String(args.selector ?? \"\"));\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(args)) {\n if (value === null || value === undefined) out[key] = null;\n else if (typeof value === \"boolean\" || typeof value === \"number\")\n out[key] = value;\n else if (typeof value === \"string\") {\n if (\n SECRET_KEY.test(key) ||\n SECRET_VALUE.test(value) ||\n (secretField && key === \"text\")\n )\n out[key] = \"[redacted]\";\n else\n out[key] =\n value.length <= EVENT_MAX_STRING\n ? value\n : value.slice(0, EVENT_MAX_STRING) + \"…\";\n } else out[key] = \"[omitted]\";\n }\n return out;\n}\n\n/**\n * Ships browser action events to the platform, off the action's hot path.\n *\n * `post` receives a batch of events (the request body's `events`). Events\n * are numbered here, so ordering survives batching and retries — the\n * platform dedups on `(agentId, seq)`. A batch that keeps failing is dropped\n * with a warning: telemetry must never stall or fail the agent.\n *\n * Numbering is durable across recorders: `nextSeq()` hands out a position\n * within this recorder, and the first send adds the base `resumeFrom`\n * reports — the platform's next free seq for this agent — so an agent id\n * reopened in a later process appends to its timeline instead of colliding\n * with (and being deduplicated against) what it already recorded. The base\n * is fixed once resolved, which keeps retries idempotent.\n */\nexport class BrowserActionRecorder {\n private seq = 0;\n private base: Promise<number> | null = null;\n private queue: BrowserActionEvent[] = [];\n private timer: ReturnType<typeof setTimeout> | null = null;\n private inflight: Promise<void> = Promise.resolve();\n sent = 0;\n dropped = 0;\n\n constructor(\n private readonly post: (events: BrowserActionEvent[]) => Promise<void>,\n readonly agentId: string,\n private readonly opts: {\n /** The platform's next free seq for `agentId`; 0 when not given. */\n resumeFrom?: () => Promise<number>;\n batchSize?: number;\n flushIntervalMs?: number;\n maxRetries?: number;\n sleep?: (ms: number) => Promise<void>;\n warn?: (message: string) => void;\n } = {},\n ) {}\n\n /** This recorder's next position; the wire seq is `resumeFrom() + this`. */\n nextSeq(): number {\n return this.seq++;\n }\n\n private resolveBase(): Promise<number> {\n if (this.base === null) {\n const resolve = this.opts.resumeFrom ?? (async () => 0);\n this.base = resolve().then((n) => {\n if (!Number.isInteger(n) || n < 0)\n throw new Error(\n `browser event base seq must be a non-negative integer, got ${String(n)}`,\n );\n return n;\n });\n // A failed lookup is retried with the batch, not remembered.\n this.base.catch(() => {\n this.base = null;\n });\n }\n return this.base;\n }\n\n record(event: BrowserActionEvent): void {\n this.queue.push(event);\n if (this.queue.length >= (this.opts.batchSize ?? EVENT_BATCH_SIZE)) {\n this.drain();\n } else if (this.timer === null) {\n this.timer = setTimeout(\n () => this.drain(),\n this.opts.flushIntervalMs ?? EVENT_FLUSH_INTERVAL_MS,\n );\n if (typeof this.timer === \"object\" && \"unref\" in this.timer)\n this.timer.unref();\n }\n }\n\n /** Resolve once everything recorded so far has been posted (or dropped). */\n async flush(): Promise<void> {\n this.drain();\n await this.inflight;\n }\n\n async close(): Promise<void> {\n await this.flush();\n }\n\n private drain(): void {\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n if (this.queue.length === 0) return;\n const batch = this.queue;\n this.queue = [];\n this.inflight = this.inflight.then(() => this.send(batch));\n }\n\n private async send(batch: BrowserActionEvent[]): Promise<void> {\n const retries = this.opts.maxRetries ?? EVENT_MAX_RETRIES;\n const sleep =\n this.opts.sleep ??\n ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));\n for (let attempt = 0; attempt < retries; attempt++) {\n try {\n const base = await this.resolveBase();\n await this.post(\n base === 0 ? batch : batch.map((e) => ({ ...e, seq: base + e.seq })),\n );\n this.sent += batch.length;\n return;\n } catch (error) {\n if (attempt + 1 === retries) {\n this.dropped += batch.length;\n (this.opts.warn ?? console.warn)(\n `dropping ${batch.length} browser events after ${attempt + 1} attempts: ${String(error)}`,\n );\n return;\n }\n await sleep(500 * 2 ** attempt);\n }\n }\n }\n}\n\n/**\n * One Playwright page on the session's UI. Thin on purpose — `page` is the\n * real Playwright page for anything this wrapper does not cover.\n */\nexport class WorldBrowser {\n private current: BrowserPage;\n private inflight = 0;\n private lastNetwork = Date.now();\n /** Where the page last was after an action, token stripped: what a\n * reconnect reopens. Null until the page has left `about:blank`. */\n private lastUrl: string | null = null;\n\n constructor(\n page: BrowserPage,\n readonly ui: SessionSurfaces[\"ui\"] | undefined,\n readonly mode: Exclude<BrowserMode, \"auto\">,\n private readonly teardown: () => Promise<void>,\n readonly viewport: { width: number; height: number } = DEFAULT_VIEWPORT,\n readonly recorder: BrowserActionRecorder | null = null,\n private readonly reconnector: BrowserReconnector | null = null,\n /** Takes session credentials out of every error this browser records. */\n private readonly scrubber: SecretScrubber = new SecretScrubber([ui?.token]),\n ) {\n this.current = page;\n this.watchNetwork(page);\n }\n\n /** The live Playwright page; a new object after a reconnect. */\n get page(): BrowserPage {\n return this.current;\n }\n\n get agentId(): string | null {\n return this.recorder?.agentId ?? null;\n }\n\n private watchNetwork(page: BrowserPage): void {\n page.on(\"request\", () => {\n this.inflight += 1;\n this.lastNetwork = Date.now();\n });\n const done = () => {\n this.inflight = Math.max(0, this.inflight - 1);\n this.lastNetwork = Date.now();\n };\n page.on(\"requestfinished\", done);\n page.on(\"requestfailed\", done);\n }\n\n /** Run `fn` against the page. If it fails because the browser is gone,\n * recover; then `retry` runs it ONCE more and `report` throws\n * `BrowserReconnected` instead of replaying it. Any other error, and a\n * second loss during the retry, propagate unchanged. */\n private async resilient<T>(\n fn: () => Promise<T>,\n onLoss: OnBrowserLoss,\n ): Promise<T> {\n try {\n return this.remember(await fn());\n } catch (error) {\n if (!this.reconnector || !isBrowserGone(error)) throw error;\n const recovered = await this.recover(this.reconnector, error);\n if (onLoss === \"report\")\n throw new BrowserReconnected(\n recovered.outcome,\n recovered.restoredUrl,\n error,\n );\n }\n return this.remember(await fn());\n }\n\n private remember<T>(result: T): T {\n this.lastUrl = this.openedUrl() ?? this.lastUrl;\n return result;\n }\n\n /** The page's URL less its token; null while it is blank. */\n private openedUrl(): string | null {\n const url = this.page.url();\n return url && url !== \"about:blank\" ? withoutUiToken(url) : null;\n }\n\n private async recover(\n reconnector: BrowserReconnector,\n cause: unknown,\n ): Promise<RecoveryResult & { restoredUrl: string | null }> {\n const started = Date.now();\n const message = cause instanceof Error ? cause.message : String(cause);\n const args = { cause: this.scrubber.scrub(message).slice(0, 200) };\n let result: RecoveryResult;\n try {\n result = await reconnector.recover(cause, (c) => this.adopt(c));\n } catch (error) {\n await this.report(\"browser_reconnect\", args, started, error);\n throw error;\n }\n const restoredUrl = this.openedUrl();\n await this.report(\n \"browser_reconnect\",\n { ...args, ...result, restoredUrl },\n started,\n null,\n );\n return { ...result, restoredUrl };\n }\n\n /** Take over a new connection's page and reopen the page the agent was on\n * (`openBrowser` owns the connection itself). A new browser has no session\n * cookie, so a World Host UI is first loaded with its token, exactly as\n * `goto()` loads the entry page. */\n private async adopt(connection: BrowserConnection): Promise<void> {\n this.current = connection.page;\n this.inflight = 0;\n this.watchNetwork(connection.page);\n const last = this.lastUrl;\n if (!last) return;\n if (this.ui?.token)\n await this.page.goto(uiEntryUrl(this.ui), { waitUntil: \"load\" });\n if (withoutUiToken(this.page.url()) !== last)\n await this.page.goto(last, { waitUntil: \"load\" });\n await this.settle();\n }\n\n /** Run one action and report it: the event carries what was asked,\n * whether it worked, and the screen after — for failures too, so a\n * reviewer sees what the agent saw when the selector did not match. */\n private async act<T>(\n action: string,\n args: Record<string, unknown>,\n fn: () => Promise<T>,\n onLoss: OnBrowserLoss = \"report\",\n ): Promise<T> {\n const started = Date.now();\n try {\n const result = await this.resilient(fn, onLoss);\n await this.report(action, args, started, null);\n return result;\n } catch (error) {\n await this.report(action, args, started, error);\n throw error;\n }\n }\n\n /** One event on the recorder, if there is one; `failure` null means ok. */\n private async report(\n action: string,\n args: Record<string, unknown>,\n started: number,\n failure: unknown,\n ): Promise<void> {\n const recorder = this.recorder;\n if (!recorder) return;\n const error =\n failure === null\n ? null\n : this.scrubber\n .scrub(\n failure instanceof Error\n ? `${failure.name}: ${failure.message}`\n : String(failure),\n )\n .slice(0, 4000);\n recorder.record({\n agentId: recorder.agentId,\n seq: recorder.nextSeq(),\n ts: new Date().toISOString(),\n action,\n args: redactActionArgs(action, args),\n ok: failure === null,\n error,\n durationMs: Date.now() - started,\n mode: this.mode,\n viewport: { ...this.viewport },\n ...(await this.observeForEvent()),\n });\n }\n\n private async observeForEvent(): Promise<\n Pick<BrowserActionEvent, \"url\" | \"title\" | \"screenshot\">\n > {\n const out: Pick<BrowserActionEvent, \"url\" | \"title\" | \"screenshot\"> = {\n url: null,\n title: null,\n screenshot: null,\n };\n try {\n out.url = this.page.url();\n out.title = await this.page.title();\n const jpeg = await this.page.screenshot({\n type: \"jpeg\",\n quality: EVENT_SCREENSHOT_QUALITY,\n });\n out.screenshot = jpeg.toString(\"base64\");\n } catch {\n // a closed page still gets its event\n }\n return out;\n }\n\n /** Open a UI path (`/customers`), a full URL, or — with no argument — the\n * UI's declared entry page. */\n async goto(pathOrUrl?: string): Promise<string> {\n let target: string;\n if (pathOrUrl === undefined) {\n if (!this.ui)\n throw new WorldSurfaceUnavailable(\n \"ui\",\n \"this session has no UI to navigate to\",\n );\n target = uiEntryUrl(this.ui);\n } else if (/^https?:\\/\\//.test(pathOrUrl)) {\n target = pathOrUrl;\n } else {\n if (!this.ui)\n throw new WorldSurfaceUnavailable(\n \"ui\",\n \"relative paths need a UI surface\",\n );\n target = uiUrl(this.ui, pathOrUrl);\n }\n return this.act(\n \"browser_goto\",\n { path: pathOrUrl ?? null, url: withoutUiToken(target) },\n async () => {\n await this.page.goto(target, { waitUntil: \"load\" });\n await this.settle();\n return this.page.url();\n },\n // Navigating again lands on the same page: safe to replay.\n \"retry\",\n );\n }\n\n async back(): Promise<string> {\n return this.act(\"browser_back\", {}, async () => {\n await this.page.goBack({ waitUntil: \"load\" });\n await this.settle();\n return this.page.url();\n });\n }\n\n /** Wait for the page to finish reacting to an action. `load` alone is not\n * enough for client-rendered UIs (React et al.): a click returns before the\n * fetch that re-renders the page, so an agent would read stale text.\n * Playwright's `networkidle` is per navigation and resolves at once after\n * the first one, so this tracks requests itself: done when nothing is in\n * flight and the network has been quiet for `SETTLE_QUIET_MS`, bounded so\n * long-polling UIs cannot hang us. */\n private async settle(): Promise<void> {\n await this.page.waitForLoadState(\"load\");\n const deadline = Date.now() + SETTLE_TIMEOUT_MS;\n while (Date.now() < deadline) {\n const quiet = Date.now() - this.lastNetwork >= SETTLE_QUIET_MS;\n if (this.inflight === 0 && quiet) return;\n await this.page.waitForTimeout(SETTLE_POLL_MS);\n }\n }\n\n async click(selector: string): Promise<void> {\n await this.act(\"browser_click\", { selector }, async () => {\n await this.page.click(selector);\n await this.settle();\n });\n }\n\n async type(selector: string, text: string): Promise<void> {\n await this.act(\"browser_type\", { selector, text }, () =>\n this.page.fill(selector, text),\n );\n }\n\n async press(key: string): Promise<void> {\n await this.act(\"browser_press\", { key }, async () => {\n await this.page.keyboard.press(key);\n await this.settle();\n });\n }\n\n async scroll(dy: number): Promise<void> {\n await this.act(\"browser_scroll\", { dy }, () =>\n this.page.mouse.wheel(0, dy),\n );\n }\n\n async screenshot(fullPage = false): Promise<Buffer> {\n return this.resilient(\n () => this.page.screenshot({ type: \"png\", fullPage }),\n \"retry\",\n );\n }\n\n async screenshotBase64(fullPage = false): Promise<string> {\n return (await this.screenshot(fullPage)).toString(\"base64\");\n }\n\n async text(selector = \"body\"): Promise<string> {\n return this.resilient(() => this.page.innerText(selector), \"retry\");\n }\n\n async html(): Promise<string> {\n return this.resilient(() => this.page.content(), \"retry\");\n }\n\n get url(): string {\n return this.page.url();\n }\n\n async title(): Promise<string> {\n return this.resilient(() => this.page.title(), \"retry\");\n }\n\n async close(): Promise<void> {\n try {\n await this.teardown();\n } finally {\n await this.recorder?.close();\n }\n }\n}\n\n/** The Playwright entry points this module needs, so tests can inject a fake. */\nexport type PlaywrightLike = {\n chromium: {\n connect(wsEndpoint: string): Promise<PlaywrightBrowserLike>;\n connectOverCDP(endpointURL: string): Promise<PlaywrightBrowserLike>;\n launch(opts?: { headless?: boolean }): Promise<PlaywrightBrowserLike>;\n };\n};\n\nexport type PlaywrightBrowserLike = {\n newContext(opts?: {\n viewport?: { width: number; height: number };\n }): Promise<{ newPage(): Promise<BrowserPage>; close(): Promise<void> }>;\n close(): Promise<void>;\n};\n\nasync function loadPlaywright(): Promise<PlaywrightLike> {\n try {\n // A string specifier keeps bundlers from resolving the optional peer.\n const name = \"playwright\";\n return (await import(name)) as PlaywrightLike;\n } catch (error) {\n throw new Error(\n \"Driving a world UI needs Playwright: npm install playwright \" +\n \"(and `npx playwright install chromium` for local mode).\",\n { cause: error },\n );\n }\n}\n\nexport function resolveBrowserMode(\n surfaces: SessionSurfaces,\n mode: BrowserMode,\n): Exclude<BrowserMode, \"auto\"> {\n if (!surfaces.ui && !surfaces.browser)\n throw new WorldSurfaceUnavailable(\n \"ui\",\n \"open the session with surfaces: ['ui'] on a world that declares [ui]\",\n );\n const resolved =\n mode === \"auto\" ? (surfaces.browser ? \"hosted\" : \"local\") : mode;\n if (resolved === \"hosted\" && !surfaces.browser)\n throw new WorldSurfaceUnavailable(\n \"browser\",\n \"open the session with surfaces: ['browser'] to get a hosted browser\",\n );\n return resolved;\n}\n\n/** Open a browser on the session's UI in `hosted`, `local` or `auto` mode. */\nexport async function openBrowser(\n surfaces: SessionSurfaces,\n opts: {\n mode?: BrowserMode;\n headless?: boolean;\n playwright?: PlaywrightLike;\n recorder?: BrowserActionRecorder | null;\n /** The session's repair call (`session.repairBrowser`). Given, a hosted\n * `cdp` browser reconnects on its own when the browser is lost. */\n repair?: () => Promise<RepairAnswer>;\n } = {},\n): Promise<WorldBrowser> {\n const mode = resolveBrowserMode(surfaces, opts.mode ?? \"auto\");\n const pw = opts.playwright ?? (await loadPlaywright());\n const viewport = surfaces.browser?.viewport ?? DEFAULT_VIEWPORT;\n const attach = async (): Promise<BrowserConnection> => {\n const browser =\n mode === \"hosted\"\n ? surfaces.browser!.protocol === \"playwright\"\n ? await pw.chromium.connect(surfaces.browser!.wsUrl)\n : await pw.chromium.connectOverCDP(surfaces.browser!.wsUrl)\n : await pw.chromium.launch({ headless: opts.headless ?? true });\n const context = await browser.newContext({ viewport });\n return { browser, context, page: await context.newPage() };\n };\n let live = await attach();\n /** The same address again; the lost connection is released once a new one\n * stands. */\n const reattach = async (): Promise<BrowserConnection> => {\n const fresh = await attach();\n await releaseConnection(live);\n live = fresh;\n return fresh;\n };\n // A browser error quotes the URL it failed on; these carry the session.\n const scrubber = new SecretScrubber([\n surfaces.browser?.wsUrl,\n surfaces.ui?.token,\n ]);\n // Only the platform's relay can be repaired behind the same address.\n const reconnector =\n mode === \"hosted\" && surfaces.browser!.protocol === \"cdp\" && opts.repair\n ? new BrowserReconnector(opts.repair, reattach, {\n scrub: (text) => scrubber.scrub(text),\n })\n : null;\n return new WorldBrowser(\n live.page,\n surfaces.ui,\n mode,\n () => closeConnection(live),\n viewport,\n opts.recorder ?? null,\n reconnector,\n scrubber,\n );\n}\n\n// ── computer-use tools ───────────────────────────────────────────────────────\n\nexport const COMPUTER_USE_SPECS = [\n {\n name: \"browser_goto\",\n signature: \"browser_goto(path=None)\",\n doc: \"Open a page of the world's UI. `path` is a UI path like /customers, a full URL, or omitted for the entry page. Returns the URL and page text.\",\n },\n {\n name: \"browser_click\",\n signature: \"browser_click(selector)\",\n doc: \"Click an element by Playwright selector (CSS, `text=Refund`, `role=button[name=Save]`). Returns the page text after the click.\",\n },\n {\n name: \"browser_type\",\n signature: \"browser_type(selector, text)\",\n doc: \"Replace the value of an input/textarea found by selector with `text`.\",\n },\n {\n name: \"browser_press\",\n signature: \"browser_press(key)\",\n doc: \"Press a key (Enter, Tab, Escape, ArrowDown, ...). Returns the page text after.\",\n },\n {\n name: \"browser_scroll\",\n signature: \"browser_scroll(dy=600)\",\n doc: \"Scroll the page vertically by `dy` pixels (negative scrolls up).\",\n },\n {\n name: \"browser_screenshot\",\n signature: \"browser_screenshot(full_page=False)\",\n doc: \"Take a PNG screenshot; returns {image_base64, url}.\",\n },\n {\n name: \"browser_read\",\n signature: \"browser_read(selector='body')\",\n doc: \"Return the visible text of an element (default: whole page) plus the URL and title.\",\n },\n {\n name: \"browser_back\",\n signature: \"browser_back()\",\n doc: \"Go back one page in history.\",\n },\n] as const;\n\nconst str = (v: unknown, fallback: string): string =>\n typeof v === \"string\" && v.length > 0 ? v : fallback;\n\n/**\n * The browser as model tools, in the same `WorldToolkit` shape the world's\n * own tools come in — so an agent loop that already dispatches\n * `toolkit().impls` merges `computerUseToolkit(b).impls` and gains a screen\n * without a second dispatch path.\n */\nexport function computerUseToolkit(\n browser: WorldBrowser,\n opts: { maxText?: number } = {},\n): WorldToolkit {\n const maxText = opts.maxText ?? 20_000;\n const observe = async (selector = \"body\") => {\n const text = await browser.text(selector);\n return {\n url: browser.url,\n title: await browser.title(),\n text: text.slice(0, maxText),\n truncated: text.length > maxText,\n };\n };\n\n const impls: WorldToolkit[\"impls\"] = {\n browser_goto: async (a) => {\n await browser.goto(typeof a.path === \"string\" ? a.path : undefined);\n return observe();\n },\n browser_click: async (a) => {\n await browser.click(str(a.selector, \"\"));\n return observe();\n },\n browser_type: async (a) => {\n await browser.type(str(a.selector, \"\"), String(a.text ?? \"\"));\n return { ok: true, url: browser.url };\n },\n browser_press: async (a) => {\n await browser.press(str(a.key, \"Enter\"));\n return observe();\n },\n browser_scroll: async (a) => {\n await browser.scroll(typeof a.dy === \"number\" ? a.dy : 600);\n return { ok: true, url: browser.url };\n },\n browser_screenshot: async (a) => ({\n image_base64: await browser.screenshotBase64(a.full_page === true),\n url: browser.url,\n }),\n browser_read: async (a) => observe(str(a.selector, \"body\")),\n browser_back: async () => {\n await browser.back();\n return observe();\n },\n };\n\n const specs = COMPUTER_USE_SPECS.map((s) => ({ ...s }));\n return {\n schemas: specs.map((spec) => schemaFromSignature(spec)),\n impls,\n specs,\n };\n}\n","/**\n * THE NUMBERS AND WORDS A WORLD SESSION PROMISES — the TypeScript SDK twin.\n *\n * The platform declares them once in\n * `gateway/packages/shared/src/server/services/worldSessionContract.ts`; this\n * module and `gatewaysdk/environment/world_session_contract.py` repeat them, and each is\n * pinned to `conformance/world-sessions.json` by a test, so the route, the\n * World Host and the two CLIs cannot drift apart.\n */\n\n/** The largest body `POST world-sessions/{id}/calls` accepts. The SDK\n * measures the serialized body against the byte count and refuses before\n * sending; the label is what help and the refusal name. */\nexport const CALL_BODY_LIMIT_BYTES = 4 * 1024 * 1024;\nexport const CALL_BODY_LIMIT_LABEL = \"4mb\";\n\n/** `session status` warns once an unpinned session has less than this left. */\nexport const IDLE_WARNING_MINUTES = 5;\n\n/** The task an exploratory session runs on when the caller names none, and\n * the `task.source` the platform reports for it. */\nexport const EXPLORATORY_TASK = Object.freeze({\n instruction: \"exploratory session\",\n});\nexport const EXPLORATORY_TASK_SOURCE = \"none\";\n\n/** What a session that has no grader answers `grade` with, beside\n * `reward: null`. */\nexport const NO_GRADER_REASON = \"no grader\";\n\n/** The call's body exceeds the platform's limit: nothing was sent. `limit`\n * is the label the route enforces (`4mb`), `size` the body's bytes. */\nexport class WorldCallTooLarge extends Error {\n readonly code = \"payload_too_large\";\n\n constructor(\n readonly size: number,\n readonly limitBytes: number = CALL_BODY_LIMIT_BYTES,\n readonly limit: string = CALL_BODY_LIMIT_LABEL,\n ) {\n super(\n `call body is ${size} bytes; the platform accepts at most ${limit} (${limitBytes} bytes)`,\n );\n this.name = \"WorldCallTooLarge\";\n }\n\n /** The structured refusal the CLIs print. */\n toJSON(): {\n status: \"error\";\n code: \"payload_too_large\";\n limit: string;\n size: number;\n } {\n return {\n status: \"error\",\n code: this.code,\n limit: this.limit,\n size: this.size,\n };\n }\n}\n\n/** Measure a call body the way the route will and refuse an oversized one\n * before it leaves the machine. Returns the serialized body. */\nexport function serializeCallBody(body: unknown): string {\n const text = JSON.stringify(body);\n const size = Buffer.byteLength(text, \"utf8\");\n if (size > CALL_BODY_LIMIT_BYTES) throw new WorldCallTooLarge(size);\n return text;\n}\n\n/** The line `session status` prints when an unpinned session has under\n * `IDLE_WARNING_MINUTES` left, else null. `now` is for tests. */\nexport function idleWarning(\n idleExpiresAt: string | null | undefined,\n now: Date = new Date(),\n): string | null {\n if (!idleExpiresAt) return null;\n const leftMs = new Date(idleExpiresAt).getTime() - now.getTime();\n if (leftMs >= IDLE_WARNING_MINUTES * 60_000) return null;\n const minutes = Math.max(0, Math.floor(leftMs / 60_000));\n return (\n `warning: session expires in ${minutes}m (idle TTL); ` +\n \"call a tool to extend it or `gateway worlds session pin` to keep it\"\n );\n}\n","import type {\n WorldSessionTask,\n WorldTaskIdRef,\n WorldTaskRef,\n WorldTaskSpec,\n} from \"./session\";\n\n/**\n * The three shapes a task reaches `openSession` in — a bundled scenario's\n * name, a stored task's `{ id, version? }`, an inline spec — and how each is\n * told apart, labelled and checked. No task at all (`undefined`) is the\n * fourth case, an exploratory session, and is not a ref.\n */\n\nexport const isTaskIdRef = (task: WorldTaskRef): task is WorldTaskIdRef =>\n typeof task === \"object\" && task !== null && \"id\" in task;\n\nexport const isTaskSpec = (task: WorldTaskRef): task is WorldTaskSpec =>\n typeof task === \"object\" && task !== null && \"instruction\" in task;\n\n/** The label a task goes by in results: its name, `inline:<hash>` for an\n * unnamed inline task once the platform has hashed it, or the stored task's\n * name (its id until the platform has answered). */\nexport const taskLabel = (\n task: WorldTaskRef,\n info?: WorldSessionTask | null,\n): string => {\n if (typeof task === \"string\") return task;\n if (isTaskIdRef(task)) return info?.name ?? task.id;\n if (task.name) return task.name;\n return info?.hash ? `inline:${info.hash.slice(0, 12)}` : \"inline\";\n};\n\n/** A task given to `openSession` must be one of the three shapes. */\nexport const assertTaskRef = (task: WorldTaskRef): void => {\n const malformed =\n task === null ||\n (typeof task === \"string\" && !task) ||\n (isTaskIdRef(task) && !task.id) ||\n (isTaskSpec(task) && !task.instruction) ||\n (typeof task === \"object\" && !isTaskIdRef(task) && !isTaskSpec(task));\n if (malformed)\n throw new Error(\n \"openSession needs a task: a bundled task name, a stored task { id, version? } or { instruction, seed?, grader?, metadata? } — or none at all for an exploratory session\",\n );\n};\n","import { randomUUID } from \"node:crypto\";\n\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\nimport {\n BrowserActionRecorder,\n SURFACE_KINDS,\n WorldSurfaceUnavailable,\n assertBrowserTier,\n computerUseToolkit,\n openBrowser,\n uiEntryUrl,\n type BrowserActionEvent,\n type BrowserMode,\n type BrowserTier,\n type PlaywrightLike,\n type SessionSurfaces,\n type WorldBrowser,\n type WorldSurfaceKind,\n} from \"./browser\";\nimport type { RepairAnswer } from \"./browserReconnect\";\nimport type { WorldTaskSummary } from \"./tasks\";\nimport { serializeCallBody } from \"./sessionContract\";\nimport { assertTaskRef, isTaskIdRef, isTaskSpec, taskLabel } from \"./taskRef\";\n\nexport { isTaskIdRef, isTaskSpec, taskLabel } from \"./taskRef\";\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, { task: \"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 * The task can also be YOURS rather than the bundle's — an instruction, the\n * rows the session starts with and how it is graded, for one end user:\n *\n * const session = await openSession(\"acme-billing@main\", {\n * task: {\n * instruction: \"Mark invoice INV-7 as paid.\",\n * seed: { rows: { invoices: [{ id: \"INV-7\", status: \"open\" }] } },\n * grader: { kind: \"assertions\", checks: [\n * { entity: \"invoices\", where: { id: \"INV-7\", status: \"paid\" } },\n * ] },\n * metadata: { externalUserId: \"u_42\" },\n * },\n * surfaces: [\"api\"],\n * });\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 inputSchema?: Record<string, unknown>;\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\n// ── tasks ────────────────────────────────────────────────────────────────────\n\n/** A JSON scalar: what `where` filters and field predicates compare against. */\nexport type WorldTaskScalar = string | number | boolean | null;\n\n/** The rows a task starts the session with — the `seed()` contract, applied\n * by the host right after it clones the version's snapshot. `append`\n * (default) upserts by primary key onto the base data; `replace` makes the\n * named entities hold exactly these rows. */\nexport type WorldTaskSeed = {\n mode?: \"append\" | \"replace\";\n /** Redaction on the way in: `off` (default) stores the rows as given,\n * `apply` runs the world's `[redact]` policy over them first, `refuse`\n * rejects a row carrying plaintext in a redacted field. */\n redact?: \"off\" | \"apply\" | \"refuse\";\n rows: Record<string, Record<string, unknown>[]>;\n};\n\nexport type WorldTaskFieldOp =\n \"eq\" | \"neq\" | \"in\" | \"gt\" | \"gte\" | \"lt\" | \"lte\" | \"contains\";\n\n/**\n * One declarative check over the session's final rows. `where` selects rows\n * of `entity` by equality (dotted paths reach into nested objects); the\n * assertion says what must hold of the selection:\n *\n * exists (default) / absent at least one row / none\n * count `count` bound on how many\n * all / any `field op value` on every / some selected row\n *\n * A check's `id` names its entry in `rewards`; the task's reward is the\n * weighted share of checks that passed.\n */\nexport type WorldTaskCheck = {\n id?: string;\n weight?: number;\n entity: string;\n where?: Record<string, WorldTaskScalar>;\n assert?: \"exists\" | \"absent\" | \"count\" | \"all\" | \"any\";\n count?: { eq?: number; gte?: number; lte?: number };\n field?: string;\n op?: WorldTaskFieldOp;\n value?: WorldTaskScalar | WorldTaskScalar[];\n};\n\n/** One thing a rubric judge scores in [0, 1]; `id` names its entry in\n * `rewards`, `weight` (default 1) its share of the task's reward. */\nexport type WorldTaskRubricCriterion = {\n id: string;\n description: string;\n weight?: number;\n};\n\n/** A rubric is prose: what a good outcome looks like. The platform (never the\n * host) has a model read the session's final state and its call log against\n * it; the project's default evaluation model judges unless `model` pins one.\n * `grade()` then resolves asynchronously — `pending: true` first, the reward\n * once the judge has answered. */\nexport type WorldTaskRubricGrader = {\n kind: \"rubric\";\n rubric: string;\n criteria?: WorldTaskRubricCriterion[];\n model?: { provider: string; model: string };\n};\n\n/** How a task is graded: checks the host evaluates in-process, a `verify.py`\n * body (state JSON on stdin, last stdout line `{reward, ...}`) run through the\n * host's confined verifier, or a rubric judged by a model on the platform. */\nexport type WorldTaskGrader =\n | { kind: \"assertions\"; checks: WorldTaskCheck[] }\n | { kind: \"python\"; source: string; timeoutSeconds?: number }\n | WorldTaskRubricGrader;\n\n/** A task supplied at open, for one session, instead of a bundled scenario.\n * `instruction` is what the agent is told; without `seed` the session starts\n * on the version's base data, without `grader` `grade()` answers\n * `reward: null`; `tools` is the allow-list of the version's tools the agent\n * may call in this session (unset: all of them; a call outside it is refused\n * and logged); `metadata` is yours (an end-user id, a ticket) and is echoed\n * on the session, never read. Limits: shared/domain/worldTasks.ts. */\nexport type WorldTaskSpec = {\n name?: string;\n instruction: string;\n seed?: WorldTaskSeed;\n grader?: WorldTaskGrader;\n tools?: string[];\n metadata?: Record<string, unknown>;\n /** A MULTI-WORLD task: one session per alias, each on its own world with\n * its own seed, grader and tools (the top-level three are then refused).\n * Brought up together by `openTask` / `gateway worlds task up`; see\n * worlds/taskSessions.ts. */\n worlds?: Record<\n string,\n {\n slug: string;\n /** One of the world's refs; default `main`. */\n ref?: string;\n seed?: WorldTaskSeed;\n grader?: WorldTaskGrader;\n tools?: string[];\n }\n >;\n /** CROSS-WORLD VERIFIERS: deterministic graders over several of the task's\n * worlds at once, each with a `scope` of aliases (two or more). One runs on\n * the session of the first alias in its scope, over a state where every\n * scoped world's rows are `<alias>.<entity>` and its calls `<alias>.calls`;\n * the platform gathers the other worlds' evidence when `grade()` names\n * them (`TaskSessions.grade` does). Rewards come back as `x.<name>`. */\n verifiers?: WorldTaskVerifier[];\n};\n\nexport type WorldTaskVerifier = { name: string; scope: string[] } & (\n | { kind: \"assertions\"; checks: WorldTaskCheck[] }\n | { kind: \"python\"; source: string; timeoutSeconds?: number }\n);\n\n/** A stored task of the project (see worlds/tasks.ts), opened by id; the\n * session runs a copy of one version's spec — the current one by default. */\nexport type WorldTaskIdRef = { id: string; version?: number };\n\n/** What `openSession` takes as the task: a bundled scenario's name, a\n * stored task's `{ id, version? }`, or an inline spec. */\nexport type WorldTaskRef = string | WorldTaskIdRef | WorldTaskSpec;\n\n/** What a session's task is, on every session response. `hash` is the\n * content hash of the spec (inline or stored) — what warm reuse matches on;\n * `id`/`version` name the stored task the session was opened on. */\nexport type WorldSessionTask = {\n /** `none` is an exploratory session: opened with no task, no grader. */\n source: \"bundled\" | \"inline\" | \"stored\" | \"none\";\n name: string | null;\n hash: string | null;\n id?: string | null;\n version?: number | null;\n metadata: Record<string, unknown>;\n};\n\nexport type SeedResult = {\n seeded: number;\n mode: \"append\" | \"replace\";\n entity_counts: Record<string, number>;\n};\n\n/** One row of the session's call log. */\nexport type WorldSessionCall = {\n seq: number;\n kind: string;\n tool: string | null;\n args: unknown;\n result: unknown;\n error: string | null;\n completedAt: string | null;\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 /** Where the task came from and what it is; absent on platforms that\n * predate session tasks, in which case it is derived from `taskName`. */\n task?: WorldSessionTask;\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 /** When the fleet reaps this session unless a call lands first; null for\n * a pinned session (never reaped). Absent on platforms that predate it. */\n idleExpiresAt?: string | null;\n pinned?: boolean;\n /** Where the session answers besides `tools` — see worlds/browser.ts. */\n surfaces?: SessionSurfaces;\n /** Notices about the world's shape (an api bundle is a deprecated layout;\n * schema worlds are the supported shape), with what to run instead. Empty\n * for a schema world; absent on platforms that predate the notice. */\n deprecations?: WorldDeprecation[];\n};\n\n/** One notice a worlds-path answer carries: a deprecated shape or layout\n * and the command that replaces it. A retired shape is refused instead,\n * with the stable message prefix `world_kind_retired:`. */\nexport type WorldDeprecation = {\n code: string;\n message: string;\n replacement: string;\n};\n\nexport type GradeResult = {\n reward: number | null;\n rewards: Record<string, number>;\n /** Why there is no reward: `no grader` on an exploratory session. */\n reason?: string;\n /** The task's cross-world verifiers anchored on this session, by name:\n * each its own reward and named rewards, or `error` when it could not\n * grade (evidence missing, verify.py failed) — null, never zero. */\n verifiers?: Record<string, VerifierGrade>;\n raw: unknown;\n};\n\nexport type VerifierGrade = {\n reward: number | null;\n rewards: Record<string, number>;\n error?: string;\n};\n\n/** A grade payload's numbers: `reward`, and every numeric key under\n * `rewards` (the host's shape) or at the top level (a bundled verifier's). */\nfunction numericGrade(record: Record<string, unknown>): {\n reward: number | null;\n rewards: Record<string, number>;\n} {\n const rewards: Record<string, number> = {};\n const nested = record.rewards;\n if (nested && typeof nested === \"object\") {\n for (const [key, value] of Object.entries(nested)) {\n if (typeof value === \"number\") rewards[key] = value;\n }\n }\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 };\n}\n\n/** The `verifiers` block of a grade payload, or undefined when absent. */\nfunction verifierGrades(\n value: unknown,\n): Record<string, VerifierGrade> | undefined {\n if (!value || typeof value !== \"object\") return undefined;\n const out: Record<string, VerifierGrade> = {};\n for (const [name, grade] of Object.entries(value as Record<string, unknown>)) {\n const record =\n grade && typeof grade === \"object\"\n ? (grade as Record<string, unknown>)\n : {};\n out[name] = {\n ...numericGrade(record),\n ...(typeof record.error === \"string\" ? { error: record.error } : {}),\n };\n }\n return out;\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/** How long a grade the platform's judge finalizes may take: the model's own\n * timeout and retries, plus the worker's queue backoff. Polled slowly. */\nconst JUDGED_GRADE_TIMEOUT_MS = 15 * 60_000;\nconst JUDGED_GRADE_POLL_MS = 2_000;\nconst EXPORT_PAGE = 500;\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\nexport const modelToolName = (name: string): string =>\n name.replace(/[^A-Za-z0-9_-]/g, \"_\").slice(0, 64) || \"tool\";\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 if (spec.inputSchema)\n return {\n type: \"function\",\n function: {\n name: modelToolName(spec.name),\n description: spec.doc ?? spec.name,\n parameters: spec.inputSchema,\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: modelToolName(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 current: WorldSessionState,\n private readonly options: WorldsClientOptions,\n ) {}\n\n /** The task's display name: a bundled scenario's, or the inline spec's\n * `name` (null when the spec was unnamed). `task` is the same. */\n get taskName(): string | null {\n return this.current.taskName;\n }\n get task(): string | null {\n return this.taskName;\n }\n\n /** `{idleExpiresAt, pinned}` as of the last state read: when the fleet\n * reaps the session (null once pinned), and whether it is pinned. */\n get idle(): { idleExpiresAt: string | null; pinned: boolean } {\n return {\n idleExpiresAt: this.current.idleExpiresAt ?? null,\n pinned: this.current.pinned ?? false,\n };\n }\n\n /** The platform's notices about the world this session runs on (empty\n * for a schema world). Printed by the CLI on stderr at open. */\n get deprecations(): WorldDeprecation[] {\n return this.current.deprecations ?? [];\n }\n\n /** The task this session runs: bundled scenario, stored task or inline\n * spec, its name, hash and the caller's metadata. */\n get taskInfo(): WorldSessionTask {\n return (\n this.current.task ?? {\n source: \"bundled\",\n name: this.current.taskName,\n hash: null,\n metadata: {},\n }\n );\n }\n\n /** What this task asks for — the bundle's instruction.md, or the inline\n * spec's `instruction`. */\n get instruction(): string | null {\n return this.current.instruction ?? null;\n }\n\n get versionId(): string {\n return this.current.versionId;\n }\n\n /** Whether the session answered ready as of the last state read (the open,\n * a `status()`, or the poll inside `ready()`); no request is made. */\n get isReady(): boolean {\n return this.current.ready;\n }\n\n /** `api` / `ui` / `browser` are present exactly when the world declares\n * them AND the session was opened asking for them. */\n async surfaces(): Promise<SessionSurfaces> {\n if (!this.current.surfaces) await this.status();\n return this.current.surfaces ?? { tools: { kind: \"rendezvous\" } };\n }\n\n /** Base URL of the world's own HTTP API for this session. */\n async api(): Promise<string> {\n const { api } = await this.surfaces();\n if (!api)\n throw new WorldSurfaceUnavailable(\n \"api\",\n \"open the session with surfaces: ['api'] on an api-type world\",\n );\n return api.url;\n }\n\n /** Headers every request to `api()` needs. A World Host session gates its\n * api surface on a per-session token; a pod or hosted twin answers with the\n * world's own declared auth and this is `{}`. */\n async apiHeaders(): Promise<Record<string, string>> {\n const { api } = await this.surfaces();\n return api?.token ? { Authorization: `Bearer ${api.token}` } : {};\n }\n\n /** URL of the world's UI entry page for this session. */\n async ui(): Promise<string> {\n const { ui } = await this.surfaces();\n if (!ui)\n throw new WorldSurfaceUnavailable(\n \"ui\",\n \"open the session with surfaces: ['ui'] on a world that declares [ui]\",\n );\n return uiEntryUrl(ui);\n }\n\n /** A Playwright browser on this session's UI: `hosted` drives the one the\n * platform runs next to the world, `local` launches one here, `auto`\n * prefers hosted. Call `close()` when done.\n *\n * Every action is reported to the platform under `agentId` (default:\n * `GATEWAY_AGENT_ID` or a fresh `agent-<hex>`) so the session page shows\n * this agent's own timeline — several agents may share one session and\n * one hosted browser. `record: false` opts out. */\n async browser(\n opts: {\n mode?: BrowserMode;\n headless?: boolean;\n playwright?: PlaywrightLike;\n agentId?: string;\n record?: boolean;\n } = {},\n ): Promise<WorldBrowser> {\n const { agentId, record = true, ...rest } = opts;\n return openBrowser(await this.surfaces(), {\n ...rest,\n recorder: record ? this.browserRecorder(agentId) : null,\n repair: () => this.repairBrowser(),\n });\n }\n\n /** Ask the platform to make this session's hosted browser reachable again\n * after its connection dropped: `healthy` (reconnect now), `replaced` (a new,\n * blank browser behind the same wsUrl; reconnect and reopen your page) or\n * `starting` (ask again in `retryAfterMs`). `browser()` does this on its\n * own; call it when you drive your own Playwright against `wsUrl`. */\n async repairBrowser(): Promise<RepairAnswer> {\n return apiRequest<RepairAnswer>(\n this.options,\n \"POST\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/browser-repair`,\n {},\n );\n }\n\n /** The reporter `browser()` uses; exposed for a page you drive yourself. */\n browserRecorder(agentId?: string): BrowserActionRecorder {\n const path = `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/browser-events`;\n const id =\n agentId ??\n process.env.GATEWAY_AGENT_ID ??\n `agent-${randomUUID().replace(/-/g, \"\").slice(0, 8)}`;\n return new BrowserActionRecorder(\n async (events: BrowserActionEvent[]) => {\n await apiRequest(this.options, \"POST\", path, { events });\n },\n id,\n {\n // Continue this agent's timeline where the platform has it, so the\n // same id reopened later never re-numbers from zero.\n resumeFrom: async () => {\n const summary = await apiRequest<{\n agents: { agentId: string; nextSeq: number }[];\n }>(this.options, \"GET\", path);\n return summary.agents.find((a) => a.agentId === id)?.nextSeq ?? 0;\n },\n },\n );\n }\n\n /** Browser actions as model tools, in the same shape as `toolkit()`. */\n computerUseTools(browser: WorldBrowser): WorldToolkit {\n return computerUseToolkit(browser);\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.current = {\n instruction: this.current.instruction,\n tools: this.current.tools,\n surfaces: this.current.surfaces,\n task: this.current.task,\n ...fresh,\n };\n return this.current;\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: {\n kind?: \"call\" | \"grade\" | \"reset\" | \"state\" | \"seed\" | \"close\";\n tool?: string;\n args?: unknown;\n /** Grade only: the agent's report, for a rubric judge. */\n report?: string;\n },\n timeoutMs?: number,\n ): Promise<unknown> {\n // Measured the way the route measures it; over the limit nothing is sent.\n serializeCallBody(body);\n const enqueued = await apiRequest<{\n callId: string;\n seq: number;\n /** The platform's worker finalizes this call (a rubric grade). */\n pending?: boolean;\n }>(\n this.options,\n \"POST\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/calls`,\n body,\n );\n const { callId } = enqueued;\n const judged = enqueued.pending === true;\n const budgetMs =\n timeoutMs ?? (judged ? JUDGED_GRADE_TIMEOUT_MS : CALL_TIMEOUT_MS);\n const pollMs = judged ? JUDGED_GRADE_POLL_MS : CALL_POLL_MS;\n const deadline = Date.now() + budgetMs;\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 judged\n ? `Grade ${callId} still ${call.state} after ${Math.round(budgetMs / 1000)}s — the judge has not answered; the platform finalizes the call on its own, read it back with export().`\n : `Call ${callId} still ${call.state} after ${Math.round(budgetMs / 1000)}s — the container may have died.`,\n );\n await sleep(pollMs);\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.current.tools;\n if (!specs) specs = (await this.status()).tools ?? [];\n const impls: WorldToolkit[\"impls\"] = Object.create(null);\n for (const spec of specs) {\n const alias = modelToolName(spec.name);\n if (Object.hasOwn(impls, alias))\n throw new WorldSessionCallError(`Model tool name collision: ${alias}`);\n impls[alias] = (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. Graders answer\n * in one of two shapes: the scalar with named rewards beside it\n * (`{reward, check_a, check_b}`, a task's own `grade.py`), or the named\n * rewards nested under `rewards` (the api, mock-tools and World Host\n * runners). Both land in `rewards`.\n *\n * A rubric grade is finalized by the platform's judge, not the container:\n * the platform answers the enqueue with `pending: true`, and this waits on\n * the judge's budget (15 min) instead of a call's. `timeoutMs` overrides\n * either. `report` is the agent's own account of what it did and found,\n * handed to the judge as its claim beside the evidence (the state and the\n * calls); assertions and python graders ignore it. `worlds` names the\n * task's other sessions by alias (`{alias: sessionId}`): the platform\n * reads each one's evidence and hands it to the cross-world verifiers\n * anchored on this session, whose grades come back under `verifiers`. */\n async grade(\n opts: {\n timeoutMs?: number;\n report?: string;\n worlds?: Record<string, string>;\n } = {},\n ): Promise<GradeResult> {\n const raw = (await this.exchange(\n {\n kind: \"grade\",\n ...(opts.report !== undefined ? { report: opts.report } : {}),\n ...(opts.worlds && Object.keys(opts.worlds).length > 0\n ? { worlds: opts.worlds }\n : {}),\n },\n opts.timeoutMs,\n )) as Record<string, unknown> | null;\n const record = raw && typeof raw === \"object\" ? raw : {};\n const verifiers = verifierGrades(record.verifiers);\n return {\n ...numericGrade(record),\n ...(typeof record.reason === \"string\" ? { reason: record.reason } : {}),\n ...(verifiers ? { verifiers } : {}),\n raw,\n };\n }\n\n /**\n * Put rows into the LIVE world through its contract, in one batch:\n * `append` (default) upserts by primary key, `replace` makes the named\n * entities hold exactly these rows. Atomic — a refused row leaves the\n * session unchanged and the error names the entity, row and field.\n */\n async seed(\n rows: Record<string, Record<string, unknown>[]>,\n opts: {\n mode?: \"append\" | \"replace\";\n /** `apply` runs the world's `[redact]` policy over the rows first;\n * `refuse` rejects plaintext in a redacted field; default `off`. */\n redact?: \"off\" | \"apply\" | \"refuse\";\n timeoutMs?: number;\n } = {},\n ): Promise<SeedResult> {\n const mode = opts.mode ?? \"append\";\n const redact = opts.redact ?? \"off\";\n return (await this.exchange(\n {\n kind: \"seed\",\n args: { mode, rows, ...(redact !== \"off\" ? { redact } : {}) },\n },\n opts.timeoutMs,\n )) as SeedResult;\n }\n\n /** Every entity's rows as the world holds them now — the same dump a\n * grader reads. The shape is the world runtime's: a schema world answers\n * `{<entity>: {<key>: row}, snapshot}`, a mock-tools world\n * `{entities: {<entity>: [row]}}`. */\n async state(opts: { timeoutMs?: number } = {}): Promise<unknown> {\n return this.exchange({ kind: \"state\" }, opts.timeoutMs);\n }\n\n /** Back to the opening state: the version's data plus the bundled\n * scenario's or the inline task's seed. Rows written since are gone; the\n * call log stays. */\n async reset(opts: { timeoutMs?: number } = {}): Promise<void> {\n await this.exchange({ kind: \"reset\" }, opts.timeoutMs);\n }\n\n /** The session's call log, oldest first: every tool call, seed, reset,\n * grade with its result — the record of the episode. */\n async export(): Promise<WorldSessionCall[]> {\n const calls: WorldSessionCall[] = [];\n let cursor: string | undefined;\n do {\n const params = new URLSearchParams({ limit: String(EXPORT_PAGE) });\n if (cursor) params.set(\"cursor\", cursor);\n const page = await apiRequest<{\n calls: Record<string, unknown>[];\n nextCursor?: string | null;\n }>(\n this.options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/calls?${params.toString()}`,\n );\n for (const call of page.calls) {\n calls.push({\n seq: Number(call.seq),\n kind: String(call.kind ?? \"call\"),\n tool: typeof call.tool === \"string\" ? call.tool : null,\n args: call.args ?? null,\n result: call.result ?? null,\n error: typeof call.error === \"string\" ? call.error : null,\n completedAt:\n typeof call.completedAt === \"string\" ? call.completedAt : null,\n });\n }\n cursor = page.nextCursor ?? undefined;\n } while (cursor);\n return calls;\n }\n\n /**\n * Promote this session's inline task into a stored task of the project\n * (version 1, pinned to the session's world unless `world` says otherwise),\n * so a task written for one end user can be reused and its grades\n * compared. The session then records the new task's id. A session on a\n * bundled task has nothing to save; one on a stored task is already saved.\n */\n async saveTask(\n opts: { name?: string; world?: string | null; message?: string } = {},\n ): Promise<WorldTaskSummary> {\n const task = await apiRequest<WorldTaskSummary>(\n this.options,\n \"POST\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/task`,\n {\n ...(opts.name !== undefined ? { name: opts.name } : {}),\n ...(opts.world !== undefined ? { world: opts.world } : {}),\n ...(opts.message !== undefined ? { message: opts.message } : {}),\n },\n );\n this.current = {\n ...this.current,\n taskName: task.name,\n task: {\n ...this.taskInfo,\n source: \"stored\",\n name: task.name,\n id: task.id,\n version: task.version,\n },\n };\n return task;\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\nexport type OpenSessionOptions = {\n versionId?: string;\n reuseWarm?: boolean;\n /** More than `tools`: `[\"api\"]`, `[\"ui\"]`, `[\"browser\"]`. The platform\n * refuses (HTTP 400) rather than quietly serving less than asked. */\n surfaces?: WorldSurfaceKind[];\n /** Capacity for a World Host session's browser: `standard` (spot, may be\n * reclaimed) or `premium` (on-demand). Unset, the organization's default. */\n browserTier?: BrowserTier;\n options?: WorldsClientOptions;\n};\n\nconst OPEN_SESSION_OPTION_KEYS: ReadonlySet<string> = new Set([\n \"task\",\n \"versionId\",\n \"reuseWarm\",\n \"surfaces\",\n \"browserTier\",\n \"options\",\n]);\n\n/** The second argument is an options bag only when every key is one of\n * `OpenSessionOptions` (+ `task`); any other object is the positional task\n * and is validated as one, so a misspelt spec is refused, not opened bare. */\nconst isOpenSessionOptions = (\n value: unknown,\n): value is OpenSessionOptions & { task?: WorldTaskRef } =>\n typeof value === \"object\" &&\n value !== null &&\n Object.keys(value).every((key) => OPEN_SESSION_OPTION_KEYS.has(key));\n\n/**\n * Open a live session on a world. Returns as soon as the platform has\n * accepted it — call `ready()` to wait for the container.\n *\n * `task` is a bundled scenario's name, a stored task's `{ id, version? }`\n * or an inline `WorldTaskSpec` (the latter two need a host engine world — the\n * platform answers 400 for a pod world). Omitted, the session is EXPLORATORY:\n * the platform records an inline `{instruction: \"exploratory session\"}` with\n * no grader as `task.source: \"none\"`, and `grade()` answers\n * `{reward: null, reason: \"no grader\"}`. The older positional form\n * `openSession(slug, \"task-name\", opts)` still works.\n */\nexport async function openSession(\n slugOrRef: string,\n task?: OpenSessionOptions & { task?: WorldTaskRef },\n): Promise<WorldSession>;\nexport async function openSession(\n slugOrRef: string,\n task: WorldTaskRef,\n opts?: OpenSessionOptions,\n): Promise<WorldSession>;\nexport async function openSession(\n slugOrRef: string,\n taskOrOpts:\n WorldTaskRef | (OpenSessionOptions & { task?: WorldTaskRef }) = {},\n positionalOpts: OpenSessionOptions = {},\n): Promise<WorldSession> {\n const { task, ...opts } = isOpenSessionOptions(taskOrOpts)\n ? taskOrOpts\n : { task: taskOrOpts as WorldTaskRef, ...positionalOpts };\n if (task !== undefined) assertTaskRef(task);\n const options = opts.options ?? {};\n const unknown = (opts.surfaces ?? []).filter(\n (s) => !(SURFACE_KINDS as readonly string[]).includes(s),\n );\n if (unknown.length)\n throw new Error(\n `Unknown world surfaces: ${unknown.join(\", \")}; choose from ${SURFACE_KINDS.join(\", \")}`,\n );\n if (opts.browserTier !== undefined) assertBrowserTier(opts.browserTier);\n const at = slugOrRef.indexOf(\"@\");\n const slug = at === -1 ? slugOrRef : slugOrRef.slice(0, at);\n const ref = at === -1 ? \"\" : slugOrRef.slice(at + 1);\n const state = await apiRequest<WorldSessionState & { reusedWarm: boolean }>(\n options,\n \"POST\",\n \"/api/public/world-sessions\",\n {\n ...(opts.versionId\n ? { versionId: opts.versionId }\n : { slug, ...(ref && { ref }) }),\n ...(task === undefined ? {} : { task }),\n ...(opts.reuseWarm === undefined ? {} : { reuseWarm: opts.reuseWarm }),\n ...(opts.surfaces?.length ? { surfaces: opts.surfaces } : {}),\n ...(opts.browserTier === undefined\n ? {}\n : { browserTier: opts.browserTier }),\n },\n );\n return new WorldSession(state.sessionId, state, options);\n}\n\n// ── running many tasks at once ───────────────────────────────────────────────\n\nexport type SessionRunResult = {\n /** The task's name, or `inline:<hash>` for an unnamed inline task. */\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 /** Tasks that never graded: the session did not open or become ready, the\n * agent threw, or grading failed. Any failure fails the run — a 0 an agent\n * earned and a session that never opened are not the same result. */\n failed: number;\n /** True when no task failed and `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 /** Bundled task names, stored task refs and/or inline task specs\n * (default: every bundled task in the world). */\n tasks?: WorldTaskRef[];\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 /** The task's label — see `SessionRunResult.task`. */\n task: string;\n /** The task as it was given: a bundled name, a stored ref or the\n * inline spec. */\n taskRef: WorldTaskRef;\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 — and a\n // caller who pinned a version gets THAT version's task list, not the\n // branch tip's.\n const { openWorld, openWorldVersion } = await import(\"./index\");\n const world = versionId\n ? await openWorldVersion(opts.world.split(\"@\", 1)[0]!, versionId, options)\n : 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 taskRef = tasks![next++];\n let task = taskLabel(taskRef);\n let session: WorldSession | null = null;\n try {\n session = await openSession(opts.world, {\n task: taskRef,\n versionId,\n options,\n });\n task = taskLabel(taskRef, session.taskInfo);\n await session.ready();\n const toolkit = await session.toolkit();\n await opts.agent({\n session,\n toolkit,\n instruction:\n session.instruction ??\n (isTaskSpec(taskRef) ? taskRef.instruction : task),\n task,\n taskRef,\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 const failed = results.filter((r) => r.error).length;\n return {\n results: results.sort((a, b) => a.task.localeCompare(b.task)),\n mean,\n failed,\n passed:\n failed === 0 && (opts.failUnder === undefined || mean >= opts.failUnder),\n };\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\n\n/** Mirrors `WorldSessionListItemSchema` (web/features/public-api/types/world-sessions.ts). */\nexport type WorldSessionListItem = {\n sessionId: string;\n slug: string;\n containerId: string;\n state: string;\n ready: boolean;\n versionId: string;\n contentHash: string;\n taskName: string | null;\n engine: string;\n pinned: boolean;\n surfaces: string[];\n createdAt: string;\n lastUsedAt: string;\n};\n\n/** A World Host session's states (`SessionState` in shared `worldSessions.ts`). */\nexport const SESSION_STATES = [\n \"PROVISIONING\",\n \"RUNNING\",\n \"IDLE\",\n \"STOPPING\",\n \"STOPPED\",\n \"FAILED\",\n \"LOST\",\n] as const;\n\nexport type ListSessionsFilter = {\n /** One of SESSION_STATES. */\n state?: string;\n slug?: string;\n limit?: number;\n};\n\n/** The project's live sessions, newest first — the ones an agent can attach to. */\nexport async function listSessions(\n filter: ListSessionsFilter = {},\n options: WorldsClientOptions = {},\n): Promise<WorldSessionListItem[]> {\n const params = new URLSearchParams();\n if (filter.state) params.set(\"state\", filter.state);\n if (filter.slug) params.set(\"slug\", filter.slug);\n if (filter.limit !== undefined) params.set(\"limit\", String(filter.limit));\n const qs = params.toString();\n const res = await apiRequest<{ sessions: WorldSessionListItem[] }>(\n options,\n \"GET\",\n `/api/public/world-sessions${qs ? `?${qs}` : \"\"}`,\n );\n return res.sessions;\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\nimport type { WorldTaskSpec } from \"./session\";\n\n/**\n * STORED WORLD TASKS: a task spec kept by the project, outside any bundle.\n *\n * An inline task (`openSession(world, { task: { instruction, … } })`) belongs\n * to one session. A stored task is the same spec as a named, versioned\n * project resource: create it once, open as many sessions on it as you like\n * with `{ task: { id } }`, and every grade attributes back to the task and\n * its version. Updating the spec never rewrites history — it appends a\n * version, and a session opened on `{ id, version: 2 }` keeps running v2\n * after v3 exists.\n *\n * const task = await createTask({\n * name: \"refund-late-invoice\",\n * world: \"acme-billing\",\n * spec: { instruction: \"…\", seed: {…}, grader: {…} },\n * });\n * const session = await openSession(\"acme-billing\", { task: { id: task.id } });\n *\n * Tasks are project-scoped: another project's task id is not found (404),\n * never forbidden. `world` pins a task to one world's slug (validated against\n * that world's contract); null leaves it usable with any world.\n */\n\nexport type WorldTaskSummary = {\n id: string;\n name: string;\n world: string | null;\n version: number;\n hash: string;\n spec: WorldTaskSpec;\n /** A multi-world task's aliases in spec order; empty for a single world. */\n aliases: string[];\n /** Listed by world: the aliases that world plays in this task; else empty. */\n aliasesHere: string[];\n /** What grades the task, one row per check or verifier: its reward key,\n * the aliases it judges, what it checks in plain words, its source. */\n verifiers: WorldTaskVerifierRow[];\n createdAt: string;\n updatedAt: string;\n createdBy: string;\n updatedBy: string;\n /** On create, when the task is pinned to a world of a deprecated shape (an\n * api bundle): what to run instead. A retired shape is refused. */\n deprecations?: { code: string; message: string; replacement: string }[];\n};\n\nexport type WorldTaskVersionSummary = {\n version: number;\n hash: string;\n createdAt: string;\n createdBy: string;\n message: string | null;\n};\n\nexport type WorldTaskVerifierRow = {\n key: string;\n aliases: string[];\n kind: \"assertions\" | \"python\" | \"rubric\";\n description: string | null;\n source: string | null;\n sourceLanguage: \"python\" | \"text\" | null;\n};\n\nexport type WorldTaskDetail = WorldTaskSummary & {\n versions: WorldTaskVersionSummary[];\n};\n\nexport type WorldTaskPage = {\n tasks: WorldTaskSummary[];\n meta: {\n page: number;\n limit: number;\n totalItems: number;\n totalPages: number;\n /** Listed by world: the scan for multi-world tasks naming it filled its\n * bound, so `totalItems` is a floor. */\n scanTruncated?: true;\n };\n};\n\nexport type WorldTaskWorldValidation = {\n slug: string;\n ref: string;\n versionId: string;\n ok: boolean;\n checked: \"entities\" | \"none\";\n problems: string[];\n entities: string[] | null;\n};\n\nexport type WorldTaskValidation = {\n taskId: string;\n version: number;\n /** The world version the task was checked against; null for a task with\n * `worlds`, whose versions are per alias under `worlds`. */\n versionId: string | null;\n ok: boolean;\n /** `entities` when the world's contract was read and every seed and check\n * entity was matched against it; `none` when the version has no contract\n * to check (a mock-tools world), in which case `ok` says only that the\n * version exists and is READY; `worlds` for a multi-world task, checked\n * alias by alias against the ref each names. */\n checked: \"entities\" | \"none\" | \"worlds\";\n /** For a multi-world task each problem is prefixed with its alias. */\n problems: string[];\n entities: string[] | null;\n worlds?: Record<string, WorldTaskWorldValidation>;\n};\n\nconst TASKS = \"/api/public/world-tasks\";\nconst taskRoute = (id: string) => `${TASKS}/${encodeURIComponent(id)}`;\n\nconst compact = (body: Record<string, unknown>) =>\n Object.fromEntries(Object.entries(body).filter(([, v]) => v !== undefined));\n\n/** Store a task. `name` defaults to `spec.name`; one of the two is needed. */\nexport async function createTask(\n input: {\n spec: WorldTaskSpec;\n name?: string;\n world?: string | null;\n message?: string;\n },\n options: WorldsClientOptions = {},\n): Promise<WorldTaskSummary> {\n return apiRequest<WorldTaskSummary>(\n options,\n \"POST\",\n TASKS,\n compact({\n spec: input.spec,\n name: input.name,\n world: input.world,\n message: input.message,\n }),\n );\n}\n\n/** Change a task. A new `spec` becomes the next version (the old ones stay\n * readable and openable); `name` and `world` change in place. */\nexport async function updateTask(\n taskId: string,\n input: {\n spec?: WorldTaskSpec;\n name?: string;\n world?: string | null;\n message?: string;\n },\n options: WorldsClientOptions = {},\n): Promise<WorldTaskSummary> {\n if (\n input.spec === undefined &&\n input.name === undefined &&\n input.world === undefined\n )\n throw new Error(\"updateTask: nothing to update — pass spec, name or world\");\n return apiRequest<WorldTaskSummary>(\n options,\n \"PATCH\",\n taskRoute(taskId),\n compact({\n spec: input.spec,\n name: input.name,\n world: input.world,\n message: input.message,\n }),\n );\n}\n\n/** The project's tasks, newest change first. `world` keeps only tasks\n * that run against that slug (pinned to it, or naming it under an alias); `metadata` keeps tasks whose spec metadata carries\n * every given key/value (`{ externalUserId: \"u_42\" }`). */\nexport async function listTasks(\n filter: {\n world?: string;\n metadata?: Record<string, string>;\n page?: number;\n limit?: number;\n } = {},\n options: WorldsClientOptions = {},\n): Promise<WorldTaskPage> {\n const params = new URLSearchParams();\n if (filter.world) params.set(\"world\", filter.world);\n if (filter.page !== undefined) params.set(\"page\", String(filter.page));\n if (filter.limit !== undefined) params.set(\"limit\", String(filter.limit));\n for (const [key, value] of Object.entries(filter.metadata ?? {}))\n params.set(`metadata.${key}`, value);\n const query = params.toString();\n return apiRequest<WorldTaskPage>(\n options,\n \"GET\",\n query ? `${TASKS}?${query}` : TASKS,\n );\n}\n\n/** One task with its version history; `version` reads that version's spec\n * instead of the current one. */\nexport async function getTask(\n taskId: string,\n opts: { version?: number } = {},\n options: WorldsClientOptions = {},\n): Promise<WorldTaskDetail> {\n const query =\n opts.version === undefined ? \"\" : `?version=${String(opts.version)}`;\n return apiRequest<WorldTaskDetail>(\n options,\n \"GET\",\n `${taskRoute(taskId)}${query}`,\n );\n}\n\n/** Remove a task and every version. Sessions already opened on it keep\n * their copy of the spec. */\nexport async function deleteTask(\n taskId: string,\n options: WorldsClientOptions = {},\n): Promise<{ id: string; name: string }> {\n return apiRequest(options, \"DELETE\", taskRoute(taskId));\n}\n\n/** Check a task against a world version without opening a session: every\n * seed entity and every check's entity must exist in the world's contract.\n * `slug` checks against that world's head, `versionId` against an exact\n * version, neither against the task's own `world` pin. */\nexport async function validateTask(\n taskId: string,\n target: { version?: number; slug?: string; versionId?: string } = {},\n options: WorldsClientOptions = {},\n): Promise<WorldTaskValidation> {\n return apiRequest<WorldTaskValidation>(\n options,\n \"POST\",\n `${taskRoute(taskId)}/validate`,\n compact({\n version: target.version,\n slug: target.slug,\n versionId: target.versionId,\n }),\n );\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\nimport {\n assertBrowserTier,\n surfaceKinds,\n uiEntryUrl,\n type BrowserTier,\n type SessionSurfaces,\n type WorldSurfaceKind,\n} from \"./browser\";\nimport {\n WorldSession,\n attachSession,\n isTaskIdRef,\n type GradeResult,\n type VerifierGrade,\n type WorldSessionCall,\n type WorldSessionState,\n type WorldTaskIdRef,\n type WorldTaskSpec,\n} from \"./session\";\n\n/**\n * TASKS THAT NEED SEVERAL WORLDS.\n *\n * A task whose spec names `worlds` is one instruction over N hosted worlds\n * — an investigation that reads a breach feed, a threat-intel API and a\n * ticketing system, say. `openTask` brings every one of them up in ONE call\n * and hands back the sessions keyed by the aliases the spec chose:\n *\n * const task = await openTask({ id: \"wt_1\" }, { surfaces: [\"api\"] });\n * await task.ready();\n * const spycloud = task.sessions.spycloud; // a WorldSession\n * await myAgent(task.instruction, task.sessions);\n * const grade = await task.grade(); // per world + aggregate\n * await task.close();\n *\n * The platform opens the sessions (POST /world-task-sessions) and refuses\n * a partial bring-up: if one world fails, the ones that opened are closed\n * and the error names every alias that failed. Everything after — ready,\n * grade, export, close — is one `WorldSession` call per world, fanned out\n * here. `manifest()` is the record `gateway worlds task up` prints, and\n * `attachTask` rebuilds a `TaskSessions` from a stored task's live sessions.\n */\n\nconst TASK_SESSIONS = \"/api/public/world-task-sessions\";\n\n/** The per-world entry of a `WorldTaskSpec.worlds` table. */\nexport type WorldTaskWorld = {\n slug: string;\n ref?: string;\n seed?: WorldTaskSpec[\"seed\"];\n grader?: WorldTaskSpec[\"grader\"];\n tools?: string[];\n};\n\n/** One world's session as the platform answered it at up. */\nexport type TaskWorldSessionState = WorldSessionState & {\n alias: string;\n slug: string;\n ref: string;\n reusedWarm: boolean;\n};\n\n/** What `POST /world-task-sessions` answers. */\nexport type TaskSessionsResponse = {\n taskId: string | null;\n taskVersion: number | null;\n name: string | null;\n hash: string;\n instruction: string;\n sessions: Record<string, TaskWorldSessionState>;\n};\n\n/** One world in the manifest: where it answers, in the shape\n * `gateway worlds session open` prints for a single session. */\nexport type TaskManifestSession = {\n slug: string;\n ref: string | null;\n versionId: string;\n sessionId: string;\n ready: boolean;\n state: string;\n surfaces: WorldSurfaceKind[];\n api?: { url: string; token?: string };\n ui?: { url: string; entry: string; apiPath: string | null };\n browser?: { wsUrl: string; viewport?: unknown };\n};\n\n/** The manifest: every session of the task, keyed by alias. The file\n * `task up --out` writes and `task down|status|grade|export` read. */\nexport type TaskManifest = {\n taskId: string | null;\n taskVersion: number | null;\n name: string | null;\n instruction: string | null;\n sessions: Record<string, TaskManifestSession>;\n};\n\n/** A stored task's live sessions, as `GET /world-task-sessions` lists them. */\nexport type LiveTaskSession = {\n alias: string | null;\n slug: string | null;\n sessionId: string;\n state: string;\n ready: boolean;\n versionId: string;\n taskVersion: number | null;\n createdAt: string;\n};\n\n/** The task's grade: every world's own `GradeResult` under its alias, the\n * task's cross-world verifiers by name (lifted from the world each is\n * anchored on), and the aggregate. `reward` is the mean of the worlds' and\n * verifiers' numeric rewards — null when none answered one (no grader\n * anywhere, or a judge still pending); a world or verifier with no reward\n * is listed under `ungraded` (a verifier as `x.<name>`), never counted as\n * 0. `rewards` flattens each world's named rewards as `<alias>.<key>`\n * beside `<alias>` for the world's own reward, and a verifier's as\n * `x.<name>` / `x.<name>.<key>`. */\nexport type TaskGrade = {\n reward: number | null;\n rewards: Record<string, number>;\n worlds: Record<string, GradeResult>;\n ungraded: string[];\n verifiers: Record<string, VerifierGrade>;\n};\n\n/** A cross-world verifier's rewards flatten under `x.<name>`; no alias\n * starts with `x.`. */\nexport const VERIFIER_REWARD_PREFIX = \"x.\";\n\n/** Every world's call log, keyed by alias. */\nexport type TaskExport = Record<string, WorldSessionCall[]>;\n\nconst manifestSession = (\n s: SessionSurfaces,\n state: {\n sessionId: string;\n ready: boolean;\n state: string;\n versionId: string;\n },\n world: { slug: string; ref: string | null },\n): TaskManifestSession => ({\n slug: world.slug,\n ref: world.ref,\n versionId: state.versionId,\n sessionId: state.sessionId,\n ready: state.ready,\n state: state.state,\n surfaces: surfaceKinds(s),\n ...(s.api\n ? {\n api: { url: s.api.url, ...(s.api.token ? { token: s.api.token } : {}) },\n }\n : {}),\n ...(s.ui\n ? {\n ui: {\n url: s.ui.url,\n entry: uiEntryUrl(s.ui),\n apiPath: s.ui.apiPath ?? null,\n },\n }\n : {}),\n ...(s.browser\n ? { browser: { wsUrl: s.browser.wsUrl, viewport: s.browser.viewport } }\n : {}),\n});\n\n/** Combine per-world grades into the task's. Pure, so the CLI and the tests\n * share it with `TaskSessions.grade()`. */\nexport function aggregateTaskGrade(\n worlds: Record<string, GradeResult>,\n): TaskGrade {\n const rewards: Record<string, number> = {};\n const ungraded: string[] = [];\n const graded: number[] = [];\n const verifiers: Record<string, VerifierGrade> = {};\n const fold = (key: string, grade: VerifierGrade) => {\n if (typeof grade.reward === \"number\") {\n rewards[key] = grade.reward;\n graded.push(grade.reward);\n } else ungraded.push(key);\n for (const [name, value] of Object.entries(grade.rewards))\n rewards[`${key}.${name}`] = value;\n };\n for (const [alias, grade] of Object.entries(worlds)) {\n fold(alias, grade);\n Object.assign(verifiers, grade.verifiers ?? {});\n }\n for (const [name, grade] of Object.entries(verifiers))\n fold(`${VERIFIER_REWARD_PREFIX}${name}`, grade);\n const reward =\n graded.length > 0\n ? graded.reduce((a, b) => a + b, 0) / graded.length\n : null;\n return { reward, rewards, worlds, ungraded, verifiers };\n}\n\nexport class TaskSessions {\n constructor(\n /** The stored task's id, or null for a task given as a spec. */\n readonly taskId: string | null,\n readonly taskVersion: number | null,\n readonly name: string | null,\n /** The instruction every world's session shares. */\n readonly instruction: string | null,\n /** One live session per alias, in the spec's order. */\n readonly sessions: Record<string, WorldSession>,\n private readonly worlds: Record<\n string,\n { slug: string; ref: string | null }\n >,\n /** The spec's content hash — set only by `openTask` (the raw platform\n * response carries it); null for a `TaskSessions` rebuilt with\n * `attachManifest`/`attachTask`, which have no spec to hash. */\n readonly hash: string | null = null,\n ) {}\n\n /** This alias's `{slug, ref}` as recorded at open/attach — the world a\n * `TaskRun` filing needs to name, without exposing the whole map. */\n worldRef(alias: string): { slug: string; ref: string | null } {\n return this.worlds[alias] ?? { slug: \"\", ref: null };\n }\n\n /** The aliases, in the spec's order. */\n get aliases(): string[] {\n return Object.keys(this.sessions);\n }\n\n /** The alias's session, or a clear error naming the aliases there are. */\n session(alias: string): WorldSession {\n const session = this.sessions[alias];\n if (!session)\n throw new Error(\n `task has no world '${alias}'; its worlds are ${this.aliases.join(\", \")}`,\n );\n return session;\n }\n\n private async each<T>(\n fn: (session: WorldSession, alias: string) => Promise<T>,\n ): Promise<Record<string, T>> {\n const entries = await Promise.all(\n Object.entries(this.sessions).map(\n async ([alias, session]) => [alias, await fn(session, alias)] as const,\n ),\n );\n return Object.fromEntries(entries);\n }\n\n /** Wait until every world answers ready. A world that never does throws\n * `WorldSessionTimeout` naming it; the others are left up. */\n async ready(opts: { timeoutMs?: number } = {}): Promise<void> {\n await this.each((session) => session.ready(opts));\n }\n\n /** Every world's current state, keyed by alias. */\n async status(): Promise<Record<string, WorldSessionState>> {\n return this.each((session) => session.status());\n }\n\n /** The manifest: where every world answers, keyed by alias. */\n async manifest(): Promise<TaskManifest> {\n const sessions = await this.each(async (session, alias) =>\n manifestSession(\n await session.surfaces(),\n {\n sessionId: session.sessionId,\n ready: session.isReady,\n state: (await session.status()).state,\n versionId: session.versionId,\n },\n this.worlds[alias]!,\n ),\n );\n return {\n taskId: this.taskId,\n taskVersion: this.taskVersion,\n name: this.name,\n instruction: this.instruction,\n sessions,\n };\n }\n\n /** Grade every world and aggregate — see `TaskGrade`. One `report` (the\n * agent's own account of the whole investigation) goes to every world's\n * judge; a world graded by assertions or python ignores it. Each grade\n * names the task's other sessions by alias, so the cross-world verifiers\n * anchored on that world can read them. */\n async grade(\n opts: { timeoutMs?: number; report?: string } = {},\n ): Promise<TaskGrade> {\n return aggregateTaskGrade(\n await this.each((session, alias) =>\n session.grade({ ...opts, worlds: this.otherSessions(alias) }),\n ),\n );\n }\n\n /** The task's other sessions by alias: what a grade names. */\n private otherSessions(alias: string): Record<string, string> {\n return Object.fromEntries(\n Object.entries(this.sessions)\n .filter(([other]) => other !== alias)\n .map(([other, session]) => [other, session.sessionId]),\n );\n }\n\n /** Every world's call log, keyed by alias. */\n async export(): Promise<TaskExport> {\n return this.each((session) => session.export());\n }\n\n /** Close every world. Closes are attempted for all of them even when one\n * fails; the error then names every world that did not close. */\n async close(\n opts: { keepWarm?: boolean } = {},\n ): Promise<Record<string, { state: string }>> {\n const settled = await Promise.allSettled(\n Object.entries(this.sessions).map(\n async ([alias, session]) => [alias, await session.close(opts)] as const,\n ),\n );\n const failed: string[] = [];\n const closed: Record<string, { state: string }> = {};\n settled.forEach((result, i) => {\n const alias = this.aliases[i]!;\n if (result.status === \"fulfilled\") closed[alias] = result.value[1];\n else\n failed.push(\n `${alias}: ${result.reason instanceof Error ? result.reason.message : String(result.reason)}`,\n );\n });\n if (failed.length > 0)\n throw new Error(\n `${failed.length} of ${this.aliases.length} worlds did not close — ${failed.join(\"; \")}`,\n );\n return closed;\n }\n}\n\nexport type OpenTaskOptions = {\n /** With a task id: open that version of the task instead of the current. */\n version?: number;\n /** Asked of every world; the platform refuses (400) rather than serving\n * fewer surfaces than asked, and then nothing is up. */\n surfaces?: WorldSurfaceKind[];\n reuseWarm?: boolean;\n /** Browser capacity for every world the task opens: `standard` (spot, may\n * be reclaimed) or `premium` (on-demand). Unset, the organization's default. */\n browserTier?: BrowserTier;\n options?: WorldsClientOptions;\n};\n\nfunction fromResponse(\n answer: TaskSessionsResponse,\n options: WorldsClientOptions,\n): TaskSessions {\n const sessions: Record<string, WorldSession> = {};\n const worlds: Record<string, { slug: string; ref: string | null }> = {};\n for (const [alias, state] of Object.entries(answer.sessions)) {\n sessions[alias] = new WorldSession(state.sessionId, state, options);\n worlds[alias] = { slug: state.slug, ref: state.ref };\n }\n return new TaskSessions(\n answer.taskId,\n answer.taskVersion,\n answer.name,\n answer.instruction,\n sessions,\n worlds,\n answer.hash ?? null,\n );\n}\n\n/**\n * Bring every world of a task up. `ref` is a stored task's id, its\n * `{ id, version? }`, or the spec itself (one with `worlds`). Returns as\n * soon as the platform has opened every session — `ready()` waits for the\n * containers. All or nothing: a world that fails to open closes the rest\n * and the error names it.\n */\nexport async function openTask(\n ref: string | WorldTaskIdRef | WorldTaskSpec,\n opts: OpenTaskOptions = {},\n): Promise<TaskSessions> {\n const options = opts.options ?? {};\n const task: WorldTaskIdRef | WorldTaskSpec =\n typeof ref === \"string\"\n ? {\n id: ref,\n ...(opts.version !== undefined ? { version: opts.version } : {}),\n }\n : isTaskIdRef(ref) && opts.version !== undefined\n ? { ...ref, version: opts.version }\n : ref;\n if (isTaskIdRef(task) ? !task.id : !task.instruction)\n throw new Error(\n \"openTask needs a task: a stored task id, { id, version? } or a spec with worlds\",\n );\n if (!isTaskIdRef(task) && !task.worlds)\n throw new Error(\n \"openTask needs a spec that names its worlds; a single-world spec opens with openSession\",\n );\n if (opts.browserTier !== undefined) assertBrowserTier(opts.browserTier);\n const answer = await apiRequest<TaskSessionsResponse>(\n options,\n \"POST\",\n TASK_SESSIONS,\n {\n task,\n ...(opts.reuseWarm === undefined ? {} : { reuseWarm: opts.reuseWarm }),\n ...(opts.surfaces?.length ? { surfaces: opts.surfaces } : {}),\n ...(opts.browserTier === undefined\n ? {}\n : { browserTier: opts.browserTier }),\n },\n );\n return fromResponse(answer, options);\n}\n\n/** A stored task's live sessions, newest first — every session the project\n * has opened on it that is not stopped or failed. */\nexport async function listTaskSessions(\n taskId: string,\n options: WorldsClientOptions = {},\n): Promise<LiveTaskSession[]> {\n const answer = await apiRequest<{\n taskId: string;\n sessions: LiveTaskSession[];\n }>(options, \"GET\", `${TASK_SESSIONS}?taskId=${encodeURIComponent(taskId)}`);\n return answer.sessions;\n}\n\n/**\n * Attach to the sessions a stored task has up — after a crash, or from a\n * process other than the one that ran `up`. Refuses when an alias is live\n * more than once (two `up`s of the same task): which set is meant is not\n * knowable, so pass the manifest (`attachManifest`) or close the extras.\n */\nexport async function attachTask(\n taskId: string,\n options: WorldsClientOptions = {},\n): Promise<TaskSessions> {\n const live = await listTaskSessions(taskId, options);\n if (live.length === 0)\n throw new Error(\n `task ${taskId} has no live sessions; run \\`task up\\` first`,\n );\n const byAlias = new Map<string, LiveTaskSession[]>();\n for (const session of live) {\n const alias = session.alias ?? session.sessionId;\n byAlias.set(alias, [...(byAlias.get(alias) ?? []), session]);\n }\n const doubled = [...byAlias.entries()].filter(([, rows]) => rows.length > 1);\n if (doubled.length > 0)\n throw new Error(\n `task ${taskId} has more than one live session for ${doubled\n .map(\n ([alias, rows]) =>\n `'${alias}' (${rows.map((r) => r.sessionId).join(\", \")})`,\n )\n .join(\", \")}; pass the manifest from \\`task up\\`, or close the extras`,\n );\n return attachManifest(\n {\n taskId,\n taskVersion: live[0]!.taskVersion,\n name: null,\n instruction: null,\n sessions: Object.fromEntries(\n [...byAlias.entries()].map(([alias, [row]]) => [\n alias,\n {\n slug: row!.slug ?? \"\",\n ref: null,\n versionId: row!.versionId,\n sessionId: row!.sessionId,\n ready: row!.ready,\n state: row!.state,\n surfaces: [\"tools\"] as WorldSurfaceKind[],\n },\n ]),\n ),\n },\n options,\n );\n}\n\n/** Attach to the sessions a manifest names — the file `task up --out`\n * wrote. Each session is read back from the platform, so a closed one is a\n * clear error rather than a stale handle. */\nexport async function attachManifest(\n manifest: TaskManifest,\n options: WorldsClientOptions = {},\n): Promise<TaskSessions> {\n const entries = await Promise.all(\n Object.entries(manifest.sessions).map(\n async ([alias, entry]) =>\n [alias, await attachSession(entry.sessionId, options)] as const,\n ),\n );\n const sessions = Object.fromEntries(entries);\n const instruction =\n manifest.instruction ?? entries[0]?.[1].instruction ?? null;\n return new TaskSessions(\n manifest.taskId,\n manifest.taskVersion,\n manifest.name,\n instruction,\n sessions,\n Object.fromEntries(\n Object.entries(manifest.sessions).map(([alias, entry]) => [\n alias,\n { slug: entry.slug, ref: entry.ref },\n ]),\n ),\n );\n}\n\n/** Whether a parsed JSON value is a task manifest (what `task up` wrote)\n * rather than a task spec. */\nexport function isTaskManifest(value: unknown): value is TaskManifest {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n typeof (value as { sessions?: unknown }).sessions === \"object\" &&\n (value as { sessions?: unknown }).sessions !== null &&\n !(\"instruction\" in value && \"worlds\" in value)\n );\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\n\n/** TS twin of the Python SDK's GatewayEvalsClient (gatewaysdk/benchmark_hub/evals.py). */\n\nconst EVALUATIONS = \"/api/public/benchmark-containers/evaluations\";\n\nexport type EvalSample = {\n exampleId: string;\n task?: string;\n rolloutIndex?: number;\n prompt?: unknown;\n completion?: unknown;\n reward?: number;\n score?: number;\n correct?: boolean;\n rewards?: Record<string, number>;\n info?: Record<string, unknown>;\n};\n\nexport type CreateEvaluationOptions = {\n model?: string;\n /** A set run to file under; the platform refuses a run that does not admit this result. */\n runId?: string;\n rolloutsPerExample?: number;\n metadata?: Record<string, unknown>;\n};\n\nexport type FinalizeEvaluationOptions = {\n status?: \"COMPLETED\" | \"FAILED\";\n metrics?: Record<string, unknown>;\n};\n\nexport class GatewayEvalsClient {\n constructor(private readonly options: WorldsClientOptions = {}) {}\n\n async createEvaluation(\n versionId: string,\n opts: CreateEvaluationOptions = {},\n ): Promise<string> {\n const body: Record<string, unknown> = { versionId };\n if (opts.model !== undefined) body.model = opts.model;\n if (opts.runId !== undefined) body.runId = opts.runId;\n if (opts.rolloutsPerExample !== undefined)\n body.rolloutsPerExample = opts.rolloutsPerExample;\n if (opts.metadata !== undefined) body.metadata = opts.metadata;\n const answer = await apiRequest<{ evaluationId: string }>(\n this.options,\n \"POST\",\n EVALUATIONS,\n body,\n );\n return answer.evaluationId;\n }\n\n async pushSamples(\n evaluationId: string,\n samples: EvalSample[],\n ): Promise<number> {\n const answer = await apiRequest<{ inserted?: number }>(\n this.options,\n \"POST\",\n `${EVALUATIONS}/${encodeURIComponent(evaluationId)}/samples`,\n { samples },\n );\n return answer.inserted ?? samples.length;\n }\n\n async finalizeEvaluation(\n evaluationId: string,\n opts: FinalizeEvaluationOptions = {},\n ): Promise<string> {\n const body: Record<string, unknown> = {\n status: opts.status ?? \"COMPLETED\",\n };\n if (opts.metrics !== undefined) body.metrics = opts.metrics;\n const answer = await apiRequest<{ status: string }>(\n this.options,\n \"POST\",\n `${EVALUATIONS}/${encodeURIComponent(evaluationId)}/finalize`,\n body,\n );\n return answer.status;\n }\n}\n","import { randomBytes } from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport type { BrowserTier, WorldSurfaceKind } from \"./browser\";\nimport { WorldSurfaceUnavailable } from \"./browser\";\nimport { GatewayEvalsClient, type EvalSample } from \"./evals\";\nimport type { WorldsClientOptions } from \"./index\";\nimport {\n modelToolName,\n schemaFromSignature,\n WorldSession,\n type WorldTaskIdRef,\n type WorldTaskSpec,\n type WorldToolkit,\n type WorldToolSpec,\n} from \"./session\";\nimport {\n openTask,\n TaskSessions,\n type TaskGrade,\n type TaskManifest,\n} from \"./taskSessions\";\n\nexport class TaskRun {\n readonly notes: Record<string, unknown> = {};\n\n constructor(\n readonly runId: string,\n readonly instruction: string,\n readonly model: string,\n readonly sessions: Record<string, WorldSession>,\n readonly manifest: TaskManifest,\n ) {}\n\n session(alias: string): WorldSession {\n const session = this.sessions[alias];\n if (!session)\n throw new Error(\n `task run has no world '${alias}'; its worlds are ${Object.keys(this.sessions).join(\", \")}`,\n );\n return session;\n }\n\n /** Raises when the session was not opened with `surfaces: [\"api\"]`. */\n async api(alias: string): Promise<{ url: string; token?: string }> {\n const surfaces = await this.session(alias).surfaces();\n if (!surfaces.api)\n throw new WorldSurfaceUnavailable(\n \"api\",\n `open '${alias}' with surfaces: ['api']`,\n );\n return { url: surfaces.api.url, token: surfaces.api.token };\n }\n\n /** Each tool is prefixed `<alias>.<tool>` so a model can tell which world a call goes to. */\n async toolkit(): Promise<WorldToolkit> {\n const schemas: WorldToolkit[\"schemas\"] = [];\n const impls: WorldToolkit[\"impls\"] = {};\n const specs: WorldToolSpec[] = [];\n for (const [alias, session] of Object.entries(this.sessions)) {\n const kit = await session.toolkit();\n if (!kit.specs.length) continue;\n for (const spec of kit.specs) {\n const name = `${alias}.${spec.name}`;\n const prefixed: WorldToolSpec = {\n name,\n signature: spec.signature,\n doc: spec.doc,\n inputSchema: spec.inputSchema,\n };\n specs.push(prefixed);\n const schema = schemaFromSignature(prefixed);\n schema.function.name = name;\n schemas.push(schema);\n impls[name] = kit.impls[modelToolName(spec.name)]!;\n }\n }\n return { schemas, impls, specs };\n }\n\n /** Merged into `run.json` under `notes`; a later call overrides an earlier key. */\n record(notes: Record<string, unknown>): void {\n Object.assign(this.notes, notes);\n }\n}\n\nfunction worldRef(\n live: TaskSessions,\n alias: string,\n): { slug: string; ref: string | null; versionId: string; sessionId: string } {\n const { slug, ref } = live.worldRef(alias);\n const session = live.sessions[alias]!;\n return {\n slug,\n ref,\n versionId: session.versionId,\n sessionId: session.sessionId,\n };\n}\n\nasync function fileTaskRun(\n live: TaskSessions,\n runId: string,\n model: string,\n report: string | null,\n grade: TaskGrade,\n agentError: string | null,\n traced: boolean,\n runDir: string,\n options: WorldsClientOptions,\n setRunId: string | undefined,\n): Promise<string> {\n const aliases = live.aliases;\n const anchor = aliases[0]!;\n const worldsMeta = Object.fromEntries(\n aliases.map((alias) => [alias, worldRef(live, alias)]),\n );\n\n const evals = new GatewayEvalsClient(options);\n const evaluationId = await evals.createEvaluation(\n worldRef(live, anchor).versionId,\n {\n model,\n rolloutsPerExample: 1,\n ...(setRunId ? { runId: setRunId } : {}),\n metadata: {\n source: \"worlds-task-run\",\n task: {\n id: live.taskId,\n version: live.taskVersion,\n name: live.name,\n hash: live.hash,\n },\n anchor,\n worlds: worldsMeta,\n runId,\n },\n },\n );\n\n const reward = grade.reward;\n const sample: Record<string, unknown> = {\n exampleId: live.name ?? live.taskId ?? runId,\n task: live.name ?? live.taskId ?? runId,\n rolloutIndex: 0,\n prompt: live.instruction,\n ...(report === null ? {} : { completion: report }),\n rewards: grade.rewards,\n info: {\n sessionId: runId,\n worlds: Object.fromEntries(\n aliases.map((alias) => [\n alias,\n {\n ...worldRef(live, alias),\n reward: grade.worlds[alias]?.reward ?? null,\n },\n ]),\n ),\n ungraded: grade.ungraded,\n traced,\n runDir,\n ...(agentError ? { agentError } : {}),\n },\n };\n if (typeof reward === \"number\") {\n sample.reward = reward;\n sample.score = reward;\n sample.correct = reward >= 1.0;\n }\n await evals.pushSamples(evaluationId, [sample as unknown as EvalSample]);\n await evals.finalizeEvaluation(evaluationId, {\n status: agentError ? \"FAILED\" : \"COMPLETED\",\n metrics: {\n ...(typeof reward === \"number\" ? { avg_reward: reward } : {}),\n reward,\n ...Object.fromEntries(\n Object.entries(grade.rewards).map(([k, v]) => [`rewards.${k}`, v]),\n ),\n },\n });\n return evaluationId;\n}\n\nexport type RunTaskOptions = {\n model: string;\n surfaces?: WorldSurfaceKind[];\n /** Directory the run's own `<runId>/` folder is created under. Default `\"runs\"`. */\n outDir?: string;\n /** Initialize tracing when GATEWAY_* credentials are configured. Default `true`. */\n trace?: boolean;\n /** File one rollout when the run ends. Default `true`. */\n file?: boolean;\n /** Leave every session up instead of closing it when the run ends. Default `false`. */\n keepUp?: boolean;\n reuseWarm?: boolean;\n browserTier?: BrowserTier;\n /** File the rollout under this set run (`runSet` sets it). */\n setRunId?: string;\n options?: WorldsClientOptions;\n};\n\nexport type RunTaskSummary = {\n runId: string;\n taskId: string | null;\n taskVersion: number | null;\n name: string | null;\n instruction: string;\n model: string;\n aliases: string[];\n reward: number | null;\n rewards: Record<string, number>;\n ungraded: string[];\n agentError: string | null;\n report: string | null;\n traced: boolean;\n runDir: string;\n durationSeconds: number;\n notes: Record<string, unknown>;\n filed: boolean;\n evaluationId?: string;\n [extra: string]: unknown;\n};\n\nexport type TaskRunResult =\n string | { report?: unknown; [key: string]: unknown } | null | undefined;\n\nconst describeValue = (value: unknown): string =>\n Array.isArray(value) ? \"array\" : value === null ? \"null\" : typeof value;\n\nconst RESULT_CONTRACT =\n \"return a string report, an object {report?: string, ...} or nothing\";\n\nfunction reportFromResult(result: TaskRunResult): {\n report: string | null;\n extra: Record<string, unknown>;\n} {\n if (result === undefined || result === null)\n return { report: null, extra: {} };\n if (typeof result === \"string\") return { report: result, extra: {} };\n if (typeof result !== \"object\" || Array.isArray(result))\n throw new Error(\n `agent returned ${describeValue(result)}; ${RESULT_CONTRACT}`,\n );\n const { report, ...extra } = result as Record<string, unknown>;\n if (report === undefined || report === null) return { report: null, extra };\n if (typeof report !== \"string\")\n throw new Error(\n `agent returned a report of type ${describeValue(report)}; ${RESULT_CONTRACT}`,\n );\n return { report, extra };\n}\n\n/** Mirrors `gatewaysdk.world_tasks.run_task`. Sessions close unless `keepUp: true`, even when the agent throws, so grading and filing\n * still happen with the error recorded. */\nexport async function runTask(\n ref: string | WorldTaskIdRef | WorldTaskSpec,\n agent: (run: TaskRun) => TaskRunResult | Promise<TaskRunResult>,\n opts: RunTaskOptions,\n): Promise<RunTaskSummary> {\n const runId = `wtr-${randomBytes(6).toString(\"hex\")}`;\n const outDir = opts.outDir ?? \"runs\";\n const runDir = path.join(outDir, runId);\n fs.mkdirSync(runDir, { recursive: true });\n const options = opts.options ?? {};\n\n const live = await openTask(ref, {\n surfaces: opts.surfaces,\n reuseWarm: opts.reuseWarm,\n browserTier: opts.browserTier,\n options,\n });\n const started = Date.now();\n try {\n await live.ready();\n\n let traced = false;\n if (opts.trace !== false) {\n try {\n const { isGatewayConfigured, init } = await import(\"../tracing/init\");\n if (isGatewayConfigured()) {\n init();\n traced = true;\n }\n } catch {\n traced = false;\n }\n }\n\n const taskRun = new TaskRun(\n runId,\n live.instruction ?? \"\",\n opts.model,\n live.sessions,\n await live.manifest(),\n );\n\n let agentError: string | null = null;\n let report: string | null = null;\n let extra: Record<string, unknown> = {};\n try {\n const invoke = () => agent(taskRun);\n const result = traced\n ? await (await import(\"../tracing/session\")).withSession(runId, invoke)\n : await invoke();\n ({ report, extra } = reportFromResult(result));\n } catch (error) {\n const message =\n (error instanceof Error ? error.message : String(error)) ||\n \"Unknown error\";\n agentError = message.slice(0, 2000);\n }\n if (traced)\n await import(\"../tracing/init\")\n .then((tracing) => tracing.flush())\n .catch(() => undefined);\n\n const grade =\n report !== null ? await live.grade({ report }) : await live.grade();\n\n fs.writeFileSync(\n path.join(runDir, \"manifest.json\"),\n JSON.stringify(taskRun.manifest, null, 2),\n );\n fs.writeFileSync(\n path.join(runDir, \"grades.json\"),\n JSON.stringify(grade, null, 2),\n );\n if (report) fs.writeFileSync(path.join(runDir, \"report.md\"), report);\n\n const summary: RunTaskSummary = {\n runId,\n taskId: live.taskId,\n taskVersion: live.taskVersion,\n name: live.name,\n instruction: taskRun.instruction,\n model: opts.model,\n aliases: live.aliases,\n reward: grade.reward,\n rewards: grade.rewards,\n ungraded: grade.ungraded,\n agentError,\n report,\n traced,\n runDir,\n durationSeconds: Math.round((Date.now() - started) / 10) / 100,\n notes: taskRun.notes,\n filed: false,\n ...extra,\n };\n\n if (opts.file !== false) {\n summary.evaluationId = await fileTaskRun(\n live,\n runId,\n opts.model,\n report,\n grade,\n agentError,\n traced,\n runDir,\n options,\n opts.setRunId,\n );\n summary.filed = true;\n }\n\n fs.writeFileSync(\n path.join(runDir, \"run.json\"),\n JSON.stringify(summary, null, 2),\n );\n return summary;\n } finally {\n if (!opts.keepUp) {\n try {\n await live.close({ keepWarm: false });\n } catch {\n // Best-effort: a session that would not close is `task down`'s to report.\n }\n }\n }\n}\n","import { execFileSync } from \"node:child_process\";\n\nexport type Checkout = {\n branch?: string;\n commit?: string;\n repoUrl?: string;\n pr?: { number: number; url: string; title?: string };\n};\n\ntype Env = Record<string, string | undefined>;\n\n/** Labels for the reader, never used to authorize. The PR comes from `GATEWAY_PR_URL`\n * (+ `GATEWAY_PR_TITLE`), else GitHub Actions' `GITHUB_REF=refs/pull/<n>/merge`. */\nexport class CheckoutProvenance {\n constructor(\n private readonly cwd: string,\n private readonly env: Env,\n ) {}\n\n static read(cwd: string = process.cwd(), env: Env = process.env): Checkout {\n return new CheckoutProvenance(cwd, env).checkout();\n }\n\n checkout(): Checkout {\n const commit = this.git(\"rev-parse\", \"HEAD\");\n if (!commit) return this.withPr({});\n const branch =\n this.env.GITHUB_HEAD_REF || this.git(\"rev-parse\", \"--abbrev-ref\", \"HEAD\");\n const remote = this.git(\"config\", \"--get\", \"remote.origin.url\");\n return this.withPr({\n commit,\n ...(branch && branch !== \"HEAD\" ? { branch } : {}),\n ...(remote ? { repoUrl: CheckoutProvenance.withoutCredentials(remote) } : {}),\n });\n }\n\n /** Security: credentials are stripped; scp-style `git@host:org/repo` has none and is kept. */\n static withoutCredentials(url: string): string {\n return url.replace(/^([a-z][a-z0-9+.-]*:\\/\\/)[^@/]+@/i, \"$1\");\n }\n\n private withPr(checkout: Checkout): Checkout {\n const pr = this.pullRequest();\n return pr ? { ...checkout, pr } : checkout;\n }\n\n private pullRequest(): Checkout[\"pr\"] | undefined {\n const url = this.env.GATEWAY_PR_URL;\n const fromUrl = url ? /\\/pull\\/(\\d+)/.exec(url)?.[1] : undefined;\n if (url && fromUrl)\n return {\n number: Number(fromUrl),\n url,\n ...(this.env.GATEWAY_PR_TITLE ? { title: this.env.GATEWAY_PR_TITLE } : {}),\n };\n const number = /^refs\\/pull\\/(\\d+)\\//.exec(this.env.GITHUB_REF ?? \"\")?.[1];\n const server = this.env.GITHUB_SERVER_URL;\n const repo = this.env.GITHUB_REPOSITORY;\n if (!number || !server || !repo) return undefined;\n return { number: Number(number), url: `${server}/${repo}/pull/${number}` };\n }\n\n private git(...args: string[]): string | undefined {\n try {\n const out = execFileSync(\"git\", args, {\n cwd: this.cwd,\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n timeout: 5_000,\n })\n .toString()\n .trim();\n return out || undefined;\n } catch {\n return undefined;\n }\n }\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\nimport type { BrowserTier, WorldSurfaceKind } from \"./browser\";\nimport { CheckoutProvenance, type Checkout } from \"./checkoutProvenance\";\nimport {\n runTask,\n type RunTaskSummary,\n type TaskRun,\n type TaskRunResult,\n} from \"./taskRun\";\n\nconst SET_RUNS = \"/api/public/set-runs\";\n\nexport type SetRunDoc = {\n id: string;\n status: \"running\" | \"completed\" | \"failed\";\n model: string | null;\n source: string | null;\n taskSetDatasetId: string | null;\n actor: { kind: string; id: string; name?: string } | null;\n git: Checkout | null;\n progress: { done: number; planned: number };\n score: { mean: number | null; gradedTasks: number; ungradedTasks: number };\n tasks: Array<{\n worldTaskId: string;\n datasetItemId: string;\n name: string;\n evaluationId: string | null;\n sampleId: string | null;\n status: \"pending\" | \"completed\" | \"failed\";\n reward: number | null;\n checks: Array<{\n key: string;\n outcome: \"passed\" | \"failed\" | \"ungraded\";\n value: number | null;\n }>;\n }>;\n};\n\nexport type RunSetOptions = {\n model: string;\n /** Default `\"sdk\"`; the CLI passes `\"cli\"`. */\n source?: \"cli\" | \"sdk\";\n /** Default: read from the working directory; `null` records none. */\n git?: Checkout | null;\n surfaces?: WorldSurfaceKind[];\n browserTier?: BrowserTier;\n outDir?: string;\n trace?: boolean;\n onTask?: (summary: RunTaskSummary) => void;\n options?: WorldsClientOptions;\n};\n\n/** `failed`: an agent raised, a task could not run, or the platform stored the run as anything but completed. */\nexport type RunSetResult = {\n setRun: SetRunDoc;\n tasks: RunTaskSummary[];\n failed: boolean;\n closedAsRequested: boolean;\n};\n\n/** A low or missing reward is a result, not a failure; every task runs even after one fails. */\nexport async function runSet(\n datasetId: string,\n agent: (run: TaskRun) => TaskRunResult | Promise<TaskRunResult>,\n opts: RunSetOptions,\n): Promise<RunSetResult> {\n const options = opts.options ?? {};\n const git = opts.git === undefined ? CheckoutProvenance.read() : opts.git;\n const opened = await apiRequest<SetRunDoc>(options, \"POST\", SET_RUNS, {\n datasetId,\n model: opts.model,\n source: opts.source ?? \"sdk\",\n ...(git && Object.keys(git).length ? { git } : {}),\n });\n\n const close = (status: \"failed\" | \"completed\") =>\n apiRequest<SetRunDoc>(\n options,\n \"POST\",\n `${SET_RUNS}/${encodeURIComponent(opened.id)}/close`,\n { status },\n );\n // Ctrl-C closes the run failed before exiting instead of leaving it open.\n const onInterrupt = () => {\n void close(\"failed\").finally(() => process.exit(130));\n };\n process.once(\"SIGINT\", onInterrupt);\n const planned = await runPlannedTasks(opened, agent, opts, options).finally(\n () => process.off(\"SIGINT\", onInterrupt),\n );\n const { tasks, failed } = planned;\n const requested = failed ? \"failed\" : \"completed\";\n const setRun = await close(requested);\n return {\n setRun,\n tasks,\n failed: failed || setRun.status !== \"completed\",\n closedAsRequested: setRun.status === requested,\n };\n}\n\n/** Never throws, so the caller always gets to close the run. */\nasync function runPlannedTasks(\n opened: SetRunDoc,\n agent: (run: TaskRun) => TaskRunResult | Promise<TaskRunResult>,\n opts: RunSetOptions,\n options: WorldsClientOptions,\n): Promise<{ tasks: RunTaskSummary[]; failed: boolean }> {\n const tasks: RunTaskSummary[] = [];\n let failed = false;\n for (const task of opened.tasks) {\n try {\n const summary = await runTask(task.worldTaskId, agent, {\n model: opts.model,\n surfaces: opts.surfaces,\n browserTier: opts.browserTier,\n outDir: opts.outDir,\n trace: opts.trace,\n setRunId: opened.id,\n options,\n });\n tasks.push(summary);\n failed ||= summary.agentError !== null;\n opts.onTask?.(summary);\n } catch (error) {\n failed = true;\n const message = error instanceof Error ? error.message : String(error);\n process.stderr.write(`task ${task.name} could not run: ${message}\\n`);\n }\n }\n return { tasks, failed };\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\n/** What `localTreeState(dir)` reports: the tracked meta and the edits since its base. */\nexport type TreeState = {\n meta: { slug?: string; baseFiles?: Record<string, string> } | null;\n dirty: string[];\n clean: boolean;\n};\n\nexport class CheckoutRefusedError extends Error {\n constructor(message: string) {\n super(`checkout refused: ${message}`);\n this.name = \"CheckoutRefusedError\";\n }\n}\n\nconst NAMED_EDITS = 3;\n\n/**\n * Where a pull lands, decided before a byte is downloaded (P-20).\n *\n * - No target: `./<slug>`, de-duplicated with `-1`/`-2`; an existing dir is\n * never entered.\n * - Explicit target: absent or empty → used as-is; a clean checkout of the\n * same world → replaced (its base files are cleared first so files the new\n * version dropped do not linger); local edits, another world's checkout or\n * an untracked non-empty dir → refused unless `force`, which discards the\n * checkout's base files *and* its local edits (added files included) so the\n * result is the pulled version, nothing else the archive would see.\n * - A relative target stays under the current directory; one that escapes it\n * (`../x`) is refused — an absolute path is the explicit way elsewhere (P-21).\n *\n * Python twin: `gatewaysdk.benchmark_hub.checkout.CheckoutTarget`.\n */\nexport class CheckoutTarget {\n private constructor(\n readonly dir: string,\n /** Files of the checkout being replaced (its base + its local edits); removed by `clear()`. */\n readonly replaces: string[],\n ) {}\n\n static resolve(\n slug: string,\n target: string | undefined,\n opts: { cwd: string; force: boolean; state: (dir: string) => TreeState },\n ): CheckoutTarget {\n if (target === undefined) return CheckoutTarget.fresh(slug, opts.cwd);\n return CheckoutTarget.explicit(\n CheckoutTarget.confined(target, opts.cwd),\n slug,\n opts,\n );\n }\n\n /** The absolute destination; a relative target may not resolve above `cwd`. */\n private static confined(target: string, cwd: string): string {\n const dir = path.resolve(cwd, target);\n if (path.isAbsolute(target)) return dir;\n const rel = path.relative(cwd, dir);\n if (rel === \"\" || (!rel.startsWith(\"..\") && !path.isAbsolute(rel)))\n return dir;\n throw new CheckoutRefusedError(\n `--target ${target} resolves outside the current directory (${cwd}) — run from that directory, or pass an absolute path`,\n );\n }\n\n private static fresh(slug: string, cwd: string): CheckoutTarget {\n const base = path.join(cwd, slug);\n let dir = base;\n let i = 1;\n while (fs.existsSync(dir)) dir = `${base}-${i++}`;\n return new CheckoutTarget(dir, []);\n }\n\n private static explicit(\n dir: string,\n slug: string,\n opts: { force: boolean; state: (dir: string) => TreeState },\n ): CheckoutTarget {\n if (!fs.existsSync(dir)) return new CheckoutTarget(dir, []);\n if (!fs.statSync(dir).isDirectory())\n throw new CheckoutRefusedError(`${dir} is a file`);\n if (fs.readdirSync(dir).length === 0) return new CheckoutTarget(dir, []);\n const state = opts.state(dir);\n const refusal = CheckoutTarget.refusal(dir, slug, state);\n if (refusal === null || opts.force)\n return new CheckoutTarget(dir, CheckoutTarget.tracked(state));\n throw new CheckoutRefusedError(refusal);\n }\n\n /** Base files plus local edits — everything the archive would see in the old\n * checkout. `.env-metadata.json` is local input: a key that would leave the\n * checkout (`../x`, `/etc/x`) is dropped, never removed. */\n private static tracked(state: TreeState): string[] {\n if (!state.meta?.baseFiles) return [];\n return [\n ...new Set([...Object.keys(state.meta.baseFiles), ...state.dirty]),\n ]\n .filter(CheckoutTarget.confinedRel)\n .sort();\n }\n\n private static confinedRel(rel: string): boolean {\n if (rel === \"\" || path.isAbsolute(rel)) return false;\n return !rel.split(/[\\\\/]/).includes(\"..\");\n }\n\n /** Why `dir` cannot be overwritten, or null when it is a clean checkout of `slug`. */\n private static refusal(\n dir: string,\n slug: string,\n state: TreeState,\n ): string | null {\n if (!state.meta?.baseFiles)\n return `${dir} is not empty and is not a checkout of \"${slug}\" — pick an empty --target, or pass --force to overwrite it`;\n if (state.meta.slug !== undefined && state.meta.slug !== slug)\n return `${dir} tracks \"${state.meta.slug}\", not \"${slug}\" — pick another --target, or pass --force to replace it`;\n if (state.clean) return null;\n const n = state.dirty.length;\n const named = state.dirty.slice(0, NAMED_EDITS).join(\", \");\n const more = n > NAMED_EDITS ? `, +${n - NAMED_EDITS} more` : \"\";\n return `${dir} has ${n} local edit${n === 1 ? \"\" : \"s\"} not pushed (${named}${more}) — push or propose them first, or pass --force to discard them`;\n }\n\n /** Remove the replaced checkout's files (and the dirs they leave empty). */\n clear(): void {\n for (const rel of this.replaces) {\n const abs = path.join(this.dir, rel);\n fs.rmSync(abs, { force: true });\n this.pruneEmptyParents(path.dirname(abs));\n }\n }\n\n private pruneEmptyParents(from: string): void {\n let cur = from;\n while (cur !== this.dir && cur.startsWith(this.dir)) {\n if (fs.existsSync(cur) && fs.readdirSync(cur).length > 0) return;\n fs.rmSync(cur, { recursive: true, force: true });\n cur = path.dirname(cur);\n }\n }\n}\n","/**\n * What a directory IS, decided once for the TS SDK.\n *\n * `WorldDir.open(dir)` is the one detector this package has: the benchmark\n * front door (`classifyTree`, `detectEnvKind`, `harborTaskDirs`,\n * `verifiersPackage` in ../benchmarks) and the hub client (`collectArchiveRelPaths`,\n * `computeContentHash`, the contract-version lookup in ./hub.ts) are facades\n * over it. Twin of `gatewaysdk.environment.world.World` (Python) and\n * `packages/shared/src/world` (the platform); the corpus under\n * `conformance/worlds/` pins all three to the same answers.\n */\nimport { createHash } from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nexport const WORLD_MANIFEST = \"gateway-env.toml\";\nexport const API_BUNDLE_MANIFEST = \"gateway-api-world.toml\";\nexport const BUNDLED_WORLD_PREFIX = \"server/world/\";\nexport const CONNECTOR_SPEC = \"connector.toml\";\nexport const PYPROJECT = \"pyproject.toml\";\nexport const BENCHMARK_CONFIG = \"benchmark.json\";\nexport const WORLD_SCHEMA_MARKERS = [\"schema/world.json\", \"schema/runtime.json\", \"schema/lock.json\"];\nconst WORLD_ROOT_MARKERS = [CONNECTOR_SPEC, ...WORLD_SCHEMA_MARKERS];\n/** Root markers that widen the archive to every ordinary root file: a world's\n * executable contract and a benchmark's config/fixtures live at the root. */\nconst BROAD_ROOT_MARKERS = [WORLD_MANIFEST, API_BUNDLE_MANIFEST, BENCHMARK_CONFIG];\nconst SKIPPED_DIRS = new Set([\"dist\", \"build\", \"outputs\", \"__pycache__\", \"node_modules\"]);\n\n/** One entry the archive rules dropped: a whole directory (`name/`, `files`\n * counted) or a single file. */\nexport type Exclusion = { path: string; files: number };\n\n/** The runner's kind: what the dispatcher executes a pushed tree as. */\nexport type EnvKind = \"api\" | \"mock-tools\" | \"harbor\" | \"verifiers-v1\" | \"verifiers\";\n\n// The `verifiers.v1` namespace first shipped in verifiers 0.2.0: a v1 package\n// pins verifiers>=0.2 (or ~=0.2 / ==0.2.* / >=1 / ==1.*) in pyproject and/or\n// imports the namespace or subclasses Taskset alongside a v1-style `__all__`.\nconst V1_DEP = /[\"']verifiers\\s*(?:\\[[^\\]]*\\])?\\s*(?:>=|~=|==|>)\\s*(?:0\\.(?:[2-9]\\d*|[1-9]\\d+)|[1-9]\\d*)/;\nconst V1_IMPORT = /^\\s*(?:from\\s+verifiers\\.v1\\s+import\\b|from\\s+verifiers\\s+import\\s+v1\\b|import\\s+verifiers\\.v1\\b)/m;\nconst V1_TASKSET = /class\\s+\\w+\\s*\\(\\s*(?:(?:vf|v1|verifiers(?:\\.v1)?)\\.)?Taskset\\s*[,)]/;\nconst HARBOR_TASK = /^(?:tasks\\/)?([^/]+)\\/task\\.toml$/;\n\nconst skippedDir = (name: string): boolean =>\n name.startsWith(\".\") || SKIPPED_DIRS.has(name) || name.endsWith(\".egg-info\");\n\n/** Python's `sorted()` order for relpaths: code points, not UTF-16 units. */\nconst byCodePoint = (a: string, b: string): number => Buffer.compare(Buffer.from(a, \"utf-8\"), Buffer.from(b, \"utf-8\"));\n\nexport class WorldDir {\n private pathsMemo: string[] | undefined;\n\n private constructor(\n readonly dir: string,\n /** Where the authored world lives: `\"\"` for a world stored as itself,\n * `server/world/` for one stored as its api bundle. */\n readonly worldRoot: \"\" | typeof BUNDLED_WORLD_PREFIX,\n ) {}\n\n static open(dir: string): WorldDir {\n const present = (rel: string) => fs.existsSync(path.join(dir, rel));\n const bundled = present(API_BUNDLE_MANIFEST) && WORLD_ROOT_MARKERS.some((m) => present(BUNDLED_WORLD_PREFIX + m));\n return new WorldDir(dir, bundled ? BUNDLED_WORLD_PREFIX : \"\");\n }\n\n // ── Files ──────────────────────────────────────────────────────────────\n\n has(rel: string): boolean {\n return fs.existsSync(path.join(this.dir, rel));\n }\n\n text(rel: string): string | null {\n try {\n return fs.readFileSync(path.join(this.dir, rel), \"utf-8\");\n } catch {\n return null;\n }\n }\n\n /** A path under the authored world's root. */\n worldPath(rel: string): string {\n return this.worldRoot + rel;\n }\n\n /** Every regular file the archive rules keep (`_archive.py`: no hidden,\n * dist, build, outputs, pycache, node_modules or egg-info directories), as\n * sorted relpaths. Root files enter only when a Gateway manifest or\n * benchmark.json widens the root, or they are README.md, pyproject.toml or\n * Python. */\n get archivePaths(): string[] {\n if (this.pathsMemo) return this.pathsMemo;\n const broad = BROAD_ROOT_MARKERS.some((m) => this.has(m));\n const out: string[] = [];\n const walk = (rel: string) => {\n for (const entry of fs.readdirSync(rel ? path.join(this.dir, rel) : this.dir, { withFileTypes: true })) {\n const child = rel ? `${rel}/${entry.name}` : entry.name;\n if (entry.isDirectory()) {\n if (!skippedDir(entry.name)) walk(child);\n } else if (entry.isFile() && !entry.name.startsWith(\".\")) {\n const rootKept =\n broad || [\"README.md\", PYPROJECT, ...BROAD_ROOT_MARKERS].includes(entry.name) || entry.name.endsWith(\".py\");\n if (rel || rootKept) out.push(child);\n }\n }\n };\n walk(\"\");\n return (this.pathsMemo = out.sort(byCodePoint));\n }\n\n /** What the archive rules leave out, collapsed to the entry that decided\n * it: a pruned directory counts its files once, a dropped root file is\n * named. Dot entries (`.git/`, `.gateway/`, `.gitignore`) are the one\n * universal convention and stay unreported. `push` prints the rest so\n * nothing disappears silently. */\n get exclusions(): Exclusion[] {\n const kept = new Set(this.archivePaths);\n const out: Exclusion[] = [];\n const filesUnder = (rel: string): string[] =>\n fs.readdirSync(path.join(this.dir, rel), { withFileTypes: true }).flatMap((entry) => {\n const child = `${rel}/${entry.name}`;\n if (entry.isDirectory()) return filesUnder(child);\n return entry.isFile() ? [child] : [];\n });\n for (const entry of fs.readdirSync(this.dir, { withFileTypes: true }).sort((a, b) => byCodePoint(a.name, b.name))) {\n if (entry.name.startsWith(\".\")) continue;\n if (entry.isDirectory()) {\n const all = filesUnder(entry.name);\n const missing = all.filter((rel) => !kept.has(rel));\n if (missing.length === 0) continue;\n const whole = missing.length === all.length;\n out.push(...(whole ? [{ path: `${entry.name}/`, files: missing.length }] : missing.map((p) => ({ path: p, files: 1 }))));\n continue;\n }\n // A file, or a symlink to anything: the archive never follows a link.\n if (!kept.has(entry.name)) out.push({ path: entry.name, files: 1 });\n }\n return out;\n }\n\n /** A root `.gitignore` is present: the Python SDK honours it when\n * collecting, this package does not reimplement gitignore. */\n get hasRootGitignore(): boolean {\n return this.has(\".gitignore\");\n }\n\n /** SHA-256 over `utf8(\"file:\" + relpath)` + bytes per archive path in\n * sorted order: the version's identity, byte-compatible with\n * `_archive.compute_content_hash` and Prime Intellect. */\n get contentHash(): string {\n const hasher = createHash(\"sha256\");\n for (const rel of this.archivePaths) {\n hasher.update(Buffer.from(`file:${rel}`, \"utf-8\"));\n hasher.update(fs.readFileSync(path.join(this.dir, rel)));\n }\n return hasher.digest(\"hex\");\n }\n\n // ── Markers ────────────────────────────────────────────────────────────\n\n get isApiBundle(): boolean {\n return this.has(API_BUNDLE_MANIFEST);\n }\n\n get hasManifest(): boolean {\n return this.has(this.worldPath(WORLD_MANIFEST));\n }\n\n get hasSchemaMarker(): boolean {\n return WORLD_SCHEMA_MARKERS.some((m) => this.has(this.worldPath(m)));\n }\n\n /** Harbor task dirs, relative to the tree: `tasks/<name>` when a `tasks/`\n * dir holds them, else the root `<name>` dirs. */\n taskDirs(): string[] {\n const names = new Set<string>();\n for (const rel of this.archivePaths) {\n const m = HARBOR_TASK.exec(rel);\n if (m) names.add(rel.startsWith(\"tasks/\") ? `tasks/${m[1]}` : m[1]!);\n }\n const under = [...names].filter((n) => n.startsWith(\"tasks/\"));\n return (under.length ? under : [...names]).sort();\n }\n\n /** The Python package of a verifiers tree (`<pkg>/__init__.py` or\n * `src/<pkg>/__init__.py`), or null. */\n pythonPackage(): { name: string; init: string } | null {\n if (!this.has(PYPROJECT)) return null;\n for (const base of [\"\", \"src/\"]) {\n const init = this.archivePaths.find((rel) => {\n const m = /^([^/]+)\\/__init__\\.py$/.exec(rel.startsWith(base) ? rel.slice(base.length) : \"\");\n return m !== null && m[1] !== \"tests\";\n });\n if (init) return { name: init.slice(base.length).split(\"/\")[0]!, init };\n }\n return null;\n }\n\n /** The package targets the `verifiers.v1` API: read from the root\n * pyproject and every archived Python module. */\n get isVerifiersV1(): boolean {\n for (const rel of this.archivePaths) {\n if (rel !== PYPROJECT && !rel.endsWith(\".py\")) continue;\n const text = this.text(rel);\n if (text === null) continue;\n if (rel === PYPROJECT ? V1_DEP.test(text) : V1_IMPORT.test(text) || (text.includes(\"__all__\") && V1_TASKSET.test(text)))\n return true;\n }\n return false;\n }\n\n // ── The answer ─────────────────────────────────────────────────────────\n\n /** The runner's kind (`detect_env_kind`): api / mock-tools win over\n * everything, a harbor task tree next, then the verifiers API version. */\n get kind(): EnvKind {\n if (this.isApiBundle) return \"api\";\n if (this.has(WORLD_MANIFEST)) return \"mock-tools\";\n if (this.taskDirs().length) return \"harbor\";\n return this.isVerifiersV1 ? \"verifiers-v1\" : \"verifiers\";\n }\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { gunzipSync } from \"node:zlib\";\n\n/**\n * The sdk-ts reader of a world's gzipped tar bundle — the twin of the\n * platform's `packages/shared/src/server/worlds/tar.ts` walker. A bundle\n * `pull`/`checkout` downloads may have been written by any of the three\n * writers on the platform, so the walk understands every way a name can\n * travel:\n * • the 100-byte ustar `name` field, UTF-8 (this SDK's own writer),\n * • a GNU `L` long-name member naming the member that follows,\n * • a PAX `x` header whose `path=` record overrides the next name — what\n * Python's `tarfile` (the Python SDK's writer) emits for every\n * non-ASCII or >100-byte name, leaving a `?`-replaced ASCII fallback in\n * the ustar field,\n * • the POSIX ustar `prefix` field (bytes 345–500) joined as `prefix/name`.\n * Reading only the ustar field silently corrupts the other three (cold-batch\n * P-05: `ünïcödé ✓.txt` pulled as `?n?c?d? ?.txt`).\n */\n\nexport const TAR_FILE_MODE = 0o644;\nexport const TAR_EXEC_MODE = 0o755;\n\n/** The only mode detail a world keeps: executable or not. */\nexport function archiveMode(mode: number): number {\n return (mode & 0o111) !== 0 ? TAR_EXEC_MODE : TAR_FILE_MODE;\n}\n\nexport type TarMember = {\n name: string;\n bytes: Buffer;\n typeflag: string;\n mode: number;\n};\n\nfunction field(header: Buffer, start: number, end: number): string {\n return header.subarray(start, end).toString(\"utf-8\").replace(/\\0.*$/, \"\");\n}\n\nfunction octalField(header: Buffer, start: number, end: number): number {\n return parseInt(field(header, start, end).trim(), 8);\n}\n\n/** `path=` from a PAX extended-header payload (`LEN key=value\\n` records). */\nfunction paxPath(body: Buffer): string | null {\n let off = 0;\n let found: string | null = null;\n while (off < body.length) {\n const sp = body.indexOf(0x20, off);\n if (sp === -1) break;\n const len = parseInt(body.subarray(off, sp).toString(\"ascii\"), 10);\n if (!Number.isFinite(len) || len <= 0) break;\n const record = body.subarray(sp + 1, off + len);\n const eq = record.indexOf(0x3d);\n const key = eq === -1 ? \"\" : record.subarray(0, eq).toString(\"utf-8\");\n if (key === \"path\")\n found = record\n .subarray(eq + 1)\n .toString(\"utf-8\")\n .replace(/\\n$/, \"\");\n off += len;\n }\n return found;\n}\n\nexport class TarArchive {\n private constructor(private readonly tar: Buffer) {}\n\n static fromGzip(bundle: Buffer): TarArchive {\n return new TarArchive(gunzipSync(bundle));\n }\n\n static fromTar(tar: Buffer): TarArchive {\n return new TarArchive(tar);\n }\n\n /** Every member, names fully resolved; metadata members are consumed. */\n *members(): Generator<TarMember> {\n const tar = this.tar;\n let offset = 0;\n let pendingName: string | null = null;\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 size = octalField(header, 124, 136) || 0;\n const mode = octalField(header, 100, 108) || TAR_FILE_MODE;\n const typeflag = String.fromCharCode(header[156] ?? 0);\n const bytes = tar.subarray(offset, offset + size);\n offset += Math.ceil(size / 512) * 512;\n if (typeflag === \"L\") {\n pendingName = bytes.toString(\"utf-8\").replace(/\\0.*$/, \"\");\n continue;\n }\n if (typeflag === \"x\") {\n pendingName = paxPath(bytes) ?? pendingName;\n continue;\n }\n if (typeflag === \"K\" || typeflag === \"g\") continue;\n const name = pendingName ?? TarArchive.ustarName(header);\n pendingName = null;\n yield { name: name.replace(/^\\.\\//, \"\"), bytes, typeflag, mode };\n }\n }\n\n private static ustarName(header: Buffer): string {\n const name = field(header, 0, 100);\n const magic = header.subarray(257, 262).toString(\"ascii\");\n const prefix = magic === \"ustar\" ? field(header, 345, 500) : \"\";\n return prefix ? `${prefix}/${name}` : name;\n }\n\n /** Regular files only, confined to `dir` (absolute or `..` names are\n * skipped, never written). Returns the number of files written. */\n extractTo(dir: string): number {\n let written = 0;\n for (const member of this.members()) {\n if (member.typeflag !== \"0\" && member.typeflag !== \"\\0\") continue;\n if (!TarArchive.isConfined(member.name)) continue;\n const target = path.join(dir, member.name);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n const mode = archiveMode(member.mode);\n fs.writeFileSync(target, member.bytes, { mode });\n fs.chmodSync(target, mode);\n written++;\n }\n return written;\n }\n\n private static isConfined(name: string): boolean {\n if (name === \"\" || name.startsWith(\"/\")) return false;\n return !name.split(\"/\").includes(\"..\");\n }\n}\n","import { createHash } from \"node:crypto\";\nimport { gzipSync } from \"node:zlib\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\nimport { CheckoutTarget } from \"./checkoutTarget\";\nimport { WorldDir, type Exclusion } from \"./worldDir\";\nimport { TarArchive, TAR_FILE_MODE, archiveMode } from \"./tar\";\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 * The content hash is the version's identity and is byte-compatible with\n * Prime Intellect: `WorldDir.contentHash` (./worldDir.ts) computes it here,\n * `WorldTree.contentHash` on the platform and `_archive.compute_content_hash`\n * in the Python SDK; the conformance corpus pins the three to the same bytes.\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\");\n\n/** The archive-visible files of a working dir, as sorted relpaths\n * (`WorldDir.archivePaths`). Throws on a root .gitignore (see the header). */\nexport function collectArchiveRelPaths(dir: string): string[] {\n const world = WorldDir.open(dir);\n if (world.hasRootGitignore) {\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 return world.archivePaths;\n}\n\nexport function computeContentHash(dir: string): string {\n collectArchiveRelPaths(dir);\n return WorldDir.open(dir).contentHash;\n}\n\n// ── deterministic tar.gz writer ─────────────────────────────────────────────\n\nfunction octal(value: number, length: number): Buffer {\n return Buffer.from(\n value.toString(8).padStart(length - 1, \"0\") + \"\\0\",\n \"ascii\",\n );\n}\n\n/** The two modes a stored world file can have: the tar (and `pull`) keep\n * only whether a file is executable — `tests/test.sh` in a harbor tree must\n * still run after a round trip. Owner/mtime are cleared for determinism. */\nconst FILE_MODE = TAR_FILE_MODE;\nexport { archiveMode };\n\nfunction tarHeader(name: string, size: number, mode = FILE_MODE): Buffer {\n const header = Buffer.alloc(512);\n header.write(name, 0, 100, \"utf-8\");\n octal(mode, 8).copy(header, 100);\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, mode: number): 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, mode));\n } else {\n parts.push(tarHeader(name, payload.length, mode));\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 const abs = path.join(dir, relPath);\n parts.push(\n ...tarMember(\n relPath,\n fs.readFileSync(abs),\n archiveMode(fs.statSync(abs).mode),\n ),\n );\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 the checkout tracks; absent on a tag (detached) checkout. */\n branch?: string;\n /** Tag the checkout was taken from: immutable, so `push` refuses to move it. */\n tag?: 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\n/** The slug a push of `dir` lands on: an explicit one, else the slug the dir\n * was pushed to or pulled from (its `.gateway` meta), else the pyproject\n * name, else the directory's name — so a tracked checkout never creates a\n * second world named after its folder. */\nexport function pushSlug(dir: string, explicit?: string): string {\n return resolvePushSlug(dir, { explicit }).slug;\n}\n\nexport type SlugDeclaration = { source: string; slug: string };\n\nexport type PushSlugResolution = {\n slug: string;\n /** Where the slug came from (`--slug`, `.gateway metadata`, `benchmark.json`, `pyproject.toml`, `directory name`). */\n source: string;\n /** The slug the dir's `.gateway/.env-metadata.json` tracks from an earlier push or pull, if any. */\n tracked: string | null;\n /** What the tree itself declares (a caller's benchmark.json, then pyproject.toml), in precedence order. */\n declared: SlugDeclaration[];\n /** A declaration the tracked slug does not match — set only when the tracked slug won without `--slug`. */\n conflict: SlugDeclaration | null;\n};\n\n/** The platform's collision suffix: `acme-2` minted for a taken `acme`. */\nconst MINTED_SUFFIX = /^-\\d+$/;\n\n/** `pushSlug` with its provenance. `declared` are the caller's own slug sources\n * (e.g. `{ \"benchmark.json\": \"x\" }`), consulted before pyproject. A tracked slug\n * that disagrees with what the tree declares is reported as `conflict` so a\n * front door can refuse: that is how a directory pushed once with `--slug X`\n * silently landed every later push on X while its benchmark.json said Y. The\n * platform's collision suffix (`acme-2` minted for a taken `acme`) is not a\n * conflict; any other difference is (`acme-e2e` for `acme` was the mix-up). */\nexport function resolvePushSlug(\n dir: string,\n opts: { explicit?: string; declared?: Record<string, string | null | undefined> } = {},\n): PushSlugResolution {\n const meta = readLocalMeta(dir);\n const tracked = typeof meta?.slug === \"string\" && meta.slug ? meta.slug : null;\n const declared = Object.entries({ ...(opts.declared ?? {}), \"pyproject.toml\": readPyproject(dir).name })\n .filter((entry): entry is [string, string] => typeof entry[1] === \"string\" && entry[1] !== \"\")\n .map(([source, slug]) => ({ source, slug }));\n const base = { tracked, declared, conflict: null };\n if (opts.explicit) return { ...base, slug: opts.explicit, source: \"--slug\" };\n if (tracked) {\n const minted = (d: SlugDeclaration) => tracked.startsWith(d.slug) && MINTED_SUFFIX.test(tracked.slice(d.slug.length));\n const conflict = declared.find((d) => d.slug !== tracked && !minted(d)) ?? null;\n return { ...base, slug: tracked, source: \".gateway metadata\", conflict };\n }\n const first = declared[0];\n if (first) return { ...base, slug: first.slug, source: first.source };\n return { ...base, slug: path.basename(path.resolve(dir)), source: \"directory name\" };\n}\n\n/** The refusal a front door raises on `PushSlugResolution.conflict`: both slugs, both sources, every way out. */\nexport class PushSlugConflict extends Error {\n constructor(\n public readonly dir: string,\n public readonly tracked: string,\n public readonly declared: SlugDeclaration,\n ) {\n super(\n `${dir} tracks slug \\`${tracked}\\` (${META_RELPATH}, from an earlier push) but its ${declared.source} says \\`${declared.slug}\\`. ` +\n `Nothing was pushed. Pass --slug ${declared.slug} to push there (and retrack the dir), --slug ${tracked} to keep pushing to \\`${tracked}\\`, ` +\n `or delete ${META_RELPATH} to forget the earlier push.`,\n );\n this.name = \"PushSlugConflict\";\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\n/** A schema world's own version: `x-gateway.package.version` of its contract\n * (`schema/world.json`, or `server/world/schema/world.json` in an api bundle).\n * What a connector world has instead of a pyproject, so its versions read\n * \"1.0.0\" rather than \"unversioned\" on the platform. */\nfunction readWorldContractVersion(dir: string): {\n name?: string;\n version?: string;\n} {\n const world = WorldDir.open(dir);\n try {\n const parsed = JSON.parse(\n world.text(world.worldPath(\"schema/world.json\")) ?? \"\",\n ) as {\n \"x-gateway\"?: { package?: { id?: string; version?: string } };\n };\n const pkg = parsed[\"x-gateway\"]?.package;\n if (pkg?.version) return { name: pkg.id, version: pkg.version };\n } catch {\n // not a schema world\n }\n return {};\n}\n\n/** The rows the platform previews for a pushed DRAFT: the archive set, one\n * entry per file the content hash covers, so hash, tarball, manifest and\n * `pull` agree on what the world is. Finalize replaces them with rows\n * derived from the stored bytes. */\nexport function buildFileManifest(\n dir: string,\n): { path: string; isDirectory: boolean; size: number; sha256: string }[] {\n return collectArchiveRelPaths(dir).map((relPath) => {\n const payload = fs.readFileSync(path.join(dir, relPath));\n return {\n path: relPath,\n isDirectory: false,\n size: payload.length,\n sha256: createHash(\"sha256\").update(payload).digest(\"hex\"),\n };\n });\n}\n\nasync function putObject(\n url: string,\n data: Buffer,\n shaB64: string,\n): 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(\n `object PUT -> ${resp.status}: ${(await resp.text()).slice(0, 300)}`,\n );\n }\n}\n\n// ── the workflows ────────────────────────────────────────────────────────────\n\n/** The refusal `push` raises from a tag checkout: tags never move, so the\n * push needs a branch named explicitly. */\nexport class DetachedPushError extends Error {\n constructor(dir: string, tag: string) {\n super(\n `push refused: ${dir} is a checkout of tag \"${tag}\" (tags are immutable). ` +\n `Nothing was pushed. Pass --branch <name> to land these files on a branch, or checkout a branch first.`,\n );\n this.name = \"DetachedPushError\";\n }\n}\n\n/** The branch a push of `dir` moves: an explicit --branch, else the tracked\n * branch, else main — never a tag. */\nexport function pushBranch(dir: string, localMeta: LocalMeta, explicit: string | undefined): string {\n if (explicit) return explicit;\n if (typeof localMeta.tag === \"string\" && localMeta.tag) throw new DetachedPushError(dir, localMeta.tag);\n return (localMeta.branch as string | undefined) ?? DEFAULT_BRANCH;\n}\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 /** Push on top of this version instead of the local meta's base — what a\n * CI checkout (which has no local meta) passes after resolving the\n * branch tip, so re-validating a PR replaces its own previous push\n * instead of 409ing against it. */\n baseVersionId?: string | null;\n /** Container metadata recorded on resolve — the Python CLI's --name,\n * --description, --tag and --visibility. */\n name?: string;\n description?: string;\n tags?: string[];\n visibility?: string;\n /** Pre-built OCI image ref for image/agentic envs (recorded on the version). */\n imageRef?: string;\n options?: WorldsClientOptions;\n } = {},\n): Promise<{\n containerId: string;\n slug: string;\n versionId: string;\n contentHash: string;\n branch: string;\n state: string | null;\n alreadyUploaded: boolean;\n /** The edit session the push joined (`gateway worlds edit close <slug>` moves main); null when the platform landed it on main directly. */\n editSessionId: string | null;\n /** Files the archive rules kept (what the hash, manifest and tarball cover). */\n filesKept: number;\n /** What the archive rules left out, so nothing disappears silently. */\n excluded: Exclusion[];\n}> {\n const options = opts.options ?? {};\n if (!fs.statSync(dir).isDirectory())\n throw new Error(`Not a directory: ${dir}`);\n const localMeta = readLocalMeta(dir) ?? {};\n const branch = pushBranch(dir, localMeta, opts.branch);\n const baseVersionId = opts.baseVersionId ?? localMeta.versionId ?? null;\n\n const world = WorldDir.open(dir);\n const fileManifest = buildFileManifest(dir);\n if (fileManifest.length === 0)\n throw new Error(\n `Nothing to push: ${dir} has no files the archive rules keep (a world root marker, README.md, pyproject.toml, *.py, or any file below a subdirectory).`,\n );\n const contentHash = world.contentHash;\n const pyproject = readPyproject(dir);\n // A connector world carries its version on its contract, not a pyproject.\n const contractVersion = pyproject.version\n ? undefined\n : readWorldContractVersion(dir).version;\n if (contractVersion) pyproject.version = contractVersion;\n // A dir that tracks a world (created, pulled or pushed before) pushes back\n // to THAT world: its recorded slug wins over the package name, so a world\n // created as `acme-f7` is not re-published as pyproject's `acme` — which is\n // how `worlds ci` minted an unsuffixed twin of every suffixed world.\n const slug =\n opts.slug ??\n localMeta.slug ??\n pyproject.name ??\n path.basename(path.resolve(dir));\n\n // Sent twice on purpose: resolve records it on a container it CREATES,\n // finalize refreshes an existing one — only when the push actually lands.\n // An omitted field leaves the container's value alone; an explicit one\n // replaces it, so `\"\"` clears the description and `[]` clears the tags.\n const metadata = {\n ...(opts.name !== undefined ? { name: opts.name } : {}),\n ...(opts.description !== undefined\n ? { description: opts.description }\n : {}),\n ...(opts.tags !== undefined ? { tags: opts.tags } : {}),\n ...(opts.visibility ? { visibility: opts.visibility } : {}),\n };\n const resolve = await apiRequest<{ containerId: string }>(\n options,\n \"POST\",\n \"/api/public/benchmark-containers/resolve\",\n { slug, ...metadata },\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 alreadyUploaded?: boolean;\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,\n branch,\n baseVersionId,\n ...(opts.force ? { force: true } : {}),\n ...(opts.message ? { changeReason: opts.message } : {}),\n ...(opts.author ? { author: opts.author } : {}),\n ...(opts.imageRef ? { imageRef: opts.imageRef } : {}),\n });\n\n if (version.uploadUrl)\n await putObject(version.uploadUrl, tarball, bundleSha256);\n\n const final = await apiRequest<{ state?: string; branch?: string; editSessionId?: string }>(\n options,\n \"POST\",\n `/api/public/benchmark-containers/versions/${version.versionId}/finalize`,\n {\n branch,\n baseVersionId,\n ...(opts.force ? { force: true } : {}),\n ...metadata,\n },\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 {\n containerId: resolve.containerId,\n slug,\n versionId: version.versionId,\n contentHash,\n branch: final.branch ?? branch,\n state: final.state ?? null,\n alreadyUploaded: Boolean(version.alreadyUploaded),\n editSessionId: final.editSessionId ?? null,\n filesKept: fileManifest.length,\n excluded: world.exclusions,\n };\n}\n\n/** Extract a downloaded bundle into `dir` (paths confined, executable bit\n * kept; every name encoding the platform's writers emit — see ./tar.ts). */\nexport function extractBundle(bundle: Buffer, dir: string): number {\n return TarArchive.fromGzip(bundle).extractTo(dir);\n}\n\n/** What a checkout tracks after a pull: the branch that answered the ref, or\n * the tag it was taken from (detached). Older servers name neither: latest\n * and semver/hash pins land on main; any other ref was a branch. */\nexport function checkoutIdentity(\n ref: string,\n resolved: { branch?: string | null; tag?: string | null },\n): { branch?: string; tag?: string } {\n if (resolved.tag) return { tag: resolved.tag };\n if (resolved.branch) return { branch: resolved.branch };\n const pinned = ref === \"latest\" || /^\\d|^[0-9a-f]{8,}$/.test(ref);\n return { branch: pinned ? DEFAULT_BRANCH : ref };\n}\n\nexport async function pull(\n slugRef: string,\n target?: string,\n options: WorldsClientOptions = {},\n opts: { force?: boolean } = {},\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 // Decided first: a refused target costs no request and touches no file.\n const landing = CheckoutTarget.resolve(slug, target, {\n cwd: process.cwd(),\n force: opts.force ?? false,\n state: localTreeState,\n });\n\n const details = await apiRequest<{\n versionId: string;\n contentHash: string;\n semanticVersion?: string | null;\n branch?: string | null;\n tag?: 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 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 dir = landing.dir;\n fs.mkdirSync(dir, { recursive: true });\n landing.clear();\n const files = extractBundle(bundle, dir);\n writeLocalMeta(dir, {\n slug,\n ref,\n ...checkoutIdentity(ref, details),\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: {\n title: string;\n reason: string;\n targetBranch?: string;\n options?: WorldsClientOptions;\n },\n): Promise<{ proposalId: string }> {\n const meta = readLocalMeta(dir);\n if (!meta?.slug || !meta.baseFiles) {\n throw new Error(\n \"This dir has no pull/push base — run pull first, then edit, then propose.\",\n );\n }\n const state = localTreeState(dir);\n if (state.clean)\n 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))\n 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, pushSlug } 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 source?: { repoUrl?: string; commit?: string },\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 // Name the exact source that ran: the commit on GitHub when we know it,\n // always the content hash the platform pinned.\n const commitLink =\n source?.repoUrl && source?.commit\n ? `[\\`${source.commit.slice(0, 12)}\\`](${source.repoUrl}/commit/${source.commit})`\n : null;\n lines.push(\n `Ran the pull request's own world source` +\n (commitLink ? ` (${commitLink} on \\`${report.branch}\\`` : ` (`) +\n `${commitLink ? \", \" : \"\"}pinned as \\`${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 // Every scenario, in the open: a validation whose per-scenario grades hide\n // behind a fold reads as one opaque number. Fold only when the table is\n // genuinely long.\n if (taskRows.length > 0) {\n const fold = taskRows.length > 12;\n lines.push(\"\");\n if (fold) {\n lines.push(\n `<details><summary>Per-scenario rewards (${taskRows.length})</summary>`,\n );\n lines.push(\"\");\n } else {\n lines.push(`**Scenarios (${taskRows.length})**`);\n lines.push(\"\");\n }\n lines.push(\"| Scenario | 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 if (fold) {\n lines.push(\"\");\n lines.push(\"</details>\");\n }\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 const slug = pushSlug(dir, opts.slug);\n progress(`pushing ${dir} as ${slug}@${branch}…`);\n // CI checkouts carry no local push meta, so a re-validation would 409\n // against the branch tip its own previous run created. Validation's\n // semantics are \"this branch's tip BECOMES the PR's source\": resolve the\n // current tip and push on top of it. A branch that does not exist yet\n // resolves to no base, which is a fresh branch — also correct.\n let tipVersionId: string | null = null;\n try {\n const tip = await apiRequest<{ versionId?: string }>(\n options,\n \"POST\",\n \"/api/public/benchmark-containers/resolve-version\",\n { slug, ref: branch },\n );\n tipVersionId = tip.versionId ?? null;\n } catch {\n tipVersionId = null;\n }\n const pushed = await push(dir, {\n slug,\n branch,\n baseVersionId: tipVersionId,\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 {\n ...base,\n markdown: buildMarkdown(base, minScore, {\n repoUrl: provenance.repoUrl,\n commit: provenance.commit,\n }),\n };\n}\n","import { ApiError, apiRequest, type WorldsClientOptions } from \"./index\";\nimport type { PlatformMethod } from \"./transport\";\n\n/**\n * The CLI sandbox: a server-side workspace opened on a READY version of a\n * world (`/workspace/env` in the console agent's sandbox) — or, with\n * `{ new, from }`, on a world that does not exist yet, seeded from the\n * `schema init` scaffold or a shipped template and created by its first\n * commit — edited and run there, and committed straight into the version\n * service; the source never lands on the caller's disk. `importData` is the\n * data door beside `commit`: a rows file in the sandbox tree into the platform\n * world's data ledger, read out by the platform (no credential enters the\n * sandbox, nothing passes through this machine). One client under\n * both `gateway worlds sandbox …` and `gateway bench sandbox …`; the\n * Python twin is `gatewaysdk.benchmark_hub.sandbox.WorldSandboxClient`.\n */\n\n/** Mirrors `SandboxSummaryResponse` (web/features/public-api/types/world-sandboxes.ts). */\nexport type SandboxSummary = {\n sandboxId: string;\n slug: string;\n /** null while a new-world sandbox awaits its first commit. */\n containerId: string | null;\n /** The version the next commit is validated against; advances on commit. null before the first commit of a new world. */\n baseVersionId: string | null;\n /** Set on a new-world sandbox until its first commit creates the world. */\n pendingSlug: string | null;\n status: \"open\" | \"closed\";\n lastCommitVersionId: string | null;\n createdAt: string;\n};\n\nexport type SandboxOpened = SandboxSummary & {\n /** null for a new-world sandbox (no base). */\n baseContentHash: string | null;\n branch: string;\n dataSnapshotId: string | null;\n fileCount: number;\n workdir: string;\n /** The `gateway` CLI `exec` finds on PATH (the platform's version, staged runtime digest); null when the image cannot host it — `warnings` says why. */\n cli: { version: string; digest: string } | null;\n warnings: string[];\n};\n\nexport type SandboxExecResult = {\n exitCode: number;\n stdout: string;\n stderr: string;\n timedOut: boolean;\n truncated: boolean;\n durationMs: number;\n /** Why `gateway`/`sqlite3` were not on PATH for this command; empty when the runtime is staged. */\n warnings: string[];\n};\n\nexport type SandboxChanges = { added: string[]; modified: string[]; removed: string[] };\n\nexport type SandboxCheckResult = {\n ok: boolean;\n contentHash: string | null;\n noChange: boolean;\n fileCount: number;\n changes: SandboxChanges;\n /** Working-tree paths left out of the version: `.gatewayignore`, default scratch, credential-shaped files, links. */\n ignored: string[];\n /** Why a listed path was held back (credential-shaped, a link, unhashed by the gate); paths only. */\n warnings: string[];\n error: string | null;\n};\n\nexport type SandboxCommitResult = {\n /** The world the commit landed on. */\n slug: string;\n versionId: string;\n contentHash: string;\n branch: string;\n deduped: boolean;\n noChange: boolean;\n changes: SandboxChanges;\n ignored: string[];\n /** The same warnings `check` gives, so a commit never hides what it left out. */\n warnings: string[];\n /** The API key's edit session the commit joined; `gateway worlds edit close <slug>` moves main. */\n editSessionId?: string;\n};\n\n/** Mirrors `PostSandboxImportBody`. */\nexport type SandboxImportInput = {\n /** A .json/.jsonl/.ndjson/.csv/.tsv (optionally .gz) relative to the world root. */\n path: string;\n entity?: string;\n /** One character (a real tab for TSV); defaults by extension. */\n delimiter?: string;\n mode?: \"append\" | \"replace\";\n merge?: \"upsert\" | \"fill\";\n redact?: \"off\" | \"apply\" | \"refuse\";\n atomic?: boolean;\n dryRun?: boolean;\n message?: string;\n};\n\n/** Mirrors `PostSandboxImportResponse` (201). */\nexport type SandboxImportResult = {\n containerId: string;\n slug: string;\n batchId: string | null;\n state: string;\n versionId: string | null;\n baseVersionId: string;\n contentHash: string | null;\n deduped: boolean;\n entityCounts: Record<string, number>;\n kind: string | null;\n dryRun: boolean;\n refusalCount: number;\n rowCount: number;\n chunkCount: number;\n /** `sandbox:<id>/<path>`. */\n source: string;\n};\n\n/** Mirrors `PostSandboxImportPendingResponse` (202): poll `worlds data batches`. */\nexport type SandboxImportPending = {\n batchId: string;\n state: string;\n rowCount: number;\n chunkCount: number;\n source: string;\n};\n\nexport const isSandboxImportPending = (\n answer: SandboxImportResult | SandboxImportPending,\n): answer is SandboxImportPending => !(\"versionId\" in answer);\n\n/** Mirrors `PostSandboxOpenBody`: an existing world at a ref, or a new world seeded from a template. */\nexport type SandboxOpenExisting = { slug: string; ref?: string };\nexport type SandboxOpenNew = { new: string; from: string };\nexport type SandboxOpenTarget = SandboxOpenExisting | SandboxOpenNew;\n\n/** `slug` or `slug@ref` → the open body; a bare slug opens the latest READY version. */\nexport function parseSlugRef(slugRef: string): SandboxOpenExisting {\n const at = slugRef.indexOf(\"@\");\n if (at === -1) return { slug: slugRef };\n return { slug: slugRef.slice(0, at), ref: slugRef.slice(at + 1) };\n}\n\nconst sid = encodeURIComponent;\n\nconst SANDBOXES = \"/api/public/benchmark-containers/sandboxes\";\n\n/** One sandbox request may run the platform's longest exec (600 s) plus the answer; the Python twin waits the same 660 s. */\nexport const SANDBOX_REQUEST_TIMEOUT_MS = 660_000;\n\n/** Mirrors `PostSandboxCommitBody`: `rebase` replays the sandbox's edits onto the branch head when the base moved. */\nexport type SandboxCommitInput = { message: string; branch?: string; rebase?: boolean };\n\n/** One path a rebase refused, as the 409 body's `conflicts[]` names it. */\nexport type RebaseConflictPath = { path: string; reason: string };\n\n/** A 409 from `commit --rebase`: the paths both sides changed and why each was refused. Null for any other failure. */\nexport function rebaseConflicts(error: unknown): RebaseConflictPath[] | null {\n if (!(error instanceof ApiError) || error.status !== 409) return null;\n let body: unknown;\n try {\n body = JSON.parse(error.text);\n } catch {\n return null;\n }\n const conflicts = (body as { conflicts?: unknown } | null)?.conflicts;\n if (!Array.isArray(conflicts)) return null;\n return conflicts.filter(isConflictPath).map(({ path, reason }) => ({ path, reason }));\n}\n\nfunction isConflictPath(value: unknown): value is RebaseConflictPath {\n const entry = value as Partial<RebaseConflictPath> | null;\n return typeof entry?.path === \"string\" && typeof entry.reason === \"string\";\n}\n\n/** A 409 `sandbox_uncommitted` from `close`: the paths a commit would keep. Null for any other failure. */\nexport function uncommittedPaths(error: unknown): string[] | null {\n if (!(error instanceof ApiError) || error.status !== 409 || error.code !== \"sandbox_uncommitted\") return null;\n let body: unknown;\n try {\n body = JSON.parse(error.text);\n } catch {\n return null;\n }\n const uncommitted = (body as { uncommitted?: unknown } | null)?.uncommitted;\n if (!Array.isArray(uncommitted)) return null;\n return uncommitted.filter((p): p is string => typeof p === \"string\");\n}\n\n/** `sandbox list` narrows: status, world, count (newest first). */\nexport type SandboxListFilter = {\n status?: \"open\" | \"closed\";\n slug?: string;\n limit?: number;\n};\n\nfunction listQuery(filter: SandboxListFilter): string {\n const params = new URLSearchParams();\n if (filter.status) params.set(\"status\", filter.status);\n if (filter.slug) params.set(\"slug\", filter.slug);\n if (filter.limit !== undefined) params.set(\"limit\", String(filter.limit));\n const qs = params.toString();\n return qs ? `?${qs}` : \"\";\n}\n\nexport class WorldSandboxClient {\n constructor(private readonly options: WorldsClientOptions = {}) {}\n\n private request<T>(method: PlatformMethod, path: string, body?: unknown): Promise<T> {\n return apiRequest<T>(this.options, method, path, body, {\n timeoutMs: SANDBOX_REQUEST_TIMEOUT_MS,\n });\n }\n\n /**\n * `{ slug, ref? }` opens a READY version; `{ new, from }` opens a sandbox on\n * a world that does not exist yet (409 `world_exists` if the slug is taken,\n * 400 naming the shipped templates if `from` is unknown). Its first commit\n * creates the world on `main`.\n */\n open(target: SandboxOpenTarget): Promise<SandboxOpened> {\n return this.request(\"POST\", `${SANDBOXES}`, target);\n }\n\n status(sandboxId: string): Promise<SandboxSummary> {\n return this.request(\"GET\", `${SANDBOXES}/${sid(sandboxId)}`);\n }\n\n /** The project's sandboxes, newest first — how an agent finds one it left open. */\n async list(filter: SandboxListFilter = {}): Promise<SandboxSummary[]> {\n const res = await this.request<{ sandboxes: SandboxSummary[] }>(\"GET\", `${SANDBOXES}${listQuery(filter)}`);\n return res.sandboxes;\n }\n\n async read(sandboxId: string, filePath: string): Promise<{ path: string; size: number; bytes: Buffer }> {\n const res = await this.request<{ path: string; size: number; contentBase64: string }>(\n \"GET\",\n `${SANDBOXES}/${sid(sandboxId)}/file?path=${encodeURIComponent(filePath)}`,\n );\n return { path: res.path, size: res.size, bytes: Buffer.from(res.contentBase64, \"base64\") };\n }\n\n write(sandboxId: string, filePath: string, bytes: Buffer): Promise<{ path: string; size: number }> {\n return this.request(\"PUT\", `${SANDBOXES}/${sid(sandboxId)}/file`, {\n path: filePath,\n contentBase64: bytes.toString(\"base64\"),\n });\n }\n\n exec(\n sandboxId: string,\n input: { command: string; cwd?: string; timeoutMs?: number },\n ): Promise<SandboxExecResult> {\n return this.request(\"POST\", `${SANDBOXES}/${sid(sandboxId)}/exec`, input);\n }\n\n check(sandboxId: string): Promise<SandboxCheckResult> {\n return this.request(\"POST\", `${SANDBOXES}/${sid(sandboxId)}/check`, {});\n }\n\n /** With `rebase`, a moved base is replayed onto; a 409 then names the conflicting paths (`rebaseConflicts`). */\n commit(sandboxId: string, input: SandboxCommitInput): Promise<SandboxCommitResult> {\n const { rebase, ...rest } = input;\n return this.request(\"POST\", `${SANDBOXES}/${sid(sandboxId)}/commit`, rebase ? { ...rest, rebase: true } : rest);\n }\n\n /**\n * A rows file already in the sandbox tree into the PLATFORM world the\n * sandbox was opened on (201 with the version, 202 with the batch to poll,\n * 400 naming a refused row). Not `commit`: a commit versions the source\n * tree and never carries data.\n */\n importData(sandboxId: string, input: SandboxImportInput): Promise<SandboxImportResult | SandboxImportPending> {\n return this.request(\"POST\", `${SANDBOXES}/${sid(sandboxId)}/import`, input);\n }\n\n /** Uncommitted work is a 409 (`uncommittedPaths`) unless `force` discards it. */\n close(sandboxId: string, opts: { force?: boolean } = {}): Promise<SandboxSummary> {\n return this.request(\"DELETE\", `${SANDBOXES}/${sid(sandboxId)}`, opts.force ? { force: true } : undefined);\n }\n}\n","/**\n * `describeWorld(slug)` — what a world holds and how each field is stored,\n * from `GET /api/public/worlds/{slug}`: the entities (primary key, unique\n * keys, relationships, row count, fields with their `[redact]` policy) and\n * the `[redact]` table itself, so `storedForms(world, field, plaintext)`\n * can compute a lookup value without Python. The CLI twin is\n * `gateway worlds describe <slug>`; for a directory the CLI asks the schema\n * runtime instead and merges the same shape.\n */\n\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\nimport type { RedactPolicy, Redaction } from \"./redaction\";\nimport { parseSlugRef } from \"./sandbox\";\n\nexport type WorldField = {\n name: string;\n type: string | null;\n required: boolean;\n /** How the store holds it; null means in the clear (queryable by plaintext as given). */\n redaction: Redaction | null;\n};\n\nexport type WorldRelationship = {\n fields: string[];\n target: string;\n on_delete?: string;\n};\n\nexport type WorldEntityMapping = {\n localEntity: string;\n localField: string;\n depEntity: string;\n depField: string;\n /** A closed set, applied left to right before each world's own redaction. */\n transform: string[];\n};\n\nexport type WorldDependency = {\n alias: string;\n dependsOn: { slug: string | null; versionId: string };\n task: string | null;\n tools: string[];\n entities: WorldEntityMapping[];\n};\n\nexport type WorldEntity = {\n name: string;\n primaryKey: string[];\n unique: string[][];\n relationships: WorldRelationship[];\n /** Rows in the head version; null when the platform does not count this kind. */\n rowCount: number | null;\n fields: WorldField[];\n};\n\nexport type WorldDescription = {\n slug: string;\n name: string;\n description: string | null;\n kind: string;\n version: { id: string; contentHash: string; semanticVersion: string | null };\n url: string;\n hostedUrl: string | null;\n tools: { name: string; signature: string; doc: string | null }[];\n taskCount: number;\n links: { tasks: string; sessions: string };\n /** World-to-world links from `[dependencies]`, resolved at commit, with the\n * entity mappings `--across` follows. */\n dependencies?: WorldDependency[];\n entities: WorldEntity[];\n redact: RedactPolicy | null;\n};\n\n/** The world at `slug@ref`, described — `ref` is the one grammar shared with\n * pull/checkout/sandbox (`latest` | branch | tag | semver | version id | hash\n * prefix); a bare slug describes the head of `main`. An unknown ref is the\n * route's 404, never the head. */\nexport async function describeWorld(\n slugRef: string,\n options: WorldsClientOptions = {},\n): Promise<WorldDescription> {\n const { slug, ref } = parseSlugRef(slugRef);\n const query = ref === undefined ? \"\" : `?ref=${encodeURIComponent(ref)}`;\n return apiRequest<WorldDescription>(\n options,\n \"GET\",\n `/api/public/worlds/${encodeURIComponent(slug)}${query}`,\n );\n}\n","/**\n * JSON as the Python CLI sees it, so both CLIs write the same bytes.\n *\n * `JSON.parse` + `JSON.stringify` are not enough for parity with\n * `json.loads` + `json.dumps(separators=(\",\", \":\"), ensure_ascii=False)`:\n * JavaScript loses `1.0` vs `1` (Python keeps the float), rounds integers past\n * 2^53, moves integer-like keys to the front of an object, and spells\n * exponents differently (`1e-7` vs `1e-07`). Here a number keeps its source\n * text and its Python type, an object is a Map (insertion order, always), and\n * `dumps` renders exactly what CPython renders.\n */\n\nexport class JsonNumber {\n /** The lexeme as it appeared, e.g. \"1.0\", \"-0\", \"1e21\". */\n constructor(readonly text: string) {}\n /** A float in Python's eyes: a fraction, an exponent, or a non-finite literal. */\n get isFloat(): boolean {\n return /[.eE]/.test(this.text) || /[nN]/.test(this.text);\n }\n get value(): number {\n return Number(this.text);\n }\n}\n\nexport type JsonObject = Map<string, JsonValue>;\nexport type JsonValue = null | boolean | string | JsonNumber | JsonValue[] | JsonObject;\n\nexport class JsonSyntaxError extends Error {}\n\nexport const isObject = (value: JsonValue | undefined): value is JsonObject => value instanceof Map;\n\n// ------------------------------------------------------------------ parsing\n\n/** Parse one JSON text (a line, a row, a document) into the model above.\n * Accepts what `json.loads` accepts, including NaN/Infinity literals. */\nexport function parseJson(text: string): JsonValue {\n const p = new Parser(text);\n p.skipWs();\n const value = p.value();\n p.skipWs();\n if (p.i < text.length) throw new JsonSyntaxError(`Extra data at ${p.i}`);\n return value;\n}\n\nclass Parser {\n i = 0;\n constructor(readonly s: string) {}\n\n skipWs(): void {\n const s = this.s;\n while (this.i < s.length) {\n const c = s.charCodeAt(this.i);\n if (c === 0x20 || c === 0x0a || c === 0x0d || c === 0x09) this.i++;\n else break;\n }\n }\n\n fail(what: string): never {\n throw new JsonSyntaxError(`${what} at ${this.i}`);\n }\n\n value(): JsonValue {\n const s = this.s;\n if (this.i >= s.length) this.fail(\"Expecting value\");\n const c = s[this.i]!;\n if (c === \"{\") return this.object();\n if (c === \"[\") return this.array();\n if (c === '\"') return this.string();\n if (c === \"t\") return this.literal(\"true\", true);\n if (c === \"f\") return this.literal(\"false\", false);\n if (c === \"n\") return this.literal(\"null\", null);\n if (c === \"N\") return this.literal(\"NaN\", new JsonNumber(\"NaN\"));\n if (c === \"I\") return this.literal(\"Infinity\", new JsonNumber(\"Infinity\"));\n return this.number();\n }\n\n literal<T extends JsonValue>(word: string, value: T): T {\n if (!this.s.startsWith(word, this.i)) this.fail(\"Expecting value\");\n this.i += word.length;\n return value;\n }\n\n number(): JsonNumber {\n const s = this.s;\n const start = this.i;\n if (s[this.i] === \"-\") {\n this.i++;\n if (s.startsWith(\"Infinity\", this.i)) {\n this.i += 8;\n return new JsonNumber(\"-Infinity\");\n }\n }\n const intStart = this.i;\n if (s[this.i] === \"0\") this.i++;\n else {\n while (this.i < s.length && isDigit(s.charCodeAt(this.i))) this.i++;\n if (this.i === intStart) this.fail(\"Expecting value\");\n }\n if (s[this.i] === \".\") {\n this.i++;\n const fracStart = this.i;\n while (this.i < s.length && isDigit(s.charCodeAt(this.i))) this.i++;\n if (this.i === fracStart) this.fail(\"Invalid number\");\n }\n if (s[this.i] === \"e\" || s[this.i] === \"E\") {\n this.i++;\n if (s[this.i] === \"+\" || s[this.i] === \"-\") this.i++;\n const expStart = this.i;\n while (this.i < s.length && isDigit(s.charCodeAt(this.i))) this.i++;\n if (this.i === expStart) this.fail(\"Invalid number\");\n }\n return new JsonNumber(s.slice(start, this.i));\n }\n\n string(): string {\n const s = this.s;\n this.i++; // opening quote\n let out = \"\";\n let runStart = this.i;\n for (;;) {\n if (this.i >= s.length) this.fail(\"Unterminated string\");\n const c = s.charCodeAt(this.i);\n if (c === 0x22) {\n out += s.slice(runStart, this.i);\n this.i++;\n return out;\n }\n if (c < 0x20) this.fail(\"Invalid control character\");\n if (c !== 0x5c) {\n this.i++;\n continue;\n }\n out += s.slice(runStart, this.i);\n this.i++;\n const e = s[this.i];\n switch (e) {\n case '\"':\n case \"\\\\\":\n case \"/\":\n out += e;\n break;\n case \"b\":\n out += \"\\b\";\n break;\n case \"f\":\n out += \"\\f\";\n break;\n case \"n\":\n out += \"\\n\";\n break;\n case \"r\":\n out += \"\\r\";\n break;\n case \"t\":\n out += \"\\t\";\n break;\n case \"u\": {\n const hex = s.slice(this.i + 1, this.i + 5);\n if (!/^[0-9a-fA-F]{4}$/.test(hex)) this.fail(\"Invalid \\\\u escape\");\n out += String.fromCharCode(parseInt(hex, 16));\n this.i += 4;\n break;\n }\n default:\n this.fail(\"Invalid escape\");\n }\n this.i++;\n runStart = this.i;\n }\n }\n\n array(): JsonValue[] {\n this.i++;\n const out: JsonValue[] = [];\n this.skipWs();\n if (this.s[this.i] === \"]\") {\n this.i++;\n return out;\n }\n for (;;) {\n this.skipWs();\n out.push(this.value());\n this.skipWs();\n const c = this.s[this.i];\n if (c === \",\") {\n this.i++;\n continue;\n }\n if (c === \"]\") {\n this.i++;\n return out;\n }\n this.fail(\"Expecting ',' delimiter\");\n }\n }\n\n object(): JsonObject {\n this.i++;\n const out: JsonObject = new Map();\n this.skipWs();\n if (this.s[this.i] === \"}\") {\n this.i++;\n return out;\n }\n for (;;) {\n this.skipWs();\n if (this.s[this.i] !== '\"') this.fail(\"Expecting property name enclosed in double quotes\");\n const key = this.string();\n this.skipWs();\n if (this.s[this.i] !== \":\") this.fail(\"Expecting ':' delimiter\");\n this.i++;\n this.skipWs();\n out.set(key, this.value());\n this.skipWs();\n const c = this.s[this.i];\n if (c === \",\") {\n this.i++;\n continue;\n }\n if (c === \"}\") {\n this.i++;\n return out;\n }\n this.fail(\"Expecting ',' delimiter\");\n }\n }\n}\n\nconst isDigit = (c: number): boolean => c >= 0x30 && c <= 0x39;\n\n// ------------------------------------------------------------ serialising\n\n/** `json.dumps(value, separators=(\",\", \":\"), ensure_ascii=False)`, byte for byte. */\nexport function dumps(value: JsonValue): string {\n if (value === null) return \"null\";\n if (value === true) return \"true\";\n if (value === false) return \"false\";\n if (typeof value === \"string\") return JSON.stringify(value);\n if (value instanceof JsonNumber) return numberText(value);\n if (Array.isArray(value)) return \"[\" + value.map(dumps).join(\",\") + \"]\";\n const parts: string[] = [];\n for (const [key, item] of value) parts.push(JSON.stringify(key) + \":\" + dumps(item));\n return \"{\" + parts.join(\",\") + \"}\";\n}\n\n/** How `json.dumps` spells a parsed number: ints verbatim (`-0` becomes `0`),\n * floats through `float.__repr__`, non-finite as NaN/Infinity. */\nexport function numberText(n: JsonNumber): string {\n if (!n.isFloat) return /^-0+$/.test(n.text) ? \"0\" : n.text;\n const value = n.value;\n if (Number.isNaN(value)) return \"NaN\";\n if (value === Infinity) return \"Infinity\";\n if (value === -Infinity) return \"-Infinity\";\n return pyFloatRepr(value);\n}\n\n/** `str(value)` for the values the redaction digest sees: str, int, float, bool. */\nexport function pyStr(value: string | boolean | JsonNumber): string {\n if (typeof value === \"string\") return value;\n if (typeof value === \"boolean\") return value ? \"True\" : \"False\";\n if (!value.isFloat) return numberText(value);\n const v = value.value;\n if (Number.isNaN(v)) return \"nan\";\n if (v === Infinity) return \"inf\";\n if (v === -Infinity) return \"-inf\";\n return pyFloatRepr(v);\n}\n\n/**\n * CPython's `repr(float)`: the shortest digits that round-trip (which\n * JavaScript's `String(x)` also produces), laid out Python's way — a\n * trailing `.0` on integral values, scientific notation only below 1e-4 or\n * from 1e16, and exponents of at least two digits with a sign.\n */\nexport function pyFloatRepr(x: number): string {\n if (x === 0) return Object.is(x, -0) ? \"-0.0\" : \"0.0\";\n const sign = x < 0 ? \"-\" : \"\";\n const js = String(Math.abs(x));\n const [mantissa, exponentPart] = js.split(\"e\");\n let exponent = exponentPart ? Number(exponentPart) : 0;\n const [intPart, fracPart = \"\"] = mantissa!.split(\".\");\n let digits = intPart! + fracPart;\n // decpt: how many digits sit before the decimal point (may be <= 0 or > length).\n let decpt = intPart!.length + exponent;\n const leading = digits.match(/^0*/)![0].length;\n digits = digits.slice(leading);\n decpt -= leading;\n digits = digits.replace(/0+$/, \"\");\n if (digits === \"\") return sign + \"0.0\";\n const sci = decpt - 1;\n if (sci >= -4 && sci < 16) {\n if (decpt <= 0) return sign + \"0.\" + \"0\".repeat(-decpt) + digits;\n if (decpt >= digits.length) return sign + digits + \"0\".repeat(decpt - digits.length) + \".0\";\n return sign + digits.slice(0, decpt) + \".\" + digits.slice(decpt);\n }\n exponent = sci;\n const mag = String(Math.abs(exponent)).padStart(2, \"0\");\n return sign + digits[0] + (digits.length > 1 ? \".\" + digits.slice(1) : \"\") + \"e\" + (exponent < 0 ? \"-\" : \"+\") + mag;\n}\n\n/**\n * Python's `round(x, ndigits)` for the redaction policy: an int is returned\n * unchanged, a float is correctly rounded on its exact binary value with ties\n * to even (`round(0.125, 2) == 0.12`), then re-read as the nearest double.\n */\nexport function pyRound(n: JsonNumber, ndigits: number): JsonNumber {\n if (!n.isFloat) return n;\n const x = n.value;\n if (!Number.isFinite(x)) return n;\n const sign = x < 0 ? -1 : 1;\n const magnitude = Math.abs(x);\n // Every double at or above 2^53 is an integer already.\n if (magnitude >= 9007199254740992) return new JsonNumber(pyFloatRepr(x));\n const { m, k } = exactFraction(magnitude); // magnitude = m / 2^k, m odd (or zero)\n let rounded: number;\n if (k <= ndigits) rounded = magnitude; // exact at this precision\n else if (k !== ndigits + 1) rounded = Number(magnitude.toFixed(ndigits)); // no tie possible: correctly rounded\n else {\n // Exactly k = ndigits + 1 fractional digits, the last one a 5: a tie. Half to even.\n const scaled = m * 5n ** BigInt(k); // magnitude * 10^k, an integer\n let kept = scaled / 10n; // magnitude * 10^ndigits, truncated\n if (kept % 2n === 1n) kept += 1n;\n const text = kept.toString().padStart(ndigits + 1, \"0\");\n rounded = ndigits === 0 ? Number(text) : Number(text.slice(0, -ndigits) + \".\" + text.slice(-ndigits));\n }\n return new JsonNumber(pyFloatRepr(sign * rounded));\n}\n\n/** A finite non-negative double as m / 2^k with m odd (m = 0, k = 0 for zero). */\nfunction exactFraction(x: number): { m: bigint; k: number } {\n if (x === 0) return { m: 0n, k: 0 };\n const view = new DataView(new ArrayBuffer(8));\n view.setFloat64(0, x);\n const bits = view.getBigUint64(0);\n const exponent = Number((bits >> 52n) & 0x7ffn);\n let mantissa = bits & ((1n << 52n) - 1n);\n let e: number;\n if (exponent === 0) e = -1074;\n else {\n mantissa |= 1n << 52n;\n e = exponent - 1075;\n }\n while (mantissa !== 0n && (mantissa & 1n) === 0n) {\n mantissa >>= 1n;\n e += 1;\n }\n if (e >= 0) return { m: mantissa << BigInt(e), k: 0 };\n return { m: mantissa, k: -e };\n}\n","/**\n * Named plaintext transforms for cross-world entity mappings.\n *\n * A mapping between two worlds' fields is rarely a raw equality: SpyCloud\n * keeps `phone` as bare digits where a Torchlight client sends\n * `+1 (559) 779-1433`; one world keys people by `email`, another by\n * `email_username`. A transform normalises the plaintext on BOTH sides of a\n * mapping before `storedForms` salts it under each world's slug, so a\n * cross-world query is answerable from the plaintext alone, with no stored\n * join.\n *\n * The set is closed and named — no expressions, no user code — because any\n * client must reproduce a transform from the manifest by itself. This is the\n * TypeScript twin of the Python runtime's `environment/schema/transforms.py`;\n * the golden vectors in `__tests__/transforms.test.ts` and the Python\n * `tests/environment/test_schema_transforms.py` pin the two to each other,\n * byte for byte.\n *\n * Whitespace, for `trim` and `collapse_ws`, is the ASCII set `\" \\t\\n\\r\\f\\v\"`\n * by definition (Python's `str.split()` and JavaScript's `\\s` disagree at the\n * edges of Unicode; `nfkc` first folds a no-break space into a plain one).\n */\n\nimport { createHash } from \"node:crypto\";\n\nimport { pyFloatRepr } from \"../cli/platform/worldData/json\";\n\nexport type Transform = (value: string) => string;\n\nexport const WHITESPACE = \" \\t\\n\\r\\f\\v\";\nconst WHITESPACE_EDGES = new RegExp(`^[${WHITESPACE}]+|[${WHITESPACE}]+$`, \"g\");\nconst WHITESPACE_RUN = new RegExp(`[${WHITESPACE}]+`, \"g\");\nconst NOT_DIGIT = /[^0-9]/g;\n\nexport const STRIP_PREFIX = \"strip_prefix\";\n\nconst trim = (value: string): string => value.replace(WHITESPACE_EDGES, \"\");\n\nconst emailLocalPart = (value: string): string => {\n const at = value.lastIndexOf(\"@\");\n return at === -1 ? value : value.slice(0, at);\n};\n\nconst emailDomain = (value: string): string => {\n const at = value.lastIndexOf(\"@\");\n return at === -1 ? \"\" : value.slice(at + 1).toLowerCase();\n};\n\nconst stripPrefix =\n (prefix: string): Transform =>\n (value) =>\n value.startsWith(prefix) ? value.slice(prefix.length) : value;\n\nconst hex = (algorithm: \"sha1\" | \"sha256\", value: string): string =>\n createHash(algorithm).update(value, \"utf8\").digest(\"hex\");\n\nconst SIMPLE: Record<string, Transform> = {\n lower: (value) => value.toLowerCase(),\n upper: (value) => value.toUpperCase(),\n trim,\n collapse_ws: (value) => trim(value).replace(WHITESPACE_RUN, \" \"),\n nfkc: (value) => value.normalize(\"NFKC\"),\n digits: (value) => value.replace(NOT_DIGIT, \"\"),\n email_local_part: emailLocalPart,\n email_domain: emailDomain,\n // Vendor-style digests: lowercase hex of the utf-8 bytes, unsalted. This is\n // how SpyCloud accepts a hashed selector (`_digests` in its api_handlers).\n sha1: (value) => hex(\"sha1\", value),\n sha256: (value) => hex(\"sha256\", value),\n};\n\n/** The closed set, as a manifest spells it. `strip_prefix` takes its parameter\n * after a colon; the parameter may hold any character but `,`. */\nexport const TRANSFORMS: readonly string[] = [...Object.keys(SIMPLE), `${STRIP_PREFIX}:<prefix>`];\n\n/** The function a transform name denotes; throws when the name is not in the set. */\nexport function parseTransform(name: string): Transform {\n const simple = Object.prototype.hasOwnProperty.call(SIMPLE, name) ? SIMPLE[name] : undefined;\n if (simple) return simple;\n const colon = name.indexOf(\":\");\n if (colon !== -1) {\n const head = name.slice(0, colon);\n const prefix = name.slice(colon + 1);\n if (head === STRIP_PREFIX && prefix && !prefix.includes(\",\")) return stripPrefix(prefix);\n }\n throw new Error(`Unknown transform '${name}'; choose one of ${TRANSFORMS.join(\", \")}`);\n}\n\n/** `str(value)` as the Python runtime spells a number: an integral number is an\n * int, any other its float repr. */\nconst text = (value: string | number): string => {\n if (typeof value === \"string\") return value;\n return Number.isInteger(value) ? String(value) : pyFloatRepr(value);\n};\n\n/**\n * Compose `chain` left to right over `value`.\n *\n * A number is written as Python's `str()` first, the way `_digest` salts one,\n * so a number keyed on one side and a string on the other transform alike. The\n * whole chain is parsed before any step runs: a bad name at the end refuses\n * the mapping outright rather than after a partial result. An empty chain is\n * the identity.\n */\nexport function applyTransforms(value: string | number, chain: readonly string[]): string {\n const steps = chain.map(parseTransform);\n let out = text(value);\n for (const step of steps) out = step(out);\n return out;\n}\n","/**\n * Stored forms: what a world's store holds for a field given its plaintext.\n *\n * A schema world's `[redact]` table (connector.toml) rewrites named fields\n * before they reach disk — `hash` to a slug-salted sha256, `preserve` to a\n * shape-preserving digest, `round` to fewer decimals, `drop` to nothing. A\n * lookup by plaintext therefore has to compute the same form the store did.\n * This module is the TypeScript twin of the Python runtime's `_digest`,\n * `_shaped`, `redaction_of` and `stored_forms` (environment/schema/connector.py):\n * the rule is `\"sha256:\" + sha256(\"<slug>:<plaintext>\")`, no lowercasing, no\n * trimming, no other salt, and the golden vectors in redaction.test.ts pin the\n * two implementations to each other.\n */\n\nimport { createHash } from \"node:crypto\";\n\nimport { JsonNumber, pyFloatRepr, pyRound } from \"../cli/platform/worldData/json\";\nimport { applyTransforms } from \"./transforms\";\n\n/** The `[redact]` table as `describe` reports it (`connection.redact`, and\n * `redact` on `GET /api/public/worlds/{slug}`). */\nexport type RedactPolicy = {\n /** The digest salt: the connector's slug from connector.toml. It can differ\n * from the platform world slug (`spycloud` vs `spycloud-world`); `storedForms`\n * prefers it and falls back to the world slug only when it is absent. */\n slug?: string;\n hash: string[];\n drop: string[];\n preserve: string[];\n round: Record<string, number>;\n};\n\n/** The policy one field is stored under; null when it is stored in the clear. */\nexport type Redaction = \"hash\" | \"drop\" | \"preserve\" | `round:${number}`;\n\n/**\n * A value as the Python runtime would see it. JavaScript has one number\n * type, so an integral number takes Python's `int` path and any other number\n * its `float` path (`100` is `100`, never `100.0`); integers stay exact within\n * the safe range only.\n */\nexport type Plaintext = string | number;\n\nconst isInt = (value: Plaintext): value is number => typeof value === \"number\" && Number.isInteger(value);\n\n/** `str(value)` for an int or str, `repr(value)` for a float — the text the\n * Python runtime salts and shapes. */\nexport function pyText(value: Plaintext): string {\n if (typeof value === \"string\") return value;\n if (Number.isInteger(value)) return String(value);\n if (Number.isNaN(value)) return \"nan\";\n if (!Number.isFinite(value)) return value > 0 ? \"inf\" : \"-inf\";\n return pyFloatRepr(value);\n}\n\n/** The `hash` form: `\"sha256:\" + sha256(\"<slug>:<plaintext>\")` as hex. */\nexport function hashForm(slug: string, plaintext: Plaintext): string {\n return \"sha256:\" + createHash(\"sha256\").update(`${slug}:${pyText(plaintext)}`, \"utf8\").digest(\"hex\");\n}\n\n/**\n * The `preserve` form, the Python `_shaped`: the same length, every ASCII\n * digit still a digit, every ASCII letter still a letter of the same case,\n * everything else (separators, punctuation, non-ASCII) left in place. The\n * bytes come from sha256 of the seed `\"<slug>:<text>\"`, re-keyed as\n * sha256(digest + seed) once the 32 bytes are spent. A number keeps its type:\n * an int keeps its digit count (a leading zero is replaced), a float is re-read.\n */\nexport function preserveForm(slug: string, plaintext: Plaintext): Plaintext {\n const kind = typeof plaintext === \"string\" ? \"str\" : isInt(plaintext) ? \"int\" : \"float\";\n const shaped = shapeText(slug, pyText(plaintext), kind);\n return kind === \"str\" ? shaped : Number(shaped);\n}\n\n/** The shaping itself, on text: `kind` says which of Python's rules apply\n * (letters are re-lettered for a str only; an int keeps its digit count). */\nexport function shapeText(slug: string, text: string, kind: \"str\" | \"int\" | \"float\"): string {\n const seed = Buffer.from(`${slug}:${text}`, \"utf8\");\n let digest = createHash(\"sha256\").update(seed).digest();\n let cursor = 0;\n const out: string[] = [];\n for (const char of text) {\n if (cursor === digest.length) {\n digest = createHash(\"sha256\").update(Buffer.concat([digest, seed])).digest();\n cursor = 0;\n }\n const byte = digest[cursor]!;\n cursor += 1;\n if (char >= \"0\" && char <= \"9\") out.push(String(byte % 10));\n else if (kind === \"str\" && char >= \"a\" && char <= \"z\") out.push(String.fromCharCode(97 + (byte % 26)));\n else if (kind === \"str\" && char >= \"A\" && char <= \"Z\") out.push(String.fromCharCode(65 + (byte % 26)));\n else out.push(char);\n }\n // An int keeps its digit count; int() would drop a leading zero.\n if (kind === \"int\" && out.length > 1 && out[0] === \"0\") out[0] = String(1 + (digest[0]! % 9));\n return out.join(\"\");\n}\n\n/** The `round` form: Python's `round(value, decimals)` — an int unchanged, a\n * float correctly rounded with ties to even; a string is not a number and\n * passes through as the runtime leaves it. */\nexport function roundForm(plaintext: Plaintext, decimals: number): Plaintext {\n if (typeof plaintext === \"string\" || isInt(plaintext) || !Number.isFinite(plaintext)) return plaintext;\n return pyRound(new JsonNumber(pyFloatRepr(plaintext)), decimals).value;\n}\n\n/**\n * The policy a field of this name falls under, ranked as the runtime applies\n * them (drop, hash, preserve, round). Read without a path: a bare name in the\n * table counts, and so does a dotted path whose last segment is the field.\n */\nexport function redactionOf(redact: RedactPolicy | null | undefined, field: string): Redaction | null {\n if (!redact) return null;\n const named = (names: string[] | undefined) =>\n (names ?? []).some((name) => name === field || name.slice(name.lastIndexOf(\".\") + 1) === field);\n if (named(redact.drop)) return \"drop\";\n if (named(redact.hash)) return \"hash\";\n if (named(redact.preserve)) return \"preserve\";\n const decimals = redact.round?.[field];\n if (typeof decimals === \"number\") return `round:${decimals}`;\n return null;\n}\n\n/**\n * Every value the store may hold for `field` given this plaintext:\n *\n * clear field -> [plaintext]\n * hash -> [\"sha256:<hex>\"]\n * preserve -> [the shape-preserving digest]\n * round -> [round(plaintext, decimals)] for a number, [plaintext] otherwise\n * drop -> [] (the field is not on disk: a documented miss, not an error)\n *\n * `world` is what `describeWorld` / the bridge's `describe` return: the slug\n * is the salt, `redact` the table.\n *\n * `transform` — a cross-world mapping's chain (`./transforms`) — runs over the\n * plaintext FIRST, so `hash` and `preserve` salt the normalised text; omitted\n * (or empty) is today's behaviour, byte for byte.\n */\nexport function storedForms(\n world: { slug: string; redact?: RedactPolicy | null },\n field: string,\n plaintext: Plaintext,\n transform?: readonly string[],\n): Plaintext[] {\n if (transform?.length) plaintext = applyTransforms(plaintext, transform);\n const policy = redactionOf(world.redact, field);\n const salt = world.redact?.slug ?? world.slug;\n if (policy === \"drop\") return [];\n if (policy === \"hash\") return [hashForm(salt, plaintext)];\n if (policy === \"preserve\") return [preserveForm(salt, plaintext)];\n if (policy !== null) return [roundForm(plaintext, world.redact!.round[field]!)];\n return [plaintext];\n}\n","/**\n * `queryRows(slug[@ref], entity, {where, resolve, limit, offset})` — the rows\n * of one entity that match a predicate, from\n * `GET /api/public/worlds/{slug}/data?ref=&entity=&where=&limit=&offset=&resolve=`.\n * `where` is field → value, or field → list of values (any of); values match\n * the STORED form as given. With `resolve: true` the values are plaintext and\n * the runtime maps each to its stored form under the world's `[redact]`\n * policy first (a hashed `email` becomes its slug-salted digest; a dropped\n * field resolves to nothing and matches no row — the answer's `resolved`\n * says so). The CLI twin is `gateway worlds data query <slug> <entity>`.\n *\n * `across: true` runs the same plaintext in every world this one links to\n * whose `[dependencies.<alias>.entities]` mapping covers a `where` field;\n * each linked world recomputes its own stored form (after the mapping's\n * transform) at query time — no join on disk, no shared salt. The answer\n * is then {@link WorldQueryAcrossResult}: one group per world, the root\n * first, and with `compare: true` a parity report saying, per field and\n * per world, `matched`, `no match` or `unmapped`.\n */\n\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\nimport type { Plaintext } from \"./redaction\";\n\nexport type WorldQueryWhere = Record<string, Plaintext | Plaintext[]>;\n\nexport type WorldQueryOptions = {\n where?: WorldQueryWhere;\n /** The `where` values are plaintext: resolve each to its stored form before matching. */\n resolve?: boolean;\n limit?: number;\n offset?: number;\n /** Query the linked worlds too; the answer becomes groups. */\n across?: boolean;\n /** With `across`: add the parity report. */\n compare?: boolean;\n};\n\n/** The options that make `queryRows` answer {@link WorldQueryAcrossResult}. */\nexport type WorldQueryAcrossOptions = WorldQueryOptions & { across: true };\n\nexport type WorldQueryResult = {\n slug: string;\n versionId: string;\n kind: string | null;\n entity: string;\n rows: Record<string, unknown>[];\n /** Rows in this page. */\n count: number;\n /** Rows matching in all; null when the store does not count them. */\n total: number | null;\n limit: number;\n offset: number;\n /** With `resolve`: the stored forms each `where` field was matched against\n * (`[]` for a dropped field, which is why such a query matches nothing). */\n resolved?: Record<string, Plaintext[]>;\n entityCounts: Record<string, number>;\n snapshot: WorldQuerySnapshot | null;\n};\n\nexport type WorldQuerySnapshot = {\n snapshotId: string;\n contractHash: string;\n batchDigest: string;\n bytes: number;\n};\n\n/** One world's page inside an across answer: the root (`alias: null`, no\n * `mapping`) or a linked world with the mappings that carried the root's\n * `where` fields into its own entity. */\nexport type WorldQueryGroup = {\n world: { slug: string; alias: string | null; versionId: string };\n entity: string;\n rows: Record<string, unknown>[];\n count: number;\n total: number | null;\n limit: number;\n offset: number;\n resolved?: Record<string, Plaintext[]>;\n mapping?: { field: string; depField: string; transform: string[] }[];\n};\n\nexport type WorldQueryCompareStatus = \"matched\" | \"no match\" | \"unmapped\";\n\n/** Per `where` field, per world: whether the field reached the world and\n * whether any row matched there; `present`/`absent` list the worlds by slug. */\nexport type WorldQueryCompare = {\n present: string[];\n absent: string[];\n perField: {\n field: string;\n worlds: {\n world: string;\n alias: string | null;\n status: WorldQueryCompareStatus;\n /** `<depEntity>.<depField>` and the transform applied (mapped worlds only). */\n depField?: string;\n transform?: string[];\n }[];\n }[];\n};\n\nexport type WorldQueryAcrossResult = {\n slug: string;\n versionId: string;\n kind: string | null;\n entity: string;\n /** The root world first, then one per linked world that was queried. */\n groups: WorldQueryGroup[];\n compare?: WorldQueryCompare;\n entityCounts: Record<string, number>;\n snapshot: WorldQuerySnapshot | null;\n};\n\n/** The query string the route reads; `where` travels as URL-encoded JSON and\n * `ref` (the `@ref` of `slug@ref`) picks the version. */\nexport function queryRowsSearch(entity: string, opts: WorldQueryOptions = {}, ref?: string): string {\n const search = new URLSearchParams();\n if (ref) search.set(\"ref\", ref);\n search.set(\"entity\", entity);\n if (opts.where && Object.keys(opts.where).length) search.set(\"where\", JSON.stringify(opts.where));\n if (opts.limit !== undefined) search.set(\"limit\", String(opts.limit));\n if (opts.offset !== undefined) search.set(\"offset\", String(opts.offset));\n if (opts.resolve) search.set(\"resolve\", \"true\");\n if (opts.across) search.set(\"across\", \"true\");\n if (opts.compare) search.set(\"compare\", \"true\");\n return `?${search.toString()}`;\n}\n\n/** One version of the world, queried: the main tip for a bare slug, or the\n * version `slug@ref` names (branch, tag, semver pin or hash prefix — the\n * `bench pull` grammar; a ref nothing answers to is the platform's 404, never\n * the head). With `across: true` the answer is the groups shape. */\nexport async function queryRows(\n slug: string,\n entity: string,\n opts: WorldQueryAcrossOptions,\n options?: WorldsClientOptions,\n): Promise<WorldQueryAcrossResult>;\nexport async function queryRows(\n slug: string,\n entity: string,\n opts?: WorldQueryOptions,\n options?: WorldsClientOptions,\n): Promise<WorldQueryResult>;\nexport async function queryRows(\n slugRef: string,\n entity: string,\n opts: WorldQueryOptions = {},\n options: WorldsClientOptions = {},\n): Promise<WorldQueryResult | WorldQueryAcrossResult> {\n const [slug, ref] = slugRef.split(\"@\", 2) as [string, string | undefined];\n if (!slug || ref === \"\") throw new Error(`queryRows needs a slug, optionally slug@ref (got ${slugRef})`);\n if (!entity) throw new Error(\"queryRows needs an entity\");\n if (opts.compare && !opts.across) throw new Error(\"queryRows: compare needs across\");\n return apiRequest<WorldQueryResult | WorldQueryAcrossResult>(\n options,\n \"GET\",\n `/api/public/worlds/${encodeURIComponent(slug)}/data${queryRowsSearch(entity, opts, ref)}`,\n );\n}\n","/**\n * `migrateWorld(slug)` — convert a stored world into a schema world, from\n * `POST /api/public/worlds/{slug}/migrate`; `migrateProjectWorlds()` plans\n * (or migrates) every connector world in the project from\n * `POST /api/public/worlds/migrate`. Dry run by default: the report says\n * what the version is, what the conversion does, or why it cannot; `apply`\n * commits the migrated tree as the next version (\"Migrated to a schema\n * world\"). Targets are the platform's connector worlds; a hand-built world\n * needs `force`. The CLI twin is `gateway worlds migrate`.\n */\n\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\n\nexport type WorldMigrationRefusal = {\n code: string;\n message: string;\n /** Paths the conversion needed and did not find. */\n missing: string[];\n};\n\nexport type WorldMigrationReport = {\n slug: string;\n containerId: string;\n versionId: string;\n /** True when the container was created from a connector template. */\n connectorWorld: boolean;\n /** schema | api-bundle | legacy-tools | harbor | verifiers */\n shape: string;\n target: \"schema\";\n /** True when the world already is a schema world. */\n unchanged: boolean;\n /** The dry-run report, one sentence each. */\n actions: string[];\n /** Files the migrated tree holds; 0 on a refusal. */\n files: number;\n refusal: WorldMigrationRefusal | null;\n /** True when this call committed the migrated tree. */\n applied: boolean;\n version: { id: string; contentHash: string } | null;\n};\n\nexport type MigrateWorldOptions = {\n /** Commit the migrated tree as the next version. Default false: dry run. */\n apply?: boolean;\n /** Migrate a world that was not created from a connector template. */\n force?: boolean;\n};\n\nexport async function migrateWorld(\n slug: string,\n input: MigrateWorldOptions = {},\n options: WorldsClientOptions = {},\n): Promise<WorldMigrationReport> {\n if (slug.includes(\"@\"))\n throw new Error(\n `migrateWorld converts a world's head version: pass the slug without @ref (got ${slug})`,\n );\n return apiRequest<WorldMigrationReport>(\n options,\n \"POST\",\n `/api/public/worlds/${encodeURIComponent(slug)}/migrate`,\n {\n ...(input.apply === undefined ? {} : { apply: input.apply }),\n ...(input.force === undefined ? {} : { force: input.force }),\n },\n );\n}\n\n/** Every connector world in the project, one report each. */\nexport async function migrateProjectWorlds(\n input: { apply?: boolean } = {},\n options: WorldsClientOptions = {},\n): Promise<{ worlds: WorldMigrationReport[]; applied: boolean }> {\n return apiRequest<{ worlds: WorldMigrationReport[]; applied: boolean }>(\n options,\n \"POST\",\n \"/api/public/worlds/migrate\",\n input.apply === undefined ? {} : { apply: input.apply },\n );\n}\n","/**\n * Records into a world's rows — the record contract, an interceptor that\n * writes it, the conversion from TOOL observations, and the door in.\n *\n * A tool's response is not the entity's shape, and nothing here assumes it\n * is. The workflow with real data is: pull the raw tool calls, look at them,\n * then ingest them through the route you declare — {@link ingest} with a\n * `transform` (your own `transform(records) -> {entity: [rows]}`, a function\n * or a script), with a `map` (an `ingest.toml` mapping for shapes that need\n * no code), or with neither, when the world's own `ingest.toml` applies or\n * each record's tool is a connector operation whose result *is* the\n * operation's response body (its `[ingest]` projection in `connector.toml`).\n * Mappings and projections run in the schema runtime (Python, bundled with\n * the CLI or on the platform), never re-implemented here; a transform runs\n * where you are.\n *\n * The record, one JSON object per line:\n *\n * {\"tool\": \"list_users\", \"args\": {\"team\": \"t1\"}, \"result\": {\"users\": [...]},\n * \"at\": \"2026-09-15T10:00:00Z\", \"session\": \"optional\", \"source\": \"optional free text\"}\n *\n * A `gateway worlds session export` line (`{seq, kind, tool, args, result,\n * error, completedAt}`) is accepted as it is. Redaction is optional and OFF\n * by default everywhere here: rows land as the tools returned them unless\n * `redact: \"apply\"` (the world's `[redact]` policy) or `\"refuse\"` is asked for.\n *\n * - {@link captureToolCalls} wraps an agent's tool functions so every real\n * call is recorded — the agent changes nothing.\n * - {@link toolCallsFromObservations} turns a trace's TOOL observations into\n * records (the `--from traces` path of `gateway worlds data ingest`).\n * - {@link ingest} puts records into a world through a transform, a mapping\n * or the operations: a local directory through the bundled runtime, a\n * platform slug through the batch lane. {@link ingestToolCalls} is the same\n * door with neither transform nor mapping of your own.\n */\n\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\n\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\n\nexport type ToolCallRecord = {\n /** The operation name in the world's `connector.toml`. */\n tool: string;\n /** The call's arguments, by name: what `carry_args` reads. */\n args: Record<string, unknown>;\n /** The operation's response body, as the tool returned it. */\n result?: unknown;\n /** ISO time of the call. */\n at?: string;\n /** The session the call belongs to, when there is one. */\n session?: string;\n /** Free text: where the record came from. */\n source?: string;\n /** Set instead of `result` when the call threw; ingest skips it, counted. */\n error?: string;\n};\n\nexport type RedactMode = \"off\" | \"apply\" | \"refuse\";\nexport type IngestMode = \"append\" | \"replace\";\n\n// ---------------------------------------------------------------- the mapping\n\n/** How one entity field is set: an item path, or a table naming exactly one of `from`, `literal`, `template`, `hash`. */\nexport type IngestFieldSpec =\n | string\n | {\n /** Item path (`name`, `customer.id`, `emails[0]`); `$`-paths reach the record: `$tool`, `$at`, `$index`, `$session`, `$source`, `$source.id`, `$source.trace`, `$record.<path>`, `$parent.<path>`. */\n from?: string;\n literal?: string | number | boolean;\n /** `{path}` holes are filled from the item or the record; a hole with no value refuses the record. */\n template?: string;\n /** sha256 of the JSON array of these paths' values; unset when any is missing. */\n hash?: string[];\n /** A chain from the closed transform set, applied to `from` or `template`. */\n transform?: string[];\n /** Used when `from` is missing or null. */\n default?: string | number | boolean;\n /** Coerce the value; a CSV cell is text until this says otherwise. */\n type?: \"string\" | \"integer\" | \"number\" | \"boolean\";\n };\n\nexport type IngestExplode = {\n /** Item path to a list (or one object) of children. */\n path: string;\n entity: string;\n /** child field <- parent ENTITY field (after the parent's mapping). */\n carry?: Record<string, string>;\n fields?: Record<string, IngestFieldSpec>;\n};\n\nexport type IngestSource = {\n /** The tool name (or several), or `\"*\"` for rows and csv records. */\n name: string | string[];\n kind?: \"tool-call\" | \"rows\" | \"csv\";\n /** Path into the record: `result`, `result.data[*]`, `args`, `$record`. */\n select: string;\n /** All must hold on the selected item: a literal, or `{ present: true | false }`. */\n when?: Record<string, string | number | boolean | { present: boolean }>;\n entity: string;\n /** Item path that dates the row for `on_conflict`; default the record's `at`. */\n at?: string;\n fields?: Record<string, IngestFieldSpec>;\n explode?: IngestExplode[];\n};\n\n/** `ingest.toml`, parsed: the grammar the schema runtime's `mapping.py` checks and applies. */\nexport type IngestMapping = {\n ingest?: { on_conflict?: \"latest\" | \"first\"; unmatched?: \"refuse\" | \"skip\" };\n sources: IngestSource[];\n};\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n// ---------------------------------------------------------------- records\n\nexport type ParsedToolCall = {\n /** The record in the contract's shape, when it is a tool call with a result. */\n record: ToolCallRecord | null;\n /** Why a well-formed record carries no rows by design (a `seed` line, a failed call). */\n skip: string | null;\n /** What is wrong with the record. */\n refusal: string | null;\n};\n\n/**\n * One raw record — the contract's shape or a session-export line — judged the\n * way the runtime judges it (`ingest.normalize_record`): the same skips, the\n * same refusals, so a file checked here is what the runtime will accept.\n */\nexport function parseToolCallRecord(raw: unknown): ParsedToolCall {\n const none = { record: null, skip: null };\n if (!isObject(raw)) return { ...none, refusal: \"record is not an object\" };\n const kind = raw.kind;\n if (kind !== undefined && kind !== null && kind !== \"call\") return { record: null, skip: `kind ${String(kind)}`, refusal: null };\n const tool = raw.tool;\n if (typeof tool !== \"string\" || !tool) return { ...none, refusal: \"record has no tool name\" };\n if (raw.error !== undefined && raw.error !== null && raw.error !== \"\") return { record: null, skip: \"call failed\", refusal: null };\n const args = raw.args ?? {};\n if (!isObject(args)) return { ...none, refusal: `args of ${tool} is not an object` };\n if (!(\"result\" in raw)) return { ...none, refusal: `record of ${tool} has no result` };\n const at = raw.at ?? raw.completedAt;\n const record: ToolCallRecord = { tool, args, result: raw.result };\n if (typeof at === \"string\") record.at = at;\n if (typeof raw.session === \"string\") record.session = raw.session;\n if (typeof raw.source === \"string\") record.source = raw.source;\n return { record, skip: null, refusal: null };\n}\n\n/**\n * Raw records from files: JSONL (one object per line) or one JSON array, several\n * files concatenated in order. A line that is not JSON, or not an object, throws\n * naming the file and line. Each record's shape is judged later, per record, so\n * the report can point at the index.\n */\nexport function readToolCallRecords(paths: string[]): unknown[] {\n const records: unknown[] = [];\n for (const file of paths) records.push(...toolCallRecordsIn(fs.readFileSync(file, \"utf8\"), file));\n return records;\n}\n\n/** The records in one text, named `where` in a refusal. */\nexport function toolCallRecordsIn(text: string, where: string): unknown[] {\n const stripped = text.trim();\n if (!stripped) return [];\n if (stripped.startsWith(\"[\")) {\n const listed = JSON.parse(stripped) as unknown;\n if (!Array.isArray(listed)) throw new Error(`${where} is neither a JSON array nor JSON Lines`);\n listed.forEach((item, index) => {\n if (!isObject(item)) throw new Error(`${where}[${index}] is not an object`);\n });\n return listed;\n }\n const records: unknown[] = [];\n const lines = text.split(/\\r?\\n/);\n for (let index = 0; index < lines.length; index++) {\n const line = lines[index]!;\n if (!line.trim()) continue;\n let item: unknown;\n try {\n item = JSON.parse(line);\n } catch {\n throw new Error(`${where}:${index + 1} is not JSON`);\n }\n if (!isObject(item)) throw new Error(`${where}:${index + 1} is not an object`);\n records.push(item);\n }\n return records;\n}\n\n// ---------------------------------------------------------------- capture\n\n/**\n * Where {@link captureToolCalls} writes each record: an array (pushed), a file\n * path (JSONL, one record per line, appended), or a callback (awaited).\n */\nexport type ToolCallSink = ToolCallRecord[] | string | ((record: ToolCallRecord) => unknown | Promise<unknown>);\n\nexport type ToolFunctions = Record<string, (args: Record<string, unknown>) => Promise<unknown>>;\n\nasync function emit(sink: ToolCallSink, record: ToolCallRecord): Promise<void> {\n if (Array.isArray(sink)) {\n sink.push(record);\n return;\n }\n if (typeof sink === \"string\") {\n fs.appendFileSync(sink, JSON.stringify(record) + \"\\n\");\n return;\n }\n if (typeof sink === \"function\") {\n await sink(record);\n return;\n }\n throw new TypeError(\"sink must be an array, a file path, or a function\");\n}\n\n/**\n * Wrap a name → async function map — the shape the Vercel AI SDK's tools and a\n * `WorldToolkit`'s `impls` share — so every call is recorded as a tool-call\n * record into `sink`, and hand back the same map. The agent changes nothing:\n * each wrapped function returns what the original returned, and an error is\n * thrown through untouched (recorded with `error` and no `result`, which\n * ingest skips and counts). Nothing is redacted here; redaction is optional\n * and off by default on the ingest side.\n *\n * const tools = captureToolCalls({ list_users: realVendor.listUsers }, \"calls.jsonl\");\n * await runMyAgent(tools); // real vendor, every call recorded\n * await ingestToolCalls(\"acme-crm\", readToolCallRecords([\"calls.jsonl\"]));\n */\nexport function captureToolCalls<T extends ToolFunctions>(\n tools: T,\n sink: ToolCallSink,\n opts: { session?: string; source?: string } = {},\n): T {\n const wrapped: ToolFunctions = Object.create(null);\n for (const [name, fn] of Object.entries(tools)) {\n wrapped[name] = async (args: Record<string, unknown> = {}) => {\n const record: ToolCallRecord = { tool: name, args, at: new Date().toISOString() };\n if (opts.session) record.session = opts.session;\n if (opts.source) record.source = opts.source;\n let result: unknown;\n try {\n result = await fn(args);\n } catch (error) {\n record.error = error instanceof Error ? error.message || error.name : String(error);\n await emit(sink, record);\n throw error;\n }\n record.result = result;\n await emit(sink, record);\n return result;\n };\n }\n return wrapped as T;\n}\n\n// ---------------------------------------------------------------- observations\n\n/** What a TOOL observation carries, as `GET /api/public/observations` and\n * `GET /api/public/sessions/{id}?includeIO=true` return it. Both routes decode\n * stored JSON text once on the way out (`parseIoAsJson` defaults to true on the\n * v1 route; the session route renders with the same default), so `input` and\n * `output` arrive as the values the tool saw — an object, or a string when the\n * tool really produced text. Nothing here parses them again. */\nexport type ObservationLike = {\n id?: string;\n traceId?: string | null;\n type?: string;\n name?: string | null;\n input?: unknown;\n output?: unknown;\n startTime?: string | Date;\n level?: string;\n statusMessage?: string | null;\n};\n\nexport type ObservationConversion = {\n records: ToolCallRecord[];\n /** TOOL observations whose name is not one of the world's operations, by name. */\n unknownTools: Record<string, number>;\n /** Observations that were not converted, by reason. */\n skipped: Record<string, number>;\n};\n\nconst isoOf = (value: string | Date | undefined): string | undefined =>\n value instanceof Date ? value.toISOString() : typeof value === \"string\" ? value : undefined;\n\n/**\n * TOOL observations → tool-call records: `name` is the tool, `input` the args,\n * `output` the result, `startTime` the time, `trace:<traceId>/<id>` the source.\n * `input`/`output` arrive from the public API already decoded (it parses the\n * stored text once), so they are taken as they are: a string `output` stays a\n * string even when it looks like JSON; an `input` that is not an object leaves\n * `args` empty rather than guessed.\n * Only `type: \"TOOL\"` converts. With `tools` (the world's operation names) an\n * observation for any other tool is counted in `unknownTools`, not converted.\n * An `ERROR`-level observation converts with `error` set, so ingest counts it\n * as a failed call instead of projecting its output.\n */\nexport function toolCallsFromObservations(\n observations: ObservationLike[],\n opts: { tools?: Iterable<string> | null; session?: string; since?: string } = {},\n): ObservationConversion {\n const known = opts.tools ? new Set(opts.tools) : null;\n const sinceMs = opts.since ? Date.parse(opts.since) : NaN;\n const out: ObservationConversion = { records: [], unknownTools: {}, skipped: {} };\n const skip = (reason: string) => {\n out.skipped[reason] = (out.skipped[reason] ?? 0) + 1;\n };\n for (const observation of observations) {\n if (observation.type !== \"TOOL\") {\n skip(`type ${observation.type ?? \"unknown\"}`);\n continue;\n }\n const tool = observation.name;\n if (typeof tool !== \"string\" || !tool) {\n skip(\"no name\");\n continue;\n }\n const at = isoOf(observation.startTime);\n if (!Number.isNaN(sinceMs) && at !== undefined && Date.parse(at) < sinceMs) {\n skip(\"before since\");\n continue;\n }\n if (known && !known.has(tool)) {\n out.unknownTools[tool] = (out.unknownTools[tool] ?? 0) + 1;\n continue;\n }\n const record: ToolCallRecord = { tool, args: isObject(observation.input) ? observation.input : {} };\n if (observation.level === \"ERROR\") record.error = observation.statusMessage || \"ERROR\";\n else record.result = observation.output;\n if (at !== undefined) record.at = at;\n if (opts.session) record.session = opts.session;\n record.source = `trace:${observation.traceId ?? \"?\"}/${observation.id ?? \"?\"}`;\n out.records.push(record);\n }\n return out;\n}\n\n// ---------------------------------------------------------------- the door\n\nexport type IngestRefusal = { index: number | null; tool: string | null; reason: string; pointer?: string };\n\n/** One `[[sources]]` of a mapping in the report. */\nexport type IngestSourceReport = {\n name: string;\n kind: string;\n select: string;\n entity: string;\n records: number;\n items: number;\n rows: Record<string, number>;\n /** Source fields no line of the source reads, with a sample value. */\n unmappedFields: Record<string, string>;\n /** Entity fields the source never sets, per entity. */\n unsetFields: Record<string, string[]>;\n};\n\nexport type IngestToolCallsReport = {\n world: string;\n /** How the rows were produced. */\n via?: \"transform\" | \"map\" | \"operations\" | \"rows\";\n /** `via: \"map\"`: each source's accounting. */\n sources?: IngestSourceReport[];\n /** `via: \"map\"` with `unmatched = \"skip\"`: records no source claimed, by tool name. */\n unmatched?: Record<string, number>;\n /** `via: \"operations\"`: that this was the operation projection, not a mapping. */\n note?: string;\n /** `via: \"transform\"`: what the script wrote to stderr. */\n stderr?: string;\n /** Records given. */\n records: number;\n /** Records that yielded rows. */\n ingested: number;\n /** Records that carried no rows by design, by reason. */\n skipped: Record<string, number>;\n /** What was wrong, per record; with any, nothing was written. */\n refusals: IngestRefusal[];\n /** Rows projected, per entity. */\n rows: Record<string, number>;\n dryRun: boolean;\n redact: RedactMode;\n changed: boolean;\n kind?: string;\n entityCounts?: Record<string, number>;\n /** A slug that was pushed: the batch's final status (`state`, `versionId`, …). */\n batch?: Record<string, unknown>;\n};\n\nexport type IngestToolCallsOptions = WorldsClientOptions & {\n /** Optional, default `\"off\"`: rows land as the tools returned them. */\n redact?: RedactMode;\n /** Project and prove the rows; write and upload nothing. */\n dryRun?: boolean;\n mode?: IngestMode;\n /** Change reason for the version a slug cuts. */\n message?: string;\n};\n\nexport type IngestReport = IngestToolCallsReport;\n\nexport type IngestOptions = IngestToolCallsOptions & {\n /** Your own `transform(records) -> {entity: [rows]}`: a function (run here) or a script path (`.py`, `.ts`, `.mjs`; a subprocess with a time limit and sockets disabled). */\n transform?: string | ((records: unknown[]) => Rows | Promise<Rows>);\n /** An `ingest.toml` mapping: its text, or the parsed table. Exclusive with `transform`. */\n map?: string | IngestMapping;\n /** For a script transform; default 120 000. */\n timeoutMs?: number;\n};\n\ntype Rows = Record<string, Record<string, unknown>[]>;\n\nfunction credentialsOf(options: WorldsClientOptions): { host: string; publicKey: string; secretKey: string } | null {\n const host = (options.host ?? process.env.GATEWAY_HOST ?? \"https://withgateway.ai\").replace(/\\/+$/, \"\");\n const publicKey = options.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;\n const secretKey = options.secretKey ?? process.env.GATEWAY_SECRET_KEY;\n return publicKey && secretKey ? { host, publicKey, secretKey } : null;\n}\n\n/**\n * Records into a world through the route you declare. `world` is a local\n * directory (written in place through the bundled schema runtime) or a\n * platform slug (pulled to a temporary directory, the rows produced and\n * proven there, then pushed through the chunked batch lane as a new version).\n *\n * With `transform` the rows are what your code returns; with `map` (or the\n * world's own `ingest.toml`) what the mapping declares; with neither, each\n * tool-call record's tool resolves to an operation of `connector.toml` and\n * its result goes through that operation's `[ingest]` projection (the report\n * says `via: \"operations\"`). A transform that fails or returns the wrong\n * shape throws. `redact` is optional and defaults to `\"off\"`.\n */\nexport async function ingest(world: string, records: unknown[], options: IngestOptions = {}): Promise<IngestReport> {\n const { ingestLocalToolCalls, importLocalWorldData, checkLocalWorldData } = await import(\"../cli/runtime/data\");\n if (options.transform !== undefined && options.map !== undefined) throw new Error(\"records go through one of transform, map\");\n const redact = options.redact ?? \"off\";\n const mode = options.mode ?? \"append\";\n const dryRun = Boolean(options.dryRun);\n const creds = credentialsOf(options);\n const local = fs.existsSync(world) && fs.statSync(world).isDirectory();\n const map = options.map === undefined ? undefined : options.map;\n\n let rows: Rows | null = null;\n let stderr = \"\";\n if (options.transform !== undefined) {\n const { transformRecords } = await import(\"../cli/platform/worldData/transform\");\n ({ rows, stderr } = await transformRecords(options.transform, records, { timeoutMs: options.timeoutMs }));\n }\n\n if (local) {\n if (rows === null) return reportOf(world, await ingestLocalToolCalls(world, records, { redact, dryRun, mode, map }, creds), redact);\n const landed = dryRun ? await checkLocalWorldData(world, rows, creds, { redact }) : await importLocalWorldData(world, rows, { mode, redact }, creds);\n return transformReport(world, records.length, rows, stderr, { dryRun, redact, changed: !dryRun && landed.changed, kind: landed.kind, entityCounts: landed.entity_counts });\n }\n if (!creds) throw new Error(\"Gateway keys missing: set GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY (or pass publicKey/secretKey).\");\n const { pull } = await import(\"./hub\");\n const slug = world.split(\"@\", 1)[0]!;\n const scratch = fs.mkdtempSync(path.join(os.tmpdir(), \"gateway-ingest-\"));\n try {\n const pulled = await pull(world, path.join(scratch, slug), options);\n // Produced and proven against the pulled contract; the platform's batch\n // lane checks every row again and redacts there, so this pass runs with\n // redaction off and hands the rows on as they were produced.\n let report: IngestReport;\n let projected: Rows;\n if (rows === null) {\n const proven = await ingestLocalToolCalls(pulled.dir, records, { redact: \"off\", dryRun: true, mode, map }, creds);\n report = reportOf(world, proven, redact);\n projected = proven.projected ?? {};\n } else {\n const proven = await checkLocalWorldData(pulled.dir, rows, creds);\n report = transformReport(world, records.length, rows, stderr, { dryRun, redact, changed: false, kind: proven.kind, entityCounts: proven.entity_counts });\n projected = rows;\n }\n report.dryRun = dryRun;\n if (dryRun || report.refusals.length || !Object.keys(projected).length) return report;\n const { pushRows } = await import(\"../cli/platform/worldData/push\");\n const status = await pushRows(creds, slug, projected, { mode, redact, message: options.message });\n report.batch = status;\n report.changed = status.state === \"applied\" || status.state === \"published\";\n if (status.entityCounts) report.entityCounts = status.entityCounts;\n return report;\n } finally {\n fs.rmSync(scratch, { recursive: true, force: true });\n }\n}\n\n/**\n * Tool-call records into a world with neither a transform nor a mapping of\n * your own: the world's `ingest.toml` when it has one, else each record's\n * tool through its operation's `[ingest]` projection (an unknown tool is a\n * refusal naming it and nothing is written). {@link ingest} with the same\n * options.\n */\nexport async function ingestToolCalls(world: string, records: unknown[], options: IngestToolCallsOptions = {}): Promise<IngestToolCallsReport> {\n return ingest(world, records, options);\n}\n\nfunction transformReport(\n world: string,\n records: number,\n rows: Rows,\n stderr: string,\n outcome: { dryRun: boolean; redact: RedactMode; changed: boolean; kind?: string; entityCounts?: Record<string, number> },\n): IngestReport {\n return {\n world,\n via: \"transform\",\n ...(stderr ? { stderr } : {}),\n records,\n ingested: records,\n skipped: {},\n refusals: [],\n rows: Object.fromEntries(Object.entries(rows).map(([entity, listed]) => [entity, listed.length])),\n dryRun: outcome.dryRun,\n redact: outcome.redact,\n changed: outcome.changed,\n ...(outcome.kind ? { kind: outcome.kind } : {}),\n ...(outcome.entityCounts ? { entityCounts: outcome.entityCounts } : {}),\n };\n}\n\nfunction reportOf(\n world: string,\n local: {\n via?: IngestReport[\"via\"];\n sources?: { name: string; kind: string; select: string; entity: string; records: number; items: number; rows: Record<string, number>; unmapped_fields: Record<string, string>; unset_fields: Record<string, string[]> }[];\n unmatched?: Record<string, number>;\n note?: string;\n records: number;\n ingested: number;\n skipped: Record<string, number>;\n refusals: IngestRefusal[];\n rows: Record<string, number>;\n dry_run: boolean;\n changed: boolean;\n kind?: string;\n entity_counts?: Record<string, number>;\n },\n redact: RedactMode,\n): IngestToolCallsReport {\n return {\n world,\n ...(local.via ? { via: local.via } : {}),\n ...(local.sources ? { sources: local.sources.map(({ unmapped_fields, unset_fields, ...rest }) => ({ ...rest, unmappedFields: unmapped_fields, unsetFields: unset_fields })) } : {}),\n ...(local.unmatched ? { unmatched: local.unmatched } : {}),\n ...(local.note ? { note: local.note } : {}),\n records: local.records,\n ingested: local.ingested,\n skipped: local.skipped,\n refusals: local.refusals,\n rows: local.rows,\n dryRun: local.dry_run,\n redact,\n changed: local.changed,\n ...(local.kind ? { kind: local.kind } : {}),\n ...(local.entity_counts ? { entityCounts: local.entity_counts } : {}),\n };\n}\n\n/** The TOOL observations of one session, every trace's, from `GET /api/public/sessions/{id}?includeIO=true`. */\nexport async function sessionToolObservations(sessionId: string, options: WorldsClientOptions = {}): Promise<ObservationLike[]> {\n const session = await apiRequest<{ traces?: { id?: string; observations?: ObservationLike[] }[] }>(\n options,\n \"GET\",\n `/api/public/sessions/${encodeURIComponent(sessionId)}?includeIO=true`,\n );\n const out: ObservationLike[] = [];\n for (const trace of session.traces ?? [])\n for (const observation of trace.observations ?? []) out.push({ traceId: trace.id ?? null, ...observation });\n return out;\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\n\n/**\n * Edit sessions: the version control unit for a world. Every write this\n * credential makes to a world (push, sandbox commit, data import, MCP, the\n * console editor) joins ONE open session per world per credential and lands\n * on that session's private branch; `close` seals the session into a version\n * on `main`, and a session nobody touches for an hour seals itself. Sessions\n * replace product-level proposals/PRs: `rollback` undoes a sealed session\n * (source + data together) as a new, itself-reversible session.\n *\n * One client under both `gateway worlds edit …` and `gateway bench edit …`;\n * the Python twin is `gatewaysdk.benchmark_hub.edit_sessions.WorldEditClient`.\n */\n\n/** Mirrors `WorldEditSessionSchema` (web/features/public-api/types/world-edits.ts). */\nexport type EditSessionSummary = {\n id: string;\n containerId: string;\n /** `apikey:<id>` for CLI/sandbox/MCP, `user:<id>` for the console, `agent:<id>` for the platform agent. */\n actor: string;\n door: string;\n status: \"open\" | \"sealing\" | \"sealed\" | \"conflict\" | \"expired\" | \"discarded\" | string;\n baseVersionId: string | null;\n tipVersionId: string | null;\n sealedVersionId: string | null;\n editCount: number;\n startedAt: string;\n lastEditAt: string;\n expiresAt: string;\n closedAt: string | null;\n closeReason: string | null;\n conflictPaths: string[] | null;\n rollbackOfId: string | null;\n message: string | null;\n};\n\nexport type EditSessionList = {\n slug: string;\n containerId: string;\n /** This credential's open session, or null. */\n current: EditSessionSummary | null;\n sessions: EditSessionSummary[];\n};\n\n/** What close/discard/rollback return. */\nexport type EditSessionResult = { slug: string; session: EditSessionSummary };\n\nexport type EditSessionListQuery = { status?: string; limit?: number };\nexport type EditSessionCloseInput = { sessionId?: string; force?: boolean; message?: string };\nexport type EditSessionRollbackInput = { sessionId: string; force?: boolean; message?: string };\n\nconst WORLDS = \"/api/public/worlds\";\nexport class WorldEditClient {\n constructor(private readonly options: WorldsClientOptions = {}) {}\n\n /** The credential's current session and the world's newest-first sessions. */\n list(slug: string, query: EditSessionListQuery = {}): Promise<EditSessionList> {\n const qs = new URLSearchParams();\n if (query.status) qs.set(\"status\", query.status);\n if (query.limit !== undefined) qs.set(\"limit\", String(query.limit));\n const suffix = qs.size ? `?${qs.toString()}` : \"\";\n return apiRequest(this.options, \"GET\", `${WORLDS}/${encodeURIComponent(slug)}/edits${suffix}`);\n }\n\n /** Seal a session into a version on main (the credential's current one when `sessionId` is omitted). */\n close(slug: string, input: EditSessionCloseInput = {}): Promise<EditSessionResult> {\n return apiRequest(this.options, \"POST\", `${WORLDS}/${encodeURIComponent(slug)}/edits/close`, input);\n }\n\n /** Drop the session's private branch without making a version. */\n discard(slug: string, input: { sessionId?: string } = {}): Promise<EditSessionResult> {\n return apiRequest(this.options, \"POST\", `${WORLDS}/${encodeURIComponent(slug)}/edits/discard`, input);\n }\n\n /** Undo a sealed session (source and data) as a new sealed session. */\n rollback(slug: string, input: EditSessionRollbackInput): Promise<EditSessionResult> {\n return apiRequest(this.options, \"POST\", `${WORLDS}/${encodeURIComponent(slug)}/edits/rollback`, input);\n }\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\n\n/**\n * The hosted one-task dry run: `POST /api/public/environments/{id}/dry-run`\n * and the run-status read that settles it. The runner runs ONE named task of a\n * harbor tree through harbor's `oracle` (the task's own `solution/solve.sh`)\n * with the real image rule (`[environment] docker_image` → pull, never build;\n * else build the Dockerfile). No model, no model key. The run is marked\n * `kind: \"dry-run\"` and never counts as a benchmark result.\n *\n * The caps are the server's: one task, one example, one rollout, the oracle.\n * The body carries the task name and, optionally, a pinned versionId; a body\n * that tries to widen the run (models, task lists, rollouts) is a 400.\n */\n\nexport const DRY_RUN_KIND = \"dry-run\" as const;\nexport const DRY_RUN_AGENT = \"oracle\" as const;\n\nexport type HostedDryRunDispatch = {\n runId: string;\n versionId: string;\n versionLabel: string;\n containerSlug: string;\n task: string;\n kind: typeof DRY_RUN_KIND;\n agent: typeof DRY_RUN_AGENT;\n evidence: false;\n where: \"hosted\";\n};\n\n/** The image decision the runner took — the SAME rule a real run applies. */\nexport type DryRunImageDecision = {\n source: \"prebuilt\" | \"dockerfile\";\n ref: string | null;\n};\n\n/** What the runner reported about the one trial (the Python twin is `benchmark_hub.dry_run.DryRunSettlement`). */\nexport type DryRunSettlement = {\n task: string;\n agent: typeof DRY_RUN_AGENT;\n image: DryRunImageDecision | null;\n command: string | null;\n reward: number | null;\n rewardFile: { name: string; content: unknown } | null;\n exitCode: number | null;\n errorTail: string | null;\n};\n\nexport type HostedDryRunStatus = {\n kind: typeof DRY_RUN_KIND;\n evidence: false;\n where: \"hosted\";\n agent: typeof DRY_RUN_AGENT;\n task: string | null;\n evaluationId: string | null;\n url: string | null;\n settlement: DryRunSettlement | null;\n};\n\n/** The run-status answer (`GET …/environments/runs/{runId}`) as a dry run reads it. */\nexport type HostedDryRunVerdict = {\n status: string;\n settled: boolean;\n progress: {\n harvested: number;\n planned: number | null;\n startedAt: string | null;\n completedAt: string | null;\n elapsedSeconds: number | null;\n } | null;\n dryRun: HostedDryRunStatus | null;\n};\n\n/** The server blocks a status read for at most this long; longer waits poll. */\nexport const STATUS_WAIT_CAP_SECONDS = 50;\n\nexport type SettleOptions = {\n /** Give up (return the last verdict, unsettled) after this long. */\n timeoutSeconds: number;\n /** Called once per unsettled poll with the verdict so far. */\n onProgress?: (verdict: HostedDryRunVerdict) => void;\n /** Injected for tests: the clock and the pause between empty polls. */\n now?: () => number;\n sleep?: (ms: number) => Promise<void>;\n};\n\nconst cid = (id: string) =>\n `/api/public/environments/${encodeURIComponent(id)}`;\n\n/** The client a `gateway benchmarks dry-run --hosted` is built on. */\nexport class HostedDryRunClient {\n constructor(private readonly options: WorldsClientOptions = {}) {}\n\n /** Dispatch ONE oracle job for `task` on `containerId` (a container id, not a slug); pins `versionId` when given. */\n dispatch(target: {\n containerId: string;\n task: string;\n versionId?: string;\n }): Promise<HostedDryRunDispatch> {\n return apiRequest(\n this.options,\n \"POST\",\n `${cid(target.containerId)}/dry-run`,\n {\n task: target.task,\n ...(target.versionId ? { versionId: target.versionId } : {}),\n },\n );\n }\n\n /** One status read, blocking server-side for up to `waitSeconds` (capped). */\n status(runId: string, waitSeconds = 0): Promise<HostedDryRunVerdict> {\n const wait = Math.max(\n 0,\n Math.min(Math.floor(waitSeconds), STATUS_WAIT_CAP_SECONDS),\n );\n const suffix = wait ? `?waitSeconds=${wait}` : \"\";\n return apiRequest(\n this.options,\n \"GET\",\n `/api/public/environments/runs/${encodeURIComponent(runId)}${suffix}`,\n );\n }\n\n /** Poll until the run settles or `timeoutSeconds` pass; the last verdict either way. */\n async settle(\n runId: string,\n opts: SettleOptions,\n ): Promise<HostedDryRunVerdict> {\n const now = opts.now ?? Date.now;\n const sleep =\n opts.sleep ??\n ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));\n const deadline = now() + opts.timeoutSeconds * 1000;\n for (;;) {\n const budget = Math.floor(\n Math.min(45, Math.max(0, (deadline - now()) / 1000)),\n );\n const asked = now();\n const verdict = await this.status(runId, budget);\n if (verdict.settled || now() >= deadline) return verdict;\n opts.onProgress?.(verdict);\n // A server that answered at once (no long poll behind it) must not be hammered.\n if (now() - asked < 1000) await sleep(1000);\n }\n }\n}\n\n/** The one exit-code decision, shared by the CLI twins: 0 only when the oracle scored exactly 1.0. */\nexport class DryRunOutcome {\n constructor(readonly verdict: HostedDryRunVerdict) {}\n\n get settlement(): DryRunSettlement | null {\n return this.verdict.dryRun?.settlement ?? null;\n }\n\n /** Why the dry run did not pass, or null when it did. */\n reason(): string | null {\n if (!this.verdict.settled) return `still running after the wait`;\n const settlement = this.settlement;\n if (!settlement)\n return `the runner filed no settlement (${this.verdict.status})`;\n const lastErrorLine =\n settlement.errorTail?.trim().split(\"\\n\").at(-1) || null;\n // A non-zero harbor exit is a failure whatever the reward file says: a\n // 1.0 written before the harness died is not a pass.\n if (settlement.exitCode !== null && settlement.exitCode !== 0)\n return `the runner failed (exit ${settlement.exitCode}): ${lastErrorLine ?? \"harbor exited non-zero\"}`;\n if (settlement.reward === null && lastErrorLine)\n return `the runner failed (exit ?): ${lastErrorLine}`;\n if (settlement.reward === null)\n return \"ungraded: the grader ran but wrote no reward\";\n if (settlement.reward !== 1)\n return `the reference solution scored ${settlement.reward}, not 1.0`;\n return null;\n }\n\n passed(): boolean {\n return this.reason() === null;\n }\n}\n","\nimport type { WorldTaskIdRef } from \"./session\";\nimport { PlatformTransport, type PlatformMethod } from \"./transport\";\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/** A platform answer outside 2xx, its status kept so a caller can act on one\n * code (a 409 on a name already taken) instead of parsing the message. A JSON\n * body renders as `<message> (<code>)` — the stable public `code`, never the\n * server's error class name. */\nexport class ApiError extends Error {\n public readonly code: string | null;\n\n constructor(\n public readonly status: number,\n method: string,\n path: string,\n public readonly text: string,\n ) {\n const parsed = parseErrorBody(text);\n super(`${method} ${path} -> ${status}: ${parsed.detail}`);\n this.name = \"ApiError\";\n this.code = parsed.code;\n }\n}\n\n/** What a client shows for one non-2xx body and the stable code it carries.\n * Python twin: `gatewaysdk.api_errors.error_detail`. */\nexport function parseErrorBody(\n text: string,\n limit = 600,\n): { detail: string; code: string | null } {\n const raw = { detail: text.slice(0, limit), code: null };\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return raw;\n }\n if (parsed === null || typeof parsed !== \"object\") return raw;\n const { message, code } = parsed as { message?: unknown; code?: unknown };\n const stableCode = typeof code === \"string\" ? code : null;\n if (typeof message !== \"string\") return { ...raw, code: stableCode };\n if (stableCode === null)\n return { detail: message.slice(0, limit), code: null };\n return {\n detail: `${message} (${stableCode})`.slice(0, limit),\n code: stableCode,\n };\n}\n\n/** Authenticated JSON request against the platform API — the primitive the\n * worlds helpers and the TS CLI share. `init.timeoutMs` is the request's own\n * budget when it legitimately outlasts `GATEWAY_TIMEOUT_MS`. */\nexport async function apiRequest<T>(\n options: WorldsClientOptions,\n method: PlatformMethod,\n path: string,\n body?: unknown,\n init: { timeoutMs?: number } = {},\n): Promise<T> {\n const reply = await new PlatformTransport(resolveEnv(options)).send(method, path, body, init);\n if (!reply.ok) throw new ApiError(reply.status, method, path, reply.text);\n return JSON.parse(reply.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\n/** What a run config selects for the runner to work through. A config runs\n * EITHER the bundle's own scenarios (`taskNames`, `taskSetDatasetId`) OR the\n * project's stored tasks (`worldTasks`, api worlds only) — never both. A\n * stored task ref without `version` runs the task's current version at\n * dispatch time; with it, that version forever. */\nexport type RunConfigInput = {\n id?: string;\n name: string;\n models: string[];\n parallelism?: number;\n numExamples?: number;\n rolloutsPerExample?: number;\n timeoutMinutes?: number;\n agent?: string;\n taskSetDatasetId?: string | null;\n taskNames?: string[];\n worldTasks?: WorldTaskIdRef[];\n autoRunOnPush?: boolean;\n};\n\n/** Create a run config, or update the one named by `id`. */\nexport async function upsertRunConfig(\n input: RunConfigInput,\n options: WorldsClientOptions = {},\n): Promise<RunConfigSummary> {\n return apiRequest<RunConfigSummary>(\n options,\n \"POST\",\n \"/api/public/benchmark-containers/run-configs\",\n input,\n );\n}\n\n/** `id[@version]` items (comma-separated or an array) → stored task refs;\n * the spelling `bench run-configs create --world-tasks` takes. */\nexport function parseWorldTaskRefs(spec: string | string[]): WorldTaskIdRef[] {\n const items = (Array.isArray(spec) ? spec : spec.split(\",\"))\n .map((s) => s.trim())\n .filter(Boolean);\n return items.map((item) => {\n const at = item.lastIndexOf(\"@\");\n if (at < 0) return { id: item };\n const id = item.slice(0, at);\n const version = Number(item.slice(at + 1));\n if (!id || !Number.isInteger(version) || version < 1)\n throw new Error(\n `stored task ref '${item}' is not <id> or <id>@<version> (version a positive integer)`,\n );\n return { id, version };\n });\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/** One run as `bench runs list` prints it (GET /benchmark-containers/runs):\n * the gate's view — no logs, samples or links; `getRun` has those. */\nexport type RunSummary = {\n id: string;\n status: string;\n terminal: boolean;\n score: number | null;\n summary: string | null;\n createdAt: string;\n completedAt: string | null;\n model: string | null;\n versionId: string | null;\n versionLabel: string | null;\n runConfigId: string | null;\n runConfigName: string | null;\n parallelism: number;\n exitCode: number | null;\n};\n\nexport type ListRunsFilter = {\n /** Only runs of this world/benchmark; a slug the project lacks lists nothing. */\n slug?: string;\n /** Case-insensitive run status (RUNNING, completed, …). */\n status?: string;\n limit?: number;\n};\n\n/** The project's runs, newest first. */\nexport async function listRuns(\n filter: ListRunsFilter = {},\n options: WorldsClientOptions = {},\n): Promise<RunSummary[]> {\n const params = new URLSearchParams();\n if (filter.slug) params.set(\"slug\", filter.slug);\n if (filter.status) params.set(\"status\", filter.status);\n if (filter.limit !== undefined) params.set(\"limit\", String(filter.limit));\n const qs = params.toString();\n const res = await apiRequest<{ runs: RunSummary[] }>(\n options,\n \"GET\",\n `/api/public/benchmark-containers/runs${qs ? `?${qs}` : \"\"}`,\n );\n return res.runs;\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 — a bundled task's\n * name or an inline `WorldTaskSpec`: the platform boots (or reuses) a warm\n * container, and your agent calls its tools through the platform. See\n * worlds/session.ts.\n */\n async open(\n task: import(\"./session\").WorldTaskRef,\n opts: {\n reuseWarm?: boolean;\n surfaces?: import(\"./browser\").WorldSurfaceKind[];\n browserTier?: import(\"./browser\").BrowserTier;\n } = {},\n ): Promise<import(\"./session\").WorldSession> {\n const { openSession } = await import(\"./session\");\n return openSession(this.slug, {\n task,\n versionId: this.version.versionId,\n reuseWarm: opts.reuseWarm,\n surfaces: opts.surfaces,\n browserTier: opts.browserTier,\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 return resolveWorld(slugRef, slug, ref, ref ? { ref } : {}, options);\n}\n\n/**\n * Resolve `slug` at one pinned READY `versionId` — the task list is THAT\n * version's, never the branch tip's. `worlds run|ci --version-id` come\n * through here; a version of another container, a draft or an unknown id\n * is a 404 from the platform, not a silent fall-through to head.\n */\nexport async function openWorldVersion(\n slug: string,\n versionId: string,\n options: WorldsClientOptions = {},\n): Promise<WorldSet> {\n return resolveWorld(\n `${slug}@${versionId}`,\n slug,\n null,\n { versionId },\n options,\n );\n}\n\nasync function resolveWorld(\n slugRef: string,\n slug: string,\n ref: string | null,\n pin: { ref?: string; versionId?: string },\n options: WorldsClientOptions,\n): Promise<WorldSet> {\n const version = await apiRequest<\n ResolvedWorldVersion & { taskNames?: string[] }\n >(options, \"POST\", \"/api/public/benchmark-containers/resolve-version\", {\n slug,\n ...pin,\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 \"./transport\";\nexport * from \"./session\";\nexport * from \"./sessionList\";\nexport * from \"./sessionContract\";\nexport * from \"./taskRef\";\n\n// Stored tasks: the task spec as a named, versioned project resource that\n// `openSession(world, { task: { id } })` opens on.\nexport * from \"./tasks\";\n\n// Tasks that need several worlds: `openTask` brings every world a task\n// names up together (or not at all) and hands back the sessions by alias.\nexport * from \"./taskSessions\";\n\n// Run a task end to end: open every world, hand the agent a `TaskRun`,\n// grade with its report, file one rollout and close — `runTask`, the\n// engine behind `gateway worlds task run`.\nexport * from \"./taskRun\";\n\n// Run every stored task of a scenario set with one model as ONE set run —\n// `runSet`, the engine behind `gateway worlds task run-set` — and the checkout\n// it records (branch, commit, remote without credentials, CI's pull request).\nexport * from \"./setRun\";\nexport * from \"./checkoutProvenance\";\n\n// The evaluations client `runTask` files a rollout through — create, push\n// samples, finalize. Exposed in case a caller wants to file its own.\nexport * from \"./evals\";\n\n// The computer-use half: surfaces, a Playwright browser on the world's UI,\n// and browser actions as model tools.\nexport * from \"./browser\";\nexport * from \"./browserReconnect\";\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\n// Discovery: what a world holds and how each field is stored (`describeWorld`),\n// and the stored forms of a plaintext under the world's [redact] table\n// (`storedForms`, `redactionOf`) — the same digest rule as the Python runtime.\nexport * from \"./describe\";\nexport * from \"./redaction\";\nexport * from \"./transforms\";\n\n// Lookup: the rows of one entity matching a predicate (`queryRows`), by\n// stored value or — with `resolve` — by plaintext the runtime maps through\n// the same [redact] table.\nexport * from \"./query\";\n\n// Migration: a stored world into a schema world (`migrateWorld`), dry run by\n// default; the project's connector worlds at once (`migrateProjectWorlds`).\nexport * from \"./migrate\";\n\n// Tool calls into rows: the record contract, `captureToolCalls` (record an\n// agent's real calls), `toolCallsFromObservations` (from a trace) and\n// `ingestToolCalls` (into a directory or a slug). Redaction optional, off by default.\nexport * from \"./ingest\";\n\n// The CLI sandbox: open a READY version in a server-side workspace, edit and\n// run there, check and commit into the version service without the source\n// ever landing on this disk (`gateway worlds|bench sandbox …`).\nexport * from \"./sandbox\";\nexport * from \"./editSessions\";\n\n// The hosted one-task dry run: ONE oracle job on the runner with the real\n// image rule, its settlement (image decision, reward file, exit code) and the\n// one pass/fail decision the CLI twins share (`gateway benchmarks dry-run --hosted`).\nexport * from \"./dryRun\";\n","/**\n * Read the project's traces, observations and trace sessions — the public\n * API behind `gateway traces …` and the MCP tools get_trace / get_observations\n * / get_session. Everything here is read-only.\n *\n * GET /api/public/traces?… a page of traces (page 1-based, limit ≤ 100)\n * GET /api/public/traces/{traceId} one trace with its observations and scores\n * GET /api/public/observations?… a page of observations (type, traceId, time window)\n * GET /api/public/sessions?… a page of trace sessions\n * GET /api/public/sessions/{sessionId} one session; includeIO=true attaches every trace's observations\n */\n\nimport { apiRequest, type WorldsClientOptions } from \"../worlds/index\";\n\nexport type TraceFilters = {\n fromTimestamp?: string;\n toTimestamp?: string;\n sessionId?: string;\n userId?: string;\n name?: string;\n tags?: string[];\n environment?: string;\n version?: string;\n release?: string;\n /** `timestamp.asc`, `timestamp.desc` (the default), … */\n orderBy?: string;\n};\n\nexport type ObservationFilters = {\n traceId?: string;\n type?: string;\n name?: string;\n userId?: string;\n level?: string;\n parentObservationId?: string;\n environment?: string;\n version?: string;\n fromStartTime?: string;\n toStartTime?: string;\n};\n\nexport type SessionFilters = { fromTimestamp?: string; toTimestamp?: string; environment?: string };\n\nexport type PageMeta = { page: number; limit: number; totalItems: number; totalPages: number };\nexport type Page<T> = { data: T[]; meta: PageMeta };\n\nexport type Trace = {\n id: string;\n timestamp: string;\n name: string | null;\n sessionId: string | null;\n userId: string | null;\n tags: string[];\n environment?: string;\n [key: string]: unknown;\n};\n\nexport type Observation = {\n id: string;\n traceId: string | null;\n type: string;\n name: string | null;\n startTime: string;\n endTime?: string | null;\n level?: string;\n [key: string]: unknown;\n};\n\nexport type TraceDetail = Trace & { observations: Observation[]; scores: unknown[]; latency?: number; totalCost?: number };\n\nexport type TraceSession = { id: string; createdAt: string; projectId: string; environment: string };\nexport type TraceSessionDetail = TraceSession & { traces: (Trace & { observations?: Observation[] })[] };\n\n/** The platform caps a page at 100. */\nexport const PAGE_LIMIT = 100;\n\ntype Scalar = string | number | boolean | undefined | null;\n\nfunction qs(params: Record<string, Scalar | string[]>): string {\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined || value === null || value === \"\") continue;\n if (Array.isArray(value)) for (const item of value) search.append(key, item);\n else search.set(key, String(value));\n }\n const text = search.toString();\n return text ? `?${text}` : \"\";\n}\n\nexport async function listTraces(\n options: WorldsClientOptions = {},\n filters: TraceFilters = {},\n page: { page?: number; limit?: number; fields?: string } = {},\n): Promise<Page<Trace>> {\n const { tags, ...rest } = filters;\n return apiRequest<Page<Trace>>(options, \"GET\", `/api/public/traces${qs({ ...rest, tags, page: page.page ?? 1, limit: page.limit ?? 50, fields: page.fields })}`);\n}\n\n/** Page through matching traces, newest first unless `orderBy` says otherwise; `max` stops early. */\nexport async function* iterateTraces(\n options: WorldsClientOptions = {},\n filters: TraceFilters = {},\n limits: { max?: number; fields?: string } = {},\n): AsyncGenerator<Trace> {\n yield* paged((page) => listTraces(options, filters, { page, limit: PAGE_LIMIT, fields: limits.fields }), limits.max);\n}\n\n/** One trace with its observations (input/output included) and scores. */\nexport async function getTrace(options: WorldsClientOptions = {}, traceId: string): Promise<TraceDetail> {\n return apiRequest<TraceDetail>(options, \"GET\", `/api/public/traces/${encodeURIComponent(traceId)}`);\n}\n\nexport async function listObservations(\n options: WorldsClientOptions = {},\n filters: ObservationFilters = {},\n page: { page?: number; limit?: number } = {},\n): Promise<Page<Observation>> {\n return apiRequest<Page<Observation>>(options, \"GET\", `/api/public/observations${qs({ ...filters, page: page.page ?? 1, limit: page.limit ?? 50 })}`);\n}\n\nexport async function* iterateObservations(\n options: WorldsClientOptions = {},\n filters: ObservationFilters = {},\n limits: { max?: number } = {},\n): AsyncGenerator<Observation> {\n yield* paged((page) => listObservations(options, filters, { page, limit: PAGE_LIMIT }), limits.max);\n}\n\nexport async function listSessions(\n options: WorldsClientOptions = {},\n filters: SessionFilters = {},\n page: { page?: number; limit?: number } = {},\n): Promise<Page<TraceSession>> {\n return apiRequest<Page<TraceSession>>(options, \"GET\", `/api/public/sessions${qs({ ...filters, page: page.page ?? 1, limit: page.limit ?? 50 })}`);\n}\n\nexport async function* iterateSessions(\n options: WorldsClientOptions = {},\n filters: SessionFilters = {},\n limits: { max?: number } = {},\n): AsyncGenerator<TraceSession> {\n yield* paged((page) => listSessions(options, filters, { page, limit: PAGE_LIMIT }), limits.max);\n}\n\n/** One trace session and its traces; `includeIO` attaches every trace's full observations. */\nexport async function getSession(\n options: WorldsClientOptions = {},\n sessionId: string,\n detail: { includeIO?: boolean } = {},\n): Promise<TraceSessionDetail> {\n return apiRequest<TraceSessionDetail>(options, \"GET\", `/api/public/sessions/${encodeURIComponent(sessionId)}${qs({ includeIO: detail.includeIO ? \"true\" : undefined })}`);\n}\n\nexport type ExportOptions = {\n /** Attach each trace's observations (one GET /traces/{id} per trace). */\n observations?: boolean;\n /** With `observations`: keep only this observation type (TOOL, GENERATION, SPAN, …). */\n type?: string;\n /** Stop after this many traces. */\n max?: number;\n};\n\nexport type ExportSummary = { traces: number; observations: number };\n\n/**\n * Every matching trace as one JSON object handed to `write`, ids and\n * timestamps exactly as the API returns them. With `observations`, each object\n * carries its `observations` array (filtered by `type` when given) and the\n * trace's `scores`, from `GET /traces/{id}`.\n */\nexport async function exportTraces(\n options: WorldsClientOptions = {},\n filters: TraceFilters = {},\n exportOptions: ExportOptions = {},\n write: (record: Record<string, unknown>) => void,\n): Promise<ExportSummary> {\n const summary: ExportSummary = { traces: 0, observations: 0 };\n const wantedType = exportOptions.type?.toUpperCase();\n for await (const trace of iterateTraces(options, filters, { max: exportOptions.max })) {\n let record: Record<string, unknown> = trace;\n if (exportOptions.observations) {\n const detail = await getTrace(options, trace.id);\n const observations = wantedType ? detail.observations.filter((o) => o.type?.toUpperCase() === wantedType) : detail.observations;\n summary.observations += observations.length;\n record = { ...detail, observations };\n }\n summary.traces++;\n write(record);\n }\n return summary;\n}\n\nasync function* paged<T>(fetchPage: (page: number) => Promise<Page<T>>, max?: number): AsyncGenerator<T> {\n let yielded = 0;\n for (let page = 1; ; page++) {\n const answer = await fetchPage(page);\n for (const item of answer.data) {\n if (max !== undefined && yielded >= max) return;\n yielded++;\n yield item;\n }\n const totalPages = answer.meta?.totalPages ?? (answer.data.length < PAGE_LIMIT ? page : page + 1);\n if (!answer.data.length || page >= totalPages) return;\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAYO,SAAS,kBAAkB,MAAyB,QAAQ,KAAa;AAC9E,QAAM,MAAM,IAAI,oBAAoB;AACpC,MAAI,QAAQ,UAAa,QAAQ,GAAI,QAAO;AAC5C,QAAM,QAAQ,OAAO,GAAG;AACxB,MAAI,OAAO,UAAU,KAAK,KAAK,QAAQ,EAAG,QAAO;AACjD,QAAM,IAAI,MAAM,GAAG,oBAAoB,2DAA2D,GAAG,KAAK;AAC5G;AAlBA,IAAa,sBAGA,6BAiBP,YACA,OAEA,QAaA,eAGO,gBA6BA,kBAaA;AAjFb;AAAA;AAAA;AAAO,IAAM,uBAAuB;AAG7B,IAAM,8BAA8B;AAiB3C,IAAM,aAAa;AACnB,IAAM,QAAQ;AAEd,IAAM,SAA2D;AAAA,MAC/D,cAAc,EAAE,QAAQ,sBAAsB,MAAM,WAAW;AAAA,MAC/D,WAAW,EAAE,QAAQ,qBAAqB,MAAM,WAAW;AAAA,MAC3D,WAAW,EAAE,QAAQ,qBAAqB,MAAM,WAAW;AAAA,MAC3D,WAAW,EAAE,QAAQ,qBAAqB,MAAM,WAAW;AAAA,MAC3D,yBAAyB,EAAE,QAAQ,qBAAqB,MAAM,WAAW;AAAA,MACzE,cAAc,EAAE,QAAQ,oBAAoB,MAAM,WAAW;AAAA,MAC7D,aAAa,EAAE,QAAQ,uBAAuB,MAAM,MAAM;AAAA,MAC1D,YAAY,EAAE,QAAQ,sBAAsB,MAAM,MAAM;AAAA,MACxD,gBAAgB,EAAE,QAAQ,sBAAsB,MAAM,MAAM;AAAA,MAC5D,OAAO,EAAE,QAAQ,sBAAsB,MAAM,MAAM;AAAA,IACrD;AAEA,IAAM,gBAAgB,EAAE,QAAQ,iBAAiB,MAAM,WAAW;AAG3D,IAAM,iBAAN,MAAM,gBAAe;AAAA,MAClB,YACG,QACA,QACA,MACT;AAHS;AACA;AACA;AAAA,MACR;AAAA,MAHQ;AAAA,MACA;AAAA,MACA;AAAA,MAGX,OAAO,QAAQ,WAAmC;AAChD,eAAO,IAAI;AAAA,UACT,mBAAmB,YAAY,GAAI;AAAA,UACnC;AAAA,UACA,yCAAyC,oBAAoB;AAAA,QAC/D;AAAA,MACF;AAAA,MAEA,OAAO,GAAG,OAAgC;AACxC,cAAM,QAAQ,iBAAiB,SAAS,MAAM,iBAAiB,QAAQ,MAAM,QAAQ;AACrF,cAAM,OAAO,SAAS,UAAU,SAAS,OAAO,MAAM,SAAS,WAAW,MAAM,OAAO;AACvF,cAAM,UAAU,OAAO,YAAY,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACxF,cAAM,QAAS,QAAQ,OAAO,IAAI,KAAM;AACxC,eAAO,IAAI,gBAAe,MAAM,QAAQ,OAAO,GAAG,IAAI,KAAK,OAAO,KAAK,SAAS,MAAM,IAAI;AAAA,MAC5F;AAAA,MAEA,WAAmB;AACjB,eAAO,KAAK,WAAW,OAAO,KAAK,SAAS,GAAG,KAAK,MAAM,KAAK,KAAK,MAAM;AAAA,MAC5E;AAAA,IACF;AAGO,IAAM,mBAAN,cAA+B,MAAM;AAAA,MAC1C,YACW,MACA,QACA,OACA,SACT;AACA,cAAM,GAAG,MAAM,IAAI,KAAK,oBAAoB,IAAI,KAAK,QAAQ,SAAS,CAAC,KAAK,QAAQ,IAAI,EAAE;AALjF;AACA;AACA;AACA;AAGT,aAAK,OAAO;AAAA,MACd;AAAA,MAPW;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IAKb;AAGO,IAAM,oBAAN,MAAwB;AAAA,MAC7B,YACmB,UACA,YAAoB,kBAAkB,GACvD;AAFiB;AACA;AAAA,MAChB;AAAA,MAFgB;AAAA,MACA;AAAA;AAAA,MAInB,OAAO,OAAwB;AAC7B,eAAO,KAAK,IAAI,SAAS,GAAG,KAAK,SAAS;AAAA,MAC5C;AAAA,MAEA,MAAM,KACJ,QACA,OACA,MACA,OAA+B,CAAC,GACR;AACxB,cAAM,YAAY,KAAK,OAAO,KAAK,SAAS;AAC5C,cAAM,UAAU,SAAS,SAAY,CAAC,IAAI,EAAE,MAAM,KAAK,UAAU,IAAI,EAAE;AACvE,cAAM,aAAa,IAAI,gBAAgB;AACvC,cAAM,QAAQ,WAAW,MAAM,WAAW,MAAM,GAAG,SAAS;AAC5D,YAAI;AACF,gBAAM,MAAM,MAAM,MAAM,GAAG,KAAK,SAAS,IAAI,GAAG,KAAK,IAAI;AAAA,YACvD;AAAA,YACA,SAAS;AAAA,cACP,gBAAgB;AAAA,cAChB,QAAQ;AAAA,cACR,eACE,WAAW,OAAO,KAAK,GAAG,KAAK,SAAS,SAAS,IAAI,KAAK,SAAS,SAAS,EAAE,EAAE,SAAS,QAAQ;AAAA,YACrG;AAAA,YACA,GAAG;AAAA,YACH,QAAQ,WAAW;AAAA,UACrB,CAAC;AACD,iBAAO,EAAE,QAAQ,IAAI,QAAQ,IAAI,IAAI,IAAI,MAAM,MAAM,IAAI,KAAK,EAAE;AAAA,QAClE,SAAS,OAAO;AACd,gBAAM,QAAQ,WAAW,OAAO,UAAU,eAAe,QAAQ,SAAS,IAAI,eAAe,GAAG,KAAK;AACrG,gBAAM,IAAI,iBAAiB,KAAK,SAAS,MAAM,QAAQ,OAAO,KAAK;AAAA,QACrE,UAAE;AACA,uBAAa,KAAK;AAAA,QACpB;AAAA,MACF;AAAA,IACF;AAAA;AAAA;;;AC1HA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;AACA;AAAA;AAAA;;;ACDA,IAaa,uBAQA;AArBb;AAAA;AAAA;AAaO,IAAM,wBAAwB,IAAI,OAAO;AAQzC,IAAM,mBAAmB,OAAO,OAAO;AAAA,MAC5C,aAAa;AAAA,IACf,CAAC;AAAA;AAAA;;;ACvBD;AAAA;AAAA;AAAA;AAAA;;;ACAA,SAAS,kBAAkB;AAA3B,IAsVM,kBAGA,iBAIA;AA7VN;AAAA;AAAA;AAEA;AACA;AAkBA;AACA;AAEA;AA8TA,IAAM,mBAAmB,KAAK;AAG9B,IAAM,kBAAkB,IAAI;AAI5B,IAAM,0BAA0B,KAAK;AAAA;AAAA;;;AC7VrC;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;AACA;AAQA;AAAA;AAAA;;;ACTA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,SAAS,mBAAmB;AAC5B,YAAY,QAAQ;AACpB,YAAY,UAAU;AAFtB;AAAA;AAAA;AAKA;AACA;AAEA;AASA;AAAA;AAAA;;;ACjBA,SAAS,oBAAoB;AAA7B;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;AAEA;AACA;AAAA;AAAA;;;ACHA,YAAYA,SAAQ;AACpB,YAAYC,WAAU;AADtB;AAAA;AAAA;AAAA;AAAA;;;ACWA,SAAS,kBAAkB;AAC3B,YAAYC,SAAQ;AACpB,YAAYC,WAAU;AAbtB,IAkBa,gBAGA,sBACP;AAtBN;AAAA;AAAA;AAkBO,IAAM,iBAAiB;AAGvB,IAAM,uBAAuB,CAAC,qBAAqB,uBAAuB,kBAAkB;AACnG,IAAM,qBAAqB,CAAC,gBAAgB,GAAG,oBAAoB;AAAA;AAAA;;;ACtBnE,YAAYC,SAAQ;AACpB,YAAYC,WAAU;AACtB,SAAS,kBAAkB;AAF3B;AAAA;AAAA;AAAA;AAAA;;;ACAA,SAAS,cAAAC,mBAAkB;AAC3B,SAAS,gBAAgB;AACzB,YAAYC,SAAQ;AACpB,YAAYC,WAAU;AAHtB,IA0BM;AA1BN;AAAA;AAAA;AAIA;AACA;AACA;AACA;AAmBA,IAAM,eAAoB,WAAK,YAAY,oBAAoB;AAAA;AAAA;;;AC1B/D;AAAA;AAAA;AAaA;AAQA;AAAA;AAAA;;;ACrBA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAUA;AAEA;AAAA;AAAA;;;ACZA;AAAA;AAAA;AAAA;AAAA;;;ACuBA,SAAS,cAAAC,mBAAkB;AAvB3B,IA6Ba,YACP,kBACA,gBACA,WAEO,cAEP,MAEA,gBAKA,aAUA,KAGA,QAiBO;AAzEb;AAAA;AAAA;AAyBA;AAIO,IAAM,aAAa;AAC1B,IAAM,mBAAmB,IAAI,OAAO,KAAK,UAAU,OAAO,UAAU,OAAO,GAAG;AAC9E,IAAM,iBAAiB,IAAI,OAAO,IAAI,UAAU,MAAM,GAAG;AACzD,IAAM,YAAY;AAEX,IAAM,eAAe;AAE5B,IAAM,OAAO,CAAC,UAA0B,MAAM,QAAQ,kBAAkB,EAAE;AAE1E,IAAM,iBAAiB,CAAC,UAA0B;AAChD,YAAM,KAAK,MAAM,YAAY,GAAG;AAChC,aAAO,OAAO,KAAK,QAAQ,MAAM,MAAM,GAAG,EAAE;AAAA,IAC9C;AAEA,IAAM,cAAc,CAAC,UAA0B;AAC7C,YAAM,KAAK,MAAM,YAAY,GAAG;AAChC,aAAO,OAAO,KAAK,KAAK,MAAM,MAAM,KAAK,CAAC,EAAE,YAAY;AAAA,IAC1D;AAOA,IAAM,MAAM,CAAC,WAA8B,UACzCA,YAAW,SAAS,EAAE,OAAO,OAAO,MAAM,EAAE,OAAO,KAAK;AAE1D,IAAM,SAAoC;AAAA,MACxC,OAAO,CAAC,UAAU,MAAM,YAAY;AAAA,MACpC,OAAO,CAAC,UAAU,MAAM,YAAY;AAAA,MACpC;AAAA,MACA,aAAa,CAAC,UAAU,KAAK,KAAK,EAAE,QAAQ,gBAAgB,GAAG;AAAA,MAC/D,MAAM,CAAC,UAAU,MAAM,UAAU,MAAM;AAAA,MACvC,QAAQ,CAAC,UAAU,MAAM,QAAQ,WAAW,EAAE;AAAA,MAC9C,kBAAkB;AAAA,MAClB,cAAc;AAAA;AAAA;AAAA,MAGd,MAAM,CAAC,UAAU,IAAI,QAAQ,KAAK;AAAA,MAClC,QAAQ,CAAC,UAAU,IAAI,UAAU,KAAK;AAAA,IACxC;AAIO,IAAM,aAAgC,CAAC,GAAG,OAAO,KAAK,MAAM,GAAG,GAAG,YAAY,WAAW;AAAA;AAAA;;;AC3DhG,SAAS,cAAAC,mBAAkB;AAd3B;AAAA;AAAA;AAgBA;AACA;AAAA;AAAA;;;ACjBA;AAAA;AAAA;AAoBA;AAAA;AAAA;;;ACpBA;AAAA;AAAA;AAWA;AAAA;AAAA;;;ACyBA,YAAYC,SAAQ;AACpB,YAAY,QAAQ;AACpB,YAAYC,WAAU;AAtCtB;AAAA;AAAA;AAwCA;AAAA;AAAA;;;ACxCA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC6BA,SAAS,WAAW,SAA8B;AAChD,QAAM,OACJ,QAAQ,QAAQ,QAAQ,IAAI,gBAAgB;AAC9C,QAAM,YAAY,QAAQ,aAAa,QAAQ,IAAI;AACnD,QAAM,YAAY,QAAQ,aAAa,QAAQ,IAAI;AACnD,MAAI,CAAC,aAAa,CAAC,WAAW;AAC5B,UAAM,IAAI;AAAA,MACR;AAAA,IAEF;AAAA,EACF;AACA,SAAO,EAAE,MAAM,KAAK,QAAQ,QAAQ,EAAE,GAAG,WAAW,UAAU;AAChE;AAwBO,SAAS,eACd,MACA,QAAQ,KACiC;AACzC,QAAM,MAAM,EAAE,QAAQ,KAAK,MAAM,GAAG,KAAK,GAAG,MAAM,KAAK;AACvD,MAAI;AACJ,MAAI;AACF,aAAS,KAAK,MAAM,IAAI;AAAA,EAC1B,QAAQ;AACN,WAAO;AAAA,EACT;AACA,MAAI,WAAW,QAAQ,OAAO,WAAW,SAAU,QAAO;AAC1D,QAAM,EAAE,SAAS,KAAK,IAAI;AAC1B,QAAM,aAAa,OAAO,SAAS,WAAW,OAAO;AACrD,MAAI,OAAO,YAAY,SAAU,QAAO,EAAE,GAAG,KAAK,MAAM,WAAW;AACnE,MAAI,eAAe;AACjB,WAAO,EAAE,QAAQ,QAAQ,MAAM,GAAG,KAAK,GAAG,MAAM,KAAK;AACvD,SAAO;AAAA,IACL,QAAQ,GAAG,OAAO,KAAK,UAAU,IAAI,MAAM,GAAG,KAAK;AAAA,IACnD,MAAM;AAAA,EACR;AACF;AAKA,eAAsB,WACpB,SACA,QACAC,OACA,MACA,OAA+B,CAAC,GACpB;AACZ,QAAM,QAAQ,MAAM,IAAI,kBAAkB,WAAW,OAAO,CAAC,EAAE,KAAK,QAAQA,OAAM,MAAM,IAAI;AAC5F,MAAI,CAAC,MAAM,GAAI,OAAM,IAAI,SAAS,MAAM,QAAQ,QAAQA,OAAM,MAAM,IAAI;AACxE,SAAO,KAAK,MAAM,MAAM,IAAI;AAC9B;AArGA,IA+Ca;AA/Cb;AAAA;AAAA;AAEA;AA+iBA;AACA;AACA;AACA;AACA;AAIA;AAIA;AAKA;AAKA;AACA;AAIA;AAIA;AACA;AAKA;AAGA;AAKA;AACA;AACA;AAKA;AAIA;AAKA;AAKA;AACA;AAKA;AA1kBO,IAAM,WAAN,cAAuB,MAAM;AAAA,MAGlC,YACkB,QAChB,QACAA,OACgB,MAChB;AACA,cAAM,SAAS,eAAe,IAAI;AAClC,cAAM,GAAG,MAAM,IAAIA,KAAI,OAAO,MAAM,KAAK,OAAO,MAAM,EAAE;AANxC;AAGA;AAIhB,aAAK,OAAO;AACZ,aAAK,OAAO,OAAO;AAAA,MACrB;AAAA,MATkB;AAAA,MAGA;AAAA,MANF;AAAA,IAalB;AAAA;AAAA;;;ACjDA;AA8DO,IAAM,aAAa;AAI1B,SAAS,GAAG,QAAmD;AAC7D,QAAM,SAAS,IAAI,gBAAgB;AACnC,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,MAAM,GAAG;AACjD,QAAI,UAAU,UAAa,UAAU,QAAQ,UAAU,GAAI;AAC3D,QAAI,MAAM,QAAQ,KAAK,EAAG,YAAW,QAAQ,MAAO,QAAO,OAAO,KAAK,IAAI;AAAA,QACtE,QAAO,IAAI,KAAK,OAAO,KAAK,CAAC;AAAA,EACpC;AACA,QAAM,OAAO,OAAO,SAAS;AAC7B,SAAO,OAAO,IAAI,IAAI,KAAK;AAC7B;AAEA,eAAsB,WACpB,UAA+B,CAAC,GAChC,UAAwB,CAAC,GACzB,OAA2D,CAAC,GACtC;AACtB,QAAM,EAAE,MAAM,GAAG,KAAK,IAAI;AAC1B,SAAO,WAAwB,SAAS,OAAO,qBAAqB,GAAG,EAAE,GAAG,MAAM,MAAM,MAAM,KAAK,QAAQ,GAAG,OAAO,KAAK,SAAS,IAAI,QAAQ,KAAK,OAAO,CAAC,CAAC,EAAE;AACjK;AAGA,gBAAuB,cACrB,UAA+B,CAAC,GAChC,UAAwB,CAAC,GACzB,SAA4C,CAAC,GACtB;AACvB,SAAO,MAAM,CAAC,SAAS,WAAW,SAAS,SAAS,EAAE,MAAM,OAAO,YAAY,QAAQ,OAAO,OAAO,CAAC,GAAG,OAAO,GAAG;AACrH;AAGA,eAAsB,SAAS,UAA+B,CAAC,GAAG,SAAuC;AACvG,SAAO,WAAwB,SAAS,OAAO,sBAAsB,mBAAmB,OAAO,CAAC,EAAE;AACpG;AAEA,eAAsB,iBACpB,UAA+B,CAAC,GAChC,UAA8B,CAAC,GAC/B,OAA0C,CAAC,GACf;AAC5B,SAAO,WAA8B,SAAS,OAAO,2BAA2B,GAAG,EAAE,GAAG,SAAS,MAAM,KAAK,QAAQ,GAAG,OAAO,KAAK,SAAS,GAAG,CAAC,CAAC,EAAE;AACrJ;AAEA,gBAAuB,oBACrB,UAA+B,CAAC,GAChC,UAA8B,CAAC,GAC/B,SAA2B,CAAC,GACC;AAC7B,SAAO,MAAM,CAAC,SAAS,iBAAiB,SAAS,SAAS,EAAE,MAAM,OAAO,WAAW,CAAC,GAAG,OAAO,GAAG;AACpG;AAEA,eAAsB,aACpB,UAA+B,CAAC,GAChC,UAA0B,CAAC,GAC3B,OAA0C,CAAC,GACd;AAC7B,SAAO,WAA+B,SAAS,OAAO,uBAAuB,GAAG,EAAE,GAAG,SAAS,MAAM,KAAK,QAAQ,GAAG,OAAO,KAAK,SAAS,GAAG,CAAC,CAAC,EAAE;AAClJ;AAEA,gBAAuB,gBACrB,UAA+B,CAAC,GAChC,UAA0B,CAAC,GAC3B,SAA2B,CAAC,GACE;AAC9B,SAAO,MAAM,CAAC,SAAS,aAAa,SAAS,SAAS,EAAE,MAAM,OAAO,WAAW,CAAC,GAAG,OAAO,GAAG;AAChG;AAGA,eAAsB,WACpB,UAA+B,CAAC,GAChC,WACA,SAAkC,CAAC,GACN;AAC7B,SAAO,WAA+B,SAAS,OAAO,wBAAwB,mBAAmB,SAAS,CAAC,GAAG,GAAG,EAAE,WAAW,OAAO,YAAY,SAAS,OAAU,CAAC,CAAC,EAAE;AAC1K;AAmBA,eAAsB,aACpB,UAA+B,CAAC,GAChC,UAAwB,CAAC,GACzB,gBAA+B,CAAC,GAChC,OACwB;AACxB,QAAM,UAAyB,EAAE,QAAQ,GAAG,cAAc,EAAE;AAC5D,QAAM,aAAa,cAAc,MAAM,YAAY;AACnD,mBAAiB,SAAS,cAAc,SAAS,SAAS,EAAE,KAAK,cAAc,IAAI,CAAC,GAAG;AACrF,QAAI,SAAkC;AACtC,QAAI,cAAc,cAAc;AAC9B,YAAM,SAAS,MAAM,SAAS,SAAS,MAAM,EAAE;AAC/C,YAAM,eAAe,aAAa,OAAO,aAAa,OAAO,CAAC,MAAM,EAAE,MAAM,YAAY,MAAM,UAAU,IAAI,OAAO;AACnH,cAAQ,gBAAgB,aAAa;AACrC,eAAS,EAAE,GAAG,QAAQ,aAAa;AAAA,IACrC;AACA,YAAQ;AACR,UAAM,MAAM;AAAA,EACd;AACA,SAAO;AACT;AAEA,gBAAgB,MAAS,WAA+C,KAAiC;AACvG,MAAI,UAAU;AACd,WAAS,OAAO,KAAK,QAAQ;AAC3B,UAAM,SAAS,MAAM,UAAU,IAAI;AACnC,eAAW,QAAQ,OAAO,MAAM;AAC9B,UAAI,QAAQ,UAAa,WAAW,IAAK;AACzC;AACA,YAAM;AAAA,IACR;AACA,UAAM,aAAa,OAAO,MAAM,eAAe,OAAO,KAAK,SAAS,aAAa,OAAO,OAAO;AAC/F,QAAI,CAAC,OAAO,KAAK,UAAU,QAAQ,WAAY;AAAA,EACjD;AACF;","names":["fs","path","fs","path","fs","path","createHash","fs","path","createHash","createHash","fs","path","path"]}
|