@withgateway/sdk 0.2.2 → 0.2.4
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 +11992 -4572
- package/dist/cli.js.map +1 -1
- package/dist/cli.mjs +11998 -4578
- package/dist/cli.mjs.map +1 -1
- package/dist/files/index.js +71 -31
- package/dist/files/index.js.map +1 -1
- package/dist/files/index.mjs +59 -20
- package/dist/files/index.mjs.map +1 -1
- package/dist/hooks/index.d.mts +1 -0
- package/dist/hooks/index.d.ts +1 -0
- package/dist/hooks/index.js +4355 -0
- package/dist/hooks/index.js.map +1 -0
- package/dist/hooks/index.mjs +4243 -0
- package/dist/hooks/index.mjs.map +1 -0
- package/dist/{index-Dpo-t8iO.d.ts → index-1xnxt0Cc.d.ts} +58 -2
- package/dist/index-B0R3IgsV.d.mts +1279 -0
- package/dist/index-B0R3IgsV.d.ts +1279 -0
- package/dist/{index-B5HUQQDE.d.mts → index-C1wDEwH4.d.mts} +58 -2
- package/dist/index.d.mts +4 -3
- package/dist/index.d.ts +4 -3
- package/dist/index.js +6547 -1552
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +6636 -1655
- package/dist/index.mjs.map +1 -1
- package/dist/traces/index.js +60 -20
- package/dist/traces/index.js.map +1 -1
- package/dist/traces/index.mjs +51 -12
- package/dist/traces/index.mjs.map +1 -1
- package/dist/tracing/index.d.mts +1 -1
- package/dist/tracing/index.d.ts +1 -1
- package/dist/tracing/index.js +46 -3
- package/dist/tracing/index.js.map +1 -1
- package/dist/tracing/index.mjs +41 -2
- package/dist/tracing/index.mjs.map +1 -1
- package/dist/worlds/index.d.mts +371 -6
- package/dist/worlds/index.d.ts +371 -6
- package/dist/worlds/index.js +2061 -235
- package/dist/worlds/index.js.map +1 -1
- package/dist/worlds/index.mjs +2050 -224
- package/dist/worlds/index.mjs.map +1 -1
- package/package.json +6 -1
- package/runtime/gatewaysdk/environment/_materialize.py +3 -3
- package/runtime/gatewaysdk/environment/schema/api.py +116 -2
- package/runtime/gatewaysdk/environment/schema/compiler.py +14 -0
- package/runtime/gatewaysdk/environment/schema/host.py +37 -11
- package/runtime/gatewaysdk/environment/schema/skills/hooks-getting-started/SKILL.md +154 -0
- package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/SKILL.md +5 -5
- package/runtime/gatewaysdk/environment/schema/snapshot.py +6 -5
- package/runtime/gatewaysdk/environment/schema/tasks.py +12 -2
- package/runtime/gatewaysdk/environment/schema/workers.py +30 -13
- package/skills/hooks-getting-started/SKILL.md +154 -0
- package/skills/worlds-getting-started/SKILL.md +5 -5
|
@@ -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/cli/router.ts","../../src/cli/config.ts","../../src/cli/runtime/local.ts","../../src/cli/runtime/client.ts","../../src/cli/runtime/data.ts","../../src/cli/platform/worldData/transform.ts","../../src/cli/platform/worldData/batches.ts","../../src/cli/platform/worldData/chunker.ts","../../src/cli/platform/worldData/push.ts","../../src/worlds/ingest.ts","../../src/worlds/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 * The `gateway` command tree, with no dependency: groups hold commands, a\n * command declares its positionals and flags, help is generated from the\n * declarations so `gateway <group> --help` always matches what runs.\n *\n * Flags: `--name value`, `--name=value`, `--flag` (boolean), repeatable flags\n * collect into arrays when declared `repeat: true`. Anything after `--` is\n * positional.\n */\n\nexport type FlagSpec = {\n name: string;\n help: string;\n /** Short alias, e.g. \"m\" for --message. */\n short?: string;\n /** Boolean flags take no value. */\n boolean?: boolean;\n repeat?: boolean;\n default?: string | boolean;\n /** Environment variable that fills the flag when it is not given. */\n env?: string;\n};\n\nexport type PositionalSpec = {\n name: string;\n help: string;\n optional?: boolean;\n /** Collects every remaining positional. */\n variadic?: boolean;\n};\n\nexport type Parsed = {\n positionals: string[];\n flags: Record<string, string | boolean | string[] | undefined>;\n};\n\nexport type CommandSpec = {\n name: string;\n help: string;\n positionals?: PositionalSpec[];\n flags?: FlagSpec[];\n /** Long-form notes printed under the usage line in `--help`. */\n notes?: string;\n run: (args: Parsed, ctx: CommandContext) => Promise<number | void>;\n};\n\nexport type CommandContext = {\n stdout: (line: string) => void;\n stderr: (line: string) => void;\n /** Read all of stdin (for --value-less secrets, piped rows). */\n stdin: () => Promise<string>;\n /** Stdin as a stream, for inputs too large to hold (`worlds data import … -`). */\n stdinStream?: () => NodeJS.ReadableStream;\n};\n\nexport class CommandGroup {\n readonly groups = new Map<string, CommandGroup>();\n readonly commands = new Map<string, CommandSpec>();\n /** Long-form notes printed under the command list in `--help`. */\n notes?: string;\n constructor(\n readonly name: string,\n readonly help: string,\n ) {}\n group(name: string, help: string): CommandGroup {\n const existing = this.groups.get(name);\n if (existing) return existing;\n const created = new CommandGroup(name, help);\n this.groups.set(name, created);\n return created;\n }\n command(spec: CommandSpec): this {\n this.commands.set(spec.name, spec);\n return this;\n }\n}\n\nexport class CliError extends Error {\n constructor(\n message: string,\n readonly exitCode = 2,\n ) {\n super(message);\n }\n}\n\nexport function parseArgs(spec: CommandSpec, argv: string[]): Parsed {\n const flagSpecs = spec.flags ?? [];\n const byName = new Map<string, FlagSpec>();\n for (const f of flagSpecs) {\n byName.set(f.name, f);\n if (f.short) byName.set(f.short, f);\n }\n const positionals: string[] = [];\n const flags: Parsed[\"flags\"] = {};\n let onlyPositionals = false;\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i]!;\n if (onlyPositionals || !arg.startsWith(\"-\") || arg === \"-\") {\n positionals.push(arg);\n continue;\n }\n if (arg === \"--\") {\n onlyPositionals = true;\n continue;\n }\n const bare = arg.replace(/^--?/, \"\");\n const [rawName, inlineValue] = bare.includes(\"=\")\n ? [bare.slice(0, bare.indexOf(\"=\")), bare.slice(bare.indexOf(\"=\") + 1)]\n : [bare, undefined];\n const f = byName.get(rawName);\n if (!f) throw new CliError(`Unknown flag --${rawName} for ${spec.name}`);\n if (f.boolean) {\n flags[f.name] =\n inlineValue === undefined ? true : inlineValue !== \"false\";\n continue;\n }\n let value = inlineValue;\n if (value === undefined) {\n const next = argv[i + 1];\n if (next === undefined || (next.startsWith(\"--\") && next.length > 2))\n throw new CliError(`--${f.name} needs a value`);\n value = next;\n i++;\n }\n if (f.repeat) {\n const current = flags[f.name];\n flags[f.name] = Array.isArray(current) ? [...current, value] : [value];\n } else flags[f.name] = value;\n }\n for (const f of flagSpecs) {\n if (flags[f.name] !== undefined) continue;\n const fromEnv = f.env ? process.env[f.env] : undefined;\n if (fromEnv !== undefined && fromEnv !== \"\") flags[f.name] = fromEnv;\n else if (f.default !== undefined) flags[f.name] = f.default;\n }\n const specs = spec.positionals ?? [];\n const required = specs.filter((p) => !p.optional && !p.variadic).length;\n if (positionals.length < required)\n throw new CliError(\n `${spec.name} needs ${specs\n .slice(0, required)\n .map((p) => `<${p.name}>`)\n .join(\" \")}`,\n );\n const variadic = specs.some((p) => p.variadic);\n if (!variadic && positionals.length > specs.length)\n throw new CliError(\n `${spec.name} takes ${specs.length} argument${specs.length === 1 ? \"\" : \"s\"}, got ${positionals.length}`,\n );\n return { positionals, flags };\n}\n\n/** Typed accessors so commands never repeat the narrowing. */\nexport const arg = {\n str(p: Parsed, name: string): string | undefined {\n const v = p.flags[name];\n return typeof v === \"string\" ? v : undefined;\n },\n bool(p: Parsed, name: string): boolean {\n return p.flags[name] === true;\n },\n list(p: Parsed, name: string): string[] {\n const v = p.flags[name];\n if (Array.isArray(v)) return v;\n return typeof v === \"string\" ? [v] : [];\n },\n int(p: Parsed, name: string): number | undefined {\n const v = arg.str(p, name);\n if (v === undefined) return undefined;\n const n = Number(v);\n if (!Number.isInteger(n))\n throw new CliError(`--${name} must be an integer`);\n return n;\n },\n};\n\nfunction usageLine(path: string[], spec: CommandSpec): string {\n const pos = (spec.positionals ?? [])\n .map((p) =>\n p.variadic\n ? `<${p.name}...>`\n : p.optional\n ? `[${p.name}]`\n : `<${p.name}>`,\n )\n .join(\" \");\n return `${path.join(\" \")} ${pos}`.trim();\n}\n\nexport function helpFor(\n path: string[],\n node: CommandGroup | CommandSpec,\n): string {\n if (node instanceof CommandGroup) {\n const lines = [`${path.join(\" \")} — ${node.help}`, \"\"];\n for (const [name, g] of node.groups)\n lines.push(` ${name.padEnd(16)} ${g.help}`);\n for (const [name, c] of node.commands)\n lines.push(` ${name.padEnd(16)} ${c.help}`);\n if (node.notes) lines.push(\"\", node.notes);\n lines.push(\"\", `Run '${path.join(\" \")} <command> --help' for details.`);\n return lines.join(\"\\n\");\n }\n const lines = [usageLine(path, node), \"\", ` ${node.help}`];\n const pos = node.positionals ?? [];\n if (pos.length) {\n lines.push(\"\", \"Arguments:\");\n for (const p of pos) lines.push(` ${p.name.padEnd(18)} ${p.help}`);\n }\n const flags = node.flags ?? [];\n if (flags.length) {\n lines.push(\"\", \"Options:\");\n for (const f of flags) {\n const label = `--${f.name}${f.short ? `, -${f.short}` : \"\"}${f.boolean ? \"\" : \" <value>\"}`;\n const extras = [\n f.default !== undefined ? `default ${String(f.default)}` : null,\n f.env ? `env ${f.env}` : null,\n ]\n .filter(Boolean)\n .join(\", \");\n lines.push(\n ` ${label.padEnd(28)} ${f.help}${extras ? ` (${extras})` : \"\"}`,\n );\n }\n }\n if (node.notes) lines.push(\"\", node.notes);\n return lines.join(\"\\n\");\n}\n\n/** Walk the tree and run: exit code 0 on success, 2 on usage error, 1 on failure. */\nexport async function dispatch(\n root: CommandGroup,\n argv: string[],\n ctx: CommandContext,\n): Promise<number> {\n let node: CommandGroup = root;\n const path = [root.name];\n let i = 0;\n while (i < argv.length) {\n const token = argv[i]!;\n if (token === \"--help\" || token === \"-h\") {\n ctx.stdout(helpFor(path, node));\n return 0;\n }\n const group = node.groups.get(token);\n if (group) {\n node = group;\n path.push(token);\n i++;\n continue;\n }\n const command = node.commands.get(token);\n if (command) {\n const rest = argv.slice(i + 1);\n if (rest.includes(\"--help\") || rest.includes(\"-h\")) {\n ctx.stdout(helpFor([...path, token], command));\n return 0;\n }\n try {\n const parsed = parseArgs(command, rest);\n const code = await command.run(parsed, ctx);\n return code ?? 0;\n } catch (error) {\n if (error instanceof CliError) {\n ctx.stderr(error.message);\n return error.exitCode;\n }\n ctx.stderr(error instanceof Error ? error.message : String(error));\n return 1;\n }\n }\n ctx.stderr(\n `Unknown command '${token}' under '${path.join(\" \")}'.\\n\\n${helpFor(path, node)}`,\n );\n return 2;\n }\n ctx.stdout(helpFor(path, node));\n return node === root ? 0 : 2;\n}\n","import * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\n\nimport { CliError } from \"./router\";\n\n/**\n * Where the CLI's credentials come from, in this order (the same as the\n * Python CLI): explicit --host, environment (GATEWAY_HOST, GATEWAY_PUBLIC_KEY,\n * GATEWAY_SECRET_KEY / GATEWAY_API_KEY), then ~/.gateway/config.json written\n * by `gateway auth login`. `GATEWAY_ENV_FILE=path` fills the environment from\n * a KEY=value file first (see `loadEnvFile`).\n */\nexport type StoredConfig = {\n host?: string;\n public_key?: string;\n api_key?: string;\n};\n\nexport function configPath(): string {\n return path.join(\n process.env.GATEWAY_CONFIG_DIR ?? path.join(os.homedir(), \".gateway\"),\n \"config.json\",\n );\n}\n\nexport function readConfig(): StoredConfig {\n try {\n return JSON.parse(fs.readFileSync(configPath(), \"utf8\")) as StoredConfig;\n } catch {\n return {};\n }\n}\n\nexport function writeConfig(config: StoredConfig): void {\n const file = configPath();\n fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });\n fs.writeFileSync(file, JSON.stringify(config, null, 2) + \"\\n\", { mode: 0o600 });\n}\n\nexport function clearConfig(): boolean {\n try {\n fs.unlinkSync(configPath());\n return true;\n } catch {\n return false;\n }\n}\n\nexport type Credentials = { host: string; publicKey: string; secretKey: string };\n\n/** The accepted env-file form, printed by `gateway --help` and the docs. */\nexport const ENV_FILE_FORM =\n \"GATEWAY_ENV_FILE=path loads a KEY=value file first: `KEY = value`, quoted values, \" +\n \"`export KEY=value` and `#` comments are all accepted; the shell's environment wins.\";\n\n/**\n * Parse a KEY=value file the way a person writes one, not the way `source`\n * reads one. Brex retrospective: the customer's `.env` had `GATEWAY_HOST = …`\n * (spaces around `=`), which the shell refused to source and the CLI could not\n * read either. Accepted: blank lines and `#` comments, an `export ` prefix,\n * spaces around `=`, single- or double-quoted values (quotes stripped, nothing\n * inside interpreted). Not accepted: a line without `=`, which is reported by\n * number rather than skipped, because a silently dropped credential shows up\n * later as \"API key not configured\".\n */\nexport function parseEnvFile(text: string): Record<string, string> {\n const values: Record<string, string> = {};\n const lines = text.split(/\\r?\\n/);\n for (let index = 0; index < lines.length; index++) {\n const line = lines[index]!.trim();\n if (!line || line.startsWith(\"#\")) continue;\n const assignment = line.startsWith(\"export \") ? line.slice(\"export \".length).trim() : line;\n const eq = assignment.indexOf(\"=\");\n if (eq === -1) throw new CliError(`env file line ${index + 1} is not KEY=value: ${line}`);\n const key = assignment.slice(0, eq).trim();\n let value = assignment.slice(eq + 1).trim();\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key))\n throw new CliError(`env file line ${index + 1} has an invalid variable name: ${key || line}`);\n const quote = value[0];\n if ((quote === '\"' || quote === \"'\") && value.length >= 2 && value.endsWith(quote))\n value = value.slice(1, -1);\n values[key] = value;\n }\n return values;\n}\n\n/**\n * Put `GATEWAY_ENV_FILE`'s variables into the process environment, without\n * overriding anything already set there. Explicit on purpose: the CLI never\n * reads a `.env` it was not pointed at. Vendor keys named by connector.toml\n * ride along, so a local capture sees them too. Returns the keys it set.\n */\nexport function loadEnvFile(): string[] {\n const file = process.env.GATEWAY_ENV_FILE;\n if (!file) return [];\n let text: string;\n try {\n text = fs.readFileSync(file, \"utf8\");\n } catch (error) {\n throw new CliError(`GATEWAY_ENV_FILE=${file} could not be read: ${(error as Error).message}`);\n }\n const set: string[] = [];\n for (const [key, value] of Object.entries(parseEnvFile(text))) {\n if (process.env[key] !== undefined) continue;\n process.env[key] = value;\n set.push(key);\n }\n return set;\n}\n\nexport function resolveCredentials(hostFlag?: string): Credentials {\n const stored = readConfig();\n const host = (hostFlag ?? process.env.GATEWAY_HOST ?? stored.host ?? \"\").replace(/\\/+$/, \"\");\n const publicKey = process.env.GATEWAY_PUBLIC_KEY ?? stored.public_key ?? \"\";\n const secretKey =\n process.env.GATEWAY_SECRET_KEY ?? process.env.GATEWAY_API_KEY ?? stored.api_key ?? \"\";\n if (!host)\n throw new CliError(\n \"Host not configured. Pass --host, set GATEWAY_HOST, or run `gateway auth login`.\",\n );\n if (!publicKey || !secretKey)\n throw new CliError(\n \"API key not configured. Set GATEWAY_PUBLIC_KEY and GATEWAY_SECRET_KEY, or run `gateway auth login`.\",\n );\n return { host, publicKey, secretKey };\n}\n\n/** A non-2xx answer from the platform: the status is a field, never something to regex out of the text. */\nexport class ApiError extends CliError {\n constructor(\n readonly status: number,\n readonly method: string,\n readonly route: string,\n readonly text: string,\n ) {\n super(`${method} ${route} -> ${status}: ${text.slice(0, 600)}`, 1);\n }\n}\n\n/** One JSON request against the platform, Basic-authenticated with the project key. */\nexport async function api<T = unknown>(\n creds: Credentials,\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\",\n route: string,\n body?: unknown,\n init: { timeoutMs?: number } = {},\n): Promise<T> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), init.timeoutMs ?? 120_000);\n try {\n const res = await fetch(`${creds.host}${route}`, {\n method,\n headers: {\n \"content-type\": \"application/json\",\n accept: \"application/json\",\n authorization:\n \"Basic \" + Buffer.from(`${creds.publicKey}:${creds.secretKey}`).toString(\"base64\"),\n },\n ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n signal: controller.signal,\n });\n const text = await res.text();\n if (!res.ok) throw new ApiError(res.status, method, route, text);\n return (text ? JSON.parse(text) : {}) as T;\n } finally {\n clearTimeout(timer);\n }\n}\n\nexport function printJson(ctx: { stdout: (line: string) => void }, value: unknown): void {\n ctx.stdout(JSON.stringify(value, null, 2));\n}\n","import { spawn, spawnSync } from \"node:child_process\";\nimport * as fs from \"node:fs\";\nimport * as net from \"node:net\";\nimport * as path from \"node:path\";\n\nimport { CliError } from \"../router\";\nimport { type Credentials, resolveCredentials } from \"../config\";\nimport type { RuntimeRequest } from \"./client\";\n\n/**\n * The schema runtime, run on THIS machine. The npm package carries the SDK's\n * `gatewaysdk/environment` directory (stdlib-only Python, the same files the\n * platform's bridge executes), so any python3 >= 3.11 on the path runs it\n * exactly as the platform does — the same bootstrap, JSON in, JSON out. No\n * pip, no PyPI. When there is no such Python, callers fall back to\n * `POST /api/public/worlds/runtime`.\n *\n * `GATEWAY_RUNTIME=local|platform|auto` (default auto) forces one side;\n * `GATEWAY_PYTHON` names the interpreter (otherwise python3.13, python3.12,\n * python3.11, python3, python, then `uv python find` are tried in that order).\n */\n\nconst MIN_PYTHON: [number, number] = [3, 11];\nconst DIAGNOSTIC_TAIL = 600;\n\n/** The end of a failed run's output: a Python traceback names the exception last. */\nfunction tailOf(output: string): string {\n return output.length > DIAGNOSTIC_TAIL\n ? `…${output.slice(-DIAGNOSTIC_TAIL)}`\n : output;\n}\n\n/** The platform's own bootstrap: build the `gatewaysdk` package in memory from\n * the runtime root and run the bridge as __main__ (see worldSchemaRuntime.ts). */\nconst BRIDGE_BOOTSTRAP = `import sys,runpy,types,os\nroot=sys.argv[1]\npackage=types.ModuleType('gatewaysdk')\npackage.__path__=[os.path.join(root,'gatewaysdk')]\nsys.modules['gatewaysdk']=package\nrunpy.run_module('gatewaysdk.environment.schema.platform',run_name='__main__')`;\n\n/** The same, but running the schema module's own CLI (serve, connector-capture …)\n * with the arguments after the root. */\nconst MODULE_BOOTSTRAP = `import sys,runpy,types,os\nroot=sys.argv[1]\npackage=types.ModuleType('gatewaysdk')\npackage.__path__=[os.path.join(root,'gatewaysdk')]\nsys.modules['gatewaysdk']=package\nsys.argv=['gateway worlds']+sys.argv[2:]\nrunpy.run_module('gatewaysdk.environment.schema',run_name='__main__')`;\n\nexport type RuntimeMode = \"auto\" | \"local\" | \"platform\";\n\nexport function runtimeMode(): RuntimeMode {\n const raw = (process.env.GATEWAY_RUNTIME ?? \"auto\").toLowerCase();\n if (raw === \"local\" || raw === \"platform\" || raw === \"auto\") return raw;\n throw new CliError(\n `GATEWAY_RUNTIME must be local, platform or auto (got ${raw})`,\n );\n}\n\n/** Where the bundled runtime lives: `<package>/runtime` beside dist/, or the\n * monorepo's SDK source when running from the repository.\n *\n * The entry is `dist/cli.js` (the published bin) or `src/cli.ts` (from\n * source): one directory under the package root either way, so the Python\n * source is `<entry dir>/../../sdk/src` — `gatewaysdk/sdk/src`. It used to\n * walk one level too far (`<repo>/sdk/src`, which does not exist), so every\n * from-source run missed the runtime and fell back to the platform, demanding\n * a host for commands that need none (`schema init --connector salesforce`,\n * 2026-09-16). */\nexport function runtimeRoot(): string | null {\n const candidates: string[] = [];\n if (process.env.GATEWAY_RUNTIME_PATH)\n candidates.push(process.env.GATEWAY_RUNTIME_PATH);\n const entry =\n process.argv[1] && fs.existsSync(process.argv[1])\n ? path.dirname(fs.realpathSync(process.argv[1]))\n : null;\n if (entry) {\n candidates.push(path.resolve(entry, \"..\", \"runtime\"));\n candidates.push(path.resolve(entry, \"..\", \"..\", \"runtime\"));\n candidates.push(path.resolve(entry, \"..\", \"..\", \"sdk\", \"src\"));\n }\n candidates.push(path.resolve(process.cwd(), \"runtime\"));\n for (const root of candidates)\n if (\n fs.existsSync(\n path.join(root, \"gatewaysdk\", \"environment\", \"schema\", \"platform.py\"),\n )\n )\n return root;\n return null;\n}\n\nlet pythonCache: string | null | undefined;\n/** What the search saw, for the one line `pythonAdvice` prints: each candidate\n * and its version, or null when it did not run. */\nlet pythonProbes: { name: string; version: string | null }[] = [];\n\n/** Forget the cached interpreter (tests re-probe with a different PATH or env). */\nexport function resetPythonCache(): void {\n pythonCache = undefined;\n pythonProbes = [];\n}\n\n/** Versioned names first: on a Mac the bare `python3` is often the system 3.9,\n * while Homebrew, pyenv or uv put a `python3.12` beside it. Last, ask uv for\n * an interpreter it manages (`uv python find` prints a path and downloads\n * nothing). Brex retrospective: the customer had to discover GATEWAY_PYTHON\n * by hand because the CLI stopped at `python3` = 3.9. */\nconst PYTHON_CANDIDATES = [\n \"python3.13\",\n \"python3.12\",\n \"python3.11\",\n \"python3\",\n \"python\",\n];\nconst UV_FIND = [\"python\", \"find\", `>=${MIN_PYTHON.join(\".\")}`];\n\nfunction probeVersion(name: string): string | null {\n const probe = spawnSync(\n name,\n [\"-c\", \"import sys;print(sys.version_info[0],sys.version_info[1])\"],\n { encoding: \"utf8\", timeout: 10_000 },\n );\n if (probe.status !== 0) return null;\n const [major, minor] = probe.stdout.trim().split(/\\s+/).map(Number);\n return Number.isInteger(major) && Number.isInteger(minor)\n ? `${major}.${minor}`\n : null;\n}\n\nfunction atLeastMinimum(version: string): boolean {\n const [major, minor] = version.split(\".\").map(Number);\n return (\n major! > MIN_PYTHON[0] ||\n (major === MIN_PYTHON[0] && minor! >= MIN_PYTHON[1])\n );\n}\n\n/** The interpreter uv would hand out, or null when uv is absent or has none. */\nfunction uvPython(): string | null {\n const found = spawnSync(\"uv\", UV_FIND, { encoding: \"utf8\", timeout: 10_000 });\n if (found.status !== 0) return null;\n const line = found.stdout.trim().split(/\\r?\\n/)[0] ?? \"\";\n return line || null;\n}\n\n/** A python3 at or above 3.11, or null. Cached for the process. `GATEWAY_PYTHON`\n * names the interpreter and is the only candidate then; otherwise the versioned\n * names, the bare ones, then uv's. */\nexport function findPython(): string | null {\n if (pythonCache !== undefined) return pythonCache;\n const named = process.env.GATEWAY_PYTHON;\n const candidates = named ? [named] : PYTHON_CANDIDATES;\n for (const name of candidates) {\n const version = probeVersion(name);\n pythonProbes.push({ name, version });\n if (version && atLeastMinimum(version)) {\n pythonCache = name;\n return name;\n }\n }\n if (!named) {\n const fromUv = uvPython();\n const version = fromUv ? probeVersion(fromUv) : null;\n pythonProbes.push({ name: fromUv ?? \"uv python find\", version });\n if (fromUv && version && atLeastMinimum(version)) {\n pythonCache = fromUv;\n return fromUv;\n }\n }\n pythonCache = null;\n return null;\n}\n\n/** ONE actionable line for a machine without a usable Python: what was found\n * and how to point the CLI at a newer interpreter. */\nexport function pythonAdvice(): string {\n findPython();\n const floor = MIN_PYTHON.join(\".\");\n const named = process.env.GATEWAY_PYTHON;\n const seen = pythonProbes\n .filter((probe) => probe.version)\n .map((probe) => `${probe.name} is ${probe.version}`);\n const found = seen.length\n ? seen.join(\", \")\n : named\n ? `${named} did not run`\n : \"none on PATH\";\n return (\n `No python3 >= ${floor} usable (${found}); set GATEWAY_PYTHON to a newer interpreter, ` +\n `e.g. GATEWAY_PYTHON=\"$(brew --prefix python@3.12)/bin/python3.12\" or GATEWAY_PYTHON=\"$(uv python find 3.12)\".`\n );\n}\n\n/** Why `localRuntime()` answers null, in one line: the mode, the interpreter\n * or the bundled files — so a refusal never blames Python on a machine that\n * merely set GATEWAY_RUNTIME=platform. */\nexport function localRuntimeReason(): string {\n if (runtimeMode() === \"platform\")\n return \"GATEWAY_RUNTIME=platform forces the hosted side.\";\n if (!findPython()) return pythonAdvice();\n if (!runtimeRoot())\n return \"The bundled runtime is missing (set GATEWAY_RUNTIME_PATH).\";\n return \"\";\n}\n\n/** Can this machine run the runtime itself? Both a Python and the bundled files. */\nexport function localRuntime(): { python: string; root: string } | null {\n if (runtimeMode() === \"platform\") return null;\n const python = findPython();\n const root = runtimeRoot();\n if (!python || !root) {\n if (runtimeMode() === \"local\")\n throw new CliError(\n !python\n ? `GATEWAY_RUNTIME=local but ${pythonAdvice()}`\n : \"GATEWAY_RUNTIME=local but the bundled runtime is missing (set GATEWAY_RUNTIME_PATH)\",\n );\n return null;\n }\n return { python, root };\n}\n\n/** Does the local Python have PyYAML? `conform` needs it for .yaml specs. */\nexport function localPythonHasYaml(python: string): boolean {\n return (\n spawnSync(python, [\"-c\", \"import yaml\"], { timeout: 10_000 }).status === 0\n );\n}\n\n/** One bridge request through the local runtime: JSON in on stdin, JSON out. */\nexport async function localBridge<T = Record<string, unknown>>(\n request: RuntimeRequest,\n local: { python: string; root: string },\n opts: { timeoutMs?: number } = {},\n): Promise<T> {\n const input = JSON.stringify(request);\n return await new Promise<T>((resolve, reject) => {\n const child = spawn(\n local.python,\n [\"-I\", \"-B\", \"-c\", BRIDGE_BOOTSTRAP, local.root],\n {\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n // This is the author's machine running the author's world: the one\n // place the runtime may import and run a world's own Python (check's\n // handler execution, `worlds call`, `worlds test` tool cases).\n env: {\n PATH: process.env.PATH ?? \"\",\n HOME: process.env.HOME ?? \"\",\n TMPDIR: process.env.TMPDIR ?? \"\",\n GATEWAY_RUNTIME_EXECUTE: \"1\",\n },\n },\n );\n const out: Buffer[] = [];\n const err: Buffer[] = [];\n const timer = setTimeout(\n () => child.kill(\"SIGKILL\"),\n opts.timeoutMs ?? 300_000,\n );\n child.stdout.on(\"data\", (chunk: Buffer) => out.push(chunk));\n child.stderr.on(\"data\", (chunk: Buffer) => err.push(chunk));\n child.on(\"error\", (error) => {\n clearTimeout(timer);\n reject(\n new CliError(\n `local runtime could not start (${local.python}): ${error.message}`,\n 1,\n ),\n );\n });\n child.on(\"close\", (code) => {\n clearTimeout(timer);\n const text = Buffer.concat(out).toString(\"utf8\");\n const stderr = Buffer.concat(err).toString(\"utf8\");\n let payload: unknown = null;\n try {\n payload = text ? JSON.parse(text) : null;\n } catch {\n payload = null;\n }\n if (payload && typeof payload === \"object\") {\n resolve(payload as T);\n return;\n }\n reject(\n new CliError(\n `local runtime (${request.command}) exited ${code}: ${tailOf((stderr || text).trim()) || \"no output\"}`,\n 1,\n ),\n );\n });\n child.stdin.end(input);\n });\n}\n\n/** `pid <n> (<command>)` of whatever listens on `port`, from lsof when this\n * machine has it; null when nothing can be said. Best effort, never an error. */\nexport function portOwner(port: number): string | null {\n const found = spawnSync(\"lsof\", [\"-nP\", `-iTCP:${port}`, \"-sTCP:LISTEN\", \"-Fpc\"], {\n encoding: \"utf8\",\n timeout: 5_000,\n });\n if (found.error || found.status !== 0) return null;\n let pid: string | null = null;\n let command: string | null = null;\n for (const line of found.stdout.split(\"\\n\")) {\n if (line.startsWith(\"p\") && pid === null) pid = line.slice(1);\n else if (line.startsWith(\"c\") && pid !== null && command === null) command = line.slice(1);\n }\n if (pid === null) return null;\n return `pid ${pid}${command ? ` (${command})` : \"\"}`;\n}\n\n/** Refuse, by name, a port another process already holds — BEFORE the runtime\n * is spawned. The Python side refuses too, but a backgrounded serve's output\n * goes unread, and every curl after it hit whatever else answered on the port\n * (CRM dogfood, 2026-09-16): this serve never answers from another server. */\nexport async function assertPortFree(port: number, host = \"127.0.0.1\"): Promise<void> {\n const taken = await new Promise<boolean>((resolve) => {\n const probe = net.createServer();\n probe.once(\"error\", () => resolve(true));\n probe.listen(port, host, () => probe.close(() => resolve(false)));\n });\n if (!taken) return;\n const owner = portOwner(port);\n throw new CliError(\n `port ${port} on ${host} is already in use${owner ? ` by ${owner}` : \"\"}; ` +\n \"nothing was served there — pass another --port, or stop that server first\",\n 1,\n );\n}\n\n/** Run the schema module's own CLI in the foreground (serve, connector-capture …). */\nexport async function localModule(\n argv: string[],\n local: { python: string; root: string },\n opts: { env?: Record<string, string>; cwd?: string } = {},\n): Promise<number> {\n return await new Promise<number>((resolve, reject) => {\n const child = spawn(\n local.python,\n [\"-B\", \"-c\", MODULE_BOOTSTRAP, local.root, ...argv],\n {\n stdio: \"inherit\",\n cwd: opts.cwd,\n env: { ...process.env, ...opts.env },\n },\n );\n // The child owns the port (`worlds serve`); a signal that stops this\n // process must stop it too, or the server lives on with no way to reach\n // the foreground that started it. A SIGKILL, or a wrapper that swallows\n // the signal, reaches nothing here — for that the runtime's `serve`\n // watches its parent pid and closes when this process is gone.\n const forward = (signal: NodeJS.Signals) => () => {\n if (child.exitCode === null && child.signalCode === null) child.kill(signal);\n };\n const handlers: [NodeJS.Signals, () => void][] = [\n [\"SIGINT\", forward(\"SIGINT\")],\n [\"SIGTERM\", forward(\"SIGTERM\")],\n [\"SIGHUP\", forward(\"SIGHUP\")],\n ];\n for (const [signal, handler] of handlers) process.on(signal, handler);\n const release = () => {\n for (const [signal, handler] of handlers) process.off(signal, handler);\n };\n child.on(\"error\", (error) => {\n release();\n reject(\n new CliError(\n `local runtime could not start (${local.python}): ${error.message}`,\n 1,\n ),\n );\n });\n child.on(\"close\", (code, signal) => {\n release();\n resolve(code ?? (signal ? 130 : 1));\n });\n });\n}\n\n/** Credentials when the platform may be needed; null when a local runtime\n * will do and none are configured (a `schema check` needs no login). */\nexport function credentialsForRuntime(hostFlag?: string): Credentials | null {\n try {\n return resolveCredentials(hostFlag);\n } catch (error) {\n if (error instanceof CliError && localRuntime()) return null;\n throw error;\n }\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport { CliError } from \"../router\";\nimport { localBridge, localPythonHasYaml, localRuntime, localRuntimeReason } from \"./local\";\nimport type { Credentials } from \"../config\";\n\n/**\n * The wire to the schema runtime, which is Python and runs on the platform:\n * a world directory goes up as `[{path, content b64}]`, one bridge request\n * comes back verbatim, and any files in the answer land back in the\n * directory. Nothing here interprets a contract — that is the bridge's job.\n */\n\nexport type WorldFile = { path: string; content: string };\n\n/** Directories that are never part of a world's files. */\nconst SKIP_DIRS = new Set([\"__pycache__\", \".git\", \"node_modules\", \".gateway\"]);\n\n/** Every file under `dir` as base64 entries with forward-slash relative paths,\n * sorted so the same tree always produces the same request. */\n/** Compiled snapshots (`db/state.*`, `scenarios/<name>/state.*`) are build outputs\n * of the tree's data, never inputs: the runtime rebuilds them from the journals\n * and strips them from what it returns, and a real world's snapshots alone can\n * exceed the bridge's 64 MiB request cap. */\nconst BUILD_OUTPUT = /(^|\\/)state\\.(sqlite|json)$/;\n\nexport function isBuildOutput(relPath: string): boolean {\n return BUILD_OUTPUT.test(relPath);\n}\n\nexport function readWorldFiles(dir: string, opts: { buildOutputs?: boolean } = {}): WorldFile[] {\n if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())\n throw new CliError(`Not a directory: ${dir}`);\n const out: WorldFile[] = [];\n const walk = (rel: string) => {\n const abs = rel ? path.join(dir, rel) : dir;\n const entries = fs.readdirSync(abs, { withFileTypes: true });\n entries.sort((a, b) => a.name.localeCompare(b.name));\n for (const entry of entries) {\n const childRel = rel ? `${rel}/${entry.name}` : entry.name;\n if (entry.isDirectory()) {\n if (!SKIP_DIRS.has(entry.name)) walk(childRel);\n } else if (entry.isFile()) {\n if (!opts.buildOutputs && isBuildOutput(childRel)) continue;\n out.push({\n path: childRel,\n content: fs.readFileSync(path.join(dir, childRel)).toString(\"base64\"),\n });\n }\n }\n };\n walk(\"\");\n return out.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));\n}\n\nfunction assertSafeRelPath(rel: string): void {\n const parts = rel.split(\"/\");\n if (\n !rel ||\n rel.startsWith(\"/\") ||\n rel.includes(\"\\\\\") ||\n /^[A-Za-z]:/.test(rel) ||\n parts.some((p) => p === \"\" || p === \".\" || p === \"..\")\n )\n throw new CliError(`The runtime returned an unsafe file path: ${rel}`, 1);\n}\n\n/** Write bridge files into `dir`. With `clean`, files the runtime did not\n * return are removed first (the skipped dirs are left alone), so the tree\n * becomes exactly what the runtime holds. Returns the written paths. */\nexport function writeWorldFiles(\n dir: string,\n files: WorldFile[],\n opts: { clean?: boolean } = {},\n): string[] {\n for (const file of files) assertSafeRelPath(file.path);\n if (opts.clean && fs.existsSync(dir)) {\n const keep = new Set(files.map((f) => f.path));\n for (const existing of readWorldFiles(dir)) {\n if (!keep.has(existing.path)) fs.rmSync(path.join(dir, existing.path));\n }\n pruneEmptyDirs(dir);\n }\n fs.mkdirSync(dir, { recursive: true });\n const written: string[] = [];\n for (const file of files) {\n const target = path.join(dir, file.path);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n fs.writeFileSync(target, Buffer.from(file.content, \"base64\"));\n written.push(file.path);\n }\n return written;\n}\n\nfunction pruneEmptyDirs(root: string): void {\n const walk = (abs: string): boolean => {\n let empty = true;\n for (const entry of fs.readdirSync(abs, { withFileTypes: true })) {\n const child = path.join(abs, entry.name);\n if (entry.isDirectory()) {\n if (SKIP_DIRS.has(entry.name)) {\n empty = false;\n continue;\n }\n if (walk(child)) fs.rmdirSync(child);\n else empty = false;\n } else empty = false;\n }\n return empty;\n };\n walk(root);\n}\n\n/** The bridge's structured diagnostic, exactly as the Python ContractError\n * carries it (`code`, `message`, `path`, `schema_path`, plus context). */\nexport type BridgeErrorDetail = {\n code: string;\n message: string;\n path?: string;\n schema_path?: string;\n [key: string]: unknown;\n};\n\n/** Rendered the way the Python CLI prints a ContractError:\n * `{code} at {schema_path or path or '/'}: {message}`. */\nexport function formatBridgeError(detail: BridgeErrorDetail): string {\n const where = detail.schema_path || detail.path || \"/\";\n return `${detail.code} at ${where}: ${detail.message}`;\n}\n\nexport class BridgeRejected extends CliError {\n constructor(readonly detail: BridgeErrorDetail) {\n super(formatBridgeError(detail), 1);\n }\n}\n\nexport function detailFrom(payload: unknown): BridgeErrorDetail | null {\n if (!payload || typeof payload !== \"object\") return null;\n const error = (payload as { error?: unknown }).error;\n if (!error || typeof error !== \"object\") return null;\n const detail = error as Record<string, unknown>;\n if (typeof detail.code !== \"string\" || typeof detail.message !== \"string\") return null;\n return detail as BridgeErrorDetail;\n}\n\nexport type RuntimeRequest = { command: string } & Record<string, unknown>;\n\n/**\n * How a world directory travels on a request that runs it (check, test, call):\n * in place, as `world`, when the bundled runtime runs on this machine — so the\n * `[dependencies]` paths beside it resolve and its handlers may run — and as\n * `files` when the platform's bridge answers, which takes a tree and runs no\n * authored code.\n */\nexport function worldPayload(dir: string): { world: string } | { files: WorldFile[] } {\n const abs = path.resolve(dir);\n if (!fs.existsSync(abs) || !fs.statSync(abs).isDirectory()) throw new CliError(`Not a directory: ${abs}`);\n return localRuntime() ? { world: abs } : { files: readWorldFiles(abs) };\n}\n\n/**\n * `POST /api/public/worlds/runtime` with the bridge request verbatim. A\n * rejection — whether the platform relays it with a 4xx or as a 200 with\n * `status: \"rejected\"` — becomes a BridgeRejected; anything else non-OK is a\n * plain CliError with the status and body excerpt.\n */\nexport async function runtime<T extends Record<string, unknown> = Record<string, unknown>>(\n creds: Credentials | null,\n request: RuntimeRequest,\n opts: { timeoutMs?: number } = {},\n): Promise<T> {\n // This machine first, when it can: the bundled runtime with a local\n // python3 is what the platform runs anyway, minus the round trip. A .yaml\n // conform spec needs PyYAML, which the vendored runtime does not carry.\n const local = localRuntime();\n const yamlSpec =\n request.command === \"conform\" &&\n Array.isArray(request.openapi) &&\n (request.openapi as { path?: string }[]).some((doc) => /\\.ya?ml$/i.test(doc.path ?? \"\"));\n if (local && !(yamlSpec && !localPythonHasYaml(local.python))) {\n const payload = await localBridge<Record<string, unknown>>(request, local, opts);\n const detail = detailFrom(payload);\n if (detail) throw new BridgeRejected(detail);\n return payload as T;\n }\n if (!creds)\n throw new CliError(\n \"This needs the schema runtime (the CLI bundles it) or platform credentials (`gateway auth login`). \" +\n localRuntimeReason(),\n );\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), opts.timeoutMs ?? 180_000);\n const route = \"/api/public/worlds/runtime\";\n try {\n const res = await fetch(`${creds.host}${route}`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n accept: \"application/json\",\n authorization:\n \"Basic \" + Buffer.from(`${creds.publicKey}:${creds.secretKey}`).toString(\"base64\"),\n },\n body: JSON.stringify(request),\n signal: controller.signal,\n });\n const text = await res.text();\n let payload: unknown = null;\n try {\n payload = text ? JSON.parse(text) : {};\n } catch {\n payload = null;\n }\n const detail = detailFrom(payload);\n if (detail) throw new BridgeRejected(detail);\n if (!res.ok)\n throw new CliError(`POST ${route} (${request.command}) -> ${res.status}: ${text.slice(0, 600)}`, 1);\n if (payload === null) throw new CliError(`POST ${route} (${request.command}) returned non-JSON`, 1);\n return payload as T;\n } finally {\n clearTimeout(timer);\n }\n}\n\n/** Basic-auth headers for the few non-runtime routes this track calls. */\nexport function authHeaders(creds: Credentials): Record<string, string> {\n return {\n accept: \"application/json\",\n authorization:\n \"Basic \" + Buffer.from(`${creds.publicKey}:${creds.secretKey}`).toString(\"base64\"),\n };\n}\n\n/** Strip the `files` echo from a bridge report before printing it. */\nexport function withoutFiles<T extends Record<string, unknown>>(report: T): Omit<T, \"files\"> {\n const { files: _files, ...rest } = report;\n return rest;\n}\n\n/** JSON with sorted keys, the way the Python CLI prints bridge reports. */\nexport function sortedJson(value: unknown, indent = 2): string {\n const sort = (v: unknown): unknown => {\n if (Array.isArray(v)) return v.map(sort);\n if (v && typeof v === \"object\") {\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(v as Record<string, unknown>).sort())\n out[key] = sort((v as Record<string, unknown>)[key]);\n return out;\n }\n return v;\n };\n return JSON.stringify(sort(value), null, indent);\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport type { Credentials } from \"../config\";\nimport { CliError } from \"../router\";\nimport type { WorldQueryAcrossResult } from \"../../worlds/query\";\nimport {\n BridgeRejected,\n detailFrom,\n readWorldFiles,\n runtime,\n writeWorldFiles,\n type WorldFile,\n} from \"./client\";\nimport { localBridge, localRuntime, localRuntimeReason } from \"./local\";\n\n/**\n * Rows into, and counts out of, a world that lives in a LOCAL directory. The\n * `worlds data import|show` commands (registered by the platform track) call\n * these two for the directory case; a slug goes to the platform's world data\n * routes instead. The gate is the world's own contract, run by the platform\n * runtime: a bad row is refused with the field named and nothing is written.\n */\n\nexport type Rows = Record<string, Record<string, unknown>[]>;\nexport type ImportMode = \"append\" | \"replace\";\n\nexport type LocalImportResult = {\n kind: string;\n entity_counts: Record<string, number>;\n changed: boolean;\n /** Build outputs (`db/state.*`) dropped because the journals they were built from changed. */\n dropped_build_outputs?: string[];\n next?: string;\n};\n\nexport async function importLocalWorldData(\n dir: string,\n rows: Rows,\n opts: { mode?: ImportMode; merge?: \"upsert\" | \"fill\"; redact?: \"off\" | \"apply\" | \"refuse\" },\n creds: Credentials | null,\n): Promise<LocalImportResult> {\n const res = await runtime<{\n kind?: string;\n entity_counts?: Record<string, number>;\n changed?: boolean;\n files?: WorldFile[];\n }>(creds, {\n command: \"import-data\",\n files: readWorldFiles(dir),\n rows,\n mode: opts.mode ?? \"append\",\n ...(opts.merge && opts.merge !== \"upsert\" ? { merge: opts.merge } : {}),\n ...(opts.redact && opts.redact !== \"off\" ? { redact: opts.redact } : {}),\n });\n if (res.files?.length) writeWorldFiles(dir, res.files);\n // Snapshots are build outputs, not tree files: the runtime answers without\n // them, and the ones on disk were built from the journals BEFORE this import.\n // A served world ignores a stale snapshot and replays the journals, but the\n // files would still sit there claiming an older state — drop them, and let\n // `worlds schema compile` build them again from the data that is there now.\n const dropped = res.changed ? dropBuildOutputs(dir) : [];\n return {\n kind: res.kind ?? \"unknown\",\n entity_counts: res.entity_counts ?? {},\n changed: Boolean(res.changed),\n ...(dropped.length\n ? {\n dropped_build_outputs: dropped,\n next: `gateway worlds schema compile ${dir} # rebuilds the snapshots from the imported data`,\n }\n : {}),\n };\n}\n\nconst BUILD_OUTPUT = /(^|\\/)state\\.(sqlite|json)$/;\n\n/** Remove the compiled snapshots (`db/state.*`, `scenarios/<name>/state.*`)\n * that no longer match the tree's journals. */\nexport function dropBuildOutputs(dir: string): string[] {\n const dropped: string[] = [];\n for (const file of readWorldFiles(dir, { buildOutputs: true })) {\n if (!BUILD_OUTPUT.test(file.path)) continue;\n fs.rmSync(path.join(dir, file.path), { force: true });\n dropped.push(file.path);\n }\n return dropped;\n}\n\n/**\n * The same bridge import over the tree, with the answered files discarded:\n * the rows are checked through the world's contract and nothing on disk\n * changes. A refused row surfaces as a BridgeRejected, as an import would.\n */\nexport async function checkLocalWorldData(\n dir: string,\n rows: Rows,\n creds: Credentials | null,\n opts: { redact?: \"off\" | \"apply\" | \"refuse\" } = {},\n): Promise<LocalImportResult> {\n const res = await runtime<{\n kind?: string;\n entity_counts?: Record<string, number>;\n changed?: boolean;\n }>(creds, {\n command: \"import-data\",\n files: readWorldFiles(dir),\n rows,\n mode: \"append\",\n ...(opts.redact && opts.redact !== \"off\" ? { redact: opts.redact } : {}),\n });\n return {\n kind: res.kind ?? \"unknown\",\n entity_counts: res.entity_counts ?? {},\n changed: Boolean(res.changed),\n };\n}\n\nexport type LocalShowResult = {\n kind: string;\n entity_counts?: Record<string, number>;\n entity?: string;\n rows?: Record<string, unknown>[];\n};\n\nexport async function showLocalWorldData(\n dir: string,\n entity: string | undefined,\n creds: Credentials | null,\n): Promise<LocalShowResult> {\n const res = await runtime<{\n kind?: string;\n entity_counts?: Record<string, number>;\n rows?: Record<string, unknown>[];\n }>(creds, {\n command: \"counts\",\n files: readWorldFiles(dir),\n ...(entity ? { entity } : {}),\n });\n const out: LocalShowResult = { kind: res.kind ?? \"unknown\" };\n if (entity) {\n out.entity = entity;\n out.rows = res.rows ?? [];\n } else out.entity_counts = res.entity_counts ?? {};\n return out;\n}\n\n/** field → stored value, or a list of them (any of). */\nexport type LocalQueryWhere = Record<string, string | string[]>;\n\nexport type LocalQueryOptions = {\n /** The `where` values are plaintext: the runtime resolves each to its stored form first. */\n resolve?: boolean;\n limit?: number;\n offset?: number;\n /** Read the rows a session opened in this scenario starts from (schema worlds). */\n scenario?: string;\n};\n\nexport type LocalQueryResult = {\n kind?: string;\n entity: string;\n scenario?: string;\n rows: Record<string, unknown>[];\n count: number;\n total: number | null;\n limit: number;\n offset: number;\n /** With `resolve`: the stored forms each field was matched against (`[]` for a dropped field). */\n resolved?: Record<string, (string | number)[]>;\n};\n\n/**\n * The bridge's `query` over the tree: one entity's rows matching `where`.\n * A refused query (unknown entity or field) surfaces as a BridgeRejected.\n */\nexport async function queryLocalWorldData(\n dir: string,\n entity: string,\n where: LocalQueryWhere,\n opts: LocalQueryOptions,\n creds: Credentials | null,\n): Promise<LocalQueryResult> {\n const res = await runtime<{\n kind?: string;\n entity?: string;\n rows?: Record<string, unknown>[];\n count?: number;\n total?: number | null;\n limit?: number;\n offset?: number;\n scenario?: string;\n resolved?: Record<string, (string | number)[]>;\n }>(creds, {\n command: \"query\",\n files: readWorldFiles(dir),\n entity,\n ...(Object.keys(where).length ? { where } : {}),\n ...(opts.limit !== undefined ? { limit: opts.limit } : {}),\n ...(opts.offset !== undefined ? { offset: opts.offset } : {}),\n ...(opts.resolve ? { resolve: true } : {}),\n ...(opts.scenario ? { scenario: opts.scenario } : {}),\n });\n const rows = res.rows ?? [];\n return {\n ...(res.kind ? { kind: res.kind } : {}),\n entity: res.entity ?? entity,\n ...(res.scenario ? { scenario: res.scenario } : {}),\n rows,\n count: res.count ?? rows.length,\n total: res.total ?? null,\n limit: res.limit ?? opts.limit ?? rows.length,\n offset: res.offset ?? opts.offset ?? 0,\n ...(res.resolved ? { resolved: res.resolved } : {}),\n };\n}\n\n/** A local across answer: the platform's groups, each world named by its\n * manifest name (the root) or its pin's slug (a dependency); no version ids,\n * since the trees are read where they sit. */\nexport type LocalQueryAcrossResult = {\n kind?: string;\n entity: string;\n groups: (Omit<WorldQueryAcrossResult[\"groups\"][number], \"world\"> & { world: { slug: string; alias: string | null } })[];\n compare?: WorldQueryAcrossResult[\"compare\"];\n};\n\n/**\n * The bridge's `query` with `across` over the tree in place: the root's rows\n * and, per `[dependencies.<alias>.entities]` mapping that carries a `where`\n * field, the linked world's, read at its `path`. Needs the bundled runtime on\n * this machine, as the paths beside the tree must resolve.\n */\nexport async function queryLocalWorldDataAcross(\n dir: string,\n entity: string,\n where: LocalQueryWhere,\n opts: LocalQueryOptions & { compare?: boolean },\n): Promise<LocalQueryAcrossResult> {\n const local = localRuntime();\n if (!local)\n throw new CliError(\n \"`--across` on a directory reads the linked worlds at their paths, so it needs the bundled runtime on this machine. \" +\n localRuntimeReason(),\n 1,\n );\n const payload = await localBridge<Record<string, unknown>>(\n {\n command: \"query\",\n world: path.resolve(dir),\n entity,\n across: true,\n ...(opts.compare ? { compare: true } : {}),\n ...(Object.keys(where).length ? { where } : {}),\n ...(opts.limit !== undefined ? { limit: opts.limit } : {}),\n ...(opts.offset !== undefined ? { offset: opts.offset } : {}),\n ...(opts.resolve ? { resolve: true } : {}),\n ...(opts.scenario ? { scenario: opts.scenario } : {}),\n },\n local,\n );\n const detail = detailFrom(payload);\n if (detail) throw new BridgeRejected(detail);\n return payload as unknown as LocalQueryAcrossResult;\n}\n\n// ---------------------------------------------------------------- tool calls\n\nexport type LocalIngestRefusal = { index: number | null; tool: string | null; reason: string; pointer?: string };\n\n/** One `[[sources]]` of a mapping in the report: what it saw and what it did not touch. */\nexport type LocalIngestSource = {\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 unmapped_fields: Record<string, string>;\n /** Entity fields the source never sets, per entity it lands in. */\n unset_fields: Record<string, string[]>;\n};\n\n/** The bridge's `ingest-calls` report (the Python `ingest.ingest_records`). */\nexport type LocalIngestResult = {\n /** How the rows were produced: a declared mapping, the operations' projection, or rows as given. */\n via?: \"map\" | \"operations\" | \"rows\" | \"transform\";\n records: number;\n ingested: number;\n skipped: Record<string, number>;\n refusals: LocalIngestRefusal[];\n rows: Record<string, number>;\n /** The projected rows themselves, as the tools returned them (before any redaction). */\n projected?: Rows;\n /** `via: \"map\"`: each source's accounting. */\n sources?: LocalIngestSource[];\n /** `via: \"map\"` with `unmatched = \"skip\"`: records no source claimed, by tool name. */\n unmatched?: Record<string, number>;\n /** `via: \"operations\"`: that the rows came through the operation projection, not a mapping. */\n note?: string;\n dry_run: boolean;\n redact: \"off\" | \"apply\" | \"refuse\";\n changed: boolean;\n kind?: string;\n entity_counts?: Record<string, number>;\n batch?: string | null;\n};\n\n/**\n * Tool-call records into a world in a LOCAL directory, through the runtime's\n * `ingest-calls`: each record's tool resolves to an operation of the world's\n * `connector.toml`, its result goes through that operation's projection the\n * way a capture does, and the rows through the world's contract. An unknown\n * tool is a refusal in the report (nothing written); a row the contract\n * refuses surfaces as a BridgeRejected, as an import would. Redaction is\n * optional and off by default. With `dryRun` the tree is untouched.\n */\nexport async function ingestLocalToolCalls(\n dir: string,\n records: unknown[],\n opts: { redact?: \"off\" | \"apply\" | \"refuse\"; dryRun?: boolean; mode?: ImportMode; map?: string | Record<string, unknown> },\n creds: Credentials | null,\n): Promise<LocalIngestResult> {\n const res = await runtime<Partial<LocalIngestResult> & { files?: WorldFile[] }>(creds, {\n command: \"ingest-calls\",\n files: readWorldFiles(dir),\n records,\n mode: opts.mode ?? \"append\",\n ...(opts.dryRun ? { dry_run: true } : {}),\n ...(opts.redact && opts.redact !== \"off\" ? { redact: opts.redact } : {}),\n ...(opts.map !== undefined ? { map: opts.map } : {}),\n });\n if (!opts.dryRun && res.files?.length) writeWorldFiles(dir, res.files);\n if (res.changed) dropBuildOutputs(dir);\n return {\n ...(res.via ? { via: res.via } : {}),\n ...(res.sources ? { sources: res.sources } : {}),\n ...(res.unmatched ? { unmatched: res.unmatched } : {}),\n ...(res.note ? { note: res.note } : {}),\n records: res.records ?? records.length,\n ingested: res.ingested ?? 0,\n skipped: res.skipped ?? {},\n refusals: res.refusals ?? [],\n rows: res.rows ?? {},\n ...(res.projected ? { projected: res.projected } : {}),\n dry_run: Boolean(res.dry_run ?? opts.dryRun),\n redact: res.redact ?? opts.redact ?? \"off\",\n changed: Boolean(res.changed),\n ...(res.kind ? { kind: res.kind } : {}),\n ...(res.entity_counts ? { entity_counts: res.entity_counts } : {}),\n ...(res.batch !== undefined ? { batch: res.batch } : {}),\n };\n}\n","import { spawn } from \"node:child_process\";\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport { createRequire } from \"node:module\";\n\nimport { CliError } from \"../../router\";\nimport type { Rows } from \"../rows\";\n\n/**\n * `--transform`: the agent's own code turns records into rows (the Python\n * `schema.transform`, wrapper for wrapper). A script — `.py`, or `.ts` /\n * `.mjs` / `.js` / `.cjs` for node — either exports `transform(records) ->\n * {entity: [rows]}` (node: `transform` or the default export) or reads the\n * records as JSONL on stdin and prints the rows document on stdout.\n *\n * The script runs in a subprocess with a time limit, its stderr passed\n * through. The wrapper disables sockets (Python) and `net`/`tls`/`http`/\n * `dgram`/`fetch` (node) before the script loads, and the child gets no\n * `GATEWAY_*` or proxy variables. That is a guard, not a sandbox: a\n * transform is the agent's own code, run on the agent's own machine.\n */\n\nexport const DEFAULT_TRANSFORM_TIMEOUT_MS = 120_000;\nexport const NODE_SUFFIXES = [\".ts\", \".mts\", \".mjs\", \".js\", \".cjs\"];\nexport const PYTHON_SUFFIXES = [\".py\"];\nconst SCRUBBED = /^(GATEWAY_|HTTPS?_PROXY$|ALL_PROXY$|https?_proxy$|all_proxy$)/;\n\nexport const PY_WRAPPER = `\nimport io, json, runpy, socket, sys\n\ndef _deny(*args, **kwargs):\n raise RuntimeError(\"network is disabled in a transform\")\n\nclass _Denied(socket.socket):\n def __init__(self, *args, **kwargs):\n _deny()\n\nsocket.socket = _Denied\nsocket.SocketType = _Denied\nsocket.create_connection = _deny\nsocket.getaddrinfo = _deny\n\ntext = sys.stdin.read()\nrecords = [json.loads(line) for line in text.splitlines() if line.strip()]\nsys.stdin = io.StringIO(text)\ncaptured = io.StringIO()\nreal = sys.stdout\nsys.stdout = captured\ntry:\n namespace = runpy.run_path(sys.argv[1], run_name=\"__main__\")\nfinally:\n sys.stdout = real\nfn = namespace.get(\"transform\")\nif callable(fn):\n out = fn(records)\nelse:\n printed = captured.getvalue().strip()\n if not printed:\n sys.stderr.write(\"the transform defines no transform(records) and printed nothing\\\\n\")\n sys.exit(3)\n out = json.loads(printed)\nreal.write(json.dumps(out))\n`;\n\nexport const NODE_WRAPPER = `\nimport { pathToFileURL } from \"node:url\";\nimport net from \"node:net\";\nimport tls from \"node:tls\";\nimport http from \"node:http\";\nimport https from \"node:https\";\nimport dgram from \"node:dgram\";\n\nconst deny = () => { throw new Error(\"network is disabled in a transform\"); };\nnet.Socket.prototype.connect = deny;\nnet.connect = deny;\nnet.createConnection = deny;\ntls.connect = deny;\nhttp.request = deny;\nhttp.get = deny;\nhttps.request = deny;\nhttps.get = deny;\ndgram.createSocket = deny;\nglobalThis.fetch = deny;\n\nconst module = await import(pathToFileURL(process.argv[2]).href);\nconst fn = typeof module.transform === \"function\" ? module.transform : typeof module.default === \"function\" ? module.default : null;\nif (fn) {\n const chunks = [];\n for await (const chunk of process.stdin) chunks.push(chunk);\n const text = Buffer.concat(chunks).toString(\"utf8\");\n const records = text.split(\"\\\\n\").filter((line) => line.trim()).map((line) => JSON.parse(line));\n const out = await fn(records);\n process.stdout.write(JSON.stringify(out));\n}\n`;\n\nconst isObject = (value: unknown): value is Record<string, unknown> => typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/** `value` as the rows document `{entity: [rows]}`, or a CliError saying what shape it has instead. */\nexport function checkRows(value: unknown, where: string): Rows {\n if (!isObject(value)) throw new CliError(`${where} must return {entity: [rows]}; got ${value === null ? \"null\" : Array.isArray(value) ? \"an array\" : typeof value}`, 1);\n for (const [entity, listed] of Object.entries(value)) {\n if (!Array.isArray(listed)) throw new CliError(`${where}: ${entity} must be a list of rows; got ${listed === null ? \"null\" : typeof listed}`, 1);\n listed.forEach((row, index) => {\n if (!isObject(row)) throw new CliError(`${where}: ${entity}[${index}] is not an object`, 1);\n });\n }\n return value as Rows;\n}\n\n/**\n * How this node runs a `.ts` transform: built-in type stripping from Node\n * 22.6 on; before that, the `tsx` command-line entry when tsx is installed\n * beside the CLI (a dev dependency here, present on CI's Node 20); otherwise\n * a refusal that names both options instead of a stack trace from node.\n * Returns the argv prefix that goes in front of the wrapper.\n */\nfunction typescriptPrefix(): string[] {\n const [major, minor] = process.versions.node.split(\".\").map(Number);\n if (!process.env.GATEWAY_NODE && (major > 22 || (major === 22 && minor >= 6))) return [\"--experimental-strip-types\", \"--no-warnings\"];\n try {\n return [createRequire(import.meta.url).resolve(\"tsx/cli\")];\n } catch {\n throw new CliError(\n `a .ts transform needs Node 22.6 or newer (built-in type stripping; this is ${process.versions.node}) or the tsx package installed beside the CLI; write the transform as .mjs or .py, or set GATEWAY_NODE to a newer node`,\n 1,\n );\n }\n}\n\nfunction command(script: string, wrapperDir: string): { file: string; args: string[] } {\n const suffix = path.extname(script).toLowerCase();\n if (PYTHON_SUFFIXES.includes(suffix)) return { file: process.env.GATEWAY_PYTHON || \"python3\", args: [\"-c\", PY_WRAPPER, script] };\n if (NODE_SUFFIXES.includes(suffix)) {\n const wrapper = path.join(wrapperDir, \"transform-wrapper.mjs\");\n fs.writeFileSync(wrapper, NODE_WRAPPER);\n const flags = suffix === \".ts\" || suffix === \".mts\" ? typescriptPrefix() : [];\n return { file: process.env.GATEWAY_NODE || process.execPath, args: [...flags, wrapper, script] };\n }\n throw new CliError(`${path.basename(script)}: a transform script is .py, .ts, .mjs, .js or .cjs`, 1);\n}\n\nconst tail = (stderr: string, lines = 12): string => {\n const kept = stderr\n .split(\"\\n\")\n .filter((line) => line.trim())\n .slice(-lines);\n return kept.length ? \"\\n\" + kept.join(\"\\n\") : \"\";\n};\n\n/**\n * Run `script` over `records`: the rows document it returns and its stderr.\n * A non-zero exit, a timeout, or output that is not the rows document is a\n * CliError (exit 1) carrying the tail of the script's stderr.\n */\nexport async function runTransform(script: string, records: unknown[], opts: { timeoutMs?: number } = {}): Promise<{ rows: Rows; stderr: string }> {\n if (!fs.existsSync(script) || !fs.statSync(script).isFile()) throw new CliError(`no transform script at ${script}`, 1);\n const resolved = path.resolve(script);\n const name = path.basename(script);\n const timeoutMs = opts.timeoutMs ?? DEFAULT_TRANSFORM_TIMEOUT_MS;\n const scratch = fs.mkdtempSync(path.join(os.tmpdir(), \"gateway-transform-\"));\n try {\n const { file, args } = command(resolved, scratch);\n const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !SCRUBBED.test(key)));\n const done = await new Promise<{ code: number | null; stdout: string; stderr: string; timedOut: boolean }>((resolve, reject) => {\n const child = spawn(file, args, { cwd: path.dirname(resolved), env, stdio: [\"pipe\", \"pipe\", \"pipe\"] });\n let stdout = \"\";\n let stderr = \"\";\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n child.kill(\"SIGKILL\");\n }, timeoutMs);\n child.stdout.setEncoding(\"utf8\").on(\"data\", (chunk: string) => (stdout += chunk));\n child.stderr.setEncoding(\"utf8\").on(\"data\", (chunk: string) => (stderr += chunk));\n child.on(\"error\", (error) => {\n clearTimeout(timer);\n reject(new CliError(`${name}: cannot run ${file}: ${error.message}`, 1));\n });\n child.on(\"close\", (code) => {\n clearTimeout(timer);\n resolve({ code, stdout, stderr, timedOut });\n });\n child.stdin.on(\"error\", () => undefined);\n child.stdin.end(records.map((record) => JSON.stringify(record) + \"\\n\").join(\"\"));\n });\n if (done.timedOut) throw new CliError(`${name} timed out after ${timeoutMs / 1000}s${tail(done.stderr)}`, 1);\n if (done.code !== 0) throw new CliError(`${name} exited ${done.code ?? \"?\"}${tail(done.stderr)}`, 1);\n let value: unknown;\n try {\n value = done.stdout.trim() ? JSON.parse(done.stdout) : null;\n } catch {\n throw new CliError(`${name} printed something other than the rows document${tail(done.stderr)}`, 1);\n }\n return { rows: checkRows(value, name), stderr: done.stderr };\n } finally {\n fs.rmSync(scratch, { recursive: true, force: true });\n }\n}\n\n/** A transform given to the SDK: a function, or a script path run as above. */\nexport type TransformLike = string | ((records: unknown[]) => Rows | Promise<Rows>);\n\nexport async function transformRecords(transform: TransformLike, records: unknown[], opts: { timeoutMs?: number } = {}): Promise<{ rows: Rows; stderr: string }> {\n if (typeof transform === \"function\") return { rows: checkRows(await transform(records), \"transform(records)\"), stderr: \"\" };\n return runTransform(transform, records, opts);\n}\n","import { createHash } from \"node:crypto\";\nimport * as fs from \"node:fs\";\n\nimport { api, type Credentials } from \"../../config\";\nimport { CliError } from \"../../router\";\nimport type { BuiltChunk } from \"./chunker\";\nimport type { ManifestChunk } from \"./manifest\";\n\n/**\n * The batch protocol of `/api/public/worlds/{slug}/data` (contract §7): open\n * a batch, register each chunk by digest (the server hands back a presigned\n * PUT, or says it already holds that content), confirm the upload, complete,\n * then poll. Thin on purpose: the server owns validation and the ledger.\n */\n\nexport type Refusal = {\n chunk: number;\n index: number;\n entity: string | null;\n primaryKey: Record<string, unknown> | null;\n field: string | null;\n pointer: string;\n detail: string;\n};\n\nexport type BatchStatus = {\n batchId: string;\n state: string;\n mode?: string;\n merge?: string;\n atomic?: boolean;\n dryRun?: boolean;\n publish?: string;\n chunks?: number;\n uploadedChunks?: number;\n rows?: number;\n refusalCount?: number;\n refusals?: Refusal[];\n reportUrl?: string;\n progress?: { phase?: string; validatedChunks?: number; appliedRows?: number };\n entityCounts?: Record<string, number>;\n snapshotId?: string | null;\n batchDigest?: string | null;\n versionId?: string | null;\n error?: string | null;\n createdAt?: string;\n updatedAt?: string;\n};\n\nexport type OpenBatchBody = {\n mode: \"append\" | \"replace\";\n merge: \"upsert\" | \"fill\";\n redact?: \"off\" | \"apply\" | \"refuse\";\n atomic: boolean;\n dryRun: boolean;\n publish: \"now\" | \"later\";\n message?: string;\n expectedChunks?: number;\n entities?: string[];\n};\n\nexport type OpenedBatch = { batchId: string; state: string; limits?: { chunkBytes?: number; batchBytes?: number; inlineBytes?: number } };\n\nexport type RegisteredChunk = {\n chunkId: string;\n uploaded: boolean;\n uploadUrl?: string;\n /** Headers the presigned PUT was signed for (content-type, content-length, x-amz-checksum-sha256); sent exactly. */\n uploadHeaders?: Record<string, string>;\n expiresAt?: string;\n};\n\nexport const TERMINAL_STATES = new Set([\"applied\", \"refused\", \"published\", \"failed\"]);\n\nexport const sleepMs = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));\n\nexport class WorldDataApi {\n readonly base: string;\n constructor(\n readonly creds: Credentials,\n readonly slug: string,\n /** Injectable for tests: the pause between retries and polls. */\n readonly sleep: (ms: number) => Promise<void> = sleepMs,\n ) {\n this.base = `/api/public/worlds/${encodeURIComponent(slug)}/data`;\n }\n\n open(body: OpenBatchBody): Promise<OpenedBatch> {\n return api<OpenedBatch>(this.creds, \"POST\", `${this.base}/batches`, body);\n }\n\n register(batchId: string, chunk: { ordinal: number; digest: string; bytes: number; rows: number; entity: string | null }): Promise<RegisteredChunk> {\n return api<RegisteredChunk>(this.creds, \"POST\", `${this.base}/batches/${batchId}/chunks`, {\n ordinal: chunk.ordinal,\n digest: chunk.digest,\n bytes: chunk.bytes,\n rows: chunk.rows,\n ...(chunk.entity ? { entity: chunk.entity } : {}),\n });\n }\n\n markUploaded(batchId: string, chunkId: string): Promise<{ chunkId: string; uploaded: boolean; bytes: number }> {\n return api(this.creds, \"POST\", `${this.base}/batches/${batchId}/chunks/${chunkId}/uploaded`);\n }\n\n complete(batchId: string): Promise<{ batchId: string; state: string }> {\n return api(this.creds, \"POST\", `${this.base}/batches/${batchId}/complete`);\n }\n\n get(batchId: string): Promise<BatchStatus> {\n return api<BatchStatus>(this.creds, \"GET\", `${this.base}/batches/${batchId}`);\n }\n\n list(limit?: number, cursor?: string): Promise<{ batches: BatchStatus[]; nextCursor?: string }> {\n const params = new URLSearchParams();\n if (limit !== undefined) params.set(\"limit\", String(limit));\n if (cursor) params.set(\"cursor\", cursor);\n const q = params.toString();\n return api(this.creds, \"GET\", `${this.base}/batches${q ? `?${q}` : \"\"}`);\n }\n\n publish(message?: string): Promise<{ versionId: string; snapshotId: string; batchIds: string[] }> {\n return api(this.creds, \"POST\", `${this.base}/publish`, message ? { message } : {});\n }\n\n /**\n * PUT the gzipped chunk to its presigned URL with exactly the headers the\n * URL was signed for (the platform's `uploadHeaders`; the same three when it\n * sends none), with backoff on a dropped connection or a 5xx.\n */\n async put(uploadUrl: string, gz: Buffer, signed?: Record<string, string>): Promise<void> {\n const headers = signed ?? uploadHeadersFor(gz);\n const delays = [500, 1500, 4000];\n for (let attempt = 0; ; attempt++) {\n try {\n const res = await fetch(uploadUrl, { method: \"PUT\", body: new Uint8Array(gz), headers });\n if (res.ok) return;\n if (res.status < 500 || attempt >= delays.length) throw new CliError(`chunk upload -> ${res.status}: ${(await res.text()).slice(0, 300)}`, 1);\n } catch (error) {\n if (error instanceof CliError || attempt >= delays.length) throw error instanceof CliError ? error : new CliError(`chunk upload failed: ${(error as Error).message}`, 1);\n }\n await this.sleep(delays[attempt]!);\n }\n }\n\n /** Register, upload unless the server already holds the content, confirm. */\n async upload(batchId: string, chunk: BuiltChunk): Promise<ManifestChunk> {\n const registered = await this.register(batchId, chunk);\n if (!registered.uploaded) {\n if (!registered.uploadUrl) throw new CliError(`the server registered chunk ${chunk.ordinal} without an upload URL`, 1);\n await this.put(registered.uploadUrl, chunk.gz, registered.uploadHeaders);\n await this.markUploaded(batchId, registered.chunkId);\n }\n return { ordinal: chunk.ordinal, digest: chunk.digest, bytes: chunk.bytes, rows: chunk.rows, entity: chunk.entity, chunkId: registered.chunkId, uploaded: true };\n }\n}\n\n/** What a chunk's presigned PUT is signed for: its type, size and sha256 (base64, S3's spelling). */\nexport function uploadHeadersFor(gz: Buffer): Record<string, string> {\n return {\n \"content-type\": \"application/gzip\",\n \"content-length\": String(gz.length),\n \"x-amz-checksum-sha256\": createHash(\"sha256\").update(gz).digest(\"base64\"),\n };\n}\n\n/** Run `fn` over an async stream with at most `limit` in flight; results in input order. */\nexport async function forEachLimited<T>(items: AsyncIterable<T>, limit: number, fn: (item: T) => Promise<void>): Promise<void> {\n const inFlight = new Set<Promise<void>>();\n let failure: unknown = null;\n const track = (p: Promise<void>) => {\n const wrapped: Promise<void> = p.then(\n () => {\n inFlight.delete(wrapped);\n },\n (error) => {\n failure ??= error;\n inFlight.delete(wrapped);\n },\n );\n inFlight.add(wrapped);\n };\n for await (const item of items) {\n if (failure) break;\n track(fn(item));\n if (inFlight.size >= limit) await Promise.race(inFlight);\n }\n await Promise.all(inFlight);\n if (failure) throw failure;\n}\n\nexport type WaitOptions = {\n /** Called once per phase change with a printable line. */\n onPhase?: (line: string) => void;\n sleep?: (ms: number) => Promise<void>;\n /** The first pause between polls (default 1 s; GATEWAY_WORLD_DATA_POLL_MS in the CLI). */\n initialDelayMs?: number;\n};\n\n/** Poll until the batch settles; 1 s growing to 10 s between polls. */\nexport async function waitForBatch(client: WorldDataApi, batchId: string, opts: WaitOptions = {}): Promise<BatchStatus> {\n const sleep = opts.sleep ?? client.sleep;\n let delay = opts.initialDelayMs ?? 1000;\n let last = \"\";\n for (;;) {\n const status = await client.get(batchId);\n const phase = phaseLine(status);\n if (phase !== last) {\n opts.onPhase?.(phase);\n last = phase;\n }\n if (TERMINAL_STATES.has(status.state)) return status;\n await sleep(delay);\n delay = Math.min(10_000, Math.round(delay * 1.5));\n }\n}\n\n/** The Python CLI's progress line: `state`, with the job's phase in parentheses when it has one. */\nexport function phaseLine(status: BatchStatus): string {\n const phase = status.progress?.phase;\n return phase ? `${status.state} (${phase})` : status.state;\n}\n\n/**\n * The refusal report as JSONL: the server's full report when it has one\n * (`reportUrl`), else the records the status carries inline. Returns the\n * number of lines written.\n */\nexport async function writeRefusalReport(status: BatchStatus, file: string): Promise<number> {\n let text: string;\n if (status.reportUrl) {\n const res = await fetch(status.reportUrl);\n if (!res.ok) throw new CliError(`refusal report -> ${res.status}`, 1);\n text = await res.text();\n if (text && !text.endsWith(\"\\n\")) text += \"\\n\";\n } else text = (status.refusals ?? []).map((r) => JSON.stringify(r) + \"\\n\").join(\"\");\n fs.writeFileSync(file, text);\n return text ? text.split(\"\\n\").filter(Boolean).length : 0;\n}\n","import { createHash } from \"node:crypto\";\nimport { deflateRawSync } from \"node:zlib\";\n\nimport { dumps, type JsonObject } from \"./json\";\nimport type { TaggedRow } from \"./rowSource\";\n\n/**\n * Rows into chunks: gzip over JSONL, cut on row boundaries at `--chunk-rows`\n * or `--chunk-bytes` (uncompressed), content-addressed by the sha256 of the\n * gzipped bytes. The same rows with the same flags give the same content\n * digests (over the JSONL) in both CLIs and on every platform, and the same\n * gzip digests wherever the two zlibs deflate alike: lines are the Python\n * serialisation (`dumps`), the deflate stream is zlib's at level 9, and the\n * gzip header is written here rather than by zlib, as CPython's\n * `gzip.compress(…, mtime=0)` writes it — zlib would stamp the platform's OS\n * byte instead. Node 20 and 24 bundle Chromium's zlib, which deflates\n * differently from CPython's stock zlib, so a chunk's gzip digest can differ\n * between CLIs while its content digest agrees; `--resume` keys on the digest\n * of what this CLI wrote, so it is unaffected. See `zlibDeflatesLikeCPython`.\n */\n\nexport const DEFAULT_CHUNK_BYTES = 64 * 1024 * 1024;\nexport const GZIP_LEVEL = 9;\n\nexport type ChunkPlan = {\n /** Always bound: the Python CLI keeps 64 MiB even with --chunk-rows. */\n chunkBytes: number;\n chunkRows: number | null;\n /** When set, chunks are declared with this entity and lines are bare rows. */\n entity: string | null;\n};\n\nexport type BuiltChunk = {\n ordinal: number;\n /** sha256 of the gzipped bytes, hex. */\n digest: string;\n /** Gzipped size. */\n bytes: number;\n rows: number;\n entity: string | null;\n /** Uncompressed JSONL size (`contentBytes` in the shared manifest). */\n rawBytes: number;\n /** sha256 of the uncompressed JSONL: the cross-zlib parity check. */\n contentSha256: string;\n /** Index of the chunk's first row in the input stream. */\n firstRow: number;\n gz: Buffer;\n};\n\n/** One row as the line a chunk carries: tagged, or bare when the chunk declares its entity. */\nexport function chunkLine(row: TaggedRow, declared: string | null): string {\n if (declared !== null) return dumps(row.row) + \"\\n\";\n const tagged: JsonObject = new Map();\n tagged.set(\"entity\", row.entity);\n tagged.set(\"row\", row.row);\n return dumps(tagged) + \"\\n\";\n}\n\nexport async function* buildChunks(rows: AsyncIterable<TaggedRow>, plan: ChunkPlan): AsyncGenerator<BuiltChunk> {\n let lines: Buffer[] = [];\n let rawBytes = 0;\n let ordinal = 0;\n let seen = 0;\n const flush = (): BuiltChunk => {\n const raw = Buffer.concat(lines);\n const built = finishChunk(ordinal++, raw, lines.length, plan.entity, seen - lines.length);\n lines = [];\n rawBytes = 0;\n return built;\n };\n for await (const row of rows) {\n const line = Buffer.from(chunkLine(row, plan.entity), \"utf8\");\n const full =\n lines.length > 0 &&\n ((plan.chunkRows !== null && lines.length >= plan.chunkRows) ||\n rawBytes + line.length > plan.chunkBytes);\n if (full) yield flush();\n lines.push(line);\n rawBytes += line.length;\n seen++;\n }\n if (lines.length) yield flush();\n}\n\nexport function finishChunk(ordinal: number, raw: Buffer, rows: number, entity: string | null, firstRow = 0): BuiltChunk {\n const gz = gzipDeterministic(raw, { name: chunkName(ordinal) });\n return {\n ordinal,\n digest: createHash(\"sha256\").update(gz).digest(\"hex\"),\n bytes: gz.length,\n rows,\n entity,\n rawBytes: raw.length,\n contentSha256: createHash(\"sha256\").update(raw).digest(\"hex\"),\n firstRow,\n gz,\n };\n}\n\n/**\n * Whether this Node's zlib deflates as the CPython that wrote the fixtures\n * did. Deflate output is a property of the zlib build, not of the format:\n * the same input inflates everywhere, but a zlib-ng or a future Chromium\n * zlib may pick different matches, and then gzip digests differ across\n * CLIs while content digests (over the JSONL) still agree. The manifest\n * parity check is on the content; the gzip digest is informative.\n */\nexport function zlibDeflatesLikeCPython(): boolean {\n return deflateRawSync(Buffer.from(CPYTHON_PROBE_TEXT), { level: GZIP_LEVEL }).toString(\"hex\") === CPYTHON_PROBE_DEFLATE;\n}\n/**\n * Two tagged rows, as the chunker writes them, and CPython's deflate of them (zlib\n * 1.2.12, which also wrote the fixtures). The probe has to be this long: \"hello\\n\"\n * deflates identically on every zlib, so it proved nothing, while on this text\n * Node 20 and 24 (Chromium's zlib 1.3.1) pick different matches and land two\n * bytes shorter than Node 25 and CPython (stock zlib).\n */\nconst CPYTHON_PROBE_TEXT = '{\"entity\":\"customers\",\"row\":{\"id\":0,\"name\":\"n0\",\"score\":0.0,\"tags\":[\"a\"]}}\\n{\"entity\":\"customers\",\"row\":{\"id\":1,\"name\":\"n1\",\"score\":1.0,\"tags\":[\"a\"]}}\\n';\nconst CPYTHON_PROBE_DEFLATE = \"ab564acd2bc92ca954b2524a2e2d2ec9cf4d2d2a56d2512aca2f57b2aa56ca4c51b232d051ca4bcc4d052ac83300ca1427e7170139067a40f192c4f46225ab68a544a5d8da5aae6a824619228c3244186588691400\";\n\n/** The file name the Python CLI gives chunk N (`chunk-00007.jsonl.gz`), which\n * its `GzipFile` records in the gzip header, so it is part of the digest. */\nexport const chunkName = (ordinal: number): string => `chunk-${String(ordinal).padStart(5, \"0\")}.jsonl`;\n\n/**\n * Gzip as CPython's `gzip.GzipFile(fileobj, \"wb\", mtime=0)` writes it: mtime\n * 0, XFL for the level, OS \"unknown\" (0xff), and — when a name is given — the\n * FNAME field, exactly as GzipFile records the basename of the file it writes.\n */\nexport function gzipDeterministic(raw: Buffer, opts: { level?: number; name?: string } = {}): Buffer {\n const level = opts.level ?? GZIP_LEVEL;\n const name = opts.name ? Buffer.concat([Buffer.from(opts.name, \"latin1\"), Buffer.from([0])]) : Buffer.alloc(0);\n const header = Buffer.from([0x1f, 0x8b, 0x08, opts.name ? 0x08 : 0x00, 0, 0, 0, 0, level === 9 ? 0x02 : level === 1 ? 0x04 : 0x00, 0xff]);\n const body = deflateRawSync(raw, { level });\n const trailer = Buffer.alloc(8);\n trailer.writeUInt32LE(crc32(raw), 0);\n trailer.writeUInt32LE(raw.length >>> 0, 4);\n return Buffer.concat([header, name, body, trailer]);\n}\n\nlet table: Uint32Array | null = null;\n\n/** CRC-32 (IEEE), the gzip trailer's checksum. A table here keeps the CLI on Node 18. */\nexport function crc32(data: Buffer): number {\n if (!table) {\n table = new Uint32Array(256);\n for (let n = 0; n < 256; n++) {\n let c = n;\n for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;\n table[n] = c >>> 0;\n }\n }\n let crc = 0xffffffff;\n for (let i = 0; i < data.length; i++) crc = table[(crc ^ data[i]!) & 0xff]! ^ (crc >>> 8);\n return (crc ^ 0xffffffff) >>> 0;\n}\n\n/** The Python CLI's `_parse_size`: an integer and a unit — none, b, k, kib, kb, m, mib, mb, g, gib, gb. */\nexport function parseSize(text: string): number {\n const units: Record<string, number> = { \"\": 1, b: 1, k: 1024, kib: 1024, kb: 1000, m: 1024 ** 2, mib: 1024 ** 2, mb: 1000 ** 2, g: 1024 ** 3, gib: 1024 ** 3, gb: 1000 ** 3 };\n const raw = text.trim().toLowerCase().replace(/ /g, \"\");\n const m = /^(\\d+)([a-z]*)$/.exec(raw);\n if (!m || !(m[2]! in units)) throw new Error(`--chunk-bytes takes a size like 64MiB or 1000000, not '${text}'`);\n return Number(m[1]) * units[m[2]!]!;\n}\n","import type { Credentials } from \"../../config\";\nimport type { Rows } from \"../rows\";\nimport { forEachLimited, waitForBatch, WorldDataApi, type BatchStatus } from \"./batches\";\nimport { buildChunks, DEFAULT_CHUNK_BYTES } from \"./chunker\";\nimport { parseJson, type JsonObject } from \"./json\";\nimport type { TaggedRow } from \"./rowSource\";\n\n/**\n * Rows already in memory into a platform world through the batch lane —\n * open, chunk, upload, complete, wait — with none of the CLI's file, manifest\n * or resume machinery. What `ingestToolCalls` (the SDK) pushes after the\n * runtime projected a slug's records; the CLI keeps `data import`'s lane.\n * `redact` is optional and defaults to off: the platform stores the rows as\n * given unless asked to apply its `[redact]` policy.\n */\nexport async function pushRows(\n creds: Credentials,\n slug: string,\n rows: Rows,\n opts: {\n mode?: \"append\" | \"replace\";\n redact?: \"off\" | \"apply\" | \"refuse\";\n message?: string;\n publish?: \"now\" | \"later\";\n chunkBytes?: number;\n parallel?: number;\n dryRun?: boolean;\n sleep?: (ms: number) => Promise<void>;\n } = {},\n): Promise<BatchStatus> {\n const client = opts.sleep ? new WorldDataApi(creds, slug, opts.sleep) : new WorldDataApi(creds, slug);\n const opened = await client.open({\n mode: opts.mode ?? \"append\",\n merge: \"upsert\",\n ...(opts.redact && opts.redact !== \"off\" ? { redact: opts.redact } : {}),\n atomic: true,\n dryRun: Boolean(opts.dryRun),\n publish: opts.publish ?? \"now\",\n ...(opts.message ? { message: opts.message } : {}),\n });\n if (!opened.batchId) throw new Error(\"the platform opened no batch (no batchId in the answer)\");\n // The chunker speaks the file lane's JSON model (CPython-faithful numbers and\n // key order), so each row takes the same road a JSONL line does: serialized, parsed.\n const tagged = (async function* (): AsyncGenerator<TaggedRow> {\n for (const [entity, listed] of Object.entries(rows))\n for (let index = 0; index < listed.length; index++)\n yield { entity, row: parseJson(JSON.stringify(listed[index]!)) as JsonObject, where: `${entity}[${index}]` };\n })();\n const chunks = buildChunks(tagged, { chunkBytes: opts.chunkBytes ?? DEFAULT_CHUNK_BYTES, chunkRows: null, entity: null });\n await forEachLimited(chunks, Math.max(1, opts.parallel ?? 4), async (chunk) => {\n await client.upload(opened.batchId, chunk);\n });\n await client.complete(opened.batchId);\n return waitForBatch(client, opened.batchId, { initialDelayMs: pollMs() });\n}\n\nfunction pollMs(): number {\n const raw = Number(process.env.GATEWAY_WORLD_DATA_POLL_MS ?? 1000);\n return Number.isFinite(raw) && raw >= 0 ? raw : 1000;\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"],"mappings":";;;;;;;;;;;;;;;;;;;AAoGO,SAAS,aAAa,GAAwC;AACnE,QAAM,QAA4B,CAAC,OAAO;AAC1C,MAAI,EAAE,IAAK,OAAM,KAAK,KAAK;AAC3B,MAAI,EAAE,GAAI,OAAM,KAAK,IAAI;AACzB,MAAI,EAAE,QAAS,OAAM,KAAK,SAAS;AACnC,SAAO;AACT;AAOO,SAAS,MACd,IACAA,OACQ;AACR,QAAM,OAAO,GAAG,IAAI,QAAQ,QAAQ,EAAE;AACtC,QAAM,MAAMA,MAAK,WAAW,GAAG,IAAIA,QAAO,IAAIA,KAAI;AAClD,MAAI,CAAC,GAAG,MAAO,QAAO,OAAO;AAC7B,QAAM,CAAC,YAAY,IAAI,IAAI,UAAU,GAAG;AACxC,QAAM,SAAS,WAAW,SAAS,GAAG,IAAI,MAAM;AAChD,QAAM,QAAQ,GAAG,cAAc,IAAI,mBAAmB,GAAG,KAAK,CAAC;AAC/D,SAAO,OAAO,aAAa,SAAS,QAAQ;AAC9C;AAEO,SAAS,WAAW,IAAgD;AACzE,SAAO,MAAM,IAAI,GAAG,SAAS,GAAG;AAClC;AAGO,SAAS,eAAe,KAAqB;AAClD,QAAM,CAAC,YAAY,IAAI,IAAI,UAAU,GAAG;AACxC,QAAM,IAAI,WAAW,QAAQ,GAAG;AAChC,MAAI,IAAI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,gBAAM,QAAQ,KAAK,MAAM,IAAI,CAAC,MAAM,EAAE,WAAW,EAAE,IAAI,EAAE,KAAK,IAAI;AAClE,gBAAM,IAAI,MAAM,mBAAmB,OAAO,WAAW,KAAK,EAAE;AAAA,QAC9D;AACA,eAAO;AAAA,MACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAQA,MAAM,KACJ,MACA,OAGI,CAAC,GACsC;AAC3C,cAAM,EAAE,aAAAC,aAAY,IAAI,MAAM;AAC9B,eAAOA,aAAY,KAAK,MAAM;AAAA,UAC5B;AAAA,UACA,WAAW,KAAK,QAAQ;AAAA,UACxB,WAAW,KAAK;AAAA,UAChB,UAAU,KAAK;AAAA,UACf,SAAS,KAAK;AAAA,QAChB,CAAC;AAAA,MACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAOA,MAAM,SACJ,aACA,OAKI,CAAC,GACqD;AAC1D,cAAM,aAAa,KAAK,cAAc,iBAAiB;AACvD,eAAO;AAAA,UACL,KAAK;AAAA,UACL;AAAA,UACA;AAAA,UACA;AAAA,YACE;AAAA,YACA,GAAI,KAAK,cAAc,EAAE,aAAa,KAAK,YAAY,IAAI,CAAC;AAAA,YAC5D,WAAW,KAAK,aAAa,KAAK,QAAQ;AAAA,YAC1C,GAAG;AAAA,UACL;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA;AAAA;","names":["path","text","resolve","sleep","openWorld","api","path","pollMs","pad","text","resolve","text","hex","createHash","createHash","text","fs","path","text","fs","path","resolve","text","fs","path","SKIP_DIRS","text","fs","path","BUILD_OUTPUT","spawn","fs","os","path","resolve","createHash","fs","sleep","resolve","createHash","fs","os","path","isObject","text","ingestLocalToolCalls","importLocalWorldData","checkLocalWorldData","transformRecords","pull","pushRows","path","text","resolve","openSession"]}
|
|
1
|
+
{"version":3,"sources":["../../src/worlds/browser.ts","../../src/worlds/session.ts","../../src/worlds/tasks.ts","../../src/worlds/taskSessions.ts","../../src/worlds/evals.ts","../../src/users/index.ts","../../src/tracing/identity.ts","../../src/tracing/session.ts","../../src/scores/index.ts","../../package.json","../../src/build/index.ts","../../src/tracing/init.ts","../../src/worlds/taskRun.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/cli/router.ts","../../src/cli/config.ts","../../src/cli/runtime/local.ts","../../src/cli/runtime/client.ts","../../src/cli/runtime/data.ts","../../src/cli/platform/worldData/transform.ts","../../src/cli/platform/worldData/batches.ts","../../src/cli/platform/worldData/chunker.ts","../../src/cli/platform/worldData/push.ts","../../src/worlds/ingest.ts","../../src/worlds/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\"\n | \"neq\"\n | \"in\"\n | \"gt\"\n | \"gte\"\n | \"lt\"\n | \"lte\"\n | \"contains\";\n\n/**\n * One declarative check over the session's final rows. `where` selects rows\n * of `entity` by equality (dotted paths reach into nested objects); the\n * assertion says what must hold of the selection:\n *\n * exists (default) / absent at least one row / none\n * count `count` bound on how many\n * all / any `field op value` on every / some selected row\n *\n * A check's `id` names its entry in `rewards`; the task's reward is the\n * weighted share of checks that passed.\n */\nexport type WorldTaskCheck = {\n id?: string;\n weight?: number;\n entity: string;\n where?: Record<string, WorldTaskScalar>;\n assert?: \"exists\" | \"absent\" | \"count\" | \"all\" | \"any\";\n count?: { eq?: number; gte?: number; lte?: number };\n field?: string;\n op?: WorldTaskFieldOp;\n value?: WorldTaskScalar | WorldTaskScalar[];\n};\n\n/** One thing a rubric judge scores in [0, 1]; `id` names its entry in\n * `rewards`, `weight` (default 1) its share of the task's reward. */\nexport type WorldTaskRubricCriterion = {\n id: string;\n description: string;\n weight?: number;\n};\n\n/** A rubric is prose: what a good outcome looks like. The platform (never the\n * host) has a model read the session's final state and its call log against\n * it; the project's default evaluation model judges unless `model` pins one.\n * `grade()` then resolves asynchronously — `pending: true` first, the reward\n * once the judge has answered. */\nexport type WorldTaskRubricGrader = {\n kind: \"rubric\";\n rubric: string;\n criteria?: WorldTaskRubricCriterion[];\n model?: { provider: string; model: string };\n};\n\n/** How a task is graded: checks the host evaluates in-process, a `verify.py`\n * body (state JSON on stdin, last stdout line `{reward, ...}`) run through the\n * host's confined verifier, or a rubric judged by a model on the platform. */\nexport type WorldTaskGrader =\n | { kind: \"assertions\"; checks: WorldTaskCheck[] }\n | { kind: \"python\"; source: string; timeoutSeconds?: number }\n | WorldTaskRubricGrader;\n\n/** A task supplied at open, for one session, instead of a bundled scenario.\n * `instruction` is what the agent is told; without `seed` the session starts\n * on the version's base data, without `grader` `grade()` answers\n * `reward: null`; `tools` is the allow-list of the version's tools the agent\n * may call in this session (unset: all of them; a call outside it is refused\n * and logged); `metadata` is yours (an end-user id, a ticket) and is echoed\n * on the session, never read. Limits: shared/domain/worldTasks.ts. */\nexport type WorldTaskSpec = {\n name?: string;\n instruction: string;\n seed?: WorldTaskSeed;\n grader?: WorldTaskGrader;\n tools?: string[];\n metadata?: Record<string, unknown>;\n /** A MULTI-WORLD task: one session per alias, each on its own world with\n * its own seed, grader and tools (the top-level three are then refused).\n * Brought up together by `openTask` / `gateway worlds task up`; see\n * worlds/taskSessions.ts. */\n worlds?: Record<\n string,\n {\n slug: string;\n /** One of the world's refs; default `main`. */\n ref?: string;\n seed?: WorldTaskSeed;\n grader?: WorldTaskGrader;\n tools?: string[];\n }\n >;\n};\n\n/** A stored task of the project (see worlds/tasks.ts), opened by id; the\n * session runs a copy of one version's spec — the current one by default. */\nexport type WorldTaskIdRef = { id: string; version?: number };\n\n/** What `openSession` takes as the task: a bundled scenario's name, a\n * stored task's `{ id, version? }`, or an inline spec. */\nexport type WorldTaskRef = string | WorldTaskIdRef | WorldTaskSpec;\n\n/** What a session's task is, on every session response. `hash` is the\n * content hash of the spec (inline or stored) — what warm reuse matches on;\n * `id`/`version` name the stored task the session was opened on. */\nexport type WorldSessionTask = {\n source: \"bundled\" | \"inline\" | \"stored\";\n name: string | null;\n hash: string | null;\n id?: string | null;\n version?: number | null;\n metadata: Record<string, unknown>;\n};\n\nexport const isTaskIdRef = (task: WorldTaskRef): task is WorldTaskIdRef =>\n typeof task === \"object\" && task !== null && \"id\" in task;\n\nexport const isTaskSpec = (task: WorldTaskRef): task is WorldTaskSpec =>\n typeof task === \"object\" && task !== null && \"instruction\" in task;\n\n/** The label a task goes by in results: its name, `inline:<hash>` for an\n * unnamed inline task once the platform has hashed it, or the stored task's\n * name (its id until the platform has answered). */\nexport const taskLabel = (\n task: WorldTaskRef,\n info?: WorldSessionTask | null,\n): string => {\n if (typeof task === \"string\") return task;\n if (isTaskIdRef(task)) return info?.name ?? task.id;\n if (task.name) return task.name;\n return info?.hash ? `inline:${info.hash.slice(0, 12)}` : \"inline\";\n};\n\nexport type SeedResult = {\n seeded: number;\n mode: \"append\" | \"replace\";\n entity_counts: Record<string, number>;\n};\n\n/** One row of the session's call log. */\nexport type WorldSessionCall = {\n seq: number;\n kind: string;\n tool: string | null;\n args: unknown;\n result: unknown;\n error: string | null;\n completedAt: string | null;\n};\n\nexport type WorldSessionState = {\n sessionId: string;\n state: string;\n ready: boolean;\n versionId: string;\n contentHash: string;\n taskName: string | null;\n /** Where the task came from and what it is; absent on platforms that\n * predate session tasks, in which case it is derived from `taskName`. */\n task?: WorldSessionTask;\n /** The task's objective — present when the session was opened (not on a\n * bare status read), so a client never needs the bundle on disk. */\n instruction?: string | null;\n /** The tools this task serves. */\n tools?: WorldToolSpec[];\n /** Where the session answers besides `tools` — see worlds/browser.ts. */\n surfaces?: SessionSurfaces;\n /** Notices about the world's shape (an api bundle is a deprecated layout;\n * schema worlds are the supported shape), with what to run instead. Empty\n * for a schema world; absent on platforms that predate the notice. */\n deprecations?: WorldDeprecation[];\n};\n\n/** One notice a worlds-path answer carries: a deprecated shape or layout\n * and the command that replaces it. A retired shape is refused instead,\n * with the stable message prefix `world_kind_retired:`. */\nexport type WorldDeprecation = {\n code: string;\n message: string;\n replacement: string;\n};\n\nexport type GradeResult = {\n reward: number | null;\n rewards: Record<string, number>;\n raw: unknown;\n};\n\n/** How long `ready()` waits, and how often it asks. */\nconst READY_TIMEOUT_MS = 10 * 60_000;\nconst READY_POLL_MS = 2_000;\n/** How long one call may take end to end (container claim + execution). */\nconst CALL_TIMEOUT_MS = 3 * 60_000;\nconst CALL_POLL_MS = 400;\n/** How long a grade the platform's judge finalizes may take: the model's own\n * timeout and retries, plus the worker's queue backoff. Polled slowly. */\nconst JUDGED_GRADE_TIMEOUT_MS = 15 * 60_000;\nconst JUDGED_GRADE_POLL_MS = 2_000;\nconst EXPORT_PAGE = 500;\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\nexport const modelToolName = (name: string): string =>\n name.replace(/[^A-Za-z0-9_-]/g, \"_\").slice(0, 64) || \"tool\";\n\n/**\n * Turn a world's Python signature into a JSON schema the model can call.\n *\n * `crm_update_deal(id, stage=None, owner=None, amount=None)` becomes an\n * object with `id` required and the rest optional. Types are read from the\n * DEFAULTS the world declares — a numeric default means a number, a boolean\n * default a boolean — because that is the only type information a signature\n * actually carries. Everything else is a string, which is what a tool CLI\n * receives anyway.\n */\nexport function schemaFromSignature(spec: WorldToolSpec): {\n type: \"function\";\n function: {\n name: string;\n description: string;\n parameters: Record<string, unknown>;\n };\n} {\n if (spec.inputSchema)\n return {\n type: \"function\",\n function: {\n name: modelToolName(spec.name),\n description: spec.doc ?? spec.name,\n parameters: spec.inputSchema,\n },\n };\n const inside = /\\(([\\s\\S]*)\\)\\s*$/.exec(spec.signature.trim())?.[1] ?? \"\";\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n // Split on top-level commas only: a default like `{\"a\": 1}` has its own.\n const params: string[] = [];\n let depth = 0;\n let current = \"\";\n for (const ch of inside) {\n if (\"([{\".includes(ch)) depth++;\n if (\")]}\".includes(ch)) depth--;\n if (ch === \",\" && depth === 0) {\n params.push(current);\n current = \"\";\n } else current += ch;\n }\n if (current.trim()) params.push(current);\n\n for (const raw of params) {\n const param = raw.trim();\n if (!param || param.startsWith(\"*\") || param === \"self\") continue;\n const eq = param.indexOf(\"=\");\n const name = (eq === -1 ? param : param.slice(0, eq)).split(\":\")[0].trim();\n if (!name) continue;\n if (eq === -1) {\n properties[name] = { type: \"string\" };\n required.push(name);\n continue;\n }\n const value = param.slice(eq + 1).trim();\n if (/^-?\\d+(\\.\\d+)?$/.test(value)) properties[name] = { type: \"number\" };\n else if (value === \"True\" || value === \"False\")\n properties[name] = { type: \"boolean\" };\n else properties[name] = { type: \"string\" };\n }\n return {\n type: \"function\",\n function: {\n name: modelToolName(spec.name),\n description: spec.doc ?? spec.name,\n parameters: { type: \"object\", properties, required },\n },\n };\n}\n\nexport class WorldSessionTimeout extends Error {}\nexport class WorldSessionCallError extends Error {}\n\nexport class WorldSession {\n constructor(\n readonly sessionId: string,\n private current: WorldSessionState,\n private readonly options: WorldsClientOptions,\n ) {}\n\n /** The task's display name: a bundled scenario's, or the inline spec's\n * `name` (null when the spec was unnamed). Same as `taskName`. */\n get task(): string | null {\n return this.current.taskName;\n }\n\n /** The task's display name: a bundled scenario's, or the inline spec's\n * `name` (null when the spec was unnamed). */\n get taskName(): string | null {\n return this.current.taskName;\n }\n\n /** The platform's notices about the world this session runs on (empty\n * for a schema world). Printed by the CLI on stderr at open. */\n get deprecations(): WorldDeprecation[] {\n return this.current.deprecations ?? [];\n }\n\n /** The task this session runs: bundled scenario, stored task or inline\n * spec, its name, hash and the caller's metadata. */\n get taskInfo(): WorldSessionTask {\n return (\n this.current.task ?? {\n source: \"bundled\",\n name: this.current.taskName,\n hash: null,\n metadata: {},\n }\n );\n }\n\n /** What this task asks for — the bundle's instruction.md, or the inline\n * spec's `instruction`. */\n get instruction(): string | null {\n return this.current.instruction ?? null;\n }\n\n get versionId(): string {\n return this.current.versionId;\n }\n\n /** Whether the session answered ready as of the last state read (the open,\n * a `status()`, or the poll inside `ready()`); no request is made. */\n get isReady(): boolean {\n return this.current.ready;\n }\n\n /** `api` / `ui` / `browser` are present exactly when the world declares\n * them AND the session was opened asking for them. */\n async surfaces(): Promise<SessionSurfaces> {\n if (!this.current.surfaces) await this.status();\n return this.current.surfaces ?? { tools: { kind: \"rendezvous\" } };\n }\n\n /** Base URL of the world's own HTTP API for this session. */\n async api(): Promise<string> {\n const { api } = await this.surfaces();\n if (!api)\n throw new WorldSurfaceUnavailable(\n \"api\",\n \"open the session with surfaces: ['api'] on an api-type world\",\n );\n return api.url;\n }\n\n /** Headers every request to `api()` needs. A World Host session gates its\n * api surface on a per-session token; a pod or hosted twin answers with the\n * world's own declared auth and this is `{}`. */\n async apiHeaders(): Promise<Record<string, string>> {\n const { api } = await this.surfaces();\n return api?.token ? { Authorization: `Bearer ${api.token}` } : {};\n }\n\n /** URL of the world's UI entry page for this session. */\n async ui(): Promise<string> {\n const { ui } = await this.surfaces();\n if (!ui)\n throw new WorldSurfaceUnavailable(\n \"ui\",\n \"open the session with surfaces: ['ui'] on a world that declares [ui]\",\n );\n return uiEntryUrl(ui);\n }\n\n /** A Playwright browser on this session's UI: `hosted` drives the one the\n * platform runs next to the world, `local` launches one here, `auto`\n * prefers hosted. Call `close()` when done.\n *\n * Every action is reported to the platform under `agentId` (default:\n * `GATEWAY_AGENT_ID` or a fresh `agent-<hex>`) so the session page shows\n * this agent's own timeline — several agents may share one session and\n * one hosted browser. `record: false` opts out. */\n async browser(\n opts: {\n mode?: BrowserMode;\n headless?: boolean;\n playwright?: PlaywrightLike;\n agentId?: string;\n record?: boolean;\n } = {},\n ): Promise<WorldBrowser> {\n const { agentId, record = true, ...rest } = opts;\n return openBrowser(await this.surfaces(), {\n ...rest,\n recorder: record ? this.browserRecorder(agentId) : null,\n });\n }\n\n /** The reporter `browser()` uses; exposed for a page you drive yourself. */\n browserRecorder(agentId?: string): BrowserActionRecorder {\n const path = `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/browser-events`;\n const id =\n agentId ??\n process.env.GATEWAY_AGENT_ID ??\n `agent-${randomUUID().replace(/-/g, \"\").slice(0, 8)}`;\n return new BrowserActionRecorder(\n async (events: BrowserActionEvent[]) => {\n await apiRequest(this.options, \"POST\", path, { events });\n },\n id,\n {\n // Continue this agent's timeline where the platform has it, so the\n // same id reopened later never re-numbers from zero.\n resumeFrom: async () => {\n const summary = await apiRequest<{\n agents: { agentId: string; nextSeq: number }[];\n }>(this.options, \"GET\", path);\n return summary.agents.find((a) => a.agentId === id)?.nextSeq ?? 0;\n },\n },\n );\n }\n\n /** Browser actions as model tools, in the same shape as `toolkit()`. */\n computerUseTools(browser: WorldBrowser): WorldToolkit {\n return computerUseToolkit(browser);\n }\n\n /** The session's latest platform state (one request, no waiting). */\n async status(): Promise<WorldSessionState> {\n const fresh = await apiRequest<WorldSessionState>(\n this.options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}`,\n );\n // A status read does not carry the objective; keep the one we opened with.\n this.current = {\n instruction: this.current.instruction,\n tools: this.current.tools,\n surfaces: this.current.surfaces,\n task: this.current.task,\n ...fresh,\n };\n return this.current;\n }\n\n /**\n * Wait until the container is warm — meaning the process inside it has\n * asked the platform for work, not merely that a job was accepted.\n */\n async ready(opts: { timeoutMs?: number } = {}): Promise<WorldSessionState> {\n const deadline = Date.now() + (opts.timeoutMs ?? READY_TIMEOUT_MS);\n for (;;) {\n const state = await this.status();\n if (state.ready) return state;\n if (state.state === \"FAILED\" || state.state === \"STOPPED\")\n throw new WorldSessionCallError(\n `World session ${state.state.toLowerCase()} before it was ready.`,\n );\n if (Date.now() > deadline)\n throw new WorldSessionTimeout(\n `World session still ${state.state} after ${Math.round((opts.timeoutMs ?? READY_TIMEOUT_MS) / 1000)}s.`,\n );\n await sleep(READY_POLL_MS);\n }\n }\n\n /** Enqueue one interaction and wait for the container's answer. */\n private async exchange(\n body: {\n kind?: \"call\" | \"grade\" | \"reset\" | \"state\" | \"seed\" | \"close\";\n tool?: string;\n args?: unknown;\n /** Grade only: the agent's report, for a rubric judge. */\n report?: string;\n },\n timeoutMs?: number,\n ): Promise<unknown> {\n const enqueued = await apiRequest<{\n callId: string;\n seq: number;\n /** The platform's worker finalizes this call (a rubric grade). */\n pending?: boolean;\n }>(\n this.options,\n \"POST\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/calls`,\n body,\n );\n const { callId } = enqueued;\n const judged = enqueued.pending === true;\n const budgetMs =\n timeoutMs ?? (judged ? JUDGED_GRADE_TIMEOUT_MS : CALL_TIMEOUT_MS);\n const pollMs = judged ? JUDGED_GRADE_POLL_MS : CALL_POLL_MS;\n const deadline = Date.now() + budgetMs;\n for (;;) {\n const call = await apiRequest<{\n done: boolean;\n state: string;\n result: unknown;\n error: string | null;\n }>(\n this.options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/calls/${encodeURIComponent(callId)}`,\n );\n if (call.done) {\n if (call.error) throw new WorldSessionCallError(call.error);\n return call.result;\n }\n if (Date.now() > deadline)\n throw new WorldSessionTimeout(\n judged\n ? `Grade ${callId} still ${call.state} after ${Math.round(budgetMs / 1000)}s — the judge has not answered; the platform finalizes the call on its own, read it back with export().`\n : `Call ${callId} still ${call.state} after ${Math.round(budgetMs / 1000)}s — the container may have died.`,\n );\n await sleep(pollMs);\n }\n }\n\n /**\n * Run one of the world's tools INSIDE the container. The arguments and the\n * result are the world's own contract — this layer neither validates nor\n * reshapes them, so a tool error reads exactly as it would in a hosted run.\n */\n async call(\n tool: string,\n args: Record<string, unknown> = {},\n opts: { timeoutMs?: number } = {},\n ): Promise<unknown> {\n return this.exchange({ kind: \"call\", tool, args }, opts.timeoutMs);\n }\n\n /**\n * THE WORLD'S TOOLS, READY TO HAND TO A MODEL. Schemas come from the\n * world's own signatures and implementations call into this session, so a\n * caller never writes — and never has to re-sync — a tool map of their own:\n *\n * const { schemas, impls } = await session.toolkit();\n * await runMyAgent(impls, schemas, session.instruction);\n *\n * A tool added to the world shows up here on the next run; a tool renamed\n * in the world renames here too, instead of failing at call time against a\n * hand-written map that still remembers the old name.\n */\n async toolkit(): Promise<WorldToolkit> {\n let specs = this.current.tools;\n if (!specs) specs = (await this.status()).tools ?? [];\n const impls: WorldToolkit[\"impls\"] = Object.create(null);\n for (const spec of specs) {\n const alias = modelToolName(spec.name);\n if (Object.hasOwn(impls, alias))\n throw new WorldSessionCallError(`Model tool name collision: ${alias}`);\n impls[alias] = (args: Record<string, unknown> = {}) =>\n this.call(spec.name, args);\n }\n return { schemas: specs.map(schemaFromSignature), impls, specs };\n }\n\n /** Run the task's grader against the container's END STATE. Graders answer\n * in one of two shapes: the scalar with named rewards beside it\n * (`{reward, check_a, check_b}`, a task's own `grade.py`), or the named\n * rewards nested under `rewards` (the api, mock-tools and World Host\n * runners). Both land in `rewards`.\n *\n * A rubric grade is finalized by the platform's judge, not the container:\n * the platform answers the enqueue with `pending: true`, and this waits on\n * the judge's budget (15 min) instead of a call's. `timeoutMs` overrides\n * either. `report` is the agent's own account of what it did and found,\n * handed to the judge as its claim beside the evidence (the state and the\n * calls); assertions and python graders ignore it. */\n async grade(\n opts: { timeoutMs?: number; report?: string } = {},\n ): Promise<GradeResult> {\n const raw = (await this.exchange(\n opts.report !== undefined\n ? { kind: \"grade\", report: opts.report }\n : { kind: \"grade\" },\n opts.timeoutMs,\n )) as Record<string, unknown> | null;\n const record = raw && typeof raw === \"object\" ? raw : {};\n const rewards: Record<string, number> = {};\n const nested = record.rewards;\n if (nested && typeof nested === \"object\") {\n for (const [key, value] of Object.entries(nested)) {\n if (typeof value === \"number\") rewards[key] = value;\n }\n }\n for (const [key, value] of Object.entries(record)) {\n if (key !== \"reward\" && typeof value === \"number\") rewards[key] = value;\n }\n return {\n reward: typeof record.reward === \"number\" ? record.reward : null,\n rewards,\n raw,\n };\n }\n\n /**\n * Put rows into the LIVE world through its contract, in one batch:\n * `append` (default) upserts by primary key, `replace` makes the named\n * entities hold exactly these rows. Atomic — a refused row leaves the\n * session unchanged and the error names the entity, row and field.\n */\n async seed(\n rows: Record<string, Record<string, unknown>[]>,\n opts: {\n mode?: \"append\" | \"replace\";\n /** `apply` runs the world's `[redact]` policy over the rows first;\n * `refuse` rejects plaintext in a redacted field; default `off`. */\n redact?: \"off\" | \"apply\" | \"refuse\";\n timeoutMs?: number;\n } = {},\n ): Promise<SeedResult> {\n const mode = opts.mode ?? \"append\";\n const redact = opts.redact ?? \"off\";\n return (await this.exchange(\n {\n kind: \"seed\",\n args: { mode, rows, ...(redact !== \"off\" ? { redact } : {}) },\n },\n opts.timeoutMs,\n )) as SeedResult;\n }\n\n /** Every entity's rows as the world holds them now — the same dump a\n * grader reads. The shape is the world runtime's: a schema world answers\n * `{<entity>: {<key>: row}, snapshot}`, a mock-tools world\n * `{entities: {<entity>: [row]}}`. */\n async state(opts: { timeoutMs?: number } = {}): Promise<unknown> {\n return this.exchange({ kind: \"state\" }, opts.timeoutMs);\n }\n\n /** Back to the opening state: the version's data plus the bundled\n * scenario's or the inline task's seed. Rows written since are gone; the\n * call log stays. */\n async reset(opts: { timeoutMs?: number } = {}): Promise<void> {\n await this.exchange({ kind: \"reset\" }, opts.timeoutMs);\n }\n\n /** The session's call log, oldest first: every tool call, seed, reset,\n * grade with its result — the record of the episode. */\n async export(): Promise<WorldSessionCall[]> {\n const calls: WorldSessionCall[] = [];\n let cursor: string | undefined;\n do {\n const params = new URLSearchParams({ limit: String(EXPORT_PAGE) });\n if (cursor) params.set(\"cursor\", cursor);\n const page = await apiRequest<{\n calls: Record<string, unknown>[];\n nextCursor?: string | null;\n }>(\n this.options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/calls?${params.toString()}`,\n );\n for (const call of page.calls) {\n calls.push({\n seq: Number(call.seq),\n kind: String(call.kind ?? \"call\"),\n tool: typeof call.tool === \"string\" ? call.tool : null,\n args: call.args ?? null,\n result: call.result ?? null,\n error: typeof call.error === \"string\" ? call.error : null,\n completedAt:\n typeof call.completedAt === \"string\" ? call.completedAt : null,\n });\n }\n cursor = page.nextCursor ?? undefined;\n } while (cursor);\n return calls;\n }\n\n /**\n * Promote this session's inline task into a stored task of the project\n * (version 1, pinned to the session's world unless `world` says otherwise),\n * so a task written for one end user can be reused and its grades\n * compared. The session then records the new task's id. A session on a\n * bundled task has nothing to save; one on a stored task is already saved.\n */\n async saveTask(\n opts: { name?: string; world?: string | null; message?: string } = {},\n ): Promise<WorldTaskSummary> {\n const task = await apiRequest<WorldTaskSummary>(\n this.options,\n \"POST\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/task`,\n {\n ...(opts.name !== undefined ? { name: opts.name } : {}),\n ...(opts.world !== undefined ? { world: opts.world } : {}),\n ...(opts.message !== undefined ? { message: opts.message } : {}),\n },\n );\n this.current = {\n ...this.current,\n taskName: task.name,\n task: {\n ...this.taskInfo,\n source: \"stored\",\n name: task.name,\n id: task.id,\n version: task.version,\n },\n };\n return task;\n }\n\n /**\n * End the session. `keepWarm` hands the container back to the pool instead\n * of tearing it down, so the next session for the same task starts warm —\n * the pooled instance still obeys the fleet's idle TTL and pinning.\n */\n async close(opts: { keepWarm?: boolean } = {}): Promise<{ state: string }> {\n return apiRequest(\n this.options,\n \"DELETE\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}`,\n { keepWarm: opts.keepWarm ?? false },\n );\n }\n}\n\n/**\n * Attach to a session that already exists — resuming after a crash, or\n * driving a session someone else opened (a container started by hand on a\n * self-hosted install, a session opened by CI and handed to a developer).\n */\nexport async function attachSession(\n sessionId: string,\n options: WorldsClientOptions = {},\n): Promise<WorldSession> {\n const state = await apiRequest<WorldSessionState>(\n options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(sessionId)}`,\n );\n return new WorldSession(sessionId, state, options);\n}\n\nexport type OpenSessionOptions = {\n versionId?: string;\n reuseWarm?: boolean;\n /** More than `tools`: `[\"api\"]`, `[\"ui\"]`, `[\"browser\"]`. The platform\n * refuses (HTTP 400) rather than quietly serving less than asked. */\n surfaces?: WorldSurfaceKind[];\n options?: WorldsClientOptions;\n};\n\n/**\n * Open a live session against one task of a world. Returns as soon as the\n * platform has accepted it — call `ready()` to wait for the container.\n *\n * `task` is a bundled scenario's name, a stored task's `{ id, version? }`\n * or an inline `WorldTaskSpec` (the latter two need a host engine world — the\n * platform answers 400 for a pod world). The older positional form\n * `openSession(slug, \"task-name\", opts)` still works.\n */\nexport async function openSession(\n slugOrRef: string,\n task: OpenSessionOptions & { task: WorldTaskRef },\n): Promise<WorldSession>;\nexport async function openSession(\n slugOrRef: string,\n task: WorldTaskRef,\n opts?: OpenSessionOptions,\n): Promise<WorldSession>;\nexport async function openSession(\n slugOrRef: string,\n taskOrOpts: WorldTaskRef | (OpenSessionOptions & { task: WorldTaskRef }),\n positionalOpts: OpenSessionOptions = {},\n): Promise<WorldSession> {\n const { task, ...opts } =\n typeof taskOrOpts === \"object\" && \"task\" in taskOrOpts\n ? taskOrOpts\n : { task: taskOrOpts as WorldTaskRef, ...positionalOpts };\n if (\n task === undefined ||\n task === null ||\n (typeof task === \"string\" && !task) ||\n (isTaskIdRef(task) && !task.id) ||\n (isTaskSpec(task) && !task.instruction) ||\n (typeof task === \"object\" && !isTaskIdRef(task) && !isTaskSpec(task))\n )\n throw new Error(\n \"openSession needs a task: a bundled task name, a stored task { id, version? } or { instruction, seed?, grader?, metadata? }\",\n );\n const options = opts.options ?? {};\n const unknown = (opts.surfaces ?? []).filter(\n (s) => !(SURFACE_KINDS as readonly string[]).includes(s),\n );\n if (unknown.length)\n throw new Error(\n `Unknown world surfaces: ${unknown.join(\", \")}; choose from ${SURFACE_KINDS.join(\", \")}`,\n );\n const at = slugOrRef.indexOf(\"@\");\n const slug = at === -1 ? slugOrRef : slugOrRef.slice(0, at);\n const 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 WorldTaskWorldValidation = {\n slug: string;\n ref: string;\n versionId: string;\n ok: boolean;\n checked: \"entities\" | \"none\";\n problems: string[];\n entities: string[] | null;\n};\n\nexport type WorldTaskValidation = {\n taskId: string;\n version: number;\n /** The world version the task was checked against; null for a task with\n * `worlds`, whose versions are per alias under `worlds`. */\n versionId: string | null;\n ok: boolean;\n /** `entities` when the world's contract was read and every seed and check\n * entity was matched against it; `none` when the version has no contract\n * to check (a mock-tools world), in which case `ok` says only that the\n * version exists and is READY; `worlds` for a multi-world task, checked\n * alias by alias against the ref each names. */\n checked: \"entities\" | \"none\" | \"worlds\";\n /** For a multi-world task each problem is prefixed with its alias. */\n problems: string[];\n entities: string[] | null;\n worlds?: Record<string, WorldTaskWorldValidation>;\n};\n\nconst TASKS = \"/api/public/world-tasks\";\nconst taskRoute = (id: string) => `${TASKS}/${encodeURIComponent(id)}`;\n\nconst compact = (body: Record<string, unknown>) =>\n Object.fromEntries(Object.entries(body).filter(([, v]) => v !== undefined));\n\n/** Store a task. `name` defaults to `spec.name`; one of the two is needed. */\nexport async function createTask(\n input: {\n spec: WorldTaskSpec;\n name?: string;\n world?: string | null;\n message?: string;\n },\n options: WorldsClientOptions = {},\n): Promise<WorldTaskSummary> {\n return apiRequest<WorldTaskSummary>(\n options,\n \"POST\",\n TASKS,\n compact({\n spec: input.spec,\n name: input.name,\n world: input.world,\n message: input.message,\n }),\n );\n}\n\n/** Change a task. A new `spec` becomes the next version (the old ones stay\n * readable and openable); `name` and `world` change in place. */\nexport async function updateTask(\n taskId: string,\n input: {\n spec?: WorldTaskSpec;\n name?: string;\n world?: string | null;\n message?: string;\n },\n options: WorldsClientOptions = {},\n): Promise<WorldTaskSummary> {\n if (\n input.spec === undefined &&\n input.name === undefined &&\n input.world === undefined\n )\n throw new Error(\"updateTask: nothing to update — pass spec, name or world\");\n return apiRequest<WorldTaskSummary>(\n options,\n \"PATCH\",\n taskRoute(taskId),\n compact({\n spec: input.spec,\n name: input.name,\n world: input.world,\n message: input.message,\n }),\n );\n}\n\n/** The project's tasks, newest change first. `world` keeps only tasks\n * pinned to that slug; `metadata` keeps tasks whose spec metadata carries\n * every given key/value (`{ externalUserId: \"u_42\" }`). */\nexport async function listTasks(\n filter: {\n world?: string;\n metadata?: Record<string, string>;\n page?: number;\n limit?: number;\n } = {},\n options: WorldsClientOptions = {},\n): Promise<WorldTaskPage> {\n const params = new URLSearchParams();\n if (filter.world) params.set(\"world\", filter.world);\n if (filter.page !== undefined) params.set(\"page\", String(filter.page));\n if (filter.limit !== undefined) params.set(\"limit\", String(filter.limit));\n for (const [key, value] of Object.entries(filter.metadata ?? {}))\n params.set(`metadata.${key}`, value);\n const query = params.toString();\n return apiRequest<WorldTaskPage>(\n options,\n \"GET\",\n query ? `${TASKS}?${query}` : TASKS,\n );\n}\n\n/** One task with its version history; `version` reads that version's spec\n * instead of the current one. */\nexport async function getTask(\n taskId: string,\n opts: { version?: number } = {},\n options: WorldsClientOptions = {},\n): Promise<WorldTaskDetail> {\n const query =\n opts.version === undefined ? \"\" : `?version=${String(opts.version)}`;\n return apiRequest<WorldTaskDetail>(\n options,\n \"GET\",\n `${taskRoute(taskId)}${query}`,\n );\n}\n\n/** Remove a task and every version. Sessions already opened on it keep\n * their copy of the spec. */\nexport async function deleteTask(\n taskId: string,\n options: WorldsClientOptions = {},\n): Promise<{ id: string; name: string }> {\n return apiRequest(options, \"DELETE\", taskRoute(taskId));\n}\n\n/** Check a task against a world version without opening a session: every\n * seed entity and every check's entity must exist in the world's contract.\n * `slug` checks against that world's head, `versionId` against an exact\n * version, neither against the task's own `world` pin. */\nexport async function validateTask(\n taskId: string,\n target: { version?: number; slug?: string; versionId?: string } = {},\n options: WorldsClientOptions = {},\n): Promise<WorldTaskValidation> {\n return apiRequest<WorldTaskValidation>(\n options,\n \"POST\",\n `${taskRoute(taskId)}/validate`,\n compact({\n version: target.version,\n slug: target.slug,\n versionId: target.versionId,\n }),\n );\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\nimport {\n surfaceKinds,\n uiEntryUrl,\n type SessionSurfaces,\n type WorldSurfaceKind,\n} from \"./browser\";\nimport {\n WorldSession,\n attachSession,\n isTaskIdRef,\n type GradeResult,\n type WorldSessionCall,\n type WorldSessionState,\n type WorldTaskIdRef,\n type WorldTaskSpec,\n} from \"./session\";\n\n/**\n * TASKS THAT NEED SEVERAL WORLDS.\n *\n * A task whose spec names `worlds` is one instruction over N hosted worlds\n * — an investigation that reads a breach feed, a threat-intel API and a\n * ticketing system, say. `openTask` brings every one of them up in ONE call\n * and hands back the sessions keyed by the aliases the spec chose:\n *\n * const task = await openTask({ id: \"wt_1\" }, { surfaces: [\"api\"] });\n * await task.ready();\n * const spycloud = task.sessions.spycloud; // a WorldSession\n * await myAgent(task.instruction, task.sessions);\n * const grade = await task.grade(); // per world + aggregate\n * await task.close();\n *\n * The platform opens the sessions (POST /world-task-sessions) and refuses\n * a partial bring-up: if one world fails, the ones that opened are closed\n * and the error names every alias that failed. Everything after — ready,\n * grade, export, close — is one `WorldSession` call per world, fanned out\n * here. `manifest()` is the record `gateway worlds task up` prints, and\n * `attachTask` rebuilds a `TaskSessions` from a stored task's live sessions.\n */\n\nconst TASK_SESSIONS = \"/api/public/world-task-sessions\";\n\n/** The per-world entry of a `WorldTaskSpec.worlds` table. */\nexport type WorldTaskWorld = {\n slug: string;\n ref?: string;\n seed?: WorldTaskSpec[\"seed\"];\n grader?: WorldTaskSpec[\"grader\"];\n tools?: string[];\n};\n\n/** One world's session as the platform answered it at up. */\nexport type TaskWorldSessionState = WorldSessionState & {\n alias: string;\n slug: string;\n ref: string;\n reusedWarm: boolean;\n};\n\n/** What `POST /world-task-sessions` answers. */\nexport type TaskSessionsResponse = {\n taskId: string | null;\n taskVersion: number | null;\n name: string | null;\n hash: string;\n instruction: string;\n sessions: Record<string, TaskWorldSessionState>;\n};\n\n/** One world in the manifest: where it answers, in the shape\n * `gateway worlds session open` prints for a single session. */\nexport type TaskManifestSession = {\n slug: string;\n ref: string | null;\n versionId: string;\n sessionId: string;\n ready: boolean;\n state: string;\n surfaces: WorldSurfaceKind[];\n api?: { url: string; token?: string };\n ui?: { url: string; entry: string; apiPath: string | null };\n browser?: { wsUrl: string; viewport?: unknown };\n};\n\n/** The manifest: every session of the task, keyed by alias. The file\n * `task up --out` writes and `task down|status|grade|export` read. */\nexport type TaskManifest = {\n taskId: string | null;\n taskVersion: number | null;\n name: string | null;\n instruction: string | null;\n sessions: Record<string, TaskManifestSession>;\n};\n\n/** A stored task's live sessions, as `GET /world-task-sessions` lists them. */\nexport type LiveTaskSession = {\n alias: string | null;\n slug: string | null;\n sessionId: string;\n state: string;\n ready: boolean;\n versionId: string;\n taskVersion: number | null;\n createdAt: string;\n};\n\n/** The task's grade: every world's own `GradeResult` under its alias, and\n * the aggregate. `reward` is the mean of the worlds' numeric rewards — null\n * when no world answered one (no grader anywhere, or a judge still\n * pending); a world with no reward is listed under `ungraded`, never\n * counted as 0. `rewards` flattens each world's named rewards as\n * `<alias>.<key>` beside `<alias>` for the world's own reward. */\nexport type TaskGrade = {\n reward: number | null;\n rewards: Record<string, number>;\n worlds: Record<string, GradeResult>;\n ungraded: string[];\n};\n\n/** Every world's call log, keyed by alias. */\nexport type TaskExport = Record<string, WorldSessionCall[]>;\n\nconst manifestSession = (\n s: SessionSurfaces,\n state: {\n sessionId: string;\n ready: boolean;\n state: string;\n versionId: string;\n },\n world: { slug: string; ref: string | null },\n): TaskManifestSession => ({\n slug: world.slug,\n ref: world.ref,\n versionId: state.versionId,\n sessionId: state.sessionId,\n ready: state.ready,\n state: state.state,\n surfaces: surfaceKinds(s),\n ...(s.api\n ? {\n api: { url: s.api.url, ...(s.api.token ? { token: s.api.token } : {}) },\n }\n : {}),\n ...(s.ui\n ? {\n ui: {\n url: s.ui.url,\n entry: uiEntryUrl(s.ui),\n apiPath: s.ui.apiPath ?? null,\n },\n }\n : {}),\n ...(s.browser\n ? { browser: { wsUrl: s.browser.wsUrl, viewport: s.browser.viewport } }\n : {}),\n});\n\n/** Combine per-world grades into the task's. Pure, so the CLI and the tests\n * share it with `TaskSessions.grade()`. */\nexport function aggregateTaskGrade(\n worlds: Record<string, GradeResult>,\n): TaskGrade {\n const rewards: Record<string, number> = {};\n const ungraded: string[] = [];\n const graded: number[] = [];\n for (const [alias, grade] of Object.entries(worlds)) {\n if (typeof grade.reward === \"number\") {\n rewards[alias] = grade.reward;\n graded.push(grade.reward);\n } else ungraded.push(alias);\n for (const [key, value] of Object.entries(grade.rewards))\n rewards[`${alias}.${key}`] = value;\n }\n const reward =\n graded.length > 0\n ? graded.reduce((a, b) => a + b, 0) / graded.length\n : null;\n return { reward, rewards, worlds, ungraded };\n}\n\nexport class TaskSessions {\n constructor(\n /** The stored task's id, or null for a task given as a spec. */\n readonly taskId: string | null,\n readonly taskVersion: number | null,\n readonly name: string | null,\n /** The instruction every world's session shares. */\n readonly instruction: string | null,\n /** One live session per alias, in the spec's order. */\n readonly sessions: Record<string, WorldSession>,\n private readonly worlds: Record<\n string,\n { slug: string; ref: string | null }\n >,\n /** The spec's content hash — set only by `openTask` (the raw platform\n * response carries it); null for a `TaskSessions` rebuilt with\n * `attachManifest`/`attachTask`, which have no spec to hash. */\n readonly hash: string | null = null,\n ) {}\n\n /** This alias's `{slug, ref}` as recorded at open/attach — the world a\n * `TaskRun` filing needs to name, without exposing the whole map. */\n worldRef(alias: string): { slug: string; ref: string | null } {\n return this.worlds[alias] ?? { slug: \"\", ref: null };\n }\n\n /** The aliases, in the spec's order. */\n get aliases(): string[] {\n return Object.keys(this.sessions);\n }\n\n /** The alias's session, or a clear error naming the aliases there are. */\n session(alias: string): WorldSession {\n const session = this.sessions[alias];\n if (!session)\n throw new Error(\n `task has no world '${alias}'; its worlds are ${this.aliases.join(\", \")}`,\n );\n return session;\n }\n\n private async each<T>(\n fn: (session: WorldSession, alias: string) => Promise<T>,\n ): Promise<Record<string, T>> {\n const entries = await Promise.all(\n Object.entries(this.sessions).map(\n async ([alias, session]) => [alias, await fn(session, alias)] as const,\n ),\n );\n return Object.fromEntries(entries);\n }\n\n /** Wait until every world answers ready. A world that never does throws\n * `WorldSessionTimeout` naming it; the others are left up. */\n async ready(opts: { timeoutMs?: number } = {}): Promise<void> {\n await this.each((session) => session.ready(opts));\n }\n\n /** Every world's current state, keyed by alias. */\n async status(): Promise<Record<string, WorldSessionState>> {\n return this.each((session) => session.status());\n }\n\n /** The manifest: where every world answers, keyed by alias. */\n async manifest(): Promise<TaskManifest> {\n const sessions = await this.each(async (session, alias) =>\n manifestSession(\n await session.surfaces(),\n {\n sessionId: session.sessionId,\n ready: session.isReady,\n state: (await session.status()).state,\n versionId: session.versionId,\n },\n this.worlds[alias]!,\n ),\n );\n return {\n taskId: this.taskId,\n taskVersion: this.taskVersion,\n name: this.name,\n instruction: this.instruction,\n sessions,\n };\n }\n\n /** Grade every world and aggregate — see `TaskGrade`. One `report` (the\n * agent's own account of the whole investigation) goes to every world's\n * judge; a world graded by assertions or python ignores it. */\n async grade(\n opts: { timeoutMs?: number; report?: string } = {},\n ): Promise<TaskGrade> {\n return aggregateTaskGrade(\n await this.each((session) => session.grade(opts)),\n );\n }\n\n /** Every world's call log, keyed by alias. */\n async export(): Promise<TaskExport> {\n return this.each((session) => session.export());\n }\n\n /** Close every world. Closes are attempted for all of them even when one\n * fails; the error then names every world that did not close. */\n async close(\n opts: { keepWarm?: boolean } = {},\n ): Promise<Record<string, { state: string }>> {\n const settled = await Promise.allSettled(\n Object.entries(this.sessions).map(\n async ([alias, session]) => [alias, await session.close(opts)] as const,\n ),\n );\n const failed: string[] = [];\n const closed: Record<string, { state: string }> = {};\n settled.forEach((result, i) => {\n const alias = this.aliases[i]!;\n if (result.status === \"fulfilled\") closed[alias] = result.value[1];\n else\n failed.push(\n `${alias}: ${result.reason instanceof Error ? result.reason.message : String(result.reason)}`,\n );\n });\n if (failed.length > 0)\n throw new Error(\n `${failed.length} of ${this.aliases.length} worlds did not close — ${failed.join(\"; \")}`,\n );\n return closed;\n }\n}\n\nexport type OpenTaskOptions = {\n /** With a task id: open that version of the task instead of the current. */\n version?: number;\n /** Asked of every world; the platform refuses (400) rather than serving\n * fewer surfaces than asked, and then nothing is up. */\n surfaces?: WorldSurfaceKind[];\n reuseWarm?: boolean;\n options?: WorldsClientOptions;\n};\n\nfunction fromResponse(\n answer: TaskSessionsResponse,\n options: WorldsClientOptions,\n): TaskSessions {\n const sessions: Record<string, WorldSession> = {};\n const worlds: Record<string, { slug: string; ref: string | null }> = {};\n for (const [alias, state] of Object.entries(answer.sessions)) {\n sessions[alias] = new WorldSession(state.sessionId, state, options);\n worlds[alias] = { slug: state.slug, ref: state.ref };\n }\n return new TaskSessions(\n answer.taskId,\n answer.taskVersion,\n answer.name,\n answer.instruction,\n sessions,\n worlds,\n answer.hash ?? null,\n );\n}\n\n/**\n * Bring every world of a task up. `ref` is a stored task's id, its\n * `{ id, version? }`, or the spec itself (one with `worlds`). Returns as\n * soon as the platform has opened every session — `ready()` waits for the\n * containers. All or nothing: a world that fails to open closes the rest\n * and the error names it.\n */\nexport async function openTask(\n ref: string | WorldTaskIdRef | WorldTaskSpec,\n opts: OpenTaskOptions = {},\n): Promise<TaskSessions> {\n const options = opts.options ?? {};\n const task: WorldTaskIdRef | WorldTaskSpec =\n typeof ref === \"string\"\n ? {\n id: ref,\n ...(opts.version !== undefined ? { version: opts.version } : {}),\n }\n : isTaskIdRef(ref) && opts.version !== undefined\n ? { ...ref, version: opts.version }\n : ref;\n if (isTaskIdRef(task) ? !task.id : !task.instruction)\n throw new Error(\n \"openTask needs a task: a stored task id, { id, version? } or a spec with worlds\",\n );\n if (!isTaskIdRef(task) && !task.worlds)\n throw new Error(\n \"openTask needs a spec that names its worlds; a single-world spec opens with openSession\",\n );\n const answer = await apiRequest<TaskSessionsResponse>(\n options,\n \"POST\",\n TASK_SESSIONS,\n {\n task,\n ...(opts.reuseWarm === undefined ? {} : { reuseWarm: opts.reuseWarm }),\n ...(opts.surfaces?.length ? { surfaces: opts.surfaces } : {}),\n },\n );\n return fromResponse(answer, options);\n}\n\n/** A stored task's live sessions, newest first — every session the project\n * has opened on it that is not stopped or failed. */\nexport async function listTaskSessions(\n taskId: string,\n options: WorldsClientOptions = {},\n): Promise<LiveTaskSession[]> {\n const answer = await apiRequest<{\n taskId: string;\n sessions: LiveTaskSession[];\n }>(options, \"GET\", `${TASK_SESSIONS}?taskId=${encodeURIComponent(taskId)}`);\n return answer.sessions;\n}\n\n/**\n * Attach to the sessions a stored task has up — after a crash, or from a\n * process other than the one that ran `up`. Refuses when an alias is live\n * more than once (two `up`s of the same task): which set is meant is not\n * knowable, so pass the manifest (`attachManifest`) or close the extras.\n */\nexport async function attachTask(\n taskId: string,\n options: WorldsClientOptions = {},\n): Promise<TaskSessions> {\n const live = await listTaskSessions(taskId, options);\n if (live.length === 0)\n throw new Error(\n `task ${taskId} has no live sessions; run \\`task up\\` first`,\n );\n const byAlias = new Map<string, LiveTaskSession[]>();\n for (const session of live) {\n const alias = session.alias ?? session.sessionId;\n byAlias.set(alias, [...(byAlias.get(alias) ?? []), session]);\n }\n const doubled = [...byAlias.entries()].filter(([, rows]) => rows.length > 1);\n if (doubled.length > 0)\n throw new Error(\n `task ${taskId} has more than one live session for ${doubled\n .map(\n ([alias, rows]) =>\n `'${alias}' (${rows.map((r) => r.sessionId).join(\", \")})`,\n )\n .join(\", \")}; pass the manifest from \\`task up\\`, or close the extras`,\n );\n return attachManifest(\n {\n taskId,\n taskVersion: live[0]!.taskVersion,\n name: null,\n instruction: null,\n sessions: Object.fromEntries(\n [...byAlias.entries()].map(([alias, [row]]) => [\n alias,\n {\n slug: row!.slug ?? \"\",\n ref: null,\n versionId: row!.versionId,\n sessionId: row!.sessionId,\n ready: row!.ready,\n state: row!.state,\n surfaces: [\"tools\"] as WorldSurfaceKind[],\n },\n ]),\n ),\n },\n options,\n );\n}\n\n/** Attach to the sessions a manifest names — the file `task up --out`\n * wrote. Each session is read back from the platform, so a closed one is a\n * clear error rather than a stale handle. */\nexport async function attachManifest(\n manifest: TaskManifest,\n options: WorldsClientOptions = {},\n): Promise<TaskSessions> {\n const entries = await Promise.all(\n Object.entries(manifest.sessions).map(\n async ([alias, entry]) =>\n [alias, await attachSession(entry.sessionId, options)] as const,\n ),\n );\n const sessions = Object.fromEntries(entries);\n const instruction =\n manifest.instruction ?? entries[0]?.[1].instruction ?? null;\n return new TaskSessions(\n manifest.taskId,\n manifest.taskVersion,\n manifest.name,\n instruction,\n sessions,\n Object.fromEntries(\n Object.entries(manifest.sessions).map(([alias, entry]) => [\n alias,\n { slug: entry.slug, ref: entry.ref },\n ]),\n ),\n );\n}\n\n/** Whether a parsed JSON value is a task manifest (what `task up` wrote)\n * rather than a task spec. */\nexport function isTaskManifest(value: unknown): value is TaskManifest {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n typeof (value as { sessions?: unknown }).sessions === \"object\" &&\n (value as { sessions?: unknown }).sessions !== null &&\n !(\"instruction\" in value && \"worlds\" in value)\n );\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\n\n/**\n * Create/push/finalize evaluations against the platform — the TS twin of\n * the Python SDK's `GatewayEvalsClient` (gatewaysdk/benchmark_hub/evals.py):\n * create_evaluation -> push_samples -> finalize_evaluation, anchored to an\n * immutable container version so scores stay reproducible across re-pushes.\n *\n * Used by `runTask` (worlds/taskRun.ts) to file a task run's rollout; kept\n * minimal on purpose — no batching, no rollout-session emission — since\n * that is all a task run needs today. Basic auth from the same\n * `WorldsClientOptions` the rest of the worlds client takes.\n */\n\nconst EVALUATIONS = \"/api/public/benchmark-containers/evaluations\";\n\n/** One rollout, in the platform's sample shape. */\nexport type EvalSample = {\n exampleId: string;\n task?: string;\n rolloutIndex?: number;\n prompt?: unknown;\n completion?: unknown;\n reward?: number;\n score?: number;\n correct?: boolean;\n rewards?: Record<string, number>;\n info?: Record<string, unknown>;\n};\n\nexport type CreateEvaluationOptions = {\n model?: string;\n rolloutsPerExample?: number;\n metadata?: Record<string, unknown>;\n};\n\nexport type FinalizeEvaluationOptions = {\n status?: \"COMPLETED\" | \"FAILED\";\n metrics?: Record<string, unknown>;\n};\n\nexport class GatewayEvalsClient {\n constructor(private readonly options: WorldsClientOptions = {}) {}\n\n /** Anchor a new evaluation to `versionId`; returns its id. */\n async createEvaluation(\n versionId: string,\n opts: CreateEvaluationOptions = {},\n ): Promise<string> {\n const body: Record<string, unknown> = { versionId };\n if (opts.model !== undefined) body.model = opts.model;\n if (opts.rolloutsPerExample !== undefined)\n body.rolloutsPerExample = opts.rolloutsPerExample;\n if (opts.metadata !== undefined) body.metadata = opts.metadata;\n const answer = await apiRequest<{ evaluationId: string }>(\n this.options,\n \"POST\",\n EVALUATIONS,\n body,\n );\n return answer.evaluationId;\n }\n\n /** Push one batch of samples; returns how many the platform inserted. */\n async pushSamples(\n evaluationId: string,\n samples: EvalSample[],\n ): Promise<number> {\n const answer = await apiRequest<{ inserted?: number }>(\n this.options,\n \"POST\",\n `${EVALUATIONS}/${encodeURIComponent(evaluationId)}/samples`,\n { samples },\n );\n return answer.inserted ?? samples.length;\n }\n\n /** Close the evaluation out; returns its final status. */\n async finalizeEvaluation(\n evaluationId: string,\n opts: FinalizeEvaluationOptions = {},\n ): Promise<string> {\n const body: Record<string, unknown> = {\n status: opts.status ?? \"COMPLETED\",\n };\n if (opts.metrics !== undefined) body.metrics = opts.metrics;\n const answer = await apiRequest<{ status: string }>(\n this.options,\n \"POST\",\n `${EVALUATIONS}/${encodeURIComponent(evaluationId)}/finalize`,\n body,\n );\n return answer.status;\n }\n}\n","/**\n * End-user profiles — attribute usage and ROI to the real people behind\n * your agent's traffic.\n *\n * Profiles pair with the platform's per-user usage metrics (traces, tokens,\n * lifetime cost) on the Users page. Attributes merge by default, so pushing\n * an incremental ROI fact is one call:\n *\n * ```typescript\n * import { UsersClient } from \"@withgateway/sdk/users\";\n *\n * const users = UsersClient.fromEnv();\n * await users.update(\"user-123\", {\n * displayName: \"Acme Corp — Jane D.\",\n * attributes: { plan: \"enterprise\", account_value: \"48000\" },\n * });\n * ```\n *\n * Tip: `identify(\"user-123\", { attributes: {...} })` does this in the\n * background AND attributes the current trace/session to the user.\n *\n * Mirrors the Python SDK's `gatewaysdk.users` module.\n */\n\ntype UserProfile = {\n userId: string;\n displayName: string | null;\n email: string | null;\n attributes: Record<string, string>;\n notes: string | null;\n};\n\ntype UserProfileUpdate = {\n displayName?: string;\n email?: string;\n attributes?: Record<string, string>;\n notes?: string;\n /**\n * Attributes merge with the stored set by default. Set `merge: false`\n * to replace the stored attributes wholesale.\n */\n merge?: boolean;\n};\n\ntype UserEvent = {\n id: string;\n userId: string;\n event: string;\n /** Emitter-defined value (e.g. minutes saved, revenue). Summed at rollup. */\n value: number | null;\n metadata: Record<string, unknown>;\n traceId: string | null;\n sessionId: string | null;\n createdAt: Date;\n};\n\ntype UserEventOptions = {\n /** Worth of the event in your terms (minutes saved, revenue…). */\n value?: number;\n metadata?: Record<string, unknown>;\n /** Link to the trace that produced the event. */\n traceId?: string;\n /** Link to the session that produced the event. */\n sessionId?: string;\n};\n\ntype UsersClientConfig = {\n host: string;\n publicKey: string;\n secretKey: string;\n timeoutSeconds?: number;\n debug?: boolean;\n};\n\ntype UsersClientFromEnvConfig = Partial<UsersClientConfig>;\n\n/** Raised when the Gateway user-profiles API cannot complete a request. */\nexport class UserProfileError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message);\n this.name = \"UserProfileError\";\n this.cause = options?.cause;\n }\n}\n\n/** Client for Gateway's end-user profile endpoints (Basic project keys). */\nexport class UsersClient {\n private readonly host: string;\n private readonly publicKey: string;\n private readonly secretKey: string;\n private readonly timeoutSeconds: number;\n private readonly debug: boolean;\n\n constructor(config: UsersClientConfig) {\n this.host = config.host.replace(/\\/$/, \"\");\n this.publicKey = config.publicKey;\n this.secretKey = config.secretKey;\n this.timeoutSeconds = config.timeoutSeconds ?? 15;\n this.debug = config.debug ?? false;\n }\n\n /** Create a client from GATEWAY_HOST / GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY. */\n static fromEnv(config: UsersClientFromEnvConfig = {}) {\n const host = config.host ?? process.env.GATEWAY_HOST;\n const publicKey = config.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;\n const secretKey = config.secretKey ?? process.env.GATEWAY_SECRET_KEY;\n\n const missing = [\n [\"host\", host],\n [\"publicKey\", publicKey],\n [\"secretKey\", secretKey],\n ]\n .filter(([, value]) => !value)\n .map(([name]) => name);\n\n if (missing.length > 0) {\n throw new UserProfileError(\n `Missing Gateway user-profile configuration: ${missing.join(\", \")}`,\n );\n }\n\n return new UsersClient({\n ...config,\n host: host!,\n publicKey: publicKey!,\n secretKey: secretKey!,\n });\n }\n\n /** Fetch a user's stored profile. */\n async get(userId: string): Promise<UserProfile> {\n return parseProfile(\n await this.requestJson(\n \"GET\",\n `/api/public/user-profiles/${encodeURIComponent(userId)}`,\n ),\n );\n }\n\n /**\n * Upsert a user's profile. `attributes` merge with the stored set unless\n * `merge: false` (which replaces it).\n */\n async update(\n userId: string,\n update: UserProfileUpdate = {},\n ): Promise<UserProfile> {\n const body: Record<string, unknown> = {\n userId,\n attributes: update.attributes ?? {},\n mergeAttributes: update.merge ?? true,\n ...(update.displayName !== undefined\n ? { displayName: update.displayName }\n : {}),\n ...(update.email !== undefined ? { email: update.email } : {}),\n ...(update.notes !== undefined ? { notes: update.notes } : {}),\n };\n return parseProfile(\n await this.requestJson(\"POST\", \"/api/public/user-profiles\", body),\n );\n }\n\n /**\n * Record a VALUE EVENT for a user — the per-user ROI stream. `value` is\n * whatever the event is worth in your terms (minutes saved, revenue…);\n * Gateway sums it in the hours-saved/ROI rollups, and evals and task-set\n * replays can assert against the events. Link `traceId`/`sessionId` to tie\n * the event to the run that produced it.\n *\n * @example\n * ```ts\n * await client.trackEvent(\"user-123\", \"checkout_completed\", {\n * value: 25,\n * metadata: { cartSize: 3 },\n * sessionId,\n * });\n * ```\n */\n async trackEvent(\n userId: string,\n event: string,\n options: UserEventOptions = {},\n ): Promise<UserEvent> {\n const body: Record<string, unknown> = {\n userId,\n event,\n metadata: options.metadata ?? {},\n ...(options.value !== undefined ? { value: options.value } : {}),\n ...(options.traceId !== undefined ? { traceId: options.traceId } : {}),\n ...(options.sessionId !== undefined\n ? { sessionId: options.sessionId }\n : {}),\n };\n return parseEvent(\n await this.requestJson(\"POST\", \"/api/public/user-events\", body),\n );\n }\n\n /** List a project's user events, optionally filtered by user/event/time. */\n async listEvents(\n filter: {\n userId?: string;\n event?: string;\n fromTimestamp?: Date;\n toTimestamp?: Date;\n page?: number;\n limit?: number;\n } = {},\n ): Promise<{ data: UserEvent[]; totalItems: number }> {\n const params = new URLSearchParams();\n if (filter.userId) params.set(\"userId\", filter.userId);\n if (filter.event) params.set(\"event\", filter.event);\n if (filter.fromTimestamp)\n params.set(\"fromTimestamp\", filter.fromTimestamp.toISOString());\n if (filter.toTimestamp)\n params.set(\"toTimestamp\", filter.toTimestamp.toISOString());\n if (filter.page) params.set(\"page\", String(filter.page));\n if (filter.limit) params.set(\"limit\", String(filter.limit));\n const qs = params.toString();\n const payload = await this.requestJson(\n \"GET\",\n `/api/public/user-events${qs ? `?${qs}` : \"\"}`,\n );\n const rows = Array.isArray(payload.data) ? payload.data : [];\n const meta =\n payload.meta && typeof payload.meta === \"object\"\n ? (payload.meta as Record<string, unknown>)\n : {};\n return {\n data: rows.map((row) => parseEvent(row as Record<string, unknown>)),\n totalItems: Number(meta.totalItems ?? rows.length),\n };\n }\n\n private async requestJson(\n method: \"GET\" | \"POST\",\n path: string,\n payload?: Record<string, unknown>,\n ): Promise<Record<string, unknown>> {\n let response: Response;\n try {\n response = await fetch(`${this.host}${path}`, {\n method,\n headers: {\n Authorization: this.authHeader(),\n \"Content-Type\": \"application/json\",\n },\n ...(payload ? { body: JSON.stringify(payload) } : {}),\n signal: AbortSignal.timeout(this.timeoutSeconds * 1000),\n });\n } catch (error) {\n throw new UserProfileError(\n `${method} ${path} failed: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n\n const text = await response.text();\n if (!response.ok) {\n throw new UserProfileError(\n `${method} ${path} failed (${response.status}): ${text.slice(0, 500)}`,\n );\n }\n\n this.log(\"%s %s -> %s\", method, path, response.status);\n return safeJson(text);\n }\n\n private authHeader() {\n return `Basic ${Buffer.from(`${this.publicKey}:${this.secretKey}`).toString(\n \"base64\",\n )}`;\n }\n\n private log(message: string, ...args: unknown[]) {\n if (this.debug) {\n console.log(`[gateway.users] ${message}`, ...args);\n }\n }\n}\n\nfunction parseEvent(payload: Record<string, unknown>): UserEvent {\n return {\n id: String(payload.id ?? \"\"),\n userId: String(payload.userId ?? \"\"),\n event: String(payload.event ?? \"\"),\n value: typeof payload.value === \"number\" ? payload.value : null,\n metadata:\n payload.metadata &&\n typeof payload.metadata === \"object\" &&\n !Array.isArray(payload.metadata)\n ? (payload.metadata as Record<string, unknown>)\n : {},\n traceId: typeof payload.traceId === \"string\" ? payload.traceId : null,\n sessionId:\n typeof payload.sessionId === \"string\" ? payload.sessionId : null,\n createdAt:\n typeof payload.createdAt === \"string\"\n ? new Date(payload.createdAt)\n : new Date(0),\n };\n}\n\nfunction parseProfile(payload: Record<string, unknown>): UserProfile {\n return {\n userId: String(payload.userId ?? \"\"),\n displayName:\n typeof payload.displayName === \"string\" ? payload.displayName : null,\n email: typeof payload.email === \"string\" ? payload.email : null,\n attributes: parseAttributes(payload.attributes),\n notes: typeof payload.notes === \"string\" ? payload.notes : null,\n };\n}\n\nfunction parseAttributes(value: unknown): Record<string, string> {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return {};\n const attributes: Record<string, string> = {};\n for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {\n attributes[key] = String(entry);\n }\n return attributes;\n}\n\nfunction safeJson(value: string): Record<string, unknown> {\n try {\n const parsed = JSON.parse(value);\n return parsed && typeof parsed === \"object\" && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : {};\n } catch {\n return {};\n }\n}\n\nexport const users = {\n fromEnv: UsersClient.fromEnv,\n};\n\nexport type {\n UserProfile,\n UserProfileUpdate,\n UserEvent,\n UserEventOptions,\n UsersClientConfig,\n UsersClientFromEnvConfig,\n};\n","/**\n * End-user identity for GatewaySDK tracing.\n *\n * Mirrors the Python SDK's `gatewaysdk.tracing.identity` user half:\n *\n * - The ambient user is set via `identify()` and stored in an\n * AsyncLocalStorage (the TS analogue of Python's ContextVar), so\n * concurrent requests serving different users never bleed into each other.\n * - `IdentitySpanProcessor` (registered by `tracing.init()`) stamps the\n * ambient user on every span at start, so everything traced after\n * `identify()` is attributed automatically — the same seam as Python's\n * `TracingContextSpanProcessor` and this SDK's `ExperimentSpanProcessor`.\n * - `identify()` also stamps the currently open span directly, because\n * ingestion treats `gateway.user.id` on ANY span as a trace-level update —\n * the in-flight trace is attributed immediately.\n */\n\nimport { AsyncLocalStorage } from \"async_hooks\";\nimport { isSpanContextValid, trace } from \"@opentelemetry/api\";\nimport type { Context } from \"@opentelemetry/api\";\nimport type {\n ReadableSpan,\n Span,\n SpanProcessor,\n} from \"@opentelemetry/sdk-trace-base\";\nimport { UsersClient } from \"../users/index\";\n\nexport const USER_ID_ATTRIBUTE = \"gateway.user.id\";\n\n// Per-async-context user identity set via identify() — AsyncLocalStorage so\n// concurrent requests serving different users never bleed into each other.\nconst currentUserStorage = new AsyncLocalStorage<string>();\n\n/**\n * The active end-user id: identify() context > GATEWAY_USER_ID env.\n *\n * Per-request user attribution (e.g. from auth middleware) can also override\n * per span by setting the `gateway.user.id` attribute directly — explicit\n * set wins over the ambient default stamped at span start.\n */\nexport function resolveUserId(): string | undefined {\n const contextual = currentUserStorage.getStore();\n if (contextual) return contextual;\n const envUser = process.env.GATEWAY_USER_ID?.trim();\n return envUser ? envUser : undefined;\n}\n\nexport interface IdentifyOptions {\n /** Profile attributes to merge into the user's stored profile. */\n attributes?: Record<string, string | number | boolean>;\n displayName?: string;\n email?: string;\n}\n\n/**\n * Attribute everything that follows (and the current trace) to a user.\n *\n * - Sets the user for all spans started in this async context, and stamps\n * the currently open span so the in-flight trace is attributed immediately.\n * - When `attributes`/`displayName`/`email` are given, the user's platform\n * profile is updated in the background (attributes merge with what's\n * stored — ideal for incremental ROI facts like plan or account_value).\n * Requires GATEWAY_HOST/GATEWAY_PUBLIC_KEY/GATEWAY_SECRET_KEY for the\n * profile update; tracing attribution works without them. Failures are\n * swallowed (debug-logged) and never produce unhandled rejections.\n *\n * @example\n * ```typescript\n * import { identify } from \"@withgateway/sdk\";\n *\n * identify(\"user-123\", {\n * attributes: { plan: \"enterprise\", account_value: \"48000\" },\n * });\n * ```\n */\nexport function identify(userId: string, options: IdentifyOptions = {}): void {\n const cleaned = userId.trim();\n if (!cleaned) return;\n\n currentUserStorage.enterWith(cleaned);\n\n // Stamp the open span so the in-flight trace is upserted with the user —\n // ingestion treats user.id on ANY span as a trace-level update.\n try {\n const span = trace.getActiveSpan();\n if (span && isSpanContextValid(span.spanContext())) {\n span.setAttribute(USER_ID_ATTRIBUTE, cleaned);\n }\n } catch (error) {\n debugLog(\"identify(): no active span to stamp\", error);\n }\n\n if (options.attributes || options.displayName || options.email) {\n void pushProfile(cleaned, options);\n }\n}\n\nasync function pushProfile(\n userId: string,\n options: IdentifyOptions,\n): Promise<void> {\n try {\n const attributes: Record<string, string> = {};\n for (const [key, value] of Object.entries(options.attributes ?? {})) {\n attributes[key] = String(value);\n }\n await UsersClient.fromEnv().update(userId, {\n ...(options.displayName !== undefined\n ? { displayName: options.displayName }\n : {}),\n ...(options.email !== undefined ? { email: options.email } : {}),\n attributes,\n });\n } catch (error) {\n debugLog(\"identify(): profile update failed\", error);\n }\n}\n\n/** Testing hook: clear the ambient user for the current async context. */\nexport function resetAmbientUser(): void {\n currentUserStorage.enterWith(undefined as unknown as string);\n}\n\n/**\n * Stamps the ambient end-user identity (identify() context or\n * GATEWAY_USER_ID env) on every span at start. Registered automatically by\n * `tracing.init()`. Explicit `setAttribute` calls after span start win over\n * this ambient default.\n */\nexport class IdentitySpanProcessor implements SpanProcessor {\n onStart(span: Span, _parentContext: Context): void {\n const userId = resolveUserId();\n if (userId) {\n span.setAttribute(USER_ID_ATTRIBUTE, userId);\n }\n }\n\n onEnd(_span: ReadableSpan): void {}\n\n async shutdown(): Promise<void> {}\n\n async forceFlush(): Promise<void> {}\n}\n\nfunction debugLog(message: string, ...args: unknown[]): void {\n if (process.env.GATEWAY_DEBUG) {\n console.debug(`[gatewaysdk.tracing] ${message}`, ...args);\n }\n}\n","/**\n * Session grouping for GatewaySDK tracing.\n *\n * Mirrors the Python SDK's `gatewaysdk.tracing.session()` context manager\n * (gatewaysdk/tracing/context.py): every trace recorded inside the block\n * carries the same session id, so auto-instrumented LLM calls and tool\n * spans are grouped into one session without threading the id through\n * application code.\n *\n * The TS tracing package has no ContextVar/context-manager mechanism of its\n * own — the identity half (`identify()` / `IdentitySpanProcessor` in\n * identity.ts) is the closest analogue, so this follows the same shape: an\n * AsyncLocalStorage the current async context reads, and a SpanProcessor\n * that stamps it onto every span at start.\n */\n\nimport { AsyncLocalStorage } from \"async_hooks\";\nimport type { Context } from \"@opentelemetry/api\";\nimport type {\n ReadableSpan,\n Span,\n SpanProcessor,\n} from \"@opentelemetry/sdk-trace-base\";\n\nexport const SESSION_ID_ATTRIBUTE = \"gateway.session.id\";\n\n// Per-async-context session id set by withSession() — AsyncLocalStorage so\n// concurrent runs (or requests) grouping different sessions never bleed\n// into each other.\nconst currentSessionStorage = new AsyncLocalStorage<string>();\n\n/** The ambient session id set by the innermost enclosing `withSession()`\n * call, or `undefined` outside one. */\nexport function getAmbientSessionId(): string | undefined {\n return currentSessionStorage.getStore();\n}\n\n/**\n * Group every trace recorded inside `fn` under one session id — the TS\n * twin of the Python SDK's `with tracing.session(session_id): ...`.\n *\n * ```typescript\n * import { withSession } from \"@withgateway/sdk/tracing\";\n *\n * await withSession(\"checkout-regression-001\", async () => {\n * await observe(\"turn-1\", async () => { ... }); // carries the session id\n * });\n * ```\n *\n * Works via AsyncLocalStorage, so it groups auto-instrumented spans too;\n * nesting is fine — the innermost session wins for the code that runs\n * inside it, the same as Python's context propagation.\n */\nexport function withSession<T>(\n sessionId: string,\n fn: () => T | Promise<T>,\n): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n currentSessionStorage.run(sessionId, () => {\n Promise.resolve().then(fn).then(resolve, reject);\n });\n });\n}\n\n/**\n * Stamps the ambient session id (set by `withSession()`) on every span at\n * start. Registered automatically by `tracing.init()`/`initIsolated()`,\n * alongside `IdentitySpanProcessor`. An explicit\n * `setAttribute(SESSION_ID_ATTRIBUTE, ...)` call after span start wins over\n * this ambient default — same rule as `IdentitySpanProcessor`.\n */\nexport class SessionSpanProcessor implements SpanProcessor {\n onStart(span: Span, _parentContext: Context): void {\n const sessionId = getAmbientSessionId();\n if (sessionId) {\n span.setAttribute(SESSION_ID_ATTRIBUTE, sessionId);\n }\n }\n\n onEnd(_span: ReadableSpan): void {}\n\n async shutdown(): Promise<void> {}\n\n async forceFlush(): Promise<void> {}\n}\n","/**\n * Scores & success signals — record evaluation results and ROI-shaped success\n * signals against a Gateway project.\n *\n * A **score** is any evaluation value attached to a trace or session (visible\n * on the Scores page and in trace/session detail). A **success signal** is a\n * score carrying `metadata[\"gateway.success.signal\"]`, which the platform's\n * Success Metrics feature aggregates into a metric's headline count/pass-rate\n * (the `HOOK` metric source). Emit one whenever a real unit of business value\n * happens (\"resolved a ticket\", \"ran an eval\", \"a human accepted an edit\").\n *\n * This mirrors the Python SDK's `Run.score()` / `Run.success()`\n * (`gatewaysdk/sdk/src/gatewaysdk/run.py`). The score shape — name, numeric\n * value, `gateway.success.signal` + `gateway.success.metricName` metadata, and\n * the trace/session target — is IDENTICAL so the platform aggregates signals\n * from either SDK unchanged.\n *\n * ```typescript\n * import { ScoresClient } from \"@withgateway/sdk/scores\";\n *\n * const scores = ScoresClient.fromEnv();\n * // A pass/fail signal that feeds the \"resolved_ticket\" Success Metric:\n * await scores.success(\"resolved_ticket\", true, {\n * agentId: \"support-triage\",\n * sessionId,\n * });\n * // A numeric signal:\n * await scores.success(\"handle_time_s\", 42, { agentId: \"support-triage\", sessionId });\n * ```\n *\n * Under `tracing.initIsolated(...)` the returned handle exposes a `scores`\n * client already bound to that project's keys — that is how the platform\n * self-traces its own agents into dedicated projects.\n */\n\nimport { isSpanContextValid, trace } from \"@opentelemetry/api\";\n\n/** Score value data type, matching Gateway's ingestion schema. */\nexport type ScoreDataType = \"NUMERIC\" | \"CATEGORICAL\" | \"BOOLEAN\";\n\n/** Reserved metadata keys that mark a score as an aggregatable success signal. */\nexport const SUCCESS_SIGNAL_KEY = \"gateway.success.signal\";\nexport const SUCCESS_METRIC_NAME_KEY = \"gateway.success.metricName\";\nexport const AGENT_ID_KEY = \"gateway.agent.id\";\n\nexport type ScoreOptions = {\n /**\n * Trace to link the score to. Auto-detected from the active OpenTelemetry\n * span when omitted and no `sessionId` is given (mirrors the Python SDK).\n */\n traceId?: string;\n /** Session to link the score to. Preferred target when present. */\n sessionId?: string;\n /** Dataset-run to link the score to (dataset-run scores). */\n datasetRunId?: string;\n /** Span-level score — requires `traceId`. */\n observationId?: string;\n /** \"NUMERIC\" | \"CATEGORICAL\" | \"BOOLEAN\"; inferred when omitted. */\n dataType?: ScoreDataType;\n /** Optional comment stored alongside the score. */\n comment?: string;\n /** Extra metadata merged into the score. */\n metadata?: Record<string, unknown>;\n /** Environment tag; defaults to the project's `default` environment. */\n environment?: string;\n};\n\nexport type SuccessOptions = Omit<ScoreOptions, \"dataType\"> & {\n /**\n * The agent this signal belongs to (`gateway.agent.id`). Lets the platform\n * roll the signal into that agent's Success Metric without a trace join.\n */\n agentId?: string;\n /** The Success Metric name; defaults to the signal `name`. */\n metricName?: string;\n /** Override the inferred \"BOOLEAN\"/\"NUMERIC\" data type. */\n dataType?: \"NUMERIC\" | \"BOOLEAN\";\n};\n\nexport type ScoresClientConfig = {\n host: string;\n publicKey: string;\n secretKey: string;\n timeoutSeconds?: number;\n debug?: boolean;\n};\n\nexport type ScoresClientFromEnvConfig = Partial<ScoresClientConfig>;\n\n/** Raised by the low-level {@link ScoresClient.postScore} on a failed request. */\nexport class ScoreError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message);\n this.name = \"ScoreError\";\n this.cause = options?.cause;\n }\n}\n\n/**\n * Read the current trace id (32-hex) from the active OpenTelemetry span, or\n * undefined when there is no valid active span. Mirrors the Python SDK's\n * `_get_current_trace_id`.\n */\nexport function currentTraceId(): string | undefined {\n try {\n const span = trace.getActiveSpan();\n if (!span) return undefined;\n const ctx = span.spanContext();\n if (!ctx || !isSpanContextValid(ctx)) return undefined;\n return ctx.traceId;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Client for Gateway's public scores ingestion endpoint (Basic project keys).\n * The `score`/`success` convenience methods are FAIL-SOFT — they never reject\n * into the caller, they warn and resolve — matching the Python SDK's\n * fire-and-forget scoring. The raw {@link postScore} throws on failure for\n * callers that want to handle it.\n */\nexport class ScoresClient {\n private readonly host: string;\n private readonly publicKey: string;\n private readonly secretKey: string;\n private readonly timeoutSeconds: number;\n private readonly debug: boolean;\n\n constructor(config: ScoresClientConfig) {\n this.host = config.host.replace(/\\/$/, \"\");\n this.publicKey = config.publicKey;\n this.secretKey = config.secretKey;\n this.timeoutSeconds = config.timeoutSeconds ?? 15;\n this.debug = config.debug ?? false;\n }\n\n /** Create a client from GATEWAY_HOST / GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY. */\n static fromEnv(config: ScoresClientFromEnvConfig = {}): ScoresClient {\n const host = config.host ?? process.env.GATEWAY_HOST;\n const publicKey = config.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;\n const secretKey = config.secretKey ?? process.env.GATEWAY_SECRET_KEY;\n\n const missing = [\n [\"host\", host],\n [\"publicKey\", publicKey],\n [\"secretKey\", secretKey],\n ]\n .filter(([, value]) => !value)\n .map(([name]) => name);\n\n if (missing.length > 0) {\n throw new ScoreError(\n `Missing Gateway scores configuration: ${missing.join(\", \")}`,\n );\n }\n\n return new ScoresClient({\n ...config,\n host: host!,\n publicKey: publicKey!,\n secretKey: secretKey!,\n });\n }\n\n /**\n * Post a score, throwing {@link ScoreError} on any failure. Builds the exact\n * `POST /api/public/scores` body the Python SDK sends: exactly one of\n * `sessionId` / `traceId` (+ optional `observationId`) / `datasetRunId`.\n * When no target is provided, the active OTel trace id is used; if none is\n * available the call is a no-op (returns without posting), matching Python.\n */\n async postScore(\n name: string,\n value: number | string,\n options: ScoreOptions = {},\n ): Promise<void> {\n const body = this.buildScoreBody(name, value, options);\n if (!body) {\n this.log(\n \"score '%s' dropped: no sessionId, traceId or datasetRunId available\",\n name,\n );\n return;\n }\n await this.request(\"POST\", \"/api/public/scores\", body);\n }\n\n /**\n * Build the score request body, or null when no target can be resolved.\n * Split out so it is unit-testable and shared by score()/success().\n */\n buildScoreBody(\n name: string,\n value: number | string,\n options: ScoreOptions = {},\n ): Record<string, unknown> | null {\n // Prefer sessionId (scores typically grade a whole session/rollout), then\n // datasetRunId, then an explicit traceId, then the ambient OTel trace.\n const traceId = options.traceId ?? currentTraceId();\n const target: Record<string, unknown> = {};\n if (options.sessionId) {\n target.sessionId = options.sessionId;\n } else if (options.datasetRunId) {\n target.datasetRunId = options.datasetRunId;\n } else if (traceId) {\n target.traceId = traceId;\n if (options.observationId) target.observationId = options.observationId;\n } else {\n return null;\n }\n\n // Base metadata mirrors the Python SDK (source tag), then the caller's\n // metadata is merged on top — identical to `score_metadata.update(...)`.\n const metadata: Record<string, unknown> = {\n source: \"gatewaysdk\",\n ...(options.metadata ?? {}),\n };\n\n return {\n name,\n value,\n dataType: options.dataType ?? \"NUMERIC\",\n environment: options.environment ?? \"default\",\n ...(options.comment ? { comment: options.comment } : {}),\n metadata,\n ...target,\n };\n }\n\n /**\n * Post a score, FAIL-SOFT: warns and resolves on any failure so a broken\n * transport never throws into (or rejects out of) the caller.\n */\n async score(\n name: string,\n value: number | string,\n options: ScoreOptions = {},\n ): Promise<void> {\n try {\n await this.postScore(name, value, options);\n } catch (error) {\n this.warn(`score '${name}' failed`, error);\n }\n }\n\n /**\n * Emit a SUCCESS SIGNAL that feeds a Gateway Success Metric — a score tagged\n * with `gateway.success.signal` + `gateway.success.metricName` (and the agent\n * identity when `agentId` is set). A boolean `value` records a 1/0 BOOLEAN\n * score (pass/fail); a number records a NUMERIC score. FAIL-SOFT.\n *\n * The metadata shape matches the Python SDK's `Run.success()` exactly, so the\n * platform's Success Metrics aggregation counts signals from either SDK\n * without change.\n *\n * @example\n * ```ts\n * await scores.success(\"resolved_ticket\", true, { agentId: \"support-triage\", sessionId });\n * await scores.success(\"handle_time_s\", 42, { agentId: \"support-triage\", sessionId });\n * ```\n */\n async success(\n name: string,\n value: boolean | number = true,\n options: SuccessOptions = {},\n ): Promise<void> {\n const { numericValue, inferredType } = coerceSignalValue(value);\n const { agentId, metricName, metadata, dataType, ...rest } = options;\n\n // Required signal keys are written LAST so a caller's `metadata` cannot\n // accidentally clobber them and silently drop the signal from aggregation.\n const signalMetadata: Record<string, unknown> = {\n ...(metadata ?? {}),\n [SUCCESS_SIGNAL_KEY]: true,\n [SUCCESS_METRIC_NAME_KEY]: metricName ?? name,\n ...(agentId ? { [AGENT_ID_KEY]: agentId } : {}),\n };\n\n await this.score(name, numericValue, {\n ...rest,\n dataType: dataType ?? inferredType,\n metadata: signalMetadata,\n });\n }\n\n private async request(\n method: \"POST\",\n path: string,\n payload: Record<string, unknown>,\n ): Promise<void> {\n let response: Response;\n try {\n response = await fetch(`${this.host}${path}`, {\n method,\n headers: {\n Authorization: this.authHeader(),\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(payload),\n signal: AbortSignal.timeout(this.timeoutSeconds * 1000),\n });\n } catch (error) {\n throw new ScoreError(\n `${method} ${path} failed: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n\n const text = await response.text();\n if (!response.ok) {\n throw new ScoreError(\n `${method} ${path} failed (${response.status}): ${text.slice(0, 500)}`,\n );\n }\n this.log(\"%s %s -> %s\", method, path, response.status);\n }\n\n private authHeader(): string {\n return `Basic ${Buffer.from(`${this.publicKey}:${this.secretKey}`).toString(\n \"base64\",\n )}`;\n }\n\n private log(message: string, ...args: unknown[]): void {\n if (this.debug) {\n console.log(`[gateway.scores] ${message}`, ...args);\n }\n }\n\n private warn(message: string, ...args: unknown[]): void {\n console.warn(`[gateway.scores] ${message}`, ...args);\n }\n}\n\n/** Map a success value to its numeric score + inferred data type. */\nfunction coerceSignalValue(value: boolean | number): {\n numericValue: number;\n inferredType: \"NUMERIC\" | \"BOOLEAN\";\n} {\n if (typeof value === \"boolean\") {\n return { numericValue: value ? 1 : 0, inferredType: \"BOOLEAN\" };\n }\n return { numericValue: value, inferredType: \"NUMERIC\" };\n}\n\n/**\n * Emit a success signal using credentials from the environment\n * (GATEWAY_HOST / GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY) — the ergonomic\n * top-level entry point for the default `tracing.init()` path, mirroring the\n * Python SDK's `run.success(...)`. FAIL-SOFT end to end: a missing/invalid\n * environment or a transport failure warns and resolves, never throwing into\n * the caller. For isolated providers use the handle's bound client\n * (`handle.scores.success(...)`) instead so the signal lands in that project.\n */\nexport async function success(\n name: string,\n value: boolean | number = true,\n options: SuccessOptions = {},\n): Promise<void> {\n let client: ScoresClient;\n try {\n client = ScoresClient.fromEnv();\n } catch (error) {\n console.warn(`[gateway.scores] success '${name}' skipped`, error);\n return;\n }\n await client.success(name, value, options);\n}\n\n/** Lowercase convenience namespace, matching the `users` export. */\nexport const scores = {\n fromEnv: ScoresClient.fromEnv,\n success,\n};\n","{\n \"name\": \"@withgateway/sdk\",\n \"version\": \"0.2.4\",\n \"description\": \"Gateway SDK for TypeScript - A/B experiments, tracing, and observability\",\n \"main\": \"./dist/index.js\",\n \"module\": \"./dist/index.mjs\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.mjs\",\n \"require\": \"./dist/index.js\"\n },\n \"./experiments\": {\n \"types\": \"./dist/experiments/index.d.ts\",\n \"import\": \"./dist/experiments/index.mjs\",\n \"require\": \"./dist/experiments/index.js\"\n },\n \"./context\": {\n \"types\": \"./dist/context/index.d.ts\",\n \"import\": \"./dist/context/index.mjs\",\n \"require\": \"./dist/context/index.js\"\n },\n \"./memory\": {\n \"types\": \"./dist/memory/index.d.ts\",\n \"import\": \"./dist/memory/index.mjs\",\n \"require\": \"./dist/memory/index.js\"\n },\n \"./personas\": {\n \"types\": \"./dist/personas/index.d.ts\",\n \"import\": \"./dist/personas/index.mjs\",\n \"require\": \"./dist/personas/index.js\"\n },\n \"./replay\": {\n \"types\": \"./dist/replay/index.d.ts\",\n \"import\": \"./dist/replay/index.mjs\",\n \"require\": \"./dist/replay/index.js\"\n },\n \"./sessions\": {\n \"types\": \"./dist/sessions/index.d.ts\",\n \"import\": \"./dist/sessions/index.mjs\",\n \"require\": \"./dist/sessions/index.js\"\n },\n \"./tracing\": {\n \"types\": \"./dist/tracing/index.d.ts\",\n \"import\": \"./dist/tracing/index.mjs\",\n \"require\": \"./dist/tracing/index.js\"\n },\n \"./security\": {\n \"types\": \"./dist/security/index.d.ts\",\n \"import\": \"./dist/security/index.mjs\",\n \"require\": \"./dist/security/index.js\"\n },\n \"./users\": {\n \"types\": \"./dist/users/index.d.ts\",\n \"import\": \"./dist/users/index.mjs\",\n \"require\": \"./dist/users/index.js\"\n },\n \"./scores\": {\n \"types\": \"./dist/scores/index.d.ts\",\n \"import\": \"./dist/scores/index.mjs\",\n \"require\": \"./dist/scores/index.js\"\n },\n \"./worlds\": {\n \"types\": \"./dist/worlds/index.d.ts\",\n \"import\": \"./dist/worlds/index.mjs\",\n \"require\": \"./dist/worlds/index.js\"\n },\n \"./files\": {\n \"types\": \"./dist/files/index.d.ts\",\n \"import\": \"./dist/files/index.mjs\",\n \"require\": \"./dist/files/index.js\"\n },\n \"./traces\": {\n \"types\": \"./dist/traces/index.d.ts\",\n \"import\": \"./dist/traces/index.mjs\",\n \"require\": \"./dist/traces/index.js\"\n },\n \"./hooks\": {\n \"types\": \"./dist/hooks/index.d.ts\",\n \"import\": \"./dist/hooks/index.mjs\",\n \"require\": \"./dist/hooks/index.js\"\n },\n \"./cli\": {\n \"types\": \"./dist/cli.d.ts\",\n \"import\": \"./dist/cli.mjs\",\n \"require\": \"./dist/cli.js\"\n }\n },\n \"files\": [\n \"dist\",\n \"skills\",\n \"runtime\",\n \"README.md\"\n ],\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"scripts\": {\n \"prebuild\": \"node scripts/copy-skills.mjs && node scripts/copy-runtime.mjs\",\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"typecheck\": \"tsc --noEmit\",\n \"typecheck:examples\": \"tsc -p tsconfig.examples.json --noEmit\",\n \"test\": \"vitest\",\n \"test:run\": \"vitest run\",\n \"lint\": \"eslint src --ext .ts\",\n \"clean\": \"rm -rf dist\",\n \"example\": \"tsx examples/test-ab-experiment.ts\",\n \"test:crm\": \"tsx examples/test-crm-ab-experiment.ts\",\n \"test:crm:balanced\": \"tsx examples/test-crm-ab-experiment.ts --balanced\",\n \"test:crm:full\": \"tsx examples/test-crm-ab-experiment.ts --users 12 --all-tasks --concurrency 3\"\n },\n \"keywords\": [\n \"gateway\",\n \"ab-testing\",\n \"experiments\",\n \"opentelemetry\",\n \"tracing\",\n \"observability\",\n \"llm\"\n ],\n \"author\": \"Gateway Team\",\n \"license\": \"MIT\",\n \"engines\": {\n \"node\": \">=18.0.0\"\n },\n \"peerDependencies\": {\n \"@opentelemetry/api\": \"^1.0.0\",\n \"@opentelemetry/exporter-trace-otlp-http\": \">=0.50.0\",\n \"@opentelemetry/resources\": \">=1.0.0\",\n \"@opentelemetry/sdk-trace-base\": \">=1.0.0\",\n \"@opentelemetry/sdk-trace-node\": \">=1.0.0\",\n \"playwright\": \">=1.40.0\"\n },\n \"peerDependenciesMeta\": {\n \"@opentelemetry/api\": {\n \"optional\": true\n },\n \"@opentelemetry/sdk-trace-base\": {\n \"optional\": true\n },\n \"@opentelemetry/sdk-trace-node\": {\n \"optional\": true\n },\n \"@opentelemetry/exporter-trace-otlp-http\": {\n \"optional\": true\n },\n \"@opentelemetry/resources\": {\n \"optional\": true\n },\n \"playwright\": {\n \"optional\": true\n }\n },\n \"optionalDependencies\": {\n \"@arizeai/openinference-instrumentation-anthropic\": \"^0.1.15\",\n \"@arizeai/openinference-instrumentation-openai\": \"^4.1.5\"\n },\n \"devDependencies\": {\n \"@anthropic-ai/sdk\": \"^0.79.0\",\n \"@opentelemetry/api\": \"^1.9.0\",\n \"@opentelemetry/exporter-trace-otlp-http\": \"^0.212.0\",\n \"@opentelemetry/resources\": \"^2.6.0\",\n \"@opentelemetry/sdk-trace-base\": \"^1.30.1\",\n \"@opentelemetry/sdk-trace-node\": \"^2.6.0\",\n \"@opentelemetry/semantic-conventions\": \"^1.40.0\",\n \"@types/node\": \"^20.0.0\",\n \"openai\": \"^4.70.0\",\n \"tsup\": \"^8.0.0\",\n \"tsx\": \"^4.0.0\",\n \"typescript\": \"^5.0.0\",\n \"vitest\": \"^3.2.6\"\n },\n \"overrides\": {\n \"protobufjs\": \"^8.4.1\",\n \"vite@6\": \"^6.4.3\",\n \"postcss\": \"^8.5.18\",\n \"picomatch@4\": \"^4.0.4\"\n },\n \"pnpm\": {\n \"overrides\": {\n \"protobufjs\": \"^8.4.1\",\n \"vitest\": \"^3.2.6\",\n \"vite@6\": \"^6.4.3\",\n \"postcss\": \"^8.5.18\",\n \"picomatch@4\": \"^4.0.4\"\n }\n },\n \"bin\": {\n \"gateway\": \"./dist/cli.js\"\n }\n}\n","/**\n * Agent build identity — \"the agent IS the manifest.\"\n *\n * There is no build file and no lockfile. As the agent constructs itself,\n * the SDK observes everything that defines a build: tools registered through\n * defineTool() (name, declared version, schema hash, effects, source\n * location), prompts registered through registerPrompt(), the code ref from\n * CI/env, and the SDK's own version. tracing.init({ agent, version })\n * assembles the canonical manifest, computes the content-addressed\n * buildHash, stamps it on every span, and auto-registers the build with\n * Gateway (idempotent on hash — every replica of the same code is one\n * build). Releases are label moves on the platform, never mutations here.\n *\n * v1 versioning is developer-declared: you bump `version` on the agent and\n * on tools; Gateway records schema/impl hashes as evidence alongside.\n */\nimport { createHash } from \"node:crypto\";\n\nexport type ToolEffects = \"read\" | \"write\" | \"irreversible\";\n\nexport interface ToolIdentity {\n name: string;\n version?: string;\n effects?: ToolEffects;\n schemaHash: string;\n description?: string;\n /** Source location of the defineTool call (\"src/tools/checkout.ts:42\"). */\n source?: string;\n}\n\n/** Any versioned artifact an agent is built from — tools, prompts, skills,\n * datasets, guardrails, configs… `content` hashes locally (off-platform);\n * `ref` pins a platform-hosted artifact (\"prompt/system@label:production\"). */\nexport interface ArtifactIdentity {\n kind: string;\n name: string;\n version?: string;\n contentHash?: string;\n ref?: string;\n source?: string;\n metadata?: Record<string, string>;\n}\n\nexport interface AgentBuildManifest {\n agentId: string;\n codeRef?: string;\n sdk: string;\n tools: ToolIdentity[];\n prompts: Record<string, string>;\n skills: Record<string, string>;\n artifacts: ArtifactIdentity[];\n}\n\n/** Deterministic JSON: object keys sorted recursively, arrays kept in order. */\nexport function canonicalJson(value: unknown): string {\n if (value === null || typeof value !== \"object\") {\n return JSON.stringify(value);\n }\n if (Array.isArray(value)) {\n return `[${value.map(canonicalJson).join(\",\")}]`;\n }\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n return `{${entries\n .map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`)\n .join(\",\")}}`;\n}\n\nexport function sha256(text: string): string {\n return `sha256:${createHash(\"sha256\").update(text).digest(\"hex\")}`;\n}\n\n// ── Registry (module-level; one agent process = one registry) ──────────────\n\nconst registeredTools = new Map<string, ToolIdentity>();\nconst registeredPrompts = new Map<string, string>();\nconst registeredSkills = new Map<string, string>();\nconst registeredArtifacts = new Map<string, ArtifactIdentity>();\n\n/** First app-code frame of the current stack (\"src/tools/checkout.ts:42\"). */\nfunction captureSource(): string | undefined {\n const stack = new Error().stack?.split(\"\\n\") ?? [];\n for (const line of stack.slice(1)) {\n // Skip the SDK's own frames (this module, packaged dist) and node internals\n // — NOT the whole install dir, or apps developed inside a monorepo next to\n // the SDK would never resolve a source.\n if (\n line.includes(\"build/index.ts\") ||\n line.includes(\"build/index.js\") ||\n line.includes(\"build/index.mjs\") ||\n line.includes(\"node_modules/@withgateway/\")\n ) {\n continue;\n }\n if (line.includes(\"node:internal\") || line.includes(\"(node:\")) continue;\n const match = /\\(?([^()\\s]+):(\\d+):\\d+\\)?$/.exec(line.trim());\n if (match) {\n const file = match[1].replace(/^file:\\/\\//, \"\");\n // Trim to a repo-relative-ish path for readability.\n const short = file.includes(\"/\") ? file.split(\"/\").slice(-4).join(\"/\") : file;\n return `${short}:${match[2]}`;\n }\n }\n return undefined;\n}\n\nexport interface DefineToolInput {\n name: string;\n /** Developer-declared tool version, e.g. \"2.1\" (v1: bumped manually). */\n version?: string;\n /** Side-effect class — feeds approval policies and gate severity. */\n effects?: ToolEffects;\n description?: string;\n /** JSON schema (or zod-serializable shape) of the tool's parameters. */\n schema?: unknown;\n /** Alias accepted for frameworks that call it inputSchema. */\n inputSchema?: unknown;\n}\n\n/**\n * Register a tool's identity and pass the definition through unchanged, so\n * it wraps ANY framework's tool shape:\n *\n * ```ts\n * const checkout = defineTool({\n * name: \"checkout\", version: \"2.1\", effects: \"write\",\n * schema, description, execute,\n * });\n * ```\n */\nexport function defineTool<T extends DefineToolInput>(tool: T): T {\n const schemaBasis = tool.schema ?? tool.inputSchema ?? null;\n const source = captureSource();\n const identity: ToolIdentity = {\n name: tool.name,\n ...(tool.version !== undefined ? { version: tool.version } : {}),\n ...(tool.effects !== undefined ? { effects: tool.effects } : {}),\n ...(tool.description !== undefined\n ? { description: tool.description.slice(0, 500) }\n : {}),\n schemaHash: sha256(\n canonicalJson({ schema: schemaBasis, description: tool.description ?? \"\" }),\n ),\n ...(source ? { source } : {}),\n };\n registeredTools.set(tool.name, identity);\n notifyRegistryChanged();\n return tool;\n}\n\n/**\n * Register a code-shipped prompt so it joins the build identity:\n * `const SYSTEM = registerPrompt(\"system\", \"You are…\")`. Returns the content\n * unchanged. Platform-served prompts don't need this — pin them by label.\n */\nexport interface RegisterArtifactOptions {\n /** Developer-declared version, e.g. \"1.2\" (v1: bumped manually). */\n version?: string;\n /** Local content — hashed into the identity (off-platform artifacts). */\n content?: string;\n /** Platform reference (on-platform artifacts): \"prompt/system@label:production\". */\n ref?: string;\n metadata?: Record<string, string>;\n}\n\n/**\n * Version ANY artifact the agent is built from — the generic primitive\n * behind registerPrompt/registerSkill. Works on- and off-platform:\n *\n * ```ts\n * registerArtifact(\"guardrail\", \"pii-filter\", { version: \"2.0\", content: RULES });\n * registerArtifact(\"prompt\", \"planner\", { ref: \"planner@label:production\" });\n * ```\n */\nexport function registerArtifact(\n kind: string,\n name: string,\n options: RegisterArtifactOptions = {},\n): ArtifactIdentity {\n const source = captureSource();\n const identity: ArtifactIdentity = {\n kind,\n name,\n ...(options.version !== undefined ? { version: options.version } : {}),\n ...(options.content !== undefined\n ? { contentHash: sha256(options.content) }\n : {}),\n ...(options.ref !== undefined ? { ref: options.ref } : {}),\n ...(source ? { source } : {}),\n ...(options.metadata ? { metadata: options.metadata } : {}),\n };\n registeredArtifacts.set(`${kind}:${name}`, identity);\n notifyRegistryChanged();\n return identity;\n}\n\nexport function registerPrompt(\n name: string,\n content: string,\n options: { version?: string } = {},\n): string {\n registeredPrompts.set(name, sha256(content));\n registerArtifact(\"prompt\", name, { ...options, content });\n return content;\n}\n\nexport function getRegisteredTools(): ToolIdentity[] {\n return [...registeredTools.values()].sort((a, b) =>\n a.name < b.name ? -1 : a.name > b.name ? 1 : 0,\n );\n}\n\n/**\n * Register a skill's identity — `registerSkill(\"triage\", \"1.0\")` — so skills\n * are versioned in the build like tools and prompts. The version string is\n * whatever you bump (or a content hash for file-based skills).\n */\nexport function registerSkill(\n name: string,\n version: string,\n options: { content?: string; ref?: string } = {},\n): void {\n registeredSkills.set(name, version);\n registerArtifact(\"skill\", name, { version, ...options });\n}\n\nexport function getRegisteredArtifacts(): ArtifactIdentity[] {\n return [...registeredArtifacts.values()].sort((a, b) =>\n `${a.kind}:${a.name}` < `${b.kind}:${b.name}` ? -1 : 1,\n );\n}\n\nexport function getRegisteredSkills(): Record<string, string> {\n return Object.fromEntries(\n [...registeredSkills.entries()].sort(([a], [b]) =>\n a < b ? -1 : a > b ? 1 : 0,\n ),\n );\n}\n\nexport function getRegisteredPrompts(): Record<string, string> {\n return Object.fromEntries(\n [...registeredPrompts.entries()].sort(([a], [b]) =>\n a < b ? -1 : a > b ? 1 : 0,\n ),\n );\n}\n\n/** Test hook. */\nexport function resetBuildRegistry(): void {\n registeredTools.clear();\n registeredPrompts.clear();\n registeredSkills.clear();\n registeredArtifacts.clear();\n activeBuilds.length = 0;\n if (reRegisterTimer) clearTimeout(reRegisterTimer);\n reRegisterTimer = null;\n}\n\n// ── Manifest assembly + registration ───────────────────────────────────────\n\nfunction sdkVersion(): string {\n try {\n // dist/build/index.js -> ../../package.json ; src/build -> same shape.\n /* eslint-disable-next-line @typescript-eslint/no-require-imports */\n const pkg = require(\"../../package.json\") as { version?: string };\n return `@withgateway/sdk@${pkg.version ?? \"unknown\"}`;\n } catch {\n return \"@withgateway/sdk\";\n }\n}\n\n/**\n * Git context most PaaS runtimes inject automatically (Vercel, Render,\n * Railway, Netlify, Heroku). On those hosts attribution is fully\n * zero-config — no GATEWAY_* or GITHUB_* env plumbing needed. Explicit\n * env vars always win; this only fills gaps.\n */\nexport function paasGitContext(): {\n provider: string;\n sha?: string;\n repo?: string;\n branch?: string;\n login?: string;\n} | null {\n const env = process.env;\n if (env.VERCEL_GIT_COMMIT_SHA) {\n // Only surface the repo when it's GitHub-shaped — enrichment is\n // GitHub-only; a GitLab/Bitbucket repo would just 404 over there.\n const isGithub = (env.VERCEL_GIT_PROVIDER ?? \"github\") === \"github\";\n return {\n provider: \"vercel\",\n sha: env.VERCEL_GIT_COMMIT_SHA,\n repo:\n isGithub && env.VERCEL_GIT_REPO_OWNER && env.VERCEL_GIT_REPO_SLUG\n ? `${env.VERCEL_GIT_REPO_OWNER}/${env.VERCEL_GIT_REPO_SLUG}`\n : undefined,\n branch: env.VERCEL_GIT_COMMIT_REF,\n login: env.VERCEL_GIT_COMMIT_AUTHOR_LOGIN,\n };\n }\n if (env.RENDER_GIT_COMMIT) {\n return {\n provider: \"render\",\n sha: env.RENDER_GIT_COMMIT,\n repo: env.RENDER_GIT_REPO_SLUG, // already \"owner/repo\"\n branch: env.RENDER_GIT_BRANCH,\n };\n }\n if (env.RAILWAY_GIT_COMMIT_SHA) {\n return {\n provider: \"railway\",\n sha: env.RAILWAY_GIT_COMMIT_SHA,\n repo:\n env.RAILWAY_GIT_REPO_OWNER && env.RAILWAY_GIT_REPO_NAME\n ? `${env.RAILWAY_GIT_REPO_OWNER}/${env.RAILWAY_GIT_REPO_NAME}`\n : undefined,\n branch: env.RAILWAY_GIT_BRANCH,\n login: env.RAILWAY_GIT_AUTHOR,\n };\n }\n if (env.NETLIFY && env.COMMIT_REF) {\n const repoMatch = /github\\.com[/:]([^/]+\\/[^/.]+)/.exec(\n env.REPOSITORY_URL ?? \"\",\n );\n return {\n provider: \"netlify\",\n sha: env.COMMIT_REF,\n repo: repoMatch?.[1],\n branch: env.BRANCH,\n };\n }\n // Heroku (dyno metadata) and common bare conventions: sha only — the\n // platform resolves the repo server-side via the GitHub connection.\n const bareSha =\n env.HEROKU_SLUG_COMMIT ?? env.SOURCE_VERSION ?? env.GIT_COMMIT ?? env.COMMIT_SHA;\n if (bareSha) {\n return {\n provider: env.HEROKU_SLUG_COMMIT || env.SOURCE_VERSION ? \"heroku\" : \"generic\",\n sha: bareSha,\n };\n }\n return null;\n}\n\nfunction codeRef(): string | undefined {\n const paas = paasGitContext();\n const sha =\n process.env.GATEWAY_COMMIT ??\n process.env.GITHUB_SHA ??\n process.env.CI_COMMIT_SHA ?? // GitLab\n process.env.CIRCLE_SHA1 ??\n paas?.sha;\n if (!sha) return undefined;\n const repo =\n process.env.GITHUB_REPOSITORY ?? process.env.CI_PROJECT_PATH ?? paas?.repo;\n return repo ? `git:${repo}@${sha}` : `git:${sha}`;\n}\n\nexport function assembleManifest(agentId: string): AgentBuildManifest {\n return {\n agentId,\n ...(codeRef() ? { codeRef: codeRef() } : {}),\n sdk: sdkVersion(),\n tools: getRegisteredTools(),\n prompts: getRegisteredPrompts(),\n skills: getRegisteredSkills(),\n artifacts: getRegisteredArtifacts(),\n };\n}\n\nexport function computeBuildHash(manifest: AgentBuildManifest): string {\n // Source locations are display metadata, not identity — the same tool\n // declared on a different line (or after a refactor that moved it) is the\n // same tool. They stay in the manifest payload for the platform to show.\n const identity = {\n ...manifest,\n tools: manifest.tools.map(({ source: _source, ...tool }) => tool),\n artifacts: manifest.artifacts.map(\n ({ source: _source, ...artifact }) => artifact,\n ),\n };\n return sha256(canonicalJson(identity));\n}\n\nexport function attributionFromEnv(): Record<string, unknown> {\n const attribution: Record<string, unknown> = { source: \"runtime\" };\n if (process.env.GITHUB_ACTIONS) attribution.source = \"ci\";\n if (process.env.GITHUB_ACTOR) attribution.githubLogin = process.env.GITHUB_ACTOR;\n const sha = process.env.GATEWAY_COMMIT ?? process.env.GITHUB_SHA;\n if (sha) attribution.commitSha = sha;\n if (process.env.GITHUB_REPOSITORY) attribution.repo = process.env.GITHUB_REPOSITORY;\n const branch = process.env.GITHUB_HEAD_REF ?? process.env.GITHUB_REF_NAME;\n if (branch) attribution.branch = branch;\n // PaaS-injected git context (Vercel/Render/Railway/Netlify/Heroku) fills\n // any gaps — zero-config attribution on those hosts. Explicit env wins.\n const paas = paasGitContext();\n if (paas) {\n if (attribution.source === \"runtime\") attribution.source = `paas:${paas.provider}`;\n if (!attribution.commitSha && paas.sha) attribution.commitSha = paas.sha;\n if (!attribution.repo && paas.repo) attribution.repo = paas.repo;\n if (!attribution.branch && paas.branch) attribution.branch = paas.branch;\n if (!attribution.githubLogin && paas.login) attribution.githubLogin = paas.login;\n }\n const ref = process.env.GITHUB_REF ?? \"\";\n const prMatch = /refs\\/pull\\/(\\d+)\\//.exec(ref);\n if (prMatch) attribution.prNumber = Number(prMatch[1]);\n // PR title/body are NOT in the default Actions env — workflows pass them\n // through in two lines:\n // env:\n // GATEWAY_PR_TITLE: ${{ github.event.pull_request.title }}\n // GATEWAY_PR_BODY: ${{ github.event.pull_request.body }}\n if (process.env.GATEWAY_PR_TITLE) {\n attribution.prTitle = process.env.GATEWAY_PR_TITLE.slice(0, 300);\n }\n if (process.env.GATEWAY_PR_BODY) {\n attribution.prDescription = process.env.GATEWAY_PR_BODY.slice(0, 2000);\n }\n if (\n attribution.repo &&\n attribution.prNumber &&\n !(\"prUrl\" in attribution)\n ) {\n attribution.prUrl = `https://github.com/${String(attribution.repo)}/pull/${String(attribution.prNumber)}`;\n }\n return attribution;\n}\n\n// ── Late registration ──────────────────────────────────────────────────────\n// Many agents build their tool maps lazily (per request), AFTER init. Any\n// defineTool/registerPrompt/registerSkill call re-assembles the manifest for\n// every active agent build (debounced) and re-registers when the hash moved.\n// Content-addressed and idempotent: the registry simply gains the fullest\n// manifest; traces keep the hash stamped at init (documented behavior).\n\nexport interface ActiveBuildContext {\n host: string;\n publicKey: string;\n secretKey: string;\n agentId: string;\n version?: string;\n lastRegisteredHash?: string;\n}\n\nconst activeBuilds: ActiveBuildContext[] = [];\nlet reRegisterTimer: ReturnType<typeof setTimeout> | null = null;\nconst RE_REGISTER_DEBOUNCE_MS = 3000;\n\nexport function trackActiveBuild(context: ActiveBuildContext): void {\n activeBuilds.push(context);\n}\n\nfunction notifyRegistryChanged(): void {\n if (activeBuilds.length === 0) return;\n if (reRegisterTimer) clearTimeout(reRegisterTimer);\n reRegisterTimer = setTimeout(() => {\n reRegisterTimer = null;\n for (const context of activeBuilds) {\n const manifest = assembleManifest(context.agentId);\n const buildHash = computeBuildHash(manifest);\n if (buildHash === context.lastRegisteredHash) continue;\n context.lastRegisteredHash = buildHash;\n void registerBuild({ ...context, manifest, buildHash }).catch(() => {\n // fail-soft; a later change retries via the next notify\n context.lastRegisteredHash = undefined;\n });\n }\n }, RE_REGISTER_DEBOUNCE_MS);\n // Never hold the process open just to re-register.\n if (typeof reRegisterTimer === \"object\" && \"unref\" in reRegisterTimer) {\n (reRegisterTimer as { unref(): void }).unref();\n }\n}\n\n/**\n * Fire-and-forget build registration. Idempotent on buildHash server-side;\n * failures are logged once and never affect the agent.\n */\nexport async function registerBuild(params: {\n host: string;\n publicKey: string;\n secretKey: string;\n agentId: string;\n version?: string;\n manifest: AgentBuildManifest;\n buildHash: string;\n}): Promise<void> {\n const auth = Buffer.from(`${params.publicKey}:${params.secretKey}`).toString(\n \"base64\",\n );\n const response = await fetch(\n `${params.host.replace(/\\/$/, \"\")}/api/public/agent-builds`,\n {\n method: \"POST\",\n headers: {\n Authorization: `Basic ${auth}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n agentId: params.agentId,\n buildHash: params.buildHash,\n ...(params.version ? { semanticVer: params.version } : {}),\n manifest: params.manifest,\n attribution: attributionFromEnv(),\n }),\n signal: AbortSignal.timeout(15_000),\n },\n );\n if (!response.ok) {\n throw new Error(\n `build registration failed (${response.status}): ${(await response.text()).slice(0, 300)}`,\n );\n }\n}\n","/**\n * Initialization and lifecycle management for GatewaySDK tracing.\n *\n * This module provides the core init(), shutdown(), and flush() functions\n * for managing the OpenTelemetry TracerProvider lifecycle, plus\n * initIsolated() for creating additional self-contained providers (e.g. one\n * process exporting different agents to different Gateway projects).\n *\n * Mirrors the Python SDK's tracing.init() for a consistent developer experience.\n */\n\nimport type { Tracer } from \"@opentelemetry/api\";\nimport type { TracingConfig, TracingState } from \"./types\";\nimport { IdentitySpanProcessor } from \"./identity\";\nimport { SessionSpanProcessor } from \"./session\";\nimport { ScoresClient } from \"../scores/index\";\nimport {\n assembleManifest,\n computeBuildHash,\n registerBuild,\n trackActiveBuild,\n type AgentBuildManifest,\n} from \"../build/index\";\n\n// Environment variable names. (A legacy BRIDGELAYER_* prefix predated the\n// rebrand but was never in any published release, so only GATEWAY_* exists.)\nconst ENV_VARS = {\n HOST: \"GATEWAY_HOST\",\n PUBLIC_KEY: \"GATEWAY_PUBLIC_KEY\",\n SECRET_KEY: \"GATEWAY_SECRET_KEY\",\n ENDPOINT: \"GATEWAY_OTLP_ENDPOINT\",\n} as const;\n\nconst DEFAULT_OTLP_PATH = \"/api/public/otel/v1/traces\";\n\n// Module-level state\nconst state: TracingState & { debug?: boolean } = {\n initialized: false,\n provider: null,\n};\n\nfunction getEnv(key: string): string | undefined {\n const value = process.env[key];\n return value ? value : undefined;\n}\n\nfunction log(message: string, ...args: unknown[]): void {\n if (state.debug) {\n console.log(`[gatewaysdk.tracing] ${message}`, ...args);\n }\n}\n\nfunction warn(message: string, ...args: unknown[]): void {\n console.warn(`[gatewaysdk.tracing] ${message}`, ...args);\n}\n\ntype LogFn = (message: string, ...args: unknown[]) => void;\n\n/**\n * Handle to an isolated tracing provider created by initIsolated().\n * Spans started from `tracer` export to that provider's Gateway project;\n * the global tracer (from init()) is untouched.\n */\nexport interface TracingHandle {\n tracer: Tracer;\n /**\n * Scores/success-signal client bound to THIS provider's project keys. Emit\n * ROI success signals into the same project the handle's spans export to —\n * `handle.scores.success(\"resolved_ticket\", true, { agentId, sessionId })` —\n * without threading credentials through your own code. Fail-soft, like the\n * rest of the client.\n */\n scores: ScoresClient;\n /** Force-flush pending spans for this provider only. */\n flush(): Promise<void>;\n /** Flush and shut down this provider only. */\n shutdown(): Promise<void>;\n}\n\n/**\n * Build a fully-configured NodeTracerProvider from config + env. Shared by\n * init() (which registers it globally) and initIsolated() (which does not).\n */\n/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-require-imports */\nfunction buildProvider(config: TracingConfig, logFn: LogFn): any {\n // Resolve configuration from params or environment\n const host = config.host ?? getEnv(ENV_VARS.HOST);\n const publicKey = config.publicKey ?? getEnv(ENV_VARS.PUBLIC_KEY);\n const secretKey = config.secretKey ?? getEnv(ENV_VARS.SECRET_KEY);\n const endpoint =\n config.endpoint ??\n getEnv(ENV_VARS.ENDPOINT) ??\n (host ? `${host.replace(/\\/$/, \"\")}${DEFAULT_OTLP_PATH}` : undefined);\n\n // Validate required configuration\n const missing: string[] = [];\n if (!host) missing.push(\"host (or GATEWAY_HOST env var)\");\n if (!publicKey) missing.push(\"publicKey (or GATEWAY_PUBLIC_KEY env var)\");\n if (!secretKey) missing.push(\"secretKey (or GATEWAY_SECRET_KEY env var)\");\n\n if (missing.length > 0) {\n throw new Error(\n `Missing required Gateway configuration: ${missing.join(\", \")}. ` +\n \"Provide these values via init() parameters or environment variables.\",\n );\n }\n\n // Dynamically import OpenTelemetry modules (they're peer dependencies)\n // Using 'any' to avoid version conflicts between OTel packages\n let NodeTracerProvider: any;\n let BatchSpanProcessor: any;\n let OTLPTraceExporter: any;\n let createResource: (attrs: Record<string, string>) => any;\n let ATTR_SERVICE_NAME: string;\n\n try {\n const traceNode = require(\"@opentelemetry/sdk-trace-node\");\n const traceBase = require(\"@opentelemetry/sdk-trace-base\");\n const otlpHttp = require(\"@opentelemetry/exporter-trace-otlp-http\");\n const resources = require(\"@opentelemetry/resources\");\n\n NodeTracerProvider = traceNode.NodeTracerProvider;\n BatchSpanProcessor = traceBase.BatchSpanProcessor;\n OTLPTraceExporter = otlpHttp.OTLPTraceExporter;\n\n // Handle both old (Resource class) and new (resourceFromAttributes function) APIs\n if (resources.Resource) {\n createResource = (attrs) => new resources.Resource(attrs);\n } else if (resources.resourceFromAttributes) {\n createResource = resources.resourceFromAttributes;\n } else {\n createResource = () => resources.defaultResource();\n }\n\n // Try semantic conventions, fall back to string literal\n try {\n const semconv = require(\"@opentelemetry/semantic-conventions\");\n ATTR_SERVICE_NAME =\n semconv.ATTR_SERVICE_NAME ??\n semconv.SEMRESATTRS_SERVICE_NAME ??\n \"service.name\";\n } catch {\n ATTR_SERVICE_NAME = \"service.name\";\n }\n } catch {\n throw new Error(\n \"OpenTelemetry packages not found. Install them with:\\n\" +\n \"npm install @opentelemetry/sdk-trace-node @opentelemetry/sdk-trace-base \" +\n \"@opentelemetry/exporter-trace-otlp-http @opentelemetry/resources\",\n );\n }\n\n // Build resource attributes\n const resourceAttrs: Record<string, string> = {\n [ATTR_SERVICE_NAME]: config.serviceName ?? \"gatewaysdk-tracing\",\n };\n if (config.environment) {\n resourceAttrs[\"gateway.environment\"] = config.environment;\n }\n if (config.version) {\n resourceAttrs[\"gateway.version\"] = config.version;\n }\n\n // Agent build identity — \"the agent IS the manifest\": assemble from\n // everything registered before init, stamp the content-addressed hash on\n // every span. (Tools defined AFTER init don't join the identity — define\n // them first.)\n let buildInfo: { manifest: AgentBuildManifest; buildHash: string } | null =\n null;\n if (config.agent) {\n const manifest = assembleManifest(config.agent);\n const buildHash = computeBuildHash(manifest);\n buildInfo = { manifest, buildHash };\n resourceAttrs[\"gateway.agent.id\"] = config.agent;\n resourceAttrs[\"gateway.build.hash\"] = buildHash;\n if (config.version) {\n resourceAttrs[\"gateway.agent.version\"] = config.version;\n }\n logFn(\n \"Agent build identity: %s @ %s (%d tools, %d prompts)\",\n config.agent,\n buildHash.slice(0, 15),\n manifest.tools.length,\n Object.keys(manifest.prompts).length,\n );\n }\n\n // Security check: block insecure HTTP (except localhost/127.0.0.1)\n let isLocalhost = false;\n if (endpoint) {\n try {\n const parsed = new URL(endpoint);\n isLocalhost =\n parsed.hostname === \"localhost\" || parsed.hostname === \"127.0.0.1\";\n } catch {\n isLocalhost = false;\n }\n }\n if (endpoint && !endpoint.startsWith(\"https://\") && !isLocalhost) {\n throw new Error(\n `Refusing to send credentials over insecure HTTP to ${endpoint}. ` +\n \"Use HTTPS or localhost for development.\",\n );\n }\n\n // Construct Basic Auth header\n const credentials = `${publicKey}:${secretKey}`;\n const encoded = Buffer.from(credentials).toString(\"base64\");\n const authHeader = `Basic ${encoded}`;\n\n // Create OTLP exporter\n const exporter = new OTLPTraceExporter({\n url: endpoint,\n headers: {\n Authorization: authHeader,\n },\n });\n\n logFn(\"Configured Gateway exporter: endpoint=%s\", endpoint);\n\n // Build span processors — custom processors go first (before the BatchSpanProcessor)\n const spanProcessors: any[] = [];\n\n if (config.customSpanProcessors) {\n for (const sp of config.customSpanProcessors) {\n spanProcessors.push(sp);\n logFn(\n \"Added custom span processor: %s\",\n (sp as { constructor?: { name?: string } }).constructor?.name ??\n \"unknown\",\n );\n }\n }\n\n // Stamp the ambient end-user identity (identify() / GATEWAY_USER_ID) on\n // every span at start — mirrors the Python SDK's TracingContextSpanProcessor.\n spanProcessors.push(new IdentitySpanProcessor());\n\n // Stamp the ambient session id (withSession()) on every span at start —\n // the TS twin of the Python SDK's tracing.session() + the same processor.\n spanProcessors.push(new SessionSpanProcessor());\n\n // Add BatchSpanProcessor with exporter\n const batchConfig: Record<string, number> = {};\n if (config.batch?.maxQueueSize) {\n batchConfig.maxQueueSize = config.batch.maxQueueSize;\n }\n if (config.batch?.scheduledDelayMillis) {\n batchConfig.scheduledDelayMillis = config.batch.scheduledDelayMillis;\n }\n if (config.batch?.maxExportBatchSize) {\n batchConfig.maxExportBatchSize = config.batch.maxExportBatchSize;\n }\n\n spanProcessors.push(new BatchSpanProcessor(exporter, batchConfig));\n\n // Create provider — detect v1 vs v2 API via runtime feature check.\n // v1 has addSpanProcessor(); v2 removed it and requires spanProcessors in constructor.\n let provider: any = new NodeTracerProvider({\n resource: createResource(resourceAttrs),\n });\n\n if (typeof provider.addSpanProcessor === \"function\") {\n // v1 API: register each processor individually\n for (const sp of spanProcessors) {\n provider.addSpanProcessor(sp);\n }\n } else {\n // v2 API: must pass spanProcessors in constructor — recreate\n provider = new NodeTracerProvider({\n resource: createResource(resourceAttrs),\n spanProcessors,\n });\n }\n\n return {\n provider,\n buildInfo,\n connection: { host: host!, publicKey: publicKey!, secretKey: secretKey! },\n };\n}\n/* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/no-require-imports */\n\n/** Fire-and-forget build registration for a provider built with `agent`. */\nfunction scheduleBuildRegistration(\n config: TracingConfig,\n built: ReturnType<typeof buildProvider>,\n): void {\n if (!config.agent || !built.buildInfo || config.registerBuild === false) {\n return;\n }\n const { manifest, buildHash } = built.buildInfo;\n // Track so tools/prompts/skills registered AFTER init re-register the\n // fullest manifest (debounced, content-addressed, idempotent).\n trackActiveBuild({\n host: built.connection.host,\n publicKey: built.connection.publicKey,\n secretKey: built.connection.secretKey,\n agentId: config.agent,\n version: config.version,\n lastRegisteredHash: buildHash,\n });\n void registerBuild({\n host: built.connection.host,\n publicKey: built.connection.publicKey,\n secretKey: built.connection.secretKey,\n agentId: config.agent,\n version: config.version,\n manifest,\n buildHash,\n }).catch((err: unknown) => {\n warn(\"Build registration failed (agent keeps running):\", err);\n });\n}\n\n/**\n * Initialize GatewaySDK tracing with automatic OpenTelemetry configuration.\n *\n * This function configures OpenTelemetry with a connection to Gateway\n * and sets up the ExperimentSpanProcessor for automatic experiment tagging.\n *\n * @example\n * ```typescript\n * import { tracing } from \"@withgateway/sdk\";\n *\n * // Using environment variables (GATEWAY_HOST, GATEWAY_PUBLIC_KEY, GATEWAY_SECRET_KEY)\n * tracing.init();\n *\n * // Or with explicit configuration\n * tracing.init({\n * host: \"https://app.gateway.dev\",\n * publicKey: \"pk-lf-...\",\n * secretKey: \"sk-lf-...\",\n * serviceName: \"my-agent\",\n * environment: \"production\",\n * });\n * ```\n */\nexport function init(config: TracingConfig = {}): void {\n if (state.initialized) {\n log(\"Tracing already initialized. Call shutdown() first to reinitialize.\");\n return;\n }\n\n // Store debug flag in state for log() function\n state.debug = config.debug ?? false;\n\n const built = buildProvider(config, log);\n const provider = built.provider;\n provider.register();\n scheduleBuildRegistration(config, built);\n\n state.provider = provider;\n state.initialized = true;\n\n log(\n \"GatewaySDK tracing initialized successfully (service=%s)\",\n config.serviceName ?? \"gatewaysdk-tracing\",\n );\n}\n\n/**\n * Create an ISOLATED tracing provider that is NOT registered globally.\n *\n * Use this when one process must export different work to different Gateway\n * projects (e.g. a server hosting several agents, each with its own project\n * keys), or when the process already has its own global OpenTelemetry\n * provider that must not be replaced.\n *\n * Spans only reach the isolated provider when started from its `tracer` —\n * pass it explicitly to observe()/observeClaude() via their `tracer` option,\n * or to a framework's telemetry hook (e.g. the Vercel AI SDK's\n * `experimental_telemetry.tracer`). Context propagation still works across\n * providers, so nesting behaves exactly as with init().\n *\n * Can be called any number of times; each handle has its own exporter,\n * batch queue, and lifecycle.\n *\n * @example\n * ```typescript\n * import { tracing } from \"@withgateway/sdk\";\n *\n * const support = tracing.initIsolated({\n * host: \"https://app.gateway.dev\",\n * publicKey: \"pk-lf-support...\",\n * secretKey: \"sk-lf-support...\",\n * serviceName: \"support-agent\",\n * });\n *\n * await tracing.observe(\"support.run\", run, { tracer: support.tracer });\n * await support.flush();\n * ```\n */\nexport function initIsolated(config: TracingConfig = {}): TracingHandle {\n const debugLog: LogFn = config.debug\n ? (message, ...args) =>\n console.log(`[gatewaysdk.tracing:isolated] ${message}`, ...args)\n : () => {};\n\n const built = buildProvider(config, debugLog);\n const provider = built.provider;\n scheduleBuildRegistration(config, built);\n const tracer = provider.getTracer(\"@withgateway/sdk\") as Tracer;\n\n // Scores client bound to the SAME project keys the exporter uses, so a\n // handle can emit success signals into its own project with no extra wiring.\n const scores = new ScoresClient({\n host: built.connection.host,\n publicKey: built.connection.publicKey,\n secretKey: built.connection.secretKey,\n debug: config.debug ?? false,\n });\n\n debugLog(\n \"Isolated tracing provider created (service=%s)\",\n config.serviceName ?? \"gatewaysdk-tracing\",\n );\n\n return {\n tracer,\n scores,\n async flush() {\n try {\n await (provider as { forceFlush: () => Promise<void> }).forceFlush();\n } catch (e) {\n warn(\"Error during isolated flush:\", e);\n }\n },\n async shutdown() {\n try {\n await (provider as { shutdown: () => Promise<void> }).shutdown();\n } catch (e) {\n warn(\"Error during isolated shutdown:\", e);\n }\n },\n };\n}\n\n/**\n * Force flush all pending spans without shutting down.\n *\n * Useful for ensuring spans are exported at specific points\n * (e.g., after completing a batch of work) without ending the tracing session.\n *\n * @returns Promise that resolves when flush completes\n */\nexport async function flush(): Promise<void> {\n if (!state.provider) {\n log(\"No provider to flush\");\n return;\n }\n\n try {\n await (state.provider as { forceFlush: () => Promise<void> }).forceFlush();\n log(\"Flush completed successfully\");\n } catch (e) {\n warn(\"Error during flush:\", e);\n }\n}\n\n/**\n * Force flush all pending spans and shutdown the tracer provider.\n *\n * This function should be called before process exit to ensure all spans\n * are exported. It is safe to call multiple times.\n *\n * @example\n * ```typescript\n * import { tracing } from \"@withgateway/sdk\";\n *\n * tracing.init();\n *\n * // On shutdown\n * process.on(\"SIGTERM\", async () => {\n * await tracing.shutdown();\n * process.exit(0);\n * });\n * ```\n */\nexport async function shutdown(): Promise<void> {\n if (!state.initialized || !state.provider) {\n log(\"Tracing not initialized, nothing to shutdown\");\n return;\n }\n\n try {\n await (state.provider as { shutdown: () => Promise<void> }).shutdown();\n log(\"Shutdown complete\");\n } catch (e) {\n warn(\"Error during shutdown:\", e);\n }\n\n state.provider = null;\n state.initialized = false;\n}\n\n/**\n * Check if tracing has been initialized.\n */\nexport function isInitialized(): boolean {\n return state.initialized;\n}\n\n/**\n * Check if Gateway is configured via environment variables.\n */\nexport function isGatewayConfigured(): boolean {\n const host = getEnv(ENV_VARS.HOST);\n const publicKey = getEnv(ENV_VARS.PUBLIC_KEY);\n const secretKey = getEnv(ENV_VARS.SECRET_KEY);\n return !!(host && publicKey && secretKey);\n}\n","import { randomBytes } from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport type { WorldSurfaceKind } from \"./browser\";\nimport { WorldSurfaceUnavailable } from \"./browser\";\nimport { GatewayEvalsClient, type EvalSample } from \"./evals\";\nimport type { WorldsClientOptions } from \"./index\";\nimport {\n modelToolName,\n schemaFromSignature,\n WorldSession,\n type WorldTaskIdRef,\n type WorldTaskSpec,\n type WorldToolkit,\n type WorldToolSpec,\n} from \"./session\";\nimport {\n openTask,\n TaskSessions,\n type TaskGrade,\n type TaskManifest,\n} from \"./taskSessions\";\n\n/**\n * RUN A TASK END TO END: open, agent, grade, file, close.\n *\n * `runTask` is `gateway worlds task run` in one call: bring every world of a\n * task up, hand the agent a small `TaskRun` (its sessions, a merged\n * toolkit, a place to record notes), grade every world with the agent's own\n * report, file one rollout the same way the Python SDK's `World.run` does\n * for a single in-process world, and close everything down — a run\n * directory on disk is the paper trail (`manifest.json`, `grades.json`,\n * `report.md`, `run.json`). Mirrors `gatewaysdk.world_tasks.run_task`.\n *\n * const summary = await runTask(\"wt_1\", async (run) => {\n * const { url, token } = await run.api(\"spycloud\");\n * // ... call the agent, using run.sessions / run.toolkit() ...\n * return \"found and locked the account\";\n * }, { model: \"claude-sonnet-4-5\" });\n */\n\n/** What the agent callable given to `runTask` is called with: the run's\n * identity, every world's live session, and a place to leave notes that\n * land in the run's `run.json`. */\nexport class TaskRun {\n readonly notes: Record<string, unknown> = {};\n\n constructor(\n readonly runId: string,\n readonly instruction: string,\n readonly model: string,\n readonly sessions: Record<string, WorldSession>,\n readonly manifest: TaskManifest,\n ) {}\n\n /** The alias's session, or a clear error naming the aliases there are. */\n session(alias: string): WorldSession {\n const session = this.sessions[alias];\n if (!session)\n throw new Error(\n `task run has no world '${alias}'; its worlds are ${Object.keys(this.sessions).join(\", \")}`,\n );\n return session;\n }\n\n /** `alias`'s HTTP API. Raises the same error the session itself would\n * when it was not opened with `surfaces: [\"api\"]`. */\n async api(alias: string): Promise<{ url: string; token?: string }> {\n const surfaces = await this.session(alias).surfaces();\n if (!surfaces.api)\n throw new WorldSurfaceUnavailable(\n \"api\",\n `open '${alias}' with surfaces: ['api']`,\n );\n return { url: surfaces.api.url, token: surfaces.api.token };\n }\n\n /** Every world's tools merged into one toolkit, each name prefixed\n * `<alias>.<tool>` so a model can tell which world a call goes to. A\n * world that exposes no tools contributes nothing — there is nothing to\n * merge. */\n async toolkit(): Promise<WorldToolkit> {\n const schemas: WorldToolkit[\"schemas\"] = [];\n const impls: WorldToolkit[\"impls\"] = {};\n const specs: WorldToolSpec[] = [];\n for (const [alias, session] of Object.entries(this.sessions)) {\n const kit = await session.toolkit();\n if (!kit.specs.length) continue;\n for (const spec of kit.specs) {\n const name = `${alias}.${spec.name}`;\n const prefixed: WorldToolSpec = {\n name,\n signature: spec.signature,\n doc: spec.doc,\n inputSchema: spec.inputSchema,\n };\n specs.push(prefixed);\n const schema = schemaFromSignature(prefixed);\n schema.function.name = name;\n schemas.push(schema);\n impls[name] = kit.impls[modelToolName(spec.name)]!;\n }\n }\n return { schemas, impls, specs };\n }\n\n /** Log arbitrary notes into this run's `run.json` (merged; a later call\n * overrides a key an earlier one set). */\n record(notes: Record<string, unknown>): void {\n Object.assign(this.notes, notes);\n }\n}\n\nfunction worldRef(\n live: TaskSessions,\n alias: string,\n): { slug: string; ref: string | null; versionId: string; sessionId: string } {\n const { slug, ref } = live.worldRef(alias);\n const session = live.sessions[alias]!;\n return {\n slug,\n ref,\n versionId: session.versionId,\n sessionId: session.sessionId,\n };\n}\n\n/** File one rollout for a task run, the same create/push/finalize shape\n * `gatewaysdk.world_tasks._file_task_run` uses. */\nasync function fileTaskRun(\n live: TaskSessions,\n runId: string,\n model: string,\n report: string | null,\n grade: TaskGrade,\n agentError: string | null,\n traced: boolean,\n runDir: string,\n options: WorldsClientOptions,\n): Promise<string> {\n const aliases = live.aliases;\n // The platform anchors an evaluation to ONE version today; a multi-world\n // task has no single version, so the first alias stands in and every\n // world's own version travels in `metadata.worlds` instead.\n const anchor = aliases[0]!;\n const worldsMeta = Object.fromEntries(\n aliases.map((alias) => [alias, worldRef(live, alias)]),\n );\n\n const evals = new GatewayEvalsClient(options);\n const evaluationId = await evals.createEvaluation(\n worldRef(live, anchor).versionId,\n {\n model,\n rolloutsPerExample: 1,\n metadata: {\n source: \"worlds-task-run\",\n task: {\n id: live.taskId,\n version: live.taskVersion,\n name: live.name,\n hash: live.hash,\n },\n anchor,\n worlds: worldsMeta,\n runId,\n },\n },\n );\n\n const reward = grade.reward;\n const sample: Record<string, unknown> = {\n exampleId: live.name ?? live.taskId ?? runId,\n task: live.name ?? live.taskId ?? runId,\n rolloutIndex: 0,\n prompt: live.instruction,\n completion: report,\n rewards: grade.rewards,\n info: {\n sessionId: runId,\n worlds: Object.fromEntries(\n aliases.map((alias) => [\n alias,\n {\n ...worldRef(live, alias),\n reward: grade.worlds[alias]?.reward ?? null,\n },\n ]),\n ),\n ungraded: grade.ungraded,\n traced,\n runDir,\n ...(agentError ? { agentError } : {}),\n },\n };\n if (typeof reward === \"number\") {\n sample.reward = reward;\n sample.score = reward;\n sample.correct = reward >= 1.0;\n }\n await evals.pushSamples(evaluationId, [sample as unknown as EvalSample]);\n await evals.finalizeEvaluation(evaluationId, {\n status: agentError ? \"FAILED\" : \"COMPLETED\",\n metrics: {\n ...(typeof reward === \"number\" ? { avg_reward: reward } : {}),\n reward,\n ...Object.fromEntries(\n Object.entries(grade.rewards).map(([k, v]) => [`rewards.${k}`, v]),\n ),\n },\n });\n return evaluationId;\n}\n\nexport type RunTaskOptions = {\n /** Model label recorded on the filed run. */\n model: string;\n /** Asked of every world besides tools: api, ui, browser. */\n surfaces?: WorldSurfaceKind[];\n /** Directory the run's own `<runId>/` folder is created under. Default `\"runs\"`. */\n outDir?: string;\n /** Initialize tracing when GATEWAY_* credentials are configured. Default `true`. */\n trace?: boolean;\n /** File one rollout when the run ends. Default `true`. */\n file?: boolean;\n /** Leave every session up instead of closing it when the run ends. Default `false`. */\n keepUp?: boolean;\n reuseWarm?: boolean;\n options?: WorldsClientOptions;\n};\n\n/** What `runTask` returns and writes to `<runDir>/run.json`. */\nexport type RunTaskSummary = {\n runId: string;\n taskId: string | null;\n taskVersion: number | null;\n name: string | null;\n instruction: string;\n model: string;\n aliases: string[];\n reward: number | null;\n rewards: Record<string, number>;\n ungraded: string[];\n agentError: string | null;\n report: string | null;\n traced: boolean;\n runDir: string;\n durationSeconds: number;\n notes: Record<string, unknown>;\n filed: boolean;\n evaluationId?: string;\n [extra: string]: unknown;\n};\n\n/** The report an agent callable may return: a string, or an object with a\n * `report` key (any other keys are kept in `run.json` as-is). */\nexport type TaskRunResult =\n | string\n | { report?: unknown; [key: string]: unknown }\n | null\n | undefined;\n\nfunction reportFromResult(result: TaskRunResult): {\n report: string | null;\n extra: Record<string, unknown>;\n} {\n if (typeof result === \"string\") return { report: result, extra: {} };\n if (result && typeof result === \"object\") {\n const { report, ...extra } = result as Record<string, unknown>;\n return {\n report:\n report === undefined || report === null\n ? null\n : typeof report === \"string\"\n ? report\n : String(report),\n extra,\n };\n }\n if (result !== undefined && result !== null)\n return { report: String(result), extra: {} };\n return { report: null, extra: {} };\n}\n\n/**\n * Open every world of a task, run `agent` once against all of them, grade\n * with its report, file one rollout and close — the engine behind `gateway\n * worlds task run`. `agent` is called as `agent(taskRun)` with a `TaskRun`;\n * its return value becomes the report handed to every world's grader.\n *\n * Every step has a flag and a default, nothing implicit: tracing runs when\n * `GATEWAY_*` credentials are configured unless `trace: false`; filing\n * happens unless `file: false`; every session closes unless `keepUp: true`\n * — even when the agent throws, so grading and filing still happen with the\n * error recorded (`run.json.agentError`, the filed evaluation's status\n * FAILED).\n *\n * Writes `<outDir>/<runId>/{manifest,grades,run}.json` (and `report.md`\n * when the agent gave one).\n */\nexport async function runTask(\n ref: string | WorldTaskIdRef | WorldTaskSpec,\n agent: (run: TaskRun) => TaskRunResult | Promise<TaskRunResult>,\n opts: RunTaskOptions,\n): Promise<RunTaskSummary> {\n const runId = `wtr-${randomBytes(6).toString(\"hex\")}`;\n const outDir = opts.outDir ?? \"runs\";\n const runDir = path.join(outDir, runId);\n fs.mkdirSync(runDir, { recursive: true });\n const options = opts.options ?? {};\n\n const live = await openTask(ref, {\n surfaces: opts.surfaces,\n reuseWarm: opts.reuseWarm,\n options,\n });\n const started = Date.now();\n try {\n await live.ready();\n\n let traced = false;\n if (opts.trace !== false) {\n try {\n const { isGatewayConfigured, init } = await import(\"../tracing/init\");\n if (isGatewayConfigured()) {\n init();\n traced = true;\n }\n } catch {\n // Tracing must never sink a run.\n traced = false;\n }\n }\n\n const taskRun = new TaskRun(\n runId,\n live.instruction ?? \"\",\n opts.model,\n live.sessions,\n await live.manifest(),\n );\n\n let agentError: string | null = null;\n let report: string | null = null;\n let extra: Record<string, unknown> = {};\n try {\n const invoke = () => agent(taskRun);\n const result = traced\n ? await (await import(\"../tracing/session\")).withSession(runId, invoke)\n : await invoke();\n ({ report, extra } = reportFromResult(result));\n } catch (error) {\n const message =\n (error instanceof Error ? error.message : String(error)) ||\n \"Unknown error\";\n agentError = message.slice(0, 2000);\n }\n\n const grade =\n report !== null ? await live.grade({ report }) : await live.grade();\n\n fs.writeFileSync(\n path.join(runDir, \"manifest.json\"),\n JSON.stringify(taskRun.manifest, null, 2),\n );\n fs.writeFileSync(\n path.join(runDir, \"grades.json\"),\n JSON.stringify(grade, null, 2),\n );\n if (report) fs.writeFileSync(path.join(runDir, \"report.md\"), report);\n\n const summary: RunTaskSummary = {\n runId,\n taskId: live.taskId,\n taskVersion: live.taskVersion,\n name: live.name,\n instruction: taskRun.instruction,\n model: opts.model,\n aliases: live.aliases,\n reward: grade.reward,\n rewards: grade.rewards,\n ungraded: grade.ungraded,\n agentError,\n report,\n traced,\n runDir,\n durationSeconds: Math.round((Date.now() - started) / 10) / 100,\n notes: taskRun.notes,\n filed: false,\n ...extra,\n };\n\n if (opts.file !== false) {\n summary.evaluationId = await fileTaskRun(\n live,\n runId,\n opts.model,\n report,\n grade,\n agentError,\n traced,\n runDir,\n options,\n );\n summary.filed = true;\n }\n\n fs.writeFileSync(\n path.join(runDir, \"run.json\"),\n JSON.stringify(summary, null, 2),\n );\n return summary;\n } finally {\n if (!opts.keepUp) {\n try {\n await live.close({ keepWarm: false });\n } catch {\n // Every close is best-effort here; a session that would not close\n // is not this function's failure to report — `task down` covers it.\n }\n }\n }\n}\n","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\n/** The slug a push of `dir` lands on: an explicit one, else the slug the dir\n * was pushed to or pulled from (its `.gateway` meta), else the pyproject\n * name, else the directory's name — so a tracked checkout never creates a\n * second world named after its folder. */\nexport function pushSlug(dir: string, explicit?: string): string {\n if (explicit) return explicit;\n const meta = readLocalMeta(dir);\n if (typeof meta?.slug === \"string\" && meta.slug) return meta.slug;\n return readPyproject(dir).name ?? path.basename(path.resolve(dir));\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, pushSlug } from \"./hub\";\n\nexport type ValidatedRun = {\n model: string;\n runId: string;\n report: RunReport | null;\n /** Why this run fails the gate, or null when it passes. */\n failure: string | null;\n};\n\nexport type ValidateReport = {\n ok: boolean;\n slug: string;\n branch: string;\n versionId: string;\n contentHash: string;\n runConfig: { id: string; name: string };\n runs: ValidatedRun[];\n /** A PR-comment-ready summary of the whole validation. */\n markdown: string;\n};\n\nfunction fmtScore(score: number | null): string {\n return score === null ? \"no score\" : score.toFixed(3);\n}\n\nfunction buildMarkdown(\n report: Omit<ValidateReport, \"markdown\">,\n minScore: number | null,\n source?: { repoUrl?: string; commit?: string },\n): string {\n const lines: string[] = [];\n lines.push(\n `### World validation ${report.ok ? \"passed\" : \"failed\"} — \\`${report.slug}@${report.branch}\\``,\n );\n lines.push(\"\");\n // Name the exact source that ran: the commit on GitHub when we know it,\n // always the content hash the platform pinned.\n const commitLink =\n source?.repoUrl && source?.commit\n ? `[\\`${source.commit.slice(0, 12)}\\`](${source.repoUrl}/commit/${source.commit})`\n : null;\n lines.push(\n `Ran the pull request's own world source` +\n (commitLink ? ` (${commitLink} on \\`${report.branch}\\`` : ` (`) +\n `${commitLink ? \", \" : \"\"}pinned as \\`${report.contentHash.slice(0, 12)}\\`) ` +\n `through run config **${report.runConfig.name}**` +\n (minScore !== null ? `, gating at score ≥ ${minScore}.` : \".\"),\n );\n lines.push(\"\");\n lines.push(\"| Model | Status | Score | Run |\");\n lines.push(\"| --- | --- | ---: | --- |\");\n for (const run of report.runs) {\n const r = run.report;\n const link = r?.url ? `[open](${r.url})` : \"—\";\n const status = run.failure\n ? `❌ ${run.failure}`\n : `✅ ${r?.status ?? \"COMPLETED\"}`;\n lines.push(\n `| \\`${run.model}\\` | ${status} | ${fmtScore(r?.score ?? null)} | ${link} |`,\n );\n }\n const taskRows = report.runs.flatMap((run) =>\n (run.report?.samples ?? []).map((sample) => ({\n model: run.model,\n task: sample.task ?? \"?\",\n reward: sample.reward,\n })),\n );\n // Every scenario, in the open: a validation whose per-scenario grades hide\n // behind a fold reads as one opaque number. Fold only when the table is\n // genuinely long.\n if (taskRows.length > 0) {\n const fold = taskRows.length > 12;\n lines.push(\"\");\n if (fold) {\n lines.push(\n `<details><summary>Per-scenario rewards (${taskRows.length})</summary>`,\n );\n lines.push(\"\");\n } else {\n lines.push(`**Scenarios (${taskRows.length})**`);\n lines.push(\"\");\n }\n lines.push(\"| Scenario | Model | Reward |\");\n lines.push(\"| --- | --- | ---: |\");\n for (const row of taskRows) {\n lines.push(\n `| ${row.task} | \\`${row.model}\\` | ${row.reward === null ? \"no score\" : row.reward.toFixed(2)} |`,\n );\n }\n if (fold) {\n lines.push(\"\");\n lines.push(\"</details>\");\n }\n }\n return lines.join(\"\\n\");\n}\n\n/**\n * Push `dir` on the current (or given) branch, dispatch the named run config\n * against the pushed version, wait for every run, and gate.\n *\n * The gate: every dispatch accepted, every run terminal COMPLETED, and — when\n * `minScore` is set — every run's score meets it. A run with NO score fails a\n * score gate rather than passing it: null is \"not scored\", never 0 and never\n * fine.\n */\nexport async function validateWorld(\n dir: string,\n opts: {\n slug?: string;\n runConfig: string;\n branch?: string;\n minScore?: number | null;\n timeoutMinutes?: number;\n onProgress?: (line: string) => void;\n options?: WorldsClientOptions;\n },\n): Promise<ValidateReport> {\n const options = opts.options ?? {};\n const progress = opts.onProgress ?? (() => {});\n const minScore = opts.minScore ?? null;\n\n const provenance = detectProvenance();\n const branch = opts.branch ?? provenance.branch;\n if (!branch)\n throw new Error(\n \"No branch to validate on: pass --branch or run inside a git checkout / GitHub Actions.\",\n );\n\n const slug = pushSlug(dir, opts.slug);\n progress(`pushing ${dir} as ${slug}@${branch}…`);\n // CI checkouts carry no local push meta, so a re-validation would 409\n // against the branch tip its own previous run created. Validation's\n // semantics are \"this branch's tip BECOMES the PR's source\": resolve the\n // current tip and push on top of it. A branch that does not exist yet\n // resolves to no base, which is a fresh branch — also correct.\n let tipVersionId: string | null = null;\n try {\n const tip = await apiRequest<{ versionId?: string }>(\n options,\n \"POST\",\n \"/api/public/benchmark-containers/resolve-version\",\n { slug, ref: branch },\n );\n tipVersionId = tip.versionId ?? null;\n } catch {\n tipVersionId = null;\n }\n const pushed = await push(dir, {\n slug,\n branch,\n baseVersionId: tipVersionId,\n message: `PR validation push (${provenance.commit?.slice(0, 12) ?? \"local\"})`,\n ...(provenance.actor?.name ? { author: provenance.actor.name } : {}),\n options,\n });\n progress(`pushed version ${pushed.versionId} (${pushed.contentHash.slice(0, 12)})`);\n\n // Resolve the run config by name (the stable handle CI configures) or id.\n const configs = await listRunConfigs(options);\n const runConfig =\n configs.find((c) => c.id === opts.runConfig) ??\n configs.find((c) => c.name === opts.runConfig);\n if (!runConfig) {\n const known = configs.map((c) => c.name).join(\", \") || \"(none)\";\n throw new Error(\n `Run config \"${opts.runConfig}\" not found in this project. Have: ${known}`,\n );\n }\n\n progress(`dispatching run config \"${runConfig.name}\" (${runConfig.models.join(\", \")})…`);\n const dispatched = await apiRequest<{\n versionLabel: string;\n runs: { model: string; runId: string; ok: boolean; error?: string }[];\n }>(options, \"POST\", \"/api/public/benchmark-containers/run-configs/dispatch\", {\n runConfigId: runConfig.id,\n versionId: pushed.versionId,\n ...provenance,\n });\n\n // The run's platform page. New deployments return it on the run report\n // (`url`); against an older deployment we build the same page from the\n // evaluation id, because a PR comment that cannot link the run defeats\n // the point of the comment.\n const host = (\n options.host ??\n process.env.GATEWAY_HOST ??\n \"https://withgateway.ai\"\n ).replace(/\\/+$/, \"\");\n let projectId: string | null = null;\n try {\n const projects = await apiRequest<{ data?: { id?: string }[] }>(\n options,\n \"GET\",\n \"/api/public/projects\",\n );\n projectId = projects.data?.[0]?.id ?? null;\n } catch {\n projectId = null;\n }\n const fallbackUrl = (report: RunReport): string | null => {\n if (report.url) return report.url;\n const evaluationId = report.evaluations[0]?.id;\n return projectId && evaluationId\n ? `${host}/project/${projectId}/environment/runs/${encodeURIComponent(evaluationId)}`\n : null;\n };\n\n const runs: ValidatedRun[] = [];\n for (const run of dispatched.runs) {\n if (!run.ok) {\n runs.push({\n model: run.model,\n runId: run.runId,\n report: null,\n failure: `dispatch failed: ${run.error ?? \"unknown error\"}`,\n });\n continue;\n }\n progress(`waiting on ${run.model} (run ${run.runId})…`);\n let report: RunReport | null = null;\n let failure: string | null = null;\n try {\n report = await waitForRun(run.runId, {\n timeoutMinutes: opts.timeoutMinutes ?? 45,\n options,\n onTick: (r) =>\n progress(\n `…${run.model}: ${r.status.toLowerCase()} (${r.shardsCompleted ?? 0}/${r.parallelism} shards)`,\n ),\n });\n report = { ...report, url: fallbackUrl(report) };\n if (report.status.toUpperCase() !== \"COMPLETED\") {\n failure = report.status;\n } else if (minScore !== null) {\n if (report.score === null) failure = \"completed without a score\";\n else if (report.score < minScore)\n failure = `score ${fmtScore(report.score)} < ${minScore}`;\n }\n } catch (error) {\n failure = error instanceof Error ? error.message : String(error);\n }\n runs.push({ model: run.model, runId: run.runId, report, failure });\n }\n\n const base = {\n ok: runs.length > 0 && runs.every((r) => r.failure === null),\n slug: pushed.slug,\n branch,\n versionId: pushed.versionId,\n contentHash: pushed.contentHash,\n runConfig: { id: runConfig.id, name: runConfig.name },\n runs,\n };\n return {\n ...base,\n markdown: buildMarkdown(base, minScore, {\n repoUrl: provenance.repoUrl,\n commit: provenance.commit,\n }),\n };\n}\n","/**\n * `describeWorld(slug)` — what a world holds and how each field is stored,\n * from `GET /api/public/worlds/{slug}`: the entities (primary key, unique\n * keys, relationships, row count, fields with their `[redact]` policy) and\n * the `[redact]` table itself, so `storedForms(world, field, plaintext)`\n * can compute a lookup value without Python. The CLI twin is\n * `gateway worlds describe <slug>`; for a directory the CLI asks the schema\n * runtime instead and merges the same shape.\n */\n\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\nimport type { RedactPolicy, Redaction } from \"./redaction\";\n\nexport type WorldField = {\n name: string;\n type: string | null;\n required: boolean;\n /** How the store holds it; null means in the clear (queryable by plaintext as given). */\n redaction: Redaction | null;\n};\n\nexport type WorldRelationship = {\n fields: string[];\n target: string;\n on_delete?: string;\n};\n\nexport type WorldEntityMapping = {\n localEntity: string;\n localField: string;\n depEntity: string;\n depField: string;\n /** A closed set, applied left to right before each world's own redaction. */\n transform: string[];\n};\n\nexport type WorldDependency = {\n alias: string;\n dependsOn: { slug: string | null; versionId: string };\n task: string | null;\n tools: string[];\n entities: WorldEntityMapping[];\n};\n\nexport type WorldEntity = {\n name: string;\n primaryKey: string[];\n unique: string[][];\n relationships: WorldRelationship[];\n /** Rows in the head version; null when the platform does not count this kind. */\n rowCount: number | null;\n fields: WorldField[];\n};\n\nexport type WorldDescription = {\n slug: string;\n name: string;\n description: string | null;\n kind: string;\n version: { id: string; contentHash: string; semanticVersion: string | null };\n url: string;\n hostedUrl: string | null;\n tools: { name: string; signature: string; doc: string | null }[];\n taskCount: number;\n links: { tasks: string; sessions: string };\n /** World-to-world links from `[dependencies]`, resolved at commit, with the\n * entity mappings `--across` follows. */\n dependencies?: WorldDependency[];\n entities: WorldEntity[];\n redact: RedactPolicy | null;\n};\n\n/** The world's head version, described. The route reads the head only, so a\n * `slug@ref` is refused rather than silently served as the head. */\nexport async function describeWorld(\n slug: string,\n options: WorldsClientOptions = {},\n): Promise<WorldDescription> {\n if (slug.includes(\"@\"))\n throw new Error(\n `describeWorld reads a world's head version: pass the slug without @ref (got ${slug})`,\n );\n return apiRequest<WorldDescription>(\n options,\n \"GET\",\n `/api/public/worlds/${encodeURIComponent(slug)}`,\n );\n}\n","/**\n * JSON as the Python CLI sees it, so both CLIs write the same bytes.\n *\n * `JSON.parse` + `JSON.stringify` are not enough for parity with\n * `json.loads` + `json.dumps(separators=(\",\", \":\"), ensure_ascii=False)`:\n * JavaScript loses `1.0` vs `1` (Python keeps the float), rounds integers past\n * 2^53, moves integer-like keys to the front of an object, and spells\n * exponents differently (`1e-7` vs `1e-07`). Here a number keeps its source\n * text and its Python type, an object is a Map (insertion order, always), and\n * `dumps` renders exactly what CPython renders.\n */\n\nexport class JsonNumber {\n /** The lexeme as it appeared, e.g. \"1.0\", \"-0\", \"1e21\". */\n constructor(readonly text: string) {}\n /** A float in Python's eyes: a fraction, an exponent, or a non-finite literal. */\n get isFloat(): boolean {\n return /[.eE]/.test(this.text) || /[nN]/.test(this.text);\n }\n get value(): number {\n return Number(this.text);\n }\n}\n\nexport type JsonObject = Map<string, JsonValue>;\nexport type JsonValue = null | boolean | string | JsonNumber | JsonValue[] | JsonObject;\n\nexport class JsonSyntaxError extends Error {}\n\nexport const isObject = (value: JsonValue | undefined): value is JsonObject => value instanceof Map;\n\n// ------------------------------------------------------------------ parsing\n\n/** Parse one JSON text (a line, a row, a document) into the model above.\n * Accepts what `json.loads` accepts, including NaN/Infinity literals. */\nexport function parseJson(text: string): JsonValue {\n const p = new Parser(text);\n p.skipWs();\n const value = p.value();\n p.skipWs();\n if (p.i < text.length) throw new JsonSyntaxError(`Extra data at ${p.i}`);\n return value;\n}\n\nclass Parser {\n i = 0;\n constructor(readonly s: string) {}\n\n skipWs(): void {\n const s = this.s;\n while (this.i < s.length) {\n const c = s.charCodeAt(this.i);\n if (c === 0x20 || c === 0x0a || c === 0x0d || c === 0x09) this.i++;\n else break;\n }\n }\n\n fail(what: string): never {\n throw new JsonSyntaxError(`${what} at ${this.i}`);\n }\n\n value(): JsonValue {\n const s = this.s;\n if (this.i >= s.length) this.fail(\"Expecting value\");\n const c = s[this.i]!;\n if (c === \"{\") return this.object();\n if (c === \"[\") return this.array();\n if (c === '\"') return this.string();\n if (c === \"t\") return this.literal(\"true\", true);\n if (c === \"f\") return this.literal(\"false\", false);\n if (c === \"n\") return this.literal(\"null\", null);\n if (c === \"N\") return this.literal(\"NaN\", new JsonNumber(\"NaN\"));\n if (c === \"I\") return this.literal(\"Infinity\", new JsonNumber(\"Infinity\"));\n return this.number();\n }\n\n literal<T extends JsonValue>(word: string, value: T): T {\n if (!this.s.startsWith(word, this.i)) this.fail(\"Expecting value\");\n this.i += word.length;\n return value;\n }\n\n number(): JsonNumber {\n const s = this.s;\n const start = this.i;\n if (s[this.i] === \"-\") {\n this.i++;\n if (s.startsWith(\"Infinity\", this.i)) {\n this.i += 8;\n return new JsonNumber(\"-Infinity\");\n }\n }\n const intStart = this.i;\n if (s[this.i] === \"0\") this.i++;\n else {\n while (this.i < s.length && isDigit(s.charCodeAt(this.i))) this.i++;\n if (this.i === intStart) this.fail(\"Expecting value\");\n }\n if (s[this.i] === \".\") {\n this.i++;\n const fracStart = this.i;\n while (this.i < s.length && isDigit(s.charCodeAt(this.i))) this.i++;\n if (this.i === fracStart) this.fail(\"Invalid number\");\n }\n if (s[this.i] === \"e\" || s[this.i] === \"E\") {\n this.i++;\n if (s[this.i] === \"+\" || s[this.i] === \"-\") this.i++;\n const expStart = this.i;\n while (this.i < s.length && isDigit(s.charCodeAt(this.i))) this.i++;\n if (this.i === expStart) this.fail(\"Invalid number\");\n }\n return new JsonNumber(s.slice(start, this.i));\n }\n\n string(): string {\n const s = this.s;\n this.i++; // opening quote\n let out = \"\";\n let runStart = this.i;\n for (;;) {\n if (this.i >= s.length) this.fail(\"Unterminated string\");\n const c = s.charCodeAt(this.i);\n if (c === 0x22) {\n out += s.slice(runStart, this.i);\n this.i++;\n return out;\n }\n if (c < 0x20) this.fail(\"Invalid control character\");\n if (c !== 0x5c) {\n this.i++;\n continue;\n }\n out += s.slice(runStart, this.i);\n this.i++;\n const e = s[this.i];\n switch (e) {\n case '\"':\n case \"\\\\\":\n case \"/\":\n out += e;\n break;\n case \"b\":\n out += \"\\b\";\n break;\n case \"f\":\n out += \"\\f\";\n break;\n case \"n\":\n out += \"\\n\";\n break;\n case \"r\":\n out += \"\\r\";\n break;\n case \"t\":\n out += \"\\t\";\n break;\n case \"u\": {\n const hex = s.slice(this.i + 1, this.i + 5);\n if (!/^[0-9a-fA-F]{4}$/.test(hex)) this.fail(\"Invalid \\\\u escape\");\n out += String.fromCharCode(parseInt(hex, 16));\n this.i += 4;\n break;\n }\n default:\n this.fail(\"Invalid escape\");\n }\n this.i++;\n runStart = this.i;\n }\n }\n\n array(): JsonValue[] {\n this.i++;\n const out: JsonValue[] = [];\n this.skipWs();\n if (this.s[this.i] === \"]\") {\n this.i++;\n return out;\n }\n for (;;) {\n this.skipWs();\n out.push(this.value());\n this.skipWs();\n const c = this.s[this.i];\n if (c === \",\") {\n this.i++;\n continue;\n }\n if (c === \"]\") {\n this.i++;\n return out;\n }\n this.fail(\"Expecting ',' delimiter\");\n }\n }\n\n object(): JsonObject {\n this.i++;\n const out: JsonObject = new Map();\n this.skipWs();\n if (this.s[this.i] === \"}\") {\n this.i++;\n return out;\n }\n for (;;) {\n this.skipWs();\n if (this.s[this.i] !== '\"') this.fail(\"Expecting property name enclosed in double quotes\");\n const key = this.string();\n this.skipWs();\n if (this.s[this.i] !== \":\") this.fail(\"Expecting ':' delimiter\");\n this.i++;\n this.skipWs();\n out.set(key, this.value());\n this.skipWs();\n const c = this.s[this.i];\n if (c === \",\") {\n this.i++;\n continue;\n }\n if (c === \"}\") {\n this.i++;\n return out;\n }\n this.fail(\"Expecting ',' delimiter\");\n }\n }\n}\n\nconst isDigit = (c: number): boolean => c >= 0x30 && c <= 0x39;\n\n// ------------------------------------------------------------ serialising\n\n/** `json.dumps(value, separators=(\",\", \":\"), ensure_ascii=False)`, byte for byte. */\nexport function dumps(value: JsonValue): string {\n if (value === null) return \"null\";\n if (value === true) return \"true\";\n if (value === false) return \"false\";\n if (typeof value === \"string\") return JSON.stringify(value);\n if (value instanceof JsonNumber) return numberText(value);\n if (Array.isArray(value)) return \"[\" + value.map(dumps).join(\",\") + \"]\";\n const parts: string[] = [];\n for (const [key, item] of value) parts.push(JSON.stringify(key) + \":\" + dumps(item));\n return \"{\" + parts.join(\",\") + \"}\";\n}\n\n/** How `json.dumps` spells a parsed number: ints verbatim (`-0` becomes `0`),\n * floats through `float.__repr__`, non-finite as NaN/Infinity. */\nexport function numberText(n: JsonNumber): string {\n if (!n.isFloat) return /^-0+$/.test(n.text) ? \"0\" : n.text;\n const value = n.value;\n if (Number.isNaN(value)) return \"NaN\";\n if (value === Infinity) return \"Infinity\";\n if (value === -Infinity) return \"-Infinity\";\n return pyFloatRepr(value);\n}\n\n/** `str(value)` for the values the redaction digest sees: str, int, float, bool. */\nexport function pyStr(value: string | boolean | JsonNumber): string {\n if (typeof value === \"string\") return value;\n if (typeof value === \"boolean\") return value ? \"True\" : \"False\";\n if (!value.isFloat) return numberText(value);\n const v = value.value;\n if (Number.isNaN(v)) return \"nan\";\n if (v === Infinity) return \"inf\";\n if (v === -Infinity) return \"-inf\";\n return pyFloatRepr(v);\n}\n\n/**\n * CPython's `repr(float)`: the shortest digits that round-trip (which\n * JavaScript's `String(x)` also produces), laid out Python's way — a\n * trailing `.0` on integral values, scientific notation only below 1e-4 or\n * from 1e16, and exponents of at least two digits with a sign.\n */\nexport function pyFloatRepr(x: number): string {\n if (x === 0) return Object.is(x, -0) ? \"-0.0\" : \"0.0\";\n const sign = x < 0 ? \"-\" : \"\";\n const js = String(Math.abs(x));\n const [mantissa, exponentPart] = js.split(\"e\");\n let exponent = exponentPart ? Number(exponentPart) : 0;\n const [intPart, fracPart = \"\"] = mantissa!.split(\".\");\n let digits = intPart! + fracPart;\n // decpt: how many digits sit before the decimal point (may be <= 0 or > length).\n let decpt = intPart!.length + exponent;\n const leading = digits.match(/^0*/)![0].length;\n digits = digits.slice(leading);\n decpt -= leading;\n digits = digits.replace(/0+$/, \"\");\n if (digits === \"\") return sign + \"0.0\";\n const sci = decpt - 1;\n if (sci >= -4 && sci < 16) {\n if (decpt <= 0) return sign + \"0.\" + \"0\".repeat(-decpt) + digits;\n if (decpt >= digits.length) return sign + digits + \"0\".repeat(decpt - digits.length) + \".0\";\n return sign + digits.slice(0, decpt) + \".\" + digits.slice(decpt);\n }\n exponent = sci;\n const mag = String(Math.abs(exponent)).padStart(2, \"0\");\n return sign + digits[0] + (digits.length > 1 ? \".\" + digits.slice(1) : \"\") + \"e\" + (exponent < 0 ? \"-\" : \"+\") + mag;\n}\n\n/**\n * Python's `round(x, ndigits)` for the redaction policy: an int is returned\n * unchanged, a float is correctly rounded on its exact binary value with ties\n * to even (`round(0.125, 2) == 0.12`), then re-read as the nearest double.\n */\nexport function pyRound(n: JsonNumber, ndigits: number): JsonNumber {\n if (!n.isFloat) return n;\n const x = n.value;\n if (!Number.isFinite(x)) return n;\n const sign = x < 0 ? -1 : 1;\n const magnitude = Math.abs(x);\n // Every double at or above 2^53 is an integer already.\n if (magnitude >= 9007199254740992) return new JsonNumber(pyFloatRepr(x));\n const { m, k } = exactFraction(magnitude); // magnitude = m / 2^k, m odd (or zero)\n let rounded: number;\n if (k <= ndigits) rounded = magnitude; // exact at this precision\n else if (k !== ndigits + 1) rounded = Number(magnitude.toFixed(ndigits)); // no tie possible: correctly rounded\n else {\n // Exactly k = ndigits + 1 fractional digits, the last one a 5: a tie. Half to even.\n const scaled = m * 5n ** BigInt(k); // magnitude * 10^k, an integer\n let kept = scaled / 10n; // magnitude * 10^ndigits, truncated\n if (kept % 2n === 1n) kept += 1n;\n const text = kept.toString().padStart(ndigits + 1, \"0\");\n rounded = ndigits === 0 ? Number(text) : Number(text.slice(0, -ndigits) + \".\" + text.slice(-ndigits));\n }\n return new JsonNumber(pyFloatRepr(sign * rounded));\n}\n\n/** A finite non-negative double as m / 2^k with m odd (m = 0, k = 0 for zero). */\nfunction exactFraction(x: number): { m: bigint; k: number } {\n if (x === 0) return { m: 0n, k: 0 };\n const view = new DataView(new ArrayBuffer(8));\n view.setFloat64(0, x);\n const bits = view.getBigUint64(0);\n const exponent = Number((bits >> 52n) & 0x7ffn);\n let mantissa = bits & ((1n << 52n) - 1n);\n let e: number;\n if (exponent === 0) e = -1074;\n else {\n mantissa |= 1n << 52n;\n e = exponent - 1075;\n }\n while (mantissa !== 0n && (mantissa & 1n) === 0n) {\n mantissa >>= 1n;\n e += 1;\n }\n if (e >= 0) return { m: mantissa << BigInt(e), k: 0 };\n return { m: mantissa, k: -e };\n}\n","/**\n * Named plaintext transforms for cross-world entity mappings.\n *\n * A mapping between two worlds' fields is rarely a raw equality: SpyCloud\n * keeps `phone` as bare digits where a Torchlight client sends\n * `+1 (559) 779-1433`; one world keys people by `email`, another by\n * `email_username`. A transform normalises the plaintext on BOTH sides of a\n * mapping before `storedForms` salts it under each world's slug, so a\n * cross-world query is answerable from the plaintext alone, with no stored\n * join.\n *\n * The set is closed and named — no expressions, no user code — because any\n * client must reproduce a transform from the manifest by itself. This is the\n * TypeScript twin of the Python runtime's `environment/schema/transforms.py`;\n * the golden vectors in `__tests__/transforms.test.ts` and the Python\n * `tests/environment/test_schema_transforms.py` pin the two to each other,\n * byte for byte.\n *\n * Whitespace, for `trim` and `collapse_ws`, is the ASCII set `\" \\t\\n\\r\\f\\v\"`\n * by definition (Python's `str.split()` and JavaScript's `\\s` disagree at the\n * edges of Unicode; `nfkc` first folds a no-break space into a plain one).\n */\n\nimport { createHash } from \"node:crypto\";\n\nimport { pyFloatRepr } from \"../cli/platform/worldData/json\";\n\nexport type Transform = (value: string) => string;\n\nexport const WHITESPACE = \" \\t\\n\\r\\f\\v\";\nconst WHITESPACE_EDGES = /^[ \\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 * The `gateway` command tree, with no dependency: groups hold commands, a\n * command declares its positionals and flags, help is generated from the\n * declarations so `gateway <group> --help` always matches what runs.\n *\n * Flags: `--name value`, `--name=value`, `--flag` (boolean), repeatable flags\n * collect into arrays when declared `repeat: true`. Anything after `--` is\n * positional.\n */\n\nexport type FlagSpec = {\n name: string;\n help: string;\n /** Short alias, e.g. \"m\" for --message. */\n short?: string;\n /** Boolean flags take no value. */\n boolean?: boolean;\n repeat?: boolean;\n default?: string | boolean;\n /** Environment variable that fills the flag when it is not given. */\n env?: string;\n};\n\nexport type PositionalSpec = {\n name: string;\n help: string;\n optional?: boolean;\n /** Collects every remaining positional. */\n variadic?: boolean;\n};\n\nexport type Parsed = {\n positionals: string[];\n flags: Record<string, string | boolean | string[] | undefined>;\n /** Flags the caller actually typed (defaults and env fills are not in here). */\n given: Set<string>;\n};\n\nexport type CommandSpec = {\n name: string;\n help: string;\n positionals?: PositionalSpec[];\n flags?: FlagSpec[];\n /** Long-form notes printed under the usage line in `--help`. */\n notes?: string;\n run: (args: Parsed, ctx: CommandContext) => Promise<number | void>;\n};\n\nexport type CommandContext = {\n stdout: (line: string) => void;\n stderr: (line: string) => void;\n /** Read all of stdin (for --value-less secrets, piped rows). */\n stdin: () => Promise<string>;\n /** Stdin as a stream, for inputs too large to hold (`worlds data import … -`). */\n stdinStream?: () => NodeJS.ReadableStream;\n};\n\nexport class CommandGroup {\n readonly groups = new Map<string, CommandGroup>();\n readonly commands = new Map<string, CommandSpec>();\n /** Long-form notes printed under the command list in `--help`. */\n notes?: string;\n constructor(\n readonly name: string,\n readonly help: string,\n ) {}\n group(name: string, help: string): CommandGroup {\n const existing = this.groups.get(name);\n if (existing) return existing;\n const created = new CommandGroup(name, help);\n this.groups.set(name, created);\n return created;\n }\n command(spec: CommandSpec): this {\n this.commands.set(spec.name, spec);\n return this;\n }\n}\n\nexport class CliError extends Error {\n constructor(\n message: string,\n readonly exitCode = 2,\n ) {\n super(message);\n }\n}\n\nexport function parseArgs(spec: CommandSpec, argv: string[]): Parsed {\n const flagSpecs = spec.flags ?? [];\n const byName = new Map<string, FlagSpec>();\n for (const f of flagSpecs) {\n byName.set(f.name, f);\n if (f.short) byName.set(f.short, f);\n }\n const positionals: string[] = [];\n const flags: Parsed[\"flags\"] = {};\n const given = new Set<string>();\n let onlyPositionals = false;\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i]!;\n if (onlyPositionals || !arg.startsWith(\"-\") || arg === \"-\") {\n positionals.push(arg);\n continue;\n }\n if (arg === \"--\") {\n onlyPositionals = true;\n continue;\n }\n const bare = arg.replace(/^--?/, \"\");\n const [rawName, inlineValue] = bare.includes(\"=\")\n ? [bare.slice(0, bare.indexOf(\"=\")), bare.slice(bare.indexOf(\"=\") + 1)]\n : [bare, undefined];\n const f = byName.get(rawName);\n if (!f) throw new CliError(`Unknown flag --${rawName} for ${spec.name}`);\n given.add(f.name);\n if (f.boolean) {\n flags[f.name] =\n inlineValue === undefined ? true : inlineValue !== \"false\";\n continue;\n }\n let value = inlineValue;\n if (value === undefined) {\n const next = argv[i + 1];\n if (next === undefined || (next.startsWith(\"--\") && next.length > 2))\n throw new CliError(`--${f.name} needs a value`);\n value = next;\n i++;\n }\n if (f.repeat) {\n const current = flags[f.name];\n flags[f.name] = Array.isArray(current) ? [...current, value] : [value];\n } else flags[f.name] = value;\n }\n for (const f of flagSpecs) {\n if (flags[f.name] !== undefined) continue;\n const fromEnv = f.env ? process.env[f.env] : undefined;\n if (fromEnv !== undefined && fromEnv !== \"\") flags[f.name] = fromEnv;\n else if (f.default !== undefined) flags[f.name] = f.default;\n }\n const specs = spec.positionals ?? [];\n const required = specs.filter((p) => !p.optional && !p.variadic).length;\n if (positionals.length < required)\n throw new CliError(\n `${spec.name} needs ${specs\n .slice(0, required)\n .map((p) => `<${p.name}>`)\n .join(\" \")}`,\n );\n const variadic = specs.some((p) => p.variadic);\n if (!variadic && positionals.length > specs.length)\n throw new CliError(\n `${spec.name} takes ${specs.length} argument${specs.length === 1 ? \"\" : \"s\"}, got ${positionals.length}`,\n );\n return { positionals, flags, given };\n}\n\n/** Typed accessors so commands never repeat the narrowing. */\nexport const arg = {\n str(p: Parsed, name: string): string | undefined {\n const v = p.flags[name];\n return typeof v === \"string\" ? v : undefined;\n },\n bool(p: Parsed, name: string): boolean {\n return p.flags[name] === true;\n },\n list(p: Parsed, name: string): string[] {\n const v = p.flags[name];\n if (Array.isArray(v)) return v;\n return typeof v === \"string\" ? [v] : [];\n },\n int(p: Parsed, name: string): number | undefined {\n const v = arg.str(p, name);\n if (v === undefined) return undefined;\n const n = Number(v);\n if (!Number.isInteger(n))\n throw new CliError(`--${name} must be an integer`);\n return n;\n },\n};\n\nfunction usageLine(path: string[], spec: CommandSpec): string {\n const pos = (spec.positionals ?? [])\n .map((p) =>\n p.variadic\n ? `<${p.name}...>`\n : p.optional\n ? `[${p.name}]`\n : `<${p.name}>`,\n )\n .join(\" \");\n return `${path.join(\" \")} ${pos}`.trim();\n}\n\nexport function helpFor(\n path: string[],\n node: CommandGroup | CommandSpec,\n): string {\n if (node instanceof CommandGroup) {\n const lines = [`${path.join(\" \")} — ${node.help}`, \"\"];\n for (const [name, g] of node.groups)\n lines.push(` ${name.padEnd(16)} ${g.help}`);\n for (const [name, c] of node.commands)\n lines.push(` ${name.padEnd(16)} ${c.help}`);\n if (node.notes) lines.push(\"\", node.notes);\n lines.push(\"\", `Run '${path.join(\" \")} <command> --help' for details.`);\n return lines.join(\"\\n\");\n }\n const lines = [usageLine(path, node), \"\", ` ${node.help}`];\n const pos = node.positionals ?? [];\n if (pos.length) {\n lines.push(\"\", \"Arguments:\");\n for (const p of pos) lines.push(` ${p.name.padEnd(18)} ${p.help}`);\n }\n const flags = node.flags ?? [];\n if (flags.length) {\n lines.push(\"\", \"Options:\");\n for (const f of flags) {\n const label = `--${f.name}${f.short ? `, -${f.short}` : \"\"}${f.boolean ? \"\" : \" <value>\"}`;\n const extras = [\n f.default !== undefined ? `default ${String(f.default)}` : null,\n f.env ? `env ${f.env}` : null,\n ]\n .filter(Boolean)\n .join(\", \");\n lines.push(\n ` ${label.padEnd(28)} ${f.help}${extras ? ` (${extras})` : \"\"}`,\n );\n }\n }\n if (node.notes) lines.push(\"\", node.notes);\n return lines.join(\"\\n\");\n}\n\n/** Walk the tree and run: exit code 0 on success, 2 on usage error, 1 on failure. */\nexport async function dispatch(\n root: CommandGroup,\n argv: string[],\n ctx: CommandContext,\n): Promise<number> {\n let node: CommandGroup = root;\n const path = [root.name];\n let i = 0;\n while (i < argv.length) {\n const token = argv[i]!;\n if (token === \"--help\" || token === \"-h\") {\n ctx.stdout(helpFor(path, node));\n return 0;\n }\n const group = node.groups.get(token);\n if (group) {\n node = group;\n path.push(token);\n i++;\n continue;\n }\n const command = node.commands.get(token);\n if (command) {\n const rest = argv.slice(i + 1);\n if (rest.includes(\"--help\") || rest.includes(\"-h\")) {\n ctx.stdout(helpFor([...path, token], command));\n return 0;\n }\n try {\n const parsed = parseArgs(command, rest);\n const code = await command.run(parsed, ctx);\n return code ?? 0;\n } catch (error) {\n if (error instanceof CliError) {\n ctx.stderr(error.message);\n return error.exitCode;\n }\n ctx.stderr(error instanceof Error ? error.message : String(error));\n return 1;\n }\n }\n ctx.stderr(\n `Unknown command '${token}' under '${path.join(\" \")}'.\\n\\n${helpFor(path, node)}`,\n );\n return 2;\n }\n ctx.stdout(helpFor(path, node));\n return node === root ? 0 : 2;\n}\n","import * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\n\nimport { CliError } from \"./router\";\n\n/**\n * Where the CLI's credentials come from, in this order (the same as the\n * Python CLI): explicit --host, environment (GATEWAY_HOST, GATEWAY_PUBLIC_KEY,\n * GATEWAY_SECRET_KEY / GATEWAY_API_KEY), then ~/.gateway/config.json written\n * by `gateway auth login`. `GATEWAY_ENV_FILE=path` fills the environment from\n * a KEY=value file first (see `loadEnvFile`).\n */\nexport type StoredConfig = {\n host?: string;\n public_key?: string;\n api_key?: string;\n};\n\nexport function configPath(): string {\n return path.join(\n process.env.GATEWAY_CONFIG_DIR ?? path.join(os.homedir(), \".gateway\"),\n \"config.json\",\n );\n}\n\nexport function readConfig(): StoredConfig {\n try {\n return JSON.parse(fs.readFileSync(configPath(), \"utf8\")) as StoredConfig;\n } catch {\n return {};\n }\n}\n\nexport function writeConfig(config: StoredConfig): void {\n const file = configPath();\n fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });\n fs.writeFileSync(file, JSON.stringify(config, null, 2) + \"\\n\", { mode: 0o600 });\n}\n\nexport function clearConfig(): boolean {\n try {\n fs.unlinkSync(configPath());\n return true;\n } catch {\n return false;\n }\n}\n\nexport type Credentials = { host: string; publicKey: string; secretKey: string };\n\n/** The accepted env-file form, printed by `gateway --help` and the docs. */\nexport const ENV_FILE_FORM =\n \"GATEWAY_ENV_FILE=path loads a KEY=value file first: `KEY = value`, quoted values, \" +\n \"`export KEY=value` and `#` comments are all accepted; the shell's environment wins.\";\n\n/**\n * Parse a KEY=value file the way a person writes one, not the way `source`\n * reads one. Brex retrospective: the customer's `.env` had `GATEWAY_HOST = …`\n * (spaces around `=`), which the shell refused to source and the CLI could not\n * read either. Accepted: blank lines and `#` comments, an `export ` prefix,\n * spaces around `=`, single- or double-quoted values (quotes stripped, nothing\n * inside interpreted). Not accepted: a line without `=`, which is reported by\n * number rather than skipped, because a silently dropped credential shows up\n * later as \"API key not configured\".\n */\nexport function parseEnvFile(text: string): Record<string, string> {\n const values: Record<string, string> = {};\n const lines = text.split(/\\r?\\n/);\n for (let index = 0; index < lines.length; index++) {\n const line = lines[index]!.trim();\n if (!line || line.startsWith(\"#\")) continue;\n const assignment = line.startsWith(\"export \") ? line.slice(\"export \".length).trim() : line;\n const eq = assignment.indexOf(\"=\");\n if (eq === -1) throw new CliError(`env file line ${index + 1} is not KEY=value: ${line}`);\n const key = assignment.slice(0, eq).trim();\n let value = assignment.slice(eq + 1).trim();\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key))\n throw new CliError(`env file line ${index + 1} has an invalid variable name: ${key || line}`);\n const quote = value[0];\n if ((quote === '\"' || quote === \"'\") && value.length >= 2 && value.endsWith(quote))\n value = value.slice(1, -1);\n values[key] = value;\n }\n return values;\n}\n\n/**\n * Put `GATEWAY_ENV_FILE`'s variables into the process environment, without\n * overriding anything already set there. Explicit on purpose: the CLI never\n * reads a `.env` it was not pointed at. Vendor keys named by connector.toml\n * ride along, so a local capture sees them too. Returns the keys it set.\n */\nexport function loadEnvFile(): string[] {\n const file = process.env.GATEWAY_ENV_FILE;\n if (!file) return [];\n let text: string;\n try {\n text = fs.readFileSync(file, \"utf8\");\n } catch (error) {\n throw new CliError(`GATEWAY_ENV_FILE=${file} could not be read: ${(error as Error).message}`);\n }\n const set: string[] = [];\n for (const [key, value] of Object.entries(parseEnvFile(text))) {\n if (process.env[key] !== undefined) continue;\n process.env[key] = value;\n set.push(key);\n }\n return set;\n}\n\nexport function resolveCredentials(hostFlag?: string): Credentials {\n const stored = readConfig();\n const host = (hostFlag ?? process.env.GATEWAY_HOST ?? stored.host ?? \"\").replace(/\\/+$/, \"\");\n const publicKey = process.env.GATEWAY_PUBLIC_KEY ?? stored.public_key ?? \"\";\n const secretKey =\n process.env.GATEWAY_SECRET_KEY ?? process.env.GATEWAY_API_KEY ?? stored.api_key ?? \"\";\n if (!host)\n throw new CliError(\n \"Host not configured. Pass --host, set GATEWAY_HOST, or run `gateway auth login`.\",\n );\n if (!publicKey || !secretKey)\n throw new CliError(\n \"API key not configured. Set GATEWAY_PUBLIC_KEY and GATEWAY_SECRET_KEY, or run `gateway auth login`.\",\n );\n return { host, publicKey, secretKey };\n}\n\n/** A non-2xx answer from the platform: the status is a field, never something to regex out of the text. */\nexport class ApiError extends CliError {\n constructor(\n readonly status: number,\n readonly method: string,\n readonly route: string,\n readonly text: string,\n ) {\n super(`${method} ${route} -> ${status}: ${text.slice(0, 600)}`, 1);\n }\n}\n\n/** One JSON request against the platform, Basic-authenticated with the project key. */\nexport async function api<T = unknown>(\n creds: Credentials,\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\",\n route: string,\n body?: unknown,\n init: { timeoutMs?: number } = {},\n): Promise<T> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), init.timeoutMs ?? 120_000);\n try {\n const res = await fetch(`${creds.host}${route}`, {\n method,\n headers: {\n \"content-type\": \"application/json\",\n accept: \"application/json\",\n authorization:\n \"Basic \" + Buffer.from(`${creds.publicKey}:${creds.secretKey}`).toString(\"base64\"),\n },\n ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n signal: controller.signal,\n });\n const text = await res.text();\n if (!res.ok) throw new ApiError(res.status, method, route, text);\n return (text ? JSON.parse(text) : {}) as T;\n } finally {\n clearTimeout(timer);\n }\n}\n\nexport function printJson(ctx: { stdout: (line: string) => void }, value: unknown): void {\n ctx.stdout(JSON.stringify(value, null, 2));\n}\n","import { spawn, spawnSync } from \"node:child_process\";\nimport * as fs from \"node:fs\";\nimport * as net from \"node:net\";\nimport * as path from \"node:path\";\n\nimport { CliError } from \"../router\";\nimport { type Credentials, resolveCredentials } from \"../config\";\nimport type { RuntimeRequest } from \"./client\";\n\n/**\n * The schema runtime, run on THIS machine. The npm package carries the SDK's\n * `gatewaysdk/environment` directory (stdlib-only Python, the same files the\n * platform's bridge executes), so any python3 >= 3.11 on the path runs it\n * exactly as the platform does — the same bootstrap, JSON in, JSON out. No\n * pip, no PyPI. When there is no such Python, callers fall back to\n * `POST /api/public/worlds/runtime`.\n *\n * `GATEWAY_RUNTIME=local|platform|auto` (default auto) forces one side;\n * `GATEWAY_PYTHON` names the interpreter (otherwise python3.13, python3.12,\n * python3.11, python3, python, then `uv python find` are tried in that order).\n */\n\nconst MIN_PYTHON: [number, number] = [3, 11];\nconst DIAGNOSTIC_TAIL = 600;\n\n/** The end of a failed run's output: a Python traceback names the exception last. */\nfunction tailOf(output: string): string {\n return output.length > DIAGNOSTIC_TAIL\n ? `…${output.slice(-DIAGNOSTIC_TAIL)}`\n : output;\n}\n\n/** The platform's own bootstrap: build the `gatewaysdk` package in memory from\n * the runtime root and run the bridge as __main__ (see worldSchemaRuntime.ts). */\nconst BRIDGE_BOOTSTRAP = `import sys,runpy,types,os\nroot=sys.argv[1]\npackage=types.ModuleType('gatewaysdk')\npackage.__path__=[os.path.join(root,'gatewaysdk')]\nsys.modules['gatewaysdk']=package\nrunpy.run_module('gatewaysdk.environment.schema.platform',run_name='__main__')`;\n\n/** The same, but running the schema module's own CLI (serve, connector-capture …)\n * with the arguments after the root. */\nconst MODULE_BOOTSTRAP = `import sys,runpy,types,os\nroot=sys.argv[1]\npackage=types.ModuleType('gatewaysdk')\npackage.__path__=[os.path.join(root,'gatewaysdk')]\nsys.modules['gatewaysdk']=package\nsys.argv=['gateway worlds']+sys.argv[2:]\nrunpy.run_module('gatewaysdk.environment.schema',run_name='__main__')`;\n\nexport type RuntimeMode = \"auto\" | \"local\" | \"platform\";\n\nexport function runtimeMode(): RuntimeMode {\n const raw = (process.env.GATEWAY_RUNTIME ?? \"auto\").toLowerCase();\n if (raw === \"local\" || raw === \"platform\" || raw === \"auto\") return raw;\n throw new CliError(\n `GATEWAY_RUNTIME must be local, platform or auto (got ${raw})`,\n );\n}\n\n/** Where the bundled runtime lives: `<package>/runtime` beside dist/, or the\n * monorepo's SDK source when running from the repository.\n *\n * The entry is `dist/cli.js` (the published bin) or `src/cli.ts` (from\n * source): one directory under the package root either way, so the Python\n * source is `<entry dir>/../../sdk/src` — `gatewaysdk/sdk/src`. It used to\n * walk one level too far (`<repo>/sdk/src`, which does not exist), so every\n * from-source run missed the runtime and fell back to the platform, demanding\n * a host for commands that need none (`schema init --connector salesforce`,\n * 2026-09-16). */\nexport function runtimeRoot(): string | null {\n const candidates: string[] = [];\n if (process.env.GATEWAY_RUNTIME_PATH)\n candidates.push(process.env.GATEWAY_RUNTIME_PATH);\n const entry =\n process.argv[1] && fs.existsSync(process.argv[1])\n ? path.dirname(fs.realpathSync(process.argv[1]))\n : null;\n if (entry) {\n candidates.push(path.resolve(entry, \"..\", \"runtime\"));\n candidates.push(path.resolve(entry, \"..\", \"..\", \"runtime\"));\n candidates.push(path.resolve(entry, \"..\", \"..\", \"sdk\", \"src\"));\n }\n candidates.push(path.resolve(process.cwd(), \"runtime\"));\n for (const root of candidates)\n if (\n fs.existsSync(\n path.join(root, \"gatewaysdk\", \"environment\", \"schema\", \"platform.py\"),\n )\n )\n return root;\n return null;\n}\n\nlet pythonCache: string | null | undefined;\n/** What the search saw, for the one line `pythonAdvice` prints: each candidate\n * and its version, or null when it did not run. */\nlet pythonProbes: { name: string; version: string | null }[] = [];\n\n/** Forget the cached interpreter (tests re-probe with a different PATH or env). */\nexport function resetPythonCache(): void {\n pythonCache = undefined;\n pythonProbes = [];\n}\n\n/** Versioned names first: on a Mac the bare `python3` is often the system 3.9,\n * while Homebrew, pyenv or uv put a `python3.12` beside it. Last, ask uv for\n * an interpreter it manages (`uv python find` prints a path and downloads\n * nothing). Brex retrospective: the customer had to discover GATEWAY_PYTHON\n * by hand because the CLI stopped at `python3` = 3.9. */\nconst PYTHON_CANDIDATES = [\n \"python3.13\",\n \"python3.12\",\n \"python3.11\",\n \"python3\",\n \"python\",\n];\nconst UV_FIND = [\"python\", \"find\", `>=${MIN_PYTHON.join(\".\")}`];\n\nfunction probeVersion(name: string): string | null {\n const probe = spawnSync(\n name,\n [\"-c\", \"import sys;print(sys.version_info[0],sys.version_info[1])\"],\n { encoding: \"utf8\", timeout: 10_000 },\n );\n if (probe.status !== 0) return null;\n const [major, minor] = probe.stdout.trim().split(/\\s+/).map(Number);\n return Number.isInteger(major) && Number.isInteger(minor)\n ? `${major}.${minor}`\n : null;\n}\n\nfunction atLeastMinimum(version: string): boolean {\n const [major, minor] = version.split(\".\").map(Number);\n return (\n major! > MIN_PYTHON[0] ||\n (major === MIN_PYTHON[0] && minor! >= MIN_PYTHON[1])\n );\n}\n\n/** The interpreter uv would hand out, or null when uv is absent or has none. */\nfunction uvPython(): string | null {\n const found = spawnSync(\"uv\", UV_FIND, { encoding: \"utf8\", timeout: 10_000 });\n if (found.status !== 0) return null;\n const line = found.stdout.trim().split(/\\r?\\n/)[0] ?? \"\";\n return line || null;\n}\n\n/** A python3 at or above 3.11, or null. Cached for the process. `GATEWAY_PYTHON`\n * names the interpreter and is the only candidate then; otherwise the versioned\n * names, the bare ones, then uv's. */\nexport function findPython(): string | null {\n if (pythonCache !== undefined) return pythonCache;\n const named = process.env.GATEWAY_PYTHON;\n const candidates = named ? [named] : PYTHON_CANDIDATES;\n for (const name of candidates) {\n const version = probeVersion(name);\n pythonProbes.push({ name, version });\n if (version && atLeastMinimum(version)) {\n pythonCache = name;\n return name;\n }\n }\n if (!named) {\n const fromUv = uvPython();\n const version = fromUv ? probeVersion(fromUv) : null;\n pythonProbes.push({ name: fromUv ?? \"uv python find\", version });\n if (fromUv && version && atLeastMinimum(version)) {\n pythonCache = fromUv;\n return fromUv;\n }\n }\n pythonCache = null;\n return null;\n}\n\n/** ONE actionable line for a machine without a usable Python: what was found\n * and how to point the CLI at a newer interpreter. */\nexport function pythonAdvice(): string {\n findPython();\n const floor = MIN_PYTHON.join(\".\");\n const named = process.env.GATEWAY_PYTHON;\n const seen = pythonProbes\n .filter((probe) => probe.version)\n .map((probe) => `${probe.name} is ${probe.version}`);\n const found = seen.length\n ? seen.join(\", \")\n : named\n ? `${named} did not run`\n : \"none on PATH\";\n return (\n `No python3 >= ${floor} usable (${found}); set GATEWAY_PYTHON to a newer interpreter, ` +\n `e.g. GATEWAY_PYTHON=\"$(brew --prefix python@3.12)/bin/python3.12\" or GATEWAY_PYTHON=\"$(uv python find 3.12)\".`\n );\n}\n\n/** Why `localRuntime()` answers null, in one line: the mode, the interpreter\n * or the bundled files — so a refusal never blames Python on a machine that\n * merely set GATEWAY_RUNTIME=platform. */\nexport function localRuntimeReason(): string {\n if (runtimeMode() === \"platform\")\n return \"GATEWAY_RUNTIME=platform forces the hosted side.\";\n if (!findPython()) return pythonAdvice();\n if (!runtimeRoot())\n return \"The bundled runtime is missing (set GATEWAY_RUNTIME_PATH).\";\n return \"\";\n}\n\n/** Can this machine run the runtime itself? Both a Python and the bundled files. */\nexport function localRuntime(): { python: string; root: string } | null {\n if (runtimeMode() === \"platform\") return null;\n const python = findPython();\n const root = runtimeRoot();\n if (!python || !root) {\n if (runtimeMode() === \"local\")\n throw new CliError(\n !python\n ? `GATEWAY_RUNTIME=local but ${pythonAdvice()}`\n : \"GATEWAY_RUNTIME=local but the bundled runtime is missing (set GATEWAY_RUNTIME_PATH)\",\n );\n return null;\n }\n return { python, root };\n}\n\n/** Does the local Python have PyYAML? `conform` needs it for .yaml specs. */\nexport function localPythonHasYaml(python: string): boolean {\n return (\n spawnSync(python, [\"-c\", \"import yaml\"], { timeout: 10_000 }).status === 0\n );\n}\n\n/** One bridge request through the local runtime: JSON in on stdin, JSON out. */\nexport async function localBridge<T = Record<string, unknown>>(\n request: RuntimeRequest,\n local: { python: string; root: string },\n opts: { timeoutMs?: number } = {},\n): Promise<T> {\n const input = JSON.stringify(request);\n return await new Promise<T>((resolve, reject) => {\n const child = spawn(\n local.python,\n [\"-I\", \"-B\", \"-c\", BRIDGE_BOOTSTRAP, local.root],\n {\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n // This is the author's machine running the author's world: the one\n // place the runtime may import and run a world's own Python (check's\n // handler execution, `worlds call`, `worlds test` tool cases).\n env: {\n PATH: process.env.PATH ?? \"\",\n HOME: process.env.HOME ?? \"\",\n TMPDIR: process.env.TMPDIR ?? \"\",\n GATEWAY_RUNTIME_EXECUTE: \"1\",\n },\n },\n );\n const out: Buffer[] = [];\n const err: Buffer[] = [];\n const timer = setTimeout(\n () => child.kill(\"SIGKILL\"),\n opts.timeoutMs ?? 300_000,\n );\n child.stdout.on(\"data\", (chunk: Buffer) => out.push(chunk));\n child.stderr.on(\"data\", (chunk: Buffer) => err.push(chunk));\n child.on(\"error\", (error) => {\n clearTimeout(timer);\n reject(\n new CliError(\n `local runtime could not start (${local.python}): ${error.message}`,\n 1,\n ),\n );\n });\n child.on(\"close\", (code) => {\n clearTimeout(timer);\n const text = Buffer.concat(out).toString(\"utf8\");\n const stderr = Buffer.concat(err).toString(\"utf8\");\n let payload: unknown = null;\n try {\n payload = text ? JSON.parse(text) : null;\n } catch {\n payload = null;\n }\n if (payload && typeof payload === \"object\") {\n resolve(payload as T);\n return;\n }\n reject(\n new CliError(\n `local runtime (${request.command}) exited ${code}: ${tailOf((stderr || text).trim()) || \"no output\"}`,\n 1,\n ),\n );\n });\n child.stdin.end(input);\n });\n}\n\n/** `pid <n> (<command>)` of whatever listens on `port`, from lsof when this\n * machine has it; null when nothing can be said. Best effort, never an error. */\nexport function portOwner(port: number): string | null {\n const found = spawnSync(\"lsof\", [\"-nP\", `-iTCP:${port}`, \"-sTCP:LISTEN\", \"-Fpc\"], {\n encoding: \"utf8\",\n timeout: 5_000,\n });\n if (found.error || found.status !== 0) return null;\n let pid: string | null = null;\n let command: string | null = null;\n for (const line of found.stdout.split(\"\\n\")) {\n if (line.startsWith(\"p\") && pid === null) pid = line.slice(1);\n else if (line.startsWith(\"c\") && pid !== null && command === null) command = line.slice(1);\n }\n if (pid === null) return null;\n return `pid ${pid}${command ? ` (${command})` : \"\"}`;\n}\n\n/** Refuse, by name, a port another process already holds — BEFORE the runtime\n * is spawned. The Python side refuses too, but a backgrounded serve's output\n * goes unread, and every curl after it hit whatever else answered on the port\n * (CRM dogfood, 2026-09-16): this serve never answers from another server. */\nexport async function assertPortFree(port: number, host = \"127.0.0.1\"): Promise<void> {\n const taken = await new Promise<boolean>((resolve) => {\n const probe = net.createServer();\n probe.once(\"error\", () => resolve(true));\n probe.listen(port, host, () => probe.close(() => resolve(false)));\n });\n if (!taken) return;\n const owner = portOwner(port);\n throw new CliError(\n `port ${port} on ${host} is already in use${owner ? ` by ${owner}` : \"\"}; ` +\n \"nothing was served there — pass another --port, or stop that server first\",\n 1,\n );\n}\n\n/** Run the schema module's own CLI in the foreground (serve, connector-capture …). */\nexport async function localModule(\n argv: string[],\n local: { python: string; root: string },\n opts: { env?: Record<string, string>; cwd?: string } = {},\n): Promise<number> {\n return await new Promise<number>((resolve, reject) => {\n const child = spawn(\n local.python,\n [\"-B\", \"-c\", MODULE_BOOTSTRAP, local.root, ...argv],\n {\n stdio: \"inherit\",\n cwd: opts.cwd,\n env: { ...process.env, ...opts.env },\n },\n );\n // The child owns the port (`worlds serve`); a signal that stops this\n // process must stop it too, or the server lives on with no way to reach\n // the foreground that started it. A SIGKILL, or a wrapper that swallows\n // the signal, reaches nothing here — for that the runtime's `serve`\n // watches its parent pid and closes when this process is gone.\n const forward = (signal: NodeJS.Signals) => () => {\n if (child.exitCode === null && child.signalCode === null) child.kill(signal);\n };\n const handlers: [NodeJS.Signals, () => void][] = [\n [\"SIGINT\", forward(\"SIGINT\")],\n [\"SIGTERM\", forward(\"SIGTERM\")],\n [\"SIGHUP\", forward(\"SIGHUP\")],\n ];\n for (const [signal, handler] of handlers) process.on(signal, handler);\n const release = () => {\n for (const [signal, handler] of handlers) process.off(signal, handler);\n };\n child.on(\"error\", (error) => {\n release();\n reject(\n new CliError(\n `local runtime could not start (${local.python}): ${error.message}`,\n 1,\n ),\n );\n });\n child.on(\"close\", (code, signal) => {\n release();\n resolve(code ?? (signal ? 130 : 1));\n });\n });\n}\n\n/** Credentials when the platform may be needed; null when a local runtime\n * will do and none are configured (a `schema check` needs no login). */\nexport function credentialsForRuntime(hostFlag?: string): Credentials | null {\n try {\n return resolveCredentials(hostFlag);\n } catch (error) {\n if (error instanceof CliError && localRuntime()) return null;\n throw error;\n }\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport { CliError } from \"../router\";\nimport { localBridge, localPythonHasYaml, localRuntime, localRuntimeReason } from \"./local\";\nimport type { Credentials } from \"../config\";\n\n/**\n * The wire to the schema runtime, which is Python and runs on the platform:\n * a world directory goes up as `[{path, content b64}]`, one bridge request\n * comes back verbatim, and any files in the answer land back in the\n * directory. Nothing here interprets a contract — that is the bridge's job.\n */\n\nexport type WorldFile = { path: string; content: string };\n\n/** Directories that are never part of a world's files. */\nconst SKIP_DIRS = new Set([\"__pycache__\", \".git\", \"node_modules\", \".gateway\"]);\n\n/** Every file under `dir` as base64 entries with forward-slash relative paths,\n * sorted so the same tree always produces the same request. */\n/** Compiled snapshots (`db/state.*`, `scenarios/<name>/state.*`) are build outputs\n * of the tree's data, never inputs: the runtime rebuilds them from the journals\n * and strips them from what it returns, and a real world's snapshots alone can\n * exceed the bridge's 64 MiB request cap. */\nconst BUILD_OUTPUT = /(^|\\/)state\\.(sqlite|json)$/;\n\nexport function isBuildOutput(relPath: string): boolean {\n return BUILD_OUTPUT.test(relPath);\n}\n\nexport function readWorldFiles(dir: string, opts: { buildOutputs?: boolean } = {}): WorldFile[] {\n if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())\n throw new CliError(`Not a directory: ${dir}`);\n const out: WorldFile[] = [];\n const walk = (rel: string) => {\n const abs = rel ? path.join(dir, rel) : dir;\n const entries = fs.readdirSync(abs, { withFileTypes: true });\n entries.sort((a, b) => a.name.localeCompare(b.name));\n for (const entry of entries) {\n const childRel = rel ? `${rel}/${entry.name}` : entry.name;\n if (entry.isDirectory()) {\n if (!SKIP_DIRS.has(entry.name)) walk(childRel);\n } else if (entry.isFile()) {\n if (!opts.buildOutputs && isBuildOutput(childRel)) continue;\n out.push({\n path: childRel,\n content: fs.readFileSync(path.join(dir, childRel)).toString(\"base64\"),\n });\n }\n }\n };\n walk(\"\");\n return out.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));\n}\n\nfunction assertSafeRelPath(rel: string): void {\n const parts = rel.split(\"/\");\n if (\n !rel ||\n rel.startsWith(\"/\") ||\n rel.includes(\"\\\\\") ||\n /^[A-Za-z]:/.test(rel) ||\n parts.some((p) => p === \"\" || p === \".\" || p === \"..\")\n )\n throw new CliError(`The runtime returned an unsafe file path: ${rel}`, 1);\n}\n\n/** Write bridge files into `dir`. With `clean`, files the runtime did not\n * return are removed first (the skipped dirs are left alone), so the tree\n * becomes exactly what the runtime holds. Returns the written paths. */\nexport function writeWorldFiles(\n dir: string,\n files: WorldFile[],\n opts: { clean?: boolean } = {},\n): string[] {\n for (const file of files) assertSafeRelPath(file.path);\n if (opts.clean && fs.existsSync(dir)) {\n const keep = new Set(files.map((f) => f.path));\n for (const existing of readWorldFiles(dir)) {\n if (!keep.has(existing.path)) fs.rmSync(path.join(dir, existing.path));\n }\n pruneEmptyDirs(dir);\n }\n fs.mkdirSync(dir, { recursive: true });\n const written: string[] = [];\n for (const file of files) {\n const target = path.join(dir, file.path);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n fs.writeFileSync(target, Buffer.from(file.content, \"base64\"));\n written.push(file.path);\n }\n return written;\n}\n\nfunction pruneEmptyDirs(root: string): void {\n const walk = (abs: string): boolean => {\n let empty = true;\n for (const entry of fs.readdirSync(abs, { withFileTypes: true })) {\n const child = path.join(abs, entry.name);\n if (entry.isDirectory()) {\n if (SKIP_DIRS.has(entry.name)) {\n empty = false;\n continue;\n }\n if (walk(child)) fs.rmdirSync(child);\n else empty = false;\n } else empty = false;\n }\n return empty;\n };\n walk(root);\n}\n\n/** The bridge's structured diagnostic, exactly as the Python ContractError\n * carries it (`code`, `message`, `path`, `schema_path`, plus context). */\nexport type BridgeErrorDetail = {\n code: string;\n message: string;\n path?: string;\n schema_path?: string;\n [key: string]: unknown;\n};\n\n/** Rendered the way the Python CLI prints a ContractError:\n * `{code} at {schema_path or path or '/'}: {message}`. */\nexport function formatBridgeError(detail: BridgeErrorDetail): string {\n const where = detail.schema_path || detail.path || \"/\";\n return `${detail.code} at ${where}: ${detail.message}`;\n}\n\nexport class BridgeRejected extends CliError {\n constructor(readonly detail: BridgeErrorDetail) {\n super(formatBridgeError(detail), 1);\n }\n}\n\nexport function detailFrom(payload: unknown): BridgeErrorDetail | null {\n if (!payload || typeof payload !== \"object\") return null;\n const error = (payload as { error?: unknown }).error;\n if (!error || typeof error !== \"object\") return null;\n const detail = error as Record<string, unknown>;\n if (typeof detail.code !== \"string\" || typeof detail.message !== \"string\") return null;\n return detail as BridgeErrorDetail;\n}\n\nexport type RuntimeRequest = { command: string } & Record<string, unknown>;\n\n/**\n * How a world directory travels on a request that runs it (check, test, call):\n * in place, as `world`, when the bundled runtime runs on this machine — so the\n * `[dependencies]` paths beside it resolve and its handlers may run — and as\n * `files` when the platform's bridge answers, which takes a tree and runs no\n * authored code.\n */\nexport function worldPayload(dir: string): { world: string } | { files: WorldFile[] } {\n const abs = path.resolve(dir);\n if (!fs.existsSync(abs) || !fs.statSync(abs).isDirectory()) throw new CliError(`Not a directory: ${abs}`);\n return localRuntime() ? { world: abs } : { files: readWorldFiles(abs) };\n}\n\n/**\n * `POST /api/public/worlds/runtime` with the bridge request verbatim. A\n * rejection — whether the platform relays it with a 4xx or as a 200 with\n * `status: \"rejected\"` — becomes a BridgeRejected; anything else non-OK is a\n * plain CliError with the status and body excerpt.\n */\nexport async function runtime<T extends Record<string, unknown> = Record<string, unknown>>(\n creds: Credentials | null,\n request: RuntimeRequest,\n opts: { timeoutMs?: number } = {},\n): Promise<T> {\n // This machine first, when it can: the bundled runtime with a local\n // python3 is what the platform runs anyway, minus the round trip. A .yaml\n // conform spec needs PyYAML, which the vendored runtime does not carry.\n const local = localRuntime();\n const yamlSpec =\n request.command === \"conform\" &&\n Array.isArray(request.openapi) &&\n (request.openapi as { path?: string }[]).some((doc) => /\\.ya?ml$/i.test(doc.path ?? \"\"));\n if (local && !(yamlSpec && !localPythonHasYaml(local.python))) {\n const payload = await localBridge<Record<string, unknown>>(request, local, opts);\n const detail = detailFrom(payload);\n if (detail) throw new BridgeRejected(detail);\n return payload as T;\n }\n if (!creds)\n throw new CliError(\n \"This needs the schema runtime (the CLI bundles it) or platform credentials (`gateway auth login`). \" +\n localRuntimeReason(),\n );\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), opts.timeoutMs ?? 180_000);\n const route = \"/api/public/worlds/runtime\";\n try {\n const res = await fetch(`${creds.host}${route}`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n accept: \"application/json\",\n authorization:\n \"Basic \" + Buffer.from(`${creds.publicKey}:${creds.secretKey}`).toString(\"base64\"),\n },\n body: JSON.stringify(request),\n signal: controller.signal,\n });\n const text = await res.text();\n let payload: unknown = null;\n try {\n payload = text ? JSON.parse(text) : {};\n } catch {\n payload = null;\n }\n const detail = detailFrom(payload);\n if (detail) throw new BridgeRejected(detail);\n if (!res.ok)\n throw new CliError(`POST ${route} (${request.command}) -> ${res.status}: ${text.slice(0, 600)}`, 1);\n if (payload === null) throw new CliError(`POST ${route} (${request.command}) returned non-JSON`, 1);\n return payload as T;\n } finally {\n clearTimeout(timer);\n }\n}\n\n/** Basic-auth headers for the few non-runtime routes this track calls. */\nexport function authHeaders(creds: Credentials): Record<string, string> {\n return {\n accept: \"application/json\",\n authorization:\n \"Basic \" + Buffer.from(`${creds.publicKey}:${creds.secretKey}`).toString(\"base64\"),\n };\n}\n\n/** Strip the `files` echo from a bridge report before printing it. */\nexport function withoutFiles<T extends Record<string, unknown>>(report: T): Omit<T, \"files\"> {\n const { files: _files, ...rest } = report;\n return rest;\n}\n\n/** JSON with sorted keys, the way the Python CLI prints bridge reports. */\nexport function sortedJson(value: unknown, indent = 2): string {\n const sort = (v: unknown): unknown => {\n if (Array.isArray(v)) return v.map(sort);\n if (v && typeof v === \"object\") {\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(v as Record<string, unknown>).sort())\n out[key] = sort((v as Record<string, unknown>)[key]);\n return out;\n }\n return v;\n };\n return JSON.stringify(sort(value), null, indent);\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport type { Credentials } from \"../config\";\nimport { CliError } from \"../router\";\nimport type { WorldQueryAcrossResult } from \"../../worlds/query\";\nimport {\n BridgeRejected,\n detailFrom,\n readWorldFiles,\n runtime,\n writeWorldFiles,\n type WorldFile,\n} from \"./client\";\nimport { localBridge, localRuntime, localRuntimeReason } from \"./local\";\n\n/**\n * Rows into, and counts out of, a world that lives in a LOCAL directory. The\n * `worlds data import|show` commands (registered by the platform track) call\n * these two for the directory case; a slug goes to the platform's world data\n * routes instead. The gate is the world's own contract, run by the platform\n * runtime: a bad row is refused with the field named and nothing is written.\n */\n\nexport type Rows = Record<string, Record<string, unknown>[]>;\nexport type ImportMode = \"append\" | \"replace\";\n\nexport type LocalImportResult = {\n kind: string;\n entity_counts: Record<string, number>;\n changed: boolean;\n /** Build outputs (`db/state.*`) dropped because the journals they were built from changed. */\n dropped_build_outputs?: string[];\n next?: string;\n};\n\nexport async function importLocalWorldData(\n dir: string,\n rows: Rows,\n opts: { mode?: ImportMode; merge?: \"upsert\" | \"fill\"; redact?: \"off\" | \"apply\" | \"refuse\" },\n creds: Credentials | null,\n): Promise<LocalImportResult> {\n const res = await runtime<{\n kind?: string;\n entity_counts?: Record<string, number>;\n changed?: boolean;\n files?: WorldFile[];\n }>(creds, {\n command: \"import-data\",\n files: readWorldFiles(dir),\n rows,\n mode: opts.mode ?? \"append\",\n ...(opts.merge && opts.merge !== \"upsert\" ? { merge: opts.merge } : {}),\n ...(opts.redact && opts.redact !== \"off\" ? { redact: opts.redact } : {}),\n });\n if (res.files?.length) writeWorldFiles(dir, res.files);\n // Snapshots are build outputs, not tree files: the runtime answers without\n // them, and the ones on disk were built from the journals BEFORE this import.\n // A served world ignores a stale snapshot and replays the journals, but the\n // files would still sit there claiming an older state — drop them, and let\n // `worlds schema compile` build them again from the data that is there now.\n const dropped = res.changed ? dropBuildOutputs(dir) : [];\n return {\n kind: res.kind ?? \"unknown\",\n entity_counts: res.entity_counts ?? {},\n changed: Boolean(res.changed),\n ...(dropped.length\n ? {\n dropped_build_outputs: dropped,\n next: `gateway worlds schema compile ${dir} # rebuilds the snapshots from the imported data`,\n }\n : {}),\n };\n}\n\nconst BUILD_OUTPUT = /(^|\\/)state\\.(sqlite|json)$/;\n\n/** Remove the compiled snapshots (`db/state.*`, `scenarios/<name>/state.*`)\n * that no longer match the tree's journals. */\nexport function dropBuildOutputs(dir: string): string[] {\n const dropped: string[] = [];\n for (const file of readWorldFiles(dir, { buildOutputs: true })) {\n if (!BUILD_OUTPUT.test(file.path)) continue;\n fs.rmSync(path.join(dir, file.path), { force: true });\n dropped.push(file.path);\n }\n return dropped;\n}\n\n/**\n * The same bridge import over the tree, with the answered files discarded:\n * the rows are checked through the world's contract and nothing on disk\n * changes. A refused row surfaces as a BridgeRejected, as an import would.\n */\nexport async function checkLocalWorldData(\n dir: string,\n rows: Rows,\n creds: Credentials | null,\n opts: { redact?: \"off\" | \"apply\" | \"refuse\" } = {},\n): Promise<LocalImportResult> {\n const res = await runtime<{\n kind?: string;\n entity_counts?: Record<string, number>;\n changed?: boolean;\n }>(creds, {\n command: \"import-data\",\n files: readWorldFiles(dir),\n rows,\n mode: \"append\",\n ...(opts.redact && opts.redact !== \"off\" ? { redact: opts.redact } : {}),\n });\n return {\n kind: res.kind ?? \"unknown\",\n entity_counts: res.entity_counts ?? {},\n changed: Boolean(res.changed),\n };\n}\n\nexport type LocalShowResult = {\n kind: string;\n entity_counts?: Record<string, number>;\n entity?: string;\n rows?: Record<string, unknown>[];\n};\n\nexport async function showLocalWorldData(\n dir: string,\n entity: string | undefined,\n creds: Credentials | null,\n): Promise<LocalShowResult> {\n const res = await runtime<{\n kind?: string;\n entity_counts?: Record<string, number>;\n rows?: Record<string, unknown>[];\n }>(creds, {\n command: \"counts\",\n files: readWorldFiles(dir),\n ...(entity ? { entity } : {}),\n });\n const out: LocalShowResult = { kind: res.kind ?? \"unknown\" };\n if (entity) {\n out.entity = entity;\n out.rows = res.rows ?? [];\n } else out.entity_counts = res.entity_counts ?? {};\n return out;\n}\n\n/** field → stored value, or a list of them (any of). */\nexport type LocalQueryWhere = Record<string, string | string[]>;\n\nexport type LocalQueryOptions = {\n /** The `where` values are plaintext: the runtime resolves each to its stored form first. */\n resolve?: boolean;\n limit?: number;\n offset?: number;\n /** Read the rows a session opened in this scenario starts from (schema worlds). */\n scenario?: string;\n};\n\nexport type LocalQueryResult = {\n kind?: string;\n entity: string;\n scenario?: string;\n rows: Record<string, unknown>[];\n count: number;\n total: number | null;\n limit: number;\n offset: number;\n /** With `resolve`: the stored forms each field was matched against (`[]` for a dropped field). */\n resolved?: Record<string, (string | number)[]>;\n};\n\n/**\n * The bridge's `query` over the tree: one entity's rows matching `where`.\n * A refused query (unknown entity or field) surfaces as a BridgeRejected.\n */\nexport async function queryLocalWorldData(\n dir: string,\n entity: string,\n where: LocalQueryWhere,\n opts: LocalQueryOptions,\n creds: Credentials | null,\n): Promise<LocalQueryResult> {\n const res = await runtime<{\n kind?: string;\n entity?: string;\n rows?: Record<string, unknown>[];\n count?: number;\n total?: number | null;\n limit?: number;\n offset?: number;\n scenario?: string;\n resolved?: Record<string, (string | number)[]>;\n }>(creds, {\n command: \"query\",\n files: readWorldFiles(dir),\n entity,\n ...(Object.keys(where).length ? { where } : {}),\n ...(opts.limit !== undefined ? { limit: opts.limit } : {}),\n ...(opts.offset !== undefined ? { offset: opts.offset } : {}),\n ...(opts.resolve ? { resolve: true } : {}),\n ...(opts.scenario ? { scenario: opts.scenario } : {}),\n });\n const rows = res.rows ?? [];\n return {\n ...(res.kind ? { kind: res.kind } : {}),\n entity: res.entity ?? entity,\n ...(res.scenario ? { scenario: res.scenario } : {}),\n rows,\n count: res.count ?? rows.length,\n total: res.total ?? null,\n limit: res.limit ?? opts.limit ?? rows.length,\n offset: res.offset ?? opts.offset ?? 0,\n ...(res.resolved ? { resolved: res.resolved } : {}),\n };\n}\n\n/** A local across answer: the platform's groups, each world named by its\n * manifest name (the root) or its pin's slug (a dependency); no version ids,\n * since the trees are read where they sit. */\nexport type LocalQueryAcrossResult = {\n kind?: string;\n entity: string;\n groups: (Omit<WorldQueryAcrossResult[\"groups\"][number], \"world\"> & { world: { slug: string; alias: string | null } })[];\n compare?: WorldQueryAcrossResult[\"compare\"];\n};\n\n/**\n * The bridge's `query` with `across` over the tree in place: the root's rows\n * and, per `[dependencies.<alias>.entities]` mapping that carries a `where`\n * field, the linked world's, read at its `path`. Needs the bundled runtime on\n * this machine, as the paths beside the tree must resolve.\n */\nexport async function queryLocalWorldDataAcross(\n dir: string,\n entity: string,\n where: LocalQueryWhere,\n opts: LocalQueryOptions & { compare?: boolean },\n): Promise<LocalQueryAcrossResult> {\n const local = localRuntime();\n if (!local)\n throw new CliError(\n \"`--across` on a directory reads the linked worlds at their paths, so it needs the bundled runtime on this machine. \" +\n localRuntimeReason(),\n 1,\n );\n const payload = await localBridge<Record<string, unknown>>(\n {\n command: \"query\",\n world: path.resolve(dir),\n entity,\n across: true,\n ...(opts.compare ? { compare: true } : {}),\n ...(Object.keys(where).length ? { where } : {}),\n ...(opts.limit !== undefined ? { limit: opts.limit } : {}),\n ...(opts.offset !== undefined ? { offset: opts.offset } : {}),\n ...(opts.resolve ? { resolve: true } : {}),\n ...(opts.scenario ? { scenario: opts.scenario } : {}),\n },\n local,\n );\n const detail = detailFrom(payload);\n if (detail) throw new BridgeRejected(detail);\n return payload as unknown as LocalQueryAcrossResult;\n}\n\n// ---------------------------------------------------------------- tool calls\n\nexport type LocalIngestRefusal = { index: number | null; tool: string | null; reason: string; pointer?: string };\n\n/** One `[[sources]]` of a mapping in the report: what it saw and what it did not touch. */\nexport type LocalIngestSource = {\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 unmapped_fields: Record<string, string>;\n /** Entity fields the source never sets, per entity it lands in. */\n unset_fields: Record<string, string[]>;\n};\n\n/** The bridge's `ingest-calls` report (the Python `ingest.ingest_records`). */\nexport type LocalIngestResult = {\n /** How the rows were produced: a declared mapping, the operations' projection, or rows as given. */\n via?: \"map\" | \"operations\" | \"rows\" | \"transform\";\n records: number;\n ingested: number;\n skipped: Record<string, number>;\n refusals: LocalIngestRefusal[];\n rows: Record<string, number>;\n /** The projected rows themselves, as the tools returned them (before any redaction). */\n projected?: Rows;\n /** `via: \"map\"`: each source's accounting. */\n sources?: LocalIngestSource[];\n /** `via: \"map\"` with `unmatched = \"skip\"`: records no source claimed, by tool name. */\n unmatched?: Record<string, number>;\n /** `via: \"operations\"`: that the rows came through the operation projection, not a mapping. */\n note?: string;\n dry_run: boolean;\n redact: \"off\" | \"apply\" | \"refuse\";\n changed: boolean;\n kind?: string;\n entity_counts?: Record<string, number>;\n batch?: string | null;\n};\n\n/**\n * Tool-call records into a world in a LOCAL directory, through the runtime's\n * `ingest-calls`: each record's tool resolves to an operation of the world's\n * `connector.toml`, its result goes through that operation's projection the\n * way a capture does, and the rows through the world's contract. An unknown\n * tool is a refusal in the report (nothing written); a row the contract\n * refuses surfaces as a BridgeRejected, as an import would. Redaction is\n * optional and off by default. With `dryRun` the tree is untouched.\n */\nexport async function ingestLocalToolCalls(\n dir: string,\n records: unknown[],\n opts: { redact?: \"off\" | \"apply\" | \"refuse\"; dryRun?: boolean; mode?: ImportMode; map?: string | Record<string, unknown> },\n creds: Credentials | null,\n): Promise<LocalIngestResult> {\n const res = await runtime<Partial<LocalIngestResult> & { files?: WorldFile[] }>(creds, {\n command: \"ingest-calls\",\n files: readWorldFiles(dir),\n records,\n mode: opts.mode ?? \"append\",\n ...(opts.dryRun ? { dry_run: true } : {}),\n ...(opts.redact && opts.redact !== \"off\" ? { redact: opts.redact } : {}),\n ...(opts.map !== undefined ? { map: opts.map } : {}),\n });\n if (!opts.dryRun && res.files?.length) writeWorldFiles(dir, res.files);\n if (res.changed) dropBuildOutputs(dir);\n return {\n ...(res.via ? { via: res.via } : {}),\n ...(res.sources ? { sources: res.sources } : {}),\n ...(res.unmatched ? { unmatched: res.unmatched } : {}),\n ...(res.note ? { note: res.note } : {}),\n records: res.records ?? records.length,\n ingested: res.ingested ?? 0,\n skipped: res.skipped ?? {},\n refusals: res.refusals ?? [],\n rows: res.rows ?? {},\n ...(res.projected ? { projected: res.projected } : {}),\n dry_run: Boolean(res.dry_run ?? opts.dryRun),\n redact: res.redact ?? opts.redact ?? \"off\",\n changed: Boolean(res.changed),\n ...(res.kind ? { kind: res.kind } : {}),\n ...(res.entity_counts ? { entity_counts: res.entity_counts } : {}),\n ...(res.batch !== undefined ? { batch: res.batch } : {}),\n };\n}\n","import { spawn } from \"node:child_process\";\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport { createRequire } from \"node:module\";\n\nimport { CliError } from \"../../router\";\nimport type { Rows } from \"../rows\";\n\n/**\n * `--transform`: the agent's own code turns records into rows (the Python\n * `schema.transform`, wrapper for wrapper). A script — `.py`, or `.ts` /\n * `.mjs` / `.js` / `.cjs` for node — either exports `transform(records) ->\n * {entity: [rows]}` (node: `transform` or the default export) or reads the\n * records as JSONL on stdin and prints the rows document on stdout.\n *\n * The script runs in a subprocess with a time limit, its stderr passed\n * through. The wrapper disables sockets (Python) and `net`/`tls`/`http`/\n * `dgram`/`fetch` (node) before the script loads, and the child gets no\n * `GATEWAY_*` or proxy variables. That is a guard, not a sandbox: a\n * transform is the agent's own code, run on the agent's own machine.\n */\n\nexport const DEFAULT_TRANSFORM_TIMEOUT_MS = 120_000;\nexport const NODE_SUFFIXES = [\".ts\", \".mts\", \".mjs\", \".js\", \".cjs\"];\nexport const PYTHON_SUFFIXES = [\".py\"];\nconst SCRUBBED = /^(GATEWAY_|HTTPS?_PROXY$|ALL_PROXY$|https?_proxy$|all_proxy$)/;\n\nexport const PY_WRAPPER = `\nimport io, json, runpy, socket, sys\n\ndef _deny(*args, **kwargs):\n raise RuntimeError(\"network is disabled in a transform\")\n\nclass _Denied(socket.socket):\n def __init__(self, *args, **kwargs):\n _deny()\n\nsocket.socket = _Denied\nsocket.SocketType = _Denied\nsocket.create_connection = _deny\nsocket.getaddrinfo = _deny\n\ntext = sys.stdin.read()\nrecords = [json.loads(line) for line in text.splitlines() if line.strip()]\nsys.stdin = io.StringIO(text)\ncaptured = io.StringIO()\nreal = sys.stdout\nsys.stdout = captured\ntry:\n namespace = runpy.run_path(sys.argv[1], run_name=\"__main__\")\nfinally:\n sys.stdout = real\nfn = namespace.get(\"transform\")\nif callable(fn):\n out = fn(records)\nelse:\n printed = captured.getvalue().strip()\n if not printed:\n sys.stderr.write(\"the transform defines no transform(records) and printed nothing\\\\n\")\n sys.exit(3)\n out = json.loads(printed)\nreal.write(json.dumps(out))\n`;\n\nexport const NODE_WRAPPER = `\nimport { pathToFileURL } from \"node:url\";\nimport net from \"node:net\";\nimport tls from \"node:tls\";\nimport http from \"node:http\";\nimport https from \"node:https\";\nimport dgram from \"node:dgram\";\n\nconst deny = () => { throw new Error(\"network is disabled in a transform\"); };\nnet.Socket.prototype.connect = deny;\nnet.connect = deny;\nnet.createConnection = deny;\ntls.connect = deny;\nhttp.request = deny;\nhttp.get = deny;\nhttps.request = deny;\nhttps.get = deny;\ndgram.createSocket = deny;\nglobalThis.fetch = deny;\n\nconst module = await import(pathToFileURL(process.argv[2]).href);\nconst fn = typeof module.transform === \"function\" ? module.transform : typeof module.default === \"function\" ? module.default : null;\nif (fn) {\n const chunks = [];\n for await (const chunk of process.stdin) chunks.push(chunk);\n const text = Buffer.concat(chunks).toString(\"utf8\");\n const records = text.split(\"\\\\n\").filter((line) => line.trim()).map((line) => JSON.parse(line));\n const out = await fn(records);\n process.stdout.write(JSON.stringify(out));\n}\n`;\n\nconst isObject = (value: unknown): value is Record<string, unknown> => typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/** `value` as the rows document `{entity: [rows]}`, or a CliError saying what shape it has instead. */\nexport function checkRows(value: unknown, where: string): Rows {\n if (!isObject(value)) throw new CliError(`${where} must return {entity: [rows]}; got ${value === null ? \"null\" : Array.isArray(value) ? \"an array\" : typeof value}`, 1);\n for (const [entity, listed] of Object.entries(value)) {\n if (!Array.isArray(listed)) throw new CliError(`${where}: ${entity} must be a list of rows; got ${listed === null ? \"null\" : typeof listed}`, 1);\n listed.forEach((row, index) => {\n if (!isObject(row)) throw new CliError(`${where}: ${entity}[${index}] is not an object`, 1);\n });\n }\n return value as Rows;\n}\n\n/**\n * How this node runs a `.ts` transform: built-in type stripping from Node\n * 22.6 on; before that, the `tsx` command-line entry when tsx is installed\n * beside the CLI (a dev dependency here, present on CI's Node 20); otherwise\n * a refusal that names both options instead of a stack trace from node.\n * Returns the argv prefix that goes in front of the wrapper.\n */\nfunction typescriptPrefix(): string[] {\n const [major, minor] = process.versions.node.split(\".\").map(Number);\n if (!process.env.GATEWAY_NODE && (major > 22 || (major === 22 && minor >= 6))) return [\"--experimental-strip-types\", \"--no-warnings\"];\n try {\n return [createRequire(import.meta.url).resolve(\"tsx/cli\")];\n } catch {\n throw new CliError(\n `a .ts transform needs Node 22.6 or newer (built-in type stripping; this is ${process.versions.node}) or the tsx package installed beside the CLI; write the transform as .mjs or .py, or set GATEWAY_NODE to a newer node`,\n 1,\n );\n }\n}\n\nfunction command(script: string, wrapperDir: string): { file: string; args: string[] } {\n const suffix = path.extname(script).toLowerCase();\n if (PYTHON_SUFFIXES.includes(suffix)) return { file: process.env.GATEWAY_PYTHON || \"python3\", args: [\"-c\", PY_WRAPPER, script] };\n if (NODE_SUFFIXES.includes(suffix)) {\n const wrapper = path.join(wrapperDir, \"transform-wrapper.mjs\");\n fs.writeFileSync(wrapper, NODE_WRAPPER);\n const flags = suffix === \".ts\" || suffix === \".mts\" ? typescriptPrefix() : [];\n return { file: process.env.GATEWAY_NODE || process.execPath, args: [...flags, wrapper, script] };\n }\n throw new CliError(`${path.basename(script)}: a transform script is .py, .ts, .mjs, .js or .cjs`, 1);\n}\n\nconst tail = (stderr: string, lines = 12): string => {\n const kept = stderr\n .split(\"\\n\")\n .filter((line) => line.trim())\n .slice(-lines);\n return kept.length ? \"\\n\" + kept.join(\"\\n\") : \"\";\n};\n\n/**\n * Run `script` over `records`: the rows document it returns and its stderr.\n * A non-zero exit, a timeout, or output that is not the rows document is a\n * CliError (exit 1) carrying the tail of the script's stderr.\n */\nexport async function runTransform(script: string, records: unknown[], opts: { timeoutMs?: number } = {}): Promise<{ rows: Rows; stderr: string }> {\n if (!fs.existsSync(script) || !fs.statSync(script).isFile()) throw new CliError(`no transform script at ${script}`, 1);\n const resolved = path.resolve(script);\n const name = path.basename(script);\n const timeoutMs = opts.timeoutMs ?? DEFAULT_TRANSFORM_TIMEOUT_MS;\n const scratch = fs.mkdtempSync(path.join(os.tmpdir(), \"gateway-transform-\"));\n try {\n const { file, args } = command(resolved, scratch);\n const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !SCRUBBED.test(key)));\n const done = await new Promise<{ code: number | null; stdout: string; stderr: string; timedOut: boolean }>((resolve, reject) => {\n const child = spawn(file, args, { cwd: path.dirname(resolved), env, stdio: [\"pipe\", \"pipe\", \"pipe\"] });\n let stdout = \"\";\n let stderr = \"\";\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n child.kill(\"SIGKILL\");\n }, timeoutMs);\n child.stdout.setEncoding(\"utf8\").on(\"data\", (chunk: string) => (stdout += chunk));\n child.stderr.setEncoding(\"utf8\").on(\"data\", (chunk: string) => (stderr += chunk));\n child.on(\"error\", (error) => {\n clearTimeout(timer);\n reject(new CliError(`${name}: cannot run ${file}: ${error.message}`, 1));\n });\n child.on(\"close\", (code) => {\n clearTimeout(timer);\n resolve({ code, stdout, stderr, timedOut });\n });\n child.stdin.on(\"error\", () => undefined);\n child.stdin.end(records.map((record) => JSON.stringify(record) + \"\\n\").join(\"\"));\n });\n if (done.timedOut) throw new CliError(`${name} timed out after ${timeoutMs / 1000}s${tail(done.stderr)}`, 1);\n if (done.code !== 0) throw new CliError(`${name} exited ${done.code ?? \"?\"}${tail(done.stderr)}`, 1);\n let value: unknown;\n try {\n value = done.stdout.trim() ? JSON.parse(done.stdout) : null;\n } catch {\n throw new CliError(`${name} printed something other than the rows document${tail(done.stderr)}`, 1);\n }\n return { rows: checkRows(value, name), stderr: done.stderr };\n } finally {\n fs.rmSync(scratch, { recursive: true, force: true });\n }\n}\n\n/** A transform given to the SDK: a function, or a script path run as above. */\nexport type TransformLike = string | ((records: unknown[]) => Rows | Promise<Rows>);\n\nexport async function transformRecords(transform: TransformLike, records: unknown[], opts: { timeoutMs?: number } = {}): Promise<{ rows: Rows; stderr: string }> {\n if (typeof transform === \"function\") return { rows: checkRows(await transform(records), \"transform(records)\"), stderr: \"\" };\n return runTransform(transform, records, opts);\n}\n","import { createHash } from \"node:crypto\";\nimport * as fs from \"node:fs\";\n\nimport { api, type Credentials } from \"../../config\";\nimport { CliError } from \"../../router\";\nimport type { BuiltChunk } from \"./chunker\";\nimport type { ManifestChunk } from \"./manifest\";\n\n/**\n * The batch protocol of `/api/public/worlds/{slug}/data` (contract §7): open\n * a batch, register each chunk by digest (the server hands back a presigned\n * PUT, or says it already holds that content), confirm the upload, complete,\n * then poll. Thin on purpose: the server owns validation and the ledger.\n */\n\nexport type Refusal = {\n chunk: number;\n index: number;\n entity: string | null;\n primaryKey: Record<string, unknown> | null;\n field: string | null;\n pointer: string;\n detail: string;\n};\n\nexport type BatchStatus = {\n batchId: string;\n state: string;\n mode?: string;\n merge?: string;\n atomic?: boolean;\n dryRun?: boolean;\n publish?: string;\n chunks?: number;\n uploadedChunks?: number;\n rows?: number;\n refusalCount?: number;\n refusals?: Refusal[];\n reportUrl?: string;\n progress?: { phase?: string; validatedChunks?: number; appliedRows?: number };\n entityCounts?: Record<string, number>;\n snapshotId?: string | null;\n batchDigest?: string | null;\n versionId?: string | null;\n error?: string | null;\n createdAt?: string;\n updatedAt?: string;\n};\n\nexport type OpenBatchBody = {\n mode: \"append\" | \"replace\";\n merge: \"upsert\" | \"fill\";\n redact?: \"off\" | \"apply\" | \"refuse\";\n atomic: boolean;\n dryRun: boolean;\n publish: \"now\" | \"later\";\n message?: string;\n expectedChunks?: number;\n entities?: string[];\n};\n\nexport type OpenedBatch = { batchId: string; state: string; limits?: { chunkBytes?: number; batchBytes?: number; inlineBytes?: number } };\n\nexport type RegisteredChunk = {\n chunkId: string;\n uploaded: boolean;\n uploadUrl?: string;\n /** Headers the presigned PUT was signed for (content-type, content-length, x-amz-checksum-sha256); sent exactly. */\n uploadHeaders?: Record<string, string>;\n expiresAt?: string;\n};\n\nexport const TERMINAL_STATES = new Set([\"applied\", \"refused\", \"published\", \"failed\"]);\n\nexport const sleepMs = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));\n\nexport class WorldDataApi {\n readonly base: string;\n constructor(\n readonly creds: Credentials,\n readonly slug: string,\n /** Injectable for tests: the pause between retries and polls. */\n readonly sleep: (ms: number) => Promise<void> = sleepMs,\n ) {\n this.base = `/api/public/worlds/${encodeURIComponent(slug)}/data`;\n }\n\n open(body: OpenBatchBody): Promise<OpenedBatch> {\n return api<OpenedBatch>(this.creds, \"POST\", `${this.base}/batches`, body);\n }\n\n register(batchId: string, chunk: { ordinal: number; digest: string; bytes: number; rows: number; entity: string | null }): Promise<RegisteredChunk> {\n return api<RegisteredChunk>(this.creds, \"POST\", `${this.base}/batches/${batchId}/chunks`, {\n ordinal: chunk.ordinal,\n digest: chunk.digest,\n bytes: chunk.bytes,\n rows: chunk.rows,\n ...(chunk.entity ? { entity: chunk.entity } : {}),\n });\n }\n\n markUploaded(batchId: string, chunkId: string): Promise<{ chunkId: string; uploaded: boolean; bytes: number }> {\n return api(this.creds, \"POST\", `${this.base}/batches/${batchId}/chunks/${chunkId}/uploaded`);\n }\n\n complete(batchId: string): Promise<{ batchId: string; state: string }> {\n return api(this.creds, \"POST\", `${this.base}/batches/${batchId}/complete`);\n }\n\n get(batchId: string): Promise<BatchStatus> {\n return api<BatchStatus>(this.creds, \"GET\", `${this.base}/batches/${batchId}`);\n }\n\n list(limit?: number, cursor?: string): Promise<{ batches: BatchStatus[]; nextCursor?: string }> {\n const params = new URLSearchParams();\n if (limit !== undefined) params.set(\"limit\", String(limit));\n if (cursor) params.set(\"cursor\", cursor);\n const q = params.toString();\n return api(this.creds, \"GET\", `${this.base}/batches${q ? `?${q}` : \"\"}`);\n }\n\n publish(message?: string): Promise<{ versionId: string; snapshotId: string; batchIds: string[] }> {\n return api(this.creds, \"POST\", `${this.base}/publish`, message ? { message } : {});\n }\n\n /**\n * PUT the gzipped chunk to its presigned URL with exactly the headers the\n * URL was signed for (the platform's `uploadHeaders`; the same three when it\n * sends none), with backoff on a dropped connection or a 5xx.\n */\n async put(uploadUrl: string, gz: Buffer, signed?: Record<string, string>): Promise<void> {\n const headers = signed ?? uploadHeadersFor(gz);\n const delays = [500, 1500, 4000];\n for (let attempt = 0; ; attempt++) {\n try {\n const res = await fetch(uploadUrl, { method: \"PUT\", body: new Uint8Array(gz), headers });\n if (res.ok) return;\n if (res.status < 500 || attempt >= delays.length) throw new CliError(`chunk upload -> ${res.status}: ${(await res.text()).slice(0, 300)}`, 1);\n } catch (error) {\n if (error instanceof CliError || attempt >= delays.length) throw error instanceof CliError ? error : new CliError(`chunk upload failed: ${(error as Error).message}`, 1);\n }\n await this.sleep(delays[attempt]!);\n }\n }\n\n /** Register, upload unless the server already holds the content, confirm. */\n async upload(batchId: string, chunk: BuiltChunk): Promise<ManifestChunk> {\n const registered = await this.register(batchId, chunk);\n if (!registered.uploaded) {\n if (!registered.uploadUrl) throw new CliError(`the server registered chunk ${chunk.ordinal} without an upload URL`, 1);\n await this.put(registered.uploadUrl, chunk.gz, registered.uploadHeaders);\n await this.markUploaded(batchId, registered.chunkId);\n }\n return { ordinal: chunk.ordinal, digest: chunk.digest, bytes: chunk.bytes, rows: chunk.rows, entity: chunk.entity, chunkId: registered.chunkId, uploaded: true };\n }\n}\n\n/** What a chunk's presigned PUT is signed for: its type, size and sha256 (base64, S3's spelling). */\nexport function uploadHeadersFor(gz: Buffer): Record<string, string> {\n return {\n \"content-type\": \"application/gzip\",\n \"content-length\": String(gz.length),\n \"x-amz-checksum-sha256\": createHash(\"sha256\").update(gz).digest(\"base64\"),\n };\n}\n\n/** Run `fn` over an async stream with at most `limit` in flight; results in input order. */\nexport async function forEachLimited<T>(items: AsyncIterable<T>, limit: number, fn: (item: T) => Promise<void>): Promise<void> {\n const inFlight = new Set<Promise<void>>();\n let failure: unknown = null;\n const track = (p: Promise<void>) => {\n const wrapped: Promise<void> = p.then(\n () => {\n inFlight.delete(wrapped);\n },\n (error) => {\n failure ??= error;\n inFlight.delete(wrapped);\n },\n );\n inFlight.add(wrapped);\n };\n for await (const item of items) {\n if (failure) break;\n track(fn(item));\n if (inFlight.size >= limit) await Promise.race(inFlight);\n }\n await Promise.all(inFlight);\n if (failure) throw failure;\n}\n\nexport type WaitOptions = {\n /** Called once per phase change with a printable line. */\n onPhase?: (line: string) => void;\n sleep?: (ms: number) => Promise<void>;\n /** The first pause between polls (default 1 s; GATEWAY_WORLD_DATA_POLL_MS in the CLI). */\n initialDelayMs?: number;\n};\n\n/** Poll until the batch settles; 1 s growing to 10 s between polls. */\nexport async function waitForBatch(client: WorldDataApi, batchId: string, opts: WaitOptions = {}): Promise<BatchStatus> {\n const sleep = opts.sleep ?? client.sleep;\n let delay = opts.initialDelayMs ?? 1000;\n let last = \"\";\n for (;;) {\n const status = await client.get(batchId);\n const phase = phaseLine(status);\n if (phase !== last) {\n opts.onPhase?.(phase);\n last = phase;\n }\n if (TERMINAL_STATES.has(status.state)) return status;\n await sleep(delay);\n delay = Math.min(10_000, Math.round(delay * 1.5));\n }\n}\n\n/** The Python CLI's progress line: `state`, with the job's phase in parentheses when it has one. */\nexport function phaseLine(status: BatchStatus): string {\n const phase = status.progress?.phase;\n return phase ? `${status.state} (${phase})` : status.state;\n}\n\n/**\n * The refusal report as JSONL: the server's full report when it has one\n * (`reportUrl`), else the records the status carries inline. Returns the\n * number of lines written.\n */\nexport async function writeRefusalReport(status: BatchStatus, file: string): Promise<number> {\n let text: string;\n if (status.reportUrl) {\n const res = await fetch(status.reportUrl);\n if (!res.ok) throw new CliError(`refusal report -> ${res.status}`, 1);\n text = await res.text();\n if (text && !text.endsWith(\"\\n\")) text += \"\\n\";\n } else text = (status.refusals ?? []).map((r) => JSON.stringify(r) + \"\\n\").join(\"\");\n fs.writeFileSync(file, text);\n return text ? text.split(\"\\n\").filter(Boolean).length : 0;\n}\n","import { createHash } from \"node:crypto\";\nimport { deflateRawSync } from \"node:zlib\";\n\nimport { dumps, type JsonObject } from \"./json\";\nimport type { TaggedRow } from \"./rowSource\";\n\n/**\n * Rows into chunks: gzip over JSONL, cut on row boundaries at `--chunk-rows`\n * or `--chunk-bytes` (uncompressed), content-addressed by the sha256 of the\n * gzipped bytes. The same rows with the same flags give the same content\n * digests (over the JSONL) in both CLIs and on every platform, and the same\n * gzip digests wherever the two zlibs deflate alike: lines are the Python\n * serialisation (`dumps`), the deflate stream is zlib's at level 9, and the\n * gzip header is written here rather than by zlib, as CPython's\n * `gzip.compress(…, mtime=0)` writes it — zlib would stamp the platform's OS\n * byte instead. Node 20 and 24 bundle Chromium's zlib, which deflates\n * differently from CPython's stock zlib, so a chunk's gzip digest can differ\n * between CLIs while its content digest agrees; `--resume` keys on the digest\n * of what this CLI wrote, so it is unaffected. See `zlibDeflatesLikeCPython`.\n */\n\nexport const DEFAULT_CHUNK_BYTES = 64 * 1024 * 1024;\nexport const GZIP_LEVEL = 9;\n\nexport type ChunkPlan = {\n /** Always bound: the Python CLI keeps 64 MiB even with --chunk-rows. */\n chunkBytes: number;\n chunkRows: number | null;\n /** When set, chunks are declared with this entity and lines are bare rows. */\n entity: string | null;\n};\n\nexport type BuiltChunk = {\n ordinal: number;\n /** sha256 of the gzipped bytes, hex. */\n digest: string;\n /** Gzipped size. */\n bytes: number;\n rows: number;\n entity: string | null;\n /** Uncompressed JSONL size (`contentBytes` in the shared manifest). */\n rawBytes: number;\n /** sha256 of the uncompressed JSONL: the cross-zlib parity check. */\n contentSha256: string;\n /** Index of the chunk's first row in the input stream. */\n firstRow: number;\n gz: Buffer;\n};\n\n/** One row as the line a chunk carries: tagged, or bare when the chunk declares its entity. */\nexport function chunkLine(row: TaggedRow, declared: string | null): string {\n if (declared !== null) return dumps(row.row) + \"\\n\";\n const tagged: JsonObject = new Map();\n tagged.set(\"entity\", row.entity);\n tagged.set(\"row\", row.row);\n return dumps(tagged) + \"\\n\";\n}\n\nexport async function* buildChunks(rows: AsyncIterable<TaggedRow>, plan: ChunkPlan): AsyncGenerator<BuiltChunk> {\n let lines: Buffer[] = [];\n let rawBytes = 0;\n let ordinal = 0;\n let seen = 0;\n const flush = (): BuiltChunk => {\n const raw = Buffer.concat(lines);\n const built = finishChunk(ordinal++, raw, lines.length, plan.entity, seen - lines.length);\n lines = [];\n rawBytes = 0;\n return built;\n };\n for await (const row of rows) {\n const line = Buffer.from(chunkLine(row, plan.entity), \"utf8\");\n const full =\n lines.length > 0 &&\n ((plan.chunkRows !== null && lines.length >= plan.chunkRows) ||\n rawBytes + line.length > plan.chunkBytes);\n if (full) yield flush();\n lines.push(line);\n rawBytes += line.length;\n seen++;\n }\n if (lines.length) yield flush();\n}\n\nexport function finishChunk(ordinal: number, raw: Buffer, rows: number, entity: string | null, firstRow = 0): BuiltChunk {\n const gz = gzipDeterministic(raw, { name: chunkName(ordinal) });\n return {\n ordinal,\n digest: createHash(\"sha256\").update(gz).digest(\"hex\"),\n bytes: gz.length,\n rows,\n entity,\n rawBytes: raw.length,\n contentSha256: createHash(\"sha256\").update(raw).digest(\"hex\"),\n firstRow,\n gz,\n };\n}\n\n/**\n * Whether this Node's zlib deflates as the CPython that wrote the fixtures\n * did. Deflate output is a property of the zlib build, not of the format:\n * the same input inflates everywhere, but a zlib-ng or a future Chromium\n * zlib may pick different matches, and then gzip digests differ across\n * CLIs while content digests (over the JSONL) still agree. The manifest\n * parity check is on the content; the gzip digest is informative.\n */\nexport function zlibDeflatesLikeCPython(): boolean {\n return deflateRawSync(Buffer.from(CPYTHON_PROBE_TEXT), { level: GZIP_LEVEL }).toString(\"hex\") === CPYTHON_PROBE_DEFLATE;\n}\n/**\n * Two tagged rows, as the chunker writes them, and CPython's deflate of them (zlib\n * 1.2.12, which also wrote the fixtures). The probe has to be this long: \"hello\\n\"\n * deflates identically on every zlib, so it proved nothing, while on this text\n * Node 20 and 24 (Chromium's zlib 1.3.1) pick different matches and land two\n * bytes shorter than Node 25 and CPython (stock zlib).\n */\nconst CPYTHON_PROBE_TEXT = '{\"entity\":\"customers\",\"row\":{\"id\":0,\"name\":\"n0\",\"score\":0.0,\"tags\":[\"a\"]}}\\n{\"entity\":\"customers\",\"row\":{\"id\":1,\"name\":\"n1\",\"score\":1.0,\"tags\":[\"a\"]}}\\n';\nconst CPYTHON_PROBE_DEFLATE = \"ab564acd2bc92ca954b2524a2e2d2ec9cf4d2d2a56d2512aca2f57b2aa56ca4c51b232d051ca4bcc4d052ac83300ca1427e7170139067a40f192c4f46225ab68a544a5d8da5aae6a824619228c3244186588691400\";\n\n/** The file name the Python CLI gives chunk N (`chunk-00007.jsonl.gz`), which\n * its `GzipFile` records in the gzip header, so it is part of the digest. */\nexport const chunkName = (ordinal: number): string => `chunk-${String(ordinal).padStart(5, \"0\")}.jsonl`;\n\n/**\n * Gzip as CPython's `gzip.GzipFile(fileobj, \"wb\", mtime=0)` writes it: mtime\n * 0, XFL for the level, OS \"unknown\" (0xff), and — when a name is given — the\n * FNAME field, exactly as GzipFile records the basename of the file it writes.\n */\nexport function gzipDeterministic(raw: Buffer, opts: { level?: number; name?: string } = {}): Buffer {\n const level = opts.level ?? GZIP_LEVEL;\n const name = opts.name ? Buffer.concat([Buffer.from(opts.name, \"latin1\"), Buffer.from([0])]) : Buffer.alloc(0);\n const header = Buffer.from([0x1f, 0x8b, 0x08, opts.name ? 0x08 : 0x00, 0, 0, 0, 0, level === 9 ? 0x02 : level === 1 ? 0x04 : 0x00, 0xff]);\n const body = deflateRawSync(raw, { level });\n const trailer = Buffer.alloc(8);\n trailer.writeUInt32LE(crc32(raw), 0);\n trailer.writeUInt32LE(raw.length >>> 0, 4);\n return Buffer.concat([header, name, body, trailer]);\n}\n\nlet table: Uint32Array | null = null;\n\n/** CRC-32 (IEEE), the gzip trailer's checksum. A table here keeps the CLI on Node 18. */\nexport function crc32(data: Buffer): number {\n if (!table) {\n table = new Uint32Array(256);\n for (let n = 0; n < 256; n++) {\n let c = n;\n for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;\n table[n] = c >>> 0;\n }\n }\n let crc = 0xffffffff;\n for (let i = 0; i < data.length; i++) crc = table[(crc ^ data[i]!) & 0xff]! ^ (crc >>> 8);\n return (crc ^ 0xffffffff) >>> 0;\n}\n\n/** The Python CLI's `_parse_size`: an integer and a unit — none, b, k, kib, kb, m, mib, mb, g, gib, gb. */\nexport function parseSize(text: string): number {\n const units: Record<string, number> = { \"\": 1, b: 1, k: 1024, kib: 1024, kb: 1000, m: 1024 ** 2, mib: 1024 ** 2, mb: 1000 ** 2, g: 1024 ** 3, gib: 1024 ** 3, gb: 1000 ** 3 };\n const raw = text.trim().toLowerCase().replace(/ /g, \"\");\n const m = /^(\\d+)([a-z]*)$/.exec(raw);\n if (!m || !(m[2]! in units)) throw new Error(`--chunk-bytes takes a size like 64MiB or 1000000, not '${text}'`);\n return Number(m[1]) * units[m[2]!]!;\n}\n","import type { Credentials } from \"../../config\";\nimport type { Rows } from \"../rows\";\nimport { forEachLimited, waitForBatch, WorldDataApi, type BatchStatus } from \"./batches\";\nimport { buildChunks, DEFAULT_CHUNK_BYTES } from \"./chunker\";\nimport { parseJson, type JsonObject } from \"./json\";\nimport type { TaggedRow } from \"./rowSource\";\n\n/**\n * Rows already in memory into a platform world through the batch lane —\n * open, chunk, upload, complete, wait — with none of the CLI's file, manifest\n * or resume machinery. What `ingestToolCalls` (the SDK) pushes after the\n * runtime projected a slug's records; the CLI keeps `data import`'s lane.\n * `redact` is optional and defaults to off: the platform stores the rows as\n * given unless asked to apply its `[redact]` policy.\n */\nexport async function pushRows(\n creds: Credentials,\n slug: string,\n rows: Rows,\n opts: {\n mode?: \"append\" | \"replace\";\n redact?: \"off\" | \"apply\" | \"refuse\";\n message?: string;\n publish?: \"now\" | \"later\";\n chunkBytes?: number;\n parallel?: number;\n dryRun?: boolean;\n sleep?: (ms: number) => Promise<void>;\n } = {},\n): Promise<BatchStatus> {\n const client = opts.sleep ? new WorldDataApi(creds, slug, opts.sleep) : new WorldDataApi(creds, slug);\n const opened = await client.open({\n mode: opts.mode ?? \"append\",\n merge: \"upsert\",\n ...(opts.redact && opts.redact !== \"off\" ? { redact: opts.redact } : {}),\n atomic: true,\n dryRun: Boolean(opts.dryRun),\n publish: opts.publish ?? \"now\",\n ...(opts.message ? { message: opts.message } : {}),\n });\n if (!opened.batchId) throw new Error(\"the platform opened no batch (no batchId in the answer)\");\n // The chunker speaks the file lane's JSON model (CPython-faithful numbers and\n // key order), so each row takes the same road a JSONL line does: serialized, parsed.\n const tagged = (async function* (): AsyncGenerator<TaggedRow> {\n for (const [entity, listed] of Object.entries(rows))\n for (let index = 0; index < listed.length; index++)\n yield { entity, row: parseJson(JSON.stringify(listed[index]!)) as JsonObject, where: `${entity}[${index}]` };\n })();\n const chunks = buildChunks(tagged, { chunkBytes: opts.chunkBytes ?? DEFAULT_CHUNK_BYTES, chunkRows: null, entity: null });\n await forEachLimited(chunks, Math.max(1, opts.parallel ?? 4), async (chunk) => {\n await client.upload(opened.batchId, chunk);\n });\n await client.complete(opened.batchId);\n return waitForBatch(client, opened.batchId, { initialDelayMs: pollMs() });\n}\n\nfunction pollMs(): number {\n const raw = Number(process.env.GATEWAY_WORLD_DATA_POLL_MS ?? 1000);\n return Number.isFinite(raw) && raw >= 0 ? raw : 1000;\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// Tasks that need several worlds: `openTask` brings every world a task\n// names up together (or not at all) and hands back the sessions by alias.\nexport * from \"./taskSessions\";\n\n// Run a task end to end: open every world, hand the agent a `TaskRun`,\n// grade with its report, file one rollout and close — `runTask`, the\n// engine behind `gateway worlds task run`.\nexport * from \"./taskRun\";\n\n// The evaluations client `runTask` files a rollout through — create, push\n// samples, finalize. Exposed in case a caller wants to file its own.\nexport * from \"./evals\";\n\n// The computer-use half: surfaces, a Playwright browser on the world's UI,\n// and browser actions as model tools.\nexport * from \"./browser\";\n\n// The hub half: push, pull, propose and the content-hash primitives the CLI\n// runs on. These were reachable only from inside the package, so a consumer\n// could drive a world but never publish one.\nexport * from \"./hub\";\n\n// PR validation: push-dispatch-wait-gate as one composed call, for CI.\nexport * from \"./validate\";\n\n// Discovery: what a world holds and how each field is stored (`describeWorld`),\n// and the stored forms of a plaintext under the world's [redact] table\n// (`storedForms`, `redactionOf`) — the same digest rule as the Python runtime.\nexport * from \"./describe\";\nexport * from \"./redaction\";\nexport * from \"./transforms\";\n\n// Lookup: the rows of one entity matching a predicate (`queryRows`), by\n// stored value or — with `resolve` — by plaintext the runtime maps through\n// the same [redact] table.\nexport * from \"./query\";\n\n// Migration: a stored world into a schema world (`migrateWorld`), dry run by\n// default; the project's connector worlds at once (`migrateProjectWorlds`).\nexport * from \"./migrate\";\n\n// Tool calls into rows: the record contract, `captureToolCalls` (record an\n// agent's real calls), `toolCallsFromObservations` (from a trace) and\n// `ingestToolCalls` (into a directory or a slug). Redaction optional, off by default.\nexport * from \"./ingest\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAoGO,SAAS,aAAa,GAAwC;AACnE,QAAM,QAA4B,CAAC,OAAO;AAC1C,MAAI,EAAE,IAAK,OAAM,KAAK,KAAK;AAC3B,MAAI,EAAE,GAAI,OAAM,KAAK,IAAI;AACzB,MAAI,EAAE,QAAS,OAAM,KAAK,SAAS;AACnC,SAAO;AACT;AAOO,SAAS,MACd,IACAA,OACQ;AACR,QAAM,OAAO,GAAG,IAAI,QAAQ,QAAQ,EAAE;AACtC,QAAM,MAAMA,MAAK,WAAW,GAAG,IAAIA,QAAO,IAAIA,KAAI;AAClD,MAAI,CAAC,GAAG,MAAO,QAAO,OAAO;AAC7B,QAAM,CAAC,YAAY,IAAI,IAAI,UAAU,GAAG;AACxC,QAAM,SAAS,WAAW,SAAS,GAAG,IAAI,MAAM;AAChD,QAAM,QAAQ,GAAG,cAAc,IAAI,mBAAmB,GAAG,KAAK,CAAC;AAC/D,SAAO,OAAO,aAAa,SAAS,QAAQ;AAC9C;AAEO,SAAS,WAAW,IAAgD;AACzE,SAAO,MAAM,IAAI,GAAG,SAAS,GAAG;AAClC;AAGO,SAAS,eAAe,KAAqB;AAClD,QAAM,CAAC,YAAY,IAAI,IAAI,UAAU,GAAG;AACxC,QAAM,IAAI,WAAW,QAAQ,GAAG;AAChC,MAAI,IAAI,EAAG,QAAO;AAClB,QAAM,OAAO,WACV,MAAM,IAAI,CAAC,EACX,MAAM,GAAG,EACT,O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AAO;AAAA,MACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAQA,MAAM,KACJ,MACA,OAGI,CAAC,GACsC;AAC3C,cAAM,EAAE,aAAAG,aAAY,IAAI,MAAM;AAC9B,eAAOA,aAAY,KAAK,MAAM;AAAA,UAC5B;AAAA,UACA,WAAW,KAAK,QAAQ;AAAA,UACxB,WAAW,KAAK;AAAA,UAChB,UAAU,KAAK;AAAA,UACf,SAAS,KAAK;AAAA,QAChB,CAAC;AAAA,MACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAOA,MAAM,SACJ,aACA,OAKI,CAAC,GACqD;AAC1D,cAAM,aAAa,KAAK,cAAc,iBAAiB;AACvD,eAAO;AAAA,UACL,KAAK;AAAA,UACL;AAAA,UACA;AAAA,UACA;AAAA,YACE;AAAA,YACA,GAAI,KAAK,cAAc,EAAE,aAAa,KAAK,YAAY,IAAI,CAAC;AAAA,YAC5D,WAAW,KAAK,aAAa,KAAK,QAAQ;AAAA,YAC1C,GAAG;AAAA,UACL;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA;AAAA;","names":["path","text","resolve","sleep","state","openWorld","api","path","pollMs","state","path","text","session_exports","AsyncLocalStorage","resolve","init_session","isSpanContextValid","trace","path","text","text","scores","init_session","isGatewayConfigured","init","createHash","fs","path","pad","text","resolve","state","text","hex","createHash","createHash","text","fs","path","init","text","fs","path","resolve","text","fs","path","SKIP_DIRS","text","fs","path","BUILD_OUTPUT","spawn","fs","os","path","resolve","createHash","fs","sleep","resolve","createHash","flush","fs","os","path","isObject","text","ingestLocalToolCalls","importLocalWorldData","checkLocalWorldData","transformRecords","pull","pushRows","trace","ApiError","path","text","resolve","openSession"]}
|