@withgateway/sdk 0.2.2 → 0.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +129 -22
- package/dist/cli.js.map +1 -1
- package/dist/cli.mjs +130 -23
- package/dist/cli.mjs.map +1 -1
- package/dist/files/index.js +9 -5
- package/dist/files/index.js.map +1 -1
- package/dist/files/index.mjs +9 -5
- package/dist/files/index.mjs.map +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +14 -8
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +13 -8
- package/dist/index.mjs.map +1 -1
- package/dist/traces/index.js +9 -5
- package/dist/traces/index.js.map +1 -1
- package/dist/traces/index.mjs +9 -5
- package/dist/traces/index.mjs.map +1 -1
- package/dist/tracing/index.js +1 -1
- package/dist/tracing/index.js.map +1 -1
- package/dist/tracing/index.mjs +1 -1
- package/dist/tracing/index.mjs.map +1 -1
- package/dist/worlds/index.d.mts +7 -1
- package/dist/worlds/index.d.ts +7 -1
- package/dist/worlds/index.js +12 -7
- package/dist/worlds/index.js.map +1 -1
- package/dist/worlds/index.mjs +12 -7
- package/dist/worlds/index.mjs.map +1 -1
- package/package.json +1 -1
- package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/SKILL.md +5 -5
- package/skills/worlds-getting-started/SKILL.md +5 -5
package/dist/traces/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/worlds/browser.ts","../../src/worlds/session.ts","../../src/worlds/tasks.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/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};\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\nconst 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 },\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. */\n async grade(opts: { timeoutMs?: number } = {}): Promise<GradeResult> {\n const raw = (await this.exchange(\n { kind: \"grade\" },\n opts.timeoutMs,\n )) as Record<string, unknown> | null;\n const record = raw && typeof raw === \"object\" ? raw : {};\n const rewards: Record<string, number> = {};\n 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 state = await apiRequest<WorldSessionState & { reusedWarm: boolean }>(\n options,\n \"POST\",\n \"/api/public/world-sessions\",\n {\n ...(opts.versionId ? { versionId: opts.versionId } : { slug }),\n task,\n ...(opts.reuseWarm === undefined ? {} : { reuseWarm: opts.reuseWarm }),\n ...(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 /** True when `mean >= failUnder` (or no gate was set). */\n passed: boolean;\n};\n\n/**\n * RUN MANY TASKS IN PARALLEL, one warm container each.\n *\n * Parallelism against live worlds is the normal case — a suite is a dozen\n * tasks and each needs its own container, because two agents sharing one\n * world state would corrupt both episodes. Every caller was writing the same\n * pool, the same per-task open/ready/toolkit/grade/close, and the same\n * \"don't let one failure kill the run\" logic, so it belongs here:\n *\n * const report = await runSessions({\n * world: \"revenue-ops-sim@main\",\n * tasks, // default: every task in the world\n * concurrency: 4,\n * failUnder: 0.7,\n * agent: async ({ toolkit, instruction }) =>\n * myAgent(toolkit.impls, toolkit.schemas, instruction),\n * });\n *\n * The handler gets a ready session with its toolkit already bound; grading,\n * closing (warm) and aggregation are handled. A task that throws scores 0\n * and records why — the tasks that passed keep their results.\n */\nexport async function runSessions(opts: {\n world: string;\n /** 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.\n const { openWorld } = await import(\"./index\");\n const world = await openWorld(opts.world, options);\n tasks = tasks ?? world.tasks.map((t) => t.name);\n versionId = versionId ?? world.version.versionId;\n }\n\n const results: SessionRunResult[] = [];\n let next = 0;\n await Promise.all(\n Array.from({ length: Math.min(concurrency, tasks.length) }, async () => {\n while (next < tasks!.length) {\n const 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 return {\n results: results.sort((a, b) => a.task.localeCompare(b.task)),\n mean,\n passed: opts.failUnder === undefined ? true : mean >= opts.failUnder,\n };\n}\n","import { 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 WorldTaskValidation = {\n taskId: string;\n version: number;\n /** The world version the task was checked against. */\n versionId: string;\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. */\n checked: \"entities\" | \"none\";\n problems: string[];\n entities: string[] | null;\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 { createHash } from \"node:crypto\";\nimport { gzipSync, gunzipSync } from \"node:zlib\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\n\n/**\n * The working-dir half of the TS CLI: push / pull / checkout / status /\n * branch / tag / propose — a faithful port of the Python client\n * (`gatewaysdk/benchmark_hub/client.py` + `_archive.py`).\n *\n * LOCKSTEP WARNING — the content hash is the version's identity and is\n * byte-compatible with Prime Intellect. It now has FOUR implementations that\n * must stay identical: worker `environmentAgent/tar.ts`, web\n * `benchmark-hub/server/benchmarkContentHash.ts`, Python `_archive.py`, and\n * this file. This one is a line-for-line port of the WEB TypeScript\n * implementation (same language, same crypto) — if the rule ever changes,\n * change all four or push identity splits by client.\n *\n * One deliberate refusal, same policy as the web upload path: a bundle with\n * a ROOT `.gitignore` is refused rather than mis-hashed — the Python CLI\n * honors it via `gitignore_parser`, and an imperfect reimplementation here\n * would produce a wrong, Prime-incompatible hash silently.\n */\n\nexport const DEFAULT_BRANCH = \"main\";\nconst META_RELPATH = path.join(\".gateway\", \".env-metadata.json\");\nconst SKIP_DIRS = new Set([\n \".git\",\n \"__pycache__\",\n \"node_modules\",\n \".venv\",\n \".mypy_cache\",\n \"dist\",\n \"build\",\n \"outputs\",\n]);\nconst ROOT_EXCLUDED_DIRS = new Set([\"dist\", \"build\", \"outputs\", \"__pycache__\"]);\n\n/** Gateway-only root markers that widen collection to every ordinary root\n * file. The FOURTH copy of this list (python SDK `_archive.py`, web\n * `benchmarkContentHash.ts`, worker `tar.ts`, and here) — all four MUST stay\n * identical or the same tree hashes differently per pusher. This copy\n * missing `gateway-api-world.toml` is exactly how an api world pushed from\n * TS landed on the hub with no OpenAPI contract and no marker: the root\n * files never entered the manifest, and nothing downstream could tell. */\nconst BROAD_ROOT_MARKERS = [\"gateway-env.toml\", \"gateway-api-world.toml\"];\n\n// ── content-hash rules (port of web benchmarkContentHash.ts) ───────────────\n\nfunction isExcludedDirComponent(component: string): boolean {\n return (\n component.startsWith(\".\") ||\n ROOT_EXCLUDED_DIRS.has(component) ||\n component.endsWith(\".egg-info\")\n );\n}\n\nexport function isIncludedInContentHash(\n relPath: string,\n includeAllRootFiles: boolean,\n): boolean {\n const parts = relPath.split(\"/\");\n const name = parts[parts.length - 1];\n const dirParts = parts.slice(0, -1);\n if (name.startsWith(\".\")) return false;\n if (parts.includes(\"__pycache__\")) return false;\n if (dirParts.length === 0) {\n return (\n includeAllRootFiles ||\n name === \"README.md\" ||\n name === \"pyproject.toml\" ||\n BROAD_ROOT_MARKERS.includes(name) ||\n name.endsWith(\".py\")\n );\n }\n return !dirParts.some(isExcludedDirComponent);\n}\n\n/** The archive-visible files of a working dir, as sorted relpaths. Throws on\n * a root .gitignore (see the header). */\nexport function collectArchiveRelPaths(dir: string): string[] {\n if (fs.existsSync(path.join(dir, \".gitignore\"))) {\n throw new Error(\n \"This bundle has a root .gitignore, which the Python CLI honors via \" +\n \"gitignore_parser. Reimplementing that imperfectly here would \" +\n \"silently produce a different content hash, so the TS CLI refuses. \" +\n \"Remove the .gitignore (or bake its effect into the tree) and retry.\",\n );\n }\n const out: string[] = [];\n const includeAllRootFiles = BROAD_ROOT_MARKERS.some((marker) =>\n fs.existsSync(path.join(dir, marker)),\n );\n const walk = (rel: string) => {\n const abs = rel ? path.join(dir, rel) : dir;\n for (const entry of fs.readdirSync(abs, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {\n const childRel = rel ? `${rel}/${entry.name}` : entry.name;\n if (entry.isDirectory()) {\n if (!isExcludedDirComponent(entry.name)) walk(childRel);\n } else if (entry.isFile()) {\n if (isIncludedInContentHash(childRel, includeAllRootFiles)) {\n out.push(childRel);\n }\n }\n }\n };\n walk(\"\");\n return out.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));\n}\n\nexport function computeContentHash(dir: string): string {\n const hasher = createHash(\"sha256\");\n for (const relPath of collectArchiveRelPaths(dir)) {\n hasher.update(Buffer.from(`file:${relPath}`, \"utf-8\"));\n hasher.update(fs.readFileSync(path.join(dir, relPath)));\n }\n return hasher.digest(\"hex\");\n}\n\n// ── deterministic tar.gz writer ─────────────────────────────────────────────\n\nfunction octal(value: number, length: number): Buffer {\n return Buffer.from(value.toString(8).padStart(length - 1, \"0\") + \"\\0\", \"ascii\");\n}\n\nfunction tarHeader(name: string, size: number): Buffer {\n const header = Buffer.alloc(512);\n header.write(name, 0, 100, \"utf-8\");\n octal(0o644, 8).copy(header, 100); // mode\n octal(0, 8).copy(header, 108); // uid\n octal(0, 8).copy(header, 116); // gid\n octal(size, 12).copy(header, 124);\n octal(0, 12).copy(header, 136); // mtime = 0 (deterministic)\n header.write(\" \", 148, \"ascii\"); // checksum placeholder = spaces\n header.write(\"0\", 156, \"ascii\"); // regular file\n header.write(\"ustar\", 257, \"ascii\");\n header.write(\"00\", 263, \"ascii\");\n let sum = 0;\n for (const byte of header) sum += byte;\n header.write(sum.toString(8).padStart(6, \"0\") + \"\\0 \", 148, \"ascii\");\n return header;\n}\n\nfunction tarMember(name: string, payload: Buffer): Buffer[] {\n const parts: Buffer[] = [];\n const nameBytes = Buffer.byteLength(name, \"utf-8\");\n if (nameBytes > 100) {\n // GNU long name: an 'L' member whose body is the real name.\n const body = Buffer.from(name + \"\\0\", \"utf-8\");\n const lHeader = tarHeader(\"././@LongLink\", body.length);\n lHeader.write(\"L\", 156, \"ascii\");\n let sum = 0;\n lHeader.write(\" \", 148, \"ascii\");\n for (const byte of lHeader) sum += byte;\n lHeader.write(sum.toString(8).padStart(6, \"0\") + \"\\0 \", 148, \"ascii\");\n parts.push(lHeader, body);\n const pad = body.length % 512 === 0 ? 0 : 512 - (body.length % 512);\n if (pad) parts.push(Buffer.alloc(pad));\n parts.push(tarHeader(name.slice(0, 100), payload.length));\n } else {\n parts.push(tarHeader(name, payload.length));\n }\n parts.push(payload);\n const pad = payload.length % 512 === 0 ? 0 : 512 - (payload.length % 512);\n if (pad) parts.push(Buffer.alloc(pad));\n return parts;\n}\n\n/** A deterministic .tar.gz of the source files (node's gzip stamps no mtime,\n * matching the Python's mtime=0 gzip). */\nexport function buildSourceTarball(dir: string): Buffer {\n const parts: Buffer[] = [];\n for (const relPath of collectArchiveRelPaths(dir)) {\n parts.push(...tarMember(relPath, fs.readFileSync(path.join(dir, relPath))));\n }\n parts.push(Buffer.alloc(1024)); // end-of-archive\n return gzipSync(Buffer.concat(parts), { level: 9 });\n}\n\n// ── local metadata (.gateway/.env-metadata.json) ────────────────────────────\n\nexport type LocalMeta = Record<string, unknown> & {\n slug?: string;\n branch?: string;\n versionId?: string;\n contentHash?: string;\n baseFiles?: Record<string, string>;\n};\n\nexport function readLocalMeta(dir: string): LocalMeta | null {\n try {\n const raw = fs.readFileSync(path.join(dir, META_RELPATH), \"utf-8\");\n const parsed = JSON.parse(raw);\n return parsed && typeof parsed === \"object\" ? (parsed as LocalMeta) : null;\n } catch {\n return null;\n }\n}\n\nexport function writeLocalMeta(dir: string, meta: LocalMeta): void {\n fs.mkdirSync(path.join(dir, \".gateway\"), { recursive: true });\n fs.writeFileSync(path.join(dir, META_RELPATH), JSON.stringify(meta, null, 2));\n}\n\nexport function snapshotTreeHashes(dir: string): Record<string, string> {\n const out: Record<string, string> = {};\n for (const relPath of collectArchiveRelPaths(dir)) {\n out[relPath] = createHash(\"sha256\")\n .update(fs.readFileSync(path.join(dir, relPath)))\n .digest(\"hex\");\n }\n return out;\n}\n\nexport function localTreeState(dir: string): {\n meta: LocalMeta | null;\n dirty: string[];\n clean: boolean;\n} {\n const meta = readLocalMeta(dir);\n const base = meta?.baseFiles;\n if (!base || typeof base !== \"object\") {\n return { meta, dirty: [], clean: false };\n }\n const now = snapshotTreeHashes(dir);\n const dirty = new Set<string>();\n for (const [p, h] of Object.entries(now)) if (base[p] !== h) dirty.add(p);\n for (const p of Object.keys(base)) if (!(p in now)) dirty.add(p);\n return { meta, dirty: [...dirty].sort(), clean: dirty.size === 0 };\n}\n\n// ── protocol helpers ─────────────────────────────────────────────────────────\n\nconst sha256b64 = (data: Buffer) =>\n createHash(\"sha256\").update(data).digest(\"base64\");\n\nfunction readPyproject(dir: string): { name?: string; version?: string } {\n try {\n const text = fs.readFileSync(path.join(dir, \"pyproject.toml\"), \"utf-8\");\n // Minimal [project] reads — name and version only, quoted single-line form.\n const section = /\\[project\\]([\\s\\S]*?)(\\n\\[|$)/.exec(text)?.[1] ?? \"\";\n const name = /\\bname\\s*=\\s*\"([^\"]+)\"/.exec(section)?.[1];\n const version = /\\bversion\\s*=\\s*\"([^\"]+)\"/.exec(section)?.[1];\n return { name, version };\n } catch {\n return {};\n }\n}\n\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): { name?: string; version?: string } {\n for (const rel of [\"schema/world.json\", path.join(\"server\", \"world\", \"schema\", \"world.json\")]) {\n try {\n const parsed = JSON.parse(fs.readFileSync(path.join(dir, rel), \"utf-8\")) 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, or not at this root\n }\n }\n return {};\n}\n\nfunction buildFileManifest(\n dir: string,\n): { path: string; isDirectory: boolean; size: number; sha256: string }[] {\n const entries: { path: string; isDirectory: boolean; size: number; sha256: string }[] = [];\n const walk = (rel: string) => {\n const abs = rel ? path.join(dir, rel) : dir;\n for (const entry of fs.readdirSync(abs, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {\n const childRel = rel ? `${rel}/${entry.name}` : entry.name;\n if (entry.isDirectory()) {\n if (!SKIP_DIRS.has(entry.name) && !entry.name.endsWith(\".egg-info\")) {\n walk(childRel);\n }\n } else if (entry.isFile()) {\n const payload = fs.readFileSync(path.join(dir, childRel));\n entries.push({\n path: childRel,\n isDirectory: false,\n size: payload.length,\n sha256: createHash(\"sha256\").update(payload).digest(\"hex\"),\n });\n }\n }\n };\n walk(\"\");\n return entries;\n}\n\nasync function putObject(url: string, data: Buffer, shaB64: string): Promise<void> {\n const resp = await fetch(url, {\n method: \"PUT\",\n headers: {\n \"Content-Type\": \"application/gzip\",\n \"x-amz-checksum-sha256\": shaB64,\n },\n body: new Uint8Array(data),\n });\n if (!resp.ok) {\n throw new Error(`object PUT -> ${resp.status}: ${(await resp.text()).slice(0, 300)}`);\n }\n}\n\n// ── the workflows ────────────────────────────────────────────────────────────\n\nexport async function push(\n dir: string,\n opts: {\n slug?: string;\n branch?: string;\n force?: boolean;\n message?: string;\n author?: string;\n /** 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()) throw new Error(`Not a directory: ${dir}`);\n const localMeta = readLocalMeta(dir) ?? {};\n const branch = opts.branch ?? (localMeta.branch as string | undefined) ?? DEFAULT_BRANCH;\n const baseVersionId = opts.baseVersionId ?? localMeta.versionId ?? null;\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 ? undefined : readWorldContractVersion(dir).version;\n if (contractVersion) pyproject.version = contractVersion;\n const slug = opts.slug ?? pyproject.name ?? path.basename(path.resolve(dir));\n\n const resolve = await apiRequest<{ containerId: string }>(\n options,\n \"POST\",\n \"/api/public/benchmark-containers/resolve\",\n {\n slug,\n name: opts.name ?? pyproject.name ?? slug,\n ...(opts.description ? { description: opts.description } : {}),\n ...(opts.tags?.length ? { tags: opts.tags } : {}),\n ...(opts.visibility ? { visibility: opts.visibility } : {}),\n },\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: buildFileManifest(dir),\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) 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 { branch, baseVersionId, ...(opts.force ? { force: true } : {}) },\n );\n\n writeLocalMeta(dir, {\n ...localMeta,\n slug,\n ref: branch,\n branch,\n versionId: version.versionId,\n contentHash,\n semanticVersion: pyproject.version,\n forkedFromVersionId: baseVersionId,\n baseFiles: snapshotTreeHashes(dir),\n });\n return {\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). */\nfunction extractBundle(bundle: Buffer, dir: string): number {\n const tar = gunzipSync(bundle);\n let offset = 0;\n let longName: string | null = null;\n let written = 0;\n while (offset + 512 <= tar.length) {\n const header = tar.subarray(offset, offset + 512);\n offset += 512;\n if (header.every((b) => b === 0)) break;\n const rawName = header.subarray(0, 100).toString(\"utf-8\").replace(/\\0.*$/, \"\");\n const size = parseInt(header.subarray(124, 136).toString(\"ascii\").replace(/\\0.*$/, \"\").trim(), 8) || 0;\n const typeflag = header.subarray(156, 157).toString(\"ascii\");\n const body = tar.subarray(offset, offset + size);\n offset += size + (size % 512 === 0 ? 0 : 512 - (size % 512));\n if (typeflag === \"L\") {\n longName = body.toString(\"utf-8\").replace(/\\0.*$/, \"\");\n continue;\n }\n const name = (longName ?? rawName).replace(/^\\.\\//, \"\");\n longName = null;\n if (typeflag !== \"0\" && typeflag !== \"\") continue;\n // Safe extract: no absolute paths, no traversal.\n if (name.startsWith(\"/\") || name.split(\"/\").includes(\"..\")) continue;\n const target = path.join(dir, name);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n fs.writeFileSync(target, body);\n written++;\n }\n return written;\n}\n\nexport async function pull(\n slugRef: string,\n target?: string,\n options: WorldsClientOptions = {},\n): Promise<{ slug: string; dir: string; versionId: string; files: number }> {\n const at = slugRef.indexOf(\"@\");\n const slug = at === -1 ? slugRef : slugRef.slice(0, at);\n const ref = at === -1 ? \"latest\" : slugRef.slice(at + 1);\n\n const details = await apiRequest<{\n versionId: string;\n contentHash: string;\n semanticVersion?: string | null;\n downloadUrl?: string;\n bundleSha256?: string;\n }>(options, \"POST\", \"/api/public/benchmark-containers/resolve-version\", {\n slug,\n ref,\n });\n if (!details.downloadUrl) {\n throw new Error(`${slug}@${ref} resolved but has no uploaded bundle`);\n }\n\n let dir = target ?? path.join(process.cwd(), slug);\n if (!target) {\n let i = 1;\n const base = dir;\n while (fs.existsSync(dir)) dir = `${base}-${i++}`;\n }\n fs.mkdirSync(dir, { recursive: true });\n\n const resp = await fetch(details.downloadUrl);\n if (!resp.ok) throw new Error(`bundle download -> ${resp.status}`);\n const bundle = Buffer.from(await resp.arrayBuffer());\n if (details.bundleSha256 && sha256b64(bundle) !== details.bundleSha256) {\n throw new Error(\n `bundle integrity check failed for ${slug}@${ref}: downloaded sha256 != recorded bundleSha256`,\n );\n }\n\n const files = extractBundle(bundle, dir);\n const branch = ref === \"latest\" || /^\\d|^[0-9a-f]{8,}$/.test(ref) ? DEFAULT_BRANCH : ref;\n writeLocalMeta(dir, {\n slug,\n ref,\n branch,\n versionId: details.versionId,\n contentHash: details.contentHash,\n semanticVersion: details.semanticVersion ?? undefined,\n baseFiles: snapshotTreeHashes(dir),\n });\n return { slug, dir, versionId: details.versionId, files };\n}\n\nexport async function propose(\n dir: string,\n opts: { title: string; reason: string; targetBranch?: string; options?: WorldsClientOptions },\n): Promise<{ proposalId: string }> {\n const meta = readLocalMeta(dir);\n if (!meta?.slug || !meta.baseFiles) {\n throw new Error(\"This dir has no pull/push base — run pull first, then edit, then propose.\");\n }\n const state = localTreeState(dir);\n if (state.clean) throw new Error(\"Nothing to propose — the tree matches its base.\");\n const changes = state.dirty.map((relPath) => {\n const abs = path.join(dir, relPath);\n if (!fs.existsSync(abs)) return { path: relPath, action: \"delete\" as const };\n return {\n path: relPath,\n action: \"write\" as const,\n newContent: fs.readFileSync(abs, \"utf-8\"),\n };\n });\n const res = await apiRequest<{ proposalId: string }>(\n opts.options ?? {},\n \"POST\",\n \"/api/public/benchmark-containers/proposals\",\n {\n slug: meta.slug,\n title: opts.title,\n changeReason: opts.reason,\n baseVersionId: meta.versionId,\n ...(opts.targetBranch ? { targetBranch: opts.targetBranch } : {}),\n changes,\n },\n );\n return res;\n}\n\nexport async function createRef(\n slug: string,\n name: string,\n kind: \"branch\" | \"tag\",\n versionId?: string,\n options: WorldsClientOptions = {},\n): Promise<{ name: string; kind: string; versionId: string }> {\n return apiRequest(options, \"POST\", \"/api/public/benchmark-containers/refs\", {\n slug,\n name,\n kind,\n ...(versionId ? { versionId } : {}),\n });\n}\n","/**\n * PR validation: push the checkout's world source, run it, gate on the graded\n * result — one composed call, because CI should not have to re-derive the\n * choreography from primitives.\n *\n * The differentiating property, stated so it stays true: validation runs the\n * PULL REQUEST'S OWN world source. The push files the checkout as a version on\n * the PR's branch (content-hash dedup makes re-runs cheap), the dispatch pins\n * that version, and the platform resolves the branch back to its open PR — so\n * the run page names the PR and the PR comment names the run. Nothing here\n * validates a standing deployment while pretending to validate the change.\n */\n\nimport {\n apiRequest,\n detectProvenance,\n listRunConfigs,\n waitForRun,\n type RunReport,\n type WorldsClientOptions,\n} from \"./index\";\nimport { push } from \"./hub\";\n\nexport type ValidatedRun = {\n model: string;\n runId: string;\n report: RunReport | null;\n /** Why this run fails the gate, or null when it passes. */\n failure: string | null;\n};\n\nexport type ValidateReport = {\n ok: boolean;\n slug: string;\n branch: string;\n versionId: string;\n contentHash: string;\n runConfig: { id: string; name: string };\n runs: ValidatedRun[];\n /** A PR-comment-ready summary of the whole validation. */\n markdown: string;\n};\n\nfunction fmtScore(score: number | null): string {\n return score === null ? \"no score\" : score.toFixed(3);\n}\n\nfunction buildMarkdown(\n report: Omit<ValidateReport, \"markdown\">,\n minScore: number | null,\n 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 progress(`pushing ${dir} as ${opts.slug ?? \"(pyproject name)\"}@${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 if (opts.slug) {\n try {\n const tip = await apiRequest<{ versionId?: string }>(\n options,\n \"POST\",\n \"/api/public/benchmark-containers/resolve-version\",\n { slug: opts.slug, ref: branch },\n );\n tipVersionId = tip.versionId ?? null;\n } catch {\n tipVersionId = null;\n }\n }\n const pushed = await push(dir, {\n slug: opts.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 = /^[ \\t\\n\\r\\f\\v]+|[ \\t\\n\\r\\f\\v]+$/g;\nconst WHITESPACE_RUN = /[ \\t\\n\\r\\f\\v]+/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, entity, {where, resolve, limit, offset})` — the rows of\n * one entity that match a predicate, from\n * `GET /api/public/worlds/{slug}/data?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. */\nexport function queryRowsSearch(entity: string, opts: WorldQueryOptions = {}): string {\n const search = new URLSearchParams();\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/** The world's head version, queried. The route reads the head only, so a\n * `slug@ref` is refused rather than silently served as the head. With\n * `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 slug: string,\n entity: string,\n opts: WorldQueryOptions = {},\n options: WorldsClientOptions = {},\n): Promise<WorldQueryResult | WorldQueryAcrossResult> {\n if (slug.includes(\"@\"))\n throw new Error(\n `queryRows reads a world's head version: pass the slug without @ref (got ${slug})`,\n );\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)}`,\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. */\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\n/** A serialized value back to JSON when it parses; otherwise as it is. */\nfunction jsonish(value: unknown): unknown {\n if (typeof value !== \"string\") return value;\n try {\n return JSON.parse(value);\n } catch {\n return value;\n }\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 * A serialized `input`/`output` (the SDK stores JSON text) is parsed back;\n * an `input` that is not an object leaves `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 input = jsonish(observation.input);\n const record: ToolCallRecord = { tool, args: isObject(input) ? input : {} };\n if (observation.level === \"ERROR\") record.error = observation.statusMessage || \"ERROR\";\n else record.result = jsonish(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","/**\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/** 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) {\n throw new Error(\n `${method} ${path} -> ${res.status}: ${text.slice(0, 400)}`,\n );\n }\n return JSON.parse(text) as T;\n}\n\n/** Set (or rotate) one environment secret — write-only: no API returns it. */\nexport async function setEnvSecret(\n slug: string,\n key: string,\n value: string,\n options: WorldsClientOptions = {},\n): Promise<{ key: string; created: boolean }> {\n return apiRequest(\n options,\n \"PUT\",\n \"/api/public/benchmark-containers/secrets\",\n {\n slug,\n key,\n value,\n },\n );\n}\n\n/** Keys and rotation timestamps only — never values. */\nexport async function listEnvSecretKeys(\n slug: string,\n options: WorldsClientOptions = {},\n): Promise<{ key: string; updatedAt: string }[]> {\n const res = await apiRequest<{\n secrets: { key: string; updatedAt: string }[];\n }>(\n options,\n \"GET\",\n `/api/public/benchmark-containers/secrets?slug=${encodeURIComponent(slug)}`,\n );\n return res.secrets;\n}\n\nexport async function deleteEnvSecret(\n slug: string,\n key: string,\n options: WorldsClientOptions = {},\n): Promise<void> {\n await apiRequest(\n options,\n \"DELETE\",\n \"/api/public/benchmark-containers/secrets\",\n {\n slug,\n key,\n },\n );\n}\n\nexport type RunConfigSummary = {\n id: string;\n name: string;\n runType: string;\n createdAt: string;\n models: string[];\n parallelism: number;\n autoRunOnPush: boolean;\n agent: string | null;\n};\n\n/** Run configs in the project. CI resolves by NAME and dispatches by id. */\nexport async function listRunConfigs(\n options: WorldsClientOptions = {},\n): Promise<RunConfigSummary[]> {\n const res = await apiRequest<{ runConfigs: RunConfigSummary[] }>(\n options,\n \"GET\",\n \"/api/public/benchmark-containers/run-configs\",\n );\n return res.runConfigs;\n}\n\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\n const version = await apiRequest<\n ResolvedWorldVersion & { taskNames?: string[] }\n >(options, \"POST\", \"/api/public/benchmark-containers/resolve-version\", {\n slug,\n ...(ref ? { ref } : {}),\n });\n\n const world = new WorldSet(\n slugRef,\n slug,\n ref,\n {\n versionId: version.versionId,\n semanticVersion: version.semanticVersion ?? null,\n contentHash: version.contentHash,\n state: version.state,\n },\n [],\n options,\n );\n for (const name of version.taskNames ?? []) {\n const variant = /^[a-z0-9]+-([a-z0-9]+)-/.exec(name)?.[1] ?? null;\n world.tasks.push(new WorldTask(world, name, variant));\n }\n return world;\n}\n\n// The session surface completes the worlds module, so `@withgateway/sdk/worlds`\n// carries both halves: running a world locally, and driving one the platform\n// hosts. (session.ts imports apiRequest from here; the cycle is function-level\n// only, and the build below is what proves it resolves.)\nexport * from \"./session\";\n\n// Stored tasks: the task spec as a named, versioned project resource that\n// `openSession(world, { task: { id } })` opens on.\nexport * from \"./tasks\";\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 * 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,wBA6QM,kBAGA,iBAIA;AApRN;AAAA;AAAA;AAAA,yBAA2B;AAE3B;AACA;AA0QA,IAAM,mBAAmB,KAAK;AAG9B,IAAM,kBAAkB,IAAI;AAI5B,IAAM,0BAA0B,KAAK;AAAA;AAAA;;;ACpRrC;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,qBACA,kBACA,IACA,MAuBM;AA1BN;AAAA;AAAA;AAAA,IAAAA,sBAA2B;AAC3B,uBAAqC;AACrC,SAAoB;AACpB,WAAsB;AACtB;AAsBA,IAAM,eAAoB,UAAK,YAAY,oBAAoB;AAAA;AAAA;;;AC1B/D;AAAA;AAAA;AAaA;AAQA;AAAA;AAAA;;;ACrBA;AAAA;AAAA;AAUA;AAAA;AAAA;;;ACVA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAuBAC,qBAOM,kBACA,gBACA,WAEO,cAEP,MAEA,gBAKA,aAUA,KAGA,QAiBO;AAzEb;AAAA;AAAA;AAuBA,IAAAA,sBAA2B;AAE3B;AAKA,IAAM,mBAAmB;AACzB,IAAM,iBAAiB;AACvB,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,cACzC,gCAAW,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;;;ACzEhG,IAcAC;AAdA;AAAA;AAAA;AAcA,IAAAA,sBAA2B;AAE3B;AACA;AAAA;AAAA;;;ACjBA;AAAA;AAAA;AAoBA;AAAA;AAAA;;;ACpBA;AAAA;AAAA;AAWA;AAAA;AAAA;;;ACXA,IAoCAC,KACA,IACAC;AAtCA;AAAA;AAAA;AAoCA,IAAAD,MAAoB;AACpB,SAAoB;AACpB,IAAAC,QAAsB;AAEtB;AAAA;AAAA;;;ACAA,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;AAIA,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,IAAI;AACX,UAAM,IAAI;AAAA,MACR,GAAG,MAAM,IAAIA,KAAI,OAAO,IAAI,MAAM,KAAK,KAAK,MAAM,GAAG,GAAG,CAAC;AAAA,IAC3D;AAAA,EACF;AACA,SAAO,KAAK,MAAM,IAAI;AACxB;AA/EA;AAAA;AAAA;AA+cA;AAIA;AAIA;AAKA;AAGA;AAKA;AACA;AACA;AAKA;AAIA;AAKA;AAAA;AAAA;;;ACpfA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAYA;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":["import_node_crypto","import_node_crypto","import_node_crypto","fs","path","path"]}
|
|
1
|
+
{"version":3,"sources":["../../src/worlds/browser.ts","../../src/worlds/session.ts","../../src/worlds/tasks.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/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};\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\nconst 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 },\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. */\n async grade(opts: { timeoutMs?: number } = {}): Promise<GradeResult> {\n const raw = (await this.exchange(\n { kind: \"grade\" },\n opts.timeoutMs,\n )) as Record<string, unknown> | null;\n const record = raw && typeof raw === \"object\" ? raw : {};\n const rewards: Record<string, number> = {};\n 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 state = await apiRequest<WorldSessionState & { reusedWarm: boolean }>(\n options,\n \"POST\",\n \"/api/public/world-sessions\",\n {\n ...(opts.versionId ? { versionId: opts.versionId } : { slug }),\n task,\n ...(opts.reuseWarm === undefined ? {} : { reuseWarm: opts.reuseWarm }),\n ...(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 /** True when `mean >= failUnder` (or no gate was set). */\n passed: boolean;\n};\n\n/**\n * RUN MANY TASKS IN PARALLEL, one warm container each.\n *\n * Parallelism against live worlds is the normal case — a suite is a dozen\n * tasks and each needs its own container, because two agents sharing one\n * world state would corrupt both episodes. Every caller was writing the same\n * pool, the same per-task open/ready/toolkit/grade/close, and the same\n * \"don't let one failure kill the run\" logic, so it belongs here:\n *\n * const report = await runSessions({\n * world: \"revenue-ops-sim@main\",\n * tasks, // default: every task in the world\n * concurrency: 4,\n * failUnder: 0.7,\n * agent: async ({ toolkit, instruction }) =>\n * myAgent(toolkit.impls, toolkit.schemas, instruction),\n * });\n *\n * The handler gets a ready session with its toolkit already bound; grading,\n * closing (warm) and aggregation are handled. A task that throws scores 0\n * and records why — the tasks that passed keep their results.\n */\nexport async function runSessions(opts: {\n world: string;\n /** 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.\n const { openWorld } = await import(\"./index\");\n const world = await openWorld(opts.world, options);\n tasks = tasks ?? world.tasks.map((t) => t.name);\n versionId = versionId ?? world.version.versionId;\n }\n\n const results: SessionRunResult[] = [];\n let next = 0;\n await Promise.all(\n Array.from({ length: Math.min(concurrency, tasks.length) }, async () => {\n while (next < tasks!.length) {\n const 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 return {\n results: results.sort((a, b) => a.task.localeCompare(b.task)),\n mean,\n passed: opts.failUnder === undefined ? true : mean >= opts.failUnder,\n };\n}\n","import { 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 WorldTaskValidation = {\n taskId: string;\n version: number;\n /** The world version the task was checked against. */\n versionId: string;\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. */\n checked: \"entities\" | \"none\";\n problems: string[];\n entities: string[] | null;\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 { createHash } from \"node:crypto\";\nimport { gzipSync, gunzipSync } from \"node:zlib\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\n\n/**\n * The working-dir half of the TS CLI: push / pull / checkout / status /\n * branch / tag / propose — a faithful port of the Python client\n * (`gatewaysdk/benchmark_hub/client.py` + `_archive.py`).\n *\n * LOCKSTEP WARNING — the content hash is the version's identity and is\n * byte-compatible with Prime Intellect. It now has FOUR implementations that\n * must stay identical: worker `environmentAgent/tar.ts`, web\n * `benchmark-hub/server/benchmarkContentHash.ts`, Python `_archive.py`, and\n * this file. This one is a line-for-line port of the WEB TypeScript\n * implementation (same language, same crypto) — if the rule ever changes,\n * change all four or push identity splits by client.\n *\n * One deliberate refusal, same policy as the web upload path: a bundle with\n * a ROOT `.gitignore` is refused rather than mis-hashed — the Python CLI\n * honors it via `gitignore_parser`, and an imperfect reimplementation here\n * would produce a wrong, Prime-incompatible hash silently.\n */\n\nexport const DEFAULT_BRANCH = \"main\";\nconst META_RELPATH = path.join(\".gateway\", \".env-metadata.json\");\nconst SKIP_DIRS = new Set([\n \".git\",\n \"__pycache__\",\n \"node_modules\",\n \".venv\",\n \".mypy_cache\",\n \"dist\",\n \"build\",\n \"outputs\",\n]);\nconst ROOT_EXCLUDED_DIRS = new Set([\"dist\", \"build\", \"outputs\", \"__pycache__\"]);\n\n/** Gateway-only root markers that widen collection to every ordinary root\n * file. The FOURTH copy of this list (python SDK `_archive.py`, web\n * `benchmarkContentHash.ts`, worker `tar.ts`, and here) — all four MUST stay\n * identical or the same tree hashes differently per pusher. This copy\n * missing `gateway-api-world.toml` is exactly how an api world pushed from\n * TS landed on the hub with no OpenAPI contract and no marker: the root\n * files never entered the manifest, and nothing downstream could tell. */\nconst BROAD_ROOT_MARKERS = [\"gateway-env.toml\", \"gateway-api-world.toml\"];\n\n// ── content-hash rules (port of web benchmarkContentHash.ts) ───────────────\n\nfunction isExcludedDirComponent(component: string): boolean {\n return (\n component.startsWith(\".\") ||\n ROOT_EXCLUDED_DIRS.has(component) ||\n component.endsWith(\".egg-info\")\n );\n}\n\nexport function isIncludedInContentHash(\n relPath: string,\n includeAllRootFiles: boolean,\n): boolean {\n const parts = relPath.split(\"/\");\n const name = parts[parts.length - 1];\n const dirParts = parts.slice(0, -1);\n if (name.startsWith(\".\")) return false;\n if (parts.includes(\"__pycache__\")) return false;\n if (dirParts.length === 0) {\n return (\n includeAllRootFiles ||\n name === \"README.md\" ||\n name === \"pyproject.toml\" ||\n BROAD_ROOT_MARKERS.includes(name) ||\n name.endsWith(\".py\")\n );\n }\n return !dirParts.some(isExcludedDirComponent);\n}\n\n/** The archive-visible files of a working dir, as sorted relpaths. Throws on\n * a root .gitignore (see the header). */\nexport function collectArchiveRelPaths(dir: string): string[] {\n if (fs.existsSync(path.join(dir, \".gitignore\"))) {\n throw new Error(\n \"This bundle has a root .gitignore, which the Python CLI honors via \" +\n \"gitignore_parser. Reimplementing that imperfectly here would \" +\n \"silently produce a different content hash, so the TS CLI refuses. \" +\n \"Remove the .gitignore (or bake its effect into the tree) and retry.\",\n );\n }\n const out: string[] = [];\n const includeAllRootFiles = BROAD_ROOT_MARKERS.some((marker) =>\n fs.existsSync(path.join(dir, marker)),\n );\n const walk = (rel: string) => {\n const abs = rel ? path.join(dir, rel) : dir;\n for (const entry of fs.readdirSync(abs, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {\n const childRel = rel ? `${rel}/${entry.name}` : entry.name;\n if (entry.isDirectory()) {\n if (!isExcludedDirComponent(entry.name)) walk(childRel);\n } else if (entry.isFile()) {\n if (isIncludedInContentHash(childRel, includeAllRootFiles)) {\n out.push(childRel);\n }\n }\n }\n };\n walk(\"\");\n return out.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));\n}\n\nexport function computeContentHash(dir: string): string {\n const hasher = createHash(\"sha256\");\n for (const relPath of collectArchiveRelPaths(dir)) {\n hasher.update(Buffer.from(`file:${relPath}`, \"utf-8\"));\n hasher.update(fs.readFileSync(path.join(dir, relPath)));\n }\n return hasher.digest(\"hex\");\n}\n\n// ── deterministic tar.gz writer ─────────────────────────────────────────────\n\nfunction octal(value: number, length: number): Buffer {\n return Buffer.from(value.toString(8).padStart(length - 1, \"0\") + \"\\0\", \"ascii\");\n}\n\nfunction tarHeader(name: string, size: number): Buffer {\n const header = Buffer.alloc(512);\n header.write(name, 0, 100, \"utf-8\");\n octal(0o644, 8).copy(header, 100); // mode\n octal(0, 8).copy(header, 108); // uid\n octal(0, 8).copy(header, 116); // gid\n octal(size, 12).copy(header, 124);\n octal(0, 12).copy(header, 136); // mtime = 0 (deterministic)\n header.write(\" \", 148, \"ascii\"); // checksum placeholder = spaces\n header.write(\"0\", 156, \"ascii\"); // regular file\n header.write(\"ustar\", 257, \"ascii\");\n header.write(\"00\", 263, \"ascii\");\n let sum = 0;\n for (const byte of header) sum += byte;\n header.write(sum.toString(8).padStart(6, \"0\") + \"\\0 \", 148, \"ascii\");\n return header;\n}\n\nfunction tarMember(name: string, payload: Buffer): Buffer[] {\n const parts: Buffer[] = [];\n const nameBytes = Buffer.byteLength(name, \"utf-8\");\n if (nameBytes > 100) {\n // GNU long name: an 'L' member whose body is the real name.\n const body = Buffer.from(name + \"\\0\", \"utf-8\");\n const lHeader = tarHeader(\"././@LongLink\", body.length);\n lHeader.write(\"L\", 156, \"ascii\");\n let sum = 0;\n lHeader.write(\" \", 148, \"ascii\");\n for (const byte of lHeader) sum += byte;\n lHeader.write(sum.toString(8).padStart(6, \"0\") + \"\\0 \", 148, \"ascii\");\n parts.push(lHeader, body);\n const pad = body.length % 512 === 0 ? 0 : 512 - (body.length % 512);\n if (pad) parts.push(Buffer.alloc(pad));\n parts.push(tarHeader(name.slice(0, 100), payload.length));\n } else {\n parts.push(tarHeader(name, payload.length));\n }\n parts.push(payload);\n const pad = payload.length % 512 === 0 ? 0 : 512 - (payload.length % 512);\n if (pad) parts.push(Buffer.alloc(pad));\n return parts;\n}\n\n/** A deterministic .tar.gz of the source files (node's gzip stamps no mtime,\n * matching the Python's mtime=0 gzip). */\nexport function buildSourceTarball(dir: string): Buffer {\n const parts: Buffer[] = [];\n for (const relPath of collectArchiveRelPaths(dir)) {\n parts.push(...tarMember(relPath, fs.readFileSync(path.join(dir, relPath))));\n }\n parts.push(Buffer.alloc(1024)); // end-of-archive\n return gzipSync(Buffer.concat(parts), { level: 9 });\n}\n\n// ── local metadata (.gateway/.env-metadata.json) ────────────────────────────\n\nexport type LocalMeta = Record<string, unknown> & {\n slug?: string;\n branch?: string;\n versionId?: string;\n contentHash?: string;\n baseFiles?: Record<string, string>;\n};\n\nexport function readLocalMeta(dir: string): LocalMeta | null {\n try {\n const raw = fs.readFileSync(path.join(dir, META_RELPATH), \"utf-8\");\n const parsed = JSON.parse(raw);\n return parsed && typeof parsed === \"object\" ? (parsed as LocalMeta) : null;\n } catch {\n return null;\n }\n}\n\nexport function writeLocalMeta(dir: string, meta: LocalMeta): void {\n fs.mkdirSync(path.join(dir, \".gateway\"), { recursive: true });\n fs.writeFileSync(path.join(dir, META_RELPATH), JSON.stringify(meta, null, 2));\n}\n\nexport function snapshotTreeHashes(dir: string): Record<string, string> {\n const out: Record<string, string> = {};\n for (const relPath of collectArchiveRelPaths(dir)) {\n out[relPath] = createHash(\"sha256\")\n .update(fs.readFileSync(path.join(dir, relPath)))\n .digest(\"hex\");\n }\n return out;\n}\n\nexport function localTreeState(dir: string): {\n meta: LocalMeta | null;\n dirty: string[];\n clean: boolean;\n} {\n const meta = readLocalMeta(dir);\n const base = meta?.baseFiles;\n if (!base || typeof base !== \"object\") {\n return { meta, dirty: [], clean: false };\n }\n const now = snapshotTreeHashes(dir);\n const dirty = new Set<string>();\n for (const [p, h] of Object.entries(now)) if (base[p] !== h) dirty.add(p);\n for (const p of Object.keys(base)) if (!(p in now)) dirty.add(p);\n return { meta, dirty: [...dirty].sort(), clean: dirty.size === 0 };\n}\n\n// ── protocol helpers ─────────────────────────────────────────────────────────\n\nconst sha256b64 = (data: Buffer) =>\n createHash(\"sha256\").update(data).digest(\"base64\");\n\nfunction readPyproject(dir: string): { name?: string; version?: string } {\n try {\n const text = fs.readFileSync(path.join(dir, \"pyproject.toml\"), \"utf-8\");\n // Minimal [project] reads — name and version only, quoted single-line form.\n const section = /\\[project\\]([\\s\\S]*?)(\\n\\[|$)/.exec(text)?.[1] ?? \"\";\n const name = /\\bname\\s*=\\s*\"([^\"]+)\"/.exec(section)?.[1];\n const version = /\\bversion\\s*=\\s*\"([^\"]+)\"/.exec(section)?.[1];\n return { name, version };\n } catch {\n return {};\n }\n}\n\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): { name?: string; version?: string } {\n for (const rel of [\"schema/world.json\", path.join(\"server\", \"world\", \"schema\", \"world.json\")]) {\n try {\n const parsed = JSON.parse(fs.readFileSync(path.join(dir, rel), \"utf-8\")) 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, or not at this root\n }\n }\n return {};\n}\n\nfunction buildFileManifest(\n dir: string,\n): { path: string; isDirectory: boolean; size: number; sha256: string }[] {\n const entries: { path: string; isDirectory: boolean; size: number; sha256: string }[] = [];\n const walk = (rel: string) => {\n const abs = rel ? path.join(dir, rel) : dir;\n for (const entry of fs.readdirSync(abs, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {\n const childRel = rel ? `${rel}/${entry.name}` : entry.name;\n if (entry.isDirectory()) {\n if (!SKIP_DIRS.has(entry.name) && !entry.name.endsWith(\".egg-info\")) {\n walk(childRel);\n }\n } else if (entry.isFile()) {\n const payload = fs.readFileSync(path.join(dir, childRel));\n entries.push({\n path: childRel,\n isDirectory: false,\n size: payload.length,\n sha256: createHash(\"sha256\").update(payload).digest(\"hex\"),\n });\n }\n }\n };\n walk(\"\");\n return entries;\n}\n\nasync function putObject(url: string, data: Buffer, shaB64: string): Promise<void> {\n const resp = await fetch(url, {\n method: \"PUT\",\n headers: {\n \"Content-Type\": \"application/gzip\",\n \"x-amz-checksum-sha256\": shaB64,\n },\n body: new Uint8Array(data),\n });\n if (!resp.ok) {\n throw new Error(`object PUT -> ${resp.status}: ${(await resp.text()).slice(0, 300)}`);\n }\n}\n\n// ── the workflows ────────────────────────────────────────────────────────────\n\nexport async function push(\n dir: string,\n opts: {\n slug?: string;\n branch?: string;\n force?: boolean;\n message?: string;\n author?: string;\n /** 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()) throw new Error(`Not a directory: ${dir}`);\n const localMeta = readLocalMeta(dir) ?? {};\n const branch = opts.branch ?? (localMeta.branch as string | undefined) ?? DEFAULT_BRANCH;\n const baseVersionId = opts.baseVersionId ?? localMeta.versionId ?? null;\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 ? undefined : 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 = opts.slug ?? localMeta.slug ?? pyproject.name ?? path.basename(path.resolve(dir));\n\n const resolve = await apiRequest<{ containerId: string }>(\n options,\n \"POST\",\n \"/api/public/benchmark-containers/resolve\",\n {\n slug,\n name: opts.name ?? pyproject.name ?? slug,\n ...(opts.description ? { description: opts.description } : {}),\n ...(opts.tags?.length ? { tags: opts.tags } : {}),\n ...(opts.visibility ? { visibility: opts.visibility } : {}),\n },\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: buildFileManifest(dir),\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) 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 { branch, baseVersionId, ...(opts.force ? { force: true } : {}) },\n );\n\n writeLocalMeta(dir, {\n ...localMeta,\n slug,\n ref: branch,\n branch,\n versionId: version.versionId,\n contentHash,\n semanticVersion: pyproject.version,\n forkedFromVersionId: baseVersionId,\n baseFiles: snapshotTreeHashes(dir),\n });\n return {\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). */\nfunction extractBundle(bundle: Buffer, dir: string): number {\n const tar = gunzipSync(bundle);\n let offset = 0;\n let longName: string | null = null;\n let written = 0;\n while (offset + 512 <= tar.length) {\n const header = tar.subarray(offset, offset + 512);\n offset += 512;\n if (header.every((b) => b === 0)) break;\n const rawName = header.subarray(0, 100).toString(\"utf-8\").replace(/\\0.*$/, \"\");\n const size = parseInt(header.subarray(124, 136).toString(\"ascii\").replace(/\\0.*$/, \"\").trim(), 8) || 0;\n const typeflag = header.subarray(156, 157).toString(\"ascii\");\n const body = tar.subarray(offset, offset + size);\n offset += size + (size % 512 === 0 ? 0 : 512 - (size % 512));\n if (typeflag === \"L\") {\n longName = body.toString(\"utf-8\").replace(/\\0.*$/, \"\");\n continue;\n }\n const name = (longName ?? rawName).replace(/^\\.\\//, \"\");\n longName = null;\n if (typeflag !== \"0\" && typeflag !== \"\") continue;\n // Safe extract: no absolute paths, no traversal.\n if (name.startsWith(\"/\") || name.split(\"/\").includes(\"..\")) continue;\n const target = path.join(dir, name);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n fs.writeFileSync(target, body);\n written++;\n }\n return written;\n}\n\nexport async function pull(\n slugRef: string,\n target?: string,\n options: WorldsClientOptions = {},\n): Promise<{ slug: string; dir: string; versionId: string; files: number }> {\n const at = slugRef.indexOf(\"@\");\n const slug = at === -1 ? slugRef : slugRef.slice(0, at);\n const ref = at === -1 ? \"latest\" : slugRef.slice(at + 1);\n\n const details = await apiRequest<{\n versionId: string;\n contentHash: string;\n semanticVersion?: string | null;\n downloadUrl?: string;\n bundleSha256?: string;\n }>(options, \"POST\", \"/api/public/benchmark-containers/resolve-version\", {\n slug,\n ref,\n });\n if (!details.downloadUrl) {\n throw new Error(`${slug}@${ref} resolved but has no uploaded bundle`);\n }\n\n let dir = target ?? path.join(process.cwd(), slug);\n if (!target) {\n let i = 1;\n const base = dir;\n while (fs.existsSync(dir)) dir = `${base}-${i++}`;\n }\n fs.mkdirSync(dir, { recursive: true });\n\n const resp = await fetch(details.downloadUrl);\n if (!resp.ok) throw new Error(`bundle download -> ${resp.status}`);\n const bundle = Buffer.from(await resp.arrayBuffer());\n if (details.bundleSha256 && sha256b64(bundle) !== details.bundleSha256) {\n throw new Error(\n `bundle integrity check failed for ${slug}@${ref}: downloaded sha256 != recorded bundleSha256`,\n );\n }\n\n const files = extractBundle(bundle, dir);\n const branch = ref === \"latest\" || /^\\d|^[0-9a-f]{8,}$/.test(ref) ? DEFAULT_BRANCH : ref;\n writeLocalMeta(dir, {\n slug,\n ref,\n branch,\n versionId: details.versionId,\n contentHash: details.contentHash,\n semanticVersion: details.semanticVersion ?? undefined,\n baseFiles: snapshotTreeHashes(dir),\n });\n return { slug, dir, versionId: details.versionId, files };\n}\n\nexport async function propose(\n dir: string,\n opts: { title: string; reason: string; targetBranch?: string; options?: WorldsClientOptions },\n): Promise<{ proposalId: string }> {\n const meta = readLocalMeta(dir);\n if (!meta?.slug || !meta.baseFiles) {\n throw new Error(\"This dir has no pull/push base — run pull first, then edit, then propose.\");\n }\n const state = localTreeState(dir);\n if (state.clean) throw new Error(\"Nothing to propose — the tree matches its base.\");\n const changes = state.dirty.map((relPath) => {\n const abs = path.join(dir, relPath);\n if (!fs.existsSync(abs)) return { path: relPath, action: \"delete\" as const };\n return {\n path: relPath,\n action: \"write\" as const,\n newContent: fs.readFileSync(abs, \"utf-8\"),\n };\n });\n const res = await apiRequest<{ proposalId: string }>(\n opts.options ?? {},\n \"POST\",\n \"/api/public/benchmark-containers/proposals\",\n {\n slug: meta.slug,\n title: opts.title,\n changeReason: opts.reason,\n baseVersionId: meta.versionId,\n ...(opts.targetBranch ? { targetBranch: opts.targetBranch } : {}),\n changes,\n },\n );\n return res;\n}\n\nexport async function createRef(\n slug: string,\n name: string,\n kind: \"branch\" | \"tag\",\n versionId?: string,\n options: WorldsClientOptions = {},\n): Promise<{ name: string; kind: string; versionId: string }> {\n return apiRequest(options, \"POST\", \"/api/public/benchmark-containers/refs\", {\n slug,\n name,\n kind,\n ...(versionId ? { versionId } : {}),\n });\n}\n","/**\n * PR validation: push the checkout's world source, run it, gate on the graded\n * result — one composed call, because CI should not have to re-derive the\n * choreography from primitives.\n *\n * The differentiating property, stated so it stays true: validation runs the\n * PULL REQUEST'S OWN world source. The push files the checkout as a version on\n * the PR's branch (content-hash dedup makes re-runs cheap), the dispatch pins\n * that version, and the platform resolves the branch back to its open PR — so\n * the run page names the PR and the PR comment names the run. Nothing here\n * validates a standing deployment while pretending to validate the change.\n */\n\nimport {\n apiRequest,\n detectProvenance,\n listRunConfigs,\n waitForRun,\n type RunReport,\n type WorldsClientOptions,\n} from \"./index\";\nimport { push } from \"./hub\";\n\nexport type ValidatedRun = {\n model: string;\n runId: string;\n report: RunReport | null;\n /** Why this run fails the gate, or null when it passes. */\n failure: string | null;\n};\n\nexport type ValidateReport = {\n ok: boolean;\n slug: string;\n branch: string;\n versionId: string;\n contentHash: string;\n runConfig: { id: string; name: string };\n runs: ValidatedRun[];\n /** A PR-comment-ready summary of the whole validation. */\n markdown: string;\n};\n\nfunction fmtScore(score: number | null): string {\n return score === null ? \"no score\" : score.toFixed(3);\n}\n\nfunction buildMarkdown(\n report: Omit<ValidateReport, \"markdown\">,\n minScore: number | null,\n 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 progress(`pushing ${dir} as ${opts.slug ?? \"(pyproject name)\"}@${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 if (opts.slug) {\n try {\n const tip = await apiRequest<{ versionId?: string }>(\n options,\n \"POST\",\n \"/api/public/benchmark-containers/resolve-version\",\n { slug: opts.slug, ref: branch },\n );\n tipVersionId = tip.versionId ?? null;\n } catch {\n tipVersionId = null;\n }\n }\n const pushed = await push(dir, {\n slug: opts.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 = /^[ \\t\\n\\r\\f\\v]+|[ \\t\\n\\r\\f\\v]+$/g;\nconst WHITESPACE_RUN = /[ \\t\\n\\r\\f\\v]+/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, entity, {where, resolve, limit, offset})` — the rows of\n * one entity that match a predicate, from\n * `GET /api/public/worlds/{slug}/data?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. */\nexport function queryRowsSearch(entity: string, opts: WorldQueryOptions = {}): string {\n const search = new URLSearchParams();\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/** The world's head version, queried. The route reads the head only, so a\n * `slug@ref` is refused rather than silently served as the head. With\n * `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 slug: string,\n entity: string,\n opts: WorldQueryOptions = {},\n options: WorldsClientOptions = {},\n): Promise<WorldQueryResult | WorldQueryAcrossResult> {\n if (slug.includes(\"@\"))\n throw new Error(\n `queryRows reads a world's head version: pass the slug without @ref (got ${slug})`,\n );\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)}`,\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. */\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\n/** A serialized value back to JSON when it parses; otherwise as it is. */\nfunction jsonish(value: unknown): unknown {\n if (typeof value !== \"string\") return value;\n try {\n return JSON.parse(value);\n } catch {\n return value;\n }\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 * A serialized `input`/`output` (the SDK stores JSON text) is parsed back;\n * an `input` that is not an object leaves `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 input = jsonish(observation.input);\n const record: ToolCallRecord = { tool, args: isObject(input) ? input : {} };\n if (observation.level === \"ERROR\") record.error = observation.statusMessage || \"ERROR\";\n else record.result = jsonish(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","/**\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\n const version = await apiRequest<\n ResolvedWorldVersion & { taskNames?: string[] }\n >(options, \"POST\", \"/api/public/benchmark-containers/resolve-version\", {\n slug,\n ...(ref ? { ref } : {}),\n });\n\n const world = new WorldSet(\n slugRef,\n slug,\n ref,\n {\n versionId: version.versionId,\n semanticVersion: version.semanticVersion ?? null,\n contentHash: version.contentHash,\n state: version.state,\n },\n [],\n options,\n );\n for (const name of version.taskNames ?? []) {\n const variant = /^[a-z0-9]+-([a-z0-9]+)-/.exec(name)?.[1] ?? null;\n world.tasks.push(new WorldTask(world, name, variant));\n }\n return world;\n}\n\n// The session surface completes the worlds module, so `@withgateway/sdk/worlds`\n// carries both halves: running a world locally, and driving one the platform\n// hosts. (session.ts imports apiRequest from here; the cycle is function-level\n// only, and the build below is what proves it resolves.)\nexport * from \"./session\";\n\n// Stored tasks: the task spec as a named, versioned project resource that\n// `openSession(world, { task: { id } })` opens on.\nexport * from \"./tasks\";\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 * 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,wBA6QM,kBAGA,iBAIA;AApRN;AAAA;AAAA;AAAA,yBAA2B;AAE3B;AACA;AA0QA,IAAM,mBAAmB,KAAK;AAG9B,IAAM,kBAAkB,IAAI;AAI5B,IAAM,0BAA0B,KAAK;AAAA;AAAA;;;ACpRrC;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,qBACA,kBACA,IACA,MAuBM;AA1BN;AAAA;AAAA;AAAA,IAAAA,sBAA2B;AAC3B,uBAAqC;AACrC,SAAoB;AACpB,WAAsB;AACtB;AAsBA,IAAM,eAAoB,UAAK,YAAY,oBAAoB;AAAA;AAAA;;;AC1B/D;AAAA;AAAA;AAaA;AAQA;AAAA;AAAA;;;ACrBA;AAAA;AAAA;AAUA;AAAA;AAAA;;;ACVA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAuBAC,qBAOM,kBACA,gBACA,WAEO,cAEP,MAEA,gBAKA,aAUA,KAGA,QAiBO;AAzEb;AAAA;AAAA;AAuBA,IAAAA,sBAA2B;AAE3B;AAKA,IAAM,mBAAmB;AACzB,IAAM,iBAAiB;AACvB,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,cACzC,gCAAW,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;;;ACzEhG,IAcAC;AAdA;AAAA;AAAA;AAcA,IAAAA,sBAA2B;AAE3B;AACA;AAAA;AAAA;;;ACjBA;AAAA;AAAA;AAoBA;AAAA;AAAA;;;ACpBA;AAAA;AAAA;AAWA;AAAA;AAAA;;;ACXA,IAoCAC,KACA,IACAC;AAtCA;AAAA;AAAA;AAoCA,IAAAD,MAAoB;AACpB,SAAoB;AACpB,IAAAC,QAAsB;AAEtB;AAAA;AAAA;;;ACAA,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;AAydA;AAIA;AAIA;AAKA;AAGA;AAKA;AACA;AACA;AAKA;AAIA;AAKA;AAtcO,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;;;AClEA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAYA;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":["import_node_crypto","import_node_crypto","import_node_crypto","fs","path","path"]}
|