@withgateway/sdk 0.2.8 → 0.2.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +24 -8
- package/dist/cli.js +332 -163
- package/dist/cli.js.map +1 -1
- package/dist/cli.mjs +332 -163
- package/dist/cli.mjs.map +1 -1
- package/dist/files/index.js +119 -15
- package/dist/files/index.js.map +1 -1
- package/dist/files/index.mjs +119 -15
- package/dist/files/index.mjs.map +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +229 -120
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +220 -120
- package/dist/index.mjs.map +1 -1
- package/dist/traces/index.js +119 -15
- package/dist/traces/index.js.map +1 -1
- package/dist/traces/index.mjs +119 -15
- package/dist/traces/index.mjs.map +1 -1
- package/dist/tracing/index.js +1 -1
- package/dist/tracing/index.js.map +1 -1
- package/dist/tracing/index.mjs +1 -1
- package/dist/tracing/index.mjs.map +1 -1
- package/dist/worlds/index.d.mts +78 -9
- package/dist/worlds/index.d.ts +78 -9
- package/dist/worlds/index.js +219 -119
- package/dist/worlds/index.js.map +1 -1
- package/dist/worlds/index.mjs +220 -120
- package/dist/worlds/index.mjs.map +1 -1
- package/package.json +1 -1
- package/runtime/gatewaysdk/environment/_toml.py +3 -10
- package/runtime/gatewaysdk/environment/schema/skills/benchmarks-getting-started/SKILL.md +3 -3
- package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/SKILL.md +1 -1
- package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/SKILL.md +11 -11
- package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/cli-mcp-map.md +3 -2
- package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/gotchas.md +5 -1
- package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/new-world-sandbox.md +5 -3
- package/runtime/gatewaysdk/environment/schema/store.py +15 -6
- package/skills/benchmarks-getting-started/SKILL.md +3 -3
- package/skills/connector-schema-authoring/SKILL.md +1 -1
- package/skills/connector-schema-authoring/world-schema.md +1 -1
- package/skills/worlds-getting-started/SKILL.md +11 -11
- package/skills/worlds-getting-started/references/cli-mcp-map.md +3 -2
- package/skills/worlds-getting-started/references/gotchas.md +5 -1
- package/skills/worlds-getting-started/references/new-world-sandbox.md +5 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/worlds/browserReconnect.ts","../../src/worlds/browser.ts","../../src/worlds/sessionContract.ts","../../src/worlds/taskRef.ts","../../src/worlds/session.ts","../../src/worlds/sessionList.ts","../../src/worlds/tasks.ts","../../src/worlds/taskSessions.ts","../../src/worlds/evals.ts","../../src/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/checkoutProvenance.ts","../../src/worlds/setRun.ts","../../src/worlds/checkoutTarget.ts","../../src/worlds/worldDir.ts","../../src/worlds/tar.ts","../../src/worlds/hub.ts","../../src/worlds/validate.ts","../../src/worlds/sandbox.ts","../../src/worlds/describe.ts","../../src/cli/platform/worldData/json.ts","../../src/worlds/transforms.ts","../../src/worlds/redaction.ts","../../src/worlds/query.ts","../../src/worlds/migrate.ts","../../src/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/editSessions.ts","../../src/worlds/dryRun.ts","../../src/worlds/index.ts"],"sourcesContent":["import type { BrowserPage, PlaywrightBrowserLike } from \"./browser\";\n\n/**\n * A HOSTED BROWSER THAT COMES BACK. A World Host session's browser is a pool\n * pod; on the `standard` tier it runs on spot capacity and can be reclaimed\n * with two minutes' notice. The browser dies, the world does not, and the\n * platform can put a new browser behind the SAME `surfaces.browser.wsUrl`.\n *\n * `BrowserReconnector` is the client half of that repair: on a lost\n * connection it asks the platform to repair (`POST .../browser-repair`),\n * waits while a browser starts, reconnects to the same address and hands the\n * new connection to its owner to restore the page. It knows nothing of HTTP\n * or Playwright — both come in as collaborators, so tests drive it with\n * fakes. Twin of `gatewaysdk/world_browser_reconnect.py`, call for call.\n */\n\n/** What the platform answers a repair with. `healthy`: the browser is alive,\n * reconnect now. `replaced`: a new, blank browser; reconnect and reopen the\n * page. `starting`: a browser is coming up; ask again in `retryAfterMs`. */\nexport type RepairAnswer = {\n outcome: \"healthy\" | \"replaced\" | \"starting\";\n retryAfterMs: number | null;\n};\n\ntype BrowserContextLike = Awaited<\n ReturnType<PlaywrightBrowserLike[\"newContext\"]>\n>;\n\n/** One live attachment to the session's browser. */\nexport type BrowserConnection = {\n browser: PlaywrightBrowserLike;\n context: BrowserContextLike;\n page: BrowserPage;\n};\n\nexport async function closeConnection(c: BrowserConnection): Promise<void> {\n await c.context.close();\n await c.browser.close();\n}\n\n/** Close a connection whose browser is already gone: it only frees the\n * handle, so a failure is ignored. */\nexport async function releaseConnection(c: BrowserConnection): Promise<void> {\n await closeConnection(c).catch(() => undefined);\n}\n\nexport const RECOVER_BUDGET_MS = 90_000;\nconst BACKOFF_BASE_MS = 1_000;\nconst BACKOFF_CAP_MS = 5_000;\n\n/** What Playwright says when the browser or its connection is gone, as\n * opposed to an action that failed on a live page. Matched case-insensitively\n * against the error message; nothing else triggers a reconnect. */\nexport const BROWSER_GONE_PATTERNS: readonly RegExp[] = [\n /target page, context or browser has been closed/i,\n /\\bbrowser has been (closed|disconnected)\\b/i,\n /\\bbrowser (has )?disconnected\\b/i,\n /\\btarget closed\\b/i,\n /\\bwebsocket is not open\\b/i,\n /\\bconnection closed\\b/i,\n];\n\n/** A failed page load (`net::ERR_INTERNET_DISCONNECTED`,\n * `net::ERR_CONNECTION_CLOSED`) is the world UI's network, not the browser:\n * the browser is alive, and repairing it would throw away a live page. */\nconst PAGE_NETWORK_ERROR = /net::ERR_/i;\n\nexport function isBrowserGone(error: unknown): boolean {\n const message = error instanceof Error ? error.message : String(error);\n if (PAGE_NETWORK_ERROR.test(message)) return false;\n return BROWSER_GONE_PATTERNS.some((p) => p.test(message));\n}\n\nconst REDACTED = \"<redacted>\";\nconst TOKEN_QUERY_VALUE = /([?&]token=)[^&#\\s\"')]*/gi;\n\n/**\n * Takes a session's credentials out of text that leaves the process — an\n * error recorded into the browser timeline, a recovery's reason. A browser\n * error quotes the URL it failed on, and those URLs carry the session: the\n * hosted browser's `wsUrl` (its path is the credential), the UI's token, and\n * any `?token=` a landing URL presents. Each becomes `<redacted>`.\n */\nexport class SecretScrubber {\n private readonly secrets: string[];\n\n constructor(secrets: readonly (string | null | undefined)[]) {\n const known = secrets.filter((s): s is string => Boolean(s));\n // Longest first, so a wsUrl goes whole before a token inside it.\n this.secrets = [\n ...new Set([...known, ...known.map((s) => encodeURIComponent(s))]),\n ].sort((a, b) => b.length - a.length);\n }\n\n scrub(text: string): string {\n const bare = this.secrets.reduce(\n (out, secret) => out.split(secret).join(REDACTED),\n text,\n );\n return bare.replace(TOKEN_QUERY_VALUE, `$1${REDACTED}`);\n }\n}\n\n/** A mutating action (click, type, press, back, scroll) lost its browser.\n * The browser was repaired and the page reopened at `restoredUrl`, but the\n * action is NOT replayed: its input may already have reached the world.\n * `cause` is the error the action failed with. */\nexport class BrowserReconnected extends Error {\n constructor(\n readonly outcome: RecoveryResult[\"outcome\"],\n readonly restoredUrl: string | null,\n cause: unknown,\n ) {\n super(\n `the browser was lost mid-action and reconnected (${outcome}); ` +\n (restoredUrl\n ? `the page was reopened at ${restoredUrl}. `\n : \"it is on a blank page. \") +\n \"The action may or may not have taken effect — look at the page before acting again.\",\n { cause },\n );\n this.name = \"BrowserReconnected\";\n }\n}\n\n/** The session's browser stayed gone for the whole budget. `cause` is the\n * error the action first failed with. */\nexport class BrowserUnrecoverable extends Error {\n constructor(message: string, cause: unknown) {\n super(message, { cause });\n this.name = \"BrowserUnrecoverable\";\n }\n}\n\n/** A repair refusal worth waiting out: no answer at all (the network), the\n * platform's own failure, or a full pool. Anything else (a 404 for a session\n * that is not open with a browser) ends the recovery. */\nfunction refusalIsTransient(error: unknown): boolean {\n const { status, code } = error as { status?: unknown; code?: unknown };\n if (typeof status !== \"number\") return true;\n if (status >= 500) return true;\n return status === 400 && code === \"browser_capacity\";\n}\n\nfunction describe(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\ntype Step =\n | { kind: \"recovered\"; outcome: RecoveryResult[\"outcome\"] }\n | { kind: \"stop\" }\n | { kind: \"wait\"; reason: string; waitMs: number | null };\n\nexport type RecoveryResult = {\n outcome: \"healthy\" | \"replaced\";\n attempts: number;\n};\n\nexport class BrowserReconnector {\n private readonly sleep: (ms: number) => Promise<void>;\n private readonly now: () => number;\n private readonly scrub: (text: string) => string;\n readonly budgetMs: number;\n\n constructor(\n private readonly repair: () => Promise<RepairAnswer>,\n private readonly connect: () => Promise<BrowserConnection>,\n opts: {\n sleep?: (ms: number) => Promise<void>;\n now?: () => number;\n budgetMs?: number;\n /** Takes credentials out of a reason before it is thrown. */\n scrub?: (text: string) => string;\n } = {},\n ) {\n this.sleep =\n opts.sleep ?? ((ms) => new Promise<void>((r) => setTimeout(r, ms)));\n this.now = opts.now ?? Date.now;\n this.budgetMs = opts.budgetMs ?? RECOVER_BUDGET_MS;\n this.scrub = opts.scrub ?? ((text) => text);\n }\n\n /**\n * Repair, reconnect and `restore` until it works or the budget runs out.\n * `restore` receives each new connection (the owner adopts it and reopens\n * its page); a restore that fails counts as a failed reconnect, because the\n * browser may have died again. A repair the platform refuses for good\n * rethrows `cause` untouched.\n */\n async recover(\n cause: unknown,\n restore: (connection: BrowserConnection) => Promise<void>,\n ): Promise<RecoveryResult> {\n const deadline = this.now() + this.budgetMs;\n let reason = describe(cause);\n for (let attempt = 1; ; attempt++) {\n const step = await this.attempt(restore);\n if (step.kind === \"recovered\")\n return { outcome: step.outcome, attempts: attempt };\n if (step.kind === \"stop\") throw cause;\n reason = step.reason;\n const remaining = deadline - this.now();\n if (remaining <= 0) break;\n const backoff = Math.min(\n BACKOFF_BASE_MS * 2 ** (attempt - 1),\n BACKOFF_CAP_MS,\n );\n await this.sleep(Math.min(step.waitMs ?? backoff, remaining));\n }\n throw new BrowserUnrecoverable(\n `the session's browser could not be recovered within ${Math.round(this.budgetMs / 1000)}s: ${this.scrub(reason)}`,\n cause,\n );\n }\n\n private async attempt(\n restore: (connection: BrowserConnection) => Promise<void>,\n ): Promise<Step> {\n let answer: RepairAnswer;\n try {\n answer = await this.repair();\n } catch (error) {\n if (!refusalIsTransient(error)) return { kind: \"stop\" };\n return {\n kind: \"wait\",\n reason: `repair failed: ${describe(error)}`,\n waitMs: null,\n };\n }\n const outcome = answer.outcome;\n if (outcome === \"starting\")\n return {\n kind: \"wait\",\n reason: \"a new browser is still starting\",\n waitMs: answer.retryAfterMs,\n };\n try {\n await restore(await this.connect());\n } catch (error) {\n return {\n kind: \"wait\",\n reason: `reconnect failed: ${describe(error)}`,\n waitMs: null,\n };\n }\n return { kind: \"recovered\", outcome };\n }\n}\n","import { schemaFromSignature, type WorldToolkit } from \"./session\";\nimport {\n BrowserReconnected,\n BrowserReconnector,\n SecretScrubber,\n closeConnection,\n isBrowserGone,\n releaseConnection,\n type BrowserConnection,\n type RecoveryResult,\n type RepairAnswer,\n} from \"./browserReconnect\";\n\n/**\n * A BROWSER ON A WORLD'S UI — the computer-use half of a live session.\n *\n * A session answers on SURFACES. `tools` is always there (the world's own\n * operations over the rendezvous). An api-type world may also answer on\n * `api` (the service itself), `ui` (its dashboard, over the same state) and\n * `browser` — a headless Chromium the platform runs NEXT TO that UI, which\n * an agent drives through Playwright. This file is the TS client for the\n * last two, call for call with `gatewaysdk/world_browser.py`.\n *\n * const s = await openSession(\"payments-like\", \"refund-dispute\", {\n * surfaces: [\"ui\", \"browser\"],\n * });\n * await s.ready();\n * const b = await s.browser(); // hosted, next to the world\n * await b.goto(); // the UI's entry page\n * await b.click(\"text=Refund\");\n * const tools = computerUseToolkit(b); // the same actions as model tools\n * await b.close();\n *\n * Playwright is an OPTIONAL peer: nothing here imports it until a browser is\n * opened, so sessions that never touch a UI never load it.\n *\n * MODES. `hosted` connects to the session's own browser (a Playwright server\n * the pod exposes over an authenticated websocket). `local` launches Chromium\n * on this machine and points it at the UI — a laptop against a hosted twin,\n * or a test. `auto` prefers hosted. Asking for a mode the session cannot\n * serve throws `WorldSurfaceUnavailable`; there is no silent fallback to a\n * browser other than the one the episode is judged on.\n *\n * OBSERVABILITY. Every action a `WorldBrowser` takes (goto, click, type,\n * press, scroll, back) is reported to the platform as one event — what was\n * done, whether it worked, where the page ended up, and a JPEG of the screen\n * after — through a `BrowserActionRecorder`. Reporting is fire-and-forget\n * and never fails the action; the platform renders it as the session's\n * browser timeline. Text typed into secret-looking fields is redacted before\n * it leaves the process.\n *\n * RECONNECT. A World Host browser on the `standard` tier can be reclaimed\n * mid-session. When an action fails because the browser or its connection is\n * gone, a hosted `cdp` browser asks the platform to repair it, reconnects to\n * the same address and reopens the page it was on (see `browserReconnect.ts`).\n * A read or a `goto` then runs once more; a click, type, press, back or scroll\n * is NOT replayed — its input may already have reached the world — and throws\n * `BrowserReconnected` so the agent looks at the page again. Local and\n * `playwright`-protocol browsers never reconnect.\n */\n\nexport const SURFACE_KINDS = [\"tools\", \"api\", \"ui\", \"browser\"] as const;\nexport type WorldSurfaceKind = (typeof SURFACE_KINDS)[number];\n\n/** Capacity behind a World Host session's browser. `standard` runs on spot\n * capacity first (about half the price) and may be reclaimed with two\n * minutes' notice, ending the browser but never the world; `premium` is\n * on-demand and never spot-reclaimed. Unset, the organization's default applies. */\nexport const BROWSER_TIERS = [\"standard\", \"premium\"] as const;\nexport type BrowserTier = (typeof BROWSER_TIERS)[number];\n\n/** Refuse a tier the platform does not know, before any request is sent. */\nexport function assertBrowserTier(value: unknown): asserts value is BrowserTier {\n if ((BROWSER_TIERS as readonly unknown[]).includes(value)) return;\n throw new Error(\n `Unknown browser tier: ${String(value)}; choose from ${BROWSER_TIERS.join(\", \")}`,\n );\n}\n\nexport const DEFAULT_VIEWPORT = { width: 1280, height: 800 };\nconst SETTLE_TIMEOUT_MS = 5_000;\nconst SETTLE_QUIET_MS = 150;\nconst SETTLE_POLL_MS = 25;\n\nexport const EVENT_BATCH_SIZE = 10;\nexport const EVENT_FLUSH_INTERVAL_MS = 1_000;\nexport const EVENT_MAX_RETRIES = 3;\nconst EVENT_SCREENSHOT_QUALITY = 60;\nconst EVENT_MAX_STRING = 500;\n\nconst SECRET_KEY =\n /pass(word|wd)?|secret|token|api[-_]?key|authorization|cookie|(^|[-_ #.\\[\"'=])(otp|pin|cvv|ssn)([-_ \\]\"']|$)/i;\n/** What a call that lost its browser does once the browser is back: a read or\n * a navigation runs again (`retry`); an action that may already have reached\n * the world is not replayed, and the agent is told (`report`). */\ntype OnBrowserLoss = \"retry\" | \"report\";\n\nconst SECRET_VALUE =\n /^((sk|pk|ghp|xox[abp])[-_][-_A-Za-z0-9]{8,}|AKIA[0-9A-Z]{12,}|Bearer [-_.A-Za-z0-9]{8,})/;\n\n/** The `surfaces` block of a session descriptor, as the platform sends it. */\nexport type SessionSurfaces = {\n tools: { kind: \"rendezvous\" };\n api?: {\n url: string;\n /** Per-session credential of a World Host session: send it as\n * `Authorization: Bearer <token>` (the header only; a token in the URL is\n * refused). Absent when the world\n * itself answers with its declared auth (a pod or a customer-hosted twin). */\n token?: string;\n };\n ui?: {\n url: string;\n entry: string;\n /** Same-origin prefix the UI proxies to the world API, e.g. `/__world-api`;\n * null when the UI only reaches the API server-side. */\n apiPath?: string | null;\n /** Per-session credential of a World Host UI. A browser navigation cannot\n * carry a header, so the first page load presents it once as `?token=`\n * and the host answers with an HttpOnly cookie. Absent for pod UIs. */\n token?: string;\n };\n browser?: {\n wsUrl: string;\n /** `cdp`: the platform's Chromium relay (any number of agents share one\n * browser, each in its own context). `playwright`: a `run-server` endpoint. */\n protocol: \"cdp\" | \"playwright\";\n viewport: { width: number; height: number };\n /** The capacity tier the browser runs on; present for World Host sessions. */\n tier?: BrowserTier;\n };\n};\n\nexport class WorldSurfaceUnavailable extends Error {\n constructor(\n readonly surface: WorldSurfaceKind,\n reason: string,\n ) {\n super(`World surface '${surface}' is unavailable: ${reason}`);\n }\n}\n\nexport function surfaceKinds(s: SessionSurfaces): WorldSurfaceKind[] {\n const kinds: WorldSurfaceKind[] = [\"tools\"];\n if (s.api) kinds.push(\"api\");\n if (s.ui) kinds.push(\"ui\");\n if (s.browser) kinds.push(\"browser\");\n return kinds;\n}\n\nconst UI_TOKEN_QUERY = \"token\";\n\n/** The URL of `path` on a UI surface, carrying the session token when the\n * surface has one. `path` may already have a query string; the token is\n * appended to it. */\nexport function uiUrl(\n ui: NonNullable<SessionSurfaces[\"ui\"]>,\n path: string,\n): string {\n const base = ui.url.replace(/\\/+$/, \"\");\n const rel = path.startsWith(\"/\") ? path : `/${path}`;\n if (!ui.token) return base + rel;\n const [beforeHash, hash] = splitHash(rel);\n const joiner = beforeHash.includes(\"?\") ? \"&\" : \"?\";\n const query = `${UI_TOKEN_QUERY}=${encodeURIComponent(ui.token)}`;\n return base + beforeHash + joiner + query + hash;\n}\n\nexport function uiEntryUrl(ui: NonNullable<SessionSurfaces[\"ui\"]>): string {\n return uiUrl(ui, ui.entry || \"/\");\n}\n\n/** `url` without its `token` query parameter: what may be logged or shown. */\nexport function withoutUiToken(url: string): string {\n const [beforeHash, hash] = splitHash(url);\n const q = beforeHash.indexOf(\"?\");\n if (q < 0) return url;\n const kept = beforeHash\n .slice(q + 1)\n .split(\"&\")\n .filter((pair) => pair !== \"\" && pair.split(\"=\")[0] !== UI_TOKEN_QUERY);\n return (\n beforeHash.slice(0, q) + (kept.length ? `?${kept.join(\"&\")}` : \"\") + hash\n );\n}\n\nfunction splitHash(url: string): [string, string] {\n const h = url.indexOf(\"#\");\n return h < 0 ? [url, \"\"] : [url.slice(0, h), url.slice(h)];\n}\n\n/** The slice of a Playwright `Page` this module drives. */\nexport type BrowserPage = {\n url(): string;\n goto(url: string, opts?: { waitUntil?: \"load\" }): Promise<unknown>;\n click(selector: string): Promise<void>;\n fill(selector: string, value: string): Promise<void>;\n screenshot(opts?: {\n type?: \"png\" | \"jpeg\";\n quality?: number;\n fullPage?: boolean;\n }): Promise<Buffer>;\n innerText(selector: string): Promise<string>;\n content(): Promise<string>;\n goBack(opts?: { waitUntil?: \"load\" }): Promise<unknown>;\n waitForLoadState(state?: \"load\"): Promise<void>;\n waitForTimeout(ms: number): Promise<void>;\n on(\n event: \"request\" | \"requestfinished\" | \"requestfailed\",\n handler: (request: unknown) => void,\n ): unknown;\n title(): Promise<string>;\n keyboard: { press(key: string): Promise<void> };\n mouse: { wheel(dx: number, dy: number): Promise<void> };\n};\n\nexport type BrowserMode = \"auto\" | \"hosted\" | \"local\";\n\n// ── action events ────────────────────────────────────────────────────────────\n\n/** One browser action as the platform ingests it\n * (`POST /world-sessions/{id}/browser-events`). */\nexport type BrowserActionEvent = {\n agentId: string;\n seq: number;\n ts: string;\n action: string;\n args: Record<string, unknown>;\n ok: boolean;\n error: string | null;\n durationMs: number;\n url: string | null;\n title: string | null;\n mode: Exclude<BrowserMode, \"auto\">;\n viewport: { width: number; height: number };\n /** base64 JPEG of the screen after the action; null if it could not be taken. */\n screenshot: string | null;\n};\n\n/** What of an action's arguments may leave the process. Selectors, paths\n * and keys are what a reviewer needs; anything keyed like a credential, or\n * typed into a field whose selector names one, or shaped like a known key,\n * is replaced. Strings are capped, nested values dropped. */\nexport function redactActionArgs(\n action: string,\n args: Record<string, unknown>,\n): Record<string, unknown> {\n const secretField =\n action === \"browser_type\" && SECRET_KEY.test(String(args.selector ?? \"\"));\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(args)) {\n if (value === null || value === undefined) out[key] = null;\n else if (typeof value === \"boolean\" || typeof value === \"number\")\n out[key] = value;\n else if (typeof value === \"string\") {\n if (\n SECRET_KEY.test(key) ||\n SECRET_VALUE.test(value) ||\n (secretField && key === \"text\")\n )\n out[key] = \"[redacted]\";\n else\n out[key] =\n value.length <= EVENT_MAX_STRING\n ? value\n : value.slice(0, EVENT_MAX_STRING) + \"…\";\n } else out[key] = \"[omitted]\";\n }\n return out;\n}\n\n/**\n * Ships browser action events to the platform, off the action's hot path.\n *\n * `post` receives a batch of events (the request body's `events`). Events\n * are numbered here, so ordering survives batching and retries — the\n * platform dedups on `(agentId, seq)`. A batch that keeps failing is dropped\n * with a warning: telemetry must never stall or fail the agent.\n *\n * Numbering is durable across recorders: `nextSeq()` hands out a position\n * within this recorder, and the first send adds the base `resumeFrom`\n * reports — the platform's next free seq for this agent — so an agent id\n * reopened in a later process appends to its timeline instead of colliding\n * with (and being deduplicated against) what it already recorded. The base\n * is fixed once resolved, which keeps retries idempotent.\n */\nexport class BrowserActionRecorder {\n private seq = 0;\n private base: Promise<number> | null = null;\n private queue: BrowserActionEvent[] = [];\n private timer: ReturnType<typeof setTimeout> | null = null;\n private inflight: Promise<void> = Promise.resolve();\n sent = 0;\n dropped = 0;\n\n constructor(\n private readonly post: (events: BrowserActionEvent[]) => Promise<void>,\n readonly agentId: string,\n private readonly opts: {\n /** The platform's next free seq for `agentId`; 0 when not given. */\n resumeFrom?: () => Promise<number>;\n batchSize?: number;\n flushIntervalMs?: number;\n maxRetries?: number;\n sleep?: (ms: number) => Promise<void>;\n warn?: (message: string) => void;\n } = {},\n ) {}\n\n /** This recorder's next position; the wire seq is `resumeFrom() + this`. */\n nextSeq(): number {\n return this.seq++;\n }\n\n private resolveBase(): Promise<number> {\n if (this.base === null) {\n const resolve = this.opts.resumeFrom ?? (async () => 0);\n this.base = resolve().then((n) => {\n if (!Number.isInteger(n) || n < 0)\n throw new Error(\n `browser event base seq must be a non-negative integer, got ${String(n)}`,\n );\n return n;\n });\n // A failed lookup is retried with the batch, not remembered.\n this.base.catch(() => {\n this.base = null;\n });\n }\n return this.base;\n }\n\n record(event: BrowserActionEvent): void {\n this.queue.push(event);\n if (this.queue.length >= (this.opts.batchSize ?? EVENT_BATCH_SIZE)) {\n this.drain();\n } else if (this.timer === null) {\n this.timer = setTimeout(\n () => this.drain(),\n this.opts.flushIntervalMs ?? EVENT_FLUSH_INTERVAL_MS,\n );\n if (typeof this.timer === \"object\" && \"unref\" in this.timer)\n this.timer.unref();\n }\n }\n\n /** Resolve once everything recorded so far has been posted (or dropped). */\n async flush(): Promise<void> {\n this.drain();\n await this.inflight;\n }\n\n async close(): Promise<void> {\n await this.flush();\n }\n\n private drain(): void {\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n if (this.queue.length === 0) return;\n const batch = this.queue;\n this.queue = [];\n this.inflight = this.inflight.then(() => this.send(batch));\n }\n\n private async send(batch: BrowserActionEvent[]): Promise<void> {\n const retries = this.opts.maxRetries ?? EVENT_MAX_RETRIES;\n const sleep =\n this.opts.sleep ??\n ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));\n for (let attempt = 0; attempt < retries; attempt++) {\n try {\n const base = await this.resolveBase();\n await this.post(\n base === 0 ? batch : batch.map((e) => ({ ...e, seq: base + e.seq })),\n );\n this.sent += batch.length;\n return;\n } catch (error) {\n if (attempt + 1 === retries) {\n this.dropped += batch.length;\n (this.opts.warn ?? console.warn)(\n `dropping ${batch.length} browser events after ${attempt + 1} attempts: ${String(error)}`,\n );\n return;\n }\n await sleep(500 * 2 ** attempt);\n }\n }\n }\n}\n\n/**\n * One Playwright page on the session's UI. Thin on purpose — `page` is the\n * real Playwright page for anything this wrapper does not cover.\n */\nexport class WorldBrowser {\n private current: BrowserPage;\n private inflight = 0;\n private lastNetwork = Date.now();\n /** Where the page last was after an action, token stripped: what a\n * reconnect reopens. Null until the page has left `about:blank`. */\n private lastUrl: string | null = null;\n\n constructor(\n page: BrowserPage,\n readonly ui: SessionSurfaces[\"ui\"] | undefined,\n readonly mode: Exclude<BrowserMode, \"auto\">,\n private readonly teardown: () => Promise<void>,\n readonly viewport: { width: number; height: number } = DEFAULT_VIEWPORT,\n readonly recorder: BrowserActionRecorder | null = null,\n private readonly reconnector: BrowserReconnector | null = null,\n /** Takes session credentials out of every error this browser records. */\n private readonly scrubber: SecretScrubber = new SecretScrubber([ui?.token]),\n ) {\n this.current = page;\n this.watchNetwork(page);\n }\n\n /** The live Playwright page; a new object after a reconnect. */\n get page(): BrowserPage {\n return this.current;\n }\n\n get agentId(): string | null {\n return this.recorder?.agentId ?? null;\n }\n\n private watchNetwork(page: BrowserPage): void {\n page.on(\"request\", () => {\n this.inflight += 1;\n this.lastNetwork = Date.now();\n });\n const done = () => {\n this.inflight = Math.max(0, this.inflight - 1);\n this.lastNetwork = Date.now();\n };\n page.on(\"requestfinished\", done);\n page.on(\"requestfailed\", done);\n }\n\n /** Run `fn` against the page. If it fails because the browser is gone,\n * recover; then `retry` runs it ONCE more and `report` throws\n * `BrowserReconnected` instead of replaying it. Any other error, and a\n * second loss during the retry, propagate unchanged. */\n private async resilient<T>(\n fn: () => Promise<T>,\n onLoss: OnBrowserLoss,\n ): Promise<T> {\n try {\n return this.remember(await fn());\n } catch (error) {\n if (!this.reconnector || !isBrowserGone(error)) throw error;\n const recovered = await this.recover(this.reconnector, error);\n if (onLoss === \"report\")\n throw new BrowserReconnected(\n recovered.outcome,\n recovered.restoredUrl,\n error,\n );\n }\n return this.remember(await fn());\n }\n\n private remember<T>(result: T): T {\n this.lastUrl = this.openedUrl() ?? this.lastUrl;\n return result;\n }\n\n /** The page's URL less its token; null while it is blank. */\n private openedUrl(): string | null {\n const url = this.page.url();\n return url && url !== \"about:blank\" ? withoutUiToken(url) : null;\n }\n\n private async recover(\n reconnector: BrowserReconnector,\n cause: unknown,\n ): Promise<RecoveryResult & { restoredUrl: string | null }> {\n const started = Date.now();\n const message = cause instanceof Error ? cause.message : String(cause);\n const args = { cause: this.scrubber.scrub(message).slice(0, 200) };\n let result: RecoveryResult;\n try {\n result = await reconnector.recover(cause, (c) => this.adopt(c));\n } catch (error) {\n await this.report(\"browser_reconnect\", args, started, error);\n throw error;\n }\n const restoredUrl = this.openedUrl();\n await this.report(\n \"browser_reconnect\",\n { ...args, ...result, restoredUrl },\n started,\n null,\n );\n return { ...result, restoredUrl };\n }\n\n /** Take over a new connection's page and reopen the page the agent was on\n * (`openBrowser` owns the connection itself). A new browser has no session\n * cookie, so a World Host UI is first loaded with its token, exactly as\n * `goto()` loads the entry page. */\n private async adopt(connection: BrowserConnection): Promise<void> {\n this.current = connection.page;\n this.inflight = 0;\n this.watchNetwork(connection.page);\n const last = this.lastUrl;\n if (!last) return;\n if (this.ui?.token)\n await this.page.goto(uiEntryUrl(this.ui), { waitUntil: \"load\" });\n if (withoutUiToken(this.page.url()) !== last)\n await this.page.goto(last, { waitUntil: \"load\" });\n await this.settle();\n }\n\n /** Run one action and report it: the event carries what was asked,\n * whether it worked, and the screen after — for failures too, so a\n * reviewer sees what the agent saw when the selector did not match. */\n private async act<T>(\n action: string,\n args: Record<string, unknown>,\n fn: () => Promise<T>,\n onLoss: OnBrowserLoss = \"report\",\n ): Promise<T> {\n const started = Date.now();\n try {\n const result = await this.resilient(fn, onLoss);\n await this.report(action, args, started, null);\n return result;\n } catch (error) {\n await this.report(action, args, started, error);\n throw error;\n }\n }\n\n /** One event on the recorder, if there is one; `failure` null means ok. */\n private async report(\n action: string,\n args: Record<string, unknown>,\n started: number,\n failure: unknown,\n ): Promise<void> {\n const recorder = this.recorder;\n if (!recorder) return;\n const error =\n failure === null\n ? null\n : this.scrubber\n .scrub(\n failure instanceof Error\n ? `${failure.name}: ${failure.message}`\n : String(failure),\n )\n .slice(0, 4000);\n recorder.record({\n agentId: recorder.agentId,\n seq: recorder.nextSeq(),\n ts: new Date().toISOString(),\n action,\n args: redactActionArgs(action, args),\n ok: failure === null,\n error,\n durationMs: Date.now() - started,\n mode: this.mode,\n viewport: { ...this.viewport },\n ...(await this.observeForEvent()),\n });\n }\n\n private async observeForEvent(): Promise<\n Pick<BrowserActionEvent, \"url\" | \"title\" | \"screenshot\">\n > {\n const out: Pick<BrowserActionEvent, \"url\" | \"title\" | \"screenshot\"> = {\n url: null,\n title: null,\n screenshot: null,\n };\n try {\n out.url = this.page.url();\n out.title = await this.page.title();\n const jpeg = await this.page.screenshot({\n type: \"jpeg\",\n quality: EVENT_SCREENSHOT_QUALITY,\n });\n out.screenshot = jpeg.toString(\"base64\");\n } catch {\n // a closed page still gets its event\n }\n return out;\n }\n\n /** Open a UI path (`/customers`), a full URL, or — with no argument — the\n * UI's declared entry page. */\n async goto(pathOrUrl?: string): Promise<string> {\n let target: string;\n if (pathOrUrl === undefined) {\n if (!this.ui)\n throw new WorldSurfaceUnavailable(\n \"ui\",\n \"this session has no UI to navigate to\",\n );\n target = uiEntryUrl(this.ui);\n } else if (/^https?:\\/\\//.test(pathOrUrl)) {\n target = pathOrUrl;\n } else {\n if (!this.ui)\n throw new WorldSurfaceUnavailable(\n \"ui\",\n \"relative paths need a UI surface\",\n );\n target = uiUrl(this.ui, pathOrUrl);\n }\n return this.act(\n \"browser_goto\",\n { path: pathOrUrl ?? null, url: withoutUiToken(target) },\n async () => {\n await this.page.goto(target, { waitUntil: \"load\" });\n await this.settle();\n return this.page.url();\n },\n // Navigating again lands on the same page: safe to replay.\n \"retry\",\n );\n }\n\n async back(): Promise<string> {\n return this.act(\"browser_back\", {}, async () => {\n await this.page.goBack({ waitUntil: \"load\" });\n await this.settle();\n return this.page.url();\n });\n }\n\n /** Wait for the page to finish reacting to an action. `load` alone is not\n * enough for client-rendered UIs (React et al.): a click returns before the\n * fetch that re-renders the page, so an agent would read stale text.\n * Playwright's `networkidle` is per navigation and resolves at once after\n * the first one, so this tracks requests itself: done when nothing is in\n * flight and the network has been quiet for `SETTLE_QUIET_MS`, bounded so\n * long-polling UIs cannot hang us. */\n private async settle(): Promise<void> {\n await this.page.waitForLoadState(\"load\");\n const deadline = Date.now() + SETTLE_TIMEOUT_MS;\n while (Date.now() < deadline) {\n const quiet = Date.now() - this.lastNetwork >= SETTLE_QUIET_MS;\n if (this.inflight === 0 && quiet) return;\n await this.page.waitForTimeout(SETTLE_POLL_MS);\n }\n }\n\n async click(selector: string): Promise<void> {\n await this.act(\"browser_click\", { selector }, async () => {\n await this.page.click(selector);\n await this.settle();\n });\n }\n\n async type(selector: string, text: string): Promise<void> {\n await this.act(\"browser_type\", { selector, text }, () =>\n this.page.fill(selector, text),\n );\n }\n\n async press(key: string): Promise<void> {\n await this.act(\"browser_press\", { key }, async () => {\n await this.page.keyboard.press(key);\n await this.settle();\n });\n }\n\n async scroll(dy: number): Promise<void> {\n await this.act(\"browser_scroll\", { dy }, () =>\n this.page.mouse.wheel(0, dy),\n );\n }\n\n async screenshot(fullPage = false): Promise<Buffer> {\n return this.resilient(\n () => this.page.screenshot({ type: \"png\", fullPage }),\n \"retry\",\n );\n }\n\n async screenshotBase64(fullPage = false): Promise<string> {\n return (await this.screenshot(fullPage)).toString(\"base64\");\n }\n\n async text(selector = \"body\"): Promise<string> {\n return this.resilient(() => this.page.innerText(selector), \"retry\");\n }\n\n async html(): Promise<string> {\n return this.resilient(() => this.page.content(), \"retry\");\n }\n\n get url(): string {\n return this.page.url();\n }\n\n async title(): Promise<string> {\n return this.resilient(() => this.page.title(), \"retry\");\n }\n\n async close(): Promise<void> {\n try {\n await this.teardown();\n } finally {\n await this.recorder?.close();\n }\n }\n}\n\n/** The Playwright entry points this module needs, so tests can inject a fake. */\nexport type PlaywrightLike = {\n chromium: {\n connect(wsEndpoint: string): Promise<PlaywrightBrowserLike>;\n connectOverCDP(endpointURL: string): Promise<PlaywrightBrowserLike>;\n launch(opts?: { headless?: boolean }): Promise<PlaywrightBrowserLike>;\n };\n};\n\nexport type PlaywrightBrowserLike = {\n newContext(opts?: {\n viewport?: { width: number; height: number };\n }): Promise<{ newPage(): Promise<BrowserPage>; close(): Promise<void> }>;\n close(): Promise<void>;\n};\n\nasync function loadPlaywright(): Promise<PlaywrightLike> {\n try {\n // A string specifier keeps bundlers from resolving the optional peer.\n const name = \"playwright\";\n return (await import(name)) as PlaywrightLike;\n } catch (error) {\n throw new Error(\n \"Driving a world UI needs Playwright: npm install playwright \" +\n \"(and `npx playwright install chromium` for local mode).\",\n { cause: error },\n );\n }\n}\n\nexport function resolveBrowserMode(\n surfaces: SessionSurfaces,\n mode: BrowserMode,\n): Exclude<BrowserMode, \"auto\"> {\n if (!surfaces.ui && !surfaces.browser)\n throw new WorldSurfaceUnavailable(\n \"ui\",\n \"open the session with surfaces: ['ui'] on a world that declares [ui]\",\n );\n const resolved =\n mode === \"auto\" ? (surfaces.browser ? \"hosted\" : \"local\") : mode;\n if (resolved === \"hosted\" && !surfaces.browser)\n throw new WorldSurfaceUnavailable(\n \"browser\",\n \"open the session with surfaces: ['browser'] to get a hosted browser\",\n );\n return resolved;\n}\n\n/** Open a browser on the session's UI in `hosted`, `local` or `auto` mode. */\nexport async function openBrowser(\n surfaces: SessionSurfaces,\n opts: {\n mode?: BrowserMode;\n headless?: boolean;\n playwright?: PlaywrightLike;\n recorder?: BrowserActionRecorder | null;\n /** The session's repair call (`session.repairBrowser`). Given, a hosted\n * `cdp` browser reconnects on its own when the browser is lost. */\n repair?: () => Promise<RepairAnswer>;\n } = {},\n): Promise<WorldBrowser> {\n const mode = resolveBrowserMode(surfaces, opts.mode ?? \"auto\");\n const pw = opts.playwright ?? (await loadPlaywright());\n const viewport = surfaces.browser?.viewport ?? DEFAULT_VIEWPORT;\n const attach = async (): Promise<BrowserConnection> => {\n const browser =\n mode === \"hosted\"\n ? surfaces.browser!.protocol === \"playwright\"\n ? await pw.chromium.connect(surfaces.browser!.wsUrl)\n : await pw.chromium.connectOverCDP(surfaces.browser!.wsUrl)\n : await pw.chromium.launch({ headless: opts.headless ?? true });\n const context = await browser.newContext({ viewport });\n return { browser, context, page: await context.newPage() };\n };\n let live = await attach();\n /** The same address again; the lost connection is released once a new one\n * stands. */\n const reattach = async (): Promise<BrowserConnection> => {\n const fresh = await attach();\n await releaseConnection(live);\n live = fresh;\n return fresh;\n };\n // A browser error quotes the URL it failed on; these carry the session.\n const scrubber = new SecretScrubber([\n surfaces.browser?.wsUrl,\n surfaces.ui?.token,\n ]);\n // Only the platform's relay can be repaired behind the same address.\n const reconnector =\n mode === \"hosted\" && surfaces.browser!.protocol === \"cdp\" && opts.repair\n ? new BrowserReconnector(opts.repair, reattach, {\n scrub: (text) => scrubber.scrub(text),\n })\n : null;\n return new WorldBrowser(\n live.page,\n surfaces.ui,\n mode,\n () => closeConnection(live),\n viewport,\n opts.recorder ?? null,\n reconnector,\n scrubber,\n );\n}\n\n// ── computer-use tools ───────────────────────────────────────────────────────\n\nexport const COMPUTER_USE_SPECS = [\n {\n name: \"browser_goto\",\n signature: \"browser_goto(path=None)\",\n doc: \"Open a page of the world's UI. `path` is a UI path like /customers, a full URL, or omitted for the entry page. Returns the URL and page text.\",\n },\n {\n name: \"browser_click\",\n signature: \"browser_click(selector)\",\n doc: \"Click an element by Playwright selector (CSS, `text=Refund`, `role=button[name=Save]`). Returns the page text after the click.\",\n },\n {\n name: \"browser_type\",\n signature: \"browser_type(selector, text)\",\n doc: \"Replace the value of an input/textarea found by selector with `text`.\",\n },\n {\n name: \"browser_press\",\n signature: \"browser_press(key)\",\n doc: \"Press a key (Enter, Tab, Escape, ArrowDown, ...). Returns the page text after.\",\n },\n {\n name: \"browser_scroll\",\n signature: \"browser_scroll(dy=600)\",\n doc: \"Scroll the page vertically by `dy` pixels (negative scrolls up).\",\n },\n {\n name: \"browser_screenshot\",\n signature: \"browser_screenshot(full_page=False)\",\n doc: \"Take a PNG screenshot; returns {image_base64, url}.\",\n },\n {\n name: \"browser_read\",\n signature: \"browser_read(selector='body')\",\n doc: \"Return the visible text of an element (default: whole page) plus the URL and title.\",\n },\n {\n name: \"browser_back\",\n signature: \"browser_back()\",\n doc: \"Go back one page in history.\",\n },\n] as const;\n\nconst str = (v: unknown, fallback: string): string =>\n typeof v === \"string\" && v.length > 0 ? v : fallback;\n\n/**\n * The browser as model tools, in the same `WorldToolkit` shape the world's\n * own tools come in — so an agent loop that already dispatches\n * `toolkit().impls` merges `computerUseToolkit(b).impls` and gains a screen\n * without a second dispatch path.\n */\nexport function computerUseToolkit(\n browser: WorldBrowser,\n opts: { maxText?: number } = {},\n): WorldToolkit {\n const maxText = opts.maxText ?? 20_000;\n const observe = async (selector = \"body\") => {\n const text = await browser.text(selector);\n return {\n url: browser.url,\n title: await browser.title(),\n text: text.slice(0, maxText),\n truncated: text.length > maxText,\n };\n };\n\n const impls: WorldToolkit[\"impls\"] = {\n browser_goto: async (a) => {\n await browser.goto(typeof a.path === \"string\" ? a.path : undefined);\n return observe();\n },\n browser_click: async (a) => {\n await browser.click(str(a.selector, \"\"));\n return observe();\n },\n browser_type: async (a) => {\n await browser.type(str(a.selector, \"\"), String(a.text ?? \"\"));\n return { ok: true, url: browser.url };\n },\n browser_press: async (a) => {\n await browser.press(str(a.key, \"Enter\"));\n return observe();\n },\n browser_scroll: async (a) => {\n await browser.scroll(typeof a.dy === \"number\" ? a.dy : 600);\n return { ok: true, url: browser.url };\n },\n browser_screenshot: async (a) => ({\n image_base64: await browser.screenshotBase64(a.full_page === true),\n url: browser.url,\n }),\n browser_read: async (a) => observe(str(a.selector, \"body\")),\n browser_back: async () => {\n await browser.back();\n return observe();\n },\n };\n\n const specs = COMPUTER_USE_SPECS.map((s) => ({ ...s }));\n return {\n schemas: specs.map((spec) => schemaFromSignature(spec)),\n impls,\n specs,\n };\n}\n","/**\n * THE NUMBERS AND WORDS A WORLD SESSION PROMISES — the TypeScript SDK twin.\n *\n * The platform declares them once in\n * `gateway/packages/shared/src/server/services/worldSessionContract.ts`; this\n * module and `gatewaysdk/environment/world_session_contract.py` repeat them, and each is\n * pinned to `conformance/world-sessions.json` by a test, so the route, the\n * World Host and the two CLIs cannot drift apart.\n */\n\n/** The largest body `POST world-sessions/{id}/calls` accepts. The SDK\n * measures the serialized body against the byte count and refuses before\n * sending; the label is what help and the refusal name. */\nexport const CALL_BODY_LIMIT_BYTES = 4 * 1024 * 1024;\nexport const CALL_BODY_LIMIT_LABEL = \"4mb\";\n\n/** `session status` warns once an unpinned session has less than this left. */\nexport const IDLE_WARNING_MINUTES = 5;\n\n/** The task an exploratory session runs on when the caller names none, and\n * the `task.source` the platform reports for it. */\nexport const EXPLORATORY_TASK = Object.freeze({\n instruction: \"exploratory session\",\n});\nexport const EXPLORATORY_TASK_SOURCE = \"none\";\n\n/** What a session that has no grader answers `grade` with, beside\n * `reward: null`. */\nexport const NO_GRADER_REASON = \"no grader\";\n\n/** The call's body exceeds the platform's limit: nothing was sent. `limit`\n * is the label the route enforces (`4mb`), `size` the body's bytes. */\nexport class WorldCallTooLarge extends Error {\n readonly code = \"payload_too_large\";\n\n constructor(\n readonly size: number,\n readonly limitBytes: number = CALL_BODY_LIMIT_BYTES,\n readonly limit: string = CALL_BODY_LIMIT_LABEL,\n ) {\n super(\n `call body is ${size} bytes; the platform accepts at most ${limit} (${limitBytes} bytes)`,\n );\n this.name = \"WorldCallTooLarge\";\n }\n\n /** The structured refusal the CLIs print. */\n toJSON(): {\n status: \"error\";\n code: \"payload_too_large\";\n limit: string;\n size: number;\n } {\n return {\n status: \"error\",\n code: this.code,\n limit: this.limit,\n size: this.size,\n };\n }\n}\n\n/** Measure a call body the way the route will and refuse an oversized one\n * before it leaves the machine. Returns the serialized body. */\nexport function serializeCallBody(body: unknown): string {\n const text = JSON.stringify(body);\n const size = Buffer.byteLength(text, \"utf8\");\n if (size > CALL_BODY_LIMIT_BYTES) throw new WorldCallTooLarge(size);\n return text;\n}\n\n/** The line `session status` prints when an unpinned session has under\n * `IDLE_WARNING_MINUTES` left, else null. `now` is for tests. */\nexport function idleWarning(\n idleExpiresAt: string | null | undefined,\n now: Date = new Date(),\n): string | null {\n if (!idleExpiresAt) return null;\n const leftMs = new Date(idleExpiresAt).getTime() - now.getTime();\n if (leftMs >= IDLE_WARNING_MINUTES * 60_000) return null;\n const minutes = Math.max(0, Math.floor(leftMs / 60_000));\n return (\n `warning: session expires in ${minutes}m (idle TTL); ` +\n \"call a tool to extend it or `gateway worlds session pin` to keep it\"\n );\n}\n","import type {\n WorldSessionTask,\n WorldTaskIdRef,\n WorldTaskRef,\n WorldTaskSpec,\n} from \"./session\";\n\n/**\n * The three shapes a task reaches `openSession` in — a bundled scenario's\n * name, a stored task's `{ id, version? }`, an inline spec — and how each is\n * told apart, labelled and checked. No task at all (`undefined`) is the\n * fourth case, an exploratory session, and is not a ref.\n */\n\nexport const isTaskIdRef = (task: WorldTaskRef): task is WorldTaskIdRef =>\n typeof task === \"object\" && task !== null && \"id\" in task;\n\nexport const isTaskSpec = (task: WorldTaskRef): task is WorldTaskSpec =>\n typeof task === \"object\" && task !== null && \"instruction\" in task;\n\n/** The label a task goes by in results: its name, `inline:<hash>` for an\n * unnamed inline task once the platform has hashed it, or the stored task's\n * name (its id until the platform has answered). */\nexport const taskLabel = (\n task: WorldTaskRef,\n info?: WorldSessionTask | null,\n): string => {\n if (typeof task === \"string\") return task;\n if (isTaskIdRef(task)) return info?.name ?? task.id;\n if (task.name) return task.name;\n return info?.hash ? `inline:${info.hash.slice(0, 12)}` : \"inline\";\n};\n\n/** A task given to `openSession` must be one of the three shapes. */\nexport const assertTaskRef = (task: WorldTaskRef): void => {\n const malformed =\n task === null ||\n (typeof task === \"string\" && !task) ||\n (isTaskIdRef(task) && !task.id) ||\n (isTaskSpec(task) && !task.instruction) ||\n (typeof task === \"object\" && !isTaskIdRef(task) && !isTaskSpec(task));\n if (malformed)\n throw new Error(\n \"openSession needs a task: a bundled task name, a stored task { id, version? } or { instruction, seed?, grader?, metadata? } — or none at all for an exploratory session\",\n );\n};\n","import { randomUUID } from \"node:crypto\";\n\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\nimport {\n BrowserActionRecorder,\n SURFACE_KINDS,\n WorldSurfaceUnavailable,\n assertBrowserTier,\n computerUseToolkit,\n openBrowser,\n uiEntryUrl,\n type BrowserActionEvent,\n type BrowserMode,\n type BrowserTier,\n type PlaywrightLike,\n type SessionSurfaces,\n type WorldBrowser,\n type WorldSurfaceKind,\n} from \"./browser\";\nimport type { RepairAnswer } from \"./browserReconnect\";\nimport type { WorldTaskSummary } from \"./tasks\";\nimport { serializeCallBody } from \"./sessionContract\";\nimport { assertTaskRef, isTaskIdRef, isTaskSpec, taskLabel } from \"./taskRef\";\n\nexport { isTaskIdRef, isTaskSpec, taskLabel } from \"./taskRef\";\n\n/**\n * LIVE WORLD SESSIONS from TypeScript: your agent, the platform's container.\n *\n * The other two ways of running a world each give up something. Pulling the\n * bundle and executing it locally tests your agent against a COPY — your\n * python, your sqlite, your machine's idea of the environment. Dispatching a\n * hosted run gives you the real container but runs the platform's agent\n * inside it, so your agent never touches the world.\n *\n * A session is both: the platform boots the task's container and holds it\n * warm, and every `call()` here executes inside THAT container. Your agent\n * stays where it is — this file is just the wire.\n *\n * const world = await openWorld(\"revenue-ops-sim@main\");\n * const session = await openSession(world.slug, { task: \"revops-mara-dedupe-contacts\" });\n * await session.ready(); // wait for the container\n * await session.call(\"crm_search\", { entity: \"deals\" });\n * const { reward, rewards } = await session.grade();\n * await session.close({ keepWarm: true }); // hand it back to the pool\n *\n * The task can also be YOURS rather than the bundle's — an instruction, the\n * rows the session starts with and how it is graded, for one end user:\n *\n * const session = await openSession(\"acme-billing@main\", {\n * task: {\n * instruction: \"Mark invoice INV-7 as paid.\",\n * seed: { rows: { invoices: [{ id: \"INV-7\", status: \"open\" }] } },\n * grader: { kind: \"assertions\", checks: [\n * { entity: \"invoices\", where: { id: \"INV-7\", status: \"paid\" } },\n * ] },\n * metadata: { externalUserId: \"u_42\" },\n * },\n * surfaces: [\"api\"],\n * });\n *\n * Every call is a row on the platform before it is an effect in a container,\n * so the episode is on the record — and the platform traces the session\n * itself, which is why these sessions show up under Sessions without the\n * caller instrumenting anything.\n */\n\nexport type WorldToolSpec = {\n name: string;\n /** The world's own signature, e.g. `crm_search(q=None, entity=\"deals\")`. */\n signature: string;\n doc: string | null;\n inputSchema?: Record<string, unknown>;\n};\n\n/** What a model needs to call a world: the schemas to advertise, and the\n * implementations that run them in the container. */\nexport type WorldToolkit = {\n /** OpenAI-shaped tool definitions, derived from the world's signatures. */\n schemas: {\n type: \"function\";\n function: {\n name: string;\n description: string;\n parameters: Record<string, unknown>;\n };\n }[];\n /** name -> implementation, each one a call into THIS session. */\n impls: Record<string, (args: Record<string, unknown>) => Promise<unknown>>;\n specs: WorldToolSpec[];\n};\n\n// ── tasks ────────────────────────────────────────────────────────────────────\n\n/** A JSON scalar: what `where` filters and field predicates compare against. */\nexport type WorldTaskScalar = string | number | boolean | null;\n\n/** The rows a task starts the session with — the `seed()` contract, applied\n * by the host right after it clones the version's snapshot. `append`\n * (default) upserts by primary key onto the base data; `replace` makes the\n * named entities hold exactly these rows. */\nexport type WorldTaskSeed = {\n mode?: \"append\" | \"replace\";\n /** Redaction on the way in: `off` (default) stores the rows as given,\n * `apply` runs the world's `[redact]` policy over them first, `refuse`\n * rejects a row carrying plaintext in a redacted field. */\n redact?: \"off\" | \"apply\" | \"refuse\";\n rows: Record<string, Record<string, unknown>[]>;\n};\n\nexport type WorldTaskFieldOp =\n \"eq\" | \"neq\" | \"in\" | \"gt\" | \"gte\" | \"lt\" | \"lte\" | \"contains\";\n\n/**\n * One declarative check over the session's final rows. `where` selects rows\n * of `entity` by equality (dotted paths reach into nested objects); the\n * assertion says what must hold of the selection:\n *\n * exists (default) / absent at least one row / none\n * count `count` bound on how many\n * all / any `field op value` on every / some selected row\n *\n * A check's `id` names its entry in `rewards`; the task's reward is the\n * weighted share of checks that passed.\n */\nexport type WorldTaskCheck = {\n id?: string;\n weight?: number;\n entity: string;\n where?: Record<string, WorldTaskScalar>;\n assert?: \"exists\" | \"absent\" | \"count\" | \"all\" | \"any\";\n count?: { eq?: number; gte?: number; lte?: number };\n field?: string;\n op?: WorldTaskFieldOp;\n value?: WorldTaskScalar | WorldTaskScalar[];\n};\n\n/** One thing a rubric judge scores in [0, 1]; `id` names its entry in\n * `rewards`, `weight` (default 1) its share of the task's reward. */\nexport type WorldTaskRubricCriterion = {\n id: string;\n description: string;\n weight?: number;\n};\n\n/** A rubric is prose: what a good outcome looks like. The platform (never the\n * host) has a model read the session's final state and its call log against\n * it; the project's default evaluation model judges unless `model` pins one.\n * `grade()` then resolves asynchronously — `pending: true` first, the reward\n * once the judge has answered. */\nexport type WorldTaskRubricGrader = {\n kind: \"rubric\";\n rubric: string;\n criteria?: WorldTaskRubricCriterion[];\n model?: { provider: string; model: string };\n};\n\n/** How a task is graded: checks the host evaluates in-process, a `verify.py`\n * body (state JSON on stdin, last stdout line `{reward, ...}`) run through the\n * host's confined verifier, or a rubric judged by a model on the platform. */\nexport type WorldTaskGrader =\n | { kind: \"assertions\"; checks: WorldTaskCheck[] }\n | { kind: \"python\"; source: string; timeoutSeconds?: number }\n | WorldTaskRubricGrader;\n\n/** A task supplied at open, for one session, instead of a bundled scenario.\n * `instruction` is what the agent is told; without `seed` the session starts\n * on the version's base data, without `grader` `grade()` answers\n * `reward: null`; `tools` is the allow-list of the version's tools the agent\n * may call in this session (unset: all of them; a call outside it is refused\n * and logged); `metadata` is yours (an end-user id, a ticket) and is echoed\n * on the session, never read. Limits: shared/domain/worldTasks.ts. */\nexport type WorldTaskSpec = {\n name?: string;\n instruction: string;\n seed?: WorldTaskSeed;\n grader?: WorldTaskGrader;\n tools?: string[];\n metadata?: Record<string, unknown>;\n /** A MULTI-WORLD task: one session per alias, each on its own world with\n * its own seed, grader and tools (the top-level three are then refused).\n * Brought up together by `openTask` / `gateway worlds task up`; see\n * worlds/taskSessions.ts. */\n worlds?: Record<\n string,\n {\n slug: string;\n /** One of the world's refs; default `main`. */\n ref?: string;\n seed?: WorldTaskSeed;\n grader?: WorldTaskGrader;\n tools?: string[];\n }\n >;\n /** CROSS-WORLD VERIFIERS: deterministic graders over several of the task's\n * worlds at once, each with a `scope` of aliases (two or more). One runs on\n * the session of the first alias in its scope, over a state where every\n * scoped world's rows are `<alias>.<entity>` and its calls `<alias>.calls`;\n * the platform gathers the other worlds' evidence when `grade()` names\n * them (`TaskSessions.grade` does). Rewards come back as `x.<name>`. */\n verifiers?: WorldTaskVerifier[];\n};\n\nexport type WorldTaskVerifier = { name: string; scope: string[] } & (\n | { kind: \"assertions\"; checks: WorldTaskCheck[] }\n | { kind: \"python\"; source: string; timeoutSeconds?: number }\n);\n\n/** A stored task of the project (see worlds/tasks.ts), opened by id; the\n * session runs a copy of one version's spec — the current one by default. */\nexport type WorldTaskIdRef = { id: string; version?: number };\n\n/** What `openSession` takes as the task: a bundled scenario's name, a\n * stored task's `{ id, version? }`, or an inline spec. */\nexport type WorldTaskRef = string | WorldTaskIdRef | WorldTaskSpec;\n\n/** What a session's task is, on every session response. `hash` is the\n * content hash of the spec (inline or stored) — what warm reuse matches on;\n * `id`/`version` name the stored task the session was opened on. */\nexport type WorldSessionTask = {\n /** `none` is an exploratory session: opened with no task, no grader. */\n source: \"bundled\" | \"inline\" | \"stored\" | \"none\";\n name: string | null;\n hash: string | null;\n id?: string | null;\n version?: number | null;\n metadata: Record<string, unknown>;\n};\n\nexport type SeedResult = {\n seeded: number;\n mode: \"append\" | \"replace\";\n entity_counts: Record<string, number>;\n};\n\n/** One row of the session's call log. */\nexport type WorldSessionCall = {\n seq: number;\n kind: string;\n tool: string | null;\n args: unknown;\n result: unknown;\n error: string | null;\n completedAt: string | null;\n};\n\nexport type WorldSessionState = {\n sessionId: string;\n state: string;\n ready: boolean;\n versionId: string;\n contentHash: string;\n taskName: string | null;\n /** Where the task came from and what it is; absent on platforms that\n * predate session tasks, in which case it is derived from `taskName`. */\n task?: WorldSessionTask;\n /** The task's objective — present when the session was opened (not on a\n * bare status read), so a client never needs the bundle on disk. */\n instruction?: string | null;\n /** The tools this task serves. */\n tools?: WorldToolSpec[];\n /** When the fleet reaps this session unless a call lands first; null for\n * a pinned session (never reaped). Absent on platforms that predate it. */\n idleExpiresAt?: string | null;\n pinned?: boolean;\n /** Where the session answers besides `tools` — see worlds/browser.ts. */\n surfaces?: SessionSurfaces;\n /** Notices about the world's shape (an api bundle is a deprecated layout;\n * schema worlds are the supported shape), with what to run instead. Empty\n * for a schema world; absent on platforms that predate the notice. */\n deprecations?: WorldDeprecation[];\n};\n\n/** One notice a worlds-path answer carries: a deprecated shape or layout\n * and the command that replaces it. A retired shape is refused instead,\n * with the stable message prefix `world_kind_retired:`. */\nexport type WorldDeprecation = {\n code: string;\n message: string;\n replacement: string;\n};\n\nexport type GradeResult = {\n reward: number | null;\n rewards: Record<string, number>;\n /** Why there is no reward: `no grader` on an exploratory session. */\n reason?: string;\n /** The task's cross-world verifiers anchored on this session, by name:\n * each its own reward and named rewards, or `error` when it could not\n * grade (evidence missing, verify.py failed) — null, never zero. */\n verifiers?: Record<string, VerifierGrade>;\n raw: unknown;\n};\n\nexport type VerifierGrade = {\n reward: number | null;\n rewards: Record<string, number>;\n error?: string;\n};\n\n/** A grade payload's numbers: `reward`, and every numeric key under\n * `rewards` (the host's shape) or at the top level (a bundled verifier's). */\nfunction numericGrade(record: Record<string, unknown>): {\n reward: number | null;\n rewards: Record<string, number>;\n} {\n const rewards: Record<string, number> = {};\n const nested = record.rewards;\n if (nested && typeof nested === \"object\") {\n for (const [key, value] of Object.entries(nested)) {\n if (typeof value === \"number\") rewards[key] = value;\n }\n }\n for (const [key, value] of Object.entries(record)) {\n if (key !== \"reward\" && typeof value === \"number\") rewards[key] = value;\n }\n return {\n reward: typeof record.reward === \"number\" ? record.reward : null,\n rewards,\n };\n}\n\n/** The `verifiers` block of a grade payload, or undefined when absent. */\nfunction verifierGrades(\n value: unknown,\n): Record<string, VerifierGrade> | undefined {\n if (!value || typeof value !== \"object\") return undefined;\n const out: Record<string, VerifierGrade> = {};\n for (const [name, grade] of Object.entries(value as Record<string, unknown>)) {\n const record =\n grade && typeof grade === \"object\"\n ? (grade as Record<string, unknown>)\n : {};\n out[name] = {\n ...numericGrade(record),\n ...(typeof record.error === \"string\" ? { error: record.error } : {}),\n };\n }\n return out;\n}\n\n/** How long `ready()` waits, and how often it asks. */\nconst READY_TIMEOUT_MS = 10 * 60_000;\nconst READY_POLL_MS = 2_000;\n/** How long one call may take end to end (container claim + execution). */\nconst CALL_TIMEOUT_MS = 3 * 60_000;\nconst CALL_POLL_MS = 400;\n/** How long a grade the platform's judge finalizes may take: the model's own\n * timeout and retries, plus the worker's queue backoff. Polled slowly. */\nconst JUDGED_GRADE_TIMEOUT_MS = 15 * 60_000;\nconst JUDGED_GRADE_POLL_MS = 2_000;\nconst EXPORT_PAGE = 500;\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\nexport const modelToolName = (name: string): string =>\n name.replace(/[^A-Za-z0-9_-]/g, \"_\").slice(0, 64) || \"tool\";\n\n/**\n * Turn a world's Python signature into a JSON schema the model can call.\n *\n * `crm_update_deal(id, stage=None, owner=None, amount=None)` becomes an\n * object with `id` required and the rest optional. Types are read from the\n * DEFAULTS the world declares — a numeric default means a number, a boolean\n * default a boolean — because that is the only type information a signature\n * actually carries. Everything else is a string, which is what a tool CLI\n * receives anyway.\n */\nexport function schemaFromSignature(spec: WorldToolSpec): {\n type: \"function\";\n function: {\n name: string;\n description: string;\n parameters: Record<string, unknown>;\n };\n} {\n if (spec.inputSchema)\n return {\n type: \"function\",\n function: {\n name: modelToolName(spec.name),\n description: spec.doc ?? spec.name,\n parameters: spec.inputSchema,\n },\n };\n const inside = /\\(([\\s\\S]*)\\)\\s*$/.exec(spec.signature.trim())?.[1] ?? \"\";\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n // Split on top-level commas only: a default like `{\"a\": 1}` has its own.\n const params: string[] = [];\n let depth = 0;\n let current = \"\";\n for (const ch of inside) {\n if (\"([{\".includes(ch)) depth++;\n if (\")]}\".includes(ch)) depth--;\n if (ch === \",\" && depth === 0) {\n params.push(current);\n current = \"\";\n } else current += ch;\n }\n if (current.trim()) params.push(current);\n\n for (const raw of params) {\n const param = raw.trim();\n if (!param || param.startsWith(\"*\") || param === \"self\") continue;\n const eq = param.indexOf(\"=\");\n const name = (eq === -1 ? param : param.slice(0, eq)).split(\":\")[0].trim();\n if (!name) continue;\n if (eq === -1) {\n properties[name] = { type: \"string\" };\n required.push(name);\n continue;\n }\n const value = param.slice(eq + 1).trim();\n if (/^-?\\d+(\\.\\d+)?$/.test(value)) properties[name] = { type: \"number\" };\n else if (value === \"True\" || value === \"False\")\n properties[name] = { type: \"boolean\" };\n else properties[name] = { type: \"string\" };\n }\n return {\n type: \"function\",\n function: {\n name: modelToolName(spec.name),\n description: spec.doc ?? spec.name,\n parameters: { type: \"object\", properties, required },\n },\n };\n}\n\nexport class WorldSessionTimeout extends Error {}\nexport class WorldSessionCallError extends Error {}\n\nexport class WorldSession {\n constructor(\n readonly sessionId: string,\n private current: WorldSessionState,\n private readonly options: WorldsClientOptions,\n ) {}\n\n /** The task's display name: a bundled scenario's, or the inline spec's\n * `name` (null when the spec was unnamed). `task` is the same. */\n get taskName(): string | null {\n return this.current.taskName;\n }\n get task(): string | null {\n return this.taskName;\n }\n\n /** `{idleExpiresAt, pinned}` as of the last state read: when the fleet\n * reaps the session (null once pinned), and whether it is pinned. */\n get idle(): { idleExpiresAt: string | null; pinned: boolean } {\n return {\n idleExpiresAt: this.current.idleExpiresAt ?? null,\n pinned: this.current.pinned ?? false,\n };\n }\n\n /** The platform's notices about the world this session runs on (empty\n * for a schema world). Printed by the CLI on stderr at open. */\n get deprecations(): WorldDeprecation[] {\n return this.current.deprecations ?? [];\n }\n\n /** The task this session runs: bundled scenario, stored task or inline\n * spec, its name, hash and the caller's metadata. */\n get taskInfo(): WorldSessionTask {\n return (\n this.current.task ?? {\n source: \"bundled\",\n name: this.current.taskName,\n hash: null,\n metadata: {},\n }\n );\n }\n\n /** What this task asks for — the bundle's instruction.md, or the inline\n * spec's `instruction`. */\n get instruction(): string | null {\n return this.current.instruction ?? null;\n }\n\n get versionId(): string {\n return this.current.versionId;\n }\n\n /** Whether the session answered ready as of the last state read (the open,\n * a `status()`, or the poll inside `ready()`); no request is made. */\n get isReady(): boolean {\n return this.current.ready;\n }\n\n /** `api` / `ui` / `browser` are present exactly when the world declares\n * them AND the session was opened asking for them. */\n async surfaces(): Promise<SessionSurfaces> {\n if (!this.current.surfaces) await this.status();\n return this.current.surfaces ?? { tools: { kind: \"rendezvous\" } };\n }\n\n /** Base URL of the world's own HTTP API for this session. */\n async api(): Promise<string> {\n const { api } = await this.surfaces();\n if (!api)\n throw new WorldSurfaceUnavailable(\n \"api\",\n \"open the session with surfaces: ['api'] on an api-type world\",\n );\n return api.url;\n }\n\n /** Headers every request to `api()` needs. A World Host session gates its\n * api surface on a per-session token; a pod or hosted twin answers with the\n * world's own declared auth and this is `{}`. */\n async apiHeaders(): Promise<Record<string, string>> {\n const { api } = await this.surfaces();\n return api?.token ? { Authorization: `Bearer ${api.token}` } : {};\n }\n\n /** URL of the world's UI entry page for this session. */\n async ui(): Promise<string> {\n const { ui } = await this.surfaces();\n if (!ui)\n throw new WorldSurfaceUnavailable(\n \"ui\",\n \"open the session with surfaces: ['ui'] on a world that declares [ui]\",\n );\n return uiEntryUrl(ui);\n }\n\n /** A Playwright browser on this session's UI: `hosted` drives the one the\n * platform runs next to the world, `local` launches one here, `auto`\n * prefers hosted. Call `close()` when done.\n *\n * Every action is reported to the platform under `agentId` (default:\n * `GATEWAY_AGENT_ID` or a fresh `agent-<hex>`) so the session page shows\n * this agent's own timeline — several agents may share one session and\n * one hosted browser. `record: false` opts out. */\n async browser(\n opts: {\n mode?: BrowserMode;\n headless?: boolean;\n playwright?: PlaywrightLike;\n agentId?: string;\n record?: boolean;\n } = {},\n ): Promise<WorldBrowser> {\n const { agentId, record = true, ...rest } = opts;\n return openBrowser(await this.surfaces(), {\n ...rest,\n recorder: record ? this.browserRecorder(agentId) : null,\n repair: () => this.repairBrowser(),\n });\n }\n\n /** Ask the platform to make this session's hosted browser reachable again\n * after its connection dropped: `healthy` (reconnect now), `replaced` (a new,\n * blank browser behind the same wsUrl; reconnect and reopen your page) or\n * `starting` (ask again in `retryAfterMs`). `browser()` does this on its\n * own; call it when you drive your own Playwright against `wsUrl`. */\n async repairBrowser(): Promise<RepairAnswer> {\n return apiRequest<RepairAnswer>(\n this.options,\n \"POST\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/browser-repair`,\n {},\n );\n }\n\n /** The reporter `browser()` uses; exposed for a page you drive yourself. */\n browserRecorder(agentId?: string): BrowserActionRecorder {\n const path = `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/browser-events`;\n const id =\n agentId ??\n process.env.GATEWAY_AGENT_ID ??\n `agent-${randomUUID().replace(/-/g, \"\").slice(0, 8)}`;\n return new BrowserActionRecorder(\n async (events: BrowserActionEvent[]) => {\n await apiRequest(this.options, \"POST\", path, { events });\n },\n id,\n {\n // Continue this agent's timeline where the platform has it, so the\n // same id reopened later never re-numbers from zero.\n resumeFrom: async () => {\n const summary = await apiRequest<{\n agents: { agentId: string; nextSeq: number }[];\n }>(this.options, \"GET\", path);\n return summary.agents.find((a) => a.agentId === id)?.nextSeq ?? 0;\n },\n },\n );\n }\n\n /** Browser actions as model tools, in the same shape as `toolkit()`. */\n computerUseTools(browser: WorldBrowser): WorldToolkit {\n return computerUseToolkit(browser);\n }\n\n /** The session's latest platform state (one request, no waiting). */\n async status(): Promise<WorldSessionState> {\n const fresh = await apiRequest<WorldSessionState>(\n this.options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}`,\n );\n // A status read does not carry the objective; keep the one we opened with.\n this.current = {\n instruction: this.current.instruction,\n tools: this.current.tools,\n surfaces: this.current.surfaces,\n task: this.current.task,\n ...fresh,\n };\n return this.current;\n }\n\n /**\n * Wait until the container is warm — meaning the process inside it has\n * asked the platform for work, not merely that a job was accepted.\n */\n async ready(opts: { timeoutMs?: number } = {}): Promise<WorldSessionState> {\n const deadline = Date.now() + (opts.timeoutMs ?? READY_TIMEOUT_MS);\n for (;;) {\n const state = await this.status();\n if (state.ready) return state;\n if (state.state === \"FAILED\" || state.state === \"STOPPED\")\n throw new WorldSessionCallError(\n `World session ${state.state.toLowerCase()} before it was ready.`,\n );\n if (Date.now() > deadline)\n throw new WorldSessionTimeout(\n `World session still ${state.state} after ${Math.round((opts.timeoutMs ?? READY_TIMEOUT_MS) / 1000)}s.`,\n );\n await sleep(READY_POLL_MS);\n }\n }\n\n /** Enqueue one interaction and wait for the container's answer. */\n private async exchange(\n body: {\n kind?: \"call\" | \"grade\" | \"reset\" | \"state\" | \"seed\" | \"close\";\n tool?: string;\n args?: unknown;\n /** Grade only: the agent's report, for a rubric judge. */\n report?: string;\n },\n timeoutMs?: number,\n ): Promise<unknown> {\n // Measured the way the route measures it; over the limit nothing is sent.\n serializeCallBody(body);\n const enqueued = await apiRequest<{\n callId: string;\n seq: number;\n /** The platform's worker finalizes this call (a rubric grade). */\n pending?: boolean;\n }>(\n this.options,\n \"POST\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/calls`,\n body,\n );\n const { callId } = enqueued;\n const judged = enqueued.pending === true;\n const budgetMs =\n timeoutMs ?? (judged ? JUDGED_GRADE_TIMEOUT_MS : CALL_TIMEOUT_MS);\n const pollMs = judged ? JUDGED_GRADE_POLL_MS : CALL_POLL_MS;\n const deadline = Date.now() + budgetMs;\n for (;;) {\n const call = await apiRequest<{\n done: boolean;\n state: string;\n result: unknown;\n error: string | null;\n }>(\n this.options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/calls/${encodeURIComponent(callId)}`,\n );\n if (call.done) {\n if (call.error) throw new WorldSessionCallError(call.error);\n return call.result;\n }\n if (Date.now() > deadline)\n throw new WorldSessionTimeout(\n judged\n ? `Grade ${callId} still ${call.state} after ${Math.round(budgetMs / 1000)}s — the judge has not answered; the platform finalizes the call on its own, read it back with export().`\n : `Call ${callId} still ${call.state} after ${Math.round(budgetMs / 1000)}s — the container may have died.`,\n );\n await sleep(pollMs);\n }\n }\n\n /**\n * Run one of the world's tools INSIDE the container. The arguments and the\n * result are the world's own contract — this layer neither validates nor\n * reshapes them, so a tool error reads exactly as it would in a hosted run.\n */\n async call(\n tool: string,\n args: Record<string, unknown> = {},\n opts: { timeoutMs?: number } = {},\n ): Promise<unknown> {\n return this.exchange({ kind: \"call\", tool, args }, opts.timeoutMs);\n }\n\n /**\n * THE WORLD'S TOOLS, READY TO HAND TO A MODEL. Schemas come from the\n * world's own signatures and implementations call into this session, so a\n * caller never writes — and never has to re-sync — a tool map of their own:\n *\n * const { schemas, impls } = await session.toolkit();\n * await runMyAgent(impls, schemas, session.instruction);\n *\n * A tool added to the world shows up here on the next run; a tool renamed\n * in the world renames here too, instead of failing at call time against a\n * hand-written map that still remembers the old name.\n */\n async toolkit(): Promise<WorldToolkit> {\n let specs = this.current.tools;\n if (!specs) specs = (await this.status()).tools ?? [];\n const impls: WorldToolkit[\"impls\"] = Object.create(null);\n for (const spec of specs) {\n const alias = modelToolName(spec.name);\n if (Object.hasOwn(impls, alias))\n throw new WorldSessionCallError(`Model tool name collision: ${alias}`);\n impls[alias] = (args: Record<string, unknown> = {}) =>\n this.call(spec.name, args);\n }\n return { schemas: specs.map(schemaFromSignature), impls, specs };\n }\n\n /** Run the task's grader against the container's END STATE. Graders answer\n * in one of two shapes: the scalar with named rewards beside it\n * (`{reward, check_a, check_b}`, a task's own `grade.py`), or the named\n * rewards nested under `rewards` (the api, mock-tools and World Host\n * runners). Both land in `rewards`.\n *\n * A rubric grade is finalized by the platform's judge, not the container:\n * the platform answers the enqueue with `pending: true`, and this waits on\n * the judge's budget (15 min) instead of a call's. `timeoutMs` overrides\n * either. `report` is the agent's own account of what it did and found,\n * handed to the judge as its claim beside the evidence (the state and the\n * calls); assertions and python graders ignore it. `worlds` names the\n * task's other sessions by alias (`{alias: sessionId}`): the platform\n * reads each one's evidence and hands it to the cross-world verifiers\n * anchored on this session, whose grades come back under `verifiers`. */\n async grade(\n opts: {\n timeoutMs?: number;\n report?: string;\n worlds?: Record<string, string>;\n } = {},\n ): Promise<GradeResult> {\n const raw = (await this.exchange(\n {\n kind: \"grade\",\n ...(opts.report !== undefined ? { report: opts.report } : {}),\n ...(opts.worlds && Object.keys(opts.worlds).length > 0\n ? { worlds: opts.worlds }\n : {}),\n },\n opts.timeoutMs,\n )) as Record<string, unknown> | null;\n const record = raw && typeof raw === \"object\" ? raw : {};\n const verifiers = verifierGrades(record.verifiers);\n return {\n ...numericGrade(record),\n ...(typeof record.reason === \"string\" ? { reason: record.reason } : {}),\n ...(verifiers ? { verifiers } : {}),\n raw,\n };\n }\n\n /**\n * Put rows into the LIVE world through its contract, in one batch:\n * `append` (default) upserts by primary key, `replace` makes the named\n * entities hold exactly these rows. Atomic — a refused row leaves the\n * session unchanged and the error names the entity, row and field.\n */\n async seed(\n rows: Record<string, Record<string, unknown>[]>,\n opts: {\n mode?: \"append\" | \"replace\";\n /** `apply` runs the world's `[redact]` policy over the rows first;\n * `refuse` rejects plaintext in a redacted field; default `off`. */\n redact?: \"off\" | \"apply\" | \"refuse\";\n timeoutMs?: number;\n } = {},\n ): Promise<SeedResult> {\n const mode = opts.mode ?? \"append\";\n const redact = opts.redact ?? \"off\";\n return (await this.exchange(\n {\n kind: \"seed\",\n args: { mode, rows, ...(redact !== \"off\" ? { redact } : {}) },\n },\n opts.timeoutMs,\n )) as SeedResult;\n }\n\n /** Every entity's rows as the world holds them now — the same dump a\n * grader reads. The shape is the world runtime's: a schema world answers\n * `{<entity>: {<key>: row}, snapshot}`, a mock-tools world\n * `{entities: {<entity>: [row]}}`. */\n async state(opts: { timeoutMs?: number } = {}): Promise<unknown> {\n return this.exchange({ kind: \"state\" }, opts.timeoutMs);\n }\n\n /** Back to the opening state: the version's data plus the bundled\n * scenario's or the inline task's seed. Rows written since are gone; the\n * call log stays. */\n async reset(opts: { timeoutMs?: number } = {}): Promise<void> {\n await this.exchange({ kind: \"reset\" }, opts.timeoutMs);\n }\n\n /** The session's call log, oldest first: every tool call, seed, reset,\n * grade with its result — the record of the episode. */\n async export(): Promise<WorldSessionCall[]> {\n const calls: WorldSessionCall[] = [];\n let cursor: string | undefined;\n do {\n const params = new URLSearchParams({ limit: String(EXPORT_PAGE) });\n if (cursor) params.set(\"cursor\", cursor);\n const page = await apiRequest<{\n calls: Record<string, unknown>[];\n nextCursor?: string | null;\n }>(\n this.options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/calls?${params.toString()}`,\n );\n for (const call of page.calls) {\n calls.push({\n seq: Number(call.seq),\n kind: String(call.kind ?? \"call\"),\n tool: typeof call.tool === \"string\" ? call.tool : null,\n args: call.args ?? null,\n result: call.result ?? null,\n error: typeof call.error === \"string\" ? call.error : null,\n completedAt:\n typeof call.completedAt === \"string\" ? call.completedAt : null,\n });\n }\n cursor = page.nextCursor ?? undefined;\n } while (cursor);\n return calls;\n }\n\n /**\n * Promote this session's inline task into a stored task of the project\n * (version 1, pinned to the session's world unless `world` says otherwise),\n * so a task written for one end user can be reused and its grades\n * compared. The session then records the new task's id. A session on a\n * bundled task has nothing to save; one on a stored task is already saved.\n */\n async saveTask(\n opts: { name?: string; world?: string | null; message?: string } = {},\n ): Promise<WorldTaskSummary> {\n const task = await apiRequest<WorldTaskSummary>(\n this.options,\n \"POST\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/task`,\n {\n ...(opts.name !== undefined ? { name: opts.name } : {}),\n ...(opts.world !== undefined ? { world: opts.world } : {}),\n ...(opts.message !== undefined ? { message: opts.message } : {}),\n },\n );\n this.current = {\n ...this.current,\n taskName: task.name,\n task: {\n ...this.taskInfo,\n source: \"stored\",\n name: task.name,\n id: task.id,\n version: task.version,\n },\n };\n return task;\n }\n\n /**\n * End the session. `keepWarm` hands the container back to the pool instead\n * of tearing it down, so the next session for the same task starts warm —\n * the pooled instance still obeys the fleet's idle TTL and pinning.\n */\n async close(opts: { keepWarm?: boolean } = {}): Promise<{ state: string }> {\n return apiRequest(\n this.options,\n \"DELETE\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}`,\n { keepWarm: opts.keepWarm ?? false },\n );\n }\n}\n\n/**\n * Attach to a session that already exists — resuming after a crash, or\n * driving a session someone else opened (a container started by hand on a\n * self-hosted install, a session opened by CI and handed to a developer).\n */\nexport async function attachSession(\n sessionId: string,\n options: WorldsClientOptions = {},\n): Promise<WorldSession> {\n const state = await apiRequest<WorldSessionState>(\n options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(sessionId)}`,\n );\n return new WorldSession(sessionId, state, options);\n}\n\nexport type OpenSessionOptions = {\n versionId?: string;\n reuseWarm?: boolean;\n /** More than `tools`: `[\"api\"]`, `[\"ui\"]`, `[\"browser\"]`. The platform\n * refuses (HTTP 400) rather than quietly serving less than asked. */\n surfaces?: WorldSurfaceKind[];\n /** Capacity for a World Host session's browser: `standard` (spot, may be\n * reclaimed) or `premium` (on-demand). Unset, the organization's default. */\n browserTier?: BrowserTier;\n options?: WorldsClientOptions;\n};\n\nconst OPEN_SESSION_OPTION_KEYS: ReadonlySet<string> = new Set([\n \"task\",\n \"versionId\",\n \"reuseWarm\",\n \"surfaces\",\n \"browserTier\",\n \"options\",\n]);\n\n/** The second argument is an options bag only when every key is one of\n * `OpenSessionOptions` (+ `task`); any other object is the positional task\n * and is validated as one, so a misspelt spec is refused, not opened bare. */\nconst isOpenSessionOptions = (\n value: unknown,\n): value is OpenSessionOptions & { task?: WorldTaskRef } =>\n typeof value === \"object\" &&\n value !== null &&\n Object.keys(value).every((key) => OPEN_SESSION_OPTION_KEYS.has(key));\n\n/**\n * Open a live session on a world. Returns as soon as the platform has\n * accepted it — call `ready()` to wait for the container.\n *\n * `task` is a bundled scenario's name, a stored task's `{ id, version? }`\n * or an inline `WorldTaskSpec` (the latter two need a host engine world — the\n * platform answers 400 for a pod world). Omitted, the session is EXPLORATORY:\n * the platform records an inline `{instruction: \"exploratory session\"}` with\n * no grader as `task.source: \"none\"`, and `grade()` answers\n * `{reward: null, reason: \"no grader\"}`. The older positional form\n * `openSession(slug, \"task-name\", opts)` still works.\n */\nexport async function openSession(\n slugOrRef: string,\n task?: OpenSessionOptions & { task?: WorldTaskRef },\n): Promise<WorldSession>;\nexport async function openSession(\n slugOrRef: string,\n task: WorldTaskRef,\n opts?: OpenSessionOptions,\n): Promise<WorldSession>;\nexport async function openSession(\n slugOrRef: string,\n taskOrOpts:\n WorldTaskRef | (OpenSessionOptions & { task?: WorldTaskRef }) = {},\n positionalOpts: OpenSessionOptions = {},\n): Promise<WorldSession> {\n const { task, ...opts } = isOpenSessionOptions(taskOrOpts)\n ? taskOrOpts\n : { task: taskOrOpts as WorldTaskRef, ...positionalOpts };\n if (task !== undefined) assertTaskRef(task);\n const options = opts.options ?? {};\n const unknown = (opts.surfaces ?? []).filter(\n (s) => !(SURFACE_KINDS as readonly string[]).includes(s),\n );\n if (unknown.length)\n throw new Error(\n `Unknown world surfaces: ${unknown.join(\", \")}; choose from ${SURFACE_KINDS.join(\", \")}`,\n );\n if (opts.browserTier !== undefined) assertBrowserTier(opts.browserTier);\n const at = slugOrRef.indexOf(\"@\");\n const slug = at === -1 ? slugOrRef : slugOrRef.slice(0, at);\n const ref = at === -1 ? \"\" : slugOrRef.slice(at + 1);\n const state = await apiRequest<WorldSessionState & { reusedWarm: boolean }>(\n options,\n \"POST\",\n \"/api/public/world-sessions\",\n {\n ...(opts.versionId\n ? { versionId: opts.versionId }\n : { slug, ...(ref && { ref }) }),\n ...(task === undefined ? {} : { task }),\n ...(opts.reuseWarm === undefined ? {} : { reuseWarm: opts.reuseWarm }),\n ...(opts.surfaces?.length ? { surfaces: opts.surfaces } : {}),\n ...(opts.browserTier === undefined\n ? {}\n : { browserTier: opts.browserTier }),\n },\n );\n return new WorldSession(state.sessionId, state, options);\n}\n\n// ── running many tasks at once ───────────────────────────────────────────────\n\nexport type SessionRunResult = {\n /** The task's name, or `inline:<hash>` for an unnamed inline task. */\n task: string;\n sessionId: string;\n reward: number | null;\n rewards: Record<string, number>;\n /** Set when the task threw instead of grading. */\n error?: string;\n};\n\nexport type SessionRunReport = {\n results: SessionRunResult[];\n /** Mean reward over every task, counting failures as 0. */\n mean: number;\n /** Tasks that never graded: the session did not open or become ready, the\n * agent threw, or grading failed. Any failure fails the run — a 0 an agent\n * earned and a session that never opened are not the same result. */\n failed: number;\n /** True when no task failed and `mean >= failUnder` (or no gate was set). */\n passed: boolean;\n};\n\n/**\n * RUN MANY TASKS IN PARALLEL, one warm container each.\n *\n * Parallelism against live worlds is the normal case — a suite is a dozen\n * tasks and each needs its own container, because two agents sharing one\n * world state would corrupt both episodes. Every caller was writing the same\n * pool, the same per-task open/ready/toolkit/grade/close, and the same\n * \"don't let one failure kill the run\" logic, so it belongs here:\n *\n * const report = await runSessions({\n * world: \"revenue-ops-sim@main\",\n * tasks, // default: every task in the world\n * concurrency: 4,\n * failUnder: 0.7,\n * agent: async ({ toolkit, instruction }) =>\n * myAgent(toolkit.impls, toolkit.schemas, instruction),\n * });\n *\n * The handler gets a ready session with its toolkit already bound; grading,\n * closing (warm) and aggregation are handled. A task that throws scores 0\n * and records why — the tasks that passed keep their results.\n */\nexport async function runSessions(opts: {\n world: string;\n /** Bundled task names, stored task refs and/or inline task specs\n * (default: every bundled task in the world). */\n tasks?: WorldTaskRef[];\n concurrency?: number;\n failUnder?: number;\n /** Pin every session to one version (default: the world's head). */\n versionId?: string;\n /** Hand the containers back warm for the next run (default: true). */\n keepWarm?: boolean;\n agent: (ctx: {\n session: WorldSession;\n toolkit: WorldToolkit;\n instruction: string;\n /** The task's label — see `SessionRunResult.task`. */\n task: string;\n /** The task as it was given: a bundled name, a stored ref or the\n * inline spec. */\n taskRef: WorldTaskRef;\n }) => Promise<unknown>;\n onResult?: (result: SessionRunResult) => void;\n options?: WorldsClientOptions;\n}): Promise<SessionRunReport> {\n const options = opts.options ?? {};\n const concurrency = Math.max(1, opts.concurrency ?? 3);\n\n let tasks = opts.tasks;\n let versionId = opts.versionId;\n if (!tasks || !versionId) {\n // One resolve for the whole run: every session pins the SAME version, so\n // a push mid-suite cannot split the results across two worlds — and a\n // caller who pinned a version gets THAT version's task list, not the\n // branch tip's.\n const { openWorld, openWorldVersion } = await import(\"./index\");\n const world = versionId\n ? await openWorldVersion(opts.world.split(\"@\", 1)[0]!, versionId, options)\n : await openWorld(opts.world, options);\n tasks = tasks ?? world.tasks.map((t) => t.name);\n versionId = versionId ?? world.version.versionId;\n }\n\n const results: SessionRunResult[] = [];\n let next = 0;\n await Promise.all(\n Array.from({ length: Math.min(concurrency, tasks.length) }, async () => {\n while (next < tasks!.length) {\n const taskRef = tasks![next++];\n let task = taskLabel(taskRef);\n let session: WorldSession | null = null;\n try {\n session = await openSession(opts.world, {\n task: taskRef,\n versionId,\n options,\n });\n task = taskLabel(taskRef, session.taskInfo);\n await session.ready();\n const toolkit = await session.toolkit();\n await opts.agent({\n session,\n toolkit,\n instruction:\n session.instruction ??\n (isTaskSpec(taskRef) ? taskRef.instruction : task),\n task,\n taskRef,\n });\n const graded = await session.grade();\n const result: SessionRunResult = {\n task,\n sessionId: session.sessionId,\n reward: graded.reward,\n rewards: graded.rewards,\n };\n results.push(result);\n opts.onResult?.(result);\n } catch (error) {\n const result: SessionRunResult = {\n task,\n sessionId: session?.sessionId ?? \"\",\n reward: 0,\n rewards: {},\n // An Error with an empty message would read as \"no error\" to any\n // caller checking truthiness; name the type instead.\n error:\n (error instanceof Error ? error.message : String(error)) ||\n (error instanceof Error ? error.name : \"Unknown error\"),\n };\n results.push(result);\n opts.onResult?.(result);\n } finally {\n // Always give the container back — a leaked session bills until the\n // fleet's idle TTL reaps it.\n await session\n ?.close({ keepWarm: opts.keepWarm ?? true })\n .catch(() => undefined);\n }\n }\n }),\n );\n\n const mean =\n results.reduce((sum, r) => sum + (r.reward ?? 0), 0) /\n (results.length || 1);\n const failed = results.filter((r) => r.error).length;\n return {\n results: results.sort((a, b) => a.task.localeCompare(b.task)),\n mean,\n failed,\n passed:\n failed === 0 && (opts.failUnder === undefined || mean >= opts.failUnder),\n };\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\n\n/** Mirrors `WorldSessionListItemSchema` (web/features/public-api/types/world-sessions.ts). */\nexport type WorldSessionListItem = {\n sessionId: string;\n slug: string;\n containerId: string;\n state: string;\n ready: boolean;\n versionId: string;\n contentHash: string;\n taskName: string | null;\n engine: string;\n pinned: boolean;\n surfaces: string[];\n createdAt: string;\n lastUsedAt: string;\n};\n\n/** A World Host session's states (`SessionState` in shared `worldSessions.ts`). */\nexport const SESSION_STATES = [\n \"PROVISIONING\",\n \"RUNNING\",\n \"IDLE\",\n \"STOPPING\",\n \"STOPPED\",\n \"FAILED\",\n \"LOST\",\n] as const;\n\nexport type ListSessionsFilter = {\n /** One of SESSION_STATES. */\n state?: string;\n slug?: string;\n limit?: number;\n};\n\n/** The project's live sessions, newest first — the ones an agent can attach to. */\nexport async function listSessions(\n filter: ListSessionsFilter = {},\n options: WorldsClientOptions = {},\n): Promise<WorldSessionListItem[]> {\n const params = new URLSearchParams();\n if (filter.state) params.set(\"state\", filter.state);\n if (filter.slug) params.set(\"slug\", filter.slug);\n if (filter.limit !== undefined) params.set(\"limit\", String(filter.limit));\n const qs = params.toString();\n const res = await apiRequest<{ sessions: WorldSessionListItem[] }>(\n options,\n \"GET\",\n `/api/public/world-sessions${qs ? `?${qs}` : \"\"}`,\n );\n return res.sessions;\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\nimport type { WorldTaskSpec } from \"./session\";\n\n/**\n * STORED WORLD TASKS: a task spec kept by the project, outside any bundle.\n *\n * An inline task (`openSession(world, { task: { instruction, … } })`) belongs\n * to one session. A stored task is the same spec as a named, versioned\n * project resource: create it once, open as many sessions on it as you like\n * with `{ task: { id } }`, and every grade attributes back to the task and\n * its version. Updating the spec never rewrites history — it appends a\n * version, and a session opened on `{ id, version: 2 }` keeps running v2\n * after v3 exists.\n *\n * const task = await createTask({\n * name: \"refund-late-invoice\",\n * world: \"acme-billing\",\n * spec: { instruction: \"…\", seed: {…}, grader: {…} },\n * });\n * const session = await openSession(\"acme-billing\", { task: { id: task.id } });\n *\n * Tasks are project-scoped: another project's task id is not found (404),\n * never forbidden. `world` pins a task to one world's slug (validated against\n * that world's contract); null leaves it usable with any world.\n */\n\nexport type WorldTaskSummary = {\n id: string;\n name: string;\n world: string | null;\n version: number;\n hash: string;\n spec: WorldTaskSpec;\n /** A multi-world task's aliases in spec order; empty for a single world. */\n aliases: string[];\n /** Listed by world: the aliases that world plays in this task; else empty. */\n aliasesHere: string[];\n /** What grades the task, one row per check or verifier: its reward key,\n * the aliases it judges, what it checks in plain words, its source. */\n verifiers: WorldTaskVerifierRow[];\n createdAt: string;\n updatedAt: string;\n createdBy: string;\n updatedBy: string;\n /** On create, when the task is pinned to a world of a deprecated shape (an\n * api bundle): what to run instead. A retired shape is refused. */\n deprecations?: { code: string; message: string; replacement: string }[];\n};\n\nexport type WorldTaskVersionSummary = {\n version: number;\n hash: string;\n createdAt: string;\n createdBy: string;\n message: string | null;\n};\n\nexport type WorldTaskVerifierRow = {\n key: string;\n aliases: string[];\n kind: \"assertions\" | \"python\" | \"rubric\";\n description: string | null;\n source: string | null;\n sourceLanguage: \"python\" | \"text\" | null;\n};\n\nexport type WorldTaskDetail = WorldTaskSummary & {\n versions: WorldTaskVersionSummary[];\n};\n\nexport type WorldTaskPage = {\n tasks: WorldTaskSummary[];\n meta: {\n page: number;\n limit: number;\n totalItems: number;\n totalPages: number;\n /** Listed by world: the scan for multi-world tasks naming it filled its\n * bound, so `totalItems` is a floor. */\n scanTruncated?: true;\n };\n};\n\nexport type WorldTaskWorldValidation = {\n slug: string;\n ref: string;\n versionId: string;\n ok: boolean;\n checked: \"entities\" | \"none\";\n problems: string[];\n entities: string[] | null;\n};\n\nexport type WorldTaskValidation = {\n taskId: string;\n version: number;\n /** The world version the task was checked against; null for a task with\n * `worlds`, whose versions are per alias under `worlds`. */\n versionId: string | null;\n ok: boolean;\n /** `entities` when the world's contract was read and every seed and check\n * entity was matched against it; `none` when the version has no contract\n * to check (a mock-tools world), in which case `ok` says only that the\n * version exists and is READY; `worlds` for a multi-world task, checked\n * alias by alias against the ref each names. */\n checked: \"entities\" | \"none\" | \"worlds\";\n /** For a multi-world task each problem is prefixed with its alias. */\n problems: string[];\n entities: string[] | null;\n worlds?: Record<string, WorldTaskWorldValidation>;\n};\n\nconst TASKS = \"/api/public/world-tasks\";\nconst taskRoute = (id: string) => `${TASKS}/${encodeURIComponent(id)}`;\n\nconst compact = (body: Record<string, unknown>) =>\n Object.fromEntries(Object.entries(body).filter(([, v]) => v !== undefined));\n\n/** Store a task. `name` defaults to `spec.name`; one of the two is needed. */\nexport async function createTask(\n input: {\n spec: WorldTaskSpec;\n name?: string;\n world?: string | null;\n message?: string;\n },\n options: WorldsClientOptions = {},\n): Promise<WorldTaskSummary> {\n return apiRequest<WorldTaskSummary>(\n options,\n \"POST\",\n TASKS,\n compact({\n spec: input.spec,\n name: input.name,\n world: input.world,\n message: input.message,\n }),\n );\n}\n\n/** Change a task. A new `spec` becomes the next version (the old ones stay\n * readable and openable); `name` and `world` change in place. */\nexport async function updateTask(\n taskId: string,\n input: {\n spec?: WorldTaskSpec;\n name?: string;\n world?: string | null;\n message?: string;\n },\n options: WorldsClientOptions = {},\n): Promise<WorldTaskSummary> {\n if (\n input.spec === undefined &&\n input.name === undefined &&\n input.world === undefined\n )\n throw new Error(\"updateTask: nothing to update — pass spec, name or world\");\n return apiRequest<WorldTaskSummary>(\n options,\n \"PATCH\",\n taskRoute(taskId),\n compact({\n spec: input.spec,\n name: input.name,\n world: input.world,\n message: input.message,\n }),\n );\n}\n\n/** The project's tasks, newest change first. `world` keeps only tasks\n * that run against that slug (pinned to it, or naming it under an alias); `metadata` keeps tasks whose spec metadata carries\n * every given key/value (`{ externalUserId: \"u_42\" }`). */\nexport async function listTasks(\n filter: {\n world?: string;\n metadata?: Record<string, string>;\n page?: number;\n limit?: number;\n } = {},\n options: WorldsClientOptions = {},\n): Promise<WorldTaskPage> {\n const params = new URLSearchParams();\n if (filter.world) params.set(\"world\", filter.world);\n if (filter.page !== undefined) params.set(\"page\", String(filter.page));\n if (filter.limit !== undefined) params.set(\"limit\", String(filter.limit));\n for (const [key, value] of Object.entries(filter.metadata ?? {}))\n params.set(`metadata.${key}`, value);\n const query = params.toString();\n return apiRequest<WorldTaskPage>(\n options,\n \"GET\",\n query ? `${TASKS}?${query}` : TASKS,\n );\n}\n\n/** One task with its version history; `version` reads that version's spec\n * instead of the current one. */\nexport async function getTask(\n taskId: string,\n opts: { version?: number } = {},\n options: WorldsClientOptions = {},\n): Promise<WorldTaskDetail> {\n const query =\n opts.version === undefined ? \"\" : `?version=${String(opts.version)}`;\n return apiRequest<WorldTaskDetail>(\n options,\n \"GET\",\n `${taskRoute(taskId)}${query}`,\n );\n}\n\n/** Remove a task and every version. Sessions already opened on it keep\n * their copy of the spec. */\nexport async function deleteTask(\n taskId: string,\n options: WorldsClientOptions = {},\n): Promise<{ id: string; name: string }> {\n return apiRequest(options, \"DELETE\", taskRoute(taskId));\n}\n\n/** Check a task against a world version without opening a session: every\n * seed entity and every check's entity must exist in the world's contract.\n * `slug` checks against that world's head, `versionId` against an exact\n * version, neither against the task's own `world` pin. */\nexport async function validateTask(\n taskId: string,\n target: { version?: number; slug?: string; versionId?: string } = {},\n options: WorldsClientOptions = {},\n): Promise<WorldTaskValidation> {\n return apiRequest<WorldTaskValidation>(\n options,\n \"POST\",\n `${taskRoute(taskId)}/validate`,\n compact({\n version: target.version,\n slug: target.slug,\n versionId: target.versionId,\n }),\n );\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\nimport {\n assertBrowserTier,\n surfaceKinds,\n uiEntryUrl,\n type BrowserTier,\n type SessionSurfaces,\n type WorldSurfaceKind,\n} from \"./browser\";\nimport {\n WorldSession,\n attachSession,\n isTaskIdRef,\n type GradeResult,\n type VerifierGrade,\n type WorldSessionCall,\n type WorldSessionState,\n type WorldTaskIdRef,\n type WorldTaskSpec,\n} from \"./session\";\n\n/**\n * TASKS THAT NEED SEVERAL WORLDS.\n *\n * A task whose spec names `worlds` is one instruction over N hosted worlds\n * — an investigation that reads a breach feed, a threat-intel API and a\n * ticketing system, say. `openTask` brings every one of them up in ONE call\n * and hands back the sessions keyed by the aliases the spec chose:\n *\n * const task = await openTask({ id: \"wt_1\" }, { surfaces: [\"api\"] });\n * await task.ready();\n * const spycloud = task.sessions.spycloud; // a WorldSession\n * await myAgent(task.instruction, task.sessions);\n * const grade = await task.grade(); // per world + aggregate\n * await task.close();\n *\n * The platform opens the sessions (POST /world-task-sessions) and refuses\n * a partial bring-up: if one world fails, the ones that opened are closed\n * and the error names every alias that failed. Everything after — ready,\n * grade, export, close — is one `WorldSession` call per world, fanned out\n * here. `manifest()` is the record `gateway worlds task up` prints, and\n * `attachTask` rebuilds a `TaskSessions` from a stored task's live sessions.\n */\n\nconst TASK_SESSIONS = \"/api/public/world-task-sessions\";\n\n/** The per-world entry of a `WorldTaskSpec.worlds` table. */\nexport type WorldTaskWorld = {\n slug: string;\n ref?: string;\n seed?: WorldTaskSpec[\"seed\"];\n grader?: WorldTaskSpec[\"grader\"];\n tools?: string[];\n};\n\n/** One world's session as the platform answered it at up. */\nexport type TaskWorldSessionState = WorldSessionState & {\n alias: string;\n slug: string;\n ref: string;\n reusedWarm: boolean;\n};\n\n/** What `POST /world-task-sessions` answers. */\nexport type TaskSessionsResponse = {\n taskId: string | null;\n taskVersion: number | null;\n name: string | null;\n hash: string;\n instruction: string;\n sessions: Record<string, TaskWorldSessionState>;\n};\n\n/** One world in the manifest: where it answers, in the shape\n * `gateway worlds session open` prints for a single session. */\nexport type TaskManifestSession = {\n slug: string;\n ref: string | null;\n versionId: string;\n sessionId: string;\n ready: boolean;\n state: string;\n surfaces: WorldSurfaceKind[];\n api?: { url: string; token?: string };\n ui?: { url: string; entry: string; apiPath: string | null };\n browser?: { wsUrl: string; viewport?: unknown };\n};\n\n/** The manifest: every session of the task, keyed by alias. The file\n * `task up --out` writes and `task down|status|grade|export` read. */\nexport type TaskManifest = {\n taskId: string | null;\n taskVersion: number | null;\n name: string | null;\n instruction: string | null;\n sessions: Record<string, TaskManifestSession>;\n};\n\n/** A stored task's live sessions, as `GET /world-task-sessions` lists them. */\nexport type LiveTaskSession = {\n alias: string | null;\n slug: string | null;\n sessionId: string;\n state: string;\n ready: boolean;\n versionId: string;\n taskVersion: number | null;\n createdAt: string;\n};\n\n/** The task's grade: every world's own `GradeResult` under its alias, the\n * task's cross-world verifiers by name (lifted from the world each is\n * anchored on), and the aggregate. `reward` is the mean of the worlds' and\n * verifiers' numeric rewards — null when none answered one (no grader\n * anywhere, or a judge still pending); a world or verifier with no reward\n * is listed under `ungraded` (a verifier as `x.<name>`), never counted as\n * 0. `rewards` flattens each world's named rewards as `<alias>.<key>`\n * beside `<alias>` for the world's own reward, and a verifier's as\n * `x.<name>` / `x.<name>.<key>`. */\nexport type TaskGrade = {\n reward: number | null;\n rewards: Record<string, number>;\n worlds: Record<string, GradeResult>;\n ungraded: string[];\n verifiers: Record<string, VerifierGrade>;\n};\n\n/** A cross-world verifier's rewards flatten under `x.<name>`; no alias\n * starts with `x.`. */\nexport const VERIFIER_REWARD_PREFIX = \"x.\";\n\n/** Every world's call log, keyed by alias. */\nexport type TaskExport = Record<string, WorldSessionCall[]>;\n\nconst manifestSession = (\n s: SessionSurfaces,\n state: {\n sessionId: string;\n ready: boolean;\n state: string;\n versionId: string;\n },\n world: { slug: string; ref: string | null },\n): TaskManifestSession => ({\n slug: world.slug,\n ref: world.ref,\n versionId: state.versionId,\n sessionId: state.sessionId,\n ready: state.ready,\n state: state.state,\n surfaces: surfaceKinds(s),\n ...(s.api\n ? {\n api: { url: s.api.url, ...(s.api.token ? { token: s.api.token } : {}) },\n }\n : {}),\n ...(s.ui\n ? {\n ui: {\n url: s.ui.url,\n entry: uiEntryUrl(s.ui),\n apiPath: s.ui.apiPath ?? null,\n },\n }\n : {}),\n ...(s.browser\n ? { browser: { wsUrl: s.browser.wsUrl, viewport: s.browser.viewport } }\n : {}),\n});\n\n/** Combine per-world grades into the task's. Pure, so the CLI and the tests\n * share it with `TaskSessions.grade()`. */\nexport function aggregateTaskGrade(\n worlds: Record<string, GradeResult>,\n): TaskGrade {\n const rewards: Record<string, number> = {};\n const ungraded: string[] = [];\n const graded: number[] = [];\n const verifiers: Record<string, VerifierGrade> = {};\n const fold = (key: string, grade: VerifierGrade) => {\n if (typeof grade.reward === \"number\") {\n rewards[key] = grade.reward;\n graded.push(grade.reward);\n } else ungraded.push(key);\n for (const [name, value] of Object.entries(grade.rewards))\n rewards[`${key}.${name}`] = value;\n };\n for (const [alias, grade] of Object.entries(worlds)) {\n fold(alias, grade);\n Object.assign(verifiers, grade.verifiers ?? {});\n }\n for (const [name, grade] of Object.entries(verifiers))\n fold(`${VERIFIER_REWARD_PREFIX}${name}`, grade);\n const reward =\n graded.length > 0\n ? graded.reduce((a, b) => a + b, 0) / graded.length\n : null;\n return { reward, rewards, worlds, ungraded, verifiers };\n}\n\nexport class TaskSessions {\n constructor(\n /** The stored task's id, or null for a task given as a spec. */\n readonly taskId: string | null,\n readonly taskVersion: number | null,\n readonly name: string | null,\n /** The instruction every world's session shares. */\n readonly instruction: string | null,\n /** One live session per alias, in the spec's order. */\n readonly sessions: Record<string, WorldSession>,\n private readonly worlds: Record<\n string,\n { slug: string; ref: string | null }\n >,\n /** The spec's content hash — set only by `openTask` (the raw platform\n * response carries it); null for a `TaskSessions` rebuilt with\n * `attachManifest`/`attachTask`, which have no spec to hash. */\n readonly hash: string | null = null,\n ) {}\n\n /** This alias's `{slug, ref}` as recorded at open/attach — the world a\n * `TaskRun` filing needs to name, without exposing the whole map. */\n worldRef(alias: string): { slug: string; ref: string | null } {\n return this.worlds[alias] ?? { slug: \"\", ref: null };\n }\n\n /** The aliases, in the spec's order. */\n get aliases(): string[] {\n return Object.keys(this.sessions);\n }\n\n /** The alias's session, or a clear error naming the aliases there are. */\n session(alias: string): WorldSession {\n const session = this.sessions[alias];\n if (!session)\n throw new Error(\n `task has no world '${alias}'; its worlds are ${this.aliases.join(\", \")}`,\n );\n return session;\n }\n\n private async each<T>(\n fn: (session: WorldSession, alias: string) => Promise<T>,\n ): Promise<Record<string, T>> {\n const entries = await Promise.all(\n Object.entries(this.sessions).map(\n async ([alias, session]) => [alias, await fn(session, alias)] as const,\n ),\n );\n return Object.fromEntries(entries);\n }\n\n /** Wait until every world answers ready. A world that never does throws\n * `WorldSessionTimeout` naming it; the others are left up. */\n async ready(opts: { timeoutMs?: number } = {}): Promise<void> {\n await this.each((session) => session.ready(opts));\n }\n\n /** Every world's current state, keyed by alias. */\n async status(): Promise<Record<string, WorldSessionState>> {\n return this.each((session) => session.status());\n }\n\n /** The manifest: where every world answers, keyed by alias. */\n async manifest(): Promise<TaskManifest> {\n const sessions = await this.each(async (session, alias) =>\n manifestSession(\n await session.surfaces(),\n {\n sessionId: session.sessionId,\n ready: session.isReady,\n state: (await session.status()).state,\n versionId: session.versionId,\n },\n this.worlds[alias]!,\n ),\n );\n return {\n taskId: this.taskId,\n taskVersion: this.taskVersion,\n name: this.name,\n instruction: this.instruction,\n sessions,\n };\n }\n\n /** Grade every world and aggregate — see `TaskGrade`. One `report` (the\n * agent's own account of the whole investigation) goes to every world's\n * judge; a world graded by assertions or python ignores it. Each grade\n * names the task's other sessions by alias, so the cross-world verifiers\n * anchored on that world can read them. */\n async grade(\n opts: { timeoutMs?: number; report?: string } = {},\n ): Promise<TaskGrade> {\n return aggregateTaskGrade(\n await this.each((session, alias) =>\n session.grade({ ...opts, worlds: this.otherSessions(alias) }),\n ),\n );\n }\n\n /** The task's other sessions by alias: what a grade names. */\n private otherSessions(alias: string): Record<string, string> {\n return Object.fromEntries(\n Object.entries(this.sessions)\n .filter(([other]) => other !== alias)\n .map(([other, session]) => [other, session.sessionId]),\n );\n }\n\n /** Every world's call log, keyed by alias. */\n async export(): Promise<TaskExport> {\n return this.each((session) => session.export());\n }\n\n /** Close every world. Closes are attempted for all of them even when one\n * fails; the error then names every world that did not close. */\n async close(\n opts: { keepWarm?: boolean } = {},\n ): Promise<Record<string, { state: string }>> {\n const settled = await Promise.allSettled(\n Object.entries(this.sessions).map(\n async ([alias, session]) => [alias, await session.close(opts)] as const,\n ),\n );\n const failed: string[] = [];\n const closed: Record<string, { state: string }> = {};\n settled.forEach((result, i) => {\n const alias = this.aliases[i]!;\n if (result.status === \"fulfilled\") closed[alias] = result.value[1];\n else\n failed.push(\n `${alias}: ${result.reason instanceof Error ? result.reason.message : String(result.reason)}`,\n );\n });\n if (failed.length > 0)\n throw new Error(\n `${failed.length} of ${this.aliases.length} worlds did not close — ${failed.join(\"; \")}`,\n );\n return closed;\n }\n}\n\nexport type OpenTaskOptions = {\n /** With a task id: open that version of the task instead of the current. */\n version?: number;\n /** Asked of every world; the platform refuses (400) rather than serving\n * fewer surfaces than asked, and then nothing is up. */\n surfaces?: WorldSurfaceKind[];\n reuseWarm?: boolean;\n /** Browser capacity for every world the task opens: `standard` (spot, may\n * be reclaimed) or `premium` (on-demand). Unset, the organization's default. */\n browserTier?: BrowserTier;\n options?: WorldsClientOptions;\n};\n\nfunction fromResponse(\n answer: TaskSessionsResponse,\n options: WorldsClientOptions,\n): TaskSessions {\n const sessions: Record<string, WorldSession> = {};\n const worlds: Record<string, { slug: string; ref: string | null }> = {};\n for (const [alias, state] of Object.entries(answer.sessions)) {\n sessions[alias] = new WorldSession(state.sessionId, state, options);\n worlds[alias] = { slug: state.slug, ref: state.ref };\n }\n return new TaskSessions(\n answer.taskId,\n answer.taskVersion,\n answer.name,\n answer.instruction,\n sessions,\n worlds,\n answer.hash ?? null,\n );\n}\n\n/**\n * Bring every world of a task up. `ref` is a stored task's id, its\n * `{ id, version? }`, or the spec itself (one with `worlds`). Returns as\n * soon as the platform has opened every session — `ready()` waits for the\n * containers. All or nothing: a world that fails to open closes the rest\n * and the error names it.\n */\nexport async function openTask(\n ref: string | WorldTaskIdRef | WorldTaskSpec,\n opts: OpenTaskOptions = {},\n): Promise<TaskSessions> {\n const options = opts.options ?? {};\n const task: WorldTaskIdRef | WorldTaskSpec =\n typeof ref === \"string\"\n ? {\n id: ref,\n ...(opts.version !== undefined ? { version: opts.version } : {}),\n }\n : isTaskIdRef(ref) && opts.version !== undefined\n ? { ...ref, version: opts.version }\n : ref;\n if (isTaskIdRef(task) ? !task.id : !task.instruction)\n throw new Error(\n \"openTask needs a task: a stored task id, { id, version? } or a spec with worlds\",\n );\n if (!isTaskIdRef(task) && !task.worlds)\n throw new Error(\n \"openTask needs a spec that names its worlds; a single-world spec opens with openSession\",\n );\n if (opts.browserTier !== undefined) assertBrowserTier(opts.browserTier);\n const answer = await apiRequest<TaskSessionsResponse>(\n options,\n \"POST\",\n TASK_SESSIONS,\n {\n task,\n ...(opts.reuseWarm === undefined ? {} : { reuseWarm: opts.reuseWarm }),\n ...(opts.surfaces?.length ? { surfaces: opts.surfaces } : {}),\n ...(opts.browserTier === undefined\n ? {}\n : { browserTier: opts.browserTier }),\n },\n );\n return fromResponse(answer, options);\n}\n\n/** A stored task's live sessions, newest first — every session the project\n * has opened on it that is not stopped or failed. */\nexport async function listTaskSessions(\n taskId: string,\n options: WorldsClientOptions = {},\n): Promise<LiveTaskSession[]> {\n const answer = await apiRequest<{\n taskId: string;\n sessions: LiveTaskSession[];\n }>(options, \"GET\", `${TASK_SESSIONS}?taskId=${encodeURIComponent(taskId)}`);\n return answer.sessions;\n}\n\n/**\n * Attach to the sessions a stored task has up — after a crash, or from a\n * process other than the one that ran `up`. Refuses when an alias is live\n * more than once (two `up`s of the same task): which set is meant is not\n * knowable, so pass the manifest (`attachManifest`) or close the extras.\n */\nexport async function attachTask(\n taskId: string,\n options: WorldsClientOptions = {},\n): Promise<TaskSessions> {\n const live = await listTaskSessions(taskId, options);\n if (live.length === 0)\n throw new Error(\n `task ${taskId} has no live sessions; run \\`task up\\` first`,\n );\n const byAlias = new Map<string, LiveTaskSession[]>();\n for (const session of live) {\n const alias = session.alias ?? session.sessionId;\n byAlias.set(alias, [...(byAlias.get(alias) ?? []), session]);\n }\n const doubled = [...byAlias.entries()].filter(([, rows]) => rows.length > 1);\n if (doubled.length > 0)\n throw new Error(\n `task ${taskId} has more than one live session for ${doubled\n .map(\n ([alias, rows]) =>\n `'${alias}' (${rows.map((r) => r.sessionId).join(\", \")})`,\n )\n .join(\", \")}; pass the manifest from \\`task up\\`, or close the extras`,\n );\n return attachManifest(\n {\n taskId,\n taskVersion: live[0]!.taskVersion,\n name: null,\n instruction: null,\n sessions: Object.fromEntries(\n [...byAlias.entries()].map(([alias, [row]]) => [\n alias,\n {\n slug: row!.slug ?? \"\",\n ref: null,\n versionId: row!.versionId,\n sessionId: row!.sessionId,\n ready: row!.ready,\n state: row!.state,\n surfaces: [\"tools\"] as WorldSurfaceKind[],\n },\n ]),\n ),\n },\n options,\n );\n}\n\n/** Attach to the sessions a manifest names — the file `task up --out`\n * wrote. Each session is read back from the platform, so a closed one is a\n * clear error rather than a stale handle. */\nexport async function attachManifest(\n manifest: TaskManifest,\n options: WorldsClientOptions = {},\n): Promise<TaskSessions> {\n const entries = await Promise.all(\n Object.entries(manifest.sessions).map(\n async ([alias, entry]) =>\n [alias, await attachSession(entry.sessionId, options)] as const,\n ),\n );\n const sessions = Object.fromEntries(entries);\n const instruction =\n manifest.instruction ?? entries[0]?.[1].instruction ?? null;\n return new TaskSessions(\n manifest.taskId,\n manifest.taskVersion,\n manifest.name,\n instruction,\n sessions,\n Object.fromEntries(\n Object.entries(manifest.sessions).map(([alias, entry]) => [\n alias,\n { slug: entry.slug, ref: entry.ref },\n ]),\n ),\n );\n}\n\n/** Whether a parsed JSON value is a task manifest (what `task up` wrote)\n * rather than a task spec. */\nexport function isTaskManifest(value: unknown): value is TaskManifest {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n typeof (value as { sessions?: unknown }).sessions === \"object\" &&\n (value as { sessions?: unknown }).sessions !== null &&\n !(\"instruction\" in value && \"worlds\" in value)\n );\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\n\n/** TS twin of the Python SDK's GatewayEvalsClient (gatewaysdk/benchmark_hub/evals.py). */\n\nconst EVALUATIONS = \"/api/public/benchmark-containers/evaluations\";\n\nexport type EvalSample = {\n exampleId: string;\n task?: string;\n rolloutIndex?: number;\n prompt?: unknown;\n completion?: unknown;\n reward?: number;\n score?: number;\n correct?: boolean;\n rewards?: Record<string, number>;\n info?: Record<string, unknown>;\n};\n\nexport type CreateEvaluationOptions = {\n model?: string;\n /** A set run to file under; the platform refuses a run that does not admit this result. */\n runId?: string;\n rolloutsPerExample?: number;\n metadata?: Record<string, unknown>;\n};\n\nexport type FinalizeEvaluationOptions = {\n status?: \"COMPLETED\" | \"FAILED\";\n metrics?: Record<string, unknown>;\n};\n\nexport class GatewayEvalsClient {\n constructor(private readonly options: WorldsClientOptions = {}) {}\n\n async createEvaluation(\n versionId: string,\n opts: CreateEvaluationOptions = {},\n ): Promise<string> {\n const body: Record<string, unknown> = { versionId };\n if (opts.model !== undefined) body.model = opts.model;\n if (opts.runId !== undefined) body.runId = opts.runId;\n if (opts.rolloutsPerExample !== undefined)\n body.rolloutsPerExample = opts.rolloutsPerExample;\n if (opts.metadata !== undefined) body.metadata = opts.metadata;\n const answer = await apiRequest<{ evaluationId: string }>(\n this.options,\n \"POST\",\n EVALUATIONS,\n body,\n );\n return answer.evaluationId;\n }\n\n async pushSamples(\n evaluationId: string,\n samples: EvalSample[],\n ): Promise<number> {\n const answer = await apiRequest<{ inserted?: number }>(\n this.options,\n \"POST\",\n `${EVALUATIONS}/${encodeURIComponent(evaluationId)}/samples`,\n { samples },\n );\n return answer.inserted ?? samples.length;\n }\n\n async finalizeEvaluation(\n evaluationId: string,\n opts: FinalizeEvaluationOptions = {},\n ): Promise<string> {\n const body: Record<string, unknown> = {\n status: opts.status ?? \"COMPLETED\",\n };\n if (opts.metrics !== undefined) body.metrics = opts.metrics;\n const answer = await apiRequest<{ status: string }>(\n this.options,\n \"POST\",\n `${EVALUATIONS}/${encodeURIComponent(evaluationId)}/finalize`,\n body,\n );\n return answer.status;\n }\n}\n","/**\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.8\",\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 \"test:integration\": \"vitest run --config vitest.integration.config.ts\",\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.2.8\",\n \"@arizeai/openinference-instrumentation-openai\": \"^4.2.7\"\n },\n \"devDependencies\": {\n \"@anthropic-ai/sdk\": \"^0.91.1\",\n \"@opentelemetry/api\": \"^1.9.0\",\n \"@opentelemetry/exporter-trace-otlp-http\": \"^0.222.0\",\n \"@opentelemetry/resources\": \"^2.11.0\",\n \"@opentelemetry/sdk-trace-base\": \"^2.11.0\",\n \"@opentelemetry/sdk-trace-node\": \"^2.11.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 \"nanoid\": \">=3.3.18\",\n \"esbuild\": \">=0.28.1\"\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 \"nanoid\": \">=3.3.18\",\n \"esbuild\": \">=0.28.1\"\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 { BrowserTier, WorldSurfaceKind } from \"./browser\";\nimport { WorldSurfaceUnavailable } from \"./browser\";\nimport { GatewayEvalsClient, type EvalSample } from \"./evals\";\nimport type { WorldsClientOptions } from \"./index\";\nimport {\n modelToolName,\n schemaFromSignature,\n WorldSession,\n type WorldTaskIdRef,\n type WorldTaskSpec,\n type WorldToolkit,\n type WorldToolSpec,\n} from \"./session\";\nimport {\n openTask,\n TaskSessions,\n type TaskGrade,\n type TaskManifest,\n} from \"./taskSessions\";\n\nexport class TaskRun {\n readonly notes: Record<string, unknown> = {};\n\n constructor(\n readonly runId: string,\n readonly instruction: string,\n readonly model: string,\n readonly sessions: Record<string, WorldSession>,\n readonly manifest: TaskManifest,\n ) {}\n\n session(alias: string): WorldSession {\n const session = this.sessions[alias];\n if (!session)\n throw new Error(\n `task run has no world '${alias}'; its worlds are ${Object.keys(this.sessions).join(\", \")}`,\n );\n return session;\n }\n\n /** Raises when the session was not opened with `surfaces: [\"api\"]`. */\n async api(alias: string): Promise<{ url: string; token?: string }> {\n const surfaces = await this.session(alias).surfaces();\n if (!surfaces.api)\n throw new WorldSurfaceUnavailable(\n \"api\",\n `open '${alias}' with surfaces: ['api']`,\n );\n return { url: surfaces.api.url, token: surfaces.api.token };\n }\n\n /** Each tool is prefixed `<alias>.<tool>` so a model can tell which world a call goes to. */\n async toolkit(): Promise<WorldToolkit> {\n const schemas: WorldToolkit[\"schemas\"] = [];\n const impls: WorldToolkit[\"impls\"] = {};\n const specs: WorldToolSpec[] = [];\n for (const [alias, session] of Object.entries(this.sessions)) {\n const kit = await session.toolkit();\n if (!kit.specs.length) continue;\n for (const spec of kit.specs) {\n const name = `${alias}.${spec.name}`;\n const prefixed: WorldToolSpec = {\n name,\n signature: spec.signature,\n doc: spec.doc,\n inputSchema: spec.inputSchema,\n };\n specs.push(prefixed);\n const schema = schemaFromSignature(prefixed);\n schema.function.name = name;\n schemas.push(schema);\n impls[name] = kit.impls[modelToolName(spec.name)]!;\n }\n }\n return { schemas, impls, specs };\n }\n\n /** Merged into `run.json` under `notes`; a later call overrides an earlier key. */\n record(notes: Record<string, unknown>): void {\n Object.assign(this.notes, notes);\n }\n}\n\nfunction worldRef(\n live: TaskSessions,\n alias: string,\n): { slug: string; ref: string | null; versionId: string; sessionId: string } {\n const { slug, ref } = live.worldRef(alias);\n const session = live.sessions[alias]!;\n return {\n slug,\n ref,\n versionId: session.versionId,\n sessionId: session.sessionId,\n };\n}\n\nasync function fileTaskRun(\n live: TaskSessions,\n runId: string,\n model: string,\n report: string | null,\n grade: TaskGrade,\n agentError: string | null,\n traced: boolean,\n runDir: string,\n options: WorldsClientOptions,\n setRunId: string | undefined,\n): Promise<string> {\n const aliases = live.aliases;\n const anchor = aliases[0]!;\n const worldsMeta = Object.fromEntries(\n aliases.map((alias) => [alias, worldRef(live, alias)]),\n );\n\n const evals = new GatewayEvalsClient(options);\n const evaluationId = await evals.createEvaluation(\n worldRef(live, anchor).versionId,\n {\n model,\n rolloutsPerExample: 1,\n ...(setRunId ? { runId: setRunId } : {}),\n metadata: {\n source: \"worlds-task-run\",\n task: {\n id: live.taskId,\n version: live.taskVersion,\n name: live.name,\n hash: live.hash,\n },\n anchor,\n worlds: worldsMeta,\n runId,\n },\n },\n );\n\n const reward = grade.reward;\n const sample: Record<string, unknown> = {\n exampleId: live.name ?? live.taskId ?? runId,\n task: live.name ?? live.taskId ?? runId,\n rolloutIndex: 0,\n prompt: live.instruction,\n ...(report === null ? {} : { completion: report }),\n rewards: grade.rewards,\n info: {\n sessionId: runId,\n worlds: Object.fromEntries(\n aliases.map((alias) => [\n alias,\n {\n ...worldRef(live, alias),\n reward: grade.worlds[alias]?.reward ?? null,\n },\n ]),\n ),\n ungraded: grade.ungraded,\n traced,\n runDir,\n ...(agentError ? { agentError } : {}),\n },\n };\n if (typeof reward === \"number\") {\n sample.reward = reward;\n sample.score = reward;\n sample.correct = reward >= 1.0;\n }\n await evals.pushSamples(evaluationId, [sample as unknown as EvalSample]);\n await evals.finalizeEvaluation(evaluationId, {\n status: agentError ? \"FAILED\" : \"COMPLETED\",\n metrics: {\n ...(typeof reward === \"number\" ? { avg_reward: reward } : {}),\n reward,\n ...Object.fromEntries(\n Object.entries(grade.rewards).map(([k, v]) => [`rewards.${k}`, v]),\n ),\n },\n });\n return evaluationId;\n}\n\nexport type RunTaskOptions = {\n model: string;\n surfaces?: WorldSurfaceKind[];\n /** Directory the run's own `<runId>/` folder is created under. Default `\"runs\"`. */\n outDir?: string;\n /** Initialize tracing when GATEWAY_* credentials are configured. Default `true`. */\n trace?: boolean;\n /** File one rollout when the run ends. Default `true`. */\n file?: boolean;\n /** Leave every session up instead of closing it when the run ends. Default `false`. */\n keepUp?: boolean;\n reuseWarm?: boolean;\n browserTier?: BrowserTier;\n /** File the rollout under this set run (`runSet` sets it). */\n setRunId?: string;\n options?: WorldsClientOptions;\n};\n\nexport type RunTaskSummary = {\n runId: string;\n taskId: string | null;\n taskVersion: number | null;\n name: string | null;\n instruction: string;\n model: string;\n aliases: string[];\n reward: number | null;\n rewards: Record<string, number>;\n ungraded: string[];\n agentError: string | null;\n report: string | null;\n traced: boolean;\n runDir: string;\n durationSeconds: number;\n notes: Record<string, unknown>;\n filed: boolean;\n evaluationId?: string;\n [extra: string]: unknown;\n};\n\nexport type TaskRunResult =\n string | { report?: unknown; [key: string]: unknown } | null | undefined;\n\nconst describeValue = (value: unknown): string =>\n Array.isArray(value) ? \"array\" : value === null ? \"null\" : typeof value;\n\nconst RESULT_CONTRACT =\n \"return a string report, an object {report?: string, ...} or nothing\";\n\nfunction reportFromResult(result: TaskRunResult): {\n report: string | null;\n extra: Record<string, unknown>;\n} {\n if (result === undefined || result === null)\n return { report: null, extra: {} };\n if (typeof result === \"string\") return { report: result, extra: {} };\n if (typeof result !== \"object\" || Array.isArray(result))\n throw new Error(\n `agent returned ${describeValue(result)}; ${RESULT_CONTRACT}`,\n );\n const { report, ...extra } = result as Record<string, unknown>;\n if (report === undefined || report === null) return { report: null, extra };\n if (typeof report !== \"string\")\n throw new Error(\n `agent returned a report of type ${describeValue(report)}; ${RESULT_CONTRACT}`,\n );\n return { report, extra };\n}\n\n/** Mirrors `gatewaysdk.world_tasks.run_task`. Sessions close unless `keepUp: true`, even when the agent throws, so grading and filing\n * still happen with the error recorded. */\nexport async function runTask(\n ref: string | WorldTaskIdRef | WorldTaskSpec,\n agent: (run: TaskRun) => TaskRunResult | Promise<TaskRunResult>,\n opts: RunTaskOptions,\n): Promise<RunTaskSummary> {\n const runId = `wtr-${randomBytes(6).toString(\"hex\")}`;\n const outDir = opts.outDir ?? \"runs\";\n const runDir = path.join(outDir, runId);\n fs.mkdirSync(runDir, { recursive: true });\n const options = opts.options ?? {};\n\n const live = await openTask(ref, {\n surfaces: opts.surfaces,\n reuseWarm: opts.reuseWarm,\n browserTier: opts.browserTier,\n options,\n });\n const started = Date.now();\n try {\n await live.ready();\n\n let traced = false;\n if (opts.trace !== false) {\n try {\n const { isGatewayConfigured, init } = await import(\"../tracing/init\");\n if (isGatewayConfigured()) {\n init();\n traced = true;\n }\n } catch {\n traced = false;\n }\n }\n\n const taskRun = new TaskRun(\n runId,\n live.instruction ?? \"\",\n opts.model,\n live.sessions,\n await live.manifest(),\n );\n\n let agentError: string | null = null;\n let report: string | null = null;\n let extra: Record<string, unknown> = {};\n try {\n const invoke = () => agent(taskRun);\n const result = traced\n ? await (await import(\"../tracing/session\")).withSession(runId, invoke)\n : await invoke();\n ({ report, extra } = reportFromResult(result));\n } catch (error) {\n const message =\n (error instanceof Error ? error.message : String(error)) ||\n \"Unknown error\";\n agentError = message.slice(0, 2000);\n }\n if (traced)\n await import(\"../tracing/init\")\n .then((tracing) => tracing.flush())\n .catch(() => undefined);\n\n const grade =\n report !== null ? await live.grade({ report }) : await live.grade();\n\n fs.writeFileSync(\n path.join(runDir, \"manifest.json\"),\n JSON.stringify(taskRun.manifest, null, 2),\n );\n fs.writeFileSync(\n path.join(runDir, \"grades.json\"),\n JSON.stringify(grade, null, 2),\n );\n if (report) fs.writeFileSync(path.join(runDir, \"report.md\"), report);\n\n const summary: RunTaskSummary = {\n runId,\n taskId: live.taskId,\n taskVersion: live.taskVersion,\n name: live.name,\n instruction: taskRun.instruction,\n model: opts.model,\n aliases: live.aliases,\n reward: grade.reward,\n rewards: grade.rewards,\n ungraded: grade.ungraded,\n agentError,\n report,\n traced,\n runDir,\n durationSeconds: Math.round((Date.now() - started) / 10) / 100,\n notes: taskRun.notes,\n filed: false,\n ...extra,\n };\n\n if (opts.file !== false) {\n summary.evaluationId = await fileTaskRun(\n live,\n runId,\n opts.model,\n report,\n grade,\n agentError,\n traced,\n runDir,\n options,\n opts.setRunId,\n );\n summary.filed = true;\n }\n\n fs.writeFileSync(\n path.join(runDir, \"run.json\"),\n JSON.stringify(summary, null, 2),\n );\n return summary;\n } finally {\n if (!opts.keepUp) {\n try {\n await live.close({ keepWarm: false });\n } catch {\n // Best-effort: a session that would not close is `task down`'s to report.\n }\n }\n }\n}\n","import { execFileSync } from \"node:child_process\";\n\nexport type Checkout = {\n branch?: string;\n commit?: string;\n repoUrl?: string;\n pr?: { number: number; url: string; title?: string };\n};\n\ntype Env = Record<string, string | undefined>;\n\n/** Labels for the reader, never used to authorize. The PR comes from `GATEWAY_PR_URL`\n * (+ `GATEWAY_PR_TITLE`), else GitHub Actions' `GITHUB_REF=refs/pull/<n>/merge`. */\nexport class CheckoutProvenance {\n constructor(\n private readonly cwd: string,\n private readonly env: Env,\n ) {}\n\n static read(cwd: string = process.cwd(), env: Env = process.env): Checkout {\n return new CheckoutProvenance(cwd, env).checkout();\n }\n\n checkout(): Checkout {\n const commit = this.git(\"rev-parse\", \"HEAD\");\n if (!commit) return this.withPr({});\n const branch =\n this.env.GITHUB_HEAD_REF || this.git(\"rev-parse\", \"--abbrev-ref\", \"HEAD\");\n const remote = this.git(\"config\", \"--get\", \"remote.origin.url\");\n return this.withPr({\n commit,\n ...(branch && branch !== \"HEAD\" ? { branch } : {}),\n ...(remote ? { repoUrl: CheckoutProvenance.withoutCredentials(remote) } : {}),\n });\n }\n\n /** Security: credentials are stripped; scp-style `git@host:org/repo` has none and is kept. */\n static withoutCredentials(url: string): string {\n return url.replace(/^([a-z][a-z0-9+.-]*:\\/\\/)[^@/]+@/i, \"$1\");\n }\n\n private withPr(checkout: Checkout): Checkout {\n const pr = this.pullRequest();\n return pr ? { ...checkout, pr } : checkout;\n }\n\n private pullRequest(): Checkout[\"pr\"] | undefined {\n const url = this.env.GATEWAY_PR_URL;\n const fromUrl = url ? /\\/pull\\/(\\d+)/.exec(url)?.[1] : undefined;\n if (url && fromUrl)\n return {\n number: Number(fromUrl),\n url,\n ...(this.env.GATEWAY_PR_TITLE ? { title: this.env.GATEWAY_PR_TITLE } : {}),\n };\n const number = /^refs\\/pull\\/(\\d+)\\//.exec(this.env.GITHUB_REF ?? \"\")?.[1];\n const server = this.env.GITHUB_SERVER_URL;\n const repo = this.env.GITHUB_REPOSITORY;\n if (!number || !server || !repo) return undefined;\n return { number: Number(number), url: `${server}/${repo}/pull/${number}` };\n }\n\n private git(...args: string[]): string | undefined {\n try {\n const out = execFileSync(\"git\", args, {\n cwd: this.cwd,\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n timeout: 5_000,\n })\n .toString()\n .trim();\n return out || undefined;\n } catch {\n return undefined;\n }\n }\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\nimport type { BrowserTier, WorldSurfaceKind } from \"./browser\";\nimport { CheckoutProvenance, type Checkout } from \"./checkoutProvenance\";\nimport {\n runTask,\n type RunTaskSummary,\n type TaskRun,\n type TaskRunResult,\n} from \"./taskRun\";\n\nconst SET_RUNS = \"/api/public/set-runs\";\n\nexport type SetRunDoc = {\n id: string;\n status: \"running\" | \"completed\" | \"failed\";\n model: string | null;\n source: string | null;\n taskSetDatasetId: string | null;\n actor: { kind: string; id: string; name?: string } | null;\n git: Checkout | null;\n progress: { done: number; planned: number };\n score: { mean: number | null; gradedTasks: number; ungradedTasks: number };\n tasks: Array<{\n worldTaskId: string;\n datasetItemId: string;\n name: string;\n evaluationId: string | null;\n sampleId: string | null;\n status: \"pending\" | \"completed\" | \"failed\";\n reward: number | null;\n checks: Array<{\n key: string;\n outcome: \"passed\" | \"failed\" | \"ungraded\";\n value: number | null;\n }>;\n }>;\n};\n\nexport type RunSetOptions = {\n model: string;\n /** Default `\"sdk\"`; the CLI passes `\"cli\"`. */\n source?: \"cli\" | \"sdk\";\n /** Default: read from the working directory; `null` records none. */\n git?: Checkout | null;\n surfaces?: WorldSurfaceKind[];\n browserTier?: BrowserTier;\n outDir?: string;\n trace?: boolean;\n onTask?: (summary: RunTaskSummary) => void;\n options?: WorldsClientOptions;\n};\n\n/** `failed`: an agent raised, a task could not run, or the platform stored the run as anything but completed. */\nexport type RunSetResult = {\n setRun: SetRunDoc;\n tasks: RunTaskSummary[];\n failed: boolean;\n closedAsRequested: boolean;\n};\n\n/** A low or missing reward is a result, not a failure; every task runs even after one fails. */\nexport async function runSet(\n datasetId: string,\n agent: (run: TaskRun) => TaskRunResult | Promise<TaskRunResult>,\n opts: RunSetOptions,\n): Promise<RunSetResult> {\n const options = opts.options ?? {};\n const git = opts.git === undefined ? CheckoutProvenance.read() : opts.git;\n const opened = await apiRequest<SetRunDoc>(options, \"POST\", SET_RUNS, {\n datasetId,\n model: opts.model,\n source: opts.source ?? \"sdk\",\n ...(git && Object.keys(git).length ? { git } : {}),\n });\n\n const close = (status: \"failed\" | \"completed\") =>\n apiRequest<SetRunDoc>(\n options,\n \"POST\",\n `${SET_RUNS}/${encodeURIComponent(opened.id)}/close`,\n { status },\n );\n // Ctrl-C closes the run failed before exiting instead of leaving it open.\n const onInterrupt = () => {\n void close(\"failed\").finally(() => process.exit(130));\n };\n process.once(\"SIGINT\", onInterrupt);\n const planned = await runPlannedTasks(opened, agent, opts, options).finally(\n () => process.off(\"SIGINT\", onInterrupt),\n );\n const { tasks, failed } = planned;\n const requested = failed ? \"failed\" : \"completed\";\n const setRun = await close(requested);\n return {\n setRun,\n tasks,\n failed: failed || setRun.status !== \"completed\",\n closedAsRequested: setRun.status === requested,\n };\n}\n\n/** Never throws, so the caller always gets to close the run. */\nasync function runPlannedTasks(\n opened: SetRunDoc,\n agent: (run: TaskRun) => TaskRunResult | Promise<TaskRunResult>,\n opts: RunSetOptions,\n options: WorldsClientOptions,\n): Promise<{ tasks: RunTaskSummary[]; failed: boolean }> {\n const tasks: RunTaskSummary[] = [];\n let failed = false;\n for (const task of opened.tasks) {\n try {\n const summary = await runTask(task.worldTaskId, agent, {\n model: opts.model,\n surfaces: opts.surfaces,\n browserTier: opts.browserTier,\n outDir: opts.outDir,\n trace: opts.trace,\n setRunId: opened.id,\n options,\n });\n tasks.push(summary);\n failed ||= summary.agentError !== null;\n opts.onTask?.(summary);\n } catch (error) {\n failed = true;\n const message = error instanceof Error ? error.message : String(error);\n process.stderr.write(`task ${task.name} could not run: ${message}\\n`);\n }\n }\n return { tasks, failed };\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\n/** What `localTreeState(dir)` reports: the tracked meta and the edits since its base. */\nexport type TreeState = {\n meta: { slug?: string; baseFiles?: Record<string, string> } | null;\n dirty: string[];\n clean: boolean;\n};\n\nexport class CheckoutRefusedError extends Error {\n constructor(message: string) {\n super(`checkout refused: ${message}`);\n this.name = \"CheckoutRefusedError\";\n }\n}\n\nconst NAMED_EDITS = 3;\n\n/**\n * Where a pull lands, decided before a byte is downloaded (P-20).\n *\n * - No target: `./<slug>`, de-duplicated with `-1`/`-2`; an existing dir is\n * never entered.\n * - Explicit target: absent or empty → used as-is; a clean checkout of the\n * same world → replaced (its base files are cleared first so files the new\n * version dropped do not linger); local edits, another world's checkout or\n * an untracked non-empty dir → refused unless `force`, which discards the\n * checkout's base files *and* its local edits (added files included) so the\n * result is the pulled version, nothing else the archive would see.\n * - A relative target stays under the current directory; one that escapes it\n * (`../x`) is refused — an absolute path is the explicit way elsewhere (P-21).\n *\n * Python twin: `gatewaysdk.benchmark_hub.checkout.CheckoutTarget`.\n */\nexport class CheckoutTarget {\n private constructor(\n readonly dir: string,\n /** Files of the checkout being replaced (its base + its local edits); removed by `clear()`. */\n readonly replaces: string[],\n ) {}\n\n static resolve(\n slug: string,\n target: string | undefined,\n opts: { cwd: string; force: boolean; state: (dir: string) => TreeState },\n ): CheckoutTarget {\n if (target === undefined) return CheckoutTarget.fresh(slug, opts.cwd);\n return CheckoutTarget.explicit(\n CheckoutTarget.confined(target, opts.cwd),\n slug,\n opts,\n );\n }\n\n /** The absolute destination; a relative target may not resolve above `cwd`. */\n private static confined(target: string, cwd: string): string {\n const dir = path.resolve(cwd, target);\n if (path.isAbsolute(target)) return dir;\n const rel = path.relative(cwd, dir);\n if (rel === \"\" || (!rel.startsWith(\"..\") && !path.isAbsolute(rel)))\n return dir;\n throw new CheckoutRefusedError(\n `--target ${target} resolves outside the current directory (${cwd}) — run from that directory, or pass an absolute path`,\n );\n }\n\n private static fresh(slug: string, cwd: string): CheckoutTarget {\n const base = path.join(cwd, slug);\n let dir = base;\n let i = 1;\n while (fs.existsSync(dir)) dir = `${base}-${i++}`;\n return new CheckoutTarget(dir, []);\n }\n\n private static explicit(\n dir: string,\n slug: string,\n opts: { force: boolean; state: (dir: string) => TreeState },\n ): CheckoutTarget {\n if (!fs.existsSync(dir)) return new CheckoutTarget(dir, []);\n if (!fs.statSync(dir).isDirectory())\n throw new CheckoutRefusedError(`${dir} is a file`);\n if (fs.readdirSync(dir).length === 0) return new CheckoutTarget(dir, []);\n const state = opts.state(dir);\n const refusal = CheckoutTarget.refusal(dir, slug, state);\n if (refusal === null || opts.force)\n return new CheckoutTarget(dir, CheckoutTarget.tracked(state));\n throw new CheckoutRefusedError(refusal);\n }\n\n /** Base files plus local edits — everything the archive would see in the old\n * checkout. `.env-metadata.json` is local input: a key that would leave the\n * checkout (`../x`, `/etc/x`) is dropped, never removed. */\n private static tracked(state: TreeState): string[] {\n if (!state.meta?.baseFiles) return [];\n return [\n ...new Set([...Object.keys(state.meta.baseFiles), ...state.dirty]),\n ]\n .filter(CheckoutTarget.confinedRel)\n .sort();\n }\n\n private static confinedRel(rel: string): boolean {\n if (rel === \"\" || path.isAbsolute(rel)) return false;\n return !rel.split(/[\\\\/]/).includes(\"..\");\n }\n\n /** Why `dir` cannot be overwritten, or null when it is a clean checkout of `slug`. */\n private static refusal(\n dir: string,\n slug: string,\n state: TreeState,\n ): string | null {\n if (!state.meta?.baseFiles)\n return `${dir} is not empty and is not a checkout of \"${slug}\" — pick an empty --target, or pass --force to overwrite it`;\n if (state.meta.slug !== undefined && state.meta.slug !== slug)\n return `${dir} tracks \"${state.meta.slug}\", not \"${slug}\" — pick another --target, or pass --force to replace it`;\n if (state.clean) return null;\n const n = state.dirty.length;\n const named = state.dirty.slice(0, NAMED_EDITS).join(\", \");\n const more = n > NAMED_EDITS ? `, +${n - NAMED_EDITS} more` : \"\";\n return `${dir} has ${n} local edit${n === 1 ? \"\" : \"s\"} not pushed (${named}${more}) — push or propose them first, or pass --force to discard them`;\n }\n\n /** Remove the replaced checkout's files (and the dirs they leave empty). */\n clear(): void {\n for (const rel of this.replaces) {\n const abs = path.join(this.dir, rel);\n fs.rmSync(abs, { force: true });\n this.pruneEmptyParents(path.dirname(abs));\n }\n }\n\n private pruneEmptyParents(from: string): void {\n let cur = from;\n while (cur !== this.dir && cur.startsWith(this.dir)) {\n if (fs.existsSync(cur) && fs.readdirSync(cur).length > 0) return;\n fs.rmSync(cur, { recursive: true, force: true });\n cur = path.dirname(cur);\n }\n }\n}\n","/**\n * What a directory IS, decided once for the TS SDK.\n *\n * `WorldDir.open(dir)` is the one detector this package has: the benchmark\n * front door (`classifyTree`, `detectEnvKind`, `harborTaskDirs`,\n * `verifiersPackage` in ../benchmarks) and the hub client (`collectArchiveRelPaths`,\n * `computeContentHash`, the contract-version lookup in ./hub.ts) are facades\n * over it. Twin of `gatewaysdk.environment.world.World` (Python) and\n * `packages/shared/src/world` (the platform); the corpus under\n * `conformance/worlds/` pins all three to the same answers.\n */\nimport { createHash } from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nexport const WORLD_MANIFEST = \"gateway-env.toml\";\nexport const API_BUNDLE_MANIFEST = \"gateway-api-world.toml\";\nexport const BUNDLED_WORLD_PREFIX = \"server/world/\";\nexport const CONNECTOR_SPEC = \"connector.toml\";\nexport const PYPROJECT = \"pyproject.toml\";\nexport const BENCHMARK_CONFIG = \"benchmark.json\";\nexport const WORLD_SCHEMA_MARKERS = [\"schema/world.json\", \"schema/runtime.json\", \"schema/lock.json\"];\nconst WORLD_ROOT_MARKERS = [CONNECTOR_SPEC, ...WORLD_SCHEMA_MARKERS];\n/** Root markers that widen the archive to every ordinary root file: a world's\n * executable contract and a benchmark's config/fixtures live at the root. */\nconst BROAD_ROOT_MARKERS = [WORLD_MANIFEST, API_BUNDLE_MANIFEST, BENCHMARK_CONFIG];\nconst SKIPPED_DIRS = new Set([\"dist\", \"build\", \"outputs\", \"__pycache__\", \"node_modules\"]);\n\n/** One entry the archive rules dropped: a whole directory (`name/`, `files`\n * counted) or a single file. */\nexport type Exclusion = { path: string; files: number };\n\n/** The runner's kind: what the dispatcher executes a pushed tree as. */\nexport type EnvKind = \"api\" | \"mock-tools\" | \"harbor\" | \"verifiers-v1\" | \"verifiers\";\n\n// The `verifiers.v1` namespace first shipped in verifiers 0.2.0: a v1 package\n// pins verifiers>=0.2 (or ~=0.2 / ==0.2.* / >=1 / ==1.*) in pyproject and/or\n// imports the namespace or subclasses Taskset alongside a v1-style `__all__`.\nconst V1_DEP = /[\"']verifiers\\s*(?:\\[[^\\]]*\\])?\\s*(?:>=|~=|==|>)\\s*(?:0\\.(?:[2-9]\\d*|[1-9]\\d+)|[1-9]\\d*)/;\nconst V1_IMPORT = /^\\s*(?:from\\s+verifiers\\.v1\\s+import\\b|from\\s+verifiers\\s+import\\s+v1\\b|import\\s+verifiers\\.v1\\b)/m;\nconst V1_TASKSET = /class\\s+\\w+\\s*\\(\\s*(?:(?:vf|v1|verifiers(?:\\.v1)?)\\.)?Taskset\\s*[,)]/;\nconst HARBOR_TASK = /^(?:tasks\\/)?([^/]+)\\/task\\.toml$/;\n\nconst skippedDir = (name: string): boolean =>\n name.startsWith(\".\") || SKIPPED_DIRS.has(name) || name.endsWith(\".egg-info\");\n\n/** Python's `sorted()` order for relpaths: code points, not UTF-16 units. */\nconst byCodePoint = (a: string, b: string): number => Buffer.compare(Buffer.from(a, \"utf-8\"), Buffer.from(b, \"utf-8\"));\n\nexport class WorldDir {\n private pathsMemo: string[] | undefined;\n\n private constructor(\n readonly dir: string,\n /** Where the authored world lives: `\"\"` for a world stored as itself,\n * `server/world/` for one stored as its api bundle. */\n readonly worldRoot: \"\" | typeof BUNDLED_WORLD_PREFIX,\n ) {}\n\n static open(dir: string): WorldDir {\n const present = (rel: string) => fs.existsSync(path.join(dir, rel));\n const bundled = present(API_BUNDLE_MANIFEST) && WORLD_ROOT_MARKERS.some((m) => present(BUNDLED_WORLD_PREFIX + m));\n return new WorldDir(dir, bundled ? BUNDLED_WORLD_PREFIX : \"\");\n }\n\n // ── Files ──────────────────────────────────────────────────────────────\n\n has(rel: string): boolean {\n return fs.existsSync(path.join(this.dir, rel));\n }\n\n text(rel: string): string | null {\n try {\n return fs.readFileSync(path.join(this.dir, rel), \"utf-8\");\n } catch {\n return null;\n }\n }\n\n /** A path under the authored world's root. */\n worldPath(rel: string): string {\n return this.worldRoot + rel;\n }\n\n /** Every regular file the archive rules keep (`_archive.py`: no hidden,\n * dist, build, outputs, pycache, node_modules or egg-info directories), as\n * sorted relpaths. Root files enter only when a Gateway manifest or\n * benchmark.json widens the root, or they are README.md, pyproject.toml or\n * Python. */\n get archivePaths(): string[] {\n if (this.pathsMemo) return this.pathsMemo;\n const broad = BROAD_ROOT_MARKERS.some((m) => this.has(m));\n const out: string[] = [];\n const walk = (rel: string) => {\n for (const entry of fs.readdirSync(rel ? path.join(this.dir, rel) : this.dir, { withFileTypes: true })) {\n const child = rel ? `${rel}/${entry.name}` : entry.name;\n if (entry.isDirectory()) {\n if (!skippedDir(entry.name)) walk(child);\n } else if (entry.isFile() && !entry.name.startsWith(\".\")) {\n const rootKept =\n broad || [\"README.md\", PYPROJECT, ...BROAD_ROOT_MARKERS].includes(entry.name) || entry.name.endsWith(\".py\");\n if (rel || rootKept) out.push(child);\n }\n }\n };\n walk(\"\");\n return (this.pathsMemo = out.sort(byCodePoint));\n }\n\n /** What the archive rules leave out, collapsed to the entry that decided\n * it: a pruned directory counts its files once, a dropped root file is\n * named. Dot entries (`.git/`, `.gateway/`, `.gitignore`) are the one\n * universal convention and stay unreported. `push` prints the rest so\n * nothing disappears silently. */\n get exclusions(): Exclusion[] {\n const kept = new Set(this.archivePaths);\n const out: Exclusion[] = [];\n const filesUnder = (rel: string): string[] =>\n fs.readdirSync(path.join(this.dir, rel), { withFileTypes: true }).flatMap((entry) => {\n const child = `${rel}/${entry.name}`;\n if (entry.isDirectory()) return filesUnder(child);\n return entry.isFile() ? [child] : [];\n });\n for (const entry of fs.readdirSync(this.dir, { withFileTypes: true }).sort((a, b) => byCodePoint(a.name, b.name))) {\n if (entry.name.startsWith(\".\")) continue;\n if (entry.isDirectory()) {\n const all = filesUnder(entry.name);\n const missing = all.filter((rel) => !kept.has(rel));\n if (missing.length === 0) continue;\n const whole = missing.length === all.length;\n out.push(...(whole ? [{ path: `${entry.name}/`, files: missing.length }] : missing.map((p) => ({ path: p, files: 1 }))));\n continue;\n }\n // A file, or a symlink to anything: the archive never follows a link.\n if (!kept.has(entry.name)) out.push({ path: entry.name, files: 1 });\n }\n return out;\n }\n\n /** A root `.gitignore` is present: the Python SDK honours it when\n * collecting, this package does not reimplement gitignore. */\n get hasRootGitignore(): boolean {\n return this.has(\".gitignore\");\n }\n\n /** SHA-256 over `utf8(\"file:\" + relpath)` + bytes per archive path in\n * sorted order: the version's identity, byte-compatible with\n * `_archive.compute_content_hash` and Prime Intellect. */\n get contentHash(): string {\n const hasher = createHash(\"sha256\");\n for (const rel of this.archivePaths) {\n hasher.update(Buffer.from(`file:${rel}`, \"utf-8\"));\n hasher.update(fs.readFileSync(path.join(this.dir, rel)));\n }\n return hasher.digest(\"hex\");\n }\n\n // ── Markers ────────────────────────────────────────────────────────────\n\n get isApiBundle(): boolean {\n return this.has(API_BUNDLE_MANIFEST);\n }\n\n get hasManifest(): boolean {\n return this.has(this.worldPath(WORLD_MANIFEST));\n }\n\n get hasSchemaMarker(): boolean {\n return WORLD_SCHEMA_MARKERS.some((m) => this.has(this.worldPath(m)));\n }\n\n /** Harbor task dirs, relative to the tree: `tasks/<name>` when a `tasks/`\n * dir holds them, else the root `<name>` dirs. */\n taskDirs(): string[] {\n const names = new Set<string>();\n for (const rel of this.archivePaths) {\n const m = HARBOR_TASK.exec(rel);\n if (m) names.add(rel.startsWith(\"tasks/\") ? `tasks/${m[1]}` : m[1]!);\n }\n const under = [...names].filter((n) => n.startsWith(\"tasks/\"));\n return (under.length ? under : [...names]).sort();\n }\n\n /** The Python package of a verifiers tree (`<pkg>/__init__.py` or\n * `src/<pkg>/__init__.py`), or null. */\n pythonPackage(): { name: string; init: string } | null {\n if (!this.has(PYPROJECT)) return null;\n for (const base of [\"\", \"src/\"]) {\n const init = this.archivePaths.find((rel) => {\n const m = /^([^/]+)\\/__init__\\.py$/.exec(rel.startsWith(base) ? rel.slice(base.length) : \"\");\n return m !== null && m[1] !== \"tests\";\n });\n if (init) return { name: init.slice(base.length).split(\"/\")[0]!, init };\n }\n return null;\n }\n\n /** The package targets the `verifiers.v1` API: read from the root\n * pyproject and every archived Python module. */\n get isVerifiersV1(): boolean {\n for (const rel of this.archivePaths) {\n if (rel !== PYPROJECT && !rel.endsWith(\".py\")) continue;\n const text = this.text(rel);\n if (text === null) continue;\n if (rel === PYPROJECT ? V1_DEP.test(text) : V1_IMPORT.test(text) || (text.includes(\"__all__\") && V1_TASKSET.test(text)))\n return true;\n }\n return false;\n }\n\n // ── The answer ─────────────────────────────────────────────────────────\n\n /** The runner's kind (`detect_env_kind`): api / mock-tools win over\n * everything, a harbor task tree next, then the verifiers API version. */\n get kind(): EnvKind {\n if (this.isApiBundle) return \"api\";\n if (this.has(WORLD_MANIFEST)) return \"mock-tools\";\n if (this.taskDirs().length) return \"harbor\";\n return this.isVerifiersV1 ? \"verifiers-v1\" : \"verifiers\";\n }\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { gunzipSync } from \"node:zlib\";\n\n/**\n * The sdk-ts reader of a world's gzipped tar bundle — the twin of the\n * platform's `packages/shared/src/server/worlds/tar.ts` walker. A bundle\n * `pull`/`checkout` downloads may have been written by any of the three\n * writers on the platform, so the walk understands every way a name can\n * travel:\n * • the 100-byte ustar `name` field, UTF-8 (this SDK's own writer),\n * • a GNU `L` long-name member naming the member that follows,\n * • a PAX `x` header whose `path=` record overrides the next name — what\n * Python's `tarfile` (the Python SDK's writer) emits for every\n * non-ASCII or >100-byte name, leaving a `?`-replaced ASCII fallback in\n * the ustar field,\n * • the POSIX ustar `prefix` field (bytes 345–500) joined as `prefix/name`.\n * Reading only the ustar field silently corrupts the other three (cold-batch\n * P-05: `ünïcödé ✓.txt` pulled as `?n?c?d? ?.txt`).\n */\n\nexport const TAR_FILE_MODE = 0o644;\nexport const TAR_EXEC_MODE = 0o755;\n\n/** The only mode detail a world keeps: executable or not. */\nexport function archiveMode(mode: number): number {\n return (mode & 0o111) !== 0 ? TAR_EXEC_MODE : TAR_FILE_MODE;\n}\n\nexport type TarMember = {\n name: string;\n bytes: Buffer;\n typeflag: string;\n mode: number;\n};\n\nfunction field(header: Buffer, start: number, end: number): string {\n return header.subarray(start, end).toString(\"utf-8\").replace(/\\0.*$/, \"\");\n}\n\nfunction octalField(header: Buffer, start: number, end: number): number {\n return parseInt(field(header, start, end).trim(), 8);\n}\n\n/** `path=` from a PAX extended-header payload (`LEN key=value\\n` records). */\nfunction paxPath(body: Buffer): string | null {\n let off = 0;\n let found: string | null = null;\n while (off < body.length) {\n const sp = body.indexOf(0x20, off);\n if (sp === -1) break;\n const len = parseInt(body.subarray(off, sp).toString(\"ascii\"), 10);\n if (!Number.isFinite(len) || len <= 0) break;\n const record = body.subarray(sp + 1, off + len);\n const eq = record.indexOf(0x3d);\n const key = eq === -1 ? \"\" : record.subarray(0, eq).toString(\"utf-8\");\n if (key === \"path\")\n found = record\n .subarray(eq + 1)\n .toString(\"utf-8\")\n .replace(/\\n$/, \"\");\n off += len;\n }\n return found;\n}\n\nexport class TarArchive {\n private constructor(private readonly tar: Buffer) {}\n\n static fromGzip(bundle: Buffer): TarArchive {\n return new TarArchive(gunzipSync(bundle));\n }\n\n static fromTar(tar: Buffer): TarArchive {\n return new TarArchive(tar);\n }\n\n /** Every member, names fully resolved; metadata members are consumed. */\n *members(): Generator<TarMember> {\n const tar = this.tar;\n let offset = 0;\n let pendingName: string | null = null;\n while (offset + 512 <= tar.length) {\n const header = tar.subarray(offset, offset + 512);\n offset += 512;\n if (header.every((b) => b === 0)) break;\n const size = octalField(header, 124, 136) || 0;\n const mode = octalField(header, 100, 108) || TAR_FILE_MODE;\n const typeflag = String.fromCharCode(header[156] ?? 0);\n const bytes = tar.subarray(offset, offset + size);\n offset += Math.ceil(size / 512) * 512;\n if (typeflag === \"L\") {\n pendingName = bytes.toString(\"utf-8\").replace(/\\0.*$/, \"\");\n continue;\n }\n if (typeflag === \"x\") {\n pendingName = paxPath(bytes) ?? pendingName;\n continue;\n }\n if (typeflag === \"K\" || typeflag === \"g\") continue;\n const name = pendingName ?? TarArchive.ustarName(header);\n pendingName = null;\n yield { name: name.replace(/^\\.\\//, \"\"), bytes, typeflag, mode };\n }\n }\n\n private static ustarName(header: Buffer): string {\n const name = field(header, 0, 100);\n const magic = header.subarray(257, 262).toString(\"ascii\");\n const prefix = magic === \"ustar\" ? field(header, 345, 500) : \"\";\n return prefix ? `${prefix}/${name}` : name;\n }\n\n /** Regular files only, confined to `dir` (absolute or `..` names are\n * skipped, never written). Returns the number of files written. */\n extractTo(dir: string): number {\n let written = 0;\n for (const member of this.members()) {\n if (member.typeflag !== \"0\" && member.typeflag !== \"\\0\") continue;\n if (!TarArchive.isConfined(member.name)) continue;\n const target = path.join(dir, member.name);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n const mode = archiveMode(member.mode);\n fs.writeFileSync(target, member.bytes, { mode });\n fs.chmodSync(target, mode);\n written++;\n }\n return written;\n }\n\n private static isConfined(name: string): boolean {\n if (name === \"\" || name.startsWith(\"/\")) return false;\n return !name.split(\"/\").includes(\"..\");\n }\n}\n","import { createHash } from \"node:crypto\";\nimport { gzipSync } from \"node:zlib\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\nimport { CheckoutTarget } from \"./checkoutTarget\";\nimport { WorldDir, type Exclusion } from \"./worldDir\";\nimport { TarArchive, TAR_FILE_MODE, archiveMode } from \"./tar\";\n\n/**\n * The working-dir half of the TS CLI: push / pull / checkout / status /\n * branch / tag / propose — a faithful port of the Python client\n * (`gatewaysdk/benchmark_hub/client.py` + `_archive.py`).\n *\n * The content hash is the version's identity and is byte-compatible with\n * Prime Intellect: `WorldDir.contentHash` (./worldDir.ts) computes it here,\n * `WorldTree.contentHash` on the platform and `_archive.compute_content_hash`\n * in the Python SDK; the conformance corpus pins the three to the same bytes.\n *\n * One deliberate refusal, same policy as the web upload path: a bundle with\n * a ROOT `.gitignore` is refused rather than mis-hashed — the Python CLI\n * honors it via `gitignore_parser`, and an imperfect reimplementation here\n * would produce a wrong, Prime-incompatible hash silently.\n */\n\nexport const DEFAULT_BRANCH = \"main\";\nconst META_RELPATH = path.join(\".gateway\", \".env-metadata.json\");\n\n/** The archive-visible files of a working dir, as sorted relpaths\n * (`WorldDir.archivePaths`). Throws on a root .gitignore (see the header). */\nexport function collectArchiveRelPaths(dir: string): string[] {\n const world = WorldDir.open(dir);\n if (world.hasRootGitignore) {\n throw new Error(\n \"This bundle has a root .gitignore, which the Python CLI honors via \" +\n \"gitignore_parser. Reimplementing that imperfectly here would \" +\n \"silently produce a different content hash, so the TS CLI refuses. \" +\n \"Remove the .gitignore (or bake its effect into the tree) and retry.\",\n );\n }\n return world.archivePaths;\n}\n\nexport function computeContentHash(dir: string): string {\n collectArchiveRelPaths(dir);\n return WorldDir.open(dir).contentHash;\n}\n\n// ── deterministic tar.gz writer ─────────────────────────────────────────────\n\nfunction octal(value: number, length: number): Buffer {\n return Buffer.from(\n value.toString(8).padStart(length - 1, \"0\") + \"\\0\",\n \"ascii\",\n );\n}\n\n/** The two modes a stored world file can have: the tar (and `pull`) keep\n * only whether a file is executable — `tests/test.sh` in a harbor tree must\n * still run after a round trip. Owner/mtime are cleared for determinism. */\nconst FILE_MODE = TAR_FILE_MODE;\nexport { archiveMode };\n\nfunction tarHeader(name: string, size: number, mode = FILE_MODE): Buffer {\n const header = Buffer.alloc(512);\n header.write(name, 0, 100, \"utf-8\");\n octal(mode, 8).copy(header, 100);\n octal(0, 8).copy(header, 108); // uid\n octal(0, 8).copy(header, 116); // gid\n octal(size, 12).copy(header, 124);\n octal(0, 12).copy(header, 136); // mtime = 0 (deterministic)\n header.write(\" \", 148, \"ascii\"); // checksum placeholder = spaces\n header.write(\"0\", 156, \"ascii\"); // regular file\n header.write(\"ustar\", 257, \"ascii\");\n header.write(\"00\", 263, \"ascii\");\n let sum = 0;\n for (const byte of header) sum += byte;\n header.write(sum.toString(8).padStart(6, \"0\") + \"\\0 \", 148, \"ascii\");\n return header;\n}\n\nfunction tarMember(name: string, payload: Buffer, mode: number): Buffer[] {\n const parts: Buffer[] = [];\n const nameBytes = Buffer.byteLength(name, \"utf-8\");\n if (nameBytes > 100) {\n // GNU long name: an 'L' member whose body is the real name.\n const body = Buffer.from(name + \"\\0\", \"utf-8\");\n const lHeader = tarHeader(\"././@LongLink\", body.length);\n lHeader.write(\"L\", 156, \"ascii\");\n let sum = 0;\n lHeader.write(\" \", 148, \"ascii\");\n for (const byte of lHeader) sum += byte;\n lHeader.write(sum.toString(8).padStart(6, \"0\") + \"\\0 \", 148, \"ascii\");\n parts.push(lHeader, body);\n const pad = body.length % 512 === 0 ? 0 : 512 - (body.length % 512);\n if (pad) parts.push(Buffer.alloc(pad));\n parts.push(tarHeader(name.slice(0, 100), payload.length, mode));\n } else {\n parts.push(tarHeader(name, payload.length, mode));\n }\n parts.push(payload);\n const pad = payload.length % 512 === 0 ? 0 : 512 - (payload.length % 512);\n if (pad) parts.push(Buffer.alloc(pad));\n return parts;\n}\n\n/** A deterministic .tar.gz of the source files (node's gzip stamps no mtime,\n * matching the Python's mtime=0 gzip). */\nexport function buildSourceTarball(dir: string): Buffer {\n const parts: Buffer[] = [];\n for (const relPath of collectArchiveRelPaths(dir)) {\n const abs = path.join(dir, relPath);\n parts.push(\n ...tarMember(\n relPath,\n fs.readFileSync(abs),\n archiveMode(fs.statSync(abs).mode),\n ),\n );\n }\n parts.push(Buffer.alloc(1024)); // end-of-archive\n return gzipSync(Buffer.concat(parts), { level: 9 });\n}\n\n// ── local metadata (.gateway/.env-metadata.json) ────────────────────────────\n\nexport type LocalMeta = Record<string, unknown> & {\n slug?: string;\n /** Branch the checkout tracks; absent on a tag (detached) checkout. */\n branch?: string;\n /** Tag the checkout was taken from: immutable, so `push` refuses to move it. */\n tag?: string;\n versionId?: string;\n contentHash?: string;\n baseFiles?: Record<string, string>;\n};\n\nexport function readLocalMeta(dir: string): LocalMeta | null {\n try {\n const raw = fs.readFileSync(path.join(dir, META_RELPATH), \"utf-8\");\n const parsed = JSON.parse(raw);\n return parsed && typeof parsed === \"object\" ? (parsed as LocalMeta) : null;\n } catch {\n return null;\n }\n}\n\n/** The slug a push of `dir` lands on: an explicit one, else the slug the dir\n * was pushed to or pulled from (its `.gateway` meta), else the pyproject\n * name, else the directory's name — so a tracked checkout never creates a\n * second world named after its folder. */\nexport function pushSlug(dir: string, explicit?: string): string {\n return resolvePushSlug(dir, { explicit }).slug;\n}\n\nexport type SlugDeclaration = { source: string; slug: string };\n\nexport type PushSlugResolution = {\n slug: string;\n /** Where the slug came from (`--slug`, `.gateway metadata`, `benchmark.json`, `pyproject.toml`, `directory name`). */\n source: string;\n /** The slug the dir's `.gateway/.env-metadata.json` tracks from an earlier push or pull, if any. */\n tracked: string | null;\n /** What the tree itself declares (a caller's benchmark.json, then pyproject.toml), in precedence order. */\n declared: SlugDeclaration[];\n /** A declaration the tracked slug does not match — set only when the tracked slug won without `--slug`. */\n conflict: SlugDeclaration | null;\n};\n\n/** The platform's collision suffix: `acme-2` minted for a taken `acme`. */\nconst MINTED_SUFFIX = /^-\\d+$/;\n\n/** `pushSlug` with its provenance. `declared` are the caller's own slug sources\n * (e.g. `{ \"benchmark.json\": \"x\" }`), consulted before pyproject. A tracked slug\n * that disagrees with what the tree declares is reported as `conflict` so a\n * front door can refuse: that is how a directory pushed once with `--slug X`\n * silently landed every later push on X while its benchmark.json said Y. The\n * platform's collision suffix (`acme-2` minted for a taken `acme`) is not a\n * conflict; any other difference is (`acme-e2e` for `acme` was the mix-up). */\nexport function resolvePushSlug(\n dir: string,\n opts: { explicit?: string; declared?: Record<string, string | null | undefined> } = {},\n): PushSlugResolution {\n const meta = readLocalMeta(dir);\n const tracked = typeof meta?.slug === \"string\" && meta.slug ? meta.slug : null;\n const declared = Object.entries({ ...(opts.declared ?? {}), \"pyproject.toml\": readPyproject(dir).name })\n .filter((entry): entry is [string, string] => typeof entry[1] === \"string\" && entry[1] !== \"\")\n .map(([source, slug]) => ({ source, slug }));\n const base = { tracked, declared, conflict: null };\n if (opts.explicit) return { ...base, slug: opts.explicit, source: \"--slug\" };\n if (tracked) {\n const minted = (d: SlugDeclaration) => tracked.startsWith(d.slug) && MINTED_SUFFIX.test(tracked.slice(d.slug.length));\n const conflict = declared.find((d) => d.slug !== tracked && !minted(d)) ?? null;\n return { ...base, slug: tracked, source: \".gateway metadata\", conflict };\n }\n const first = declared[0];\n if (first) return { ...base, slug: first.slug, source: first.source };\n return { ...base, slug: path.basename(path.resolve(dir)), source: \"directory name\" };\n}\n\n/** The refusal a front door raises on `PushSlugResolution.conflict`: both slugs, both sources, every way out. */\nexport class PushSlugConflict extends Error {\n constructor(\n public readonly dir: string,\n public readonly tracked: string,\n public readonly declared: SlugDeclaration,\n ) {\n super(\n `${dir} tracks slug \\`${tracked}\\` (${META_RELPATH}, from an earlier push) but its ${declared.source} says \\`${declared.slug}\\`. ` +\n `Nothing was pushed. Pass --slug ${declared.slug} to push there (and retrack the dir), --slug ${tracked} to keep pushing to \\`${tracked}\\`, ` +\n `or delete ${META_RELPATH} to forget the earlier push.`,\n );\n this.name = \"PushSlugConflict\";\n }\n}\n\nexport function writeLocalMeta(dir: string, meta: LocalMeta): void {\n fs.mkdirSync(path.join(dir, \".gateway\"), { recursive: true });\n fs.writeFileSync(path.join(dir, META_RELPATH), JSON.stringify(meta, null, 2));\n}\n\nexport function snapshotTreeHashes(dir: string): Record<string, string> {\n const out: Record<string, string> = {};\n for (const relPath of collectArchiveRelPaths(dir)) {\n out[relPath] = createHash(\"sha256\")\n .update(fs.readFileSync(path.join(dir, relPath)))\n .digest(\"hex\");\n }\n return out;\n}\n\nexport function localTreeState(dir: string): {\n meta: LocalMeta | null;\n dirty: string[];\n clean: boolean;\n} {\n const meta = readLocalMeta(dir);\n const base = meta?.baseFiles;\n if (!base || typeof base !== \"object\") {\n return { meta, dirty: [], clean: false };\n }\n const now = snapshotTreeHashes(dir);\n const dirty = new Set<string>();\n for (const [p, h] of Object.entries(now)) if (base[p] !== h) dirty.add(p);\n for (const p of Object.keys(base)) if (!(p in now)) dirty.add(p);\n return { meta, dirty: [...dirty].sort(), clean: dirty.size === 0 };\n}\n\n// ── protocol helpers ─────────────────────────────────────────────────────────\n\nconst sha256b64 = (data: Buffer) =>\n createHash(\"sha256\").update(data).digest(\"base64\");\n\nfunction readPyproject(dir: string): { name?: string; version?: string } {\n try {\n const text = fs.readFileSync(path.join(dir, \"pyproject.toml\"), \"utf-8\");\n // Minimal [project] reads — name and version only, quoted single-line form.\n const section = /\\[project\\]([\\s\\S]*?)(\\n\\[|$)/.exec(text)?.[1] ?? \"\";\n const name = /\\bname\\s*=\\s*\"([^\"]+)\"/.exec(section)?.[1];\n const version = /\\bversion\\s*=\\s*\"([^\"]+)\"/.exec(section)?.[1];\n return { name, version };\n } catch {\n return {};\n }\n}\n\n/** A schema world's own version: `x-gateway.package.version` of its contract\n * (`schema/world.json`, or `server/world/schema/world.json` in an api bundle).\n * What a connector world has instead of a pyproject, so its versions read\n * \"1.0.0\" rather than \"unversioned\" on the platform. */\nfunction readWorldContractVersion(dir: string): {\n name?: string;\n version?: string;\n} {\n const world = WorldDir.open(dir);\n try {\n const parsed = JSON.parse(\n world.text(world.worldPath(\"schema/world.json\")) ?? \"\",\n ) as {\n \"x-gateway\"?: { package?: { id?: string; version?: string } };\n };\n const pkg = parsed[\"x-gateway\"]?.package;\n if (pkg?.version) return { name: pkg.id, version: pkg.version };\n } catch {\n // not a schema world\n }\n return {};\n}\n\n/** The rows the platform previews for a pushed DRAFT: the archive set, one\n * entry per file the content hash covers, so hash, tarball, manifest and\n * `pull` agree on what the world is. Finalize replaces them with rows\n * derived from the stored bytes. */\nexport function buildFileManifest(\n dir: string,\n): { path: string; isDirectory: boolean; size: number; sha256: string }[] {\n return collectArchiveRelPaths(dir).map((relPath) => {\n const payload = fs.readFileSync(path.join(dir, relPath));\n return {\n path: relPath,\n isDirectory: false,\n size: payload.length,\n sha256: createHash(\"sha256\").update(payload).digest(\"hex\"),\n };\n });\n}\n\nasync function putObject(\n url: string,\n data: Buffer,\n shaB64: string,\n): Promise<void> {\n const resp = await fetch(url, {\n method: \"PUT\",\n headers: {\n \"Content-Type\": \"application/gzip\",\n \"x-amz-checksum-sha256\": shaB64,\n },\n body: new Uint8Array(data),\n });\n if (!resp.ok) {\n throw new Error(\n `object PUT -> ${resp.status}: ${(await resp.text()).slice(0, 300)}`,\n );\n }\n}\n\n// ── the workflows ────────────────────────────────────────────────────────────\n\n/** The refusal `push` raises from a tag checkout: tags never move, so the\n * push needs a branch named explicitly. */\nexport class DetachedPushError extends Error {\n constructor(dir: string, tag: string) {\n super(\n `push refused: ${dir} is a checkout of tag \"${tag}\" (tags are immutable). ` +\n `Nothing was pushed. Pass --branch <name> to land these files on a branch, or checkout a branch first.`,\n );\n this.name = \"DetachedPushError\";\n }\n}\n\n/** The branch a push of `dir` moves: an explicit --branch, else the tracked\n * branch, else main — never a tag. */\nexport function pushBranch(dir: string, localMeta: LocalMeta, explicit: string | undefined): string {\n if (explicit) return explicit;\n if (typeof localMeta.tag === \"string\" && localMeta.tag) throw new DetachedPushError(dir, localMeta.tag);\n return (localMeta.branch as string | undefined) ?? DEFAULT_BRANCH;\n}\n\nexport async function push(\n dir: string,\n opts: {\n slug?: string;\n branch?: string;\n force?: boolean;\n message?: string;\n author?: string;\n /** Push on top of this version instead of the local meta's base — what a\n * CI checkout (which has no local meta) passes after resolving the\n * branch tip, so re-validating a PR replaces its own previous push\n * instead of 409ing against it. */\n baseVersionId?: string | null;\n /** Container metadata recorded on resolve — the Python CLI's --name,\n * --description, --tag and --visibility. */\n name?: string;\n description?: string;\n tags?: string[];\n visibility?: string;\n /** Pre-built OCI image ref for image/agentic envs (recorded on the version). */\n imageRef?: string;\n options?: WorldsClientOptions;\n } = {},\n): Promise<{\n containerId: string;\n slug: string;\n versionId: string;\n contentHash: string;\n branch: string;\n state: string | null;\n alreadyUploaded: boolean;\n /** The edit session the push joined (`gateway worlds edit close <slug>` moves main); null when the platform landed it on main directly. */\n editSessionId: string | null;\n /** Files the archive rules kept (what the hash, manifest and tarball cover). */\n filesKept: number;\n /** What the archive rules left out, so nothing disappears silently. */\n excluded: Exclusion[];\n}> {\n const options = opts.options ?? {};\n if (!fs.statSync(dir).isDirectory())\n throw new Error(`Not a directory: ${dir}`);\n const localMeta = readLocalMeta(dir) ?? {};\n const branch = pushBranch(dir, localMeta, opts.branch);\n const baseVersionId = opts.baseVersionId ?? localMeta.versionId ?? null;\n\n const world = WorldDir.open(dir);\n const fileManifest = buildFileManifest(dir);\n if (fileManifest.length === 0)\n throw new Error(\n `Nothing to push: ${dir} has no files the archive rules keep (a world root marker, README.md, pyproject.toml, *.py, or any file below a subdirectory).`,\n );\n const contentHash = world.contentHash;\n const pyproject = readPyproject(dir);\n // A connector world carries its version on its contract, not a pyproject.\n const contractVersion = pyproject.version\n ? undefined\n : readWorldContractVersion(dir).version;\n if (contractVersion) pyproject.version = contractVersion;\n // A dir that tracks a world (created, pulled or pushed before) pushes back\n // to THAT world: its recorded slug wins over the package name, so a world\n // created as `acme-f7` is not re-published as pyproject's `acme` — which is\n // how `worlds ci` minted an unsuffixed twin of every suffixed world.\n const slug =\n opts.slug ??\n localMeta.slug ??\n pyproject.name ??\n path.basename(path.resolve(dir));\n\n // Sent twice on purpose: resolve records it on a container it CREATES,\n // finalize refreshes an existing one — only when the push actually lands.\n // An omitted field leaves the container's value alone; an explicit one\n // replaces it, so `\"\"` clears the description and `[]` clears the tags.\n const metadata = {\n ...(opts.name !== undefined ? { name: opts.name } : {}),\n ...(opts.description !== undefined\n ? { description: opts.description }\n : {}),\n ...(opts.tags !== undefined ? { tags: opts.tags } : {}),\n ...(opts.visibility ? { visibility: opts.visibility } : {}),\n };\n const resolve = await apiRequest<{ containerId: string }>(\n options,\n \"POST\",\n \"/api/public/benchmark-containers/resolve\",\n { slug, ...metadata },\n );\n\n const tarball = buildSourceTarball(dir);\n const bundleSha256 = sha256b64(tarball);\n\n const version = await apiRequest<{\n versionId: string;\n uploadUrl?: string;\n alreadyUploaded?: boolean;\n }>(options, \"POST\", \"/api/public/benchmark-containers/versions\", {\n containerId: resolve.containerId,\n contentHash,\n bundleSha256,\n bundleSizeBytes: tarball.length,\n ...(pyproject.version ? { semanticVersion: pyproject.version } : {}),\n pyprojectMeta: pyproject,\n fileManifest,\n branch,\n baseVersionId,\n ...(opts.force ? { force: true } : {}),\n ...(opts.message ? { changeReason: opts.message } : {}),\n ...(opts.author ? { author: opts.author } : {}),\n ...(opts.imageRef ? { imageRef: opts.imageRef } : {}),\n });\n\n if (version.uploadUrl)\n await putObject(version.uploadUrl, tarball, bundleSha256);\n\n const final = await apiRequest<{ state?: string; branch?: string; editSessionId?: string }>(\n options,\n \"POST\",\n `/api/public/benchmark-containers/versions/${version.versionId}/finalize`,\n {\n branch,\n baseVersionId,\n ...(opts.force ? { force: true } : {}),\n ...metadata,\n },\n );\n\n writeLocalMeta(dir, {\n ...localMeta,\n slug,\n ref: branch,\n branch,\n versionId: version.versionId,\n contentHash,\n semanticVersion: pyproject.version,\n forkedFromVersionId: baseVersionId,\n baseFiles: snapshotTreeHashes(dir),\n });\n return {\n containerId: resolve.containerId,\n slug,\n versionId: version.versionId,\n contentHash,\n branch: final.branch ?? branch,\n state: final.state ?? null,\n alreadyUploaded: Boolean(version.alreadyUploaded),\n editSessionId: final.editSessionId ?? null,\n filesKept: fileManifest.length,\n excluded: world.exclusions,\n };\n}\n\n/** Extract a downloaded bundle into `dir` (paths confined, executable bit\n * kept; every name encoding the platform's writers emit — see ./tar.ts). */\nexport function extractBundle(bundle: Buffer, dir: string): number {\n return TarArchive.fromGzip(bundle).extractTo(dir);\n}\n\n/** What a checkout tracks after a pull: the branch that answered the ref, or\n * the tag it was taken from (detached). Older servers name neither: latest\n * and semver/hash pins land on main; any other ref was a branch. */\nexport function checkoutIdentity(\n ref: string,\n resolved: { branch?: string | null; tag?: string | null },\n): { branch?: string; tag?: string } {\n if (resolved.tag) return { tag: resolved.tag };\n if (resolved.branch) return { branch: resolved.branch };\n const pinned = ref === \"latest\" || /^\\d|^[0-9a-f]{8,}$/.test(ref);\n return { branch: pinned ? DEFAULT_BRANCH : ref };\n}\n\nexport async function pull(\n slugRef: string,\n target?: string,\n options: WorldsClientOptions = {},\n opts: { force?: boolean } = {},\n): Promise<{ slug: string; dir: string; versionId: string; files: number }> {\n const at = slugRef.indexOf(\"@\");\n const slug = at === -1 ? slugRef : slugRef.slice(0, at);\n const ref = at === -1 ? \"latest\" : slugRef.slice(at + 1);\n // Decided first: a refused target costs no request and touches no file.\n const landing = CheckoutTarget.resolve(slug, target, {\n cwd: process.cwd(),\n force: opts.force ?? false,\n state: localTreeState,\n });\n\n const details = await apiRequest<{\n versionId: string;\n contentHash: string;\n semanticVersion?: string | null;\n branch?: string | null;\n tag?: string | null;\n downloadUrl?: string;\n bundleSha256?: string;\n }>(options, \"POST\", \"/api/public/benchmark-containers/resolve-version\", {\n slug,\n ref,\n });\n if (!details.downloadUrl) {\n throw new Error(`${slug}@${ref} resolved but has no uploaded bundle`);\n }\n\n const resp = await fetch(details.downloadUrl);\n if (!resp.ok) throw new Error(`bundle download -> ${resp.status}`);\n const bundle = Buffer.from(await resp.arrayBuffer());\n if (details.bundleSha256 && sha256b64(bundle) !== details.bundleSha256) {\n throw new Error(\n `bundle integrity check failed for ${slug}@${ref}: downloaded sha256 != recorded bundleSha256`,\n );\n }\n\n const dir = landing.dir;\n fs.mkdirSync(dir, { recursive: true });\n landing.clear();\n const files = extractBundle(bundle, dir);\n writeLocalMeta(dir, {\n slug,\n ref,\n ...checkoutIdentity(ref, details),\n versionId: details.versionId,\n contentHash: details.contentHash,\n semanticVersion: details.semanticVersion ?? undefined,\n baseFiles: snapshotTreeHashes(dir),\n });\n return { slug, dir, versionId: details.versionId, files };\n}\n\nexport async function propose(\n dir: string,\n opts: {\n title: string;\n reason: string;\n targetBranch?: string;\n options?: WorldsClientOptions;\n },\n): Promise<{ proposalId: string }> {\n const meta = readLocalMeta(dir);\n if (!meta?.slug || !meta.baseFiles) {\n throw new Error(\n \"This dir has no pull/push base — run pull first, then edit, then propose.\",\n );\n }\n const state = localTreeState(dir);\n if (state.clean)\n throw new Error(\"Nothing to propose — the tree matches its base.\");\n const changes = state.dirty.map((relPath) => {\n const abs = path.join(dir, relPath);\n if (!fs.existsSync(abs))\n return { path: relPath, action: \"delete\" as const };\n return {\n path: relPath,\n action: \"write\" as const,\n newContent: fs.readFileSync(abs, \"utf-8\"),\n };\n });\n const res = await apiRequest<{ proposalId: string }>(\n opts.options ?? {},\n \"POST\",\n \"/api/public/benchmark-containers/proposals\",\n {\n slug: meta.slug,\n title: opts.title,\n changeReason: opts.reason,\n baseVersionId: meta.versionId,\n ...(opts.targetBranch ? { targetBranch: opts.targetBranch } : {}),\n changes,\n },\n );\n return res;\n}\n\nexport async function createRef(\n slug: string,\n name: string,\n kind: \"branch\" | \"tag\",\n versionId?: string,\n options: WorldsClientOptions = {},\n): Promise<{ name: string; kind: string; versionId: string }> {\n return apiRequest(options, \"POST\", \"/api/public/benchmark-containers/refs\", {\n slug,\n name,\n kind,\n ...(versionId ? { versionId } : {}),\n });\n}\n","/**\n * PR validation: push the checkout's world source, run it, gate on the graded\n * result — one composed call, because CI should not have to re-derive the\n * choreography from primitives.\n *\n * The differentiating property, stated so it stays true: validation runs the\n * PULL REQUEST'S OWN world source. The push files the checkout as a version on\n * the PR's branch (content-hash dedup makes re-runs cheap), the dispatch pins\n * that version, and the platform resolves the branch back to its open PR — so\n * the run page names the PR and the PR comment names the run. Nothing here\n * validates a standing deployment while pretending to validate the change.\n */\n\nimport {\n apiRequest,\n detectProvenance,\n listRunConfigs,\n waitForRun,\n type RunReport,\n type WorldsClientOptions,\n} from \"./index\";\nimport { push, pushSlug } from \"./hub\";\n\nexport type ValidatedRun = {\n model: string;\n runId: string;\n report: RunReport | null;\n /** Why this run fails the gate, or null when it passes. */\n failure: string | null;\n};\n\nexport type ValidateReport = {\n ok: boolean;\n slug: string;\n branch: string;\n versionId: string;\n contentHash: string;\n runConfig: { id: string; name: string };\n runs: ValidatedRun[];\n /** A PR-comment-ready summary of the whole validation. */\n markdown: string;\n};\n\nfunction fmtScore(score: number | null): string {\n return score === null ? \"no score\" : score.toFixed(3);\n}\n\nfunction buildMarkdown(\n report: Omit<ValidateReport, \"markdown\">,\n minScore: number | null,\n source?: { repoUrl?: string; commit?: string },\n): string {\n const lines: string[] = [];\n lines.push(\n `### World validation ${report.ok ? \"passed\" : \"failed\"} — \\`${report.slug}@${report.branch}\\``,\n );\n lines.push(\"\");\n // Name the exact source that ran: the commit on GitHub when we know it,\n // always the content hash the platform pinned.\n const commitLink =\n source?.repoUrl && source?.commit\n ? `[\\`${source.commit.slice(0, 12)}\\`](${source.repoUrl}/commit/${source.commit})`\n : null;\n lines.push(\n `Ran the pull request's own world source` +\n (commitLink ? ` (${commitLink} on \\`${report.branch}\\`` : ` (`) +\n `${commitLink ? \", \" : \"\"}pinned as \\`${report.contentHash.slice(0, 12)}\\`) ` +\n `through run config **${report.runConfig.name}**` +\n (minScore !== null ? `, gating at score ≥ ${minScore}.` : \".\"),\n );\n lines.push(\"\");\n lines.push(\"| Model | Status | Score | Run |\");\n lines.push(\"| --- | --- | ---: | --- |\");\n for (const run of report.runs) {\n const r = run.report;\n const link = r?.url ? `[open](${r.url})` : \"—\";\n const status = run.failure\n ? `❌ ${run.failure}`\n : `✅ ${r?.status ?? \"COMPLETED\"}`;\n lines.push(\n `| \\`${run.model}\\` | ${status} | ${fmtScore(r?.score ?? null)} | ${link} |`,\n );\n }\n const taskRows = report.runs.flatMap((run) =>\n (run.report?.samples ?? []).map((sample) => ({\n model: run.model,\n task: sample.task ?? \"?\",\n reward: sample.reward,\n })),\n );\n // Every scenario, in the open: a validation whose per-scenario grades hide\n // behind a fold reads as one opaque number. Fold only when the table is\n // genuinely long.\n if (taskRows.length > 0) {\n const fold = taskRows.length > 12;\n lines.push(\"\");\n if (fold) {\n lines.push(\n `<details><summary>Per-scenario rewards (${taskRows.length})</summary>`,\n );\n lines.push(\"\");\n } else {\n lines.push(`**Scenarios (${taskRows.length})**`);\n lines.push(\"\");\n }\n lines.push(\"| Scenario | Model | Reward |\");\n lines.push(\"| --- | --- | ---: |\");\n for (const row of taskRows) {\n lines.push(\n `| ${row.task} | \\`${row.model}\\` | ${row.reward === null ? \"no score\" : row.reward.toFixed(2)} |`,\n );\n }\n if (fold) {\n lines.push(\"\");\n lines.push(\"</details>\");\n }\n }\n return lines.join(\"\\n\");\n}\n\n/**\n * Push `dir` on the current (or given) branch, dispatch the named run config\n * against the pushed version, wait for every run, and gate.\n *\n * The gate: every dispatch accepted, every run terminal COMPLETED, and — when\n * `minScore` is set — every run's score meets it. A run with NO score fails a\n * score gate rather than passing it: null is \"not scored\", never 0 and never\n * fine.\n */\nexport async function validateWorld(\n dir: string,\n opts: {\n slug?: string;\n runConfig: string;\n branch?: string;\n minScore?: number | null;\n timeoutMinutes?: number;\n onProgress?: (line: string) => void;\n options?: WorldsClientOptions;\n },\n): Promise<ValidateReport> {\n const options = opts.options ?? {};\n const progress = opts.onProgress ?? (() => {});\n const minScore = opts.minScore ?? null;\n\n const provenance = detectProvenance();\n const branch = opts.branch ?? provenance.branch;\n if (!branch)\n throw new Error(\n \"No branch to validate on: pass --branch or run inside a git checkout / GitHub Actions.\",\n );\n\n const slug = pushSlug(dir, opts.slug);\n progress(`pushing ${dir} as ${slug}@${branch}…`);\n // CI checkouts carry no local push meta, so a re-validation would 409\n // against the branch tip its own previous run created. Validation's\n // semantics are \"this branch's tip BECOMES the PR's source\": resolve the\n // current tip and push on top of it. A branch that does not exist yet\n // resolves to no base, which is a fresh branch — also correct.\n let tipVersionId: string | null = null;\n try {\n const tip = await apiRequest<{ versionId?: string }>(\n options,\n \"POST\",\n \"/api/public/benchmark-containers/resolve-version\",\n { slug, ref: branch },\n );\n tipVersionId = tip.versionId ?? null;\n } catch {\n tipVersionId = null;\n }\n const pushed = await push(dir, {\n slug,\n branch,\n baseVersionId: tipVersionId,\n message: `PR validation push (${provenance.commit?.slice(0, 12) ?? \"local\"})`,\n ...(provenance.actor?.name ? { author: provenance.actor.name } : {}),\n options,\n });\n progress(`pushed version ${pushed.versionId} (${pushed.contentHash.slice(0, 12)})`);\n\n // Resolve the run config by name (the stable handle CI configures) or id.\n const configs = await listRunConfigs(options);\n const runConfig =\n configs.find((c) => c.id === opts.runConfig) ??\n configs.find((c) => c.name === opts.runConfig);\n if (!runConfig) {\n const known = configs.map((c) => c.name).join(\", \") || \"(none)\";\n throw new Error(\n `Run config \"${opts.runConfig}\" not found in this project. Have: ${known}`,\n );\n }\n\n progress(`dispatching run config \"${runConfig.name}\" (${runConfig.models.join(\", \")})…`);\n const dispatched = await apiRequest<{\n versionLabel: string;\n runs: { model: string; runId: string; ok: boolean; error?: string }[];\n }>(options, \"POST\", \"/api/public/benchmark-containers/run-configs/dispatch\", {\n runConfigId: runConfig.id,\n versionId: pushed.versionId,\n ...provenance,\n });\n\n // The run's platform page. New deployments return it on the run report\n // (`url`); against an older deployment we build the same page from the\n // evaluation id, because a PR comment that cannot link the run defeats\n // the point of the comment.\n const host = (\n options.host ??\n process.env.GATEWAY_HOST ??\n \"https://withgateway.ai\"\n ).replace(/\\/+$/, \"\");\n let projectId: string | null = null;\n try {\n const projects = await apiRequest<{ data?: { id?: string }[] }>(\n options,\n \"GET\",\n \"/api/public/projects\",\n );\n projectId = projects.data?.[0]?.id ?? null;\n } catch {\n projectId = null;\n }\n const fallbackUrl = (report: RunReport): string | null => {\n if (report.url) return report.url;\n const evaluationId = report.evaluations[0]?.id;\n return projectId && evaluationId\n ? `${host}/project/${projectId}/environment/runs/${encodeURIComponent(evaluationId)}`\n : null;\n };\n\n const runs: ValidatedRun[] = [];\n for (const run of dispatched.runs) {\n if (!run.ok) {\n runs.push({\n model: run.model,\n runId: run.runId,\n report: null,\n failure: `dispatch failed: ${run.error ?? \"unknown error\"}`,\n });\n continue;\n }\n progress(`waiting on ${run.model} (run ${run.runId})…`);\n let report: RunReport | null = null;\n let failure: string | null = null;\n try {\n report = await waitForRun(run.runId, {\n timeoutMinutes: opts.timeoutMinutes ?? 45,\n options,\n onTick: (r) =>\n progress(\n `…${run.model}: ${r.status.toLowerCase()} (${r.shardsCompleted ?? 0}/${r.parallelism} shards)`,\n ),\n });\n report = { ...report, url: fallbackUrl(report) };\n if (report.status.toUpperCase() !== \"COMPLETED\") {\n failure = report.status;\n } else if (minScore !== null) {\n if (report.score === null) failure = \"completed without a score\";\n else if (report.score < minScore)\n failure = `score ${fmtScore(report.score)} < ${minScore}`;\n }\n } catch (error) {\n failure = error instanceof Error ? error.message : String(error);\n }\n runs.push({ model: run.model, runId: run.runId, report, failure });\n }\n\n const base = {\n ok: runs.length > 0 && runs.every((r) => r.failure === null),\n slug: pushed.slug,\n branch,\n versionId: pushed.versionId,\n contentHash: pushed.contentHash,\n runConfig: { id: runConfig.id, name: runConfig.name },\n runs,\n };\n return {\n ...base,\n markdown: buildMarkdown(base, minScore, {\n repoUrl: provenance.repoUrl,\n commit: provenance.commit,\n }),\n };\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\n\n/**\n * The CLI sandbox: a server-side workspace opened on a READY version of a\n * world (`/workspace/env` in the console agent's sandbox) — or, with\n * `{ new, from }`, on a world that does not exist yet, seeded from the\n * `schema init` scaffold or a shipped template and created by its first\n * commit — edited and run there, and committed straight into the version\n * service; the source never lands on the caller's disk. `importData` is the\n * data door beside `commit`: a rows file in the sandbox tree into the platform\n * world's data ledger, read out by the platform (no credential enters the\n * sandbox, nothing passes through this machine). One client under\n * both `gateway worlds sandbox …` and `gateway bench sandbox …`; the\n * Python twin is `gatewaysdk.benchmark_hub.sandbox.WorldSandboxClient`.\n */\n\n/** Mirrors `SandboxSummaryResponse` (web/features/public-api/types/world-sandboxes.ts). */\nexport type SandboxSummary = {\n sandboxId: string;\n slug: string;\n /** null while a new-world sandbox awaits its first commit. */\n containerId: string | null;\n /** The version the next commit is validated against; advances on commit. null before the first commit of a new world. */\n baseVersionId: string | null;\n /** Set on a new-world sandbox until its first commit creates the world. */\n pendingSlug: string | null;\n status: \"open\" | \"closed\";\n lastCommitVersionId: string | null;\n createdAt: string;\n};\n\nexport type SandboxOpened = SandboxSummary & {\n /** null for a new-world sandbox (no base). */\n baseContentHash: string | null;\n branch: string;\n dataSnapshotId: string | null;\n fileCount: number;\n workdir: string;\n /** The `gateway` CLI `exec` finds on PATH (the platform's version, staged runtime digest); null when the image cannot host it — `warnings` says why. */\n cli: { version: string; digest: string } | null;\n warnings: string[];\n};\n\nexport type SandboxExecResult = {\n exitCode: number;\n stdout: string;\n stderr: string;\n timedOut: boolean;\n truncated: boolean;\n durationMs: number;\n /** Why `gateway`/`sqlite3` were not on PATH for this command; empty when the runtime is staged. */\n warnings: string[];\n};\n\nexport type SandboxChanges = { added: string[]; modified: string[]; removed: string[] };\n\nexport type SandboxCheckResult = {\n ok: boolean;\n contentHash: string | null;\n noChange: boolean;\n fileCount: number;\n changes: SandboxChanges;\n /** Working-tree paths left out of the version: `.gatewayignore`, default scratch, credential-shaped files, links. */\n ignored: string[];\n /** Why a listed path was held back (credential-shaped, a link, unhashed by the gate); paths only. */\n warnings: string[];\n error: string | null;\n};\n\nexport type SandboxCommitResult = {\n /** The world the commit landed on. */\n slug: string;\n versionId: string;\n contentHash: string;\n branch: string;\n deduped: boolean;\n noChange: boolean;\n changes: SandboxChanges;\n ignored: string[];\n /** The same warnings `check` gives, so a commit never hides what it left out. */\n warnings: string[];\n /** The API key's edit session the commit joined; `gateway worlds edit close <slug>` moves main. */\n editSessionId?: string;\n};\n\n/** Mirrors `PostSandboxImportBody`. */\nexport type SandboxImportInput = {\n /** A .json/.jsonl/.ndjson/.csv/.tsv (optionally .gz) relative to the world root. */\n path: string;\n entity?: string;\n /** One character (a real tab for TSV); defaults by extension. */\n delimiter?: string;\n mode?: \"append\" | \"replace\";\n merge?: \"upsert\" | \"fill\";\n redact?: \"off\" | \"apply\" | \"refuse\";\n atomic?: boolean;\n dryRun?: boolean;\n message?: string;\n};\n\n/** Mirrors `PostSandboxImportResponse` (201). */\nexport type SandboxImportResult = {\n containerId: string;\n slug: string;\n batchId: string | null;\n state: string;\n versionId: string | null;\n baseVersionId: string;\n contentHash: string | null;\n deduped: boolean;\n entityCounts: Record<string, number>;\n kind: string | null;\n dryRun: boolean;\n refusalCount: number;\n rowCount: number;\n chunkCount: number;\n /** `sandbox:<id>/<path>`. */\n source: string;\n};\n\n/** Mirrors `PostSandboxImportPendingResponse` (202): poll `worlds data batches`. */\nexport type SandboxImportPending = {\n batchId: string;\n state: string;\n rowCount: number;\n chunkCount: number;\n source: string;\n};\n\nexport const isSandboxImportPending = (\n answer: SandboxImportResult | SandboxImportPending,\n): answer is SandboxImportPending => !(\"versionId\" in answer);\n\n/** Mirrors `PostSandboxOpenBody`: an existing world at a ref, or a new world seeded from a template. */\nexport type SandboxOpenExisting = { slug: string; ref?: string };\nexport type SandboxOpenNew = { new: string; from: string };\nexport type SandboxOpenTarget = SandboxOpenExisting | SandboxOpenNew;\n\n/** `slug` or `slug@ref` → the open body; a bare slug opens the latest READY version. */\nexport function parseSlugRef(slugRef: string): SandboxOpenExisting {\n const at = slugRef.indexOf(\"@\");\n if (at === -1) return { slug: slugRef };\n return { slug: slugRef.slice(0, at), ref: slugRef.slice(at + 1) };\n}\n\nconst sid = encodeURIComponent;\n\n/** `sandbox list` narrows: status, world, count (newest first). */\nexport type SandboxListFilter = {\n status?: \"open\" | \"closed\";\n slug?: string;\n limit?: number;\n};\n\nfunction listQuery(filter: SandboxListFilter): string {\n const params = new URLSearchParams();\n if (filter.status) params.set(\"status\", filter.status);\n if (filter.slug) params.set(\"slug\", filter.slug);\n if (filter.limit !== undefined) params.set(\"limit\", String(filter.limit));\n const qs = params.toString();\n return qs ? `?${qs}` : \"\";\n}\n\nexport class WorldSandboxClient {\n constructor(private readonly options: WorldsClientOptions = {}) {}\n\n /**\n * `{ slug, ref? }` opens a READY version; `{ new, from }` opens a sandbox on\n * a world that does not exist yet (409 `world_exists` if the slug is taken,\n * 400 naming the shipped templates if `from` is unknown). Its first commit\n * creates the world on `main`.\n */\n open(target: SandboxOpenTarget): Promise<SandboxOpened> {\n return apiRequest(this.options, \"POST\", \"/api/public/benchmark-containers/sandboxes\", target);\n }\n\n status(sandboxId: string): Promise<SandboxSummary> {\n return apiRequest(this.options, \"GET\", `/api/public/benchmark-containers/sandboxes/${sid(sandboxId)}`);\n }\n\n /** The project's sandboxes, newest first — how an agent finds one it left open. */\n async list(filter: SandboxListFilter = {}): Promise<SandboxSummary[]> {\n const res = await apiRequest<{ sandboxes: SandboxSummary[] }>(\n this.options,\n \"GET\",\n `/api/public/benchmark-containers/sandboxes${listQuery(filter)}`,\n );\n return res.sandboxes;\n }\n\n async read(sandboxId: string, filePath: string): Promise<{ path: string; size: number; bytes: Buffer }> {\n const res = await apiRequest<{ path: string; size: number; contentBase64: string }>(\n this.options,\n \"GET\",\n `/api/public/benchmark-containers/sandboxes/${sid(sandboxId)}/file?path=${encodeURIComponent(filePath)}`,\n );\n return { path: res.path, size: res.size, bytes: Buffer.from(res.contentBase64, \"base64\") };\n }\n\n write(sandboxId: string, filePath: string, bytes: Buffer): Promise<{ path: string; size: number }> {\n return apiRequest(this.options, \"PUT\", `/api/public/benchmark-containers/sandboxes/${sid(sandboxId)}/file`, {\n path: filePath,\n contentBase64: bytes.toString(\"base64\"),\n });\n }\n\n exec(\n sandboxId: string,\n input: { command: string; cwd?: string; timeoutMs?: number },\n ): Promise<SandboxExecResult> {\n return apiRequest(this.options, \"POST\", `/api/public/benchmark-containers/sandboxes/${sid(sandboxId)}/exec`, input);\n }\n\n check(sandboxId: string): Promise<SandboxCheckResult> {\n return apiRequest(this.options, \"POST\", `/api/public/benchmark-containers/sandboxes/${sid(sandboxId)}/check`, {});\n }\n\n commit(sandboxId: string, input: { message: string; branch?: string }): Promise<SandboxCommitResult> {\n return apiRequest(this.options, \"POST\", `/api/public/benchmark-containers/sandboxes/${sid(sandboxId)}/commit`, input);\n }\n\n /**\n * A rows file already in the sandbox tree into the PLATFORM world the\n * sandbox was opened on (201 with the version, 202 with the batch to poll,\n * 400 naming a refused row). Not `commit`: a commit versions the source\n * tree and never carries data.\n */\n importData(sandboxId: string, input: SandboxImportInput): Promise<SandboxImportResult | SandboxImportPending> {\n return apiRequest(this.options, \"POST\", `/api/public/benchmark-containers/sandboxes/${sid(sandboxId)}/import`, input);\n }\n\n close(sandboxId: string): Promise<SandboxSummary> {\n return apiRequest(this.options, \"DELETE\", `/api/public/benchmark-containers/sandboxes/${sid(sandboxId)}`);\n }\n}\n","/**\n * `describeWorld(slug)` — what a world holds and how each field is stored,\n * from `GET /api/public/worlds/{slug}`: the entities (primary key, unique\n * keys, relationships, row count, fields with their `[redact]` policy) and\n * the `[redact]` table itself, so `storedForms(world, field, plaintext)`\n * can compute a lookup value without Python. The CLI twin is\n * `gateway worlds describe <slug>`; for a directory the CLI asks the schema\n * runtime instead and merges the same shape.\n */\n\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\nimport type { RedactPolicy, Redaction } from \"./redaction\";\nimport { parseSlugRef } from \"./sandbox\";\n\nexport type WorldField = {\n name: string;\n type: string | null;\n required: boolean;\n /** How the store holds it; null means in the clear (queryable by plaintext as given). */\n redaction: Redaction | null;\n};\n\nexport type WorldRelationship = {\n fields: string[];\n target: string;\n on_delete?: string;\n};\n\nexport type WorldEntityMapping = {\n localEntity: string;\n localField: string;\n depEntity: string;\n depField: string;\n /** A closed set, applied left to right before each world's own redaction. */\n transform: string[];\n};\n\nexport type WorldDependency = {\n alias: string;\n dependsOn: { slug: string | null; versionId: string };\n task: string | null;\n tools: string[];\n entities: WorldEntityMapping[];\n};\n\nexport type WorldEntity = {\n name: string;\n primaryKey: string[];\n unique: string[][];\n relationships: WorldRelationship[];\n /** Rows in the head version; null when the platform does not count this kind. */\n rowCount: number | null;\n fields: WorldField[];\n};\n\nexport type WorldDescription = {\n slug: string;\n name: string;\n description: string | null;\n kind: string;\n version: { id: string; contentHash: string; semanticVersion: string | null };\n url: string;\n hostedUrl: string | null;\n tools: { name: string; signature: string; doc: string | null }[];\n taskCount: number;\n links: { tasks: string; sessions: string };\n /** World-to-world links from `[dependencies]`, resolved at commit, with the\n * entity mappings `--across` follows. */\n dependencies?: WorldDependency[];\n entities: WorldEntity[];\n redact: RedactPolicy | null;\n};\n\n/** The world at `slug@ref`, described — `ref` is the one grammar shared with\n * pull/checkout/sandbox (`latest` | branch | tag | semver | version id | hash\n * prefix); a bare slug describes the head of `main`. An unknown ref is the\n * route's 404, never the head. */\nexport async function describeWorld(\n slugRef: string,\n options: WorldsClientOptions = {},\n): Promise<WorldDescription> {\n const { slug, ref } = parseSlugRef(slugRef);\n const query = ref === undefined ? \"\" : `?ref=${encodeURIComponent(ref)}`;\n return apiRequest<WorldDescription>(\n options,\n \"GET\",\n `/api/public/worlds/${encodeURIComponent(slug)}${query}`,\n );\n}\n","/**\n * JSON as the Python CLI sees it, so both CLIs write the same bytes.\n *\n * `JSON.parse` + `JSON.stringify` are not enough for parity with\n * `json.loads` + `json.dumps(separators=(\",\", \":\"), ensure_ascii=False)`:\n * JavaScript loses `1.0` vs `1` (Python keeps the float), rounds integers past\n * 2^53, moves integer-like keys to the front of an object, and spells\n * exponents differently (`1e-7` vs `1e-07`). Here a number keeps its source\n * text and its Python type, an object is a Map (insertion order, always), and\n * `dumps` renders exactly what CPython renders.\n */\n\nexport class JsonNumber {\n /** The lexeme as it appeared, e.g. \"1.0\", \"-0\", \"1e21\". */\n constructor(readonly text: string) {}\n /** A float in Python's eyes: a fraction, an exponent, or a non-finite literal. */\n get isFloat(): boolean {\n return /[.eE]/.test(this.text) || /[nN]/.test(this.text);\n }\n get value(): number {\n return Number(this.text);\n }\n}\n\nexport type JsonObject = Map<string, JsonValue>;\nexport type JsonValue = null | boolean | string | JsonNumber | JsonValue[] | JsonObject;\n\nexport class JsonSyntaxError extends Error {}\n\nexport const isObject = (value: JsonValue | undefined): value is JsonObject => value instanceof Map;\n\n// ------------------------------------------------------------------ parsing\n\n/** Parse one JSON text (a line, a row, a document) into the model above.\n * Accepts what `json.loads` accepts, including NaN/Infinity literals. */\nexport function parseJson(text: string): JsonValue {\n const p = new Parser(text);\n p.skipWs();\n const value = p.value();\n p.skipWs();\n if (p.i < text.length) throw new JsonSyntaxError(`Extra data at ${p.i}`);\n return value;\n}\n\nclass Parser {\n i = 0;\n constructor(readonly s: string) {}\n\n skipWs(): void {\n const s = this.s;\n while (this.i < s.length) {\n const c = s.charCodeAt(this.i);\n if (c === 0x20 || c === 0x0a || c === 0x0d || c === 0x09) this.i++;\n else break;\n }\n }\n\n fail(what: string): never {\n throw new JsonSyntaxError(`${what} at ${this.i}`);\n }\n\n value(): JsonValue {\n const s = this.s;\n if (this.i >= s.length) this.fail(\"Expecting value\");\n const c = s[this.i]!;\n if (c === \"{\") return this.object();\n if (c === \"[\") return this.array();\n if (c === '\"') return this.string();\n if (c === \"t\") return this.literal(\"true\", true);\n if (c === \"f\") return this.literal(\"false\", false);\n if (c === \"n\") return this.literal(\"null\", null);\n if (c === \"N\") return this.literal(\"NaN\", new JsonNumber(\"NaN\"));\n if (c === \"I\") return this.literal(\"Infinity\", new JsonNumber(\"Infinity\"));\n return this.number();\n }\n\n literal<T extends JsonValue>(word: string, value: T): T {\n if (!this.s.startsWith(word, this.i)) this.fail(\"Expecting value\");\n this.i += word.length;\n return value;\n }\n\n number(): JsonNumber {\n const s = this.s;\n const start = this.i;\n if (s[this.i] === \"-\") {\n this.i++;\n if (s.startsWith(\"Infinity\", this.i)) {\n this.i += 8;\n return new JsonNumber(\"-Infinity\");\n }\n }\n const intStart = this.i;\n if (s[this.i] === \"0\") this.i++;\n else {\n while (this.i < s.length && isDigit(s.charCodeAt(this.i))) this.i++;\n if (this.i === intStart) this.fail(\"Expecting value\");\n }\n if (s[this.i] === \".\") {\n this.i++;\n const fracStart = this.i;\n while (this.i < s.length && isDigit(s.charCodeAt(this.i))) this.i++;\n if (this.i === fracStart) this.fail(\"Invalid number\");\n }\n if (s[this.i] === \"e\" || s[this.i] === \"E\") {\n this.i++;\n if (s[this.i] === \"+\" || s[this.i] === \"-\") this.i++;\n const expStart = this.i;\n while (this.i < s.length && isDigit(s.charCodeAt(this.i))) this.i++;\n if (this.i === expStart) this.fail(\"Invalid number\");\n }\n return new JsonNumber(s.slice(start, this.i));\n }\n\n string(): string {\n const s = this.s;\n this.i++; // opening quote\n let out = \"\";\n let runStart = this.i;\n for (;;) {\n if (this.i >= s.length) this.fail(\"Unterminated string\");\n const c = s.charCodeAt(this.i);\n if (c === 0x22) {\n out += s.slice(runStart, this.i);\n this.i++;\n return out;\n }\n if (c < 0x20) this.fail(\"Invalid control character\");\n if (c !== 0x5c) {\n this.i++;\n continue;\n }\n out += s.slice(runStart, this.i);\n this.i++;\n const e = s[this.i];\n switch (e) {\n case '\"':\n case \"\\\\\":\n case \"/\":\n out += e;\n break;\n case \"b\":\n out += \"\\b\";\n break;\n case \"f\":\n out += \"\\f\";\n break;\n case \"n\":\n out += \"\\n\";\n break;\n case \"r\":\n out += \"\\r\";\n break;\n case \"t\":\n out += \"\\t\";\n break;\n case \"u\": {\n const hex = s.slice(this.i + 1, this.i + 5);\n if (!/^[0-9a-fA-F]{4}$/.test(hex)) this.fail(\"Invalid \\\\u escape\");\n out += String.fromCharCode(parseInt(hex, 16));\n this.i += 4;\n break;\n }\n default:\n this.fail(\"Invalid escape\");\n }\n this.i++;\n runStart = this.i;\n }\n }\n\n array(): JsonValue[] {\n this.i++;\n const out: JsonValue[] = [];\n this.skipWs();\n if (this.s[this.i] === \"]\") {\n this.i++;\n return out;\n }\n for (;;) {\n this.skipWs();\n out.push(this.value());\n this.skipWs();\n const c = this.s[this.i];\n if (c === \",\") {\n this.i++;\n continue;\n }\n if (c === \"]\") {\n this.i++;\n return out;\n }\n this.fail(\"Expecting ',' delimiter\");\n }\n }\n\n object(): JsonObject {\n this.i++;\n const out: JsonObject = new Map();\n this.skipWs();\n if (this.s[this.i] === \"}\") {\n this.i++;\n return out;\n }\n for (;;) {\n this.skipWs();\n if (this.s[this.i] !== '\"') this.fail(\"Expecting property name enclosed in double quotes\");\n const key = this.string();\n this.skipWs();\n if (this.s[this.i] !== \":\") this.fail(\"Expecting ':' delimiter\");\n this.i++;\n this.skipWs();\n out.set(key, this.value());\n this.skipWs();\n const c = this.s[this.i];\n if (c === \",\") {\n this.i++;\n continue;\n }\n if (c === \"}\") {\n this.i++;\n return out;\n }\n this.fail(\"Expecting ',' delimiter\");\n }\n }\n}\n\nconst isDigit = (c: number): boolean => c >= 0x30 && c <= 0x39;\n\n// ------------------------------------------------------------ serialising\n\n/** `json.dumps(value, separators=(\",\", \":\"), ensure_ascii=False)`, byte for byte. */\nexport function dumps(value: JsonValue): string {\n if (value === null) return \"null\";\n if (value === true) return \"true\";\n if (value === false) return \"false\";\n if (typeof value === \"string\") return JSON.stringify(value);\n if (value instanceof JsonNumber) return numberText(value);\n if (Array.isArray(value)) return \"[\" + value.map(dumps).join(\",\") + \"]\";\n const parts: string[] = [];\n for (const [key, item] of value) parts.push(JSON.stringify(key) + \":\" + dumps(item));\n return \"{\" + parts.join(\",\") + \"}\";\n}\n\n/** How `json.dumps` spells a parsed number: ints verbatim (`-0` becomes `0`),\n * floats through `float.__repr__`, non-finite as NaN/Infinity. */\nexport function numberText(n: JsonNumber): string {\n if (!n.isFloat) return /^-0+$/.test(n.text) ? \"0\" : n.text;\n const value = n.value;\n if (Number.isNaN(value)) return \"NaN\";\n if (value === Infinity) return \"Infinity\";\n if (value === -Infinity) return \"-Infinity\";\n return pyFloatRepr(value);\n}\n\n/** `str(value)` for the values the redaction digest sees: str, int, float, bool. */\nexport function pyStr(value: string | boolean | JsonNumber): string {\n if (typeof value === \"string\") return value;\n if (typeof value === \"boolean\") return value ? \"True\" : \"False\";\n if (!value.isFloat) return numberText(value);\n const v = value.value;\n if (Number.isNaN(v)) return \"nan\";\n if (v === Infinity) return \"inf\";\n if (v === -Infinity) return \"-inf\";\n return pyFloatRepr(v);\n}\n\n/**\n * CPython's `repr(float)`: the shortest digits that round-trip (which\n * JavaScript's `String(x)` also produces), laid out Python's way — a\n * trailing `.0` on integral values, scientific notation only below 1e-4 or\n * from 1e16, and exponents of at least two digits with a sign.\n */\nexport function pyFloatRepr(x: number): string {\n if (x === 0) return Object.is(x, -0) ? \"-0.0\" : \"0.0\";\n const sign = x < 0 ? \"-\" : \"\";\n const js = String(Math.abs(x));\n const [mantissa, exponentPart] = js.split(\"e\");\n let exponent = exponentPart ? Number(exponentPart) : 0;\n const [intPart, fracPart = \"\"] = mantissa!.split(\".\");\n let digits = intPart! + fracPart;\n // decpt: how many digits sit before the decimal point (may be <= 0 or > length).\n let decpt = intPart!.length + exponent;\n const leading = digits.match(/^0*/)![0].length;\n digits = digits.slice(leading);\n decpt -= leading;\n digits = digits.replace(/0+$/, \"\");\n if (digits === \"\") return sign + \"0.0\";\n const sci = decpt - 1;\n if (sci >= -4 && sci < 16) {\n if (decpt <= 0) return sign + \"0.\" + \"0\".repeat(-decpt) + digits;\n if (decpt >= digits.length) return sign + digits + \"0\".repeat(decpt - digits.length) + \".0\";\n return sign + digits.slice(0, decpt) + \".\" + digits.slice(decpt);\n }\n exponent = sci;\n const mag = String(Math.abs(exponent)).padStart(2, \"0\");\n return sign + digits[0] + (digits.length > 1 ? \".\" + digits.slice(1) : \"\") + \"e\" + (exponent < 0 ? \"-\" : \"+\") + mag;\n}\n\n/**\n * Python's `round(x, ndigits)` for the redaction policy: an int is returned\n * unchanged, a float is correctly rounded on its exact binary value with ties\n * to even (`round(0.125, 2) == 0.12`), then re-read as the nearest double.\n */\nexport function pyRound(n: JsonNumber, ndigits: number): JsonNumber {\n if (!n.isFloat) return n;\n const x = n.value;\n if (!Number.isFinite(x)) return n;\n const sign = x < 0 ? -1 : 1;\n const magnitude = Math.abs(x);\n // Every double at or above 2^53 is an integer already.\n if (magnitude >= 9007199254740992) return new JsonNumber(pyFloatRepr(x));\n const { m, k } = exactFraction(magnitude); // magnitude = m / 2^k, m odd (or zero)\n let rounded: number;\n if (k <= ndigits) rounded = magnitude; // exact at this precision\n else if (k !== ndigits + 1) rounded = Number(magnitude.toFixed(ndigits)); // no tie possible: correctly rounded\n else {\n // Exactly k = ndigits + 1 fractional digits, the last one a 5: a tie. Half to even.\n const scaled = m * 5n ** BigInt(k); // magnitude * 10^k, an integer\n let kept = scaled / 10n; // magnitude * 10^ndigits, truncated\n if (kept % 2n === 1n) kept += 1n;\n const text = kept.toString().padStart(ndigits + 1, \"0\");\n rounded = ndigits === 0 ? Number(text) : Number(text.slice(0, -ndigits) + \".\" + text.slice(-ndigits));\n }\n return new JsonNumber(pyFloatRepr(sign * rounded));\n}\n\n/** A finite non-negative double as m / 2^k with m odd (m = 0, k = 0 for zero). */\nfunction exactFraction(x: number): { m: bigint; k: number } {\n if (x === 0) return { m: 0n, k: 0 };\n const view = new DataView(new ArrayBuffer(8));\n view.setFloat64(0, x);\n const bits = view.getBigUint64(0);\n const exponent = Number((bits >> 52n) & 0x7ffn);\n let mantissa = bits & ((1n << 52n) - 1n);\n let e: number;\n if (exponent === 0) e = -1074;\n else {\n mantissa |= 1n << 52n;\n e = exponent - 1075;\n }\n while (mantissa !== 0n && (mantissa & 1n) === 0n) {\n mantissa >>= 1n;\n e += 1;\n }\n if (e >= 0) return { m: mantissa << BigInt(e), k: 0 };\n return { m: mantissa, k: -e };\n}\n","/**\n * Named plaintext transforms for cross-world entity mappings.\n *\n * A mapping between two worlds' fields is rarely a raw equality: SpyCloud\n * keeps `phone` as bare digits where a Torchlight client sends\n * `+1 (559) 779-1433`; one world keys people by `email`, another by\n * `email_username`. A transform normalises the plaintext on BOTH sides of a\n * mapping before `storedForms` salts it under each world's slug, so a\n * cross-world query is answerable from the plaintext alone, with no stored\n * join.\n *\n * The set is closed and named — no expressions, no user code — because any\n * client must reproduce a transform from the manifest by itself. This is the\n * TypeScript twin of the Python runtime's `environment/schema/transforms.py`;\n * the golden vectors in `__tests__/transforms.test.ts` and the Python\n * `tests/environment/test_schema_transforms.py` pin the two to each other,\n * byte for byte.\n *\n * Whitespace, for `trim` and `collapse_ws`, is the ASCII set `\" \\t\\n\\r\\f\\v\"`\n * by definition (Python's `str.split()` and JavaScript's `\\s` disagree at the\n * edges of Unicode; `nfkc` first folds a no-break space into a plain one).\n */\n\nimport { createHash } from \"node:crypto\";\n\nimport { pyFloatRepr } from \"../cli/platform/worldData/json\";\n\nexport type Transform = (value: string) => string;\n\nexport const WHITESPACE = \" \\t\\n\\r\\f\\v\";\nconst WHITESPACE_EDGES = new RegExp(`^[${WHITESPACE}]+|[${WHITESPACE}]+$`, \"g\");\nconst WHITESPACE_RUN = new RegExp(`[${WHITESPACE}]+`, \"g\");\nconst NOT_DIGIT = /[^0-9]/g;\n\nexport const STRIP_PREFIX = \"strip_prefix\";\n\nconst trim = (value: string): string => value.replace(WHITESPACE_EDGES, \"\");\n\nconst emailLocalPart = (value: string): string => {\n const at = value.lastIndexOf(\"@\");\n return at === -1 ? value : value.slice(0, at);\n};\n\nconst emailDomain = (value: string): string => {\n const at = value.lastIndexOf(\"@\");\n return at === -1 ? \"\" : value.slice(at + 1).toLowerCase();\n};\n\nconst stripPrefix =\n (prefix: string): Transform =>\n (value) =>\n value.startsWith(prefix) ? value.slice(prefix.length) : value;\n\nconst hex = (algorithm: \"sha1\" | \"sha256\", value: string): string =>\n createHash(algorithm).update(value, \"utf8\").digest(\"hex\");\n\nconst SIMPLE: Record<string, Transform> = {\n lower: (value) => value.toLowerCase(),\n upper: (value) => value.toUpperCase(),\n trim,\n collapse_ws: (value) => trim(value).replace(WHITESPACE_RUN, \" \"),\n nfkc: (value) => value.normalize(\"NFKC\"),\n digits: (value) => value.replace(NOT_DIGIT, \"\"),\n email_local_part: emailLocalPart,\n email_domain: emailDomain,\n // Vendor-style digests: lowercase hex of the utf-8 bytes, unsalted. This is\n // how SpyCloud accepts a hashed selector (`_digests` in its api_handlers).\n sha1: (value) => hex(\"sha1\", value),\n sha256: (value) => hex(\"sha256\", value),\n};\n\n/** The closed set, as a manifest spells it. `strip_prefix` takes its parameter\n * after a colon; the parameter may hold any character but `,`. */\nexport const TRANSFORMS: readonly string[] = [...Object.keys(SIMPLE), `${STRIP_PREFIX}:<prefix>`];\n\n/** The function a transform name denotes; throws when the name is not in the set. */\nexport function parseTransform(name: string): Transform {\n const simple = Object.prototype.hasOwnProperty.call(SIMPLE, name) ? SIMPLE[name] : undefined;\n if (simple) return simple;\n const colon = name.indexOf(\":\");\n if (colon !== -1) {\n const head = name.slice(0, colon);\n const prefix = name.slice(colon + 1);\n if (head === STRIP_PREFIX && prefix && !prefix.includes(\",\")) return stripPrefix(prefix);\n }\n throw new Error(`Unknown transform '${name}'; choose one of ${TRANSFORMS.join(\", \")}`);\n}\n\n/** `str(value)` as the Python runtime spells a number: an integral number is an\n * int, any other its float repr. */\nconst text = (value: string | number): string => {\n if (typeof value === \"string\") return value;\n return Number.isInteger(value) ? String(value) : pyFloatRepr(value);\n};\n\n/**\n * Compose `chain` left to right over `value`.\n *\n * A number is written as Python's `str()` first, the way `_digest` salts one,\n * so a number keyed on one side and a string on the other transform alike. The\n * whole chain is parsed before any step runs: a bad name at the end refuses\n * the mapping outright rather than after a partial result. An empty chain is\n * the identity.\n */\nexport function applyTransforms(value: string | number, chain: readonly string[]): string {\n const steps = chain.map(parseTransform);\n let out = text(value);\n for (const step of steps) out = step(out);\n return out;\n}\n","/**\n * Stored forms: what a world's store holds for a field given its plaintext.\n *\n * A schema world's `[redact]` table (connector.toml) rewrites named fields\n * before they reach disk — `hash` to a slug-salted sha256, `preserve` to a\n * shape-preserving digest, `round` to fewer decimals, `drop` to nothing. A\n * lookup by plaintext therefore has to compute the same form the store did.\n * This module is the TypeScript twin of the Python runtime's `_digest`,\n * `_shaped`, `redaction_of` and `stored_forms` (environment/schema/connector.py):\n * the rule is `\"sha256:\" + sha256(\"<slug>:<plaintext>\")`, no lowercasing, no\n * trimming, no other salt, and the golden vectors in redaction.test.ts pin the\n * two implementations to each other.\n */\n\nimport { createHash } from \"node:crypto\";\n\nimport { JsonNumber, pyFloatRepr, pyRound } from \"../cli/platform/worldData/json\";\nimport { applyTransforms } from \"./transforms\";\n\n/** The `[redact]` table as `describe` reports it (`connection.redact`, and\n * `redact` on `GET /api/public/worlds/{slug}`). */\nexport type RedactPolicy = {\n /** The digest salt: the connector's slug from connector.toml. It can differ\n * from the platform world slug (`spycloud` vs `spycloud-world`); `storedForms`\n * prefers it and falls back to the world slug only when it is absent. */\n slug?: string;\n hash: string[];\n drop: string[];\n preserve: string[];\n round: Record<string, number>;\n};\n\n/** The policy one field is stored under; null when it is stored in the clear. */\nexport type Redaction = \"hash\" | \"drop\" | \"preserve\" | `round:${number}`;\n\n/**\n * A value as the Python runtime would see it. JavaScript has one number\n * type, so an integral number takes Python's `int` path and any other number\n * its `float` path (`100` is `100`, never `100.0`); integers stay exact within\n * the safe range only.\n */\nexport type Plaintext = string | number;\n\nconst isInt = (value: Plaintext): value is number => typeof value === \"number\" && Number.isInteger(value);\n\n/** `str(value)` for an int or str, `repr(value)` for a float — the text the\n * Python runtime salts and shapes. */\nexport function pyText(value: Plaintext): string {\n if (typeof value === \"string\") return value;\n if (Number.isInteger(value)) return String(value);\n if (Number.isNaN(value)) return \"nan\";\n if (!Number.isFinite(value)) return value > 0 ? \"inf\" : \"-inf\";\n return pyFloatRepr(value);\n}\n\n/** The `hash` form: `\"sha256:\" + sha256(\"<slug>:<plaintext>\")` as hex. */\nexport function hashForm(slug: string, plaintext: Plaintext): string {\n return \"sha256:\" + createHash(\"sha256\").update(`${slug}:${pyText(plaintext)}`, \"utf8\").digest(\"hex\");\n}\n\n/**\n * The `preserve` form, the Python `_shaped`: the same length, every ASCII\n * digit still a digit, every ASCII letter still a letter of the same case,\n * everything else (separators, punctuation, non-ASCII) left in place. The\n * bytes come from sha256 of the seed `\"<slug>:<text>\"`, re-keyed as\n * sha256(digest + seed) once the 32 bytes are spent. A number keeps its type:\n * an int keeps its digit count (a leading zero is replaced), a float is re-read.\n */\nexport function preserveForm(slug: string, plaintext: Plaintext): Plaintext {\n const kind = typeof plaintext === \"string\" ? \"str\" : isInt(plaintext) ? \"int\" : \"float\";\n const shaped = shapeText(slug, pyText(plaintext), kind);\n return kind === \"str\" ? shaped : Number(shaped);\n}\n\n/** The shaping itself, on text: `kind` says which of Python's rules apply\n * (letters are re-lettered for a str only; an int keeps its digit count). */\nexport function shapeText(slug: string, text: string, kind: \"str\" | \"int\" | \"float\"): string {\n const seed = Buffer.from(`${slug}:${text}`, \"utf8\");\n let digest = createHash(\"sha256\").update(seed).digest();\n let cursor = 0;\n const out: string[] = [];\n for (const char of text) {\n if (cursor === digest.length) {\n digest = createHash(\"sha256\").update(Buffer.concat([digest, seed])).digest();\n cursor = 0;\n }\n const byte = digest[cursor]!;\n cursor += 1;\n if (char >= \"0\" && char <= \"9\") out.push(String(byte % 10));\n else if (kind === \"str\" && char >= \"a\" && char <= \"z\") out.push(String.fromCharCode(97 + (byte % 26)));\n else if (kind === \"str\" && char >= \"A\" && char <= \"Z\") out.push(String.fromCharCode(65 + (byte % 26)));\n else out.push(char);\n }\n // An int keeps its digit count; int() would drop a leading zero.\n if (kind === \"int\" && out.length > 1 && out[0] === \"0\") out[0] = String(1 + (digest[0]! % 9));\n return out.join(\"\");\n}\n\n/** The `round` form: Python's `round(value, decimals)` — an int unchanged, a\n * float correctly rounded with ties to even; a string is not a number and\n * passes through as the runtime leaves it. */\nexport function roundForm(plaintext: Plaintext, decimals: number): Plaintext {\n if (typeof plaintext === \"string\" || isInt(plaintext) || !Number.isFinite(plaintext)) return plaintext;\n return pyRound(new JsonNumber(pyFloatRepr(plaintext)), decimals).value;\n}\n\n/**\n * The policy a field of this name falls under, ranked as the runtime applies\n * them (drop, hash, preserve, round). Read without a path: a bare name in the\n * table counts, and so does a dotted path whose last segment is the field.\n */\nexport function redactionOf(redact: RedactPolicy | null | undefined, field: string): Redaction | null {\n if (!redact) return null;\n const named = (names: string[] | undefined) =>\n (names ?? []).some((name) => name === field || name.slice(name.lastIndexOf(\".\") + 1) === field);\n if (named(redact.drop)) return \"drop\";\n if (named(redact.hash)) return \"hash\";\n if (named(redact.preserve)) return \"preserve\";\n const decimals = redact.round?.[field];\n if (typeof decimals === \"number\") return `round:${decimals}`;\n return null;\n}\n\n/**\n * Every value the store may hold for `field` given this plaintext:\n *\n * clear field -> [plaintext]\n * hash -> [\"sha256:<hex>\"]\n * preserve -> [the shape-preserving digest]\n * round -> [round(plaintext, decimals)] for a number, [plaintext] otherwise\n * drop -> [] (the field is not on disk: a documented miss, not an error)\n *\n * `world` is what `describeWorld` / the bridge's `describe` return: the slug\n * is the salt, `redact` the table.\n *\n * `transform` — a cross-world mapping's chain (`./transforms`) — runs over the\n * plaintext FIRST, so `hash` and `preserve` salt the normalised text; omitted\n * (or empty) is today's behaviour, byte for byte.\n */\nexport function storedForms(\n world: { slug: string; redact?: RedactPolicy | null },\n field: string,\n plaintext: Plaintext,\n transform?: readonly string[],\n): Plaintext[] {\n if (transform?.length) plaintext = applyTransforms(plaintext, transform);\n const policy = redactionOf(world.redact, field);\n const salt = world.redact?.slug ?? world.slug;\n if (policy === \"drop\") return [];\n if (policy === \"hash\") return [hashForm(salt, plaintext)];\n if (policy === \"preserve\") return [preserveForm(salt, plaintext)];\n if (policy !== null) return [roundForm(plaintext, world.redact!.round[field]!)];\n return [plaintext];\n}\n","/**\n * `queryRows(slug[@ref], entity, {where, resolve, limit, offset})` — the rows\n * of one entity that match a predicate, from\n * `GET /api/public/worlds/{slug}/data?ref=&entity=&where=&limit=&offset=&resolve=`.\n * `where` is field → value, or field → list of values (any of); values match\n * the STORED form as given. With `resolve: true` the values are plaintext and\n * the runtime maps each to its stored form under the world's `[redact]`\n * policy first (a hashed `email` becomes its slug-salted digest; a dropped\n * field resolves to nothing and matches no row — the answer's `resolved`\n * says so). The CLI twin is `gateway worlds data query <slug> <entity>`.\n *\n * `across: true` runs the same plaintext in every world this one links to\n * whose `[dependencies.<alias>.entities]` mapping covers a `where` field;\n * each linked world recomputes its own stored form (after the mapping's\n * transform) at query time — no join on disk, no shared salt. The answer\n * is then {@link WorldQueryAcrossResult}: one group per world, the root\n * first, and with `compare: true` a parity report saying, per field and\n * per world, `matched`, `no match` or `unmapped`.\n */\n\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\nimport type { Plaintext } from \"./redaction\";\n\nexport type WorldQueryWhere = Record<string, Plaintext | Plaintext[]>;\n\nexport type WorldQueryOptions = {\n where?: WorldQueryWhere;\n /** The `where` values are plaintext: resolve each to its stored form before matching. */\n resolve?: boolean;\n limit?: number;\n offset?: number;\n /** Query the linked worlds too; the answer becomes groups. */\n across?: boolean;\n /** With `across`: add the parity report. */\n compare?: boolean;\n};\n\n/** The options that make `queryRows` answer {@link WorldQueryAcrossResult}. */\nexport type WorldQueryAcrossOptions = WorldQueryOptions & { across: true };\n\nexport type WorldQueryResult = {\n slug: string;\n versionId: string;\n kind: string | null;\n entity: string;\n rows: Record<string, unknown>[];\n /** Rows in this page. */\n count: number;\n /** Rows matching in all; null when the store does not count them. */\n total: number | null;\n limit: number;\n offset: number;\n /** With `resolve`: the stored forms each `where` field was matched against\n * (`[]` for a dropped field, which is why such a query matches nothing). */\n resolved?: Record<string, Plaintext[]>;\n entityCounts: Record<string, number>;\n snapshot: WorldQuerySnapshot | null;\n};\n\nexport type WorldQuerySnapshot = {\n snapshotId: string;\n contractHash: string;\n batchDigest: string;\n bytes: number;\n};\n\n/** One world's page inside an across answer: the root (`alias: null`, no\n * `mapping`) or a linked world with the mappings that carried the root's\n * `where` fields into its own entity. */\nexport type WorldQueryGroup = {\n world: { slug: string; alias: string | null; versionId: string };\n entity: string;\n rows: Record<string, unknown>[];\n count: number;\n total: number | null;\n limit: number;\n offset: number;\n resolved?: Record<string, Plaintext[]>;\n mapping?: { field: string; depField: string; transform: string[] }[];\n};\n\nexport type WorldQueryCompareStatus = \"matched\" | \"no match\" | \"unmapped\";\n\n/** Per `where` field, per world: whether the field reached the world and\n * whether any row matched there; `present`/`absent` list the worlds by slug. */\nexport type WorldQueryCompare = {\n present: string[];\n absent: string[];\n perField: {\n field: string;\n worlds: {\n world: string;\n alias: string | null;\n status: WorldQueryCompareStatus;\n /** `<depEntity>.<depField>` and the transform applied (mapped worlds only). */\n depField?: string;\n transform?: string[];\n }[];\n }[];\n};\n\nexport type WorldQueryAcrossResult = {\n slug: string;\n versionId: string;\n kind: string | null;\n entity: string;\n /** The root world first, then one per linked world that was queried. */\n groups: WorldQueryGroup[];\n compare?: WorldQueryCompare;\n entityCounts: Record<string, number>;\n snapshot: WorldQuerySnapshot | null;\n};\n\n/** The query string the route reads; `where` travels as URL-encoded JSON and\n * `ref` (the `@ref` of `slug@ref`) picks the version. */\nexport function queryRowsSearch(entity: string, opts: WorldQueryOptions = {}, ref?: string): string {\n const search = new URLSearchParams();\n if (ref) search.set(\"ref\", ref);\n search.set(\"entity\", entity);\n if (opts.where && Object.keys(opts.where).length) search.set(\"where\", JSON.stringify(opts.where));\n if (opts.limit !== undefined) search.set(\"limit\", String(opts.limit));\n if (opts.offset !== undefined) search.set(\"offset\", String(opts.offset));\n if (opts.resolve) search.set(\"resolve\", \"true\");\n if (opts.across) search.set(\"across\", \"true\");\n if (opts.compare) search.set(\"compare\", \"true\");\n return `?${search.toString()}`;\n}\n\n/** One version of the world, queried: the main tip for a bare slug, or the\n * version `slug@ref` names (branch, tag, semver pin or hash prefix — the\n * `bench pull` grammar; a ref nothing answers to is the platform's 404, never\n * the head). With `across: true` the answer is the groups shape. */\nexport async function queryRows(\n slug: string,\n entity: string,\n opts: WorldQueryAcrossOptions,\n options?: WorldsClientOptions,\n): Promise<WorldQueryAcrossResult>;\nexport async function queryRows(\n slug: string,\n entity: string,\n opts?: WorldQueryOptions,\n options?: WorldsClientOptions,\n): Promise<WorldQueryResult>;\nexport async function queryRows(\n slugRef: string,\n entity: string,\n opts: WorldQueryOptions = {},\n options: WorldsClientOptions = {},\n): Promise<WorldQueryResult | WorldQueryAcrossResult> {\n const [slug, ref] = slugRef.split(\"@\", 2) as [string, string | undefined];\n if (!slug || ref === \"\") throw new Error(`queryRows needs a slug, optionally slug@ref (got ${slugRef})`);\n if (!entity) throw new Error(\"queryRows needs an entity\");\n if (opts.compare && !opts.across) throw new Error(\"queryRows: compare needs across\");\n return apiRequest<WorldQueryResult | WorldQueryAcrossResult>(\n options,\n \"GET\",\n `/api/public/worlds/${encodeURIComponent(slug)}/data${queryRowsSearch(entity, opts, ref)}`,\n );\n}\n","/**\n * `migrateWorld(slug)` — convert a stored world into a schema world, from\n * `POST /api/public/worlds/{slug}/migrate`; `migrateProjectWorlds()` plans\n * (or migrates) every connector world in the project from\n * `POST /api/public/worlds/migrate`. Dry run by default: the report says\n * what the version is, what the conversion does, or why it cannot; `apply`\n * commits the migrated tree as the next version (\"Migrated to a schema\n * world\"). Targets are the platform's connector worlds; a hand-built world\n * needs `force`. The CLI twin is `gateway worlds migrate`.\n */\n\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\n\nexport type WorldMigrationRefusal = {\n code: string;\n message: string;\n /** Paths the conversion needed and did not find. */\n missing: string[];\n};\n\nexport type WorldMigrationReport = {\n slug: string;\n containerId: string;\n versionId: string;\n /** True when the container was created from a connector template. */\n connectorWorld: boolean;\n /** schema | api-bundle | legacy-tools | harbor | verifiers */\n shape: string;\n target: \"schema\";\n /** True when the world already is a schema world. */\n unchanged: boolean;\n /** The dry-run report, one sentence each. */\n actions: string[];\n /** Files the migrated tree holds; 0 on a refusal. */\n files: number;\n refusal: WorldMigrationRefusal | null;\n /** True when this call committed the migrated tree. */\n applied: boolean;\n version: { id: string; contentHash: string } | null;\n};\n\nexport type MigrateWorldOptions = {\n /** Commit the migrated tree as the next version. Default false: dry run. */\n apply?: boolean;\n /** Migrate a world that was not created from a connector template. */\n force?: boolean;\n};\n\nexport async function migrateWorld(\n slug: string,\n input: MigrateWorldOptions = {},\n options: WorldsClientOptions = {},\n): Promise<WorldMigrationReport> {\n if (slug.includes(\"@\"))\n throw new Error(\n `migrateWorld converts a world's head version: pass the slug without @ref (got ${slug})`,\n );\n return apiRequest<WorldMigrationReport>(\n options,\n \"POST\",\n `/api/public/worlds/${encodeURIComponent(slug)}/migrate`,\n {\n ...(input.apply === undefined ? {} : { apply: input.apply }),\n ...(input.force === undefined ? {} : { force: input.force }),\n },\n );\n}\n\n/** Every connector world in the project, one report each. */\nexport async function migrateProjectWorlds(\n input: { apply?: boolean } = {},\n options: WorldsClientOptions = {},\n): Promise<{ worlds: WorldMigrationReport[]; applied: boolean }> {\n return apiRequest<{ worlds: WorldMigrationReport[]; applied: boolean }>(\n options,\n \"POST\",\n \"/api/public/worlds/migrate\",\n input.apply === undefined ? {} : { apply: input.apply },\n );\n}\n","/**\n * 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 /** `--name \"\"` is meaningful (clears a field); otherwise an empty value is a usage error. */\n allowEmpty?: boolean;\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 /** A read verb whose output is JSON accepts `--json` (a no-op) so every read verb shares the flag. */\n output?: \"json\";\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 /** Whether stdin is a terminal — a person is typing, so a read prompts on stderr. */\n stdinIsTTY?: () => boolean;\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 /** Set on the root only: `gateway --version` prints `<name> <version>`. */\n version?: 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, withJsonFlag(spec));\n return this;\n }\n}\n\nconst JSON_FLAG: FlagSpec = {\n name: \"json\",\n help: \"Output is JSON (the default for this command; accepted so every read verb takes --json).\",\n boolean: true,\n};\n\n/** The `--json` flag of a read verb whose default output is text. */\nexport const JSON_OUTPUT_FLAG: FlagSpec = {\n name: \"json\",\n help: \"Print JSON instead of the text lines.\",\n boolean: true,\n};\n\n/** One output door for text-by-default read verbs: `--json` prints `value`, otherwise `lines`. */\nexport function emit(\n ctx: CommandContext,\n args: Parsed,\n value: unknown,\n lines: () => string[],\n): void {\n if (args.flags.json === true) {\n ctx.stdout(JSON.stringify(value, null, 2));\n return;\n }\n for (const line of lines()) ctx.stdout(line);\n}\n\nfunction withJsonFlag(spec: CommandSpec): CommandSpec {\n if (spec.output !== \"json\") return spec;\n if ((spec.flags ?? []).some((f) => f.name === \"json\")) return spec;\n return { ...spec, flags: [...(spec.flags ?? []), JSON_FLAG] };\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 if (given.has(f.name) && !f.repeat)\n throw new CliError(`--${f.name} given twice`);\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 || looksLikeFlag(next, byName))\n throw new CliError(`--${f.name} needs a value`);\n value = next;\n i++;\n }\n if (value.trim() === \"\" && !f.allowEmpty)\n throw new CliError(`--${f.name} must not be empty`);\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 const blank = positionals.findIndex((p) => p.trim() === \"\");\n if (blank >= 0) {\n const name = specs[Math.min(blank, specs.length - 1)]?.name ?? \"argument\";\n throw new CliError(`${spec.name}: <${name}> must not be empty`);\n }\n return { positionals, flags, given };\n}\n\n/** `--publish -m x` must not read `-m` as --publish's value: a token that is\n * a long flag, or a short flag this command knows, is a flag. `-` and `-1`\n * stay values. */\nfunction looksLikeFlag(token: string, known: Map<string, FlagSpec>): boolean {\n if (token.startsWith(\"--\")) return token.length > 2;\n if (!token.startsWith(\"-\") || token.length < 2) return false;\n const name = token.slice(1).split(\"=\")[0]!;\n return known.has(name);\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 if (node === root && root.version !== undefined && (token === \"--version\" || token === \"-V\")) {\n ctx.stdout(`${root.name} ${root.version}`);\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\";\nimport { parseErrorBody } from \"../worlds\";\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;\n * the body renders through `parseErrorBody` (stable public `code`, never a server class name). */\nexport class ApiError extends CliError {\n readonly code: string | null;\n\n constructor(\n readonly status: number,\n readonly method: string,\n readonly route: string,\n readonly text: string,\n ) {\n const body = parseErrorBody(text);\n super(`${method} ${route} -> ${status}: ${body.detail}`, 1);\n this.code = body.code;\n }\n}\n\n/** The request never got an answer: name the host, the route and the\n * socket-level cause (undici's `fetch failed` hides it under `cause`), and\n * say that a retry is the next step. Nothing else is knowable here. */\nexport class UnreachableError extends CliError {\n constructor(\n readonly host: string,\n readonly method: string,\n readonly route: string,\n readonly detail: string,\n ) {\n super(`${method} ${route}: no answer from ${host} (${detail}). Check the host and the network, then retry.`, 1);\n }\n}\n\nfunction transportDetail(error: unknown, timeoutMs: number): string {\n if (error instanceof Error && error.name === \"AbortError\") return `timed out after ${Math.round(timeoutMs / 1000)}s`;\n const cause = error instanceof Error && error.cause instanceof Error ? error.cause : undefined;\n const code = cause && \"code\" in cause && typeof cause.code === \"string\" ? `${cause.code}: ` : \"\";\n const message = cause?.message ?? (error instanceof Error ? error.message : String(error));\n return `${code}${message}`;\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 timeoutMs = init.timeoutMs ?? 120_000;\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n let res: Response;\n try {\n 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 } catch (error) {\n clearTimeout(timer);\n throw new UnreachableError(creds.host, method, route, transportDetail(error, timeoutMs));\n }\n try {\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/** The bridge's file-count cap (`platform.MAX_FILES`): a tree the runtime\n * returns with more entries than this is refused before anything is written. */\nexport const MAX_WORLD_FILES = 2000;\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 if (files.length > MAX_WORLD_FILES)\n throw new CliError(`The runtime returned ${files.length} files, over the ${MAX_WORLD_FILES} limit`, 1);\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\nconst YAML_NAME = /\\.ya?ml$/i;\n\n/** The Python parser's rule (`conform.parse_openapi`): JSON when the name says\n * so or the text opens with `{`/`[`, YAML otherwise — so an extensionless YAML\n * document is routed to a runtime that can parse it. */\nfunction isYamlSource(name: string, base64: string): boolean {\n if (name.endsWith(\".json\")) return false;\n if (YAML_NAME.test(name)) return true;\n const head = Buffer.from(base64.slice(0, 256), \"base64\").toString(\"utf8\").trimStart();\n return ![\"{\", \"[\"].includes(head[0] ?? \"\");\n}\n\n/** Whether the request names a YAML OpenAPI document the runtime must parse. */\nfunction yamlDocument(request: RuntimeRequest): boolean {\n if (request.command === \"init-openapi\")\n return isYamlSource(String(request.source ?? \"\"), String(request.document ?? \"\"));\n return (\n request.command === \"conform\" &&\n Array.isArray(request.openapi) &&\n (request.openapi as { path?: string }[]).some((doc) => YAML_NAME.test(doc.path ?? \"\"))\n );\n}\n\n/** Whether `runtime()` will answer this request with the bundled runtime on this\n * machine (a python3, plus PyYAML when the request names a YAML document). */\nexport function runsLocally(request: RuntimeRequest): boolean {\n const local = localRuntime();\n return local !== null && !(yamlDocument(request) && !localPythonHasYaml(local.python));\n}\n\n/** `schema init` writes only into a directory that does not exist yet or is empty. */\nexport function assertEmptyTarget(dir: string): void {\n if (!fs.existsSync(dir)) return;\n if (!fs.statSync(dir).isDirectory()) throw new CliError(`${dir} exists and is not a directory`);\n if (fs.readdirSync(dir).length > 0) throw new CliError(`${dir} must be a new or empty directory`);\n}\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 * A schema world is checked here before it is pushed, the way the Python CLI\n * does: a tree edited after its last compile would otherwise travel to the\n * platform only to be refused at finalize. Runs only with the bundled runtime\n * on this machine (no round trip); without one the platform's own check\n * refuses the version instead.\n */\nexport async function checkSchemaTreeBeforePush(dir: string): Promise<void> {\n const abs = path.resolve(dir);\n if (!fs.existsSync(path.join(abs, \"gateway-env.toml\")) || !localRuntime()) return;\n try {\n await runtime(null, { command: \"validate\", world: abs });\n } catch (error) {\n if (error instanceof BridgeRejected)\n throw new CliError(`Schema world check failed before push: ${error.message}`, 1);\n throw error;\n }\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 // OpenAPI document (conform, init-openapi) needs PyYAML, which the vendored\n // runtime does not carry.\n const local = localRuntime();\n if (local && runsLocally(request)) {\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/** 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\nexport type LocalFilesOptions = {\n entity?: string;\n delimiter?: string;\n mode?: ImportMode;\n merge?: \"upsert\" | \"fill\";\n redact?: \"off\" | \"apply\" | \"refuse\";\n dryRun?: boolean;\n};\n\nexport type LocalFilesResult = LocalImportResult & {\n /** How many rows the files held. */\n rows: number;\n proof?: string;\n deferred?: string[];\n};\n\n/**\n * Rows FILES into a local directory, streamed: the runtime on this machine\n * opens the files and the tree in place (`import-files`), so a 100 MB CSV\n * costs one row of memory at a time and nothing travels through the bridge\n * but paths. Only the bundled runtime can do this — the platform's bridge\n * reads no file of this machine — so without one the caller falls back to\n * `importLocalWorldData` within its inline cap. The snapshots are rebuilt\n * in place by the runtime; nothing to drop.\n */\nexport async function importLocalWorldFiles(\n dir: string,\n sources: string[],\n opts: LocalFilesOptions,\n): Promise<LocalFilesResult> {\n const local = localRuntime();\n if (!local)\n throw new CliError(\n `Rows files stream into a directory through the bundled runtime on this machine, and none can run: ${localRuntimeReason()}`,\n 1,\n );\n const res = await runtime<{\n kind?: string;\n entity_counts?: Record<string, number>;\n changed?: boolean;\n rows?: number;\n proof?: string;\n deferred?: string[];\n }>(null, {\n command: \"import-files\",\n world: path.resolve(dir),\n sources: sources.map((source) => path.resolve(source)),\n mode: opts.mode ?? \"append\",\n ...(opts.entity ? { entity: opts.entity } : {}),\n ...(opts.delimiter ? { delimiter: opts.delimiter } : {}),\n ...(opts.merge && opts.merge !== \"upsert\" ? { merge: opts.merge } : {}),\n ...(opts.redact && opts.redact !== \"off\" ? { redact: opts.redact } : {}),\n ...(opts.dryRun ? { dry_run: true } : {}),\n });\n return {\n kind: res.kind ?? \"unknown\",\n entity_counts: res.entity_counts ?? {},\n changed: Boolean(res.changed),\n rows: res.rows ?? 0,\n ...(res.proof ? { proof: res.proof } : {}),\n ...(res.deferred ? { deferred: res.deferred } : {}),\n };\n}\n\nexport type LocalChunksOptions = {\n entity?: string;\n delimiter?: string;\n chunkBytes?: number;\n chunkRows?: number;\n};\n\nexport type LocalChunk = {\n ordinal: number;\n path: string;\n rows: number;\n bytes: number;\n digest: string;\n entity: string | null;\n};\n\nexport type LocalChunksResult = { rows: number; chunks: LocalChunk[] };\n\n/**\n * Rows FILES into the gzipped JSONL chunks a platform data batch takes,\n * written under `out` by the runtime on this machine (`chunk-files`): the\n * files are typed by the directory's contract exactly as `importLocalWorldFiles`\n * types them, but nothing lands in the tree — the chunks are bound for a\n * platform snapshot. This is the sandbox-side half of `worlds sandbox import`:\n * the platform runs `gateway worlds data chunks` inside the sandbox, whose\n * staged `gateway` is this CLI, then reads the chunk files out itself.\n */\nexport async function chunkLocalWorldFiles(\n dir: string,\n sources: string[],\n out: string,\n opts: LocalChunksOptions,\n): Promise<LocalChunksResult> {\n const local = localRuntime();\n if (!local)\n throw new CliError(\n `Rows files are cut into chunks by the bundled runtime on this machine, and none can run: ${localRuntimeReason()}`,\n 1,\n );\n const res = await runtime<{ rows?: number; chunks?: LocalChunk[] }>(null, {\n command: \"chunk-files\",\n world: path.resolve(dir),\n sources: sources.map((source) => path.resolve(source)),\n out: path.resolve(out),\n ...(opts.entity ? { entity: opts.entity } : {}),\n ...(opts.delimiter ? { delimiter: opts.delimiter } : {}),\n ...(opts.chunkBytes ? { chunk_bytes: opts.chunkBytes } : {}),\n ...(opts.chunkRows ? { chunk_rows: opts.chunkRows } : {}),\n });\n return { rows: res.rows ?? 0, chunks: res.chunks ?? [] };\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 dry_run: true,\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 = {\n batchId: string;\n state: string;\n limits?: { chunkBytes?: number; batchBytes?: number; inlineBytes?: number };\n};\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([\n \"applied\",\n \"refused\",\n \"published\",\n \"failed\",\n]);\n\n/** Whether the batch is done moving. The worker records `applied` and then, for\n * a `publish: now` batch, cuts the version and records `published`; a poll that\n * lands between the two must keep going or the caller reads a version that is\n * not there yet. Dry runs and `publish: later` rest at `applied`. */\nexport function isSettled(status: BatchStatus): boolean {\n if (!TERMINAL_STATES.has(status.state)) return false;\n if (status.state !== \"applied\") return true;\n return (\n status.dryRun === true || status.publish !== \"now\" || !status.snapshotId\n );\n}\n\nexport const sleepMs = (ms: number): Promise<void> =>\n new Promise((resolve) => setTimeout(resolve, ms));\n\n/** The bare slug of a `slug` or `slug@ref` world argument — what `WorldDataApi` addresses. */\nexport const slugOf = (world: string): string => world.split(\"@\", 1)[0]!;\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(\n batchId: string,\n chunk: {\n ordinal: number;\n digest: string;\n bytes: number;\n rows: number;\n entity: string | null;\n },\n ): Promise<RegisteredChunk> {\n return api<RegisteredChunk>(\n this.creds,\n \"POST\",\n `${this.base}/batches/${batchId}/chunks`,\n {\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\n /**\n * Stage a project-drive rows file as one chunk, on the platform: the server\n * streams it out of drive storage into chunk storage and answers with the\n * digest and gzipped size it derived. No bytes pass through this process.\n */\n async stageDrive(\n batchId: string,\n chunk: { ordinal: number; path: string; entity: string | null },\n ): Promise<ManifestChunk> {\n const staged = await api<{\n chunkId: string;\n uploaded: boolean;\n digest?: string;\n bytes?: number;\n rows?: number;\n }>(this.creds, \"POST\", `${this.base}/batches/${batchId}/chunks`, {\n ordinal: chunk.ordinal,\n drive: chunk.path,\n ...(chunk.entity ? { entity: chunk.entity } : {}),\n });\n if (\n !staged.uploaded ||\n !staged.digest ||\n staged.bytes === undefined ||\n staged.rows === undefined\n )\n throw new CliError(\n `the server staged drive:${chunk.path} as chunk ${chunk.ordinal} without its digest, size and rows`,\n 1,\n );\n return {\n ordinal: chunk.ordinal,\n digest: staged.digest,\n bytes: staged.bytes,\n rows: staged.rows,\n entity: chunk.entity,\n chunkId: staged.chunkId,\n uploaded: true,\n };\n }\n\n markUploaded(\n batchId: string,\n chunkId: string,\n ): Promise<{ chunkId: string; uploaded: boolean; bytes: number }> {\n return api(\n this.creds,\n \"POST\",\n `${this.base}/batches/${batchId}/chunks/${chunkId}/uploaded`,\n );\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>(\n this.creds,\n \"GET\",\n `${this.base}/batches/${batchId}`,\n );\n }\n\n list(\n limit?: number,\n cursor?: string,\n ): 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(\n message?: string,\n ): Promise<{ versionId: string; snapshotId: string; batchIds: string[] }> {\n return api(\n this.creds,\n \"POST\",\n `${this.base}/publish`,\n message ? { message } : {},\n );\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(\n uploadUrl: string,\n gz: Buffer,\n signed?: Record<string, string>,\n ): 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, {\n method: \"PUT\",\n body: new Uint8Array(gz),\n headers,\n });\n if (res.ok) return;\n if (res.status < 500 || attempt >= delays.length)\n throw new CliError(\n `chunk upload -> ${res.status}: ${(await res.text()).slice(0, 300)}`,\n 1,\n );\n } catch (error) {\n if (error instanceof CliError || attempt >= delays.length)\n throw error instanceof CliError\n ? error\n : new CliError(\n `chunk upload failed: ${(error as Error).message}`,\n 1,\n );\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)\n throw new CliError(\n `the server registered chunk ${chunk.ordinal} without an upload URL`,\n 1,\n );\n await this.put(registered.uploadUrl, chunk.gz, registered.uploadHeaders);\n await this.markUploaded(batchId, registered.chunkId);\n }\n return {\n ordinal: chunk.ordinal,\n digest: chunk.digest,\n bytes: chunk.bytes,\n rows: chunk.rows,\n entity: chunk.entity,\n chunkId: registered.chunkId,\n uploaded: true,\n };\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>(\n items: AsyncIterable<T>,\n limit: number,\n fn: (item: T) => Promise<void>,\n): 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(\n client: WorldDataApi,\n batchId: string,\n opts: WaitOptions = {},\n): 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 (isSettled(status)) 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/** A batch as the CLI prints it: `reportUrl` (a signed, credential-bearing,\n * expiring URL) never reaches stdout; `reportAvailable` says the platform\n * holds the full refusal report, which `--report <file>` fetches. */\nexport type PrintableBatch = Omit<BatchStatus, \"reportUrl\"> & {\n reportAvailable: boolean;\n};\n\nexport function printableStatus(status: BatchStatus): PrintableBatch {\n const { reportUrl, ...rest } = status;\n return { ...rest, reportAvailable: Boolean(reportUrl) };\n}\n\n/** One stderr line pointing at the full report when the platform holds one. */\nexport function reportHint(status: BatchStatus): string | null {\n if (!status.reportUrl) return null;\n const count = status.refusalCount ?? 0;\n return `${count} refusal${count === 1 ? \"\" : \"s\"}; the first ${Math.min(count, 200)} are inline — rerun with --report <file> for the full JSONL report.`;\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(\n status: BatchStatus,\n file: string,\n): 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\n text = (status.refusals ?? [])\n .map((r) => JSON.stringify(r) + \"\\n\")\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\n/** Cut the row stream into chunks numbered from `ordinalStart` (the chunks a\n * batch already holds ahead of these, e.g. drive files the platform staged). */\nexport async function* buildChunks(\n rows: AsyncIterable<TaggedRow>,\n plan: ChunkPlan,\n ordinalStart = 0,\n): AsyncGenerator<BuiltChunk> {\n let lines: Buffer[] = [];\n let rawBytes = 0;\n let ordinal = ordinalStart;\n let seen = 0;\n const flush = (): BuiltChunk => {\n const raw = Buffer.concat(lines);\n const built = finishChunk(\n ordinal++,\n raw,\n lines.length,\n plan.entity,\n seen - lines.length,\n );\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(\n ordinal: number,\n raw: Buffer,\n rows: number,\n entity: string | null,\n firstRow = 0,\n): 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 (\n deflateRawSync(Buffer.from(CPYTHON_PROBE_TEXT), {\n level: GZIP_LEVEL,\n }).toString(\"hex\") === CPYTHON_PROBE_DEFLATE\n );\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 =\n '{\"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 =\n \"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 =>\n `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(\n raw: Buffer,\n opts: { level?: number; name?: string } = {},\n): Buffer {\n const level = opts.level ?? GZIP_LEVEL;\n const name = opts.name\n ? Buffer.concat([Buffer.from(opts.name, \"latin1\"), Buffer.from([0])])\n : Buffer.alloc(0);\n const header = Buffer.from([\n 0x1f,\n 0x8b,\n 0x08,\n opts.name ? 0x08 : 0x00,\n 0,\n 0,\n 0,\n 0,\n level === 9 ? 0x02 : level === 1 ? 0x04 : 0x00,\n 0xff,\n ]);\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++)\n 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> = {\n \"\": 1,\n b: 1,\n k: 1024,\n kib: 1024,\n kb: 1000,\n m: 1024 ** 2,\n mib: 1024 ** 2,\n mb: 1000 ** 2,\n g: 1024 ** 3,\n gib: 1024 ** 3,\n gb: 1000 ** 3,\n };\n const raw = text.trim().toLowerCase().replace(/ /g, \"\");\n const m = /^(\\d+)([a-z]*)$/.exec(raw);\n if (!m || !(m[2]! in units))\n throw new Error(\n `--chunk-bytes takes a size like 64MiB or 1000000, not '${text}'`,\n );\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. Both routes decode\n * stored JSON text once on the way out (`parseIoAsJson` defaults to true on the\n * v1 route; the session route renders with the same default), so `input` and\n * `output` arrive as the values the tool saw — an object, or a string when the\n * tool really produced text. Nothing here parses them again. */\nexport type ObservationLike = {\n id?: string;\n traceId?: string | null;\n type?: string;\n name?: string | null;\n input?: unknown;\n output?: unknown;\n startTime?: string | Date;\n level?: string;\n statusMessage?: string | null;\n};\n\nexport type ObservationConversion = {\n records: ToolCallRecord[];\n /** TOOL observations whose name is not one of the world's operations, by name. */\n unknownTools: Record<string, number>;\n /** Observations that were not converted, by reason. */\n skipped: Record<string, number>;\n};\n\nconst isoOf = (value: string | Date | undefined): string | undefined =>\n value instanceof Date ? value.toISOString() : typeof value === \"string\" ? value : undefined;\n\n/**\n * TOOL observations → tool-call records: `name` is the tool, `input` the args,\n * `output` the result, `startTime` the time, `trace:<traceId>/<id>` the source.\n * `input`/`output` arrive from the public API already decoded (it parses the\n * stored text once), so they are taken as they are: a string `output` stays a\n * string even when it looks like JSON; an `input` that is not an object leaves\n * `args` empty rather than guessed.\n * Only `type: \"TOOL\"` converts. With `tools` (the world's operation names) an\n * observation for any other tool is counted in `unknownTools`, not converted.\n * An `ERROR`-level observation converts with `error` set, so ingest counts it\n * as a failed call instead of projecting its output.\n */\nexport function toolCallsFromObservations(\n observations: ObservationLike[],\n opts: { tools?: Iterable<string> | null; session?: string; since?: string } = {},\n): ObservationConversion {\n const known = opts.tools ? new Set(opts.tools) : null;\n const sinceMs = opts.since ? Date.parse(opts.since) : NaN;\n const out: ObservationConversion = { records: [], unknownTools: {}, skipped: {} };\n const skip = (reason: string) => {\n out.skipped[reason] = (out.skipped[reason] ?? 0) + 1;\n };\n for (const observation of observations) {\n if (observation.type !== \"TOOL\") {\n skip(`type ${observation.type ?? \"unknown\"}`);\n continue;\n }\n const tool = observation.name;\n if (typeof tool !== \"string\" || !tool) {\n skip(\"no name\");\n continue;\n }\n const at = isoOf(observation.startTime);\n if (!Number.isNaN(sinceMs) && at !== undefined && Date.parse(at) < sinceMs) {\n skip(\"before since\");\n continue;\n }\n if (known && !known.has(tool)) {\n out.unknownTools[tool] = (out.unknownTools[tool] ?? 0) + 1;\n continue;\n }\n const record: ToolCallRecord = { tool, args: isObject(observation.input) ? observation.input : {} };\n if (observation.level === \"ERROR\") record.error = observation.statusMessage || \"ERROR\";\n else record.result = observation.output;\n if (at !== undefined) record.at = at;\n if (opts.session) record.session = opts.session;\n record.source = `trace:${observation.traceId ?? \"?\"}/${observation.id ?? \"?\"}`;\n out.records.push(record);\n }\n return out;\n}\n\n// ---------------------------------------------------------------- the door\n\nexport type IngestRefusal = { index: number | null; tool: string | null; reason: string; pointer?: string };\n\n/** One `[[sources]]` of a mapping in the report. */\nexport type IngestSourceReport = {\n name: string;\n kind: string;\n select: string;\n entity: string;\n records: number;\n items: number;\n rows: Record<string, number>;\n /** Source fields no line of the source reads, with a sample value. */\n unmappedFields: Record<string, string>;\n /** Entity fields the source never sets, per entity. */\n unsetFields: Record<string, string[]>;\n};\n\nexport type IngestToolCallsReport = {\n world: string;\n /** How the rows were produced. */\n via?: \"transform\" | \"map\" | \"operations\" | \"rows\";\n /** `via: \"map\"`: each source's accounting. */\n sources?: IngestSourceReport[];\n /** `via: \"map\"` with `unmatched = \"skip\"`: records no source claimed, by tool name. */\n unmatched?: Record<string, number>;\n /** `via: \"operations\"`: that this was the operation projection, not a mapping. */\n note?: string;\n /** `via: \"transform\"`: what the script wrote to stderr. */\n stderr?: string;\n /** Records given. */\n records: number;\n /** Records that yielded rows. */\n ingested: number;\n /** Records that carried no rows by design, by reason. */\n skipped: Record<string, number>;\n /** What was wrong, per record; with any, nothing was written. */\n refusals: IngestRefusal[];\n /** Rows projected, per entity. */\n rows: Record<string, number>;\n dryRun: boolean;\n redact: RedactMode;\n changed: boolean;\n kind?: string;\n entityCounts?: Record<string, number>;\n /** A slug that was pushed: the batch's final status (`state`, `versionId`, …). */\n batch?: Record<string, unknown>;\n};\n\nexport type IngestToolCallsOptions = WorldsClientOptions & {\n /** Optional, default `\"off\"`: rows land as the tools returned them. */\n redact?: RedactMode;\n /** Project and prove the rows; write and upload nothing. */\n dryRun?: boolean;\n mode?: IngestMode;\n /** Change reason for the version a slug cuts. */\n message?: string;\n};\n\nexport type IngestReport = IngestToolCallsReport;\n\nexport type IngestOptions = IngestToolCallsOptions & {\n /** Your own `transform(records) -> {entity: [rows]}`: a function (run here) or a script path (`.py`, `.ts`, `.mjs`; a subprocess with a time limit and sockets disabled). */\n transform?: string | ((records: unknown[]) => Rows | Promise<Rows>);\n /** An `ingest.toml` mapping: its text, or the parsed table. Exclusive with `transform`. */\n map?: string | IngestMapping;\n /** For a script transform; default 120 000. */\n timeoutMs?: number;\n};\n\ntype Rows = Record<string, Record<string, unknown>[]>;\n\nfunction credentialsOf(options: WorldsClientOptions): { host: string; publicKey: string; secretKey: string } | null {\n const host = (options.host ?? process.env.GATEWAY_HOST ?? \"https://withgateway.ai\").replace(/\\/+$/, \"\");\n const publicKey = options.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;\n const secretKey = options.secretKey ?? process.env.GATEWAY_SECRET_KEY;\n return publicKey && secretKey ? { host, publicKey, secretKey } : null;\n}\n\n/**\n * Records into a world through the route you declare. `world` is a local\n * directory (written in place through the bundled schema runtime) or a\n * platform slug (pulled to a temporary directory, the rows produced and\n * proven there, then pushed through the chunked batch lane as a new version).\n *\n * With `transform` the rows are what your code returns; with `map` (or the\n * world's own `ingest.toml`) what the mapping declares; with neither, each\n * tool-call record's tool resolves to an operation of `connector.toml` and\n * its result goes through that operation's `[ingest]` projection (the report\n * says `via: \"operations\"`). A transform that fails or returns the wrong\n * shape throws. `redact` is optional and defaults to `\"off\"`.\n */\nexport async function ingest(world: string, records: unknown[], options: IngestOptions = {}): Promise<IngestReport> {\n const { ingestLocalToolCalls, importLocalWorldData, checkLocalWorldData } = await import(\"../cli/runtime/data\");\n if (options.transform !== undefined && options.map !== undefined) throw new Error(\"records go through one of transform, map\");\n const redact = options.redact ?? \"off\";\n const mode = options.mode ?? \"append\";\n const dryRun = Boolean(options.dryRun);\n const creds = credentialsOf(options);\n const local = fs.existsSync(world) && fs.statSync(world).isDirectory();\n const map = options.map === undefined ? undefined : options.map;\n\n let rows: Rows | null = null;\n let stderr = \"\";\n if (options.transform !== undefined) {\n const { transformRecords } = await import(\"../cli/platform/worldData/transform\");\n ({ rows, stderr } = await transformRecords(options.transform, records, { timeoutMs: options.timeoutMs }));\n }\n\n if (local) {\n if (rows === null) return reportOf(world, await ingestLocalToolCalls(world, records, { redact, dryRun, mode, map }, creds), redact);\n const landed = dryRun ? await checkLocalWorldData(world, rows, creds, { redact }) : await importLocalWorldData(world, rows, { mode, redact }, creds);\n return transformReport(world, records.length, rows, stderr, { dryRun, redact, changed: !dryRun && landed.changed, kind: landed.kind, entityCounts: landed.entity_counts });\n }\n if (!creds) throw new Error(\"Gateway keys missing: set GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY (or pass publicKey/secretKey).\");\n const { pull } = await import(\"./hub\");\n const slug = world.split(\"@\", 1)[0]!;\n const scratch = fs.mkdtempSync(path.join(os.tmpdir(), \"gateway-ingest-\"));\n try {\n const pulled = await pull(world, path.join(scratch, slug), options);\n // Produced and proven against the pulled contract; the platform's batch\n // lane checks every row again and redacts there, so this pass runs with\n // redaction off and hands the rows on as they were produced.\n let report: IngestReport;\n let projected: Rows;\n if (rows === null) {\n const proven = await ingestLocalToolCalls(pulled.dir, records, { redact: \"off\", dryRun: true, mode, map }, creds);\n report = reportOf(world, proven, redact);\n projected = proven.projected ?? {};\n } else {\n const proven = await checkLocalWorldData(pulled.dir, rows, creds);\n report = transformReport(world, records.length, rows, stderr, { dryRun, redact, changed: false, kind: proven.kind, entityCounts: proven.entity_counts });\n projected = rows;\n }\n report.dryRun = dryRun;\n if (dryRun || report.refusals.length || !Object.keys(projected).length) return report;\n const { pushRows } = await import(\"../cli/platform/worldData/push\");\n const status = await pushRows(creds, slug, projected, { mode, redact, message: options.message });\n report.batch = status;\n report.changed = status.state === \"applied\" || status.state === \"published\";\n if (status.entityCounts) report.entityCounts = status.entityCounts;\n return report;\n } finally {\n fs.rmSync(scratch, { recursive: true, force: true });\n }\n}\n\n/**\n * Tool-call records into a world with neither a transform nor a mapping of\n * your own: the world's `ingest.toml` when it has one, else each record's\n * tool through its operation's `[ingest]` projection (an unknown tool is a\n * refusal naming it and nothing is written). {@link ingest} with the same\n * options.\n */\nexport async function ingestToolCalls(world: string, records: unknown[], options: IngestToolCallsOptions = {}): Promise<IngestToolCallsReport> {\n return ingest(world, records, options);\n}\n\nfunction transformReport(\n world: string,\n records: number,\n rows: Rows,\n stderr: string,\n outcome: { dryRun: boolean; redact: RedactMode; changed: boolean; kind?: string; entityCounts?: Record<string, number> },\n): IngestReport {\n return {\n world,\n via: \"transform\",\n ...(stderr ? { stderr } : {}),\n records,\n ingested: records,\n skipped: {},\n refusals: [],\n rows: Object.fromEntries(Object.entries(rows).map(([entity, listed]) => [entity, listed.length])),\n dryRun: outcome.dryRun,\n redact: outcome.redact,\n changed: outcome.changed,\n ...(outcome.kind ? { kind: outcome.kind } : {}),\n ...(outcome.entityCounts ? { entityCounts: outcome.entityCounts } : {}),\n };\n}\n\nfunction reportOf(\n world: string,\n local: {\n via?: IngestReport[\"via\"];\n sources?: { name: string; kind: string; select: string; entity: string; records: number; items: number; rows: Record<string, number>; unmapped_fields: Record<string, string>; unset_fields: Record<string, string[]> }[];\n unmatched?: Record<string, number>;\n note?: string;\n records: number;\n ingested: number;\n skipped: Record<string, number>;\n refusals: IngestRefusal[];\n rows: Record<string, number>;\n dry_run: boolean;\n changed: boolean;\n kind?: string;\n entity_counts?: Record<string, number>;\n },\n redact: RedactMode,\n): IngestToolCallsReport {\n return {\n world,\n ...(local.via ? { via: local.via } : {}),\n ...(local.sources ? { sources: local.sources.map(({ unmapped_fields, unset_fields, ...rest }) => ({ ...rest, unmappedFields: unmapped_fields, unsetFields: unset_fields })) } : {}),\n ...(local.unmatched ? { unmatched: local.unmatched } : {}),\n ...(local.note ? { note: local.note } : {}),\n records: local.records,\n ingested: local.ingested,\n skipped: local.skipped,\n refusals: local.refusals,\n rows: local.rows,\n dryRun: local.dry_run,\n redact,\n changed: local.changed,\n ...(local.kind ? { kind: local.kind } : {}),\n ...(local.entity_counts ? { entityCounts: local.entity_counts } : {}),\n };\n}\n\n/** The TOOL observations of one session, every trace's, from `GET /api/public/sessions/{id}?includeIO=true`. */\nexport async function sessionToolObservations(sessionId: string, options: WorldsClientOptions = {}): Promise<ObservationLike[]> {\n const session = await apiRequest<{ traces?: { id?: string; observations?: ObservationLike[] }[] }>(\n options,\n \"GET\",\n `/api/public/sessions/${encodeURIComponent(sessionId)}?includeIO=true`,\n );\n const out: ObservationLike[] = [];\n for (const trace of session.traces ?? [])\n for (const observation of trace.observations ?? []) out.push({ traceId: trace.id ?? null, ...observation });\n return out;\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\n\n/**\n * Edit sessions: the version control unit for a world. Every write this\n * credential makes to a world (push, sandbox commit, data import, MCP, the\n * console editor) joins ONE open session per world per credential and lands\n * on that session's private branch; `close` seals the session into a version\n * on `main`, and a session nobody touches for an hour seals itself. Sessions\n * replace product-level proposals/PRs: `rollback` undoes a sealed session\n * (source + data together) as a new, itself-reversible session.\n *\n * One client under both `gateway worlds edit …` and `gateway bench edit …`;\n * the Python twin is `gatewaysdk.benchmark_hub.edit_sessions.WorldEditClient`.\n */\n\n/** Mirrors `WorldEditSessionSchema` (web/features/public-api/types/world-edits.ts). */\nexport type EditSessionSummary = {\n id: string;\n containerId: string;\n /** `apikey:<id>` for CLI/sandbox/MCP, `user:<id>` for the console, `agent:<id>` for the platform agent. */\n actor: string;\n door: string;\n status: \"open\" | \"sealing\" | \"sealed\" | \"conflict\" | \"expired\" | \"discarded\" | string;\n baseVersionId: string | null;\n tipVersionId: string | null;\n sealedVersionId: string | null;\n editCount: number;\n startedAt: string;\n lastEditAt: string;\n expiresAt: string;\n closedAt: string | null;\n closeReason: string | null;\n conflictPaths: string[] | null;\n rollbackOfId: string | null;\n message: string | null;\n};\n\nexport type EditSessionList = {\n slug: string;\n containerId: string;\n /** This credential's open session, or null. */\n current: EditSessionSummary | null;\n sessions: EditSessionSummary[];\n};\n\n/** What close/discard/rollback return. */\nexport type EditSessionResult = { slug: string; session: EditSessionSummary };\n\nexport type EditSessionListQuery = { status?: string; limit?: number };\nexport type EditSessionCloseInput = { sessionId?: string; force?: boolean; message?: string };\nexport type EditSessionRollbackInput = { sessionId: string; force?: boolean; message?: string };\n\nconst WORLDS = \"/api/public/worlds\";\nexport class WorldEditClient {\n constructor(private readonly options: WorldsClientOptions = {}) {}\n\n /** The credential's current session and the world's newest-first sessions. */\n list(slug: string, query: EditSessionListQuery = {}): Promise<EditSessionList> {\n const qs = new URLSearchParams();\n if (query.status) qs.set(\"status\", query.status);\n if (query.limit !== undefined) qs.set(\"limit\", String(query.limit));\n const suffix = qs.size ? `?${qs.toString()}` : \"\";\n return apiRequest(this.options, \"GET\", `${WORLDS}/${encodeURIComponent(slug)}/edits${suffix}`);\n }\n\n /** Seal a session into a version on main (the credential's current one when `sessionId` is omitted). */\n close(slug: string, input: EditSessionCloseInput = {}): Promise<EditSessionResult> {\n return apiRequest(this.options, \"POST\", `${WORLDS}/${encodeURIComponent(slug)}/edits/close`, input);\n }\n\n /** Drop the session's private branch without making a version. */\n discard(slug: string, input: { sessionId?: string } = {}): Promise<EditSessionResult> {\n return apiRequest(this.options, \"POST\", `${WORLDS}/${encodeURIComponent(slug)}/edits/discard`, input);\n }\n\n /** Undo a sealed session (source and data) as a new sealed session. */\n rollback(slug: string, input: EditSessionRollbackInput): Promise<EditSessionResult> {\n return apiRequest(this.options, \"POST\", `${WORLDS}/${encodeURIComponent(slug)}/edits/rollback`, input);\n }\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\n\n/**\n * The hosted one-task dry run: `POST /api/public/environments/{id}/dry-run`\n * and the run-status read that settles it. The runner runs ONE named task of a\n * harbor tree through harbor's `oracle` (the task's own `solution/solve.sh`)\n * with the real image rule (`[environment] docker_image` → pull, never build;\n * else build the Dockerfile). No model, no model key. The run is marked\n * `kind: \"dry-run\"` and never counts as a benchmark result.\n *\n * The caps are the server's: one task, one example, one rollout, the oracle.\n * The body carries the task name and, optionally, a pinned versionId; a body\n * that tries to widen the run (models, task lists, rollouts) is a 400.\n */\n\nexport const DRY_RUN_KIND = \"dry-run\" as const;\nexport const DRY_RUN_AGENT = \"oracle\" as const;\n\nexport type HostedDryRunDispatch = {\n runId: string;\n versionId: string;\n versionLabel: string;\n containerSlug: string;\n task: string;\n kind: typeof DRY_RUN_KIND;\n agent: typeof DRY_RUN_AGENT;\n evidence: false;\n where: \"hosted\";\n};\n\n/** The image decision the runner took — the SAME rule a real run applies. */\nexport type DryRunImageDecision = {\n source: \"prebuilt\" | \"dockerfile\";\n ref: string | null;\n};\n\n/** What the runner reported about the one trial (the Python twin is `benchmark_hub.dry_run.DryRunSettlement`). */\nexport type DryRunSettlement = {\n task: string;\n agent: typeof DRY_RUN_AGENT;\n image: DryRunImageDecision | null;\n command: string | null;\n reward: number | null;\n rewardFile: { name: string; content: unknown } | null;\n exitCode: number | null;\n errorTail: string | null;\n};\n\nexport type HostedDryRunStatus = {\n kind: typeof DRY_RUN_KIND;\n evidence: false;\n where: \"hosted\";\n agent: typeof DRY_RUN_AGENT;\n task: string | null;\n evaluationId: string | null;\n url: string | null;\n settlement: DryRunSettlement | null;\n};\n\n/** The run-status answer (`GET …/environments/runs/{runId}`) as a dry run reads it. */\nexport type HostedDryRunVerdict = {\n status: string;\n settled: boolean;\n progress: {\n harvested: number;\n planned: number | null;\n startedAt: string | null;\n completedAt: string | null;\n elapsedSeconds: number | null;\n } | null;\n dryRun: HostedDryRunStatus | null;\n};\n\n/** The server blocks a status read for at most this long; longer waits poll. */\nexport const STATUS_WAIT_CAP_SECONDS = 50;\n\nexport type SettleOptions = {\n /** Give up (return the last verdict, unsettled) after this long. */\n timeoutSeconds: number;\n /** Called once per unsettled poll with the verdict so far. */\n onProgress?: (verdict: HostedDryRunVerdict) => void;\n /** Injected for tests: the clock and the pause between empty polls. */\n now?: () => number;\n sleep?: (ms: number) => Promise<void>;\n};\n\nconst cid = (id: string) =>\n `/api/public/environments/${encodeURIComponent(id)}`;\n\n/** The client a `gateway benchmarks dry-run --hosted` is built on. */\nexport class HostedDryRunClient {\n constructor(private readonly options: WorldsClientOptions = {}) {}\n\n /** Dispatch ONE oracle job for `task` on `containerId` (a container id, not a slug); pins `versionId` when given. */\n dispatch(target: {\n containerId: string;\n task: string;\n versionId?: string;\n }): Promise<HostedDryRunDispatch> {\n return apiRequest(\n this.options,\n \"POST\",\n `${cid(target.containerId)}/dry-run`,\n {\n task: target.task,\n ...(target.versionId ? { versionId: target.versionId } : {}),\n },\n );\n }\n\n /** One status read, blocking server-side for up to `waitSeconds` (capped). */\n status(runId: string, waitSeconds = 0): Promise<HostedDryRunVerdict> {\n const wait = Math.max(\n 0,\n Math.min(Math.floor(waitSeconds), STATUS_WAIT_CAP_SECONDS),\n );\n const suffix = wait ? `?waitSeconds=${wait}` : \"\";\n return apiRequest(\n this.options,\n \"GET\",\n `/api/public/environments/runs/${encodeURIComponent(runId)}${suffix}`,\n );\n }\n\n /** Poll until the run settles or `timeoutSeconds` pass; the last verdict either way. */\n async settle(\n runId: string,\n opts: SettleOptions,\n ): Promise<HostedDryRunVerdict> {\n const now = opts.now ?? Date.now;\n const sleep =\n opts.sleep ??\n ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));\n const deadline = now() + opts.timeoutSeconds * 1000;\n for (;;) {\n const budget = Math.floor(\n Math.min(45, Math.max(0, (deadline - now()) / 1000)),\n );\n const asked = now();\n const verdict = await this.status(runId, budget);\n if (verdict.settled || now() >= deadline) return verdict;\n opts.onProgress?.(verdict);\n // A server that answered at once (no long poll behind it) must not be hammered.\n if (now() - asked < 1000) await sleep(1000);\n }\n }\n}\n\n/** The one exit-code decision, shared by the CLI twins: 0 only when the oracle scored exactly 1.0. */\nexport class DryRunOutcome {\n constructor(readonly verdict: HostedDryRunVerdict) {}\n\n get settlement(): DryRunSettlement | null {\n return this.verdict.dryRun?.settlement ?? null;\n }\n\n /** Why the dry run did not pass, or null when it did. */\n reason(): string | null {\n if (!this.verdict.settled) return `still running after the wait`;\n const settlement = this.settlement;\n if (!settlement)\n return `the runner filed no settlement (${this.verdict.status})`;\n const lastErrorLine =\n settlement.errorTail?.trim().split(\"\\n\").at(-1) || null;\n // A non-zero harbor exit is a failure whatever the reward file says: a\n // 1.0 written before the harness died is not a pass.\n if (settlement.exitCode !== null && settlement.exitCode !== 0)\n return `the runner failed (exit ${settlement.exitCode}): ${lastErrorLine ?? \"harbor exited non-zero\"}`;\n if (settlement.reward === null && lastErrorLine)\n return `the runner failed (exit ?): ${lastErrorLine}`;\n if (settlement.reward === null)\n return \"ungraded: the grader ran but wrote no reward\";\n if (settlement.reward !== 1)\n return `the reference solution scored ${settlement.reward}, not 1.0`;\n return null;\n }\n\n passed(): boolean {\n return this.reason() === null;\n }\n}\n","\nimport type { WorldTaskIdRef } from \"./session\";\n\nexport type WorldsClientOptions = {\n host?: string;\n publicKey?: string;\n secretKey?: string;\n};\n\nexport type ResolvedWorldVersion = {\n versionId: string;\n semanticVersion: string | null;\n contentHash: string;\n state?: string;\n};\n\nexport type WorldTaskInfo = {\n name: string;\n variant: string | null;\n};\n\nexport type DispatchedRun = {\n model: string;\n runId: string;\n ok: boolean;\n error?: string;\n};\n\nfunction resolveEnv(options: WorldsClientOptions) {\n const host =\n options.host ?? process.env.GATEWAY_HOST ?? \"https://withgateway.ai\";\n const publicKey = options.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;\n const secretKey = options.secretKey ?? process.env.GATEWAY_SECRET_KEY;\n if (!publicKey || !secretKey) {\n throw new Error(\n \"Gateway keys missing: set GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY \" +\n \"(or pass publicKey/secretKey).\",\n );\n }\n return { host: host.replace(/\\/+$/, \"\"), publicKey, secretKey };\n}\n\n/** A platform answer outside 2xx, its status kept so a caller can act on one\n * code (a 409 on a name already taken) instead of parsing the message. A JSON\n * body renders as `<message> (<code>)` — the stable public `code`, never the\n * server's error class name. */\nexport class ApiError extends Error {\n public readonly code: string | null;\n\n constructor(\n public readonly status: number,\n method: string,\n path: string,\n body: string,\n ) {\n const parsed = parseErrorBody(body);\n super(`${method} ${path} -> ${status}: ${parsed.detail}`);\n this.name = \"ApiError\";\n this.code = parsed.code;\n }\n}\n\n/** What a client shows for one non-2xx body and the stable code it carries.\n * Python twin: `gatewaysdk.api_errors.error_detail`. */\nexport function parseErrorBody(\n text: string,\n limit = 600,\n): { detail: string; code: string | null } {\n const raw = { detail: text.slice(0, limit), code: null };\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return raw;\n }\n if (parsed === null || typeof parsed !== \"object\") return raw;\n const { message, code } = parsed as { message?: unknown; code?: unknown };\n const stableCode = typeof code === \"string\" ? code : null;\n if (typeof message !== \"string\") return { ...raw, code: stableCode };\n if (stableCode === null)\n return { detail: message.slice(0, limit), code: null };\n return {\n detail: `${message} (${stableCode})`.slice(0, limit),\n code: stableCode,\n };\n}\n\n/** Authenticated JSON request against the platform API — the primitive the\n * worlds helpers and the TS CLI share. */\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);\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/** One run as `bench runs list` prints it (GET /benchmark-containers/runs):\n * the gate's view — no logs, samples or links; `getRun` has those. */\nexport type RunSummary = {\n id: string;\n status: string;\n terminal: boolean;\n score: number | null;\n summary: string | null;\n createdAt: string;\n completedAt: string | null;\n model: string | null;\n versionId: string | null;\n versionLabel: string | null;\n runConfigId: string | null;\n runConfigName: string | null;\n parallelism: number;\n exitCode: number | null;\n};\n\nexport type ListRunsFilter = {\n /** Only runs of this world/benchmark; a slug the project lacks lists nothing. */\n slug?: string;\n /** Case-insensitive run status (RUNNING, completed, …). */\n status?: string;\n limit?: number;\n};\n\n/** The project's runs, newest first. */\nexport async function listRuns(\n filter: ListRunsFilter = {},\n options: WorldsClientOptions = {},\n): Promise<RunSummary[]> {\n const params = new URLSearchParams();\n if (filter.slug) params.set(\"slug\", filter.slug);\n if (filter.status) params.set(\"status\", filter.status);\n if (filter.limit !== undefined) params.set(\"limit\", String(filter.limit));\n const qs = params.toString();\n const res = await apiRequest<{ runs: RunSummary[] }>(\n options,\n \"GET\",\n `/api/public/benchmark-containers/runs${qs ? `?${qs}` : \"\"}`,\n );\n return res.runs;\n}\n\n/** Poll a run to terminal (default every 20s, up to `timeoutMinutes`). */\nexport async function waitForRun(\n runId: string,\n opts: {\n timeoutMinutes?: number;\n intervalSeconds?: number;\n onTick?: (run: RunReport) => void;\n options?: WorldsClientOptions;\n } = {},\n): Promise<RunReport> {\n const deadline = Date.now() + (opts.timeoutMinutes ?? 45) * 60_000;\n for (;;) {\n const run = await getRun(runId, opts.options ?? {});\n if (run.terminal) return run;\n if (Date.now() > deadline)\n throw new Error(\n `Run ${runId} still ${run.status} after the wait timeout.`,\n );\n opts.onTick?.(run);\n await new Promise((resolve) =>\n setTimeout(resolve, (opts.intervalSeconds ?? 20) * 1000),\n );\n }\n}\n\nexport type RunProvenance = {\n branch?: string;\n commit?: string;\n repoUrl?: string;\n actor?: { id?: string; name?: string; imageUrl?: string; kind?: string };\n};\n\n/**\n * Where a dispatch comes from, DETECTED rather than configured: the CI\n * checkout's branch/commit/actor under GitHub Actions, else the developer's\n * own git checkout. A run nobody can trace to a branch is a score with no\n * code attached, so every dispatch carries this unless overridden.\n */\nexport function detectProvenance(): RunProvenance {\n const env =\n (globalThis as { process?: { env?: Record<string, string | undefined> } })\n .process?.env ?? {};\n const out: RunProvenance = {};\n const ref = env.GITHUB_HEAD_REF || env.GITHUB_REF_NAME;\n if (ref) out.branch = ref;\n if (env.GITHUB_SHA) out.commit = env.GITHUB_SHA;\n const server = env.GITHUB_SERVER_URL ?? \"https://github.com\";\n if (env.GITHUB_REPOSITORY) out.repoUrl = `${server}/${env.GITHUB_REPOSITORY}`;\n if (env.GITHUB_ACTOR) {\n out.actor = {\n kind: \"ci\",\n id: env.GITHUB_ACTOR,\n name: env.GITHUB_ACTOR,\n // GitHub serves every account's avatar at /<login>.png.\n imageUrl: `${server}/${env.GITHUB_ACTOR}.png`,\n };\n }\n if (!out.branch || !out.commit) {\n try {\n const { execFileSync } =\n require(\"node:child_process\") as typeof import(\"node:child_process\");\n const git = (args: string[]) =>\n execFileSync(\"git\", args, {\n encoding: \"utf-8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n })\n .toString()\n .trim();\n out.branch = out.branch ?? git([\"rev-parse\", \"--abbrev-ref\", \"HEAD\"]);\n out.commit = out.commit ?? git([\"rev-parse\", \"HEAD\"]);\n if (!out.repoUrl) {\n const remote = git([\"config\", \"--get\", \"remote.origin.url\"]);\n if (remote) out.repoUrl = remote.replace(/\\.git$/, \"\");\n }\n if (!out.actor) {\n const name = git([\"config\", \"--get\", \"user.name\"]);\n if (name) out.actor = { kind: \"user\", name };\n }\n } catch {\n // No git here — dispatch without provenance rather than failing.\n }\n }\n return out;\n}\n\n/** One scenario of a world, as data. */\nexport class WorldTask {\n constructor(\n readonly world: WorldSet,\n readonly name: string,\n readonly variant: string | null,\n ) {}\n}\n\n/**\n * THE world, from a TS process: pinned identity + its tasks + hosted runs.\n *\n * const world = await openWorld(\"google-drive-sim@main\");\n * console.log(world.version.semanticVersion, world.tasks.length);\n * const runs = await world.dispatch(runConfigId);\n */\nexport class WorldSet {\n constructor(\n readonly slugRef: string,\n readonly slug: string,\n readonly ref: string | null,\n readonly version: ResolvedWorldVersion,\n public tasks: WorldTask[],\n private readonly options: WorldsClientOptions,\n ) {}\n\n task(variant: string): WorldTask {\n const hit = this.tasks.find(\n (t) => t.variant === variant || t.name.includes(variant),\n );\n if (!hit) {\n const known = this.tasks.map((t) => t.variant ?? t.name).join(\", \");\n throw new Error(`no task matches ${variant}; have: ${known}`);\n }\n return hit;\n }\n\n /**\n * Open a LIVE session against one of this world's tasks — a bundled task's\n * name or an inline `WorldTaskSpec`: the platform boots (or reuses) a warm\n * container, and your agent calls its tools through the platform. See\n * worlds/session.ts.\n */\n async open(\n task: import(\"./session\").WorldTaskRef,\n opts: {\n reuseWarm?: boolean;\n surfaces?: import(\"./browser\").WorldSurfaceKind[];\n browserTier?: import(\"./browser\").BrowserTier;\n } = {},\n ): Promise<import(\"./session\").WorldSession> {\n const { openSession } = await import(\"./session\");\n return openSession(this.slug, {\n task,\n versionId: this.version.versionId,\n reuseWarm: opts.reuseWarm,\n surfaces: opts.surfaces,\n browserTier: opts.browserTier,\n options: this.options,\n });\n }\n\n /**\n * Start a HOSTED run of a run config against this world — the platform\n * executes the (Python) world in parallel containers per the config's\n * `parallelism` and files one graded run per model. Returns those runs.\n */\n async dispatch(\n runConfigId: string,\n opts: {\n containerId?: string;\n versionId?: string;\n /** Override the auto-detected branch/commit/actor. */\n provenance?: RunProvenance;\n } = {},\n ): Promise<{ versionLabel: string; runs: DispatchedRun[] }> {\n const provenance = opts.provenance ?? detectProvenance();\n return apiRequest(\n this.options,\n \"POST\",\n \"/api/public/benchmark-containers/run-configs/dispatch\",\n {\n runConfigId,\n ...(opts.containerId ? { containerId: opts.containerId } : {}),\n versionId: opts.versionId ?? this.version.versionId,\n ...provenance,\n },\n );\n }\n}\n\n/**\n * Resolve `slug` / `slug@branch|tag|semver|hash` to its pinned version and\n * task list. The task list comes from the version's file manifest\n * (`tasks/<name>/task.toml`), so it needs no bundle download.\n */\nexport async function openWorld(\n slugRef: string,\n options: WorldsClientOptions = {},\n): Promise<WorldSet> {\n const at = slugRef.indexOf(\"@\");\n const slug = at === -1 ? slugRef : slugRef.slice(0, at);\n const ref = at === -1 ? null : slugRef.slice(at + 1);\n return resolveWorld(slugRef, slug, ref, ref ? { ref } : {}, options);\n}\n\n/**\n * Resolve `slug` at one pinned READY `versionId` — the task list is THAT\n * version's, never the branch tip's. `worlds run|ci --version-id` come\n * through here; a version of another container, a draft or an unknown id\n * is a 404 from the platform, not a silent fall-through to head.\n */\nexport async function openWorldVersion(\n slug: string,\n versionId: string,\n options: WorldsClientOptions = {},\n): Promise<WorldSet> {\n return resolveWorld(\n `${slug}@${versionId}`,\n slug,\n null,\n { versionId },\n options,\n );\n}\n\nasync function resolveWorld(\n slugRef: string,\n slug: string,\n ref: string | null,\n pin: { ref?: string; versionId?: string },\n options: WorldsClientOptions,\n): Promise<WorldSet> {\n const version = await apiRequest<\n ResolvedWorldVersion & { taskNames?: string[] }\n >(options, \"POST\", \"/api/public/benchmark-containers/resolve-version\", {\n slug,\n ...pin,\n });\n\n const world = new WorldSet(\n slugRef,\n slug,\n ref,\n {\n versionId: version.versionId,\n semanticVersion: version.semanticVersion ?? null,\n contentHash: version.contentHash,\n state: version.state,\n },\n [],\n options,\n );\n for (const name of version.taskNames ?? []) {\n const variant = /^[a-z0-9]+-([a-z0-9]+)-/.exec(name)?.[1] ?? null;\n world.tasks.push(new WorldTask(world, name, variant));\n }\n return world;\n}\n\n// The session surface completes the worlds module, so `@withgateway/sdk/worlds`\n// carries both halves: running a world locally, and driving one the platform\n// hosts. (session.ts imports apiRequest from here; the cycle is function-level\n// only, and the build below is what proves it resolves.)\nexport * from \"./session\";\nexport * from \"./sessionList\";\nexport * from \"./sessionContract\";\nexport * from \"./taskRef\";\n\n// Stored tasks: the task spec as a named, versioned project resource that\n// `openSession(world, { task: { id } })` opens on.\nexport * from \"./tasks\";\n\n// Tasks that need several worlds: `openTask` brings every world a task\n// names up together (or not at all) and hands back the sessions by alias.\nexport * from \"./taskSessions\";\n\n// Run a task end to end: open every world, hand the agent a `TaskRun`,\n// grade with its report, file one rollout and close — `runTask`, the\n// engine behind `gateway worlds task run`.\nexport * from \"./taskRun\";\n\n// Run every stored task of a scenario set with one model as ONE set run —\n// `runSet`, the engine behind `gateway worlds task run-set` — and the checkout\n// it records (branch, commit, remote without credentials, CI's pull request).\nexport * from \"./setRun\";\nexport * from \"./checkoutProvenance\";\n\n// The evaluations client `runTask` files a rollout through — create, push\n// samples, finalize. Exposed in case a caller wants to file its own.\nexport * from \"./evals\";\n\n// The computer-use half: surfaces, a Playwright browser on the world's UI,\n// and browser actions as model tools.\nexport * from \"./browser\";\nexport * from \"./browserReconnect\";\n\n// The hub half: push, pull, propose and the content-hash primitives the CLI\n// runs on. These were reachable only from inside the package, so a consumer\n// could drive a world but never publish one.\nexport * from \"./hub\";\n\n// PR validation: push-dispatch-wait-gate as one composed call, for CI.\nexport * from \"./validate\";\n\n// Discovery: what a world holds and how each field is stored (`describeWorld`),\n// and the stored forms of a plaintext under the world's [redact] table\n// (`storedForms`, `redactionOf`) — the same digest rule as the Python runtime.\nexport * from \"./describe\";\nexport * from \"./redaction\";\nexport * from \"./transforms\";\n\n// Lookup: the rows of one entity matching a predicate (`queryRows`), by\n// stored value or — with `resolve` — by plaintext the runtime maps through\n// the same [redact] table.\nexport * from \"./query\";\n\n// Migration: a stored world into a schema world (`migrateWorld`), dry run by\n// default; the project's connector worlds at once (`migrateProjectWorlds`).\nexport * from \"./migrate\";\n\n// Tool calls into rows: the record contract, `captureToolCalls` (record an\n// agent's real calls), `toolCallsFromObservations` (from a trace) and\n// `ingestToolCalls` (into a directory or a slug). Redaction optional, off by default.\nexport * from \"./ingest\";\n\n// The CLI sandbox: open a READY version in a server-side workspace, edit and\n// run there, check and commit into the version service without the source\n// ever landing on this disk (`gateway worlds|bench sandbox …`).\nexport * from \"./sandbox\";\nexport * from \"./editSessions\";\n\n// The hosted one-task dry run: ONE oracle job on the runner with the real\n// image rule, its settlement (image decision, reward file, exit code) and the\n// one pass/fail decision the CLI twins share (`gateway benchmarks dry-run --hosted`).\nexport * from \"./dryRun\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,eAAsB,gBAAgB,GAAqC;AACzE,QAAM,EAAE,QAAQ,MAAM;AACtB,QAAM,EAAE,QAAQ,MAAM;AACxB;AAIA,eAAsB,kBAAkB,GAAqC;AAC3E,QAAM,gBAAgB,CAAC,EAAE,MAAM,MAAM,MAAS;AAChD;AAuBO,SAAS,cAAc,OAAyB;AACrD,QAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,MAAI,mBAAmB,KAAK,OAAO,EAAG,QAAO;AAC7C,SAAO,sBAAsB,KAAK,CAAC,MAAM,EAAE,KAAK,OAAO,CAAC;AAC1D;AAkEA,SAAS,mBAAmB,OAAyB;AACnD,QAAM,EAAE,QAAQ,KAAK,IAAI;AACzB,MAAI,OAAO,WAAW,SAAU,QAAO;AACvC,MAAI,UAAU,IAAK,QAAO;AAC1B,SAAO,WAAW,OAAO,SAAS;AACpC;AAEA,SAAS,SAAS,OAAwB;AACxC,SAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D;AAlJA,IA8Ca,mBACP,iBACA,gBAKO,uBAYP,oBAQA,UACA,mBASO,gBAwBA,oBAoBA,sBA+BA;AA9Jb;AAAA;AAAA;AA8CO,IAAM,oBAAoB;AACjC,IAAM,kBAAkB;AACxB,IAAM,iBAAiB;AAKhB,IAAM,wBAA2C;AAAA,MACtD;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAKA,IAAM,qBAAqB;AAQ3B,IAAM,WAAW;AACjB,IAAM,oBAAoB;AASnB,IAAM,iBAAN,MAAq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MAAM;AAC9B,eAAOA,aAAY,KAAK,MAAM;AAAA,UAC5B;AAAA,UACA,WAAW,KAAK,QAAQ;AAAA,UACxB,WAAW,KAAK;AAAA,UAChB,UAAU,KAAK;AAAA,UACf,aAAa,KAAK;AAAA,UAClB,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":["text","path","text","resolve","sleep","text","state","openWorld","openWorldVersion","api","path","pollMs","state","path","text","session_exports","AsyncLocalStorage","resolve","init_session","isSpanContextValid","trace","path","text","text","scores","init_session","isGatewayConfigured","init","fs","path","state","createHash","fs","path","init","text","fs","path","createHash","fs","path","pad","text","resolve","state","text","hex","createHash","createHash","text","field","fs","path","init","text","fs","path","resolve","text","fs","path","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","sleep","resolve","ApiError","text","path","resolve","execFileSync","openSession"]}
|
|
1
|
+
{"version":3,"sources":["../../src/worlds/transport.ts","../../src/worlds/browserReconnect.ts","../../src/worlds/browser.ts","../../src/worlds/sessionContract.ts","../../src/worlds/taskRef.ts","../../src/worlds/session.ts","../../src/worlds/sessionList.ts","../../src/worlds/tasks.ts","../../src/worlds/taskSessions.ts","../../src/worlds/evals.ts","../../src/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/checkoutProvenance.ts","../../src/worlds/setRun.ts","../../src/worlds/checkoutTarget.ts","../../src/worlds/worldDir.ts","../../src/worlds/tar.ts","../../src/worlds/hub.ts","../../src/worlds/validate.ts","../../src/worlds/sandbox.ts","../../src/worlds/describe.ts","../../src/cli/platform/worldData/json.ts","../../src/worlds/transforms.ts","../../src/worlds/redaction.ts","../../src/worlds/query.ts","../../src/worlds/migrate.ts","../../src/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/editSessions.ts","../../src/worlds/dryRun.ts","../../src/worlds/index.ts"],"sourcesContent":["export const PLATFORM_TIMEOUT_ENV = \"GATEWAY_TIMEOUT_MS\";\n\n/** How long one platform request may go unanswered before it is abandoned; `GATEWAY_TIMEOUT_MS` overrides it. */\nexport const PLATFORM_TIMEOUT_DEFAULT_MS = 120_000;\n\nexport type PlatformEndpoint = { host: string; publicKey: string; secretKey: string };\n\nexport type PlatformMethod = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n\nexport type PlatformReply = { status: number; ok: boolean; text: string };\n\n/** The request budget in force: `GATEWAY_TIMEOUT_MS` when set, else the default. */\nexport function platformTimeoutMs(env: NodeJS.ProcessEnv = process.env): number {\n const raw = env[PLATFORM_TIMEOUT_ENV];\n if (raw === undefined || raw === \"\") return PLATFORM_TIMEOUT_DEFAULT_MS;\n const value = Number(raw);\n if (Number.isInteger(value) && value > 0) return value;\n throw new Error(`${PLATFORM_TIMEOUT_ENV} must be a positive whole number of milliseconds, not \\`${raw}\\`.`);\n}\n\nconst CHECK_HOST = \"Check GATEWAY_HOST (or --host) points at a running platform, then retry.\";\nconst RETRY = \"Retry; if it repeats, check the network between here and the platform.\";\n\nconst CAUSES: Record<string, { reason: string; next: string }> = {\n ECONNREFUSED: { reason: \"connection refused\", next: CHECK_HOST },\n ENOTFOUND: { reason: \"DNS lookup failed\", next: CHECK_HOST },\n EAI_AGAIN: { reason: \"DNS lookup failed\", next: CHECK_HOST },\n ETIMEDOUT: { reason: \"connect timed out\", next: CHECK_HOST },\n UND_ERR_CONNECT_TIMEOUT: { reason: \"connect timed out\", next: CHECK_HOST },\n EHOSTUNREACH: { reason: \"host unreachable\", next: CHECK_HOST },\n ENETUNREACH: { reason: \"network unreachable\", next: RETRY },\n ECONNRESET: { reason: \"connection dropped\", next: RETRY },\n UND_ERR_SOCKET: { reason: \"connection dropped\", next: RETRY },\n EPIPE: { reason: \"connection dropped\", next: RETRY },\n};\n\nconst UNKNOWN_CAUSE = { reason: \"network error\", next: CHECK_HOST };\n\n/** Why a request got no answer, from the socket-level error undici hides under `fetch failed`. */\nexport class TransportCause {\n private constructor(\n readonly reason: string,\n readonly detail: string | null,\n readonly next: string,\n ) {}\n\n static timeout(timeoutMs: number): TransportCause {\n return new TransportCause(\n `timed out after ${timeoutMs / 1000}s`,\n null,\n `Retry; if the platform is slow, raise ${PLATFORM_TIMEOUT_ENV} (milliseconds per request).`,\n );\n }\n\n static of(error: unknown): TransportCause {\n const cause = error instanceof Error && error.cause instanceof Error ? error.cause : undefined;\n const code = cause && \"code\" in cause && typeof cause.code === \"string\" ? cause.code : null;\n const message = cause?.message ?? (error instanceof Error ? error.message : String(error));\n const known = (code && CAUSES[code]) || UNKNOWN_CAUSE;\n return new TransportCause(known.reason, code ? `${code}: ${message}` : message, known.next);\n }\n\n describe(): string {\n return this.detail === null ? this.reason : `${this.reason} (${this.detail})`;\n }\n}\n\n/** A platform request that never got an answer: one line naming the request, the host, the cause and the next step. */\nexport class UnreachableError extends Error {\n constructor(\n readonly host: string,\n readonly method: string,\n readonly route: string,\n readonly failure: TransportCause,\n ) {\n super(`${method} ${route}: no answer from ${host}: ${failure.describe()}. ${failure.next}`);\n this.name = \"UnreachableError\";\n }\n}\n\n/** The one door every CLI and SDK request to the platform goes through: Basic auth with the project key, a per-request timeout, and a transport failure turned into an `UnreachableError`. */\nexport class PlatformTransport {\n constructor(\n private readonly endpoint: PlatformEndpoint,\n private readonly timeoutMs: number = platformTimeoutMs(),\n ) {}\n\n /** A request that legitimately takes longer (a sandbox exec, a world create) waits its own budget; every other one waits the default. */\n budget(ownMs?: number): number {\n return Math.max(ownMs ?? 0, this.timeoutMs);\n }\n\n async send(\n method: PlatformMethod,\n route: string,\n body?: unknown,\n opts: { timeoutMs?: number } = {},\n ): Promise<PlatformReply> {\n const timeoutMs = this.budget(opts.timeoutMs);\n const payload = body === undefined ? {} : { body: JSON.stringify(body) };\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n try {\n const res = await fetch(`${this.endpoint.host}${route}`, {\n method,\n headers: {\n \"content-type\": \"application/json\",\n accept: \"application/json\",\n authorization:\n \"Basic \" + Buffer.from(`${this.endpoint.publicKey}:${this.endpoint.secretKey}`).toString(\"base64\"),\n },\n ...payload,\n signal: controller.signal,\n });\n return { status: res.status, ok: res.ok, text: await res.text() };\n } catch (error) {\n const cause = controller.signal.aborted ? TransportCause.timeout(timeoutMs) : TransportCause.of(error);\n throw new UnreachableError(this.endpoint.host, method, route, cause);\n } finally {\n clearTimeout(timer);\n }\n }\n}\n","import type { BrowserPage, PlaywrightBrowserLike } from \"./browser\";\n\n/**\n * A HOSTED BROWSER THAT COMES BACK. A World Host session's browser is a pool\n * pod; on the `standard` tier it runs on spot capacity and can be reclaimed\n * with two minutes' notice. The browser dies, the world does not, and the\n * platform can put a new browser behind the SAME `surfaces.browser.wsUrl`.\n *\n * `BrowserReconnector` is the client half of that repair: on a lost\n * connection it asks the platform to repair (`POST .../browser-repair`),\n * waits while a browser starts, reconnects to the same address and hands the\n * new connection to its owner to restore the page. It knows nothing of HTTP\n * or Playwright — both come in as collaborators, so tests drive it with\n * fakes. Twin of `gatewaysdk/world_browser_reconnect.py`, call for call.\n */\n\n/** What the platform answers a repair with. `healthy`: the browser is alive,\n * reconnect now. `replaced`: a new, blank browser; reconnect and reopen the\n * page. `starting`: a browser is coming up; ask again in `retryAfterMs`. */\nexport type RepairAnswer = {\n outcome: \"healthy\" | \"replaced\" | \"starting\";\n retryAfterMs: number | null;\n};\n\ntype BrowserContextLike = Awaited<\n ReturnType<PlaywrightBrowserLike[\"newContext\"]>\n>;\n\n/** One live attachment to the session's browser. */\nexport type BrowserConnection = {\n browser: PlaywrightBrowserLike;\n context: BrowserContextLike;\n page: BrowserPage;\n};\n\nexport async function closeConnection(c: BrowserConnection): Promise<void> {\n await c.context.close();\n await c.browser.close();\n}\n\n/** Close a connection whose browser is already gone: it only frees the\n * handle, so a failure is ignored. */\nexport async function releaseConnection(c: BrowserConnection): Promise<void> {\n await closeConnection(c).catch(() => undefined);\n}\n\nexport const RECOVER_BUDGET_MS = 90_000;\nconst BACKOFF_BASE_MS = 1_000;\nconst BACKOFF_CAP_MS = 5_000;\n\n/** What Playwright says when the browser or its connection is gone, as\n * opposed to an action that failed on a live page. Matched case-insensitively\n * against the error message; nothing else triggers a reconnect. */\nexport const BROWSER_GONE_PATTERNS: readonly RegExp[] = [\n /target page, context or browser has been closed/i,\n /\\bbrowser has been (closed|disconnected)\\b/i,\n /\\bbrowser (has )?disconnected\\b/i,\n /\\btarget closed\\b/i,\n /\\bwebsocket is not open\\b/i,\n /\\bconnection closed\\b/i,\n];\n\n/** A failed page load (`net::ERR_INTERNET_DISCONNECTED`,\n * `net::ERR_CONNECTION_CLOSED`) is the world UI's network, not the browser:\n * the browser is alive, and repairing it would throw away a live page. */\nconst PAGE_NETWORK_ERROR = /net::ERR_/i;\n\nexport function isBrowserGone(error: unknown): boolean {\n const message = error instanceof Error ? error.message : String(error);\n if (PAGE_NETWORK_ERROR.test(message)) return false;\n return BROWSER_GONE_PATTERNS.some((p) => p.test(message));\n}\n\nconst REDACTED = \"<redacted>\";\nconst TOKEN_QUERY_VALUE = /([?&]token=)[^&#\\s\"')]*/gi;\n\n/**\n * Takes a session's credentials out of text that leaves the process — an\n * error recorded into the browser timeline, a recovery's reason. A browser\n * error quotes the URL it failed on, and those URLs carry the session: the\n * hosted browser's `wsUrl` (its path is the credential), the UI's token, and\n * any `?token=` a landing URL presents. Each becomes `<redacted>`.\n */\nexport class SecretScrubber {\n private readonly secrets: string[];\n\n constructor(secrets: readonly (string | null | undefined)[]) {\n const known = secrets.filter((s): s is string => Boolean(s));\n // Longest first, so a wsUrl goes whole before a token inside it.\n this.secrets = [\n ...new Set([...known, ...known.map((s) => encodeURIComponent(s))]),\n ].sort((a, b) => b.length - a.length);\n }\n\n scrub(text: string): string {\n const bare = this.secrets.reduce(\n (out, secret) => out.split(secret).join(REDACTED),\n text,\n );\n return bare.replace(TOKEN_QUERY_VALUE, `$1${REDACTED}`);\n }\n}\n\n/** A mutating action (click, type, press, back, scroll) lost its browser.\n * The browser was repaired and the page reopened at `restoredUrl`, but the\n * action is NOT replayed: its input may already have reached the world.\n * `cause` is the error the action failed with. */\nexport class BrowserReconnected extends Error {\n constructor(\n readonly outcome: RecoveryResult[\"outcome\"],\n readonly restoredUrl: string | null,\n cause: unknown,\n ) {\n super(\n `the browser was lost mid-action and reconnected (${outcome}); ` +\n (restoredUrl\n ? `the page was reopened at ${restoredUrl}. `\n : \"it is on a blank page. \") +\n \"The action may or may not have taken effect — look at the page before acting again.\",\n { cause },\n );\n this.name = \"BrowserReconnected\";\n }\n}\n\n/** The session's browser stayed gone for the whole budget. `cause` is the\n * error the action first failed with. */\nexport class BrowserUnrecoverable extends Error {\n constructor(message: string, cause: unknown) {\n super(message, { cause });\n this.name = \"BrowserUnrecoverable\";\n }\n}\n\n/** A repair refusal worth waiting out: no answer at all (the network), the\n * platform's own failure, or a full pool. Anything else (a 404 for a session\n * that is not open with a browser) ends the recovery. */\nfunction refusalIsTransient(error: unknown): boolean {\n const { status, code } = error as { status?: unknown; code?: unknown };\n if (typeof status !== \"number\") return true;\n if (status >= 500) return true;\n return status === 400 && code === \"browser_capacity\";\n}\n\nfunction describe(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\ntype Step =\n | { kind: \"recovered\"; outcome: RecoveryResult[\"outcome\"] }\n | { kind: \"stop\" }\n | { kind: \"wait\"; reason: string; waitMs: number | null };\n\nexport type RecoveryResult = {\n outcome: \"healthy\" | \"replaced\";\n attempts: number;\n};\n\nexport class BrowserReconnector {\n private readonly sleep: (ms: number) => Promise<void>;\n private readonly now: () => number;\n private readonly scrub: (text: string) => string;\n readonly budgetMs: number;\n\n constructor(\n private readonly repair: () => Promise<RepairAnswer>,\n private readonly connect: () => Promise<BrowserConnection>,\n opts: {\n sleep?: (ms: number) => Promise<void>;\n now?: () => number;\n budgetMs?: number;\n /** Takes credentials out of a reason before it is thrown. */\n scrub?: (text: string) => string;\n } = {},\n ) {\n this.sleep =\n opts.sleep ?? ((ms) => new Promise<void>((r) => setTimeout(r, ms)));\n this.now = opts.now ?? Date.now;\n this.budgetMs = opts.budgetMs ?? RECOVER_BUDGET_MS;\n this.scrub = opts.scrub ?? ((text) => text);\n }\n\n /**\n * Repair, reconnect and `restore` until it works or the budget runs out.\n * `restore` receives each new connection (the owner adopts it and reopens\n * its page); a restore that fails counts as a failed reconnect, because the\n * browser may have died again. A repair the platform refuses for good\n * rethrows `cause` untouched.\n */\n async recover(\n cause: unknown,\n restore: (connection: BrowserConnection) => Promise<void>,\n ): Promise<RecoveryResult> {\n const deadline = this.now() + this.budgetMs;\n let reason = describe(cause);\n for (let attempt = 1; ; attempt++) {\n const step = await this.attempt(restore);\n if (step.kind === \"recovered\")\n return { outcome: step.outcome, attempts: attempt };\n if (step.kind === \"stop\") throw cause;\n reason = step.reason;\n const remaining = deadline - this.now();\n if (remaining <= 0) break;\n const backoff = Math.min(\n BACKOFF_BASE_MS * 2 ** (attempt - 1),\n BACKOFF_CAP_MS,\n );\n await this.sleep(Math.min(step.waitMs ?? backoff, remaining));\n }\n throw new BrowserUnrecoverable(\n `the session's browser could not be recovered within ${Math.round(this.budgetMs / 1000)}s: ${this.scrub(reason)}`,\n cause,\n );\n }\n\n private async attempt(\n restore: (connection: BrowserConnection) => Promise<void>,\n ): Promise<Step> {\n let answer: RepairAnswer;\n try {\n answer = await this.repair();\n } catch (error) {\n if (!refusalIsTransient(error)) return { kind: \"stop\" };\n return {\n kind: \"wait\",\n reason: `repair failed: ${describe(error)}`,\n waitMs: null,\n };\n }\n const outcome = answer.outcome;\n if (outcome === \"starting\")\n return {\n kind: \"wait\",\n reason: \"a new browser is still starting\",\n waitMs: answer.retryAfterMs,\n };\n try {\n await restore(await this.connect());\n } catch (error) {\n return {\n kind: \"wait\",\n reason: `reconnect failed: ${describe(error)}`,\n waitMs: null,\n };\n }\n return { kind: \"recovered\", outcome };\n }\n}\n","import { schemaFromSignature, type WorldToolkit } from \"./session\";\nimport {\n BrowserReconnected,\n BrowserReconnector,\n SecretScrubber,\n closeConnection,\n isBrowserGone,\n releaseConnection,\n type BrowserConnection,\n type RecoveryResult,\n type RepairAnswer,\n} from \"./browserReconnect\";\n\n/**\n * A BROWSER ON A WORLD'S UI — the computer-use half of a live session.\n *\n * A session answers on SURFACES. `tools` is always there (the world's own\n * operations over the rendezvous). An api-type world may also answer on\n * `api` (the service itself), `ui` (its dashboard, over the same state) and\n * `browser` — a headless Chromium the platform runs NEXT TO that UI, which\n * an agent drives through Playwright. This file is the TS client for the\n * last two, call for call with `gatewaysdk/world_browser.py`.\n *\n * const s = await openSession(\"payments-like\", \"refund-dispute\", {\n * surfaces: [\"ui\", \"browser\"],\n * });\n * await s.ready();\n * const b = await s.browser(); // hosted, next to the world\n * await b.goto(); // the UI's entry page\n * await b.click(\"text=Refund\");\n * const tools = computerUseToolkit(b); // the same actions as model tools\n * await b.close();\n *\n * Playwright is an OPTIONAL peer: nothing here imports it until a browser is\n * opened, so sessions that never touch a UI never load it.\n *\n * MODES. `hosted` connects to the session's own browser (a Playwright server\n * the pod exposes over an authenticated websocket). `local` launches Chromium\n * on this machine and points it at the UI — a laptop against a hosted twin,\n * or a test. `auto` prefers hosted. Asking for a mode the session cannot\n * serve throws `WorldSurfaceUnavailable`; there is no silent fallback to a\n * browser other than the one the episode is judged on.\n *\n * OBSERVABILITY. Every action a `WorldBrowser` takes (goto, click, type,\n * press, scroll, back) is reported to the platform as one event — what was\n * done, whether it worked, where the page ended up, and a JPEG of the screen\n * after — through a `BrowserActionRecorder`. Reporting is fire-and-forget\n * and never fails the action; the platform renders it as the session's\n * browser timeline. Text typed into secret-looking fields is redacted before\n * it leaves the process.\n *\n * RECONNECT. A World Host browser on the `standard` tier can be reclaimed\n * mid-session. When an action fails because the browser or its connection is\n * gone, a hosted `cdp` browser asks the platform to repair it, reconnects to\n * the same address and reopens the page it was on (see `browserReconnect.ts`).\n * A read or a `goto` then runs once more; a click, type, press, back or scroll\n * is NOT replayed — its input may already have reached the world — and throws\n * `BrowserReconnected` so the agent looks at the page again. Local and\n * `playwright`-protocol browsers never reconnect.\n */\n\nexport const SURFACE_KINDS = [\"tools\", \"api\", \"ui\", \"browser\"] as const;\nexport type WorldSurfaceKind = (typeof SURFACE_KINDS)[number];\n\n/** Capacity behind a World Host session's browser. `standard` runs on spot\n * capacity first (about half the price) and may be reclaimed with two\n * minutes' notice, ending the browser but never the world; `premium` is\n * on-demand and never spot-reclaimed. Unset, the organization's default applies. */\nexport const BROWSER_TIERS = [\"standard\", \"premium\"] as const;\nexport type BrowserTier = (typeof BROWSER_TIERS)[number];\n\n/** Refuse a tier the platform does not know, before any request is sent. */\nexport function assertBrowserTier(value: unknown): asserts value is BrowserTier {\n if ((BROWSER_TIERS as readonly unknown[]).includes(value)) return;\n throw new Error(\n `Unknown browser tier: ${String(value)}; choose from ${BROWSER_TIERS.join(\", \")}`,\n );\n}\n\nexport const DEFAULT_VIEWPORT = { width: 1280, height: 800 };\nconst SETTLE_TIMEOUT_MS = 5_000;\nconst SETTLE_QUIET_MS = 150;\nconst SETTLE_POLL_MS = 25;\n\nexport const EVENT_BATCH_SIZE = 10;\nexport const EVENT_FLUSH_INTERVAL_MS = 1_000;\nexport const EVENT_MAX_RETRIES = 3;\nconst EVENT_SCREENSHOT_QUALITY = 60;\nconst EVENT_MAX_STRING = 500;\n\nconst SECRET_KEY =\n /pass(word|wd)?|secret|token|api[-_]?key|authorization|cookie|(^|[-_ #.\\[\"'=])(otp|pin|cvv|ssn)([-_ \\]\"']|$)/i;\n/** What a call that lost its browser does once the browser is back: a read or\n * a navigation runs again (`retry`); an action that may already have reached\n * the world is not replayed, and the agent is told (`report`). */\ntype OnBrowserLoss = \"retry\" | \"report\";\n\nconst SECRET_VALUE =\n /^((sk|pk|ghp|xox[abp])[-_][-_A-Za-z0-9]{8,}|AKIA[0-9A-Z]{12,}|Bearer [-_.A-Za-z0-9]{8,})/;\n\n/** The `surfaces` block of a session descriptor, as the platform sends it. */\nexport type SessionSurfaces = {\n tools: { kind: \"rendezvous\" };\n api?: {\n url: string;\n /** Per-session credential of a World Host session: send it as\n * `Authorization: Bearer <token>` (the header only; a token in the URL is\n * refused). Absent when the world\n * itself answers with its declared auth (a pod or a customer-hosted twin). */\n token?: string;\n };\n ui?: {\n url: string;\n entry: string;\n /** Same-origin prefix the UI proxies to the world API, e.g. `/__world-api`;\n * null when the UI only reaches the API server-side. */\n apiPath?: string | null;\n /** Per-session credential of a World Host UI. A browser navigation cannot\n * carry a header, so the first page load presents it once as `?token=`\n * and the host answers with an HttpOnly cookie. Absent for pod UIs. */\n token?: string;\n };\n browser?: {\n wsUrl: string;\n /** `cdp`: the platform's Chromium relay (any number of agents share one\n * browser, each in its own context). `playwright`: a `run-server` endpoint. */\n protocol: \"cdp\" | \"playwright\";\n viewport: { width: number; height: number };\n /** The capacity tier the browser runs on; present for World Host sessions. */\n tier?: BrowserTier;\n };\n};\n\nexport class WorldSurfaceUnavailable extends Error {\n constructor(\n readonly surface: WorldSurfaceKind,\n reason: string,\n ) {\n super(`World surface '${surface}' is unavailable: ${reason}`);\n }\n}\n\nexport function surfaceKinds(s: SessionSurfaces): WorldSurfaceKind[] {\n const kinds: WorldSurfaceKind[] = [\"tools\"];\n if (s.api) kinds.push(\"api\");\n if (s.ui) kinds.push(\"ui\");\n if (s.browser) kinds.push(\"browser\");\n return kinds;\n}\n\nconst UI_TOKEN_QUERY = \"token\";\n\n/** The URL of `path` on a UI surface, carrying the session token when the\n * surface has one. `path` may already have a query string; the token is\n * appended to it. */\nexport function uiUrl(\n ui: NonNullable<SessionSurfaces[\"ui\"]>,\n path: string,\n): string {\n const base = ui.url.replace(/\\/+$/, \"\");\n const rel = path.startsWith(\"/\") ? path : `/${path}`;\n if (!ui.token) return base + rel;\n const [beforeHash, hash] = splitHash(rel);\n const joiner = beforeHash.includes(\"?\") ? \"&\" : \"?\";\n const query = `${UI_TOKEN_QUERY}=${encodeURIComponent(ui.token)}`;\n return base + beforeHash + joiner + query + hash;\n}\n\nexport function uiEntryUrl(ui: NonNullable<SessionSurfaces[\"ui\"]>): string {\n return uiUrl(ui, ui.entry || \"/\");\n}\n\n/** `url` without its `token` query parameter: what may be logged or shown. */\nexport function withoutUiToken(url: string): string {\n const [beforeHash, hash] = splitHash(url);\n const q = beforeHash.indexOf(\"?\");\n if (q < 0) return url;\n const kept = beforeHash\n .slice(q + 1)\n .split(\"&\")\n .filter((pair) => pair !== \"\" && pair.split(\"=\")[0] !== UI_TOKEN_QUERY);\n return (\n beforeHash.slice(0, q) + (kept.length ? `?${kept.join(\"&\")}` : \"\") + hash\n );\n}\n\nfunction splitHash(url: string): [string, string] {\n const h = url.indexOf(\"#\");\n return h < 0 ? [url, \"\"] : [url.slice(0, h), url.slice(h)];\n}\n\n/** The slice of a Playwright `Page` this module drives. */\nexport type BrowserPage = {\n url(): string;\n goto(url: string, opts?: { waitUntil?: \"load\" }): Promise<unknown>;\n click(selector: string): Promise<void>;\n fill(selector: string, value: string): Promise<void>;\n screenshot(opts?: {\n type?: \"png\" | \"jpeg\";\n quality?: number;\n fullPage?: boolean;\n }): Promise<Buffer>;\n innerText(selector: string): Promise<string>;\n content(): Promise<string>;\n goBack(opts?: { waitUntil?: \"load\" }): Promise<unknown>;\n waitForLoadState(state?: \"load\"): Promise<void>;\n waitForTimeout(ms: number): Promise<void>;\n on(\n event: \"request\" | \"requestfinished\" | \"requestfailed\",\n handler: (request: unknown) => void,\n ): unknown;\n title(): Promise<string>;\n keyboard: { press(key: string): Promise<void> };\n mouse: { wheel(dx: number, dy: number): Promise<void> };\n};\n\nexport type BrowserMode = \"auto\" | \"hosted\" | \"local\";\n\n// ── action events ────────────────────────────────────────────────────────────\n\n/** One browser action as the platform ingests it\n * (`POST /world-sessions/{id}/browser-events`). */\nexport type BrowserActionEvent = {\n agentId: string;\n seq: number;\n ts: string;\n action: string;\n args: Record<string, unknown>;\n ok: boolean;\n error: string | null;\n durationMs: number;\n url: string | null;\n title: string | null;\n mode: Exclude<BrowserMode, \"auto\">;\n viewport: { width: number; height: number };\n /** base64 JPEG of the screen after the action; null if it could not be taken. */\n screenshot: string | null;\n};\n\n/** What of an action's arguments may leave the process. Selectors, paths\n * and keys are what a reviewer needs; anything keyed like a credential, or\n * typed into a field whose selector names one, or shaped like a known key,\n * is replaced. Strings are capped, nested values dropped. */\nexport function redactActionArgs(\n action: string,\n args: Record<string, unknown>,\n): Record<string, unknown> {\n const secretField =\n action === \"browser_type\" && SECRET_KEY.test(String(args.selector ?? \"\"));\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(args)) {\n if (value === null || value === undefined) out[key] = null;\n else if (typeof value === \"boolean\" || typeof value === \"number\")\n out[key] = value;\n else if (typeof value === \"string\") {\n if (\n SECRET_KEY.test(key) ||\n SECRET_VALUE.test(value) ||\n (secretField && key === \"text\")\n )\n out[key] = \"[redacted]\";\n else\n out[key] =\n value.length <= EVENT_MAX_STRING\n ? value\n : value.slice(0, EVENT_MAX_STRING) + \"…\";\n } else out[key] = \"[omitted]\";\n }\n return out;\n}\n\n/**\n * Ships browser action events to the platform, off the action's hot path.\n *\n * `post` receives a batch of events (the request body's `events`). Events\n * are numbered here, so ordering survives batching and retries — the\n * platform dedups on `(agentId, seq)`. A batch that keeps failing is dropped\n * with a warning: telemetry must never stall or fail the agent.\n *\n * Numbering is durable across recorders: `nextSeq()` hands out a position\n * within this recorder, and the first send adds the base `resumeFrom`\n * reports — the platform's next free seq for this agent — so an agent id\n * reopened in a later process appends to its timeline instead of colliding\n * with (and being deduplicated against) what it already recorded. The base\n * is fixed once resolved, which keeps retries idempotent.\n */\nexport class BrowserActionRecorder {\n private seq = 0;\n private base: Promise<number> | null = null;\n private queue: BrowserActionEvent[] = [];\n private timer: ReturnType<typeof setTimeout> | null = null;\n private inflight: Promise<void> = Promise.resolve();\n sent = 0;\n dropped = 0;\n\n constructor(\n private readonly post: (events: BrowserActionEvent[]) => Promise<void>,\n readonly agentId: string,\n private readonly opts: {\n /** The platform's next free seq for `agentId`; 0 when not given. */\n resumeFrom?: () => Promise<number>;\n batchSize?: number;\n flushIntervalMs?: number;\n maxRetries?: number;\n sleep?: (ms: number) => Promise<void>;\n warn?: (message: string) => void;\n } = {},\n ) {}\n\n /** This recorder's next position; the wire seq is `resumeFrom() + this`. */\n nextSeq(): number {\n return this.seq++;\n }\n\n private resolveBase(): Promise<number> {\n if (this.base === null) {\n const resolve = this.opts.resumeFrom ?? (async () => 0);\n this.base = resolve().then((n) => {\n if (!Number.isInteger(n) || n < 0)\n throw new Error(\n `browser event base seq must be a non-negative integer, got ${String(n)}`,\n );\n return n;\n });\n // A failed lookup is retried with the batch, not remembered.\n this.base.catch(() => {\n this.base = null;\n });\n }\n return this.base;\n }\n\n record(event: BrowserActionEvent): void {\n this.queue.push(event);\n if (this.queue.length >= (this.opts.batchSize ?? EVENT_BATCH_SIZE)) {\n this.drain();\n } else if (this.timer === null) {\n this.timer = setTimeout(\n () => this.drain(),\n this.opts.flushIntervalMs ?? EVENT_FLUSH_INTERVAL_MS,\n );\n if (typeof this.timer === \"object\" && \"unref\" in this.timer)\n this.timer.unref();\n }\n }\n\n /** Resolve once everything recorded so far has been posted (or dropped). */\n async flush(): Promise<void> {\n this.drain();\n await this.inflight;\n }\n\n async close(): Promise<void> {\n await this.flush();\n }\n\n private drain(): void {\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n if (this.queue.length === 0) return;\n const batch = this.queue;\n this.queue = [];\n this.inflight = this.inflight.then(() => this.send(batch));\n }\n\n private async send(batch: BrowserActionEvent[]): Promise<void> {\n const retries = this.opts.maxRetries ?? EVENT_MAX_RETRIES;\n const sleep =\n this.opts.sleep ??\n ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));\n for (let attempt = 0; attempt < retries; attempt++) {\n try {\n const base = await this.resolveBase();\n await this.post(\n base === 0 ? batch : batch.map((e) => ({ ...e, seq: base + e.seq })),\n );\n this.sent += batch.length;\n return;\n } catch (error) {\n if (attempt + 1 === retries) {\n this.dropped += batch.length;\n (this.opts.warn ?? console.warn)(\n `dropping ${batch.length} browser events after ${attempt + 1} attempts: ${String(error)}`,\n );\n return;\n }\n await sleep(500 * 2 ** attempt);\n }\n }\n }\n}\n\n/**\n * One Playwright page on the session's UI. Thin on purpose — `page` is the\n * real Playwright page for anything this wrapper does not cover.\n */\nexport class WorldBrowser {\n private current: BrowserPage;\n private inflight = 0;\n private lastNetwork = Date.now();\n /** Where the page last was after an action, token stripped: what a\n * reconnect reopens. Null until the page has left `about:blank`. */\n private lastUrl: string | null = null;\n\n constructor(\n page: BrowserPage,\n readonly ui: SessionSurfaces[\"ui\"] | undefined,\n readonly mode: Exclude<BrowserMode, \"auto\">,\n private readonly teardown: () => Promise<void>,\n readonly viewport: { width: number; height: number } = DEFAULT_VIEWPORT,\n readonly recorder: BrowserActionRecorder | null = null,\n private readonly reconnector: BrowserReconnector | null = null,\n /** Takes session credentials out of every error this browser records. */\n private readonly scrubber: SecretScrubber = new SecretScrubber([ui?.token]),\n ) {\n this.current = page;\n this.watchNetwork(page);\n }\n\n /** The live Playwright page; a new object after a reconnect. */\n get page(): BrowserPage {\n return this.current;\n }\n\n get agentId(): string | null {\n return this.recorder?.agentId ?? null;\n }\n\n private watchNetwork(page: BrowserPage): void {\n page.on(\"request\", () => {\n this.inflight += 1;\n this.lastNetwork = Date.now();\n });\n const done = () => {\n this.inflight = Math.max(0, this.inflight - 1);\n this.lastNetwork = Date.now();\n };\n page.on(\"requestfinished\", done);\n page.on(\"requestfailed\", done);\n }\n\n /** Run `fn` against the page. If it fails because the browser is gone,\n * recover; then `retry` runs it ONCE more and `report` throws\n * `BrowserReconnected` instead of replaying it. Any other error, and a\n * second loss during the retry, propagate unchanged. */\n private async resilient<T>(\n fn: () => Promise<T>,\n onLoss: OnBrowserLoss,\n ): Promise<T> {\n try {\n return this.remember(await fn());\n } catch (error) {\n if (!this.reconnector || !isBrowserGone(error)) throw error;\n const recovered = await this.recover(this.reconnector, error);\n if (onLoss === \"report\")\n throw new BrowserReconnected(\n recovered.outcome,\n recovered.restoredUrl,\n error,\n );\n }\n return this.remember(await fn());\n }\n\n private remember<T>(result: T): T {\n this.lastUrl = this.openedUrl() ?? this.lastUrl;\n return result;\n }\n\n /** The page's URL less its token; null while it is blank. */\n private openedUrl(): string | null {\n const url = this.page.url();\n return url && url !== \"about:blank\" ? withoutUiToken(url) : null;\n }\n\n private async recover(\n reconnector: BrowserReconnector,\n cause: unknown,\n ): Promise<RecoveryResult & { restoredUrl: string | null }> {\n const started = Date.now();\n const message = cause instanceof Error ? cause.message : String(cause);\n const args = { cause: this.scrubber.scrub(message).slice(0, 200) };\n let result: RecoveryResult;\n try {\n result = await reconnector.recover(cause, (c) => this.adopt(c));\n } catch (error) {\n await this.report(\"browser_reconnect\", args, started, error);\n throw error;\n }\n const restoredUrl = this.openedUrl();\n await this.report(\n \"browser_reconnect\",\n { ...args, ...result, restoredUrl },\n started,\n null,\n );\n return { ...result, restoredUrl };\n }\n\n /** Take over a new connection's page and reopen the page the agent was on\n * (`openBrowser` owns the connection itself). A new browser has no session\n * cookie, so a World Host UI is first loaded with its token, exactly as\n * `goto()` loads the entry page. */\n private async adopt(connection: BrowserConnection): Promise<void> {\n this.current = connection.page;\n this.inflight = 0;\n this.watchNetwork(connection.page);\n const last = this.lastUrl;\n if (!last) return;\n if (this.ui?.token)\n await this.page.goto(uiEntryUrl(this.ui), { waitUntil: \"load\" });\n if (withoutUiToken(this.page.url()) !== last)\n await this.page.goto(last, { waitUntil: \"load\" });\n await this.settle();\n }\n\n /** Run one action and report it: the event carries what was asked,\n * whether it worked, and the screen after — for failures too, so a\n * reviewer sees what the agent saw when the selector did not match. */\n private async act<T>(\n action: string,\n args: Record<string, unknown>,\n fn: () => Promise<T>,\n onLoss: OnBrowserLoss = \"report\",\n ): Promise<T> {\n const started = Date.now();\n try {\n const result = await this.resilient(fn, onLoss);\n await this.report(action, args, started, null);\n return result;\n } catch (error) {\n await this.report(action, args, started, error);\n throw error;\n }\n }\n\n /** One event on the recorder, if there is one; `failure` null means ok. */\n private async report(\n action: string,\n args: Record<string, unknown>,\n started: number,\n failure: unknown,\n ): Promise<void> {\n const recorder = this.recorder;\n if (!recorder) return;\n const error =\n failure === null\n ? null\n : this.scrubber\n .scrub(\n failure instanceof Error\n ? `${failure.name}: ${failure.message}`\n : String(failure),\n )\n .slice(0, 4000);\n recorder.record({\n agentId: recorder.agentId,\n seq: recorder.nextSeq(),\n ts: new Date().toISOString(),\n action,\n args: redactActionArgs(action, args),\n ok: failure === null,\n error,\n durationMs: Date.now() - started,\n mode: this.mode,\n viewport: { ...this.viewport },\n ...(await this.observeForEvent()),\n });\n }\n\n private async observeForEvent(): Promise<\n Pick<BrowserActionEvent, \"url\" | \"title\" | \"screenshot\">\n > {\n const out: Pick<BrowserActionEvent, \"url\" | \"title\" | \"screenshot\"> = {\n url: null,\n title: null,\n screenshot: null,\n };\n try {\n out.url = this.page.url();\n out.title = await this.page.title();\n const jpeg = await this.page.screenshot({\n type: \"jpeg\",\n quality: EVENT_SCREENSHOT_QUALITY,\n });\n out.screenshot = jpeg.toString(\"base64\");\n } catch {\n // a closed page still gets its event\n }\n return out;\n }\n\n /** Open a UI path (`/customers`), a full URL, or — with no argument — the\n * UI's declared entry page. */\n async goto(pathOrUrl?: string): Promise<string> {\n let target: string;\n if (pathOrUrl === undefined) {\n if (!this.ui)\n throw new WorldSurfaceUnavailable(\n \"ui\",\n \"this session has no UI to navigate to\",\n );\n target = uiEntryUrl(this.ui);\n } else if (/^https?:\\/\\//.test(pathOrUrl)) {\n target = pathOrUrl;\n } else {\n if (!this.ui)\n throw new WorldSurfaceUnavailable(\n \"ui\",\n \"relative paths need a UI surface\",\n );\n target = uiUrl(this.ui, pathOrUrl);\n }\n return this.act(\n \"browser_goto\",\n { path: pathOrUrl ?? null, url: withoutUiToken(target) },\n async () => {\n await this.page.goto(target, { waitUntil: \"load\" });\n await this.settle();\n return this.page.url();\n },\n // Navigating again lands on the same page: safe to replay.\n \"retry\",\n );\n }\n\n async back(): Promise<string> {\n return this.act(\"browser_back\", {}, async () => {\n await this.page.goBack({ waitUntil: \"load\" });\n await this.settle();\n return this.page.url();\n });\n }\n\n /** Wait for the page to finish reacting to an action. `load` alone is not\n * enough for client-rendered UIs (React et al.): a click returns before the\n * fetch that re-renders the page, so an agent would read stale text.\n * Playwright's `networkidle` is per navigation and resolves at once after\n * the first one, so this tracks requests itself: done when nothing is in\n * flight and the network has been quiet for `SETTLE_QUIET_MS`, bounded so\n * long-polling UIs cannot hang us. */\n private async settle(): Promise<void> {\n await this.page.waitForLoadState(\"load\");\n const deadline = Date.now() + SETTLE_TIMEOUT_MS;\n while (Date.now() < deadline) {\n const quiet = Date.now() - this.lastNetwork >= SETTLE_QUIET_MS;\n if (this.inflight === 0 && quiet) return;\n await this.page.waitForTimeout(SETTLE_POLL_MS);\n }\n }\n\n async click(selector: string): Promise<void> {\n await this.act(\"browser_click\", { selector }, async () => {\n await this.page.click(selector);\n await this.settle();\n });\n }\n\n async type(selector: string, text: string): Promise<void> {\n await this.act(\"browser_type\", { selector, text }, () =>\n this.page.fill(selector, text),\n );\n }\n\n async press(key: string): Promise<void> {\n await this.act(\"browser_press\", { key }, async () => {\n await this.page.keyboard.press(key);\n await this.settle();\n });\n }\n\n async scroll(dy: number): Promise<void> {\n await this.act(\"browser_scroll\", { dy }, () =>\n this.page.mouse.wheel(0, dy),\n );\n }\n\n async screenshot(fullPage = false): Promise<Buffer> {\n return this.resilient(\n () => this.page.screenshot({ type: \"png\", fullPage }),\n \"retry\",\n );\n }\n\n async screenshotBase64(fullPage = false): Promise<string> {\n return (await this.screenshot(fullPage)).toString(\"base64\");\n }\n\n async text(selector = \"body\"): Promise<string> {\n return this.resilient(() => this.page.innerText(selector), \"retry\");\n }\n\n async html(): Promise<string> {\n return this.resilient(() => this.page.content(), \"retry\");\n }\n\n get url(): string {\n return this.page.url();\n }\n\n async title(): Promise<string> {\n return this.resilient(() => this.page.title(), \"retry\");\n }\n\n async close(): Promise<void> {\n try {\n await this.teardown();\n } finally {\n await this.recorder?.close();\n }\n }\n}\n\n/** The Playwright entry points this module needs, so tests can inject a fake. */\nexport type PlaywrightLike = {\n chromium: {\n connect(wsEndpoint: string): Promise<PlaywrightBrowserLike>;\n connectOverCDP(endpointURL: string): Promise<PlaywrightBrowserLike>;\n launch(opts?: { headless?: boolean }): Promise<PlaywrightBrowserLike>;\n };\n};\n\nexport type PlaywrightBrowserLike = {\n newContext(opts?: {\n viewport?: { width: number; height: number };\n }): Promise<{ newPage(): Promise<BrowserPage>; close(): Promise<void> }>;\n close(): Promise<void>;\n};\n\nasync function loadPlaywright(): Promise<PlaywrightLike> {\n try {\n // A string specifier keeps bundlers from resolving the optional peer.\n const name = \"playwright\";\n return (await import(name)) as PlaywrightLike;\n } catch (error) {\n throw new Error(\n \"Driving a world UI needs Playwright: npm install playwright \" +\n \"(and `npx playwright install chromium` for local mode).\",\n { cause: error },\n );\n }\n}\n\nexport function resolveBrowserMode(\n surfaces: SessionSurfaces,\n mode: BrowserMode,\n): Exclude<BrowserMode, \"auto\"> {\n if (!surfaces.ui && !surfaces.browser)\n throw new WorldSurfaceUnavailable(\n \"ui\",\n \"open the session with surfaces: ['ui'] on a world that declares [ui]\",\n );\n const resolved =\n mode === \"auto\" ? (surfaces.browser ? \"hosted\" : \"local\") : mode;\n if (resolved === \"hosted\" && !surfaces.browser)\n throw new WorldSurfaceUnavailable(\n \"browser\",\n \"open the session with surfaces: ['browser'] to get a hosted browser\",\n );\n return resolved;\n}\n\n/** Open a browser on the session's UI in `hosted`, `local` or `auto` mode. */\nexport async function openBrowser(\n surfaces: SessionSurfaces,\n opts: {\n mode?: BrowserMode;\n headless?: boolean;\n playwright?: PlaywrightLike;\n recorder?: BrowserActionRecorder | null;\n /** The session's repair call (`session.repairBrowser`). Given, a hosted\n * `cdp` browser reconnects on its own when the browser is lost. */\n repair?: () => Promise<RepairAnswer>;\n } = {},\n): Promise<WorldBrowser> {\n const mode = resolveBrowserMode(surfaces, opts.mode ?? \"auto\");\n const pw = opts.playwright ?? (await loadPlaywright());\n const viewport = surfaces.browser?.viewport ?? DEFAULT_VIEWPORT;\n const attach = async (): Promise<BrowserConnection> => {\n const browser =\n mode === \"hosted\"\n ? surfaces.browser!.protocol === \"playwright\"\n ? await pw.chromium.connect(surfaces.browser!.wsUrl)\n : await pw.chromium.connectOverCDP(surfaces.browser!.wsUrl)\n : await pw.chromium.launch({ headless: opts.headless ?? true });\n const context = await browser.newContext({ viewport });\n return { browser, context, page: await context.newPage() };\n };\n let live = await attach();\n /** The same address again; the lost connection is released once a new one\n * stands. */\n const reattach = async (): Promise<BrowserConnection> => {\n const fresh = await attach();\n await releaseConnection(live);\n live = fresh;\n return fresh;\n };\n // A browser error quotes the URL it failed on; these carry the session.\n const scrubber = new SecretScrubber([\n surfaces.browser?.wsUrl,\n surfaces.ui?.token,\n ]);\n // Only the platform's relay can be repaired behind the same address.\n const reconnector =\n mode === \"hosted\" && surfaces.browser!.protocol === \"cdp\" && opts.repair\n ? new BrowserReconnector(opts.repair, reattach, {\n scrub: (text) => scrubber.scrub(text),\n })\n : null;\n return new WorldBrowser(\n live.page,\n surfaces.ui,\n mode,\n () => closeConnection(live),\n viewport,\n opts.recorder ?? null,\n reconnector,\n scrubber,\n );\n}\n\n// ── computer-use tools ───────────────────────────────────────────────────────\n\nexport const COMPUTER_USE_SPECS = [\n {\n name: \"browser_goto\",\n signature: \"browser_goto(path=None)\",\n doc: \"Open a page of the world's UI. `path` is a UI path like /customers, a full URL, or omitted for the entry page. Returns the URL and page text.\",\n },\n {\n name: \"browser_click\",\n signature: \"browser_click(selector)\",\n doc: \"Click an element by Playwright selector (CSS, `text=Refund`, `role=button[name=Save]`). Returns the page text after the click.\",\n },\n {\n name: \"browser_type\",\n signature: \"browser_type(selector, text)\",\n doc: \"Replace the value of an input/textarea found by selector with `text`.\",\n },\n {\n name: \"browser_press\",\n signature: \"browser_press(key)\",\n doc: \"Press a key (Enter, Tab, Escape, ArrowDown, ...). Returns the page text after.\",\n },\n {\n name: \"browser_scroll\",\n signature: \"browser_scroll(dy=600)\",\n doc: \"Scroll the page vertically by `dy` pixels (negative scrolls up).\",\n },\n {\n name: \"browser_screenshot\",\n signature: \"browser_screenshot(full_page=False)\",\n doc: \"Take a PNG screenshot; returns {image_base64, url}.\",\n },\n {\n name: \"browser_read\",\n signature: \"browser_read(selector='body')\",\n doc: \"Return the visible text of an element (default: whole page) plus the URL and title.\",\n },\n {\n name: \"browser_back\",\n signature: \"browser_back()\",\n doc: \"Go back one page in history.\",\n },\n] as const;\n\nconst str = (v: unknown, fallback: string): string =>\n typeof v === \"string\" && v.length > 0 ? v : fallback;\n\n/**\n * The browser as model tools, in the same `WorldToolkit` shape the world's\n * own tools come in — so an agent loop that already dispatches\n * `toolkit().impls` merges `computerUseToolkit(b).impls` and gains a screen\n * without a second dispatch path.\n */\nexport function computerUseToolkit(\n browser: WorldBrowser,\n opts: { maxText?: number } = {},\n): WorldToolkit {\n const maxText = opts.maxText ?? 20_000;\n const observe = async (selector = \"body\") => {\n const text = await browser.text(selector);\n return {\n url: browser.url,\n title: await browser.title(),\n text: text.slice(0, maxText),\n truncated: text.length > maxText,\n };\n };\n\n const impls: WorldToolkit[\"impls\"] = {\n browser_goto: async (a) => {\n await browser.goto(typeof a.path === \"string\" ? a.path : undefined);\n return observe();\n },\n browser_click: async (a) => {\n await browser.click(str(a.selector, \"\"));\n return observe();\n },\n browser_type: async (a) => {\n await browser.type(str(a.selector, \"\"), String(a.text ?? \"\"));\n return { ok: true, url: browser.url };\n },\n browser_press: async (a) => {\n await browser.press(str(a.key, \"Enter\"));\n return observe();\n },\n browser_scroll: async (a) => {\n await browser.scroll(typeof a.dy === \"number\" ? a.dy : 600);\n return { ok: true, url: browser.url };\n },\n browser_screenshot: async (a) => ({\n image_base64: await browser.screenshotBase64(a.full_page === true),\n url: browser.url,\n }),\n browser_read: async (a) => observe(str(a.selector, \"body\")),\n browser_back: async () => {\n await browser.back();\n return observe();\n },\n };\n\n const specs = COMPUTER_USE_SPECS.map((s) => ({ ...s }));\n return {\n schemas: specs.map((spec) => schemaFromSignature(spec)),\n impls,\n specs,\n };\n}\n","/**\n * THE NUMBERS AND WORDS A WORLD SESSION PROMISES — the TypeScript SDK twin.\n *\n * The platform declares them once in\n * `gateway/packages/shared/src/server/services/worldSessionContract.ts`; this\n * module and `gatewaysdk/environment/world_session_contract.py` repeat them, and each is\n * pinned to `conformance/world-sessions.json` by a test, so the route, the\n * World Host and the two CLIs cannot drift apart.\n */\n\n/** The largest body `POST world-sessions/{id}/calls` accepts. The SDK\n * measures the serialized body against the byte count and refuses before\n * sending; the label is what help and the refusal name. */\nexport const CALL_BODY_LIMIT_BYTES = 4 * 1024 * 1024;\nexport const CALL_BODY_LIMIT_LABEL = \"4mb\";\n\n/** `session status` warns once an unpinned session has less than this left. */\nexport const IDLE_WARNING_MINUTES = 5;\n\n/** The task an exploratory session runs on when the caller names none, and\n * the `task.source` the platform reports for it. */\nexport const EXPLORATORY_TASK = Object.freeze({\n instruction: \"exploratory session\",\n});\nexport const EXPLORATORY_TASK_SOURCE = \"none\";\n\n/** What a session that has no grader answers `grade` with, beside\n * `reward: null`. */\nexport const NO_GRADER_REASON = \"no grader\";\n\n/** The call's body exceeds the platform's limit: nothing was sent. `limit`\n * is the label the route enforces (`4mb`), `size` the body's bytes. */\nexport class WorldCallTooLarge extends Error {\n readonly code = \"payload_too_large\";\n\n constructor(\n readonly size: number,\n readonly limitBytes: number = CALL_BODY_LIMIT_BYTES,\n readonly limit: string = CALL_BODY_LIMIT_LABEL,\n ) {\n super(\n `call body is ${size} bytes; the platform accepts at most ${limit} (${limitBytes} bytes)`,\n );\n this.name = \"WorldCallTooLarge\";\n }\n\n /** The structured refusal the CLIs print. */\n toJSON(): {\n status: \"error\";\n code: \"payload_too_large\";\n limit: string;\n size: number;\n } {\n return {\n status: \"error\",\n code: this.code,\n limit: this.limit,\n size: this.size,\n };\n }\n}\n\n/** Measure a call body the way the route will and refuse an oversized one\n * before it leaves the machine. Returns the serialized body. */\nexport function serializeCallBody(body: unknown): string {\n const text = JSON.stringify(body);\n const size = Buffer.byteLength(text, \"utf8\");\n if (size > CALL_BODY_LIMIT_BYTES) throw new WorldCallTooLarge(size);\n return text;\n}\n\n/** The line `session status` prints when an unpinned session has under\n * `IDLE_WARNING_MINUTES` left, else null. `now` is for tests. */\nexport function idleWarning(\n idleExpiresAt: string | null | undefined,\n now: Date = new Date(),\n): string | null {\n if (!idleExpiresAt) return null;\n const leftMs = new Date(idleExpiresAt).getTime() - now.getTime();\n if (leftMs >= IDLE_WARNING_MINUTES * 60_000) return null;\n const minutes = Math.max(0, Math.floor(leftMs / 60_000));\n return (\n `warning: session expires in ${minutes}m (idle TTL); ` +\n \"call a tool to extend it or `gateway worlds session pin` to keep it\"\n );\n}\n","import type {\n WorldSessionTask,\n WorldTaskIdRef,\n WorldTaskRef,\n WorldTaskSpec,\n} from \"./session\";\n\n/**\n * The three shapes a task reaches `openSession` in — a bundled scenario's\n * name, a stored task's `{ id, version? }`, an inline spec — and how each is\n * told apart, labelled and checked. No task at all (`undefined`) is the\n * fourth case, an exploratory session, and is not a ref.\n */\n\nexport const isTaskIdRef = (task: WorldTaskRef): task is WorldTaskIdRef =>\n typeof task === \"object\" && task !== null && \"id\" in task;\n\nexport const isTaskSpec = (task: WorldTaskRef): task is WorldTaskSpec =>\n typeof task === \"object\" && task !== null && \"instruction\" in task;\n\n/** The label a task goes by in results: its name, `inline:<hash>` for an\n * unnamed inline task once the platform has hashed it, or the stored task's\n * name (its id until the platform has answered). */\nexport const taskLabel = (\n task: WorldTaskRef,\n info?: WorldSessionTask | null,\n): string => {\n if (typeof task === \"string\") return task;\n if (isTaskIdRef(task)) return info?.name ?? task.id;\n if (task.name) return task.name;\n return info?.hash ? `inline:${info.hash.slice(0, 12)}` : \"inline\";\n};\n\n/** A task given to `openSession` must be one of the three shapes. */\nexport const assertTaskRef = (task: WorldTaskRef): void => {\n const malformed =\n task === null ||\n (typeof task === \"string\" && !task) ||\n (isTaskIdRef(task) && !task.id) ||\n (isTaskSpec(task) && !task.instruction) ||\n (typeof task === \"object\" && !isTaskIdRef(task) && !isTaskSpec(task));\n if (malformed)\n throw new Error(\n \"openSession needs a task: a bundled task name, a stored task { id, version? } or { instruction, seed?, grader?, metadata? } — or none at all for an exploratory session\",\n );\n};\n","import { randomUUID } from \"node:crypto\";\n\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\nimport {\n BrowserActionRecorder,\n SURFACE_KINDS,\n WorldSurfaceUnavailable,\n assertBrowserTier,\n computerUseToolkit,\n openBrowser,\n uiEntryUrl,\n type BrowserActionEvent,\n type BrowserMode,\n type BrowserTier,\n type PlaywrightLike,\n type SessionSurfaces,\n type WorldBrowser,\n type WorldSurfaceKind,\n} from \"./browser\";\nimport type { RepairAnswer } from \"./browserReconnect\";\nimport type { WorldTaskSummary } from \"./tasks\";\nimport { serializeCallBody } from \"./sessionContract\";\nimport { assertTaskRef, isTaskIdRef, isTaskSpec, taskLabel } from \"./taskRef\";\n\nexport { isTaskIdRef, isTaskSpec, taskLabel } from \"./taskRef\";\n\n/**\n * LIVE WORLD SESSIONS from TypeScript: your agent, the platform's container.\n *\n * The other two ways of running a world each give up something. Pulling the\n * bundle and executing it locally tests your agent against a COPY — your\n * python, your sqlite, your machine's idea of the environment. Dispatching a\n * hosted run gives you the real container but runs the platform's agent\n * inside it, so your agent never touches the world.\n *\n * A session is both: the platform boots the task's container and holds it\n * warm, and every `call()` here executes inside THAT container. Your agent\n * stays where it is — this file is just the wire.\n *\n * const world = await openWorld(\"revenue-ops-sim@main\");\n * const session = await openSession(world.slug, { task: \"revops-mara-dedupe-contacts\" });\n * await session.ready(); // wait for the container\n * await session.call(\"crm_search\", { entity: \"deals\" });\n * const { reward, rewards } = await session.grade();\n * await session.close({ keepWarm: true }); // hand it back to the pool\n *\n * The task can also be YOURS rather than the bundle's — an instruction, the\n * rows the session starts with and how it is graded, for one end user:\n *\n * const session = await openSession(\"acme-billing@main\", {\n * task: {\n * instruction: \"Mark invoice INV-7 as paid.\",\n * seed: { rows: { invoices: [{ id: \"INV-7\", status: \"open\" }] } },\n * grader: { kind: \"assertions\", checks: [\n * { entity: \"invoices\", where: { id: \"INV-7\", status: \"paid\" } },\n * ] },\n * metadata: { externalUserId: \"u_42\" },\n * },\n * surfaces: [\"api\"],\n * });\n *\n * Every call is a row on the platform before it is an effect in a container,\n * so the episode is on the record — and the platform traces the session\n * itself, which is why these sessions show up under Sessions without the\n * caller instrumenting anything.\n */\n\nexport type WorldToolSpec = {\n name: string;\n /** The world's own signature, e.g. `crm_search(q=None, entity=\"deals\")`. */\n signature: string;\n doc: string | null;\n inputSchema?: Record<string, unknown>;\n};\n\n/** What a model needs to call a world: the schemas to advertise, and the\n * implementations that run them in the container. */\nexport type WorldToolkit = {\n /** OpenAI-shaped tool definitions, derived from the world's signatures. */\n schemas: {\n type: \"function\";\n function: {\n name: string;\n description: string;\n parameters: Record<string, unknown>;\n };\n }[];\n /** name -> implementation, each one a call into THIS session. */\n impls: Record<string, (args: Record<string, unknown>) => Promise<unknown>>;\n specs: WorldToolSpec[];\n};\n\n// ── tasks ────────────────────────────────────────────────────────────────────\n\n/** A JSON scalar: what `where` filters and field predicates compare against. */\nexport type WorldTaskScalar = string | number | boolean | null;\n\n/** The rows a task starts the session with — the `seed()` contract, applied\n * by the host right after it clones the version's snapshot. `append`\n * (default) upserts by primary key onto the base data; `replace` makes the\n * named entities hold exactly these rows. */\nexport type WorldTaskSeed = {\n mode?: \"append\" | \"replace\";\n /** Redaction on the way in: `off` (default) stores the rows as given,\n * `apply` runs the world's `[redact]` policy over them first, `refuse`\n * rejects a row carrying plaintext in a redacted field. */\n redact?: \"off\" | \"apply\" | \"refuse\";\n rows: Record<string, Record<string, unknown>[]>;\n};\n\nexport type WorldTaskFieldOp =\n \"eq\" | \"neq\" | \"in\" | \"gt\" | \"gte\" | \"lt\" | \"lte\" | \"contains\";\n\n/**\n * One declarative check over the session's final rows. `where` selects rows\n * of `entity` by equality (dotted paths reach into nested objects); the\n * assertion says what must hold of the selection:\n *\n * exists (default) / absent at least one row / none\n * count `count` bound on how many\n * all / any `field op value` on every / some selected row\n *\n * A check's `id` names its entry in `rewards`; the task's reward is the\n * weighted share of checks that passed.\n */\nexport type WorldTaskCheck = {\n id?: string;\n weight?: number;\n entity: string;\n where?: Record<string, WorldTaskScalar>;\n assert?: \"exists\" | \"absent\" | \"count\" | \"all\" | \"any\";\n count?: { eq?: number; gte?: number; lte?: number };\n field?: string;\n op?: WorldTaskFieldOp;\n value?: WorldTaskScalar | WorldTaskScalar[];\n};\n\n/** One thing a rubric judge scores in [0, 1]; `id` names its entry in\n * `rewards`, `weight` (default 1) its share of the task's reward. */\nexport type WorldTaskRubricCriterion = {\n id: string;\n description: string;\n weight?: number;\n};\n\n/** A rubric is prose: what a good outcome looks like. The platform (never the\n * host) has a model read the session's final state and its call log against\n * it; the project's default evaluation model judges unless `model` pins one.\n * `grade()` then resolves asynchronously — `pending: true` first, the reward\n * once the judge has answered. */\nexport type WorldTaskRubricGrader = {\n kind: \"rubric\";\n rubric: string;\n criteria?: WorldTaskRubricCriterion[];\n model?: { provider: string; model: string };\n};\n\n/** How a task is graded: checks the host evaluates in-process, a `verify.py`\n * body (state JSON on stdin, last stdout line `{reward, ...}`) run through the\n * host's confined verifier, or a rubric judged by a model on the platform. */\nexport type WorldTaskGrader =\n | { kind: \"assertions\"; checks: WorldTaskCheck[] }\n | { kind: \"python\"; source: string; timeoutSeconds?: number }\n | WorldTaskRubricGrader;\n\n/** A task supplied at open, for one session, instead of a bundled scenario.\n * `instruction` is what the agent is told; without `seed` the session starts\n * on the version's base data, without `grader` `grade()` answers\n * `reward: null`; `tools` is the allow-list of the version's tools the agent\n * may call in this session (unset: all of them; a call outside it is refused\n * and logged); `metadata` is yours (an end-user id, a ticket) and is echoed\n * on the session, never read. Limits: shared/domain/worldTasks.ts. */\nexport type WorldTaskSpec = {\n name?: string;\n instruction: string;\n seed?: WorldTaskSeed;\n grader?: WorldTaskGrader;\n tools?: string[];\n metadata?: Record<string, unknown>;\n /** A MULTI-WORLD task: one session per alias, each on its own world with\n * its own seed, grader and tools (the top-level three are then refused).\n * Brought up together by `openTask` / `gateway worlds task up`; see\n * worlds/taskSessions.ts. */\n worlds?: Record<\n string,\n {\n slug: string;\n /** One of the world's refs; default `main`. */\n ref?: string;\n seed?: WorldTaskSeed;\n grader?: WorldTaskGrader;\n tools?: string[];\n }\n >;\n /** CROSS-WORLD VERIFIERS: deterministic graders over several of the task's\n * worlds at once, each with a `scope` of aliases (two or more). One runs on\n * the session of the first alias in its scope, over a state where every\n * scoped world's rows are `<alias>.<entity>` and its calls `<alias>.calls`;\n * the platform gathers the other worlds' evidence when `grade()` names\n * them (`TaskSessions.grade` does). Rewards come back as `x.<name>`. */\n verifiers?: WorldTaskVerifier[];\n};\n\nexport type WorldTaskVerifier = { name: string; scope: string[] } & (\n | { kind: \"assertions\"; checks: WorldTaskCheck[] }\n | { kind: \"python\"; source: string; timeoutSeconds?: number }\n);\n\n/** A stored task of the project (see worlds/tasks.ts), opened by id; the\n * session runs a copy of one version's spec — the current one by default. */\nexport type WorldTaskIdRef = { id: string; version?: number };\n\n/** What `openSession` takes as the task: a bundled scenario's name, a\n * stored task's `{ id, version? }`, or an inline spec. */\nexport type WorldTaskRef = string | WorldTaskIdRef | WorldTaskSpec;\n\n/** What a session's task is, on every session response. `hash` is the\n * content hash of the spec (inline or stored) — what warm reuse matches on;\n * `id`/`version` name the stored task the session was opened on. */\nexport type WorldSessionTask = {\n /** `none` is an exploratory session: opened with no task, no grader. */\n source: \"bundled\" | \"inline\" | \"stored\" | \"none\";\n name: string | null;\n hash: string | null;\n id?: string | null;\n version?: number | null;\n metadata: Record<string, unknown>;\n};\n\nexport type SeedResult = {\n seeded: number;\n mode: \"append\" | \"replace\";\n entity_counts: Record<string, number>;\n};\n\n/** One row of the session's call log. */\nexport type WorldSessionCall = {\n seq: number;\n kind: string;\n tool: string | null;\n args: unknown;\n result: unknown;\n error: string | null;\n completedAt: string | null;\n};\n\nexport type WorldSessionState = {\n sessionId: string;\n state: string;\n ready: boolean;\n versionId: string;\n contentHash: string;\n taskName: string | null;\n /** Where the task came from and what it is; absent on platforms that\n * predate session tasks, in which case it is derived from `taskName`. */\n task?: WorldSessionTask;\n /** The task's objective — present when the session was opened (not on a\n * bare status read), so a client never needs the bundle on disk. */\n instruction?: string | null;\n /** The tools this task serves. */\n tools?: WorldToolSpec[];\n /** When the fleet reaps this session unless a call lands first; null for\n * a pinned session (never reaped). Absent on platforms that predate it. */\n idleExpiresAt?: string | null;\n pinned?: boolean;\n /** Where the session answers besides `tools` — see worlds/browser.ts. */\n surfaces?: SessionSurfaces;\n /** Notices about the world's shape (an api bundle is a deprecated layout;\n * schema worlds are the supported shape), with what to run instead. Empty\n * for a schema world; absent on platforms that predate the notice. */\n deprecations?: WorldDeprecation[];\n};\n\n/** One notice a worlds-path answer carries: a deprecated shape or layout\n * and the command that replaces it. A retired shape is refused instead,\n * with the stable message prefix `world_kind_retired:`. */\nexport type WorldDeprecation = {\n code: string;\n message: string;\n replacement: string;\n};\n\nexport type GradeResult = {\n reward: number | null;\n rewards: Record<string, number>;\n /** Why there is no reward: `no grader` on an exploratory session. */\n reason?: string;\n /** The task's cross-world verifiers anchored on this session, by name:\n * each its own reward and named rewards, or `error` when it could not\n * grade (evidence missing, verify.py failed) — null, never zero. */\n verifiers?: Record<string, VerifierGrade>;\n raw: unknown;\n};\n\nexport type VerifierGrade = {\n reward: number | null;\n rewards: Record<string, number>;\n error?: string;\n};\n\n/** A grade payload's numbers: `reward`, and every numeric key under\n * `rewards` (the host's shape) or at the top level (a bundled verifier's). */\nfunction numericGrade(record: Record<string, unknown>): {\n reward: number | null;\n rewards: Record<string, number>;\n} {\n const rewards: Record<string, number> = {};\n const nested = record.rewards;\n if (nested && typeof nested === \"object\") {\n for (const [key, value] of Object.entries(nested)) {\n if (typeof value === \"number\") rewards[key] = value;\n }\n }\n for (const [key, value] of Object.entries(record)) {\n if (key !== \"reward\" && typeof value === \"number\") rewards[key] = value;\n }\n return {\n reward: typeof record.reward === \"number\" ? record.reward : null,\n rewards,\n };\n}\n\n/** The `verifiers` block of a grade payload, or undefined when absent. */\nfunction verifierGrades(\n value: unknown,\n): Record<string, VerifierGrade> | undefined {\n if (!value || typeof value !== \"object\") return undefined;\n const out: Record<string, VerifierGrade> = {};\n for (const [name, grade] of Object.entries(value as Record<string, unknown>)) {\n const record =\n grade && typeof grade === \"object\"\n ? (grade as Record<string, unknown>)\n : {};\n out[name] = {\n ...numericGrade(record),\n ...(typeof record.error === \"string\" ? { error: record.error } : {}),\n };\n }\n return out;\n}\n\n/** How long `ready()` waits, and how often it asks. */\nconst READY_TIMEOUT_MS = 10 * 60_000;\nconst READY_POLL_MS = 2_000;\n/** How long one call may take end to end (container claim + execution). */\nconst CALL_TIMEOUT_MS = 3 * 60_000;\nconst CALL_POLL_MS = 400;\n/** How long a grade the platform's judge finalizes may take: the model's own\n * timeout and retries, plus the worker's queue backoff. Polled slowly. */\nconst JUDGED_GRADE_TIMEOUT_MS = 15 * 60_000;\nconst JUDGED_GRADE_POLL_MS = 2_000;\nconst EXPORT_PAGE = 500;\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\nexport const modelToolName = (name: string): string =>\n name.replace(/[^A-Za-z0-9_-]/g, \"_\").slice(0, 64) || \"tool\";\n\n/**\n * Turn a world's Python signature into a JSON schema the model can call.\n *\n * `crm_update_deal(id, stage=None, owner=None, amount=None)` becomes an\n * object with `id` required and the rest optional. Types are read from the\n * DEFAULTS the world declares — a numeric default means a number, a boolean\n * default a boolean — because that is the only type information a signature\n * actually carries. Everything else is a string, which is what a tool CLI\n * receives anyway.\n */\nexport function schemaFromSignature(spec: WorldToolSpec): {\n type: \"function\";\n function: {\n name: string;\n description: string;\n parameters: Record<string, unknown>;\n };\n} {\n if (spec.inputSchema)\n return {\n type: \"function\",\n function: {\n name: modelToolName(spec.name),\n description: spec.doc ?? spec.name,\n parameters: spec.inputSchema,\n },\n };\n const inside = /\\(([\\s\\S]*)\\)\\s*$/.exec(spec.signature.trim())?.[1] ?? \"\";\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n // Split on top-level commas only: a default like `{\"a\": 1}` has its own.\n const params: string[] = [];\n let depth = 0;\n let current = \"\";\n for (const ch of inside) {\n if (\"([{\".includes(ch)) depth++;\n if (\")]}\".includes(ch)) depth--;\n if (ch === \",\" && depth === 0) {\n params.push(current);\n current = \"\";\n } else current += ch;\n }\n if (current.trim()) params.push(current);\n\n for (const raw of params) {\n const param = raw.trim();\n if (!param || param.startsWith(\"*\") || param === \"self\") continue;\n const eq = param.indexOf(\"=\");\n const name = (eq === -1 ? param : param.slice(0, eq)).split(\":\")[0].trim();\n if (!name) continue;\n if (eq === -1) {\n properties[name] = { type: \"string\" };\n required.push(name);\n continue;\n }\n const value = param.slice(eq + 1).trim();\n if (/^-?\\d+(\\.\\d+)?$/.test(value)) properties[name] = { type: \"number\" };\n else if (value === \"True\" || value === \"False\")\n properties[name] = { type: \"boolean\" };\n else properties[name] = { type: \"string\" };\n }\n return {\n type: \"function\",\n function: {\n name: modelToolName(spec.name),\n description: spec.doc ?? spec.name,\n parameters: { type: \"object\", properties, required },\n },\n };\n}\n\nexport class WorldSessionTimeout extends Error {}\nexport class WorldSessionCallError extends Error {}\n\nexport class WorldSession {\n constructor(\n readonly sessionId: string,\n private current: WorldSessionState,\n private readonly options: WorldsClientOptions,\n ) {}\n\n /** The task's display name: a bundled scenario's, or the inline spec's\n * `name` (null when the spec was unnamed). `task` is the same. */\n get taskName(): string | null {\n return this.current.taskName;\n }\n get task(): string | null {\n return this.taskName;\n }\n\n /** `{idleExpiresAt, pinned}` as of the last state read: when the fleet\n * reaps the session (null once pinned), and whether it is pinned. */\n get idle(): { idleExpiresAt: string | null; pinned: boolean } {\n return {\n idleExpiresAt: this.current.idleExpiresAt ?? null,\n pinned: this.current.pinned ?? false,\n };\n }\n\n /** The platform's notices about the world this session runs on (empty\n * for a schema world). Printed by the CLI on stderr at open. */\n get deprecations(): WorldDeprecation[] {\n return this.current.deprecations ?? [];\n }\n\n /** The task this session runs: bundled scenario, stored task or inline\n * spec, its name, hash and the caller's metadata. */\n get taskInfo(): WorldSessionTask {\n return (\n this.current.task ?? {\n source: \"bundled\",\n name: this.current.taskName,\n hash: null,\n metadata: {},\n }\n );\n }\n\n /** What this task asks for — the bundle's instruction.md, or the inline\n * spec's `instruction`. */\n get instruction(): string | null {\n return this.current.instruction ?? null;\n }\n\n get versionId(): string {\n return this.current.versionId;\n }\n\n /** Whether the session answered ready as of the last state read (the open,\n * a `status()`, or the poll inside `ready()`); no request is made. */\n get isReady(): boolean {\n return this.current.ready;\n }\n\n /** `api` / `ui` / `browser` are present exactly when the world declares\n * them AND the session was opened asking for them. */\n async surfaces(): Promise<SessionSurfaces> {\n if (!this.current.surfaces) await this.status();\n return this.current.surfaces ?? { tools: { kind: \"rendezvous\" } };\n }\n\n /** Base URL of the world's own HTTP API for this session. */\n async api(): Promise<string> {\n const { api } = await this.surfaces();\n if (!api)\n throw new WorldSurfaceUnavailable(\n \"api\",\n \"open the session with surfaces: ['api'] on an api-type world\",\n );\n return api.url;\n }\n\n /** Headers every request to `api()` needs. A World Host session gates its\n * api surface on a per-session token; a pod or hosted twin answers with the\n * world's own declared auth and this is `{}`. */\n async apiHeaders(): Promise<Record<string, string>> {\n const { api } = await this.surfaces();\n return api?.token ? { Authorization: `Bearer ${api.token}` } : {};\n }\n\n /** URL of the world's UI entry page for this session. */\n async ui(): Promise<string> {\n const { ui } = await this.surfaces();\n if (!ui)\n throw new WorldSurfaceUnavailable(\n \"ui\",\n \"open the session with surfaces: ['ui'] on a world that declares [ui]\",\n );\n return uiEntryUrl(ui);\n }\n\n /** A Playwright browser on this session's UI: `hosted` drives the one the\n * platform runs next to the world, `local` launches one here, `auto`\n * prefers hosted. Call `close()` when done.\n *\n * Every action is reported to the platform under `agentId` (default:\n * `GATEWAY_AGENT_ID` or a fresh `agent-<hex>`) so the session page shows\n * this agent's own timeline — several agents may share one session and\n * one hosted browser. `record: false` opts out. */\n async browser(\n opts: {\n mode?: BrowserMode;\n headless?: boolean;\n playwright?: PlaywrightLike;\n agentId?: string;\n record?: boolean;\n } = {},\n ): Promise<WorldBrowser> {\n const { agentId, record = true, ...rest } = opts;\n return openBrowser(await this.surfaces(), {\n ...rest,\n recorder: record ? this.browserRecorder(agentId) : null,\n repair: () => this.repairBrowser(),\n });\n }\n\n /** Ask the platform to make this session's hosted browser reachable again\n * after its connection dropped: `healthy` (reconnect now), `replaced` (a new,\n * blank browser behind the same wsUrl; reconnect and reopen your page) or\n * `starting` (ask again in `retryAfterMs`). `browser()` does this on its\n * own; call it when you drive your own Playwright against `wsUrl`. */\n async repairBrowser(): Promise<RepairAnswer> {\n return apiRequest<RepairAnswer>(\n this.options,\n \"POST\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/browser-repair`,\n {},\n );\n }\n\n /** The reporter `browser()` uses; exposed for a page you drive yourself. */\n browserRecorder(agentId?: string): BrowserActionRecorder {\n const path = `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/browser-events`;\n const id =\n agentId ??\n process.env.GATEWAY_AGENT_ID ??\n `agent-${randomUUID().replace(/-/g, \"\").slice(0, 8)}`;\n return new BrowserActionRecorder(\n async (events: BrowserActionEvent[]) => {\n await apiRequest(this.options, \"POST\", path, { events });\n },\n id,\n {\n // Continue this agent's timeline where the platform has it, so the\n // same id reopened later never re-numbers from zero.\n resumeFrom: async () => {\n const summary = await apiRequest<{\n agents: { agentId: string; nextSeq: number }[];\n }>(this.options, \"GET\", path);\n return summary.agents.find((a) => a.agentId === id)?.nextSeq ?? 0;\n },\n },\n );\n }\n\n /** Browser actions as model tools, in the same shape as `toolkit()`. */\n computerUseTools(browser: WorldBrowser): WorldToolkit {\n return computerUseToolkit(browser);\n }\n\n /** The session's latest platform state (one request, no waiting). */\n async status(): Promise<WorldSessionState> {\n const fresh = await apiRequest<WorldSessionState>(\n this.options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}`,\n );\n // A status read does not carry the objective; keep the one we opened with.\n this.current = {\n instruction: this.current.instruction,\n tools: this.current.tools,\n surfaces: this.current.surfaces,\n task: this.current.task,\n ...fresh,\n };\n return this.current;\n }\n\n /**\n * Wait until the container is warm — meaning the process inside it has\n * asked the platform for work, not merely that a job was accepted.\n */\n async ready(opts: { timeoutMs?: number } = {}): Promise<WorldSessionState> {\n const deadline = Date.now() + (opts.timeoutMs ?? READY_TIMEOUT_MS);\n for (;;) {\n const state = await this.status();\n if (state.ready) return state;\n if (state.state === \"FAILED\" || state.state === \"STOPPED\")\n throw new WorldSessionCallError(\n `World session ${state.state.toLowerCase()} before it was ready.`,\n );\n if (Date.now() > deadline)\n throw new WorldSessionTimeout(\n `World session still ${state.state} after ${Math.round((opts.timeoutMs ?? READY_TIMEOUT_MS) / 1000)}s.`,\n );\n await sleep(READY_POLL_MS);\n }\n }\n\n /** Enqueue one interaction and wait for the container's answer. */\n private async exchange(\n body: {\n kind?: \"call\" | \"grade\" | \"reset\" | \"state\" | \"seed\" | \"close\";\n tool?: string;\n args?: unknown;\n /** Grade only: the agent's report, for a rubric judge. */\n report?: string;\n },\n timeoutMs?: number,\n ): Promise<unknown> {\n // Measured the way the route measures it; over the limit nothing is sent.\n serializeCallBody(body);\n const enqueued = await apiRequest<{\n callId: string;\n seq: number;\n /** The platform's worker finalizes this call (a rubric grade). */\n pending?: boolean;\n }>(\n this.options,\n \"POST\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/calls`,\n body,\n );\n const { callId } = enqueued;\n const judged = enqueued.pending === true;\n const budgetMs =\n timeoutMs ?? (judged ? JUDGED_GRADE_TIMEOUT_MS : CALL_TIMEOUT_MS);\n const pollMs = judged ? JUDGED_GRADE_POLL_MS : CALL_POLL_MS;\n const deadline = Date.now() + budgetMs;\n for (;;) {\n const call = await apiRequest<{\n done: boolean;\n state: string;\n result: unknown;\n error: string | null;\n }>(\n this.options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/calls/${encodeURIComponent(callId)}`,\n );\n if (call.done) {\n if (call.error) throw new WorldSessionCallError(call.error);\n return call.result;\n }\n if (Date.now() > deadline)\n throw new WorldSessionTimeout(\n judged\n ? `Grade ${callId} still ${call.state} after ${Math.round(budgetMs / 1000)}s — the judge has not answered; the platform finalizes the call on its own, read it back with export().`\n : `Call ${callId} still ${call.state} after ${Math.round(budgetMs / 1000)}s — the container may have died.`,\n );\n await sleep(pollMs);\n }\n }\n\n /**\n * Run one of the world's tools INSIDE the container. The arguments and the\n * result are the world's own contract — this layer neither validates nor\n * reshapes them, so a tool error reads exactly as it would in a hosted run.\n */\n async call(\n tool: string,\n args: Record<string, unknown> = {},\n opts: { timeoutMs?: number } = {},\n ): Promise<unknown> {\n return this.exchange({ kind: \"call\", tool, args }, opts.timeoutMs);\n }\n\n /**\n * THE WORLD'S TOOLS, READY TO HAND TO A MODEL. Schemas come from the\n * world's own signatures and implementations call into this session, so a\n * caller never writes — and never has to re-sync — a tool map of their own:\n *\n * const { schemas, impls } = await session.toolkit();\n * await runMyAgent(impls, schemas, session.instruction);\n *\n * A tool added to the world shows up here on the next run; a tool renamed\n * in the world renames here too, instead of failing at call time against a\n * hand-written map that still remembers the old name.\n */\n async toolkit(): Promise<WorldToolkit> {\n let specs = this.current.tools;\n if (!specs) specs = (await this.status()).tools ?? [];\n const impls: WorldToolkit[\"impls\"] = Object.create(null);\n for (const spec of specs) {\n const alias = modelToolName(spec.name);\n if (Object.hasOwn(impls, alias))\n throw new WorldSessionCallError(`Model tool name collision: ${alias}`);\n impls[alias] = (args: Record<string, unknown> = {}) =>\n this.call(spec.name, args);\n }\n return { schemas: specs.map(schemaFromSignature), impls, specs };\n }\n\n /** Run the task's grader against the container's END STATE. Graders answer\n * in one of two shapes: the scalar with named rewards beside it\n * (`{reward, check_a, check_b}`, a task's own `grade.py`), or the named\n * rewards nested under `rewards` (the api, mock-tools and World Host\n * runners). Both land in `rewards`.\n *\n * A rubric grade is finalized by the platform's judge, not the container:\n * the platform answers the enqueue with `pending: true`, and this waits on\n * the judge's budget (15 min) instead of a call's. `timeoutMs` overrides\n * either. `report` is the agent's own account of what it did and found,\n * handed to the judge as its claim beside the evidence (the state and the\n * calls); assertions and python graders ignore it. `worlds` names the\n * task's other sessions by alias (`{alias: sessionId}`): the platform\n * reads each one's evidence and hands it to the cross-world verifiers\n * anchored on this session, whose grades come back under `verifiers`. */\n async grade(\n opts: {\n timeoutMs?: number;\n report?: string;\n worlds?: Record<string, string>;\n } = {},\n ): Promise<GradeResult> {\n const raw = (await this.exchange(\n {\n kind: \"grade\",\n ...(opts.report !== undefined ? { report: opts.report } : {}),\n ...(opts.worlds && Object.keys(opts.worlds).length > 0\n ? { worlds: opts.worlds }\n : {}),\n },\n opts.timeoutMs,\n )) as Record<string, unknown> | null;\n const record = raw && typeof raw === \"object\" ? raw : {};\n const verifiers = verifierGrades(record.verifiers);\n return {\n ...numericGrade(record),\n ...(typeof record.reason === \"string\" ? { reason: record.reason } : {}),\n ...(verifiers ? { verifiers } : {}),\n raw,\n };\n }\n\n /**\n * Put rows into the LIVE world through its contract, in one batch:\n * `append` (default) upserts by primary key, `replace` makes the named\n * entities hold exactly these rows. Atomic — a refused row leaves the\n * session unchanged and the error names the entity, row and field.\n */\n async seed(\n rows: Record<string, Record<string, unknown>[]>,\n opts: {\n mode?: \"append\" | \"replace\";\n /** `apply` runs the world's `[redact]` policy over the rows first;\n * `refuse` rejects plaintext in a redacted field; default `off`. */\n redact?: \"off\" | \"apply\" | \"refuse\";\n timeoutMs?: number;\n } = {},\n ): Promise<SeedResult> {\n const mode = opts.mode ?? \"append\";\n const redact = opts.redact ?? \"off\";\n return (await this.exchange(\n {\n kind: \"seed\",\n args: { mode, rows, ...(redact !== \"off\" ? { redact } : {}) },\n },\n opts.timeoutMs,\n )) as SeedResult;\n }\n\n /** Every entity's rows as the world holds them now — the same dump a\n * grader reads. The shape is the world runtime's: a schema world answers\n * `{<entity>: {<key>: row}, snapshot}`, a mock-tools world\n * `{entities: {<entity>: [row]}}`. */\n async state(opts: { timeoutMs?: number } = {}): Promise<unknown> {\n return this.exchange({ kind: \"state\" }, opts.timeoutMs);\n }\n\n /** Back to the opening state: the version's data plus the bundled\n * scenario's or the inline task's seed. Rows written since are gone; the\n * call log stays. */\n async reset(opts: { timeoutMs?: number } = {}): Promise<void> {\n await this.exchange({ kind: \"reset\" }, opts.timeoutMs);\n }\n\n /** The session's call log, oldest first: every tool call, seed, reset,\n * grade with its result — the record of the episode. */\n async export(): Promise<WorldSessionCall[]> {\n const calls: WorldSessionCall[] = [];\n let cursor: string | undefined;\n do {\n const params = new URLSearchParams({ limit: String(EXPORT_PAGE) });\n if (cursor) params.set(\"cursor\", cursor);\n const page = await apiRequest<{\n calls: Record<string, unknown>[];\n nextCursor?: string | null;\n }>(\n this.options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/calls?${params.toString()}`,\n );\n for (const call of page.calls) {\n calls.push({\n seq: Number(call.seq),\n kind: String(call.kind ?? \"call\"),\n tool: typeof call.tool === \"string\" ? call.tool : null,\n args: call.args ?? null,\n result: call.result ?? null,\n error: typeof call.error === \"string\" ? call.error : null,\n completedAt:\n typeof call.completedAt === \"string\" ? call.completedAt : null,\n });\n }\n cursor = page.nextCursor ?? undefined;\n } while (cursor);\n return calls;\n }\n\n /**\n * Promote this session's inline task into a stored task of the project\n * (version 1, pinned to the session's world unless `world` says otherwise),\n * so a task written for one end user can be reused and its grades\n * compared. The session then records the new task's id. A session on a\n * bundled task has nothing to save; one on a stored task is already saved.\n */\n async saveTask(\n opts: { name?: string; world?: string | null; message?: string } = {},\n ): Promise<WorldTaskSummary> {\n const task = await apiRequest<WorldTaskSummary>(\n this.options,\n \"POST\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/task`,\n {\n ...(opts.name !== undefined ? { name: opts.name } : {}),\n ...(opts.world !== undefined ? { world: opts.world } : {}),\n ...(opts.message !== undefined ? { message: opts.message } : {}),\n },\n );\n this.current = {\n ...this.current,\n taskName: task.name,\n task: {\n ...this.taskInfo,\n source: \"stored\",\n name: task.name,\n id: task.id,\n version: task.version,\n },\n };\n return task;\n }\n\n /**\n * End the session. `keepWarm` hands the container back to the pool instead\n * of tearing it down, so the next session for the same task starts warm —\n * the pooled instance still obeys the fleet's idle TTL and pinning.\n */\n async close(opts: { keepWarm?: boolean } = {}): Promise<{ state: string }> {\n return apiRequest(\n this.options,\n \"DELETE\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}`,\n { keepWarm: opts.keepWarm ?? false },\n );\n }\n}\n\n/**\n * Attach to a session that already exists — resuming after a crash, or\n * driving a session someone else opened (a container started by hand on a\n * self-hosted install, a session opened by CI and handed to a developer).\n */\nexport async function attachSession(\n sessionId: string,\n options: WorldsClientOptions = {},\n): Promise<WorldSession> {\n const state = await apiRequest<WorldSessionState>(\n options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(sessionId)}`,\n );\n return new WorldSession(sessionId, state, options);\n}\n\nexport type OpenSessionOptions = {\n versionId?: string;\n reuseWarm?: boolean;\n /** More than `tools`: `[\"api\"]`, `[\"ui\"]`, `[\"browser\"]`. The platform\n * refuses (HTTP 400) rather than quietly serving less than asked. */\n surfaces?: WorldSurfaceKind[];\n /** Capacity for a World Host session's browser: `standard` (spot, may be\n * reclaimed) or `premium` (on-demand). Unset, the organization's default. */\n browserTier?: BrowserTier;\n options?: WorldsClientOptions;\n};\n\nconst OPEN_SESSION_OPTION_KEYS: ReadonlySet<string> = new Set([\n \"task\",\n \"versionId\",\n \"reuseWarm\",\n \"surfaces\",\n \"browserTier\",\n \"options\",\n]);\n\n/** The second argument is an options bag only when every key is one of\n * `OpenSessionOptions` (+ `task`); any other object is the positional task\n * and is validated as one, so a misspelt spec is refused, not opened bare. */\nconst isOpenSessionOptions = (\n value: unknown,\n): value is OpenSessionOptions & { task?: WorldTaskRef } =>\n typeof value === \"object\" &&\n value !== null &&\n Object.keys(value).every((key) => OPEN_SESSION_OPTION_KEYS.has(key));\n\n/**\n * Open a live session on a world. Returns as soon as the platform has\n * accepted it — call `ready()` to wait for the container.\n *\n * `task` is a bundled scenario's name, a stored task's `{ id, version? }`\n * or an inline `WorldTaskSpec` (the latter two need a host engine world — the\n * platform answers 400 for a pod world). Omitted, the session is EXPLORATORY:\n * the platform records an inline `{instruction: \"exploratory session\"}` with\n * no grader as `task.source: \"none\"`, and `grade()` answers\n * `{reward: null, reason: \"no grader\"}`. The older positional form\n * `openSession(slug, \"task-name\", opts)` still works.\n */\nexport async function openSession(\n slugOrRef: string,\n task?: OpenSessionOptions & { task?: WorldTaskRef },\n): Promise<WorldSession>;\nexport async function openSession(\n slugOrRef: string,\n task: WorldTaskRef,\n opts?: OpenSessionOptions,\n): Promise<WorldSession>;\nexport async function openSession(\n slugOrRef: string,\n taskOrOpts:\n WorldTaskRef | (OpenSessionOptions & { task?: WorldTaskRef }) = {},\n positionalOpts: OpenSessionOptions = {},\n): Promise<WorldSession> {\n const { task, ...opts } = isOpenSessionOptions(taskOrOpts)\n ? taskOrOpts\n : { task: taskOrOpts as WorldTaskRef, ...positionalOpts };\n if (task !== undefined) assertTaskRef(task);\n const options = opts.options ?? {};\n const unknown = (opts.surfaces ?? []).filter(\n (s) => !(SURFACE_KINDS as readonly string[]).includes(s),\n );\n if (unknown.length)\n throw new Error(\n `Unknown world surfaces: ${unknown.join(\", \")}; choose from ${SURFACE_KINDS.join(\", \")}`,\n );\n if (opts.browserTier !== undefined) assertBrowserTier(opts.browserTier);\n const at = slugOrRef.indexOf(\"@\");\n const slug = at === -1 ? slugOrRef : slugOrRef.slice(0, at);\n const ref = at === -1 ? \"\" : slugOrRef.slice(at + 1);\n const state = await apiRequest<WorldSessionState & { reusedWarm: boolean }>(\n options,\n \"POST\",\n \"/api/public/world-sessions\",\n {\n ...(opts.versionId\n ? { versionId: opts.versionId }\n : { slug, ...(ref && { ref }) }),\n ...(task === undefined ? {} : { task }),\n ...(opts.reuseWarm === undefined ? {} : { reuseWarm: opts.reuseWarm }),\n ...(opts.surfaces?.length ? { surfaces: opts.surfaces } : {}),\n ...(opts.browserTier === undefined\n ? {}\n : { browserTier: opts.browserTier }),\n },\n );\n return new WorldSession(state.sessionId, state, options);\n}\n\n// ── running many tasks at once ───────────────────────────────────────────────\n\nexport type SessionRunResult = {\n /** The task's name, or `inline:<hash>` for an unnamed inline task. */\n task: string;\n sessionId: string;\n reward: number | null;\n rewards: Record<string, number>;\n /** Set when the task threw instead of grading. */\n error?: string;\n};\n\nexport type SessionRunReport = {\n results: SessionRunResult[];\n /** Mean reward over every task, counting failures as 0. */\n mean: number;\n /** Tasks that never graded: the session did not open or become ready, the\n * agent threw, or grading failed. Any failure fails the run — a 0 an agent\n * earned and a session that never opened are not the same result. */\n failed: number;\n /** True when no task failed and `mean >= failUnder` (or no gate was set). */\n passed: boolean;\n};\n\n/**\n * RUN MANY TASKS IN PARALLEL, one warm container each.\n *\n * Parallelism against live worlds is the normal case — a suite is a dozen\n * tasks and each needs its own container, because two agents sharing one\n * world state would corrupt both episodes. Every caller was writing the same\n * pool, the same per-task open/ready/toolkit/grade/close, and the same\n * \"don't let one failure kill the run\" logic, so it belongs here:\n *\n * const report = await runSessions({\n * world: \"revenue-ops-sim@main\",\n * tasks, // default: every task in the world\n * concurrency: 4,\n * failUnder: 0.7,\n * agent: async ({ toolkit, instruction }) =>\n * myAgent(toolkit.impls, toolkit.schemas, instruction),\n * });\n *\n * The handler gets a ready session with its toolkit already bound; grading,\n * closing (warm) and aggregation are handled. A task that throws scores 0\n * and records why — the tasks that passed keep their results.\n */\nexport async function runSessions(opts: {\n world: string;\n /** Bundled task names, stored task refs and/or inline task specs\n * (default: every bundled task in the world). */\n tasks?: WorldTaskRef[];\n concurrency?: number;\n failUnder?: number;\n /** Pin every session to one version (default: the world's head). */\n versionId?: string;\n /** Hand the containers back warm for the next run (default: true). */\n keepWarm?: boolean;\n agent: (ctx: {\n session: WorldSession;\n toolkit: WorldToolkit;\n instruction: string;\n /** The task's label — see `SessionRunResult.task`. */\n task: string;\n /** The task as it was given: a bundled name, a stored ref or the\n * inline spec. */\n taskRef: WorldTaskRef;\n }) => Promise<unknown>;\n onResult?: (result: SessionRunResult) => void;\n options?: WorldsClientOptions;\n}): Promise<SessionRunReport> {\n const options = opts.options ?? {};\n const concurrency = Math.max(1, opts.concurrency ?? 3);\n\n let tasks = opts.tasks;\n let versionId = opts.versionId;\n if (!tasks || !versionId) {\n // One resolve for the whole run: every session pins the SAME version, so\n // a push mid-suite cannot split the results across two worlds — and a\n // caller who pinned a version gets THAT version's task list, not the\n // branch tip's.\n const { openWorld, openWorldVersion } = await import(\"./index\");\n const world = versionId\n ? await openWorldVersion(opts.world.split(\"@\", 1)[0]!, versionId, options)\n : await openWorld(opts.world, options);\n tasks = tasks ?? world.tasks.map((t) => t.name);\n versionId = versionId ?? world.version.versionId;\n }\n\n const results: SessionRunResult[] = [];\n let next = 0;\n await Promise.all(\n Array.from({ length: Math.min(concurrency, tasks.length) }, async () => {\n while (next < tasks!.length) {\n const taskRef = tasks![next++];\n let task = taskLabel(taskRef);\n let session: WorldSession | null = null;\n try {\n session = await openSession(opts.world, {\n task: taskRef,\n versionId,\n options,\n });\n task = taskLabel(taskRef, session.taskInfo);\n await session.ready();\n const toolkit = await session.toolkit();\n await opts.agent({\n session,\n toolkit,\n instruction:\n session.instruction ??\n (isTaskSpec(taskRef) ? taskRef.instruction : task),\n task,\n taskRef,\n });\n const graded = await session.grade();\n const result: SessionRunResult = {\n task,\n sessionId: session.sessionId,\n reward: graded.reward,\n rewards: graded.rewards,\n };\n results.push(result);\n opts.onResult?.(result);\n } catch (error) {\n const result: SessionRunResult = {\n task,\n sessionId: session?.sessionId ?? \"\",\n reward: 0,\n rewards: {},\n // An Error with an empty message would read as \"no error\" to any\n // caller checking truthiness; name the type instead.\n error:\n (error instanceof Error ? error.message : String(error)) ||\n (error instanceof Error ? error.name : \"Unknown error\"),\n };\n results.push(result);\n opts.onResult?.(result);\n } finally {\n // Always give the container back — a leaked session bills until the\n // fleet's idle TTL reaps it.\n await session\n ?.close({ keepWarm: opts.keepWarm ?? true })\n .catch(() => undefined);\n }\n }\n }),\n );\n\n const mean =\n results.reduce((sum, r) => sum + (r.reward ?? 0), 0) /\n (results.length || 1);\n const failed = results.filter((r) => r.error).length;\n return {\n results: results.sort((a, b) => a.task.localeCompare(b.task)),\n mean,\n failed,\n passed:\n failed === 0 && (opts.failUnder === undefined || mean >= opts.failUnder),\n };\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\n\n/** Mirrors `WorldSessionListItemSchema` (web/features/public-api/types/world-sessions.ts). */\nexport type WorldSessionListItem = {\n sessionId: string;\n slug: string;\n containerId: string;\n state: string;\n ready: boolean;\n versionId: string;\n contentHash: string;\n taskName: string | null;\n engine: string;\n pinned: boolean;\n surfaces: string[];\n createdAt: string;\n lastUsedAt: string;\n};\n\n/** A World Host session's states (`SessionState` in shared `worldSessions.ts`). */\nexport const SESSION_STATES = [\n \"PROVISIONING\",\n \"RUNNING\",\n \"IDLE\",\n \"STOPPING\",\n \"STOPPED\",\n \"FAILED\",\n \"LOST\",\n] as const;\n\nexport type ListSessionsFilter = {\n /** One of SESSION_STATES. */\n state?: string;\n slug?: string;\n limit?: number;\n};\n\n/** The project's live sessions, newest first — the ones an agent can attach to. */\nexport async function listSessions(\n filter: ListSessionsFilter = {},\n options: WorldsClientOptions = {},\n): Promise<WorldSessionListItem[]> {\n const params = new URLSearchParams();\n if (filter.state) params.set(\"state\", filter.state);\n if (filter.slug) params.set(\"slug\", filter.slug);\n if (filter.limit !== undefined) params.set(\"limit\", String(filter.limit));\n const qs = params.toString();\n const res = await apiRequest<{ sessions: WorldSessionListItem[] }>(\n options,\n \"GET\",\n `/api/public/world-sessions${qs ? `?${qs}` : \"\"}`,\n );\n return res.sessions;\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\nimport type { WorldTaskSpec } from \"./session\";\n\n/**\n * STORED WORLD TASKS: a task spec kept by the project, outside any bundle.\n *\n * An inline task (`openSession(world, { task: { instruction, … } })`) belongs\n * to one session. A stored task is the same spec as a named, versioned\n * project resource: create it once, open as many sessions on it as you like\n * with `{ task: { id } }`, and every grade attributes back to the task and\n * its version. Updating the spec never rewrites history — it appends a\n * version, and a session opened on `{ id, version: 2 }` keeps running v2\n * after v3 exists.\n *\n * const task = await createTask({\n * name: \"refund-late-invoice\",\n * world: \"acme-billing\",\n * spec: { instruction: \"…\", seed: {…}, grader: {…} },\n * });\n * const session = await openSession(\"acme-billing\", { task: { id: task.id } });\n *\n * Tasks are project-scoped: another project's task id is not found (404),\n * never forbidden. `world` pins a task to one world's slug (validated against\n * that world's contract); null leaves it usable with any world.\n */\n\nexport type WorldTaskSummary = {\n id: string;\n name: string;\n world: string | null;\n version: number;\n hash: string;\n spec: WorldTaskSpec;\n /** A multi-world task's aliases in spec order; empty for a single world. */\n aliases: string[];\n /** Listed by world: the aliases that world plays in this task; else empty. */\n aliasesHere: string[];\n /** What grades the task, one row per check or verifier: its reward key,\n * the aliases it judges, what it checks in plain words, its source. */\n verifiers: WorldTaskVerifierRow[];\n createdAt: string;\n updatedAt: string;\n createdBy: string;\n updatedBy: string;\n /** On create, when the task is pinned to a world of a deprecated shape (an\n * api bundle): what to run instead. A retired shape is refused. */\n deprecations?: { code: string; message: string; replacement: string }[];\n};\n\nexport type WorldTaskVersionSummary = {\n version: number;\n hash: string;\n createdAt: string;\n createdBy: string;\n message: string | null;\n};\n\nexport type WorldTaskVerifierRow = {\n key: string;\n aliases: string[];\n kind: \"assertions\" | \"python\" | \"rubric\";\n description: string | null;\n source: string | null;\n sourceLanguage: \"python\" | \"text\" | null;\n};\n\nexport type WorldTaskDetail = WorldTaskSummary & {\n versions: WorldTaskVersionSummary[];\n};\n\nexport type WorldTaskPage = {\n tasks: WorldTaskSummary[];\n meta: {\n page: number;\n limit: number;\n totalItems: number;\n totalPages: number;\n /** Listed by world: the scan for multi-world tasks naming it filled its\n * bound, so `totalItems` is a floor. */\n scanTruncated?: true;\n };\n};\n\nexport type WorldTaskWorldValidation = {\n slug: string;\n ref: string;\n versionId: string;\n ok: boolean;\n checked: \"entities\" | \"none\";\n problems: string[];\n entities: string[] | null;\n};\n\nexport type WorldTaskValidation = {\n taskId: string;\n version: number;\n /** The world version the task was checked against; null for a task with\n * `worlds`, whose versions are per alias under `worlds`. */\n versionId: string | null;\n ok: boolean;\n /** `entities` when the world's contract was read and every seed and check\n * entity was matched against it; `none` when the version has no contract\n * to check (a mock-tools world), in which case `ok` says only that the\n * version exists and is READY; `worlds` for a multi-world task, checked\n * alias by alias against the ref each names. */\n checked: \"entities\" | \"none\" | \"worlds\";\n /** For a multi-world task each problem is prefixed with its alias. */\n problems: string[];\n entities: string[] | null;\n worlds?: Record<string, WorldTaskWorldValidation>;\n};\n\nconst TASKS = \"/api/public/world-tasks\";\nconst taskRoute = (id: string) => `${TASKS}/${encodeURIComponent(id)}`;\n\nconst compact = (body: Record<string, unknown>) =>\n Object.fromEntries(Object.entries(body).filter(([, v]) => v !== undefined));\n\n/** Store a task. `name` defaults to `spec.name`; one of the two is needed. */\nexport async function createTask(\n input: {\n spec: WorldTaskSpec;\n name?: string;\n world?: string | null;\n message?: string;\n },\n options: WorldsClientOptions = {},\n): Promise<WorldTaskSummary> {\n return apiRequest<WorldTaskSummary>(\n options,\n \"POST\",\n TASKS,\n compact({\n spec: input.spec,\n name: input.name,\n world: input.world,\n message: input.message,\n }),\n );\n}\n\n/** Change a task. A new `spec` becomes the next version (the old ones stay\n * readable and openable); `name` and `world` change in place. */\nexport async function updateTask(\n taskId: string,\n input: {\n spec?: WorldTaskSpec;\n name?: string;\n world?: string | null;\n message?: string;\n },\n options: WorldsClientOptions = {},\n): Promise<WorldTaskSummary> {\n if (\n input.spec === undefined &&\n input.name === undefined &&\n input.world === undefined\n )\n throw new Error(\"updateTask: nothing to update — pass spec, name or world\");\n return apiRequest<WorldTaskSummary>(\n options,\n \"PATCH\",\n taskRoute(taskId),\n compact({\n spec: input.spec,\n name: input.name,\n world: input.world,\n message: input.message,\n }),\n );\n}\n\n/** The project's tasks, newest change first. `world` keeps only tasks\n * that run against that slug (pinned to it, or naming it under an alias); `metadata` keeps tasks whose spec metadata carries\n * every given key/value (`{ externalUserId: \"u_42\" }`). */\nexport async function listTasks(\n filter: {\n world?: string;\n metadata?: Record<string, string>;\n page?: number;\n limit?: number;\n } = {},\n options: WorldsClientOptions = {},\n): Promise<WorldTaskPage> {\n const params = new URLSearchParams();\n if (filter.world) params.set(\"world\", filter.world);\n if (filter.page !== undefined) params.set(\"page\", String(filter.page));\n if (filter.limit !== undefined) params.set(\"limit\", String(filter.limit));\n for (const [key, value] of Object.entries(filter.metadata ?? {}))\n params.set(`metadata.${key}`, value);\n const query = params.toString();\n return apiRequest<WorldTaskPage>(\n options,\n \"GET\",\n query ? `${TASKS}?${query}` : TASKS,\n );\n}\n\n/** One task with its version history; `version` reads that version's spec\n * instead of the current one. */\nexport async function getTask(\n taskId: string,\n opts: { version?: number } = {},\n options: WorldsClientOptions = {},\n): Promise<WorldTaskDetail> {\n const query =\n opts.version === undefined ? \"\" : `?version=${String(opts.version)}`;\n return apiRequest<WorldTaskDetail>(\n options,\n \"GET\",\n `${taskRoute(taskId)}${query}`,\n );\n}\n\n/** Remove a task and every version. Sessions already opened on it keep\n * their copy of the spec. */\nexport async function deleteTask(\n taskId: string,\n options: WorldsClientOptions = {},\n): Promise<{ id: string; name: string }> {\n return apiRequest(options, \"DELETE\", taskRoute(taskId));\n}\n\n/** Check a task against a world version without opening a session: every\n * seed entity and every check's entity must exist in the world's contract.\n * `slug` checks against that world's head, `versionId` against an exact\n * version, neither against the task's own `world` pin. */\nexport async function validateTask(\n taskId: string,\n target: { version?: number; slug?: string; versionId?: string } = {},\n options: WorldsClientOptions = {},\n): Promise<WorldTaskValidation> {\n return apiRequest<WorldTaskValidation>(\n options,\n \"POST\",\n `${taskRoute(taskId)}/validate`,\n compact({\n version: target.version,\n slug: target.slug,\n versionId: target.versionId,\n }),\n );\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\nimport {\n assertBrowserTier,\n surfaceKinds,\n uiEntryUrl,\n type BrowserTier,\n type SessionSurfaces,\n type WorldSurfaceKind,\n} from \"./browser\";\nimport {\n WorldSession,\n attachSession,\n isTaskIdRef,\n type GradeResult,\n type VerifierGrade,\n type WorldSessionCall,\n type WorldSessionState,\n type WorldTaskIdRef,\n type WorldTaskSpec,\n} from \"./session\";\n\n/**\n * TASKS THAT NEED SEVERAL WORLDS.\n *\n * A task whose spec names `worlds` is one instruction over N hosted worlds\n * — an investigation that reads a breach feed, a threat-intel API and a\n * ticketing system, say. `openTask` brings every one of them up in ONE call\n * and hands back the sessions keyed by the aliases the spec chose:\n *\n * const task = await openTask({ id: \"wt_1\" }, { surfaces: [\"api\"] });\n * await task.ready();\n * const spycloud = task.sessions.spycloud; // a WorldSession\n * await myAgent(task.instruction, task.sessions);\n * const grade = await task.grade(); // per world + aggregate\n * await task.close();\n *\n * The platform opens the sessions (POST /world-task-sessions) and refuses\n * a partial bring-up: if one world fails, the ones that opened are closed\n * and the error names every alias that failed. Everything after — ready,\n * grade, export, close — is one `WorldSession` call per world, fanned out\n * here. `manifest()` is the record `gateway worlds task up` prints, and\n * `attachTask` rebuilds a `TaskSessions` from a stored task's live sessions.\n */\n\nconst TASK_SESSIONS = \"/api/public/world-task-sessions\";\n\n/** The per-world entry of a `WorldTaskSpec.worlds` table. */\nexport type WorldTaskWorld = {\n slug: string;\n ref?: string;\n seed?: WorldTaskSpec[\"seed\"];\n grader?: WorldTaskSpec[\"grader\"];\n tools?: string[];\n};\n\n/** One world's session as the platform answered it at up. */\nexport type TaskWorldSessionState = WorldSessionState & {\n alias: string;\n slug: string;\n ref: string;\n reusedWarm: boolean;\n};\n\n/** What `POST /world-task-sessions` answers. */\nexport type TaskSessionsResponse = {\n taskId: string | null;\n taskVersion: number | null;\n name: string | null;\n hash: string;\n instruction: string;\n sessions: Record<string, TaskWorldSessionState>;\n};\n\n/** One world in the manifest: where it answers, in the shape\n * `gateway worlds session open` prints for a single session. */\nexport type TaskManifestSession = {\n slug: string;\n ref: string | null;\n versionId: string;\n sessionId: string;\n ready: boolean;\n state: string;\n surfaces: WorldSurfaceKind[];\n api?: { url: string; token?: string };\n ui?: { url: string; entry: string; apiPath: string | null };\n browser?: { wsUrl: string; viewport?: unknown };\n};\n\n/** The manifest: every session of the task, keyed by alias. The file\n * `task up --out` writes and `task down|status|grade|export` read. */\nexport type TaskManifest = {\n taskId: string | null;\n taskVersion: number | null;\n name: string | null;\n instruction: string | null;\n sessions: Record<string, TaskManifestSession>;\n};\n\n/** A stored task's live sessions, as `GET /world-task-sessions` lists them. */\nexport type LiveTaskSession = {\n alias: string | null;\n slug: string | null;\n sessionId: string;\n state: string;\n ready: boolean;\n versionId: string;\n taskVersion: number | null;\n createdAt: string;\n};\n\n/** The task's grade: every world's own `GradeResult` under its alias, the\n * task's cross-world verifiers by name (lifted from the world each is\n * anchored on), and the aggregate. `reward` is the mean of the worlds' and\n * verifiers' numeric rewards — null when none answered one (no grader\n * anywhere, or a judge still pending); a world or verifier with no reward\n * is listed under `ungraded` (a verifier as `x.<name>`), never counted as\n * 0. `rewards` flattens each world's named rewards as `<alias>.<key>`\n * beside `<alias>` for the world's own reward, and a verifier's as\n * `x.<name>` / `x.<name>.<key>`. */\nexport type TaskGrade = {\n reward: number | null;\n rewards: Record<string, number>;\n worlds: Record<string, GradeResult>;\n ungraded: string[];\n verifiers: Record<string, VerifierGrade>;\n};\n\n/** A cross-world verifier's rewards flatten under `x.<name>`; no alias\n * starts with `x.`. */\nexport const VERIFIER_REWARD_PREFIX = \"x.\";\n\n/** Every world's call log, keyed by alias. */\nexport type TaskExport = Record<string, WorldSessionCall[]>;\n\nconst manifestSession = (\n s: SessionSurfaces,\n state: {\n sessionId: string;\n ready: boolean;\n state: string;\n versionId: string;\n },\n world: { slug: string; ref: string | null },\n): TaskManifestSession => ({\n slug: world.slug,\n ref: world.ref,\n versionId: state.versionId,\n sessionId: state.sessionId,\n ready: state.ready,\n state: state.state,\n surfaces: surfaceKinds(s),\n ...(s.api\n ? {\n api: { url: s.api.url, ...(s.api.token ? { token: s.api.token } : {}) },\n }\n : {}),\n ...(s.ui\n ? {\n ui: {\n url: s.ui.url,\n entry: uiEntryUrl(s.ui),\n apiPath: s.ui.apiPath ?? null,\n },\n }\n : {}),\n ...(s.browser\n ? { browser: { wsUrl: s.browser.wsUrl, viewport: s.browser.viewport } }\n : {}),\n});\n\n/** Combine per-world grades into the task's. Pure, so the CLI and the tests\n * share it with `TaskSessions.grade()`. */\nexport function aggregateTaskGrade(\n worlds: Record<string, GradeResult>,\n): TaskGrade {\n const rewards: Record<string, number> = {};\n const ungraded: string[] = [];\n const graded: number[] = [];\n const verifiers: Record<string, VerifierGrade> = {};\n const fold = (key: string, grade: VerifierGrade) => {\n if (typeof grade.reward === \"number\") {\n rewards[key] = grade.reward;\n graded.push(grade.reward);\n } else ungraded.push(key);\n for (const [name, value] of Object.entries(grade.rewards))\n rewards[`${key}.${name}`] = value;\n };\n for (const [alias, grade] of Object.entries(worlds)) {\n fold(alias, grade);\n Object.assign(verifiers, grade.verifiers ?? {});\n }\n for (const [name, grade] of Object.entries(verifiers))\n fold(`${VERIFIER_REWARD_PREFIX}${name}`, grade);\n const reward =\n graded.length > 0\n ? graded.reduce((a, b) => a + b, 0) / graded.length\n : null;\n return { reward, rewards, worlds, ungraded, verifiers };\n}\n\nexport class TaskSessions {\n constructor(\n /** The stored task's id, or null for a task given as a spec. */\n readonly taskId: string | null,\n readonly taskVersion: number | null,\n readonly name: string | null,\n /** The instruction every world's session shares. */\n readonly instruction: string | null,\n /** One live session per alias, in the spec's order. */\n readonly sessions: Record<string, WorldSession>,\n private readonly worlds: Record<\n string,\n { slug: string; ref: string | null }\n >,\n /** The spec's content hash — set only by `openTask` (the raw platform\n * response carries it); null for a `TaskSessions` rebuilt with\n * `attachManifest`/`attachTask`, which have no spec to hash. */\n readonly hash: string | null = null,\n ) {}\n\n /** This alias's `{slug, ref}` as recorded at open/attach — the world a\n * `TaskRun` filing needs to name, without exposing the whole map. */\n worldRef(alias: string): { slug: string; ref: string | null } {\n return this.worlds[alias] ?? { slug: \"\", ref: null };\n }\n\n /** The aliases, in the spec's order. */\n get aliases(): string[] {\n return Object.keys(this.sessions);\n }\n\n /** The alias's session, or a clear error naming the aliases there are. */\n session(alias: string): WorldSession {\n const session = this.sessions[alias];\n if (!session)\n throw new Error(\n `task has no world '${alias}'; its worlds are ${this.aliases.join(\", \")}`,\n );\n return session;\n }\n\n private async each<T>(\n fn: (session: WorldSession, alias: string) => Promise<T>,\n ): Promise<Record<string, T>> {\n const entries = await Promise.all(\n Object.entries(this.sessions).map(\n async ([alias, session]) => [alias, await fn(session, alias)] as const,\n ),\n );\n return Object.fromEntries(entries);\n }\n\n /** Wait until every world answers ready. A world that never does throws\n * `WorldSessionTimeout` naming it; the others are left up. */\n async ready(opts: { timeoutMs?: number } = {}): Promise<void> {\n await this.each((session) => session.ready(opts));\n }\n\n /** Every world's current state, keyed by alias. */\n async status(): Promise<Record<string, WorldSessionState>> {\n return this.each((session) => session.status());\n }\n\n /** The manifest: where every world answers, keyed by alias. */\n async manifest(): Promise<TaskManifest> {\n const sessions = await this.each(async (session, alias) =>\n manifestSession(\n await session.surfaces(),\n {\n sessionId: session.sessionId,\n ready: session.isReady,\n state: (await session.status()).state,\n versionId: session.versionId,\n },\n this.worlds[alias]!,\n ),\n );\n return {\n taskId: this.taskId,\n taskVersion: this.taskVersion,\n name: this.name,\n instruction: this.instruction,\n sessions,\n };\n }\n\n /** Grade every world and aggregate — see `TaskGrade`. One `report` (the\n * agent's own account of the whole investigation) goes to every world's\n * judge; a world graded by assertions or python ignores it. Each grade\n * names the task's other sessions by alias, so the cross-world verifiers\n * anchored on that world can read them. */\n async grade(\n opts: { timeoutMs?: number; report?: string } = {},\n ): Promise<TaskGrade> {\n return aggregateTaskGrade(\n await this.each((session, alias) =>\n session.grade({ ...opts, worlds: this.otherSessions(alias) }),\n ),\n );\n }\n\n /** The task's other sessions by alias: what a grade names. */\n private otherSessions(alias: string): Record<string, string> {\n return Object.fromEntries(\n Object.entries(this.sessions)\n .filter(([other]) => other !== alias)\n .map(([other, session]) => [other, session.sessionId]),\n );\n }\n\n /** Every world's call log, keyed by alias. */\n async export(): Promise<TaskExport> {\n return this.each((session) => session.export());\n }\n\n /** Close every world. Closes are attempted for all of them even when one\n * fails; the error then names every world that did not close. */\n async close(\n opts: { keepWarm?: boolean } = {},\n ): Promise<Record<string, { state: string }>> {\n const settled = await Promise.allSettled(\n Object.entries(this.sessions).map(\n async ([alias, session]) => [alias, await session.close(opts)] as const,\n ),\n );\n const failed: string[] = [];\n const closed: Record<string, { state: string }> = {};\n settled.forEach((result, i) => {\n const alias = this.aliases[i]!;\n if (result.status === \"fulfilled\") closed[alias] = result.value[1];\n else\n failed.push(\n `${alias}: ${result.reason instanceof Error ? result.reason.message : String(result.reason)}`,\n );\n });\n if (failed.length > 0)\n throw new Error(\n `${failed.length} of ${this.aliases.length} worlds did not close — ${failed.join(\"; \")}`,\n );\n return closed;\n }\n}\n\nexport type OpenTaskOptions = {\n /** With a task id: open that version of the task instead of the current. */\n version?: number;\n /** Asked of every world; the platform refuses (400) rather than serving\n * fewer surfaces than asked, and then nothing is up. */\n surfaces?: WorldSurfaceKind[];\n reuseWarm?: boolean;\n /** Browser capacity for every world the task opens: `standard` (spot, may\n * be reclaimed) or `premium` (on-demand). Unset, the organization's default. */\n browserTier?: BrowserTier;\n options?: WorldsClientOptions;\n};\n\nfunction fromResponse(\n answer: TaskSessionsResponse,\n options: WorldsClientOptions,\n): TaskSessions {\n const sessions: Record<string, WorldSession> = {};\n const worlds: Record<string, { slug: string; ref: string | null }> = {};\n for (const [alias, state] of Object.entries(answer.sessions)) {\n sessions[alias] = new WorldSession(state.sessionId, state, options);\n worlds[alias] = { slug: state.slug, ref: state.ref };\n }\n return new TaskSessions(\n answer.taskId,\n answer.taskVersion,\n answer.name,\n answer.instruction,\n sessions,\n worlds,\n answer.hash ?? null,\n );\n}\n\n/**\n * Bring every world of a task up. `ref` is a stored task's id, its\n * `{ id, version? }`, or the spec itself (one with `worlds`). Returns as\n * soon as the platform has opened every session — `ready()` waits for the\n * containers. All or nothing: a world that fails to open closes the rest\n * and the error names it.\n */\nexport async function openTask(\n ref: string | WorldTaskIdRef | WorldTaskSpec,\n opts: OpenTaskOptions = {},\n): Promise<TaskSessions> {\n const options = opts.options ?? {};\n const task: WorldTaskIdRef | WorldTaskSpec =\n typeof ref === \"string\"\n ? {\n id: ref,\n ...(opts.version !== undefined ? { version: opts.version } : {}),\n }\n : isTaskIdRef(ref) && opts.version !== undefined\n ? { ...ref, version: opts.version }\n : ref;\n if (isTaskIdRef(task) ? !task.id : !task.instruction)\n throw new Error(\n \"openTask needs a task: a stored task id, { id, version? } or a spec with worlds\",\n );\n if (!isTaskIdRef(task) && !task.worlds)\n throw new Error(\n \"openTask needs a spec that names its worlds; a single-world spec opens with openSession\",\n );\n if (opts.browserTier !== undefined) assertBrowserTier(opts.browserTier);\n const answer = await apiRequest<TaskSessionsResponse>(\n options,\n \"POST\",\n TASK_SESSIONS,\n {\n task,\n ...(opts.reuseWarm === undefined ? {} : { reuseWarm: opts.reuseWarm }),\n ...(opts.surfaces?.length ? { surfaces: opts.surfaces } : {}),\n ...(opts.browserTier === undefined\n ? {}\n : { browserTier: opts.browserTier }),\n },\n );\n return fromResponse(answer, options);\n}\n\n/** A stored task's live sessions, newest first — every session the project\n * has opened on it that is not stopped or failed. */\nexport async function listTaskSessions(\n taskId: string,\n options: WorldsClientOptions = {},\n): Promise<LiveTaskSession[]> {\n const answer = await apiRequest<{\n taskId: string;\n sessions: LiveTaskSession[];\n }>(options, \"GET\", `${TASK_SESSIONS}?taskId=${encodeURIComponent(taskId)}`);\n return answer.sessions;\n}\n\n/**\n * Attach to the sessions a stored task has up — after a crash, or from a\n * process other than the one that ran `up`. Refuses when an alias is live\n * more than once (two `up`s of the same task): which set is meant is not\n * knowable, so pass the manifest (`attachManifest`) or close the extras.\n */\nexport async function attachTask(\n taskId: string,\n options: WorldsClientOptions = {},\n): Promise<TaskSessions> {\n const live = await listTaskSessions(taskId, options);\n if (live.length === 0)\n throw new Error(\n `task ${taskId} has no live sessions; run \\`task up\\` first`,\n );\n const byAlias = new Map<string, LiveTaskSession[]>();\n for (const session of live) {\n const alias = session.alias ?? session.sessionId;\n byAlias.set(alias, [...(byAlias.get(alias) ?? []), session]);\n }\n const doubled = [...byAlias.entries()].filter(([, rows]) => rows.length > 1);\n if (doubled.length > 0)\n throw new Error(\n `task ${taskId} has more than one live session for ${doubled\n .map(\n ([alias, rows]) =>\n `'${alias}' (${rows.map((r) => r.sessionId).join(\", \")})`,\n )\n .join(\", \")}; pass the manifest from \\`task up\\`, or close the extras`,\n );\n return attachManifest(\n {\n taskId,\n taskVersion: live[0]!.taskVersion,\n name: null,\n instruction: null,\n sessions: Object.fromEntries(\n [...byAlias.entries()].map(([alias, [row]]) => [\n alias,\n {\n slug: row!.slug ?? \"\",\n ref: null,\n versionId: row!.versionId,\n sessionId: row!.sessionId,\n ready: row!.ready,\n state: row!.state,\n surfaces: [\"tools\"] as WorldSurfaceKind[],\n },\n ]),\n ),\n },\n options,\n );\n}\n\n/** Attach to the sessions a manifest names — the file `task up --out`\n * wrote. Each session is read back from the platform, so a closed one is a\n * clear error rather than a stale handle. */\nexport async function attachManifest(\n manifest: TaskManifest,\n options: WorldsClientOptions = {},\n): Promise<TaskSessions> {\n const entries = await Promise.all(\n Object.entries(manifest.sessions).map(\n async ([alias, entry]) =>\n [alias, await attachSession(entry.sessionId, options)] as const,\n ),\n );\n const sessions = Object.fromEntries(entries);\n const instruction =\n manifest.instruction ?? entries[0]?.[1].instruction ?? null;\n return new TaskSessions(\n manifest.taskId,\n manifest.taskVersion,\n manifest.name,\n instruction,\n sessions,\n Object.fromEntries(\n Object.entries(manifest.sessions).map(([alias, entry]) => [\n alias,\n { slug: entry.slug, ref: entry.ref },\n ]),\n ),\n );\n}\n\n/** Whether a parsed JSON value is a task manifest (what `task up` wrote)\n * rather than a task spec. */\nexport function isTaskManifest(value: unknown): value is TaskManifest {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n typeof (value as { sessions?: unknown }).sessions === \"object\" &&\n (value as { sessions?: unknown }).sessions !== null &&\n !(\"instruction\" in value && \"worlds\" in value)\n );\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\n\n/** TS twin of the Python SDK's GatewayEvalsClient (gatewaysdk/benchmark_hub/evals.py). */\n\nconst EVALUATIONS = \"/api/public/benchmark-containers/evaluations\";\n\nexport type EvalSample = {\n exampleId: string;\n task?: string;\n rolloutIndex?: number;\n prompt?: unknown;\n completion?: unknown;\n reward?: number;\n score?: number;\n correct?: boolean;\n rewards?: Record<string, number>;\n info?: Record<string, unknown>;\n};\n\nexport type CreateEvaluationOptions = {\n model?: string;\n /** A set run to file under; the platform refuses a run that does not admit this result. */\n runId?: string;\n rolloutsPerExample?: number;\n metadata?: Record<string, unknown>;\n};\n\nexport type FinalizeEvaluationOptions = {\n status?: \"COMPLETED\" | \"FAILED\";\n metrics?: Record<string, unknown>;\n};\n\nexport class GatewayEvalsClient {\n constructor(private readonly options: WorldsClientOptions = {}) {}\n\n async createEvaluation(\n versionId: string,\n opts: CreateEvaluationOptions = {},\n ): Promise<string> {\n const body: Record<string, unknown> = { versionId };\n if (opts.model !== undefined) body.model = opts.model;\n if (opts.runId !== undefined) body.runId = opts.runId;\n if (opts.rolloutsPerExample !== undefined)\n body.rolloutsPerExample = opts.rolloutsPerExample;\n if (opts.metadata !== undefined) body.metadata = opts.metadata;\n const answer = await apiRequest<{ evaluationId: string }>(\n this.options,\n \"POST\",\n EVALUATIONS,\n body,\n );\n return answer.evaluationId;\n }\n\n async pushSamples(\n evaluationId: string,\n samples: EvalSample[],\n ): Promise<number> {\n const answer = await apiRequest<{ inserted?: number }>(\n this.options,\n \"POST\",\n `${EVALUATIONS}/${encodeURIComponent(evaluationId)}/samples`,\n { samples },\n );\n return answer.inserted ?? samples.length;\n }\n\n async finalizeEvaluation(\n evaluationId: string,\n opts: FinalizeEvaluationOptions = {},\n ): Promise<string> {\n const body: Record<string, unknown> = {\n status: opts.status ?? \"COMPLETED\",\n };\n if (opts.metrics !== undefined) body.metrics = opts.metrics;\n const answer = await apiRequest<{ status: string }>(\n this.options,\n \"POST\",\n `${EVALUATIONS}/${encodeURIComponent(evaluationId)}/finalize`,\n body,\n );\n return answer.status;\n }\n}\n","/**\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.9\",\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 \"test:integration\": \"vitest run --config vitest.integration.config.ts\",\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.2.8\",\n \"@arizeai/openinference-instrumentation-openai\": \"^4.2.7\"\n },\n \"devDependencies\": {\n \"@anthropic-ai/sdk\": \"^0.91.1\",\n \"@opentelemetry/api\": \"^1.9.0\",\n \"@opentelemetry/exporter-trace-otlp-http\": \"^0.222.0\",\n \"@opentelemetry/resources\": \"^2.11.0\",\n \"@opentelemetry/sdk-trace-base\": \"^2.11.0\",\n \"@opentelemetry/sdk-trace-node\": \"^2.11.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 \"nanoid\": \">=3.3.18\",\n \"esbuild\": \">=0.28.1\"\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 \"nanoid\": \">=3.3.18\",\n \"esbuild\": \">=0.28.1\"\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 { BrowserTier, WorldSurfaceKind } from \"./browser\";\nimport { WorldSurfaceUnavailable } from \"./browser\";\nimport { GatewayEvalsClient, type EvalSample } from \"./evals\";\nimport type { WorldsClientOptions } from \"./index\";\nimport {\n modelToolName,\n schemaFromSignature,\n WorldSession,\n type WorldTaskIdRef,\n type WorldTaskSpec,\n type WorldToolkit,\n type WorldToolSpec,\n} from \"./session\";\nimport {\n openTask,\n TaskSessions,\n type TaskGrade,\n type TaskManifest,\n} from \"./taskSessions\";\n\nexport class TaskRun {\n readonly notes: Record<string, unknown> = {};\n\n constructor(\n readonly runId: string,\n readonly instruction: string,\n readonly model: string,\n readonly sessions: Record<string, WorldSession>,\n readonly manifest: TaskManifest,\n ) {}\n\n session(alias: string): WorldSession {\n const session = this.sessions[alias];\n if (!session)\n throw new Error(\n `task run has no world '${alias}'; its worlds are ${Object.keys(this.sessions).join(\", \")}`,\n );\n return session;\n }\n\n /** Raises when the session was not opened with `surfaces: [\"api\"]`. */\n async api(alias: string): Promise<{ url: string; token?: string }> {\n const surfaces = await this.session(alias).surfaces();\n if (!surfaces.api)\n throw new WorldSurfaceUnavailable(\n \"api\",\n `open '${alias}' with surfaces: ['api']`,\n );\n return { url: surfaces.api.url, token: surfaces.api.token };\n }\n\n /** Each tool is prefixed `<alias>.<tool>` so a model can tell which world a call goes to. */\n async toolkit(): Promise<WorldToolkit> {\n const schemas: WorldToolkit[\"schemas\"] = [];\n const impls: WorldToolkit[\"impls\"] = {};\n const specs: WorldToolSpec[] = [];\n for (const [alias, session] of Object.entries(this.sessions)) {\n const kit = await session.toolkit();\n if (!kit.specs.length) continue;\n for (const spec of kit.specs) {\n const name = `${alias}.${spec.name}`;\n const prefixed: WorldToolSpec = {\n name,\n signature: spec.signature,\n doc: spec.doc,\n inputSchema: spec.inputSchema,\n };\n specs.push(prefixed);\n const schema = schemaFromSignature(prefixed);\n schema.function.name = name;\n schemas.push(schema);\n impls[name] = kit.impls[modelToolName(spec.name)]!;\n }\n }\n return { schemas, impls, specs };\n }\n\n /** Merged into `run.json` under `notes`; a later call overrides an earlier key. */\n record(notes: Record<string, unknown>): void {\n Object.assign(this.notes, notes);\n }\n}\n\nfunction worldRef(\n live: TaskSessions,\n alias: string,\n): { slug: string; ref: string | null; versionId: string; sessionId: string } {\n const { slug, ref } = live.worldRef(alias);\n const session = live.sessions[alias]!;\n return {\n slug,\n ref,\n versionId: session.versionId,\n sessionId: session.sessionId,\n };\n}\n\nasync function fileTaskRun(\n live: TaskSessions,\n runId: string,\n model: string,\n report: string | null,\n grade: TaskGrade,\n agentError: string | null,\n traced: boolean,\n runDir: string,\n options: WorldsClientOptions,\n setRunId: string | undefined,\n): Promise<string> {\n const aliases = live.aliases;\n const anchor = aliases[0]!;\n const worldsMeta = Object.fromEntries(\n aliases.map((alias) => [alias, worldRef(live, alias)]),\n );\n\n const evals = new GatewayEvalsClient(options);\n const evaluationId = await evals.createEvaluation(\n worldRef(live, anchor).versionId,\n {\n model,\n rolloutsPerExample: 1,\n ...(setRunId ? { runId: setRunId } : {}),\n metadata: {\n source: \"worlds-task-run\",\n task: {\n id: live.taskId,\n version: live.taskVersion,\n name: live.name,\n hash: live.hash,\n },\n anchor,\n worlds: worldsMeta,\n runId,\n },\n },\n );\n\n const reward = grade.reward;\n const sample: Record<string, unknown> = {\n exampleId: live.name ?? live.taskId ?? runId,\n task: live.name ?? live.taskId ?? runId,\n rolloutIndex: 0,\n prompt: live.instruction,\n ...(report === null ? {} : { completion: report }),\n rewards: grade.rewards,\n info: {\n sessionId: runId,\n worlds: Object.fromEntries(\n aliases.map((alias) => [\n alias,\n {\n ...worldRef(live, alias),\n reward: grade.worlds[alias]?.reward ?? null,\n },\n ]),\n ),\n ungraded: grade.ungraded,\n traced,\n runDir,\n ...(agentError ? { agentError } : {}),\n },\n };\n if (typeof reward === \"number\") {\n sample.reward = reward;\n sample.score = reward;\n sample.correct = reward >= 1.0;\n }\n await evals.pushSamples(evaluationId, [sample as unknown as EvalSample]);\n await evals.finalizeEvaluation(evaluationId, {\n status: agentError ? \"FAILED\" : \"COMPLETED\",\n metrics: {\n ...(typeof reward === \"number\" ? { avg_reward: reward } : {}),\n reward,\n ...Object.fromEntries(\n Object.entries(grade.rewards).map(([k, v]) => [`rewards.${k}`, v]),\n ),\n },\n });\n return evaluationId;\n}\n\nexport type RunTaskOptions = {\n model: string;\n surfaces?: WorldSurfaceKind[];\n /** Directory the run's own `<runId>/` folder is created under. Default `\"runs\"`. */\n outDir?: string;\n /** Initialize tracing when GATEWAY_* credentials are configured. Default `true`. */\n trace?: boolean;\n /** File one rollout when the run ends. Default `true`. */\n file?: boolean;\n /** Leave every session up instead of closing it when the run ends. Default `false`. */\n keepUp?: boolean;\n reuseWarm?: boolean;\n browserTier?: BrowserTier;\n /** File the rollout under this set run (`runSet` sets it). */\n setRunId?: string;\n options?: WorldsClientOptions;\n};\n\nexport type RunTaskSummary = {\n runId: string;\n taskId: string | null;\n taskVersion: number | null;\n name: string | null;\n instruction: string;\n model: string;\n aliases: string[];\n reward: number | null;\n rewards: Record<string, number>;\n ungraded: string[];\n agentError: string | null;\n report: string | null;\n traced: boolean;\n runDir: string;\n durationSeconds: number;\n notes: Record<string, unknown>;\n filed: boolean;\n evaluationId?: string;\n [extra: string]: unknown;\n};\n\nexport type TaskRunResult =\n string | { report?: unknown; [key: string]: unknown } | null | undefined;\n\nconst describeValue = (value: unknown): string =>\n Array.isArray(value) ? \"array\" : value === null ? \"null\" : typeof value;\n\nconst RESULT_CONTRACT =\n \"return a string report, an object {report?: string, ...} or nothing\";\n\nfunction reportFromResult(result: TaskRunResult): {\n report: string | null;\n extra: Record<string, unknown>;\n} {\n if (result === undefined || result === null)\n return { report: null, extra: {} };\n if (typeof result === \"string\") return { report: result, extra: {} };\n if (typeof result !== \"object\" || Array.isArray(result))\n throw new Error(\n `agent returned ${describeValue(result)}; ${RESULT_CONTRACT}`,\n );\n const { report, ...extra } = result as Record<string, unknown>;\n if (report === undefined || report === null) return { report: null, extra };\n if (typeof report !== \"string\")\n throw new Error(\n `agent returned a report of type ${describeValue(report)}; ${RESULT_CONTRACT}`,\n );\n return { report, extra };\n}\n\n/** Mirrors `gatewaysdk.world_tasks.run_task`. Sessions close unless `keepUp: true`, even when the agent throws, so grading and filing\n * still happen with the error recorded. */\nexport async function runTask(\n ref: string | WorldTaskIdRef | WorldTaskSpec,\n agent: (run: TaskRun) => TaskRunResult | Promise<TaskRunResult>,\n opts: RunTaskOptions,\n): Promise<RunTaskSummary> {\n const runId = `wtr-${randomBytes(6).toString(\"hex\")}`;\n const outDir = opts.outDir ?? \"runs\";\n const runDir = path.join(outDir, runId);\n fs.mkdirSync(runDir, { recursive: true });\n const options = opts.options ?? {};\n\n const live = await openTask(ref, {\n surfaces: opts.surfaces,\n reuseWarm: opts.reuseWarm,\n browserTier: opts.browserTier,\n options,\n });\n const started = Date.now();\n try {\n await live.ready();\n\n let traced = false;\n if (opts.trace !== false) {\n try {\n const { isGatewayConfigured, init } = await import(\"../tracing/init\");\n if (isGatewayConfigured()) {\n init();\n traced = true;\n }\n } catch {\n traced = false;\n }\n }\n\n const taskRun = new TaskRun(\n runId,\n live.instruction ?? \"\",\n opts.model,\n live.sessions,\n await live.manifest(),\n );\n\n let agentError: string | null = null;\n let report: string | null = null;\n let extra: Record<string, unknown> = {};\n try {\n const invoke = () => agent(taskRun);\n const result = traced\n ? await (await import(\"../tracing/session\")).withSession(runId, invoke)\n : await invoke();\n ({ report, extra } = reportFromResult(result));\n } catch (error) {\n const message =\n (error instanceof Error ? error.message : String(error)) ||\n \"Unknown error\";\n agentError = message.slice(0, 2000);\n }\n if (traced)\n await import(\"../tracing/init\")\n .then((tracing) => tracing.flush())\n .catch(() => undefined);\n\n const grade =\n report !== null ? await live.grade({ report }) : await live.grade();\n\n fs.writeFileSync(\n path.join(runDir, \"manifest.json\"),\n JSON.stringify(taskRun.manifest, null, 2),\n );\n fs.writeFileSync(\n path.join(runDir, \"grades.json\"),\n JSON.stringify(grade, null, 2),\n );\n if (report) fs.writeFileSync(path.join(runDir, \"report.md\"), report);\n\n const summary: RunTaskSummary = {\n runId,\n taskId: live.taskId,\n taskVersion: live.taskVersion,\n name: live.name,\n instruction: taskRun.instruction,\n model: opts.model,\n aliases: live.aliases,\n reward: grade.reward,\n rewards: grade.rewards,\n ungraded: grade.ungraded,\n agentError,\n report,\n traced,\n runDir,\n durationSeconds: Math.round((Date.now() - started) / 10) / 100,\n notes: taskRun.notes,\n filed: false,\n ...extra,\n };\n\n if (opts.file !== false) {\n summary.evaluationId = await fileTaskRun(\n live,\n runId,\n opts.model,\n report,\n grade,\n agentError,\n traced,\n runDir,\n options,\n opts.setRunId,\n );\n summary.filed = true;\n }\n\n fs.writeFileSync(\n path.join(runDir, \"run.json\"),\n JSON.stringify(summary, null, 2),\n );\n return summary;\n } finally {\n if (!opts.keepUp) {\n try {\n await live.close({ keepWarm: false });\n } catch {\n // Best-effort: a session that would not close is `task down`'s to report.\n }\n }\n }\n}\n","import { execFileSync } from \"node:child_process\";\n\nexport type Checkout = {\n branch?: string;\n commit?: string;\n repoUrl?: string;\n pr?: { number: number; url: string; title?: string };\n};\n\ntype Env = Record<string, string | undefined>;\n\n/** Labels for the reader, never used to authorize. The PR comes from `GATEWAY_PR_URL`\n * (+ `GATEWAY_PR_TITLE`), else GitHub Actions' `GITHUB_REF=refs/pull/<n>/merge`. */\nexport class CheckoutProvenance {\n constructor(\n private readonly cwd: string,\n private readonly env: Env,\n ) {}\n\n static read(cwd: string = process.cwd(), env: Env = process.env): Checkout {\n return new CheckoutProvenance(cwd, env).checkout();\n }\n\n checkout(): Checkout {\n const commit = this.git(\"rev-parse\", \"HEAD\");\n if (!commit) return this.withPr({});\n const branch =\n this.env.GITHUB_HEAD_REF || this.git(\"rev-parse\", \"--abbrev-ref\", \"HEAD\");\n const remote = this.git(\"config\", \"--get\", \"remote.origin.url\");\n return this.withPr({\n commit,\n ...(branch && branch !== \"HEAD\" ? { branch } : {}),\n ...(remote ? { repoUrl: CheckoutProvenance.withoutCredentials(remote) } : {}),\n });\n }\n\n /** Security: credentials are stripped; scp-style `git@host:org/repo` has none and is kept. */\n static withoutCredentials(url: string): string {\n return url.replace(/^([a-z][a-z0-9+.-]*:\\/\\/)[^@/]+@/i, \"$1\");\n }\n\n private withPr(checkout: Checkout): Checkout {\n const pr = this.pullRequest();\n return pr ? { ...checkout, pr } : checkout;\n }\n\n private pullRequest(): Checkout[\"pr\"] | undefined {\n const url = this.env.GATEWAY_PR_URL;\n const fromUrl = url ? /\\/pull\\/(\\d+)/.exec(url)?.[1] : undefined;\n if (url && fromUrl)\n return {\n number: Number(fromUrl),\n url,\n ...(this.env.GATEWAY_PR_TITLE ? { title: this.env.GATEWAY_PR_TITLE } : {}),\n };\n const number = /^refs\\/pull\\/(\\d+)\\//.exec(this.env.GITHUB_REF ?? \"\")?.[1];\n const server = this.env.GITHUB_SERVER_URL;\n const repo = this.env.GITHUB_REPOSITORY;\n if (!number || !server || !repo) return undefined;\n return { number: Number(number), url: `${server}/${repo}/pull/${number}` };\n }\n\n private git(...args: string[]): string | undefined {\n try {\n const out = execFileSync(\"git\", args, {\n cwd: this.cwd,\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n timeout: 5_000,\n })\n .toString()\n .trim();\n return out || undefined;\n } catch {\n return undefined;\n }\n }\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\nimport type { BrowserTier, WorldSurfaceKind } from \"./browser\";\nimport { CheckoutProvenance, type Checkout } from \"./checkoutProvenance\";\nimport {\n runTask,\n type RunTaskSummary,\n type TaskRun,\n type TaskRunResult,\n} from \"./taskRun\";\n\nconst SET_RUNS = \"/api/public/set-runs\";\n\nexport type SetRunDoc = {\n id: string;\n status: \"running\" | \"completed\" | \"failed\";\n model: string | null;\n source: string | null;\n taskSetDatasetId: string | null;\n actor: { kind: string; id: string; name?: string } | null;\n git: Checkout | null;\n progress: { done: number; planned: number };\n score: { mean: number | null; gradedTasks: number; ungradedTasks: number };\n tasks: Array<{\n worldTaskId: string;\n datasetItemId: string;\n name: string;\n evaluationId: string | null;\n sampleId: string | null;\n status: \"pending\" | \"completed\" | \"failed\";\n reward: number | null;\n checks: Array<{\n key: string;\n outcome: \"passed\" | \"failed\" | \"ungraded\";\n value: number | null;\n }>;\n }>;\n};\n\nexport type RunSetOptions = {\n model: string;\n /** Default `\"sdk\"`; the CLI passes `\"cli\"`. */\n source?: \"cli\" | \"sdk\";\n /** Default: read from the working directory; `null` records none. */\n git?: Checkout | null;\n surfaces?: WorldSurfaceKind[];\n browserTier?: BrowserTier;\n outDir?: string;\n trace?: boolean;\n onTask?: (summary: RunTaskSummary) => void;\n options?: WorldsClientOptions;\n};\n\n/** `failed`: an agent raised, a task could not run, or the platform stored the run as anything but completed. */\nexport type RunSetResult = {\n setRun: SetRunDoc;\n tasks: RunTaskSummary[];\n failed: boolean;\n closedAsRequested: boolean;\n};\n\n/** A low or missing reward is a result, not a failure; every task runs even after one fails. */\nexport async function runSet(\n datasetId: string,\n agent: (run: TaskRun) => TaskRunResult | Promise<TaskRunResult>,\n opts: RunSetOptions,\n): Promise<RunSetResult> {\n const options = opts.options ?? {};\n const git = opts.git === undefined ? CheckoutProvenance.read() : opts.git;\n const opened = await apiRequest<SetRunDoc>(options, \"POST\", SET_RUNS, {\n datasetId,\n model: opts.model,\n source: opts.source ?? \"sdk\",\n ...(git && Object.keys(git).length ? { git } : {}),\n });\n\n const close = (status: \"failed\" | \"completed\") =>\n apiRequest<SetRunDoc>(\n options,\n \"POST\",\n `${SET_RUNS}/${encodeURIComponent(opened.id)}/close`,\n { status },\n );\n // Ctrl-C closes the run failed before exiting instead of leaving it open.\n const onInterrupt = () => {\n void close(\"failed\").finally(() => process.exit(130));\n };\n process.once(\"SIGINT\", onInterrupt);\n const planned = await runPlannedTasks(opened, agent, opts, options).finally(\n () => process.off(\"SIGINT\", onInterrupt),\n );\n const { tasks, failed } = planned;\n const requested = failed ? \"failed\" : \"completed\";\n const setRun = await close(requested);\n return {\n setRun,\n tasks,\n failed: failed || setRun.status !== \"completed\",\n closedAsRequested: setRun.status === requested,\n };\n}\n\n/** Never throws, so the caller always gets to close the run. */\nasync function runPlannedTasks(\n opened: SetRunDoc,\n agent: (run: TaskRun) => TaskRunResult | Promise<TaskRunResult>,\n opts: RunSetOptions,\n options: WorldsClientOptions,\n): Promise<{ tasks: RunTaskSummary[]; failed: boolean }> {\n const tasks: RunTaskSummary[] = [];\n let failed = false;\n for (const task of opened.tasks) {\n try {\n const summary = await runTask(task.worldTaskId, agent, {\n model: opts.model,\n surfaces: opts.surfaces,\n browserTier: opts.browserTier,\n outDir: opts.outDir,\n trace: opts.trace,\n setRunId: opened.id,\n options,\n });\n tasks.push(summary);\n failed ||= summary.agentError !== null;\n opts.onTask?.(summary);\n } catch (error) {\n failed = true;\n const message = error instanceof Error ? error.message : String(error);\n process.stderr.write(`task ${task.name} could not run: ${message}\\n`);\n }\n }\n return { tasks, failed };\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\n/** What `localTreeState(dir)` reports: the tracked meta and the edits since its base. */\nexport type TreeState = {\n meta: { slug?: string; baseFiles?: Record<string, string> } | null;\n dirty: string[];\n clean: boolean;\n};\n\nexport class CheckoutRefusedError extends Error {\n constructor(message: string) {\n super(`checkout refused: ${message}`);\n this.name = \"CheckoutRefusedError\";\n }\n}\n\nconst NAMED_EDITS = 3;\n\n/**\n * Where a pull lands, decided before a byte is downloaded (P-20).\n *\n * - No target: `./<slug>`, de-duplicated with `-1`/`-2`; an existing dir is\n * never entered.\n * - Explicit target: absent or empty → used as-is; a clean checkout of the\n * same world → replaced (its base files are cleared first so files the new\n * version dropped do not linger); local edits, another world's checkout or\n * an untracked non-empty dir → refused unless `force`, which discards the\n * checkout's base files *and* its local edits (added files included) so the\n * result is the pulled version, nothing else the archive would see.\n * - A relative target stays under the current directory; one that escapes it\n * (`../x`) is refused — an absolute path is the explicit way elsewhere (P-21).\n *\n * Python twin: `gatewaysdk.benchmark_hub.checkout.CheckoutTarget`.\n */\nexport class CheckoutTarget {\n private constructor(\n readonly dir: string,\n /** Files of the checkout being replaced (its base + its local edits); removed by `clear()`. */\n readonly replaces: string[],\n ) {}\n\n static resolve(\n slug: string,\n target: string | undefined,\n opts: { cwd: string; force: boolean; state: (dir: string) => TreeState },\n ): CheckoutTarget {\n if (target === undefined) return CheckoutTarget.fresh(slug, opts.cwd);\n return CheckoutTarget.explicit(\n CheckoutTarget.confined(target, opts.cwd),\n slug,\n opts,\n );\n }\n\n /** The absolute destination; a relative target may not resolve above `cwd`. */\n private static confined(target: string, cwd: string): string {\n const dir = path.resolve(cwd, target);\n if (path.isAbsolute(target)) return dir;\n const rel = path.relative(cwd, dir);\n if (rel === \"\" || (!rel.startsWith(\"..\") && !path.isAbsolute(rel)))\n return dir;\n throw new CheckoutRefusedError(\n `--target ${target} resolves outside the current directory (${cwd}) — run from that directory, or pass an absolute path`,\n );\n }\n\n private static fresh(slug: string, cwd: string): CheckoutTarget {\n const base = path.join(cwd, slug);\n let dir = base;\n let i = 1;\n while (fs.existsSync(dir)) dir = `${base}-${i++}`;\n return new CheckoutTarget(dir, []);\n }\n\n private static explicit(\n dir: string,\n slug: string,\n opts: { force: boolean; state: (dir: string) => TreeState },\n ): CheckoutTarget {\n if (!fs.existsSync(dir)) return new CheckoutTarget(dir, []);\n if (!fs.statSync(dir).isDirectory())\n throw new CheckoutRefusedError(`${dir} is a file`);\n if (fs.readdirSync(dir).length === 0) return new CheckoutTarget(dir, []);\n const state = opts.state(dir);\n const refusal = CheckoutTarget.refusal(dir, slug, state);\n if (refusal === null || opts.force)\n return new CheckoutTarget(dir, CheckoutTarget.tracked(state));\n throw new CheckoutRefusedError(refusal);\n }\n\n /** Base files plus local edits — everything the archive would see in the old\n * checkout. `.env-metadata.json` is local input: a key that would leave the\n * checkout (`../x`, `/etc/x`) is dropped, never removed. */\n private static tracked(state: TreeState): string[] {\n if (!state.meta?.baseFiles) return [];\n return [\n ...new Set([...Object.keys(state.meta.baseFiles), ...state.dirty]),\n ]\n .filter(CheckoutTarget.confinedRel)\n .sort();\n }\n\n private static confinedRel(rel: string): boolean {\n if (rel === \"\" || path.isAbsolute(rel)) return false;\n return !rel.split(/[\\\\/]/).includes(\"..\");\n }\n\n /** Why `dir` cannot be overwritten, or null when it is a clean checkout of `slug`. */\n private static refusal(\n dir: string,\n slug: string,\n state: TreeState,\n ): string | null {\n if (!state.meta?.baseFiles)\n return `${dir} is not empty and is not a checkout of \"${slug}\" — pick an empty --target, or pass --force to overwrite it`;\n if (state.meta.slug !== undefined && state.meta.slug !== slug)\n return `${dir} tracks \"${state.meta.slug}\", not \"${slug}\" — pick another --target, or pass --force to replace it`;\n if (state.clean) return null;\n const n = state.dirty.length;\n const named = state.dirty.slice(0, NAMED_EDITS).join(\", \");\n const more = n > NAMED_EDITS ? `, +${n - NAMED_EDITS} more` : \"\";\n return `${dir} has ${n} local edit${n === 1 ? \"\" : \"s\"} not pushed (${named}${more}) — push or propose them first, or pass --force to discard them`;\n }\n\n /** Remove the replaced checkout's files (and the dirs they leave empty). */\n clear(): void {\n for (const rel of this.replaces) {\n const abs = path.join(this.dir, rel);\n fs.rmSync(abs, { force: true });\n this.pruneEmptyParents(path.dirname(abs));\n }\n }\n\n private pruneEmptyParents(from: string): void {\n let cur = from;\n while (cur !== this.dir && cur.startsWith(this.dir)) {\n if (fs.existsSync(cur) && fs.readdirSync(cur).length > 0) return;\n fs.rmSync(cur, { recursive: true, force: true });\n cur = path.dirname(cur);\n }\n }\n}\n","/**\n * What a directory IS, decided once for the TS SDK.\n *\n * `WorldDir.open(dir)` is the one detector this package has: the benchmark\n * front door (`classifyTree`, `detectEnvKind`, `harborTaskDirs`,\n * `verifiersPackage` in ../benchmarks) and the hub client (`collectArchiveRelPaths`,\n * `computeContentHash`, the contract-version lookup in ./hub.ts) are facades\n * over it. Twin of `gatewaysdk.environment.world.World` (Python) and\n * `packages/shared/src/world` (the platform); the corpus under\n * `conformance/worlds/` pins all three to the same answers.\n */\nimport { createHash } from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nexport const WORLD_MANIFEST = \"gateway-env.toml\";\nexport const API_BUNDLE_MANIFEST = \"gateway-api-world.toml\";\nexport const BUNDLED_WORLD_PREFIX = \"server/world/\";\nexport const CONNECTOR_SPEC = \"connector.toml\";\nexport const PYPROJECT = \"pyproject.toml\";\nexport const BENCHMARK_CONFIG = \"benchmark.json\";\nexport const WORLD_SCHEMA_MARKERS = [\"schema/world.json\", \"schema/runtime.json\", \"schema/lock.json\"];\nconst WORLD_ROOT_MARKERS = [CONNECTOR_SPEC, ...WORLD_SCHEMA_MARKERS];\n/** Root markers that widen the archive to every ordinary root file: a world's\n * executable contract and a benchmark's config/fixtures live at the root. */\nconst BROAD_ROOT_MARKERS = [WORLD_MANIFEST, API_BUNDLE_MANIFEST, BENCHMARK_CONFIG];\nconst SKIPPED_DIRS = new Set([\"dist\", \"build\", \"outputs\", \"__pycache__\", \"node_modules\"]);\n\n/** One entry the archive rules dropped: a whole directory (`name/`, `files`\n * counted) or a single file. */\nexport type Exclusion = { path: string; files: number };\n\n/** The runner's kind: what the dispatcher executes a pushed tree as. */\nexport type EnvKind = \"api\" | \"mock-tools\" | \"harbor\" | \"verifiers-v1\" | \"verifiers\";\n\n// The `verifiers.v1` namespace first shipped in verifiers 0.2.0: a v1 package\n// pins verifiers>=0.2 (or ~=0.2 / ==0.2.* / >=1 / ==1.*) in pyproject and/or\n// imports the namespace or subclasses Taskset alongside a v1-style `__all__`.\nconst V1_DEP = /[\"']verifiers\\s*(?:\\[[^\\]]*\\])?\\s*(?:>=|~=|==|>)\\s*(?:0\\.(?:[2-9]\\d*|[1-9]\\d+)|[1-9]\\d*)/;\nconst V1_IMPORT = /^\\s*(?:from\\s+verifiers\\.v1\\s+import\\b|from\\s+verifiers\\s+import\\s+v1\\b|import\\s+verifiers\\.v1\\b)/m;\nconst V1_TASKSET = /class\\s+\\w+\\s*\\(\\s*(?:(?:vf|v1|verifiers(?:\\.v1)?)\\.)?Taskset\\s*[,)]/;\nconst HARBOR_TASK = /^(?:tasks\\/)?([^/]+)\\/task\\.toml$/;\n\nconst skippedDir = (name: string): boolean =>\n name.startsWith(\".\") || SKIPPED_DIRS.has(name) || name.endsWith(\".egg-info\");\n\n/** Python's `sorted()` order for relpaths: code points, not UTF-16 units. */\nconst byCodePoint = (a: string, b: string): number => Buffer.compare(Buffer.from(a, \"utf-8\"), Buffer.from(b, \"utf-8\"));\n\nexport class WorldDir {\n private pathsMemo: string[] | undefined;\n\n private constructor(\n readonly dir: string,\n /** Where the authored world lives: `\"\"` for a world stored as itself,\n * `server/world/` for one stored as its api bundle. */\n readonly worldRoot: \"\" | typeof BUNDLED_WORLD_PREFIX,\n ) {}\n\n static open(dir: string): WorldDir {\n const present = (rel: string) => fs.existsSync(path.join(dir, rel));\n const bundled = present(API_BUNDLE_MANIFEST) && WORLD_ROOT_MARKERS.some((m) => present(BUNDLED_WORLD_PREFIX + m));\n return new WorldDir(dir, bundled ? BUNDLED_WORLD_PREFIX : \"\");\n }\n\n // ── Files ──────────────────────────────────────────────────────────────\n\n has(rel: string): boolean {\n return fs.existsSync(path.join(this.dir, rel));\n }\n\n text(rel: string): string | null {\n try {\n return fs.readFileSync(path.join(this.dir, rel), \"utf-8\");\n } catch {\n return null;\n }\n }\n\n /** A path under the authored world's root. */\n worldPath(rel: string): string {\n return this.worldRoot + rel;\n }\n\n /** Every regular file the archive rules keep (`_archive.py`: no hidden,\n * dist, build, outputs, pycache, node_modules or egg-info directories), as\n * sorted relpaths. Root files enter only when a Gateway manifest or\n * benchmark.json widens the root, or they are README.md, pyproject.toml or\n * Python. */\n get archivePaths(): string[] {\n if (this.pathsMemo) return this.pathsMemo;\n const broad = BROAD_ROOT_MARKERS.some((m) => this.has(m));\n const out: string[] = [];\n const walk = (rel: string) => {\n for (const entry of fs.readdirSync(rel ? path.join(this.dir, rel) : this.dir, { withFileTypes: true })) {\n const child = rel ? `${rel}/${entry.name}` : entry.name;\n if (entry.isDirectory()) {\n if (!skippedDir(entry.name)) walk(child);\n } else if (entry.isFile() && !entry.name.startsWith(\".\")) {\n const rootKept =\n broad || [\"README.md\", PYPROJECT, ...BROAD_ROOT_MARKERS].includes(entry.name) || entry.name.endsWith(\".py\");\n if (rel || rootKept) out.push(child);\n }\n }\n };\n walk(\"\");\n return (this.pathsMemo = out.sort(byCodePoint));\n }\n\n /** What the archive rules leave out, collapsed to the entry that decided\n * it: a pruned directory counts its files once, a dropped root file is\n * named. Dot entries (`.git/`, `.gateway/`, `.gitignore`) are the one\n * universal convention and stay unreported. `push` prints the rest so\n * nothing disappears silently. */\n get exclusions(): Exclusion[] {\n const kept = new Set(this.archivePaths);\n const out: Exclusion[] = [];\n const filesUnder = (rel: string): string[] =>\n fs.readdirSync(path.join(this.dir, rel), { withFileTypes: true }).flatMap((entry) => {\n const child = `${rel}/${entry.name}`;\n if (entry.isDirectory()) return filesUnder(child);\n return entry.isFile() ? [child] : [];\n });\n for (const entry of fs.readdirSync(this.dir, { withFileTypes: true }).sort((a, b) => byCodePoint(a.name, b.name))) {\n if (entry.name.startsWith(\".\")) continue;\n if (entry.isDirectory()) {\n const all = filesUnder(entry.name);\n const missing = all.filter((rel) => !kept.has(rel));\n if (missing.length === 0) continue;\n const whole = missing.length === all.length;\n out.push(...(whole ? [{ path: `${entry.name}/`, files: missing.length }] : missing.map((p) => ({ path: p, files: 1 }))));\n continue;\n }\n // A file, or a symlink to anything: the archive never follows a link.\n if (!kept.has(entry.name)) out.push({ path: entry.name, files: 1 });\n }\n return out;\n }\n\n /** A root `.gitignore` is present: the Python SDK honours it when\n * collecting, this package does not reimplement gitignore. */\n get hasRootGitignore(): boolean {\n return this.has(\".gitignore\");\n }\n\n /** SHA-256 over `utf8(\"file:\" + relpath)` + bytes per archive path in\n * sorted order: the version's identity, byte-compatible with\n * `_archive.compute_content_hash` and Prime Intellect. */\n get contentHash(): string {\n const hasher = createHash(\"sha256\");\n for (const rel of this.archivePaths) {\n hasher.update(Buffer.from(`file:${rel}`, \"utf-8\"));\n hasher.update(fs.readFileSync(path.join(this.dir, rel)));\n }\n return hasher.digest(\"hex\");\n }\n\n // ── Markers ────────────────────────────────────────────────────────────\n\n get isApiBundle(): boolean {\n return this.has(API_BUNDLE_MANIFEST);\n }\n\n get hasManifest(): boolean {\n return this.has(this.worldPath(WORLD_MANIFEST));\n }\n\n get hasSchemaMarker(): boolean {\n return WORLD_SCHEMA_MARKERS.some((m) => this.has(this.worldPath(m)));\n }\n\n /** Harbor task dirs, relative to the tree: `tasks/<name>` when a `tasks/`\n * dir holds them, else the root `<name>` dirs. */\n taskDirs(): string[] {\n const names = new Set<string>();\n for (const rel of this.archivePaths) {\n const m = HARBOR_TASK.exec(rel);\n if (m) names.add(rel.startsWith(\"tasks/\") ? `tasks/${m[1]}` : m[1]!);\n }\n const under = [...names].filter((n) => n.startsWith(\"tasks/\"));\n return (under.length ? under : [...names]).sort();\n }\n\n /** The Python package of a verifiers tree (`<pkg>/__init__.py` or\n * `src/<pkg>/__init__.py`), or null. */\n pythonPackage(): { name: string; init: string } | null {\n if (!this.has(PYPROJECT)) return null;\n for (const base of [\"\", \"src/\"]) {\n const init = this.archivePaths.find((rel) => {\n const m = /^([^/]+)\\/__init__\\.py$/.exec(rel.startsWith(base) ? rel.slice(base.length) : \"\");\n return m !== null && m[1] !== \"tests\";\n });\n if (init) return { name: init.slice(base.length).split(\"/\")[0]!, init };\n }\n return null;\n }\n\n /** The package targets the `verifiers.v1` API: read from the root\n * pyproject and every archived Python module. */\n get isVerifiersV1(): boolean {\n for (const rel of this.archivePaths) {\n if (rel !== PYPROJECT && !rel.endsWith(\".py\")) continue;\n const text = this.text(rel);\n if (text === null) continue;\n if (rel === PYPROJECT ? V1_DEP.test(text) : V1_IMPORT.test(text) || (text.includes(\"__all__\") && V1_TASKSET.test(text)))\n return true;\n }\n return false;\n }\n\n // ── The answer ─────────────────────────────────────────────────────────\n\n /** The runner's kind (`detect_env_kind`): api / mock-tools win over\n * everything, a harbor task tree next, then the verifiers API version. */\n get kind(): EnvKind {\n if (this.isApiBundle) return \"api\";\n if (this.has(WORLD_MANIFEST)) return \"mock-tools\";\n if (this.taskDirs().length) return \"harbor\";\n return this.isVerifiersV1 ? \"verifiers-v1\" : \"verifiers\";\n }\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { gunzipSync } from \"node:zlib\";\n\n/**\n * The sdk-ts reader of a world's gzipped tar bundle — the twin of the\n * platform's `packages/shared/src/server/worlds/tar.ts` walker. A bundle\n * `pull`/`checkout` downloads may have been written by any of the three\n * writers on the platform, so the walk understands every way a name can\n * travel:\n * • the 100-byte ustar `name` field, UTF-8 (this SDK's own writer),\n * • a GNU `L` long-name member naming the member that follows,\n * • a PAX `x` header whose `path=` record overrides the next name — what\n * Python's `tarfile` (the Python SDK's writer) emits for every\n * non-ASCII or >100-byte name, leaving a `?`-replaced ASCII fallback in\n * the ustar field,\n * • the POSIX ustar `prefix` field (bytes 345–500) joined as `prefix/name`.\n * Reading only the ustar field silently corrupts the other three (cold-batch\n * P-05: `ünïcödé ✓.txt` pulled as `?n?c?d? ?.txt`).\n */\n\nexport const TAR_FILE_MODE = 0o644;\nexport const TAR_EXEC_MODE = 0o755;\n\n/** The only mode detail a world keeps: executable or not. */\nexport function archiveMode(mode: number): number {\n return (mode & 0o111) !== 0 ? TAR_EXEC_MODE : TAR_FILE_MODE;\n}\n\nexport type TarMember = {\n name: string;\n bytes: Buffer;\n typeflag: string;\n mode: number;\n};\n\nfunction field(header: Buffer, start: number, end: number): string {\n return header.subarray(start, end).toString(\"utf-8\").replace(/\\0.*$/, \"\");\n}\n\nfunction octalField(header: Buffer, start: number, end: number): number {\n return parseInt(field(header, start, end).trim(), 8);\n}\n\n/** `path=` from a PAX extended-header payload (`LEN key=value\\n` records). */\nfunction paxPath(body: Buffer): string | null {\n let off = 0;\n let found: string | null = null;\n while (off < body.length) {\n const sp = body.indexOf(0x20, off);\n if (sp === -1) break;\n const len = parseInt(body.subarray(off, sp).toString(\"ascii\"), 10);\n if (!Number.isFinite(len) || len <= 0) break;\n const record = body.subarray(sp + 1, off + len);\n const eq = record.indexOf(0x3d);\n const key = eq === -1 ? \"\" : record.subarray(0, eq).toString(\"utf-8\");\n if (key === \"path\")\n found = record\n .subarray(eq + 1)\n .toString(\"utf-8\")\n .replace(/\\n$/, \"\");\n off += len;\n }\n return found;\n}\n\nexport class TarArchive {\n private constructor(private readonly tar: Buffer) {}\n\n static fromGzip(bundle: Buffer): TarArchive {\n return new TarArchive(gunzipSync(bundle));\n }\n\n static fromTar(tar: Buffer): TarArchive {\n return new TarArchive(tar);\n }\n\n /** Every member, names fully resolved; metadata members are consumed. */\n *members(): Generator<TarMember> {\n const tar = this.tar;\n let offset = 0;\n let pendingName: string | null = null;\n while (offset + 512 <= tar.length) {\n const header = tar.subarray(offset, offset + 512);\n offset += 512;\n if (header.every((b) => b === 0)) break;\n const size = octalField(header, 124, 136) || 0;\n const mode = octalField(header, 100, 108) || TAR_FILE_MODE;\n const typeflag = String.fromCharCode(header[156] ?? 0);\n const bytes = tar.subarray(offset, offset + size);\n offset += Math.ceil(size / 512) * 512;\n if (typeflag === \"L\") {\n pendingName = bytes.toString(\"utf-8\").replace(/\\0.*$/, \"\");\n continue;\n }\n if (typeflag === \"x\") {\n pendingName = paxPath(bytes) ?? pendingName;\n continue;\n }\n if (typeflag === \"K\" || typeflag === \"g\") continue;\n const name = pendingName ?? TarArchive.ustarName(header);\n pendingName = null;\n yield { name: name.replace(/^\\.\\//, \"\"), bytes, typeflag, mode };\n }\n }\n\n private static ustarName(header: Buffer): string {\n const name = field(header, 0, 100);\n const magic = header.subarray(257, 262).toString(\"ascii\");\n const prefix = magic === \"ustar\" ? field(header, 345, 500) : \"\";\n return prefix ? `${prefix}/${name}` : name;\n }\n\n /** Regular files only, confined to `dir` (absolute or `..` names are\n * skipped, never written). Returns the number of files written. */\n extractTo(dir: string): number {\n let written = 0;\n for (const member of this.members()) {\n if (member.typeflag !== \"0\" && member.typeflag !== \"\\0\") continue;\n if (!TarArchive.isConfined(member.name)) continue;\n const target = path.join(dir, member.name);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n const mode = archiveMode(member.mode);\n fs.writeFileSync(target, member.bytes, { mode });\n fs.chmodSync(target, mode);\n written++;\n }\n return written;\n }\n\n private static isConfined(name: string): boolean {\n if (name === \"\" || name.startsWith(\"/\")) return false;\n return !name.split(\"/\").includes(\"..\");\n }\n}\n","import { createHash } from \"node:crypto\";\nimport { gzipSync } from \"node:zlib\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\nimport { CheckoutTarget } from \"./checkoutTarget\";\nimport { WorldDir, type Exclusion } from \"./worldDir\";\nimport { TarArchive, TAR_FILE_MODE, archiveMode } from \"./tar\";\n\n/**\n * The working-dir half of the TS CLI: push / pull / checkout / status /\n * branch / tag / propose — a faithful port of the Python client\n * (`gatewaysdk/benchmark_hub/client.py` + `_archive.py`).\n *\n * The content hash is the version's identity and is byte-compatible with\n * Prime Intellect: `WorldDir.contentHash` (./worldDir.ts) computes it here,\n * `WorldTree.contentHash` on the platform and `_archive.compute_content_hash`\n * in the Python SDK; the conformance corpus pins the three to the same bytes.\n *\n * One deliberate refusal, same policy as the web upload path: a bundle with\n * a ROOT `.gitignore` is refused rather than mis-hashed — the Python CLI\n * honors it via `gitignore_parser`, and an imperfect reimplementation here\n * would produce a wrong, Prime-incompatible hash silently.\n */\n\nexport const DEFAULT_BRANCH = \"main\";\nconst META_RELPATH = path.join(\".gateway\", \".env-metadata.json\");\n\n/** The archive-visible files of a working dir, as sorted relpaths\n * (`WorldDir.archivePaths`). Throws on a root .gitignore (see the header). */\nexport function collectArchiveRelPaths(dir: string): string[] {\n const world = WorldDir.open(dir);\n if (world.hasRootGitignore) {\n throw new Error(\n \"This bundle has a root .gitignore, which the Python CLI honors via \" +\n \"gitignore_parser. Reimplementing that imperfectly here would \" +\n \"silently produce a different content hash, so the TS CLI refuses. \" +\n \"Remove the .gitignore (or bake its effect into the tree) and retry.\",\n );\n }\n return world.archivePaths;\n}\n\nexport function computeContentHash(dir: string): string {\n collectArchiveRelPaths(dir);\n return WorldDir.open(dir).contentHash;\n}\n\n// ── deterministic tar.gz writer ─────────────────────────────────────────────\n\nfunction octal(value: number, length: number): Buffer {\n return Buffer.from(\n value.toString(8).padStart(length - 1, \"0\") + \"\\0\",\n \"ascii\",\n );\n}\n\n/** The two modes a stored world file can have: the tar (and `pull`) keep\n * only whether a file is executable — `tests/test.sh` in a harbor tree must\n * still run after a round trip. Owner/mtime are cleared for determinism. */\nconst FILE_MODE = TAR_FILE_MODE;\nexport { archiveMode };\n\nfunction tarHeader(name: string, size: number, mode = FILE_MODE): Buffer {\n const header = Buffer.alloc(512);\n header.write(name, 0, 100, \"utf-8\");\n octal(mode, 8).copy(header, 100);\n octal(0, 8).copy(header, 108); // uid\n octal(0, 8).copy(header, 116); // gid\n octal(size, 12).copy(header, 124);\n octal(0, 12).copy(header, 136); // mtime = 0 (deterministic)\n header.write(\" \", 148, \"ascii\"); // checksum placeholder = spaces\n header.write(\"0\", 156, \"ascii\"); // regular file\n header.write(\"ustar\", 257, \"ascii\");\n header.write(\"00\", 263, \"ascii\");\n let sum = 0;\n for (const byte of header) sum += byte;\n header.write(sum.toString(8).padStart(6, \"0\") + \"\\0 \", 148, \"ascii\");\n return header;\n}\n\nfunction tarMember(name: string, payload: Buffer, mode: number): Buffer[] {\n const parts: Buffer[] = [];\n const nameBytes = Buffer.byteLength(name, \"utf-8\");\n if (nameBytes > 100) {\n // GNU long name: an 'L' member whose body is the real name.\n const body = Buffer.from(name + \"\\0\", \"utf-8\");\n const lHeader = tarHeader(\"././@LongLink\", body.length);\n lHeader.write(\"L\", 156, \"ascii\");\n let sum = 0;\n lHeader.write(\" \", 148, \"ascii\");\n for (const byte of lHeader) sum += byte;\n lHeader.write(sum.toString(8).padStart(6, \"0\") + \"\\0 \", 148, \"ascii\");\n parts.push(lHeader, body);\n const pad = body.length % 512 === 0 ? 0 : 512 - (body.length % 512);\n if (pad) parts.push(Buffer.alloc(pad));\n parts.push(tarHeader(name.slice(0, 100), payload.length, mode));\n } else {\n parts.push(tarHeader(name, payload.length, mode));\n }\n parts.push(payload);\n const pad = payload.length % 512 === 0 ? 0 : 512 - (payload.length % 512);\n if (pad) parts.push(Buffer.alloc(pad));\n return parts;\n}\n\n/** A deterministic .tar.gz of the source files (node's gzip stamps no mtime,\n * matching the Python's mtime=0 gzip). */\nexport function buildSourceTarball(dir: string): Buffer {\n const parts: Buffer[] = [];\n for (const relPath of collectArchiveRelPaths(dir)) {\n const abs = path.join(dir, relPath);\n parts.push(\n ...tarMember(\n relPath,\n fs.readFileSync(abs),\n archiveMode(fs.statSync(abs).mode),\n ),\n );\n }\n parts.push(Buffer.alloc(1024)); // end-of-archive\n return gzipSync(Buffer.concat(parts), { level: 9 });\n}\n\n// ── local metadata (.gateway/.env-metadata.json) ────────────────────────────\n\nexport type LocalMeta = Record<string, unknown> & {\n slug?: string;\n /** Branch the checkout tracks; absent on a tag (detached) checkout. */\n branch?: string;\n /** Tag the checkout was taken from: immutable, so `push` refuses to move it. */\n tag?: string;\n versionId?: string;\n contentHash?: string;\n baseFiles?: Record<string, string>;\n};\n\nexport function readLocalMeta(dir: string): LocalMeta | null {\n try {\n const raw = fs.readFileSync(path.join(dir, META_RELPATH), \"utf-8\");\n const parsed = JSON.parse(raw);\n return parsed && typeof parsed === \"object\" ? (parsed as LocalMeta) : null;\n } catch {\n return null;\n }\n}\n\n/** The slug a push of `dir` lands on: an explicit one, else the slug the dir\n * was pushed to or pulled from (its `.gateway` meta), else the pyproject\n * name, else the directory's name — so a tracked checkout never creates a\n * second world named after its folder. */\nexport function pushSlug(dir: string, explicit?: string): string {\n return resolvePushSlug(dir, { explicit }).slug;\n}\n\nexport type SlugDeclaration = { source: string; slug: string };\n\nexport type PushSlugResolution = {\n slug: string;\n /** Where the slug came from (`--slug`, `.gateway metadata`, `benchmark.json`, `pyproject.toml`, `directory name`). */\n source: string;\n /** The slug the dir's `.gateway/.env-metadata.json` tracks from an earlier push or pull, if any. */\n tracked: string | null;\n /** What the tree itself declares (a caller's benchmark.json, then pyproject.toml), in precedence order. */\n declared: SlugDeclaration[];\n /** A declaration the tracked slug does not match — set only when the tracked slug won without `--slug`. */\n conflict: SlugDeclaration | null;\n};\n\n/** The platform's collision suffix: `acme-2` minted for a taken `acme`. */\nconst MINTED_SUFFIX = /^-\\d+$/;\n\n/** `pushSlug` with its provenance. `declared` are the caller's own slug sources\n * (e.g. `{ \"benchmark.json\": \"x\" }`), consulted before pyproject. A tracked slug\n * that disagrees with what the tree declares is reported as `conflict` so a\n * front door can refuse: that is how a directory pushed once with `--slug X`\n * silently landed every later push on X while its benchmark.json said Y. The\n * platform's collision suffix (`acme-2` minted for a taken `acme`) is not a\n * conflict; any other difference is (`acme-e2e` for `acme` was the mix-up). */\nexport function resolvePushSlug(\n dir: string,\n opts: { explicit?: string; declared?: Record<string, string | null | undefined> } = {},\n): PushSlugResolution {\n const meta = readLocalMeta(dir);\n const tracked = typeof meta?.slug === \"string\" && meta.slug ? meta.slug : null;\n const declared = Object.entries({ ...(opts.declared ?? {}), \"pyproject.toml\": readPyproject(dir).name })\n .filter((entry): entry is [string, string] => typeof entry[1] === \"string\" && entry[1] !== \"\")\n .map(([source, slug]) => ({ source, slug }));\n const base = { tracked, declared, conflict: null };\n if (opts.explicit) return { ...base, slug: opts.explicit, source: \"--slug\" };\n if (tracked) {\n const minted = (d: SlugDeclaration) => tracked.startsWith(d.slug) && MINTED_SUFFIX.test(tracked.slice(d.slug.length));\n const conflict = declared.find((d) => d.slug !== tracked && !minted(d)) ?? null;\n return { ...base, slug: tracked, source: \".gateway metadata\", conflict };\n }\n const first = declared[0];\n if (first) return { ...base, slug: first.slug, source: first.source };\n return { ...base, slug: path.basename(path.resolve(dir)), source: \"directory name\" };\n}\n\n/** The refusal a front door raises on `PushSlugResolution.conflict`: both slugs, both sources, every way out. */\nexport class PushSlugConflict extends Error {\n constructor(\n public readonly dir: string,\n public readonly tracked: string,\n public readonly declared: SlugDeclaration,\n ) {\n super(\n `${dir} tracks slug \\`${tracked}\\` (${META_RELPATH}, from an earlier push) but its ${declared.source} says \\`${declared.slug}\\`. ` +\n `Nothing was pushed. Pass --slug ${declared.slug} to push there (and retrack the dir), --slug ${tracked} to keep pushing to \\`${tracked}\\`, ` +\n `or delete ${META_RELPATH} to forget the earlier push.`,\n );\n this.name = \"PushSlugConflict\";\n }\n}\n\nexport function writeLocalMeta(dir: string, meta: LocalMeta): void {\n fs.mkdirSync(path.join(dir, \".gateway\"), { recursive: true });\n fs.writeFileSync(path.join(dir, META_RELPATH), JSON.stringify(meta, null, 2));\n}\n\nexport function snapshotTreeHashes(dir: string): Record<string, string> {\n const out: Record<string, string> = {};\n for (const relPath of collectArchiveRelPaths(dir)) {\n out[relPath] = createHash(\"sha256\")\n .update(fs.readFileSync(path.join(dir, relPath)))\n .digest(\"hex\");\n }\n return out;\n}\n\nexport function localTreeState(dir: string): {\n meta: LocalMeta | null;\n dirty: string[];\n clean: boolean;\n} {\n const meta = readLocalMeta(dir);\n const base = meta?.baseFiles;\n if (!base || typeof base !== \"object\") {\n return { meta, dirty: [], clean: false };\n }\n const now = snapshotTreeHashes(dir);\n const dirty = new Set<string>();\n for (const [p, h] of Object.entries(now)) if (base[p] !== h) dirty.add(p);\n for (const p of Object.keys(base)) if (!(p in now)) dirty.add(p);\n return { meta, dirty: [...dirty].sort(), clean: dirty.size === 0 };\n}\n\n// ── protocol helpers ─────────────────────────────────────────────────────────\n\nconst sha256b64 = (data: Buffer) =>\n createHash(\"sha256\").update(data).digest(\"base64\");\n\nfunction readPyproject(dir: string): { name?: string; version?: string } {\n try {\n const text = fs.readFileSync(path.join(dir, \"pyproject.toml\"), \"utf-8\");\n // Minimal [project] reads — name and version only, quoted single-line form.\n const section = /\\[project\\]([\\s\\S]*?)(\\n\\[|$)/.exec(text)?.[1] ?? \"\";\n const name = /\\bname\\s*=\\s*\"([^\"]+)\"/.exec(section)?.[1];\n const version = /\\bversion\\s*=\\s*\"([^\"]+)\"/.exec(section)?.[1];\n return { name, version };\n } catch {\n return {};\n }\n}\n\n/** A schema world's own version: `x-gateway.package.version` of its contract\n * (`schema/world.json`, or `server/world/schema/world.json` in an api bundle).\n * What a connector world has instead of a pyproject, so its versions read\n * \"1.0.0\" rather than \"unversioned\" on the platform. */\nfunction readWorldContractVersion(dir: string): {\n name?: string;\n version?: string;\n} {\n const world = WorldDir.open(dir);\n try {\n const parsed = JSON.parse(\n world.text(world.worldPath(\"schema/world.json\")) ?? \"\",\n ) as {\n \"x-gateway\"?: { package?: { id?: string; version?: string } };\n };\n const pkg = parsed[\"x-gateway\"]?.package;\n if (pkg?.version) return { name: pkg.id, version: pkg.version };\n } catch {\n // not a schema world\n }\n return {};\n}\n\n/** The rows the platform previews for a pushed DRAFT: the archive set, one\n * entry per file the content hash covers, so hash, tarball, manifest and\n * `pull` agree on what the world is. Finalize replaces them with rows\n * derived from the stored bytes. */\nexport function buildFileManifest(\n dir: string,\n): { path: string; isDirectory: boolean; size: number; sha256: string }[] {\n return collectArchiveRelPaths(dir).map((relPath) => {\n const payload = fs.readFileSync(path.join(dir, relPath));\n return {\n path: relPath,\n isDirectory: false,\n size: payload.length,\n sha256: createHash(\"sha256\").update(payload).digest(\"hex\"),\n };\n });\n}\n\nasync function putObject(\n url: string,\n data: Buffer,\n shaB64: string,\n): Promise<void> {\n const resp = await fetch(url, {\n method: \"PUT\",\n headers: {\n \"Content-Type\": \"application/gzip\",\n \"x-amz-checksum-sha256\": shaB64,\n },\n body: new Uint8Array(data),\n });\n if (!resp.ok) {\n throw new Error(\n `object PUT -> ${resp.status}: ${(await resp.text()).slice(0, 300)}`,\n );\n }\n}\n\n// ── the workflows ────────────────────────────────────────────────────────────\n\n/** The refusal `push` raises from a tag checkout: tags never move, so the\n * push needs a branch named explicitly. */\nexport class DetachedPushError extends Error {\n constructor(dir: string, tag: string) {\n super(\n `push refused: ${dir} is a checkout of tag \"${tag}\" (tags are immutable). ` +\n `Nothing was pushed. Pass --branch <name> to land these files on a branch, or checkout a branch first.`,\n );\n this.name = \"DetachedPushError\";\n }\n}\n\n/** The branch a push of `dir` moves: an explicit --branch, else the tracked\n * branch, else main — never a tag. */\nexport function pushBranch(dir: string, localMeta: LocalMeta, explicit: string | undefined): string {\n if (explicit) return explicit;\n if (typeof localMeta.tag === \"string\" && localMeta.tag) throw new DetachedPushError(dir, localMeta.tag);\n return (localMeta.branch as string | undefined) ?? DEFAULT_BRANCH;\n}\n\nexport async function push(\n dir: string,\n opts: {\n slug?: string;\n branch?: string;\n force?: boolean;\n message?: string;\n author?: string;\n /** Push on top of this version instead of the local meta's base — what a\n * CI checkout (which has no local meta) passes after resolving the\n * branch tip, so re-validating a PR replaces its own previous push\n * instead of 409ing against it. */\n baseVersionId?: string | null;\n /** Container metadata recorded on resolve — the Python CLI's --name,\n * --description, --tag and --visibility. */\n name?: string;\n description?: string;\n tags?: string[];\n visibility?: string;\n /** Pre-built OCI image ref for image/agentic envs (recorded on the version). */\n imageRef?: string;\n options?: WorldsClientOptions;\n } = {},\n): Promise<{\n containerId: string;\n slug: string;\n versionId: string;\n contentHash: string;\n branch: string;\n state: string | null;\n alreadyUploaded: boolean;\n /** The edit session the push joined (`gateway worlds edit close <slug>` moves main); null when the platform landed it on main directly. */\n editSessionId: string | null;\n /** Files the archive rules kept (what the hash, manifest and tarball cover). */\n filesKept: number;\n /** What the archive rules left out, so nothing disappears silently. */\n excluded: Exclusion[];\n}> {\n const options = opts.options ?? {};\n if (!fs.statSync(dir).isDirectory())\n throw new Error(`Not a directory: ${dir}`);\n const localMeta = readLocalMeta(dir) ?? {};\n const branch = pushBranch(dir, localMeta, opts.branch);\n const baseVersionId = opts.baseVersionId ?? localMeta.versionId ?? null;\n\n const world = WorldDir.open(dir);\n const fileManifest = buildFileManifest(dir);\n if (fileManifest.length === 0)\n throw new Error(\n `Nothing to push: ${dir} has no files the archive rules keep (a world root marker, README.md, pyproject.toml, *.py, or any file below a subdirectory).`,\n );\n const contentHash = world.contentHash;\n const pyproject = readPyproject(dir);\n // A connector world carries its version on its contract, not a pyproject.\n const contractVersion = pyproject.version\n ? undefined\n : readWorldContractVersion(dir).version;\n if (contractVersion) pyproject.version = contractVersion;\n // A dir that tracks a world (created, pulled or pushed before) pushes back\n // to THAT world: its recorded slug wins over the package name, so a world\n // created as `acme-f7` is not re-published as pyproject's `acme` — which is\n // how `worlds ci` minted an unsuffixed twin of every suffixed world.\n const slug =\n opts.slug ??\n localMeta.slug ??\n pyproject.name ??\n path.basename(path.resolve(dir));\n\n // Sent twice on purpose: resolve records it on a container it CREATES,\n // finalize refreshes an existing one — only when the push actually lands.\n // An omitted field leaves the container's value alone; an explicit one\n // replaces it, so `\"\"` clears the description and `[]` clears the tags.\n const metadata = {\n ...(opts.name !== undefined ? { name: opts.name } : {}),\n ...(opts.description !== undefined\n ? { description: opts.description }\n : {}),\n ...(opts.tags !== undefined ? { tags: opts.tags } : {}),\n ...(opts.visibility ? { visibility: opts.visibility } : {}),\n };\n const resolve = await apiRequest<{ containerId: string }>(\n options,\n \"POST\",\n \"/api/public/benchmark-containers/resolve\",\n { slug, ...metadata },\n );\n\n const tarball = buildSourceTarball(dir);\n const bundleSha256 = sha256b64(tarball);\n\n const version = await apiRequest<{\n versionId: string;\n uploadUrl?: string;\n alreadyUploaded?: boolean;\n }>(options, \"POST\", \"/api/public/benchmark-containers/versions\", {\n containerId: resolve.containerId,\n contentHash,\n bundleSha256,\n bundleSizeBytes: tarball.length,\n ...(pyproject.version ? { semanticVersion: pyproject.version } : {}),\n pyprojectMeta: pyproject,\n fileManifest,\n branch,\n baseVersionId,\n ...(opts.force ? { force: true } : {}),\n ...(opts.message ? { changeReason: opts.message } : {}),\n ...(opts.author ? { author: opts.author } : {}),\n ...(opts.imageRef ? { imageRef: opts.imageRef } : {}),\n });\n\n if (version.uploadUrl)\n await putObject(version.uploadUrl, tarball, bundleSha256);\n\n const final = await apiRequest<{ state?: string; branch?: string; editSessionId?: string }>(\n options,\n \"POST\",\n `/api/public/benchmark-containers/versions/${version.versionId}/finalize`,\n {\n branch,\n baseVersionId,\n ...(opts.force ? { force: true } : {}),\n ...metadata,\n },\n );\n\n writeLocalMeta(dir, {\n ...localMeta,\n slug,\n ref: branch,\n branch,\n versionId: version.versionId,\n contentHash,\n semanticVersion: pyproject.version,\n forkedFromVersionId: baseVersionId,\n baseFiles: snapshotTreeHashes(dir),\n });\n return {\n containerId: resolve.containerId,\n slug,\n versionId: version.versionId,\n contentHash,\n branch: final.branch ?? branch,\n state: final.state ?? null,\n alreadyUploaded: Boolean(version.alreadyUploaded),\n editSessionId: final.editSessionId ?? null,\n filesKept: fileManifest.length,\n excluded: world.exclusions,\n };\n}\n\n/** Extract a downloaded bundle into `dir` (paths confined, executable bit\n * kept; every name encoding the platform's writers emit — see ./tar.ts). */\nexport function extractBundle(bundle: Buffer, dir: string): number {\n return TarArchive.fromGzip(bundle).extractTo(dir);\n}\n\n/** What a checkout tracks after a pull: the branch that answered the ref, or\n * the tag it was taken from (detached). Older servers name neither: latest\n * and semver/hash pins land on main; any other ref was a branch. */\nexport function checkoutIdentity(\n ref: string,\n resolved: { branch?: string | null; tag?: string | null },\n): { branch?: string; tag?: string } {\n if (resolved.tag) return { tag: resolved.tag };\n if (resolved.branch) return { branch: resolved.branch };\n const pinned = ref === \"latest\" || /^\\d|^[0-9a-f]{8,}$/.test(ref);\n return { branch: pinned ? DEFAULT_BRANCH : ref };\n}\n\nexport async function pull(\n slugRef: string,\n target?: string,\n options: WorldsClientOptions = {},\n opts: { force?: boolean } = {},\n): Promise<{ slug: string; dir: string; versionId: string; files: number }> {\n const at = slugRef.indexOf(\"@\");\n const slug = at === -1 ? slugRef : slugRef.slice(0, at);\n const ref = at === -1 ? \"latest\" : slugRef.slice(at + 1);\n // Decided first: a refused target costs no request and touches no file.\n const landing = CheckoutTarget.resolve(slug, target, {\n cwd: process.cwd(),\n force: opts.force ?? false,\n state: localTreeState,\n });\n\n const details = await apiRequest<{\n versionId: string;\n contentHash: string;\n semanticVersion?: string | null;\n branch?: string | null;\n tag?: string | null;\n downloadUrl?: string;\n bundleSha256?: string;\n }>(options, \"POST\", \"/api/public/benchmark-containers/resolve-version\", {\n slug,\n ref,\n });\n if (!details.downloadUrl) {\n throw new Error(`${slug}@${ref} resolved but has no uploaded bundle`);\n }\n\n const resp = await fetch(details.downloadUrl);\n if (!resp.ok) throw new Error(`bundle download -> ${resp.status}`);\n const bundle = Buffer.from(await resp.arrayBuffer());\n if (details.bundleSha256 && sha256b64(bundle) !== details.bundleSha256) {\n throw new Error(\n `bundle integrity check failed for ${slug}@${ref}: downloaded sha256 != recorded bundleSha256`,\n );\n }\n\n const dir = landing.dir;\n fs.mkdirSync(dir, { recursive: true });\n landing.clear();\n const files = extractBundle(bundle, dir);\n writeLocalMeta(dir, {\n slug,\n ref,\n ...checkoutIdentity(ref, details),\n versionId: details.versionId,\n contentHash: details.contentHash,\n semanticVersion: details.semanticVersion ?? undefined,\n baseFiles: snapshotTreeHashes(dir),\n });\n return { slug, dir, versionId: details.versionId, files };\n}\n\nexport async function propose(\n dir: string,\n opts: {\n title: string;\n reason: string;\n targetBranch?: string;\n options?: WorldsClientOptions;\n },\n): Promise<{ proposalId: string }> {\n const meta = readLocalMeta(dir);\n if (!meta?.slug || !meta.baseFiles) {\n throw new Error(\n \"This dir has no pull/push base — run pull first, then edit, then propose.\",\n );\n }\n const state = localTreeState(dir);\n if (state.clean)\n throw new Error(\"Nothing to propose — the tree matches its base.\");\n const changes = state.dirty.map((relPath) => {\n const abs = path.join(dir, relPath);\n if (!fs.existsSync(abs))\n return { path: relPath, action: \"delete\" as const };\n return {\n path: relPath,\n action: \"write\" as const,\n newContent: fs.readFileSync(abs, \"utf-8\"),\n };\n });\n const res = await apiRequest<{ proposalId: string }>(\n opts.options ?? {},\n \"POST\",\n \"/api/public/benchmark-containers/proposals\",\n {\n slug: meta.slug,\n title: opts.title,\n changeReason: opts.reason,\n baseVersionId: meta.versionId,\n ...(opts.targetBranch ? { targetBranch: opts.targetBranch } : {}),\n changes,\n },\n );\n return res;\n}\n\nexport async function createRef(\n slug: string,\n name: string,\n kind: \"branch\" | \"tag\",\n versionId?: string,\n options: WorldsClientOptions = {},\n): Promise<{ name: string; kind: string; versionId: string }> {\n return apiRequest(options, \"POST\", \"/api/public/benchmark-containers/refs\", {\n slug,\n name,\n kind,\n ...(versionId ? { versionId } : {}),\n });\n}\n","/**\n * PR validation: push the checkout's world source, run it, gate on the graded\n * result — one composed call, because CI should not have to re-derive the\n * choreography from primitives.\n *\n * The differentiating property, stated so it stays true: validation runs the\n * PULL REQUEST'S OWN world source. The push files the checkout as a version on\n * the PR's branch (content-hash dedup makes re-runs cheap), the dispatch pins\n * that version, and the platform resolves the branch back to its open PR — so\n * the run page names the PR and the PR comment names the run. Nothing here\n * validates a standing deployment while pretending to validate the change.\n */\n\nimport {\n apiRequest,\n detectProvenance,\n listRunConfigs,\n waitForRun,\n type RunReport,\n type WorldsClientOptions,\n} from \"./index\";\nimport { push, pushSlug } from \"./hub\";\n\nexport type ValidatedRun = {\n model: string;\n runId: string;\n report: RunReport | null;\n /** Why this run fails the gate, or null when it passes. */\n failure: string | null;\n};\n\nexport type ValidateReport = {\n ok: boolean;\n slug: string;\n branch: string;\n versionId: string;\n contentHash: string;\n runConfig: { id: string; name: string };\n runs: ValidatedRun[];\n /** A PR-comment-ready summary of the whole validation. */\n markdown: string;\n};\n\nfunction fmtScore(score: number | null): string {\n return score === null ? \"no score\" : score.toFixed(3);\n}\n\nfunction buildMarkdown(\n report: Omit<ValidateReport, \"markdown\">,\n minScore: number | null,\n source?: { repoUrl?: string; commit?: string },\n): string {\n const lines: string[] = [];\n lines.push(\n `### World validation ${report.ok ? \"passed\" : \"failed\"} — \\`${report.slug}@${report.branch}\\``,\n );\n lines.push(\"\");\n // Name the exact source that ran: the commit on GitHub when we know it,\n // always the content hash the platform pinned.\n const commitLink =\n source?.repoUrl && source?.commit\n ? `[\\`${source.commit.slice(0, 12)}\\`](${source.repoUrl}/commit/${source.commit})`\n : null;\n lines.push(\n `Ran the pull request's own world source` +\n (commitLink ? ` (${commitLink} on \\`${report.branch}\\`` : ` (`) +\n `${commitLink ? \", \" : \"\"}pinned as \\`${report.contentHash.slice(0, 12)}\\`) ` +\n `through run config **${report.runConfig.name}**` +\n (minScore !== null ? `, gating at score ≥ ${minScore}.` : \".\"),\n );\n lines.push(\"\");\n lines.push(\"| Model | Status | Score | Run |\");\n lines.push(\"| --- | --- | ---: | --- |\");\n for (const run of report.runs) {\n const r = run.report;\n const link = r?.url ? `[open](${r.url})` : \"—\";\n const status = run.failure\n ? `❌ ${run.failure}`\n : `✅ ${r?.status ?? \"COMPLETED\"}`;\n lines.push(\n `| \\`${run.model}\\` | ${status} | ${fmtScore(r?.score ?? null)} | ${link} |`,\n );\n }\n const taskRows = report.runs.flatMap((run) =>\n (run.report?.samples ?? []).map((sample) => ({\n model: run.model,\n task: sample.task ?? \"?\",\n reward: sample.reward,\n })),\n );\n // Every scenario, in the open: a validation whose per-scenario grades hide\n // behind a fold reads as one opaque number. Fold only when the table is\n // genuinely long.\n if (taskRows.length > 0) {\n const fold = taskRows.length > 12;\n lines.push(\"\");\n if (fold) {\n lines.push(\n `<details><summary>Per-scenario rewards (${taskRows.length})</summary>`,\n );\n lines.push(\"\");\n } else {\n lines.push(`**Scenarios (${taskRows.length})**`);\n lines.push(\"\");\n }\n lines.push(\"| Scenario | Model | Reward |\");\n lines.push(\"| --- | --- | ---: |\");\n for (const row of taskRows) {\n lines.push(\n `| ${row.task} | \\`${row.model}\\` | ${row.reward === null ? \"no score\" : row.reward.toFixed(2)} |`,\n );\n }\n if (fold) {\n lines.push(\"\");\n lines.push(\"</details>\");\n }\n }\n return lines.join(\"\\n\");\n}\n\n/**\n * Push `dir` on the current (or given) branch, dispatch the named run config\n * against the pushed version, wait for every run, and gate.\n *\n * The gate: every dispatch accepted, every run terminal COMPLETED, and — when\n * `minScore` is set — every run's score meets it. A run with NO score fails a\n * score gate rather than passing it: null is \"not scored\", never 0 and never\n * fine.\n */\nexport async function validateWorld(\n dir: string,\n opts: {\n slug?: string;\n runConfig: string;\n branch?: string;\n minScore?: number | null;\n timeoutMinutes?: number;\n onProgress?: (line: string) => void;\n options?: WorldsClientOptions;\n },\n): Promise<ValidateReport> {\n const options = opts.options ?? {};\n const progress = opts.onProgress ?? (() => {});\n const minScore = opts.minScore ?? null;\n\n const provenance = detectProvenance();\n const branch = opts.branch ?? provenance.branch;\n if (!branch)\n throw new Error(\n \"No branch to validate on: pass --branch or run inside a git checkout / GitHub Actions.\",\n );\n\n const slug = pushSlug(dir, opts.slug);\n progress(`pushing ${dir} as ${slug}@${branch}…`);\n // CI checkouts carry no local push meta, so a re-validation would 409\n // against the branch tip its own previous run created. Validation's\n // semantics are \"this branch's tip BECOMES the PR's source\": resolve the\n // current tip and push on top of it. A branch that does not exist yet\n // resolves to no base, which is a fresh branch — also correct.\n let tipVersionId: string | null = null;\n try {\n const tip = await apiRequest<{ versionId?: string }>(\n options,\n \"POST\",\n \"/api/public/benchmark-containers/resolve-version\",\n { slug, ref: branch },\n );\n tipVersionId = tip.versionId ?? null;\n } catch {\n tipVersionId = null;\n }\n const pushed = await push(dir, {\n slug,\n branch,\n baseVersionId: tipVersionId,\n message: `PR validation push (${provenance.commit?.slice(0, 12) ?? \"local\"})`,\n ...(provenance.actor?.name ? { author: provenance.actor.name } : {}),\n options,\n });\n progress(`pushed version ${pushed.versionId} (${pushed.contentHash.slice(0, 12)})`);\n\n // Resolve the run config by name (the stable handle CI configures) or id.\n const configs = await listRunConfigs(options);\n const runConfig =\n configs.find((c) => c.id === opts.runConfig) ??\n configs.find((c) => c.name === opts.runConfig);\n if (!runConfig) {\n const known = configs.map((c) => c.name).join(\", \") || \"(none)\";\n throw new Error(\n `Run config \"${opts.runConfig}\" not found in this project. Have: ${known}`,\n );\n }\n\n progress(`dispatching run config \"${runConfig.name}\" (${runConfig.models.join(\", \")})…`);\n const dispatched = await apiRequest<{\n versionLabel: string;\n runs: { model: string; runId: string; ok: boolean; error?: string }[];\n }>(options, \"POST\", \"/api/public/benchmark-containers/run-configs/dispatch\", {\n runConfigId: runConfig.id,\n versionId: pushed.versionId,\n ...provenance,\n });\n\n // The run's platform page. New deployments return it on the run report\n // (`url`); against an older deployment we build the same page from the\n // evaluation id, because a PR comment that cannot link the run defeats\n // the point of the comment.\n const host = (\n options.host ??\n process.env.GATEWAY_HOST ??\n \"https://withgateway.ai\"\n ).replace(/\\/+$/, \"\");\n let projectId: string | null = null;\n try {\n const projects = await apiRequest<{ data?: { id?: string }[] }>(\n options,\n \"GET\",\n \"/api/public/projects\",\n );\n projectId = projects.data?.[0]?.id ?? null;\n } catch {\n projectId = null;\n }\n const fallbackUrl = (report: RunReport): string | null => {\n if (report.url) return report.url;\n const evaluationId = report.evaluations[0]?.id;\n return projectId && evaluationId\n ? `${host}/project/${projectId}/environment/runs/${encodeURIComponent(evaluationId)}`\n : null;\n };\n\n const runs: ValidatedRun[] = [];\n for (const run of dispatched.runs) {\n if (!run.ok) {\n runs.push({\n model: run.model,\n runId: run.runId,\n report: null,\n failure: `dispatch failed: ${run.error ?? \"unknown error\"}`,\n });\n continue;\n }\n progress(`waiting on ${run.model} (run ${run.runId})…`);\n let report: RunReport | null = null;\n let failure: string | null = null;\n try {\n report = await waitForRun(run.runId, {\n timeoutMinutes: opts.timeoutMinutes ?? 45,\n options,\n onTick: (r) =>\n progress(\n `…${run.model}: ${r.status.toLowerCase()} (${r.shardsCompleted ?? 0}/${r.parallelism} shards)`,\n ),\n });\n report = { ...report, url: fallbackUrl(report) };\n if (report.status.toUpperCase() !== \"COMPLETED\") {\n failure = report.status;\n } else if (minScore !== null) {\n if (report.score === null) failure = \"completed without a score\";\n else if (report.score < minScore)\n failure = `score ${fmtScore(report.score)} < ${minScore}`;\n }\n } catch (error) {\n failure = error instanceof Error ? error.message : String(error);\n }\n runs.push({ model: run.model, runId: run.runId, report, failure });\n }\n\n const base = {\n ok: runs.length > 0 && runs.every((r) => r.failure === null),\n slug: pushed.slug,\n branch,\n versionId: pushed.versionId,\n contentHash: pushed.contentHash,\n runConfig: { id: runConfig.id, name: runConfig.name },\n runs,\n };\n return {\n ...base,\n markdown: buildMarkdown(base, minScore, {\n repoUrl: provenance.repoUrl,\n commit: provenance.commit,\n }),\n };\n}\n","import { ApiError, apiRequest, type WorldsClientOptions } from \"./index\";\nimport type { PlatformMethod } from \"./transport\";\n\n/**\n * The CLI sandbox: a server-side workspace opened on a READY version of a\n * world (`/workspace/env` in the console agent's sandbox) — or, with\n * `{ new, from }`, on a world that does not exist yet, seeded from the\n * `schema init` scaffold or a shipped template and created by its first\n * commit — edited and run there, and committed straight into the version\n * service; the source never lands on the caller's disk. `importData` is the\n * data door beside `commit`: a rows file in the sandbox tree into the platform\n * world's data ledger, read out by the platform (no credential enters the\n * sandbox, nothing passes through this machine). One client under\n * both `gateway worlds sandbox …` and `gateway bench sandbox …`; the\n * Python twin is `gatewaysdk.benchmark_hub.sandbox.WorldSandboxClient`.\n */\n\n/** Mirrors `SandboxSummaryResponse` (web/features/public-api/types/world-sandboxes.ts). */\nexport type SandboxSummary = {\n sandboxId: string;\n slug: string;\n /** null while a new-world sandbox awaits its first commit. */\n containerId: string | null;\n /** The version the next commit is validated against; advances on commit. null before the first commit of a new world. */\n baseVersionId: string | null;\n /** Set on a new-world sandbox until its first commit creates the world. */\n pendingSlug: string | null;\n status: \"open\" | \"closed\";\n lastCommitVersionId: string | null;\n createdAt: string;\n};\n\nexport type SandboxOpened = SandboxSummary & {\n /** null for a new-world sandbox (no base). */\n baseContentHash: string | null;\n branch: string;\n dataSnapshotId: string | null;\n fileCount: number;\n workdir: string;\n /** The `gateway` CLI `exec` finds on PATH (the platform's version, staged runtime digest); null when the image cannot host it — `warnings` says why. */\n cli: { version: string; digest: string } | null;\n warnings: string[];\n};\n\nexport type SandboxExecResult = {\n exitCode: number;\n stdout: string;\n stderr: string;\n timedOut: boolean;\n truncated: boolean;\n durationMs: number;\n /** Why `gateway`/`sqlite3` were not on PATH for this command; empty when the runtime is staged. */\n warnings: string[];\n};\n\nexport type SandboxChanges = { added: string[]; modified: string[]; removed: string[] };\n\nexport type SandboxCheckResult = {\n ok: boolean;\n contentHash: string | null;\n noChange: boolean;\n fileCount: number;\n changes: SandboxChanges;\n /** Working-tree paths left out of the version: `.gatewayignore`, default scratch, credential-shaped files, links. */\n ignored: string[];\n /** Why a listed path was held back (credential-shaped, a link, unhashed by the gate); paths only. */\n warnings: string[];\n error: string | null;\n};\n\nexport type SandboxCommitResult = {\n /** The world the commit landed on. */\n slug: string;\n versionId: string;\n contentHash: string;\n branch: string;\n deduped: boolean;\n noChange: boolean;\n changes: SandboxChanges;\n ignored: string[];\n /** The same warnings `check` gives, so a commit never hides what it left out. */\n warnings: string[];\n /** The API key's edit session the commit joined; `gateway worlds edit close <slug>` moves main. */\n editSessionId?: string;\n};\n\n/** Mirrors `PostSandboxImportBody`. */\nexport type SandboxImportInput = {\n /** A .json/.jsonl/.ndjson/.csv/.tsv (optionally .gz) relative to the world root. */\n path: string;\n entity?: string;\n /** One character (a real tab for TSV); defaults by extension. */\n delimiter?: string;\n mode?: \"append\" | \"replace\";\n merge?: \"upsert\" | \"fill\";\n redact?: \"off\" | \"apply\" | \"refuse\";\n atomic?: boolean;\n dryRun?: boolean;\n message?: string;\n};\n\n/** Mirrors `PostSandboxImportResponse` (201). */\nexport type SandboxImportResult = {\n containerId: string;\n slug: string;\n batchId: string | null;\n state: string;\n versionId: string | null;\n baseVersionId: string;\n contentHash: string | null;\n deduped: boolean;\n entityCounts: Record<string, number>;\n kind: string | null;\n dryRun: boolean;\n refusalCount: number;\n rowCount: number;\n chunkCount: number;\n /** `sandbox:<id>/<path>`. */\n source: string;\n};\n\n/** Mirrors `PostSandboxImportPendingResponse` (202): poll `worlds data batches`. */\nexport type SandboxImportPending = {\n batchId: string;\n state: string;\n rowCount: number;\n chunkCount: number;\n source: string;\n};\n\nexport const isSandboxImportPending = (\n answer: SandboxImportResult | SandboxImportPending,\n): answer is SandboxImportPending => !(\"versionId\" in answer);\n\n/** Mirrors `PostSandboxOpenBody`: an existing world at a ref, or a new world seeded from a template. */\nexport type SandboxOpenExisting = { slug: string; ref?: string };\nexport type SandboxOpenNew = { new: string; from: string };\nexport type SandboxOpenTarget = SandboxOpenExisting | SandboxOpenNew;\n\n/** `slug` or `slug@ref` → the open body; a bare slug opens the latest READY version. */\nexport function parseSlugRef(slugRef: string): SandboxOpenExisting {\n const at = slugRef.indexOf(\"@\");\n if (at === -1) return { slug: slugRef };\n return { slug: slugRef.slice(0, at), ref: slugRef.slice(at + 1) };\n}\n\nconst sid = encodeURIComponent;\n\nconst SANDBOXES = \"/api/public/benchmark-containers/sandboxes\";\n\n/** One sandbox request may run the platform's longest exec (600 s) plus the answer; the Python twin waits the same 660 s. */\nexport const SANDBOX_REQUEST_TIMEOUT_MS = 660_000;\n\n/** Mirrors `PostSandboxCommitBody`: `rebase` replays the sandbox's edits onto the branch head when the base moved. */\nexport type SandboxCommitInput = { message: string; branch?: string; rebase?: boolean };\n\n/** One path a rebase refused, as the 409 body's `conflicts[]` names it. */\nexport type RebaseConflictPath = { path: string; reason: string };\n\n/** A 409 from `commit --rebase`: the paths both sides changed and why each was refused. Null for any other failure. */\nexport function rebaseConflicts(error: unknown): RebaseConflictPath[] | null {\n if (!(error instanceof ApiError) || error.status !== 409) return null;\n let body: unknown;\n try {\n body = JSON.parse(error.text);\n } catch {\n return null;\n }\n const conflicts = (body as { conflicts?: unknown } | null)?.conflicts;\n if (!Array.isArray(conflicts)) return null;\n return conflicts.filter(isConflictPath).map(({ path, reason }) => ({ path, reason }));\n}\n\nfunction isConflictPath(value: unknown): value is RebaseConflictPath {\n const entry = value as Partial<RebaseConflictPath> | null;\n return typeof entry?.path === \"string\" && typeof entry.reason === \"string\";\n}\n\n/** A 409 `sandbox_uncommitted` from `close`: the paths a commit would keep. Null for any other failure. */\nexport function uncommittedPaths(error: unknown): string[] | null {\n if (!(error instanceof ApiError) || error.status !== 409 || error.code !== \"sandbox_uncommitted\") return null;\n let body: unknown;\n try {\n body = JSON.parse(error.text);\n } catch {\n return null;\n }\n const uncommitted = (body as { uncommitted?: unknown } | null)?.uncommitted;\n if (!Array.isArray(uncommitted)) return null;\n return uncommitted.filter((p): p is string => typeof p === \"string\");\n}\n\n/** `sandbox list` narrows: status, world, count (newest first). */\nexport type SandboxListFilter = {\n status?: \"open\" | \"closed\";\n slug?: string;\n limit?: number;\n};\n\nfunction listQuery(filter: SandboxListFilter): string {\n const params = new URLSearchParams();\n if (filter.status) params.set(\"status\", filter.status);\n if (filter.slug) params.set(\"slug\", filter.slug);\n if (filter.limit !== undefined) params.set(\"limit\", String(filter.limit));\n const qs = params.toString();\n return qs ? `?${qs}` : \"\";\n}\n\nexport class WorldSandboxClient {\n constructor(private readonly options: WorldsClientOptions = {}) {}\n\n private request<T>(method: PlatformMethod, path: string, body?: unknown): Promise<T> {\n return apiRequest<T>(this.options, method, path, body, {\n timeoutMs: SANDBOX_REQUEST_TIMEOUT_MS,\n });\n }\n\n /**\n * `{ slug, ref? }` opens a READY version; `{ new, from }` opens a sandbox on\n * a world that does not exist yet (409 `world_exists` if the slug is taken,\n * 400 naming the shipped templates if `from` is unknown). Its first commit\n * creates the world on `main`.\n */\n open(target: SandboxOpenTarget): Promise<SandboxOpened> {\n return this.request(\"POST\", `${SANDBOXES}`, target);\n }\n\n status(sandboxId: string): Promise<SandboxSummary> {\n return this.request(\"GET\", `${SANDBOXES}/${sid(sandboxId)}`);\n }\n\n /** The project's sandboxes, newest first — how an agent finds one it left open. */\n async list(filter: SandboxListFilter = {}): Promise<SandboxSummary[]> {\n const res = await this.request<{ sandboxes: SandboxSummary[] }>(\"GET\", `${SANDBOXES}${listQuery(filter)}`);\n return res.sandboxes;\n }\n\n async read(sandboxId: string, filePath: string): Promise<{ path: string; size: number; bytes: Buffer }> {\n const res = await this.request<{ path: string; size: number; contentBase64: string }>(\n \"GET\",\n `${SANDBOXES}/${sid(sandboxId)}/file?path=${encodeURIComponent(filePath)}`,\n );\n return { path: res.path, size: res.size, bytes: Buffer.from(res.contentBase64, \"base64\") };\n }\n\n write(sandboxId: string, filePath: string, bytes: Buffer): Promise<{ path: string; size: number }> {\n return this.request(\"PUT\", `${SANDBOXES}/${sid(sandboxId)}/file`, {\n path: filePath,\n contentBase64: bytes.toString(\"base64\"),\n });\n }\n\n exec(\n sandboxId: string,\n input: { command: string; cwd?: string; timeoutMs?: number },\n ): Promise<SandboxExecResult> {\n return this.request(\"POST\", `${SANDBOXES}/${sid(sandboxId)}/exec`, input);\n }\n\n check(sandboxId: string): Promise<SandboxCheckResult> {\n return this.request(\"POST\", `${SANDBOXES}/${sid(sandboxId)}/check`, {});\n }\n\n /** With `rebase`, a moved base is replayed onto; a 409 then names the conflicting paths (`rebaseConflicts`). */\n commit(sandboxId: string, input: SandboxCommitInput): Promise<SandboxCommitResult> {\n const { rebase, ...rest } = input;\n return this.request(\"POST\", `${SANDBOXES}/${sid(sandboxId)}/commit`, rebase ? { ...rest, rebase: true } : rest);\n }\n\n /**\n * A rows file already in the sandbox tree into the PLATFORM world the\n * sandbox was opened on (201 with the version, 202 with the batch to poll,\n * 400 naming a refused row). Not `commit`: a commit versions the source\n * tree and never carries data.\n */\n importData(sandboxId: string, input: SandboxImportInput): Promise<SandboxImportResult | SandboxImportPending> {\n return this.request(\"POST\", `${SANDBOXES}/${sid(sandboxId)}/import`, input);\n }\n\n /** Uncommitted work is a 409 (`uncommittedPaths`) unless `force` discards it. */\n close(sandboxId: string, opts: { force?: boolean } = {}): Promise<SandboxSummary> {\n return this.request(\"DELETE\", `${SANDBOXES}/${sid(sandboxId)}`, opts.force ? { force: true } : undefined);\n }\n}\n","/**\n * `describeWorld(slug)` — what a world holds and how each field is stored,\n * from `GET /api/public/worlds/{slug}`: the entities (primary key, unique\n * keys, relationships, row count, fields with their `[redact]` policy) and\n * the `[redact]` table itself, so `storedForms(world, field, plaintext)`\n * can compute a lookup value without Python. The CLI twin is\n * `gateway worlds describe <slug>`; for a directory the CLI asks the schema\n * runtime instead and merges the same shape.\n */\n\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\nimport type { RedactPolicy, Redaction } from \"./redaction\";\nimport { parseSlugRef } from \"./sandbox\";\n\nexport type WorldField = {\n name: string;\n type: string | null;\n required: boolean;\n /** How the store holds it; null means in the clear (queryable by plaintext as given). */\n redaction: Redaction | null;\n};\n\nexport type WorldRelationship = {\n fields: string[];\n target: string;\n on_delete?: string;\n};\n\nexport type WorldEntityMapping = {\n localEntity: string;\n localField: string;\n depEntity: string;\n depField: string;\n /** A closed set, applied left to right before each world's own redaction. */\n transform: string[];\n};\n\nexport type WorldDependency = {\n alias: string;\n dependsOn: { slug: string | null; versionId: string };\n task: string | null;\n tools: string[];\n entities: WorldEntityMapping[];\n};\n\nexport type WorldEntity = {\n name: string;\n primaryKey: string[];\n unique: string[][];\n relationships: WorldRelationship[];\n /** Rows in the head version; null when the platform does not count this kind. */\n rowCount: number | null;\n fields: WorldField[];\n};\n\nexport type WorldDescription = {\n slug: string;\n name: string;\n description: string | null;\n kind: string;\n version: { id: string; contentHash: string; semanticVersion: string | null };\n url: string;\n hostedUrl: string | null;\n tools: { name: string; signature: string; doc: string | null }[];\n taskCount: number;\n links: { tasks: string; sessions: string };\n /** World-to-world links from `[dependencies]`, resolved at commit, with the\n * entity mappings `--across` follows. */\n dependencies?: WorldDependency[];\n entities: WorldEntity[];\n redact: RedactPolicy | null;\n};\n\n/** The world at `slug@ref`, described — `ref` is the one grammar shared with\n * pull/checkout/sandbox (`latest` | branch | tag | semver | version id | hash\n * prefix); a bare slug describes the head of `main`. An unknown ref is the\n * route's 404, never the head. */\nexport async function describeWorld(\n slugRef: string,\n options: WorldsClientOptions = {},\n): Promise<WorldDescription> {\n const { slug, ref } = parseSlugRef(slugRef);\n const query = ref === undefined ? \"\" : `?ref=${encodeURIComponent(ref)}`;\n return apiRequest<WorldDescription>(\n options,\n \"GET\",\n `/api/public/worlds/${encodeURIComponent(slug)}${query}`,\n );\n}\n","/**\n * JSON as the Python CLI sees it, so both CLIs write the same bytes.\n *\n * `JSON.parse` + `JSON.stringify` are not enough for parity with\n * `json.loads` + `json.dumps(separators=(\",\", \":\"), ensure_ascii=False)`:\n * JavaScript loses `1.0` vs `1` (Python keeps the float), rounds integers past\n * 2^53, moves integer-like keys to the front of an object, and spells\n * exponents differently (`1e-7` vs `1e-07`). Here a number keeps its source\n * text and its Python type, an object is a Map (insertion order, always), and\n * `dumps` renders exactly what CPython renders.\n */\n\nexport class JsonNumber {\n /** The lexeme as it appeared, e.g. \"1.0\", \"-0\", \"1e21\". */\n constructor(readonly text: string) {}\n /** A float in Python's eyes: a fraction, an exponent, or a non-finite literal. */\n get isFloat(): boolean {\n return /[.eE]/.test(this.text) || /[nN]/.test(this.text);\n }\n get value(): number {\n return Number(this.text);\n }\n}\n\nexport type JsonObject = Map<string, JsonValue>;\nexport type JsonValue = null | boolean | string | JsonNumber | JsonValue[] | JsonObject;\n\nexport class JsonSyntaxError extends Error {}\n\nexport const isObject = (value: JsonValue | undefined): value is JsonObject => value instanceof Map;\n\n// ------------------------------------------------------------------ parsing\n\n/** Parse one JSON text (a line, a row, a document) into the model above.\n * Accepts what `json.loads` accepts, including NaN/Infinity literals. */\nexport function parseJson(text: string): JsonValue {\n const p = new Parser(text);\n p.skipWs();\n const value = p.value();\n p.skipWs();\n if (p.i < text.length) throw new JsonSyntaxError(`Extra data at ${p.i}`);\n return value;\n}\n\nclass Parser {\n i = 0;\n constructor(readonly s: string) {}\n\n skipWs(): void {\n const s = this.s;\n while (this.i < s.length) {\n const c = s.charCodeAt(this.i);\n if (c === 0x20 || c === 0x0a || c === 0x0d || c === 0x09) this.i++;\n else break;\n }\n }\n\n fail(what: string): never {\n throw new JsonSyntaxError(`${what} at ${this.i}`);\n }\n\n value(): JsonValue {\n const s = this.s;\n if (this.i >= s.length) this.fail(\"Expecting value\");\n const c = s[this.i]!;\n if (c === \"{\") return this.object();\n if (c === \"[\") return this.array();\n if (c === '\"') return this.string();\n if (c === \"t\") return this.literal(\"true\", true);\n if (c === \"f\") return this.literal(\"false\", false);\n if (c === \"n\") return this.literal(\"null\", null);\n if (c === \"N\") return this.literal(\"NaN\", new JsonNumber(\"NaN\"));\n if (c === \"I\") return this.literal(\"Infinity\", new JsonNumber(\"Infinity\"));\n return this.number();\n }\n\n literal<T extends JsonValue>(word: string, value: T): T {\n if (!this.s.startsWith(word, this.i)) this.fail(\"Expecting value\");\n this.i += word.length;\n return value;\n }\n\n number(): JsonNumber {\n const s = this.s;\n const start = this.i;\n if (s[this.i] === \"-\") {\n this.i++;\n if (s.startsWith(\"Infinity\", this.i)) {\n this.i += 8;\n return new JsonNumber(\"-Infinity\");\n }\n }\n const intStart = this.i;\n if (s[this.i] === \"0\") this.i++;\n else {\n while (this.i < s.length && isDigit(s.charCodeAt(this.i))) this.i++;\n if (this.i === intStart) this.fail(\"Expecting value\");\n }\n if (s[this.i] === \".\") {\n this.i++;\n const fracStart = this.i;\n while (this.i < s.length && isDigit(s.charCodeAt(this.i))) this.i++;\n if (this.i === fracStart) this.fail(\"Invalid number\");\n }\n if (s[this.i] === \"e\" || s[this.i] === \"E\") {\n this.i++;\n if (s[this.i] === \"+\" || s[this.i] === \"-\") this.i++;\n const expStart = this.i;\n while (this.i < s.length && isDigit(s.charCodeAt(this.i))) this.i++;\n if (this.i === expStart) this.fail(\"Invalid number\");\n }\n return new JsonNumber(s.slice(start, this.i));\n }\n\n string(): string {\n const s = this.s;\n this.i++; // opening quote\n let out = \"\";\n let runStart = this.i;\n for (;;) {\n if (this.i >= s.length) this.fail(\"Unterminated string\");\n const c = s.charCodeAt(this.i);\n if (c === 0x22) {\n out += s.slice(runStart, this.i);\n this.i++;\n return out;\n }\n if (c < 0x20) this.fail(\"Invalid control character\");\n if (c !== 0x5c) {\n this.i++;\n continue;\n }\n out += s.slice(runStart, this.i);\n this.i++;\n const e = s[this.i];\n switch (e) {\n case '\"':\n case \"\\\\\":\n case \"/\":\n out += e;\n break;\n case \"b\":\n out += \"\\b\";\n break;\n case \"f\":\n out += \"\\f\";\n break;\n case \"n\":\n out += \"\\n\";\n break;\n case \"r\":\n out += \"\\r\";\n break;\n case \"t\":\n out += \"\\t\";\n break;\n case \"u\": {\n const hex = s.slice(this.i + 1, this.i + 5);\n if (!/^[0-9a-fA-F]{4}$/.test(hex)) this.fail(\"Invalid \\\\u escape\");\n out += String.fromCharCode(parseInt(hex, 16));\n this.i += 4;\n break;\n }\n default:\n this.fail(\"Invalid escape\");\n }\n this.i++;\n runStart = this.i;\n }\n }\n\n array(): JsonValue[] {\n this.i++;\n const out: JsonValue[] = [];\n this.skipWs();\n if (this.s[this.i] === \"]\") {\n this.i++;\n return out;\n }\n for (;;) {\n this.skipWs();\n out.push(this.value());\n this.skipWs();\n const c = this.s[this.i];\n if (c === \",\") {\n this.i++;\n continue;\n }\n if (c === \"]\") {\n this.i++;\n return out;\n }\n this.fail(\"Expecting ',' delimiter\");\n }\n }\n\n object(): JsonObject {\n this.i++;\n const out: JsonObject = new Map();\n this.skipWs();\n if (this.s[this.i] === \"}\") {\n this.i++;\n return out;\n }\n for (;;) {\n this.skipWs();\n if (this.s[this.i] !== '\"') this.fail(\"Expecting property name enclosed in double quotes\");\n const key = this.string();\n this.skipWs();\n if (this.s[this.i] !== \":\") this.fail(\"Expecting ':' delimiter\");\n this.i++;\n this.skipWs();\n out.set(key, this.value());\n this.skipWs();\n const c = this.s[this.i];\n if (c === \",\") {\n this.i++;\n continue;\n }\n if (c === \"}\") {\n this.i++;\n return out;\n }\n this.fail(\"Expecting ',' delimiter\");\n }\n }\n}\n\nconst isDigit = (c: number): boolean => c >= 0x30 && c <= 0x39;\n\n// ------------------------------------------------------------ serialising\n\n/** `json.dumps(value, separators=(\",\", \":\"), ensure_ascii=False)`, byte for byte. */\nexport function dumps(value: JsonValue): string {\n if (value === null) return \"null\";\n if (value === true) return \"true\";\n if (value === false) return \"false\";\n if (typeof value === \"string\") return JSON.stringify(value);\n if (value instanceof JsonNumber) return numberText(value);\n if (Array.isArray(value)) return \"[\" + value.map(dumps).join(\",\") + \"]\";\n const parts: string[] = [];\n for (const [key, item] of value) parts.push(JSON.stringify(key) + \":\" + dumps(item));\n return \"{\" + parts.join(\",\") + \"}\";\n}\n\n/** How `json.dumps` spells a parsed number: ints verbatim (`-0` becomes `0`),\n * floats through `float.__repr__`, non-finite as NaN/Infinity. */\nexport function numberText(n: JsonNumber): string {\n if (!n.isFloat) return /^-0+$/.test(n.text) ? \"0\" : n.text;\n const value = n.value;\n if (Number.isNaN(value)) return \"NaN\";\n if (value === Infinity) return \"Infinity\";\n if (value === -Infinity) return \"-Infinity\";\n return pyFloatRepr(value);\n}\n\n/** `str(value)` for the values the redaction digest sees: str, int, float, bool. */\nexport function pyStr(value: string | boolean | JsonNumber): string {\n if (typeof value === \"string\") return value;\n if (typeof value === \"boolean\") return value ? \"True\" : \"False\";\n if (!value.isFloat) return numberText(value);\n const v = value.value;\n if (Number.isNaN(v)) return \"nan\";\n if (v === Infinity) return \"inf\";\n if (v === -Infinity) return \"-inf\";\n return pyFloatRepr(v);\n}\n\n/**\n * CPython's `repr(float)`: the shortest digits that round-trip (which\n * JavaScript's `String(x)` also produces), laid out Python's way — a\n * trailing `.0` on integral values, scientific notation only below 1e-4 or\n * from 1e16, and exponents of at least two digits with a sign.\n */\nexport function pyFloatRepr(x: number): string {\n if (x === 0) return Object.is(x, -0) ? \"-0.0\" : \"0.0\";\n const sign = x < 0 ? \"-\" : \"\";\n const js = String(Math.abs(x));\n const [mantissa, exponentPart] = js.split(\"e\");\n let exponent = exponentPart ? Number(exponentPart) : 0;\n const [intPart, fracPart = \"\"] = mantissa!.split(\".\");\n let digits = intPart! + fracPart;\n // decpt: how many digits sit before the decimal point (may be <= 0 or > length).\n let decpt = intPart!.length + exponent;\n const leading = digits.match(/^0*/)![0].length;\n digits = digits.slice(leading);\n decpt -= leading;\n digits = digits.replace(/0+$/, \"\");\n if (digits === \"\") return sign + \"0.0\";\n const sci = decpt - 1;\n if (sci >= -4 && sci < 16) {\n if (decpt <= 0) return sign + \"0.\" + \"0\".repeat(-decpt) + digits;\n if (decpt >= digits.length) return sign + digits + \"0\".repeat(decpt - digits.length) + \".0\";\n return sign + digits.slice(0, decpt) + \".\" + digits.slice(decpt);\n }\n exponent = sci;\n const mag = String(Math.abs(exponent)).padStart(2, \"0\");\n return sign + digits[0] + (digits.length > 1 ? \".\" + digits.slice(1) : \"\") + \"e\" + (exponent < 0 ? \"-\" : \"+\") + mag;\n}\n\n/**\n * Python's `round(x, ndigits)` for the redaction policy: an int is returned\n * unchanged, a float is correctly rounded on its exact binary value with ties\n * to even (`round(0.125, 2) == 0.12`), then re-read as the nearest double.\n */\nexport function pyRound(n: JsonNumber, ndigits: number): JsonNumber {\n if (!n.isFloat) return n;\n const x = n.value;\n if (!Number.isFinite(x)) return n;\n const sign = x < 0 ? -1 : 1;\n const magnitude = Math.abs(x);\n // Every double at or above 2^53 is an integer already.\n if (magnitude >= 9007199254740992) return new JsonNumber(pyFloatRepr(x));\n const { m, k } = exactFraction(magnitude); // magnitude = m / 2^k, m odd (or zero)\n let rounded: number;\n if (k <= ndigits) rounded = magnitude; // exact at this precision\n else if (k !== ndigits + 1) rounded = Number(magnitude.toFixed(ndigits)); // no tie possible: correctly rounded\n else {\n // Exactly k = ndigits + 1 fractional digits, the last one a 5: a tie. Half to even.\n const scaled = m * 5n ** BigInt(k); // magnitude * 10^k, an integer\n let kept = scaled / 10n; // magnitude * 10^ndigits, truncated\n if (kept % 2n === 1n) kept += 1n;\n const text = kept.toString().padStart(ndigits + 1, \"0\");\n rounded = ndigits === 0 ? Number(text) : Number(text.slice(0, -ndigits) + \".\" + text.slice(-ndigits));\n }\n return new JsonNumber(pyFloatRepr(sign * rounded));\n}\n\n/** A finite non-negative double as m / 2^k with m odd (m = 0, k = 0 for zero). */\nfunction exactFraction(x: number): { m: bigint; k: number } {\n if (x === 0) return { m: 0n, k: 0 };\n const view = new DataView(new ArrayBuffer(8));\n view.setFloat64(0, x);\n const bits = view.getBigUint64(0);\n const exponent = Number((bits >> 52n) & 0x7ffn);\n let mantissa = bits & ((1n << 52n) - 1n);\n let e: number;\n if (exponent === 0) e = -1074;\n else {\n mantissa |= 1n << 52n;\n e = exponent - 1075;\n }\n while (mantissa !== 0n && (mantissa & 1n) === 0n) {\n mantissa >>= 1n;\n e += 1;\n }\n if (e >= 0) return { m: mantissa << BigInt(e), k: 0 };\n return { m: mantissa, k: -e };\n}\n","/**\n * Named plaintext transforms for cross-world entity mappings.\n *\n * A mapping between two worlds' fields is rarely a raw equality: SpyCloud\n * keeps `phone` as bare digits where a Torchlight client sends\n * `+1 (559) 779-1433`; one world keys people by `email`, another by\n * `email_username`. A transform normalises the plaintext on BOTH sides of a\n * mapping before `storedForms` salts it under each world's slug, so a\n * cross-world query is answerable from the plaintext alone, with no stored\n * join.\n *\n * The set is closed and named — no expressions, no user code — because any\n * client must reproduce a transform from the manifest by itself. This is the\n * TypeScript twin of the Python runtime's `environment/schema/transforms.py`;\n * the golden vectors in `__tests__/transforms.test.ts` and the Python\n * `tests/environment/test_schema_transforms.py` pin the two to each other,\n * byte for byte.\n *\n * Whitespace, for `trim` and `collapse_ws`, is the ASCII set `\" \\t\\n\\r\\f\\v\"`\n * by definition (Python's `str.split()` and JavaScript's `\\s` disagree at the\n * edges of Unicode; `nfkc` first folds a no-break space into a plain one).\n */\n\nimport { createHash } from \"node:crypto\";\n\nimport { pyFloatRepr } from \"../cli/platform/worldData/json\";\n\nexport type Transform = (value: string) => string;\n\nexport const WHITESPACE = \" \\t\\n\\r\\f\\v\";\nconst WHITESPACE_EDGES = new RegExp(`^[${WHITESPACE}]+|[${WHITESPACE}]+$`, \"g\");\nconst WHITESPACE_RUN = new RegExp(`[${WHITESPACE}]+`, \"g\");\nconst NOT_DIGIT = /[^0-9]/g;\n\nexport const STRIP_PREFIX = \"strip_prefix\";\n\nconst trim = (value: string): string => value.replace(WHITESPACE_EDGES, \"\");\n\nconst emailLocalPart = (value: string): string => {\n const at = value.lastIndexOf(\"@\");\n return at === -1 ? value : value.slice(0, at);\n};\n\nconst emailDomain = (value: string): string => {\n const at = value.lastIndexOf(\"@\");\n return at === -1 ? \"\" : value.slice(at + 1).toLowerCase();\n};\n\nconst stripPrefix =\n (prefix: string): Transform =>\n (value) =>\n value.startsWith(prefix) ? value.slice(prefix.length) : value;\n\nconst hex = (algorithm: \"sha1\" | \"sha256\", value: string): string =>\n createHash(algorithm).update(value, \"utf8\").digest(\"hex\");\n\nconst SIMPLE: Record<string, Transform> = {\n lower: (value) => value.toLowerCase(),\n upper: (value) => value.toUpperCase(),\n trim,\n collapse_ws: (value) => trim(value).replace(WHITESPACE_RUN, \" \"),\n nfkc: (value) => value.normalize(\"NFKC\"),\n digits: (value) => value.replace(NOT_DIGIT, \"\"),\n email_local_part: emailLocalPart,\n email_domain: emailDomain,\n // Vendor-style digests: lowercase hex of the utf-8 bytes, unsalted. This is\n // how SpyCloud accepts a hashed selector (`_digests` in its api_handlers).\n sha1: (value) => hex(\"sha1\", value),\n sha256: (value) => hex(\"sha256\", value),\n};\n\n/** The closed set, as a manifest spells it. `strip_prefix` takes its parameter\n * after a colon; the parameter may hold any character but `,`. */\nexport const TRANSFORMS: readonly string[] = [...Object.keys(SIMPLE), `${STRIP_PREFIX}:<prefix>`];\n\n/** The function a transform name denotes; throws when the name is not in the set. */\nexport function parseTransform(name: string): Transform {\n const simple = Object.prototype.hasOwnProperty.call(SIMPLE, name) ? SIMPLE[name] : undefined;\n if (simple) return simple;\n const colon = name.indexOf(\":\");\n if (colon !== -1) {\n const head = name.slice(0, colon);\n const prefix = name.slice(colon + 1);\n if (head === STRIP_PREFIX && prefix && !prefix.includes(\",\")) return stripPrefix(prefix);\n }\n throw new Error(`Unknown transform '${name}'; choose one of ${TRANSFORMS.join(\", \")}`);\n}\n\n/** `str(value)` as the Python runtime spells a number: an integral number is an\n * int, any other its float repr. */\nconst text = (value: string | number): string => {\n if (typeof value === \"string\") return value;\n return Number.isInteger(value) ? String(value) : pyFloatRepr(value);\n};\n\n/**\n * Compose `chain` left to right over `value`.\n *\n * A number is written as Python's `str()` first, the way `_digest` salts one,\n * so a number keyed on one side and a string on the other transform alike. The\n * whole chain is parsed before any step runs: a bad name at the end refuses\n * the mapping outright rather than after a partial result. An empty chain is\n * the identity.\n */\nexport function applyTransforms(value: string | number, chain: readonly string[]): string {\n const steps = chain.map(parseTransform);\n let out = text(value);\n for (const step of steps) out = step(out);\n return out;\n}\n","/**\n * Stored forms: what a world's store holds for a field given its plaintext.\n *\n * A schema world's `[redact]` table (connector.toml) rewrites named fields\n * before they reach disk — `hash` to a slug-salted sha256, `preserve` to a\n * shape-preserving digest, `round` to fewer decimals, `drop` to nothing. A\n * lookup by plaintext therefore has to compute the same form the store did.\n * This module is the TypeScript twin of the Python runtime's `_digest`,\n * `_shaped`, `redaction_of` and `stored_forms` (environment/schema/connector.py):\n * the rule is `\"sha256:\" + sha256(\"<slug>:<plaintext>\")`, no lowercasing, no\n * trimming, no other salt, and the golden vectors in redaction.test.ts pin the\n * two implementations to each other.\n */\n\nimport { createHash } from \"node:crypto\";\n\nimport { JsonNumber, pyFloatRepr, pyRound } from \"../cli/platform/worldData/json\";\nimport { applyTransforms } from \"./transforms\";\n\n/** The `[redact]` table as `describe` reports it (`connection.redact`, and\n * `redact` on `GET /api/public/worlds/{slug}`). */\nexport type RedactPolicy = {\n /** The digest salt: the connector's slug from connector.toml. It can differ\n * from the platform world slug (`spycloud` vs `spycloud-world`); `storedForms`\n * prefers it and falls back to the world slug only when it is absent. */\n slug?: string;\n hash: string[];\n drop: string[];\n preserve: string[];\n round: Record<string, number>;\n};\n\n/** The policy one field is stored under; null when it is stored in the clear. */\nexport type Redaction = \"hash\" | \"drop\" | \"preserve\" | `round:${number}`;\n\n/**\n * A value as the Python runtime would see it. JavaScript has one number\n * type, so an integral number takes Python's `int` path and any other number\n * its `float` path (`100` is `100`, never `100.0`); integers stay exact within\n * the safe range only.\n */\nexport type Plaintext = string | number;\n\nconst isInt = (value: Plaintext): value is number => typeof value === \"number\" && Number.isInteger(value);\n\n/** `str(value)` for an int or str, `repr(value)` for a float — the text the\n * Python runtime salts and shapes. */\nexport function pyText(value: Plaintext): string {\n if (typeof value === \"string\") return value;\n if (Number.isInteger(value)) return String(value);\n if (Number.isNaN(value)) return \"nan\";\n if (!Number.isFinite(value)) return value > 0 ? \"inf\" : \"-inf\";\n return pyFloatRepr(value);\n}\n\n/** The `hash` form: `\"sha256:\" + sha256(\"<slug>:<plaintext>\")` as hex. */\nexport function hashForm(slug: string, plaintext: Plaintext): string {\n return \"sha256:\" + createHash(\"sha256\").update(`${slug}:${pyText(plaintext)}`, \"utf8\").digest(\"hex\");\n}\n\n/**\n * The `preserve` form, the Python `_shaped`: the same length, every ASCII\n * digit still a digit, every ASCII letter still a letter of the same case,\n * everything else (separators, punctuation, non-ASCII) left in place. The\n * bytes come from sha256 of the seed `\"<slug>:<text>\"`, re-keyed as\n * sha256(digest + seed) once the 32 bytes are spent. A number keeps its type:\n * an int keeps its digit count (a leading zero is replaced), a float is re-read.\n */\nexport function preserveForm(slug: string, plaintext: Plaintext): Plaintext {\n const kind = typeof plaintext === \"string\" ? \"str\" : isInt(plaintext) ? \"int\" : \"float\";\n const shaped = shapeText(slug, pyText(plaintext), kind);\n return kind === \"str\" ? shaped : Number(shaped);\n}\n\n/** The shaping itself, on text: `kind` says which of Python's rules apply\n * (letters are re-lettered for a str only; an int keeps its digit count). */\nexport function shapeText(slug: string, text: string, kind: \"str\" | \"int\" | \"float\"): string {\n const seed = Buffer.from(`${slug}:${text}`, \"utf8\");\n let digest = createHash(\"sha256\").update(seed).digest();\n let cursor = 0;\n const out: string[] = [];\n for (const char of text) {\n if (cursor === digest.length) {\n digest = createHash(\"sha256\").update(Buffer.concat([digest, seed])).digest();\n cursor = 0;\n }\n const byte = digest[cursor]!;\n cursor += 1;\n if (char >= \"0\" && char <= \"9\") out.push(String(byte % 10));\n else if (kind === \"str\" && char >= \"a\" && char <= \"z\") out.push(String.fromCharCode(97 + (byte % 26)));\n else if (kind === \"str\" && char >= \"A\" && char <= \"Z\") out.push(String.fromCharCode(65 + (byte % 26)));\n else out.push(char);\n }\n // An int keeps its digit count; int() would drop a leading zero.\n if (kind === \"int\" && out.length > 1 && out[0] === \"0\") out[0] = String(1 + (digest[0]! % 9));\n return out.join(\"\");\n}\n\n/** The `round` form: Python's `round(value, decimals)` — an int unchanged, a\n * float correctly rounded with ties to even; a string is not a number and\n * passes through as the runtime leaves it. */\nexport function roundForm(plaintext: Plaintext, decimals: number): Plaintext {\n if (typeof plaintext === \"string\" || isInt(plaintext) || !Number.isFinite(plaintext)) return plaintext;\n return pyRound(new JsonNumber(pyFloatRepr(plaintext)), decimals).value;\n}\n\n/**\n * The policy a field of this name falls under, ranked as the runtime applies\n * them (drop, hash, preserve, round). Read without a path: a bare name in the\n * table counts, and so does a dotted path whose last segment is the field.\n */\nexport function redactionOf(redact: RedactPolicy | null | undefined, field: string): Redaction | null {\n if (!redact) return null;\n const named = (names: string[] | undefined) =>\n (names ?? []).some((name) => name === field || name.slice(name.lastIndexOf(\".\") + 1) === field);\n if (named(redact.drop)) return \"drop\";\n if (named(redact.hash)) return \"hash\";\n if (named(redact.preserve)) return \"preserve\";\n const decimals = redact.round?.[field];\n if (typeof decimals === \"number\") return `round:${decimals}`;\n return null;\n}\n\n/**\n * Every value the store may hold for `field` given this plaintext:\n *\n * clear field -> [plaintext]\n * hash -> [\"sha256:<hex>\"]\n * preserve -> [the shape-preserving digest]\n * round -> [round(plaintext, decimals)] for a number, [plaintext] otherwise\n * drop -> [] (the field is not on disk: a documented miss, not an error)\n *\n * `world` is what `describeWorld` / the bridge's `describe` return: the slug\n * is the salt, `redact` the table.\n *\n * `transform` — a cross-world mapping's chain (`./transforms`) — runs over the\n * plaintext FIRST, so `hash` and `preserve` salt the normalised text; omitted\n * (or empty) is today's behaviour, byte for byte.\n */\nexport function storedForms(\n world: { slug: string; redact?: RedactPolicy | null },\n field: string,\n plaintext: Plaintext,\n transform?: readonly string[],\n): Plaintext[] {\n if (transform?.length) plaintext = applyTransforms(plaintext, transform);\n const policy = redactionOf(world.redact, field);\n const salt = world.redact?.slug ?? world.slug;\n if (policy === \"drop\") return [];\n if (policy === \"hash\") return [hashForm(salt, plaintext)];\n if (policy === \"preserve\") return [preserveForm(salt, plaintext)];\n if (policy !== null) return [roundForm(plaintext, world.redact!.round[field]!)];\n return [plaintext];\n}\n","/**\n * `queryRows(slug[@ref], entity, {where, resolve, limit, offset})` — the rows\n * of one entity that match a predicate, from\n * `GET /api/public/worlds/{slug}/data?ref=&entity=&where=&limit=&offset=&resolve=`.\n * `where` is field → value, or field → list of values (any of); values match\n * the STORED form as given. With `resolve: true` the values are plaintext and\n * the runtime maps each to its stored form under the world's `[redact]`\n * policy first (a hashed `email` becomes its slug-salted digest; a dropped\n * field resolves to nothing and matches no row — the answer's `resolved`\n * says so). The CLI twin is `gateway worlds data query <slug> <entity>`.\n *\n * `across: true` runs the same plaintext in every world this one links to\n * whose `[dependencies.<alias>.entities]` mapping covers a `where` field;\n * each linked world recomputes its own stored form (after the mapping's\n * transform) at query time — no join on disk, no shared salt. The answer\n * is then {@link WorldQueryAcrossResult}: one group per world, the root\n * first, and with `compare: true` a parity report saying, per field and\n * per world, `matched`, `no match` or `unmapped`.\n */\n\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\nimport type { Plaintext } from \"./redaction\";\n\nexport type WorldQueryWhere = Record<string, Plaintext | Plaintext[]>;\n\nexport type WorldQueryOptions = {\n where?: WorldQueryWhere;\n /** The `where` values are plaintext: resolve each to its stored form before matching. */\n resolve?: boolean;\n limit?: number;\n offset?: number;\n /** Query the linked worlds too; the answer becomes groups. */\n across?: boolean;\n /** With `across`: add the parity report. */\n compare?: boolean;\n};\n\n/** The options that make `queryRows` answer {@link WorldQueryAcrossResult}. */\nexport type WorldQueryAcrossOptions = WorldQueryOptions & { across: true };\n\nexport type WorldQueryResult = {\n slug: string;\n versionId: string;\n kind: string | null;\n entity: string;\n rows: Record<string, unknown>[];\n /** Rows in this page. */\n count: number;\n /** Rows matching in all; null when the store does not count them. */\n total: number | null;\n limit: number;\n offset: number;\n /** With `resolve`: the stored forms each `where` field was matched against\n * (`[]` for a dropped field, which is why such a query matches nothing). */\n resolved?: Record<string, Plaintext[]>;\n entityCounts: Record<string, number>;\n snapshot: WorldQuerySnapshot | null;\n};\n\nexport type WorldQuerySnapshot = {\n snapshotId: string;\n contractHash: string;\n batchDigest: string;\n bytes: number;\n};\n\n/** One world's page inside an across answer: the root (`alias: null`, no\n * `mapping`) or a linked world with the mappings that carried the root's\n * `where` fields into its own entity. */\nexport type WorldQueryGroup = {\n world: { slug: string; alias: string | null; versionId: string };\n entity: string;\n rows: Record<string, unknown>[];\n count: number;\n total: number | null;\n limit: number;\n offset: number;\n resolved?: Record<string, Plaintext[]>;\n mapping?: { field: string; depField: string; transform: string[] }[];\n};\n\nexport type WorldQueryCompareStatus = \"matched\" | \"no match\" | \"unmapped\";\n\n/** Per `where` field, per world: whether the field reached the world and\n * whether any row matched there; `present`/`absent` list the worlds by slug. */\nexport type WorldQueryCompare = {\n present: string[];\n absent: string[];\n perField: {\n field: string;\n worlds: {\n world: string;\n alias: string | null;\n status: WorldQueryCompareStatus;\n /** `<depEntity>.<depField>` and the transform applied (mapped worlds only). */\n depField?: string;\n transform?: string[];\n }[];\n }[];\n};\n\nexport type WorldQueryAcrossResult = {\n slug: string;\n versionId: string;\n kind: string | null;\n entity: string;\n /** The root world first, then one per linked world that was queried. */\n groups: WorldQueryGroup[];\n compare?: WorldQueryCompare;\n entityCounts: Record<string, number>;\n snapshot: WorldQuerySnapshot | null;\n};\n\n/** The query string the route reads; `where` travels as URL-encoded JSON and\n * `ref` (the `@ref` of `slug@ref`) picks the version. */\nexport function queryRowsSearch(entity: string, opts: WorldQueryOptions = {}, ref?: string): string {\n const search = new URLSearchParams();\n if (ref) search.set(\"ref\", ref);\n search.set(\"entity\", entity);\n if (opts.where && Object.keys(opts.where).length) search.set(\"where\", JSON.stringify(opts.where));\n if (opts.limit !== undefined) search.set(\"limit\", String(opts.limit));\n if (opts.offset !== undefined) search.set(\"offset\", String(opts.offset));\n if (opts.resolve) search.set(\"resolve\", \"true\");\n if (opts.across) search.set(\"across\", \"true\");\n if (opts.compare) search.set(\"compare\", \"true\");\n return `?${search.toString()}`;\n}\n\n/** One version of the world, queried: the main tip for a bare slug, or the\n * version `slug@ref` names (branch, tag, semver pin or hash prefix — the\n * `bench pull` grammar; a ref nothing answers to is the platform's 404, never\n * the head). With `across: true` the answer is the groups shape. */\nexport async function queryRows(\n slug: string,\n entity: string,\n opts: WorldQueryAcrossOptions,\n options?: WorldsClientOptions,\n): Promise<WorldQueryAcrossResult>;\nexport async function queryRows(\n slug: string,\n entity: string,\n opts?: WorldQueryOptions,\n options?: WorldsClientOptions,\n): Promise<WorldQueryResult>;\nexport async function queryRows(\n slugRef: string,\n entity: string,\n opts: WorldQueryOptions = {},\n options: WorldsClientOptions = {},\n): Promise<WorldQueryResult | WorldQueryAcrossResult> {\n const [slug, ref] = slugRef.split(\"@\", 2) as [string, string | undefined];\n if (!slug || ref === \"\") throw new Error(`queryRows needs a slug, optionally slug@ref (got ${slugRef})`);\n if (!entity) throw new Error(\"queryRows needs an entity\");\n if (opts.compare && !opts.across) throw new Error(\"queryRows: compare needs across\");\n return apiRequest<WorldQueryResult | WorldQueryAcrossResult>(\n options,\n \"GET\",\n `/api/public/worlds/${encodeURIComponent(slug)}/data${queryRowsSearch(entity, opts, ref)}`,\n );\n}\n","/**\n * `migrateWorld(slug)` — convert a stored world into a schema world, from\n * `POST /api/public/worlds/{slug}/migrate`; `migrateProjectWorlds()` plans\n * (or migrates) every connector world in the project from\n * `POST /api/public/worlds/migrate`. Dry run by default: the report says\n * what the version is, what the conversion does, or why it cannot; `apply`\n * commits the migrated tree as the next version (\"Migrated to a schema\n * world\"). Targets are the platform's connector worlds; a hand-built world\n * needs `force`. The CLI twin is `gateway worlds migrate`.\n */\n\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\n\nexport type WorldMigrationRefusal = {\n code: string;\n message: string;\n /** Paths the conversion needed and did not find. */\n missing: string[];\n};\n\nexport type WorldMigrationReport = {\n slug: string;\n containerId: string;\n versionId: string;\n /** True when the container was created from a connector template. */\n connectorWorld: boolean;\n /** schema | api-bundle | legacy-tools | harbor | verifiers */\n shape: string;\n target: \"schema\";\n /** True when the world already is a schema world. */\n unchanged: boolean;\n /** The dry-run report, one sentence each. */\n actions: string[];\n /** Files the migrated tree holds; 0 on a refusal. */\n files: number;\n refusal: WorldMigrationRefusal | null;\n /** True when this call committed the migrated tree. */\n applied: boolean;\n version: { id: string; contentHash: string } | null;\n};\n\nexport type MigrateWorldOptions = {\n /** Commit the migrated tree as the next version. Default false: dry run. */\n apply?: boolean;\n /** Migrate a world that was not created from a connector template. */\n force?: boolean;\n};\n\nexport async function migrateWorld(\n slug: string,\n input: MigrateWorldOptions = {},\n options: WorldsClientOptions = {},\n): Promise<WorldMigrationReport> {\n if (slug.includes(\"@\"))\n throw new Error(\n `migrateWorld converts a world's head version: pass the slug without @ref (got ${slug})`,\n );\n return apiRequest<WorldMigrationReport>(\n options,\n \"POST\",\n `/api/public/worlds/${encodeURIComponent(slug)}/migrate`,\n {\n ...(input.apply === undefined ? {} : { apply: input.apply }),\n ...(input.force === undefined ? {} : { force: input.force }),\n },\n );\n}\n\n/** Every connector world in the project, one report each. */\nexport async function migrateProjectWorlds(\n input: { apply?: boolean } = {},\n options: WorldsClientOptions = {},\n): Promise<{ worlds: WorldMigrationReport[]; applied: boolean }> {\n return apiRequest<{ worlds: WorldMigrationReport[]; applied: boolean }>(\n options,\n \"POST\",\n \"/api/public/worlds/migrate\",\n input.apply === undefined ? {} : { apply: input.apply },\n );\n}\n","/**\n * 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 /** `--name \"\"` is meaningful (clears a field); otherwise an empty value is a usage error. */\n allowEmpty?: boolean;\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 /** A verb whose output is always JSON accepts `--json` as a no-op, so an agent that passes it everywhere never fails. */\n output?: \"json\";\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 /** Whether stdin is a terminal — a person is typing, so a read prompts on stderr. */\n stdinIsTTY?: () => boolean;\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 /** Set on the root only: `gateway --version` prints `<name> <version>`. */\n version?: 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, withJsonFlag(spec));\n return this;\n }\n}\n\nconst JSON_FLAG: FlagSpec = {\n name: \"json\",\n help: \"Output is JSON (the default for this command; accepted so every JSON verb takes --json).\",\n boolean: true,\n};\n\n/** The `--json` flag of a read verb whose default output is text. */\nexport const JSON_OUTPUT_FLAG: FlagSpec = {\n name: \"json\",\n help: \"Print JSON instead of the text lines.\",\n boolean: true,\n};\n\n/** One output door for text-by-default read verbs: `--json` prints `value`, otherwise `lines`. */\nexport function emit(\n ctx: CommandContext,\n args: Parsed,\n value: unknown,\n lines: () => string[],\n): void {\n if (args.flags.json === true) {\n ctx.stdout(JSON.stringify(value, null, 2));\n return;\n }\n for (const line of lines()) ctx.stdout(line);\n}\n\nfunction withJsonFlag(spec: CommandSpec): CommandSpec {\n if (spec.output !== \"json\") return spec;\n if ((spec.flags ?? []).some((f) => f.name === \"json\")) return spec;\n return { ...spec, flags: [...(spec.flags ?? []), JSON_FLAG] };\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 if (given.has(f.name) && !f.repeat)\n throw new CliError(`--${f.name} given twice`);\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 || looksLikeFlag(next, byName))\n throw new CliError(`--${f.name} needs a value`);\n value = next;\n i++;\n }\n if (value.trim() === \"\" && !f.allowEmpty)\n throw new CliError(`--${f.name} must not be empty`);\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 const blank = positionals.findIndex((p) => p.trim() === \"\");\n if (blank >= 0) {\n const name = specs[Math.min(blank, specs.length - 1)]?.name ?? \"argument\";\n throw new CliError(`${spec.name}: <${name}> must not be empty`);\n }\n return { positionals, flags, given };\n}\n\n/** `--publish -m x` must not read `-m` as --publish's value, yet `--content \"-- x\"` must write\n * `-- x`: a token is a flag only when it names a flag this command knows. */\nfunction looksLikeFlag(token: string, known: Map<string, FlagSpec>): boolean {\n if (!token.startsWith(\"-\") || token.length < 2) return false;\n const name = token.replace(/^--?/, \"\").split(\"=\")[0]!;\n return known.has(name);\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 if (node === root && root.version !== undefined && (token === \"--version\" || token === \"-V\")) {\n ctx.stdout(`${root.name} ${root.version}`);\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\";\nimport { parseErrorBody } from \"../worlds\";\nimport { PlatformTransport, type PlatformMethod } from \"../worlds/transport\";\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\nconst STORED_FIELDS = [\"host\", \"public_key\", \"api_key\"] as const;\n\n/** An empty `GATEWAY_CONFIG_DIR` is unset, never the working directory. */\nexport function configPath(): string {\n return path.join(process.env.GATEWAY_CONFIG_DIR || path.join(os.homedir(), \".gateway\"), \"config.json\");\n}\n\n/** The stored strings; an unreadable, empty or malformed file reads as no login. */\nexport function readConfig(): StoredConfig {\n let stored: unknown;\n try {\n stored = JSON.parse(fs.readFileSync(configPath(), \"utf8\"));\n } catch {\n return {};\n }\n const record = (stored ?? {}) as Record<string, unknown>;\n return Object.fromEntries(STORED_FIELDS.filter((f) => typeof record[f] === \"string\").map((f) => [f, record[f]]));\n}\n\n/** Owner-only from the first byte through one descriptor: an older, looser file is tightened, a symlink refused. */\nexport function writeConfig(config: StoredConfig): void {\n const file = configPath();\n fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });\n const { O_WRONLY, O_CREAT, O_TRUNC, O_NOFOLLOW = 0 } = fs.constants;\n const fd = fs.openSync(file, O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0o600);\n try {\n fs.fchmodSync(fd, 0o600);\n fs.writeFileSync(fd, JSON.stringify(config, null, 2) + \"\\n\");\n } finally {\n fs.closeSync(fd);\n }\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, secretKeyFlag?: string): Credentials {\n const stored = readConfig();\n // `||`: an empty variable is unset, as in the Python twin's `PlatformCredentials`.\n const host = (hostFlag || process.env.GATEWAY_HOST || stored.host || \"\").replace(/\\/+$/, \"\");\n // The stored keys belong to the stored host: never send them to another one.\n const login = host === (stored.host ?? \"\").replace(/\\/+$/, \"\") ? stored : {};\n const publicKey = process.env.GATEWAY_PUBLIC_KEY || login.public_key || \"\";\n const secretKey =\n secretKeyFlag || process.env.GATEWAY_SECRET_KEY || process.env.GATEWAY_API_KEY || login.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;\n * the body renders through `parseErrorBody` (stable public `code`, never a server class name). */\nexport class ApiError extends CliError {\n readonly code: string | null;\n\n constructor(\n readonly status: number,\n readonly method: string,\n readonly route: string,\n readonly text: string,\n ) {\n const body = parseErrorBody(text);\n super(`${method} ${route} -> ${status}: ${body.detail}`, 1);\n this.code = body.code;\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: PlatformMethod,\n route: string,\n body?: unknown,\n init: { timeoutMs?: number } = {},\n): Promise<T> {\n const reply = await new PlatformTransport(creds).send(method, route, body, init);\n if (!reply.ok) throw new ApiError(reply.status, method, route, reply.text);\n return (reply.text ? JSON.parse(reply.text) : {}) as T;\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.12 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, python, then `uv python find` are tried in that order).\n */\n\n/** The world store's sqlite `setconfig` is 3.12+ (`schema/store.py` refuses older). */\nconst MIN_PYTHON: [number, number] = [3, 12];\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\",\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.12, 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\";\nimport { PlatformTransport } from \"../../worlds/transport\";\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/** The bridge's file-count cap (`platform.MAX_FILES`): a tree the runtime\n * returns with more entries than this is refused before anything is written. */\nexport const MAX_WORLD_FILES = 2000;\n\nconst RUNTIME_TIMEOUT_MS = 180_000;\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 if (files.length > MAX_WORLD_FILES)\n throw new CliError(`The runtime returned ${files.length} files, over the ${MAX_WORLD_FILES} limit`, 1);\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\nconst YAML_NAME = /\\.ya?ml$/i;\n\n/** The Python parser's rule (`conform.parse_openapi`): JSON when the name says\n * so or the text opens with `{`/`[`, YAML otherwise — so an extensionless YAML\n * document is routed to a runtime that can parse it. */\nfunction isYamlSource(name: string, base64: string): boolean {\n if (name.endsWith(\".json\")) return false;\n if (YAML_NAME.test(name)) return true;\n const head = Buffer.from(base64.slice(0, 256), \"base64\").toString(\"utf8\").trimStart();\n return ![\"{\", \"[\"].includes(head[0] ?? \"\");\n}\n\n/** Whether the request names a YAML OpenAPI document the runtime must parse. */\nfunction yamlDocument(request: RuntimeRequest): boolean {\n if (request.command === \"init-openapi\")\n return isYamlSource(String(request.source ?? \"\"), String(request.document ?? \"\"));\n return (\n request.command === \"conform\" &&\n Array.isArray(request.openapi) &&\n (request.openapi as { path?: string }[]).some((doc) => YAML_NAME.test(doc.path ?? \"\"))\n );\n}\n\n/** Whether `runtime()` will answer this request with the bundled runtime on this\n * machine (a python3, plus PyYAML when the request names a YAML document). */\nexport function runsLocally(request: RuntimeRequest): boolean {\n const local = localRuntime();\n return local !== null && !(yamlDocument(request) && !localPythonHasYaml(local.python));\n}\n\n/** `schema init` writes only into a directory that does not exist yet or is empty. */\nexport function assertEmptyTarget(dir: string): void {\n if (!fs.existsSync(dir)) return;\n if (!fs.statSync(dir).isDirectory()) throw new CliError(`${dir} exists and is not a directory`);\n if (fs.readdirSync(dir).length > 0) throw new CliError(`${dir} must be a new or empty directory`);\n}\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 * A schema world is checked here before it is pushed, the way the Python CLI\n * does: a tree edited after its last compile would otherwise travel to the\n * platform only to be refused at finalize. Runs only with the bundled runtime\n * on this machine (no round trip); without one the platform's own check\n * refuses the version instead.\n */\nexport async function checkSchemaTreeBeforePush(dir: string): Promise<void> {\n const abs = path.resolve(dir);\n if (!fs.existsSync(path.join(abs, \"gateway-env.toml\")) || !localRuntime()) return;\n try {\n await runtime(null, { command: \"validate\", world: abs });\n } catch (error) {\n if (error instanceof BridgeRejected)\n throw new CliError(`Schema world check failed before push: ${error.message}`, 1);\n throw error;\n }\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 // OpenAPI document (conform, init-openapi) needs PyYAML, which the vendored\n // runtime does not carry.\n const local = localRuntime();\n if (local && runsLocally(request)) {\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 route = \"/api/public/worlds/runtime\";\n const res = await new PlatformTransport(creds).send(\"POST\", route, request, {\n timeoutMs: opts.timeoutMs ?? RUNTIME_TIMEOUT_MS,\n });\n let payload: unknown = null;\n try {\n payload = res.text ? JSON.parse(res.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}: ${res.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}\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\nexport type LocalFilesOptions = {\n entity?: string;\n delimiter?: string;\n mode?: ImportMode;\n merge?: \"upsert\" | \"fill\";\n redact?: \"off\" | \"apply\" | \"refuse\";\n dryRun?: boolean;\n};\n\nexport type LocalFilesResult = LocalImportResult & {\n /** How many rows the files held. */\n rows: number;\n proof?: string;\n deferred?: string[];\n};\n\n/**\n * Rows FILES into a local directory, streamed: the runtime on this machine\n * opens the files and the tree in place (`import-files`), so a 100 MB CSV\n * costs one row of memory at a time and nothing travels through the bridge\n * but paths. Only the bundled runtime can do this — the platform's bridge\n * reads no file of this machine — so without one the caller falls back to\n * `importLocalWorldData` within its inline cap. The snapshots are rebuilt\n * in place by the runtime; nothing to drop.\n */\nexport async function importLocalWorldFiles(\n dir: string,\n sources: string[],\n opts: LocalFilesOptions,\n): Promise<LocalFilesResult> {\n const local = localRuntime();\n if (!local)\n throw new CliError(\n `Rows files stream into a directory through the bundled runtime on this machine, and none can run: ${localRuntimeReason()}`,\n 1,\n );\n const res = await runtime<{\n kind?: string;\n entity_counts?: Record<string, number>;\n changed?: boolean;\n rows?: number;\n proof?: string;\n deferred?: string[];\n }>(null, {\n command: \"import-files\",\n world: path.resolve(dir),\n sources: sources.map((source) => path.resolve(source)),\n mode: opts.mode ?? \"append\",\n ...(opts.entity ? { entity: opts.entity } : {}),\n ...(opts.delimiter ? { delimiter: opts.delimiter } : {}),\n ...(opts.merge && opts.merge !== \"upsert\" ? { merge: opts.merge } : {}),\n ...(opts.redact && opts.redact !== \"off\" ? { redact: opts.redact } : {}),\n ...(opts.dryRun ? { dry_run: true } : {}),\n });\n return {\n kind: res.kind ?? \"unknown\",\n entity_counts: res.entity_counts ?? {},\n changed: Boolean(res.changed),\n rows: res.rows ?? 0,\n ...(res.proof ? { proof: res.proof } : {}),\n ...(res.deferred ? { deferred: res.deferred } : {}),\n };\n}\n\nexport type LocalChunksOptions = {\n entity?: string;\n delimiter?: string;\n chunkBytes?: number;\n chunkRows?: number;\n};\n\nexport type LocalChunk = {\n ordinal: number;\n path: string;\n rows: number;\n bytes: number;\n digest: string;\n entity: string | null;\n};\n\nexport type LocalChunksResult = { rows: number; chunks: LocalChunk[] };\n\n/**\n * Rows FILES into the gzipped JSONL chunks a platform data batch takes,\n * written under `out` by the runtime on this machine (`chunk-files`): the\n * files are typed by the directory's contract exactly as `importLocalWorldFiles`\n * types them, but nothing lands in the tree — the chunks are bound for a\n * platform snapshot. This is the sandbox-side half of `worlds sandbox import`:\n * the platform runs `gateway worlds data chunks` inside the sandbox, whose\n * staged `gateway` is this CLI, then reads the chunk files out itself.\n */\nexport async function chunkLocalWorldFiles(\n dir: string,\n sources: string[],\n out: string,\n opts: LocalChunksOptions,\n): Promise<LocalChunksResult> {\n const local = localRuntime();\n if (!local)\n throw new CliError(\n `Rows files are cut into chunks by the bundled runtime on this machine, and none can run: ${localRuntimeReason()}`,\n 1,\n );\n const res = await runtime<{ rows?: number; chunks?: LocalChunk[] }>(null, {\n command: \"chunk-files\",\n world: path.resolve(dir),\n sources: sources.map((source) => path.resolve(source)),\n out: path.resolve(out),\n ...(opts.entity ? { entity: opts.entity } : {}),\n ...(opts.delimiter ? { delimiter: opts.delimiter } : {}),\n ...(opts.chunkBytes ? { chunk_bytes: opts.chunkBytes } : {}),\n ...(opts.chunkRows ? { chunk_rows: opts.chunkRows } : {}),\n });\n return { rows: res.rows ?? 0, chunks: res.chunks ?? [] };\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 dry_run: true,\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 = {\n batchId: string;\n state: string;\n limits?: { chunkBytes?: number; batchBytes?: number; inlineBytes?: number };\n};\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([\n \"applied\",\n \"refused\",\n \"published\",\n \"failed\",\n]);\n\n/** Whether the batch is done moving. The worker records `applied` and then, for\n * a `publish: now` batch, cuts the version and records `published`; a poll that\n * lands between the two must keep going or the caller reads a version that is\n * not there yet. Dry runs and `publish: later` rest at `applied`. */\nexport function isSettled(status: BatchStatus): boolean {\n if (!TERMINAL_STATES.has(status.state)) return false;\n if (status.state !== \"applied\") return true;\n return (\n status.dryRun === true || status.publish !== \"now\" || !status.snapshotId\n );\n}\n\nexport const sleepMs = (ms: number): Promise<void> =>\n new Promise((resolve) => setTimeout(resolve, ms));\n\n/** The bare slug of a `slug` or `slug@ref` world argument — what `WorldDataApi` addresses. */\nexport const slugOf = (world: string): string => world.split(\"@\", 1)[0]!;\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(\n batchId: string,\n chunk: {\n ordinal: number;\n digest: string;\n bytes: number;\n rows: number;\n entity: string | null;\n },\n ): Promise<RegisteredChunk> {\n return api<RegisteredChunk>(\n this.creds,\n \"POST\",\n `${this.base}/batches/${batchId}/chunks`,\n {\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\n /**\n * Stage a project-drive rows file as one chunk, on the platform: the server\n * streams it out of drive storage into chunk storage and answers with the\n * digest and gzipped size it derived. No bytes pass through this process.\n */\n async stageDrive(\n batchId: string,\n chunk: { ordinal: number; path: string; entity: string | null },\n ): Promise<ManifestChunk> {\n const staged = await api<{\n chunkId: string;\n uploaded: boolean;\n digest?: string;\n bytes?: number;\n rows?: number;\n }>(this.creds, \"POST\", `${this.base}/batches/${batchId}/chunks`, {\n ordinal: chunk.ordinal,\n drive: chunk.path,\n ...(chunk.entity ? { entity: chunk.entity } : {}),\n });\n if (\n !staged.uploaded ||\n !staged.digest ||\n staged.bytes === undefined ||\n staged.rows === undefined\n )\n throw new CliError(\n `the server staged drive:${chunk.path} as chunk ${chunk.ordinal} without its digest, size and rows`,\n 1,\n );\n return {\n ordinal: chunk.ordinal,\n digest: staged.digest,\n bytes: staged.bytes,\n rows: staged.rows,\n entity: chunk.entity,\n chunkId: staged.chunkId,\n uploaded: true,\n };\n }\n\n markUploaded(\n batchId: string,\n chunkId: string,\n ): Promise<{ chunkId: string; uploaded: boolean; bytes: number }> {\n return api(\n this.creds,\n \"POST\",\n `${this.base}/batches/${batchId}/chunks/${chunkId}/uploaded`,\n );\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>(\n this.creds,\n \"GET\",\n `${this.base}/batches/${batchId}`,\n );\n }\n\n list(\n limit?: number,\n cursor?: string,\n ): 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(\n message?: string,\n ): Promise<{ versionId: string; snapshotId: string; batchIds: string[] }> {\n return api(\n this.creds,\n \"POST\",\n `${this.base}/publish`,\n message ? { message } : {},\n );\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(\n uploadUrl: string,\n gz: Buffer,\n signed?: Record<string, string>,\n ): 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, {\n method: \"PUT\",\n body: new Uint8Array(gz),\n headers,\n });\n if (res.ok) return;\n if (res.status < 500 || attempt >= delays.length)\n throw new CliError(\n `chunk upload -> ${res.status}: ${(await res.text()).slice(0, 300)}`,\n 1,\n );\n } catch (error) {\n if (error instanceof CliError || attempt >= delays.length)\n throw error instanceof CliError\n ? error\n : new CliError(\n `chunk upload failed: ${(error as Error).message}`,\n 1,\n );\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)\n throw new CliError(\n `the server registered chunk ${chunk.ordinal} without an upload URL`,\n 1,\n );\n await this.put(registered.uploadUrl, chunk.gz, registered.uploadHeaders);\n await this.markUploaded(batchId, registered.chunkId);\n }\n return {\n ordinal: chunk.ordinal,\n digest: chunk.digest,\n bytes: chunk.bytes,\n rows: chunk.rows,\n entity: chunk.entity,\n chunkId: registered.chunkId,\n uploaded: true,\n };\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>(\n items: AsyncIterable<T>,\n limit: number,\n fn: (item: T) => Promise<void>,\n): 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(\n client: WorldDataApi,\n batchId: string,\n opts: WaitOptions = {},\n): 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 (isSettled(status)) 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/** A batch as the CLI prints it: `reportUrl` (a signed, credential-bearing,\n * expiring URL) never reaches stdout; `reportAvailable` says the platform\n * holds the full refusal report, which `--report <file>` fetches. */\nexport type PrintableBatch = Omit<BatchStatus, \"reportUrl\"> & {\n reportAvailable: boolean;\n};\n\nexport function printableStatus(status: BatchStatus): PrintableBatch {\n const { reportUrl, ...rest } = status;\n return { ...rest, reportAvailable: Boolean(reportUrl) };\n}\n\n/** One stderr line pointing at the full report when the platform holds one. */\nexport function reportHint(status: BatchStatus): string | null {\n if (!status.reportUrl) return null;\n const count = status.refusalCount ?? 0;\n return `${count} refusal${count === 1 ? \"\" : \"s\"}; the first ${Math.min(count, 200)} are inline — rerun with --report <file> for the full JSONL report.`;\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(\n status: BatchStatus,\n file: string,\n): 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\n text = (status.refusals ?? [])\n .map((r) => JSON.stringify(r) + \"\\n\")\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\n/** Cut the row stream into chunks numbered from `ordinalStart` (the chunks a\n * batch already holds ahead of these, e.g. drive files the platform staged). */\nexport async function* buildChunks(\n rows: AsyncIterable<TaggedRow>,\n plan: ChunkPlan,\n ordinalStart = 0,\n): AsyncGenerator<BuiltChunk> {\n let lines: Buffer[] = [];\n let rawBytes = 0;\n let ordinal = ordinalStart;\n let seen = 0;\n const flush = (): BuiltChunk => {\n const raw = Buffer.concat(lines);\n const built = finishChunk(\n ordinal++,\n raw,\n lines.length,\n plan.entity,\n seen - lines.length,\n );\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(\n ordinal: number,\n raw: Buffer,\n rows: number,\n entity: string | null,\n firstRow = 0,\n): 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 (\n deflateRawSync(Buffer.from(CPYTHON_PROBE_TEXT), {\n level: GZIP_LEVEL,\n }).toString(\"hex\") === CPYTHON_PROBE_DEFLATE\n );\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 =\n '{\"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 =\n \"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 =>\n `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(\n raw: Buffer,\n opts: { level?: number; name?: string } = {},\n): Buffer {\n const level = opts.level ?? GZIP_LEVEL;\n const name = opts.name\n ? Buffer.concat([Buffer.from(opts.name, \"latin1\"), Buffer.from([0])])\n : Buffer.alloc(0);\n const header = Buffer.from([\n 0x1f,\n 0x8b,\n 0x08,\n opts.name ? 0x08 : 0x00,\n 0,\n 0,\n 0,\n 0,\n level === 9 ? 0x02 : level === 1 ? 0x04 : 0x00,\n 0xff,\n ]);\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++)\n 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> = {\n \"\": 1,\n b: 1,\n k: 1024,\n kib: 1024,\n kb: 1000,\n m: 1024 ** 2,\n mib: 1024 ** 2,\n mb: 1000 ** 2,\n g: 1024 ** 3,\n gib: 1024 ** 3,\n gb: 1000 ** 3,\n };\n const raw = text.trim().toLowerCase().replace(/ /g, \"\");\n const m = /^(\\d+)([a-z]*)$/.exec(raw);\n if (!m || !(m[2]! in units))\n throw new Error(\n `--chunk-bytes takes a size like 64MiB or 1000000, not '${text}'`,\n );\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. Both routes decode\n * stored JSON text once on the way out (`parseIoAsJson` defaults to true on the\n * v1 route; the session route renders with the same default), so `input` and\n * `output` arrive as the values the tool saw — an object, or a string when the\n * tool really produced text. Nothing here parses them again. */\nexport type ObservationLike = {\n id?: string;\n traceId?: string | null;\n type?: string;\n name?: string | null;\n input?: unknown;\n output?: unknown;\n startTime?: string | Date;\n level?: string;\n statusMessage?: string | null;\n};\n\nexport type ObservationConversion = {\n records: ToolCallRecord[];\n /** TOOL observations whose name is not one of the world's operations, by name. */\n unknownTools: Record<string, number>;\n /** Observations that were not converted, by reason. */\n skipped: Record<string, number>;\n};\n\nconst isoOf = (value: string | Date | undefined): string | undefined =>\n value instanceof Date ? value.toISOString() : typeof value === \"string\" ? value : undefined;\n\n/**\n * TOOL observations → tool-call records: `name` is the tool, `input` the args,\n * `output` the result, `startTime` the time, `trace:<traceId>/<id>` the source.\n * `input`/`output` arrive from the public API already decoded (it parses the\n * stored text once), so they are taken as they are: a string `output` stays a\n * string even when it looks like JSON; an `input` that is not an object leaves\n * `args` empty rather than guessed.\n * Only `type: \"TOOL\"` converts. With `tools` (the world's operation names) an\n * observation for any other tool is counted in `unknownTools`, not converted.\n * An `ERROR`-level observation converts with `error` set, so ingest counts it\n * as a failed call instead of projecting its output.\n */\nexport function toolCallsFromObservations(\n observations: ObservationLike[],\n opts: { tools?: Iterable<string> | null; session?: string; since?: string } = {},\n): ObservationConversion {\n const known = opts.tools ? new Set(opts.tools) : null;\n const sinceMs = opts.since ? Date.parse(opts.since) : NaN;\n const out: ObservationConversion = { records: [], unknownTools: {}, skipped: {} };\n const skip = (reason: string) => {\n out.skipped[reason] = (out.skipped[reason] ?? 0) + 1;\n };\n for (const observation of observations) {\n if (observation.type !== \"TOOL\") {\n skip(`type ${observation.type ?? \"unknown\"}`);\n continue;\n }\n const tool = observation.name;\n if (typeof tool !== \"string\" || !tool) {\n skip(\"no name\");\n continue;\n }\n const at = isoOf(observation.startTime);\n if (!Number.isNaN(sinceMs) && at !== undefined && Date.parse(at) < sinceMs) {\n skip(\"before since\");\n continue;\n }\n if (known && !known.has(tool)) {\n out.unknownTools[tool] = (out.unknownTools[tool] ?? 0) + 1;\n continue;\n }\n const record: ToolCallRecord = { tool, args: isObject(observation.input) ? observation.input : {} };\n if (observation.level === \"ERROR\") record.error = observation.statusMessage || \"ERROR\";\n else record.result = observation.output;\n if (at !== undefined) record.at = at;\n if (opts.session) record.session = opts.session;\n record.source = `trace:${observation.traceId ?? \"?\"}/${observation.id ?? \"?\"}`;\n out.records.push(record);\n }\n return out;\n}\n\n// ---------------------------------------------------------------- the door\n\nexport type IngestRefusal = { index: number | null; tool: string | null; reason: string; pointer?: string };\n\n/** One `[[sources]]` of a mapping in the report. */\nexport type IngestSourceReport = {\n name: string;\n kind: string;\n select: string;\n entity: string;\n records: number;\n items: number;\n rows: Record<string, number>;\n /** Source fields no line of the source reads, with a sample value. */\n unmappedFields: Record<string, string>;\n /** Entity fields the source never sets, per entity. */\n unsetFields: Record<string, string[]>;\n};\n\nexport type IngestToolCallsReport = {\n world: string;\n /** How the rows were produced. */\n via?: \"transform\" | \"map\" | \"operations\" | \"rows\";\n /** `via: \"map\"`: each source's accounting. */\n sources?: IngestSourceReport[];\n /** `via: \"map\"` with `unmatched = \"skip\"`: records no source claimed, by tool name. */\n unmatched?: Record<string, number>;\n /** `via: \"operations\"`: that this was the operation projection, not a mapping. */\n note?: string;\n /** `via: \"transform\"`: what the script wrote to stderr. */\n stderr?: string;\n /** Records given. */\n records: number;\n /** Records that yielded rows. */\n ingested: number;\n /** Records that carried no rows by design, by reason. */\n skipped: Record<string, number>;\n /** What was wrong, per record; with any, nothing was written. */\n refusals: IngestRefusal[];\n /** Rows projected, per entity. */\n rows: Record<string, number>;\n dryRun: boolean;\n redact: RedactMode;\n changed: boolean;\n kind?: string;\n entityCounts?: Record<string, number>;\n /** A slug that was pushed: the batch's final status (`state`, `versionId`, …). */\n batch?: Record<string, unknown>;\n};\n\nexport type IngestToolCallsOptions = WorldsClientOptions & {\n /** Optional, default `\"off\"`: rows land as the tools returned them. */\n redact?: RedactMode;\n /** Project and prove the rows; write and upload nothing. */\n dryRun?: boolean;\n mode?: IngestMode;\n /** Change reason for the version a slug cuts. */\n message?: string;\n};\n\nexport type IngestReport = IngestToolCallsReport;\n\nexport type IngestOptions = IngestToolCallsOptions & {\n /** Your own `transform(records) -> {entity: [rows]}`: a function (run here) or a script path (`.py`, `.ts`, `.mjs`; a subprocess with a time limit and sockets disabled). */\n transform?: string | ((records: unknown[]) => Rows | Promise<Rows>);\n /** An `ingest.toml` mapping: its text, or the parsed table. Exclusive with `transform`. */\n map?: string | IngestMapping;\n /** For a script transform; default 120 000. */\n timeoutMs?: number;\n};\n\ntype Rows = Record<string, Record<string, unknown>[]>;\n\nfunction credentialsOf(options: WorldsClientOptions): { host: string; publicKey: string; secretKey: string } | null {\n const host = (options.host ?? process.env.GATEWAY_HOST ?? \"https://withgateway.ai\").replace(/\\/+$/, \"\");\n const publicKey = options.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;\n const secretKey = options.secretKey ?? process.env.GATEWAY_SECRET_KEY;\n return publicKey && secretKey ? { host, publicKey, secretKey } : null;\n}\n\n/**\n * Records into a world through the route you declare. `world` is a local\n * directory (written in place through the bundled schema runtime) or a\n * platform slug (pulled to a temporary directory, the rows produced and\n * proven there, then pushed through the chunked batch lane as a new version).\n *\n * With `transform` the rows are what your code returns; with `map` (or the\n * world's own `ingest.toml`) what the mapping declares; with neither, each\n * tool-call record's tool resolves to an operation of `connector.toml` and\n * its result goes through that operation's `[ingest]` projection (the report\n * says `via: \"operations\"`). A transform that fails or returns the wrong\n * shape throws. `redact` is optional and defaults to `\"off\"`.\n */\nexport async function ingest(world: string, records: unknown[], options: IngestOptions = {}): Promise<IngestReport> {\n const { ingestLocalToolCalls, importLocalWorldData, checkLocalWorldData } = await import(\"../cli/runtime/data\");\n if (options.transform !== undefined && options.map !== undefined) throw new Error(\"records go through one of transform, map\");\n const redact = options.redact ?? \"off\";\n const mode = options.mode ?? \"append\";\n const dryRun = Boolean(options.dryRun);\n const creds = credentialsOf(options);\n const local = fs.existsSync(world) && fs.statSync(world).isDirectory();\n const map = options.map === undefined ? undefined : options.map;\n\n let rows: Rows | null = null;\n let stderr = \"\";\n if (options.transform !== undefined) {\n const { transformRecords } = await import(\"../cli/platform/worldData/transform\");\n ({ rows, stderr } = await transformRecords(options.transform, records, { timeoutMs: options.timeoutMs }));\n }\n\n if (local) {\n if (rows === null) return reportOf(world, await ingestLocalToolCalls(world, records, { redact, dryRun, mode, map }, creds), redact);\n const landed = dryRun ? await checkLocalWorldData(world, rows, creds, { redact }) : await importLocalWorldData(world, rows, { mode, redact }, creds);\n return transformReport(world, records.length, rows, stderr, { dryRun, redact, changed: !dryRun && landed.changed, kind: landed.kind, entityCounts: landed.entity_counts });\n }\n if (!creds) throw new Error(\"Gateway keys missing: set GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY (or pass publicKey/secretKey).\");\n const { pull } = await import(\"./hub\");\n const slug = world.split(\"@\", 1)[0]!;\n const scratch = fs.mkdtempSync(path.join(os.tmpdir(), \"gateway-ingest-\"));\n try {\n const pulled = await pull(world, path.join(scratch, slug), options);\n // Produced and proven against the pulled contract; the platform's batch\n // lane checks every row again and redacts there, so this pass runs with\n // redaction off and hands the rows on as they were produced.\n let report: IngestReport;\n let projected: Rows;\n if (rows === null) {\n const proven = await ingestLocalToolCalls(pulled.dir, records, { redact: \"off\", dryRun: true, mode, map }, creds);\n report = reportOf(world, proven, redact);\n projected = proven.projected ?? {};\n } else {\n const proven = await checkLocalWorldData(pulled.dir, rows, creds);\n report = transformReport(world, records.length, rows, stderr, { dryRun, redact, changed: false, kind: proven.kind, entityCounts: proven.entity_counts });\n projected = rows;\n }\n report.dryRun = dryRun;\n if (dryRun || report.refusals.length || !Object.keys(projected).length) return report;\n const { pushRows } = await import(\"../cli/platform/worldData/push\");\n const status = await pushRows(creds, slug, projected, { mode, redact, message: options.message });\n report.batch = status;\n report.changed = status.state === \"applied\" || status.state === \"published\";\n if (status.entityCounts) report.entityCounts = status.entityCounts;\n return report;\n } finally {\n fs.rmSync(scratch, { recursive: true, force: true });\n }\n}\n\n/**\n * Tool-call records into a world with neither a transform nor a mapping of\n * your own: the world's `ingest.toml` when it has one, else each record's\n * tool through its operation's `[ingest]` projection (an unknown tool is a\n * refusal naming it and nothing is written). {@link ingest} with the same\n * options.\n */\nexport async function ingestToolCalls(world: string, records: unknown[], options: IngestToolCallsOptions = {}): Promise<IngestToolCallsReport> {\n return ingest(world, records, options);\n}\n\nfunction transformReport(\n world: string,\n records: number,\n rows: Rows,\n stderr: string,\n outcome: { dryRun: boolean; redact: RedactMode; changed: boolean; kind?: string; entityCounts?: Record<string, number> },\n): IngestReport {\n return {\n world,\n via: \"transform\",\n ...(stderr ? { stderr } : {}),\n records,\n ingested: records,\n skipped: {},\n refusals: [],\n rows: Object.fromEntries(Object.entries(rows).map(([entity, listed]) => [entity, listed.length])),\n dryRun: outcome.dryRun,\n redact: outcome.redact,\n changed: outcome.changed,\n ...(outcome.kind ? { kind: outcome.kind } : {}),\n ...(outcome.entityCounts ? { entityCounts: outcome.entityCounts } : {}),\n };\n}\n\nfunction reportOf(\n world: string,\n local: {\n via?: IngestReport[\"via\"];\n sources?: { name: string; kind: string; select: string; entity: string; records: number; items: number; rows: Record<string, number>; unmapped_fields: Record<string, string>; unset_fields: Record<string, string[]> }[];\n unmatched?: Record<string, number>;\n note?: string;\n records: number;\n ingested: number;\n skipped: Record<string, number>;\n refusals: IngestRefusal[];\n rows: Record<string, number>;\n dry_run: boolean;\n changed: boolean;\n kind?: string;\n entity_counts?: Record<string, number>;\n },\n redact: RedactMode,\n): IngestToolCallsReport {\n return {\n world,\n ...(local.via ? { via: local.via } : {}),\n ...(local.sources ? { sources: local.sources.map(({ unmapped_fields, unset_fields, ...rest }) => ({ ...rest, unmappedFields: unmapped_fields, unsetFields: unset_fields })) } : {}),\n ...(local.unmatched ? { unmatched: local.unmatched } : {}),\n ...(local.note ? { note: local.note } : {}),\n records: local.records,\n ingested: local.ingested,\n skipped: local.skipped,\n refusals: local.refusals,\n rows: local.rows,\n dryRun: local.dry_run,\n redact,\n changed: local.changed,\n ...(local.kind ? { kind: local.kind } : {}),\n ...(local.entity_counts ? { entityCounts: local.entity_counts } : {}),\n };\n}\n\n/** The TOOL observations of one session, every trace's, from `GET /api/public/sessions/{id}?includeIO=true`. */\nexport async function sessionToolObservations(sessionId: string, options: WorldsClientOptions = {}): Promise<ObservationLike[]> {\n const session = await apiRequest<{ traces?: { id?: string; observations?: ObservationLike[] }[] }>(\n options,\n \"GET\",\n `/api/public/sessions/${encodeURIComponent(sessionId)}?includeIO=true`,\n );\n const out: ObservationLike[] = [];\n for (const trace of session.traces ?? [])\n for (const observation of trace.observations ?? []) out.push({ traceId: trace.id ?? null, ...observation });\n return out;\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\n\n/**\n * Edit sessions: the version control unit for a world. Every write this\n * credential makes to a world (push, sandbox commit, data import, MCP, the\n * console editor) joins ONE open session per world per credential and lands\n * on that session's private branch; `close` seals the session into a version\n * on `main`, and a session nobody touches for an hour seals itself. Sessions\n * replace product-level proposals/PRs: `rollback` undoes a sealed session\n * (source + data together) as a new, itself-reversible session.\n *\n * One client under both `gateway worlds edit …` and `gateway bench edit …`;\n * the Python twin is `gatewaysdk.benchmark_hub.edit_sessions.WorldEditClient`.\n */\n\n/** Mirrors `WorldEditSessionSchema` (web/features/public-api/types/world-edits.ts). */\nexport type EditSessionSummary = {\n id: string;\n containerId: string;\n /** `apikey:<id>` for CLI/sandbox/MCP, `user:<id>` for the console, `agent:<id>` for the platform agent. */\n actor: string;\n door: string;\n status: \"open\" | \"sealing\" | \"sealed\" | \"conflict\" | \"expired\" | \"discarded\" | string;\n baseVersionId: string | null;\n tipVersionId: string | null;\n sealedVersionId: string | null;\n editCount: number;\n startedAt: string;\n lastEditAt: string;\n expiresAt: string;\n closedAt: string | null;\n closeReason: string | null;\n conflictPaths: string[] | null;\n rollbackOfId: string | null;\n message: string | null;\n};\n\nexport type EditSessionList = {\n slug: string;\n containerId: string;\n /** This credential's open session, or null. */\n current: EditSessionSummary | null;\n sessions: EditSessionSummary[];\n};\n\n/** What close/discard/rollback return. */\nexport type EditSessionResult = { slug: string; session: EditSessionSummary };\n\nexport type EditSessionListQuery = { status?: string; limit?: number };\nexport type EditSessionCloseInput = { sessionId?: string; force?: boolean; message?: string };\nexport type EditSessionRollbackInput = { sessionId: string; force?: boolean; message?: string };\n\nconst WORLDS = \"/api/public/worlds\";\nexport class WorldEditClient {\n constructor(private readonly options: WorldsClientOptions = {}) {}\n\n /** The credential's current session and the world's newest-first sessions. */\n list(slug: string, query: EditSessionListQuery = {}): Promise<EditSessionList> {\n const qs = new URLSearchParams();\n if (query.status) qs.set(\"status\", query.status);\n if (query.limit !== undefined) qs.set(\"limit\", String(query.limit));\n const suffix = qs.size ? `?${qs.toString()}` : \"\";\n return apiRequest(this.options, \"GET\", `${WORLDS}/${encodeURIComponent(slug)}/edits${suffix}`);\n }\n\n /** Seal a session into a version on main (the credential's current one when `sessionId` is omitted). */\n close(slug: string, input: EditSessionCloseInput = {}): Promise<EditSessionResult> {\n return apiRequest(this.options, \"POST\", `${WORLDS}/${encodeURIComponent(slug)}/edits/close`, input);\n }\n\n /** Drop the session's private branch without making a version. */\n discard(slug: string, input: { sessionId?: string } = {}): Promise<EditSessionResult> {\n return apiRequest(this.options, \"POST\", `${WORLDS}/${encodeURIComponent(slug)}/edits/discard`, input);\n }\n\n /** Undo a sealed session (source and data) as a new sealed session. */\n rollback(slug: string, input: EditSessionRollbackInput): Promise<EditSessionResult> {\n return apiRequest(this.options, \"POST\", `${WORLDS}/${encodeURIComponent(slug)}/edits/rollback`, input);\n }\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\n\n/**\n * The hosted one-task dry run: `POST /api/public/environments/{id}/dry-run`\n * and the run-status read that settles it. The runner runs ONE named task of a\n * harbor tree through harbor's `oracle` (the task's own `solution/solve.sh`)\n * with the real image rule (`[environment] docker_image` → pull, never build;\n * else build the Dockerfile). No model, no model key. The run is marked\n * `kind: \"dry-run\"` and never counts as a benchmark result.\n *\n * The caps are the server's: one task, one example, one rollout, the oracle.\n * The body carries the task name and, optionally, a pinned versionId; a body\n * that tries to widen the run (models, task lists, rollouts) is a 400.\n */\n\nexport const DRY_RUN_KIND = \"dry-run\" as const;\nexport const DRY_RUN_AGENT = \"oracle\" as const;\n\nexport type HostedDryRunDispatch = {\n runId: string;\n versionId: string;\n versionLabel: string;\n containerSlug: string;\n task: string;\n kind: typeof DRY_RUN_KIND;\n agent: typeof DRY_RUN_AGENT;\n evidence: false;\n where: \"hosted\";\n};\n\n/** The image decision the runner took — the SAME rule a real run applies. */\nexport type DryRunImageDecision = {\n source: \"prebuilt\" | \"dockerfile\";\n ref: string | null;\n};\n\n/** What the runner reported about the one trial (the Python twin is `benchmark_hub.dry_run.DryRunSettlement`). */\nexport type DryRunSettlement = {\n task: string;\n agent: typeof DRY_RUN_AGENT;\n image: DryRunImageDecision | null;\n command: string | null;\n reward: number | null;\n rewardFile: { name: string; content: unknown } | null;\n exitCode: number | null;\n errorTail: string | null;\n};\n\nexport type HostedDryRunStatus = {\n kind: typeof DRY_RUN_KIND;\n evidence: false;\n where: \"hosted\";\n agent: typeof DRY_RUN_AGENT;\n task: string | null;\n evaluationId: string | null;\n url: string | null;\n settlement: DryRunSettlement | null;\n};\n\n/** The run-status answer (`GET …/environments/runs/{runId}`) as a dry run reads it. */\nexport type HostedDryRunVerdict = {\n status: string;\n settled: boolean;\n progress: {\n harvested: number;\n planned: number | null;\n startedAt: string | null;\n completedAt: string | null;\n elapsedSeconds: number | null;\n } | null;\n dryRun: HostedDryRunStatus | null;\n};\n\n/** The server blocks a status read for at most this long; longer waits poll. */\nexport const STATUS_WAIT_CAP_SECONDS = 50;\n\nexport type SettleOptions = {\n /** Give up (return the last verdict, unsettled) after this long. */\n timeoutSeconds: number;\n /** Called once per unsettled poll with the verdict so far. */\n onProgress?: (verdict: HostedDryRunVerdict) => void;\n /** Injected for tests: the clock and the pause between empty polls. */\n now?: () => number;\n sleep?: (ms: number) => Promise<void>;\n};\n\nconst cid = (id: string) =>\n `/api/public/environments/${encodeURIComponent(id)}`;\n\n/** The client a `gateway benchmarks dry-run --hosted` is built on. */\nexport class HostedDryRunClient {\n constructor(private readonly options: WorldsClientOptions = {}) {}\n\n /** Dispatch ONE oracle job for `task` on `containerId` (a container id, not a slug); pins `versionId` when given. */\n dispatch(target: {\n containerId: string;\n task: string;\n versionId?: string;\n }): Promise<HostedDryRunDispatch> {\n return apiRequest(\n this.options,\n \"POST\",\n `${cid(target.containerId)}/dry-run`,\n {\n task: target.task,\n ...(target.versionId ? { versionId: target.versionId } : {}),\n },\n );\n }\n\n /** One status read, blocking server-side for up to `waitSeconds` (capped). */\n status(runId: string, waitSeconds = 0): Promise<HostedDryRunVerdict> {\n const wait = Math.max(\n 0,\n Math.min(Math.floor(waitSeconds), STATUS_WAIT_CAP_SECONDS),\n );\n const suffix = wait ? `?waitSeconds=${wait}` : \"\";\n return apiRequest(\n this.options,\n \"GET\",\n `/api/public/environments/runs/${encodeURIComponent(runId)}${suffix}`,\n );\n }\n\n /** Poll until the run settles or `timeoutSeconds` pass; the last verdict either way. */\n async settle(\n runId: string,\n opts: SettleOptions,\n ): Promise<HostedDryRunVerdict> {\n const now = opts.now ?? Date.now;\n const sleep =\n opts.sleep ??\n ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));\n const deadline = now() + opts.timeoutSeconds * 1000;\n for (;;) {\n const budget = Math.floor(\n Math.min(45, Math.max(0, (deadline - now()) / 1000)),\n );\n const asked = now();\n const verdict = await this.status(runId, budget);\n if (verdict.settled || now() >= deadline) return verdict;\n opts.onProgress?.(verdict);\n // A server that answered at once (no long poll behind it) must not be hammered.\n if (now() - asked < 1000) await sleep(1000);\n }\n }\n}\n\n/** The one exit-code decision, shared by the CLI twins: 0 only when the oracle scored exactly 1.0. */\nexport class DryRunOutcome {\n constructor(readonly verdict: HostedDryRunVerdict) {}\n\n get settlement(): DryRunSettlement | null {\n return this.verdict.dryRun?.settlement ?? null;\n }\n\n /** Why the dry run did not pass, or null when it did. */\n reason(): string | null {\n if (!this.verdict.settled) return `still running after the wait`;\n const settlement = this.settlement;\n if (!settlement)\n return `the runner filed no settlement (${this.verdict.status})`;\n const lastErrorLine =\n settlement.errorTail?.trim().split(\"\\n\").at(-1) || null;\n // A non-zero harbor exit is a failure whatever the reward file says: a\n // 1.0 written before the harness died is not a pass.\n if (settlement.exitCode !== null && settlement.exitCode !== 0)\n return `the runner failed (exit ${settlement.exitCode}): ${lastErrorLine ?? \"harbor exited non-zero\"}`;\n if (settlement.reward === null && lastErrorLine)\n return `the runner failed (exit ?): ${lastErrorLine}`;\n if (settlement.reward === null)\n return \"ungraded: the grader ran but wrote no reward\";\n if (settlement.reward !== 1)\n return `the reference solution scored ${settlement.reward}, not 1.0`;\n return null;\n }\n\n passed(): boolean {\n return this.reason() === null;\n }\n}\n","\nimport type { WorldTaskIdRef } from \"./session\";\nimport { PlatformTransport, type PlatformMethod } from \"./transport\";\n\nexport type WorldsClientOptions = {\n host?: string;\n publicKey?: string;\n secretKey?: string;\n};\n\nexport type ResolvedWorldVersion = {\n versionId: string;\n semanticVersion: string | null;\n contentHash: string;\n state?: string;\n};\n\nexport type WorldTaskInfo = {\n name: string;\n variant: string | null;\n};\n\nexport type DispatchedRun = {\n model: string;\n runId: string;\n ok: boolean;\n error?: string;\n};\n\nfunction resolveEnv(options: WorldsClientOptions) {\n const host =\n options.host ?? process.env.GATEWAY_HOST ?? \"https://withgateway.ai\";\n const publicKey = options.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;\n const secretKey = options.secretKey ?? process.env.GATEWAY_SECRET_KEY;\n if (!publicKey || !secretKey) {\n throw new Error(\n \"Gateway keys missing: set GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY \" +\n \"(or pass publicKey/secretKey).\",\n );\n }\n return { host: host.replace(/\\/+$/, \"\"), publicKey, secretKey };\n}\n\n/** A platform answer outside 2xx, its status kept so a caller can act on one\n * code (a 409 on a name already taken) instead of parsing the message. A JSON\n * body renders as `<message> (<code>)` — the stable public `code`, never the\n * server's error class name. */\nexport class ApiError extends Error {\n public readonly code: string | null;\n\n constructor(\n public readonly status: number,\n method: string,\n path: string,\n public readonly text: string,\n ) {\n const parsed = parseErrorBody(text);\n super(`${method} ${path} -> ${status}: ${parsed.detail}`);\n this.name = \"ApiError\";\n this.code = parsed.code;\n }\n}\n\n/** What a client shows for one non-2xx body and the stable code it carries.\n * Python twin: `gatewaysdk.api_errors.error_detail`. */\nexport function parseErrorBody(\n text: string,\n limit = 600,\n): { detail: string; code: string | null } {\n const raw = { detail: text.slice(0, limit), code: null };\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return raw;\n }\n if (parsed === null || typeof parsed !== \"object\") return raw;\n const { message, code } = parsed as { message?: unknown; code?: unknown };\n const stableCode = typeof code === \"string\" ? code : null;\n if (typeof message !== \"string\") return { ...raw, code: stableCode };\n if (stableCode === null)\n return { detail: message.slice(0, limit), code: null };\n return {\n detail: `${message} (${stableCode})`.slice(0, limit),\n code: stableCode,\n };\n}\n\n/** Authenticated JSON request against the platform API — the primitive the\n * worlds helpers and the TS CLI share. `init.timeoutMs` is the request's own\n * budget when it legitimately outlasts `GATEWAY_TIMEOUT_MS`. */\nexport async function apiRequest<T>(\n options: WorldsClientOptions,\n method: PlatformMethod,\n path: string,\n body?: unknown,\n init: { timeoutMs?: number } = {},\n): Promise<T> {\n const reply = await new PlatformTransport(resolveEnv(options)).send(method, path, body, init);\n if (!reply.ok) throw new ApiError(reply.status, method, path, reply.text);\n return JSON.parse(reply.text) as T;\n}\n\n/** Set (or rotate) one environment secret — write-only: no API returns it. */\nexport async function setEnvSecret(\n slug: string,\n key: string,\n value: string,\n options: WorldsClientOptions = {},\n): Promise<{ key: string; created: boolean }> {\n return apiRequest(\n options,\n \"PUT\",\n \"/api/public/benchmark-containers/secrets\",\n {\n slug,\n key,\n value,\n },\n );\n}\n\n/** Keys and rotation timestamps only — never values. */\nexport async function listEnvSecretKeys(\n slug: string,\n options: WorldsClientOptions = {},\n): Promise<{ key: string; updatedAt: string }[]> {\n const res = await apiRequest<{\n secrets: { key: string; updatedAt: string }[];\n }>(\n options,\n \"GET\",\n `/api/public/benchmark-containers/secrets?slug=${encodeURIComponent(slug)}`,\n );\n return res.secrets;\n}\n\nexport async function deleteEnvSecret(\n slug: string,\n key: string,\n options: WorldsClientOptions = {},\n): Promise<void> {\n await apiRequest(\n options,\n \"DELETE\",\n \"/api/public/benchmark-containers/secrets\",\n {\n slug,\n key,\n },\n );\n}\n\nexport type RunConfigSummary = {\n id: string;\n name: string;\n runType: string;\n createdAt: string;\n models: string[];\n parallelism: number;\n autoRunOnPush: boolean;\n agent: string | null;\n};\n\n/** Run configs in the project. CI resolves by NAME and dispatches by id. */\nexport async function listRunConfigs(\n options: WorldsClientOptions = {},\n): Promise<RunConfigSummary[]> {\n const res = await apiRequest<{ runConfigs: RunConfigSummary[] }>(\n options,\n \"GET\",\n \"/api/public/benchmark-containers/run-configs\",\n );\n return res.runConfigs;\n}\n\n/** What a run config selects for the runner to work through. A config runs\n * EITHER the bundle's own scenarios (`taskNames`, `taskSetDatasetId`) OR the\n * project's stored tasks (`worldTasks`, api worlds only) — never both. A\n * stored task ref without `version` runs the task's current version at\n * dispatch time; with it, that version forever. */\nexport type RunConfigInput = {\n id?: string;\n name: string;\n models: string[];\n parallelism?: number;\n numExamples?: number;\n rolloutsPerExample?: number;\n timeoutMinutes?: number;\n agent?: string;\n taskSetDatasetId?: string | null;\n taskNames?: string[];\n worldTasks?: WorldTaskIdRef[];\n autoRunOnPush?: boolean;\n};\n\n/** Create a run config, or update the one named by `id`. */\nexport async function upsertRunConfig(\n input: RunConfigInput,\n options: WorldsClientOptions = {},\n): Promise<RunConfigSummary> {\n return apiRequest<RunConfigSummary>(\n options,\n \"POST\",\n \"/api/public/benchmark-containers/run-configs\",\n input,\n );\n}\n\n/** `id[@version]` items (comma-separated or an array) → stored task refs;\n * the spelling `bench run-configs create --world-tasks` takes. */\nexport function parseWorldTaskRefs(spec: string | string[]): WorldTaskIdRef[] {\n const items = (Array.isArray(spec) ? spec : spec.split(\",\"))\n .map((s) => s.trim())\n .filter(Boolean);\n return items.map((item) => {\n const at = item.lastIndexOf(\"@\");\n if (at < 0) return { id: item };\n const id = item.slice(0, at);\n const version = Number(item.slice(at + 1));\n if (!id || !Number.isInteger(version) || version < 1)\n throw new Error(\n `stored task ref '${item}' is not <id> or <id>@<version> (version a positive integer)`,\n );\n return { id, version };\n });\n}\n\nexport type RunReport = {\n id: string;\n status: string;\n terminal: boolean;\n score: number | null;\n summary: string | null;\n model: string | null;\n versionLabel: string | null;\n parallelism: number;\n shardsCompleted: number | null;\n /** The run's page on the platform — what a PR comment should link. */\n url: string | null;\n evaluations: {\n id: string;\n status: string;\n avgReward: number | null;\n url: string | null;\n }[];\n samples: {\n task: string | null;\n reward: number | null;\n rewards: Record<string, unknown>;\n sessionId: string | null;\n }[];\n};\n\n/** The read half of dispatch: status, score, per-shard evaluations, and\n * per-task rewards — everything a CI gate needs. */\nexport async function getRun(\n runId: string,\n options: WorldsClientOptions = {},\n): Promise<RunReport> {\n return apiRequest(\n options,\n \"GET\",\n `/api/public/benchmark-containers/runs/${encodeURIComponent(runId)}`,\n );\n}\n\n/** One run as `bench runs list` prints it (GET /benchmark-containers/runs):\n * the gate's view — no logs, samples or links; `getRun` has those. */\nexport type RunSummary = {\n id: string;\n status: string;\n terminal: boolean;\n score: number | null;\n summary: string | null;\n createdAt: string;\n completedAt: string | null;\n model: string | null;\n versionId: string | null;\n versionLabel: string | null;\n runConfigId: string | null;\n runConfigName: string | null;\n parallelism: number;\n exitCode: number | null;\n};\n\nexport type ListRunsFilter = {\n /** Only runs of this world/benchmark; a slug the project lacks lists nothing. */\n slug?: string;\n /** Case-insensitive run status (RUNNING, completed, …). */\n status?: string;\n limit?: number;\n};\n\n/** The project's runs, newest first. */\nexport async function listRuns(\n filter: ListRunsFilter = {},\n options: WorldsClientOptions = {},\n): Promise<RunSummary[]> {\n const params = new URLSearchParams();\n if (filter.slug) params.set(\"slug\", filter.slug);\n if (filter.status) params.set(\"status\", filter.status);\n if (filter.limit !== undefined) params.set(\"limit\", String(filter.limit));\n const qs = params.toString();\n const res = await apiRequest<{ runs: RunSummary[] }>(\n options,\n \"GET\",\n `/api/public/benchmark-containers/runs${qs ? `?${qs}` : \"\"}`,\n );\n return res.runs;\n}\n\n/** Poll a run to terminal (default every 20s, up to `timeoutMinutes`). */\nexport async function waitForRun(\n runId: string,\n opts: {\n timeoutMinutes?: number;\n intervalSeconds?: number;\n onTick?: (run: RunReport) => void;\n options?: WorldsClientOptions;\n } = {},\n): Promise<RunReport> {\n const deadline = Date.now() + (opts.timeoutMinutes ?? 45) * 60_000;\n for (;;) {\n const run = await getRun(runId, opts.options ?? {});\n if (run.terminal) return run;\n if (Date.now() > deadline)\n throw new Error(\n `Run ${runId} still ${run.status} after the wait timeout.`,\n );\n opts.onTick?.(run);\n await new Promise((resolve) =>\n setTimeout(resolve, (opts.intervalSeconds ?? 20) * 1000),\n );\n }\n}\n\nexport type RunProvenance = {\n branch?: string;\n commit?: string;\n repoUrl?: string;\n actor?: { id?: string; name?: string; imageUrl?: string; kind?: string };\n};\n\n/**\n * Where a dispatch comes from, DETECTED rather than configured: the CI\n * checkout's branch/commit/actor under GitHub Actions, else the developer's\n * own git checkout. A run nobody can trace to a branch is a score with no\n * code attached, so every dispatch carries this unless overridden.\n */\nexport function detectProvenance(): RunProvenance {\n const env =\n (globalThis as { process?: { env?: Record<string, string | undefined> } })\n .process?.env ?? {};\n const out: RunProvenance = {};\n const ref = env.GITHUB_HEAD_REF || env.GITHUB_REF_NAME;\n if (ref) out.branch = ref;\n if (env.GITHUB_SHA) out.commit = env.GITHUB_SHA;\n const server = env.GITHUB_SERVER_URL ?? \"https://github.com\";\n if (env.GITHUB_REPOSITORY) out.repoUrl = `${server}/${env.GITHUB_REPOSITORY}`;\n if (env.GITHUB_ACTOR) {\n out.actor = {\n kind: \"ci\",\n id: env.GITHUB_ACTOR,\n name: env.GITHUB_ACTOR,\n // GitHub serves every account's avatar at /<login>.png.\n imageUrl: `${server}/${env.GITHUB_ACTOR}.png`,\n };\n }\n if (!out.branch || !out.commit) {\n try {\n const { execFileSync } =\n require(\"node:child_process\") as typeof import(\"node:child_process\");\n const git = (args: string[]) =>\n execFileSync(\"git\", args, {\n encoding: \"utf-8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n })\n .toString()\n .trim();\n out.branch = out.branch ?? git([\"rev-parse\", \"--abbrev-ref\", \"HEAD\"]);\n out.commit = out.commit ?? git([\"rev-parse\", \"HEAD\"]);\n if (!out.repoUrl) {\n const remote = git([\"config\", \"--get\", \"remote.origin.url\"]);\n if (remote) out.repoUrl = remote.replace(/\\.git$/, \"\");\n }\n if (!out.actor) {\n const name = git([\"config\", \"--get\", \"user.name\"]);\n if (name) out.actor = { kind: \"user\", name };\n }\n } catch {\n // No git here — dispatch without provenance rather than failing.\n }\n }\n return out;\n}\n\n/** One scenario of a world, as data. */\nexport class WorldTask {\n constructor(\n readonly world: WorldSet,\n readonly name: string,\n readonly variant: string | null,\n ) {}\n}\n\n/**\n * THE world, from a TS process: pinned identity + its tasks + hosted runs.\n *\n * const world = await openWorld(\"google-drive-sim@main\");\n * console.log(world.version.semanticVersion, world.tasks.length);\n * const runs = await world.dispatch(runConfigId);\n */\nexport class WorldSet {\n constructor(\n readonly slugRef: string,\n readonly slug: string,\n readonly ref: string | null,\n readonly version: ResolvedWorldVersion,\n public tasks: WorldTask[],\n private readonly options: WorldsClientOptions,\n ) {}\n\n task(variant: string): WorldTask {\n const hit = this.tasks.find(\n (t) => t.variant === variant || t.name.includes(variant),\n );\n if (!hit) {\n const known = this.tasks.map((t) => t.variant ?? t.name).join(\", \");\n throw new Error(`no task matches ${variant}; have: ${known}`);\n }\n return hit;\n }\n\n /**\n * Open a LIVE session against one of this world's tasks — a bundled task's\n * name or an inline `WorldTaskSpec`: the platform boots (or reuses) a warm\n * container, and your agent calls its tools through the platform. See\n * worlds/session.ts.\n */\n async open(\n task: import(\"./session\").WorldTaskRef,\n opts: {\n reuseWarm?: boolean;\n surfaces?: import(\"./browser\").WorldSurfaceKind[];\n browserTier?: import(\"./browser\").BrowserTier;\n } = {},\n ): Promise<import(\"./session\").WorldSession> {\n const { openSession } = await import(\"./session\");\n return openSession(this.slug, {\n task,\n versionId: this.version.versionId,\n reuseWarm: opts.reuseWarm,\n surfaces: opts.surfaces,\n browserTier: opts.browserTier,\n options: this.options,\n });\n }\n\n /**\n * Start a HOSTED run of a run config against this world — the platform\n * executes the (Python) world in parallel containers per the config's\n * `parallelism` and files one graded run per model. Returns those runs.\n */\n async dispatch(\n runConfigId: string,\n opts: {\n containerId?: string;\n versionId?: string;\n /** Override the auto-detected branch/commit/actor. */\n provenance?: RunProvenance;\n } = {},\n ): Promise<{ versionLabel: string; runs: DispatchedRun[] }> {\n const provenance = opts.provenance ?? detectProvenance();\n return apiRequest(\n this.options,\n \"POST\",\n \"/api/public/benchmark-containers/run-configs/dispatch\",\n {\n runConfigId,\n ...(opts.containerId ? { containerId: opts.containerId } : {}),\n versionId: opts.versionId ?? this.version.versionId,\n ...provenance,\n },\n );\n }\n}\n\n/**\n * Resolve `slug` / `slug@branch|tag|semver|hash` to its pinned version and\n * task list. The task list comes from the version's file manifest\n * (`tasks/<name>/task.toml`), so it needs no bundle download.\n */\nexport async function openWorld(\n slugRef: string,\n options: WorldsClientOptions = {},\n): Promise<WorldSet> {\n const at = slugRef.indexOf(\"@\");\n const slug = at === -1 ? slugRef : slugRef.slice(0, at);\n const ref = at === -1 ? null : slugRef.slice(at + 1);\n return resolveWorld(slugRef, slug, ref, ref ? { ref } : {}, options);\n}\n\n/**\n * Resolve `slug` at one pinned READY `versionId` — the task list is THAT\n * version's, never the branch tip's. `worlds run|ci --version-id` come\n * through here; a version of another container, a draft or an unknown id\n * is a 404 from the platform, not a silent fall-through to head.\n */\nexport async function openWorldVersion(\n slug: string,\n versionId: string,\n options: WorldsClientOptions = {},\n): Promise<WorldSet> {\n return resolveWorld(\n `${slug}@${versionId}`,\n slug,\n null,\n { versionId },\n options,\n );\n}\n\nasync function resolveWorld(\n slugRef: string,\n slug: string,\n ref: string | null,\n pin: { ref?: string; versionId?: string },\n options: WorldsClientOptions,\n): Promise<WorldSet> {\n const version = await apiRequest<\n ResolvedWorldVersion & { taskNames?: string[] }\n >(options, \"POST\", \"/api/public/benchmark-containers/resolve-version\", {\n slug,\n ...pin,\n });\n\n const world = new WorldSet(\n slugRef,\n slug,\n ref,\n {\n versionId: version.versionId,\n semanticVersion: version.semanticVersion ?? null,\n contentHash: version.contentHash,\n state: version.state,\n },\n [],\n options,\n );\n for (const name of version.taskNames ?? []) {\n const variant = /^[a-z0-9]+-([a-z0-9]+)-/.exec(name)?.[1] ?? null;\n world.tasks.push(new WorldTask(world, name, variant));\n }\n return world;\n}\n\n// The session surface completes the worlds module, so `@withgateway/sdk/worlds`\n// carries both halves: running a world locally, and driving one the platform\n// hosts. (session.ts imports apiRequest from here; the cycle is function-level\n// only, and the build below is what proves it resolves.)\nexport * from \"./transport\";\nexport * from \"./session\";\nexport * from \"./sessionList\";\nexport * from \"./sessionContract\";\nexport * from \"./taskRef\";\n\n// Stored tasks: the task spec as a named, versioned project resource that\n// `openSession(world, { task: { id } })` opens on.\nexport * from \"./tasks\";\n\n// Tasks that need several worlds: `openTask` brings every world a task\n// names up together (or not at all) and hands back the sessions by alias.\nexport * from \"./taskSessions\";\n\n// Run a task end to end: open every world, hand the agent a `TaskRun`,\n// grade with its report, file one rollout and close — `runTask`, the\n// engine behind `gateway worlds task run`.\nexport * from \"./taskRun\";\n\n// Run every stored task of a scenario set with one model as ONE set run —\n// `runSet`, the engine behind `gateway worlds task run-set` — and the checkout\n// it records (branch, commit, remote without credentials, CI's pull request).\nexport * from \"./setRun\";\nexport * from \"./checkoutProvenance\";\n\n// The evaluations client `runTask` files a rollout through — create, push\n// samples, finalize. Exposed in case a caller wants to file its own.\nexport * from \"./evals\";\n\n// The computer-use half: surfaces, a Playwright browser on the world's UI,\n// and browser actions as model tools.\nexport * from \"./browser\";\nexport * from \"./browserReconnect\";\n\n// The hub half: push, pull, propose and the content-hash primitives the CLI\n// runs on. These were reachable only from inside the package, so a consumer\n// could drive a world but never publish one.\nexport * from \"./hub\";\n\n// PR validation: push-dispatch-wait-gate as one composed call, for CI.\nexport * from \"./validate\";\n\n// Discovery: what a world holds and how each field is stored (`describeWorld`),\n// and the stored forms of a plaintext under the world's [redact] table\n// (`storedForms`, `redactionOf`) — the same digest rule as the Python runtime.\nexport * from \"./describe\";\nexport * from \"./redaction\";\nexport * from \"./transforms\";\n\n// Lookup: the rows of one entity matching a predicate (`queryRows`), by\n// stored value or — with `resolve` — by plaintext the runtime maps through\n// the same [redact] table.\nexport * from \"./query\";\n\n// Migration: a stored world into a schema world (`migrateWorld`), dry run by\n// default; the project's connector worlds at once (`migrateProjectWorlds`).\nexport * from \"./migrate\";\n\n// Tool calls into rows: the record contract, `captureToolCalls` (record an\n// agent's real calls), `toolCallsFromObservations` (from a trace) and\n// `ingestToolCalls` (into a directory or a slug). Redaction optional, off by default.\nexport * from \"./ingest\";\n\n// The CLI sandbox: open a READY version in a server-side workspace, edit and\n// run there, check and commit into the version service without the source\n// ever landing on this disk (`gateway worlds|bench sandbox …`).\nexport * from \"./sandbox\";\nexport * from \"./editSessions\";\n\n// The hosted one-task dry run: ONE oracle job on the runner with the real\n// image rule, its settlement (image decision, reward file, exit code) and the\n// one pass/fail decision the CLI twins share (`gateway benchmarks dry-run --hosted`).\nexport * from \"./dryRun\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAYO,SAAS,kBAAkB,MAAyB,QAAQ,KAAa;AAC9E,QAAM,MAAM,IAAI,oBAAoB;AACpC,MAAI,QAAQ,UAAa,QAAQ,GAAI,QAAO;AAC5C,QAAM,QAAQ,OAAO,GAAG;AACxB,MAAI,OAAO,UAAU,KAAK,KAAK,QAAQ,EAAG,QAAO;AACjD,QAAM,IAAI,MAAM,GAAG,oBAAoB,2DAA2D,GAAG,KAAK;AAC5G;AAlBA,IAAa,sBAGA,6BAiBP,YACA,OAEA,QAaA,eAGO,gBA6BA,kBAaA;AAjFb;AAAA;AAAA;AAAO,IAAM,uBAAuB;AAG7B,IAAM,8BAA8B;AAiB3C,IAAM,aAAa;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IAAI,CAAC;AAAA,YAC5D,WAAW,KAAK,aAAa,KAAK,QAAQ;AAAA,YAC1C,GAAG;AAAA,UACL;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA;AAAA;","names":["text","path","text","resolve","sleep","text","state","openWorld","openWorldVersion","api","path","pollMs","state","path","text","session_exports","AsyncLocalStorage","resolve","init_session","isSpanContextValid","trace","path","text","text","scores","init_session","isGatewayConfigured","init","fs","path","state","createHash","fs","path","init","text","fs","path","createHash","fs","path","pad","text","resolve","state","path","text","hex","createHash","createHash","text","field","fs","path","init","ApiError","text","fs","path","resolve","text","fs","path","payload","detail","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","sleep","resolve","text","path","init","resolve","execFileSync","openSession"]}
|