@withgateway/sdk 0.2.2 → 0.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +129 -22
- package/dist/cli.js.map +1 -1
- package/dist/cli.mjs +130 -23
- package/dist/cli.mjs.map +1 -1
- package/dist/files/index.js +9 -5
- package/dist/files/index.js.map +1 -1
- package/dist/files/index.mjs +9 -5
- package/dist/files/index.mjs.map +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +14 -8
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +13 -8
- package/dist/index.mjs.map +1 -1
- package/dist/traces/index.js +9 -5
- package/dist/traces/index.js.map +1 -1
- package/dist/traces/index.mjs +9 -5
- package/dist/traces/index.mjs.map +1 -1
- package/dist/tracing/index.js +1 -1
- package/dist/tracing/index.js.map +1 -1
- package/dist/tracing/index.mjs +1 -1
- package/dist/tracing/index.mjs.map +1 -1
- package/dist/worlds/index.d.mts +7 -1
- package/dist/worlds/index.d.ts +7 -1
- package/dist/worlds/index.js +12 -7
- package/dist/worlds/index.js.map +1 -1
- package/dist/worlds/index.mjs +12 -7
- package/dist/worlds/index.mjs.map +1 -1
- package/package.json +1 -1
- package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/SKILL.md +5 -5
- package/skills/worlds-getting-started/SKILL.md +5 -5
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/worlds/browser.ts","../src/worlds/session.ts","../src/worlds/tasks.ts","../src/worlds/hub.ts","../src/worlds/validate.ts","../src/worlds/describe.ts","../src/cli/platform/worldData/json.ts","../src/worlds/transforms.ts","../src/worlds/redaction.ts","../src/worlds/query.ts","../src/worlds/migrate.ts","../src/cli/router.ts","../src/cli/config.ts","../src/cli/runtime/local.ts","../src/cli/runtime/client.ts","../src/cli/runtime/data.ts","../src/cli/platform/worldData/transform.ts","../src/cli/platform/worldData/batches.ts","../src/cli/platform/worldData/chunker.ts","../src/cli/platform/worldData/push.ts","../src/worlds/ingest.ts","../src/worlds/index.ts","../package.json","../src/index.ts","../src/experiments/assignment.ts","../src/experiments/context.ts","../src/experiments/exposure-logger.ts","../src/experiments/client.ts","../src/experiments/otel.ts","../src/experiments/singleton.ts","../src/context/index.ts","../src/memory/index.ts","../src/personas/index.ts","../src/sessions/index.ts","../src/replay/index.ts","../src/security/index.ts","../src/users/index.ts","../src/scores/index.ts","../src/files/index.ts","../src/traces/index.ts","../src/build/index.ts","../src/tracing/identity.ts","../src/tracing/index.ts","../src/tracing/init.ts","../src/tracing/observe.ts","../src/tracing/instrument.ts","../src/tracing/claude.ts"],"sourcesContent":["import { schemaFromSignature, type WorldToolkit } from \"./session\";\n\n/**\n * A BROWSER ON A WORLD'S UI — the computer-use half of a live session.\n *\n * A session answers on SURFACES. `tools` is always there (the world's own\n * operations over the rendezvous). An api-type world may also answer on\n * `api` (the service itself), `ui` (its dashboard, over the same state) and\n * `browser` — a headless Chromium the platform runs NEXT TO that UI, which\n * an agent drives through Playwright. This file is the TS client for the\n * last two, call for call with `gatewaysdk/world_browser.py`.\n *\n * const s = await openSession(\"payments-like\", \"refund-dispute\", {\n * surfaces: [\"ui\", \"browser\"],\n * });\n * await s.ready();\n * const b = await s.browser(); // hosted, next to the world\n * await b.goto(); // the UI's entry page\n * await b.click(\"text=Refund\");\n * const tools = computerUseToolkit(b); // the same actions as model tools\n * await b.close();\n *\n * Playwright is an OPTIONAL peer: nothing here imports it until a browser is\n * opened, so sessions that never touch a UI never load it.\n *\n * MODES. `hosted` connects to the session's own browser (a Playwright server\n * the pod exposes over an authenticated websocket). `local` launches Chromium\n * on this machine and points it at the UI — a laptop against a hosted twin,\n * or a test. `auto` prefers hosted. Asking for a mode the session cannot\n * serve throws `WorldSurfaceUnavailable`; there is no silent fallback to a\n * browser other than the one the episode is judged on.\n *\n * OBSERVABILITY. Every action a `WorldBrowser` takes (goto, click, type,\n * press, scroll, back) is reported to the platform as one event — what was\n * done, whether it worked, where the page ended up, and a JPEG of the screen\n * after — through a `BrowserActionRecorder`. Reporting is fire-and-forget\n * and never fails the action; the platform renders it as the session's\n * browser timeline. Text typed into secret-looking fields is redacted before\n * it leaves the process.\n */\n\nexport const SURFACE_KINDS = [\"tools\", \"api\", \"ui\", \"browser\"] as const;\nexport type WorldSurfaceKind = (typeof SURFACE_KINDS)[number];\n\nexport const DEFAULT_VIEWPORT = { width: 1280, height: 800 };\nconst SETTLE_TIMEOUT_MS = 5_000;\nconst SETTLE_QUIET_MS = 150;\nconst SETTLE_POLL_MS = 25;\n\nexport const EVENT_BATCH_SIZE = 10;\nexport const EVENT_FLUSH_INTERVAL_MS = 1_000;\nexport const EVENT_MAX_RETRIES = 3;\nconst EVENT_SCREENSHOT_QUALITY = 60;\nconst EVENT_MAX_STRING = 500;\n\nconst SECRET_KEY =\n /pass(word|wd)?|secret|token|api[-_]?key|authorization|cookie|(^|[-_ #.\\[\"'=])(otp|pin|cvv|ssn)([-_ \\]\"']|$)/i;\nconst SECRET_VALUE =\n /^((sk|pk|ghp|xox[abp])[-_][-_A-Za-z0-9]{8,}|AKIA[0-9A-Z]{12,}|Bearer [-_.A-Za-z0-9]{8,})/;\n\n/** The `surfaces` block of a session descriptor, as the platform sends it. */\nexport type SessionSurfaces = {\n tools: { kind: \"rendezvous\" };\n api?: {\n url: string;\n /** Per-session credential of a World Host session: send it as\n * `Authorization: Bearer <token>` (the header only; a token in the URL is\n * refused). Absent when the world\n * itself answers with its declared auth (a pod or a customer-hosted twin). */\n token?: string;\n };\n ui?: {\n url: string;\n entry: string;\n /** Same-origin prefix the UI proxies to the world API, e.g. `/__world-api`;\n * null when the UI only reaches the API server-side. */\n apiPath?: string | null;\n /** Per-session credential of a World Host UI. A browser navigation cannot\n * carry a header, so the first page load presents it once as `?token=`\n * and the host answers with an HttpOnly cookie. Absent for pod UIs. */\n token?: string;\n };\n browser?: {\n wsUrl: string;\n /** `cdp`: the platform's Chromium relay (any number of agents share one\n * browser, each in its own context). `playwright`: a `run-server` endpoint. */\n protocol: \"cdp\" | \"playwright\";\n viewport: { width: number; height: number };\n };\n};\n\nexport class WorldSurfaceUnavailable extends Error {\n constructor(\n readonly surface: WorldSurfaceKind,\n reason: string,\n ) {\n super(`World surface '${surface}' is unavailable: ${reason}`);\n }\n}\n\nexport function surfaceKinds(s: SessionSurfaces): WorldSurfaceKind[] {\n const kinds: WorldSurfaceKind[] = [\"tools\"];\n if (s.api) kinds.push(\"api\");\n if (s.ui) kinds.push(\"ui\");\n if (s.browser) kinds.push(\"browser\");\n return kinds;\n}\n\nconst UI_TOKEN_QUERY = \"token\";\n\n/** The URL of `path` on a UI surface, carrying the session token when the\n * surface has one. `path` may already have a query string; the token is\n * appended to it. */\nexport function uiUrl(\n ui: NonNullable<SessionSurfaces[\"ui\"]>,\n path: string,\n): string {\n const base = ui.url.replace(/\\/+$/, \"\");\n const rel = path.startsWith(\"/\") ? path : `/${path}`;\n if (!ui.token) return base + rel;\n const [beforeHash, hash] = splitHash(rel);\n const joiner = beforeHash.includes(\"?\") ? \"&\" : \"?\";\n const query = `${UI_TOKEN_QUERY}=${encodeURIComponent(ui.token)}`;\n return base + beforeHash + joiner + query + hash;\n}\n\nexport function uiEntryUrl(ui: NonNullable<SessionSurfaces[\"ui\"]>): string {\n return uiUrl(ui, ui.entry || \"/\");\n}\n\n/** `url` without its `token` query parameter: what may be logged or shown. */\nexport function withoutUiToken(url: string): string {\n const [beforeHash, hash] = splitHash(url);\n const q = beforeHash.indexOf(\"?\");\n if (q < 0) return url;\n const kept = beforeHash\n .slice(q + 1)\n .split(\"&\")\n .filter((pair) => pair !== \"\" && pair.split(\"=\")[0] !== UI_TOKEN_QUERY);\n return (\n beforeHash.slice(0, q) + (kept.length ? `?${kept.join(\"&\")}` : \"\") + hash\n );\n}\n\nfunction splitHash(url: string): [string, string] {\n const h = url.indexOf(\"#\");\n return h < 0 ? [url, \"\"] : [url.slice(0, h), url.slice(h)];\n}\n\n/** The slice of a Playwright `Page` this module drives. */\nexport type BrowserPage = {\n url(): string;\n goto(url: string, opts?: { waitUntil?: \"load\" }): Promise<unknown>;\n click(selector: string): Promise<void>;\n fill(selector: string, value: string): Promise<void>;\n screenshot(opts?: {\n type?: \"png\" | \"jpeg\";\n quality?: number;\n fullPage?: boolean;\n }): Promise<Buffer>;\n innerText(selector: string): Promise<string>;\n content(): Promise<string>;\n goBack(opts?: { waitUntil?: \"load\" }): Promise<unknown>;\n waitForLoadState(state?: \"load\"): Promise<void>;\n waitForTimeout(ms: number): Promise<void>;\n on(\n event: \"request\" | \"requestfinished\" | \"requestfailed\",\n handler: (request: unknown) => void,\n ): unknown;\n title(): Promise<string>;\n keyboard: { press(key: string): Promise<void> };\n mouse: { wheel(dx: number, dy: number): Promise<void> };\n};\n\nexport type BrowserMode = \"auto\" | \"hosted\" | \"local\";\n\n// ── action events ────────────────────────────────────────────────────────────\n\n/** One browser action as the platform ingests it\n * (`POST /world-sessions/{id}/browser-events`). */\nexport type BrowserActionEvent = {\n agentId: string;\n seq: number;\n ts: string;\n action: string;\n args: Record<string, unknown>;\n ok: boolean;\n error: string | null;\n durationMs: number;\n url: string | null;\n title: string | null;\n mode: Exclude<BrowserMode, \"auto\">;\n viewport: { width: number; height: number };\n /** base64 JPEG of the screen after the action; null if it could not be taken. */\n screenshot: string | null;\n};\n\n/** What of an action's arguments may leave the process. Selectors, paths\n * and keys are what a reviewer needs; anything keyed like a credential, or\n * typed into a field whose selector names one, or shaped like a known key,\n * is replaced. Strings are capped, nested values dropped. */\nexport function redactActionArgs(\n action: string,\n args: Record<string, unknown>,\n): Record<string, unknown> {\n const secretField =\n action === \"browser_type\" && SECRET_KEY.test(String(args.selector ?? \"\"));\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(args)) {\n if (value === null || value === undefined) out[key] = null;\n else if (typeof value === \"boolean\" || typeof value === \"number\")\n out[key] = value;\n else if (typeof value === \"string\") {\n if (\n SECRET_KEY.test(key) ||\n SECRET_VALUE.test(value) ||\n (secretField && key === \"text\")\n )\n out[key] = \"[redacted]\";\n else\n out[key] =\n value.length <= EVENT_MAX_STRING\n ? value\n : value.slice(0, EVENT_MAX_STRING) + \"…\";\n } else out[key] = \"[omitted]\";\n }\n return out;\n}\n\n/**\n * Ships browser action events to the platform, off the action's hot path.\n *\n * `post` receives a batch of events (the request body's `events`). Events\n * are numbered here, so ordering survives batching and retries — the\n * platform dedups on `(agentId, seq)`. A batch that keeps failing is dropped\n * with a warning: telemetry must never stall or fail the agent.\n *\n * Numbering is durable across recorders: `nextSeq()` hands out a position\n * within this recorder, and the first send adds the base `resumeFrom`\n * reports — the platform's next free seq for this agent — so an agent id\n * reopened in a later process appends to its timeline instead of colliding\n * with (and being deduplicated against) what it already recorded. The base\n * is fixed once resolved, which keeps retries idempotent.\n */\nexport class BrowserActionRecorder {\n private seq = 0;\n private base: Promise<number> | null = null;\n private queue: BrowserActionEvent[] = [];\n private timer: ReturnType<typeof setTimeout> | null = null;\n private inflight: Promise<void> = Promise.resolve();\n sent = 0;\n dropped = 0;\n\n constructor(\n private readonly post: (events: BrowserActionEvent[]) => Promise<void>,\n readonly agentId: string,\n private readonly opts: {\n /** The platform's next free seq for `agentId`; 0 when not given. */\n resumeFrom?: () => Promise<number>;\n batchSize?: number;\n flushIntervalMs?: number;\n maxRetries?: number;\n sleep?: (ms: number) => Promise<void>;\n warn?: (message: string) => void;\n } = {},\n ) {}\n\n /** This recorder's next position; the wire seq is `resumeFrom() + this`. */\n nextSeq(): number {\n return this.seq++;\n }\n\n private resolveBase(): Promise<number> {\n if (this.base === null) {\n const resolve = this.opts.resumeFrom ?? (async () => 0);\n this.base = resolve().then((n) => {\n if (!Number.isInteger(n) || n < 0)\n throw new Error(\n `browser event base seq must be a non-negative integer, got ${String(n)}`,\n );\n return n;\n });\n // A failed lookup is retried with the batch, not remembered.\n this.base.catch(() => {\n this.base = null;\n });\n }\n return this.base;\n }\n\n record(event: BrowserActionEvent): void {\n this.queue.push(event);\n if (this.queue.length >= (this.opts.batchSize ?? EVENT_BATCH_SIZE)) {\n this.drain();\n } else if (this.timer === null) {\n this.timer = setTimeout(\n () => this.drain(),\n this.opts.flushIntervalMs ?? EVENT_FLUSH_INTERVAL_MS,\n );\n if (typeof this.timer === \"object\" && \"unref\" in this.timer)\n this.timer.unref();\n }\n }\n\n /** Resolve once everything recorded so far has been posted (or dropped). */\n async flush(): Promise<void> {\n this.drain();\n await this.inflight;\n }\n\n async close(): Promise<void> {\n await this.flush();\n }\n\n private drain(): void {\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n if (this.queue.length === 0) return;\n const batch = this.queue;\n this.queue = [];\n this.inflight = this.inflight.then(() => this.send(batch));\n }\n\n private async send(batch: BrowserActionEvent[]): Promise<void> {\n const retries = this.opts.maxRetries ?? EVENT_MAX_RETRIES;\n const sleep =\n this.opts.sleep ??\n ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));\n for (let attempt = 0; attempt < retries; attempt++) {\n try {\n const base = await this.resolveBase();\n await this.post(\n base === 0 ? batch : batch.map((e) => ({ ...e, seq: base + e.seq })),\n );\n this.sent += batch.length;\n return;\n } catch (error) {\n if (attempt + 1 === retries) {\n this.dropped += batch.length;\n (this.opts.warn ?? console.warn)(\n `dropping ${batch.length} browser events after ${attempt + 1} attempts: ${String(error)}`,\n );\n return;\n }\n await sleep(500 * 2 ** attempt);\n }\n }\n }\n}\n\n/**\n * One Playwright page on the session's UI. Thin on purpose — `page` is the\n * real Playwright page for anything this wrapper does not cover.\n */\nexport class WorldBrowser {\n constructor(\n readonly page: BrowserPage,\n readonly ui: SessionSurfaces[\"ui\"] | undefined,\n readonly mode: Exclude<BrowserMode, \"auto\">,\n private readonly teardown: () => Promise<void>,\n readonly viewport: { width: number; height: number } = DEFAULT_VIEWPORT,\n readonly recorder: BrowserActionRecorder | null = null,\n ) {\n page.on(\"request\", () => {\n this.inflight += 1;\n this.lastNetwork = Date.now();\n });\n const done = () => {\n this.inflight = Math.max(0, this.inflight - 1);\n this.lastNetwork = Date.now();\n };\n page.on(\"requestfinished\", done);\n page.on(\"requestfailed\", done);\n }\n\n private inflight = 0;\n private lastNetwork = Date.now();\n\n get agentId(): string | null {\n return this.recorder?.agentId ?? null;\n }\n\n /** Run one action and report it: the event carries what was asked,\n * whether it worked, and the screen after — for failures too, so a\n * reviewer sees what the agent saw when the selector did not match. */\n private async act<T>(\n action: string,\n args: Record<string, unknown>,\n fn: () => Promise<T>,\n ): Promise<T> {\n const recorder = this.recorder;\n if (!recorder) return fn();\n const started = Date.now();\n let ok = true;\n let error: string | null = null;\n try {\n return await fn();\n } catch (err) {\n ok = false;\n error = (\n err instanceof Error ? `${err.name}: ${err.message}` : String(err)\n ).slice(0, 4000);\n throw err;\n } finally {\n recorder.record({\n agentId: recorder.agentId,\n seq: recorder.nextSeq(),\n ts: new Date().toISOString(),\n action,\n args: redactActionArgs(action, args),\n ok,\n error,\n durationMs: Date.now() - started,\n mode: this.mode,\n viewport: { ...this.viewport },\n ...(await this.observeForEvent()),\n });\n }\n }\n\n private async observeForEvent(): Promise<\n Pick<BrowserActionEvent, \"url\" | \"title\" | \"screenshot\">\n > {\n const out: Pick<BrowserActionEvent, \"url\" | \"title\" | \"screenshot\"> = {\n url: null,\n title: null,\n screenshot: null,\n };\n try {\n out.url = this.page.url();\n out.title = await this.page.title();\n const jpeg = await this.page.screenshot({\n type: \"jpeg\",\n quality: EVENT_SCREENSHOT_QUALITY,\n });\n out.screenshot = jpeg.toString(\"base64\");\n } catch {\n // a closed page still gets its event\n }\n return out;\n }\n\n /** Open a UI path (`/customers`), a full URL, or — with no argument — the\n * UI's declared entry page. */\n async goto(pathOrUrl?: string): Promise<string> {\n let target: string;\n if (pathOrUrl === undefined) {\n if (!this.ui)\n throw new WorldSurfaceUnavailable(\n \"ui\",\n \"this session has no UI to navigate to\",\n );\n target = uiEntryUrl(this.ui);\n } else if (/^https?:\\/\\//.test(pathOrUrl)) {\n target = pathOrUrl;\n } else {\n if (!this.ui)\n throw new WorldSurfaceUnavailable(\n \"ui\",\n \"relative paths need a UI surface\",\n );\n target = uiUrl(this.ui, pathOrUrl);\n }\n return this.act(\n \"browser_goto\",\n { path: pathOrUrl ?? null, url: withoutUiToken(target) },\n async () => {\n await this.page.goto(target, { waitUntil: \"load\" });\n await this.settle();\n return this.page.url();\n },\n );\n }\n\n async back(): Promise<string> {\n return this.act(\"browser_back\", {}, async () => {\n await this.page.goBack({ waitUntil: \"load\" });\n await this.settle();\n return this.page.url();\n });\n }\n\n /** Wait for the page to finish reacting to an action. `load` alone is not\n * enough for client-rendered UIs (React et al.): a click returns before the\n * fetch that re-renders the page, so an agent would read stale text.\n * Playwright's `networkidle` is per navigation and resolves at once after\n * the first one, so this tracks requests itself: done when nothing is in\n * flight and the network has been quiet for `SETTLE_QUIET_MS`, bounded so\n * long-polling UIs cannot hang us. */\n private async settle(): Promise<void> {\n await this.page.waitForLoadState(\"load\");\n const deadline = Date.now() + SETTLE_TIMEOUT_MS;\n while (Date.now() < deadline) {\n const quiet = Date.now() - this.lastNetwork >= SETTLE_QUIET_MS;\n if (this.inflight === 0 && quiet) return;\n await this.page.waitForTimeout(SETTLE_POLL_MS);\n }\n }\n\n async click(selector: string): Promise<void> {\n await this.act(\"browser_click\", { selector }, async () => {\n await this.page.click(selector);\n await this.settle();\n });\n }\n\n async type(selector: string, text: string): Promise<void> {\n await this.act(\"browser_type\", { selector, text }, () =>\n this.page.fill(selector, text),\n );\n }\n\n async press(key: string): Promise<void> {\n await this.act(\"browser_press\", { key }, async () => {\n await this.page.keyboard.press(key);\n await this.settle();\n });\n }\n\n async scroll(dy: number): Promise<void> {\n await this.act(\"browser_scroll\", { dy }, () =>\n this.page.mouse.wheel(0, dy),\n );\n }\n\n async screenshot(fullPage = false): Promise<Buffer> {\n return this.page.screenshot({ type: \"png\", fullPage });\n }\n\n async screenshotBase64(fullPage = false): Promise<string> {\n return (await this.screenshot(fullPage)).toString(\"base64\");\n }\n\n async text(selector = \"body\"): Promise<string> {\n return this.page.innerText(selector);\n }\n\n async html(): Promise<string> {\n return this.page.content();\n }\n\n get url(): string {\n return this.page.url();\n }\n\n async title(): Promise<string> {\n return this.page.title();\n }\n\n async close(): Promise<void> {\n try {\n await this.teardown();\n } finally {\n await this.recorder?.close();\n }\n }\n}\n\n/** The Playwright entry points this module needs, so tests can inject a fake. */\nexport type PlaywrightLike = {\n chromium: {\n connect(wsEndpoint: string): Promise<PlaywrightBrowserLike>;\n connectOverCDP(endpointURL: string): Promise<PlaywrightBrowserLike>;\n launch(opts?: { headless?: boolean }): Promise<PlaywrightBrowserLike>;\n };\n};\n\nexport type PlaywrightBrowserLike = {\n newContext(opts?: {\n viewport?: { width: number; height: number };\n }): Promise<{ newPage(): Promise<BrowserPage>; close(): Promise<void> }>;\n close(): Promise<void>;\n};\n\nasync function loadPlaywright(): Promise<PlaywrightLike> {\n try {\n // A string specifier keeps bundlers from resolving the optional peer.\n const name = \"playwright\";\n return (await import(name)) as PlaywrightLike;\n } catch (error) {\n throw new Error(\n \"Driving a world UI needs Playwright: npm install playwright \" +\n \"(and `npx playwright install chromium` for local mode).\",\n { cause: error },\n );\n }\n}\n\nexport function resolveBrowserMode(\n surfaces: SessionSurfaces,\n mode: BrowserMode,\n): Exclude<BrowserMode, \"auto\"> {\n if (!surfaces.ui && !surfaces.browser)\n throw new WorldSurfaceUnavailable(\n \"ui\",\n \"open the session with surfaces: ['ui'] on a world that declares [ui]\",\n );\n const resolved =\n mode === \"auto\" ? (surfaces.browser ? \"hosted\" : \"local\") : mode;\n if (resolved === \"hosted\" && !surfaces.browser)\n throw new WorldSurfaceUnavailable(\n \"browser\",\n \"open the session with surfaces: ['browser'] to get a hosted browser\",\n );\n return resolved;\n}\n\n/** Open a browser on the session's UI in `hosted`, `local` or `auto` mode. */\nexport async function openBrowser(\n surfaces: SessionSurfaces,\n opts: {\n mode?: BrowserMode;\n headless?: boolean;\n playwright?: PlaywrightLike;\n recorder?: BrowserActionRecorder | null;\n } = {},\n): Promise<WorldBrowser> {\n const mode = resolveBrowserMode(surfaces, opts.mode ?? \"auto\");\n const pw = opts.playwright ?? (await loadPlaywright());\n const viewport = surfaces.browser?.viewport ?? DEFAULT_VIEWPORT;\n const browser =\n mode === \"hosted\"\n ? surfaces.browser!.protocol === \"playwright\"\n ? await pw.chromium.connect(surfaces.browser!.wsUrl)\n : await pw.chromium.connectOverCDP(surfaces.browser!.wsUrl)\n : await pw.chromium.launch({ headless: opts.headless ?? true });\n const context = await browser.newContext({ viewport });\n const page = await context.newPage();\n return new WorldBrowser(\n page,\n surfaces.ui,\n mode,\n async () => {\n await context.close();\n await browser.close();\n },\n viewport,\n opts.recorder ?? null,\n );\n}\n\n// ── computer-use tools ───────────────────────────────────────────────────────\n\nexport const COMPUTER_USE_SPECS = [\n {\n name: \"browser_goto\",\n signature: \"browser_goto(path=None)\",\n doc: \"Open a page of the world's UI. `path` is a UI path like /customers, a full URL, or omitted for the entry page. Returns the URL and page text.\",\n },\n {\n name: \"browser_click\",\n signature: \"browser_click(selector)\",\n doc: \"Click an element by Playwright selector (CSS, `text=Refund`, `role=button[name=Save]`). Returns the page text after the click.\",\n },\n {\n name: \"browser_type\",\n signature: \"browser_type(selector, text)\",\n doc: \"Replace the value of an input/textarea found by selector with `text`.\",\n },\n {\n name: \"browser_press\",\n signature: \"browser_press(key)\",\n doc: \"Press a key (Enter, Tab, Escape, ArrowDown, ...). Returns the page text after.\",\n },\n {\n name: \"browser_scroll\",\n signature: \"browser_scroll(dy=600)\",\n doc: \"Scroll the page vertically by `dy` pixels (negative scrolls up).\",\n },\n {\n name: \"browser_screenshot\",\n signature: \"browser_screenshot(full_page=False)\",\n doc: \"Take a PNG screenshot; returns {image_base64, url}.\",\n },\n {\n name: \"browser_read\",\n signature: \"browser_read(selector='body')\",\n doc: \"Return the visible text of an element (default: whole page) plus the URL and title.\",\n },\n {\n name: \"browser_back\",\n signature: \"browser_back()\",\n doc: \"Go back one page in history.\",\n },\n] as const;\n\nconst str = (v: unknown, fallback: string): string =>\n typeof v === \"string\" && v.length > 0 ? v : fallback;\n\n/**\n * The browser as model tools, in the same `WorldToolkit` shape the world's\n * own tools come in — so an agent loop that already dispatches\n * `toolkit().impls` merges `computerUseToolkit(b).impls` and gains a screen\n * without a second dispatch path.\n */\nexport function computerUseToolkit(\n browser: WorldBrowser,\n opts: { maxText?: number } = {},\n): WorldToolkit {\n const maxText = opts.maxText ?? 20_000;\n const observe = async (selector = \"body\") => {\n const text = await browser.text(selector);\n return {\n url: browser.url,\n title: await browser.title(),\n text: text.slice(0, maxText),\n truncated: text.length > maxText,\n };\n };\n\n const impls: WorldToolkit[\"impls\"] = {\n browser_goto: async (a) => {\n await browser.goto(typeof a.path === \"string\" ? a.path : undefined);\n return observe();\n },\n browser_click: async (a) => {\n await browser.click(str(a.selector, \"\"));\n return observe();\n },\n browser_type: async (a) => {\n await browser.type(str(a.selector, \"\"), String(a.text ?? \"\"));\n return { ok: true, url: browser.url };\n },\n browser_press: async (a) => {\n await browser.press(str(a.key, \"Enter\"));\n return observe();\n },\n browser_scroll: async (a) => {\n await browser.scroll(typeof a.dy === \"number\" ? a.dy : 600);\n return { ok: true, url: browser.url };\n },\n browser_screenshot: async (a) => ({\n image_base64: await browser.screenshotBase64(a.full_page === true),\n url: browser.url,\n }),\n browser_read: async (a) => observe(str(a.selector, \"body\")),\n browser_back: async () => {\n await browser.back();\n return observe();\n },\n };\n\n const specs = COMPUTER_USE_SPECS.map((s) => ({ ...s }));\n return {\n schemas: specs.map((spec) => schemaFromSignature(spec)),\n impls,\n specs,\n };\n}\n","import { randomUUID } from \"node:crypto\";\n\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\nimport {\n BrowserActionRecorder,\n SURFACE_KINDS,\n WorldSurfaceUnavailable,\n computerUseToolkit,\n openBrowser,\n uiEntryUrl,\n type BrowserActionEvent,\n type BrowserMode,\n type PlaywrightLike,\n type SessionSurfaces,\n type WorldBrowser,\n type WorldSurfaceKind,\n} from \"./browser\";\nimport type { WorldTaskSummary } from \"./tasks\";\n\n/**\n * LIVE WORLD SESSIONS from TypeScript: your agent, the platform's container.\n *\n * The other two ways of running a world each give up something. Pulling the\n * bundle and executing it locally tests your agent against a COPY — your\n * python, your sqlite, your machine's idea of the environment. Dispatching a\n * hosted run gives you the real container but runs the platform's agent\n * inside it, so your agent never touches the world.\n *\n * A session is both: the platform boots the task's container and holds it\n * warm, and every `call()` here executes inside THAT container. Your agent\n * stays where it is — this file is just the wire.\n *\n * const world = await openWorld(\"revenue-ops-sim@main\");\n * const session = await openSession(world.slug, { task: \"revops-mara-dedupe-contacts\" });\n * await session.ready(); // wait for the container\n * await session.call(\"crm_search\", { entity: \"deals\" });\n * const { reward, rewards } = await session.grade();\n * await session.close({ keepWarm: true }); // hand it back to the pool\n *\n * The task can also be YOURS rather than the bundle's — an instruction, the\n * rows the session starts with and how it is graded, for one end user:\n *\n * const session = await openSession(\"acme-billing@main\", {\n * task: {\n * instruction: \"Mark invoice INV-7 as paid.\",\n * seed: { rows: { invoices: [{ id: \"INV-7\", status: \"open\" }] } },\n * grader: { kind: \"assertions\", checks: [\n * { entity: \"invoices\", where: { id: \"INV-7\", status: \"paid\" } },\n * ] },\n * metadata: { externalUserId: \"u_42\" },\n * },\n * surfaces: [\"api\"],\n * });\n *\n * Every call is a row on the platform before it is an effect in a container,\n * so the episode is on the record — and the platform traces the session\n * itself, which is why these sessions show up under Sessions without the\n * caller instrumenting anything.\n */\n\nexport type WorldToolSpec = {\n name: string;\n /** The world's own signature, e.g. `crm_search(q=None, entity=\"deals\")`. */\n signature: string;\n doc: string | null;\n inputSchema?: Record<string, unknown>;\n};\n\n/** What a model needs to call a world: the schemas to advertise, and the\n * implementations that run them in the container. */\nexport type WorldToolkit = {\n /** OpenAI-shaped tool definitions, derived from the world's signatures. */\n schemas: {\n type: \"function\";\n function: {\n name: string;\n description: string;\n parameters: Record<string, unknown>;\n };\n }[];\n /** name -> implementation, each one a call into THIS session. */\n impls: Record<string, (args: Record<string, unknown>) => Promise<unknown>>;\n specs: WorldToolSpec[];\n};\n\n// ── tasks ────────────────────────────────────────────────────────────────────\n\n/** A JSON scalar: what `where` filters and field predicates compare against. */\nexport type WorldTaskScalar = string | number | boolean | null;\n\n/** The rows a task starts the session with — the `seed()` contract, applied\n * by the host right after it clones the version's snapshot. `append`\n * (default) upserts by primary key onto the base data; `replace` makes the\n * named entities hold exactly these rows. */\nexport type WorldTaskSeed = {\n mode?: \"append\" | \"replace\";\n /** Redaction on the way in: `off` (default) stores the rows as given,\n * `apply` runs the world's `[redact]` policy over them first, `refuse`\n * rejects a row carrying plaintext in a redacted field. */\n redact?: \"off\" | \"apply\" | \"refuse\";\n rows: Record<string, Record<string, unknown>[]>;\n};\n\nexport type WorldTaskFieldOp =\n \"eq\" | \"neq\" | \"in\" | \"gt\" | \"gte\" | \"lt\" | \"lte\" | \"contains\";\n\n/**\n * One declarative check over the session's final rows. `where` selects rows\n * of `entity` by equality (dotted paths reach into nested objects); the\n * assertion says what must hold of the selection:\n *\n * exists (default) / absent at least one row / none\n * count `count` bound on how many\n * all / any `field op value` on every / some selected row\n *\n * A check's `id` names its entry in `rewards`; the task's reward is the\n * weighted share of checks that passed.\n */\nexport type WorldTaskCheck = {\n id?: string;\n weight?: number;\n entity: string;\n where?: Record<string, WorldTaskScalar>;\n assert?: \"exists\" | \"absent\" | \"count\" | \"all\" | \"any\";\n count?: { eq?: number; gte?: number; lte?: number };\n field?: string;\n op?: WorldTaskFieldOp;\n value?: WorldTaskScalar | WorldTaskScalar[];\n};\n\n/** One thing a rubric judge scores in [0, 1]; `id` names its entry in\n * `rewards`, `weight` (default 1) its share of the task's reward. */\nexport type WorldTaskRubricCriterion = {\n id: string;\n description: string;\n weight?: number;\n};\n\n/** A rubric is prose: what a good outcome looks like. The platform (never the\n * host) has a model read the session's final state and its call log against\n * it; the project's default evaluation model judges unless `model` pins one.\n * `grade()` then resolves asynchronously — `pending: true` first, the reward\n * once the judge has answered. */\nexport type WorldTaskRubricGrader = {\n kind: \"rubric\";\n rubric: string;\n criteria?: WorldTaskRubricCriterion[];\n model?: { provider: string; model: string };\n};\n\n/** How a task is graded: checks the host evaluates in-process, a `verify.py`\n * body (state JSON on stdin, last stdout line `{reward, ...}`) run through the\n * host's confined verifier, or a rubric judged by a model on the platform. */\nexport type WorldTaskGrader =\n | { kind: \"assertions\"; checks: WorldTaskCheck[] }\n | { kind: \"python\"; source: string; timeoutSeconds?: number }\n | WorldTaskRubricGrader;\n\n/** A task supplied at open, for one session, instead of a bundled scenario.\n * `instruction` is what the agent is told; without `seed` the session starts\n * on the version's base data, without `grader` `grade()` answers\n * `reward: null`; `tools` is the allow-list of the version's tools the agent\n * may call in this session (unset: all of them; a call outside it is refused\n * and logged); `metadata` is yours (an end-user id, a ticket) and is echoed\n * on the session, never read. Limits: shared/domain/worldTasks.ts. */\nexport type WorldTaskSpec = {\n name?: string;\n instruction: string;\n seed?: WorldTaskSeed;\n grader?: WorldTaskGrader;\n tools?: string[];\n metadata?: Record<string, unknown>;\n};\n\n/** A stored task of the project (see worlds/tasks.ts), opened by id; the\n * session runs a copy of one version's spec — the current one by default. */\nexport type WorldTaskIdRef = { id: string; version?: number };\n\n/** What `openSession` takes as the task: a bundled scenario's name, a\n * stored task's `{ id, version? }`, or an inline spec. */\nexport type WorldTaskRef = string | WorldTaskIdRef | WorldTaskSpec;\n\n/** What a session's task is, on every session response. `hash` is the\n * content hash of the spec (inline or stored) — what warm reuse matches on;\n * `id`/`version` name the stored task the session was opened on. */\nexport type WorldSessionTask = {\n source: \"bundled\" | \"inline\" | \"stored\";\n name: string | null;\n hash: string | null;\n id?: string | null;\n version?: number | null;\n metadata: Record<string, unknown>;\n};\n\nexport const isTaskIdRef = (task: WorldTaskRef): task is WorldTaskIdRef =>\n typeof task === \"object\" && task !== null && \"id\" in task;\n\nexport const isTaskSpec = (task: WorldTaskRef): task is WorldTaskSpec =>\n typeof task === \"object\" && task !== null && \"instruction\" in task;\n\n/** The label a task goes by in results: its name, `inline:<hash>` for an\n * unnamed inline task once the platform has hashed it, or the stored task's\n * name (its id until the platform has answered). */\nexport const taskLabel = (\n task: WorldTaskRef,\n info?: WorldSessionTask | null,\n): string => {\n if (typeof task === \"string\") return task;\n if (isTaskIdRef(task)) return info?.name ?? task.id;\n if (task.name) return task.name;\n return info?.hash ? `inline:${info.hash.slice(0, 12)}` : \"inline\";\n};\n\nexport type SeedResult = {\n seeded: number;\n mode: \"append\" | \"replace\";\n entity_counts: Record<string, number>;\n};\n\n/** One row of the session's call log. */\nexport type WorldSessionCall = {\n seq: number;\n kind: string;\n tool: string | null;\n args: unknown;\n result: unknown;\n error: string | null;\n completedAt: string | null;\n};\n\nexport type WorldSessionState = {\n sessionId: string;\n state: string;\n ready: boolean;\n versionId: string;\n contentHash: string;\n taskName: string | null;\n /** Where the task came from and what it is; absent on platforms that\n * predate session tasks, in which case it is derived from `taskName`. */\n task?: WorldSessionTask;\n /** The task's objective — present when the session was opened (not on a\n * bare status read), so a client never needs the bundle on disk. */\n instruction?: string | null;\n /** The tools this task serves. */\n tools?: WorldToolSpec[];\n /** Where the session answers besides `tools` — see worlds/browser.ts. */\n surfaces?: SessionSurfaces;\n /** Notices about the world's shape (an api bundle is a deprecated layout;\n * schema worlds are the supported shape), with what to run instead. Empty\n * for a schema world; absent on platforms that predate the notice. */\n deprecations?: WorldDeprecation[];\n};\n\n/** One notice a worlds-path answer carries: a deprecated shape or layout\n * and the command that replaces it. A retired shape is refused instead,\n * with the stable message prefix `world_kind_retired:`. */\nexport type WorldDeprecation = {\n code: string;\n message: string;\n replacement: string;\n};\n\nexport type GradeResult = {\n reward: number | null;\n rewards: Record<string, number>;\n raw: unknown;\n};\n\n/** How long `ready()` waits, and how often it asks. */\nconst READY_TIMEOUT_MS = 10 * 60_000;\nconst READY_POLL_MS = 2_000;\n/** How long one call may take end to end (container claim + execution). */\nconst CALL_TIMEOUT_MS = 3 * 60_000;\nconst CALL_POLL_MS = 400;\n/** How long a grade the platform's judge finalizes may take: the model's own\n * timeout and retries, plus the worker's queue backoff. Polled slowly. */\nconst JUDGED_GRADE_TIMEOUT_MS = 15 * 60_000;\nconst JUDGED_GRADE_POLL_MS = 2_000;\nconst EXPORT_PAGE = 500;\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\nconst modelToolName = (name: string): string =>\n name.replace(/[^A-Za-z0-9_-]/g, \"_\").slice(0, 64) || \"tool\";\n\n/**\n * Turn a world's Python signature into a JSON schema the model can call.\n *\n * `crm_update_deal(id, stage=None, owner=None, amount=None)` becomes an\n * object with `id` required and the rest optional. Types are read from the\n * DEFAULTS the world declares — a numeric default means a number, a boolean\n * default a boolean — because that is the only type information a signature\n * actually carries. Everything else is a string, which is what a tool CLI\n * receives anyway.\n */\nexport function schemaFromSignature(spec: WorldToolSpec): {\n type: \"function\";\n function: {\n name: string;\n description: string;\n parameters: Record<string, unknown>;\n };\n} {\n if (spec.inputSchema)\n return {\n type: \"function\",\n function: {\n name: modelToolName(spec.name),\n description: spec.doc ?? spec.name,\n parameters: spec.inputSchema,\n },\n };\n const inside = /\\(([\\s\\S]*)\\)\\s*$/.exec(spec.signature.trim())?.[1] ?? \"\";\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n // Split on top-level commas only: a default like `{\"a\": 1}` has its own.\n const params: string[] = [];\n let depth = 0;\n let current = \"\";\n for (const ch of inside) {\n if (\"([{\".includes(ch)) depth++;\n if (\")]}\".includes(ch)) depth--;\n if (ch === \",\" && depth === 0) {\n params.push(current);\n current = \"\";\n } else current += ch;\n }\n if (current.trim()) params.push(current);\n\n for (const raw of params) {\n const param = raw.trim();\n if (!param || param.startsWith(\"*\") || param === \"self\") continue;\n const eq = param.indexOf(\"=\");\n const name = (eq === -1 ? param : param.slice(0, eq)).split(\":\")[0].trim();\n if (!name) continue;\n if (eq === -1) {\n properties[name] = { type: \"string\" };\n required.push(name);\n continue;\n }\n const value = param.slice(eq + 1).trim();\n if (/^-?\\d+(\\.\\d+)?$/.test(value)) properties[name] = { type: \"number\" };\n else if (value === \"True\" || value === \"False\")\n properties[name] = { type: \"boolean\" };\n else properties[name] = { type: \"string\" };\n }\n return {\n type: \"function\",\n function: {\n name: modelToolName(spec.name),\n description: spec.doc ?? spec.name,\n parameters: { type: \"object\", properties, required },\n },\n };\n}\n\nexport class WorldSessionTimeout extends Error {}\nexport class WorldSessionCallError extends Error {}\n\nexport class WorldSession {\n constructor(\n readonly sessionId: string,\n private current: WorldSessionState,\n private readonly options: WorldsClientOptions,\n ) {}\n\n /** The task's display name: a bundled scenario's, or the inline spec's\n * `name` (null when the spec was unnamed). Same as `taskName`. */\n get task(): string | null {\n return this.current.taskName;\n }\n\n /** The task's display name: a bundled scenario's, or the inline spec's\n * `name` (null when the spec was unnamed). */\n get taskName(): string | null {\n return this.current.taskName;\n }\n\n /** The platform's notices about the world this session runs on (empty\n * for a schema world). Printed by the CLI on stderr at open. */\n get deprecations(): WorldDeprecation[] {\n return this.current.deprecations ?? [];\n }\n\n /** The task this session runs: bundled scenario, stored task or inline\n * spec, its name, hash and the caller's metadata. */\n get taskInfo(): WorldSessionTask {\n return (\n this.current.task ?? {\n source: \"bundled\",\n name: this.current.taskName,\n hash: null,\n metadata: {},\n }\n );\n }\n\n /** What this task asks for — the bundle's instruction.md, or the inline\n * spec's `instruction`. */\n get instruction(): string | null {\n return this.current.instruction ?? null;\n }\n\n get versionId(): string {\n return this.current.versionId;\n }\n\n /** Whether the session answered ready as of the last state read (the open,\n * a `status()`, or the poll inside `ready()`); no request is made. */\n get isReady(): boolean {\n return this.current.ready;\n }\n\n /** `api` / `ui` / `browser` are present exactly when the world declares\n * them AND the session was opened asking for them. */\n async surfaces(): Promise<SessionSurfaces> {\n if (!this.current.surfaces) await this.status();\n return this.current.surfaces ?? { tools: { kind: \"rendezvous\" } };\n }\n\n /** Base URL of the world's own HTTP API for this session. */\n async api(): Promise<string> {\n const { api } = await this.surfaces();\n if (!api)\n throw new WorldSurfaceUnavailable(\n \"api\",\n \"open the session with surfaces: ['api'] on an api-type world\",\n );\n return api.url;\n }\n\n /** Headers every request to `api()` needs. A World Host session gates its\n * api surface on a per-session token; a pod or hosted twin answers with the\n * world's own declared auth and this is `{}`. */\n async apiHeaders(): Promise<Record<string, string>> {\n const { api } = await this.surfaces();\n return api?.token ? { Authorization: `Bearer ${api.token}` } : {};\n }\n\n /** URL of the world's UI entry page for this session. */\n async ui(): Promise<string> {\n const { ui } = await this.surfaces();\n if (!ui)\n throw new WorldSurfaceUnavailable(\n \"ui\",\n \"open the session with surfaces: ['ui'] on a world that declares [ui]\",\n );\n return uiEntryUrl(ui);\n }\n\n /** A Playwright browser on this session's UI: `hosted` drives the one the\n * platform runs next to the world, `local` launches one here, `auto`\n * prefers hosted. Call `close()` when done.\n *\n * Every action is reported to the platform under `agentId` (default:\n * `GATEWAY_AGENT_ID` or a fresh `agent-<hex>`) so the session page shows\n * this agent's own timeline — several agents may share one session and\n * one hosted browser. `record: false` opts out. */\n async browser(\n opts: {\n mode?: BrowserMode;\n headless?: boolean;\n playwright?: PlaywrightLike;\n agentId?: string;\n record?: boolean;\n } = {},\n ): Promise<WorldBrowser> {\n const { agentId, record = true, ...rest } = opts;\n return openBrowser(await this.surfaces(), {\n ...rest,\n recorder: record ? this.browserRecorder(agentId) : null,\n });\n }\n\n /** The reporter `browser()` uses; exposed for a page you drive yourself. */\n browserRecorder(agentId?: string): BrowserActionRecorder {\n const path = `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/browser-events`;\n const id =\n agentId ??\n process.env.GATEWAY_AGENT_ID ??\n `agent-${randomUUID().replace(/-/g, \"\").slice(0, 8)}`;\n return new BrowserActionRecorder(\n async (events: BrowserActionEvent[]) => {\n await apiRequest(this.options, \"POST\", path, { events });\n },\n id,\n {\n // Continue this agent's timeline where the platform has it, so the\n // same id reopened later never re-numbers from zero.\n resumeFrom: async () => {\n const summary = await apiRequest<{\n agents: { agentId: string; nextSeq: number }[];\n }>(this.options, \"GET\", path);\n return summary.agents.find((a) => a.agentId === id)?.nextSeq ?? 0;\n },\n },\n );\n }\n\n /** Browser actions as model tools, in the same shape as `toolkit()`. */\n computerUseTools(browser: WorldBrowser): WorldToolkit {\n return computerUseToolkit(browser);\n }\n\n /** The session's latest platform state (one request, no waiting). */\n async status(): Promise<WorldSessionState> {\n const fresh = await apiRequest<WorldSessionState>(\n this.options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}`,\n );\n // A status read does not carry the objective; keep the one we opened with.\n this.current = {\n instruction: this.current.instruction,\n tools: this.current.tools,\n surfaces: this.current.surfaces,\n task: this.current.task,\n ...fresh,\n };\n return this.current;\n }\n\n /**\n * Wait until the container is warm — meaning the process inside it has\n * asked the platform for work, not merely that a job was accepted.\n */\n async ready(opts: { timeoutMs?: number } = {}): Promise<WorldSessionState> {\n const deadline = Date.now() + (opts.timeoutMs ?? READY_TIMEOUT_MS);\n for (;;) {\n const state = await this.status();\n if (state.ready) return state;\n if (state.state === \"FAILED\" || state.state === \"STOPPED\")\n throw new WorldSessionCallError(\n `World session ${state.state.toLowerCase()} before it was ready.`,\n );\n if (Date.now() > deadline)\n throw new WorldSessionTimeout(\n `World session still ${state.state} after ${Math.round((opts.timeoutMs ?? READY_TIMEOUT_MS) / 1000)}s.`,\n );\n await sleep(READY_POLL_MS);\n }\n }\n\n /** Enqueue one interaction and wait for the container's answer. */\n private async exchange(\n body: {\n kind?: \"call\" | \"grade\" | \"reset\" | \"state\" | \"seed\" | \"close\";\n tool?: string;\n args?: unknown;\n },\n timeoutMs?: number,\n ): Promise<unknown> {\n const enqueued = await apiRequest<{\n callId: string;\n seq: number;\n /** The platform's worker finalizes this call (a rubric grade). */\n pending?: boolean;\n }>(\n this.options,\n \"POST\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/calls`,\n body,\n );\n const { callId } = enqueued;\n const judged = enqueued.pending === true;\n const budgetMs =\n timeoutMs ?? (judged ? JUDGED_GRADE_TIMEOUT_MS : CALL_TIMEOUT_MS);\n const pollMs = judged ? JUDGED_GRADE_POLL_MS : CALL_POLL_MS;\n const deadline = Date.now() + budgetMs;\n for (;;) {\n const call = await apiRequest<{\n done: boolean;\n state: string;\n result: unknown;\n error: string | null;\n }>(\n this.options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/calls/${encodeURIComponent(callId)}`,\n );\n if (call.done) {\n if (call.error) throw new WorldSessionCallError(call.error);\n return call.result;\n }\n if (Date.now() > deadline)\n throw new WorldSessionTimeout(\n judged\n ? `Grade ${callId} still ${call.state} after ${Math.round(budgetMs / 1000)}s — the judge has not answered; the platform finalizes the call on its own, read it back with export().`\n : `Call ${callId} still ${call.state} after ${Math.round(budgetMs / 1000)}s — the container may have died.`,\n );\n await sleep(pollMs);\n }\n }\n\n /**\n * Run one of the world's tools INSIDE the container. The arguments and the\n * result are the world's own contract — this layer neither validates nor\n * reshapes them, so a tool error reads exactly as it would in a hosted run.\n */\n async call(\n tool: string,\n args: Record<string, unknown> = {},\n opts: { timeoutMs?: number } = {},\n ): Promise<unknown> {\n return this.exchange({ kind: \"call\", tool, args }, opts.timeoutMs);\n }\n\n /**\n * THE WORLD'S TOOLS, READY TO HAND TO A MODEL. Schemas come from the\n * world's own signatures and implementations call into this session, so a\n * caller never writes — and never has to re-sync — a tool map of their own:\n *\n * const { schemas, impls } = await session.toolkit();\n * await runMyAgent(impls, schemas, session.instruction);\n *\n * A tool added to the world shows up here on the next run; a tool renamed\n * in the world renames here too, instead of failing at call time against a\n * hand-written map that still remembers the old name.\n */\n async toolkit(): Promise<WorldToolkit> {\n let specs = this.current.tools;\n if (!specs) specs = (await this.status()).tools ?? [];\n const impls: WorldToolkit[\"impls\"] = Object.create(null);\n for (const spec of specs) {\n const alias = modelToolName(spec.name);\n if (Object.hasOwn(impls, alias))\n throw new WorldSessionCallError(`Model tool name collision: ${alias}`);\n impls[alias] = (args: Record<string, unknown> = {}) =>\n this.call(spec.name, args);\n }\n return { schemas: specs.map(schemaFromSignature), impls, specs };\n }\n\n /** Run the task's grader against the container's END STATE. Graders answer\n * in one of two shapes: the scalar with named rewards beside it\n * (`{reward, check_a, check_b}`, a task's own `grade.py`), or the named\n * rewards nested under `rewards` (the api, mock-tools and World Host\n * runners). Both land in `rewards`.\n *\n * A rubric grade is finalized by the platform's judge, not the container:\n * the platform answers the enqueue with `pending: true`, and this waits on\n * the judge's budget (15 min) instead of a call's. `timeoutMs` overrides\n * either. */\n async grade(opts: { timeoutMs?: number } = {}): Promise<GradeResult> {\n const raw = (await this.exchange(\n { kind: \"grade\" },\n opts.timeoutMs,\n )) as Record<string, unknown> | null;\n const record = raw && typeof raw === \"object\" ? raw : {};\n const rewards: Record<string, number> = {};\n const nested = record.rewards;\n if (nested && typeof nested === \"object\") {\n for (const [key, value] of Object.entries(nested)) {\n if (typeof value === \"number\") rewards[key] = value;\n }\n }\n for (const [key, value] of Object.entries(record)) {\n if (key !== \"reward\" && typeof value === \"number\") rewards[key] = value;\n }\n return {\n reward: typeof record.reward === \"number\" ? record.reward : null,\n rewards,\n raw,\n };\n }\n\n /**\n * Put rows into the LIVE world through its contract, in one batch:\n * `append` (default) upserts by primary key, `replace` makes the named\n * entities hold exactly these rows. Atomic — a refused row leaves the\n * session unchanged and the error names the entity, row and field.\n */\n async seed(\n rows: Record<string, Record<string, unknown>[]>,\n opts: {\n mode?: \"append\" | \"replace\";\n /** `apply` runs the world's `[redact]` policy over the rows first;\n * `refuse` rejects plaintext in a redacted field; default `off`. */\n redact?: \"off\" | \"apply\" | \"refuse\";\n timeoutMs?: number;\n } = {},\n ): Promise<SeedResult> {\n const mode = opts.mode ?? \"append\";\n const redact = opts.redact ?? \"off\";\n return (await this.exchange(\n {\n kind: \"seed\",\n args: { mode, rows, ...(redact !== \"off\" ? { redact } : {}) },\n },\n opts.timeoutMs,\n )) as SeedResult;\n }\n\n /** Every entity's rows as the world holds them now — the same dump a\n * grader reads. The shape is the world runtime's: a schema world answers\n * `{<entity>: {<key>: row}, snapshot}`, a mock-tools world\n * `{entities: {<entity>: [row]}}`. */\n async state(opts: { timeoutMs?: number } = {}): Promise<unknown> {\n return this.exchange({ kind: \"state\" }, opts.timeoutMs);\n }\n\n /** Back to the opening state: the version's data plus the bundled\n * scenario's or the inline task's seed. Rows written since are gone; the\n * call log stays. */\n async reset(opts: { timeoutMs?: number } = {}): Promise<void> {\n await this.exchange({ kind: \"reset\" }, opts.timeoutMs);\n }\n\n /** The session's call log, oldest first: every tool call, seed, reset,\n * grade with its result — the record of the episode. */\n async export(): Promise<WorldSessionCall[]> {\n const calls: WorldSessionCall[] = [];\n let cursor: string | undefined;\n do {\n const params = new URLSearchParams({ limit: String(EXPORT_PAGE) });\n if (cursor) params.set(\"cursor\", cursor);\n const page = await apiRequest<{\n calls: Record<string, unknown>[];\n nextCursor?: string | null;\n }>(\n this.options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/calls?${params.toString()}`,\n );\n for (const call of page.calls) {\n calls.push({\n seq: Number(call.seq),\n kind: String(call.kind ?? \"call\"),\n tool: typeof call.tool === \"string\" ? call.tool : null,\n args: call.args ?? null,\n result: call.result ?? null,\n error: typeof call.error === \"string\" ? call.error : null,\n completedAt:\n typeof call.completedAt === \"string\" ? call.completedAt : null,\n });\n }\n cursor = page.nextCursor ?? undefined;\n } while (cursor);\n return calls;\n }\n\n /**\n * Promote this session's inline task into a stored task of the project\n * (version 1, pinned to the session's world unless `world` says otherwise),\n * so a task written for one end user can be reused and its grades\n * compared. The session then records the new task's id. A session on a\n * bundled task has nothing to save; one on a stored task is already saved.\n */\n async saveTask(\n opts: { name?: string; world?: string | null; message?: string } = {},\n ): Promise<WorldTaskSummary> {\n const task = await apiRequest<WorldTaskSummary>(\n this.options,\n \"POST\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/task`,\n {\n ...(opts.name !== undefined ? { name: opts.name } : {}),\n ...(opts.world !== undefined ? { world: opts.world } : {}),\n ...(opts.message !== undefined ? { message: opts.message } : {}),\n },\n );\n this.current = {\n ...this.current,\n taskName: task.name,\n task: {\n ...this.taskInfo,\n source: \"stored\",\n name: task.name,\n id: task.id,\n version: task.version,\n },\n };\n return task;\n }\n\n /**\n * End the session. `keepWarm` hands the container back to the pool instead\n * of tearing it down, so the next session for the same task starts warm —\n * the pooled instance still obeys the fleet's idle TTL and pinning.\n */\n async close(opts: { keepWarm?: boolean } = {}): Promise<{ state: string }> {\n return apiRequest(\n this.options,\n \"DELETE\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}`,\n { keepWarm: opts.keepWarm ?? false },\n );\n }\n}\n\n/**\n * Attach to a session that already exists — resuming after a crash, or\n * driving a session someone else opened (a container started by hand on a\n * self-hosted install, a session opened by CI and handed to a developer).\n */\nexport async function attachSession(\n sessionId: string,\n options: WorldsClientOptions = {},\n): Promise<WorldSession> {\n const state = await apiRequest<WorldSessionState>(\n options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(sessionId)}`,\n );\n return new WorldSession(sessionId, state, options);\n}\n\nexport type OpenSessionOptions = {\n versionId?: string;\n reuseWarm?: boolean;\n /** More than `tools`: `[\"api\"]`, `[\"ui\"]`, `[\"browser\"]`. The platform\n * refuses (HTTP 400) rather than quietly serving less than asked. */\n surfaces?: WorldSurfaceKind[];\n options?: WorldsClientOptions;\n};\n\n/**\n * Open a live session against one task of a world. Returns as soon as the\n * platform has accepted it — call `ready()` to wait for the container.\n *\n * `task` is a bundled scenario's name, a stored task's `{ id, version? }`\n * or an inline `WorldTaskSpec` (the latter two need a host engine world — the\n * platform answers 400 for a pod world). The older positional form\n * `openSession(slug, \"task-name\", opts)` still works.\n */\nexport async function openSession(\n slugOrRef: string,\n task: OpenSessionOptions & { task: WorldTaskRef },\n): Promise<WorldSession>;\nexport async function openSession(\n slugOrRef: string,\n task: WorldTaskRef,\n opts?: OpenSessionOptions,\n): Promise<WorldSession>;\nexport async function openSession(\n slugOrRef: string,\n taskOrOpts: WorldTaskRef | (OpenSessionOptions & { task: WorldTaskRef }),\n positionalOpts: OpenSessionOptions = {},\n): Promise<WorldSession> {\n const { task, ...opts } =\n typeof taskOrOpts === \"object\" && \"task\" in taskOrOpts\n ? taskOrOpts\n : { task: taskOrOpts as WorldTaskRef, ...positionalOpts };\n if (\n task === undefined ||\n task === null ||\n (typeof task === \"string\" && !task) ||\n (isTaskIdRef(task) && !task.id) ||\n (isTaskSpec(task) && !task.instruction) ||\n (typeof task === \"object\" && !isTaskIdRef(task) && !isTaskSpec(task))\n )\n throw new Error(\n \"openSession needs a task: a bundled task name, a stored task { id, version? } or { instruction, seed?, grader?, metadata? }\",\n );\n const options = opts.options ?? {};\n const unknown = (opts.surfaces ?? []).filter(\n (s) => !(SURFACE_KINDS as readonly string[]).includes(s),\n );\n if (unknown.length)\n throw new Error(\n `Unknown world surfaces: ${unknown.join(\", \")}; choose from ${SURFACE_KINDS.join(\", \")}`,\n );\n const at = slugOrRef.indexOf(\"@\");\n const slug = at === -1 ? slugOrRef : slugOrRef.slice(0, at);\n const state = await apiRequest<WorldSessionState & { reusedWarm: boolean }>(\n options,\n \"POST\",\n \"/api/public/world-sessions\",\n {\n ...(opts.versionId ? { versionId: opts.versionId } : { slug }),\n task,\n ...(opts.reuseWarm === undefined ? {} : { reuseWarm: opts.reuseWarm }),\n ...(opts.surfaces?.length ? { surfaces: opts.surfaces } : {}),\n },\n );\n return new WorldSession(state.sessionId, state, options);\n}\n\n// ── running many tasks at once ───────────────────────────────────────────────\n\nexport type SessionRunResult = {\n /** The task's name, or `inline:<hash>` for an unnamed inline task. */\n task: string;\n sessionId: string;\n reward: number | null;\n rewards: Record<string, number>;\n /** Set when the task threw instead of grading. */\n error?: string;\n};\n\nexport type SessionRunReport = {\n results: SessionRunResult[];\n /** Mean reward over every task, counting failures as 0. */\n mean: number;\n /** True when `mean >= failUnder` (or no gate was set). */\n passed: boolean;\n};\n\n/**\n * RUN MANY TASKS IN PARALLEL, one warm container each.\n *\n * Parallelism against live worlds is the normal case — a suite is a dozen\n * tasks and each needs its own container, because two agents sharing one\n * world state would corrupt both episodes. Every caller was writing the same\n * pool, the same per-task open/ready/toolkit/grade/close, and the same\n * \"don't let one failure kill the run\" logic, so it belongs here:\n *\n * const report = await runSessions({\n * world: \"revenue-ops-sim@main\",\n * tasks, // default: every task in the world\n * concurrency: 4,\n * failUnder: 0.7,\n * agent: async ({ toolkit, instruction }) =>\n * myAgent(toolkit.impls, toolkit.schemas, instruction),\n * });\n *\n * The handler gets a ready session with its toolkit already bound; grading,\n * closing (warm) and aggregation are handled. A task that throws scores 0\n * and records why — the tasks that passed keep their results.\n */\nexport async function runSessions(opts: {\n world: string;\n /** Bundled task names, stored task refs and/or inline task specs\n * (default: every bundled task in the world). */\n tasks?: WorldTaskRef[];\n concurrency?: number;\n failUnder?: number;\n /** Pin every session to one version (default: the world's head). */\n versionId?: string;\n /** Hand the containers back warm for the next run (default: true). */\n keepWarm?: boolean;\n agent: (ctx: {\n session: WorldSession;\n toolkit: WorldToolkit;\n instruction: string;\n /** The task's label — see `SessionRunResult.task`. */\n task: string;\n /** The task as it was given: a bundled name, a stored ref or the\n * inline spec. */\n taskRef: WorldTaskRef;\n }) => Promise<unknown>;\n onResult?: (result: SessionRunResult) => void;\n options?: WorldsClientOptions;\n}): Promise<SessionRunReport> {\n const options = opts.options ?? {};\n const concurrency = Math.max(1, opts.concurrency ?? 3);\n\n let tasks = opts.tasks;\n let versionId = opts.versionId;\n if (!tasks || !versionId) {\n // One resolve for the whole run: every session pins the SAME version, so\n // a push mid-suite cannot split the results across two worlds.\n const { openWorld } = await import(\"./index\");\n const world = await openWorld(opts.world, options);\n tasks = tasks ?? world.tasks.map((t) => t.name);\n versionId = versionId ?? world.version.versionId;\n }\n\n const results: SessionRunResult[] = [];\n let next = 0;\n await Promise.all(\n Array.from({ length: Math.min(concurrency, tasks.length) }, async () => {\n while (next < tasks!.length) {\n const taskRef = tasks![next++];\n let task = taskLabel(taskRef);\n let session: WorldSession | null = null;\n try {\n session = await openSession(opts.world, {\n task: taskRef,\n versionId,\n options,\n });\n task = taskLabel(taskRef, session.taskInfo);\n await session.ready();\n const toolkit = await session.toolkit();\n await opts.agent({\n session,\n toolkit,\n instruction:\n session.instruction ??\n (isTaskSpec(taskRef) ? taskRef.instruction : task),\n task,\n taskRef,\n });\n const graded = await session.grade();\n const result: SessionRunResult = {\n task,\n sessionId: session.sessionId,\n reward: graded.reward,\n rewards: graded.rewards,\n };\n results.push(result);\n opts.onResult?.(result);\n } catch (error) {\n const result: SessionRunResult = {\n task,\n sessionId: session?.sessionId ?? \"\",\n reward: 0,\n rewards: {},\n // An Error with an empty message would read as \"no error\" to any\n // caller checking truthiness; name the type instead.\n error:\n (error instanceof Error ? error.message : String(error)) ||\n (error instanceof Error ? error.name : \"Unknown error\"),\n };\n results.push(result);\n opts.onResult?.(result);\n } finally {\n // Always give the container back — a leaked session bills until the\n // fleet's idle TTL reaps it.\n await session\n ?.close({ keepWarm: opts.keepWarm ?? true })\n .catch(() => undefined);\n }\n }\n }),\n );\n\n const mean =\n results.reduce((sum, r) => sum + (r.reward ?? 0), 0) /\n (results.length || 1);\n return {\n results: results.sort((a, b) => a.task.localeCompare(b.task)),\n mean,\n passed: opts.failUnder === undefined ? true : mean >= opts.failUnder,\n };\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\nimport type { WorldTaskSpec } from \"./session\";\n\n/**\n * STORED WORLD TASKS: a task spec kept by the project, outside any bundle.\n *\n * An inline task (`openSession(world, { task: { instruction, … } })`) belongs\n * to one session. A stored task is the same spec as a named, versioned\n * project resource: create it once, open as many sessions on it as you like\n * with `{ task: { id } }`, and every grade attributes back to the task and\n * its version. Updating the spec never rewrites history — it appends a\n * version, and a session opened on `{ id, version: 2 }` keeps running v2\n * after v3 exists.\n *\n * const task = await createTask({\n * name: \"refund-late-invoice\",\n * world: \"acme-billing\",\n * spec: { instruction: \"…\", seed: {…}, grader: {…} },\n * });\n * const session = await openSession(\"acme-billing\", { task: { id: task.id } });\n *\n * Tasks are project-scoped: another project's task id is not found (404),\n * never forbidden. `world` pins a task to one world's slug (validated against\n * that world's contract); null leaves it usable with any world.\n */\n\nexport type WorldTaskSummary = {\n id: string;\n name: string;\n world: string | null;\n version: number;\n hash: string;\n spec: WorldTaskSpec;\n createdAt: string;\n updatedAt: string;\n createdBy: string;\n updatedBy: string;\n /** On create, when the task is pinned to a world of a deprecated shape (an\n * api bundle): what to run instead. A retired shape is refused. */\n deprecations?: { code: string; message: string; replacement: string }[];\n};\n\nexport type WorldTaskVersionSummary = {\n version: number;\n hash: string;\n createdAt: string;\n createdBy: string;\n message: string | null;\n};\n\nexport type WorldTaskDetail = WorldTaskSummary & {\n versions: WorldTaskVersionSummary[];\n};\n\nexport type WorldTaskPage = {\n tasks: WorldTaskSummary[];\n meta: { page: number; limit: number; totalItems: number; totalPages: number };\n};\n\nexport type WorldTaskValidation = {\n taskId: string;\n version: number;\n /** The world version the task was checked against. */\n versionId: string;\n ok: boolean;\n /** `entities` when the world's contract was read and every seed and check\n * entity was matched against it; `none` when the version has no contract\n * to check (a mock-tools world), in which case `ok` says only that the\n * version exists and is READY. */\n checked: \"entities\" | \"none\";\n problems: string[];\n entities: string[] | null;\n};\n\nconst TASKS = \"/api/public/world-tasks\";\nconst taskRoute = (id: string) => `${TASKS}/${encodeURIComponent(id)}`;\n\nconst compact = (body: Record<string, unknown>) =>\n Object.fromEntries(Object.entries(body).filter(([, v]) => v !== undefined));\n\n/** Store a task. `name` defaults to `spec.name`; one of the two is needed. */\nexport async function createTask(\n input: {\n spec: WorldTaskSpec;\n name?: string;\n world?: string | null;\n message?: string;\n },\n options: WorldsClientOptions = {},\n): Promise<WorldTaskSummary> {\n return apiRequest<WorldTaskSummary>(\n options,\n \"POST\",\n TASKS,\n compact({\n spec: input.spec,\n name: input.name,\n world: input.world,\n message: input.message,\n }),\n );\n}\n\n/** Change a task. A new `spec` becomes the next version (the old ones stay\n * readable and openable); `name` and `world` change in place. */\nexport async function updateTask(\n taskId: string,\n input: {\n spec?: WorldTaskSpec;\n name?: string;\n world?: string | null;\n message?: string;\n },\n options: WorldsClientOptions = {},\n): Promise<WorldTaskSummary> {\n if (\n input.spec === undefined &&\n input.name === undefined &&\n input.world === undefined\n )\n throw new Error(\"updateTask: nothing to update — pass spec, name or world\");\n return apiRequest<WorldTaskSummary>(\n options,\n \"PATCH\",\n taskRoute(taskId),\n compact({\n spec: input.spec,\n name: input.name,\n world: input.world,\n message: input.message,\n }),\n );\n}\n\n/** The project's tasks, newest change first. `world` keeps only tasks\n * pinned to that slug; `metadata` keeps tasks whose spec metadata carries\n * every given key/value (`{ externalUserId: \"u_42\" }`). */\nexport async function listTasks(\n filter: {\n world?: string;\n metadata?: Record<string, string>;\n page?: number;\n limit?: number;\n } = {},\n options: WorldsClientOptions = {},\n): Promise<WorldTaskPage> {\n const params = new URLSearchParams();\n if (filter.world) params.set(\"world\", filter.world);\n if (filter.page !== undefined) params.set(\"page\", String(filter.page));\n if (filter.limit !== undefined) params.set(\"limit\", String(filter.limit));\n for (const [key, value] of Object.entries(filter.metadata ?? {}))\n params.set(`metadata.${key}`, value);\n const query = params.toString();\n return apiRequest<WorldTaskPage>(\n options,\n \"GET\",\n query ? `${TASKS}?${query}` : TASKS,\n );\n}\n\n/** One task with its version history; `version` reads that version's spec\n * instead of the current one. */\nexport async function getTask(\n taskId: string,\n opts: { version?: number } = {},\n options: WorldsClientOptions = {},\n): Promise<WorldTaskDetail> {\n const query =\n opts.version === undefined ? \"\" : `?version=${String(opts.version)}`;\n return apiRequest<WorldTaskDetail>(\n options,\n \"GET\",\n `${taskRoute(taskId)}${query}`,\n );\n}\n\n/** Remove a task and every version. Sessions already opened on it keep\n * their copy of the spec. */\nexport async function deleteTask(\n taskId: string,\n options: WorldsClientOptions = {},\n): Promise<{ id: string; name: string }> {\n return apiRequest(options, \"DELETE\", taskRoute(taskId));\n}\n\n/** Check a task against a world version without opening a session: every\n * seed entity and every check's entity must exist in the world's contract.\n * `slug` checks against that world's head, `versionId` against an exact\n * version, neither against the task's own `world` pin. */\nexport async function validateTask(\n taskId: string,\n target: { version?: number; slug?: string; versionId?: string } = {},\n options: WorldsClientOptions = {},\n): Promise<WorldTaskValidation> {\n return apiRequest<WorldTaskValidation>(\n options,\n \"POST\",\n `${taskRoute(taskId)}/validate`,\n compact({\n version: target.version,\n slug: target.slug,\n versionId: target.versionId,\n }),\n );\n}\n","import { createHash } from \"node:crypto\";\nimport { gzipSync, gunzipSync } from \"node:zlib\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\n\n/**\n * The working-dir half of the TS CLI: push / pull / checkout / status /\n * branch / tag / propose — a faithful port of the Python client\n * (`gatewaysdk/benchmark_hub/client.py` + `_archive.py`).\n *\n * LOCKSTEP WARNING — the content hash is the version's identity and is\n * byte-compatible with Prime Intellect. It now has FOUR implementations that\n * must stay identical: worker `environmentAgent/tar.ts`, web\n * `benchmark-hub/server/benchmarkContentHash.ts`, Python `_archive.py`, and\n * this file. This one is a line-for-line port of the WEB TypeScript\n * implementation (same language, same crypto) — if the rule ever changes,\n * change all four or push identity splits by client.\n *\n * One deliberate refusal, same policy as the web upload path: a bundle with\n * a ROOT `.gitignore` is refused rather than mis-hashed — the Python CLI\n * honors it via `gitignore_parser`, and an imperfect reimplementation here\n * would produce a wrong, Prime-incompatible hash silently.\n */\n\nexport const DEFAULT_BRANCH = \"main\";\nconst META_RELPATH = path.join(\".gateway\", \".env-metadata.json\");\nconst SKIP_DIRS = new Set([\n \".git\",\n \"__pycache__\",\n \"node_modules\",\n \".venv\",\n \".mypy_cache\",\n \"dist\",\n \"build\",\n \"outputs\",\n]);\nconst ROOT_EXCLUDED_DIRS = new Set([\"dist\", \"build\", \"outputs\", \"__pycache__\"]);\n\n/** Gateway-only root markers that widen collection to every ordinary root\n * file. The FOURTH copy of this list (python SDK `_archive.py`, web\n * `benchmarkContentHash.ts`, worker `tar.ts`, and here) — all four MUST stay\n * identical or the same tree hashes differently per pusher. This copy\n * missing `gateway-api-world.toml` is exactly how an api world pushed from\n * TS landed on the hub with no OpenAPI contract and no marker: the root\n * files never entered the manifest, and nothing downstream could tell. */\nconst BROAD_ROOT_MARKERS = [\"gateway-env.toml\", \"gateway-api-world.toml\"];\n\n// ── content-hash rules (port of web benchmarkContentHash.ts) ───────────────\n\nfunction isExcludedDirComponent(component: string): boolean {\n return (\n component.startsWith(\".\") ||\n ROOT_EXCLUDED_DIRS.has(component) ||\n component.endsWith(\".egg-info\")\n );\n}\n\nexport function isIncludedInContentHash(\n relPath: string,\n includeAllRootFiles: boolean,\n): boolean {\n const parts = relPath.split(\"/\");\n const name = parts[parts.length - 1];\n const dirParts = parts.slice(0, -1);\n if (name.startsWith(\".\")) return false;\n if (parts.includes(\"__pycache__\")) return false;\n if (dirParts.length === 0) {\n return (\n includeAllRootFiles ||\n name === \"README.md\" ||\n name === \"pyproject.toml\" ||\n BROAD_ROOT_MARKERS.includes(name) ||\n name.endsWith(\".py\")\n );\n }\n return !dirParts.some(isExcludedDirComponent);\n}\n\n/** The archive-visible files of a working dir, as sorted relpaths. Throws on\n * a root .gitignore (see the header). */\nexport function collectArchiveRelPaths(dir: string): string[] {\n if (fs.existsSync(path.join(dir, \".gitignore\"))) {\n throw new Error(\n \"This bundle has a root .gitignore, which the Python CLI honors via \" +\n \"gitignore_parser. Reimplementing that imperfectly here would \" +\n \"silently produce a different content hash, so the TS CLI refuses. \" +\n \"Remove the .gitignore (or bake its effect into the tree) and retry.\",\n );\n }\n const out: string[] = [];\n const includeAllRootFiles = BROAD_ROOT_MARKERS.some((marker) =>\n fs.existsSync(path.join(dir, marker)),\n );\n const walk = (rel: string) => {\n const abs = rel ? path.join(dir, rel) : dir;\n for (const entry of fs.readdirSync(abs, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {\n const childRel = rel ? `${rel}/${entry.name}` : entry.name;\n if (entry.isDirectory()) {\n if (!isExcludedDirComponent(entry.name)) walk(childRel);\n } else if (entry.isFile()) {\n if (isIncludedInContentHash(childRel, includeAllRootFiles)) {\n out.push(childRel);\n }\n }\n }\n };\n walk(\"\");\n return out.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));\n}\n\nexport function computeContentHash(dir: string): string {\n const hasher = createHash(\"sha256\");\n for (const relPath of collectArchiveRelPaths(dir)) {\n hasher.update(Buffer.from(`file:${relPath}`, \"utf-8\"));\n hasher.update(fs.readFileSync(path.join(dir, relPath)));\n }\n return hasher.digest(\"hex\");\n}\n\n// ── deterministic tar.gz writer ─────────────────────────────────────────────\n\nfunction octal(value: number, length: number): Buffer {\n return Buffer.from(value.toString(8).padStart(length - 1, \"0\") + \"\\0\", \"ascii\");\n}\n\nfunction tarHeader(name: string, size: number): Buffer {\n const header = Buffer.alloc(512);\n header.write(name, 0, 100, \"utf-8\");\n octal(0o644, 8).copy(header, 100); // mode\n octal(0, 8).copy(header, 108); // uid\n octal(0, 8).copy(header, 116); // gid\n octal(size, 12).copy(header, 124);\n octal(0, 12).copy(header, 136); // mtime = 0 (deterministic)\n header.write(\" \", 148, \"ascii\"); // checksum placeholder = spaces\n header.write(\"0\", 156, \"ascii\"); // regular file\n header.write(\"ustar\", 257, \"ascii\");\n header.write(\"00\", 263, \"ascii\");\n let sum = 0;\n for (const byte of header) sum += byte;\n header.write(sum.toString(8).padStart(6, \"0\") + \"\\0 \", 148, \"ascii\");\n return header;\n}\n\nfunction tarMember(name: string, payload: Buffer): Buffer[] {\n const parts: Buffer[] = [];\n const nameBytes = Buffer.byteLength(name, \"utf-8\");\n if (nameBytes > 100) {\n // GNU long name: an 'L' member whose body is the real name.\n const body = Buffer.from(name + \"\\0\", \"utf-8\");\n const lHeader = tarHeader(\"././@LongLink\", body.length);\n lHeader.write(\"L\", 156, \"ascii\");\n let sum = 0;\n lHeader.write(\" \", 148, \"ascii\");\n for (const byte of lHeader) sum += byte;\n lHeader.write(sum.toString(8).padStart(6, \"0\") + \"\\0 \", 148, \"ascii\");\n parts.push(lHeader, body);\n const pad = body.length % 512 === 0 ? 0 : 512 - (body.length % 512);\n if (pad) parts.push(Buffer.alloc(pad));\n parts.push(tarHeader(name.slice(0, 100), payload.length));\n } else {\n parts.push(tarHeader(name, payload.length));\n }\n parts.push(payload);\n const pad = payload.length % 512 === 0 ? 0 : 512 - (payload.length % 512);\n if (pad) parts.push(Buffer.alloc(pad));\n return parts;\n}\n\n/** A deterministic .tar.gz of the source files (node's gzip stamps no mtime,\n * matching the Python's mtime=0 gzip). */\nexport function buildSourceTarball(dir: string): Buffer {\n const parts: Buffer[] = [];\n for (const relPath of collectArchiveRelPaths(dir)) {\n parts.push(...tarMember(relPath, fs.readFileSync(path.join(dir, relPath))));\n }\n parts.push(Buffer.alloc(1024)); // end-of-archive\n return gzipSync(Buffer.concat(parts), { level: 9 });\n}\n\n// ── local metadata (.gateway/.env-metadata.json) ────────────────────────────\n\nexport type LocalMeta = Record<string, unknown> & {\n slug?: string;\n branch?: string;\n versionId?: string;\n contentHash?: string;\n baseFiles?: Record<string, string>;\n};\n\nexport function readLocalMeta(dir: string): LocalMeta | null {\n try {\n const raw = fs.readFileSync(path.join(dir, META_RELPATH), \"utf-8\");\n const parsed = JSON.parse(raw);\n return parsed && typeof parsed === \"object\" ? (parsed as LocalMeta) : null;\n } catch {\n return null;\n }\n}\n\nexport function writeLocalMeta(dir: string, meta: LocalMeta): void {\n fs.mkdirSync(path.join(dir, \".gateway\"), { recursive: true });\n fs.writeFileSync(path.join(dir, META_RELPATH), JSON.stringify(meta, null, 2));\n}\n\nexport function snapshotTreeHashes(dir: string): Record<string, string> {\n const out: Record<string, string> = {};\n for (const relPath of collectArchiveRelPaths(dir)) {\n out[relPath] = createHash(\"sha256\")\n .update(fs.readFileSync(path.join(dir, relPath)))\n .digest(\"hex\");\n }\n return out;\n}\n\nexport function localTreeState(dir: string): {\n meta: LocalMeta | null;\n dirty: string[];\n clean: boolean;\n} {\n const meta = readLocalMeta(dir);\n const base = meta?.baseFiles;\n if (!base || typeof base !== \"object\") {\n return { meta, dirty: [], clean: false };\n }\n const now = snapshotTreeHashes(dir);\n const dirty = new Set<string>();\n for (const [p, h] of Object.entries(now)) if (base[p] !== h) dirty.add(p);\n for (const p of Object.keys(base)) if (!(p in now)) dirty.add(p);\n return { meta, dirty: [...dirty].sort(), clean: dirty.size === 0 };\n}\n\n// ── protocol helpers ─────────────────────────────────────────────────────────\n\nconst sha256b64 = (data: Buffer) =>\n createHash(\"sha256\").update(data).digest(\"base64\");\n\nfunction readPyproject(dir: string): { name?: string; version?: string } {\n try {\n const text = fs.readFileSync(path.join(dir, \"pyproject.toml\"), \"utf-8\");\n // Minimal [project] reads — name and version only, quoted single-line form.\n const section = /\\[project\\]([\\s\\S]*?)(\\n\\[|$)/.exec(text)?.[1] ?? \"\";\n const name = /\\bname\\s*=\\s*\"([^\"]+)\"/.exec(section)?.[1];\n const version = /\\bversion\\s*=\\s*\"([^\"]+)\"/.exec(section)?.[1];\n return { name, version };\n } catch {\n return {};\n }\n}\n\n/** A schema world's own version: `x-gateway.package.version` of its contract\n * (`schema/world.json`, or `server/world/schema/world.json` in an api bundle).\n * What a connector world has instead of a pyproject, so its versions read\n * \"1.0.0\" rather than \"unversioned\" on the platform. */\nfunction readWorldContractVersion(dir: string): { name?: string; version?: string } {\n for (const rel of [\"schema/world.json\", path.join(\"server\", \"world\", \"schema\", \"world.json\")]) {\n try {\n const parsed = JSON.parse(fs.readFileSync(path.join(dir, rel), \"utf-8\")) as {\n \"x-gateway\"?: { package?: { id?: string; version?: string } };\n };\n const pkg = parsed[\"x-gateway\"]?.package;\n if (pkg?.version) return { name: pkg.id, version: pkg.version };\n } catch {\n // not a schema world, or not at this root\n }\n }\n return {};\n}\n\nfunction buildFileManifest(\n dir: string,\n): { path: string; isDirectory: boolean; size: number; sha256: string }[] {\n const entries: { path: string; isDirectory: boolean; size: number; sha256: string }[] = [];\n const walk = (rel: string) => {\n const abs = rel ? path.join(dir, rel) : dir;\n for (const entry of fs.readdirSync(abs, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {\n const childRel = rel ? `${rel}/${entry.name}` : entry.name;\n if (entry.isDirectory()) {\n if (!SKIP_DIRS.has(entry.name) && !entry.name.endsWith(\".egg-info\")) {\n walk(childRel);\n }\n } else if (entry.isFile()) {\n const payload = fs.readFileSync(path.join(dir, childRel));\n entries.push({\n path: childRel,\n isDirectory: false,\n size: payload.length,\n sha256: createHash(\"sha256\").update(payload).digest(\"hex\"),\n });\n }\n }\n };\n walk(\"\");\n return entries;\n}\n\nasync function putObject(url: string, data: Buffer, shaB64: string): Promise<void> {\n const resp = await fetch(url, {\n method: \"PUT\",\n headers: {\n \"Content-Type\": \"application/gzip\",\n \"x-amz-checksum-sha256\": shaB64,\n },\n body: new Uint8Array(data),\n });\n if (!resp.ok) {\n throw new Error(`object PUT -> ${resp.status}: ${(await resp.text()).slice(0, 300)}`);\n }\n}\n\n// ── the workflows ────────────────────────────────────────────────────────────\n\nexport async function push(\n dir: string,\n opts: {\n slug?: string;\n branch?: string;\n force?: boolean;\n message?: string;\n author?: string;\n /** Push on top of this version instead of the local meta's base — what a\n * CI checkout (which has no local meta) passes after resolving the\n * branch tip, so re-validating a PR replaces its own previous push\n * instead of 409ing against it. */\n baseVersionId?: string | null;\n /** Container metadata recorded on resolve — the Python CLI's --name,\n * --description, --tag and --visibility. */\n name?: string;\n description?: string;\n tags?: string[];\n visibility?: string;\n /** Pre-built OCI image ref for image/agentic envs (recorded on the version). */\n imageRef?: string;\n options?: WorldsClientOptions;\n } = {},\n): Promise<{\n containerId: string;\n slug: string;\n versionId: string;\n contentHash: string;\n branch: string;\n state: string | null;\n alreadyUploaded: boolean;\n}> {\n const options = opts.options ?? {};\n if (!fs.statSync(dir).isDirectory()) throw new Error(`Not a directory: ${dir}`);\n const localMeta = readLocalMeta(dir) ?? {};\n const branch = opts.branch ?? (localMeta.branch as string | undefined) ?? DEFAULT_BRANCH;\n const baseVersionId = opts.baseVersionId ?? localMeta.versionId ?? null;\n\n const contentHash = computeContentHash(dir);\n const pyproject = readPyproject(dir);\n // A connector world carries its version on its contract, not a pyproject.\n const contractVersion = pyproject.version ? undefined : readWorldContractVersion(dir).version;\n if (contractVersion) pyproject.version = contractVersion;\n const slug = opts.slug ?? pyproject.name ?? path.basename(path.resolve(dir));\n\n const resolve = await apiRequest<{ containerId: string }>(\n options,\n \"POST\",\n \"/api/public/benchmark-containers/resolve\",\n {\n slug,\n name: opts.name ?? pyproject.name ?? slug,\n ...(opts.description ? { description: opts.description } : {}),\n ...(opts.tags?.length ? { tags: opts.tags } : {}),\n ...(opts.visibility ? { visibility: opts.visibility } : {}),\n },\n );\n\n const tarball = buildSourceTarball(dir);\n const bundleSha256 = sha256b64(tarball);\n\n const version = await apiRequest<{\n versionId: string;\n uploadUrl?: string;\n alreadyUploaded?: boolean;\n }>(options, \"POST\", \"/api/public/benchmark-containers/versions\", {\n containerId: resolve.containerId,\n contentHash,\n bundleSha256,\n bundleSizeBytes: tarball.length,\n ...(pyproject.version ? { semanticVersion: pyproject.version } : {}),\n pyprojectMeta: pyproject,\n fileManifest: buildFileManifest(dir),\n branch,\n baseVersionId,\n ...(opts.force ? { force: true } : {}),\n ...(opts.message ? { changeReason: opts.message } : {}),\n ...(opts.author ? { author: opts.author } : {}),\n ...(opts.imageRef ? { imageRef: opts.imageRef } : {}),\n });\n\n if (version.uploadUrl) await putObject(version.uploadUrl, tarball, bundleSha256);\n\n const final = await apiRequest<{ state?: string; branch?: string }>(\n options,\n \"POST\",\n `/api/public/benchmark-containers/versions/${version.versionId}/finalize`,\n { branch, baseVersionId, ...(opts.force ? { force: true } : {}) },\n );\n\n writeLocalMeta(dir, {\n ...localMeta,\n slug,\n ref: branch,\n branch,\n versionId: version.versionId,\n contentHash,\n semanticVersion: pyproject.version,\n forkedFromVersionId: baseVersionId,\n baseFiles: snapshotTreeHashes(dir),\n });\n return {\n containerId: resolve.containerId,\n slug,\n versionId: version.versionId,\n contentHash,\n branch: final.branch ?? branch,\n state: final.state ?? null,\n alreadyUploaded: Boolean(version.alreadyUploaded),\n };\n}\n\n/** Extract a downloaded bundle into `dir` (paths sanitized). */\nfunction extractBundle(bundle: Buffer, dir: string): number {\n const tar = gunzipSync(bundle);\n let offset = 0;\n let longName: string | null = null;\n let written = 0;\n while (offset + 512 <= tar.length) {\n const header = tar.subarray(offset, offset + 512);\n offset += 512;\n if (header.every((b) => b === 0)) break;\n const rawName = header.subarray(0, 100).toString(\"utf-8\").replace(/\\0.*$/, \"\");\n const size = parseInt(header.subarray(124, 136).toString(\"ascii\").replace(/\\0.*$/, \"\").trim(), 8) || 0;\n const typeflag = header.subarray(156, 157).toString(\"ascii\");\n const body = tar.subarray(offset, offset + size);\n offset += size + (size % 512 === 0 ? 0 : 512 - (size % 512));\n if (typeflag === \"L\") {\n longName = body.toString(\"utf-8\").replace(/\\0.*$/, \"\");\n continue;\n }\n const name = (longName ?? rawName).replace(/^\\.\\//, \"\");\n longName = null;\n if (typeflag !== \"0\" && typeflag !== \"\") continue;\n // Safe extract: no absolute paths, no traversal.\n if (name.startsWith(\"/\") || name.split(\"/\").includes(\"..\")) continue;\n const target = path.join(dir, name);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n fs.writeFileSync(target, body);\n written++;\n }\n return written;\n}\n\nexport async function pull(\n slugRef: string,\n target?: string,\n options: WorldsClientOptions = {},\n): Promise<{ slug: string; dir: string; versionId: string; files: number }> {\n const at = slugRef.indexOf(\"@\");\n const slug = at === -1 ? slugRef : slugRef.slice(0, at);\n const ref = at === -1 ? \"latest\" : slugRef.slice(at + 1);\n\n const details = await apiRequest<{\n versionId: string;\n contentHash: string;\n semanticVersion?: string | null;\n downloadUrl?: string;\n bundleSha256?: string;\n }>(options, \"POST\", \"/api/public/benchmark-containers/resolve-version\", {\n slug,\n ref,\n });\n if (!details.downloadUrl) {\n throw new Error(`${slug}@${ref} resolved but has no uploaded bundle`);\n }\n\n let dir = target ?? path.join(process.cwd(), slug);\n if (!target) {\n let i = 1;\n const base = dir;\n while (fs.existsSync(dir)) dir = `${base}-${i++}`;\n }\n fs.mkdirSync(dir, { recursive: true });\n\n const resp = await fetch(details.downloadUrl);\n if (!resp.ok) throw new Error(`bundle download -> ${resp.status}`);\n const bundle = Buffer.from(await resp.arrayBuffer());\n if (details.bundleSha256 && sha256b64(bundle) !== details.bundleSha256) {\n throw new Error(\n `bundle integrity check failed for ${slug}@${ref}: downloaded sha256 != recorded bundleSha256`,\n );\n }\n\n const files = extractBundle(bundle, dir);\n const branch = ref === \"latest\" || /^\\d|^[0-9a-f]{8,}$/.test(ref) ? DEFAULT_BRANCH : ref;\n writeLocalMeta(dir, {\n slug,\n ref,\n branch,\n versionId: details.versionId,\n contentHash: details.contentHash,\n semanticVersion: details.semanticVersion ?? undefined,\n baseFiles: snapshotTreeHashes(dir),\n });\n return { slug, dir, versionId: details.versionId, files };\n}\n\nexport async function propose(\n dir: string,\n opts: { title: string; reason: string; targetBranch?: string; options?: WorldsClientOptions },\n): Promise<{ proposalId: string }> {\n const meta = readLocalMeta(dir);\n if (!meta?.slug || !meta.baseFiles) {\n throw new Error(\"This dir has no pull/push base — run pull first, then edit, then propose.\");\n }\n const state = localTreeState(dir);\n if (state.clean) throw new Error(\"Nothing to propose — the tree matches its base.\");\n const changes = state.dirty.map((relPath) => {\n const abs = path.join(dir, relPath);\n if (!fs.existsSync(abs)) return { path: relPath, action: \"delete\" as const };\n return {\n path: relPath,\n action: \"write\" as const,\n newContent: fs.readFileSync(abs, \"utf-8\"),\n };\n });\n const res = await apiRequest<{ proposalId: string }>(\n opts.options ?? {},\n \"POST\",\n \"/api/public/benchmark-containers/proposals\",\n {\n slug: meta.slug,\n title: opts.title,\n changeReason: opts.reason,\n baseVersionId: meta.versionId,\n ...(opts.targetBranch ? { targetBranch: opts.targetBranch } : {}),\n changes,\n },\n );\n return res;\n}\n\nexport async function createRef(\n slug: string,\n name: string,\n kind: \"branch\" | \"tag\",\n versionId?: string,\n options: WorldsClientOptions = {},\n): Promise<{ name: string; kind: string; versionId: string }> {\n return apiRequest(options, \"POST\", \"/api/public/benchmark-containers/refs\", {\n slug,\n name,\n kind,\n ...(versionId ? { versionId } : {}),\n });\n}\n","/**\n * PR validation: push the checkout's world source, run it, gate on the graded\n * result — one composed call, because CI should not have to re-derive the\n * choreography from primitives.\n *\n * The differentiating property, stated so it stays true: validation runs the\n * PULL REQUEST'S OWN world source. The push files the checkout as a version on\n * the PR's branch (content-hash dedup makes re-runs cheap), the dispatch pins\n * that version, and the platform resolves the branch back to its open PR — so\n * the run page names the PR and the PR comment names the run. Nothing here\n * validates a standing deployment while pretending to validate the change.\n */\n\nimport {\n apiRequest,\n detectProvenance,\n listRunConfigs,\n waitForRun,\n type RunReport,\n type WorldsClientOptions,\n} from \"./index\";\nimport { push } from \"./hub\";\n\nexport type ValidatedRun = {\n model: string;\n runId: string;\n report: RunReport | null;\n /** Why this run fails the gate, or null when it passes. */\n failure: string | null;\n};\n\nexport type ValidateReport = {\n ok: boolean;\n slug: string;\n branch: string;\n versionId: string;\n contentHash: string;\n runConfig: { id: string; name: string };\n runs: ValidatedRun[];\n /** A PR-comment-ready summary of the whole validation. */\n markdown: string;\n};\n\nfunction fmtScore(score: number | null): string {\n return score === null ? \"no score\" : score.toFixed(3);\n}\n\nfunction buildMarkdown(\n report: Omit<ValidateReport, \"markdown\">,\n minScore: number | null,\n source?: { repoUrl?: string; commit?: string },\n): string {\n const lines: string[] = [];\n lines.push(\n `### World validation ${report.ok ? \"passed\" : \"failed\"} — \\`${report.slug}@${report.branch}\\``,\n );\n lines.push(\"\");\n // Name the exact source that ran: the commit on GitHub when we know it,\n // always the content hash the platform pinned.\n const commitLink =\n source?.repoUrl && source?.commit\n ? `[\\`${source.commit.slice(0, 12)}\\`](${source.repoUrl}/commit/${source.commit})`\n : null;\n lines.push(\n `Ran the pull request's own world source` +\n (commitLink ? ` (${commitLink} on \\`${report.branch}\\`` : ` (`) +\n `${commitLink ? \", \" : \"\"}pinned as \\`${report.contentHash.slice(0, 12)}\\`) ` +\n `through run config **${report.runConfig.name}**` +\n (minScore !== null ? `, gating at score ≥ ${minScore}.` : \".\"),\n );\n lines.push(\"\");\n lines.push(\"| Model | Status | Score | Run |\");\n lines.push(\"| --- | --- | ---: | --- |\");\n for (const run of report.runs) {\n const r = run.report;\n const link = r?.url ? `[open](${r.url})` : \"—\";\n const status = run.failure\n ? `❌ ${run.failure}`\n : `✅ ${r?.status ?? \"COMPLETED\"}`;\n lines.push(\n `| \\`${run.model}\\` | ${status} | ${fmtScore(r?.score ?? null)} | ${link} |`,\n );\n }\n const taskRows = report.runs.flatMap((run) =>\n (run.report?.samples ?? []).map((sample) => ({\n model: run.model,\n task: sample.task ?? \"?\",\n reward: sample.reward,\n })),\n );\n // Every scenario, in the open: a validation whose per-scenario grades hide\n // behind a fold reads as one opaque number. Fold only when the table is\n // genuinely long.\n if (taskRows.length > 0) {\n const fold = taskRows.length > 12;\n lines.push(\"\");\n if (fold) {\n lines.push(\n `<details><summary>Per-scenario rewards (${taskRows.length})</summary>`,\n );\n lines.push(\"\");\n } else {\n lines.push(`**Scenarios (${taskRows.length})**`);\n lines.push(\"\");\n }\n lines.push(\"| Scenario | Model | Reward |\");\n lines.push(\"| --- | --- | ---: |\");\n for (const row of taskRows) {\n lines.push(\n `| ${row.task} | \\`${row.model}\\` | ${row.reward === null ? \"no score\" : row.reward.toFixed(2)} |`,\n );\n }\n if (fold) {\n lines.push(\"\");\n lines.push(\"</details>\");\n }\n }\n return lines.join(\"\\n\");\n}\n\n/**\n * Push `dir` on the current (or given) branch, dispatch the named run config\n * against the pushed version, wait for every run, and gate.\n *\n * The gate: every dispatch accepted, every run terminal COMPLETED, and — when\n * `minScore` is set — every run's score meets it. A run with NO score fails a\n * score gate rather than passing it: null is \"not scored\", never 0 and never\n * fine.\n */\nexport async function validateWorld(\n dir: string,\n opts: {\n slug?: string;\n runConfig: string;\n branch?: string;\n minScore?: number | null;\n timeoutMinutes?: number;\n onProgress?: (line: string) => void;\n options?: WorldsClientOptions;\n },\n): Promise<ValidateReport> {\n const options = opts.options ?? {};\n const progress = opts.onProgress ?? (() => {});\n const minScore = opts.minScore ?? null;\n\n const provenance = detectProvenance();\n const branch = opts.branch ?? provenance.branch;\n if (!branch)\n throw new Error(\n \"No branch to validate on: pass --branch or run inside a git checkout / GitHub Actions.\",\n );\n\n progress(`pushing ${dir} as ${opts.slug ?? \"(pyproject name)\"}@${branch}…`);\n // CI checkouts carry no local push meta, so a re-validation would 409\n // against the branch tip its own previous run created. Validation's\n // semantics are \"this branch's tip BECOMES the PR's source\": resolve the\n // current tip and push on top of it. A branch that does not exist yet\n // resolves to no base, which is a fresh branch — also correct.\n let tipVersionId: string | null = null;\n if (opts.slug) {\n try {\n const tip = await apiRequest<{ versionId?: string }>(\n options,\n \"POST\",\n \"/api/public/benchmark-containers/resolve-version\",\n { slug: opts.slug, ref: branch },\n );\n tipVersionId = tip.versionId ?? null;\n } catch {\n tipVersionId = null;\n }\n }\n const pushed = await push(dir, {\n slug: opts.slug,\n branch,\n baseVersionId: tipVersionId,\n message: `PR validation push (${provenance.commit?.slice(0, 12) ?? \"local\"})`,\n ...(provenance.actor?.name ? { author: provenance.actor.name } : {}),\n options,\n });\n progress(`pushed version ${pushed.versionId} (${pushed.contentHash.slice(0, 12)})`);\n\n // Resolve the run config by name (the stable handle CI configures) or id.\n const configs = await listRunConfigs(options);\n const runConfig =\n configs.find((c) => c.id === opts.runConfig) ??\n configs.find((c) => c.name === opts.runConfig);\n if (!runConfig) {\n const known = configs.map((c) => c.name).join(\", \") || \"(none)\";\n throw new Error(\n `Run config \"${opts.runConfig}\" not found in this project. Have: ${known}`,\n );\n }\n\n progress(`dispatching run config \"${runConfig.name}\" (${runConfig.models.join(\", \")})…`);\n const dispatched = await apiRequest<{\n versionLabel: string;\n runs: { model: string; runId: string; ok: boolean; error?: string }[];\n }>(options, \"POST\", \"/api/public/benchmark-containers/run-configs/dispatch\", {\n runConfigId: runConfig.id,\n versionId: pushed.versionId,\n ...provenance,\n });\n\n // The run's platform page. New deployments return it on the run report\n // (`url`); against an older deployment we build the same page from the\n // evaluation id, because a PR comment that cannot link the run defeats\n // the point of the comment.\n const host = (\n options.host ??\n process.env.GATEWAY_HOST ??\n \"https://withgateway.ai\"\n ).replace(/\\/+$/, \"\");\n let projectId: string | null = null;\n try {\n const projects = await apiRequest<{ data?: { id?: string }[] }>(\n options,\n \"GET\",\n \"/api/public/projects\",\n );\n projectId = projects.data?.[0]?.id ?? null;\n } catch {\n projectId = null;\n }\n const fallbackUrl = (report: RunReport): string | null => {\n if (report.url) return report.url;\n const evaluationId = report.evaluations[0]?.id;\n return projectId && evaluationId\n ? `${host}/project/${projectId}/environment/runs/${encodeURIComponent(evaluationId)}`\n : null;\n };\n\n const runs: ValidatedRun[] = [];\n for (const run of dispatched.runs) {\n if (!run.ok) {\n runs.push({\n model: run.model,\n runId: run.runId,\n report: null,\n failure: `dispatch failed: ${run.error ?? \"unknown error\"}`,\n });\n continue;\n }\n progress(`waiting on ${run.model} (run ${run.runId})…`);\n let report: RunReport | null = null;\n let failure: string | null = null;\n try {\n report = await waitForRun(run.runId, {\n timeoutMinutes: opts.timeoutMinutes ?? 45,\n options,\n onTick: (r) =>\n progress(\n `…${run.model}: ${r.status.toLowerCase()} (${r.shardsCompleted ?? 0}/${r.parallelism} shards)`,\n ),\n });\n report = { ...report, url: fallbackUrl(report) };\n if (report.status.toUpperCase() !== \"COMPLETED\") {\n failure = report.status;\n } else if (minScore !== null) {\n if (report.score === null) failure = \"completed without a score\";\n else if (report.score < minScore)\n failure = `score ${fmtScore(report.score)} < ${minScore}`;\n }\n } catch (error) {\n failure = error instanceof Error ? error.message : String(error);\n }\n runs.push({ model: run.model, runId: run.runId, report, failure });\n }\n\n const base = {\n ok: runs.length > 0 && runs.every((r) => r.failure === null),\n slug: pushed.slug,\n branch,\n versionId: pushed.versionId,\n contentHash: pushed.contentHash,\n runConfig: { id: runConfig.id, name: runConfig.name },\n runs,\n };\n return {\n ...base,\n markdown: buildMarkdown(base, minScore, {\n repoUrl: provenance.repoUrl,\n commit: provenance.commit,\n }),\n };\n}\n","/**\n * `describeWorld(slug)` — what a world holds and how each field is stored,\n * from `GET /api/public/worlds/{slug}`: the entities (primary key, unique\n * keys, relationships, row count, fields with their `[redact]` policy) and\n * the `[redact]` table itself, so `storedForms(world, field, plaintext)`\n * can compute a lookup value without Python. The CLI twin is\n * `gateway worlds describe <slug>`; for a directory the CLI asks the schema\n * runtime instead and merges the same shape.\n */\n\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\nimport type { RedactPolicy, Redaction } from \"./redaction\";\n\nexport type WorldField = {\n name: string;\n type: string | null;\n required: boolean;\n /** How the store holds it; null means in the clear (queryable by plaintext as given). */\n redaction: Redaction | null;\n};\n\nexport type WorldRelationship = {\n fields: string[];\n target: string;\n on_delete?: string;\n};\n\nexport type WorldEntityMapping = {\n localEntity: string;\n localField: string;\n depEntity: string;\n depField: string;\n /** A closed set, applied left to right before each world's own redaction. */\n transform: string[];\n};\n\nexport type WorldDependency = {\n alias: string;\n dependsOn: { slug: string | null; versionId: string };\n task: string | null;\n tools: string[];\n entities: WorldEntityMapping[];\n};\n\nexport type WorldEntity = {\n name: string;\n primaryKey: string[];\n unique: string[][];\n relationships: WorldRelationship[];\n /** Rows in the head version; null when the platform does not count this kind. */\n rowCount: number | null;\n fields: WorldField[];\n};\n\nexport type WorldDescription = {\n slug: string;\n name: string;\n description: string | null;\n kind: string;\n version: { id: string; contentHash: string; semanticVersion: string | null };\n url: string;\n hostedUrl: string | null;\n tools: { name: string; signature: string; doc: string | null }[];\n taskCount: number;\n links: { tasks: string; sessions: string };\n /** World-to-world links from `[dependencies]`, resolved at commit, with the\n * entity mappings `--across` follows. */\n dependencies?: WorldDependency[];\n entities: WorldEntity[];\n redact: RedactPolicy | null;\n};\n\n/** The world's head version, described. The route reads the head only, so a\n * `slug@ref` is refused rather than silently served as the head. */\nexport async function describeWorld(\n slug: string,\n options: WorldsClientOptions = {},\n): Promise<WorldDescription> {\n if (slug.includes(\"@\"))\n throw new Error(\n `describeWorld reads a world's head version: pass the slug without @ref (got ${slug})`,\n );\n return apiRequest<WorldDescription>(\n options,\n \"GET\",\n `/api/public/worlds/${encodeURIComponent(slug)}`,\n );\n}\n","/**\n * JSON as the Python CLI sees it, so both CLIs write the same bytes.\n *\n * `JSON.parse` + `JSON.stringify` are not enough for parity with\n * `json.loads` + `json.dumps(separators=(\",\", \":\"), ensure_ascii=False)`:\n * JavaScript loses `1.0` vs `1` (Python keeps the float), rounds integers past\n * 2^53, moves integer-like keys to the front of an object, and spells\n * exponents differently (`1e-7` vs `1e-07`). Here a number keeps its source\n * text and its Python type, an object is a Map (insertion order, always), and\n * `dumps` renders exactly what CPython renders.\n */\n\nexport class JsonNumber {\n /** The lexeme as it appeared, e.g. \"1.0\", \"-0\", \"1e21\". */\n constructor(readonly text: string) {}\n /** A float in Python's eyes: a fraction, an exponent, or a non-finite literal. */\n get isFloat(): boolean {\n return /[.eE]/.test(this.text) || /[nN]/.test(this.text);\n }\n get value(): number {\n return Number(this.text);\n }\n}\n\nexport type JsonObject = Map<string, JsonValue>;\nexport type JsonValue = null | boolean | string | JsonNumber | JsonValue[] | JsonObject;\n\nexport class JsonSyntaxError extends Error {}\n\nexport const isObject = (value: JsonValue | undefined): value is JsonObject => value instanceof Map;\n\n// ------------------------------------------------------------------ parsing\n\n/** Parse one JSON text (a line, a row, a document) into the model above.\n * Accepts what `json.loads` accepts, including NaN/Infinity literals. */\nexport function parseJson(text: string): JsonValue {\n const p = new Parser(text);\n p.skipWs();\n const value = p.value();\n p.skipWs();\n if (p.i < text.length) throw new JsonSyntaxError(`Extra data at ${p.i}`);\n return value;\n}\n\nclass Parser {\n i = 0;\n constructor(readonly s: string) {}\n\n skipWs(): void {\n const s = this.s;\n while (this.i < s.length) {\n const c = s.charCodeAt(this.i);\n if (c === 0x20 || c === 0x0a || c === 0x0d || c === 0x09) this.i++;\n else break;\n }\n }\n\n fail(what: string): never {\n throw new JsonSyntaxError(`${what} at ${this.i}`);\n }\n\n value(): JsonValue {\n const s = this.s;\n if (this.i >= s.length) this.fail(\"Expecting value\");\n const c = s[this.i]!;\n if (c === \"{\") return this.object();\n if (c === \"[\") return this.array();\n if (c === '\"') return this.string();\n if (c === \"t\") return this.literal(\"true\", true);\n if (c === \"f\") return this.literal(\"false\", false);\n if (c === \"n\") return this.literal(\"null\", null);\n if (c === \"N\") return this.literal(\"NaN\", new JsonNumber(\"NaN\"));\n if (c === \"I\") return this.literal(\"Infinity\", new JsonNumber(\"Infinity\"));\n return this.number();\n }\n\n literal<T extends JsonValue>(word: string, value: T): T {\n if (!this.s.startsWith(word, this.i)) this.fail(\"Expecting value\");\n this.i += word.length;\n return value;\n }\n\n number(): JsonNumber {\n const s = this.s;\n const start = this.i;\n if (s[this.i] === \"-\") {\n this.i++;\n if (s.startsWith(\"Infinity\", this.i)) {\n this.i += 8;\n return new JsonNumber(\"-Infinity\");\n }\n }\n const intStart = this.i;\n if (s[this.i] === \"0\") this.i++;\n else {\n while (this.i < s.length && isDigit(s.charCodeAt(this.i))) this.i++;\n if (this.i === intStart) this.fail(\"Expecting value\");\n }\n if (s[this.i] === \".\") {\n this.i++;\n const fracStart = this.i;\n while (this.i < s.length && isDigit(s.charCodeAt(this.i))) this.i++;\n if (this.i === fracStart) this.fail(\"Invalid number\");\n }\n if (s[this.i] === \"e\" || s[this.i] === \"E\") {\n this.i++;\n if (s[this.i] === \"+\" || s[this.i] === \"-\") this.i++;\n const expStart = this.i;\n while (this.i < s.length && isDigit(s.charCodeAt(this.i))) this.i++;\n if (this.i === expStart) this.fail(\"Invalid number\");\n }\n return new JsonNumber(s.slice(start, this.i));\n }\n\n string(): string {\n const s = this.s;\n this.i++; // opening quote\n let out = \"\";\n let runStart = this.i;\n for (;;) {\n if (this.i >= s.length) this.fail(\"Unterminated string\");\n const c = s.charCodeAt(this.i);\n if (c === 0x22) {\n out += s.slice(runStart, this.i);\n this.i++;\n return out;\n }\n if (c < 0x20) this.fail(\"Invalid control character\");\n if (c !== 0x5c) {\n this.i++;\n continue;\n }\n out += s.slice(runStart, this.i);\n this.i++;\n const e = s[this.i];\n switch (e) {\n case '\"':\n case \"\\\\\":\n case \"/\":\n out += e;\n break;\n case \"b\":\n out += \"\\b\";\n break;\n case \"f\":\n out += \"\\f\";\n break;\n case \"n\":\n out += \"\\n\";\n break;\n case \"r\":\n out += \"\\r\";\n break;\n case \"t\":\n out += \"\\t\";\n break;\n case \"u\": {\n const hex = s.slice(this.i + 1, this.i + 5);\n if (!/^[0-9a-fA-F]{4}$/.test(hex)) this.fail(\"Invalid \\\\u escape\");\n out += String.fromCharCode(parseInt(hex, 16));\n this.i += 4;\n break;\n }\n default:\n this.fail(\"Invalid escape\");\n }\n this.i++;\n runStart = this.i;\n }\n }\n\n array(): JsonValue[] {\n this.i++;\n const out: JsonValue[] = [];\n this.skipWs();\n if (this.s[this.i] === \"]\") {\n this.i++;\n return out;\n }\n for (;;) {\n this.skipWs();\n out.push(this.value());\n this.skipWs();\n const c = this.s[this.i];\n if (c === \",\") {\n this.i++;\n continue;\n }\n if (c === \"]\") {\n this.i++;\n return out;\n }\n this.fail(\"Expecting ',' delimiter\");\n }\n }\n\n object(): JsonObject {\n this.i++;\n const out: JsonObject = new Map();\n this.skipWs();\n if (this.s[this.i] === \"}\") {\n this.i++;\n return out;\n }\n for (;;) {\n this.skipWs();\n if (this.s[this.i] !== '\"') this.fail(\"Expecting property name enclosed in double quotes\");\n const key = this.string();\n this.skipWs();\n if (this.s[this.i] !== \":\") this.fail(\"Expecting ':' delimiter\");\n this.i++;\n this.skipWs();\n out.set(key, this.value());\n this.skipWs();\n const c = this.s[this.i];\n if (c === \",\") {\n this.i++;\n continue;\n }\n if (c === \"}\") {\n this.i++;\n return out;\n }\n this.fail(\"Expecting ',' delimiter\");\n }\n }\n}\n\nconst isDigit = (c: number): boolean => c >= 0x30 && c <= 0x39;\n\n// ------------------------------------------------------------ serialising\n\n/** `json.dumps(value, separators=(\",\", \":\"), ensure_ascii=False)`, byte for byte. */\nexport function dumps(value: JsonValue): string {\n if (value === null) return \"null\";\n if (value === true) return \"true\";\n if (value === false) return \"false\";\n if (typeof value === \"string\") return JSON.stringify(value);\n if (value instanceof JsonNumber) return numberText(value);\n if (Array.isArray(value)) return \"[\" + value.map(dumps).join(\",\") + \"]\";\n const parts: string[] = [];\n for (const [key, item] of value) parts.push(JSON.stringify(key) + \":\" + dumps(item));\n return \"{\" + parts.join(\",\") + \"}\";\n}\n\n/** How `json.dumps` spells a parsed number: ints verbatim (`-0` becomes `0`),\n * floats through `float.__repr__`, non-finite as NaN/Infinity. */\nexport function numberText(n: JsonNumber): string {\n if (!n.isFloat) return /^-0+$/.test(n.text) ? \"0\" : n.text;\n const value = n.value;\n if (Number.isNaN(value)) return \"NaN\";\n if (value === Infinity) return \"Infinity\";\n if (value === -Infinity) return \"-Infinity\";\n return pyFloatRepr(value);\n}\n\n/** `str(value)` for the values the redaction digest sees: str, int, float, bool. */\nexport function pyStr(value: string | boolean | JsonNumber): string {\n if (typeof value === \"string\") return value;\n if (typeof value === \"boolean\") return value ? \"True\" : \"False\";\n if (!value.isFloat) return numberText(value);\n const v = value.value;\n if (Number.isNaN(v)) return \"nan\";\n if (v === Infinity) return \"inf\";\n if (v === -Infinity) return \"-inf\";\n return pyFloatRepr(v);\n}\n\n/**\n * CPython's `repr(float)`: the shortest digits that round-trip (which\n * JavaScript's `String(x)` also produces), laid out Python's way — a\n * trailing `.0` on integral values, scientific notation only below 1e-4 or\n * from 1e16, and exponents of at least two digits with a sign.\n */\nexport function pyFloatRepr(x: number): string {\n if (x === 0) return Object.is(x, -0) ? \"-0.0\" : \"0.0\";\n const sign = x < 0 ? \"-\" : \"\";\n const js = String(Math.abs(x));\n const [mantissa, exponentPart] = js.split(\"e\");\n let exponent = exponentPart ? Number(exponentPart) : 0;\n const [intPart, fracPart = \"\"] = mantissa!.split(\".\");\n let digits = intPart! + fracPart;\n // decpt: how many digits sit before the decimal point (may be <= 0 or > length).\n let decpt = intPart!.length + exponent;\n const leading = digits.match(/^0*/)![0].length;\n digits = digits.slice(leading);\n decpt -= leading;\n digits = digits.replace(/0+$/, \"\");\n if (digits === \"\") return sign + \"0.0\";\n const sci = decpt - 1;\n if (sci >= -4 && sci < 16) {\n if (decpt <= 0) return sign + \"0.\" + \"0\".repeat(-decpt) + digits;\n if (decpt >= digits.length) return sign + digits + \"0\".repeat(decpt - digits.length) + \".0\";\n return sign + digits.slice(0, decpt) + \".\" + digits.slice(decpt);\n }\n exponent = sci;\n const mag = String(Math.abs(exponent)).padStart(2, \"0\");\n return sign + digits[0] + (digits.length > 1 ? \".\" + digits.slice(1) : \"\") + \"e\" + (exponent < 0 ? \"-\" : \"+\") + mag;\n}\n\n/**\n * Python's `round(x, ndigits)` for the redaction policy: an int is returned\n * unchanged, a float is correctly rounded on its exact binary value with ties\n * to even (`round(0.125, 2) == 0.12`), then re-read as the nearest double.\n */\nexport function pyRound(n: JsonNumber, ndigits: number): JsonNumber {\n if (!n.isFloat) return n;\n const x = n.value;\n if (!Number.isFinite(x)) return n;\n const sign = x < 0 ? -1 : 1;\n const magnitude = Math.abs(x);\n // Every double at or above 2^53 is an integer already.\n if (magnitude >= 9007199254740992) return new JsonNumber(pyFloatRepr(x));\n const { m, k } = exactFraction(magnitude); // magnitude = m / 2^k, m odd (or zero)\n let rounded: number;\n if (k <= ndigits) rounded = magnitude; // exact at this precision\n else if (k !== ndigits + 1) rounded = Number(magnitude.toFixed(ndigits)); // no tie possible: correctly rounded\n else {\n // Exactly k = ndigits + 1 fractional digits, the last one a 5: a tie. Half to even.\n const scaled = m * 5n ** BigInt(k); // magnitude * 10^k, an integer\n let kept = scaled / 10n; // magnitude * 10^ndigits, truncated\n if (kept % 2n === 1n) kept += 1n;\n const text = kept.toString().padStart(ndigits + 1, \"0\");\n rounded = ndigits === 0 ? Number(text) : Number(text.slice(0, -ndigits) + \".\" + text.slice(-ndigits));\n }\n return new JsonNumber(pyFloatRepr(sign * rounded));\n}\n\n/** A finite non-negative double as m / 2^k with m odd (m = 0, k = 0 for zero). */\nfunction exactFraction(x: number): { m: bigint; k: number } {\n if (x === 0) return { m: 0n, k: 0 };\n const view = new DataView(new ArrayBuffer(8));\n view.setFloat64(0, x);\n const bits = view.getBigUint64(0);\n const exponent = Number((bits >> 52n) & 0x7ffn);\n let mantissa = bits & ((1n << 52n) - 1n);\n let e: number;\n if (exponent === 0) e = -1074;\n else {\n mantissa |= 1n << 52n;\n e = exponent - 1075;\n }\n while (mantissa !== 0n && (mantissa & 1n) === 0n) {\n mantissa >>= 1n;\n e += 1;\n }\n if (e >= 0) return { m: mantissa << BigInt(e), k: 0 };\n return { m: mantissa, k: -e };\n}\n","/**\n * Named plaintext transforms for cross-world entity mappings.\n *\n * A mapping between two worlds' fields is rarely a raw equality: SpyCloud\n * keeps `phone` as bare digits where a Torchlight client sends\n * `+1 (559) 779-1433`; one world keys people by `email`, another by\n * `email_username`. A transform normalises the plaintext on BOTH sides of a\n * mapping before `storedForms` salts it under each world's slug, so a\n * cross-world query is answerable from the plaintext alone, with no stored\n * join.\n *\n * The set is closed and named — no expressions, no user code — because any\n * client must reproduce a transform from the manifest by itself. This is the\n * TypeScript twin of the Python runtime's `environment/schema/transforms.py`;\n * the golden vectors in `__tests__/transforms.test.ts` and the Python\n * `tests/environment/test_schema_transforms.py` pin the two to each other,\n * byte for byte.\n *\n * Whitespace, for `trim` and `collapse_ws`, is the ASCII set `\" \\t\\n\\r\\f\\v\"`\n * by definition (Python's `str.split()` and JavaScript's `\\s` disagree at the\n * edges of Unicode; `nfkc` first folds a no-break space into a plain one).\n */\n\nimport { createHash } from \"node:crypto\";\n\nimport { pyFloatRepr } from \"../cli/platform/worldData/json\";\n\nexport type Transform = (value: string) => string;\n\nexport const WHITESPACE = \" \\t\\n\\r\\f\\v\";\nconst WHITESPACE_EDGES = /^[ \\t\\n\\r\\f\\v]+|[ \\t\\n\\r\\f\\v]+$/g;\nconst WHITESPACE_RUN = /[ \\t\\n\\r\\f\\v]+/g;\nconst NOT_DIGIT = /[^0-9]/g;\n\nexport const STRIP_PREFIX = \"strip_prefix\";\n\nconst trim = (value: string): string => value.replace(WHITESPACE_EDGES, \"\");\n\nconst emailLocalPart = (value: string): string => {\n const at = value.lastIndexOf(\"@\");\n return at === -1 ? value : value.slice(0, at);\n};\n\nconst emailDomain = (value: string): string => {\n const at = value.lastIndexOf(\"@\");\n return at === -1 ? \"\" : value.slice(at + 1).toLowerCase();\n};\n\nconst stripPrefix =\n (prefix: string): Transform =>\n (value) =>\n value.startsWith(prefix) ? value.slice(prefix.length) : value;\n\nconst hex = (algorithm: \"sha1\" | \"sha256\", value: string): string =>\n createHash(algorithm).update(value, \"utf8\").digest(\"hex\");\n\nconst SIMPLE: Record<string, Transform> = {\n lower: (value) => value.toLowerCase(),\n upper: (value) => value.toUpperCase(),\n trim,\n collapse_ws: (value) => trim(value).replace(WHITESPACE_RUN, \" \"),\n nfkc: (value) => value.normalize(\"NFKC\"),\n digits: (value) => value.replace(NOT_DIGIT, \"\"),\n email_local_part: emailLocalPart,\n email_domain: emailDomain,\n // Vendor-style digests: lowercase hex of the utf-8 bytes, unsalted. This is\n // how SpyCloud accepts a hashed selector (`_digests` in its api_handlers).\n sha1: (value) => hex(\"sha1\", value),\n sha256: (value) => hex(\"sha256\", value),\n};\n\n/** The closed set, as a manifest spells it. `strip_prefix` takes its parameter\n * after a colon; the parameter may hold any character but `,`. */\nexport const TRANSFORMS: readonly string[] = [...Object.keys(SIMPLE), `${STRIP_PREFIX}:<prefix>`];\n\n/** The function a transform name denotes; throws when the name is not in the set. */\nexport function parseTransform(name: string): Transform {\n const simple = Object.prototype.hasOwnProperty.call(SIMPLE, name) ? SIMPLE[name] : undefined;\n if (simple) return simple;\n const colon = name.indexOf(\":\");\n if (colon !== -1) {\n const head = name.slice(0, colon);\n const prefix = name.slice(colon + 1);\n if (head === STRIP_PREFIX && prefix && !prefix.includes(\",\")) return stripPrefix(prefix);\n }\n throw new Error(`Unknown transform '${name}'; choose one of ${TRANSFORMS.join(\", \")}`);\n}\n\n/** `str(value)` as the Python runtime spells a number: an integral number is an\n * int, any other its float repr. */\nconst text = (value: string | number): string => {\n if (typeof value === \"string\") return value;\n return Number.isInteger(value) ? String(value) : pyFloatRepr(value);\n};\n\n/**\n * Compose `chain` left to right over `value`.\n *\n * A number is written as Python's `str()` first, the way `_digest` salts one,\n * so a number keyed on one side and a string on the other transform alike. The\n * whole chain is parsed before any step runs: a bad name at the end refuses\n * the mapping outright rather than after a partial result. An empty chain is\n * the identity.\n */\nexport function applyTransforms(value: string | number, chain: readonly string[]): string {\n const steps = chain.map(parseTransform);\n let out = text(value);\n for (const step of steps) out = step(out);\n return out;\n}\n","/**\n * Stored forms: what a world's store holds for a field given its plaintext.\n *\n * A schema world's `[redact]` table (connector.toml) rewrites named fields\n * before they reach disk — `hash` to a slug-salted sha256, `preserve` to a\n * shape-preserving digest, `round` to fewer decimals, `drop` to nothing. A\n * lookup by plaintext therefore has to compute the same form the store did.\n * This module is the TypeScript twin of the Python runtime's `_digest`,\n * `_shaped`, `redaction_of` and `stored_forms` (environment/schema/connector.py):\n * the rule is `\"sha256:\" + sha256(\"<slug>:<plaintext>\")`, no lowercasing, no\n * trimming, no other salt, and the golden vectors in redaction.test.ts pin the\n * two implementations to each other.\n */\n\nimport { createHash } from \"node:crypto\";\n\nimport { JsonNumber, pyFloatRepr, pyRound } from \"../cli/platform/worldData/json\";\nimport { applyTransforms } from \"./transforms\";\n\n/** The `[redact]` table as `describe` reports it (`connection.redact`, and\n * `redact` on `GET /api/public/worlds/{slug}`). */\nexport type RedactPolicy = {\n /** The digest salt: the connector's slug from connector.toml. It can differ\n * from the platform world slug (`spycloud` vs `spycloud-world`); `storedForms`\n * prefers it and falls back to the world slug only when it is absent. */\n slug?: string;\n hash: string[];\n drop: string[];\n preserve: string[];\n round: Record<string, number>;\n};\n\n/** The policy one field is stored under; null when it is stored in the clear. */\nexport type Redaction = \"hash\" | \"drop\" | \"preserve\" | `round:${number}`;\n\n/**\n * A value as the Python runtime would see it. JavaScript has one number\n * type, so an integral number takes Python's `int` path and any other number\n * its `float` path (`100` is `100`, never `100.0`); integers stay exact within\n * the safe range only.\n */\nexport type Plaintext = string | number;\n\nconst isInt = (value: Plaintext): value is number => typeof value === \"number\" && Number.isInteger(value);\n\n/** `str(value)` for an int or str, `repr(value)` for a float — the text the\n * Python runtime salts and shapes. */\nexport function pyText(value: Plaintext): string {\n if (typeof value === \"string\") return value;\n if (Number.isInteger(value)) return String(value);\n if (Number.isNaN(value)) return \"nan\";\n if (!Number.isFinite(value)) return value > 0 ? \"inf\" : \"-inf\";\n return pyFloatRepr(value);\n}\n\n/** The `hash` form: `\"sha256:\" + sha256(\"<slug>:<plaintext>\")` as hex. */\nexport function hashForm(slug: string, plaintext: Plaintext): string {\n return \"sha256:\" + createHash(\"sha256\").update(`${slug}:${pyText(plaintext)}`, \"utf8\").digest(\"hex\");\n}\n\n/**\n * The `preserve` form, the Python `_shaped`: the same length, every ASCII\n * digit still a digit, every ASCII letter still a letter of the same case,\n * everything else (separators, punctuation, non-ASCII) left in place. The\n * bytes come from sha256 of the seed `\"<slug>:<text>\"`, re-keyed as\n * sha256(digest + seed) once the 32 bytes are spent. A number keeps its type:\n * an int keeps its digit count (a leading zero is replaced), a float is re-read.\n */\nexport function preserveForm(slug: string, plaintext: Plaintext): Plaintext {\n const kind = typeof plaintext === \"string\" ? \"str\" : isInt(plaintext) ? \"int\" : \"float\";\n const shaped = shapeText(slug, pyText(plaintext), kind);\n return kind === \"str\" ? shaped : Number(shaped);\n}\n\n/** The shaping itself, on text: `kind` says which of Python's rules apply\n * (letters are re-lettered for a str only; an int keeps its digit count). */\nexport function shapeText(slug: string, text: string, kind: \"str\" | \"int\" | \"float\"): string {\n const seed = Buffer.from(`${slug}:${text}`, \"utf8\");\n let digest = createHash(\"sha256\").update(seed).digest();\n let cursor = 0;\n const out: string[] = [];\n for (const char of text) {\n if (cursor === digest.length) {\n digest = createHash(\"sha256\").update(Buffer.concat([digest, seed])).digest();\n cursor = 0;\n }\n const byte = digest[cursor]!;\n cursor += 1;\n if (char >= \"0\" && char <= \"9\") out.push(String(byte % 10));\n else if (kind === \"str\" && char >= \"a\" && char <= \"z\") out.push(String.fromCharCode(97 + (byte % 26)));\n else if (kind === \"str\" && char >= \"A\" && char <= \"Z\") out.push(String.fromCharCode(65 + (byte % 26)));\n else out.push(char);\n }\n // An int keeps its digit count; int() would drop a leading zero.\n if (kind === \"int\" && out.length > 1 && out[0] === \"0\") out[0] = String(1 + (digest[0]! % 9));\n return out.join(\"\");\n}\n\n/** The `round` form: Python's `round(value, decimals)` — an int unchanged, a\n * float correctly rounded with ties to even; a string is not a number and\n * passes through as the runtime leaves it. */\nexport function roundForm(plaintext: Plaintext, decimals: number): Plaintext {\n if (typeof plaintext === \"string\" || isInt(plaintext) || !Number.isFinite(plaintext)) return plaintext;\n return pyRound(new JsonNumber(pyFloatRepr(plaintext)), decimals).value;\n}\n\n/**\n * The policy a field of this name falls under, ranked as the runtime applies\n * them (drop, hash, preserve, round). Read without a path: a bare name in the\n * table counts, and so does a dotted path whose last segment is the field.\n */\nexport function redactionOf(redact: RedactPolicy | null | undefined, field: string): Redaction | null {\n if (!redact) return null;\n const named = (names: string[] | undefined) =>\n (names ?? []).some((name) => name === field || name.slice(name.lastIndexOf(\".\") + 1) === field);\n if (named(redact.drop)) return \"drop\";\n if (named(redact.hash)) return \"hash\";\n if (named(redact.preserve)) return \"preserve\";\n const decimals = redact.round?.[field];\n if (typeof decimals === \"number\") return `round:${decimals}`;\n return null;\n}\n\n/**\n * Every value the store may hold for `field` given this plaintext:\n *\n * clear field -> [plaintext]\n * hash -> [\"sha256:<hex>\"]\n * preserve -> [the shape-preserving digest]\n * round -> [round(plaintext, decimals)] for a number, [plaintext] otherwise\n * drop -> [] (the field is not on disk: a documented miss, not an error)\n *\n * `world` is what `describeWorld` / the bridge's `describe` return: the slug\n * is the salt, `redact` the table.\n *\n * `transform` — a cross-world mapping's chain (`./transforms`) — runs over the\n * plaintext FIRST, so `hash` and `preserve` salt the normalised text; omitted\n * (or empty) is today's behaviour, byte for byte.\n */\nexport function storedForms(\n world: { slug: string; redact?: RedactPolicy | null },\n field: string,\n plaintext: Plaintext,\n transform?: readonly string[],\n): Plaintext[] {\n if (transform?.length) plaintext = applyTransforms(plaintext, transform);\n const policy = redactionOf(world.redact, field);\n const salt = world.redact?.slug ?? world.slug;\n if (policy === \"drop\") return [];\n if (policy === \"hash\") return [hashForm(salt, plaintext)];\n if (policy === \"preserve\") return [preserveForm(salt, plaintext)];\n if (policy !== null) return [roundForm(plaintext, world.redact!.round[field]!)];\n return [plaintext];\n}\n","/**\n * `queryRows(slug, entity, {where, resolve, limit, offset})` — the rows of\n * one entity that match a predicate, from\n * `GET /api/public/worlds/{slug}/data?entity=&where=&limit=&offset=&resolve=`.\n * `where` is field → value, or field → list of values (any of); values match\n * the STORED form as given. With `resolve: true` the values are plaintext and\n * the runtime maps each to its stored form under the world's `[redact]`\n * policy first (a hashed `email` becomes its slug-salted digest; a dropped\n * field resolves to nothing and matches no row — the answer's `resolved`\n * says so). The CLI twin is `gateway worlds data query <slug> <entity>`.\n *\n * `across: true` runs the same plaintext in every world this one links to\n * whose `[dependencies.<alias>.entities]` mapping covers a `where` field;\n * each linked world recomputes its own stored form (after the mapping's\n * transform) at query time — no join on disk, no shared salt. The answer\n * is then {@link WorldQueryAcrossResult}: one group per world, the root\n * first, and with `compare: true` a parity report saying, per field and\n * per world, `matched`, `no match` or `unmapped`.\n */\n\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\nimport type { Plaintext } from \"./redaction\";\n\nexport type WorldQueryWhere = Record<string, Plaintext | Plaintext[]>;\n\nexport type WorldQueryOptions = {\n where?: WorldQueryWhere;\n /** The `where` values are plaintext: resolve each to its stored form before matching. */\n resolve?: boolean;\n limit?: number;\n offset?: number;\n /** Query the linked worlds too; the answer becomes groups. */\n across?: boolean;\n /** With `across`: add the parity report. */\n compare?: boolean;\n};\n\n/** The options that make `queryRows` answer {@link WorldQueryAcrossResult}. */\nexport type WorldQueryAcrossOptions = WorldQueryOptions & { across: true };\n\nexport type WorldQueryResult = {\n slug: string;\n versionId: string;\n kind: string | null;\n entity: string;\n rows: Record<string, unknown>[];\n /** Rows in this page. */\n count: number;\n /** Rows matching in all; null when the store does not count them. */\n total: number | null;\n limit: number;\n offset: number;\n /** With `resolve`: the stored forms each `where` field was matched against\n * (`[]` for a dropped field, which is why such a query matches nothing). */\n resolved?: Record<string, Plaintext[]>;\n entityCounts: Record<string, number>;\n snapshot: WorldQuerySnapshot | null;\n};\n\nexport type WorldQuerySnapshot = {\n snapshotId: string;\n contractHash: string;\n batchDigest: string;\n bytes: number;\n};\n\n/** One world's page inside an across answer: the root (`alias: null`, no\n * `mapping`) or a linked world with the mappings that carried the root's\n * `where` fields into its own entity. */\nexport type WorldQueryGroup = {\n world: { slug: string; alias: string | null; versionId: string };\n entity: string;\n rows: Record<string, unknown>[];\n count: number;\n total: number | null;\n limit: number;\n offset: number;\n resolved?: Record<string, Plaintext[]>;\n mapping?: { field: string; depField: string; transform: string[] }[];\n};\n\nexport type WorldQueryCompareStatus = \"matched\" | \"no match\" | \"unmapped\";\n\n/** Per `where` field, per world: whether the field reached the world and\n * whether any row matched there; `present`/`absent` list the worlds by slug. */\nexport type WorldQueryCompare = {\n present: string[];\n absent: string[];\n perField: {\n field: string;\n worlds: {\n world: string;\n alias: string | null;\n status: WorldQueryCompareStatus;\n /** `<depEntity>.<depField>` and the transform applied (mapped worlds only). */\n depField?: string;\n transform?: string[];\n }[];\n }[];\n};\n\nexport type WorldQueryAcrossResult = {\n slug: string;\n versionId: string;\n kind: string | null;\n entity: string;\n /** The root world first, then one per linked world that was queried. */\n groups: WorldQueryGroup[];\n compare?: WorldQueryCompare;\n entityCounts: Record<string, number>;\n snapshot: WorldQuerySnapshot | null;\n};\n\n/** The query string the route reads; `where` travels as URL-encoded JSON. */\nexport function queryRowsSearch(entity: string, opts: WorldQueryOptions = {}): string {\n const search = new URLSearchParams();\n search.set(\"entity\", entity);\n if (opts.where && Object.keys(opts.where).length) search.set(\"where\", JSON.stringify(opts.where));\n if (opts.limit !== undefined) search.set(\"limit\", String(opts.limit));\n if (opts.offset !== undefined) search.set(\"offset\", String(opts.offset));\n if (opts.resolve) search.set(\"resolve\", \"true\");\n if (opts.across) search.set(\"across\", \"true\");\n if (opts.compare) search.set(\"compare\", \"true\");\n return `?${search.toString()}`;\n}\n\n/** The world's head version, queried. The route reads the head only, so a\n * `slug@ref` is refused rather than silently served as the head. With\n * `across: true` the answer is the groups shape. */\nexport async function queryRows(\n slug: string,\n entity: string,\n opts: WorldQueryAcrossOptions,\n options?: WorldsClientOptions,\n): Promise<WorldQueryAcrossResult>;\nexport async function queryRows(\n slug: string,\n entity: string,\n opts?: WorldQueryOptions,\n options?: WorldsClientOptions,\n): Promise<WorldQueryResult>;\nexport async function queryRows(\n slug: string,\n entity: string,\n opts: WorldQueryOptions = {},\n options: WorldsClientOptions = {},\n): Promise<WorldQueryResult | WorldQueryAcrossResult> {\n if (slug.includes(\"@\"))\n throw new Error(\n `queryRows reads a world's head version: pass the slug without @ref (got ${slug})`,\n );\n if (!entity) throw new Error(\"queryRows needs an entity\");\n if (opts.compare && !opts.across) throw new Error(\"queryRows: compare needs across\");\n return apiRequest<WorldQueryResult | WorldQueryAcrossResult>(\n options,\n \"GET\",\n `/api/public/worlds/${encodeURIComponent(slug)}/data${queryRowsSearch(entity, opts)}`,\n );\n}\n","/**\n * `migrateWorld(slug)` — convert a stored world into a schema world, from\n * `POST /api/public/worlds/{slug}/migrate`; `migrateProjectWorlds()` plans\n * (or migrates) every connector world in the project from\n * `POST /api/public/worlds/migrate`. Dry run by default: the report says\n * what the version is, what the conversion does, or why it cannot; `apply`\n * commits the migrated tree as the next version (\"Migrated to a schema\n * world\"). Targets are the platform's connector worlds; a hand-built world\n * needs `force`. The CLI twin is `gateway worlds migrate`.\n */\n\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\n\nexport type WorldMigrationRefusal = {\n code: string;\n message: string;\n /** Paths the conversion needed and did not find. */\n missing: string[];\n};\n\nexport type WorldMigrationReport = {\n slug: string;\n containerId: string;\n versionId: string;\n /** True when the container was created from a connector template. */\n connectorWorld: boolean;\n /** schema | api-bundle | legacy-tools | harbor | verifiers */\n shape: string;\n target: \"schema\";\n /** True when the world already is a schema world. */\n unchanged: boolean;\n /** The dry-run report, one sentence each. */\n actions: string[];\n /** Files the migrated tree holds; 0 on a refusal. */\n files: number;\n refusal: WorldMigrationRefusal | null;\n /** True when this call committed the migrated tree. */\n applied: boolean;\n version: { id: string; contentHash: string } | null;\n};\n\nexport type MigrateWorldOptions = {\n /** Commit the migrated tree as the next version. Default false: dry run. */\n apply?: boolean;\n /** Migrate a world that was not created from a connector template. */\n force?: boolean;\n};\n\nexport async function migrateWorld(\n slug: string,\n input: MigrateWorldOptions = {},\n options: WorldsClientOptions = {},\n): Promise<WorldMigrationReport> {\n if (slug.includes(\"@\"))\n throw new Error(\n `migrateWorld converts a world's head version: pass the slug without @ref (got ${slug})`,\n );\n return apiRequest<WorldMigrationReport>(\n options,\n \"POST\",\n `/api/public/worlds/${encodeURIComponent(slug)}/migrate`,\n {\n ...(input.apply === undefined ? {} : { apply: input.apply }),\n ...(input.force === undefined ? {} : { force: input.force }),\n },\n );\n}\n\n/** Every connector world in the project, one report each. */\nexport async function migrateProjectWorlds(\n input: { apply?: boolean } = {},\n options: WorldsClientOptions = {},\n): Promise<{ worlds: WorldMigrationReport[]; applied: boolean }> {\n return apiRequest<{ worlds: WorldMigrationReport[]; applied: boolean }>(\n options,\n \"POST\",\n \"/api/public/worlds/migrate\",\n input.apply === undefined ? {} : { apply: input.apply },\n );\n}\n","/**\n * The `gateway` command tree, with no dependency: groups hold commands, a\n * command declares its positionals and flags, help is generated from the\n * declarations so `gateway <group> --help` always matches what runs.\n *\n * Flags: `--name value`, `--name=value`, `--flag` (boolean), repeatable flags\n * collect into arrays when declared `repeat: true`. Anything after `--` is\n * positional.\n */\n\nexport type FlagSpec = {\n name: string;\n help: string;\n /** Short alias, e.g. \"m\" for --message. */\n short?: string;\n /** Boolean flags take no value. */\n boolean?: boolean;\n repeat?: boolean;\n default?: string | boolean;\n /** Environment variable that fills the flag when it is not given. */\n env?: string;\n};\n\nexport type PositionalSpec = {\n name: string;\n help: string;\n optional?: boolean;\n /** Collects every remaining positional. */\n variadic?: boolean;\n};\n\nexport type Parsed = {\n positionals: string[];\n flags: Record<string, string | boolean | string[] | undefined>;\n};\n\nexport type CommandSpec = {\n name: string;\n help: string;\n positionals?: PositionalSpec[];\n flags?: FlagSpec[];\n /** Long-form notes printed under the usage line in `--help`. */\n notes?: string;\n run: (args: Parsed, ctx: CommandContext) => Promise<number | void>;\n};\n\nexport type CommandContext = {\n stdout: (line: string) => void;\n stderr: (line: string) => void;\n /** Read all of stdin (for --value-less secrets, piped rows). */\n stdin: () => Promise<string>;\n /** Stdin as a stream, for inputs too large to hold (`worlds data import … -`). */\n stdinStream?: () => NodeJS.ReadableStream;\n};\n\nexport class CommandGroup {\n readonly groups = new Map<string, CommandGroup>();\n readonly commands = new Map<string, CommandSpec>();\n /** Long-form notes printed under the command list in `--help`. */\n notes?: string;\n constructor(\n readonly name: string,\n readonly help: string,\n ) {}\n group(name: string, help: string): CommandGroup {\n const existing = this.groups.get(name);\n if (existing) return existing;\n const created = new CommandGroup(name, help);\n this.groups.set(name, created);\n return created;\n }\n command(spec: CommandSpec): this {\n this.commands.set(spec.name, spec);\n return this;\n }\n}\n\nexport class CliError extends Error {\n constructor(\n message: string,\n readonly exitCode = 2,\n ) {\n super(message);\n }\n}\n\nexport function parseArgs(spec: CommandSpec, argv: string[]): Parsed {\n const flagSpecs = spec.flags ?? [];\n const byName = new Map<string, FlagSpec>();\n for (const f of flagSpecs) {\n byName.set(f.name, f);\n if (f.short) byName.set(f.short, f);\n }\n const positionals: string[] = [];\n const flags: Parsed[\"flags\"] = {};\n let onlyPositionals = false;\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i]!;\n if (onlyPositionals || !arg.startsWith(\"-\") || arg === \"-\") {\n positionals.push(arg);\n continue;\n }\n if (arg === \"--\") {\n onlyPositionals = true;\n continue;\n }\n const bare = arg.replace(/^--?/, \"\");\n const [rawName, inlineValue] = bare.includes(\"=\")\n ? [bare.slice(0, bare.indexOf(\"=\")), bare.slice(bare.indexOf(\"=\") + 1)]\n : [bare, undefined];\n const f = byName.get(rawName);\n if (!f) throw new CliError(`Unknown flag --${rawName} for ${spec.name}`);\n if (f.boolean) {\n flags[f.name] =\n inlineValue === undefined ? true : inlineValue !== \"false\";\n continue;\n }\n let value = inlineValue;\n if (value === undefined) {\n const next = argv[i + 1];\n if (next === undefined || (next.startsWith(\"--\") && next.length > 2))\n throw new CliError(`--${f.name} needs a value`);\n value = next;\n i++;\n }\n if (f.repeat) {\n const current = flags[f.name];\n flags[f.name] = Array.isArray(current) ? [...current, value] : [value];\n } else flags[f.name] = value;\n }\n for (const f of flagSpecs) {\n if (flags[f.name] !== undefined) continue;\n const fromEnv = f.env ? process.env[f.env] : undefined;\n if (fromEnv !== undefined && fromEnv !== \"\") flags[f.name] = fromEnv;\n else if (f.default !== undefined) flags[f.name] = f.default;\n }\n const specs = spec.positionals ?? [];\n const required = specs.filter((p) => !p.optional && !p.variadic).length;\n if (positionals.length < required)\n throw new CliError(\n `${spec.name} needs ${specs\n .slice(0, required)\n .map((p) => `<${p.name}>`)\n .join(\" \")}`,\n );\n const variadic = specs.some((p) => p.variadic);\n if (!variadic && positionals.length > specs.length)\n throw new CliError(\n `${spec.name} takes ${specs.length} argument${specs.length === 1 ? \"\" : \"s\"}, got ${positionals.length}`,\n );\n return { positionals, flags };\n}\n\n/** Typed accessors so commands never repeat the narrowing. */\nexport const arg = {\n str(p: Parsed, name: string): string | undefined {\n const v = p.flags[name];\n return typeof v === \"string\" ? v : undefined;\n },\n bool(p: Parsed, name: string): boolean {\n return p.flags[name] === true;\n },\n list(p: Parsed, name: string): string[] {\n const v = p.flags[name];\n if (Array.isArray(v)) return v;\n return typeof v === \"string\" ? [v] : [];\n },\n int(p: Parsed, name: string): number | undefined {\n const v = arg.str(p, name);\n if (v === undefined) return undefined;\n const n = Number(v);\n if (!Number.isInteger(n))\n throw new CliError(`--${name} must be an integer`);\n return n;\n },\n};\n\nfunction usageLine(path: string[], spec: CommandSpec): string {\n const pos = (spec.positionals ?? [])\n .map((p) =>\n p.variadic\n ? `<${p.name}...>`\n : p.optional\n ? `[${p.name}]`\n : `<${p.name}>`,\n )\n .join(\" \");\n return `${path.join(\" \")} ${pos}`.trim();\n}\n\nexport function helpFor(\n path: string[],\n node: CommandGroup | CommandSpec,\n): string {\n if (node instanceof CommandGroup) {\n const lines = [`${path.join(\" \")} — ${node.help}`, \"\"];\n for (const [name, g] of node.groups)\n lines.push(` ${name.padEnd(16)} ${g.help}`);\n for (const [name, c] of node.commands)\n lines.push(` ${name.padEnd(16)} ${c.help}`);\n if (node.notes) lines.push(\"\", node.notes);\n lines.push(\"\", `Run '${path.join(\" \")} <command> --help' for details.`);\n return lines.join(\"\\n\");\n }\n const lines = [usageLine(path, node), \"\", ` ${node.help}`];\n const pos = node.positionals ?? [];\n if (pos.length) {\n lines.push(\"\", \"Arguments:\");\n for (const p of pos) lines.push(` ${p.name.padEnd(18)} ${p.help}`);\n }\n const flags = node.flags ?? [];\n if (flags.length) {\n lines.push(\"\", \"Options:\");\n for (const f of flags) {\n const label = `--${f.name}${f.short ? `, -${f.short}` : \"\"}${f.boolean ? \"\" : \" <value>\"}`;\n const extras = [\n f.default !== undefined ? `default ${String(f.default)}` : null,\n f.env ? `env ${f.env}` : null,\n ]\n .filter(Boolean)\n .join(\", \");\n lines.push(\n ` ${label.padEnd(28)} ${f.help}${extras ? ` (${extras})` : \"\"}`,\n );\n }\n }\n if (node.notes) lines.push(\"\", node.notes);\n return lines.join(\"\\n\");\n}\n\n/** Walk the tree and run: exit code 0 on success, 2 on usage error, 1 on failure. */\nexport async function dispatch(\n root: CommandGroup,\n argv: string[],\n ctx: CommandContext,\n): Promise<number> {\n let node: CommandGroup = root;\n const path = [root.name];\n let i = 0;\n while (i < argv.length) {\n const token = argv[i]!;\n if (token === \"--help\" || token === \"-h\") {\n ctx.stdout(helpFor(path, node));\n return 0;\n }\n const group = node.groups.get(token);\n if (group) {\n node = group;\n path.push(token);\n i++;\n continue;\n }\n const command = node.commands.get(token);\n if (command) {\n const rest = argv.slice(i + 1);\n if (rest.includes(\"--help\") || rest.includes(\"-h\")) {\n ctx.stdout(helpFor([...path, token], command));\n return 0;\n }\n try {\n const parsed = parseArgs(command, rest);\n const code = await command.run(parsed, ctx);\n return code ?? 0;\n } catch (error) {\n if (error instanceof CliError) {\n ctx.stderr(error.message);\n return error.exitCode;\n }\n ctx.stderr(error instanceof Error ? error.message : String(error));\n return 1;\n }\n }\n ctx.stderr(\n `Unknown command '${token}' under '${path.join(\" \")}'.\\n\\n${helpFor(path, node)}`,\n );\n return 2;\n }\n ctx.stdout(helpFor(path, node));\n return node === root ? 0 : 2;\n}\n","import * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\n\nimport { CliError } from \"./router\";\n\n/**\n * Where the CLI's credentials come from, in this order (the same as the\n * Python CLI): explicit --host, environment (GATEWAY_HOST, GATEWAY_PUBLIC_KEY,\n * GATEWAY_SECRET_KEY / GATEWAY_API_KEY), then ~/.gateway/config.json written\n * by `gateway auth login`. `GATEWAY_ENV_FILE=path` fills the environment from\n * a KEY=value file first (see `loadEnvFile`).\n */\nexport type StoredConfig = {\n host?: string;\n public_key?: string;\n api_key?: string;\n};\n\nexport function configPath(): string {\n return path.join(\n process.env.GATEWAY_CONFIG_DIR ?? path.join(os.homedir(), \".gateway\"),\n \"config.json\",\n );\n}\n\nexport function readConfig(): StoredConfig {\n try {\n return JSON.parse(fs.readFileSync(configPath(), \"utf8\")) as StoredConfig;\n } catch {\n return {};\n }\n}\n\nexport function writeConfig(config: StoredConfig): void {\n const file = configPath();\n fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });\n fs.writeFileSync(file, JSON.stringify(config, null, 2) + \"\\n\", { mode: 0o600 });\n}\n\nexport function clearConfig(): boolean {\n try {\n fs.unlinkSync(configPath());\n return true;\n } catch {\n return false;\n }\n}\n\nexport type Credentials = { host: string; publicKey: string; secretKey: string };\n\n/** The accepted env-file form, printed by `gateway --help` and the docs. */\nexport const ENV_FILE_FORM =\n \"GATEWAY_ENV_FILE=path loads a KEY=value file first: `KEY = value`, quoted values, \" +\n \"`export KEY=value` and `#` comments are all accepted; the shell's environment wins.\";\n\n/**\n * Parse a KEY=value file the way a person writes one, not the way `source`\n * reads one. Brex retrospective: the customer's `.env` had `GATEWAY_HOST = …`\n * (spaces around `=`), which the shell refused to source and the CLI could not\n * read either. Accepted: blank lines and `#` comments, an `export ` prefix,\n * spaces around `=`, single- or double-quoted values (quotes stripped, nothing\n * inside interpreted). Not accepted: a line without `=`, which is reported by\n * number rather than skipped, because a silently dropped credential shows up\n * later as \"API key not configured\".\n */\nexport function parseEnvFile(text: string): Record<string, string> {\n const values: Record<string, string> = {};\n const lines = text.split(/\\r?\\n/);\n for (let index = 0; index < lines.length; index++) {\n const line = lines[index]!.trim();\n if (!line || line.startsWith(\"#\")) continue;\n const assignment = line.startsWith(\"export \") ? line.slice(\"export \".length).trim() : line;\n const eq = assignment.indexOf(\"=\");\n if (eq === -1) throw new CliError(`env file line ${index + 1} is not KEY=value: ${line}`);\n const key = assignment.slice(0, eq).trim();\n let value = assignment.slice(eq + 1).trim();\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key))\n throw new CliError(`env file line ${index + 1} has an invalid variable name: ${key || line}`);\n const quote = value[0];\n if ((quote === '\"' || quote === \"'\") && value.length >= 2 && value.endsWith(quote))\n value = value.slice(1, -1);\n values[key] = value;\n }\n return values;\n}\n\n/**\n * Put `GATEWAY_ENV_FILE`'s variables into the process environment, without\n * overriding anything already set there. Explicit on purpose: the CLI never\n * reads a `.env` it was not pointed at. Vendor keys named by connector.toml\n * ride along, so a local capture sees them too. Returns the keys it set.\n */\nexport function loadEnvFile(): string[] {\n const file = process.env.GATEWAY_ENV_FILE;\n if (!file) return [];\n let text: string;\n try {\n text = fs.readFileSync(file, \"utf8\");\n } catch (error) {\n throw new CliError(`GATEWAY_ENV_FILE=${file} could not be read: ${(error as Error).message}`);\n }\n const set: string[] = [];\n for (const [key, value] of Object.entries(parseEnvFile(text))) {\n if (process.env[key] !== undefined) continue;\n process.env[key] = value;\n set.push(key);\n }\n return set;\n}\n\nexport function resolveCredentials(hostFlag?: string): Credentials {\n const stored = readConfig();\n const host = (hostFlag ?? process.env.GATEWAY_HOST ?? stored.host ?? \"\").replace(/\\/+$/, \"\");\n const publicKey = process.env.GATEWAY_PUBLIC_KEY ?? stored.public_key ?? \"\";\n const secretKey =\n process.env.GATEWAY_SECRET_KEY ?? process.env.GATEWAY_API_KEY ?? stored.api_key ?? \"\";\n if (!host)\n throw new CliError(\n \"Host not configured. Pass --host, set GATEWAY_HOST, or run `gateway auth login`.\",\n );\n if (!publicKey || !secretKey)\n throw new CliError(\n \"API key not configured. Set GATEWAY_PUBLIC_KEY and GATEWAY_SECRET_KEY, or run `gateway auth login`.\",\n );\n return { host, publicKey, secretKey };\n}\n\n/** A non-2xx answer from the platform: the status is a field, never something to regex out of the text. */\nexport class ApiError extends CliError {\n constructor(\n readonly status: number,\n readonly method: string,\n readonly route: string,\n readonly text: string,\n ) {\n super(`${method} ${route} -> ${status}: ${text.slice(0, 600)}`, 1);\n }\n}\n\n/** One JSON request against the platform, Basic-authenticated with the project key. */\nexport async function api<T = unknown>(\n creds: Credentials,\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\",\n route: string,\n body?: unknown,\n init: { timeoutMs?: number } = {},\n): Promise<T> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), init.timeoutMs ?? 120_000);\n try {\n const res = await fetch(`${creds.host}${route}`, {\n method,\n headers: {\n \"content-type\": \"application/json\",\n accept: \"application/json\",\n authorization:\n \"Basic \" + Buffer.from(`${creds.publicKey}:${creds.secretKey}`).toString(\"base64\"),\n },\n ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n signal: controller.signal,\n });\n const text = await res.text();\n if (!res.ok) throw new ApiError(res.status, method, route, text);\n return (text ? JSON.parse(text) : {}) as T;\n } finally {\n clearTimeout(timer);\n }\n}\n\nexport function printJson(ctx: { stdout: (line: string) => void }, value: unknown): void {\n ctx.stdout(JSON.stringify(value, null, 2));\n}\n","import { spawn, spawnSync } from \"node:child_process\";\nimport * as fs from \"node:fs\";\nimport * as net from \"node:net\";\nimport * as path from \"node:path\";\n\nimport { CliError } from \"../router\";\nimport { type Credentials, resolveCredentials } from \"../config\";\nimport type { RuntimeRequest } from \"./client\";\n\n/**\n * The schema runtime, run on THIS machine. The npm package carries the SDK's\n * `gatewaysdk/environment` directory (stdlib-only Python, the same files the\n * platform's bridge executes), so any python3 >= 3.11 on the path runs it\n * exactly as the platform does — the same bootstrap, JSON in, JSON out. No\n * pip, no PyPI. When there is no such Python, callers fall back to\n * `POST /api/public/worlds/runtime`.\n *\n * `GATEWAY_RUNTIME=local|platform|auto` (default auto) forces one side;\n * `GATEWAY_PYTHON` names the interpreter (otherwise python3.13, python3.12,\n * python3.11, python3, python, then `uv python find` are tried in that order).\n */\n\nconst MIN_PYTHON: [number, number] = [3, 11];\nconst DIAGNOSTIC_TAIL = 600;\n\n/** The end of a failed run's output: a Python traceback names the exception last. */\nfunction tailOf(output: string): string {\n return output.length > DIAGNOSTIC_TAIL\n ? `…${output.slice(-DIAGNOSTIC_TAIL)}`\n : output;\n}\n\n/** The platform's own bootstrap: build the `gatewaysdk` package in memory from\n * the runtime root and run the bridge as __main__ (see worldSchemaRuntime.ts). */\nconst BRIDGE_BOOTSTRAP = `import sys,runpy,types,os\nroot=sys.argv[1]\npackage=types.ModuleType('gatewaysdk')\npackage.__path__=[os.path.join(root,'gatewaysdk')]\nsys.modules['gatewaysdk']=package\nrunpy.run_module('gatewaysdk.environment.schema.platform',run_name='__main__')`;\n\n/** The same, but running the schema module's own CLI (serve, connector-capture …)\n * with the arguments after the root. */\nconst MODULE_BOOTSTRAP = `import sys,runpy,types,os\nroot=sys.argv[1]\npackage=types.ModuleType('gatewaysdk')\npackage.__path__=[os.path.join(root,'gatewaysdk')]\nsys.modules['gatewaysdk']=package\nsys.argv=['gateway worlds']+sys.argv[2:]\nrunpy.run_module('gatewaysdk.environment.schema',run_name='__main__')`;\n\nexport type RuntimeMode = \"auto\" | \"local\" | \"platform\";\n\nexport function runtimeMode(): RuntimeMode {\n const raw = (process.env.GATEWAY_RUNTIME ?? \"auto\").toLowerCase();\n if (raw === \"local\" || raw === \"platform\" || raw === \"auto\") return raw;\n throw new CliError(\n `GATEWAY_RUNTIME must be local, platform or auto (got ${raw})`,\n );\n}\n\n/** Where the bundled runtime lives: `<package>/runtime` beside dist/, or the\n * monorepo's SDK source when running from the repository.\n *\n * The entry is `dist/cli.js` (the published bin) or `src/cli.ts` (from\n * source): one directory under the package root either way, so the Python\n * source is `<entry dir>/../../sdk/src` — `gatewaysdk/sdk/src`. It used to\n * walk one level too far (`<repo>/sdk/src`, which does not exist), so every\n * from-source run missed the runtime and fell back to the platform, demanding\n * a host for commands that need none (`schema init --connector salesforce`,\n * 2026-09-16). */\nexport function runtimeRoot(): string | null {\n const candidates: string[] = [];\n if (process.env.GATEWAY_RUNTIME_PATH)\n candidates.push(process.env.GATEWAY_RUNTIME_PATH);\n const entry =\n process.argv[1] && fs.existsSync(process.argv[1])\n ? path.dirname(fs.realpathSync(process.argv[1]))\n : null;\n if (entry) {\n candidates.push(path.resolve(entry, \"..\", \"runtime\"));\n candidates.push(path.resolve(entry, \"..\", \"..\", \"runtime\"));\n candidates.push(path.resolve(entry, \"..\", \"..\", \"sdk\", \"src\"));\n }\n candidates.push(path.resolve(process.cwd(), \"runtime\"));\n for (const root of candidates)\n if (\n fs.existsSync(\n path.join(root, \"gatewaysdk\", \"environment\", \"schema\", \"platform.py\"),\n )\n )\n return root;\n return null;\n}\n\nlet pythonCache: string | null | undefined;\n/** What the search saw, for the one line `pythonAdvice` prints: each candidate\n * and its version, or null when it did not run. */\nlet pythonProbes: { name: string; version: string | null }[] = [];\n\n/** Forget the cached interpreter (tests re-probe with a different PATH or env). */\nexport function resetPythonCache(): void {\n pythonCache = undefined;\n pythonProbes = [];\n}\n\n/** Versioned names first: on a Mac the bare `python3` is often the system 3.9,\n * while Homebrew, pyenv or uv put a `python3.12` beside it. Last, ask uv for\n * an interpreter it manages (`uv python find` prints a path and downloads\n * nothing). Brex retrospective: the customer had to discover GATEWAY_PYTHON\n * by hand because the CLI stopped at `python3` = 3.9. */\nconst PYTHON_CANDIDATES = [\n \"python3.13\",\n \"python3.12\",\n \"python3.11\",\n \"python3\",\n \"python\",\n];\nconst UV_FIND = [\"python\", \"find\", `>=${MIN_PYTHON.join(\".\")}`];\n\nfunction probeVersion(name: string): string | null {\n const probe = spawnSync(\n name,\n [\"-c\", \"import sys;print(sys.version_info[0],sys.version_info[1])\"],\n { encoding: \"utf8\", timeout: 10_000 },\n );\n if (probe.status !== 0) return null;\n const [major, minor] = probe.stdout.trim().split(/\\s+/).map(Number);\n return Number.isInteger(major) && Number.isInteger(minor)\n ? `${major}.${minor}`\n : null;\n}\n\nfunction atLeastMinimum(version: string): boolean {\n const [major, minor] = version.split(\".\").map(Number);\n return (\n major! > MIN_PYTHON[0] ||\n (major === MIN_PYTHON[0] && minor! >= MIN_PYTHON[1])\n );\n}\n\n/** The interpreter uv would hand out, or null when uv is absent or has none. */\nfunction uvPython(): string | null {\n const found = spawnSync(\"uv\", UV_FIND, { encoding: \"utf8\", timeout: 10_000 });\n if (found.status !== 0) return null;\n const line = found.stdout.trim().split(/\\r?\\n/)[0] ?? \"\";\n return line || null;\n}\n\n/** A python3 at or above 3.11, or null. Cached for the process. `GATEWAY_PYTHON`\n * names the interpreter and is the only candidate then; otherwise the versioned\n * names, the bare ones, then uv's. */\nexport function findPython(): string | null {\n if (pythonCache !== undefined) return pythonCache;\n const named = process.env.GATEWAY_PYTHON;\n const candidates = named ? [named] : PYTHON_CANDIDATES;\n for (const name of candidates) {\n const version = probeVersion(name);\n pythonProbes.push({ name, version });\n if (version && atLeastMinimum(version)) {\n pythonCache = name;\n return name;\n }\n }\n if (!named) {\n const fromUv = uvPython();\n const version = fromUv ? probeVersion(fromUv) : null;\n pythonProbes.push({ name: fromUv ?? \"uv python find\", version });\n if (fromUv && version && atLeastMinimum(version)) {\n pythonCache = fromUv;\n return fromUv;\n }\n }\n pythonCache = null;\n return null;\n}\n\n/** ONE actionable line for a machine without a usable Python: what was found\n * and how to point the CLI at a newer interpreter. */\nexport function pythonAdvice(): string {\n findPython();\n const floor = MIN_PYTHON.join(\".\");\n const named = process.env.GATEWAY_PYTHON;\n const seen = pythonProbes\n .filter((probe) => probe.version)\n .map((probe) => `${probe.name} is ${probe.version}`);\n const found = seen.length\n ? seen.join(\", \")\n : named\n ? `${named} did not run`\n : \"none on PATH\";\n return (\n `No python3 >= ${floor} usable (${found}); set GATEWAY_PYTHON to a newer interpreter, ` +\n `e.g. GATEWAY_PYTHON=\"$(brew --prefix python@3.12)/bin/python3.12\" or GATEWAY_PYTHON=\"$(uv python find 3.12)\".`\n );\n}\n\n/** Why `localRuntime()` answers null, in one line: the mode, the interpreter\n * or the bundled files — so a refusal never blames Python on a machine that\n * merely set GATEWAY_RUNTIME=platform. */\nexport function localRuntimeReason(): string {\n if (runtimeMode() === \"platform\")\n return \"GATEWAY_RUNTIME=platform forces the hosted side.\";\n if (!findPython()) return pythonAdvice();\n if (!runtimeRoot())\n return \"The bundled runtime is missing (set GATEWAY_RUNTIME_PATH).\";\n return \"\";\n}\n\n/** Can this machine run the runtime itself? Both a Python and the bundled files. */\nexport function localRuntime(): { python: string; root: string } | null {\n if (runtimeMode() === \"platform\") return null;\n const python = findPython();\n const root = runtimeRoot();\n if (!python || !root) {\n if (runtimeMode() === \"local\")\n throw new CliError(\n !python\n ? `GATEWAY_RUNTIME=local but ${pythonAdvice()}`\n : \"GATEWAY_RUNTIME=local but the bundled runtime is missing (set GATEWAY_RUNTIME_PATH)\",\n );\n return null;\n }\n return { python, root };\n}\n\n/** Does the local Python have PyYAML? `conform` needs it for .yaml specs. */\nexport function localPythonHasYaml(python: string): boolean {\n return (\n spawnSync(python, [\"-c\", \"import yaml\"], { timeout: 10_000 }).status === 0\n );\n}\n\n/** One bridge request through the local runtime: JSON in on stdin, JSON out. */\nexport async function localBridge<T = Record<string, unknown>>(\n request: RuntimeRequest,\n local: { python: string; root: string },\n opts: { timeoutMs?: number } = {},\n): Promise<T> {\n const input = JSON.stringify(request);\n return await new Promise<T>((resolve, reject) => {\n const child = spawn(\n local.python,\n [\"-I\", \"-B\", \"-c\", BRIDGE_BOOTSTRAP, local.root],\n {\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n // This is the author's machine running the author's world: the one\n // place the runtime may import and run a world's own Python (check's\n // handler execution, `worlds call`, `worlds test` tool cases).\n env: {\n PATH: process.env.PATH ?? \"\",\n HOME: process.env.HOME ?? \"\",\n TMPDIR: process.env.TMPDIR ?? \"\",\n GATEWAY_RUNTIME_EXECUTE: \"1\",\n },\n },\n );\n const out: Buffer[] = [];\n const err: Buffer[] = [];\n const timer = setTimeout(\n () => child.kill(\"SIGKILL\"),\n opts.timeoutMs ?? 300_000,\n );\n child.stdout.on(\"data\", (chunk: Buffer) => out.push(chunk));\n child.stderr.on(\"data\", (chunk: Buffer) => err.push(chunk));\n child.on(\"error\", (error) => {\n clearTimeout(timer);\n reject(\n new CliError(\n `local runtime could not start (${local.python}): ${error.message}`,\n 1,\n ),\n );\n });\n child.on(\"close\", (code) => {\n clearTimeout(timer);\n const text = Buffer.concat(out).toString(\"utf8\");\n const stderr = Buffer.concat(err).toString(\"utf8\");\n let payload: unknown = null;\n try {\n payload = text ? JSON.parse(text) : null;\n } catch {\n payload = null;\n }\n if (payload && typeof payload === \"object\") {\n resolve(payload as T);\n return;\n }\n reject(\n new CliError(\n `local runtime (${request.command}) exited ${code}: ${tailOf((stderr || text).trim()) || \"no output\"}`,\n 1,\n ),\n );\n });\n child.stdin.end(input);\n });\n}\n\n/** `pid <n> (<command>)` of whatever listens on `port`, from lsof when this\n * machine has it; null when nothing can be said. Best effort, never an error. */\nexport function portOwner(port: number): string | null {\n const found = spawnSync(\"lsof\", [\"-nP\", `-iTCP:${port}`, \"-sTCP:LISTEN\", \"-Fpc\"], {\n encoding: \"utf8\",\n timeout: 5_000,\n });\n if (found.error || found.status !== 0) return null;\n let pid: string | null = null;\n let command: string | null = null;\n for (const line of found.stdout.split(\"\\n\")) {\n if (line.startsWith(\"p\") && pid === null) pid = line.slice(1);\n else if (line.startsWith(\"c\") && pid !== null && command === null) command = line.slice(1);\n }\n if (pid === null) return null;\n return `pid ${pid}${command ? ` (${command})` : \"\"}`;\n}\n\n/** Refuse, by name, a port another process already holds — BEFORE the runtime\n * is spawned. The Python side refuses too, but a backgrounded serve's output\n * goes unread, and every curl after it hit whatever else answered on the port\n * (CRM dogfood, 2026-09-16): this serve never answers from another server. */\nexport async function assertPortFree(port: number, host = \"127.0.0.1\"): Promise<void> {\n const taken = await new Promise<boolean>((resolve) => {\n const probe = net.createServer();\n probe.once(\"error\", () => resolve(true));\n probe.listen(port, host, () => probe.close(() => resolve(false)));\n });\n if (!taken) return;\n const owner = portOwner(port);\n throw new CliError(\n `port ${port} on ${host} is already in use${owner ? ` by ${owner}` : \"\"}; ` +\n \"nothing was served there — pass another --port, or stop that server first\",\n 1,\n );\n}\n\n/** Run the schema module's own CLI in the foreground (serve, connector-capture …). */\nexport async function localModule(\n argv: string[],\n local: { python: string; root: string },\n opts: { env?: Record<string, string>; cwd?: string } = {},\n): Promise<number> {\n return await new Promise<number>((resolve, reject) => {\n const child = spawn(\n local.python,\n [\"-B\", \"-c\", MODULE_BOOTSTRAP, local.root, ...argv],\n {\n stdio: \"inherit\",\n cwd: opts.cwd,\n env: { ...process.env, ...opts.env },\n },\n );\n // The child owns the port (`worlds serve`); a signal that stops this\n // process must stop it too, or the server lives on with no way to reach\n // the foreground that started it. A SIGKILL, or a wrapper that swallows\n // the signal, reaches nothing here — for that the runtime's `serve`\n // watches its parent pid and closes when this process is gone.\n const forward = (signal: NodeJS.Signals) => () => {\n if (child.exitCode === null && child.signalCode === null) child.kill(signal);\n };\n const handlers: [NodeJS.Signals, () => void][] = [\n [\"SIGINT\", forward(\"SIGINT\")],\n [\"SIGTERM\", forward(\"SIGTERM\")],\n [\"SIGHUP\", forward(\"SIGHUP\")],\n ];\n for (const [signal, handler] of handlers) process.on(signal, handler);\n const release = () => {\n for (const [signal, handler] of handlers) process.off(signal, handler);\n };\n child.on(\"error\", (error) => {\n release();\n reject(\n new CliError(\n `local runtime could not start (${local.python}): ${error.message}`,\n 1,\n ),\n );\n });\n child.on(\"close\", (code, signal) => {\n release();\n resolve(code ?? (signal ? 130 : 1));\n });\n });\n}\n\n/** Credentials when the platform may be needed; null when a local runtime\n * will do and none are configured (a `schema check` needs no login). */\nexport function credentialsForRuntime(hostFlag?: string): Credentials | null {\n try {\n return resolveCredentials(hostFlag);\n } catch (error) {\n if (error instanceof CliError && localRuntime()) return null;\n throw error;\n }\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport { CliError } from \"../router\";\nimport { localBridge, localPythonHasYaml, localRuntime, localRuntimeReason } from \"./local\";\nimport type { Credentials } from \"../config\";\n\n/**\n * The wire to the schema runtime, which is Python and runs on the platform:\n * a world directory goes up as `[{path, content b64}]`, one bridge request\n * comes back verbatim, and any files in the answer land back in the\n * directory. Nothing here interprets a contract — that is the bridge's job.\n */\n\nexport type WorldFile = { path: string; content: string };\n\n/** Directories that are never part of a world's files. */\nconst SKIP_DIRS = new Set([\"__pycache__\", \".git\", \"node_modules\", \".gateway\"]);\n\n/** Every file under `dir` as base64 entries with forward-slash relative paths,\n * sorted so the same tree always produces the same request. */\n/** Compiled snapshots (`db/state.*`, `scenarios/<name>/state.*`) are build outputs\n * of the tree's data, never inputs: the runtime rebuilds them from the journals\n * and strips them from what it returns, and a real world's snapshots alone can\n * exceed the bridge's 64 MiB request cap. */\nconst BUILD_OUTPUT = /(^|\\/)state\\.(sqlite|json)$/;\n\nexport function isBuildOutput(relPath: string): boolean {\n return BUILD_OUTPUT.test(relPath);\n}\n\nexport function readWorldFiles(dir: string, opts: { buildOutputs?: boolean } = {}): WorldFile[] {\n if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())\n throw new CliError(`Not a directory: ${dir}`);\n const out: WorldFile[] = [];\n const walk = (rel: string) => {\n const abs = rel ? path.join(dir, rel) : dir;\n const entries = fs.readdirSync(abs, { withFileTypes: true });\n entries.sort((a, b) => a.name.localeCompare(b.name));\n for (const entry of entries) {\n const childRel = rel ? `${rel}/${entry.name}` : entry.name;\n if (entry.isDirectory()) {\n if (!SKIP_DIRS.has(entry.name)) walk(childRel);\n } else if (entry.isFile()) {\n if (!opts.buildOutputs && isBuildOutput(childRel)) continue;\n out.push({\n path: childRel,\n content: fs.readFileSync(path.join(dir, childRel)).toString(\"base64\"),\n });\n }\n }\n };\n walk(\"\");\n return out.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));\n}\n\nfunction assertSafeRelPath(rel: string): void {\n const parts = rel.split(\"/\");\n if (\n !rel ||\n rel.startsWith(\"/\") ||\n rel.includes(\"\\\\\") ||\n /^[A-Za-z]:/.test(rel) ||\n parts.some((p) => p === \"\" || p === \".\" || p === \"..\")\n )\n throw new CliError(`The runtime returned an unsafe file path: ${rel}`, 1);\n}\n\n/** Write bridge files into `dir`. With `clean`, files the runtime did not\n * return are removed first (the skipped dirs are left alone), so the tree\n * becomes exactly what the runtime holds. Returns the written paths. */\nexport function writeWorldFiles(\n dir: string,\n files: WorldFile[],\n opts: { clean?: boolean } = {},\n): string[] {\n for (const file of files) assertSafeRelPath(file.path);\n if (opts.clean && fs.existsSync(dir)) {\n const keep = new Set(files.map((f) => f.path));\n for (const existing of readWorldFiles(dir)) {\n if (!keep.has(existing.path)) fs.rmSync(path.join(dir, existing.path));\n }\n pruneEmptyDirs(dir);\n }\n fs.mkdirSync(dir, { recursive: true });\n const written: string[] = [];\n for (const file of files) {\n const target = path.join(dir, file.path);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n fs.writeFileSync(target, Buffer.from(file.content, \"base64\"));\n written.push(file.path);\n }\n return written;\n}\n\nfunction pruneEmptyDirs(root: string): void {\n const walk = (abs: string): boolean => {\n let empty = true;\n for (const entry of fs.readdirSync(abs, { withFileTypes: true })) {\n const child = path.join(abs, entry.name);\n if (entry.isDirectory()) {\n if (SKIP_DIRS.has(entry.name)) {\n empty = false;\n continue;\n }\n if (walk(child)) fs.rmdirSync(child);\n else empty = false;\n } else empty = false;\n }\n return empty;\n };\n walk(root);\n}\n\n/** The bridge's structured diagnostic, exactly as the Python ContractError\n * carries it (`code`, `message`, `path`, `schema_path`, plus context). */\nexport type BridgeErrorDetail = {\n code: string;\n message: string;\n path?: string;\n schema_path?: string;\n [key: string]: unknown;\n};\n\n/** Rendered the way the Python CLI prints a ContractError:\n * `{code} at {schema_path or path or '/'}: {message}`. */\nexport function formatBridgeError(detail: BridgeErrorDetail): string {\n const where = detail.schema_path || detail.path || \"/\";\n return `${detail.code} at ${where}: ${detail.message}`;\n}\n\nexport class BridgeRejected extends CliError {\n constructor(readonly detail: BridgeErrorDetail) {\n super(formatBridgeError(detail), 1);\n }\n}\n\nexport function detailFrom(payload: unknown): BridgeErrorDetail | null {\n if (!payload || typeof payload !== \"object\") return null;\n const error = (payload as { error?: unknown }).error;\n if (!error || typeof error !== \"object\") return null;\n const detail = error as Record<string, unknown>;\n if (typeof detail.code !== \"string\" || typeof detail.message !== \"string\") return null;\n return detail as BridgeErrorDetail;\n}\n\nexport type RuntimeRequest = { command: string } & Record<string, unknown>;\n\n/**\n * How a world directory travels on a request that runs it (check, test, call):\n * in place, as `world`, when the bundled runtime runs on this machine — so the\n * `[dependencies]` paths beside it resolve and its handlers may run — and as\n * `files` when the platform's bridge answers, which takes a tree and runs no\n * authored code.\n */\nexport function worldPayload(dir: string): { world: string } | { files: WorldFile[] } {\n const abs = path.resolve(dir);\n if (!fs.existsSync(abs) || !fs.statSync(abs).isDirectory()) throw new CliError(`Not a directory: ${abs}`);\n return localRuntime() ? { world: abs } : { files: readWorldFiles(abs) };\n}\n\n/**\n * `POST /api/public/worlds/runtime` with the bridge request verbatim. A\n * rejection — whether the platform relays it with a 4xx or as a 200 with\n * `status: \"rejected\"` — becomes a BridgeRejected; anything else non-OK is a\n * plain CliError with the status and body excerpt.\n */\nexport async function runtime<T extends Record<string, unknown> = Record<string, unknown>>(\n creds: Credentials | null,\n request: RuntimeRequest,\n opts: { timeoutMs?: number } = {},\n): Promise<T> {\n // This machine first, when it can: the bundled runtime with a local\n // python3 is what the platform runs anyway, minus the round trip. A .yaml\n // conform spec needs PyYAML, which the vendored runtime does not carry.\n const local = localRuntime();\n const yamlSpec =\n request.command === \"conform\" &&\n Array.isArray(request.openapi) &&\n (request.openapi as { path?: string }[]).some((doc) => /\\.ya?ml$/i.test(doc.path ?? \"\"));\n if (local && !(yamlSpec && !localPythonHasYaml(local.python))) {\n const payload = await localBridge<Record<string, unknown>>(request, local, opts);\n const detail = detailFrom(payload);\n if (detail) throw new BridgeRejected(detail);\n return payload as T;\n }\n if (!creds)\n throw new CliError(\n \"This needs the schema runtime (the CLI bundles it) or platform credentials (`gateway auth login`). \" +\n localRuntimeReason(),\n );\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), opts.timeoutMs ?? 180_000);\n const route = \"/api/public/worlds/runtime\";\n try {\n const res = await fetch(`${creds.host}${route}`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n accept: \"application/json\",\n authorization:\n \"Basic \" + Buffer.from(`${creds.publicKey}:${creds.secretKey}`).toString(\"base64\"),\n },\n body: JSON.stringify(request),\n signal: controller.signal,\n });\n const text = await res.text();\n let payload: unknown = null;\n try {\n payload = text ? JSON.parse(text) : {};\n } catch {\n payload = null;\n }\n const detail = detailFrom(payload);\n if (detail) throw new BridgeRejected(detail);\n if (!res.ok)\n throw new CliError(`POST ${route} (${request.command}) -> ${res.status}: ${text.slice(0, 600)}`, 1);\n if (payload === null) throw new CliError(`POST ${route} (${request.command}) returned non-JSON`, 1);\n return payload as T;\n } finally {\n clearTimeout(timer);\n }\n}\n\n/** Basic-auth headers for the few non-runtime routes this track calls. */\nexport function authHeaders(creds: Credentials): Record<string, string> {\n return {\n accept: \"application/json\",\n authorization:\n \"Basic \" + Buffer.from(`${creds.publicKey}:${creds.secretKey}`).toString(\"base64\"),\n };\n}\n\n/** Strip the `files` echo from a bridge report before printing it. */\nexport function withoutFiles<T extends Record<string, unknown>>(report: T): Omit<T, \"files\"> {\n const { files: _files, ...rest } = report;\n return rest;\n}\n\n/** JSON with sorted keys, the way the Python CLI prints bridge reports. */\nexport function sortedJson(value: unknown, indent = 2): string {\n const sort = (v: unknown): unknown => {\n if (Array.isArray(v)) return v.map(sort);\n if (v && typeof v === \"object\") {\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(v as Record<string, unknown>).sort())\n out[key] = sort((v as Record<string, unknown>)[key]);\n return out;\n }\n return v;\n };\n return JSON.stringify(sort(value), null, indent);\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport type { Credentials } from \"../config\";\nimport { CliError } from \"../router\";\nimport type { WorldQueryAcrossResult } from \"../../worlds/query\";\nimport {\n BridgeRejected,\n detailFrom,\n readWorldFiles,\n runtime,\n writeWorldFiles,\n type WorldFile,\n} from \"./client\";\nimport { localBridge, localRuntime, localRuntimeReason } from \"./local\";\n\n/**\n * Rows into, and counts out of, a world that lives in a LOCAL directory. The\n * `worlds data import|show` commands (registered by the platform track) call\n * these two for the directory case; a slug goes to the platform's world data\n * routes instead. The gate is the world's own contract, run by the platform\n * runtime: a bad row is refused with the field named and nothing is written.\n */\n\nexport type Rows = Record<string, Record<string, unknown>[]>;\nexport type ImportMode = \"append\" | \"replace\";\n\nexport type LocalImportResult = {\n kind: string;\n entity_counts: Record<string, number>;\n changed: boolean;\n /** Build outputs (`db/state.*`) dropped because the journals they were built from changed. */\n dropped_build_outputs?: string[];\n next?: string;\n};\n\nexport async function importLocalWorldData(\n dir: string,\n rows: Rows,\n opts: { mode?: ImportMode; merge?: \"upsert\" | \"fill\"; redact?: \"off\" | \"apply\" | \"refuse\" },\n creds: Credentials | null,\n): Promise<LocalImportResult> {\n const res = await runtime<{\n kind?: string;\n entity_counts?: Record<string, number>;\n changed?: boolean;\n files?: WorldFile[];\n }>(creds, {\n command: \"import-data\",\n files: readWorldFiles(dir),\n rows,\n mode: opts.mode ?? \"append\",\n ...(opts.merge && opts.merge !== \"upsert\" ? { merge: opts.merge } : {}),\n ...(opts.redact && opts.redact !== \"off\" ? { redact: opts.redact } : {}),\n });\n if (res.files?.length) writeWorldFiles(dir, res.files);\n // Snapshots are build outputs, not tree files: the runtime answers without\n // them, and the ones on disk were built from the journals BEFORE this import.\n // A served world ignores a stale snapshot and replays the journals, but the\n // files would still sit there claiming an older state — drop them, and let\n // `worlds schema compile` build them again from the data that is there now.\n const dropped = res.changed ? dropBuildOutputs(dir) : [];\n return {\n kind: res.kind ?? \"unknown\",\n entity_counts: res.entity_counts ?? {},\n changed: Boolean(res.changed),\n ...(dropped.length\n ? {\n dropped_build_outputs: dropped,\n next: `gateway worlds schema compile ${dir} # rebuilds the snapshots from the imported data`,\n }\n : {}),\n };\n}\n\nconst BUILD_OUTPUT = /(^|\\/)state\\.(sqlite|json)$/;\n\n/** Remove the compiled snapshots (`db/state.*`, `scenarios/<name>/state.*`)\n * that no longer match the tree's journals. */\nexport function dropBuildOutputs(dir: string): string[] {\n const dropped: string[] = [];\n for (const file of readWorldFiles(dir, { buildOutputs: true })) {\n if (!BUILD_OUTPUT.test(file.path)) continue;\n fs.rmSync(path.join(dir, file.path), { force: true });\n dropped.push(file.path);\n }\n return dropped;\n}\n\n/**\n * The same bridge import over the tree, with the answered files discarded:\n * the rows are checked through the world's contract and nothing on disk\n * changes. A refused row surfaces as a BridgeRejected, as an import would.\n */\nexport async function checkLocalWorldData(\n dir: string,\n rows: Rows,\n creds: Credentials | null,\n opts: { redact?: \"off\" | \"apply\" | \"refuse\" } = {},\n): Promise<LocalImportResult> {\n const res = await runtime<{\n kind?: string;\n entity_counts?: Record<string, number>;\n changed?: boolean;\n }>(creds, {\n command: \"import-data\",\n files: readWorldFiles(dir),\n rows,\n mode: \"append\",\n ...(opts.redact && opts.redact !== \"off\" ? { redact: opts.redact } : {}),\n });\n return {\n kind: res.kind ?? \"unknown\",\n entity_counts: res.entity_counts ?? {},\n changed: Boolean(res.changed),\n };\n}\n\nexport type LocalShowResult = {\n kind: string;\n entity_counts?: Record<string, number>;\n entity?: string;\n rows?: Record<string, unknown>[];\n};\n\nexport async function showLocalWorldData(\n dir: string,\n entity: string | undefined,\n creds: Credentials | null,\n): Promise<LocalShowResult> {\n const res = await runtime<{\n kind?: string;\n entity_counts?: Record<string, number>;\n rows?: Record<string, unknown>[];\n }>(creds, {\n command: \"counts\",\n files: readWorldFiles(dir),\n ...(entity ? { entity } : {}),\n });\n const out: LocalShowResult = { kind: res.kind ?? \"unknown\" };\n if (entity) {\n out.entity = entity;\n out.rows = res.rows ?? [];\n } else out.entity_counts = res.entity_counts ?? {};\n return out;\n}\n\n/** field → stored value, or a list of them (any of). */\nexport type LocalQueryWhere = Record<string, string | string[]>;\n\nexport type LocalQueryOptions = {\n /** The `where` values are plaintext: the runtime resolves each to its stored form first. */\n resolve?: boolean;\n limit?: number;\n offset?: number;\n /** Read the rows a session opened in this scenario starts from (schema worlds). */\n scenario?: string;\n};\n\nexport type LocalQueryResult = {\n kind?: string;\n entity: string;\n scenario?: string;\n rows: Record<string, unknown>[];\n count: number;\n total: number | null;\n limit: number;\n offset: number;\n /** With `resolve`: the stored forms each field was matched against (`[]` for a dropped field). */\n resolved?: Record<string, (string | number)[]>;\n};\n\n/**\n * The bridge's `query` over the tree: one entity's rows matching `where`.\n * A refused query (unknown entity or field) surfaces as a BridgeRejected.\n */\nexport async function queryLocalWorldData(\n dir: string,\n entity: string,\n where: LocalQueryWhere,\n opts: LocalQueryOptions,\n creds: Credentials | null,\n): Promise<LocalQueryResult> {\n const res = await runtime<{\n kind?: string;\n entity?: string;\n rows?: Record<string, unknown>[];\n count?: number;\n total?: number | null;\n limit?: number;\n offset?: number;\n scenario?: string;\n resolved?: Record<string, (string | number)[]>;\n }>(creds, {\n command: \"query\",\n files: readWorldFiles(dir),\n entity,\n ...(Object.keys(where).length ? { where } : {}),\n ...(opts.limit !== undefined ? { limit: opts.limit } : {}),\n ...(opts.offset !== undefined ? { offset: opts.offset } : {}),\n ...(opts.resolve ? { resolve: true } : {}),\n ...(opts.scenario ? { scenario: opts.scenario } : {}),\n });\n const rows = res.rows ?? [];\n return {\n ...(res.kind ? { kind: res.kind } : {}),\n entity: res.entity ?? entity,\n ...(res.scenario ? { scenario: res.scenario } : {}),\n rows,\n count: res.count ?? rows.length,\n total: res.total ?? null,\n limit: res.limit ?? opts.limit ?? rows.length,\n offset: res.offset ?? opts.offset ?? 0,\n ...(res.resolved ? { resolved: res.resolved } : {}),\n };\n}\n\n/** A local across answer: the platform's groups, each world named by its\n * manifest name (the root) or its pin's slug (a dependency); no version ids,\n * since the trees are read where they sit. */\nexport type LocalQueryAcrossResult = {\n kind?: string;\n entity: string;\n groups: (Omit<WorldQueryAcrossResult[\"groups\"][number], \"world\"> & { world: { slug: string; alias: string | null } })[];\n compare?: WorldQueryAcrossResult[\"compare\"];\n};\n\n/**\n * The bridge's `query` with `across` over the tree in place: the root's rows\n * and, per `[dependencies.<alias>.entities]` mapping that carries a `where`\n * field, the linked world's, read at its `path`. Needs the bundled runtime on\n * this machine, as the paths beside the tree must resolve.\n */\nexport async function queryLocalWorldDataAcross(\n dir: string,\n entity: string,\n where: LocalQueryWhere,\n opts: LocalQueryOptions & { compare?: boolean },\n): Promise<LocalQueryAcrossResult> {\n const local = localRuntime();\n if (!local)\n throw new CliError(\n \"`--across` on a directory reads the linked worlds at their paths, so it needs the bundled runtime on this machine. \" +\n localRuntimeReason(),\n 1,\n );\n const payload = await localBridge<Record<string, unknown>>(\n {\n command: \"query\",\n world: path.resolve(dir),\n entity,\n across: true,\n ...(opts.compare ? { compare: true } : {}),\n ...(Object.keys(where).length ? { where } : {}),\n ...(opts.limit !== undefined ? { limit: opts.limit } : {}),\n ...(opts.offset !== undefined ? { offset: opts.offset } : {}),\n ...(opts.resolve ? { resolve: true } : {}),\n ...(opts.scenario ? { scenario: opts.scenario } : {}),\n },\n local,\n );\n const detail = detailFrom(payload);\n if (detail) throw new BridgeRejected(detail);\n return payload as unknown as LocalQueryAcrossResult;\n}\n\n// ---------------------------------------------------------------- tool calls\n\nexport type LocalIngestRefusal = { index: number | null; tool: string | null; reason: string; pointer?: string };\n\n/** One `[[sources]]` of a mapping in the report: what it saw and what it did not touch. */\nexport type LocalIngestSource = {\n name: string;\n kind: string;\n select: string;\n entity: string;\n records: number;\n items: number;\n rows: Record<string, number>;\n /** Source fields no line of the source reads, with a sample value. */\n unmapped_fields: Record<string, string>;\n /** Entity fields the source never sets, per entity it lands in. */\n unset_fields: Record<string, string[]>;\n};\n\n/** The bridge's `ingest-calls` report (the Python `ingest.ingest_records`). */\nexport type LocalIngestResult = {\n /** How the rows were produced: a declared mapping, the operations' projection, or rows as given. */\n via?: \"map\" | \"operations\" | \"rows\" | \"transform\";\n records: number;\n ingested: number;\n skipped: Record<string, number>;\n refusals: LocalIngestRefusal[];\n rows: Record<string, number>;\n /** The projected rows themselves, as the tools returned them (before any redaction). */\n projected?: Rows;\n /** `via: \"map\"`: each source's accounting. */\n sources?: LocalIngestSource[];\n /** `via: \"map\"` with `unmatched = \"skip\"`: records no source claimed, by tool name. */\n unmatched?: Record<string, number>;\n /** `via: \"operations\"`: that the rows came through the operation projection, not a mapping. */\n note?: string;\n dry_run: boolean;\n redact: \"off\" | \"apply\" | \"refuse\";\n changed: boolean;\n kind?: string;\n entity_counts?: Record<string, number>;\n batch?: string | null;\n};\n\n/**\n * Tool-call records into a world in a LOCAL directory, through the runtime's\n * `ingest-calls`: each record's tool resolves to an operation of the world's\n * `connector.toml`, its result goes through that operation's projection the\n * way a capture does, and the rows through the world's contract. An unknown\n * tool is a refusal in the report (nothing written); a row the contract\n * refuses surfaces as a BridgeRejected, as an import would. Redaction is\n * optional and off by default. With `dryRun` the tree is untouched.\n */\nexport async function ingestLocalToolCalls(\n dir: string,\n records: unknown[],\n opts: { redact?: \"off\" | \"apply\" | \"refuse\"; dryRun?: boolean; mode?: ImportMode; map?: string | Record<string, unknown> },\n creds: Credentials | null,\n): Promise<LocalIngestResult> {\n const res = await runtime<Partial<LocalIngestResult> & { files?: WorldFile[] }>(creds, {\n command: \"ingest-calls\",\n files: readWorldFiles(dir),\n records,\n mode: opts.mode ?? \"append\",\n ...(opts.dryRun ? { dry_run: true } : {}),\n ...(opts.redact && opts.redact !== \"off\" ? { redact: opts.redact } : {}),\n ...(opts.map !== undefined ? { map: opts.map } : {}),\n });\n if (!opts.dryRun && res.files?.length) writeWorldFiles(dir, res.files);\n if (res.changed) dropBuildOutputs(dir);\n return {\n ...(res.via ? { via: res.via } : {}),\n ...(res.sources ? { sources: res.sources } : {}),\n ...(res.unmatched ? { unmatched: res.unmatched } : {}),\n ...(res.note ? { note: res.note } : {}),\n records: res.records ?? records.length,\n ingested: res.ingested ?? 0,\n skipped: res.skipped ?? {},\n refusals: res.refusals ?? [],\n rows: res.rows ?? {},\n ...(res.projected ? { projected: res.projected } : {}),\n dry_run: Boolean(res.dry_run ?? opts.dryRun),\n redact: res.redact ?? opts.redact ?? \"off\",\n changed: Boolean(res.changed),\n ...(res.kind ? { kind: res.kind } : {}),\n ...(res.entity_counts ? { entity_counts: res.entity_counts } : {}),\n ...(res.batch !== undefined ? { batch: res.batch } : {}),\n };\n}\n","import { spawn } from \"node:child_process\";\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport { createRequire } from \"node:module\";\n\nimport { CliError } from \"../../router\";\nimport type { Rows } from \"../rows\";\n\n/**\n * `--transform`: the agent's own code turns records into rows (the Python\n * `schema.transform`, wrapper for wrapper). A script — `.py`, or `.ts` /\n * `.mjs` / `.js` / `.cjs` for node — either exports `transform(records) ->\n * {entity: [rows]}` (node: `transform` or the default export) or reads the\n * records as JSONL on stdin and prints the rows document on stdout.\n *\n * The script runs in a subprocess with a time limit, its stderr passed\n * through. The wrapper disables sockets (Python) and `net`/`tls`/`http`/\n * `dgram`/`fetch` (node) before the script loads, and the child gets no\n * `GATEWAY_*` or proxy variables. That is a guard, not a sandbox: a\n * transform is the agent's own code, run on the agent's own machine.\n */\n\nexport const DEFAULT_TRANSFORM_TIMEOUT_MS = 120_000;\nexport const NODE_SUFFIXES = [\".ts\", \".mts\", \".mjs\", \".js\", \".cjs\"];\nexport const PYTHON_SUFFIXES = [\".py\"];\nconst SCRUBBED = /^(GATEWAY_|HTTPS?_PROXY$|ALL_PROXY$|https?_proxy$|all_proxy$)/;\n\nexport const PY_WRAPPER = `\nimport io, json, runpy, socket, sys\n\ndef _deny(*args, **kwargs):\n raise RuntimeError(\"network is disabled in a transform\")\n\nclass _Denied(socket.socket):\n def __init__(self, *args, **kwargs):\n _deny()\n\nsocket.socket = _Denied\nsocket.SocketType = _Denied\nsocket.create_connection = _deny\nsocket.getaddrinfo = _deny\n\ntext = sys.stdin.read()\nrecords = [json.loads(line) for line in text.splitlines() if line.strip()]\nsys.stdin = io.StringIO(text)\ncaptured = io.StringIO()\nreal = sys.stdout\nsys.stdout = captured\ntry:\n namespace = runpy.run_path(sys.argv[1], run_name=\"__main__\")\nfinally:\n sys.stdout = real\nfn = namespace.get(\"transform\")\nif callable(fn):\n out = fn(records)\nelse:\n printed = captured.getvalue().strip()\n if not printed:\n sys.stderr.write(\"the transform defines no transform(records) and printed nothing\\\\n\")\n sys.exit(3)\n out = json.loads(printed)\nreal.write(json.dumps(out))\n`;\n\nexport const NODE_WRAPPER = `\nimport { pathToFileURL } from \"node:url\";\nimport net from \"node:net\";\nimport tls from \"node:tls\";\nimport http from \"node:http\";\nimport https from \"node:https\";\nimport dgram from \"node:dgram\";\n\nconst deny = () => { throw new Error(\"network is disabled in a transform\"); };\nnet.Socket.prototype.connect = deny;\nnet.connect = deny;\nnet.createConnection = deny;\ntls.connect = deny;\nhttp.request = deny;\nhttp.get = deny;\nhttps.request = deny;\nhttps.get = deny;\ndgram.createSocket = deny;\nglobalThis.fetch = deny;\n\nconst module = await import(pathToFileURL(process.argv[2]).href);\nconst fn = typeof module.transform === \"function\" ? module.transform : typeof module.default === \"function\" ? module.default : null;\nif (fn) {\n const chunks = [];\n for await (const chunk of process.stdin) chunks.push(chunk);\n const text = Buffer.concat(chunks).toString(\"utf8\");\n const records = text.split(\"\\\\n\").filter((line) => line.trim()).map((line) => JSON.parse(line));\n const out = await fn(records);\n process.stdout.write(JSON.stringify(out));\n}\n`;\n\nconst isObject = (value: unknown): value is Record<string, unknown> => typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/** `value` as the rows document `{entity: [rows]}`, or a CliError saying what shape it has instead. */\nexport function checkRows(value: unknown, where: string): Rows {\n if (!isObject(value)) throw new CliError(`${where} must return {entity: [rows]}; got ${value === null ? \"null\" : Array.isArray(value) ? \"an array\" : typeof value}`, 1);\n for (const [entity, listed] of Object.entries(value)) {\n if (!Array.isArray(listed)) throw new CliError(`${where}: ${entity} must be a list of rows; got ${listed === null ? \"null\" : typeof listed}`, 1);\n listed.forEach((row, index) => {\n if (!isObject(row)) throw new CliError(`${where}: ${entity}[${index}] is not an object`, 1);\n });\n }\n return value as Rows;\n}\n\n/**\n * How this node runs a `.ts` transform: built-in type stripping from Node\n * 22.6 on; before that, the `tsx` command-line entry when tsx is installed\n * beside the CLI (a dev dependency here, present on CI's Node 20); otherwise\n * a refusal that names both options instead of a stack trace from node.\n * Returns the argv prefix that goes in front of the wrapper.\n */\nfunction typescriptPrefix(): string[] {\n const [major, minor] = process.versions.node.split(\".\").map(Number);\n if (!process.env.GATEWAY_NODE && (major > 22 || (major === 22 && minor >= 6))) return [\"--experimental-strip-types\", \"--no-warnings\"];\n try {\n return [createRequire(import.meta.url).resolve(\"tsx/cli\")];\n } catch {\n throw new CliError(\n `a .ts transform needs Node 22.6 or newer (built-in type stripping; this is ${process.versions.node}) or the tsx package installed beside the CLI; write the transform as .mjs or .py, or set GATEWAY_NODE to a newer node`,\n 1,\n );\n }\n}\n\nfunction command(script: string, wrapperDir: string): { file: string; args: string[] } {\n const suffix = path.extname(script).toLowerCase();\n if (PYTHON_SUFFIXES.includes(suffix)) return { file: process.env.GATEWAY_PYTHON || \"python3\", args: [\"-c\", PY_WRAPPER, script] };\n if (NODE_SUFFIXES.includes(suffix)) {\n const wrapper = path.join(wrapperDir, \"transform-wrapper.mjs\");\n fs.writeFileSync(wrapper, NODE_WRAPPER);\n const flags = suffix === \".ts\" || suffix === \".mts\" ? typescriptPrefix() : [];\n return { file: process.env.GATEWAY_NODE || process.execPath, args: [...flags, wrapper, script] };\n }\n throw new CliError(`${path.basename(script)}: a transform script is .py, .ts, .mjs, .js or .cjs`, 1);\n}\n\nconst tail = (stderr: string, lines = 12): string => {\n const kept = stderr\n .split(\"\\n\")\n .filter((line) => line.trim())\n .slice(-lines);\n return kept.length ? \"\\n\" + kept.join(\"\\n\") : \"\";\n};\n\n/**\n * Run `script` over `records`: the rows document it returns and its stderr.\n * A non-zero exit, a timeout, or output that is not the rows document is a\n * CliError (exit 1) carrying the tail of the script's stderr.\n */\nexport async function runTransform(script: string, records: unknown[], opts: { timeoutMs?: number } = {}): Promise<{ rows: Rows; stderr: string }> {\n if (!fs.existsSync(script) || !fs.statSync(script).isFile()) throw new CliError(`no transform script at ${script}`, 1);\n const resolved = path.resolve(script);\n const name = path.basename(script);\n const timeoutMs = opts.timeoutMs ?? DEFAULT_TRANSFORM_TIMEOUT_MS;\n const scratch = fs.mkdtempSync(path.join(os.tmpdir(), \"gateway-transform-\"));\n try {\n const { file, args } = command(resolved, scratch);\n const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !SCRUBBED.test(key)));\n const done = await new Promise<{ code: number | null; stdout: string; stderr: string; timedOut: boolean }>((resolve, reject) => {\n const child = spawn(file, args, { cwd: path.dirname(resolved), env, stdio: [\"pipe\", \"pipe\", \"pipe\"] });\n let stdout = \"\";\n let stderr = \"\";\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n child.kill(\"SIGKILL\");\n }, timeoutMs);\n child.stdout.setEncoding(\"utf8\").on(\"data\", (chunk: string) => (stdout += chunk));\n child.stderr.setEncoding(\"utf8\").on(\"data\", (chunk: string) => (stderr += chunk));\n child.on(\"error\", (error) => {\n clearTimeout(timer);\n reject(new CliError(`${name}: cannot run ${file}: ${error.message}`, 1));\n });\n child.on(\"close\", (code) => {\n clearTimeout(timer);\n resolve({ code, stdout, stderr, timedOut });\n });\n child.stdin.on(\"error\", () => undefined);\n child.stdin.end(records.map((record) => JSON.stringify(record) + \"\\n\").join(\"\"));\n });\n if (done.timedOut) throw new CliError(`${name} timed out after ${timeoutMs / 1000}s${tail(done.stderr)}`, 1);\n if (done.code !== 0) throw new CliError(`${name} exited ${done.code ?? \"?\"}${tail(done.stderr)}`, 1);\n let value: unknown;\n try {\n value = done.stdout.trim() ? JSON.parse(done.stdout) : null;\n } catch {\n throw new CliError(`${name} printed something other than the rows document${tail(done.stderr)}`, 1);\n }\n return { rows: checkRows(value, name), stderr: done.stderr };\n } finally {\n fs.rmSync(scratch, { recursive: true, force: true });\n }\n}\n\n/** A transform given to the SDK: a function, or a script path run as above. */\nexport type TransformLike = string | ((records: unknown[]) => Rows | Promise<Rows>);\n\nexport async function transformRecords(transform: TransformLike, records: unknown[], opts: { timeoutMs?: number } = {}): Promise<{ rows: Rows; stderr: string }> {\n if (typeof transform === \"function\") return { rows: checkRows(await transform(records), \"transform(records)\"), stderr: \"\" };\n return runTransform(transform, records, opts);\n}\n","import { createHash } from \"node:crypto\";\nimport * as fs from \"node:fs\";\n\nimport { api, type Credentials } from \"../../config\";\nimport { CliError } from \"../../router\";\nimport type { BuiltChunk } from \"./chunker\";\nimport type { ManifestChunk } from \"./manifest\";\n\n/**\n * The batch protocol of `/api/public/worlds/{slug}/data` (contract §7): open\n * a batch, register each chunk by digest (the server hands back a presigned\n * PUT, or says it already holds that content), confirm the upload, complete,\n * then poll. Thin on purpose: the server owns validation and the ledger.\n */\n\nexport type Refusal = {\n chunk: number;\n index: number;\n entity: string | null;\n primaryKey: Record<string, unknown> | null;\n field: string | null;\n pointer: string;\n detail: string;\n};\n\nexport type BatchStatus = {\n batchId: string;\n state: string;\n mode?: string;\n merge?: string;\n atomic?: boolean;\n dryRun?: boolean;\n publish?: string;\n chunks?: number;\n uploadedChunks?: number;\n rows?: number;\n refusalCount?: number;\n refusals?: Refusal[];\n reportUrl?: string;\n progress?: { phase?: string; validatedChunks?: number; appliedRows?: number };\n entityCounts?: Record<string, number>;\n snapshotId?: string | null;\n batchDigest?: string | null;\n versionId?: string | null;\n error?: string | null;\n createdAt?: string;\n updatedAt?: string;\n};\n\nexport type OpenBatchBody = {\n mode: \"append\" | \"replace\";\n merge: \"upsert\" | \"fill\";\n redact?: \"off\" | \"apply\" | \"refuse\";\n atomic: boolean;\n dryRun: boolean;\n publish: \"now\" | \"later\";\n message?: string;\n expectedChunks?: number;\n entities?: string[];\n};\n\nexport type OpenedBatch = { batchId: string; state: string; limits?: { chunkBytes?: number; batchBytes?: number; inlineBytes?: number } };\n\nexport type RegisteredChunk = {\n chunkId: string;\n uploaded: boolean;\n uploadUrl?: string;\n /** Headers the presigned PUT was signed for (content-type, content-length, x-amz-checksum-sha256); sent exactly. */\n uploadHeaders?: Record<string, string>;\n expiresAt?: string;\n};\n\nexport const TERMINAL_STATES = new Set([\"applied\", \"refused\", \"published\", \"failed\"]);\n\nexport const sleepMs = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));\n\nexport class WorldDataApi {\n readonly base: string;\n constructor(\n readonly creds: Credentials,\n readonly slug: string,\n /** Injectable for tests: the pause between retries and polls. */\n readonly sleep: (ms: number) => Promise<void> = sleepMs,\n ) {\n this.base = `/api/public/worlds/${encodeURIComponent(slug)}/data`;\n }\n\n open(body: OpenBatchBody): Promise<OpenedBatch> {\n return api<OpenedBatch>(this.creds, \"POST\", `${this.base}/batches`, body);\n }\n\n register(batchId: string, chunk: { ordinal: number; digest: string; bytes: number; rows: number; entity: string | null }): Promise<RegisteredChunk> {\n return api<RegisteredChunk>(this.creds, \"POST\", `${this.base}/batches/${batchId}/chunks`, {\n ordinal: chunk.ordinal,\n digest: chunk.digest,\n bytes: chunk.bytes,\n rows: chunk.rows,\n ...(chunk.entity ? { entity: chunk.entity } : {}),\n });\n }\n\n markUploaded(batchId: string, chunkId: string): Promise<{ chunkId: string; uploaded: boolean; bytes: number }> {\n return api(this.creds, \"POST\", `${this.base}/batches/${batchId}/chunks/${chunkId}/uploaded`);\n }\n\n complete(batchId: string): Promise<{ batchId: string; state: string }> {\n return api(this.creds, \"POST\", `${this.base}/batches/${batchId}/complete`);\n }\n\n get(batchId: string): Promise<BatchStatus> {\n return api<BatchStatus>(this.creds, \"GET\", `${this.base}/batches/${batchId}`);\n }\n\n list(limit?: number, cursor?: string): Promise<{ batches: BatchStatus[]; nextCursor?: string }> {\n const params = new URLSearchParams();\n if (limit !== undefined) params.set(\"limit\", String(limit));\n if (cursor) params.set(\"cursor\", cursor);\n const q = params.toString();\n return api(this.creds, \"GET\", `${this.base}/batches${q ? `?${q}` : \"\"}`);\n }\n\n publish(message?: string): Promise<{ versionId: string; snapshotId: string; batchIds: string[] }> {\n return api(this.creds, \"POST\", `${this.base}/publish`, message ? { message } : {});\n }\n\n /**\n * PUT the gzipped chunk to its presigned URL with exactly the headers the\n * URL was signed for (the platform's `uploadHeaders`; the same three when it\n * sends none), with backoff on a dropped connection or a 5xx.\n */\n async put(uploadUrl: string, gz: Buffer, signed?: Record<string, string>): Promise<void> {\n const headers = signed ?? uploadHeadersFor(gz);\n const delays = [500, 1500, 4000];\n for (let attempt = 0; ; attempt++) {\n try {\n const res = await fetch(uploadUrl, { method: \"PUT\", body: new Uint8Array(gz), headers });\n if (res.ok) return;\n if (res.status < 500 || attempt >= delays.length) throw new CliError(`chunk upload -> ${res.status}: ${(await res.text()).slice(0, 300)}`, 1);\n } catch (error) {\n if (error instanceof CliError || attempt >= delays.length) throw error instanceof CliError ? error : new CliError(`chunk upload failed: ${(error as Error).message}`, 1);\n }\n await this.sleep(delays[attempt]!);\n }\n }\n\n /** Register, upload unless the server already holds the content, confirm. */\n async upload(batchId: string, chunk: BuiltChunk): Promise<ManifestChunk> {\n const registered = await this.register(batchId, chunk);\n if (!registered.uploaded) {\n if (!registered.uploadUrl) throw new CliError(`the server registered chunk ${chunk.ordinal} without an upload URL`, 1);\n await this.put(registered.uploadUrl, chunk.gz, registered.uploadHeaders);\n await this.markUploaded(batchId, registered.chunkId);\n }\n return { ordinal: chunk.ordinal, digest: chunk.digest, bytes: chunk.bytes, rows: chunk.rows, entity: chunk.entity, chunkId: registered.chunkId, uploaded: true };\n }\n}\n\n/** What a chunk's presigned PUT is signed for: its type, size and sha256 (base64, S3's spelling). */\nexport function uploadHeadersFor(gz: Buffer): Record<string, string> {\n return {\n \"content-type\": \"application/gzip\",\n \"content-length\": String(gz.length),\n \"x-amz-checksum-sha256\": createHash(\"sha256\").update(gz).digest(\"base64\"),\n };\n}\n\n/** Run `fn` over an async stream with at most `limit` in flight; results in input order. */\nexport async function forEachLimited<T>(items: AsyncIterable<T>, limit: number, fn: (item: T) => Promise<void>): Promise<void> {\n const inFlight = new Set<Promise<void>>();\n let failure: unknown = null;\n const track = (p: Promise<void>) => {\n const wrapped: Promise<void> = p.then(\n () => {\n inFlight.delete(wrapped);\n },\n (error) => {\n failure ??= error;\n inFlight.delete(wrapped);\n },\n );\n inFlight.add(wrapped);\n };\n for await (const item of items) {\n if (failure) break;\n track(fn(item));\n if (inFlight.size >= limit) await Promise.race(inFlight);\n }\n await Promise.all(inFlight);\n if (failure) throw failure;\n}\n\nexport type WaitOptions = {\n /** Called once per phase change with a printable line. */\n onPhase?: (line: string) => void;\n sleep?: (ms: number) => Promise<void>;\n /** The first pause between polls (default 1 s; GATEWAY_WORLD_DATA_POLL_MS in the CLI). */\n initialDelayMs?: number;\n};\n\n/** Poll until the batch settles; 1 s growing to 10 s between polls. */\nexport async function waitForBatch(client: WorldDataApi, batchId: string, opts: WaitOptions = {}): Promise<BatchStatus> {\n const sleep = opts.sleep ?? client.sleep;\n let delay = opts.initialDelayMs ?? 1000;\n let last = \"\";\n for (;;) {\n const status = await client.get(batchId);\n const phase = phaseLine(status);\n if (phase !== last) {\n opts.onPhase?.(phase);\n last = phase;\n }\n if (TERMINAL_STATES.has(status.state)) return status;\n await sleep(delay);\n delay = Math.min(10_000, Math.round(delay * 1.5));\n }\n}\n\n/** The Python CLI's progress line: `state`, with the job's phase in parentheses when it has one. */\nexport function phaseLine(status: BatchStatus): string {\n const phase = status.progress?.phase;\n return phase ? `${status.state} (${phase})` : status.state;\n}\n\n/**\n * The refusal report as JSONL: the server's full report when it has one\n * (`reportUrl`), else the records the status carries inline. Returns the\n * number of lines written.\n */\nexport async function writeRefusalReport(status: BatchStatus, file: string): Promise<number> {\n let text: string;\n if (status.reportUrl) {\n const res = await fetch(status.reportUrl);\n if (!res.ok) throw new CliError(`refusal report -> ${res.status}`, 1);\n text = await res.text();\n if (text && !text.endsWith(\"\\n\")) text += \"\\n\";\n } else text = (status.refusals ?? []).map((r) => JSON.stringify(r) + \"\\n\").join(\"\");\n fs.writeFileSync(file, text);\n return text ? text.split(\"\\n\").filter(Boolean).length : 0;\n}\n","import { createHash } from \"node:crypto\";\nimport { deflateRawSync } from \"node:zlib\";\n\nimport { dumps, type JsonObject } from \"./json\";\nimport type { TaggedRow } from \"./rowSource\";\n\n/**\n * Rows into chunks: gzip over JSONL, cut on row boundaries at `--chunk-rows`\n * or `--chunk-bytes` (uncompressed), content-addressed by the sha256 of the\n * gzipped bytes. The same rows with the same flags give the same content\n * digests (over the JSONL) in both CLIs and on every platform, and the same\n * gzip digests wherever the two zlibs deflate alike: lines are the Python\n * serialisation (`dumps`), the deflate stream is zlib's at level 9, and the\n * gzip header is written here rather than by zlib, as CPython's\n * `gzip.compress(…, mtime=0)` writes it — zlib would stamp the platform's OS\n * byte instead. Node 20 and 24 bundle Chromium's zlib, which deflates\n * differently from CPython's stock zlib, so a chunk's gzip digest can differ\n * between CLIs while its content digest agrees; `--resume` keys on the digest\n * of what this CLI wrote, so it is unaffected. See `zlibDeflatesLikeCPython`.\n */\n\nexport const DEFAULT_CHUNK_BYTES = 64 * 1024 * 1024;\nexport const GZIP_LEVEL = 9;\n\nexport type ChunkPlan = {\n /** Always bound: the Python CLI keeps 64 MiB even with --chunk-rows. */\n chunkBytes: number;\n chunkRows: number | null;\n /** When set, chunks are declared with this entity and lines are bare rows. */\n entity: string | null;\n};\n\nexport type BuiltChunk = {\n ordinal: number;\n /** sha256 of the gzipped bytes, hex. */\n digest: string;\n /** Gzipped size. */\n bytes: number;\n rows: number;\n entity: string | null;\n /** Uncompressed JSONL size (`contentBytes` in the shared manifest). */\n rawBytes: number;\n /** sha256 of the uncompressed JSONL: the cross-zlib parity check. */\n contentSha256: string;\n /** Index of the chunk's first row in the input stream. */\n firstRow: number;\n gz: Buffer;\n};\n\n/** One row as the line a chunk carries: tagged, or bare when the chunk declares its entity. */\nexport function chunkLine(row: TaggedRow, declared: string | null): string {\n if (declared !== null) return dumps(row.row) + \"\\n\";\n const tagged: JsonObject = new Map();\n tagged.set(\"entity\", row.entity);\n tagged.set(\"row\", row.row);\n return dumps(tagged) + \"\\n\";\n}\n\nexport async function* buildChunks(rows: AsyncIterable<TaggedRow>, plan: ChunkPlan): AsyncGenerator<BuiltChunk> {\n let lines: Buffer[] = [];\n let rawBytes = 0;\n let ordinal = 0;\n let seen = 0;\n const flush = (): BuiltChunk => {\n const raw = Buffer.concat(lines);\n const built = finishChunk(ordinal++, raw, lines.length, plan.entity, seen - lines.length);\n lines = [];\n rawBytes = 0;\n return built;\n };\n for await (const row of rows) {\n const line = Buffer.from(chunkLine(row, plan.entity), \"utf8\");\n const full =\n lines.length > 0 &&\n ((plan.chunkRows !== null && lines.length >= plan.chunkRows) ||\n rawBytes + line.length > plan.chunkBytes);\n if (full) yield flush();\n lines.push(line);\n rawBytes += line.length;\n seen++;\n }\n if (lines.length) yield flush();\n}\n\nexport function finishChunk(ordinal: number, raw: Buffer, rows: number, entity: string | null, firstRow = 0): BuiltChunk {\n const gz = gzipDeterministic(raw, { name: chunkName(ordinal) });\n return {\n ordinal,\n digest: createHash(\"sha256\").update(gz).digest(\"hex\"),\n bytes: gz.length,\n rows,\n entity,\n rawBytes: raw.length,\n contentSha256: createHash(\"sha256\").update(raw).digest(\"hex\"),\n firstRow,\n gz,\n };\n}\n\n/**\n * Whether this Node's zlib deflates as the CPython that wrote the fixtures\n * did. Deflate output is a property of the zlib build, not of the format:\n * the same input inflates everywhere, but a zlib-ng or a future Chromium\n * zlib may pick different matches, and then gzip digests differ across\n * CLIs while content digests (over the JSONL) still agree. The manifest\n * parity check is on the content; the gzip digest is informative.\n */\nexport function zlibDeflatesLikeCPython(): boolean {\n return deflateRawSync(Buffer.from(CPYTHON_PROBE_TEXT), { level: GZIP_LEVEL }).toString(\"hex\") === CPYTHON_PROBE_DEFLATE;\n}\n/**\n * Two tagged rows, as the chunker writes them, and CPython's deflate of them (zlib\n * 1.2.12, which also wrote the fixtures). The probe has to be this long: \"hello\\n\"\n * deflates identically on every zlib, so it proved nothing, while on this text\n * Node 20 and 24 (Chromium's zlib 1.3.1) pick different matches and land two\n * bytes shorter than Node 25 and CPython (stock zlib).\n */\nconst CPYTHON_PROBE_TEXT = '{\"entity\":\"customers\",\"row\":{\"id\":0,\"name\":\"n0\",\"score\":0.0,\"tags\":[\"a\"]}}\\n{\"entity\":\"customers\",\"row\":{\"id\":1,\"name\":\"n1\",\"score\":1.0,\"tags\":[\"a\"]}}\\n';\nconst CPYTHON_PROBE_DEFLATE = \"ab564acd2bc92ca954b2524a2e2d2ec9cf4d2d2a56d2512aca2f57b2aa56ca4c51b232d051ca4bcc4d052ac83300ca1427e7170139067a40f192c4f46225ab68a544a5d8da5aae6a824619228c3244186588691400\";\n\n/** The file name the Python CLI gives chunk N (`chunk-00007.jsonl.gz`), which\n * its `GzipFile` records in the gzip header, so it is part of the digest. */\nexport const chunkName = (ordinal: number): string => `chunk-${String(ordinal).padStart(5, \"0\")}.jsonl`;\n\n/**\n * Gzip as CPython's `gzip.GzipFile(fileobj, \"wb\", mtime=0)` writes it: mtime\n * 0, XFL for the level, OS \"unknown\" (0xff), and — when a name is given — the\n * FNAME field, exactly as GzipFile records the basename of the file it writes.\n */\nexport function gzipDeterministic(raw: Buffer, opts: { level?: number; name?: string } = {}): Buffer {\n const level = opts.level ?? GZIP_LEVEL;\n const name = opts.name ? Buffer.concat([Buffer.from(opts.name, \"latin1\"), Buffer.from([0])]) : Buffer.alloc(0);\n const header = Buffer.from([0x1f, 0x8b, 0x08, opts.name ? 0x08 : 0x00, 0, 0, 0, 0, level === 9 ? 0x02 : level === 1 ? 0x04 : 0x00, 0xff]);\n const body = deflateRawSync(raw, { level });\n const trailer = Buffer.alloc(8);\n trailer.writeUInt32LE(crc32(raw), 0);\n trailer.writeUInt32LE(raw.length >>> 0, 4);\n return Buffer.concat([header, name, body, trailer]);\n}\n\nlet table: Uint32Array | null = null;\n\n/** CRC-32 (IEEE), the gzip trailer's checksum. A table here keeps the CLI on Node 18. */\nexport function crc32(data: Buffer): number {\n if (!table) {\n table = new Uint32Array(256);\n for (let n = 0; n < 256; n++) {\n let c = n;\n for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;\n table[n] = c >>> 0;\n }\n }\n let crc = 0xffffffff;\n for (let i = 0; i < data.length; i++) crc = table[(crc ^ data[i]!) & 0xff]! ^ (crc >>> 8);\n return (crc ^ 0xffffffff) >>> 0;\n}\n\n/** The Python CLI's `_parse_size`: an integer and a unit — none, b, k, kib, kb, m, mib, mb, g, gib, gb. */\nexport function parseSize(text: string): number {\n const units: Record<string, number> = { \"\": 1, b: 1, k: 1024, kib: 1024, kb: 1000, m: 1024 ** 2, mib: 1024 ** 2, mb: 1000 ** 2, g: 1024 ** 3, gib: 1024 ** 3, gb: 1000 ** 3 };\n const raw = text.trim().toLowerCase().replace(/ /g, \"\");\n const m = /^(\\d+)([a-z]*)$/.exec(raw);\n if (!m || !(m[2]! in units)) throw new Error(`--chunk-bytes takes a size like 64MiB or 1000000, not '${text}'`);\n return Number(m[1]) * units[m[2]!]!;\n}\n","import type { Credentials } from \"../../config\";\nimport type { Rows } from \"../rows\";\nimport { forEachLimited, waitForBatch, WorldDataApi, type BatchStatus } from \"./batches\";\nimport { buildChunks, DEFAULT_CHUNK_BYTES } from \"./chunker\";\nimport { parseJson, type JsonObject } from \"./json\";\nimport type { TaggedRow } from \"./rowSource\";\n\n/**\n * Rows already in memory into a platform world through the batch lane —\n * open, chunk, upload, complete, wait — with none of the CLI's file, manifest\n * or resume machinery. What `ingestToolCalls` (the SDK) pushes after the\n * runtime projected a slug's records; the CLI keeps `data import`'s lane.\n * `redact` is optional and defaults to off: the platform stores the rows as\n * given unless asked to apply its `[redact]` policy.\n */\nexport async function pushRows(\n creds: Credentials,\n slug: string,\n rows: Rows,\n opts: {\n mode?: \"append\" | \"replace\";\n redact?: \"off\" | \"apply\" | \"refuse\";\n message?: string;\n publish?: \"now\" | \"later\";\n chunkBytes?: number;\n parallel?: number;\n dryRun?: boolean;\n sleep?: (ms: number) => Promise<void>;\n } = {},\n): Promise<BatchStatus> {\n const client = opts.sleep ? new WorldDataApi(creds, slug, opts.sleep) : new WorldDataApi(creds, slug);\n const opened = await client.open({\n mode: opts.mode ?? \"append\",\n merge: \"upsert\",\n ...(opts.redact && opts.redact !== \"off\" ? { redact: opts.redact } : {}),\n atomic: true,\n dryRun: Boolean(opts.dryRun),\n publish: opts.publish ?? \"now\",\n ...(opts.message ? { message: opts.message } : {}),\n });\n if (!opened.batchId) throw new Error(\"the platform opened no batch (no batchId in the answer)\");\n // The chunker speaks the file lane's JSON model (CPython-faithful numbers and\n // key order), so each row takes the same road a JSONL line does: serialized, parsed.\n const tagged = (async function* (): AsyncGenerator<TaggedRow> {\n for (const [entity, listed] of Object.entries(rows))\n for (let index = 0; index < listed.length; index++)\n yield { entity, row: parseJson(JSON.stringify(listed[index]!)) as JsonObject, where: `${entity}[${index}]` };\n })();\n const chunks = buildChunks(tagged, { chunkBytes: opts.chunkBytes ?? DEFAULT_CHUNK_BYTES, chunkRows: null, entity: null });\n await forEachLimited(chunks, Math.max(1, opts.parallel ?? 4), async (chunk) => {\n await client.upload(opened.batchId, chunk);\n });\n await client.complete(opened.batchId);\n return waitForBatch(client, opened.batchId, { initialDelayMs: pollMs() });\n}\n\nfunction pollMs(): number {\n const raw = Number(process.env.GATEWAY_WORLD_DATA_POLL_MS ?? 1000);\n return Number.isFinite(raw) && raw >= 0 ? raw : 1000;\n}\n","/**\n * Records into a world's rows — the record contract, an interceptor that\n * writes it, the conversion from TOOL observations, and the door in.\n *\n * A tool's response is not the entity's shape, and nothing here assumes it\n * is. The workflow with real data is: pull the raw tool calls, look at them,\n * then ingest them through the route you declare — {@link ingest} with a\n * `transform` (your own `transform(records) -> {entity: [rows]}`, a function\n * or a script), with a `map` (an `ingest.toml` mapping for shapes that need\n * no code), or with neither, when the world's own `ingest.toml` applies or\n * each record's tool is a connector operation whose result *is* the\n * operation's response body (its `[ingest]` projection in `connector.toml`).\n * Mappings and projections run in the schema runtime (Python, bundled with\n * the CLI or on the platform), never re-implemented here; a transform runs\n * where you are.\n *\n * The record, one JSON object per line:\n *\n * {\"tool\": \"list_users\", \"args\": {\"team\": \"t1\"}, \"result\": {\"users\": [...]},\n * \"at\": \"2026-09-15T10:00:00Z\", \"session\": \"optional\", \"source\": \"optional free text\"}\n *\n * A `gateway worlds session export` line (`{seq, kind, tool, args, result,\n * error, completedAt}`) is accepted as it is. Redaction is optional and OFF\n * by default everywhere here: rows land as the tools returned them unless\n * `redact: \"apply\"` (the world's `[redact]` policy) or `\"refuse\"` is asked for.\n *\n * - {@link captureToolCalls} wraps an agent's tool functions so every real\n * call is recorded — the agent changes nothing.\n * - {@link toolCallsFromObservations} turns a trace's TOOL observations into\n * records (the `--from traces` path of `gateway worlds data ingest`).\n * - {@link ingest} puts records into a world through a transform, a mapping\n * or the operations: a local directory through the bundled runtime, a\n * platform slug through the batch lane. {@link ingestToolCalls} is the same\n * door with neither transform nor mapping of your own.\n */\n\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\n\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\n\nexport type ToolCallRecord = {\n /** The operation name in the world's `connector.toml`. */\n tool: string;\n /** The call's arguments, by name: what `carry_args` reads. */\n args: Record<string, unknown>;\n /** The operation's response body, as the tool returned it. */\n result?: unknown;\n /** ISO time of the call. */\n at?: string;\n /** The session the call belongs to, when there is one. */\n session?: string;\n /** Free text: where the record came from. */\n source?: string;\n /** Set instead of `result` when the call threw; ingest skips it, counted. */\n error?: string;\n};\n\nexport type RedactMode = \"off\" | \"apply\" | \"refuse\";\nexport type IngestMode = \"append\" | \"replace\";\n\n// ---------------------------------------------------------------- the mapping\n\n/** How one entity field is set: an item path, or a table naming exactly one of `from`, `literal`, `template`, `hash`. */\nexport type IngestFieldSpec =\n | string\n | {\n /** Item path (`name`, `customer.id`, `emails[0]`); `$`-paths reach the record: `$tool`, `$at`, `$index`, `$session`, `$source`, `$source.id`, `$source.trace`, `$record.<path>`, `$parent.<path>`. */\n from?: string;\n literal?: string | number | boolean;\n /** `{path}` holes are filled from the item or the record; a hole with no value refuses the record. */\n template?: string;\n /** sha256 of the JSON array of these paths' values; unset when any is missing. */\n hash?: string[];\n /** A chain from the closed transform set, applied to `from` or `template`. */\n transform?: string[];\n /** Used when `from` is missing or null. */\n default?: string | number | boolean;\n /** Coerce the value; a CSV cell is text until this says otherwise. */\n type?: \"string\" | \"integer\" | \"number\" | \"boolean\";\n };\n\nexport type IngestExplode = {\n /** Item path to a list (or one object) of children. */\n path: string;\n entity: string;\n /** child field <- parent ENTITY field (after the parent's mapping). */\n carry?: Record<string, string>;\n fields?: Record<string, IngestFieldSpec>;\n};\n\nexport type IngestSource = {\n /** The tool name (or several), or `\"*\"` for rows and csv records. */\n name: string | string[];\n kind?: \"tool-call\" | \"rows\" | \"csv\";\n /** Path into the record: `result`, `result.data[*]`, `args`, `$record`. */\n select: string;\n /** All must hold on the selected item: a literal, or `{ present: true | false }`. */\n when?: Record<string, string | number | boolean | { present: boolean }>;\n entity: string;\n /** Item path that dates the row for `on_conflict`; default the record's `at`. */\n at?: string;\n fields?: Record<string, IngestFieldSpec>;\n explode?: IngestExplode[];\n};\n\n/** `ingest.toml`, parsed: the grammar the schema runtime's `mapping.py` checks and applies. */\nexport type IngestMapping = {\n ingest?: { on_conflict?: \"latest\" | \"first\"; unmatched?: \"refuse\" | \"skip\" };\n sources: IngestSource[];\n};\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n// ---------------------------------------------------------------- records\n\nexport type ParsedToolCall = {\n /** The record in the contract's shape, when it is a tool call with a result. */\n record: ToolCallRecord | null;\n /** Why a well-formed record carries no rows by design (a `seed` line, a failed call). */\n skip: string | null;\n /** What is wrong with the record. */\n refusal: string | null;\n};\n\n/**\n * One raw record — the contract's shape or a session-export line — judged the\n * way the runtime judges it (`ingest.normalize_record`): the same skips, the\n * same refusals, so a file checked here is what the runtime will accept.\n */\nexport function parseToolCallRecord(raw: unknown): ParsedToolCall {\n const none = { record: null, skip: null };\n if (!isObject(raw)) return { ...none, refusal: \"record is not an object\" };\n const kind = raw.kind;\n if (kind !== undefined && kind !== null && kind !== \"call\") return { record: null, skip: `kind ${String(kind)}`, refusal: null };\n const tool = raw.tool;\n if (typeof tool !== \"string\" || !tool) return { ...none, refusal: \"record has no tool name\" };\n if (raw.error !== undefined && raw.error !== null && raw.error !== \"\") return { record: null, skip: \"call failed\", refusal: null };\n const args = raw.args ?? {};\n if (!isObject(args)) return { ...none, refusal: `args of ${tool} is not an object` };\n if (!(\"result\" in raw)) return { ...none, refusal: `record of ${tool} has no result` };\n const at = raw.at ?? raw.completedAt;\n const record: ToolCallRecord = { tool, args, result: raw.result };\n if (typeof at === \"string\") record.at = at;\n if (typeof raw.session === \"string\") record.session = raw.session;\n if (typeof raw.source === \"string\") record.source = raw.source;\n return { record, skip: null, refusal: null };\n}\n\n/**\n * Raw records from files: JSONL (one object per line) or one JSON array, several\n * files concatenated in order. A line that is not JSON, or not an object, throws\n * naming the file and line. Each record's shape is judged later, per record, so\n * the report can point at the index.\n */\nexport function readToolCallRecords(paths: string[]): unknown[] {\n const records: unknown[] = [];\n for (const file of paths) records.push(...toolCallRecordsIn(fs.readFileSync(file, \"utf8\"), file));\n return records;\n}\n\n/** The records in one text, named `where` in a refusal. */\nexport function toolCallRecordsIn(text: string, where: string): unknown[] {\n const stripped = text.trim();\n if (!stripped) return [];\n if (stripped.startsWith(\"[\")) {\n const listed = JSON.parse(stripped) as unknown;\n if (!Array.isArray(listed)) throw new Error(`${where} is neither a JSON array nor JSON Lines`);\n listed.forEach((item, index) => {\n if (!isObject(item)) throw new Error(`${where}[${index}] is not an object`);\n });\n return listed;\n }\n const records: unknown[] = [];\n const lines = text.split(/\\r?\\n/);\n for (let index = 0; index < lines.length; index++) {\n const line = lines[index]!;\n if (!line.trim()) continue;\n let item: unknown;\n try {\n item = JSON.parse(line);\n } catch {\n throw new Error(`${where}:${index + 1} is not JSON`);\n }\n if (!isObject(item)) throw new Error(`${where}:${index + 1} is not an object`);\n records.push(item);\n }\n return records;\n}\n\n// ---------------------------------------------------------------- capture\n\n/**\n * Where {@link captureToolCalls} writes each record: an array (pushed), a file\n * path (JSONL, one record per line, appended), or a callback (awaited).\n */\nexport type ToolCallSink = ToolCallRecord[] | string | ((record: ToolCallRecord) => unknown | Promise<unknown>);\n\nexport type ToolFunctions = Record<string, (args: Record<string, unknown>) => Promise<unknown>>;\n\nasync function emit(sink: ToolCallSink, record: ToolCallRecord): Promise<void> {\n if (Array.isArray(sink)) {\n sink.push(record);\n return;\n }\n if (typeof sink === \"string\") {\n fs.appendFileSync(sink, JSON.stringify(record) + \"\\n\");\n return;\n }\n if (typeof sink === \"function\") {\n await sink(record);\n return;\n }\n throw new TypeError(\"sink must be an array, a file path, or a function\");\n}\n\n/**\n * Wrap a name → async function map — the shape the Vercel AI SDK's tools and a\n * `WorldToolkit`'s `impls` share — so every call is recorded as a tool-call\n * record into `sink`, and hand back the same map. The agent changes nothing:\n * each wrapped function returns what the original returned, and an error is\n * thrown through untouched (recorded with `error` and no `result`, which\n * ingest skips and counts). Nothing is redacted here; redaction is optional\n * and off by default on the ingest side.\n *\n * const tools = captureToolCalls({ list_users: realVendor.listUsers }, \"calls.jsonl\");\n * await runMyAgent(tools); // real vendor, every call recorded\n * await ingestToolCalls(\"acme-crm\", readToolCallRecords([\"calls.jsonl\"]));\n */\nexport function captureToolCalls<T extends ToolFunctions>(\n tools: T,\n sink: ToolCallSink,\n opts: { session?: string; source?: string } = {},\n): T {\n const wrapped: ToolFunctions = Object.create(null);\n for (const [name, fn] of Object.entries(tools)) {\n wrapped[name] = async (args: Record<string, unknown> = {}) => {\n const record: ToolCallRecord = { tool: name, args, at: new Date().toISOString() };\n if (opts.session) record.session = opts.session;\n if (opts.source) record.source = opts.source;\n let result: unknown;\n try {\n result = await fn(args);\n } catch (error) {\n record.error = error instanceof Error ? error.message || error.name : String(error);\n await emit(sink, record);\n throw error;\n }\n record.result = result;\n await emit(sink, record);\n return result;\n };\n }\n return wrapped as T;\n}\n\n// ---------------------------------------------------------------- observations\n\n/** What a TOOL observation carries, as `GET /api/public/observations` and\n * `GET /api/public/sessions/{id}?includeIO=true` return it. */\nexport type ObservationLike = {\n id?: string;\n traceId?: string | null;\n type?: string;\n name?: string | null;\n input?: unknown;\n output?: unknown;\n startTime?: string | Date;\n level?: string;\n statusMessage?: string | null;\n};\n\nexport type ObservationConversion = {\n records: ToolCallRecord[];\n /** TOOL observations whose name is not one of the world's operations, by name. */\n unknownTools: Record<string, number>;\n /** Observations that were not converted, by reason. */\n skipped: Record<string, number>;\n};\n\n/** A serialized value back to JSON when it parses; otherwise as it is. */\nfunction jsonish(value: unknown): unknown {\n if (typeof value !== \"string\") return value;\n try {\n return JSON.parse(value);\n } catch {\n return value;\n }\n}\n\nconst isoOf = (value: string | Date | undefined): string | undefined =>\n value instanceof Date ? value.toISOString() : typeof value === \"string\" ? value : undefined;\n\n/**\n * TOOL observations → tool-call records: `name` is the tool, `input` the args,\n * `output` the result, `startTime` the time, `trace:<traceId>/<id>` the source.\n * A serialized `input`/`output` (the SDK stores JSON text) is parsed back;\n * an `input` that is not an object leaves `args` empty rather than guessed.\n * Only `type: \"TOOL\"` converts. With `tools` (the world's operation names) an\n * observation for any other tool is counted in `unknownTools`, not converted.\n * An `ERROR`-level observation converts with `error` set, so ingest counts it\n * as a failed call instead of projecting its output.\n */\nexport function toolCallsFromObservations(\n observations: ObservationLike[],\n opts: { tools?: Iterable<string> | null; session?: string; since?: string } = {},\n): ObservationConversion {\n const known = opts.tools ? new Set(opts.tools) : null;\n const sinceMs = opts.since ? Date.parse(opts.since) : NaN;\n const out: ObservationConversion = { records: [], unknownTools: {}, skipped: {} };\n const skip = (reason: string) => {\n out.skipped[reason] = (out.skipped[reason] ?? 0) + 1;\n };\n for (const observation of observations) {\n if (observation.type !== \"TOOL\") {\n skip(`type ${observation.type ?? \"unknown\"}`);\n continue;\n }\n const tool = observation.name;\n if (typeof tool !== \"string\" || !tool) {\n skip(\"no name\");\n continue;\n }\n const at = isoOf(observation.startTime);\n if (!Number.isNaN(sinceMs) && at !== undefined && Date.parse(at) < sinceMs) {\n skip(\"before since\");\n continue;\n }\n if (known && !known.has(tool)) {\n out.unknownTools[tool] = (out.unknownTools[tool] ?? 0) + 1;\n continue;\n }\n const input = jsonish(observation.input);\n const record: ToolCallRecord = { tool, args: isObject(input) ? input : {} };\n if (observation.level === \"ERROR\") record.error = observation.statusMessage || \"ERROR\";\n else record.result = jsonish(observation.output);\n if (at !== undefined) record.at = at;\n if (opts.session) record.session = opts.session;\n record.source = `trace:${observation.traceId ?? \"?\"}/${observation.id ?? \"?\"}`;\n out.records.push(record);\n }\n return out;\n}\n\n// ---------------------------------------------------------------- the door\n\nexport type IngestRefusal = { index: number | null; tool: string | null; reason: string; pointer?: string };\n\n/** One `[[sources]]` of a mapping in the report. */\nexport type IngestSourceReport = {\n name: string;\n kind: string;\n select: string;\n entity: string;\n records: number;\n items: number;\n rows: Record<string, number>;\n /** Source fields no line of the source reads, with a sample value. */\n unmappedFields: Record<string, string>;\n /** Entity fields the source never sets, per entity. */\n unsetFields: Record<string, string[]>;\n};\n\nexport type IngestToolCallsReport = {\n world: string;\n /** How the rows were produced. */\n via?: \"transform\" | \"map\" | \"operations\" | \"rows\";\n /** `via: \"map\"`: each source's accounting. */\n sources?: IngestSourceReport[];\n /** `via: \"map\"` with `unmatched = \"skip\"`: records no source claimed, by tool name. */\n unmatched?: Record<string, number>;\n /** `via: \"operations\"`: that this was the operation projection, not a mapping. */\n note?: string;\n /** `via: \"transform\"`: what the script wrote to stderr. */\n stderr?: string;\n /** Records given. */\n records: number;\n /** Records that yielded rows. */\n ingested: number;\n /** Records that carried no rows by design, by reason. */\n skipped: Record<string, number>;\n /** What was wrong, per record; with any, nothing was written. */\n refusals: IngestRefusal[];\n /** Rows projected, per entity. */\n rows: Record<string, number>;\n dryRun: boolean;\n redact: RedactMode;\n changed: boolean;\n kind?: string;\n entityCounts?: Record<string, number>;\n /** A slug that was pushed: the batch's final status (`state`, `versionId`, …). */\n batch?: Record<string, unknown>;\n};\n\nexport type IngestToolCallsOptions = WorldsClientOptions & {\n /** Optional, default `\"off\"`: rows land as the tools returned them. */\n redact?: RedactMode;\n /** Project and prove the rows; write and upload nothing. */\n dryRun?: boolean;\n mode?: IngestMode;\n /** Change reason for the version a slug cuts. */\n message?: string;\n};\n\nexport type IngestReport = IngestToolCallsReport;\n\nexport type IngestOptions = IngestToolCallsOptions & {\n /** Your own `transform(records) -> {entity: [rows]}`: a function (run here) or a script path (`.py`, `.ts`, `.mjs`; a subprocess with a time limit and sockets disabled). */\n transform?: string | ((records: unknown[]) => Rows | Promise<Rows>);\n /** An `ingest.toml` mapping: its text, or the parsed table. Exclusive with `transform`. */\n map?: string | IngestMapping;\n /** For a script transform; default 120 000. */\n timeoutMs?: number;\n};\n\ntype Rows = Record<string, Record<string, unknown>[]>;\n\nfunction credentialsOf(options: WorldsClientOptions): { host: string; publicKey: string; secretKey: string } | null {\n const host = (options.host ?? process.env.GATEWAY_HOST ?? \"https://withgateway.ai\").replace(/\\/+$/, \"\");\n const publicKey = options.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;\n const secretKey = options.secretKey ?? process.env.GATEWAY_SECRET_KEY;\n return publicKey && secretKey ? { host, publicKey, secretKey } : null;\n}\n\n/**\n * Records into a world through the route you declare. `world` is a local\n * directory (written in place through the bundled schema runtime) or a\n * platform slug (pulled to a temporary directory, the rows produced and\n * proven there, then pushed through the chunked batch lane as a new version).\n *\n * With `transform` the rows are what your code returns; with `map` (or the\n * world's own `ingest.toml`) what the mapping declares; with neither, each\n * tool-call record's tool resolves to an operation of `connector.toml` and\n * its result goes through that operation's `[ingest]` projection (the report\n * says `via: \"operations\"`). A transform that fails or returns the wrong\n * shape throws. `redact` is optional and defaults to `\"off\"`.\n */\nexport async function ingest(world: string, records: unknown[], options: IngestOptions = {}): Promise<IngestReport> {\n const { ingestLocalToolCalls, importLocalWorldData, checkLocalWorldData } = await import(\"../cli/runtime/data\");\n if (options.transform !== undefined && options.map !== undefined) throw new Error(\"records go through one of transform, map\");\n const redact = options.redact ?? \"off\";\n const mode = options.mode ?? \"append\";\n const dryRun = Boolean(options.dryRun);\n const creds = credentialsOf(options);\n const local = fs.existsSync(world) && fs.statSync(world).isDirectory();\n const map = options.map === undefined ? undefined : options.map;\n\n let rows: Rows | null = null;\n let stderr = \"\";\n if (options.transform !== undefined) {\n const { transformRecords } = await import(\"../cli/platform/worldData/transform\");\n ({ rows, stderr } = await transformRecords(options.transform, records, { timeoutMs: options.timeoutMs }));\n }\n\n if (local) {\n if (rows === null) return reportOf(world, await ingestLocalToolCalls(world, records, { redact, dryRun, mode, map }, creds), redact);\n const landed = dryRun ? await checkLocalWorldData(world, rows, creds, { redact }) : await importLocalWorldData(world, rows, { mode, redact }, creds);\n return transformReport(world, records.length, rows, stderr, { dryRun, redact, changed: !dryRun && landed.changed, kind: landed.kind, entityCounts: landed.entity_counts });\n }\n if (!creds) throw new Error(\"Gateway keys missing: set GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY (or pass publicKey/secretKey).\");\n const { pull } = await import(\"./hub\");\n const slug = world.split(\"@\", 1)[0]!;\n const scratch = fs.mkdtempSync(path.join(os.tmpdir(), \"gateway-ingest-\"));\n try {\n const pulled = await pull(world, path.join(scratch, slug), options);\n // Produced and proven against the pulled contract; the platform's batch\n // lane checks every row again and redacts there, so this pass runs with\n // redaction off and hands the rows on as they were produced.\n let report: IngestReport;\n let projected: Rows;\n if (rows === null) {\n const proven = await ingestLocalToolCalls(pulled.dir, records, { redact: \"off\", dryRun: true, mode, map }, creds);\n report = reportOf(world, proven, redact);\n projected = proven.projected ?? {};\n } else {\n const proven = await checkLocalWorldData(pulled.dir, rows, creds);\n report = transformReport(world, records.length, rows, stderr, { dryRun, redact, changed: false, kind: proven.kind, entityCounts: proven.entity_counts });\n projected = rows;\n }\n report.dryRun = dryRun;\n if (dryRun || report.refusals.length || !Object.keys(projected).length) return report;\n const { pushRows } = await import(\"../cli/platform/worldData/push\");\n const status = await pushRows(creds, slug, projected, { mode, redact, message: options.message });\n report.batch = status;\n report.changed = status.state === \"applied\" || status.state === \"published\";\n if (status.entityCounts) report.entityCounts = status.entityCounts;\n return report;\n } finally {\n fs.rmSync(scratch, { recursive: true, force: true });\n }\n}\n\n/**\n * Tool-call records into a world with neither a transform nor a mapping of\n * your own: the world's `ingest.toml` when it has one, else each record's\n * tool through its operation's `[ingest]` projection (an unknown tool is a\n * refusal naming it and nothing is written). {@link ingest} with the same\n * options.\n */\nexport async function ingestToolCalls(world: string, records: unknown[], options: IngestToolCallsOptions = {}): Promise<IngestToolCallsReport> {\n return ingest(world, records, options);\n}\n\nfunction transformReport(\n world: string,\n records: number,\n rows: Rows,\n stderr: string,\n outcome: { dryRun: boolean; redact: RedactMode; changed: boolean; kind?: string; entityCounts?: Record<string, number> },\n): IngestReport {\n return {\n world,\n via: \"transform\",\n ...(stderr ? { stderr } : {}),\n records,\n ingested: records,\n skipped: {},\n refusals: [],\n rows: Object.fromEntries(Object.entries(rows).map(([entity, listed]) => [entity, listed.length])),\n dryRun: outcome.dryRun,\n redact: outcome.redact,\n changed: outcome.changed,\n ...(outcome.kind ? { kind: outcome.kind } : {}),\n ...(outcome.entityCounts ? { entityCounts: outcome.entityCounts } : {}),\n };\n}\n\nfunction reportOf(\n world: string,\n local: {\n via?: IngestReport[\"via\"];\n sources?: { name: string; kind: string; select: string; entity: string; records: number; items: number; rows: Record<string, number>; unmapped_fields: Record<string, string>; unset_fields: Record<string, string[]> }[];\n unmatched?: Record<string, number>;\n note?: string;\n records: number;\n ingested: number;\n skipped: Record<string, number>;\n refusals: IngestRefusal[];\n rows: Record<string, number>;\n dry_run: boolean;\n changed: boolean;\n kind?: string;\n entity_counts?: Record<string, number>;\n },\n redact: RedactMode,\n): IngestToolCallsReport {\n return {\n world,\n ...(local.via ? { via: local.via } : {}),\n ...(local.sources ? { sources: local.sources.map(({ unmapped_fields, unset_fields, ...rest }) => ({ ...rest, unmappedFields: unmapped_fields, unsetFields: unset_fields })) } : {}),\n ...(local.unmatched ? { unmatched: local.unmatched } : {}),\n ...(local.note ? { note: local.note } : {}),\n records: local.records,\n ingested: local.ingested,\n skipped: local.skipped,\n refusals: local.refusals,\n rows: local.rows,\n dryRun: local.dry_run,\n redact,\n changed: local.changed,\n ...(local.kind ? { kind: local.kind } : {}),\n ...(local.entity_counts ? { entityCounts: local.entity_counts } : {}),\n };\n}\n\n/** The TOOL observations of one session, every trace's, from `GET /api/public/sessions/{id}?includeIO=true`. */\nexport async function sessionToolObservations(sessionId: string, options: WorldsClientOptions = {}): Promise<ObservationLike[]> {\n const session = await apiRequest<{ traces?: { id?: string; observations?: ObservationLike[] }[] }>(\n options,\n \"GET\",\n `/api/public/sessions/${encodeURIComponent(sessionId)}?includeIO=true`,\n );\n const out: ObservationLike[] = [];\n for (const trace of session.traces ?? [])\n for (const observation of trace.observations ?? []) out.push({ traceId: trace.id ?? null, ...observation });\n return out;\n}\n","/**\n * Worlds from TypeScript: identity, tasks, and HOSTED execution.\n *\n * The same three-level model as the Python SDK — WorldSet → Task — with one\n * deliberate difference: a world's tools are Python modules, so TypeScript\n * does not materialize task environments in-process. What a TS agent\n * codebase needs is exactly what this module provides: resolve a world ref\n * to its pinned version, read its task list, and dispatch HOSTED runs\n * (parallelism included) that execute the world server-side and file graded,\n * version-pinned rollouts. Local in-process execution stays a Python\n * capability by design, not by omission.\n */\n\nimport type { WorldTaskIdRef } from \"./session\";\n\nexport type WorldsClientOptions = {\n host?: string;\n publicKey?: string;\n secretKey?: string;\n};\n\nexport type ResolvedWorldVersion = {\n versionId: string;\n semanticVersion: string | null;\n contentHash: string;\n state?: string;\n};\n\nexport type WorldTaskInfo = {\n name: string;\n variant: string | null;\n};\n\nexport type DispatchedRun = {\n model: string;\n runId: string;\n ok: boolean;\n error?: string;\n};\n\nfunction resolveEnv(options: WorldsClientOptions) {\n const host =\n options.host ?? process.env.GATEWAY_HOST ?? \"https://withgateway.ai\";\n const publicKey = options.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;\n const secretKey = options.secretKey ?? process.env.GATEWAY_SECRET_KEY;\n if (!publicKey || !secretKey) {\n throw new Error(\n \"Gateway keys missing: set GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY \" +\n \"(or pass publicKey/secretKey).\",\n );\n }\n return { host: host.replace(/\\/+$/, \"\"), publicKey, secretKey };\n}\n\n/** Authenticated JSON request against the platform API — the primitive the\n * worlds helpers and the TS CLI share. */\nexport async function apiRequest<T>(\n options: WorldsClientOptions,\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\",\n path: string,\n body?: unknown,\n): Promise<T> {\n const { host, publicKey, secretKey } = resolveEnv(options);\n const res = await fetch(`${host}${path}`, {\n method,\n headers: {\n \"content-type\": \"application/json\",\n authorization:\n \"Basic \" + Buffer.from(`${publicKey}:${secretKey}`).toString(\"base64\"),\n },\n ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n });\n const text = await res.text();\n if (!res.ok) {\n throw new Error(\n `${method} ${path} -> ${res.status}: ${text.slice(0, 400)}`,\n );\n }\n return JSON.parse(text) as T;\n}\n\n/** Set (or rotate) one environment secret — write-only: no API returns it. */\nexport async function setEnvSecret(\n slug: string,\n key: string,\n value: string,\n options: WorldsClientOptions = {},\n): Promise<{ key: string; created: boolean }> {\n return apiRequest(\n options,\n \"PUT\",\n \"/api/public/benchmark-containers/secrets\",\n {\n slug,\n key,\n value,\n },\n );\n}\n\n/** Keys and rotation timestamps only — never values. */\nexport async function listEnvSecretKeys(\n slug: string,\n options: WorldsClientOptions = {},\n): Promise<{ key: string; updatedAt: string }[]> {\n const res = await apiRequest<{\n secrets: { key: string; updatedAt: string }[];\n }>(\n options,\n \"GET\",\n `/api/public/benchmark-containers/secrets?slug=${encodeURIComponent(slug)}`,\n );\n return res.secrets;\n}\n\nexport async function deleteEnvSecret(\n slug: string,\n key: string,\n options: WorldsClientOptions = {},\n): Promise<void> {\n await apiRequest(\n options,\n \"DELETE\",\n \"/api/public/benchmark-containers/secrets\",\n {\n slug,\n key,\n },\n );\n}\n\nexport type RunConfigSummary = {\n id: string;\n name: string;\n runType: string;\n createdAt: string;\n models: string[];\n parallelism: number;\n autoRunOnPush: boolean;\n agent: string | null;\n};\n\n/** Run configs in the project. CI resolves by NAME and dispatches by id. */\nexport async function listRunConfigs(\n options: WorldsClientOptions = {},\n): Promise<RunConfigSummary[]> {\n const res = await apiRequest<{ runConfigs: RunConfigSummary[] }>(\n options,\n \"GET\",\n \"/api/public/benchmark-containers/run-configs\",\n );\n return res.runConfigs;\n}\n\n/** What a run config selects for the runner to work through. A config runs\n * EITHER the bundle's own scenarios (`taskNames`, `taskSetDatasetId`) OR the\n * project's stored tasks (`worldTasks`, api worlds only) — never both. A\n * stored task ref without `version` runs the task's current version at\n * dispatch time; with it, that version forever. */\nexport type RunConfigInput = {\n id?: string;\n name: string;\n models: string[];\n parallelism?: number;\n numExamples?: number;\n rolloutsPerExample?: number;\n timeoutMinutes?: number;\n agent?: string;\n taskSetDatasetId?: string | null;\n taskNames?: string[];\n worldTasks?: WorldTaskIdRef[];\n autoRunOnPush?: boolean;\n};\n\n/** Create a run config, or update the one named by `id`. */\nexport async function upsertRunConfig(\n input: RunConfigInput,\n options: WorldsClientOptions = {},\n): Promise<RunConfigSummary> {\n return apiRequest<RunConfigSummary>(\n options,\n \"POST\",\n \"/api/public/benchmark-containers/run-configs\",\n input,\n );\n}\n\n/** `id[@version]` items (comma-separated or an array) → stored task refs;\n * the spelling `bench run-configs create --world-tasks` takes. */\nexport function parseWorldTaskRefs(spec: string | string[]): WorldTaskIdRef[] {\n const items = (Array.isArray(spec) ? spec : spec.split(\",\"))\n .map((s) => s.trim())\n .filter(Boolean);\n return items.map((item) => {\n const at = item.lastIndexOf(\"@\");\n if (at < 0) return { id: item };\n const id = item.slice(0, at);\n const version = Number(item.slice(at + 1));\n if (!id || !Number.isInteger(version) || version < 1)\n throw new Error(\n `stored task ref '${item}' is not <id> or <id>@<version> (version a positive integer)`,\n );\n return { id, version };\n });\n}\n\nexport type RunReport = {\n id: string;\n status: string;\n terminal: boolean;\n score: number | null;\n summary: string | null;\n model: string | null;\n versionLabel: string | null;\n parallelism: number;\n shardsCompleted: number | null;\n /** The run's page on the platform — what a PR comment should link. */\n url: string | null;\n evaluations: {\n id: string;\n status: string;\n avgReward: number | null;\n url: string | null;\n }[];\n samples: {\n task: string | null;\n reward: number | null;\n rewards: Record<string, unknown>;\n sessionId: string | null;\n }[];\n};\n\n/** The read half of dispatch: status, score, per-shard evaluations, and\n * per-task rewards — everything a CI gate needs. */\nexport async function getRun(\n runId: string,\n options: WorldsClientOptions = {},\n): Promise<RunReport> {\n return apiRequest(\n options,\n \"GET\",\n `/api/public/benchmark-containers/runs/${encodeURIComponent(runId)}`,\n );\n}\n\n/** Poll a run to terminal (default every 20s, up to `timeoutMinutes`). */\nexport async function waitForRun(\n runId: string,\n opts: {\n timeoutMinutes?: number;\n intervalSeconds?: number;\n onTick?: (run: RunReport) => void;\n options?: WorldsClientOptions;\n } = {},\n): Promise<RunReport> {\n const deadline = Date.now() + (opts.timeoutMinutes ?? 45) * 60_000;\n for (;;) {\n const run = await getRun(runId, opts.options ?? {});\n if (run.terminal) return run;\n if (Date.now() > deadline)\n throw new Error(\n `Run ${runId} still ${run.status} after the wait timeout.`,\n );\n opts.onTick?.(run);\n await new Promise((resolve) =>\n setTimeout(resolve, (opts.intervalSeconds ?? 20) * 1000),\n );\n }\n}\n\nexport type RunProvenance = {\n branch?: string;\n commit?: string;\n repoUrl?: string;\n actor?: { id?: string; name?: string; imageUrl?: string; kind?: string };\n};\n\n/**\n * Where a dispatch comes from, DETECTED rather than configured: the CI\n * checkout's branch/commit/actor under GitHub Actions, else the developer's\n * own git checkout. A run nobody can trace to a branch is a score with no\n * code attached, so every dispatch carries this unless overridden.\n */\nexport function detectProvenance(): RunProvenance {\n const env =\n (globalThis as { process?: { env?: Record<string, string | undefined> } })\n .process?.env ?? {};\n const out: RunProvenance = {};\n const ref = env.GITHUB_HEAD_REF || env.GITHUB_REF_NAME;\n if (ref) out.branch = ref;\n if (env.GITHUB_SHA) out.commit = env.GITHUB_SHA;\n const server = env.GITHUB_SERVER_URL ?? \"https://github.com\";\n if (env.GITHUB_REPOSITORY) out.repoUrl = `${server}/${env.GITHUB_REPOSITORY}`;\n if (env.GITHUB_ACTOR) {\n out.actor = {\n kind: \"ci\",\n id: env.GITHUB_ACTOR,\n name: env.GITHUB_ACTOR,\n // GitHub serves every account's avatar at /<login>.png.\n imageUrl: `${server}/${env.GITHUB_ACTOR}.png`,\n };\n }\n if (!out.branch || !out.commit) {\n try {\n const { execFileSync } =\n require(\"node:child_process\") as typeof import(\"node:child_process\");\n const git = (args: string[]) =>\n execFileSync(\"git\", args, {\n encoding: \"utf-8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n })\n .toString()\n .trim();\n out.branch = out.branch ?? git([\"rev-parse\", \"--abbrev-ref\", \"HEAD\"]);\n out.commit = out.commit ?? git([\"rev-parse\", \"HEAD\"]);\n if (!out.repoUrl) {\n const remote = git([\"config\", \"--get\", \"remote.origin.url\"]);\n if (remote) out.repoUrl = remote.replace(/\\.git$/, \"\");\n }\n if (!out.actor) {\n const name = git([\"config\", \"--get\", \"user.name\"]);\n if (name) out.actor = { kind: \"user\", name };\n }\n } catch {\n // No git here — dispatch without provenance rather than failing.\n }\n }\n return out;\n}\n\n/** One scenario of a world, as data. */\nexport class WorldTask {\n constructor(\n readonly world: WorldSet,\n readonly name: string,\n readonly variant: string | null,\n ) {}\n}\n\n/**\n * THE world, from a TS process: pinned identity + its tasks + hosted runs.\n *\n * const world = await openWorld(\"google-drive-sim@main\");\n * console.log(world.version.semanticVersion, world.tasks.length);\n * const runs = await world.dispatch(runConfigId);\n */\nexport class WorldSet {\n constructor(\n readonly slugRef: string,\n readonly slug: string,\n readonly ref: string | null,\n readonly version: ResolvedWorldVersion,\n public tasks: WorldTask[],\n private readonly options: WorldsClientOptions,\n ) {}\n\n task(variant: string): WorldTask {\n const hit = this.tasks.find(\n (t) => t.variant === variant || t.name.includes(variant),\n );\n if (!hit) {\n const known = this.tasks.map((t) => t.variant ?? t.name).join(\", \");\n throw new Error(`no task matches ${variant}; have: ${known}`);\n }\n return hit;\n }\n\n /**\n * Open a LIVE session against one of this world's tasks — a bundled task's\n * name or an inline `WorldTaskSpec`: the platform boots (or reuses) a warm\n * container, and your agent calls its tools through the platform. See\n * worlds/session.ts.\n */\n async open(\n task: import(\"./session\").WorldTaskRef,\n opts: {\n reuseWarm?: boolean;\n surfaces?: import(\"./browser\").WorldSurfaceKind[];\n } = {},\n ): Promise<import(\"./session\").WorldSession> {\n const { openSession } = await import(\"./session\");\n return openSession(this.slug, {\n task,\n versionId: this.version.versionId,\n reuseWarm: opts.reuseWarm,\n surfaces: opts.surfaces,\n options: this.options,\n });\n }\n\n /**\n * Start a HOSTED run of a run config against this world — the platform\n * executes the (Python) world in parallel containers per the config's\n * `parallelism` and files one graded run per model. Returns those runs.\n */\n async dispatch(\n runConfigId: string,\n opts: {\n containerId?: string;\n versionId?: string;\n /** Override the auto-detected branch/commit/actor. */\n provenance?: RunProvenance;\n } = {},\n ): Promise<{ versionLabel: string; runs: DispatchedRun[] }> {\n const provenance = opts.provenance ?? detectProvenance();\n return apiRequest(\n this.options,\n \"POST\",\n \"/api/public/benchmark-containers/run-configs/dispatch\",\n {\n runConfigId,\n ...(opts.containerId ? { containerId: opts.containerId } : {}),\n versionId: opts.versionId ?? this.version.versionId,\n ...provenance,\n },\n );\n }\n}\n\n/**\n * Resolve `slug` / `slug@branch|tag|semver|hash` to its pinned version and\n * task list. The task list comes from the version's file manifest\n * (`tasks/<name>/task.toml`), so it needs no bundle download.\n */\nexport async function openWorld(\n slugRef: string,\n options: WorldsClientOptions = {},\n): Promise<WorldSet> {\n const at = slugRef.indexOf(\"@\");\n const slug = at === -1 ? slugRef : slugRef.slice(0, at);\n const ref = at === -1 ? null : slugRef.slice(at + 1);\n\n const version = await apiRequest<\n ResolvedWorldVersion & { taskNames?: string[] }\n >(options, \"POST\", \"/api/public/benchmark-containers/resolve-version\", {\n slug,\n ...(ref ? { ref } : {}),\n });\n\n const world = new WorldSet(\n slugRef,\n slug,\n ref,\n {\n versionId: version.versionId,\n semanticVersion: version.semanticVersion ?? null,\n contentHash: version.contentHash,\n state: version.state,\n },\n [],\n options,\n );\n for (const name of version.taskNames ?? []) {\n const variant = /^[a-z0-9]+-([a-z0-9]+)-/.exec(name)?.[1] ?? null;\n world.tasks.push(new WorldTask(world, name, variant));\n }\n return world;\n}\n\n// The session surface completes the worlds module, so `@withgateway/sdk/worlds`\n// carries both halves: running a world locally, and driving one the platform\n// hosts. (session.ts imports apiRequest from here; the cycle is function-level\n// only, and the build below is what proves it resolves.)\nexport * from \"./session\";\n\n// Stored tasks: the task spec as a named, versioned project resource that\n// `openSession(world, { task: { id } })` opens on.\nexport * from \"./tasks\";\n\n// The computer-use half: surfaces, a Playwright browser on the world's UI,\n// and browser actions as model tools.\nexport * from \"./browser\";\n\n// The hub half: push, pull, propose and the content-hash primitives the CLI\n// runs on. These were reachable only from inside the package, so a consumer\n// could drive a world but never publish one.\nexport * from \"./hub\";\n\n// PR validation: push-dispatch-wait-gate as one composed call, for CI.\nexport * from \"./validate\";\n\n// Discovery: what a world holds and how each field is stored (`describeWorld`),\n// and the stored forms of a plaintext under the world's [redact] table\n// (`storedForms`, `redactionOf`) — the same digest rule as the Python runtime.\nexport * from \"./describe\";\nexport * from \"./redaction\";\nexport * from \"./transforms\";\n\n// Lookup: the rows of one entity matching a predicate (`queryRows`), by\n// stored value or — with `resolve` — by plaintext the runtime maps through\n// the same [redact] table.\nexport * from \"./query\";\n\n// Migration: a stored world into a schema world (`migrateWorld`), dry run by\n// default; the project's connector worlds at once (`migrateProjectWorlds`).\nexport * from \"./migrate\";\n\n// Tool calls into rows: the record contract, `captureToolCalls` (record an\n// agent's real calls), `toolCallsFromObservations` (from a trace) and\n// `ingestToolCalls` (into a directory or a slug). Redaction optional, off by default.\nexport * from \"./ingest\";\n","{\n \"name\": \"@withgateway/sdk\",\n \"version\": \"0.2.2\",\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 \"./cli\": {\n \"types\": \"./dist/cli.d.ts\",\n \"import\": \"./dist/cli.mjs\",\n \"require\": \"./dist/cli.js\"\n }\n },\n \"files\": [\n \"dist\",\n \"skills\",\n \"runtime\",\n \"README.md\"\n ],\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"scripts\": {\n \"prebuild\": \"node scripts/copy-skills.mjs && node scripts/copy-runtime.mjs\",\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"typecheck\": \"tsc --noEmit\",\n \"typecheck:examples\": \"tsc -p tsconfig.examples.json --noEmit\",\n \"test\": \"vitest\",\n \"test:run\": \"vitest run\",\n \"lint\": \"eslint src --ext .ts\",\n \"clean\": \"rm -rf dist\",\n \"example\": \"tsx examples/test-ab-experiment.ts\",\n \"test:crm\": \"tsx examples/test-crm-ab-experiment.ts\",\n \"test:crm:balanced\": \"tsx examples/test-crm-ab-experiment.ts --balanced\",\n \"test:crm:full\": \"tsx examples/test-crm-ab-experiment.ts --users 12 --all-tasks --concurrency 3\"\n },\n \"keywords\": [\n \"gateway\",\n \"ab-testing\",\n \"experiments\",\n \"opentelemetry\",\n \"tracing\",\n \"observability\",\n \"llm\"\n ],\n \"author\": \"Gateway Team\",\n \"license\": \"MIT\",\n \"engines\": {\n \"node\": \">=18.0.0\"\n },\n \"peerDependencies\": {\n \"@opentelemetry/api\": \"^1.0.0\",\n \"@opentelemetry/exporter-trace-otlp-http\": \">=0.50.0\",\n \"@opentelemetry/resources\": \">=1.0.0\",\n \"@opentelemetry/sdk-trace-base\": \">=1.0.0\",\n \"@opentelemetry/sdk-trace-node\": \">=1.0.0\",\n \"playwright\": \">=1.40.0\"\n },\n \"peerDependenciesMeta\": {\n \"@opentelemetry/api\": {\n \"optional\": true\n },\n \"@opentelemetry/sdk-trace-base\": {\n \"optional\": true\n },\n \"@opentelemetry/sdk-trace-node\": {\n \"optional\": true\n },\n \"@opentelemetry/exporter-trace-otlp-http\": {\n \"optional\": true\n },\n \"@opentelemetry/resources\": {\n \"optional\": true\n },\n \"playwright\": {\n \"optional\": true\n }\n },\n \"optionalDependencies\": {\n \"@arizeai/openinference-instrumentation-anthropic\": \"^0.1.15\",\n \"@arizeai/openinference-instrumentation-openai\": \"^4.1.5\"\n },\n \"devDependencies\": {\n \"@anthropic-ai/sdk\": \"^0.79.0\",\n \"@opentelemetry/api\": \"^1.9.0\",\n \"@opentelemetry/exporter-trace-otlp-http\": \"^0.212.0\",\n \"@opentelemetry/resources\": \"^2.6.0\",\n \"@opentelemetry/sdk-trace-base\": \"^1.30.1\",\n \"@opentelemetry/sdk-trace-node\": \"^2.6.0\",\n \"@opentelemetry/semantic-conventions\": \"^1.40.0\",\n \"@types/node\": \"^20.0.0\",\n \"openai\": \"^4.70.0\",\n \"tsup\": \"^8.0.0\",\n \"tsx\": \"^4.0.0\",\n \"typescript\": \"^5.0.0\",\n \"vitest\": \"^3.2.6\"\n },\n \"overrides\": {\n \"protobufjs\": \"^8.4.1\",\n \"vite@6\": \"^6.4.3\",\n \"postcss\": \"^8.5.18\",\n \"picomatch@4\": \"^4.0.4\"\n },\n \"pnpm\": {\n \"overrides\": {\n \"protobufjs\": \"^8.4.1\",\n \"vitest\": \"^3.2.6\",\n \"vite@6\": \"^6.4.3\",\n \"postcss\": \"^8.5.18\",\n \"picomatch@4\": \"^4.0.4\"\n }\n },\n \"bin\": {\n \"gateway\": \"./dist/cli.js\"\n }\n}\n","export * from \"./experiments/index\";\nexport * from \"./context/index\";\nexport * from \"./memory/index\";\nexport * from \"./personas/index\";\nexport * from \"./replay/index\";\nexport * from \"./security/index\";\nexport * from \"./sessions/index\";\nexport * from \"./users/index\";\nexport * from \"./scores/index\";\nexport * from \"./worlds/index\";\nexport * from \"./worlds/session\";\nexport * as files from \"./files/index\";\nexport * as traces from \"./traces/index\";\n\n// Agent build identity (\"the agent IS the manifest\") — defineTool wraps any\n// framework tool shape; registerPrompt joins code-shipped prompts to the\n// build; tracing.init({ agent }) assembles + registers the build.\nexport {\n defineTool,\n registerPrompt,\n registerSkill,\n registerArtifact,\n getRegisteredSkills,\n getRegisteredArtifacts,\n assembleManifest,\n computeBuildHash,\n canonicalJson,\n getRegisteredTools,\n getRegisteredPrompts,\n resetBuildRegistry,\n} from \"./build/index\";\nexport type {\n ToolEffects,\n ToolIdentity,\n ArtifactIdentity,\n RegisterArtifactOptions,\n AgentBuildManifest,\n DefineToolInput,\n} from \"./build/index\";\n\n// Top-level like the Python SDK's `gatewaysdk.identify` (lives in tracing/identity).\nexport { identify, resolveUserId } from \"./tracing/identity\";\nexport type { IdentifyOptions } from \"./tracing/identity\";\n\nimport * as _tracingModule from \"./tracing/index\";\nimport type { TracingConfig } from \"./tracing/types\";\nimport { ExperimentSpanProcessor } from \"./experiments/otel\";\n\n/**\n * Tracing module with automatic ExperimentSpanProcessor wiring.\n *\n * When imported from the main entry (\"@withgateway/sdk\"), init() automatically\n * adds ExperimentSpanProcessor so spans are tagged with experiment context.\n * Both modules share the same bundle, so the AsyncLocalStorage context is\n * shared — no cross-bundle duplication.\n */\nexport const tracing: typeof _tracingModule = {\n ..._tracingModule,\n init(config: TracingConfig = {}) {\n if (config.enableExperiments !== false) {\n const processors = [\n new ExperimentSpanProcessor(),\n ...(config.customSpanProcessors ?? []),\n ];\n return _tracingModule.init({\n ...config,\n customSpanProcessors: processors,\n });\n }\n return _tracingModule.init(config);\n },\n};\n","/**\n * Deterministic variant assignment for A/B experiments.\n *\n * Algorithm:\n * 1. Hash (experiment_key + user_id) → deterministic bucket [0, 1)\n * 2. If bucket >= traffic_percent/100 → user not in experiment\n * 3. Otherwise, normalize bucket within traffic and assign to variant by weight\n */\n\nimport { createHash } from \"crypto\";\nimport type { ExperimentConfig, Variant } from \"./types\";\n\nexport function computeHash(experimentKey: string, userId: string): number {\n const raw = createHash(\"sha256\")\n .update(`${experimentKey}:${userId}`)\n .digest(\"hex\");\n // Divide by 2³² to keep range strictly [0, 1)\n return parseInt(raw.slice(0, 8), 16) / 0x100000000;\n}\n\nexport function assignVariant(\n config: ExperimentConfig,\n userId: string,\n): Variant | null {\n if (!config.variants || config.variants.length === 0) {\n return null;\n }\n\n const bucket = computeHash(config.key, userId);\n const trafficThreshold = config.trafficPercent / 100;\n\n if (bucket >= trafficThreshold) {\n return null;\n }\n\n const normalizedBucket = bucket / trafficThreshold;\n const totalWeight = config.variants.reduce((sum, v) => sum + v.weight, 0);\n\n if (totalWeight <= 0) {\n return config.variants[0] ?? null;\n }\n\n let cumulative = 0;\n for (const variant of config.variants) {\n cumulative += variant.weight / totalWeight;\n if (normalizedBucket < cumulative) {\n return variant;\n }\n }\n\n return config.variants[config.variants.length - 1] ?? null;\n}\n","/**\n * Async context management for experiments.\n *\n * Uses AsyncLocalStorage.enterWith() to set context that persists for the\n * remainder of the current async execution context. This provides:\n *\n * - Request isolation in concurrent server environments\n * - Context that survives across async boundaries (streaming, etc.)\n * - No callback wrapper required\n *\n * The context persists until clearExperimentContext() is called or the\n * async context naturally ends (e.g., request completes).\n */\n\nimport { AsyncLocalStorage } from \"async_hooks\";\nimport type { ExperimentContext } from \"./types\";\n\n// AsyncLocalStorage for request-scoped context\nexport const experimentContextStorage =\n new AsyncLocalStorage<ExperimentContext>();\n\n/**\n * Get the current experiment context.\n */\nexport function getExperimentContext(): ExperimentContext | undefined {\n return experimentContextStorage.getStore();\n}\n\n/**\n * Set the experiment context for the current async execution.\n *\n * Uses enterWith() which sets context for the remainder of the current\n * async execution without requiring a callback wrapper. This means:\n * - Context persists across await boundaries\n * - Context is isolated per request in concurrent environments\n * - Context persists until clearExperimentContext() or request ends\n *\n * Called by getVariant() when a user is assigned to a variant.\n */\nexport function setExperimentContext(context: ExperimentContext): void {\n experimentContextStorage.enterWith(context);\n}\n\n/**\n * Clear the experiment context.\n *\n * Call this when you're done with an experiment session (e.g., after handling\n * a user request) to stop attributing spans to the experiment.\n *\n * Note: In most server frameworks, the async context naturally ends when the\n * request completes, so this is optional but recommended for explicit cleanup.\n */\nexport function clearExperimentContext(): void {\n // enterWith(undefined) effectively clears the context\n experimentContextStorage.enterWith(undefined as unknown as ExperimentContext);\n}\n\n/**\n * Run a function with experiment context (scoped).\n *\n * The context is automatically cleared when the function completes.\n * This is useful for synchronous operations or fully-contained async operations.\n *\n * For streaming/async patterns, prefer setExperimentContext() which persists\n * across async boundaries.\n */\nexport function runWithExperimentContext<T>(\n context: ExperimentContext,\n fn: () => T,\n): T {\n return experimentContextStorage.run(context, fn);\n}\n","/**\n * Batched asynchronous exposure logging.\n *\n * Collects exposure events in memory and flushes periodically\n * or when the batch size threshold is reached.\n */\n\nimport type { Exposure, ExposureLoggerConfig } from \"./types\";\n\nexport class ExposureLogger {\n private buffer: Exposure[] = [];\n private readonly batchSize: number;\n private readonly flushIntervalMs: number;\n private readonly apiUrl: string;\n private readonly apiKey: string;\n private readonly secretKey: string;\n private flushTimer: ReturnType<typeof setInterval> | null = null;\n private isFlushing = false;\n\n constructor(config: ExposureLoggerConfig) {\n this.apiUrl = config.apiUrl.replace(/\\/$/, \"\");\n this.apiKey = config.apiKey;\n this.secretKey = config.secretKey ?? \"\";\n this.batchSize = config.batchSize ?? 100;\n this.flushIntervalMs = config.flushIntervalMs ?? 5_000;\n\n this.flushTimer = setInterval(() => {\n this.flush().catch((err) => {\n console.error(\"[gateway] Exposure flush error:\", err);\n });\n }, this.flushIntervalMs);\n\n if (this.flushTimer.unref) {\n this.flushTimer.unref();\n }\n }\n\n log(exposure: Exposure): void {\n this.buffer.push(exposure);\n if (this.buffer.length >= this.batchSize) {\n this.flush().catch((err) => {\n console.error(\"[gateway] Exposure flush error:\", err);\n });\n }\n }\n\n async flush(): Promise<void> {\n if (this.isFlushing || this.buffer.length === 0) {\n return;\n }\n\n this.isFlushing = true;\n const batch = this.buffer.splice(0, this.buffer.length);\n\n try {\n const authHeader = this.secretKey\n ? `Basic ${Buffer.from(`${this.apiKey}:${this.secretKey}`).toString(\"base64\")}`\n : `Bearer ${this.apiKey}`;\n\n const response = await fetch(\n `${this.apiUrl}/api/public/experiments/exposures/batch`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: authHeader,\n },\n body: JSON.stringify({\n exposures: batch,\n }),\n },\n );\n if (!response.ok) {\n this.buffer.unshift(...batch);\n console.error(\n `[gateway] Failed to log exposures: ${response.status} ${response.statusText}`,\n );\n }\n } catch (error) {\n this.buffer.unshift(...batch);\n console.error(\"[gateway] Network error logging exposures:\", error);\n } finally {\n this.isFlushing = false;\n }\n }\n\n async shutdown(): Promise<void> {\n if (this.flushTimer) {\n clearInterval(this.flushTimer);\n this.flushTimer = null;\n }\n await this.flush();\n }\n}\n","/**\n * Main A/B experiment client for TypeScript.\n *\n * Mirrors the Python SDK's ExperimentClient in:\n * gatewaysdk/sdk/src/gatewaysdk/experiments/client.py\n */\n\nimport { assignVariant } from \"./assignment\";\nimport { runWithExperimentContext, setExperimentContext } from \"./context\";\nimport { ExposureLogger } from \"./exposure-logger\";\nimport type {\n ExperimentClientConfig,\n ExperimentConfig,\n GetVariantResult,\n RegisterExperimentInput,\n} from \"./types\";\n\nexport class ExperimentClient {\n private readonly apiUrl: string;\n private readonly apiKey: string;\n private readonly secretKey: string;\n private readonly projectId: string;\n private readonly configs = new Map<string, ExperimentConfig>();\n private readonly exposureLogger: ExposureLogger;\n\n constructor(config: ExperimentClientConfig) {\n this.apiUrl = config.apiUrl.replace(/\\/$/, \"\");\n this.apiKey = config.apiKey;\n this.secretKey = config.secretKey ?? \"\";\n this.projectId = config.projectId;\n this.exposureLogger = new ExposureLogger({\n apiUrl: this.apiUrl,\n apiKey: this.apiKey,\n secretKey: this.secretKey,\n batchSize: config.exposureLogger?.batchSize,\n flushIntervalMs: config.exposureLogger?.flushIntervalMs,\n });\n }\n\n async register(input: RegisterExperimentInput): Promise<void> {\n const config: ExperimentConfig = {\n key: input.key,\n trafficPercent: input.trafficPercent ?? 100,\n variants: input.variants.map((v) => ({\n key: v.key,\n weight: v.weight ?? 1,\n config: v.config ?? {},\n })),\n };\n\n this.configs.set(config.key, config);\n\n const syncToBackend = input.syncToBackend ?? true;\n if (syncToBackend) {\n this.syncToBackendAsync(config, input.evaluatorNames).catch((err) => {\n console.error(\n `[gateway] Failed to sync experiment ${config.key}:`,\n err,\n );\n });\n }\n }\n\n async fetch(experimentKeys?: string[]): Promise<void> {\n const url = new URL(`${this.apiUrl}/api/public/experiments`);\n if (experimentKeys && experimentKeys.length > 0) {\n url.searchParams.set(\"keys\", experimentKeys.join(\",\"));\n }\n\n const authHeader = this.secretKey\n ? `Basic ${Buffer.from(`${this.apiKey}:${this.secretKey}`).toString(\"base64\")}`\n : `Bearer ${this.apiKey}`;\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n headers: {\n Authorization: authHeader,\n },\n });\n\n if (!response.ok) {\n throw new Error(\n `Failed to fetch experiments: ${response.status} ${response.statusText}`,\n );\n }\n\n const data = (await response.json()) as {\n experiments: ExperimentConfig[];\n };\n for (const config of data.experiments) {\n this.configs.set(config.key, config);\n }\n }\n\n async getVariant(\n experimentKey: string,\n userId: string,\n options?: { fetchIfMissing?: boolean },\n ): Promise<GetVariantResult> {\n const fetchIfMissing = options?.fetchIfMissing ?? true;\n\n let config = this.configs.get(experimentKey);\n if (!config && fetchIfMissing) {\n try {\n await this.fetch([experimentKey]);\n config = this.configs.get(experimentKey);\n } catch (error) {\n console.error(\n `[gateway] Failed to fetch experiment ${experimentKey}:`,\n error,\n );\n }\n }\n\n if (!config) {\n return {\n variant: null,\n inExperiment: false,\n experimentKey,\n run: (fn) => fn(),\n };\n }\n\n const variant = assignVariant(config, userId);\n if (!variant) {\n return {\n variant: null,\n inExperiment: false,\n experimentKey,\n run: (fn) => fn(),\n };\n }\n\n this.exposureLogger.log({\n userId,\n experimentId: experimentKey,\n variantKey: variant.key,\n timestamp: new Date().toISOString(),\n });\n\n const context = {\n experimentId: experimentKey,\n variantKey: variant.key,\n userId,\n };\n\n // Set context via enterWith() so spans created anywhere in this async chain are tagged.\n // Context is automatically isolated per request - no cross-request contamination.\n setExperimentContext(context);\n\n return {\n variant,\n inExperiment: true,\n experimentKey,\n run: (fn) => runWithExperimentContext(context, fn),\n };\n }\n\n getConfig(experimentKey: string): ExperimentConfig | undefined {\n return this.configs.get(experimentKey);\n }\n\n async shutdown(): Promise<void> {\n await this.exposureLogger.shutdown();\n }\n\n private async syncToBackendAsync(\n config: ExperimentConfig,\n evaluatorNames?: string[],\n ): Promise<void> {\n const authHeader = this.secretKey\n ? `Basic ${Buffer.from(`${this.apiKey}:${this.secretKey}`).toString(\"base64\")}`\n : `Bearer ${this.apiKey}`;\n\n const response = await fetch(`${this.apiUrl}/api/public/experiments`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: authHeader,\n },\n body: JSON.stringify({\n key: config.key,\n trafficPercent: config.trafficPercent,\n variants: config.variants,\n evaluatorNames: evaluatorNames ?? [],\n }),\n });\n\n if (!response.ok) {\n const text = await response.text();\n throw new Error(\n `Failed to sync experiment: ${response.status} ${response.statusText} - ${text}`,\n );\n }\n\n console.log(`[gateway] Synced experiment '${config.key}' to backend`);\n }\n}\n","/**\n * OpenTelemetry integration for A/B experiments.\n *\n * Provides a SpanProcessor that automatically injects experiment\n * context into spans. Mirrors the Python SDK's TracingContextSpanProcessor.\n */\n\nimport type { Context } from \"@opentelemetry/api\";\nimport type {\n SpanProcessor,\n Span,\n ReadableSpan,\n} from \"@opentelemetry/sdk-trace-base\";\nimport { getExperimentContext } from \"./context\";\n\nexport const EXPERIMENT_ATTRIBUTES = {\n EXPERIMENT_ID: \"gateway.experiment.id\",\n VARIANT_KEY: \"gateway.variant.key\",\n USER_ID: \"gateway.experiment.user_id\",\n} as const;\n\nexport class ExperimentSpanProcessor implements SpanProcessor {\n onStart(span: Span, _parentContext: Context): void {\n const ctx = getExperimentContext();\n if (ctx) {\n span.setAttribute(EXPERIMENT_ATTRIBUTES.EXPERIMENT_ID, ctx.experimentId);\n span.setAttribute(EXPERIMENT_ATTRIBUTES.VARIANT_KEY, ctx.variantKey);\n span.setAttribute(EXPERIMENT_ATTRIBUTES.USER_ID, ctx.userId);\n }\n }\n\n onEnd(_span: ReadableSpan): void {}\n\n async shutdown(): Promise<void> {}\n\n async forceFlush(): Promise<void> {}\n}\n\nexport function addExperimentAttributes(\n span: Span,\n experimentId: string,\n variantKey: string,\n userId: string,\n): void {\n span.setAttribute(EXPERIMENT_ATTRIBUTES.EXPERIMENT_ID, experimentId);\n span.setAttribute(EXPERIMENT_ATTRIBUTES.VARIANT_KEY, variantKey);\n span.setAttribute(EXPERIMENT_ATTRIBUTES.USER_ID, userId);\n}\n","/**\n * Singleton experiment client for simple usage.\n *\n * This mirrors the Python SDK's `gateway.experiments` singleton pattern.\n * For advanced use cases, instantiate ExperimentClient directly.\n */\n\nimport { ExperimentClient } from \"./client\";\nimport { clearExperimentContext as clearContext } from \"./context\";\nimport type {\n ExperimentClientConfig,\n GetVariantResult,\n RegisterExperimentInput,\n} from \"./types\";\n\nlet client: ExperimentClient | null = null;\n\nexport interface InitConfig {\n apiKey: string;\n secretKey?: string;\n baseUrl: string;\n projectId?: string;\n}\n\n/**\n * Initialize the experiments singleton.\n * Must be called before using other methods.\n */\nexport function init(config: InitConfig): void {\n client = new ExperimentClient({\n apiUrl: config.baseUrl,\n apiKey: config.apiKey,\n secretKey: config.secretKey,\n projectId: config.projectId ?? \"\",\n });\n}\n\n/**\n * Register an experiment configuration.\n */\nexport async function register(input: RegisterExperimentInput): Promise<void> {\n if (!client) {\n throw new Error(\n \"Experiments not initialized. Call experiments.init() first.\",\n );\n }\n return client.register(input);\n}\n\n/**\n * Get variant for a user. Returns null if user is not in experiment.\n */\nexport async function getVariant(\n experimentKey: string,\n userId: string,\n options?: { fetchIfMissing?: boolean },\n): Promise<GetVariantResult> {\n if (!client) {\n throw new Error(\n \"Experiments not initialized. Call experiments.init() first.\",\n );\n }\n return client.getVariant(experimentKey, userId, options);\n}\n\n/**\n * Fetch experiment configurations from the backend.\n */\nexport async function fetch(experimentKeys?: string[]): Promise<void> {\n if (!client) {\n throw new Error(\n \"Experiments not initialized. Call experiments.init() first.\",\n );\n }\n return client.fetch(experimentKeys);\n}\n\n/**\n * Flush pending exposures and shut down the client.\n */\nexport async function shutdown(): Promise<void> {\n if (client) {\n await client.shutdown();\n client = null;\n }\n // Also clear any lingering experiment context\n clearContext();\n}\n\n/**\n * Clear the current experiment context.\n *\n * Call this when you're done with an experiment session (e.g., after handling\n * a user request) to stop attributing new spans to the experiment.\n *\n * This mirrors Python's `gateway.experiments.clear_current_experiment()`.\n */\nexport function clearExperimentContext(): void {\n clearContext();\n}\n\n/**\n * Get the underlying ExperimentClient instance.\n * Returns null if not initialized.\n */\nexport function getClient(): ExperimentClient | null {\n return client;\n}\n","type ContextRepoKind = \"agent\" | \"prompt\" | \"skill\" | \"memory\";\ntype ContextWritePolicy = \"read_only\" | \"propose\" | \"commit\";\n\ntype ContextFileEntry =\n | {\n type: \"file\";\n content: string;\n mimeType: string;\n mime_type: string;\n }\n | {\n type: \"agent\" | \"skill\";\n repoHandle: string;\n repo_handle: string;\n commitId?: string | null;\n commit_id?: string | null;\n };\n\ntype ContextRepo<TKind extends ContextRepoKind = ContextRepoKind> = {\n id: string;\n repoHandle: string;\n repo_handle: string;\n ownerHandle: string;\n owner_handle: string;\n kind: TKind;\n description: string;\n readme: string;\n tags: string[];\n writePolicy: ContextWritePolicy;\n write_policy: ContextWritePolicy;\n isPublic: boolean;\n is_public: boolean;\n isArchived: boolean;\n is_archived: boolean;\n url?: string;\n createdAt: string;\n created_at: string;\n updatedAt: string;\n updated_at: string;\n};\n\ntype ContextCommit = {\n id: string;\n commitHash: string;\n commit_hash: string;\n parentCommitHash: string | null;\n parent_commit_hash: string | null;\n createdAt: string;\n created_at: string;\n};\n\ntype ContextSnapshot<TKind extends ContextRepoKind = ContextRepoKind> = {\n repo: ContextRepo<TKind>;\n commit: ContextCommit;\n files: Record<string, ContextFileEntry>;\n};\n\ntype ContextListResponse<TKind extends ContextRepoKind = ContextRepoKind> = {\n repos: ContextRepo<TKind>[];\n limit: number;\n offset: number;\n total: number;\n};\n\ntype ContextPushResponse = {\n url: string;\n status: \"committed\" | \"proposed\";\n repoId: string;\n repo_id: string;\n commitId: string | null;\n commit_id: string | null;\n commitHash: string | null;\n commit_hash: string | null;\n proposalId?: string | null;\n proposal_id?: string | null;\n};\n\ntype ContextFileInput =\n | {\n content: string;\n mimeType?: string;\n mime_type?: string;\n }\n | {\n repoHandle?: string;\n repo_handle?: string;\n kind?: \"agent\" | \"skill\";\n type?: \"agent\" | \"skill\";\n commitId?: string | null;\n commit_id?: string | null;\n }\n | null;\n\ntype ContextRuntimeContext = {\n source?: \"sdk\" | \"agent\" | \"dream\" | \"api\" | \"platform\";\n actorType?: \"api_key\" | \"agent\" | \"process\" | \"user\";\n proposedBy?: string;\n agentId?: string;\n agentStableId?: string;\n processId?: string;\n traceId?: string;\n spanId?: string;\n sessionId?: string;\n userId?: string;\n teamId?: string;\n metadata?: Record<string, unknown>;\n};\n\ntype ContextPullOptions = {\n version?: string;\n};\n\ntype ContextListOptions = {\n query?: string;\n isPublic?: boolean;\n isArchived?: boolean;\n limit?: number;\n offset?: number;\n};\n\ntype ContextPushOptions = ContextRuntimeContext & {\n files: Record<string, ContextFileInput>;\n parentCommit?: string;\n description?: string;\n readme?: string;\n tags?: string[];\n isPublic?: boolean;\n writePolicy?: ContextWritePolicy;\n message?: string;\n};\n\ntype ContextRepoRef =\n | string\n | {\n identifier?: string;\n repoHandle?: string;\n repo_handle?: string;\n label?: string;\n version?: string;\n writable?: boolean;\n };\n\ntype ResolvedContextRef<TKind extends ContextRepoKind = ContextRepoKind> = {\n identifier: string;\n version?: string;\n writable?: boolean;\n snapshot: ContextSnapshot<TKind>;\n primaryPath: string | null;\n content: string;\n};\n\ntype ResolvedAgentContext = {\n agent: ContextSnapshot<\"agent\">;\n config: Record<string, unknown>;\n prompt: ResolvedContextRef<\"prompt\"> | null;\n prompts: ResolvedContextRef<\"prompt\">[];\n skills: ResolvedContextRef<\"skill\">[];\n memory: ResolvedContextRef<\"memory\">[];\n system: string;\n renderSystem: (options?: RenderSystemOptions) => string;\n provenance: ContextProvenance[];\n};\n\ntype ContextProvenance = {\n kind: ContextRepoKind;\n repoHandle: string;\n commitHash: string;\n label?: string;\n};\n\ntype RenderSystemOptions = {\n includeAgent?: boolean;\n includePrompts?: boolean;\n includeSkills?: boolean;\n includeMemory?: boolean;\n};\n\ntype GatewayContextConfig = {\n host: string;\n publicKey: string;\n secretKey: string;\n debug?: boolean;\n};\n\ntype GatewayContextFromEnvConfig = Partial<GatewayContextConfig>;\n\nexport class GatewayContextError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message);\n this.name = \"GatewayContextError\";\n this.cause = options?.cause;\n }\n}\n\nexport class GatewayContextConflictError extends GatewayContextError {\n readonly latestCommit: unknown;\n\n constructor(message: string, latestCommit: unknown) {\n super(message);\n this.name = \"GatewayContextConflictError\";\n this.latestCommit = latestCommit;\n }\n}\n\nexport class GatewayContext {\n private readonly host: string;\n private readonly publicKey: string;\n private readonly secretKey: string;\n private readonly debug: boolean;\n\n constructor(config: GatewayContextConfig) {\n this.host = config.host.replace(/\\/$/, \"\");\n this.publicKey = config.publicKey;\n this.secretKey = config.secretKey;\n this.debug = config.debug ?? false;\n }\n\n static fromEnv(config: GatewayContextFromEnvConfig = {}) {\n const host =\n config.host ?? process.env.GATEWAY_HOST ?? process.env.GATEWAY_HOST;\n const publicKey =\n config.publicKey ??\n process.env.GATEWAY_PUBLIC_KEY ??\n process.env.GATEWAY_PUBLIC_KEY;\n const secretKey =\n config.secretKey ??\n process.env.GATEWAY_SECRET_KEY ??\n 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 GatewayContextError(\n `Missing Gateway context configuration: ${missing.join(\", \")}`,\n );\n }\n\n return new GatewayContext({\n ...config,\n host: host!,\n publicKey: publicKey!,\n secretKey: secretKey!,\n });\n }\n\n pullAgent(identifier: string, options: ContextPullOptions = {}) {\n return this.pull(\"agent\", identifier, options);\n }\n\n pullPrompt(identifier: string, options: ContextPullOptions = {}) {\n return this.pull(\"prompt\", identifier, options);\n }\n\n pullSkill(identifier: string, options: ContextPullOptions = {}) {\n return this.pull(\"skill\", identifier, options);\n }\n\n pullMemory(identifier: string, options: ContextPullOptions = {}) {\n return this.pull(\"memory\", identifier, options);\n }\n\n pushAgent(identifier: string, options: ContextPushOptions) {\n return this.push(\"agent\", identifier, options);\n }\n\n pushPrompt(identifier: string, options: ContextPushOptions) {\n return this.push(\"prompt\", identifier, options);\n }\n\n pushSkill(identifier: string, options: ContextPushOptions) {\n return this.push(\"skill\", identifier, options);\n }\n\n pushMemory(identifier: string, options: ContextPushOptions) {\n return this.push(\"memory\", identifier, options);\n }\n\n listAgents(options: ContextListOptions = {}) {\n return this.list(\"agent\", options);\n }\n\n listPrompts(options: ContextListOptions = {}) {\n return this.list(\"prompt\", options);\n }\n\n listSkills(options: ContextListOptions = {}) {\n return this.list(\"skill\", options);\n }\n\n listMemory(options: ContextListOptions = {}) {\n return this.list(\"memory\", options);\n }\n\n agentExists(identifier: string) {\n return this.exists(\"agent\", identifier);\n }\n\n promptExists(identifier: string) {\n return this.exists(\"prompt\", identifier);\n }\n\n skillExists(identifier: string) {\n return this.exists(\"skill\", identifier);\n }\n\n memoryExists(identifier: string) {\n return this.exists(\"memory\", identifier);\n }\n\n deleteAgent(identifier: string) {\n return this.delete(\"agent\", identifier);\n }\n\n deletePrompt(identifier: string) {\n return this.delete(\"prompt\", identifier);\n }\n\n deleteSkill(identifier: string) {\n return this.delete(\"skill\", identifier);\n }\n\n deleteMemory(identifier: string) {\n return this.delete(\"memory\", identifier);\n }\n\n async resolveAgent(\n identifier: string,\n runtimeContext: ContextRuntimeContext = {},\n ): Promise<ResolvedAgentContext> {\n const agent = await this.pullAgent(identifier);\n const config = parseJsonFile(agent, \"config.json\");\n const prompts = await this.resolveRefs(\"prompt\", getPromptRefs(config));\n const skills = await this.resolveRefs(\"skill\", getRefList(config.skills));\n const memory = await this.resolveRefs(\"memory\", getRefList(config.memory));\n const bundleBase = {\n agent,\n config,\n prompt: prompts[0] ?? null,\n prompts,\n skills,\n memory,\n provenance: [\n provenanceFor(agent),\n ...prompts.map(({ snapshot, version }) => provenanceFor(snapshot, version)),\n ...skills.map(({ snapshot, version }) => provenanceFor(snapshot, version)),\n ...memory.map(({ snapshot, version }) => provenanceFor(snapshot, version)),\n ],\n };\n\n const renderSystem = (options: RenderSystemOptions = {}) =>\n renderAgentSystem(bundleBase, options);\n\n if (Object.keys(runtimeContext).length > 0) {\n this.log(\"resolveAgent runtime context %o\", runtimeContext);\n }\n\n return {\n ...bundleBase,\n system: renderSystem(),\n renderSystem,\n };\n }\n\n async pull<TKind extends ContextRepoKind>(\n kind: TKind,\n identifier: string,\n options: ContextPullOptions = {},\n ): Promise<ContextSnapshot<TKind>> {\n const query = new URLSearchParams();\n if (options.version) query.set(\"version\", options.version);\n const suffix = query.toString() ? `?${query.toString()}` : \"\";\n return this.requestJson<ContextSnapshot<TKind>>(\n \"GET\",\n `/api/public/context/${endpointForKind(kind)}/${encodeIdentifier(\n identifier,\n )}${suffix}`,\n );\n }\n\n async push<TKind extends ContextRepoKind>(\n kind: TKind,\n identifier: string,\n options: ContextPushOptions,\n ): Promise<ContextPushResponse> {\n return this.requestJson<ContextPushResponse>(\n \"POST\",\n `/api/public/context/${endpointForKind(kind)}/${encodeIdentifier(\n identifier,\n )}`,\n {\n files: options.files,\n ...(options.parentCommit ? { parentCommit: options.parentCommit } : {}),\n ...(options.description ? { description: options.description } : {}),\n ...(options.readme ? { readme: options.readme } : {}),\n ...(options.tags ? { tags: options.tags } : {}),\n ...(options.isPublic !== undefined ? { isPublic: options.isPublic } : {}),\n ...(options.writePolicy ? { writePolicy: options.writePolicy } : {}),\n ...(options.message ? { message: options.message } : {}),\n ...runtimeContextPayload(options),\n },\n );\n }\n\n async list<TKind extends ContextRepoKind>(\n kind: TKind,\n options: ContextListOptions = {},\n ): Promise<ContextListResponse<TKind>> {\n const query = new URLSearchParams();\n if (options.query) query.set(\"query\", options.query);\n if (options.isPublic !== undefined) query.set(\"isPublic\", String(options.isPublic));\n if (options.isArchived !== undefined)\n query.set(\"isArchived\", String(options.isArchived));\n if (options.limit !== undefined) query.set(\"limit\", String(options.limit));\n if (options.offset !== undefined) query.set(\"offset\", String(options.offset));\n const suffix = query.toString() ? `?${query.toString()}` : \"\";\n return this.requestJson<ContextListResponse<TKind>>(\n \"GET\",\n `/api/public/context/${endpointForKind(kind)}${suffix}`,\n );\n }\n\n async exists(kind: ContextRepoKind, identifier: string): Promise<boolean> {\n const query = new URLSearchParams({ exists: \"true\" });\n const response = await this.requestJson<{ exists: boolean }>(\n \"GET\",\n `/api/public/context/${endpointForKind(kind)}/${encodeIdentifier(\n identifier,\n )}?${query.toString()}`,\n );\n return response.exists;\n }\n\n async delete(kind: ContextRepoKind, identifier: string) {\n return this.requestJson<{ deleted: boolean; repoHandle: string; repo_handle: string }>(\n \"DELETE\",\n `/api/public/context/${endpointForKind(kind)}/${encodeIdentifier(identifier)}`,\n );\n }\n\n private async resolveRefs<TKind extends ContextRepoKind>(\n kind: TKind,\n refs: ContextRepoRef[],\n ): Promise<ResolvedContextRef<TKind>[]> {\n const resolved: ResolvedContextRef<TKind>[] = [];\n for (const ref of refs) {\n const normalized = normalizeRef(ref);\n if (!normalized) continue;\n const snapshot = await this.pull(kind, normalized.identifier, {\n version: normalized.version,\n });\n const primaryPath = primaryPathForKind(kind, snapshot);\n const content = primaryPath ? readFile(snapshot, primaryPath) ?? \"\" : \"\";\n resolved.push({\n ...normalized,\n snapshot,\n primaryPath,\n content,\n });\n }\n return resolved;\n }\n\n private async requestJson<TResponse>(\n method: \"GET\" | \"POST\" | \"DELETE\",\n path: string,\n payload?: Record<string, unknown>,\n ): Promise<TResponse> {\n const response = await fetch(`${this.host}${path}`, {\n method,\n headers: {\n Authorization: this.authHeader(),\n ...(payload ? { \"Content-Type\": \"application/json\" } : {}),\n },\n ...(payload ? { body: JSON.stringify(payload) } : {}),\n });\n\n const text = await response.text();\n const body = text ? safeJson(text) : {};\n if (!response.ok) {\n const message =\n typeof body.message === \"string\"\n ? body.message\n : `Gateway API ${response.status} on ${path}`;\n if (response.status === 409) {\n throw new GatewayContextConflictError(\n message,\n body.latestCommit ?? null,\n );\n }\n throw new GatewayContextError(message);\n }\n\n this.log(\"%s %s -> %s\", method, path, response.status);\n return body as TResponse;\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.context] ${message}`, ...args);\n }\n }\n}\n\nfunction renderAgentSystem(\n bundle: Omit<ResolvedAgentContext, \"system\" | \"renderSystem\">,\n options: RenderSystemOptions = {},\n) {\n const includeAgent = options.includeAgent ?? true;\n const includePrompts = options.includePrompts ?? true;\n const includeSkills = options.includeSkills ?? true;\n const includeMemory = options.includeMemory ?? false;\n const sections: string[] = [];\n\n if (includeAgent) {\n const agentContent = readFile(bundle.agent, \"AGENTS.md\");\n if (agentContent) sections.push(formatSection(\"Agent\", bundle.agent, agentContent));\n }\n\n if (includePrompts) {\n for (const prompt of bundle.prompts) {\n if (prompt.content) {\n sections.push(formatSection(\"Prompt\", prompt.snapshot, prompt.content));\n }\n }\n }\n\n if (includeSkills) {\n for (const skill of bundle.skills) {\n if (skill.content) {\n sections.push(formatSection(\"Skill\", skill.snapshot, skill.content));\n }\n }\n }\n\n if (includeMemory) {\n for (const memory of bundle.memory) {\n if (memory.content) {\n sections.push(formatSection(\"Memory\", memory.snapshot, memory.content));\n }\n }\n }\n\n return sections.join(\"\\n\\n---\\n\\n\");\n}\n\nfunction formatSection(\n title: string,\n snapshot: ContextSnapshot,\n content: string,\n) {\n return [\n `# ${title}: ${snapshot.repo.repoHandle}`,\n `<!-- commit: ${snapshot.commit.commitHash} -->`,\n \"\",\n content.trim(),\n ].join(\"\\n\");\n}\n\nfunction getPromptRefs(config: Record<string, unknown>): ContextRepoRef[] {\n const refs = [\n ...getRefList(config.prompt),\n ...getRefList(config.promptRef),\n ...getRefList(config.prompt_ref),\n ...getRefList(config.prompts),\n ];\n return dedupeRefs(refs);\n}\n\nfunction getRefList(value: unknown): ContextRepoRef[] {\n if (!value) return [];\n if (typeof value === \"string\") return [value];\n if (Array.isArray(value)) return value.filter(isContextRepoRef);\n if (isContextRepoRef(value)) return [value];\n return [];\n}\n\nfunction isContextRepoRef(value: unknown): value is ContextRepoRef {\n if (typeof value === \"string\") return true;\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n const record = value as Record<string, unknown>;\n return [\"identifier\", \"repoHandle\", \"repo_handle\"].some(\n (key) => typeof record[key] === \"string\",\n );\n}\n\nfunction dedupeRefs(refs: ContextRepoRef[]) {\n const seen = new Set<string>();\n return refs.filter((ref) => {\n const normalized = normalizeRef(ref);\n if (!normalized) return false;\n const key = `${normalized.identifier}:${normalized.version ?? \"\"}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n}\n\nfunction normalizeRef(ref: ContextRepoRef) {\n if (typeof ref === \"string\") {\n const identifier = ref.trim();\n return identifier ? { identifier } : null;\n }\n\n const identifier = (\n ref.identifier ??\n ref.repoHandle ??\n ref.repo_handle ??\n \"\"\n ).trim();\n if (!identifier) return null;\n\n return {\n identifier,\n version: ref.version ?? ref.label,\n writable: ref.writable,\n };\n}\n\nfunction primaryPathForKind(kind: ContextRepoKind, snapshot: ContextSnapshot) {\n const preferred =\n kind === \"agent\"\n ? \"AGENTS.md\"\n : kind === \"prompt\"\n ? \"PROMPT.md\"\n : kind === \"skill\"\n ? \"SKILL.md\"\n : \"MEMORY.md\";\n if (readFile(snapshot, preferred)) return preferred;\n return (\n Object.entries(snapshot.files).find(\n ([path, entry]) => entry.type === \"file\" && path.endsWith(\".md\"),\n )?.[0] ?? null\n );\n}\n\nfunction parseJsonFile(snapshot: ContextSnapshot, path: string) {\n const content = readFile(snapshot, path);\n if (!content) return {};\n try {\n const parsed = JSON.parse(content);\n return parsed && typeof parsed === \"object\" && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : {};\n } catch {\n return {};\n }\n}\n\nfunction readFile(snapshot: ContextSnapshot, path: string) {\n const entry = snapshot.files[path];\n return entry?.type === \"file\" ? entry.content : null;\n}\n\nfunction provenanceFor(\n snapshot: ContextSnapshot,\n label?: string,\n): ContextProvenance {\n return {\n kind: snapshot.repo.kind,\n repoHandle: snapshot.repo.repoHandle,\n commitHash: snapshot.commit.commitHash,\n ...(label ? { label } : {}),\n };\n}\n\nfunction endpointForKind(kind: ContextRepoKind) {\n return kind === \"memory\" ? \"memory\" : `${kind}s`;\n}\n\nfunction runtimeContextPayload(options: ContextRuntimeContext) {\n return {\n ...(options.source ? { source: options.source } : {}),\n ...(options.actorType ? { actorType: options.actorType } : {}),\n ...(options.proposedBy ? { proposedBy: options.proposedBy } : {}),\n ...(options.agentId ? { agentId: options.agentId } : {}),\n ...(options.agentStableId ? { agentStableId: options.agentStableId } : {}),\n ...(options.processId ? { processId: options.processId } : {}),\n ...(options.traceId ? { traceId: options.traceId } : {}),\n ...(options.spanId ? { spanId: options.spanId } : {}),\n ...(options.sessionId ? { sessionId: options.sessionId } : {}),\n ...(options.userId ? { userId: options.userId } : {}),\n ...(options.teamId ? { teamId: options.teamId } : {}),\n ...(options.metadata ? { metadata: options.metadata } : {}),\n };\n}\n\nfunction encodeIdentifier(identifier: string) {\n return identifier\n .split(\"/\")\n .filter(Boolean)\n .map((part) => encodeURIComponent(part))\n .join(\"/\");\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 context = {\n fromEnv: GatewayContext.fromEnv,\n};\n\nexport { renderAgentSystem };\n\nexport type {\n GatewayContextConfig,\n ContextCommit as GatewayContextCommit,\n ContextFileEntry as GatewayContextFileEntry,\n ContextFileInput as GatewayContextFileInput,\n ContextListOptions as GatewayContextListOptions,\n ContextListResponse as GatewayContextListResponse,\n ContextPullOptions as GatewayContextPullOptions,\n ContextPushOptions as GatewayContextPushOptions,\n ContextPushResponse as GatewayContextPushResponse,\n ContextRepo as GatewayContextRepo,\n ContextRepoKind as GatewayContextRepoKind,\n ContextRuntimeContext as GatewayContextRuntimeContext,\n ContextSnapshot as GatewayContextSnapshot,\n ContextWritePolicy as GatewayContextWritePolicy,\n RenderSystemOptions as GatewayRenderSystemOptions,\n ResolvedAgentContext as GatewayResolvedAgentContext,\n ResolvedContextRef as GatewayResolvedContextRef,\n};\n","type MemoryWritePolicy = \"read_only\" | \"propose\" | \"commit\";\n\ntype MemoryFileEntry =\n | {\n type: \"file\";\n content: string;\n mimeType: string;\n mime_type: string;\n }\n | {\n type: \"agent\" | \"skill\";\n repoHandle: string;\n repo_handle: string;\n commitId?: string | null;\n commit_id?: string | null;\n };\n\ntype MemoryRepo = {\n id: string;\n repoHandle: string;\n repo_handle: string;\n ownerHandle: string;\n owner_handle: string;\n kind: \"memory\";\n description: string;\n readme: string;\n tags: string[];\n writePolicy: MemoryWritePolicy;\n write_policy: MemoryWritePolicy;\n isPublic: boolean;\n is_public: boolean;\n isArchived: boolean;\n is_archived: boolean;\n url?: string;\n createdAt: string;\n created_at: string;\n updatedAt: string;\n updated_at: string;\n};\n\ntype MemoryCommit = {\n id: string;\n commitHash: string;\n commit_hash: string;\n parentCommitHash: string | null;\n parent_commit_hash: string | null;\n createdAt: string;\n created_at: string;\n};\n\ntype MemorySnapshot = {\n repo: MemoryRepo;\n commit: MemoryCommit;\n files: Record<string, MemoryFileEntry>;\n};\n\ntype MemoryPushResponse = {\n url: string;\n status: \"committed\" | \"proposed\";\n repoId: string;\n repo_id: string;\n commitId: string | null;\n commit_id: string | null;\n commitHash: string | null;\n commit_hash: string | null;\n proposalId?: string | null;\n proposal_id?: string | null;\n};\n\ntype MemoryRuntimeContext = {\n source?: \"sdk\" | \"agent\" | \"dream\" | \"api\" | \"platform\";\n actorType?: \"api_key\" | \"agent\" | \"process\" | \"user\";\n proposedBy?: string;\n agentId?: string;\n agentStableId?: string;\n processId?: string;\n traceId?: string;\n spanId?: string;\n sessionId?: string;\n userId?: string;\n teamId?: string;\n metadata?: Record<string, unknown>;\n};\n\ntype MemoryPullOptions = {\n version?: string;\n};\n\ntype MemoryWriteOptions = MemoryRuntimeContext & {\n parentCommit?: string;\n message?: string;\n mimeType?: string;\n};\n\ntype MemoryDeleteOptions = MemoryRuntimeContext & {\n parentCommit?: string;\n message?: string;\n};\n\ntype GatewayMemoryConfig = {\n host: string;\n publicKey: string;\n secretKey: string;\n debug?: boolean;\n};\n\ntype GatewayMemoryFromEnvConfig = Partial<GatewayMemoryConfig>;\n\nexport class GatewayMemoryError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message);\n this.name = \"GatewayMemoryError\";\n this.cause = options?.cause;\n }\n}\n\nexport class GatewayMemoryConflictError extends GatewayMemoryError {\n readonly latestCommit: unknown;\n\n constructor(message: string, latestCommit: unknown) {\n super(message);\n this.name = \"GatewayMemoryConflictError\";\n this.latestCommit = latestCommit;\n }\n}\n\nexport class GatewayMemory {\n private readonly host: string;\n private readonly publicKey: string;\n private readonly secretKey: string;\n private readonly debug: boolean;\n\n constructor(config: GatewayMemoryConfig) {\n this.host = config.host.replace(/\\/$/, \"\");\n this.publicKey = config.publicKey;\n this.secretKey = config.secretKey;\n this.debug = config.debug ?? false;\n }\n\n static fromEnv(config: GatewayMemoryFromEnvConfig = {}) {\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 GatewayMemoryError(\n `Missing Gateway memory configuration: ${missing.join(\", \")}`,\n );\n }\n\n return new GatewayMemory({\n ...config,\n host: host!,\n publicKey: publicKey!,\n secretKey: secretKey!,\n });\n }\n\n async pull(\n identifier: string,\n options: MemoryPullOptions = {},\n ): Promise<MemorySnapshot> {\n const query = new URLSearchParams();\n if (options.version) query.set(\"version\", options.version);\n const suffix = query.toString() ? `?${query.toString()}` : \"\";\n return this.requestJson<MemorySnapshot>(\n \"GET\",\n `/api/public/context/memory/${encodeIdentifier(identifier)}${suffix}`,\n );\n }\n\n async read(\n target: string | MemorySnapshot,\n path: string,\n options: MemoryPullOptions = {},\n ): Promise<string | null> {\n const snapshot =\n typeof target === \"string\" ? await this.pull(target, options) : target;\n const file = snapshot.files[path];\n return file?.type === \"file\" ? file.content : null;\n }\n\n async write(\n target: string | MemorySnapshot,\n path: string,\n content: string,\n options: MemoryWriteOptions = {},\n ) {\n const snapshot =\n typeof target === \"string\" ? await this.pull(target) : target;\n return this.push(snapshot.repo.repoHandle, {\n files: {\n [path]: {\n content,\n ...(options.mimeType ? { mimeType: options.mimeType } : {}),\n },\n },\n parentCommit: options.parentCommit ?? snapshot.commit.commitHash,\n message: options.message,\n ...runtimeContextPayload(options),\n });\n }\n\n async delete(\n target: string | MemorySnapshot,\n path: string,\n options: MemoryDeleteOptions = {},\n ) {\n const snapshot =\n typeof target === \"string\" ? await this.pull(target) : target;\n return this.push(snapshot.repo.repoHandle, {\n files: { [path]: null },\n parentCommit: options.parentCommit ?? snapshot.commit.commitHash,\n message: options.message,\n ...runtimeContextPayload(options),\n });\n }\n\n private async push(\n identifier: string,\n payload: Record<string, unknown>,\n ): Promise<MemoryPushResponse> {\n return this.requestJson<MemoryPushResponse>(\n \"POST\",\n `/api/public/context/memory/${encodeIdentifier(identifier)}`,\n payload,\n );\n }\n\n private async requestJson<TResponse>(\n method: \"GET\" | \"POST\",\n path: string,\n payload?: Record<string, unknown>,\n ): Promise<TResponse> {\n const response = await fetch(`${this.host}${path}`, {\n method,\n headers: {\n Authorization: this.authHeader(),\n ...(payload ? { \"Content-Type\": \"application/json\" } : {}),\n },\n ...(payload ? { body: JSON.stringify(payload) } : {}),\n });\n\n const text = await response.text();\n const body = text ? safeJson(text) : {};\n if (!response.ok) {\n const message =\n typeof body.message === \"string\"\n ? body.message\n : `Gateway API ${response.status} on ${path}`;\n if (response.status === 409) {\n throw new GatewayMemoryConflictError(\n message,\n body.latestCommit ?? null,\n );\n }\n throw new GatewayMemoryError(message);\n }\n\n this.log(\"%s %s -> %s\", method, path, response.status);\n return body as TResponse;\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.memory] ${message}`, ...args);\n }\n }\n}\n\nfunction runtimeContextPayload(options: MemoryRuntimeContext) {\n return {\n ...(options.source ? { source: options.source } : {}),\n ...(options.actorType ? { actorType: options.actorType } : {}),\n ...(options.proposedBy ? { proposedBy: options.proposedBy } : {}),\n ...(options.agentId ? { agentId: options.agentId } : {}),\n ...(options.agentStableId ? { agentStableId: options.agentStableId } : {}),\n ...(options.processId ? { processId: options.processId } : {}),\n ...(options.traceId ? { traceId: options.traceId } : {}),\n ...(options.spanId ? { spanId: options.spanId } : {}),\n ...(options.sessionId ? { sessionId: options.sessionId } : {}),\n ...(options.userId ? { userId: options.userId } : {}),\n ...(options.teamId ? { teamId: options.teamId } : {}),\n ...(options.metadata ? { metadata: options.metadata } : {}),\n };\n}\n\nfunction encodeIdentifier(identifier: string) {\n return identifier\n .split(\"/\")\n .filter(Boolean)\n .map((part) => encodeURIComponent(part))\n .join(\"/\");\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 memory = {\n fromEnv: GatewayMemory.fromEnv,\n};\n\nexport type {\n GatewayMemoryConfig,\n MemoryCommit as GatewayMemoryCommit,\n MemoryDeleteOptions as GatewayMemoryDeleteOptions,\n MemoryFileEntry as GatewayMemoryFileEntry,\n MemoryPullOptions as GatewayMemoryPullOptions,\n MemoryPushResponse as GatewayMemoryPushResponse,\n MemoryRepo as GatewayMemoryRepo,\n MemoryRuntimeContext as GatewayMemoryRuntimeContext,\n MemorySnapshot as GatewayMemorySnapshot,\n MemoryWriteOptions as GatewayMemoryWriteOptions,\n MemoryWritePolicy as GatewayMemoryWritePolicy,\n};\n","/**\n * Personas — simulated users served by the Gateway platform.\n *\n * A persona is a crafted user profile (usually derived from real sessions on\n * the platform) that Gateway serves as an endpoint. Use it to drive your agent\n * in tests: the persona plays the user, your agent plays itself.\n *\n * Example:\n * ```ts\n * import { PersonasClient } from \"@withgateway/sdk/personas\";\n *\n * const personas = PersonasClient.fromEnv();\n * const persona = await personas.get(\"persona_id\");\n *\n * const messages: PersonaMessage[] = [];\n * let reply = await persona.respond(messages); // persona opens the conversation\n * while (!reply.done) {\n * messages.push({ role: \"user\", content: reply.content });\n * const agentAnswer = await myAgent(messages); // your agent under test\n * messages.push({ role: \"assistant\", content: agentAnswer });\n * reply = await persona.respond(messages);\n * }\n * ```\n *\n * Message roles are from YOUR agent's perspective: `user` = the simulated\n * user's turns, `assistant` = your agent's turns.\n */\n\ntype PersonaMessage = {\n role: \"user\" | \"assistant\";\n content: string;\n};\n\n/** One simulated-user turn. */\ntype PersonaReply = {\n content: string;\n done: boolean;\n};\n\ntype PersonasClientConfig = {\n host: string;\n publicKey: string;\n secretKey: string;\n timeoutSeconds?: number;\n debug?: boolean;\n};\n\ntype PersonasClientFromEnvConfig = Partial<PersonasClientConfig>;\n\n/** Raised when the Gateway personas API cannot complete a request. */\nexport class PersonaError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message);\n this.name = \"PersonaError\";\n this.cause = options?.cause;\n }\n}\n\n/** A persona definition plus a bound `respond` helper. */\nexport class Persona {\n readonly id: string;\n readonly name: string;\n readonly description: string | null;\n readonly version: number;\n readonly instructions: string;\n readonly examples: string[];\n private readonly client: PersonasClient | null;\n\n constructor(fields: {\n id: string;\n name: string;\n description: string | null;\n version: number;\n instructions: string;\n examples?: string[];\n client?: PersonasClient | null;\n }) {\n this.id = fields.id;\n this.name = fields.name;\n this.description = fields.description;\n this.version = fields.version;\n this.instructions = fields.instructions;\n this.examples = fields.examples ?? [];\n this.client = fields.client ?? null;\n }\n\n /**\n * Get the persona's next user message for a conversation.\n *\n * `messages` use your agent's perspective: role `user` for the simulated\n * user's prior turns, `assistant` for your agent's turns.\n * `done` is true when the persona considers its goal met.\n */\n respond(messages: PersonaMessage[]): Promise<PersonaReply> {\n if (this.client === null) {\n throw new PersonaError(\"Persona is not bound to a client.\");\n }\n return this.client.chat(this.id, messages);\n }\n}\n\n/** Client for Gateway's persona endpoints (HTTP Basic project keys). */\nexport class PersonasClient {\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: PersonasClientConfig) {\n this.host = config.host.replace(/\\/$/, \"\");\n this.publicKey = config.publicKey;\n this.secretKey = config.secretKey;\n this.timeoutSeconds = config.timeoutSeconds ?? 120;\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: PersonasClientFromEnvConfig = {}) {\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 PersonaError(\n `Missing Gateway persona configuration: ${missing.join(\", \")}`,\n );\n }\n\n return new PersonasClient({\n ...config,\n host: host!,\n publicKey: publicKey!,\n secretKey: secretKey!,\n });\n }\n\n /** List the project's personas (without full instructions). */\n async list(): Promise<Persona[]> {\n const payload = await this.requestJson(\"GET\", \"/api/public/personas\");\n const items = Array.isArray(payload.data) ? payload.data : [];\n return items\n .filter(isRecord)\n .map(\n (item) =>\n new Persona({\n id: String(item.id),\n name: String(item.name),\n description: (item.description as string | null | undefined) ?? null,\n version: typeof item.version === \"number\" ? item.version : 1,\n instructions: \"\",\n client: this,\n }),\n );\n }\n\n /** Fetch a persona (full definition) bound to this client. */\n async get(personaId: string): Promise<Persona> {\n const item = await this.requestJson(\n \"GET\",\n `/api/public/personas/${encodeURIComponent(personaId)}/chat`,\n );\n return new Persona({\n id: String(item.id),\n name: String(item.name),\n description: (item.description as string | null | undefined) ?? null,\n version: typeof item.version === \"number\" ? item.version : 1,\n instructions: typeof item.instructions === \"string\" ? item.instructions : \"\",\n examples: Array.isArray(item.examples)\n ? item.examples.map((example) => String(example))\n : [],\n client: this,\n });\n }\n\n /** Play one persona turn. See {@link Persona.respond}. */\n async chat(\n personaId: string,\n messages: PersonaMessage[],\n ): Promise<PersonaReply> {\n const payload = await this.requestJson(\n \"POST\",\n `/api/public/personas/${encodeURIComponent(personaId)}/chat`,\n { messages },\n );\n return {\n content: typeof payload.content === \"string\" ? payload.content : \"\",\n done: Boolean(payload.done),\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 const reason = error instanceof Error ? error.message : String(error);\n throw new PersonaError(`${method} ${path} failed: ${reason}`, {\n cause: error,\n });\n }\n\n const text = await response.text();\n if (!response.ok) {\n const detail = text.slice(0, 500);\n throw new PersonaError(\n `${method} ${path} failed (${response.status}): ${detail}`,\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.personas] ${message}`, ...args);\n }\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction safeJson(value: string): Record<string, unknown> {\n try {\n const parsed = JSON.parse(value);\n return isRecord(parsed) ? parsed : {};\n } catch {\n return {};\n }\n}\n\nexport const personas = {\n fromEnv: PersonasClient.fromEnv,\n};\n\nexport type {\n PersonaMessage,\n PersonaReply,\n PersonasClientConfig,\n PersonasClientFromEnvConfig,\n};\n","/**\n * Load Gateway sessions for replay and test-fixture generation.\n *\n * The premier workflow: pull a real production session from the platform and\n * turn it into a regression test in your repo.\n *\n * ```typescript\n * import { loadSession } from \"@withgateway/sdk/sessions\";\n *\n * const session = await loadSession(\"session-id\"); // env-configured Gateway\n * for (const turn of session.turns()) { // (input, output) per trace\n * const result = await myAgent(turn.input);\n * assert.deepEqual(result, turn.output); // or fuzzier assertions\n * }\n *\n * session.toFixture(\"tests/fixtures/checkout_regression.json\");\n * ```\n *\n * Auth/config mirror the tracing exporter: GATEWAY_HOST, GATEWAY_PUBLIC_KEY,\n * GATEWAY_SECRET_KEY (or pass host/publicKey/secretKey explicitly). Data comes\n * from `GET /api/public/sessions/{id}?includeIO=true` — one call, full\n * untruncated input/output for every trace and observation.\n *\n * Mirrors the Python SDK's `gatewaysdk.sessions` module.\n */\n\nimport { mkdirSync, writeFileSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\n\nexport const ENV_GATEWAY_HOST = \"GATEWAY_HOST\";\nexport const ENV_GATEWAY_PUBLIC_KEY = \"GATEWAY_PUBLIC_KEY\";\nexport const ENV_GATEWAY_SECRET_KEY = \"GATEWAY_SECRET_KEY\";\n\nexport const DEFAULT_TIMEOUT_SECONDS = 30;\n\n/** Raised when a session cannot be loaded from Gateway. */\nexport class SessionLoadError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message);\n this.name = \"SessionLoadError\";\n this.cause = options?.cause;\n }\n}\n\n/** One observation (LLM generation, tool call, span) with full IO. */\nexport type SessionObservation = {\n id: string;\n type: string | null;\n name: string | null;\n level: string | null;\n statusMessage: string | null;\n model: string | null;\n input: unknown;\n output: unknown;\n metadata: unknown;\n parentObservationId: string | null;\n startTime: string | null;\n endTime: string | null;\n};\n\nexport function sessionObservationFromApi(\n raw: Record<string, unknown>,\n): SessionObservation {\n return {\n id: String(raw.id ?? \"\"),\n type: asStringOrNull(raw.type),\n name: asStringOrNull(raw.name),\n level: asStringOrNull(raw.level),\n statusMessage: asStringOrNull(raw.statusMessage),\n model: asStringOrNull(raw.model),\n input: raw.input,\n output: raw.output,\n metadata: raw.metadata ?? null,\n parentObservationId: asStringOrNull(raw.parentObservationId),\n startTime: raw.startTime ? String(raw.startTime) : null,\n endTime: raw.endTime ? String(raw.endTime) : null,\n };\n}\n\ntype SessionTraceFields = {\n id: string;\n name: string | null;\n timestamp: string | null;\n input: unknown;\n output: unknown;\n metadata?: unknown;\n tags?: string[];\n observations?: SessionObservation[];\n};\n\n/** One trace (agent turn) in the session, with full IO + observations. */\nexport class SessionTrace {\n readonly id: string;\n readonly name: string | null;\n readonly timestamp: string | null;\n readonly input: unknown;\n readonly output: unknown;\n readonly metadata: unknown;\n readonly tags: string[];\n readonly observations: SessionObservation[];\n\n constructor(fields: SessionTraceFields) {\n this.id = fields.id;\n this.name = fields.name;\n this.timestamp = fields.timestamp;\n this.input = fields.input;\n this.output = fields.output;\n this.metadata = fields.metadata ?? null;\n this.tags = fields.tags ?? [];\n this.observations = fields.observations ?? [];\n }\n\n get toolCalls(): SessionObservation[] {\n return this.observations.filter(\n (o) => (o.type ?? \"\").toUpperCase() === \"TOOL\",\n );\n }\n\n get generations(): SessionObservation[] {\n return this.observations.filter(\n (o) => (o.type ?? \"\").toUpperCase() === \"GENERATION\",\n );\n }\n\n /**\n * The user message that started this turn.\n *\n * Handles the common recorded shapes: a plain string input, an OpenAI\n * message list (last role=user entry wins — earlier ones are carried\n * history), or an object with a content/input field.\n */\n userMessage(): string | null {\n const value = this.input;\n if (typeof value === \"string\") {\n return value;\n }\n if (Array.isArray(value)) {\n for (let i = value.length - 1; i >= 0; i--) {\n const entry = value[i];\n if (isPlainObject(entry) && entry.role === \"user\") {\n const content = entry.content;\n if (typeof content === \"string\") {\n return content;\n }\n if (Array.isArray(content)) {\n // content-part lists\n const parts = content\n .filter(isPlainObject)\n .map((part) => (typeof part.text === \"string\" ? part.text : \"\"));\n return parts.join(\"\") || null;\n }\n }\n }\n return null;\n }\n if (isPlainObject(value)) {\n for (const key of [\"content\", \"input\", \"text\", \"message\"]) {\n if (typeof value[key] === \"string\") {\n return value[key] as string;\n }\n }\n }\n return null;\n }\n\n static fromApi(raw: Record<string, unknown>): SessionTrace {\n return new SessionTrace({\n id: String(raw.id ?? \"\"),\n name: asStringOrNull(raw.name),\n timestamp: raw.timestamp ? String(raw.timestamp) : null,\n input: raw.input,\n output: raw.output,\n metadata: raw.metadata ?? null,\n tags: Array.isArray(raw.tags) ? raw.tags.map(String) : [],\n observations: (Array.isArray(raw.observations) ? raw.observations : [])\n .filter(isPlainObject)\n .map(sessionObservationFromApi),\n });\n }\n}\n\ntype SessionRecordingFields = {\n sessionId: string;\n projectId: string | null;\n environment: string | null;\n traces?: SessionTrace[];\n};\n\ntype SelectFilter = {\n type?: string;\n name?: string;\n level?: string;\n};\n\n/** A fully-loaded session: every trace, every observation, full IO. */\nexport class SessionRecording {\n readonly sessionId: string;\n readonly projectId: string | null;\n readonly environment: string | null;\n readonly traces: SessionTrace[];\n\n constructor(fields: SessionRecordingFields) {\n this.sessionId = fields.sessionId;\n this.projectId = fields.projectId;\n this.environment = fields.environment;\n this.traces = fields.traces ?? [];\n }\n\n /** Traces in chronological order — one per agent turn. */\n turns(): SessionTrace[] {\n return [...this.traces].sort((a, b) => {\n const left = a.timestamp ?? \"\";\n const right = b.timestamp ?? \"\";\n return left < right ? -1 : left > right ? 1 : 0;\n });\n }\n\n /** The nth chronological turn (negative indices allowed). */\n turn(index: number): SessionTrace {\n const ordered = this.turns();\n const found = ordered.at(index);\n if (!found) {\n throw new RangeError(\n `Turn index ${index} out of range (session has ${ordered.length} turns)`,\n );\n }\n return found;\n }\n\n /**\n * The user message of each turn, in order — feed these back to an agent\n * to re-drive the recorded conversation.\n */\n userMessages(): Array<string | null> {\n return this.turns().map((trace) => trace.userMessage());\n }\n\n /** Output of the last chronological turn (null when empty). */\n finalOutput(): unknown {\n const ordered = this.turns();\n return ordered.length > 0 ? ordered[ordered.length - 1].output : null;\n }\n\n /** Every TOOL observation across the session, chronological. */\n toolCalls(): SessionObservation[] {\n return this.select({ type: \"TOOL\" });\n }\n\n /** Every GENERATION observation across the session, chronological. */\n generations(): SessionObservation[] {\n return this.select({ type: \"GENERATION\" });\n }\n\n /** Filter observations across all turns (chronological order). */\n select(filter: SelectFilter = {}): SessionObservation[] {\n const selected: SessionObservation[] = [];\n for (const trace of this.turns()) {\n for (const observation of trace.observations) {\n if (\n filter.type &&\n (observation.type ?? \"\").toUpperCase() !== filter.type.toUpperCase()\n ) {\n continue;\n }\n if (filter.name && observation.name !== filter.name) {\n continue;\n }\n if (\n filter.level &&\n (observation.level ?? \"\").toUpperCase() !== filter.level.toUpperCase()\n ) {\n continue;\n }\n selected.push(observation);\n }\n }\n return selected;\n }\n\n toJSON(): Record<string, unknown> {\n return {\n sessionId: this.sessionId,\n projectId: this.projectId,\n environment: this.environment,\n traces: this.turns().map((trace) => ({\n id: trace.id,\n name: trace.name,\n timestamp: trace.timestamp,\n input: trace.input,\n output: trace.output,\n metadata: trace.metadata,\n tags: trace.tags,\n observations: trace.observations.map((o) => ({ ...o })),\n })),\n };\n }\n\n /** Dump the full session as a JSON fixture (for regression tests). */\n toFixture(path: string): string {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, JSON.stringify(this.toJSON(), null, 2), \"utf-8\");\n return path;\n }\n\n static fromApi(raw: Record<string, unknown>): SessionRecording {\n return new SessionRecording({\n sessionId: String(raw.id ?? \"\"),\n projectId: asStringOrNull(raw.projectId),\n environment: asStringOrNull(raw.environment),\n traces: (Array.isArray(raw.traces) ? raw.traces : [])\n .filter(isPlainObject)\n .map(SessionTrace.fromApi),\n });\n }\n}\n\nexport type LoadSessionOptions = {\n host?: string;\n publicKey?: string;\n secretKey?: string;\n timeoutSeconds?: number;\n};\n\n/**\n * Load a full session (all traces + observations, untruncated IO).\n *\n * Credentials default to the same environment variables the tracing\n * exporter uses: GATEWAY_HOST, GATEWAY_PUBLIC_KEY, GATEWAY_SECRET_KEY.\n */\nexport async function loadSession(\n sessionId: string,\n options: LoadSessionOptions = {},\n): Promise<SessionRecording> {\n const host = (options.host ?? process.env[ENV_GATEWAY_HOST] ?? \"\").replace(\n /\\/+$/,\n \"\",\n );\n const publicKey =\n options.publicKey ?? process.env[ENV_GATEWAY_PUBLIC_KEY] ?? \"\";\n const secretKey =\n options.secretKey ?? process.env[ENV_GATEWAY_SECRET_KEY] ?? \"\";\n const timeoutSeconds = options.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS;\n if (!host || !publicKey || !secretKey) {\n throw new SessionLoadError(\n \"Gateway is not configured — set GATEWAY_HOST, GATEWAY_PUBLIC_KEY \" +\n \"and GATEWAY_SECRET_KEY (or pass host/publicKey/secretKey).\",\n );\n }\n\n const url = `${host}/api/public/sessions/${encodeURIComponent(sessionId)}?includeIO=true`;\n let response: Response;\n try {\n response = await fetch(url, {\n method: \"GET\",\n headers: { Authorization: basicAuthHeader(publicKey, secretKey) },\n signal: AbortSignal.timeout(timeoutSeconds * 1000),\n });\n } catch (error) {\n throw new SessionLoadError(\n `Failed to load session ${sessionId}: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n if (response.status === 404) {\n throw new SessionLoadError(`Session not found: ${sessionId}`);\n }\n const text = await response.text();\n if (!response.ok) {\n throw new SessionLoadError(\n `Failed to load session ${sessionId}: HTTP ${response.status} — ${text.slice(0, 300)}`,\n );\n }\n let payload: unknown;\n try {\n payload = JSON.parse(text);\n } catch (error) {\n throw new SessionLoadError(\n `Failed to load session ${sessionId}: response is not valid JSON`,\n { cause: error },\n );\n }\n return SessionRecording.fromApi(\n isPlainObject(payload) ? payload : {},\n );\n}\n\nexport function basicAuthHeader(publicKey: string, secretKey: string): string {\n return `Basic ${Buffer.from(`${publicKey}:${secretKey}`).toString(\"base64\")}`;\n}\n\nfunction asStringOrNull(value: unknown): string | null {\n return typeof value === \"string\" ? value : null;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nexport const sessions = {\n load: loadSession,\n};\n","/**\n * Regression suites replayed from platform task sets.\n *\n * A TASK SET on the platform (filed by the dream agent or a human) is a\n * runnable regression suite: each task carries its prompt, expected behavior,\n * and provenance to the RECORDED SESSION that motivated it. This module turns\n * that into tests:\n *\n * ```typescript\n * import { suite } from \"@withgateway/sdk/replay\";\n *\n * const regressions = await suite(\"groceat-regressions\");\n * for (const testCase of regressions) {\n * const stubs = await testCase.stubs(); // the recorded world\n * const out = await myAgent(testCase.prompt, stubs.asRegistry());\n * const result = testCase.check(out, { calledTools: stubs.calledNames() });\n * assert.ok(result.passed, result.explain());\n * }\n * ```\n *\n * Three layers pin three different things:\n * - tool stubs pin THE WORLD (recorded tool outputs → deterministic replay)\n * - invariants pin THE CONTRACT (must/must-not tool calls)\n * - your own assertions / platform judges pin THE SEMANTICS\n *\n * Case triage is three-way: PASS, FAIL (real regression — the world simulated\n * fine and the contract broke), and DRIFT (the recorded world no longer\n * matches the system — stub misses, renamed tools; the TEST is stale, not the\n * agent).\n *\n * Mirrors the Python SDK's `gatewaysdk.replay` package.\n */\n\nimport {\n DEFAULT_TIMEOUT_SECONDS,\n ENV_GATEWAY_HOST,\n ENV_GATEWAY_PUBLIC_KEY,\n ENV_GATEWAY_SECRET_KEY,\n SessionLoadError,\n type SessionObservation,\n SessionRecording,\n basicAuthHeader,\n loadSession,\n} from \"../sessions/index\";\nimport { join } from \"node:path\";\n\n/** Base error for replay loading/config problems. */\nexport class ReplayError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message);\n this.name = \"ReplayError\";\n this.cause = options?.cause;\n }\n}\n\n/** Strict-mode stub lookup failed — the recorded world has no answer. */\nexport class StubMissError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"StubMissError\";\n }\n}\n\n/** The recorded session no longer matches the system (re-baseline the case). */\nexport class DriftError extends ReplayError {\n constructor(message: string) {\n super(message);\n this.name = \"DriftError\";\n }\n}\n\n// ---------------------------------------------------------------------------\n// World simulation: recorded tool stubs\n// ---------------------------------------------------------------------------\n\n// Single-key envelopes that auto-instrumentors wrap tool inputs in (e.g. the\n// OpenInference openai-agents instrumentor records {\"args_json\": \"<json>\"},\n// agent-as-tool records {\"input\": \"...\"}). Recorded inputs must compare equal\n// to the args a live agent passes, so both sides are unwrapped before match.\nconst WRAPPER_KEYS = [\"args_json\", \"arguments\", \"kwargs\", \"args\", \"input\"];\n\nfunction canonicalize(value: unknown): unknown {\n if (typeof value === \"string\") {\n const stripped = value.trim();\n if (stripped.startsWith(\"{\") || stripped.startsWith(\"[\")) {\n try {\n return canonicalize(JSON.parse(stripped));\n } catch {\n return value;\n }\n }\n return value;\n }\n if (Array.isArray(value)) {\n return value.map(canonicalize);\n }\n if (isPlainObject(value)) {\n const entries = Object.entries(value);\n if (entries.length === 1 && WRAPPER_KEYS.includes(entries[0][0])) {\n return canonicalize(entries[0][1]);\n }\n return Object.fromEntries(\n entries.map(([key, inner]) => [key, canonicalize(inner)]),\n );\n }\n return value;\n}\n\nfunction sortKeysDeep(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(sortKeysDeep);\n }\n if (isPlainObject(value)) {\n const sorted: Record<string, unknown> = {};\n for (const key of Object.keys(value).sort()) {\n sorted[key] = sortKeysDeep(value[key]);\n }\n return sorted;\n }\n return value;\n}\n\nfunction normalizeInput(value: unknown): string {\n try {\n return (\n JSON.stringify(sortKeysDeep(canonicalize(value ?? null))) ?? \"null\"\n );\n } catch {\n return String(value);\n }\n}\n\nexport type RecordedToolCall = {\n name: string;\n input: unknown;\n output: unknown;\n observationId: string;\n};\n\nexport type MissPolicy = \"error\" | \"reuse\" | \"passthrough\";\nexport type StubMatch =\n | \"local\"\n | \"exact\"\n | \"exact-repeat\"\n | \"ordinal\"\n | \"reuse\"\n | \"miss\";\nexport type StubCallLogEntry = {\n tool: string;\n match: StubMatch;\n input: unknown;\n};\nexport type StubFallback = (toolName: string, toolInput: unknown) => unknown;\nexport type LocalTool = (toolInput: unknown) => unknown;\nexport type ToolStub = (toolInput?: unknown) => unknown;\n\n/**\n * Tool registry that synthesizes stubs for unknown names (see\n * `ToolStubRegistry.asRegistry`). Indexing an unknown name returns a callable\n * that routes through `lookup()`, so the call is LOGGED and follows the miss\n * policy instead of dying on an undefined-is-not-a-function error.\n */\nexport type StubRegistryMapping = Record<string, ToolStub>;\n\ntype StubRegistryOptions = {\n missPolicy?: MissPolicy;\n fallback?: StubFallback;\n local?: Record<string, LocalTool>;\n};\n\n/**\n * Replays recorded tool outputs from a case's recorded session.\n *\n * Match strategies (tried in order):\n * local — the tool was declared `local`: run its live impl (new\n * or deterministic tools that never need recordings)\n * exact — normalized-JSON equality of the tool input\n * exact-repeat — same (name, input) already replayed: return that output\n * again (idempotent world reads never exhaust)\n * ordinal — nth un-consumed recording for that tool name (robust to\n * arg phrasing drift across models/prompts)\n *\n * Miss policy:\n * \"error\" — throw StubMissError (strict replay; recorded as drift).\n * NOTE: most agent frameworks catch tool errors and feed\n * them to the model as error output, so this does NOT\n * hard-stop such runs — the drift still lands in the\n * report either way.\n * \"reuse\" — exhausted a tool's recordings? replay the LAST recorded\n * output for that name again (drift recorded). Keeps\n * research-heavy agents running when they make more calls\n * than the recording holds. Never-recorded names still\n * throw (or hit `fallback` when provided).\n * \"passthrough\" — call the `fallback` callable (live tool) and record the\n * miss as drift for the report\n */\nexport class ToolStubRegistry {\n readonly callLog: StubCallLogEntry[] = [];\n readonly driftEvents: string[] = [];\n\n private readonly recorded: RecordedToolCall[];\n private readonly consumed = new Set<number>();\n private readonly consumptionOrder: number[] = [];\n private missPolicy: MissPolicy;\n private fallback: StubFallback | null;\n private readonly local: Record<string, LocalTool>;\n\n constructor(calls: RecordedToolCall[], options: StubRegistryOptions = {}) {\n const missPolicy = options.missPolicy ?? \"error\";\n if (![\"error\", \"reuse\", \"passthrough\"].includes(missPolicy)) {\n throw new ReplayError(`Unknown missPolicy: ${missPolicy}`);\n }\n this.recorded = calls;\n this.missPolicy = missPolicy;\n this.fallback = options.fallback ?? null;\n this.local = { ...(options.local ?? {}) };\n }\n\n static fromSession(\n session: SessionRecording,\n options: StubRegistryOptions = {},\n ): ToolStubRegistry {\n const calls = session.toolCalls().map(\n (observation: SessionObservation): RecordedToolCall => ({\n name: observation.name ?? \"\",\n input: observation.input,\n output: observation.output,\n observationId: observation.id,\n }),\n );\n return new ToolStubRegistry(calls, options);\n }\n\n /** Resolve a tool call against the recorded world. */\n lookup(toolName: string, toolInput: unknown = null): unknown {\n // declared-local tool: always run live, logged but never drift\n if (toolName in this.local) {\n this.callLog.push({ tool: toolName, match: \"local\", input: toolInput });\n return this.local[toolName](toolInput);\n }\n const normalized = normalizeInput(toolInput);\n // exact match first\n for (let index = 0; index < this.recorded.length; index++) {\n const record = this.recorded[index];\n if (\n !this.consumed.has(index) &&\n record.name === toolName &&\n normalizeInput(record.input) === normalized\n ) {\n this.consumed.add(index);\n this.consumptionOrder.push(index);\n this.callLog.push({ tool: toolName, match: \"exact\", input: toolInput });\n return record.output;\n }\n }\n // exact-repeat: the same (name, input) was already replayed — treat the\n // recorded pair as a stable world fact and serve it again rather than\n // exhausting into ordinal/miss on idempotent re-reads\n for (let index = this.recorded.length - 1; index >= 0; index--) {\n const record = this.recorded[index];\n if (record.name === toolName && normalizeInput(record.input) === normalized) {\n this.callLog.push({\n tool: toolName,\n match: \"exact-repeat\",\n input: toolInput,\n });\n return record.output;\n }\n }\n // ordinal fallback: next un-consumed recording for this tool name\n for (let index = 0; index < this.recorded.length; index++) {\n const record = this.recorded[index];\n if (!this.consumed.has(index) && record.name === toolName) {\n this.consumed.add(index);\n this.consumptionOrder.push(index);\n this.callLog.push({\n tool: toolName,\n match: \"ordinal\",\n input: toolInput,\n });\n return record.output;\n }\n }\n // reuse: recordings for this name exist but are exhausted — replay the\n // last one again so over-calling agents (extra searches, retries) finish\n // the run; the drift below still tells the truth in triage\n if (this.missPolicy === \"reuse\") {\n for (let index = this.recorded.length - 1; index >= 0; index--) {\n const record = this.recorded[index];\n if (record.name === toolName) {\n this.driftEvents.push(\n `recordings for tool '${toolName}' exhausted — ` +\n \"replayed the last one again (reuse policy)\",\n );\n this.callLog.push({\n tool: toolName,\n match: \"reuse\",\n input: toolInput,\n });\n return record.output;\n }\n }\n }\n // miss\n const recordedNames = [...new Set(this.recorded.map((r) => r.name))].sort();\n const drift = `no recording for tool '${toolName}' (recorded tools: ${JSON.stringify(recordedNames)})`;\n this.driftEvents.push(drift);\n this.callLog.push({ tool: toolName, match: \"miss\", input: toolInput });\n if (\n this.fallback !== null &&\n (this.missPolicy === \"passthrough\" || this.missPolicy === \"reuse\")\n ) {\n return this.fallback(toolName, toolInput);\n }\n throw new StubMissError(drift);\n }\n\n /**\n * Mapping of toolName → callable, drop-in for most agent tool layers.\n *\n * `local` merges in tools that should ALWAYS run live (new tools the\n * recording predates, or deterministic/pure helpers) — they're logged for\n * the contract check but never count as drift.\n *\n * UNKNOWN tool names also resolve (to a stub that routes through\n * `lookup()`), so a call to an un-recorded tool is LOGGED and follows the\n * miss policy instead of dying on an undefined lookup — that log is what\n * lets `check()` classify a forbidden-but-unrecorded call as FAIL.\n */\n asRegistry(\n options: {\n fallback?: StubFallback;\n local?: Record<string, LocalTool>;\n } = {},\n ): StubRegistryMapping {\n if (options.fallback) {\n this.fallback = options.fallback;\n this.missPolicy = \"passthrough\";\n }\n if (options.local) {\n Object.assign(this.local, options.local);\n }\n\n const make =\n (name: string): ToolStub =>\n (toolInput?: unknown) =>\n this.lookup(name, toolInput === undefined ? {} : toolInput);\n\n const target: Record<string, ToolStub> = {};\n const names = new Set([\n ...this.recorded.map((record) => record.name),\n ...Object.keys(this.local),\n ]);\n for (const name of names) {\n if (name) {\n target[name] = make(name);\n }\n }\n return new Proxy(target, {\n get(current, prop, receiver) {\n if (typeof prop !== \"string\" || prop in current) {\n return Reflect.get(current, prop, receiver);\n }\n return make(prop);\n },\n });\n }\n\n calledNames(): string[] {\n return this.callLog.map((entry) => entry.tool);\n }\n\n /**\n * 1:1 comparison of this replay against the recorded trace.\n *\n * The recording is the expectation: every recorded tool call should be\n * replayed exactly once, in order, with nothing extra. Use for strict\n * did-it-do-everything-the-original-did checks (`mode: \"exact\"`).\n *\n * `includeLocal`: count local-tool calls as extras (default false — local\n * tools are declared live on purpose; their recorded calls are likewise\n * excluded from \"missing\", since local bypasses recordings).\n */\n compare(options: { includeLocal?: boolean } = {}): TraceDiff {\n const includeLocal = options.includeLocal ?? false;\n const missing = this.recorded\n .map((record, index) => ({ record, index }))\n .filter(\n ({ record, index }) =>\n !this.consumed.has(index) &&\n (includeLocal || !(record.name in this.local)),\n )\n .map(({ record }) => `${record.name}(${normalizeInput(record.input)})`);\n const extra: string[] = [];\n for (const entry of this.callLog) {\n if (\n [\"miss\", \"reuse\", \"exact-repeat\"].includes(entry.match) ||\n (includeLocal && entry.match === \"local\")\n ) {\n extra.push(\n `${entry.tool}(${normalizeInput(entry.input)}) [${entry.match}]`,\n );\n }\n }\n const outOfOrder: string[] = [];\n let last = -1;\n for (const index of this.consumptionOrder) {\n if (index < last) {\n const record = this.recorded[index];\n outOfOrder.push(`${record.name}(${normalizeInput(record.input)})`);\n } else {\n last = index;\n }\n }\n const matched = this.consumptionOrder.map(\n (index) => this.recorded[index].name,\n );\n return new TraceDiff({ matched, missing, extra, outOfOrder });\n }\n\n get drifted(): boolean {\n return this.driftEvents.length > 0;\n }\n}\n\n/** Replayed-vs-recorded trace comparison (see `ToolStubRegistry.compare`). */\nexport class TraceDiff {\n readonly matched: string[];\n readonly missing: string[];\n readonly extra: string[];\n readonly outOfOrder: string[];\n\n constructor(\n fields: {\n matched?: string[];\n missing?: string[];\n extra?: string[];\n outOfOrder?: string[];\n } = {},\n ) {\n this.matched = fields.matched ?? [];\n this.missing = fields.missing ?? [];\n this.extra = fields.extra ?? [];\n this.outOfOrder = fields.outOfOrder ?? [];\n }\n\n get identical(): boolean {\n return (\n this.missing.length === 0 &&\n this.extra.length === 0 &&\n this.outOfOrder.length === 0\n );\n }\n\n explain(): string {\n if (this.identical) {\n return `1:1 replay — all ${this.matched.length} recorded tool calls reproduced in order`;\n }\n const lines = [\n `trace diverges from recording (${this.matched.length} matched):`,\n ];\n lines.push(...this.missing.map((item) => ` not reproduced: ${item}`));\n lines.push(...this.extra.map((item) => ` extra call: ${item}`));\n lines.push(...this.outOfOrder.map((item) => ` out of order: ${item}`));\n return lines.join(\"\\n\");\n }\n}\n\n// ---------------------------------------------------------------------------\n// Tasks, cases, checks\n// ---------------------------------------------------------------------------\n\ntype ReplayTaskFields = {\n id: string;\n name?: string | null;\n prompt?: unknown;\n expectedOutput?: unknown;\n metadata?: Record<string, unknown>;\n};\n\n/** One task-set item as served by GET /task-sets/{id}/tasks. */\nexport class ReplayTask {\n readonly id: string;\n readonly name: string | null;\n readonly prompt: unknown;\n readonly expectedOutput: unknown;\n readonly metadata: Record<string, unknown>;\n\n constructor(fields: ReplayTaskFields) {\n this.id = fields.id;\n this.name = fields.name ?? null;\n this.prompt = fields.prompt;\n this.expectedOutput = fields.expectedOutput;\n this.metadata = fields.metadata ?? {};\n }\n\n get sourceSessionId(): string | null {\n const value = this.metadata.sourceSessionId;\n return value ? String(value) : null;\n }\n\n get sourceTraceId(): string | null {\n const value = this.metadata.sourceTraceId;\n return value ? String(value) : null;\n }\n\n static fromApi(raw: Record<string, unknown>): ReplayTask {\n const metadata = raw.metadata;\n return new ReplayTask({\n id: String(raw.id ?? \"\"),\n name: typeof raw.name === \"string\" ? raw.name : null,\n prompt: raw.prompt,\n expectedOutput: raw.expectedOutput,\n metadata: isPlainObject(metadata) ? { ...metadata } : {},\n });\n }\n}\n\nexport type ReplayStatus = \"PASS\" | \"FAIL\" | \"DRIFT\";\n\n/** Triage result: PASS | FAIL | DRIFT (+ human-readable reasons). */\nexport class ReplayCheck {\n readonly status: ReplayStatus;\n readonly failures: string[];\n readonly drift: string[];\n readonly traceDiff: TraceDiff | null;\n\n constructor(\n status: ReplayStatus,\n fields: {\n failures?: string[];\n drift?: string[];\n traceDiff?: TraceDiff | null;\n } = {},\n ) {\n this.status = status;\n this.failures = fields.failures ?? [];\n this.drift = fields.drift ?? [];\n this.traceDiff = fields.traceDiff ?? null;\n }\n\n get passed(): boolean {\n return this.status === \"PASS\";\n }\n\n get drifted(): boolean {\n return this.status === \"DRIFT\";\n }\n\n explain(): string {\n if (this.status === \"PASS\") {\n return \"PASS\";\n }\n const lines: string[] = [this.status];\n lines.push(...this.failures.map((failure) => ` FAIL: ${failure}`));\n for (const event of this.drift) {\n if (event.includes(\"reuse policy\")) {\n // exhausted-then-reused recordings = the agent explored more than\n // the recording holds, not necessarily a stale test\n lines.push(\n ` DRIFT: ${event} — recording under-covers this run; ` +\n \"re-record for exact coverage or keep the reuse policy.\",\n );\n } else {\n lines.push(\n ` DRIFT: ${event} — the test is stale, not the agent; ` +\n \"re-record the session (or declare the tool local).\",\n );\n }\n }\n return lines.join(\"\\n\");\n }\n}\n\nexport type SessionLoader = (\n sessionId: string,\n) => SessionRecording | Promise<SessionRecording>;\n\nexport type ReplayMode = \"contract\" | \"exact\";\n\ntype CheckOptions = {\n calledTools?: string[];\n stubs?: ToolStubRegistry;\n mode?: ReplayMode;\n};\n\n/** One regression case: a task bound to the session it was filed from. */\nexport class ReplayCase {\n readonly task: ReplayTask;\n private readonly loader: SessionLoader;\n private _recording: SessionRecording | null = null;\n private _stubs: ToolStubRegistry | null = null;\n\n constructor(task: ReplayTask, options: { loader: SessionLoader }) {\n this.task = task;\n this.loader = options.loader;\n }\n\n // -- identity ------------------------------------------------------------\n get id(): string {\n return this.task.id;\n }\n\n get name(): string {\n return this.task.name ?? this.task.id;\n }\n\n get prompt(): unknown {\n return this.task.prompt;\n }\n\n get expected(): unknown {\n return this.task.expectedOutput;\n }\n\n // -- recorded source session ----------------------------------------------\n /** The full recorded session this case was filed from. */\n async recording(): Promise<SessionRecording> {\n if (this._recording === null) {\n const source = this.task.sourceSessionId;\n if (!source) {\n throw new DriftError(\n `Task ${this.name} has no sourceSessionId provenance — ` +\n \"file it from a session (add_session_to_task_set) or set \" +\n \"metadata.sourceSessionId.\",\n );\n }\n this._recording = await this.loader(source);\n }\n return this._recording;\n }\n\n async stubs(options: StubRegistryOptions = {}): Promise<ToolStubRegistry> {\n this._stubs = ToolStubRegistry.fromSession(await this.recording(), options);\n return this._stubs;\n }\n\n /**\n * The recorded conversation's user messages, one per turn — feed them to\n * your agent in order to re-drive the full session (each turn was one\n * trace in the recording).\n */\n async conversation(): Promise<string[]> {\n const messages = (await this.recording()).userMessages();\n const found = messages.filter(\n (message): message is string => Boolean(message),\n );\n return found.length > 0 ? found : [String(this.prompt)];\n }\n\n // -- grading ---------------------------------------------------------------\n /**\n * Contract invariants + drift triage.\n *\n * Invariants come from task metadata (the workbench-style contract):\n * metadata.expectTools — every listed tool MUST have been called\n * metadata.mustNotCall — none of these may have been called\n * Semantic grading stays with the caller (assert on `output` /\n * `case.expected`, or run a platform judge on the replay trace).\n *\n * `mode` (or task `metadata.replayMode`):\n * \"contract\" (default) — grade only the invariants above\n * \"exact\" — true 1:1 replay: the agent must reproduce EVERY\n * recorded tool call, in order, with nothing extra\n * (see TraceDiff); any divergence is a FAIL. The\n * full diff lands in the failure reasons and\n * `traceDiff`.\n */\n check(output: unknown = undefined, options: CheckOptions = {}): ReplayCheck {\n const registry = options.stubs ?? this._stubs;\n const drift = registry ? [...registry.driftEvents] : [];\n const called =\n options.calledTools ?? (registry ? registry.calledNames() : []);\n\n // VIOLATIONS are positive evidence the contract broke (a forbidden call\n // happened, produced output contradicts an exact expectation) — they\n // FAIL even on a drifted world. OMISSIONS (an expected tool never\n // called) only FAIL on a CLEAN world: when the run drifted (stub miss\n // aborted it, tools were renamed), the drift explains the omission and\n // the right verdict is DRIFT → re-record, not \"agent regressed\".\n const violations: string[] = [];\n const omissions: string[] = [];\n const expectTools = this.task.metadata.expectTools;\n if (Array.isArray(expectTools)) {\n for (const toolName of expectTools) {\n if (!called.includes(toolName)) {\n omissions.push(`expected tool not called: ${toolName}`);\n }\n }\n }\n const mustNot = this.task.metadata.mustNotCall;\n if (Array.isArray(mustNot)) {\n for (const toolName of mustNot) {\n if (called.includes(toolName)) {\n violations.push(`must_not_call violated: ${toolName}`);\n }\n }\n }\n if (\n typeof this.expected === \"string\" &&\n this.expected.trim() &&\n typeof output === \"string\" &&\n this.task.metadata.outputExact === true &&\n output.trim() !== this.expected.trim()\n ) {\n violations.push(\"output does not exactly match expectedOutput\");\n }\n\n const replayMode = (options.mode ??\n this.task.metadata.replayMode ??\n \"contract\") as ReplayMode;\n let traceDiff: TraceDiff | null = null;\n if (registry) {\n traceDiff = registry.compare();\n }\n if (replayMode === \"exact\" && traceDiff && !traceDiff.identical) {\n violations.push(\n ...[\n ...traceDiff.missing.map((item) => `not reproduced: ${item}`),\n ...traceDiff.extra.map((item) => `extra call: ${item}`),\n ...traceDiff.outOfOrder.map((item) => `out of order: ${item}`),\n ].map((line) => `1:1 replay diverged — ${line}`),\n );\n }\n\n if (violations.length > 0) {\n return new ReplayCheck(\"FAIL\", {\n failures: [...violations, ...(drift.length > 0 ? [] : omissions)],\n drift,\n traceDiff,\n });\n }\n if (drift.length > 0) {\n return new ReplayCheck(\"DRIFT\", { drift, traceDiff });\n }\n if (omissions.length > 0) {\n return new ReplayCheck(\"FAIL\", { failures: omissions, traceDiff });\n }\n return new ReplayCheck(\"PASS\", { traceDiff });\n }\n}\n\n// ---------------------------------------------------------------------------\n// Suite loading (platform task sets)\n// ---------------------------------------------------------------------------\n\nexport type ReplayCredentials = {\n host: string;\n publicKey: string;\n secretKey: string;\n timeoutSeconds?: number;\n};\n\nexport type ReplaySuiteLoadOptions = {\n host?: string;\n publicKey?: string;\n secretKey?: string;\n timeoutSeconds?: number;\n};\n\ntype ReplaySuiteFields = {\n taskSetId: string;\n taskSetName: string;\n cases: ReplayCase[];\n /** Platform credentials for recording replay runs back to the task set. */\n credentials?: ReplayCredentials | null;\n};\n\n/** All cases of one task set, iterable and indexable by name or id. */\nexport class ReplaySuite implements Iterable<ReplayCase> {\n readonly taskSetId: string;\n readonly taskSetName: string;\n readonly cases: ReplayCase[];\n /** Credentials for recording replay runs back to the platform. */\n readonly credentials: ReplayCredentials | null;\n\n constructor(fields: ReplaySuiteFields) {\n this.taskSetId = fields.taskSetId;\n this.taskSetName = fields.taskSetName;\n this.cases = fields.cases;\n this.credentials = fields.credentials ?? null;\n }\n\n [Symbol.iterator](): Iterator<ReplayCase> {\n return this.cases[Symbol.iterator]();\n }\n\n get length(): number {\n return this.cases.length;\n }\n\n /** Look up a case by id or name (throws when absent). */\n get(key: string): ReplayCase {\n for (const testCase of this.cases) {\n if (testCase.id === key || testCase.name === key) {\n return testCase;\n }\n }\n throw new ReplayError(\n `No case '${key}' in task set ${this.taskSetName} ` +\n `(cases: ${JSON.stringify(this.cases.map((c) => c.name))})`,\n );\n }\n\n static async fromTaskSet(\n nameOrId: string,\n options: ReplaySuiteLoadOptions = {},\n ): Promise<ReplaySuite> {\n const host = (options.host ?? process.env[ENV_GATEWAY_HOST] ?? \"\").replace(\n /\\/+$/,\n \"\",\n );\n const publicKey =\n options.publicKey ?? process.env[ENV_GATEWAY_PUBLIC_KEY] ?? \"\";\n const secretKey =\n options.secretKey ?? process.env[ENV_GATEWAY_SECRET_KEY] ?? \"\";\n const timeoutSeconds = options.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS;\n if (!host || !publicKey || !secretKey) {\n throw new SessionLoadError(\n \"Gateway is not configured — set GATEWAY_HOST, \" +\n \"GATEWAY_PUBLIC_KEY and GATEWAY_SECRET_KEY.\",\n );\n }\n const headers = { Authorization: basicAuthHeader(publicKey, secretKey) };\n\n const fetchTasks = async (\n datasetId: string,\n ): Promise<Array<Record<string, unknown>> | null> => {\n const tasks: Array<Record<string, unknown>> = [];\n let page = 0;\n for (;;) {\n const response = await fetch(\n `${host}/api/public/task-sets/${encodeURIComponent(datasetId)}/tasks?page=${page}&limit=200`,\n { headers, signal: AbortSignal.timeout(timeoutSeconds * 1000) },\n );\n if (response.status === 404) {\n return null;\n }\n const text = await response.text();\n if (!response.ok) {\n throw new ReplayError(\n `Failed to list tasks for ${datasetId}: ` +\n `HTTP ${response.status} — ${text.slice(0, 300)}`,\n );\n }\n const payload = parseJsonObject(text);\n const pageTasks = Array.isArray(payload.tasks) ? payload.tasks : [];\n tasks.push(...pageTasks.filter(isPlainObject));\n if (tasks.length >= Number(payload.totalTasks ?? 0)) {\n return tasks;\n }\n page += 1;\n }\n };\n\n // Try as an id first, then resolve as a name.\n let taskSetId = nameOrId;\n let taskSetName = nameOrId;\n let rawTasks = await fetchTasks(nameOrId);\n if (rawTasks === null) {\n const response = await fetch(\n `${host}/api/public/task-sets?name=${encodeURIComponent(nameOrId)}`,\n { headers, signal: AbortSignal.timeout(timeoutSeconds * 1000) },\n );\n const text = await response.text();\n if (!response.ok) {\n throw new ReplayError(\n `Failed to resolve task set '${nameOrId}': ` +\n `HTTP ${response.status} — ${text.slice(0, 300)}`,\n );\n }\n const payload = parseJsonObject(text);\n const matches = Array.isArray(payload.taskSets)\n ? payload.taskSets.filter(isPlainObject)\n : [];\n if (matches.length === 0) {\n throw new ReplayError(`Task set not found: ${nameOrId}`);\n }\n taskSetId = String(matches[0].datasetId);\n taskSetName = String(matches[0].name);\n rawTasks = (await fetchTasks(taskSetId)) ?? [];\n }\n\n const loader: SessionLoader = (sessionId) =>\n loadSession(sessionId, { host, publicKey, secretKey, timeoutSeconds });\n const cases = rawTasks.map(\n (raw) => new ReplayCase(ReplayTask.fromApi(raw), { loader }),\n );\n return new ReplaySuite({\n taskSetId,\n taskSetName,\n cases,\n credentials: { host, publicKey, secretKey, timeoutSeconds },\n });\n }\n\n /** Run the whole suite against `agent` — see `runSuite()`. */\n run(agent: ReplayAgent, options: RunSuiteOptions = {}): Promise<ReplayReport> {\n return runSuite(this, agent, options);\n }\n\n /** Pin every case's recorded session into the repo as JSON fixtures. */\n async snapshot(directory: string): Promise<string[]> {\n const written: string[] = [];\n for (const testCase of this.cases) {\n if (!testCase.task.sourceSessionId) {\n continue;\n }\n const recording = await testCase.recording();\n written.push(\n recording.toFixture(join(directory, `${testCase.name}.recording.json`)),\n );\n }\n return written;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Runner\n// ---------------------------------------------------------------------------\n\n/**\n * The agent under test. Always invoked as `agent(prompt, tools, replayCase)`\n * — declare only the parameters you need (this replaces the Python SDK's\n * signature sniffing with idiomatic JavaScript):\n *\n * `(prompt) => ...` — prompt-only agents\n * `(prompt, tools) => ...` — the common shape\n * `(prompt, tools, replayCase) => ...` — full case access\n * (rebuild stubs via `replayCase.stubs()`)\n */\nexport type ReplayAgent = (\n prompt: unknown,\n tools: StubRegistryMapping,\n replayCase: ReplayCase,\n) => unknown | Promise<unknown>;\n\nexport class ReplayReport {\n readonly results: Record<string, ReplayCheck>;\n readonly runName: string | null;\n readonly recordingErrors: string[];\n\n constructor(\n results: Record<string, ReplayCheck>,\n fields: { runName?: string | null; recordingErrors?: string[] } = {},\n ) {\n this.results = results;\n this.runName = fields.runName ?? null;\n this.recordingErrors = fields.recordingErrors ?? [];\n }\n\n get passed(): number {\n return this.count(\"PASS\");\n }\n\n get failed(): number {\n return this.count(\"FAIL\");\n }\n\n get drifted(): number {\n return this.count(\"DRIFT\");\n }\n\n /** True when nothing FAILED (drift is stale-test signal, not failure). */\n get ok(): boolean {\n return this.failed === 0;\n }\n\n explain(): string {\n const lines = [\n `${this.passed} PASS · ${this.failed} FAIL · ${this.drifted} DRIFT` +\n (this.runName ? ` · run '${this.runName}'` : \"\"),\n ];\n for (const [name, check] of Object.entries(this.results)) {\n if (check.status !== \"PASS\") {\n lines.push(`${name}: ${check.explain()}`);\n }\n }\n for (const error of this.recordingErrors) {\n lines.push(`recording: ${error}`);\n }\n return lines.join(\"\\n\");\n }\n\n private count(status: ReplayStatus): number {\n return Object.values(this.results).filter(\n (check) => check.status === status,\n ).length;\n }\n}\n\n/**\n * Replay traffic records under this environment — the platform hides it from\n * the sessions/traces tables by default (users opt back in via the\n * environment filter), so regression runs never pollute real usage views.\n */\nexport const REPLAY_ENVIRONMENT = \"gateway-replay\";\n\n/**\n * File one dataset-run item so the replay run shows on the task set.\n *\n * Retries on 404: a replay trace reaches ClickHouse asynchronously after\n * flush, and the endpoint rejects items whose trace does not exist yet.\n * Returns an error string on final failure (recording never throws).\n */\nasync function recordRunItem(\n suiteToRecord: ReplaySuite,\n testCase: ReplayCase,\n runName: string,\n traceId: string | null,\n triage: ReplayCheck,\n options: { retries?: number; retryDelaySeconds?: number } = {},\n): Promise<string | null> {\n const retries = options.retries ?? 10;\n const retryDelaySeconds = options.retryDelaySeconds ?? 3;\n const credentials = suiteToRecord.credentials;\n if (!credentials) {\n return \"suite has no platform credentials\";\n }\n const payload = {\n runName,\n runDescription: `gatewaysdk.replay run over '${suiteToRecord.taskSetName}'`,\n datasetItemId: testCase.id,\n traceId: traceId ?? randomHex(),\n metadata: {\n replay: true,\n status: triage.status,\n failures: triage.failures,\n drift: triage.drift,\n sourceSessionId: testCase.task.sourceSessionId,\n },\n };\n let lastError = \"unknown\";\n for (let attempt = 0; attempt < retries; attempt++) {\n try {\n const response = await fetch(\n `${credentials.host}/api/public/dataset-run-items`,\n {\n method: \"POST\",\n headers: {\n Authorization: basicAuthHeader(\n credentials.publicKey,\n credentials.secretKey,\n ),\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(payload),\n signal: AbortSignal.timeout(DEFAULT_TIMEOUT_SECONDS * 1000),\n },\n );\n if (response.status === 200) {\n return null;\n }\n const text = await response.text();\n lastError = `HTTP ${response.status}: ${text.slice(0, 200)}`;\n // 404 = trace not ingested yet — wait and retry; anything else is final.\n if (response.status !== 404) {\n return lastError;\n }\n } catch (error) {\n lastError = error instanceof Error ? error.message : String(error);\n }\n if (attempt < retries - 1) {\n await sleep(retryDelaySeconds * 1000);\n }\n }\n return lastError;\n}\n\nexport type RunSuiteOptions = {\n missPolicy?: MissPolicy;\n record?: boolean;\n runName?: string;\n};\n\n/**\n * Run every case and triage. The agent is invoked as\n * `agent(prompt, tools, replayCase)` — declare only what you need.\n *\n * Recording (`record` undefined → auto when the suite was loaded from the\n * platform): each case is filed as a dataset-run item on the task set, so\n * the replay run shows up in the task set's runs with per-case status.\n *\n * NOTE: unlike the Python SDK, cases are not auto-wrapped in a traced span —\n * the TypeScript tracing module has no per-trace context primitive yet. Run\n * items are filed with a synthetic trace id, exactly like a Python run\n * without tracing configured.\n */\nexport async function runSuite(\n suiteToRun: ReplaySuite,\n agent: ReplayAgent,\n options: RunSuiteOptions = {},\n): Promise<ReplayReport> {\n const missPolicy = options.missPolicy ?? \"error\";\n const record = options.record ?? Boolean(suiteToRun.credentials);\n const runName = options.runName ?? `replay-${randomHex().slice(0, 8)}`;\n\n const results: Record<string, ReplayCheck> = {};\n const pendingRecords: Array<[ReplayCase, string | null, ReplayCheck]> = [];\n for (const testCase of suiteToRun) {\n try {\n const stubs = await testCase.stubs({ missPolicy });\n const output = await agent(\n testCase.prompt,\n stubs.asRegistry(),\n testCase,\n );\n // Triage with the case's LATEST registry — a case-driven agent may\n // have rebuilt stubs via replayCase.stubs() inside its own body.\n results[testCase.name] = testCase.check(output);\n } catch (error) {\n if (error instanceof StubMissError) {\n // The world was missing an answer — but the CONTRACT may also have\n // been violated by that very call (e.g. a forbidden tool that was\n // never recorded because the original agent never called it). Run\n // the check: FAIL dominates drift.\n let triage = testCase.check();\n if (triage.status !== \"FAIL\") {\n triage = new ReplayCheck(\"DRIFT\", {\n drift: triage.drift.length > 0 ? triage.drift : [error.message],\n });\n }\n results[testCase.name] = triage;\n } else if (error instanceof DriftError) {\n results[testCase.name] = new ReplayCheck(\"DRIFT\", {\n drift: [error.message],\n });\n } else {\n throw error;\n }\n }\n\n if (record) {\n pendingRecords.push([testCase, null, results[testCase.name]]);\n }\n }\n\n const recordingErrors: string[] = [];\n for (const [testCase, traceId, triage] of pendingRecords) {\n const error = await recordRunItem(\n suiteToRun,\n testCase,\n runName,\n traceId,\n triage,\n );\n if (error) {\n recordingErrors.push(`${testCase.name}: ${error}`);\n }\n }\n\n return new ReplayReport(results, {\n runName: record ? runName : null,\n recordingErrors,\n });\n}\n\n/**\n * Shorthand for `ReplaySuite.fromTaskSet` — the intuitive entrypoint:\n *\n * ```typescript\n * import * as replay from \"@withgateway/sdk/replay\";\n * const report = await (await replay.suite(\"checkout-regressions\")).run(myAgent);\n * ```\n */\nexport function suite(\n nameOrId: string,\n options: ReplaySuiteLoadOptions = {},\n): Promise<ReplaySuite> {\n return ReplaySuite.fromTaskSet(nameOrId, options);\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction parseJsonObject(text: string): Record<string, unknown> {\n try {\n const parsed = JSON.parse(text);\n return isPlainObject(parsed) ? parsed : {};\n } catch {\n return {};\n }\n}\n\nfunction randomHex(): string {\n return crypto.randomUUID().replace(/-/g, \"\");\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport const replay = {\n suite,\n run: runSuite,\n};\n","type AgentDescriptor = {\n id?: string;\n name?: string;\n version?: string;\n};\n\ntype SecurityContext = {\n executionId?: string;\n userId?: string;\n teamId?: string;\n environment?: string;\n contextLabel?: string;\n contextBundleHash?: string;\n traceId?: string;\n sessionId?: string;\n spanId?: string;\n metadata?: Record<string, unknown>;\n};\n\ntype ToolDescriptor = {\n id: string;\n name?: string;\n description?: string;\n metadata?: Record<string, unknown>;\n};\n\ntype ToolsetResolveResponse = {\n toolsetId: string;\n mode: \"observe\" | \"filter\" | \"enforce\";\n policyVersion: number;\n ttlSeconds: number;\n allowedToolIds: string[];\n blockedToolIds: string[];\n approvalToolIds: string[];\n secretBindings: Record<string, string[]>;\n failMode: \"open\" | \"closed\";\n};\n\ntype ToolCallAuthorizeResponse = {\n decisionId: string;\n outcome: \"allow\" | \"flag\" | \"block\" | \"approval_required\";\n reasonCode: string;\n message: string;\n policyVersion: number;\n};\n\ntype ToolObject = {\n description?: string;\n execute?: (...args: unknown[]) => unknown;\n [key: string]: unknown;\n};\n\ntype ToolCollection = Record<\n string,\n ToolObject | ((...args: unknown[]) => unknown)\n>;\n\ntype SecureToolsOptions<TTools extends ToolCollection> = {\n toolsetId: string;\n toolsetName?: string;\n provider?: string;\n tools: TTools;\n context?: SecurityContext;\n toolIds?: Partial<Record<keyof TTools & string, string>>;\n toolMetadata?: Partial<\n Record<keyof TTools & string, Record<string, unknown>>\n >;\n};\n\ntype GatewaySecurityConfig = {\n host: string;\n publicKey: string;\n secretKey: string;\n agent?: AgentDescriptor;\n debug?: boolean;\n failOpen?: boolean;\n};\n\ntype GatewaySecurityFromEnvConfig = Partial<\n Pick<GatewaySecurityConfig, \"host\" | \"publicKey\" | \"secretKey\">\n> &\n Pick<GatewaySecurityConfig, \"agent\" | \"debug\" | \"failOpen\">;\n\nconst SECURITY_ATTRIBUTES = {\n AGENT_ID: \"gateway.agent.id\",\n AGENT_NAME: \"gateway.agent.name\",\n AGENT_VERSION: \"gateway.agent.version\",\n TOOLSET_ID: \"gateway.toolset.id\",\n TOOL_ID: \"gateway.tool.id\",\n SECURITY_MODE: \"gateway.security.mode\",\n POLICY_VERSION: \"gateway.security.policy_version\",\n DECISION_OUTCOME: \"gateway.decision.outcome\",\n DECISION_REASON_CODE: \"gateway.decision.reason_code\",\n} as const;\n\nexport class GatewaySecurityError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message);\n this.name = \"GatewaySecurityError\";\n this.cause = options?.cause;\n }\n}\n\nexport class GatewayToolBlockedError extends GatewaySecurityError {\n readonly decision: ToolCallAuthorizeResponse;\n readonly toolId: string;\n\n constructor(toolId: string, decision: ToolCallAuthorizeResponse) {\n super(decision.message || `Gateway blocked tool ${toolId}`);\n this.name = \"GatewayToolBlockedError\";\n this.toolId = toolId;\n this.decision = decision;\n }\n}\n\n/**\n * Thrown when Gateway's policy returns `approval_required` for a tool call.\n * The SDK does NOT execute the tool — a human/system approval is needed first\n * (the server engine and the runtime MCP PEP both honor this; this closes the\n * SDK leg of the step-up gate so an approval decision can't be silently run).\n */\nexport class GatewayToolApprovalRequiredError extends GatewaySecurityError {\n readonly decision: ToolCallAuthorizeResponse;\n readonly toolId: string;\n\n constructor(toolId: string, decision: ToolCallAuthorizeResponse) {\n super(decision.message || `Gateway requires approval for tool ${toolId}`);\n this.name = \"GatewayToolApprovalRequiredError\";\n this.toolId = toolId;\n this.decision = decision;\n }\n}\n\nexport class GatewaySecurity {\n private readonly host: string;\n private readonly publicKey: string;\n private readonly secretKey: string;\n private readonly agent: AgentDescriptor;\n private readonly debug: boolean;\n private readonly failOpen: boolean;\n\n constructor(config: GatewaySecurityConfig) {\n this.host = config.host.replace(/\\/$/, \"\");\n this.publicKey = config.publicKey;\n this.secretKey = config.secretKey;\n this.agent = config.agent ?? {};\n this.debug = config.debug ?? false;\n this.failOpen = config.failOpen ?? false;\n }\n\n static fromEnv(config: GatewaySecurityFromEnvConfig = {}) {\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 GatewaySecurityError(\n `Missing Gateway security configuration: ${missing.join(\", \")}`,\n );\n }\n\n return new GatewaySecurity({\n ...config,\n host: host!,\n publicKey: publicKey!,\n secretKey: secretKey!,\n });\n }\n\n async secureTools<TTools extends ToolCollection>(\n options: SecureToolsOptions<TTools>,\n ): Promise<TTools> {\n const entries = Object.entries(options.tools);\n const descriptors = entries.map(([key, tool]) =>\n this.describeTool(key, tool, options),\n );\n const resolve = await this.resolveToolset({\n agent: this.agent,\n toolsetId: options.toolsetId,\n toolsetName: options.toolsetName,\n provider: options.provider,\n tools: descriptors,\n context: this.normalizeContext(options.context),\n });\n\n const securedEntries = entries.flatMap(([key, tool]) => {\n const descriptor = descriptors.find((item) => item.name === key)!;\n if (!this.shouldExposeTool(resolve, descriptor.id)) {\n this.log(\"Hiding tool %s in %s mode\", descriptor.id, resolve.mode);\n return [];\n }\n\n return [\n [\n key,\n this.wrapTool(tool, {\n toolId: descriptor.id,\n toolsetId: options.toolsetId,\n context: this.normalizeContext(options.context),\n resolve,\n }),\n ],\n ];\n });\n\n return Object.fromEntries(securedEntries) as TTools;\n }\n\n private async resolveToolset(input: {\n agent: AgentDescriptor;\n toolsetId: string;\n toolsetName?: string;\n provider?: string;\n tools: ToolDescriptor[];\n context: SecurityContext;\n }) {\n return this.postJson<ToolsetResolveResponse>(\n \"/api/public/security/toolsets/resolve\",\n input,\n );\n }\n\n private async authorizeToolCall(input: {\n toolsetId: string;\n toolId: string;\n context: SecurityContext;\n inputMetadata: Record<string, unknown>;\n }) {\n return this.postJson<ToolCallAuthorizeResponse>(\n \"/api/public/security/tool-calls/authorize\",\n {\n agent: this.agent,\n toolsetId: input.toolsetId,\n toolId: input.toolId,\n context: input.context,\n inputMetadata: input.inputMetadata,\n },\n );\n }\n\n private wrapTool(\n tool: ToolObject | ((...args: unknown[]) => unknown),\n input: {\n toolId: string;\n toolsetId: string;\n context: SecurityContext;\n resolve: ToolsetResolveResponse;\n },\n ) {\n if (typeof tool === \"function\") {\n return this.wrapExecute(tool, input);\n }\n\n if (typeof tool.execute !== \"function\") {\n return tool;\n }\n\n return {\n ...tool,\n execute: this.wrapExecute(tool.execute.bind(tool), input),\n };\n }\n\n private wrapExecute(\n execute: (...args: unknown[]) => unknown,\n input: {\n toolId: string;\n toolsetId: string;\n context: SecurityContext;\n resolve: ToolsetResolveResponse;\n },\n ) {\n return async (...args: unknown[]) => {\n this.setSpanAttributes({\n [SECURITY_ATTRIBUTES.AGENT_ID]: this.agent.id,\n [SECURITY_ATTRIBUTES.AGENT_NAME]: this.agent.name,\n [SECURITY_ATTRIBUTES.AGENT_VERSION]: this.agent.version,\n [SECURITY_ATTRIBUTES.TOOLSET_ID]: input.toolsetId,\n [SECURITY_ATTRIBUTES.TOOL_ID]: input.toolId,\n [SECURITY_ATTRIBUTES.SECURITY_MODE]: input.resolve.mode,\n [SECURITY_ATTRIBUTES.POLICY_VERSION]: input.resolve.policyVersion,\n });\n\n const decision = await this.authorizeOrFallback({\n toolsetId: input.toolsetId,\n toolId: input.toolId,\n context: input.context,\n inputMetadata: { args },\n });\n\n this.setSpanAttributes({\n [SECURITY_ATTRIBUTES.DECISION_OUTCOME]: decision.outcome,\n [SECURITY_ATTRIBUTES.DECISION_REASON_CODE]: decision.reasonCode,\n [SECURITY_ATTRIBUTES.POLICY_VERSION]: decision.policyVersion,\n });\n\n if (decision.outcome === \"block\") {\n throw new GatewayToolBlockedError(input.toolId, decision);\n }\n if (decision.outcome === \"approval_required\") {\n // Enforce the step-up gate: do NOT execute until approved. The tool\n // stays callable (so the approval flow can be triggered), but a call\n // is refused with a typed error rather than running unapproved.\n throw new GatewayToolApprovalRequiredError(input.toolId, decision);\n }\n\n return execute(...args);\n };\n }\n\n private async authorizeOrFallback(input: {\n toolsetId: string;\n toolId: string;\n context: SecurityContext;\n inputMetadata: Record<string, unknown>;\n }) {\n try {\n return await this.authorizeToolCall(input);\n } catch (error) {\n if (this.failOpen) {\n this.log(\"Authorization failed open for tool %s\", input.toolId, error);\n return {\n decisionId: \"local-fail-open\",\n outcome: \"flag\" as const,\n reasonCode: \"authorization_unavailable_fail_open\",\n message:\n \"Gateway authorization was unavailable; failOpen allowed execution.\",\n policyVersion: 0,\n };\n }\n throw new GatewaySecurityError(\n `Gateway authorization failed for tool ${input.toolId}`,\n { cause: error },\n );\n }\n }\n\n private async postJson<TResponse>(\n path: string,\n payload: Record<string, unknown>,\n ): Promise<TResponse> {\n const response = await fetch(`${this.host}${path}`, {\n method: \"POST\",\n headers: {\n Authorization: this.authHeader(),\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const body = await response.text();\n throw new GatewaySecurityError(\n `Gateway API ${response.status} on ${path}: ${body || response.statusText}`,\n );\n }\n\n return (await response.json()) as TResponse;\n }\n\n private describeTool<TTools extends ToolCollection>(\n key: string,\n tool: ToolObject | ((...args: unknown[]) => unknown),\n options: SecureToolsOptions<TTools>,\n ): ToolDescriptor & { name: string } {\n const toolObject = typeof tool === \"function\" ? undefined : tool;\n const id =\n options.toolIds?.[key] ?? `${options.toolsetId}.${toSnakeCase(key)}`;\n return {\n id,\n name: key,\n description:\n typeof toolObject?.description === \"string\"\n ? toolObject.description\n : undefined,\n metadata: options.toolMetadata?.[key] ?? {},\n };\n }\n\n private shouldExposeTool(resolve: ToolsetResolveResponse, toolId: string) {\n if (resolve.mode === \"observe\") return true;\n if (resolve.blockedToolIds.includes(toolId)) return false;\n return true;\n }\n\n private normalizeContext(context?: SecurityContext): SecurityContext {\n return {\n ...(context ?? {}),\n metadata: context?.metadata ?? {},\n };\n }\n\n private authHeader() {\n return `Basic ${Buffer.from(`${this.publicKey}:${this.secretKey}`).toString(\n \"base64\",\n )}`;\n }\n\n private setSpanAttributes(attributes: Record<string, unknown>) {\n const span = getActiveSpan();\n if (!span) return;\n\n for (const [key, value] of Object.entries(attributes)) {\n if (value === undefined || value === null) continue;\n span.setAttribute(key, value);\n }\n }\n\n private log(message: string, ...args: unknown[]) {\n if (this.debug) {\n console.log(`[gateway.security] ${message}`, ...args);\n }\n }\n}\n\nfunction getActiveSpan(): {\n setAttribute: (key: string, value: unknown) => void;\n} | null {\n try {\n // Optional peer dependency. Avoid making security unusable without tracing.\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const otel = require(\"@opentelemetry/api\") as {\n trace?: {\n getActiveSpan?: () =>\n | { setAttribute: (key: string, value: unknown) => void }\n | undefined;\n };\n };\n return otel.trace?.getActiveSpan?.() ?? null;\n } catch {\n return null;\n }\n}\n\nfunction toSnakeCase(value: string) {\n return value\n .replace(/([a-z0-9])([A-Z])/g, \"$1_$2\")\n .replace(/[\\s-]+/g, \"_\")\n .toLowerCase();\n}\n\nexport const gateway = {\n fromEnv: GatewaySecurity.fromEnv,\n};\n\nexport type {\n AgentDescriptor as GatewayAgentDescriptor,\n GatewaySecurityConfig,\n SecurityContext as GatewaySecurityContext,\n SecureToolsOptions,\n ToolCallAuthorizeResponse as GatewayToolCallAuthorizeResponse,\n ToolDescriptor as GatewayToolDescriptor,\n ToolsetResolveResponse as GatewayToolsetResolveResponse,\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 * 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 * The project's file drive from code: the same routes the dashboard, the MCP\n * tools (list_files, get_file, request_file_upload, confirm_file_upload,\n * delete_file, move_file, create_folder) and `gateway files …` use.\n *\n * GET /api/public/files?prefix=&page=&limit= list a folder\n * POST /api/public/files presigned PUT, then\n * POST /api/public/files/confirm mark it ready\n * GET /api/public/files/download?path= presigned GET + metadata\n * DELETE /api/public/files?path= a file, or a folder subtree\n * POST /api/public/files/move { fromPath, toPath }\n * POST /api/public/files/folders { path }\n *\n * Bytes go straight to storage: an upload is a PUT to the presigned URL with\n * the SHA-256 S3 enforces, a download a GET from one. The app never proxies\n * them, so a file of any size the project allows moves at storage speed. Files\n * are addressed by PATH; the API returns a fileId on upload only to confirm it.\n */\n\nimport { createHash } from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { Readable, Transform } from \"node:stream\";\nimport { pipeline } from \"node:stream/promises\";\n\nimport { apiRequest, type WorldsClientOptions } from \"../worlds/index\";\n\nexport type DriveFile = {\n path: string;\n name: string;\n sizeBytes: number | null;\n contentType: string | null;\n sha256: string | null;\n author: string | null;\n authorLabel: string;\n updatedAt: string;\n};\n\nexport type DriveFolder = { name: string; path: string };\n\nexport type DriveListing = {\n prefix: string;\n folders: DriveFolder[];\n files: DriveFile[];\n totalFiles: number;\n page: number;\n limit: number;\n};\n\n/** What `GET /files/download` answers: the file's metadata and a time-limited URL for its bytes. */\nexport type DriveDownload = {\n path: string;\n url: string;\n urlExpiry: string;\n sizeBytes: number | null;\n contentType: string | null;\n sha256: string | null;\n};\n\nexport type UploadResult = { path: string; fileId: string; sizeBytes: number; sha256: string; contentType: string };\n\nexport type UploadOptions = {\n contentType?: string;\n /** Replace a READY file at the same path. Default false: the platform refuses a taken path. */\n overwrite?: boolean;\n /** Bytes sent so far, called as the PUT streams. */\n onProgress?: (sent: number, total: number) => void;\n};\n\n/** The spelling that names a drive file where a local path would go: `drive:<path>`. */\nexport const DRIVE_PREFIX = \"drive:\";\n\nexport function isDriveRef(value: string): boolean {\n return value.startsWith(DRIVE_PREFIX);\n}\n\n/** `drive:corpora/x.jsonl` → `corpora/x.jsonl`; a leading slash is dropped, the platform keys paths without one. */\nexport function drivePath(ref: string): string {\n const raw = isDriveRef(ref) ? ref.slice(DRIVE_PREFIX.length) : ref;\n const trimmed = raw.replace(/^\\/+/, \"\");\n if (!trimmed) throw new Error(`${ref} names no file in the drive`);\n return trimmed;\n}\n\nconst PAGE_LIMIT = 200;\nconst BASE = \"/api/public/files\";\n\nfunction qs(params: Record<string, string | number | undefined>): string {\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) if (value !== undefined && value !== \"\") search.set(key, String(value));\n const text = search.toString();\n return text ? `?${text}` : \"\";\n}\n\nexport async function listFiles(\n options: WorldsClientOptions = {},\n params: { prefix?: string; page?: number; limit?: number } = {},\n): Promise<DriveListing> {\n return apiRequest<DriveListing>(options, \"GET\", `${BASE}${qs({ prefix: params.prefix, page: params.page, limit: params.limit })}`);\n}\n\n/** Every file directly under a folder, paging until the listing is exhausted. */\nexport async function* iterateFiles(options: WorldsClientOptions = {}, prefix?: string): AsyncGenerator<DriveFile> {\n for (let page = 0; ; page++) {\n const listing = await listFiles(options, { prefix, page, limit: PAGE_LIMIT });\n yield* listing.files;\n const seen = (page + 1) * listing.limit;\n if (!listing.files.length || seen >= listing.totalFiles) return;\n }\n}\n\n/** Metadata plus a presigned URL for one file; a 404 names the path. */\nexport async function getFile(options: WorldsClientOptions = {}, filePath: string): Promise<DriveDownload> {\n return apiRequest<DriveDownload>(options, \"GET\", `${BASE}/download${qs({ path: drivePath(filePath) })}`);\n}\n\nasync function openDownload(url: string): Promise<Response> {\n const res = await fetch(url);\n if (!res.ok || !res.body) throw new Error(`download failed: storage answered HTTP ${res.status}`);\n return res;\n}\n\n/** The whole file in memory — for text, configs, anything you would `cat`. */\nexport async function readFile(options: WorldsClientOptions = {}, filePath: string): Promise<Buffer> {\n const file = await getFile(options, filePath);\n const res = await openDownload(file.url);\n return Buffer.from(await res.arrayBuffer());\n}\n\n/** Stream one file to a local path; the parent directory is created. */\nexport async function downloadFile(\n options: WorldsClientOptions = {},\n filePath: string,\n outPath: string,\n onProgress?: (received: number, total: number | null) => void,\n): Promise<DriveDownload & { out: string }> {\n const file = await getFile(options, filePath);\n const res = await openDownload(file.url);\n fs.mkdirSync(path.dirname(path.resolve(outPath)), { recursive: true });\n const source = Readable.fromWeb(res.body as never);\n await pipeline(source, counting((n) => onProgress?.(n, file.sizeBytes)), fs.createWriteStream(outPath));\n return { ...file, out: outPath };\n}\n\nexport async function requestUpload(\n options: WorldsClientOptions = {},\n body: { path: string; contentLength: number; contentType: string; sha256: string; overwrite?: boolean },\n): Promise<{ fileId: string; uploadUrl: string; path: string }> {\n return apiRequest(options, \"POST\", BASE, body);\n}\n\nexport async function confirmUpload(options: WorldsClientOptions = {}, fileId: string, ok = true): Promise<{ path: string }> {\n return apiRequest(options, \"POST\", `${BASE}/confirm`, { fileId, ok });\n}\n\n/** The base64 SHA-256 the platform hands to S3 (`x-amz-checksum-sha256`), computed by streaming. */\nexport async function sha256Base64(localPath: string): Promise<string> {\n const hash = createHash(\"sha256\");\n for await (const chunk of fs.createReadStream(localPath)) hash.update(chunk as Buffer);\n return hash.digest(\"base64\");\n}\n\nconst CONTENT_TYPES: Record<string, string> = {\n \".json\": \"application/json\",\n \".jsonl\": \"application/x-ndjson\",\n \".ndjson\": \"application/x-ndjson\",\n \".csv\": \"text/csv\",\n \".tsv\": \"text/tab-separated-values\",\n \".txt\": \"text/plain\",\n \".md\": \"text/markdown\",\n \".toml\": \"application/toml\",\n \".yaml\": \"application/yaml\",\n \".yml\": \"application/yaml\",\n \".xml\": \"application/xml\",\n \".html\": \"text/html\",\n \".sql\": \"application/sql\",\n \".py\": \"text/x-python\",\n \".ts\": \"text/plain\",\n \".js\": \"text/javascript\",\n \".pdf\": \"application/pdf\",\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".gif\": \"image/gif\",\n \".webp\": \"image/webp\",\n \".svg\": \"image/svg+xml\",\n \".zip\": \"application/zip\",\n \".gz\": \"application/gzip\",\n \".tar\": \"application/x-tar\",\n \".parquet\": \"application/vnd.apache.parquet\",\n \".wav\": \"audio/wav\",\n \".mp3\": \"audio/mpeg\",\n \".mp4\": \"video/mp4\",\n};\n\n/** A MIME type from the extension; `application/octet-stream` when none is known. */\nexport function contentTypeFor(name: string): string {\n return CONTENT_TYPES[path.extname(name).toLowerCase()] ?? \"application/octet-stream\";\n}\n\n/** A transform that reports the bytes that passed through it. */\nfunction counting(report: (n: number) => void): Transform {\n let seen = 0;\n return new Transform({\n transform(chunk, _encoding, callback) {\n seen += (chunk as Buffer).length;\n report(seen);\n callback(null, chunk);\n },\n });\n}\n\nasync function putPresigned(\n uploadUrl: string,\n body: BodyInit,\n headers: { contentType: string; contentLength: number; sha256: string },\n): Promise<void> {\n const res = await fetch(uploadUrl, {\n method: \"PUT\",\n headers: {\n \"content-type\": headers.contentType,\n \"content-length\": String(headers.contentLength),\n \"x-amz-checksum-sha256\": headers.sha256,\n },\n body,\n // A streamed request body needs the half-duplex declaration (Node's fetch).\n duplex: \"half\",\n } as RequestInit);\n if (!res.ok) throw new Error(`upload failed: storage answered HTTP ${res.status}: ${(await res.text()).slice(0, 300)}`);\n}\n\n/**\n * Request, PUT, confirm — the three-step presigned upload as one call. The\n * bytes stream from disk; a failed PUT is confirmed with ok=false so no\n * PENDING placeholder is left behind, then the error is rethrown.\n */\nexport async function uploadFile(\n options: WorldsClientOptions = {},\n localPath: string,\n targetPath: string,\n upload: UploadOptions = {},\n): Promise<UploadResult> {\n const stat = fs.statSync(localPath);\n if (!stat.isFile()) throw new Error(`${localPath} is not a file`);\n if (stat.size === 0) throw new Error(`${localPath} is empty; the drive refuses zero-byte uploads`);\n const contentType = upload.contentType ?? contentTypeFor(localPath);\n const sha256 = await sha256Base64(localPath);\n const target = drivePath(targetPath);\n const granted = await requestUpload(options, { path: target, contentLength: stat.size, contentType, sha256, ...(upload.overwrite ? { overwrite: true } : {}) });\n try {\n const stream = fs.createReadStream(localPath).pipe(counting((n) => upload.onProgress?.(n, stat.size)));\n await putPresigned(granted.uploadUrl, Readable.toWeb(stream) as unknown as BodyInit, { contentType, contentLength: stat.size, sha256 });\n } catch (error) {\n await confirmUpload(options, granted.fileId, false).catch(() => undefined);\n throw error;\n }\n const confirmed = await confirmUpload(options, granted.fileId, true);\n return { path: confirmed.path, fileId: granted.fileId, sizeBytes: stat.size, sha256, contentType };\n}\n\n/** The same three steps for bytes already in memory (a fetched URL, a generated export). */\nexport async function uploadBytes(\n options: WorldsClientOptions = {},\n bytes: Buffer,\n targetPath: string,\n upload: Omit<UploadOptions, \"onProgress\"> = {},\n): Promise<UploadResult> {\n if (!bytes.length) throw new Error(\"nothing to upload: the content is empty\");\n const target = drivePath(targetPath);\n const contentType = upload.contentType ?? contentTypeFor(target);\n const sha256 = createHash(\"sha256\").update(bytes).digest(\"base64\");\n const granted = await requestUpload(options, { path: target, contentLength: bytes.length, contentType, sha256, ...(upload.overwrite ? { overwrite: true } : {}) });\n try {\n await putPresigned(granted.uploadUrl, new Uint8Array(bytes), { contentType, contentLength: bytes.length, sha256 });\n } catch (error) {\n await confirmUpload(options, granted.fileId, false).catch(() => undefined);\n throw error;\n }\n const confirmed = await confirmUpload(options, granted.fileId, true);\n return { path: confirmed.path, fileId: granted.fileId, sizeBytes: bytes.length, sha256, contentType };\n}\n\n/** Delete a file, or a folder and everything under it. Answers how many entries went. */\nexport async function deleteFile(options: WorldsClientOptions = {}, filePath: string): Promise<{ deleted: number }> {\n return apiRequest(options, \"DELETE\", `${BASE}${qs({ path: drivePath(filePath) })}`);\n}\n\n/** Rename or move a file or a whole folder; metadata only, no bytes re-copied. */\nexport async function moveFile(options: WorldsClientOptions = {}, fromPath: string, toPath: string): Promise<{ moved: number }> {\n return apiRequest(options, \"POST\", `${BASE}/move`, { fromPath: drivePath(fromPath), toPath: drivePath(toPath) });\n}\n\n/** Create an (empty) folder. Idempotent. */\nexport async function createFolder(options: WorldsClientOptions = {}, folderPath: string): Promise<{ path: string }> {\n return apiRequest(options, \"POST\", `${BASE}/folders`, { path: drivePath(folderPath) });\n}\n\nexport type FileConnector = {\n id: string;\n name: string;\n kind: string;\n connectionId: string | null;\n targetPrefix: string;\n lastSyncAt: string | null;\n lastStatus: string | null;\n};\n\n/** The connectors a human shared with agents — `GET /api/public/files/connectors`. */\nexport async function listFileConnectors(options: WorldsClientOptions = {}): Promise<{ connectors: FileConnector[] }> {\n return apiRequest(options, \"GET\", `${BASE}/connectors`);\n}\n\n/** Run one connector's sync now — `POST /api/public/files/connectors/sync`. */\nexport async function syncFileConnector(options: WorldsClientOptions = {}, connectorId: string): Promise<Record<string, unknown>> {\n return apiRequest(options, \"POST\", `${BASE}/connectors/sync`, { connectorId });\n}\n","/**\n * Read the project's traces, observations and trace sessions — the public\n * API behind `gateway traces …` and the MCP tools get_trace / get_observations\n * / get_session. Everything here is read-only.\n *\n * GET /api/public/traces?… a page of traces (page 1-based, limit ≤ 100)\n * GET /api/public/traces/{traceId} one trace with its observations and scores\n * GET /api/public/observations?… a page of observations (type, traceId, time window)\n * GET /api/public/sessions?… a page of trace sessions\n * GET /api/public/sessions/{sessionId} one session; includeIO=true attaches every trace's observations\n */\n\nimport { apiRequest, type WorldsClientOptions } from \"../worlds/index\";\n\nexport type TraceFilters = {\n fromTimestamp?: string;\n toTimestamp?: string;\n sessionId?: string;\n userId?: string;\n name?: string;\n tags?: string[];\n environment?: string;\n version?: string;\n release?: string;\n /** `timestamp.asc`, `timestamp.desc` (the default), … */\n orderBy?: string;\n};\n\nexport type ObservationFilters = {\n traceId?: string;\n type?: string;\n name?: string;\n userId?: string;\n level?: string;\n parentObservationId?: string;\n environment?: string;\n version?: string;\n fromStartTime?: string;\n toStartTime?: string;\n};\n\nexport type SessionFilters = { fromTimestamp?: string; toTimestamp?: string; environment?: string };\n\nexport type PageMeta = { page: number; limit: number; totalItems: number; totalPages: number };\nexport type Page<T> = { data: T[]; meta: PageMeta };\n\nexport type Trace = {\n id: string;\n timestamp: string;\n name: string | null;\n sessionId: string | null;\n userId: string | null;\n tags: string[];\n environment?: string;\n [key: string]: unknown;\n};\n\nexport type Observation = {\n id: string;\n traceId: string | null;\n type: string;\n name: string | null;\n startTime: string;\n endTime?: string | null;\n level?: string;\n [key: string]: unknown;\n};\n\nexport type TraceDetail = Trace & { observations: Observation[]; scores: unknown[]; latency?: number; totalCost?: number };\n\nexport type TraceSession = { id: string; createdAt: string; projectId: string; environment: string };\nexport type TraceSessionDetail = TraceSession & { traces: (Trace & { observations?: Observation[] })[] };\n\n/** The platform caps a page at 100. */\nexport const PAGE_LIMIT = 100;\n\ntype Scalar = string | number | boolean | undefined | null;\n\nfunction qs(params: Record<string, Scalar | string[]>): string {\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined || value === null || value === \"\") continue;\n if (Array.isArray(value)) for (const item of value) search.append(key, item);\n else search.set(key, String(value));\n }\n const text = search.toString();\n return text ? `?${text}` : \"\";\n}\n\nexport async function listTraces(\n options: WorldsClientOptions = {},\n filters: TraceFilters = {},\n page: { page?: number; limit?: number; fields?: string } = {},\n): Promise<Page<Trace>> {\n const { tags, ...rest } = filters;\n return apiRequest<Page<Trace>>(options, \"GET\", `/api/public/traces${qs({ ...rest, tags, page: page.page ?? 1, limit: page.limit ?? 50, fields: page.fields })}`);\n}\n\n/** Page through matching traces, newest first unless `orderBy` says otherwise; `max` stops early. */\nexport async function* iterateTraces(\n options: WorldsClientOptions = {},\n filters: TraceFilters = {},\n limits: { max?: number; fields?: string } = {},\n): AsyncGenerator<Trace> {\n yield* paged((page) => listTraces(options, filters, { page, limit: PAGE_LIMIT, fields: limits.fields }), limits.max);\n}\n\n/** One trace with its observations (input/output included) and scores. */\nexport async function getTrace(options: WorldsClientOptions = {}, traceId: string): Promise<TraceDetail> {\n return apiRequest<TraceDetail>(options, \"GET\", `/api/public/traces/${encodeURIComponent(traceId)}`);\n}\n\nexport async function listObservations(\n options: WorldsClientOptions = {},\n filters: ObservationFilters = {},\n page: { page?: number; limit?: number } = {},\n): Promise<Page<Observation>> {\n return apiRequest<Page<Observation>>(options, \"GET\", `/api/public/observations${qs({ ...filters, page: page.page ?? 1, limit: page.limit ?? 50 })}`);\n}\n\nexport async function* iterateObservations(\n options: WorldsClientOptions = {},\n filters: ObservationFilters = {},\n limits: { max?: number } = {},\n): AsyncGenerator<Observation> {\n yield* paged((page) => listObservations(options, filters, { page, limit: PAGE_LIMIT }), limits.max);\n}\n\nexport async function listSessions(\n options: WorldsClientOptions = {},\n filters: SessionFilters = {},\n page: { page?: number; limit?: number } = {},\n): Promise<Page<TraceSession>> {\n return apiRequest<Page<TraceSession>>(options, \"GET\", `/api/public/sessions${qs({ ...filters, page: page.page ?? 1, limit: page.limit ?? 50 })}`);\n}\n\nexport async function* iterateSessions(\n options: WorldsClientOptions = {},\n filters: SessionFilters = {},\n limits: { max?: number } = {},\n): AsyncGenerator<TraceSession> {\n yield* paged((page) => listSessions(options, filters, { page, limit: PAGE_LIMIT }), limits.max);\n}\n\n/** One trace session and its traces; `includeIO` attaches every trace's full observations. */\nexport async function getSession(\n options: WorldsClientOptions = {},\n sessionId: string,\n detail: { includeIO?: boolean } = {},\n): Promise<TraceSessionDetail> {\n return apiRequest<TraceSessionDetail>(options, \"GET\", `/api/public/sessions/${encodeURIComponent(sessionId)}${qs({ includeIO: detail.includeIO ? \"true\" : undefined })}`);\n}\n\nexport type ExportOptions = {\n /** Attach each trace's observations (one GET /traces/{id} per trace). */\n observations?: boolean;\n /** With `observations`: keep only this observation type (TOOL, GENERATION, SPAN, …). */\n type?: string;\n /** Stop after this many traces. */\n max?: number;\n};\n\nexport type ExportSummary = { traces: number; observations: number };\n\n/**\n * Every matching trace as one JSON object handed to `write`, ids and\n * timestamps exactly as the API returns them. With `observations`, each object\n * carries its `observations` array (filtered by `type` when given) and the\n * trace's `scores`, from `GET /traces/{id}`.\n */\nexport async function exportTraces(\n options: WorldsClientOptions = {},\n filters: TraceFilters = {},\n exportOptions: ExportOptions = {},\n write: (record: Record<string, unknown>) => void,\n): Promise<ExportSummary> {\n const summary: ExportSummary = { traces: 0, observations: 0 };\n const wantedType = exportOptions.type?.toUpperCase();\n for await (const trace of iterateTraces(options, filters, { max: exportOptions.max })) {\n let record: Record<string, unknown> = trace;\n if (exportOptions.observations) {\n const detail = await getTrace(options, trace.id);\n const observations = wantedType ? detail.observations.filter((o) => o.type?.toUpperCase() === wantedType) : detail.observations;\n summary.observations += observations.length;\n record = { ...detail, observations };\n }\n summary.traces++;\n write(record);\n }\n return summary;\n}\n\nasync function* paged<T>(fetchPage: (page: number) => Promise<Page<T>>, max?: number): AsyncGenerator<T> {\n let yielded = 0;\n for (let page = 1; ; page++) {\n const answer = await fetchPage(page);\n for (const item of answer.data) {\n if (max !== undefined && yielded >= max) return;\n yielded++;\n yield item;\n }\n const totalPages = answer.meta?.totalPages ?? (answer.data.length < PAGE_LIMIT ? page : page + 1);\n if (!answer.data.length || page >= totalPages) return;\n }\n}\n","/**\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 * 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 * Tracing module for GatewaySDK TypeScript SDK.\n *\n * Provides a simple init() function that configures OpenTelemetry with\n * Gateway, mirroring the Python SDK's tracing.init() experience.\n *\n * @example\n * ```typescript\n * import { tracing } from \"@withgateway/sdk\";\n *\n * // Initialize with environment variables\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 * });\n *\n * // Ensure cleanup on shutdown\n * process.on(\"SIGTERM\", () => tracing.shutdown());\n * ```\n */\n\nexport type { TracingConfig, TracingState } from \"./types\";\n\nexport {\n init,\n initIsolated,\n shutdown,\n flush,\n isInitialized,\n isGatewayConfigured,\n} from \"./init\";\nexport type { TracingHandle } from \"./init\";\n\nexport {\n identify,\n resolveUserId,\n resetAmbientUser,\n IdentitySpanProcessor,\n USER_ID_ATTRIBUTE,\n} from \"./identity\";\nexport type { IdentifyOptions } from \"./identity\";\n\nexport { observe } from \"./observe\";\nexport type { ObserveOptions, ObservationKind } from \"./observe\";\n\nexport { observeOpenAI, observeAnthropic } from \"./instrument\";\n\nexport { observeClaude } from \"./claude\";\nexport type { ObserveClaudeOptions } from \"./claude\";\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 { 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 ?? semconv.SEMRESATTRS_SERVICE_NAME ?? \"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 // 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","/**\n * observe() — group a unit of work (an agent run, a tool call) into a single\n * span so nested LLM/tool spans attach to it and the whole thing is one trace.\n *\n * Mirrors Langfuse's `observe()` / `startActiveObservation()`. This is what an\n * app uses to define a trace boundary when it drives a raw client loop (which\n * has no framework root span of its own): the callback runs inside the span's\n * OpenTelemetry context, so any auto-instrumented calls (see observeOpenAI) and\n * any nested observe() calls become children of it.\n *\n * The span carries OpenInference attributes (openinference.span.kind, input.value,\n * output.value), and Gateway maps a root span's input.value/output.value to the\n * trace-level input/output — so the trace shows the user input and final output.\n */\nimport { trace, context, SpanStatusCode } from \"@opentelemetry/api\";\nimport type { Tracer } from \"@opentelemetry/api\";\n\nexport type ObservationKind = \"AGENT\" | \"CHAIN\" | \"TOOL\" | \"LLM\" | \"RETRIEVER\";\n\nexport interface ObserveOptions {\n /** Recorded as input.value on the span (JSON-stringified if not a string). */\n input?: unknown;\n /** OpenInference span kind. Defaults to \"AGENT\" for the outer run. */\n kind?: ObservationKind;\n /**\n * When true (default), the callback's return value is recorded as\n * output.value. Set false if the return value is large/uninteresting.\n */\n captureOutput?: boolean;\n /**\n * Tracer to start the span from. Defaults to the GLOBAL tracer (set up by\n * tracing.init()). Pass an initIsolated() handle's tracer to route this\n * observation to that handle's Gateway project instead.\n */\n tracer?: Tracer;\n /**\n * Extra attributes for the span — e.g. gateway.session.id /\n * gateway.user.id to group runs into a session and attribute them to a user.\n */\n attributes?: Record<string, string>;\n}\n\nfunction asAttr(value: unknown): string {\n return typeof value === \"string\" ? value : JSON.stringify(value);\n}\n\n/**\n * Run `fn` inside a span named `name`. Anything traced inside (auto-instrumented\n * client calls, nested observe() calls) nests under it, forming one trace.\n *\n * @example\n * ```ts\n * const result = await observe(\"my-agent.run\", async () => {\n * // client.chat.completions.create(...) here becomes a child GENERATION\n * return finalText;\n * }, { input: prompt });\n * ```\n */\nexport async function observe<T>(\n name: string,\n fn: () => Promise<T>,\n options: ObserveOptions = {},\n): Promise<T> {\n const tracer = options.tracer ?? trace.getTracer(\"@withgateway/sdk\");\n const span = tracer.startSpan(name, {\n attributes: {\n \"openinference.span.kind\": options.kind ?? \"AGENT\",\n ...(options.input !== undefined\n ? { \"input.value\": asAttr(options.input) }\n : {}),\n ...(options.attributes ?? {}),\n },\n });\n\n try {\n const result = await context.with(\n trace.setSpan(context.active(), span),\n fn,\n );\n if (options.captureOutput !== false && result !== undefined) {\n span.setAttribute(\"output.value\", asAttr(result));\n }\n span.setStatus({ code: SpanStatusCode.OK });\n return result;\n } catch (error) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: error instanceof Error ? error.message : String(error),\n });\n throw error;\n } finally {\n span.end();\n }\n}\n","/**\n * Client wrappers that turn an SDK's calls into spans on the Gateway provider.\n *\n * Node ESM can't retroactively patch a module the app already imported, so — as\n * Langfuse does with `observeOpenAI` — the app hands us the client and we\n * instrument it explicitly. One SDK call, no OpenTelemetry in the app.\n *\n * The OpenInference instrumentations are bundled optional deps of this package;\n * we load them with require() (the ESM build injects a real createRequire).\n */\n/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-require-imports */\n\nfunction warn(message: string, ...args: unknown[]): void {\n console.warn(`[gatewaysdk.tracing] ${message}`, ...args);\n}\n\n/**\n * Instrument an OpenAI client so its requests become GENERATION spans on the\n * Gateway provider. Returns the same client (its class prototype is patched, so\n * this and every other instance of that client are traced).\n *\n * @example\n * ```ts\n * import OpenAI from \"openai\";\n * import { init, observeOpenAI } from \"@withgateway/sdk/tracing\";\n * init();\n * const client = observeOpenAI(new OpenAI());\n * ```\n */\nexport function observeOpenAI<T extends object>(client: T): T {\n try {\n const {\n OpenAIInstrumentation,\n } = require(\"@arizeai/openinference-instrumentation-openai\");\n // OpenInference patches `module.OpenAI.Chat.Completions.prototype`, so it\n // needs an object shaped like the openai module. Reconstruct it from the\n // instance's class (client.constructor === the OpenAI class).\n const OpenAIClass = (client as { constructor: unknown }).constructor;\n new OpenAIInstrumentation().manuallyInstrument({ OpenAI: OpenAIClass });\n } catch (error) {\n warn(\n \"observeOpenAI: could not load @arizeai/openinference-instrumentation-openai — OpenAI calls will not be traced.\",\n error,\n );\n }\n return client;\n}\n\n/**\n * Instrument an Anthropic client so its requests become GENERATION spans.\n *\n * @example\n * ```ts\n * import Anthropic from \"@anthropic-ai/sdk\";\n * import { init, observeAnthropic } from \"@withgateway/sdk/tracing\";\n * init();\n * const client = observeAnthropic(new Anthropic());\n * ```\n */\nexport function observeAnthropic<T extends object>(client: T): T {\n try {\n const {\n AnthropicInstrumentation,\n } = require(\"@arizeai/openinference-instrumentation-anthropic\");\n // The instrumentor patches `module.Messages.prototype.create`, so it wants\n // an object whose `Messages` is the Anthropic client's Messages class (a\n // static on the class). `client.messages` resolves `create` through that\n // prototype, so patching it traces this client and every other instance.\n const AnthropicClass = (client as { constructor: { Messages?: unknown } })\n .constructor;\n new AnthropicInstrumentation().manuallyInstrument({\n Messages: AnthropicClass.Messages,\n });\n } catch (error) {\n warn(\n \"observeAnthropic: could not load @arizeai/openinference-instrumentation-anthropic — Anthropic calls will not be traced.\",\n error,\n );\n }\n return client;\n}\n","/**\n * observeClaude() — trace a Claude Agent SDK run.\n *\n * The Claude Agent SDK runs the agent in a separate `claude` CLI subprocess, so\n * there's nothing in-process to patch. What the app has is the message stream it\n * iterates. Wrap that stream with observeClaude() and it yields the same\n * messages unchanged while emitting spans on the Gateway provider.\n *\n * Default (one trace per run):\n *\n * AGENT (root)\n * ├─ GENERATION per assistant turn (with per-turn token usage)\n * └─ TOOL per tool call (input from tool_use, output from the\n * matching tool_result, matched by id)\n *\n * With `perTurn: true` (one trace PER ASSISTANT TURN — long agent runs read as\n * a session of turn traces, the way a chat thread does):\n *\n * AGENT \"<name> · turn N\" (detached root; session/user attributes on every turn)\n * ├─ GENERATION (that turn's usage + text)\n * └─ TOOL per tool call in the turn\n *\n * The TS equivalent of the Python SDK's claude-agent-sdk instrumentor.\n *\n * @example\n * ```ts\n * const stream = query({ prompt, options });\n * for await (const message of observeClaude(stream, { name, input: prompt })) {\n * // ...consume messages as usual\n * }\n * ```\n */\nimport {\n trace,\n context,\n SpanStatusCode,\n type Span,\n type Context,\n type Tracer,\n} from \"@opentelemetry/api\";\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nexport interface ObserveClaudeOptions {\n /** Root span name (becomes the trace name; per-turn mode appends `· turn N`). */\n name: string;\n /** Recorded as input.value on the root span → trace-level input. */\n input?: string;\n /** Model label for the generation spans. */\n model?: string;\n /**\n * Tracer to start spans from. Defaults to the GLOBAL tracer (set up by\n * tracing.init()). Pass an initIsolated() handle's tracer to route this\n * run to that handle's Gateway project instead.\n */\n tracer?: Tracer;\n /**\n * Extra attributes for the root span(s) — e.g. gateway.session.id /\n * gateway.user.id to group runs into a session and attribute them to a user.\n * In per-turn mode these ride EVERY turn root, so each turn trace maps to\n * the session.\n */\n attributes?: Record<string, string>;\n /**\n * Emit one TRACE PER ASSISTANT TURN instead of a single trace for the whole\n * run. Each turn's trace carries that turn's generation and tool calls; the\n * turn's input is the run input (turn 1) or the tool results that fed it\n * (later turns). Turn roots are detached (`root: true`), so they never nest\n * under ambient spans. Combine with `attributes.gateway.session.id` to read\n * a whole run as a session of turns.\n */\n perTurn?: boolean;\n}\n\n/** Strip the `mcp__<server>__` prefix so tool names read cleanly. */\nfunction cleanToolName(name: string): string {\n return name.replace(/^mcp__[^_]+__/, \"\");\n}\n\nfunction toolResultText(content: unknown): string {\n if (typeof content === \"string\") return content;\n if (Array.isArray(content))\n return content\n .map((b) =>\n b && typeof b === \"object\" && \"text\" in b\n ? String((b as { text: unknown }).text)\n : JSON.stringify(b),\n )\n .join(\"\");\n return JSON.stringify(content ?? \"\");\n}\n\nconst TURN_INPUT_MAX = 4000;\n\nexport async function* observeClaude(\n stream: AsyncIterable<any>,\n options: ObserveClaudeOptions,\n): AsyncGenerator<any> {\n const tracer = options.tracer ?? trace.getTracer(\"@withgateway/sdk\");\n const model = options.model ?? \"claude\";\n const openTools = new Map<string, Span>();\n\n // Single-trace mode: one root for the whole run.\n let root: Span | null = null;\n let rootCtx: Context | null = null;\n if (!options.perTurn) {\n root = tracer.startSpan(options.name, {\n attributes: {\n \"openinference.span.kind\": \"AGENT\",\n ...(options.input !== undefined\n ? { \"input.value\": options.input }\n : {}),\n ...(options.attributes ?? {}),\n },\n });\n rootCtx = trace.setSpan(context.active(), root);\n }\n\n // Per-turn mode: the current turn's root, rotated on each assistant message.\n let turnRoot: Span | null = null;\n let turnCtx: Context | null = null;\n let turnIndex = 0;\n let turnText = \"\";\n // What fed the CURRENT turn: the run input for turn 1, then the tool results\n // produced since the previous assistant message.\n let pendingTurnInput = options.input ?? \"\";\n\n let finalText = \"\";\n\n const endTurn = () => {\n if (!turnRoot) return;\n if (turnText) turnRoot.setAttribute(\"output.value\", turnText);\n turnRoot.setStatus({ code: SpanStatusCode.OK });\n turnRoot.end();\n turnRoot = null;\n turnCtx = null;\n };\n\n try {\n for await (const message of stream) {\n if (message?.type === \"assistant\") {\n if (options.perTurn) {\n // A new assistant message starts a new turn: any tools still open\n // belong to the previous turn — settle them, then rotate the root.\n for (const span of openTools.values()) span.end();\n openTools.clear();\n endTurn();\n turnIndex += 1;\n turnText = \"\";\n turnRoot = tracer.startSpan(`${options.name} · turn ${turnIndex}`, {\n root: true,\n attributes: {\n \"openinference.span.kind\": \"AGENT\",\n ...(pendingTurnInput\n ? { \"input.value\": pendingTurnInput.slice(0, TURN_INPUT_MAX) }\n : {}),\n ...(options.attributes ?? {}),\n },\n });\n turnCtx = trace.setSpan(context.active(), turnRoot);\n pendingTurnInput = \"\";\n }\n const childCtx = (options.perTurn ? turnCtx : rootCtx)!;\n\n let text = \"\";\n const toolUses: Array<{ id: string; name: string; input: unknown }> =\n [];\n for (const block of message.message?.content ?? []) {\n if (block?.type === \"text\") {\n finalText += block.text;\n text += block.text;\n }\n if (block?.type === \"tool_use\") {\n toolUses.push({\n id: block.id,\n name: block.name,\n input: block.input,\n });\n }\n }\n turnText += text;\n\n const gen = tracer.startSpan(\n \"assistant\",\n {\n attributes: {\n \"openinference.span.kind\": \"LLM\",\n \"llm.model_name\": model,\n \"llm.provider\": \"anthropic\",\n \"output.value\":\n text ||\n toolUses.map((t) => `→ ${cleanToolName(t.name)}`).join(\", \"),\n },\n },\n childCtx,\n );\n const usage = message.message?.usage;\n if (usage?.input_tokens != null)\n gen.setAttribute(\"llm.token_count.prompt\", usage.input_tokens);\n if (usage?.output_tokens != null)\n gen.setAttribute(\"llm.token_count.completion\", usage.output_tokens);\n gen.end();\n\n for (const t of toolUses) {\n const span = tracer.startSpan(\n `tool.${cleanToolName(t.name)}`,\n {\n attributes: {\n \"openinference.span.kind\": \"TOOL\",\n \"tool.name\": cleanToolName(t.name),\n \"input.value\": JSON.stringify(t.input),\n },\n },\n childCtx,\n );\n openTools.set(t.id, span);\n }\n }\n\n // tool_result (in a `user` message) closes the matching TOOL span, and in\n // per-turn mode also becomes part of the NEXT turn's input.\n if (message?.type === \"user\") {\n const content = message.message?.content;\n if (Array.isArray(content)) {\n for (const block of content) {\n if (block?.type === \"tool_result\") {\n const resultText = toolResultText(block.content);\n const span = openTools.get(block.tool_use_id);\n if (span) {\n span.setAttribute(\"output.value\", resultText);\n span.setStatus({ code: SpanStatusCode.OK });\n span.end();\n openTools.delete(block.tool_use_id);\n }\n if (\n options.perTurn &&\n pendingTurnInput.length < TURN_INPUT_MAX\n ) {\n pendingTurnInput +=\n (pendingTurnInput ? \"\\n\" : \"\") +\n resultText.slice(0, TURN_INPUT_MAX - pendingTurnInput.length);\n }\n }\n }\n }\n }\n\n yield message;\n }\n } finally {\n for (const span of openTools.values()) span.end();\n openTools.clear();\n if (options.perTurn) {\n endTurn();\n } else if (root) {\n root.setAttribute(\"output.value\", finalText);\n root.setStatus({ code: SpanStatusCode.OK });\n root.end();\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoGO,SAAS,aAAa,GAAwC;AACnE,QAAM,QAA4B,CAAC,OAAO;AAC1C,MAAI,EAAE,IAAK,OAAM,KAAK,KAAK;AAC3B,MAAI,EAAE,GAAI,OAAM,KAAK,IAAI;AACzB,MAAI,EAAE,QAAS,OAAM,KAAK,SAAS;AACnC,SAAO;AACT;AAOO,SAAS,MACd,IACAA,OACQ;AACR,QAAM,OAAO,GAAG,IAAI,QAAQ,QAAQ,EAAE;AACtC,QAAM,MAAMA,MAAK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F;AAAA,MACF;AAEA,YAAM;AAAA,IACR;AAAA,EACF,UAAE;AACA,eAAW,QAAQ,UAAU,OAAO,EAAG,MAAK,IAAI;AAChD,cAAU,MAAM;AAChB,QAAI,QAAQ,SAAS;AACnB,cAAQ;AAAA,IACV,WAAW,MAAM;AACf,WAAK,aAAa,gBAAgB,SAAS;AAC3C,WAAK,UAAU,EAAE,MAAM,2BAAe,GAAG,CAAC;AAC1C,WAAK,IAAI;AAAA,IACX;AAAA,EACF;AACF;;;AvB5MO,IAAM,UAAiC;AAAA,EAC5C,GAAG;AAAA,EACH,KAAK,SAAwB,CAAC,GAAG;AAC/B,QAAI,OAAO,sBAAsB,OAAO;AACtC,YAAM,aAAa;AAAA,QACjB,IAAI,wBAAwB;AAAA,QAC5B,GAAI,OAAO,wBAAwB,CAAC;AAAA,MACtC;AACA,aAAsBC,MAAK;AAAA,QACzB,GAAG;AAAA,QACH,sBAAsB;AAAA,MACxB,CAAC;AAAA,IACH;AACA,WAAsBA,MAAK,MAAM;AAAA,EACnC;AACF;","names":["path","context","observe","text","resolve","sleep","state","openWorld","sleep","api","path","pollMs","pad","text","resolve","state","import_node_crypto","text","hex","import_node_crypto","text","import_node_crypto","init","text","fs","path","resolve","text","fs","path","SKIP_DIRS","text","fs","path","BUILD_OUTPUT","fs","path","resolve","import_node_child_process","fs","os","path","client","sleep","import_node_crypto","fs","resolve","flush","import_node_crypto","import_node_zlib","client","isObject","text","ingestLocalToolCalls","importLocalWorldData","checkLocalWorldData","transformRecords","pull","pushRows","trace","fs","os","path","path","text","resolve","openSession","exports","module","context","context","text","clearExperimentContext","fetch","fetch","clearExperimentContext","memory","path","text","identifier","encodeIdentifier","path","runtimeContextPayload","text","safeJson","path","text","safeJson","trace","path","text","import_node_path","isPlainObject","text","resolve","resolve","path","context","qs","path","text","safeJson","path","text","client","readFile","import_node_crypto","fs","path","text","sha256","PAGE_LIMIT","qs","text","trace","import_node_crypto","text","context","import_async_hooks","import_api","init","shutdown","init","debugLog","scores","shutdown","import_api","warn","client","import_api","text","init"]}
|
|
1
|
+
{"version":3,"sources":["../src/worlds/browser.ts","../src/worlds/session.ts","../src/worlds/tasks.ts","../src/worlds/hub.ts","../src/worlds/validate.ts","../src/worlds/describe.ts","../src/cli/platform/worldData/json.ts","../src/worlds/transforms.ts","../src/worlds/redaction.ts","../src/worlds/query.ts","../src/worlds/migrate.ts","../src/cli/router.ts","../src/cli/config.ts","../src/cli/runtime/local.ts","../src/cli/runtime/client.ts","../src/cli/runtime/data.ts","../src/cli/platform/worldData/transform.ts","../src/cli/platform/worldData/batches.ts","../src/cli/platform/worldData/chunker.ts","../src/cli/platform/worldData/push.ts","../src/worlds/ingest.ts","../src/worlds/index.ts","../package.json","../src/index.ts","../src/experiments/assignment.ts","../src/experiments/context.ts","../src/experiments/exposure-logger.ts","../src/experiments/client.ts","../src/experiments/otel.ts","../src/experiments/singleton.ts","../src/context/index.ts","../src/memory/index.ts","../src/personas/index.ts","../src/sessions/index.ts","../src/replay/index.ts","../src/security/index.ts","../src/users/index.ts","../src/scores/index.ts","../src/files/index.ts","../src/traces/index.ts","../src/build/index.ts","../src/tracing/identity.ts","../src/tracing/index.ts","../src/tracing/init.ts","../src/tracing/observe.ts","../src/tracing/instrument.ts","../src/tracing/claude.ts"],"sourcesContent":["import { schemaFromSignature, type WorldToolkit } from \"./session\";\n\n/**\n * A BROWSER ON A WORLD'S UI — the computer-use half of a live session.\n *\n * A session answers on SURFACES. `tools` is always there (the world's own\n * operations over the rendezvous). An api-type world may also answer on\n * `api` (the service itself), `ui` (its dashboard, over the same state) and\n * `browser` — a headless Chromium the platform runs NEXT TO that UI, which\n * an agent drives through Playwright. This file is the TS client for the\n * last two, call for call with `gatewaysdk/world_browser.py`.\n *\n * const s = await openSession(\"payments-like\", \"refund-dispute\", {\n * surfaces: [\"ui\", \"browser\"],\n * });\n * await s.ready();\n * const b = await s.browser(); // hosted, next to the world\n * await b.goto(); // the UI's entry page\n * await b.click(\"text=Refund\");\n * const tools = computerUseToolkit(b); // the same actions as model tools\n * await b.close();\n *\n * Playwright is an OPTIONAL peer: nothing here imports it until a browser is\n * opened, so sessions that never touch a UI never load it.\n *\n * MODES. `hosted` connects to the session's own browser (a Playwright server\n * the pod exposes over an authenticated websocket). `local` launches Chromium\n * on this machine and points it at the UI — a laptop against a hosted twin,\n * or a test. `auto` prefers hosted. Asking for a mode the session cannot\n * serve throws `WorldSurfaceUnavailable`; there is no silent fallback to a\n * browser other than the one the episode is judged on.\n *\n * OBSERVABILITY. Every action a `WorldBrowser` takes (goto, click, type,\n * press, scroll, back) is reported to the platform as one event — what was\n * done, whether it worked, where the page ended up, and a JPEG of the screen\n * after — through a `BrowserActionRecorder`. Reporting is fire-and-forget\n * and never fails the action; the platform renders it as the session's\n * browser timeline. Text typed into secret-looking fields is redacted before\n * it leaves the process.\n */\n\nexport const SURFACE_KINDS = [\"tools\", \"api\", \"ui\", \"browser\"] as const;\nexport type WorldSurfaceKind = (typeof SURFACE_KINDS)[number];\n\nexport const DEFAULT_VIEWPORT = { width: 1280, height: 800 };\nconst SETTLE_TIMEOUT_MS = 5_000;\nconst SETTLE_QUIET_MS = 150;\nconst SETTLE_POLL_MS = 25;\n\nexport const EVENT_BATCH_SIZE = 10;\nexport const EVENT_FLUSH_INTERVAL_MS = 1_000;\nexport const EVENT_MAX_RETRIES = 3;\nconst EVENT_SCREENSHOT_QUALITY = 60;\nconst EVENT_MAX_STRING = 500;\n\nconst SECRET_KEY =\n /pass(word|wd)?|secret|token|api[-_]?key|authorization|cookie|(^|[-_ #.\\[\"'=])(otp|pin|cvv|ssn)([-_ \\]\"']|$)/i;\nconst SECRET_VALUE =\n /^((sk|pk|ghp|xox[abp])[-_][-_A-Za-z0-9]{8,}|AKIA[0-9A-Z]{12,}|Bearer [-_.A-Za-z0-9]{8,})/;\n\n/** The `surfaces` block of a session descriptor, as the platform sends it. */\nexport type SessionSurfaces = {\n tools: { kind: \"rendezvous\" };\n api?: {\n url: string;\n /** Per-session credential of a World Host session: send it as\n * `Authorization: Bearer <token>` (the header only; a token in the URL is\n * refused). Absent when the world\n * itself answers with its declared auth (a pod or a customer-hosted twin). */\n token?: string;\n };\n ui?: {\n url: string;\n entry: string;\n /** Same-origin prefix the UI proxies to the world API, e.g. `/__world-api`;\n * null when the UI only reaches the API server-side. */\n apiPath?: string | null;\n /** Per-session credential of a World Host UI. A browser navigation cannot\n * carry a header, so the first page load presents it once as `?token=`\n * and the host answers with an HttpOnly cookie. Absent for pod UIs. */\n token?: string;\n };\n browser?: {\n wsUrl: string;\n /** `cdp`: the platform's Chromium relay (any number of agents share one\n * browser, each in its own context). `playwright`: a `run-server` endpoint. */\n protocol: \"cdp\" | \"playwright\";\n viewport: { width: number; height: number };\n };\n};\n\nexport class WorldSurfaceUnavailable extends Error {\n constructor(\n readonly surface: WorldSurfaceKind,\n reason: string,\n ) {\n super(`World surface '${surface}' is unavailable: ${reason}`);\n }\n}\n\nexport function surfaceKinds(s: SessionSurfaces): WorldSurfaceKind[] {\n const kinds: WorldSurfaceKind[] = [\"tools\"];\n if (s.api) kinds.push(\"api\");\n if (s.ui) kinds.push(\"ui\");\n if (s.browser) kinds.push(\"browser\");\n return kinds;\n}\n\nconst UI_TOKEN_QUERY = \"token\";\n\n/** The URL of `path` on a UI surface, carrying the session token when the\n * surface has one. `path` may already have a query string; the token is\n * appended to it. */\nexport function uiUrl(\n ui: NonNullable<SessionSurfaces[\"ui\"]>,\n path: string,\n): string {\n const base = ui.url.replace(/\\/+$/, \"\");\n const rel = path.startsWith(\"/\") ? path : `/${path}`;\n if (!ui.token) return base + rel;\n const [beforeHash, hash] = splitHash(rel);\n const joiner = beforeHash.includes(\"?\") ? \"&\" : \"?\";\n const query = `${UI_TOKEN_QUERY}=${encodeURIComponent(ui.token)}`;\n return base + beforeHash + joiner + query + hash;\n}\n\nexport function uiEntryUrl(ui: NonNullable<SessionSurfaces[\"ui\"]>): string {\n return uiUrl(ui, ui.entry || \"/\");\n}\n\n/** `url` without its `token` query parameter: what may be logged or shown. */\nexport function withoutUiToken(url: string): string {\n const [beforeHash, hash] = splitHash(url);\n const q = beforeHash.indexOf(\"?\");\n if (q < 0) return url;\n const kept = beforeHash\n .slice(q + 1)\n .split(\"&\")\n .filter((pair) => pair !== \"\" && pair.split(\"=\")[0] !== UI_TOKEN_QUERY);\n return (\n beforeHash.slice(0, q) + (kept.length ? `?${kept.join(\"&\")}` : \"\") + hash\n );\n}\n\nfunction splitHash(url: string): [string, string] {\n const h = url.indexOf(\"#\");\n return h < 0 ? [url, \"\"] : [url.slice(0, h), url.slice(h)];\n}\n\n/** The slice of a Playwright `Page` this module drives. */\nexport type BrowserPage = {\n url(): string;\n goto(url: string, opts?: { waitUntil?: \"load\" }): Promise<unknown>;\n click(selector: string): Promise<void>;\n fill(selector: string, value: string): Promise<void>;\n screenshot(opts?: {\n type?: \"png\" | \"jpeg\";\n quality?: number;\n fullPage?: boolean;\n }): Promise<Buffer>;\n innerText(selector: string): Promise<string>;\n content(): Promise<string>;\n goBack(opts?: { waitUntil?: \"load\" }): Promise<unknown>;\n waitForLoadState(state?: \"load\"): Promise<void>;\n waitForTimeout(ms: number): Promise<void>;\n on(\n event: \"request\" | \"requestfinished\" | \"requestfailed\",\n handler: (request: unknown) => void,\n ): unknown;\n title(): Promise<string>;\n keyboard: { press(key: string): Promise<void> };\n mouse: { wheel(dx: number, dy: number): Promise<void> };\n};\n\nexport type BrowserMode = \"auto\" | \"hosted\" | \"local\";\n\n// ── action events ────────────────────────────────────────────────────────────\n\n/** One browser action as the platform ingests it\n * (`POST /world-sessions/{id}/browser-events`). */\nexport type BrowserActionEvent = {\n agentId: string;\n seq: number;\n ts: string;\n action: string;\n args: Record<string, unknown>;\n ok: boolean;\n error: string | null;\n durationMs: number;\n url: string | null;\n title: string | null;\n mode: Exclude<BrowserMode, \"auto\">;\n viewport: { width: number; height: number };\n /** base64 JPEG of the screen after the action; null if it could not be taken. */\n screenshot: string | null;\n};\n\n/** What of an action's arguments may leave the process. Selectors, paths\n * and keys are what a reviewer needs; anything keyed like a credential, or\n * typed into a field whose selector names one, or shaped like a known key,\n * is replaced. Strings are capped, nested values dropped. */\nexport function redactActionArgs(\n action: string,\n args: Record<string, unknown>,\n): Record<string, unknown> {\n const secretField =\n action === \"browser_type\" && SECRET_KEY.test(String(args.selector ?? \"\"));\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(args)) {\n if (value === null || value === undefined) out[key] = null;\n else if (typeof value === \"boolean\" || typeof value === \"number\")\n out[key] = value;\n else if (typeof value === \"string\") {\n if (\n SECRET_KEY.test(key) ||\n SECRET_VALUE.test(value) ||\n (secretField && key === \"text\")\n )\n out[key] = \"[redacted]\";\n else\n out[key] =\n value.length <= EVENT_MAX_STRING\n ? value\n : value.slice(0, EVENT_MAX_STRING) + \"…\";\n } else out[key] = \"[omitted]\";\n }\n return out;\n}\n\n/**\n * Ships browser action events to the platform, off the action's hot path.\n *\n * `post` receives a batch of events (the request body's `events`). Events\n * are numbered here, so ordering survives batching and retries — the\n * platform dedups on `(agentId, seq)`. A batch that keeps failing is dropped\n * with a warning: telemetry must never stall or fail the agent.\n *\n * Numbering is durable across recorders: `nextSeq()` hands out a position\n * within this recorder, and the first send adds the base `resumeFrom`\n * reports — the platform's next free seq for this agent — so an agent id\n * reopened in a later process appends to its timeline instead of colliding\n * with (and being deduplicated against) what it already recorded. The base\n * is fixed once resolved, which keeps retries idempotent.\n */\nexport class BrowserActionRecorder {\n private seq = 0;\n private base: Promise<number> | null = null;\n private queue: BrowserActionEvent[] = [];\n private timer: ReturnType<typeof setTimeout> | null = null;\n private inflight: Promise<void> = Promise.resolve();\n sent = 0;\n dropped = 0;\n\n constructor(\n private readonly post: (events: BrowserActionEvent[]) => Promise<void>,\n readonly agentId: string,\n private readonly opts: {\n /** The platform's next free seq for `agentId`; 0 when not given. */\n resumeFrom?: () => Promise<number>;\n batchSize?: number;\n flushIntervalMs?: number;\n maxRetries?: number;\n sleep?: (ms: number) => Promise<void>;\n warn?: (message: string) => void;\n } = {},\n ) {}\n\n /** This recorder's next position; the wire seq is `resumeFrom() + this`. */\n nextSeq(): number {\n return this.seq++;\n }\n\n private resolveBase(): Promise<number> {\n if (this.base === null) {\n const resolve = this.opts.resumeFrom ?? (async () => 0);\n this.base = resolve().then((n) => {\n if (!Number.isInteger(n) || n < 0)\n throw new Error(\n `browser event base seq must be a non-negative integer, got ${String(n)}`,\n );\n return n;\n });\n // A failed lookup is retried with the batch, not remembered.\n this.base.catch(() => {\n this.base = null;\n });\n }\n return this.base;\n }\n\n record(event: BrowserActionEvent): void {\n this.queue.push(event);\n if (this.queue.length >= (this.opts.batchSize ?? EVENT_BATCH_SIZE)) {\n this.drain();\n } else if (this.timer === null) {\n this.timer = setTimeout(\n () => this.drain(),\n this.opts.flushIntervalMs ?? EVENT_FLUSH_INTERVAL_MS,\n );\n if (typeof this.timer === \"object\" && \"unref\" in this.timer)\n this.timer.unref();\n }\n }\n\n /** Resolve once everything recorded so far has been posted (or dropped). */\n async flush(): Promise<void> {\n this.drain();\n await this.inflight;\n }\n\n async close(): Promise<void> {\n await this.flush();\n }\n\n private drain(): void {\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n if (this.queue.length === 0) return;\n const batch = this.queue;\n this.queue = [];\n this.inflight = this.inflight.then(() => this.send(batch));\n }\n\n private async send(batch: BrowserActionEvent[]): Promise<void> {\n const retries = this.opts.maxRetries ?? EVENT_MAX_RETRIES;\n const sleep =\n this.opts.sleep ??\n ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));\n for (let attempt = 0; attempt < retries; attempt++) {\n try {\n const base = await this.resolveBase();\n await this.post(\n base === 0 ? batch : batch.map((e) => ({ ...e, seq: base + e.seq })),\n );\n this.sent += batch.length;\n return;\n } catch (error) {\n if (attempt + 1 === retries) {\n this.dropped += batch.length;\n (this.opts.warn ?? console.warn)(\n `dropping ${batch.length} browser events after ${attempt + 1} attempts: ${String(error)}`,\n );\n return;\n }\n await sleep(500 * 2 ** attempt);\n }\n }\n }\n}\n\n/**\n * One Playwright page on the session's UI. Thin on purpose — `page` is the\n * real Playwright page for anything this wrapper does not cover.\n */\nexport class WorldBrowser {\n constructor(\n readonly page: BrowserPage,\n readonly ui: SessionSurfaces[\"ui\"] | undefined,\n readonly mode: Exclude<BrowserMode, \"auto\">,\n private readonly teardown: () => Promise<void>,\n readonly viewport: { width: number; height: number } = DEFAULT_VIEWPORT,\n readonly recorder: BrowserActionRecorder | null = null,\n ) {\n page.on(\"request\", () => {\n this.inflight += 1;\n this.lastNetwork = Date.now();\n });\n const done = () => {\n this.inflight = Math.max(0, this.inflight - 1);\n this.lastNetwork = Date.now();\n };\n page.on(\"requestfinished\", done);\n page.on(\"requestfailed\", done);\n }\n\n private inflight = 0;\n private lastNetwork = Date.now();\n\n get agentId(): string | null {\n return this.recorder?.agentId ?? null;\n }\n\n /** Run one action and report it: the event carries what was asked,\n * whether it worked, and the screen after — for failures too, so a\n * reviewer sees what the agent saw when the selector did not match. */\n private async act<T>(\n action: string,\n args: Record<string, unknown>,\n fn: () => Promise<T>,\n ): Promise<T> {\n const recorder = this.recorder;\n if (!recorder) return fn();\n const started = Date.now();\n let ok = true;\n let error: string | null = null;\n try {\n return await fn();\n } catch (err) {\n ok = false;\n error = (\n err instanceof Error ? `${err.name}: ${err.message}` : String(err)\n ).slice(0, 4000);\n throw err;\n } finally {\n recorder.record({\n agentId: recorder.agentId,\n seq: recorder.nextSeq(),\n ts: new Date().toISOString(),\n action,\n args: redactActionArgs(action, args),\n ok,\n error,\n durationMs: Date.now() - started,\n mode: this.mode,\n viewport: { ...this.viewport },\n ...(await this.observeForEvent()),\n });\n }\n }\n\n private async observeForEvent(): Promise<\n Pick<BrowserActionEvent, \"url\" | \"title\" | \"screenshot\">\n > {\n const out: Pick<BrowserActionEvent, \"url\" | \"title\" | \"screenshot\"> = {\n url: null,\n title: null,\n screenshot: null,\n };\n try {\n out.url = this.page.url();\n out.title = await this.page.title();\n const jpeg = await this.page.screenshot({\n type: \"jpeg\",\n quality: EVENT_SCREENSHOT_QUALITY,\n });\n out.screenshot = jpeg.toString(\"base64\");\n } catch {\n // a closed page still gets its event\n }\n return out;\n }\n\n /** Open a UI path (`/customers`), a full URL, or — with no argument — the\n * UI's declared entry page. */\n async goto(pathOrUrl?: string): Promise<string> {\n let target: string;\n if (pathOrUrl === undefined) {\n if (!this.ui)\n throw new WorldSurfaceUnavailable(\n \"ui\",\n \"this session has no UI to navigate to\",\n );\n target = uiEntryUrl(this.ui);\n } else if (/^https?:\\/\\//.test(pathOrUrl)) {\n target = pathOrUrl;\n } else {\n if (!this.ui)\n throw new WorldSurfaceUnavailable(\n \"ui\",\n \"relative paths need a UI surface\",\n );\n target = uiUrl(this.ui, pathOrUrl);\n }\n return this.act(\n \"browser_goto\",\n { path: pathOrUrl ?? null, url: withoutUiToken(target) },\n async () => {\n await this.page.goto(target, { waitUntil: \"load\" });\n await this.settle();\n return this.page.url();\n },\n );\n }\n\n async back(): Promise<string> {\n return this.act(\"browser_back\", {}, async () => {\n await this.page.goBack({ waitUntil: \"load\" });\n await this.settle();\n return this.page.url();\n });\n }\n\n /** Wait for the page to finish reacting to an action. `load` alone is not\n * enough for client-rendered UIs (React et al.): a click returns before the\n * fetch that re-renders the page, so an agent would read stale text.\n * Playwright's `networkidle` is per navigation and resolves at once after\n * the first one, so this tracks requests itself: done when nothing is in\n * flight and the network has been quiet for `SETTLE_QUIET_MS`, bounded so\n * long-polling UIs cannot hang us. */\n private async settle(): Promise<void> {\n await this.page.waitForLoadState(\"load\");\n const deadline = Date.now() + SETTLE_TIMEOUT_MS;\n while (Date.now() < deadline) {\n const quiet = Date.now() - this.lastNetwork >= SETTLE_QUIET_MS;\n if (this.inflight === 0 && quiet) return;\n await this.page.waitForTimeout(SETTLE_POLL_MS);\n }\n }\n\n async click(selector: string): Promise<void> {\n await this.act(\"browser_click\", { selector }, async () => {\n await this.page.click(selector);\n await this.settle();\n });\n }\n\n async type(selector: string, text: string): Promise<void> {\n await this.act(\"browser_type\", { selector, text }, () =>\n this.page.fill(selector, text),\n );\n }\n\n async press(key: string): Promise<void> {\n await this.act(\"browser_press\", { key }, async () => {\n await this.page.keyboard.press(key);\n await this.settle();\n });\n }\n\n async scroll(dy: number): Promise<void> {\n await this.act(\"browser_scroll\", { dy }, () =>\n this.page.mouse.wheel(0, dy),\n );\n }\n\n async screenshot(fullPage = false): Promise<Buffer> {\n return this.page.screenshot({ type: \"png\", fullPage });\n }\n\n async screenshotBase64(fullPage = false): Promise<string> {\n return (await this.screenshot(fullPage)).toString(\"base64\");\n }\n\n async text(selector = \"body\"): Promise<string> {\n return this.page.innerText(selector);\n }\n\n async html(): Promise<string> {\n return this.page.content();\n }\n\n get url(): string {\n return this.page.url();\n }\n\n async title(): Promise<string> {\n return this.page.title();\n }\n\n async close(): Promise<void> {\n try {\n await this.teardown();\n } finally {\n await this.recorder?.close();\n }\n }\n}\n\n/** The Playwright entry points this module needs, so tests can inject a fake. */\nexport type PlaywrightLike = {\n chromium: {\n connect(wsEndpoint: string): Promise<PlaywrightBrowserLike>;\n connectOverCDP(endpointURL: string): Promise<PlaywrightBrowserLike>;\n launch(opts?: { headless?: boolean }): Promise<PlaywrightBrowserLike>;\n };\n};\n\nexport type PlaywrightBrowserLike = {\n newContext(opts?: {\n viewport?: { width: number; height: number };\n }): Promise<{ newPage(): Promise<BrowserPage>; close(): Promise<void> }>;\n close(): Promise<void>;\n};\n\nasync function loadPlaywright(): Promise<PlaywrightLike> {\n try {\n // A string specifier keeps bundlers from resolving the optional peer.\n const name = \"playwright\";\n return (await import(name)) as PlaywrightLike;\n } catch (error) {\n throw new Error(\n \"Driving a world UI needs Playwright: npm install playwright \" +\n \"(and `npx playwright install chromium` for local mode).\",\n { cause: error },\n );\n }\n}\n\nexport function resolveBrowserMode(\n surfaces: SessionSurfaces,\n mode: BrowserMode,\n): Exclude<BrowserMode, \"auto\"> {\n if (!surfaces.ui && !surfaces.browser)\n throw new WorldSurfaceUnavailable(\n \"ui\",\n \"open the session with surfaces: ['ui'] on a world that declares [ui]\",\n );\n const resolved =\n mode === \"auto\" ? (surfaces.browser ? \"hosted\" : \"local\") : mode;\n if (resolved === \"hosted\" && !surfaces.browser)\n throw new WorldSurfaceUnavailable(\n \"browser\",\n \"open the session with surfaces: ['browser'] to get a hosted browser\",\n );\n return resolved;\n}\n\n/** Open a browser on the session's UI in `hosted`, `local` or `auto` mode. */\nexport async function openBrowser(\n surfaces: SessionSurfaces,\n opts: {\n mode?: BrowserMode;\n headless?: boolean;\n playwright?: PlaywrightLike;\n recorder?: BrowserActionRecorder | null;\n } = {},\n): Promise<WorldBrowser> {\n const mode = resolveBrowserMode(surfaces, opts.mode ?? \"auto\");\n const pw = opts.playwright ?? (await loadPlaywright());\n const viewport = surfaces.browser?.viewport ?? DEFAULT_VIEWPORT;\n const browser =\n mode === \"hosted\"\n ? surfaces.browser!.protocol === \"playwright\"\n ? await pw.chromium.connect(surfaces.browser!.wsUrl)\n : await pw.chromium.connectOverCDP(surfaces.browser!.wsUrl)\n : await pw.chromium.launch({ headless: opts.headless ?? true });\n const context = await browser.newContext({ viewport });\n const page = await context.newPage();\n return new WorldBrowser(\n page,\n surfaces.ui,\n mode,\n async () => {\n await context.close();\n await browser.close();\n },\n viewport,\n opts.recorder ?? null,\n );\n}\n\n// ── computer-use tools ───────────────────────────────────────────────────────\n\nexport const COMPUTER_USE_SPECS = [\n {\n name: \"browser_goto\",\n signature: \"browser_goto(path=None)\",\n doc: \"Open a page of the world's UI. `path` is a UI path like /customers, a full URL, or omitted for the entry page. Returns the URL and page text.\",\n },\n {\n name: \"browser_click\",\n signature: \"browser_click(selector)\",\n doc: \"Click an element by Playwright selector (CSS, `text=Refund`, `role=button[name=Save]`). Returns the page text after the click.\",\n },\n {\n name: \"browser_type\",\n signature: \"browser_type(selector, text)\",\n doc: \"Replace the value of an input/textarea found by selector with `text`.\",\n },\n {\n name: \"browser_press\",\n signature: \"browser_press(key)\",\n doc: \"Press a key (Enter, Tab, Escape, ArrowDown, ...). Returns the page text after.\",\n },\n {\n name: \"browser_scroll\",\n signature: \"browser_scroll(dy=600)\",\n doc: \"Scroll the page vertically by `dy` pixels (negative scrolls up).\",\n },\n {\n name: \"browser_screenshot\",\n signature: \"browser_screenshot(full_page=False)\",\n doc: \"Take a PNG screenshot; returns {image_base64, url}.\",\n },\n {\n name: \"browser_read\",\n signature: \"browser_read(selector='body')\",\n doc: \"Return the visible text of an element (default: whole page) plus the URL and title.\",\n },\n {\n name: \"browser_back\",\n signature: \"browser_back()\",\n doc: \"Go back one page in history.\",\n },\n] as const;\n\nconst str = (v: unknown, fallback: string): string =>\n typeof v === \"string\" && v.length > 0 ? v : fallback;\n\n/**\n * The browser as model tools, in the same `WorldToolkit` shape the world's\n * own tools come in — so an agent loop that already dispatches\n * `toolkit().impls` merges `computerUseToolkit(b).impls` and gains a screen\n * without a second dispatch path.\n */\nexport function computerUseToolkit(\n browser: WorldBrowser,\n opts: { maxText?: number } = {},\n): WorldToolkit {\n const maxText = opts.maxText ?? 20_000;\n const observe = async (selector = \"body\") => {\n const text = await browser.text(selector);\n return {\n url: browser.url,\n title: await browser.title(),\n text: text.slice(0, maxText),\n truncated: text.length > maxText,\n };\n };\n\n const impls: WorldToolkit[\"impls\"] = {\n browser_goto: async (a) => {\n await browser.goto(typeof a.path === \"string\" ? a.path : undefined);\n return observe();\n },\n browser_click: async (a) => {\n await browser.click(str(a.selector, \"\"));\n return observe();\n },\n browser_type: async (a) => {\n await browser.type(str(a.selector, \"\"), String(a.text ?? \"\"));\n return { ok: true, url: browser.url };\n },\n browser_press: async (a) => {\n await browser.press(str(a.key, \"Enter\"));\n return observe();\n },\n browser_scroll: async (a) => {\n await browser.scroll(typeof a.dy === \"number\" ? a.dy : 600);\n return { ok: true, url: browser.url };\n },\n browser_screenshot: async (a) => ({\n image_base64: await browser.screenshotBase64(a.full_page === true),\n url: browser.url,\n }),\n browser_read: async (a) => observe(str(a.selector, \"body\")),\n browser_back: async () => {\n await browser.back();\n return observe();\n },\n };\n\n const specs = COMPUTER_USE_SPECS.map((s) => ({ ...s }));\n return {\n schemas: specs.map((spec) => schemaFromSignature(spec)),\n impls,\n specs,\n };\n}\n","import { randomUUID } from \"node:crypto\";\n\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\nimport {\n BrowserActionRecorder,\n SURFACE_KINDS,\n WorldSurfaceUnavailable,\n computerUseToolkit,\n openBrowser,\n uiEntryUrl,\n type BrowserActionEvent,\n type BrowserMode,\n type PlaywrightLike,\n type SessionSurfaces,\n type WorldBrowser,\n type WorldSurfaceKind,\n} from \"./browser\";\nimport type { WorldTaskSummary } from \"./tasks\";\n\n/**\n * LIVE WORLD SESSIONS from TypeScript: your agent, the platform's container.\n *\n * The other two ways of running a world each give up something. Pulling the\n * bundle and executing it locally tests your agent against a COPY — your\n * python, your sqlite, your machine's idea of the environment. Dispatching a\n * hosted run gives you the real container but runs the platform's agent\n * inside it, so your agent never touches the world.\n *\n * A session is both: the platform boots the task's container and holds it\n * warm, and every `call()` here executes inside THAT container. Your agent\n * stays where it is — this file is just the wire.\n *\n * const world = await openWorld(\"revenue-ops-sim@main\");\n * const session = await openSession(world.slug, { task: \"revops-mara-dedupe-contacts\" });\n * await session.ready(); // wait for the container\n * await session.call(\"crm_search\", { entity: \"deals\" });\n * const { reward, rewards } = await session.grade();\n * await session.close({ keepWarm: true }); // hand it back to the pool\n *\n * The task can also be YOURS rather than the bundle's — an instruction, the\n * rows the session starts with and how it is graded, for one end user:\n *\n * const session = await openSession(\"acme-billing@main\", {\n * task: {\n * instruction: \"Mark invoice INV-7 as paid.\",\n * seed: { rows: { invoices: [{ id: \"INV-7\", status: \"open\" }] } },\n * grader: { kind: \"assertions\", checks: [\n * { entity: \"invoices\", where: { id: \"INV-7\", status: \"paid\" } },\n * ] },\n * metadata: { externalUserId: \"u_42\" },\n * },\n * surfaces: [\"api\"],\n * });\n *\n * Every call is a row on the platform before it is an effect in a container,\n * so the episode is on the record — and the platform traces the session\n * itself, which is why these sessions show up under Sessions without the\n * caller instrumenting anything.\n */\n\nexport type WorldToolSpec = {\n name: string;\n /** The world's own signature, e.g. `crm_search(q=None, entity=\"deals\")`. */\n signature: string;\n doc: string | null;\n inputSchema?: Record<string, unknown>;\n};\n\n/** What a model needs to call a world: the schemas to advertise, and the\n * implementations that run them in the container. */\nexport type WorldToolkit = {\n /** OpenAI-shaped tool definitions, derived from the world's signatures. */\n schemas: {\n type: \"function\";\n function: {\n name: string;\n description: string;\n parameters: Record<string, unknown>;\n };\n }[];\n /** name -> implementation, each one a call into THIS session. */\n impls: Record<string, (args: Record<string, unknown>) => Promise<unknown>>;\n specs: WorldToolSpec[];\n};\n\n// ── tasks ────────────────────────────────────────────────────────────────────\n\n/** A JSON scalar: what `where` filters and field predicates compare against. */\nexport type WorldTaskScalar = string | number | boolean | null;\n\n/** The rows a task starts the session with — the `seed()` contract, applied\n * by the host right after it clones the version's snapshot. `append`\n * (default) upserts by primary key onto the base data; `replace` makes the\n * named entities hold exactly these rows. */\nexport type WorldTaskSeed = {\n mode?: \"append\" | \"replace\";\n /** Redaction on the way in: `off` (default) stores the rows as given,\n * `apply` runs the world's `[redact]` policy over them first, `refuse`\n * rejects a row carrying plaintext in a redacted field. */\n redact?: \"off\" | \"apply\" | \"refuse\";\n rows: Record<string, Record<string, unknown>[]>;\n};\n\nexport type WorldTaskFieldOp =\n \"eq\" | \"neq\" | \"in\" | \"gt\" | \"gte\" | \"lt\" | \"lte\" | \"contains\";\n\n/**\n * One declarative check over the session's final rows. `where` selects rows\n * of `entity` by equality (dotted paths reach into nested objects); the\n * assertion says what must hold of the selection:\n *\n * exists (default) / absent at least one row / none\n * count `count` bound on how many\n * all / any `field op value` on every / some selected row\n *\n * A check's `id` names its entry in `rewards`; the task's reward is the\n * weighted share of checks that passed.\n */\nexport type WorldTaskCheck = {\n id?: string;\n weight?: number;\n entity: string;\n where?: Record<string, WorldTaskScalar>;\n assert?: \"exists\" | \"absent\" | \"count\" | \"all\" | \"any\";\n count?: { eq?: number; gte?: number; lte?: number };\n field?: string;\n op?: WorldTaskFieldOp;\n value?: WorldTaskScalar | WorldTaskScalar[];\n};\n\n/** One thing a rubric judge scores in [0, 1]; `id` names its entry in\n * `rewards`, `weight` (default 1) its share of the task's reward. */\nexport type WorldTaskRubricCriterion = {\n id: string;\n description: string;\n weight?: number;\n};\n\n/** A rubric is prose: what a good outcome looks like. The platform (never the\n * host) has a model read the session's final state and its call log against\n * it; the project's default evaluation model judges unless `model` pins one.\n * `grade()` then resolves asynchronously — `pending: true` first, the reward\n * once the judge has answered. */\nexport type WorldTaskRubricGrader = {\n kind: \"rubric\";\n rubric: string;\n criteria?: WorldTaskRubricCriterion[];\n model?: { provider: string; model: string };\n};\n\n/** How a task is graded: checks the host evaluates in-process, a `verify.py`\n * body (state JSON on stdin, last stdout line `{reward, ...}`) run through the\n * host's confined verifier, or a rubric judged by a model on the platform. */\nexport type WorldTaskGrader =\n | { kind: \"assertions\"; checks: WorldTaskCheck[] }\n | { kind: \"python\"; source: string; timeoutSeconds?: number }\n | WorldTaskRubricGrader;\n\n/** A task supplied at open, for one session, instead of a bundled scenario.\n * `instruction` is what the agent is told; without `seed` the session starts\n * on the version's base data, without `grader` `grade()` answers\n * `reward: null`; `tools` is the allow-list of the version's tools the agent\n * may call in this session (unset: all of them; a call outside it is refused\n * and logged); `metadata` is yours (an end-user id, a ticket) and is echoed\n * on the session, never read. Limits: shared/domain/worldTasks.ts. */\nexport type WorldTaskSpec = {\n name?: string;\n instruction: string;\n seed?: WorldTaskSeed;\n grader?: WorldTaskGrader;\n tools?: string[];\n metadata?: Record<string, unknown>;\n};\n\n/** A stored task of the project (see worlds/tasks.ts), opened by id; the\n * session runs a copy of one version's spec — the current one by default. */\nexport type WorldTaskIdRef = { id: string; version?: number };\n\n/** What `openSession` takes as the task: a bundled scenario's name, a\n * stored task's `{ id, version? }`, or an inline spec. */\nexport type WorldTaskRef = string | WorldTaskIdRef | WorldTaskSpec;\n\n/** What a session's task is, on every session response. `hash` is the\n * content hash of the spec (inline or stored) — what warm reuse matches on;\n * `id`/`version` name the stored task the session was opened on. */\nexport type WorldSessionTask = {\n source: \"bundled\" | \"inline\" | \"stored\";\n name: string | null;\n hash: string | null;\n id?: string | null;\n version?: number | null;\n metadata: Record<string, unknown>;\n};\n\nexport const isTaskIdRef = (task: WorldTaskRef): task is WorldTaskIdRef =>\n typeof task === \"object\" && task !== null && \"id\" in task;\n\nexport const isTaskSpec = (task: WorldTaskRef): task is WorldTaskSpec =>\n typeof task === \"object\" && task !== null && \"instruction\" in task;\n\n/** The label a task goes by in results: its name, `inline:<hash>` for an\n * unnamed inline task once the platform has hashed it, or the stored task's\n * name (its id until the platform has answered). */\nexport const taskLabel = (\n task: WorldTaskRef,\n info?: WorldSessionTask | null,\n): string => {\n if (typeof task === \"string\") return task;\n if (isTaskIdRef(task)) return info?.name ?? task.id;\n if (task.name) return task.name;\n return info?.hash ? `inline:${info.hash.slice(0, 12)}` : \"inline\";\n};\n\nexport type SeedResult = {\n seeded: number;\n mode: \"append\" | \"replace\";\n entity_counts: Record<string, number>;\n};\n\n/** One row of the session's call log. */\nexport type WorldSessionCall = {\n seq: number;\n kind: string;\n tool: string | null;\n args: unknown;\n result: unknown;\n error: string | null;\n completedAt: string | null;\n};\n\nexport type WorldSessionState = {\n sessionId: string;\n state: string;\n ready: boolean;\n versionId: string;\n contentHash: string;\n taskName: string | null;\n /** Where the task came from and what it is; absent on platforms that\n * predate session tasks, in which case it is derived from `taskName`. */\n task?: WorldSessionTask;\n /** The task's objective — present when the session was opened (not on a\n * bare status read), so a client never needs the bundle on disk. */\n instruction?: string | null;\n /** The tools this task serves. */\n tools?: WorldToolSpec[];\n /** Where the session answers besides `tools` — see worlds/browser.ts. */\n surfaces?: SessionSurfaces;\n /** Notices about the world's shape (an api bundle is a deprecated layout;\n * schema worlds are the supported shape), with what to run instead. Empty\n * for a schema world; absent on platforms that predate the notice. */\n deprecations?: WorldDeprecation[];\n};\n\n/** One notice a worlds-path answer carries: a deprecated shape or layout\n * and the command that replaces it. A retired shape is refused instead,\n * with the stable message prefix `world_kind_retired:`. */\nexport type WorldDeprecation = {\n code: string;\n message: string;\n replacement: string;\n};\n\nexport type GradeResult = {\n reward: number | null;\n rewards: Record<string, number>;\n raw: unknown;\n};\n\n/** How long `ready()` waits, and how often it asks. */\nconst READY_TIMEOUT_MS = 10 * 60_000;\nconst READY_POLL_MS = 2_000;\n/** How long one call may take end to end (container claim + execution). */\nconst CALL_TIMEOUT_MS = 3 * 60_000;\nconst CALL_POLL_MS = 400;\n/** How long a grade the platform's judge finalizes may take: the model's own\n * timeout and retries, plus the worker's queue backoff. Polled slowly. */\nconst JUDGED_GRADE_TIMEOUT_MS = 15 * 60_000;\nconst JUDGED_GRADE_POLL_MS = 2_000;\nconst EXPORT_PAGE = 500;\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\nconst modelToolName = (name: string): string =>\n name.replace(/[^A-Za-z0-9_-]/g, \"_\").slice(0, 64) || \"tool\";\n\n/**\n * Turn a world's Python signature into a JSON schema the model can call.\n *\n * `crm_update_deal(id, stage=None, owner=None, amount=None)` becomes an\n * object with `id` required and the rest optional. Types are read from the\n * DEFAULTS the world declares — a numeric default means a number, a boolean\n * default a boolean — because that is the only type information a signature\n * actually carries. Everything else is a string, which is what a tool CLI\n * receives anyway.\n */\nexport function schemaFromSignature(spec: WorldToolSpec): {\n type: \"function\";\n function: {\n name: string;\n description: string;\n parameters: Record<string, unknown>;\n };\n} {\n if (spec.inputSchema)\n return {\n type: \"function\",\n function: {\n name: modelToolName(spec.name),\n description: spec.doc ?? spec.name,\n parameters: spec.inputSchema,\n },\n };\n const inside = /\\(([\\s\\S]*)\\)\\s*$/.exec(spec.signature.trim())?.[1] ?? \"\";\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n // Split on top-level commas only: a default like `{\"a\": 1}` has its own.\n const params: string[] = [];\n let depth = 0;\n let current = \"\";\n for (const ch of inside) {\n if (\"([{\".includes(ch)) depth++;\n if (\")]}\".includes(ch)) depth--;\n if (ch === \",\" && depth === 0) {\n params.push(current);\n current = \"\";\n } else current += ch;\n }\n if (current.trim()) params.push(current);\n\n for (const raw of params) {\n const param = raw.trim();\n if (!param || param.startsWith(\"*\") || param === \"self\") continue;\n const eq = param.indexOf(\"=\");\n const name = (eq === -1 ? param : param.slice(0, eq)).split(\":\")[0].trim();\n if (!name) continue;\n if (eq === -1) {\n properties[name] = { type: \"string\" };\n required.push(name);\n continue;\n }\n const value = param.slice(eq + 1).trim();\n if (/^-?\\d+(\\.\\d+)?$/.test(value)) properties[name] = { type: \"number\" };\n else if (value === \"True\" || value === \"False\")\n properties[name] = { type: \"boolean\" };\n else properties[name] = { type: \"string\" };\n }\n return {\n type: \"function\",\n function: {\n name: modelToolName(spec.name),\n description: spec.doc ?? spec.name,\n parameters: { type: \"object\", properties, required },\n },\n };\n}\n\nexport class WorldSessionTimeout extends Error {}\nexport class WorldSessionCallError extends Error {}\n\nexport class WorldSession {\n constructor(\n readonly sessionId: string,\n private current: WorldSessionState,\n private readonly options: WorldsClientOptions,\n ) {}\n\n /** The task's display name: a bundled scenario's, or the inline spec's\n * `name` (null when the spec was unnamed). Same as `taskName`. */\n get task(): string | null {\n return this.current.taskName;\n }\n\n /** The task's display name: a bundled scenario's, or the inline spec's\n * `name` (null when the spec was unnamed). */\n get taskName(): string | null {\n return this.current.taskName;\n }\n\n /** The platform's notices about the world this session runs on (empty\n * for a schema world). Printed by the CLI on stderr at open. */\n get deprecations(): WorldDeprecation[] {\n return this.current.deprecations ?? [];\n }\n\n /** The task this session runs: bundled scenario, stored task or inline\n * spec, its name, hash and the caller's metadata. */\n get taskInfo(): WorldSessionTask {\n return (\n this.current.task ?? {\n source: \"bundled\",\n name: this.current.taskName,\n hash: null,\n metadata: {},\n }\n );\n }\n\n /** What this task asks for — the bundle's instruction.md, or the inline\n * spec's `instruction`. */\n get instruction(): string | null {\n return this.current.instruction ?? null;\n }\n\n get versionId(): string {\n return this.current.versionId;\n }\n\n /** Whether the session answered ready as of the last state read (the open,\n * a `status()`, or the poll inside `ready()`); no request is made. */\n get isReady(): boolean {\n return this.current.ready;\n }\n\n /** `api` / `ui` / `browser` are present exactly when the world declares\n * them AND the session was opened asking for them. */\n async surfaces(): Promise<SessionSurfaces> {\n if (!this.current.surfaces) await this.status();\n return this.current.surfaces ?? { tools: { kind: \"rendezvous\" } };\n }\n\n /** Base URL of the world's own HTTP API for this session. */\n async api(): Promise<string> {\n const { api } = await this.surfaces();\n if (!api)\n throw new WorldSurfaceUnavailable(\n \"api\",\n \"open the session with surfaces: ['api'] on an api-type world\",\n );\n return api.url;\n }\n\n /** Headers every request to `api()` needs. A World Host session gates its\n * api surface on a per-session token; a pod or hosted twin answers with the\n * world's own declared auth and this is `{}`. */\n async apiHeaders(): Promise<Record<string, string>> {\n const { api } = await this.surfaces();\n return api?.token ? { Authorization: `Bearer ${api.token}` } : {};\n }\n\n /** URL of the world's UI entry page for this session. */\n async ui(): Promise<string> {\n const { ui } = await this.surfaces();\n if (!ui)\n throw new WorldSurfaceUnavailable(\n \"ui\",\n \"open the session with surfaces: ['ui'] on a world that declares [ui]\",\n );\n return uiEntryUrl(ui);\n }\n\n /** A Playwright browser on this session's UI: `hosted` drives the one the\n * platform runs next to the world, `local` launches one here, `auto`\n * prefers hosted. Call `close()` when done.\n *\n * Every action is reported to the platform under `agentId` (default:\n * `GATEWAY_AGENT_ID` or a fresh `agent-<hex>`) so the session page shows\n * this agent's own timeline — several agents may share one session and\n * one hosted browser. `record: false` opts out. */\n async browser(\n opts: {\n mode?: BrowserMode;\n headless?: boolean;\n playwright?: PlaywrightLike;\n agentId?: string;\n record?: boolean;\n } = {},\n ): Promise<WorldBrowser> {\n const { agentId, record = true, ...rest } = opts;\n return openBrowser(await this.surfaces(), {\n ...rest,\n recorder: record ? this.browserRecorder(agentId) : null,\n });\n }\n\n /** The reporter `browser()` uses; exposed for a page you drive yourself. */\n browserRecorder(agentId?: string): BrowserActionRecorder {\n const path = `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/browser-events`;\n const id =\n agentId ??\n process.env.GATEWAY_AGENT_ID ??\n `agent-${randomUUID().replace(/-/g, \"\").slice(0, 8)}`;\n return new BrowserActionRecorder(\n async (events: BrowserActionEvent[]) => {\n await apiRequest(this.options, \"POST\", path, { events });\n },\n id,\n {\n // Continue this agent's timeline where the platform has it, so the\n // same id reopened later never re-numbers from zero.\n resumeFrom: async () => {\n const summary = await apiRequest<{\n agents: { agentId: string; nextSeq: number }[];\n }>(this.options, \"GET\", path);\n return summary.agents.find((a) => a.agentId === id)?.nextSeq ?? 0;\n },\n },\n );\n }\n\n /** Browser actions as model tools, in the same shape as `toolkit()`. */\n computerUseTools(browser: WorldBrowser): WorldToolkit {\n return computerUseToolkit(browser);\n }\n\n /** The session's latest platform state (one request, no waiting). */\n async status(): Promise<WorldSessionState> {\n const fresh = await apiRequest<WorldSessionState>(\n this.options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}`,\n );\n // A status read does not carry the objective; keep the one we opened with.\n this.current = {\n instruction: this.current.instruction,\n tools: this.current.tools,\n surfaces: this.current.surfaces,\n task: this.current.task,\n ...fresh,\n };\n return this.current;\n }\n\n /**\n * Wait until the container is warm — meaning the process inside it has\n * asked the platform for work, not merely that a job was accepted.\n */\n async ready(opts: { timeoutMs?: number } = {}): Promise<WorldSessionState> {\n const deadline = Date.now() + (opts.timeoutMs ?? READY_TIMEOUT_MS);\n for (;;) {\n const state = await this.status();\n if (state.ready) return state;\n if (state.state === \"FAILED\" || state.state === \"STOPPED\")\n throw new WorldSessionCallError(\n `World session ${state.state.toLowerCase()} before it was ready.`,\n );\n if (Date.now() > deadline)\n throw new WorldSessionTimeout(\n `World session still ${state.state} after ${Math.round((opts.timeoutMs ?? READY_TIMEOUT_MS) / 1000)}s.`,\n );\n await sleep(READY_POLL_MS);\n }\n }\n\n /** Enqueue one interaction and wait for the container's answer. */\n private async exchange(\n body: {\n kind?: \"call\" | \"grade\" | \"reset\" | \"state\" | \"seed\" | \"close\";\n tool?: string;\n args?: unknown;\n },\n timeoutMs?: number,\n ): Promise<unknown> {\n const enqueued = await apiRequest<{\n callId: string;\n seq: number;\n /** The platform's worker finalizes this call (a rubric grade). */\n pending?: boolean;\n }>(\n this.options,\n \"POST\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/calls`,\n body,\n );\n const { callId } = enqueued;\n const judged = enqueued.pending === true;\n const budgetMs =\n timeoutMs ?? (judged ? JUDGED_GRADE_TIMEOUT_MS : CALL_TIMEOUT_MS);\n const pollMs = judged ? JUDGED_GRADE_POLL_MS : CALL_POLL_MS;\n const deadline = Date.now() + budgetMs;\n for (;;) {\n const call = await apiRequest<{\n done: boolean;\n state: string;\n result: unknown;\n error: string | null;\n }>(\n this.options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/calls/${encodeURIComponent(callId)}`,\n );\n if (call.done) {\n if (call.error) throw new WorldSessionCallError(call.error);\n return call.result;\n }\n if (Date.now() > deadline)\n throw new WorldSessionTimeout(\n judged\n ? `Grade ${callId} still ${call.state} after ${Math.round(budgetMs / 1000)}s — the judge has not answered; the platform finalizes the call on its own, read it back with export().`\n : `Call ${callId} still ${call.state} after ${Math.round(budgetMs / 1000)}s — the container may have died.`,\n );\n await sleep(pollMs);\n }\n }\n\n /**\n * Run one of the world's tools INSIDE the container. The arguments and the\n * result are the world's own contract — this layer neither validates nor\n * reshapes them, so a tool error reads exactly as it would in a hosted run.\n */\n async call(\n tool: string,\n args: Record<string, unknown> = {},\n opts: { timeoutMs?: number } = {},\n ): Promise<unknown> {\n return this.exchange({ kind: \"call\", tool, args }, opts.timeoutMs);\n }\n\n /**\n * THE WORLD'S TOOLS, READY TO HAND TO A MODEL. Schemas come from the\n * world's own signatures and implementations call into this session, so a\n * caller never writes — and never has to re-sync — a tool map of their own:\n *\n * const { schemas, impls } = await session.toolkit();\n * await runMyAgent(impls, schemas, session.instruction);\n *\n * A tool added to the world shows up here on the next run; a tool renamed\n * in the world renames here too, instead of failing at call time against a\n * hand-written map that still remembers the old name.\n */\n async toolkit(): Promise<WorldToolkit> {\n let specs = this.current.tools;\n if (!specs) specs = (await this.status()).tools ?? [];\n const impls: WorldToolkit[\"impls\"] = Object.create(null);\n for (const spec of specs) {\n const alias = modelToolName(spec.name);\n if (Object.hasOwn(impls, alias))\n throw new WorldSessionCallError(`Model tool name collision: ${alias}`);\n impls[alias] = (args: Record<string, unknown> = {}) =>\n this.call(spec.name, args);\n }\n return { schemas: specs.map(schemaFromSignature), impls, specs };\n }\n\n /** Run the task's grader against the container's END STATE. Graders answer\n * in one of two shapes: the scalar with named rewards beside it\n * (`{reward, check_a, check_b}`, a task's own `grade.py`), or the named\n * rewards nested under `rewards` (the api, mock-tools and World Host\n * runners). Both land in `rewards`.\n *\n * A rubric grade is finalized by the platform's judge, not the container:\n * the platform answers the enqueue with `pending: true`, and this waits on\n * the judge's budget (15 min) instead of a call's. `timeoutMs` overrides\n * either. */\n async grade(opts: { timeoutMs?: number } = {}): Promise<GradeResult> {\n const raw = (await this.exchange(\n { kind: \"grade\" },\n opts.timeoutMs,\n )) as Record<string, unknown> | null;\n const record = raw && typeof raw === \"object\" ? raw : {};\n const rewards: Record<string, number> = {};\n const nested = record.rewards;\n if (nested && typeof nested === \"object\") {\n for (const [key, value] of Object.entries(nested)) {\n if (typeof value === \"number\") rewards[key] = value;\n }\n }\n for (const [key, value] of Object.entries(record)) {\n if (key !== \"reward\" && typeof value === \"number\") rewards[key] = value;\n }\n return {\n reward: typeof record.reward === \"number\" ? record.reward : null,\n rewards,\n raw,\n };\n }\n\n /**\n * Put rows into the LIVE world through its contract, in one batch:\n * `append` (default) upserts by primary key, `replace` makes the named\n * entities hold exactly these rows. Atomic — a refused row leaves the\n * session unchanged and the error names the entity, row and field.\n */\n async seed(\n rows: Record<string, Record<string, unknown>[]>,\n opts: {\n mode?: \"append\" | \"replace\";\n /** `apply` runs the world's `[redact]` policy over the rows first;\n * `refuse` rejects plaintext in a redacted field; default `off`. */\n redact?: \"off\" | \"apply\" | \"refuse\";\n timeoutMs?: number;\n } = {},\n ): Promise<SeedResult> {\n const mode = opts.mode ?? \"append\";\n const redact = opts.redact ?? \"off\";\n return (await this.exchange(\n {\n kind: \"seed\",\n args: { mode, rows, ...(redact !== \"off\" ? { redact } : {}) },\n },\n opts.timeoutMs,\n )) as SeedResult;\n }\n\n /** Every entity's rows as the world holds them now — the same dump a\n * grader reads. The shape is the world runtime's: a schema world answers\n * `{<entity>: {<key>: row}, snapshot}`, a mock-tools world\n * `{entities: {<entity>: [row]}}`. */\n async state(opts: { timeoutMs?: number } = {}): Promise<unknown> {\n return this.exchange({ kind: \"state\" }, opts.timeoutMs);\n }\n\n /** Back to the opening state: the version's data plus the bundled\n * scenario's or the inline task's seed. Rows written since are gone; the\n * call log stays. */\n async reset(opts: { timeoutMs?: number } = {}): Promise<void> {\n await this.exchange({ kind: \"reset\" }, opts.timeoutMs);\n }\n\n /** The session's call log, oldest first: every tool call, seed, reset,\n * grade with its result — the record of the episode. */\n async export(): Promise<WorldSessionCall[]> {\n const calls: WorldSessionCall[] = [];\n let cursor: string | undefined;\n do {\n const params = new URLSearchParams({ limit: String(EXPORT_PAGE) });\n if (cursor) params.set(\"cursor\", cursor);\n const page = await apiRequest<{\n calls: Record<string, unknown>[];\n nextCursor?: string | null;\n }>(\n this.options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/calls?${params.toString()}`,\n );\n for (const call of page.calls) {\n calls.push({\n seq: Number(call.seq),\n kind: String(call.kind ?? \"call\"),\n tool: typeof call.tool === \"string\" ? call.tool : null,\n args: call.args ?? null,\n result: call.result ?? null,\n error: typeof call.error === \"string\" ? call.error : null,\n completedAt:\n typeof call.completedAt === \"string\" ? call.completedAt : null,\n });\n }\n cursor = page.nextCursor ?? undefined;\n } while (cursor);\n return calls;\n }\n\n /**\n * Promote this session's inline task into a stored task of the project\n * (version 1, pinned to the session's world unless `world` says otherwise),\n * so a task written for one end user can be reused and its grades\n * compared. The session then records the new task's id. A session on a\n * bundled task has nothing to save; one on a stored task is already saved.\n */\n async saveTask(\n opts: { name?: string; world?: string | null; message?: string } = {},\n ): Promise<WorldTaskSummary> {\n const task = await apiRequest<WorldTaskSummary>(\n this.options,\n \"POST\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/task`,\n {\n ...(opts.name !== undefined ? { name: opts.name } : {}),\n ...(opts.world !== undefined ? { world: opts.world } : {}),\n ...(opts.message !== undefined ? { message: opts.message } : {}),\n },\n );\n this.current = {\n ...this.current,\n taskName: task.name,\n task: {\n ...this.taskInfo,\n source: \"stored\",\n name: task.name,\n id: task.id,\n version: task.version,\n },\n };\n return task;\n }\n\n /**\n * End the session. `keepWarm` hands the container back to the pool instead\n * of tearing it down, so the next session for the same task starts warm —\n * the pooled instance still obeys the fleet's idle TTL and pinning.\n */\n async close(opts: { keepWarm?: boolean } = {}): Promise<{ state: string }> {\n return apiRequest(\n this.options,\n \"DELETE\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}`,\n { keepWarm: opts.keepWarm ?? false },\n );\n }\n}\n\n/**\n * Attach to a session that already exists — resuming after a crash, or\n * driving a session someone else opened (a container started by hand on a\n * self-hosted install, a session opened by CI and handed to a developer).\n */\nexport async function attachSession(\n sessionId: string,\n options: WorldsClientOptions = {},\n): Promise<WorldSession> {\n const state = await apiRequest<WorldSessionState>(\n options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(sessionId)}`,\n );\n return new WorldSession(sessionId, state, options);\n}\n\nexport type OpenSessionOptions = {\n versionId?: string;\n reuseWarm?: boolean;\n /** More than `tools`: `[\"api\"]`, `[\"ui\"]`, `[\"browser\"]`. The platform\n * refuses (HTTP 400) rather than quietly serving less than asked. */\n surfaces?: WorldSurfaceKind[];\n options?: WorldsClientOptions;\n};\n\n/**\n * Open a live session against one task of a world. Returns as soon as the\n * platform has accepted it — call `ready()` to wait for the container.\n *\n * `task` is a bundled scenario's name, a stored task's `{ id, version? }`\n * or an inline `WorldTaskSpec` (the latter two need a host engine world — the\n * platform answers 400 for a pod world). The older positional form\n * `openSession(slug, \"task-name\", opts)` still works.\n */\nexport async function openSession(\n slugOrRef: string,\n task: OpenSessionOptions & { task: WorldTaskRef },\n): Promise<WorldSession>;\nexport async function openSession(\n slugOrRef: string,\n task: WorldTaskRef,\n opts?: OpenSessionOptions,\n): Promise<WorldSession>;\nexport async function openSession(\n slugOrRef: string,\n taskOrOpts: WorldTaskRef | (OpenSessionOptions & { task: WorldTaskRef }),\n positionalOpts: OpenSessionOptions = {},\n): Promise<WorldSession> {\n const { task, ...opts } =\n typeof taskOrOpts === \"object\" && \"task\" in taskOrOpts\n ? taskOrOpts\n : { task: taskOrOpts as WorldTaskRef, ...positionalOpts };\n if (\n task === undefined ||\n task === null ||\n (typeof task === \"string\" && !task) ||\n (isTaskIdRef(task) && !task.id) ||\n (isTaskSpec(task) && !task.instruction) ||\n (typeof task === \"object\" && !isTaskIdRef(task) && !isTaskSpec(task))\n )\n throw new Error(\n \"openSession needs a task: a bundled task name, a stored task { id, version? } or { instruction, seed?, grader?, metadata? }\",\n );\n const options = opts.options ?? {};\n const unknown = (opts.surfaces ?? []).filter(\n (s) => !(SURFACE_KINDS as readonly string[]).includes(s),\n );\n if (unknown.length)\n throw new Error(\n `Unknown world surfaces: ${unknown.join(\", \")}; choose from ${SURFACE_KINDS.join(\", \")}`,\n );\n const at = slugOrRef.indexOf(\"@\");\n const slug = at === -1 ? slugOrRef : slugOrRef.slice(0, at);\n const state = await apiRequest<WorldSessionState & { reusedWarm: boolean }>(\n options,\n \"POST\",\n \"/api/public/world-sessions\",\n {\n ...(opts.versionId ? { versionId: opts.versionId } : { slug }),\n task,\n ...(opts.reuseWarm === undefined ? {} : { reuseWarm: opts.reuseWarm }),\n ...(opts.surfaces?.length ? { surfaces: opts.surfaces } : {}),\n },\n );\n return new WorldSession(state.sessionId, state, options);\n}\n\n// ── running many tasks at once ───────────────────────────────────────────────\n\nexport type SessionRunResult = {\n /** The task's name, or `inline:<hash>` for an unnamed inline task. */\n task: string;\n sessionId: string;\n reward: number | null;\n rewards: Record<string, number>;\n /** Set when the task threw instead of grading. */\n error?: string;\n};\n\nexport type SessionRunReport = {\n results: SessionRunResult[];\n /** Mean reward over every task, counting failures as 0. */\n mean: number;\n /** True when `mean >= failUnder` (or no gate was set). */\n passed: boolean;\n};\n\n/**\n * RUN MANY TASKS IN PARALLEL, one warm container each.\n *\n * Parallelism against live worlds is the normal case — a suite is a dozen\n * tasks and each needs its own container, because two agents sharing one\n * world state would corrupt both episodes. Every caller was writing the same\n * pool, the same per-task open/ready/toolkit/grade/close, and the same\n * \"don't let one failure kill the run\" logic, so it belongs here:\n *\n * const report = await runSessions({\n * world: \"revenue-ops-sim@main\",\n * tasks, // default: every task in the world\n * concurrency: 4,\n * failUnder: 0.7,\n * agent: async ({ toolkit, instruction }) =>\n * myAgent(toolkit.impls, toolkit.schemas, instruction),\n * });\n *\n * The handler gets a ready session with its toolkit already bound; grading,\n * closing (warm) and aggregation are handled. A task that throws scores 0\n * and records why — the tasks that passed keep their results.\n */\nexport async function runSessions(opts: {\n world: string;\n /** Bundled task names, stored task refs and/or inline task specs\n * (default: every bundled task in the world). */\n tasks?: WorldTaskRef[];\n concurrency?: number;\n failUnder?: number;\n /** Pin every session to one version (default: the world's head). */\n versionId?: string;\n /** Hand the containers back warm for the next run (default: true). */\n keepWarm?: boolean;\n agent: (ctx: {\n session: WorldSession;\n toolkit: WorldToolkit;\n instruction: string;\n /** The task's label — see `SessionRunResult.task`. */\n task: string;\n /** The task as it was given: a bundled name, a stored ref or the\n * inline spec. */\n taskRef: WorldTaskRef;\n }) => Promise<unknown>;\n onResult?: (result: SessionRunResult) => void;\n options?: WorldsClientOptions;\n}): Promise<SessionRunReport> {\n const options = opts.options ?? {};\n const concurrency = Math.max(1, opts.concurrency ?? 3);\n\n let tasks = opts.tasks;\n let versionId = opts.versionId;\n if (!tasks || !versionId) {\n // One resolve for the whole run: every session pins the SAME version, so\n // a push mid-suite cannot split the results across two worlds.\n const { openWorld } = await import(\"./index\");\n const world = await openWorld(opts.world, options);\n tasks = tasks ?? world.tasks.map((t) => t.name);\n versionId = versionId ?? world.version.versionId;\n }\n\n const results: SessionRunResult[] = [];\n let next = 0;\n await Promise.all(\n Array.from({ length: Math.min(concurrency, tasks.length) }, async () => {\n while (next < tasks!.length) {\n const taskRef = tasks![next++];\n let task = taskLabel(taskRef);\n let session: WorldSession | null = null;\n try {\n session = await openSession(opts.world, {\n task: taskRef,\n versionId,\n options,\n });\n task = taskLabel(taskRef, session.taskInfo);\n await session.ready();\n const toolkit = await session.toolkit();\n await opts.agent({\n session,\n toolkit,\n instruction:\n session.instruction ??\n (isTaskSpec(taskRef) ? taskRef.instruction : task),\n task,\n taskRef,\n });\n const graded = await session.grade();\n const result: SessionRunResult = {\n task,\n sessionId: session.sessionId,\n reward: graded.reward,\n rewards: graded.rewards,\n };\n results.push(result);\n opts.onResult?.(result);\n } catch (error) {\n const result: SessionRunResult = {\n task,\n sessionId: session?.sessionId ?? \"\",\n reward: 0,\n rewards: {},\n // An Error with an empty message would read as \"no error\" to any\n // caller checking truthiness; name the type instead.\n error:\n (error instanceof Error ? error.message : String(error)) ||\n (error instanceof Error ? error.name : \"Unknown error\"),\n };\n results.push(result);\n opts.onResult?.(result);\n } finally {\n // Always give the container back — a leaked session bills until the\n // fleet's idle TTL reaps it.\n await session\n ?.close({ keepWarm: opts.keepWarm ?? true })\n .catch(() => undefined);\n }\n }\n }),\n );\n\n const mean =\n results.reduce((sum, r) => sum + (r.reward ?? 0), 0) /\n (results.length || 1);\n return {\n results: results.sort((a, b) => a.task.localeCompare(b.task)),\n mean,\n passed: opts.failUnder === undefined ? true : mean >= opts.failUnder,\n };\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\nimport type { WorldTaskSpec } from \"./session\";\n\n/**\n * STORED WORLD TASKS: a task spec kept by the project, outside any bundle.\n *\n * An inline task (`openSession(world, { task: { instruction, … } })`) belongs\n * to one session. A stored task is the same spec as a named, versioned\n * project resource: create it once, open as many sessions on it as you like\n * with `{ task: { id } }`, and every grade attributes back to the task and\n * its version. Updating the spec never rewrites history — it appends a\n * version, and a session opened on `{ id, version: 2 }` keeps running v2\n * after v3 exists.\n *\n * const task = await createTask({\n * name: \"refund-late-invoice\",\n * world: \"acme-billing\",\n * spec: { instruction: \"…\", seed: {…}, grader: {…} },\n * });\n * const session = await openSession(\"acme-billing\", { task: { id: task.id } });\n *\n * Tasks are project-scoped: another project's task id is not found (404),\n * never forbidden. `world` pins a task to one world's slug (validated against\n * that world's contract); null leaves it usable with any world.\n */\n\nexport type WorldTaskSummary = {\n id: string;\n name: string;\n world: string | null;\n version: number;\n hash: string;\n spec: WorldTaskSpec;\n createdAt: string;\n updatedAt: string;\n createdBy: string;\n updatedBy: string;\n /** On create, when the task is pinned to a world of a deprecated shape (an\n * api bundle): what to run instead. A retired shape is refused. */\n deprecations?: { code: string; message: string; replacement: string }[];\n};\n\nexport type WorldTaskVersionSummary = {\n version: number;\n hash: string;\n createdAt: string;\n createdBy: string;\n message: string | null;\n};\n\nexport type WorldTaskDetail = WorldTaskSummary & {\n versions: WorldTaskVersionSummary[];\n};\n\nexport type WorldTaskPage = {\n tasks: WorldTaskSummary[];\n meta: { page: number; limit: number; totalItems: number; totalPages: number };\n};\n\nexport type WorldTaskValidation = {\n taskId: string;\n version: number;\n /** The world version the task was checked against. */\n versionId: string;\n ok: boolean;\n /** `entities` when the world's contract was read and every seed and check\n * entity was matched against it; `none` when the version has no contract\n * to check (a mock-tools world), in which case `ok` says only that the\n * version exists and is READY. */\n checked: \"entities\" | \"none\";\n problems: string[];\n entities: string[] | null;\n};\n\nconst TASKS = \"/api/public/world-tasks\";\nconst taskRoute = (id: string) => `${TASKS}/${encodeURIComponent(id)}`;\n\nconst compact = (body: Record<string, unknown>) =>\n Object.fromEntries(Object.entries(body).filter(([, v]) => v !== undefined));\n\n/** Store a task. `name` defaults to `spec.name`; one of the two is needed. */\nexport async function createTask(\n input: {\n spec: WorldTaskSpec;\n name?: string;\n world?: string | null;\n message?: string;\n },\n options: WorldsClientOptions = {},\n): Promise<WorldTaskSummary> {\n return apiRequest<WorldTaskSummary>(\n options,\n \"POST\",\n TASKS,\n compact({\n spec: input.spec,\n name: input.name,\n world: input.world,\n message: input.message,\n }),\n );\n}\n\n/** Change a task. A new `spec` becomes the next version (the old ones stay\n * readable and openable); `name` and `world` change in place. */\nexport async function updateTask(\n taskId: string,\n input: {\n spec?: WorldTaskSpec;\n name?: string;\n world?: string | null;\n message?: string;\n },\n options: WorldsClientOptions = {},\n): Promise<WorldTaskSummary> {\n if (\n input.spec === undefined &&\n input.name === undefined &&\n input.world === undefined\n )\n throw new Error(\"updateTask: nothing to update — pass spec, name or world\");\n return apiRequest<WorldTaskSummary>(\n options,\n \"PATCH\",\n taskRoute(taskId),\n compact({\n spec: input.spec,\n name: input.name,\n world: input.world,\n message: input.message,\n }),\n );\n}\n\n/** The project's tasks, newest change first. `world` keeps only tasks\n * pinned to that slug; `metadata` keeps tasks whose spec metadata carries\n * every given key/value (`{ externalUserId: \"u_42\" }`). */\nexport async function listTasks(\n filter: {\n world?: string;\n metadata?: Record<string, string>;\n page?: number;\n limit?: number;\n } = {},\n options: WorldsClientOptions = {},\n): Promise<WorldTaskPage> {\n const params = new URLSearchParams();\n if (filter.world) params.set(\"world\", filter.world);\n if (filter.page !== undefined) params.set(\"page\", String(filter.page));\n if (filter.limit !== undefined) params.set(\"limit\", String(filter.limit));\n for (const [key, value] of Object.entries(filter.metadata ?? {}))\n params.set(`metadata.${key}`, value);\n const query = params.toString();\n return apiRequest<WorldTaskPage>(\n options,\n \"GET\",\n query ? `${TASKS}?${query}` : TASKS,\n );\n}\n\n/** One task with its version history; `version` reads that version's spec\n * instead of the current one. */\nexport async function getTask(\n taskId: string,\n opts: { version?: number } = {},\n options: WorldsClientOptions = {},\n): Promise<WorldTaskDetail> {\n const query =\n opts.version === undefined ? \"\" : `?version=${String(opts.version)}`;\n return apiRequest<WorldTaskDetail>(\n options,\n \"GET\",\n `${taskRoute(taskId)}${query}`,\n );\n}\n\n/** Remove a task and every version. Sessions already opened on it keep\n * their copy of the spec. */\nexport async function deleteTask(\n taskId: string,\n options: WorldsClientOptions = {},\n): Promise<{ id: string; name: string }> {\n return apiRequest(options, \"DELETE\", taskRoute(taskId));\n}\n\n/** Check a task against a world version without opening a session: every\n * seed entity and every check's entity must exist in the world's contract.\n * `slug` checks against that world's head, `versionId` against an exact\n * version, neither against the task's own `world` pin. */\nexport async function validateTask(\n taskId: string,\n target: { version?: number; slug?: string; versionId?: string } = {},\n options: WorldsClientOptions = {},\n): Promise<WorldTaskValidation> {\n return apiRequest<WorldTaskValidation>(\n options,\n \"POST\",\n `${taskRoute(taskId)}/validate`,\n compact({\n version: target.version,\n slug: target.slug,\n versionId: target.versionId,\n }),\n );\n}\n","import { createHash } from \"node:crypto\";\nimport { gzipSync, gunzipSync } from \"node:zlib\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\n\n/**\n * The working-dir half of the TS CLI: push / pull / checkout / status /\n * branch / tag / propose — a faithful port of the Python client\n * (`gatewaysdk/benchmark_hub/client.py` + `_archive.py`).\n *\n * LOCKSTEP WARNING — the content hash is the version's identity and is\n * byte-compatible with Prime Intellect. It now has FOUR implementations that\n * must stay identical: worker `environmentAgent/tar.ts`, web\n * `benchmark-hub/server/benchmarkContentHash.ts`, Python `_archive.py`, and\n * this file. This one is a line-for-line port of the WEB TypeScript\n * implementation (same language, same crypto) — if the rule ever changes,\n * change all four or push identity splits by client.\n *\n * One deliberate refusal, same policy as the web upload path: a bundle with\n * a ROOT `.gitignore` is refused rather than mis-hashed — the Python CLI\n * honors it via `gitignore_parser`, and an imperfect reimplementation here\n * would produce a wrong, Prime-incompatible hash silently.\n */\n\nexport const DEFAULT_BRANCH = \"main\";\nconst META_RELPATH = path.join(\".gateway\", \".env-metadata.json\");\nconst SKIP_DIRS = new Set([\n \".git\",\n \"__pycache__\",\n \"node_modules\",\n \".venv\",\n \".mypy_cache\",\n \"dist\",\n \"build\",\n \"outputs\",\n]);\nconst ROOT_EXCLUDED_DIRS = new Set([\"dist\", \"build\", \"outputs\", \"__pycache__\"]);\n\n/** Gateway-only root markers that widen collection to every ordinary root\n * file. The FOURTH copy of this list (python SDK `_archive.py`, web\n * `benchmarkContentHash.ts`, worker `tar.ts`, and here) — all four MUST stay\n * identical or the same tree hashes differently per pusher. This copy\n * missing `gateway-api-world.toml` is exactly how an api world pushed from\n * TS landed on the hub with no OpenAPI contract and no marker: the root\n * files never entered the manifest, and nothing downstream could tell. */\nconst BROAD_ROOT_MARKERS = [\"gateway-env.toml\", \"gateway-api-world.toml\"];\n\n// ── content-hash rules (port of web benchmarkContentHash.ts) ───────────────\n\nfunction isExcludedDirComponent(component: string): boolean {\n return (\n component.startsWith(\".\") ||\n ROOT_EXCLUDED_DIRS.has(component) ||\n component.endsWith(\".egg-info\")\n );\n}\n\nexport function isIncludedInContentHash(\n relPath: string,\n includeAllRootFiles: boolean,\n): boolean {\n const parts = relPath.split(\"/\");\n const name = parts[parts.length - 1];\n const dirParts = parts.slice(0, -1);\n if (name.startsWith(\".\")) return false;\n if (parts.includes(\"__pycache__\")) return false;\n if (dirParts.length === 0) {\n return (\n includeAllRootFiles ||\n name === \"README.md\" ||\n name === \"pyproject.toml\" ||\n BROAD_ROOT_MARKERS.includes(name) ||\n name.endsWith(\".py\")\n );\n }\n return !dirParts.some(isExcludedDirComponent);\n}\n\n/** The archive-visible files of a working dir, as sorted relpaths. Throws on\n * a root .gitignore (see the header). */\nexport function collectArchiveRelPaths(dir: string): string[] {\n if (fs.existsSync(path.join(dir, \".gitignore\"))) {\n throw new Error(\n \"This bundle has a root .gitignore, which the Python CLI honors via \" +\n \"gitignore_parser. Reimplementing that imperfectly here would \" +\n \"silently produce a different content hash, so the TS CLI refuses. \" +\n \"Remove the .gitignore (or bake its effect into the tree) and retry.\",\n );\n }\n const out: string[] = [];\n const includeAllRootFiles = BROAD_ROOT_MARKERS.some((marker) =>\n fs.existsSync(path.join(dir, marker)),\n );\n const walk = (rel: string) => {\n const abs = rel ? path.join(dir, rel) : dir;\n for (const entry of fs.readdirSync(abs, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {\n const childRel = rel ? `${rel}/${entry.name}` : entry.name;\n if (entry.isDirectory()) {\n if (!isExcludedDirComponent(entry.name)) walk(childRel);\n } else if (entry.isFile()) {\n if (isIncludedInContentHash(childRel, includeAllRootFiles)) {\n out.push(childRel);\n }\n }\n }\n };\n walk(\"\");\n return out.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));\n}\n\nexport function computeContentHash(dir: string): string {\n const hasher = createHash(\"sha256\");\n for (const relPath of collectArchiveRelPaths(dir)) {\n hasher.update(Buffer.from(`file:${relPath}`, \"utf-8\"));\n hasher.update(fs.readFileSync(path.join(dir, relPath)));\n }\n return hasher.digest(\"hex\");\n}\n\n// ── deterministic tar.gz writer ─────────────────────────────────────────────\n\nfunction octal(value: number, length: number): Buffer {\n return Buffer.from(value.toString(8).padStart(length - 1, \"0\") + \"\\0\", \"ascii\");\n}\n\nfunction tarHeader(name: string, size: number): Buffer {\n const header = Buffer.alloc(512);\n header.write(name, 0, 100, \"utf-8\");\n octal(0o644, 8).copy(header, 100); // mode\n octal(0, 8).copy(header, 108); // uid\n octal(0, 8).copy(header, 116); // gid\n octal(size, 12).copy(header, 124);\n octal(0, 12).copy(header, 136); // mtime = 0 (deterministic)\n header.write(\" \", 148, \"ascii\"); // checksum placeholder = spaces\n header.write(\"0\", 156, \"ascii\"); // regular file\n header.write(\"ustar\", 257, \"ascii\");\n header.write(\"00\", 263, \"ascii\");\n let sum = 0;\n for (const byte of header) sum += byte;\n header.write(sum.toString(8).padStart(6, \"0\") + \"\\0 \", 148, \"ascii\");\n return header;\n}\n\nfunction tarMember(name: string, payload: Buffer): Buffer[] {\n const parts: Buffer[] = [];\n const nameBytes = Buffer.byteLength(name, \"utf-8\");\n if (nameBytes > 100) {\n // GNU long name: an 'L' member whose body is the real name.\n const body = Buffer.from(name + \"\\0\", \"utf-8\");\n const lHeader = tarHeader(\"././@LongLink\", body.length);\n lHeader.write(\"L\", 156, \"ascii\");\n let sum = 0;\n lHeader.write(\" \", 148, \"ascii\");\n for (const byte of lHeader) sum += byte;\n lHeader.write(sum.toString(8).padStart(6, \"0\") + \"\\0 \", 148, \"ascii\");\n parts.push(lHeader, body);\n const pad = body.length % 512 === 0 ? 0 : 512 - (body.length % 512);\n if (pad) parts.push(Buffer.alloc(pad));\n parts.push(tarHeader(name.slice(0, 100), payload.length));\n } else {\n parts.push(tarHeader(name, payload.length));\n }\n parts.push(payload);\n const pad = payload.length % 512 === 0 ? 0 : 512 - (payload.length % 512);\n if (pad) parts.push(Buffer.alloc(pad));\n return parts;\n}\n\n/** A deterministic .tar.gz of the source files (node's gzip stamps no mtime,\n * matching the Python's mtime=0 gzip). */\nexport function buildSourceTarball(dir: string): Buffer {\n const parts: Buffer[] = [];\n for (const relPath of collectArchiveRelPaths(dir)) {\n parts.push(...tarMember(relPath, fs.readFileSync(path.join(dir, relPath))));\n }\n parts.push(Buffer.alloc(1024)); // end-of-archive\n return gzipSync(Buffer.concat(parts), { level: 9 });\n}\n\n// ── local metadata (.gateway/.env-metadata.json) ────────────────────────────\n\nexport type LocalMeta = Record<string, unknown> & {\n slug?: string;\n branch?: string;\n versionId?: string;\n contentHash?: string;\n baseFiles?: Record<string, string>;\n};\n\nexport function readLocalMeta(dir: string): LocalMeta | null {\n try {\n const raw = fs.readFileSync(path.join(dir, META_RELPATH), \"utf-8\");\n const parsed = JSON.parse(raw);\n return parsed && typeof parsed === \"object\" ? (parsed as LocalMeta) : null;\n } catch {\n return null;\n }\n}\n\nexport function writeLocalMeta(dir: string, meta: LocalMeta): void {\n fs.mkdirSync(path.join(dir, \".gateway\"), { recursive: true });\n fs.writeFileSync(path.join(dir, META_RELPATH), JSON.stringify(meta, null, 2));\n}\n\nexport function snapshotTreeHashes(dir: string): Record<string, string> {\n const out: Record<string, string> = {};\n for (const relPath of collectArchiveRelPaths(dir)) {\n out[relPath] = createHash(\"sha256\")\n .update(fs.readFileSync(path.join(dir, relPath)))\n .digest(\"hex\");\n }\n return out;\n}\n\nexport function localTreeState(dir: string): {\n meta: LocalMeta | null;\n dirty: string[];\n clean: boolean;\n} {\n const meta = readLocalMeta(dir);\n const base = meta?.baseFiles;\n if (!base || typeof base !== \"object\") {\n return { meta, dirty: [], clean: false };\n }\n const now = snapshotTreeHashes(dir);\n const dirty = new Set<string>();\n for (const [p, h] of Object.entries(now)) if (base[p] !== h) dirty.add(p);\n for (const p of Object.keys(base)) if (!(p in now)) dirty.add(p);\n return { meta, dirty: [...dirty].sort(), clean: dirty.size === 0 };\n}\n\n// ── protocol helpers ─────────────────────────────────────────────────────────\n\nconst sha256b64 = (data: Buffer) =>\n createHash(\"sha256\").update(data).digest(\"base64\");\n\nfunction readPyproject(dir: string): { name?: string; version?: string } {\n try {\n const text = fs.readFileSync(path.join(dir, \"pyproject.toml\"), \"utf-8\");\n // Minimal [project] reads — name and version only, quoted single-line form.\n const section = /\\[project\\]([\\s\\S]*?)(\\n\\[|$)/.exec(text)?.[1] ?? \"\";\n const name = /\\bname\\s*=\\s*\"([^\"]+)\"/.exec(section)?.[1];\n const version = /\\bversion\\s*=\\s*\"([^\"]+)\"/.exec(section)?.[1];\n return { name, version };\n } catch {\n return {};\n }\n}\n\n/** A schema world's own version: `x-gateway.package.version` of its contract\n * (`schema/world.json`, or `server/world/schema/world.json` in an api bundle).\n * What a connector world has instead of a pyproject, so its versions read\n * \"1.0.0\" rather than \"unversioned\" on the platform. */\nfunction readWorldContractVersion(dir: string): { name?: string; version?: string } {\n for (const rel of [\"schema/world.json\", path.join(\"server\", \"world\", \"schema\", \"world.json\")]) {\n try {\n const parsed = JSON.parse(fs.readFileSync(path.join(dir, rel), \"utf-8\")) as {\n \"x-gateway\"?: { package?: { id?: string; version?: string } };\n };\n const pkg = parsed[\"x-gateway\"]?.package;\n if (pkg?.version) return { name: pkg.id, version: pkg.version };\n } catch {\n // not a schema world, or not at this root\n }\n }\n return {};\n}\n\nfunction buildFileManifest(\n dir: string,\n): { path: string; isDirectory: boolean; size: number; sha256: string }[] {\n const entries: { path: string; isDirectory: boolean; size: number; sha256: string }[] = [];\n const walk = (rel: string) => {\n const abs = rel ? path.join(dir, rel) : dir;\n for (const entry of fs.readdirSync(abs, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {\n const childRel = rel ? `${rel}/${entry.name}` : entry.name;\n if (entry.isDirectory()) {\n if (!SKIP_DIRS.has(entry.name) && !entry.name.endsWith(\".egg-info\")) {\n walk(childRel);\n }\n } else if (entry.isFile()) {\n const payload = fs.readFileSync(path.join(dir, childRel));\n entries.push({\n path: childRel,\n isDirectory: false,\n size: payload.length,\n sha256: createHash(\"sha256\").update(payload).digest(\"hex\"),\n });\n }\n }\n };\n walk(\"\");\n return entries;\n}\n\nasync function putObject(url: string, data: Buffer, shaB64: string): Promise<void> {\n const resp = await fetch(url, {\n method: \"PUT\",\n headers: {\n \"Content-Type\": \"application/gzip\",\n \"x-amz-checksum-sha256\": shaB64,\n },\n body: new Uint8Array(data),\n });\n if (!resp.ok) {\n throw new Error(`object PUT -> ${resp.status}: ${(await resp.text()).slice(0, 300)}`);\n }\n}\n\n// ── the workflows ────────────────────────────────────────────────────────────\n\nexport async function push(\n dir: string,\n opts: {\n slug?: string;\n branch?: string;\n force?: boolean;\n message?: string;\n author?: string;\n /** Push on top of this version instead of the local meta's base — what a\n * CI checkout (which has no local meta) passes after resolving the\n * branch tip, so re-validating a PR replaces its own previous push\n * instead of 409ing against it. */\n baseVersionId?: string | null;\n /** Container metadata recorded on resolve — the Python CLI's --name,\n * --description, --tag and --visibility. */\n name?: string;\n description?: string;\n tags?: string[];\n visibility?: string;\n /** Pre-built OCI image ref for image/agentic envs (recorded on the version). */\n imageRef?: string;\n options?: WorldsClientOptions;\n } = {},\n): Promise<{\n containerId: string;\n slug: string;\n versionId: string;\n contentHash: string;\n branch: string;\n state: string | null;\n alreadyUploaded: boolean;\n}> {\n const options = opts.options ?? {};\n if (!fs.statSync(dir).isDirectory()) throw new Error(`Not a directory: ${dir}`);\n const localMeta = readLocalMeta(dir) ?? {};\n const branch = opts.branch ?? (localMeta.branch as string | undefined) ?? DEFAULT_BRANCH;\n const baseVersionId = opts.baseVersionId ?? localMeta.versionId ?? null;\n\n const contentHash = computeContentHash(dir);\n const pyproject = readPyproject(dir);\n // A connector world carries its version on its contract, not a pyproject.\n const contractVersion = pyproject.version ? undefined : readWorldContractVersion(dir).version;\n if (contractVersion) pyproject.version = contractVersion;\n // A dir that tracks a world (created, pulled or pushed before) pushes back\n // to THAT world: its recorded slug wins over the package name, so a world\n // created as `acme-f7` is not re-published as pyproject's `acme` — which is\n // how `worlds ci` minted an unsuffixed twin of every suffixed world.\n const slug = opts.slug ?? localMeta.slug ?? pyproject.name ?? path.basename(path.resolve(dir));\n\n const resolve = await apiRequest<{ containerId: string }>(\n options,\n \"POST\",\n \"/api/public/benchmark-containers/resolve\",\n {\n slug,\n name: opts.name ?? pyproject.name ?? slug,\n ...(opts.description ? { description: opts.description } : {}),\n ...(opts.tags?.length ? { tags: opts.tags } : {}),\n ...(opts.visibility ? { visibility: opts.visibility } : {}),\n },\n );\n\n const tarball = buildSourceTarball(dir);\n const bundleSha256 = sha256b64(tarball);\n\n const version = await apiRequest<{\n versionId: string;\n uploadUrl?: string;\n alreadyUploaded?: boolean;\n }>(options, \"POST\", \"/api/public/benchmark-containers/versions\", {\n containerId: resolve.containerId,\n contentHash,\n bundleSha256,\n bundleSizeBytes: tarball.length,\n ...(pyproject.version ? { semanticVersion: pyproject.version } : {}),\n pyprojectMeta: pyproject,\n fileManifest: buildFileManifest(dir),\n branch,\n baseVersionId,\n ...(opts.force ? { force: true } : {}),\n ...(opts.message ? { changeReason: opts.message } : {}),\n ...(opts.author ? { author: opts.author } : {}),\n ...(opts.imageRef ? { imageRef: opts.imageRef } : {}),\n });\n\n if (version.uploadUrl) await putObject(version.uploadUrl, tarball, bundleSha256);\n\n const final = await apiRequest<{ state?: string; branch?: string }>(\n options,\n \"POST\",\n `/api/public/benchmark-containers/versions/${version.versionId}/finalize`,\n { branch, baseVersionId, ...(opts.force ? { force: true } : {}) },\n );\n\n writeLocalMeta(dir, {\n ...localMeta,\n slug,\n ref: branch,\n branch,\n versionId: version.versionId,\n contentHash,\n semanticVersion: pyproject.version,\n forkedFromVersionId: baseVersionId,\n baseFiles: snapshotTreeHashes(dir),\n });\n return {\n containerId: resolve.containerId,\n slug,\n versionId: version.versionId,\n contentHash,\n branch: final.branch ?? branch,\n state: final.state ?? null,\n alreadyUploaded: Boolean(version.alreadyUploaded),\n };\n}\n\n/** Extract a downloaded bundle into `dir` (paths sanitized). */\nfunction extractBundle(bundle: Buffer, dir: string): number {\n const tar = gunzipSync(bundle);\n let offset = 0;\n let longName: string | null = null;\n let written = 0;\n while (offset + 512 <= tar.length) {\n const header = tar.subarray(offset, offset + 512);\n offset += 512;\n if (header.every((b) => b === 0)) break;\n const rawName = header.subarray(0, 100).toString(\"utf-8\").replace(/\\0.*$/, \"\");\n const size = parseInt(header.subarray(124, 136).toString(\"ascii\").replace(/\\0.*$/, \"\").trim(), 8) || 0;\n const typeflag = header.subarray(156, 157).toString(\"ascii\");\n const body = tar.subarray(offset, offset + size);\n offset += size + (size % 512 === 0 ? 0 : 512 - (size % 512));\n if (typeflag === \"L\") {\n longName = body.toString(\"utf-8\").replace(/\\0.*$/, \"\");\n continue;\n }\n const name = (longName ?? rawName).replace(/^\\.\\//, \"\");\n longName = null;\n if (typeflag !== \"0\" && typeflag !== \"\") continue;\n // Safe extract: no absolute paths, no traversal.\n if (name.startsWith(\"/\") || name.split(\"/\").includes(\"..\")) continue;\n const target = path.join(dir, name);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n fs.writeFileSync(target, body);\n written++;\n }\n return written;\n}\n\nexport async function pull(\n slugRef: string,\n target?: string,\n options: WorldsClientOptions = {},\n): Promise<{ slug: string; dir: string; versionId: string; files: number }> {\n const at = slugRef.indexOf(\"@\");\n const slug = at === -1 ? slugRef : slugRef.slice(0, at);\n const ref = at === -1 ? \"latest\" : slugRef.slice(at + 1);\n\n const details = await apiRequest<{\n versionId: string;\n contentHash: string;\n semanticVersion?: string | null;\n downloadUrl?: string;\n bundleSha256?: string;\n }>(options, \"POST\", \"/api/public/benchmark-containers/resolve-version\", {\n slug,\n ref,\n });\n if (!details.downloadUrl) {\n throw new Error(`${slug}@${ref} resolved but has no uploaded bundle`);\n }\n\n let dir = target ?? path.join(process.cwd(), slug);\n if (!target) {\n let i = 1;\n const base = dir;\n while (fs.existsSync(dir)) dir = `${base}-${i++}`;\n }\n fs.mkdirSync(dir, { recursive: true });\n\n const resp = await fetch(details.downloadUrl);\n if (!resp.ok) throw new Error(`bundle download -> ${resp.status}`);\n const bundle = Buffer.from(await resp.arrayBuffer());\n if (details.bundleSha256 && sha256b64(bundle) !== details.bundleSha256) {\n throw new Error(\n `bundle integrity check failed for ${slug}@${ref}: downloaded sha256 != recorded bundleSha256`,\n );\n }\n\n const files = extractBundle(bundle, dir);\n const branch = ref === \"latest\" || /^\\d|^[0-9a-f]{8,}$/.test(ref) ? DEFAULT_BRANCH : ref;\n writeLocalMeta(dir, {\n slug,\n ref,\n branch,\n versionId: details.versionId,\n contentHash: details.contentHash,\n semanticVersion: details.semanticVersion ?? undefined,\n baseFiles: snapshotTreeHashes(dir),\n });\n return { slug, dir, versionId: details.versionId, files };\n}\n\nexport async function propose(\n dir: string,\n opts: { title: string; reason: string; targetBranch?: string; options?: WorldsClientOptions },\n): Promise<{ proposalId: string }> {\n const meta = readLocalMeta(dir);\n if (!meta?.slug || !meta.baseFiles) {\n throw new Error(\"This dir has no pull/push base — run pull first, then edit, then propose.\");\n }\n const state = localTreeState(dir);\n if (state.clean) throw new Error(\"Nothing to propose — the tree matches its base.\");\n const changes = state.dirty.map((relPath) => {\n const abs = path.join(dir, relPath);\n if (!fs.existsSync(abs)) return { path: relPath, action: \"delete\" as const };\n return {\n path: relPath,\n action: \"write\" as const,\n newContent: fs.readFileSync(abs, \"utf-8\"),\n };\n });\n const res = await apiRequest<{ proposalId: string }>(\n opts.options ?? {},\n \"POST\",\n \"/api/public/benchmark-containers/proposals\",\n {\n slug: meta.slug,\n title: opts.title,\n changeReason: opts.reason,\n baseVersionId: meta.versionId,\n ...(opts.targetBranch ? { targetBranch: opts.targetBranch } : {}),\n changes,\n },\n );\n return res;\n}\n\nexport async function createRef(\n slug: string,\n name: string,\n kind: \"branch\" | \"tag\",\n versionId?: string,\n options: WorldsClientOptions = {},\n): Promise<{ name: string; kind: string; versionId: string }> {\n return apiRequest(options, \"POST\", \"/api/public/benchmark-containers/refs\", {\n slug,\n name,\n kind,\n ...(versionId ? { versionId } : {}),\n });\n}\n","/**\n * PR validation: push the checkout's world source, run it, gate on the graded\n * result — one composed call, because CI should not have to re-derive the\n * choreography from primitives.\n *\n * The differentiating property, stated so it stays true: validation runs the\n * PULL REQUEST'S OWN world source. The push files the checkout as a version on\n * the PR's branch (content-hash dedup makes re-runs cheap), the dispatch pins\n * that version, and the platform resolves the branch back to its open PR — so\n * the run page names the PR and the PR comment names the run. Nothing here\n * validates a standing deployment while pretending to validate the change.\n */\n\nimport {\n apiRequest,\n detectProvenance,\n listRunConfigs,\n waitForRun,\n type RunReport,\n type WorldsClientOptions,\n} from \"./index\";\nimport { push } from \"./hub\";\n\nexport type ValidatedRun = {\n model: string;\n runId: string;\n report: RunReport | null;\n /** Why this run fails the gate, or null when it passes. */\n failure: string | null;\n};\n\nexport type ValidateReport = {\n ok: boolean;\n slug: string;\n branch: string;\n versionId: string;\n contentHash: string;\n runConfig: { id: string; name: string };\n runs: ValidatedRun[];\n /** A PR-comment-ready summary of the whole validation. */\n markdown: string;\n};\n\nfunction fmtScore(score: number | null): string {\n return score === null ? \"no score\" : score.toFixed(3);\n}\n\nfunction buildMarkdown(\n report: Omit<ValidateReport, \"markdown\">,\n minScore: number | null,\n source?: { repoUrl?: string; commit?: string },\n): string {\n const lines: string[] = [];\n lines.push(\n `### World validation ${report.ok ? \"passed\" : \"failed\"} — \\`${report.slug}@${report.branch}\\``,\n );\n lines.push(\"\");\n // Name the exact source that ran: the commit on GitHub when we know it,\n // always the content hash the platform pinned.\n const commitLink =\n source?.repoUrl && source?.commit\n ? `[\\`${source.commit.slice(0, 12)}\\`](${source.repoUrl}/commit/${source.commit})`\n : null;\n lines.push(\n `Ran the pull request's own world source` +\n (commitLink ? ` (${commitLink} on \\`${report.branch}\\`` : ` (`) +\n `${commitLink ? \", \" : \"\"}pinned as \\`${report.contentHash.slice(0, 12)}\\`) ` +\n `through run config **${report.runConfig.name}**` +\n (minScore !== null ? `, gating at score ≥ ${minScore}.` : \".\"),\n );\n lines.push(\"\");\n lines.push(\"| Model | Status | Score | Run |\");\n lines.push(\"| --- | --- | ---: | --- |\");\n for (const run of report.runs) {\n const r = run.report;\n const link = r?.url ? `[open](${r.url})` : \"—\";\n const status = run.failure\n ? `❌ ${run.failure}`\n : `✅ ${r?.status ?? \"COMPLETED\"}`;\n lines.push(\n `| \\`${run.model}\\` | ${status} | ${fmtScore(r?.score ?? null)} | ${link} |`,\n );\n }\n const taskRows = report.runs.flatMap((run) =>\n (run.report?.samples ?? []).map((sample) => ({\n model: run.model,\n task: sample.task ?? \"?\",\n reward: sample.reward,\n })),\n );\n // Every scenario, in the open: a validation whose per-scenario grades hide\n // behind a fold reads as one opaque number. Fold only when the table is\n // genuinely long.\n if (taskRows.length > 0) {\n const fold = taskRows.length > 12;\n lines.push(\"\");\n if (fold) {\n lines.push(\n `<details><summary>Per-scenario rewards (${taskRows.length})</summary>`,\n );\n lines.push(\"\");\n } else {\n lines.push(`**Scenarios (${taskRows.length})**`);\n lines.push(\"\");\n }\n lines.push(\"| Scenario | Model | Reward |\");\n lines.push(\"| --- | --- | ---: |\");\n for (const row of taskRows) {\n lines.push(\n `| ${row.task} | \\`${row.model}\\` | ${row.reward === null ? \"no score\" : row.reward.toFixed(2)} |`,\n );\n }\n if (fold) {\n lines.push(\"\");\n lines.push(\"</details>\");\n }\n }\n return lines.join(\"\\n\");\n}\n\n/**\n * Push `dir` on the current (or given) branch, dispatch the named run config\n * against the pushed version, wait for every run, and gate.\n *\n * The gate: every dispatch accepted, every run terminal COMPLETED, and — when\n * `minScore` is set — every run's score meets it. A run with NO score fails a\n * score gate rather than passing it: null is \"not scored\", never 0 and never\n * fine.\n */\nexport async function validateWorld(\n dir: string,\n opts: {\n slug?: string;\n runConfig: string;\n branch?: string;\n minScore?: number | null;\n timeoutMinutes?: number;\n onProgress?: (line: string) => void;\n options?: WorldsClientOptions;\n },\n): Promise<ValidateReport> {\n const options = opts.options ?? {};\n const progress = opts.onProgress ?? (() => {});\n const minScore = opts.minScore ?? null;\n\n const provenance = detectProvenance();\n const branch = opts.branch ?? provenance.branch;\n if (!branch)\n throw new Error(\n \"No branch to validate on: pass --branch or run inside a git checkout / GitHub Actions.\",\n );\n\n progress(`pushing ${dir} as ${opts.slug ?? \"(pyproject name)\"}@${branch}…`);\n // CI checkouts carry no local push meta, so a re-validation would 409\n // against the branch tip its own previous run created. Validation's\n // semantics are \"this branch's tip BECOMES the PR's source\": resolve the\n // current tip and push on top of it. A branch that does not exist yet\n // resolves to no base, which is a fresh branch — also correct.\n let tipVersionId: string | null = null;\n if (opts.slug) {\n try {\n const tip = await apiRequest<{ versionId?: string }>(\n options,\n \"POST\",\n \"/api/public/benchmark-containers/resolve-version\",\n { slug: opts.slug, ref: branch },\n );\n tipVersionId = tip.versionId ?? null;\n } catch {\n tipVersionId = null;\n }\n }\n const pushed = await push(dir, {\n slug: opts.slug,\n branch,\n baseVersionId: tipVersionId,\n message: `PR validation push (${provenance.commit?.slice(0, 12) ?? \"local\"})`,\n ...(provenance.actor?.name ? { author: provenance.actor.name } : {}),\n options,\n });\n progress(`pushed version ${pushed.versionId} (${pushed.contentHash.slice(0, 12)})`);\n\n // Resolve the run config by name (the stable handle CI configures) or id.\n const configs = await listRunConfigs(options);\n const runConfig =\n configs.find((c) => c.id === opts.runConfig) ??\n configs.find((c) => c.name === opts.runConfig);\n if (!runConfig) {\n const known = configs.map((c) => c.name).join(\", \") || \"(none)\";\n throw new Error(\n `Run config \"${opts.runConfig}\" not found in this project. Have: ${known}`,\n );\n }\n\n progress(`dispatching run config \"${runConfig.name}\" (${runConfig.models.join(\", \")})…`);\n const dispatched = await apiRequest<{\n versionLabel: string;\n runs: { model: string; runId: string; ok: boolean; error?: string }[];\n }>(options, \"POST\", \"/api/public/benchmark-containers/run-configs/dispatch\", {\n runConfigId: runConfig.id,\n versionId: pushed.versionId,\n ...provenance,\n });\n\n // The run's platform page. New deployments return it on the run report\n // (`url`); against an older deployment we build the same page from the\n // evaluation id, because a PR comment that cannot link the run defeats\n // the point of the comment.\n const host = (\n options.host ??\n process.env.GATEWAY_HOST ??\n \"https://withgateway.ai\"\n ).replace(/\\/+$/, \"\");\n let projectId: string | null = null;\n try {\n const projects = await apiRequest<{ data?: { id?: string }[] }>(\n options,\n \"GET\",\n \"/api/public/projects\",\n );\n projectId = projects.data?.[0]?.id ?? null;\n } catch {\n projectId = null;\n }\n const fallbackUrl = (report: RunReport): string | null => {\n if (report.url) return report.url;\n const evaluationId = report.evaluations[0]?.id;\n return projectId && evaluationId\n ? `${host}/project/${projectId}/environment/runs/${encodeURIComponent(evaluationId)}`\n : null;\n };\n\n const runs: ValidatedRun[] = [];\n for (const run of dispatched.runs) {\n if (!run.ok) {\n runs.push({\n model: run.model,\n runId: run.runId,\n report: null,\n failure: `dispatch failed: ${run.error ?? \"unknown error\"}`,\n });\n continue;\n }\n progress(`waiting on ${run.model} (run ${run.runId})…`);\n let report: RunReport | null = null;\n let failure: string | null = null;\n try {\n report = await waitForRun(run.runId, {\n timeoutMinutes: opts.timeoutMinutes ?? 45,\n options,\n onTick: (r) =>\n progress(\n `…${run.model}: ${r.status.toLowerCase()} (${r.shardsCompleted ?? 0}/${r.parallelism} shards)`,\n ),\n });\n report = { ...report, url: fallbackUrl(report) };\n if (report.status.toUpperCase() !== \"COMPLETED\") {\n failure = report.status;\n } else if (minScore !== null) {\n if (report.score === null) failure = \"completed without a score\";\n else if (report.score < minScore)\n failure = `score ${fmtScore(report.score)} < ${minScore}`;\n }\n } catch (error) {\n failure = error instanceof Error ? error.message : String(error);\n }\n runs.push({ model: run.model, runId: run.runId, report, failure });\n }\n\n const base = {\n ok: runs.length > 0 && runs.every((r) => r.failure === null),\n slug: pushed.slug,\n branch,\n versionId: pushed.versionId,\n contentHash: pushed.contentHash,\n runConfig: { id: runConfig.id, name: runConfig.name },\n runs,\n };\n return {\n ...base,\n markdown: buildMarkdown(base, minScore, {\n repoUrl: provenance.repoUrl,\n commit: provenance.commit,\n }),\n };\n}\n","/**\n * `describeWorld(slug)` — what a world holds and how each field is stored,\n * from `GET /api/public/worlds/{slug}`: the entities (primary key, unique\n * keys, relationships, row count, fields with their `[redact]` policy) and\n * the `[redact]` table itself, so `storedForms(world, field, plaintext)`\n * can compute a lookup value without Python. The CLI twin is\n * `gateway worlds describe <slug>`; for a directory the CLI asks the schema\n * runtime instead and merges the same shape.\n */\n\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\nimport type { RedactPolicy, Redaction } from \"./redaction\";\n\nexport type WorldField = {\n name: string;\n type: string | null;\n required: boolean;\n /** How the store holds it; null means in the clear (queryable by plaintext as given). */\n redaction: Redaction | null;\n};\n\nexport type WorldRelationship = {\n fields: string[];\n target: string;\n on_delete?: string;\n};\n\nexport type WorldEntityMapping = {\n localEntity: string;\n localField: string;\n depEntity: string;\n depField: string;\n /** A closed set, applied left to right before each world's own redaction. */\n transform: string[];\n};\n\nexport type WorldDependency = {\n alias: string;\n dependsOn: { slug: string | null; versionId: string };\n task: string | null;\n tools: string[];\n entities: WorldEntityMapping[];\n};\n\nexport type WorldEntity = {\n name: string;\n primaryKey: string[];\n unique: string[][];\n relationships: WorldRelationship[];\n /** Rows in the head version; null when the platform does not count this kind. */\n rowCount: number | null;\n fields: WorldField[];\n};\n\nexport type WorldDescription = {\n slug: string;\n name: string;\n description: string | null;\n kind: string;\n version: { id: string; contentHash: string; semanticVersion: string | null };\n url: string;\n hostedUrl: string | null;\n tools: { name: string; signature: string; doc: string | null }[];\n taskCount: number;\n links: { tasks: string; sessions: string };\n /** World-to-world links from `[dependencies]`, resolved at commit, with the\n * entity mappings `--across` follows. */\n dependencies?: WorldDependency[];\n entities: WorldEntity[];\n redact: RedactPolicy | null;\n};\n\n/** The world's head version, described. The route reads the head only, so a\n * `slug@ref` is refused rather than silently served as the head. */\nexport async function describeWorld(\n slug: string,\n options: WorldsClientOptions = {},\n): Promise<WorldDescription> {\n if (slug.includes(\"@\"))\n throw new Error(\n `describeWorld reads a world's head version: pass the slug without @ref (got ${slug})`,\n );\n return apiRequest<WorldDescription>(\n options,\n \"GET\",\n `/api/public/worlds/${encodeURIComponent(slug)}`,\n );\n}\n","/**\n * JSON as the Python CLI sees it, so both CLIs write the same bytes.\n *\n * `JSON.parse` + `JSON.stringify` are not enough for parity with\n * `json.loads` + `json.dumps(separators=(\",\", \":\"), ensure_ascii=False)`:\n * JavaScript loses `1.0` vs `1` (Python keeps the float), rounds integers past\n * 2^53, moves integer-like keys to the front of an object, and spells\n * exponents differently (`1e-7` vs `1e-07`). Here a number keeps its source\n * text and its Python type, an object is a Map (insertion order, always), and\n * `dumps` renders exactly what CPython renders.\n */\n\nexport class JsonNumber {\n /** The lexeme as it appeared, e.g. \"1.0\", \"-0\", \"1e21\". */\n constructor(readonly text: string) {}\n /** A float in Python's eyes: a fraction, an exponent, or a non-finite literal. */\n get isFloat(): boolean {\n return /[.eE]/.test(this.text) || /[nN]/.test(this.text);\n }\n get value(): number {\n return Number(this.text);\n }\n}\n\nexport type JsonObject = Map<string, JsonValue>;\nexport type JsonValue = null | boolean | string | JsonNumber | JsonValue[] | JsonObject;\n\nexport class JsonSyntaxError extends Error {}\n\nexport const isObject = (value: JsonValue | undefined): value is JsonObject => value instanceof Map;\n\n// ------------------------------------------------------------------ parsing\n\n/** Parse one JSON text (a line, a row, a document) into the model above.\n * Accepts what `json.loads` accepts, including NaN/Infinity literals. */\nexport function parseJson(text: string): JsonValue {\n const p = new Parser(text);\n p.skipWs();\n const value = p.value();\n p.skipWs();\n if (p.i < text.length) throw new JsonSyntaxError(`Extra data at ${p.i}`);\n return value;\n}\n\nclass Parser {\n i = 0;\n constructor(readonly s: string) {}\n\n skipWs(): void {\n const s = this.s;\n while (this.i < s.length) {\n const c = s.charCodeAt(this.i);\n if (c === 0x20 || c === 0x0a || c === 0x0d || c === 0x09) this.i++;\n else break;\n }\n }\n\n fail(what: string): never {\n throw new JsonSyntaxError(`${what} at ${this.i}`);\n }\n\n value(): JsonValue {\n const s = this.s;\n if (this.i >= s.length) this.fail(\"Expecting value\");\n const c = s[this.i]!;\n if (c === \"{\") return this.object();\n if (c === \"[\") return this.array();\n if (c === '\"') return this.string();\n if (c === \"t\") return this.literal(\"true\", true);\n if (c === \"f\") return this.literal(\"false\", false);\n if (c === \"n\") return this.literal(\"null\", null);\n if (c === \"N\") return this.literal(\"NaN\", new JsonNumber(\"NaN\"));\n if (c === \"I\") return this.literal(\"Infinity\", new JsonNumber(\"Infinity\"));\n return this.number();\n }\n\n literal<T extends JsonValue>(word: string, value: T): T {\n if (!this.s.startsWith(word, this.i)) this.fail(\"Expecting value\");\n this.i += word.length;\n return value;\n }\n\n number(): JsonNumber {\n const s = this.s;\n const start = this.i;\n if (s[this.i] === \"-\") {\n this.i++;\n if (s.startsWith(\"Infinity\", this.i)) {\n this.i += 8;\n return new JsonNumber(\"-Infinity\");\n }\n }\n const intStart = this.i;\n if (s[this.i] === \"0\") this.i++;\n else {\n while (this.i < s.length && isDigit(s.charCodeAt(this.i))) this.i++;\n if (this.i === intStart) this.fail(\"Expecting value\");\n }\n if (s[this.i] === \".\") {\n this.i++;\n const fracStart = this.i;\n while (this.i < s.length && isDigit(s.charCodeAt(this.i))) this.i++;\n if (this.i === fracStart) this.fail(\"Invalid number\");\n }\n if (s[this.i] === \"e\" || s[this.i] === \"E\") {\n this.i++;\n if (s[this.i] === \"+\" || s[this.i] === \"-\") this.i++;\n const expStart = this.i;\n while (this.i < s.length && isDigit(s.charCodeAt(this.i))) this.i++;\n if (this.i === expStart) this.fail(\"Invalid number\");\n }\n return new JsonNumber(s.slice(start, this.i));\n }\n\n string(): string {\n const s = this.s;\n this.i++; // opening quote\n let out = \"\";\n let runStart = this.i;\n for (;;) {\n if (this.i >= s.length) this.fail(\"Unterminated string\");\n const c = s.charCodeAt(this.i);\n if (c === 0x22) {\n out += s.slice(runStart, this.i);\n this.i++;\n return out;\n }\n if (c < 0x20) this.fail(\"Invalid control character\");\n if (c !== 0x5c) {\n this.i++;\n continue;\n }\n out += s.slice(runStart, this.i);\n this.i++;\n const e = s[this.i];\n switch (e) {\n case '\"':\n case \"\\\\\":\n case \"/\":\n out += e;\n break;\n case \"b\":\n out += \"\\b\";\n break;\n case \"f\":\n out += \"\\f\";\n break;\n case \"n\":\n out += \"\\n\";\n break;\n case \"r\":\n out += \"\\r\";\n break;\n case \"t\":\n out += \"\\t\";\n break;\n case \"u\": {\n const hex = s.slice(this.i + 1, this.i + 5);\n if (!/^[0-9a-fA-F]{4}$/.test(hex)) this.fail(\"Invalid \\\\u escape\");\n out += String.fromCharCode(parseInt(hex, 16));\n this.i += 4;\n break;\n }\n default:\n this.fail(\"Invalid escape\");\n }\n this.i++;\n runStart = this.i;\n }\n }\n\n array(): JsonValue[] {\n this.i++;\n const out: JsonValue[] = [];\n this.skipWs();\n if (this.s[this.i] === \"]\") {\n this.i++;\n return out;\n }\n for (;;) {\n this.skipWs();\n out.push(this.value());\n this.skipWs();\n const c = this.s[this.i];\n if (c === \",\") {\n this.i++;\n continue;\n }\n if (c === \"]\") {\n this.i++;\n return out;\n }\n this.fail(\"Expecting ',' delimiter\");\n }\n }\n\n object(): JsonObject {\n this.i++;\n const out: JsonObject = new Map();\n this.skipWs();\n if (this.s[this.i] === \"}\") {\n this.i++;\n return out;\n }\n for (;;) {\n this.skipWs();\n if (this.s[this.i] !== '\"') this.fail(\"Expecting property name enclosed in double quotes\");\n const key = this.string();\n this.skipWs();\n if (this.s[this.i] !== \":\") this.fail(\"Expecting ':' delimiter\");\n this.i++;\n this.skipWs();\n out.set(key, this.value());\n this.skipWs();\n const c = this.s[this.i];\n if (c === \",\") {\n this.i++;\n continue;\n }\n if (c === \"}\") {\n this.i++;\n return out;\n }\n this.fail(\"Expecting ',' delimiter\");\n }\n }\n}\n\nconst isDigit = (c: number): boolean => c >= 0x30 && c <= 0x39;\n\n// ------------------------------------------------------------ serialising\n\n/** `json.dumps(value, separators=(\",\", \":\"), ensure_ascii=False)`, byte for byte. */\nexport function dumps(value: JsonValue): string {\n if (value === null) return \"null\";\n if (value === true) return \"true\";\n if (value === false) return \"false\";\n if (typeof value === \"string\") return JSON.stringify(value);\n if (value instanceof JsonNumber) return numberText(value);\n if (Array.isArray(value)) return \"[\" + value.map(dumps).join(\",\") + \"]\";\n const parts: string[] = [];\n for (const [key, item] of value) parts.push(JSON.stringify(key) + \":\" + dumps(item));\n return \"{\" + parts.join(\",\") + \"}\";\n}\n\n/** How `json.dumps` spells a parsed number: ints verbatim (`-0` becomes `0`),\n * floats through `float.__repr__`, non-finite as NaN/Infinity. */\nexport function numberText(n: JsonNumber): string {\n if (!n.isFloat) return /^-0+$/.test(n.text) ? \"0\" : n.text;\n const value = n.value;\n if (Number.isNaN(value)) return \"NaN\";\n if (value === Infinity) return \"Infinity\";\n if (value === -Infinity) return \"-Infinity\";\n return pyFloatRepr(value);\n}\n\n/** `str(value)` for the values the redaction digest sees: str, int, float, bool. */\nexport function pyStr(value: string | boolean | JsonNumber): string {\n if (typeof value === \"string\") return value;\n if (typeof value === \"boolean\") return value ? \"True\" : \"False\";\n if (!value.isFloat) return numberText(value);\n const v = value.value;\n if (Number.isNaN(v)) return \"nan\";\n if (v === Infinity) return \"inf\";\n if (v === -Infinity) return \"-inf\";\n return pyFloatRepr(v);\n}\n\n/**\n * CPython's `repr(float)`: the shortest digits that round-trip (which\n * JavaScript's `String(x)` also produces), laid out Python's way — a\n * trailing `.0` on integral values, scientific notation only below 1e-4 or\n * from 1e16, and exponents of at least two digits with a sign.\n */\nexport function pyFloatRepr(x: number): string {\n if (x === 0) return Object.is(x, -0) ? \"-0.0\" : \"0.0\";\n const sign = x < 0 ? \"-\" : \"\";\n const js = String(Math.abs(x));\n const [mantissa, exponentPart] = js.split(\"e\");\n let exponent = exponentPart ? Number(exponentPart) : 0;\n const [intPart, fracPart = \"\"] = mantissa!.split(\".\");\n let digits = intPart! + fracPart;\n // decpt: how many digits sit before the decimal point (may be <= 0 or > length).\n let decpt = intPart!.length + exponent;\n const leading = digits.match(/^0*/)![0].length;\n digits = digits.slice(leading);\n decpt -= leading;\n digits = digits.replace(/0+$/, \"\");\n if (digits === \"\") return sign + \"0.0\";\n const sci = decpt - 1;\n if (sci >= -4 && sci < 16) {\n if (decpt <= 0) return sign + \"0.\" + \"0\".repeat(-decpt) + digits;\n if (decpt >= digits.length) return sign + digits + \"0\".repeat(decpt - digits.length) + \".0\";\n return sign + digits.slice(0, decpt) + \".\" + digits.slice(decpt);\n }\n exponent = sci;\n const mag = String(Math.abs(exponent)).padStart(2, \"0\");\n return sign + digits[0] + (digits.length > 1 ? \".\" + digits.slice(1) : \"\") + \"e\" + (exponent < 0 ? \"-\" : \"+\") + mag;\n}\n\n/**\n * Python's `round(x, ndigits)` for the redaction policy: an int is returned\n * unchanged, a float is correctly rounded on its exact binary value with ties\n * to even (`round(0.125, 2) == 0.12`), then re-read as the nearest double.\n */\nexport function pyRound(n: JsonNumber, ndigits: number): JsonNumber {\n if (!n.isFloat) return n;\n const x = n.value;\n if (!Number.isFinite(x)) return n;\n const sign = x < 0 ? -1 : 1;\n const magnitude = Math.abs(x);\n // Every double at or above 2^53 is an integer already.\n if (magnitude >= 9007199254740992) return new JsonNumber(pyFloatRepr(x));\n const { m, k } = exactFraction(magnitude); // magnitude = m / 2^k, m odd (or zero)\n let rounded: number;\n if (k <= ndigits) rounded = magnitude; // exact at this precision\n else if (k !== ndigits + 1) rounded = Number(magnitude.toFixed(ndigits)); // no tie possible: correctly rounded\n else {\n // Exactly k = ndigits + 1 fractional digits, the last one a 5: a tie. Half to even.\n const scaled = m * 5n ** BigInt(k); // magnitude * 10^k, an integer\n let kept = scaled / 10n; // magnitude * 10^ndigits, truncated\n if (kept % 2n === 1n) kept += 1n;\n const text = kept.toString().padStart(ndigits + 1, \"0\");\n rounded = ndigits === 0 ? Number(text) : Number(text.slice(0, -ndigits) + \".\" + text.slice(-ndigits));\n }\n return new JsonNumber(pyFloatRepr(sign * rounded));\n}\n\n/** A finite non-negative double as m / 2^k with m odd (m = 0, k = 0 for zero). */\nfunction exactFraction(x: number): { m: bigint; k: number } {\n if (x === 0) return { m: 0n, k: 0 };\n const view = new DataView(new ArrayBuffer(8));\n view.setFloat64(0, x);\n const bits = view.getBigUint64(0);\n const exponent = Number((bits >> 52n) & 0x7ffn);\n let mantissa = bits & ((1n << 52n) - 1n);\n let e: number;\n if (exponent === 0) e = -1074;\n else {\n mantissa |= 1n << 52n;\n e = exponent - 1075;\n }\n while (mantissa !== 0n && (mantissa & 1n) === 0n) {\n mantissa >>= 1n;\n e += 1;\n }\n if (e >= 0) return { m: mantissa << BigInt(e), k: 0 };\n return { m: mantissa, k: -e };\n}\n","/**\n * Named plaintext transforms for cross-world entity mappings.\n *\n * A mapping between two worlds' fields is rarely a raw equality: SpyCloud\n * keeps `phone` as bare digits where a Torchlight client sends\n * `+1 (559) 779-1433`; one world keys people by `email`, another by\n * `email_username`. A transform normalises the plaintext on BOTH sides of a\n * mapping before `storedForms` salts it under each world's slug, so a\n * cross-world query is answerable from the plaintext alone, with no stored\n * join.\n *\n * The set is closed and named — no expressions, no user code — because any\n * client must reproduce a transform from the manifest by itself. This is the\n * TypeScript twin of the Python runtime's `environment/schema/transforms.py`;\n * the golden vectors in `__tests__/transforms.test.ts` and the Python\n * `tests/environment/test_schema_transforms.py` pin the two to each other,\n * byte for byte.\n *\n * Whitespace, for `trim` and `collapse_ws`, is the ASCII set `\" \\t\\n\\r\\f\\v\"`\n * by definition (Python's `str.split()` and JavaScript's `\\s` disagree at the\n * edges of Unicode; `nfkc` first folds a no-break space into a plain one).\n */\n\nimport { createHash } from \"node:crypto\";\n\nimport { pyFloatRepr } from \"../cli/platform/worldData/json\";\n\nexport type Transform = (value: string) => string;\n\nexport const WHITESPACE = \" \\t\\n\\r\\f\\v\";\nconst WHITESPACE_EDGES = /^[ \\t\\n\\r\\f\\v]+|[ \\t\\n\\r\\f\\v]+$/g;\nconst WHITESPACE_RUN = /[ \\t\\n\\r\\f\\v]+/g;\nconst NOT_DIGIT = /[^0-9]/g;\n\nexport const STRIP_PREFIX = \"strip_prefix\";\n\nconst trim = (value: string): string => value.replace(WHITESPACE_EDGES, \"\");\n\nconst emailLocalPart = (value: string): string => {\n const at = value.lastIndexOf(\"@\");\n return at === -1 ? value : value.slice(0, at);\n};\n\nconst emailDomain = (value: string): string => {\n const at = value.lastIndexOf(\"@\");\n return at === -1 ? \"\" : value.slice(at + 1).toLowerCase();\n};\n\nconst stripPrefix =\n (prefix: string): Transform =>\n (value) =>\n value.startsWith(prefix) ? value.slice(prefix.length) : value;\n\nconst hex = (algorithm: \"sha1\" | \"sha256\", value: string): string =>\n createHash(algorithm).update(value, \"utf8\").digest(\"hex\");\n\nconst SIMPLE: Record<string, Transform> = {\n lower: (value) => value.toLowerCase(),\n upper: (value) => value.toUpperCase(),\n trim,\n collapse_ws: (value) => trim(value).replace(WHITESPACE_RUN, \" \"),\n nfkc: (value) => value.normalize(\"NFKC\"),\n digits: (value) => value.replace(NOT_DIGIT, \"\"),\n email_local_part: emailLocalPart,\n email_domain: emailDomain,\n // Vendor-style digests: lowercase hex of the utf-8 bytes, unsalted. This is\n // how SpyCloud accepts a hashed selector (`_digests` in its api_handlers).\n sha1: (value) => hex(\"sha1\", value),\n sha256: (value) => hex(\"sha256\", value),\n};\n\n/** The closed set, as a manifest spells it. `strip_prefix` takes its parameter\n * after a colon; the parameter may hold any character but `,`. */\nexport const TRANSFORMS: readonly string[] = [...Object.keys(SIMPLE), `${STRIP_PREFIX}:<prefix>`];\n\n/** The function a transform name denotes; throws when the name is not in the set. */\nexport function parseTransform(name: string): Transform {\n const simple = Object.prototype.hasOwnProperty.call(SIMPLE, name) ? SIMPLE[name] : undefined;\n if (simple) return simple;\n const colon = name.indexOf(\":\");\n if (colon !== -1) {\n const head = name.slice(0, colon);\n const prefix = name.slice(colon + 1);\n if (head === STRIP_PREFIX && prefix && !prefix.includes(\",\")) return stripPrefix(prefix);\n }\n throw new Error(`Unknown transform '${name}'; choose one of ${TRANSFORMS.join(\", \")}`);\n}\n\n/** `str(value)` as the Python runtime spells a number: an integral number is an\n * int, any other its float repr. */\nconst text = (value: string | number): string => {\n if (typeof value === \"string\") return value;\n return Number.isInteger(value) ? String(value) : pyFloatRepr(value);\n};\n\n/**\n * Compose `chain` left to right over `value`.\n *\n * A number is written as Python's `str()` first, the way `_digest` salts one,\n * so a number keyed on one side and a string on the other transform alike. The\n * whole chain is parsed before any step runs: a bad name at the end refuses\n * the mapping outright rather than after a partial result. An empty chain is\n * the identity.\n */\nexport function applyTransforms(value: string | number, chain: readonly string[]): string {\n const steps = chain.map(parseTransform);\n let out = text(value);\n for (const step of steps) out = step(out);\n return out;\n}\n","/**\n * Stored forms: what a world's store holds for a field given its plaintext.\n *\n * A schema world's `[redact]` table (connector.toml) rewrites named fields\n * before they reach disk — `hash` to a slug-salted sha256, `preserve` to a\n * shape-preserving digest, `round` to fewer decimals, `drop` to nothing. A\n * lookup by plaintext therefore has to compute the same form the store did.\n * This module is the TypeScript twin of the Python runtime's `_digest`,\n * `_shaped`, `redaction_of` and `stored_forms` (environment/schema/connector.py):\n * the rule is `\"sha256:\" + sha256(\"<slug>:<plaintext>\")`, no lowercasing, no\n * trimming, no other salt, and the golden vectors in redaction.test.ts pin the\n * two implementations to each other.\n */\n\nimport { createHash } from \"node:crypto\";\n\nimport { JsonNumber, pyFloatRepr, pyRound } from \"../cli/platform/worldData/json\";\nimport { applyTransforms } from \"./transforms\";\n\n/** The `[redact]` table as `describe` reports it (`connection.redact`, and\n * `redact` on `GET /api/public/worlds/{slug}`). */\nexport type RedactPolicy = {\n /** The digest salt: the connector's slug from connector.toml. It can differ\n * from the platform world slug (`spycloud` vs `spycloud-world`); `storedForms`\n * prefers it and falls back to the world slug only when it is absent. */\n slug?: string;\n hash: string[];\n drop: string[];\n preserve: string[];\n round: Record<string, number>;\n};\n\n/** The policy one field is stored under; null when it is stored in the clear. */\nexport type Redaction = \"hash\" | \"drop\" | \"preserve\" | `round:${number}`;\n\n/**\n * A value as the Python runtime would see it. JavaScript has one number\n * type, so an integral number takes Python's `int` path and any other number\n * its `float` path (`100` is `100`, never `100.0`); integers stay exact within\n * the safe range only.\n */\nexport type Plaintext = string | number;\n\nconst isInt = (value: Plaintext): value is number => typeof value === \"number\" && Number.isInteger(value);\n\n/** `str(value)` for an int or str, `repr(value)` for a float — the text the\n * Python runtime salts and shapes. */\nexport function pyText(value: Plaintext): string {\n if (typeof value === \"string\") return value;\n if (Number.isInteger(value)) return String(value);\n if (Number.isNaN(value)) return \"nan\";\n if (!Number.isFinite(value)) return value > 0 ? \"inf\" : \"-inf\";\n return pyFloatRepr(value);\n}\n\n/** The `hash` form: `\"sha256:\" + sha256(\"<slug>:<plaintext>\")` as hex. */\nexport function hashForm(slug: string, plaintext: Plaintext): string {\n return \"sha256:\" + createHash(\"sha256\").update(`${slug}:${pyText(plaintext)}`, \"utf8\").digest(\"hex\");\n}\n\n/**\n * The `preserve` form, the Python `_shaped`: the same length, every ASCII\n * digit still a digit, every ASCII letter still a letter of the same case,\n * everything else (separators, punctuation, non-ASCII) left in place. The\n * bytes come from sha256 of the seed `\"<slug>:<text>\"`, re-keyed as\n * sha256(digest + seed) once the 32 bytes are spent. A number keeps its type:\n * an int keeps its digit count (a leading zero is replaced), a float is re-read.\n */\nexport function preserveForm(slug: string, plaintext: Plaintext): Plaintext {\n const kind = typeof plaintext === \"string\" ? \"str\" : isInt(plaintext) ? \"int\" : \"float\";\n const shaped = shapeText(slug, pyText(plaintext), kind);\n return kind === \"str\" ? shaped : Number(shaped);\n}\n\n/** The shaping itself, on text: `kind` says which of Python's rules apply\n * (letters are re-lettered for a str only; an int keeps its digit count). */\nexport function shapeText(slug: string, text: string, kind: \"str\" | \"int\" | \"float\"): string {\n const seed = Buffer.from(`${slug}:${text}`, \"utf8\");\n let digest = createHash(\"sha256\").update(seed).digest();\n let cursor = 0;\n const out: string[] = [];\n for (const char of text) {\n if (cursor === digest.length) {\n digest = createHash(\"sha256\").update(Buffer.concat([digest, seed])).digest();\n cursor = 0;\n }\n const byte = digest[cursor]!;\n cursor += 1;\n if (char >= \"0\" && char <= \"9\") out.push(String(byte % 10));\n else if (kind === \"str\" && char >= \"a\" && char <= \"z\") out.push(String.fromCharCode(97 + (byte % 26)));\n else if (kind === \"str\" && char >= \"A\" && char <= \"Z\") out.push(String.fromCharCode(65 + (byte % 26)));\n else out.push(char);\n }\n // An int keeps its digit count; int() would drop a leading zero.\n if (kind === \"int\" && out.length > 1 && out[0] === \"0\") out[0] = String(1 + (digest[0]! % 9));\n return out.join(\"\");\n}\n\n/** The `round` form: Python's `round(value, decimals)` — an int unchanged, a\n * float correctly rounded with ties to even; a string is not a number and\n * passes through as the runtime leaves it. */\nexport function roundForm(plaintext: Plaintext, decimals: number): Plaintext {\n if (typeof plaintext === \"string\" || isInt(plaintext) || !Number.isFinite(plaintext)) return plaintext;\n return pyRound(new JsonNumber(pyFloatRepr(plaintext)), decimals).value;\n}\n\n/**\n * The policy a field of this name falls under, ranked as the runtime applies\n * them (drop, hash, preserve, round). Read without a path: a bare name in the\n * table counts, and so does a dotted path whose last segment is the field.\n */\nexport function redactionOf(redact: RedactPolicy | null | undefined, field: string): Redaction | null {\n if (!redact) return null;\n const named = (names: string[] | undefined) =>\n (names ?? []).some((name) => name === field || name.slice(name.lastIndexOf(\".\") + 1) === field);\n if (named(redact.drop)) return \"drop\";\n if (named(redact.hash)) return \"hash\";\n if (named(redact.preserve)) return \"preserve\";\n const decimals = redact.round?.[field];\n if (typeof decimals === \"number\") return `round:${decimals}`;\n return null;\n}\n\n/**\n * Every value the store may hold for `field` given this plaintext:\n *\n * clear field -> [plaintext]\n * hash -> [\"sha256:<hex>\"]\n * preserve -> [the shape-preserving digest]\n * round -> [round(plaintext, decimals)] for a number, [plaintext] otherwise\n * drop -> [] (the field is not on disk: a documented miss, not an error)\n *\n * `world` is what `describeWorld` / the bridge's `describe` return: the slug\n * is the salt, `redact` the table.\n *\n * `transform` — a cross-world mapping's chain (`./transforms`) — runs over the\n * plaintext FIRST, so `hash` and `preserve` salt the normalised text; omitted\n * (or empty) is today's behaviour, byte for byte.\n */\nexport function storedForms(\n world: { slug: string; redact?: RedactPolicy | null },\n field: string,\n plaintext: Plaintext,\n transform?: readonly string[],\n): Plaintext[] {\n if (transform?.length) plaintext = applyTransforms(plaintext, transform);\n const policy = redactionOf(world.redact, field);\n const salt = world.redact?.slug ?? world.slug;\n if (policy === \"drop\") return [];\n if (policy === \"hash\") return [hashForm(salt, plaintext)];\n if (policy === \"preserve\") return [preserveForm(salt, plaintext)];\n if (policy !== null) return [roundForm(plaintext, world.redact!.round[field]!)];\n return [plaintext];\n}\n","/**\n * `queryRows(slug, entity, {where, resolve, limit, offset})` — the rows of\n * one entity that match a predicate, from\n * `GET /api/public/worlds/{slug}/data?entity=&where=&limit=&offset=&resolve=`.\n * `where` is field → value, or field → list of values (any of); values match\n * the STORED form as given. With `resolve: true` the values are plaintext and\n * the runtime maps each to its stored form under the world's `[redact]`\n * policy first (a hashed `email` becomes its slug-salted digest; a dropped\n * field resolves to nothing and matches no row — the answer's `resolved`\n * says so). The CLI twin is `gateway worlds data query <slug> <entity>`.\n *\n * `across: true` runs the same plaintext in every world this one links to\n * whose `[dependencies.<alias>.entities]` mapping covers a `where` field;\n * each linked world recomputes its own stored form (after the mapping's\n * transform) at query time — no join on disk, no shared salt. The answer\n * is then {@link WorldQueryAcrossResult}: one group per world, the root\n * first, and with `compare: true` a parity report saying, per field and\n * per world, `matched`, `no match` or `unmapped`.\n */\n\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\nimport type { Plaintext } from \"./redaction\";\n\nexport type WorldQueryWhere = Record<string, Plaintext | Plaintext[]>;\n\nexport type WorldQueryOptions = {\n where?: WorldQueryWhere;\n /** The `where` values are plaintext: resolve each to its stored form before matching. */\n resolve?: boolean;\n limit?: number;\n offset?: number;\n /** Query the linked worlds too; the answer becomes groups. */\n across?: boolean;\n /** With `across`: add the parity report. */\n compare?: boolean;\n};\n\n/** The options that make `queryRows` answer {@link WorldQueryAcrossResult}. */\nexport type WorldQueryAcrossOptions = WorldQueryOptions & { across: true };\n\nexport type WorldQueryResult = {\n slug: string;\n versionId: string;\n kind: string | null;\n entity: string;\n rows: Record<string, unknown>[];\n /** Rows in this page. */\n count: number;\n /** Rows matching in all; null when the store does not count them. */\n total: number | null;\n limit: number;\n offset: number;\n /** With `resolve`: the stored forms each `where` field was matched against\n * (`[]` for a dropped field, which is why such a query matches nothing). */\n resolved?: Record<string, Plaintext[]>;\n entityCounts: Record<string, number>;\n snapshot: WorldQuerySnapshot | null;\n};\n\nexport type WorldQuerySnapshot = {\n snapshotId: string;\n contractHash: string;\n batchDigest: string;\n bytes: number;\n};\n\n/** One world's page inside an across answer: the root (`alias: null`, no\n * `mapping`) or a linked world with the mappings that carried the root's\n * `where` fields into its own entity. */\nexport type WorldQueryGroup = {\n world: { slug: string; alias: string | null; versionId: string };\n entity: string;\n rows: Record<string, unknown>[];\n count: number;\n total: number | null;\n limit: number;\n offset: number;\n resolved?: Record<string, Plaintext[]>;\n mapping?: { field: string; depField: string; transform: string[] }[];\n};\n\nexport type WorldQueryCompareStatus = \"matched\" | \"no match\" | \"unmapped\";\n\n/** Per `where` field, per world: whether the field reached the world and\n * whether any row matched there; `present`/`absent` list the worlds by slug. */\nexport type WorldQueryCompare = {\n present: string[];\n absent: string[];\n perField: {\n field: string;\n worlds: {\n world: string;\n alias: string | null;\n status: WorldQueryCompareStatus;\n /** `<depEntity>.<depField>` and the transform applied (mapped worlds only). */\n depField?: string;\n transform?: string[];\n }[];\n }[];\n};\n\nexport type WorldQueryAcrossResult = {\n slug: string;\n versionId: string;\n kind: string | null;\n entity: string;\n /** The root world first, then one per linked world that was queried. */\n groups: WorldQueryGroup[];\n compare?: WorldQueryCompare;\n entityCounts: Record<string, number>;\n snapshot: WorldQuerySnapshot | null;\n};\n\n/** The query string the route reads; `where` travels as URL-encoded JSON. */\nexport function queryRowsSearch(entity: string, opts: WorldQueryOptions = {}): string {\n const search = new URLSearchParams();\n search.set(\"entity\", entity);\n if (opts.where && Object.keys(opts.where).length) search.set(\"where\", JSON.stringify(opts.where));\n if (opts.limit !== undefined) search.set(\"limit\", String(opts.limit));\n if (opts.offset !== undefined) search.set(\"offset\", String(opts.offset));\n if (opts.resolve) search.set(\"resolve\", \"true\");\n if (opts.across) search.set(\"across\", \"true\");\n if (opts.compare) search.set(\"compare\", \"true\");\n return `?${search.toString()}`;\n}\n\n/** The world's head version, queried. The route reads the head only, so a\n * `slug@ref` is refused rather than silently served as the head. With\n * `across: true` the answer is the groups shape. */\nexport async function queryRows(\n slug: string,\n entity: string,\n opts: WorldQueryAcrossOptions,\n options?: WorldsClientOptions,\n): Promise<WorldQueryAcrossResult>;\nexport async function queryRows(\n slug: string,\n entity: string,\n opts?: WorldQueryOptions,\n options?: WorldsClientOptions,\n): Promise<WorldQueryResult>;\nexport async function queryRows(\n slug: string,\n entity: string,\n opts: WorldQueryOptions = {},\n options: WorldsClientOptions = {},\n): Promise<WorldQueryResult | WorldQueryAcrossResult> {\n if (slug.includes(\"@\"))\n throw new Error(\n `queryRows reads a world's head version: pass the slug without @ref (got ${slug})`,\n );\n if (!entity) throw new Error(\"queryRows needs an entity\");\n if (opts.compare && !opts.across) throw new Error(\"queryRows: compare needs across\");\n return apiRequest<WorldQueryResult | WorldQueryAcrossResult>(\n options,\n \"GET\",\n `/api/public/worlds/${encodeURIComponent(slug)}/data${queryRowsSearch(entity, opts)}`,\n );\n}\n","/**\n * `migrateWorld(slug)` — convert a stored world into a schema world, from\n * `POST /api/public/worlds/{slug}/migrate`; `migrateProjectWorlds()` plans\n * (or migrates) every connector world in the project from\n * `POST /api/public/worlds/migrate`. Dry run by default: the report says\n * what the version is, what the conversion does, or why it cannot; `apply`\n * commits the migrated tree as the next version (\"Migrated to a schema\n * world\"). Targets are the platform's connector worlds; a hand-built world\n * needs `force`. The CLI twin is `gateway worlds migrate`.\n */\n\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\n\nexport type WorldMigrationRefusal = {\n code: string;\n message: string;\n /** Paths the conversion needed and did not find. */\n missing: string[];\n};\n\nexport type WorldMigrationReport = {\n slug: string;\n containerId: string;\n versionId: string;\n /** True when the container was created from a connector template. */\n connectorWorld: boolean;\n /** schema | api-bundle | legacy-tools | harbor | verifiers */\n shape: string;\n target: \"schema\";\n /** True when the world already is a schema world. */\n unchanged: boolean;\n /** The dry-run report, one sentence each. */\n actions: string[];\n /** Files the migrated tree holds; 0 on a refusal. */\n files: number;\n refusal: WorldMigrationRefusal | null;\n /** True when this call committed the migrated tree. */\n applied: boolean;\n version: { id: string; contentHash: string } | null;\n};\n\nexport type MigrateWorldOptions = {\n /** Commit the migrated tree as the next version. Default false: dry run. */\n apply?: boolean;\n /** Migrate a world that was not created from a connector template. */\n force?: boolean;\n};\n\nexport async function migrateWorld(\n slug: string,\n input: MigrateWorldOptions = {},\n options: WorldsClientOptions = {},\n): Promise<WorldMigrationReport> {\n if (slug.includes(\"@\"))\n throw new Error(\n `migrateWorld converts a world's head version: pass the slug without @ref (got ${slug})`,\n );\n return apiRequest<WorldMigrationReport>(\n options,\n \"POST\",\n `/api/public/worlds/${encodeURIComponent(slug)}/migrate`,\n {\n ...(input.apply === undefined ? {} : { apply: input.apply }),\n ...(input.force === undefined ? {} : { force: input.force }),\n },\n );\n}\n\n/** Every connector world in the project, one report each. */\nexport async function migrateProjectWorlds(\n input: { apply?: boolean } = {},\n options: WorldsClientOptions = {},\n): Promise<{ worlds: WorldMigrationReport[]; applied: boolean }> {\n return apiRequest<{ worlds: WorldMigrationReport[]; applied: boolean }>(\n options,\n \"POST\",\n \"/api/public/worlds/migrate\",\n input.apply === undefined ? {} : { apply: input.apply },\n );\n}\n","/**\n * The `gateway` command tree, with no dependency: groups hold commands, a\n * command declares its positionals and flags, help is generated from the\n * declarations so `gateway <group> --help` always matches what runs.\n *\n * Flags: `--name value`, `--name=value`, `--flag` (boolean), repeatable flags\n * collect into arrays when declared `repeat: true`. Anything after `--` is\n * positional.\n */\n\nexport type FlagSpec = {\n name: string;\n help: string;\n /** Short alias, e.g. \"m\" for --message. */\n short?: string;\n /** Boolean flags take no value. */\n boolean?: boolean;\n repeat?: boolean;\n default?: string | boolean;\n /** Environment variable that fills the flag when it is not given. */\n env?: string;\n};\n\nexport type PositionalSpec = {\n name: string;\n help: string;\n optional?: boolean;\n /** Collects every remaining positional. */\n variadic?: boolean;\n};\n\nexport type Parsed = {\n positionals: string[];\n flags: Record<string, string | boolean | string[] | undefined>;\n};\n\nexport type CommandSpec = {\n name: string;\n help: string;\n positionals?: PositionalSpec[];\n flags?: FlagSpec[];\n /** Long-form notes printed under the usage line in `--help`. */\n notes?: string;\n run: (args: Parsed, ctx: CommandContext) => Promise<number | void>;\n};\n\nexport type CommandContext = {\n stdout: (line: string) => void;\n stderr: (line: string) => void;\n /** Read all of stdin (for --value-less secrets, piped rows). */\n stdin: () => Promise<string>;\n /** Stdin as a stream, for inputs too large to hold (`worlds data import … -`). */\n stdinStream?: () => NodeJS.ReadableStream;\n};\n\nexport class CommandGroup {\n readonly groups = new Map<string, CommandGroup>();\n readonly commands = new Map<string, CommandSpec>();\n /** Long-form notes printed under the command list in `--help`. */\n notes?: string;\n constructor(\n readonly name: string,\n readonly help: string,\n ) {}\n group(name: string, help: string): CommandGroup {\n const existing = this.groups.get(name);\n if (existing) return existing;\n const created = new CommandGroup(name, help);\n this.groups.set(name, created);\n return created;\n }\n command(spec: CommandSpec): this {\n this.commands.set(spec.name, spec);\n return this;\n }\n}\n\nexport class CliError extends Error {\n constructor(\n message: string,\n readonly exitCode = 2,\n ) {\n super(message);\n }\n}\n\nexport function parseArgs(spec: CommandSpec, argv: string[]): Parsed {\n const flagSpecs = spec.flags ?? [];\n const byName = new Map<string, FlagSpec>();\n for (const f of flagSpecs) {\n byName.set(f.name, f);\n if (f.short) byName.set(f.short, f);\n }\n const positionals: string[] = [];\n const flags: Parsed[\"flags\"] = {};\n let onlyPositionals = false;\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i]!;\n if (onlyPositionals || !arg.startsWith(\"-\") || arg === \"-\") {\n positionals.push(arg);\n continue;\n }\n if (arg === \"--\") {\n onlyPositionals = true;\n continue;\n }\n const bare = arg.replace(/^--?/, \"\");\n const [rawName, inlineValue] = bare.includes(\"=\")\n ? [bare.slice(0, bare.indexOf(\"=\")), bare.slice(bare.indexOf(\"=\") + 1)]\n : [bare, undefined];\n const f = byName.get(rawName);\n if (!f) throw new CliError(`Unknown flag --${rawName} for ${spec.name}`);\n if (f.boolean) {\n flags[f.name] =\n inlineValue === undefined ? true : inlineValue !== \"false\";\n continue;\n }\n let value = inlineValue;\n if (value === undefined) {\n const next = argv[i + 1];\n if (next === undefined || (next.startsWith(\"--\") && next.length > 2))\n throw new CliError(`--${f.name} needs a value`);\n value = next;\n i++;\n }\n if (f.repeat) {\n const current = flags[f.name];\n flags[f.name] = Array.isArray(current) ? [...current, value] : [value];\n } else flags[f.name] = value;\n }\n for (const f of flagSpecs) {\n if (flags[f.name] !== undefined) continue;\n const fromEnv = f.env ? process.env[f.env] : undefined;\n if (fromEnv !== undefined && fromEnv !== \"\") flags[f.name] = fromEnv;\n else if (f.default !== undefined) flags[f.name] = f.default;\n }\n const specs = spec.positionals ?? [];\n const required = specs.filter((p) => !p.optional && !p.variadic).length;\n if (positionals.length < required)\n throw new CliError(\n `${spec.name} needs ${specs\n .slice(0, required)\n .map((p) => `<${p.name}>`)\n .join(\" \")}`,\n );\n const variadic = specs.some((p) => p.variadic);\n if (!variadic && positionals.length > specs.length)\n throw new CliError(\n `${spec.name} takes ${specs.length} argument${specs.length === 1 ? \"\" : \"s\"}, got ${positionals.length}`,\n );\n return { positionals, flags };\n}\n\n/** Typed accessors so commands never repeat the narrowing. */\nexport const arg = {\n str(p: Parsed, name: string): string | undefined {\n const v = p.flags[name];\n return typeof v === \"string\" ? v : undefined;\n },\n bool(p: Parsed, name: string): boolean {\n return p.flags[name] === true;\n },\n list(p: Parsed, name: string): string[] {\n const v = p.flags[name];\n if (Array.isArray(v)) return v;\n return typeof v === \"string\" ? [v] : [];\n },\n int(p: Parsed, name: string): number | undefined {\n const v = arg.str(p, name);\n if (v === undefined) return undefined;\n const n = Number(v);\n if (!Number.isInteger(n))\n throw new CliError(`--${name} must be an integer`);\n return n;\n },\n};\n\nfunction usageLine(path: string[], spec: CommandSpec): string {\n const pos = (spec.positionals ?? [])\n .map((p) =>\n p.variadic\n ? `<${p.name}...>`\n : p.optional\n ? `[${p.name}]`\n : `<${p.name}>`,\n )\n .join(\" \");\n return `${path.join(\" \")} ${pos}`.trim();\n}\n\nexport function helpFor(\n path: string[],\n node: CommandGroup | CommandSpec,\n): string {\n if (node instanceof CommandGroup) {\n const lines = [`${path.join(\" \")} — ${node.help}`, \"\"];\n for (const [name, g] of node.groups)\n lines.push(` ${name.padEnd(16)} ${g.help}`);\n for (const [name, c] of node.commands)\n lines.push(` ${name.padEnd(16)} ${c.help}`);\n if (node.notes) lines.push(\"\", node.notes);\n lines.push(\"\", `Run '${path.join(\" \")} <command> --help' for details.`);\n return lines.join(\"\\n\");\n }\n const lines = [usageLine(path, node), \"\", ` ${node.help}`];\n const pos = node.positionals ?? [];\n if (pos.length) {\n lines.push(\"\", \"Arguments:\");\n for (const p of pos) lines.push(` ${p.name.padEnd(18)} ${p.help}`);\n }\n const flags = node.flags ?? [];\n if (flags.length) {\n lines.push(\"\", \"Options:\");\n for (const f of flags) {\n const label = `--${f.name}${f.short ? `, -${f.short}` : \"\"}${f.boolean ? \"\" : \" <value>\"}`;\n const extras = [\n f.default !== undefined ? `default ${String(f.default)}` : null,\n f.env ? `env ${f.env}` : null,\n ]\n .filter(Boolean)\n .join(\", \");\n lines.push(\n ` ${label.padEnd(28)} ${f.help}${extras ? ` (${extras})` : \"\"}`,\n );\n }\n }\n if (node.notes) lines.push(\"\", node.notes);\n return lines.join(\"\\n\");\n}\n\n/** Walk the tree and run: exit code 0 on success, 2 on usage error, 1 on failure. */\nexport async function dispatch(\n root: CommandGroup,\n argv: string[],\n ctx: CommandContext,\n): Promise<number> {\n let node: CommandGroup = root;\n const path = [root.name];\n let i = 0;\n while (i < argv.length) {\n const token = argv[i]!;\n if (token === \"--help\" || token === \"-h\") {\n ctx.stdout(helpFor(path, node));\n return 0;\n }\n const group = node.groups.get(token);\n if (group) {\n node = group;\n path.push(token);\n i++;\n continue;\n }\n const command = node.commands.get(token);\n if (command) {\n const rest = argv.slice(i + 1);\n if (rest.includes(\"--help\") || rest.includes(\"-h\")) {\n ctx.stdout(helpFor([...path, token], command));\n return 0;\n }\n try {\n const parsed = parseArgs(command, rest);\n const code = await command.run(parsed, ctx);\n return code ?? 0;\n } catch (error) {\n if (error instanceof CliError) {\n ctx.stderr(error.message);\n return error.exitCode;\n }\n ctx.stderr(error instanceof Error ? error.message : String(error));\n return 1;\n }\n }\n ctx.stderr(\n `Unknown command '${token}' under '${path.join(\" \")}'.\\n\\n${helpFor(path, node)}`,\n );\n return 2;\n }\n ctx.stdout(helpFor(path, node));\n return node === root ? 0 : 2;\n}\n","import * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\n\nimport { CliError } from \"./router\";\n\n/**\n * Where the CLI's credentials come from, in this order (the same as the\n * Python CLI): explicit --host, environment (GATEWAY_HOST, GATEWAY_PUBLIC_KEY,\n * GATEWAY_SECRET_KEY / GATEWAY_API_KEY), then ~/.gateway/config.json written\n * by `gateway auth login`. `GATEWAY_ENV_FILE=path` fills the environment from\n * a KEY=value file first (see `loadEnvFile`).\n */\nexport type StoredConfig = {\n host?: string;\n public_key?: string;\n api_key?: string;\n};\n\nexport function configPath(): string {\n return path.join(\n process.env.GATEWAY_CONFIG_DIR ?? path.join(os.homedir(), \".gateway\"),\n \"config.json\",\n );\n}\n\nexport function readConfig(): StoredConfig {\n try {\n return JSON.parse(fs.readFileSync(configPath(), \"utf8\")) as StoredConfig;\n } catch {\n return {};\n }\n}\n\nexport function writeConfig(config: StoredConfig): void {\n const file = configPath();\n fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });\n fs.writeFileSync(file, JSON.stringify(config, null, 2) + \"\\n\", { mode: 0o600 });\n}\n\nexport function clearConfig(): boolean {\n try {\n fs.unlinkSync(configPath());\n return true;\n } catch {\n return false;\n }\n}\n\nexport type Credentials = { host: string; publicKey: string; secretKey: string };\n\n/** The accepted env-file form, printed by `gateway --help` and the docs. */\nexport const ENV_FILE_FORM =\n \"GATEWAY_ENV_FILE=path loads a KEY=value file first: `KEY = value`, quoted values, \" +\n \"`export KEY=value` and `#` comments are all accepted; the shell's environment wins.\";\n\n/**\n * Parse a KEY=value file the way a person writes one, not the way `source`\n * reads one. Brex retrospective: the customer's `.env` had `GATEWAY_HOST = …`\n * (spaces around `=`), which the shell refused to source and the CLI could not\n * read either. Accepted: blank lines and `#` comments, an `export ` prefix,\n * spaces around `=`, single- or double-quoted values (quotes stripped, nothing\n * inside interpreted). Not accepted: a line without `=`, which is reported by\n * number rather than skipped, because a silently dropped credential shows up\n * later as \"API key not configured\".\n */\nexport function parseEnvFile(text: string): Record<string, string> {\n const values: Record<string, string> = {};\n const lines = text.split(/\\r?\\n/);\n for (let index = 0; index < lines.length; index++) {\n const line = lines[index]!.trim();\n if (!line || line.startsWith(\"#\")) continue;\n const assignment = line.startsWith(\"export \") ? line.slice(\"export \".length).trim() : line;\n const eq = assignment.indexOf(\"=\");\n if (eq === -1) throw new CliError(`env file line ${index + 1} is not KEY=value: ${line}`);\n const key = assignment.slice(0, eq).trim();\n let value = assignment.slice(eq + 1).trim();\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key))\n throw new CliError(`env file line ${index + 1} has an invalid variable name: ${key || line}`);\n const quote = value[0];\n if ((quote === '\"' || quote === \"'\") && value.length >= 2 && value.endsWith(quote))\n value = value.slice(1, -1);\n values[key] = value;\n }\n return values;\n}\n\n/**\n * Put `GATEWAY_ENV_FILE`'s variables into the process environment, without\n * overriding anything already set there. Explicit on purpose: the CLI never\n * reads a `.env` it was not pointed at. Vendor keys named by connector.toml\n * ride along, so a local capture sees them too. Returns the keys it set.\n */\nexport function loadEnvFile(): string[] {\n const file = process.env.GATEWAY_ENV_FILE;\n if (!file) return [];\n let text: string;\n try {\n text = fs.readFileSync(file, \"utf8\");\n } catch (error) {\n throw new CliError(`GATEWAY_ENV_FILE=${file} could not be read: ${(error as Error).message}`);\n }\n const set: string[] = [];\n for (const [key, value] of Object.entries(parseEnvFile(text))) {\n if (process.env[key] !== undefined) continue;\n process.env[key] = value;\n set.push(key);\n }\n return set;\n}\n\nexport function resolveCredentials(hostFlag?: string): Credentials {\n const stored = readConfig();\n const host = (hostFlag ?? process.env.GATEWAY_HOST ?? stored.host ?? \"\").replace(/\\/+$/, \"\");\n const publicKey = process.env.GATEWAY_PUBLIC_KEY ?? stored.public_key ?? \"\";\n const secretKey =\n process.env.GATEWAY_SECRET_KEY ?? process.env.GATEWAY_API_KEY ?? stored.api_key ?? \"\";\n if (!host)\n throw new CliError(\n \"Host not configured. Pass --host, set GATEWAY_HOST, or run `gateway auth login`.\",\n );\n if (!publicKey || !secretKey)\n throw new CliError(\n \"API key not configured. Set GATEWAY_PUBLIC_KEY and GATEWAY_SECRET_KEY, or run `gateway auth login`.\",\n );\n return { host, publicKey, secretKey };\n}\n\n/** A non-2xx answer from the platform: the status is a field, never something to regex out of the text. */\nexport class ApiError extends CliError {\n constructor(\n readonly status: number,\n readonly method: string,\n readonly route: string,\n readonly text: string,\n ) {\n super(`${method} ${route} -> ${status}: ${text.slice(0, 600)}`, 1);\n }\n}\n\n/** One JSON request against the platform, Basic-authenticated with the project key. */\nexport async function api<T = unknown>(\n creds: Credentials,\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\",\n route: string,\n body?: unknown,\n init: { timeoutMs?: number } = {},\n): Promise<T> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), init.timeoutMs ?? 120_000);\n try {\n const res = await fetch(`${creds.host}${route}`, {\n method,\n headers: {\n \"content-type\": \"application/json\",\n accept: \"application/json\",\n authorization:\n \"Basic \" + Buffer.from(`${creds.publicKey}:${creds.secretKey}`).toString(\"base64\"),\n },\n ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n signal: controller.signal,\n });\n const text = await res.text();\n if (!res.ok) throw new ApiError(res.status, method, route, text);\n return (text ? JSON.parse(text) : {}) as T;\n } finally {\n clearTimeout(timer);\n }\n}\n\nexport function printJson(ctx: { stdout: (line: string) => void }, value: unknown): void {\n ctx.stdout(JSON.stringify(value, null, 2));\n}\n","import { spawn, spawnSync } from \"node:child_process\";\nimport * as fs from \"node:fs\";\nimport * as net from \"node:net\";\nimport * as path from \"node:path\";\n\nimport { CliError } from \"../router\";\nimport { type Credentials, resolveCredentials } from \"../config\";\nimport type { RuntimeRequest } from \"./client\";\n\n/**\n * The schema runtime, run on THIS machine. The npm package carries the SDK's\n * `gatewaysdk/environment` directory (stdlib-only Python, the same files the\n * platform's bridge executes), so any python3 >= 3.11 on the path runs it\n * exactly as the platform does — the same bootstrap, JSON in, JSON out. No\n * pip, no PyPI. When there is no such Python, callers fall back to\n * `POST /api/public/worlds/runtime`.\n *\n * `GATEWAY_RUNTIME=local|platform|auto` (default auto) forces one side;\n * `GATEWAY_PYTHON` names the interpreter (otherwise python3.13, python3.12,\n * python3.11, python3, python, then `uv python find` are tried in that order).\n */\n\nconst MIN_PYTHON: [number, number] = [3, 11];\nconst DIAGNOSTIC_TAIL = 600;\n\n/** The end of a failed run's output: a Python traceback names the exception last. */\nfunction tailOf(output: string): string {\n return output.length > DIAGNOSTIC_TAIL\n ? `…${output.slice(-DIAGNOSTIC_TAIL)}`\n : output;\n}\n\n/** The platform's own bootstrap: build the `gatewaysdk` package in memory from\n * the runtime root and run the bridge as __main__ (see worldSchemaRuntime.ts). */\nconst BRIDGE_BOOTSTRAP = `import sys,runpy,types,os\nroot=sys.argv[1]\npackage=types.ModuleType('gatewaysdk')\npackage.__path__=[os.path.join(root,'gatewaysdk')]\nsys.modules['gatewaysdk']=package\nrunpy.run_module('gatewaysdk.environment.schema.platform',run_name='__main__')`;\n\n/** The same, but running the schema module's own CLI (serve, connector-capture …)\n * with the arguments after the root. */\nconst MODULE_BOOTSTRAP = `import sys,runpy,types,os\nroot=sys.argv[1]\npackage=types.ModuleType('gatewaysdk')\npackage.__path__=[os.path.join(root,'gatewaysdk')]\nsys.modules['gatewaysdk']=package\nsys.argv=['gateway worlds']+sys.argv[2:]\nrunpy.run_module('gatewaysdk.environment.schema',run_name='__main__')`;\n\nexport type RuntimeMode = \"auto\" | \"local\" | \"platform\";\n\nexport function runtimeMode(): RuntimeMode {\n const raw = (process.env.GATEWAY_RUNTIME ?? \"auto\").toLowerCase();\n if (raw === \"local\" || raw === \"platform\" || raw === \"auto\") return raw;\n throw new CliError(\n `GATEWAY_RUNTIME must be local, platform or auto (got ${raw})`,\n );\n}\n\n/** Where the bundled runtime lives: `<package>/runtime` beside dist/, or the\n * monorepo's SDK source when running from the repository.\n *\n * The entry is `dist/cli.js` (the published bin) or `src/cli.ts` (from\n * source): one directory under the package root either way, so the Python\n * source is `<entry dir>/../../sdk/src` — `gatewaysdk/sdk/src`. It used to\n * walk one level too far (`<repo>/sdk/src`, which does not exist), so every\n * from-source run missed the runtime and fell back to the platform, demanding\n * a host for commands that need none (`schema init --connector salesforce`,\n * 2026-09-16). */\nexport function runtimeRoot(): string | null {\n const candidates: string[] = [];\n if (process.env.GATEWAY_RUNTIME_PATH)\n candidates.push(process.env.GATEWAY_RUNTIME_PATH);\n const entry =\n process.argv[1] && fs.existsSync(process.argv[1])\n ? path.dirname(fs.realpathSync(process.argv[1]))\n : null;\n if (entry) {\n candidates.push(path.resolve(entry, \"..\", \"runtime\"));\n candidates.push(path.resolve(entry, \"..\", \"..\", \"runtime\"));\n candidates.push(path.resolve(entry, \"..\", \"..\", \"sdk\", \"src\"));\n }\n candidates.push(path.resolve(process.cwd(), \"runtime\"));\n for (const root of candidates)\n if (\n fs.existsSync(\n path.join(root, \"gatewaysdk\", \"environment\", \"schema\", \"platform.py\"),\n )\n )\n return root;\n return null;\n}\n\nlet pythonCache: string | null | undefined;\n/** What the search saw, for the one line `pythonAdvice` prints: each candidate\n * and its version, or null when it did not run. */\nlet pythonProbes: { name: string; version: string | null }[] = [];\n\n/** Forget the cached interpreter (tests re-probe with a different PATH or env). */\nexport function resetPythonCache(): void {\n pythonCache = undefined;\n pythonProbes = [];\n}\n\n/** Versioned names first: on a Mac the bare `python3` is often the system 3.9,\n * while Homebrew, pyenv or uv put a `python3.12` beside it. Last, ask uv for\n * an interpreter it manages (`uv python find` prints a path and downloads\n * nothing). Brex retrospective: the customer had to discover GATEWAY_PYTHON\n * by hand because the CLI stopped at `python3` = 3.9. */\nconst PYTHON_CANDIDATES = [\n \"python3.13\",\n \"python3.12\",\n \"python3.11\",\n \"python3\",\n \"python\",\n];\nconst UV_FIND = [\"python\", \"find\", `>=${MIN_PYTHON.join(\".\")}`];\n\nfunction probeVersion(name: string): string | null {\n const probe = spawnSync(\n name,\n [\"-c\", \"import sys;print(sys.version_info[0],sys.version_info[1])\"],\n { encoding: \"utf8\", timeout: 10_000 },\n );\n if (probe.status !== 0) return null;\n const [major, minor] = probe.stdout.trim().split(/\\s+/).map(Number);\n return Number.isInteger(major) && Number.isInteger(minor)\n ? `${major}.${minor}`\n : null;\n}\n\nfunction atLeastMinimum(version: string): boolean {\n const [major, minor] = version.split(\".\").map(Number);\n return (\n major! > MIN_PYTHON[0] ||\n (major === MIN_PYTHON[0] && minor! >= MIN_PYTHON[1])\n );\n}\n\n/** The interpreter uv would hand out, or null when uv is absent or has none. */\nfunction uvPython(): string | null {\n const found = spawnSync(\"uv\", UV_FIND, { encoding: \"utf8\", timeout: 10_000 });\n if (found.status !== 0) return null;\n const line = found.stdout.trim().split(/\\r?\\n/)[0] ?? \"\";\n return line || null;\n}\n\n/** A python3 at or above 3.11, or null. Cached for the process. `GATEWAY_PYTHON`\n * names the interpreter and is the only candidate then; otherwise the versioned\n * names, the bare ones, then uv's. */\nexport function findPython(): string | null {\n if (pythonCache !== undefined) return pythonCache;\n const named = process.env.GATEWAY_PYTHON;\n const candidates = named ? [named] : PYTHON_CANDIDATES;\n for (const name of candidates) {\n const version = probeVersion(name);\n pythonProbes.push({ name, version });\n if (version && atLeastMinimum(version)) {\n pythonCache = name;\n return name;\n }\n }\n if (!named) {\n const fromUv = uvPython();\n const version = fromUv ? probeVersion(fromUv) : null;\n pythonProbes.push({ name: fromUv ?? \"uv python find\", version });\n if (fromUv && version && atLeastMinimum(version)) {\n pythonCache = fromUv;\n return fromUv;\n }\n }\n pythonCache = null;\n return null;\n}\n\n/** ONE actionable line for a machine without a usable Python: what was found\n * and how to point the CLI at a newer interpreter. */\nexport function pythonAdvice(): string {\n findPython();\n const floor = MIN_PYTHON.join(\".\");\n const named = process.env.GATEWAY_PYTHON;\n const seen = pythonProbes\n .filter((probe) => probe.version)\n .map((probe) => `${probe.name} is ${probe.version}`);\n const found = seen.length\n ? seen.join(\", \")\n : named\n ? `${named} did not run`\n : \"none on PATH\";\n return (\n `No python3 >= ${floor} usable (${found}); set GATEWAY_PYTHON to a newer interpreter, ` +\n `e.g. GATEWAY_PYTHON=\"$(brew --prefix python@3.12)/bin/python3.12\" or GATEWAY_PYTHON=\"$(uv python find 3.12)\".`\n );\n}\n\n/** Why `localRuntime()` answers null, in one line: the mode, the interpreter\n * or the bundled files — so a refusal never blames Python on a machine that\n * merely set GATEWAY_RUNTIME=platform. */\nexport function localRuntimeReason(): string {\n if (runtimeMode() === \"platform\")\n return \"GATEWAY_RUNTIME=platform forces the hosted side.\";\n if (!findPython()) return pythonAdvice();\n if (!runtimeRoot())\n return \"The bundled runtime is missing (set GATEWAY_RUNTIME_PATH).\";\n return \"\";\n}\n\n/** Can this machine run the runtime itself? Both a Python and the bundled files. */\nexport function localRuntime(): { python: string; root: string } | null {\n if (runtimeMode() === \"platform\") return null;\n const python = findPython();\n const root = runtimeRoot();\n if (!python || !root) {\n if (runtimeMode() === \"local\")\n throw new CliError(\n !python\n ? `GATEWAY_RUNTIME=local but ${pythonAdvice()}`\n : \"GATEWAY_RUNTIME=local but the bundled runtime is missing (set GATEWAY_RUNTIME_PATH)\",\n );\n return null;\n }\n return { python, root };\n}\n\n/** Does the local Python have PyYAML? `conform` needs it for .yaml specs. */\nexport function localPythonHasYaml(python: string): boolean {\n return (\n spawnSync(python, [\"-c\", \"import yaml\"], { timeout: 10_000 }).status === 0\n );\n}\n\n/** One bridge request through the local runtime: JSON in on stdin, JSON out. */\nexport async function localBridge<T = Record<string, unknown>>(\n request: RuntimeRequest,\n local: { python: string; root: string },\n opts: { timeoutMs?: number } = {},\n): Promise<T> {\n const input = JSON.stringify(request);\n return await new Promise<T>((resolve, reject) => {\n const child = spawn(\n local.python,\n [\"-I\", \"-B\", \"-c\", BRIDGE_BOOTSTRAP, local.root],\n {\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n // This is the author's machine running the author's world: the one\n // place the runtime may import and run a world's own Python (check's\n // handler execution, `worlds call`, `worlds test` tool cases).\n env: {\n PATH: process.env.PATH ?? \"\",\n HOME: process.env.HOME ?? \"\",\n TMPDIR: process.env.TMPDIR ?? \"\",\n GATEWAY_RUNTIME_EXECUTE: \"1\",\n },\n },\n );\n const out: Buffer[] = [];\n const err: Buffer[] = [];\n const timer = setTimeout(\n () => child.kill(\"SIGKILL\"),\n opts.timeoutMs ?? 300_000,\n );\n child.stdout.on(\"data\", (chunk: Buffer) => out.push(chunk));\n child.stderr.on(\"data\", (chunk: Buffer) => err.push(chunk));\n child.on(\"error\", (error) => {\n clearTimeout(timer);\n reject(\n new CliError(\n `local runtime could not start (${local.python}): ${error.message}`,\n 1,\n ),\n );\n });\n child.on(\"close\", (code) => {\n clearTimeout(timer);\n const text = Buffer.concat(out).toString(\"utf8\");\n const stderr = Buffer.concat(err).toString(\"utf8\");\n let payload: unknown = null;\n try {\n payload = text ? JSON.parse(text) : null;\n } catch {\n payload = null;\n }\n if (payload && typeof payload === \"object\") {\n resolve(payload as T);\n return;\n }\n reject(\n new CliError(\n `local runtime (${request.command}) exited ${code}: ${tailOf((stderr || text).trim()) || \"no output\"}`,\n 1,\n ),\n );\n });\n child.stdin.end(input);\n });\n}\n\n/** `pid <n> (<command>)` of whatever listens on `port`, from lsof when this\n * machine has it; null when nothing can be said. Best effort, never an error. */\nexport function portOwner(port: number): string | null {\n const found = spawnSync(\"lsof\", [\"-nP\", `-iTCP:${port}`, \"-sTCP:LISTEN\", \"-Fpc\"], {\n encoding: \"utf8\",\n timeout: 5_000,\n });\n if (found.error || found.status !== 0) return null;\n let pid: string | null = null;\n let command: string | null = null;\n for (const line of found.stdout.split(\"\\n\")) {\n if (line.startsWith(\"p\") && pid === null) pid = line.slice(1);\n else if (line.startsWith(\"c\") && pid !== null && command === null) command = line.slice(1);\n }\n if (pid === null) return null;\n return `pid ${pid}${command ? ` (${command})` : \"\"}`;\n}\n\n/** Refuse, by name, a port another process already holds — BEFORE the runtime\n * is spawned. The Python side refuses too, but a backgrounded serve's output\n * goes unread, and every curl after it hit whatever else answered on the port\n * (CRM dogfood, 2026-09-16): this serve never answers from another server. */\nexport async function assertPortFree(port: number, host = \"127.0.0.1\"): Promise<void> {\n const taken = await new Promise<boolean>((resolve) => {\n const probe = net.createServer();\n probe.once(\"error\", () => resolve(true));\n probe.listen(port, host, () => probe.close(() => resolve(false)));\n });\n if (!taken) return;\n const owner = portOwner(port);\n throw new CliError(\n `port ${port} on ${host} is already in use${owner ? ` by ${owner}` : \"\"}; ` +\n \"nothing was served there — pass another --port, or stop that server first\",\n 1,\n );\n}\n\n/** Run the schema module's own CLI in the foreground (serve, connector-capture …). */\nexport async function localModule(\n argv: string[],\n local: { python: string; root: string },\n opts: { env?: Record<string, string>; cwd?: string } = {},\n): Promise<number> {\n return await new Promise<number>((resolve, reject) => {\n const child = spawn(\n local.python,\n [\"-B\", \"-c\", MODULE_BOOTSTRAP, local.root, ...argv],\n {\n stdio: \"inherit\",\n cwd: opts.cwd,\n env: { ...process.env, ...opts.env },\n },\n );\n // The child owns the port (`worlds serve`); a signal that stops this\n // process must stop it too, or the server lives on with no way to reach\n // the foreground that started it. A SIGKILL, or a wrapper that swallows\n // the signal, reaches nothing here — for that the runtime's `serve`\n // watches its parent pid and closes when this process is gone.\n const forward = (signal: NodeJS.Signals) => () => {\n if (child.exitCode === null && child.signalCode === null) child.kill(signal);\n };\n const handlers: [NodeJS.Signals, () => void][] = [\n [\"SIGINT\", forward(\"SIGINT\")],\n [\"SIGTERM\", forward(\"SIGTERM\")],\n [\"SIGHUP\", forward(\"SIGHUP\")],\n ];\n for (const [signal, handler] of handlers) process.on(signal, handler);\n const release = () => {\n for (const [signal, handler] of handlers) process.off(signal, handler);\n };\n child.on(\"error\", (error) => {\n release();\n reject(\n new CliError(\n `local runtime could not start (${local.python}): ${error.message}`,\n 1,\n ),\n );\n });\n child.on(\"close\", (code, signal) => {\n release();\n resolve(code ?? (signal ? 130 : 1));\n });\n });\n}\n\n/** Credentials when the platform may be needed; null when a local runtime\n * will do and none are configured (a `schema check` needs no login). */\nexport function credentialsForRuntime(hostFlag?: string): Credentials | null {\n try {\n return resolveCredentials(hostFlag);\n } catch (error) {\n if (error instanceof CliError && localRuntime()) return null;\n throw error;\n }\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport { CliError } from \"../router\";\nimport { localBridge, localPythonHasYaml, localRuntime, localRuntimeReason } from \"./local\";\nimport type { Credentials } from \"../config\";\n\n/**\n * The wire to the schema runtime, which is Python and runs on the platform:\n * a world directory goes up as `[{path, content b64}]`, one bridge request\n * comes back verbatim, and any files in the answer land back in the\n * directory. Nothing here interprets a contract — that is the bridge's job.\n */\n\nexport type WorldFile = { path: string; content: string };\n\n/** Directories that are never part of a world's files. */\nconst SKIP_DIRS = new Set([\"__pycache__\", \".git\", \"node_modules\", \".gateway\"]);\n\n/** Every file under `dir` as base64 entries with forward-slash relative paths,\n * sorted so the same tree always produces the same request. */\n/** Compiled snapshots (`db/state.*`, `scenarios/<name>/state.*`) are build outputs\n * of the tree's data, never inputs: the runtime rebuilds them from the journals\n * and strips them from what it returns, and a real world's snapshots alone can\n * exceed the bridge's 64 MiB request cap. */\nconst BUILD_OUTPUT = /(^|\\/)state\\.(sqlite|json)$/;\n\nexport function isBuildOutput(relPath: string): boolean {\n return BUILD_OUTPUT.test(relPath);\n}\n\nexport function readWorldFiles(dir: string, opts: { buildOutputs?: boolean } = {}): WorldFile[] {\n if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())\n throw new CliError(`Not a directory: ${dir}`);\n const out: WorldFile[] = [];\n const walk = (rel: string) => {\n const abs = rel ? path.join(dir, rel) : dir;\n const entries = fs.readdirSync(abs, { withFileTypes: true });\n entries.sort((a, b) => a.name.localeCompare(b.name));\n for (const entry of entries) {\n const childRel = rel ? `${rel}/${entry.name}` : entry.name;\n if (entry.isDirectory()) {\n if (!SKIP_DIRS.has(entry.name)) walk(childRel);\n } else if (entry.isFile()) {\n if (!opts.buildOutputs && isBuildOutput(childRel)) continue;\n out.push({\n path: childRel,\n content: fs.readFileSync(path.join(dir, childRel)).toString(\"base64\"),\n });\n }\n }\n };\n walk(\"\");\n return out.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));\n}\n\nfunction assertSafeRelPath(rel: string): void {\n const parts = rel.split(\"/\");\n if (\n !rel ||\n rel.startsWith(\"/\") ||\n rel.includes(\"\\\\\") ||\n /^[A-Za-z]:/.test(rel) ||\n parts.some((p) => p === \"\" || p === \".\" || p === \"..\")\n )\n throw new CliError(`The runtime returned an unsafe file path: ${rel}`, 1);\n}\n\n/** Write bridge files into `dir`. With `clean`, files the runtime did not\n * return are removed first (the skipped dirs are left alone), so the tree\n * becomes exactly what the runtime holds. Returns the written paths. */\nexport function writeWorldFiles(\n dir: string,\n files: WorldFile[],\n opts: { clean?: boolean } = {},\n): string[] {\n for (const file of files) assertSafeRelPath(file.path);\n if (opts.clean && fs.existsSync(dir)) {\n const keep = new Set(files.map((f) => f.path));\n for (const existing of readWorldFiles(dir)) {\n if (!keep.has(existing.path)) fs.rmSync(path.join(dir, existing.path));\n }\n pruneEmptyDirs(dir);\n }\n fs.mkdirSync(dir, { recursive: true });\n const written: string[] = [];\n for (const file of files) {\n const target = path.join(dir, file.path);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n fs.writeFileSync(target, Buffer.from(file.content, \"base64\"));\n written.push(file.path);\n }\n return written;\n}\n\nfunction pruneEmptyDirs(root: string): void {\n const walk = (abs: string): boolean => {\n let empty = true;\n for (const entry of fs.readdirSync(abs, { withFileTypes: true })) {\n const child = path.join(abs, entry.name);\n if (entry.isDirectory()) {\n if (SKIP_DIRS.has(entry.name)) {\n empty = false;\n continue;\n }\n if (walk(child)) fs.rmdirSync(child);\n else empty = false;\n } else empty = false;\n }\n return empty;\n };\n walk(root);\n}\n\n/** The bridge's structured diagnostic, exactly as the Python ContractError\n * carries it (`code`, `message`, `path`, `schema_path`, plus context). */\nexport type BridgeErrorDetail = {\n code: string;\n message: string;\n path?: string;\n schema_path?: string;\n [key: string]: unknown;\n};\n\n/** Rendered the way the Python CLI prints a ContractError:\n * `{code} at {schema_path or path or '/'}: {message}`. */\nexport function formatBridgeError(detail: BridgeErrorDetail): string {\n const where = detail.schema_path || detail.path || \"/\";\n return `${detail.code} at ${where}: ${detail.message}`;\n}\n\nexport class BridgeRejected extends CliError {\n constructor(readonly detail: BridgeErrorDetail) {\n super(formatBridgeError(detail), 1);\n }\n}\n\nexport function detailFrom(payload: unknown): BridgeErrorDetail | null {\n if (!payload || typeof payload !== \"object\") return null;\n const error = (payload as { error?: unknown }).error;\n if (!error || typeof error !== \"object\") return null;\n const detail = error as Record<string, unknown>;\n if (typeof detail.code !== \"string\" || typeof detail.message !== \"string\") return null;\n return detail as BridgeErrorDetail;\n}\n\nexport type RuntimeRequest = { command: string } & Record<string, unknown>;\n\n/**\n * How a world directory travels on a request that runs it (check, test, call):\n * in place, as `world`, when the bundled runtime runs on this machine — so the\n * `[dependencies]` paths beside it resolve and its handlers may run — and as\n * `files` when the platform's bridge answers, which takes a tree and runs no\n * authored code.\n */\nexport function worldPayload(dir: string): { world: string } | { files: WorldFile[] } {\n const abs = path.resolve(dir);\n if (!fs.existsSync(abs) || !fs.statSync(abs).isDirectory()) throw new CliError(`Not a directory: ${abs}`);\n return localRuntime() ? { world: abs } : { files: readWorldFiles(abs) };\n}\n\n/**\n * `POST /api/public/worlds/runtime` with the bridge request verbatim. A\n * rejection — whether the platform relays it with a 4xx or as a 200 with\n * `status: \"rejected\"` — becomes a BridgeRejected; anything else non-OK is a\n * plain CliError with the status and body excerpt.\n */\nexport async function runtime<T extends Record<string, unknown> = Record<string, unknown>>(\n creds: Credentials | null,\n request: RuntimeRequest,\n opts: { timeoutMs?: number } = {},\n): Promise<T> {\n // This machine first, when it can: the bundled runtime with a local\n // python3 is what the platform runs anyway, minus the round trip. A .yaml\n // conform spec needs PyYAML, which the vendored runtime does not carry.\n const local = localRuntime();\n const yamlSpec =\n request.command === \"conform\" &&\n Array.isArray(request.openapi) &&\n (request.openapi as { path?: string }[]).some((doc) => /\\.ya?ml$/i.test(doc.path ?? \"\"));\n if (local && !(yamlSpec && !localPythonHasYaml(local.python))) {\n const payload = await localBridge<Record<string, unknown>>(request, local, opts);\n const detail = detailFrom(payload);\n if (detail) throw new BridgeRejected(detail);\n return payload as T;\n }\n if (!creds)\n throw new CliError(\n \"This needs the schema runtime (the CLI bundles it) or platform credentials (`gateway auth login`). \" +\n localRuntimeReason(),\n );\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), opts.timeoutMs ?? 180_000);\n const route = \"/api/public/worlds/runtime\";\n try {\n const res = await fetch(`${creds.host}${route}`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n accept: \"application/json\",\n authorization:\n \"Basic \" + Buffer.from(`${creds.publicKey}:${creds.secretKey}`).toString(\"base64\"),\n },\n body: JSON.stringify(request),\n signal: controller.signal,\n });\n const text = await res.text();\n let payload: unknown = null;\n try {\n payload = text ? JSON.parse(text) : {};\n } catch {\n payload = null;\n }\n const detail = detailFrom(payload);\n if (detail) throw new BridgeRejected(detail);\n if (!res.ok)\n throw new CliError(`POST ${route} (${request.command}) -> ${res.status}: ${text.slice(0, 600)}`, 1);\n if (payload === null) throw new CliError(`POST ${route} (${request.command}) returned non-JSON`, 1);\n return payload as T;\n } finally {\n clearTimeout(timer);\n }\n}\n\n/** Basic-auth headers for the few non-runtime routes this track calls. */\nexport function authHeaders(creds: Credentials): Record<string, string> {\n return {\n accept: \"application/json\",\n authorization:\n \"Basic \" + Buffer.from(`${creds.publicKey}:${creds.secretKey}`).toString(\"base64\"),\n };\n}\n\n/** Strip the `files` echo from a bridge report before printing it. */\nexport function withoutFiles<T extends Record<string, unknown>>(report: T): Omit<T, \"files\"> {\n const { files: _files, ...rest } = report;\n return rest;\n}\n\n/** JSON with sorted keys, the way the Python CLI prints bridge reports. */\nexport function sortedJson(value: unknown, indent = 2): string {\n const sort = (v: unknown): unknown => {\n if (Array.isArray(v)) return v.map(sort);\n if (v && typeof v === \"object\") {\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(v as Record<string, unknown>).sort())\n out[key] = sort((v as Record<string, unknown>)[key]);\n return out;\n }\n return v;\n };\n return JSON.stringify(sort(value), null, indent);\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport type { Credentials } from \"../config\";\nimport { CliError } from \"../router\";\nimport type { WorldQueryAcrossResult } from \"../../worlds/query\";\nimport {\n BridgeRejected,\n detailFrom,\n readWorldFiles,\n runtime,\n writeWorldFiles,\n type WorldFile,\n} from \"./client\";\nimport { localBridge, localRuntime, localRuntimeReason } from \"./local\";\n\n/**\n * Rows into, and counts out of, a world that lives in a LOCAL directory. The\n * `worlds data import|show` commands (registered by the platform track) call\n * these two for the directory case; a slug goes to the platform's world data\n * routes instead. The gate is the world's own contract, run by the platform\n * runtime: a bad row is refused with the field named and nothing is written.\n */\n\nexport type Rows = Record<string, Record<string, unknown>[]>;\nexport type ImportMode = \"append\" | \"replace\";\n\nexport type LocalImportResult = {\n kind: string;\n entity_counts: Record<string, number>;\n changed: boolean;\n /** Build outputs (`db/state.*`) dropped because the journals they were built from changed. */\n dropped_build_outputs?: string[];\n next?: string;\n};\n\nexport async function importLocalWorldData(\n dir: string,\n rows: Rows,\n opts: { mode?: ImportMode; merge?: \"upsert\" | \"fill\"; redact?: \"off\" | \"apply\" | \"refuse\" },\n creds: Credentials | null,\n): Promise<LocalImportResult> {\n const res = await runtime<{\n kind?: string;\n entity_counts?: Record<string, number>;\n changed?: boolean;\n files?: WorldFile[];\n }>(creds, {\n command: \"import-data\",\n files: readWorldFiles(dir),\n rows,\n mode: opts.mode ?? \"append\",\n ...(opts.merge && opts.merge !== \"upsert\" ? { merge: opts.merge } : {}),\n ...(opts.redact && opts.redact !== \"off\" ? { redact: opts.redact } : {}),\n });\n if (res.files?.length) writeWorldFiles(dir, res.files);\n // Snapshots are build outputs, not tree files: the runtime answers without\n // them, and the ones on disk were built from the journals BEFORE this import.\n // A served world ignores a stale snapshot and replays the journals, but the\n // files would still sit there claiming an older state — drop them, and let\n // `worlds schema compile` build them again from the data that is there now.\n const dropped = res.changed ? dropBuildOutputs(dir) : [];\n return {\n kind: res.kind ?? \"unknown\",\n entity_counts: res.entity_counts ?? {},\n changed: Boolean(res.changed),\n ...(dropped.length\n ? {\n dropped_build_outputs: dropped,\n next: `gateway worlds schema compile ${dir} # rebuilds the snapshots from the imported data`,\n }\n : {}),\n };\n}\n\nconst BUILD_OUTPUT = /(^|\\/)state\\.(sqlite|json)$/;\n\n/** Remove the compiled snapshots (`db/state.*`, `scenarios/<name>/state.*`)\n * that no longer match the tree's journals. */\nexport function dropBuildOutputs(dir: string): string[] {\n const dropped: string[] = [];\n for (const file of readWorldFiles(dir, { buildOutputs: true })) {\n if (!BUILD_OUTPUT.test(file.path)) continue;\n fs.rmSync(path.join(dir, file.path), { force: true });\n dropped.push(file.path);\n }\n return dropped;\n}\n\n/**\n * The same bridge import over the tree, with the answered files discarded:\n * the rows are checked through the world's contract and nothing on disk\n * changes. A refused row surfaces as a BridgeRejected, as an import would.\n */\nexport async function checkLocalWorldData(\n dir: string,\n rows: Rows,\n creds: Credentials | null,\n opts: { redact?: \"off\" | \"apply\" | \"refuse\" } = {},\n): Promise<LocalImportResult> {\n const res = await runtime<{\n kind?: string;\n entity_counts?: Record<string, number>;\n changed?: boolean;\n }>(creds, {\n command: \"import-data\",\n files: readWorldFiles(dir),\n rows,\n mode: \"append\",\n ...(opts.redact && opts.redact !== \"off\" ? { redact: opts.redact } : {}),\n });\n return {\n kind: res.kind ?? \"unknown\",\n entity_counts: res.entity_counts ?? {},\n changed: Boolean(res.changed),\n };\n}\n\nexport type LocalShowResult = {\n kind: string;\n entity_counts?: Record<string, number>;\n entity?: string;\n rows?: Record<string, unknown>[];\n};\n\nexport async function showLocalWorldData(\n dir: string,\n entity: string | undefined,\n creds: Credentials | null,\n): Promise<LocalShowResult> {\n const res = await runtime<{\n kind?: string;\n entity_counts?: Record<string, number>;\n rows?: Record<string, unknown>[];\n }>(creds, {\n command: \"counts\",\n files: readWorldFiles(dir),\n ...(entity ? { entity } : {}),\n });\n const out: LocalShowResult = { kind: res.kind ?? \"unknown\" };\n if (entity) {\n out.entity = entity;\n out.rows = res.rows ?? [];\n } else out.entity_counts = res.entity_counts ?? {};\n return out;\n}\n\n/** field → stored value, or a list of them (any of). */\nexport type LocalQueryWhere = Record<string, string | string[]>;\n\nexport type LocalQueryOptions = {\n /** The `where` values are plaintext: the runtime resolves each to its stored form first. */\n resolve?: boolean;\n limit?: number;\n offset?: number;\n /** Read the rows a session opened in this scenario starts from (schema worlds). */\n scenario?: string;\n};\n\nexport type LocalQueryResult = {\n kind?: string;\n entity: string;\n scenario?: string;\n rows: Record<string, unknown>[];\n count: number;\n total: number | null;\n limit: number;\n offset: number;\n /** With `resolve`: the stored forms each field was matched against (`[]` for a dropped field). */\n resolved?: Record<string, (string | number)[]>;\n};\n\n/**\n * The bridge's `query` over the tree: one entity's rows matching `where`.\n * A refused query (unknown entity or field) surfaces as a BridgeRejected.\n */\nexport async function queryLocalWorldData(\n dir: string,\n entity: string,\n where: LocalQueryWhere,\n opts: LocalQueryOptions,\n creds: Credentials | null,\n): Promise<LocalQueryResult> {\n const res = await runtime<{\n kind?: string;\n entity?: string;\n rows?: Record<string, unknown>[];\n count?: number;\n total?: number | null;\n limit?: number;\n offset?: number;\n scenario?: string;\n resolved?: Record<string, (string | number)[]>;\n }>(creds, {\n command: \"query\",\n files: readWorldFiles(dir),\n entity,\n ...(Object.keys(where).length ? { where } : {}),\n ...(opts.limit !== undefined ? { limit: opts.limit } : {}),\n ...(opts.offset !== undefined ? { offset: opts.offset } : {}),\n ...(opts.resolve ? { resolve: true } : {}),\n ...(opts.scenario ? { scenario: opts.scenario } : {}),\n });\n const rows = res.rows ?? [];\n return {\n ...(res.kind ? { kind: res.kind } : {}),\n entity: res.entity ?? entity,\n ...(res.scenario ? { scenario: res.scenario } : {}),\n rows,\n count: res.count ?? rows.length,\n total: res.total ?? null,\n limit: res.limit ?? opts.limit ?? rows.length,\n offset: res.offset ?? opts.offset ?? 0,\n ...(res.resolved ? { resolved: res.resolved } : {}),\n };\n}\n\n/** A local across answer: the platform's groups, each world named by its\n * manifest name (the root) or its pin's slug (a dependency); no version ids,\n * since the trees are read where they sit. */\nexport type LocalQueryAcrossResult = {\n kind?: string;\n entity: string;\n groups: (Omit<WorldQueryAcrossResult[\"groups\"][number], \"world\"> & { world: { slug: string; alias: string | null } })[];\n compare?: WorldQueryAcrossResult[\"compare\"];\n};\n\n/**\n * The bridge's `query` with `across` over the tree in place: the root's rows\n * and, per `[dependencies.<alias>.entities]` mapping that carries a `where`\n * field, the linked world's, read at its `path`. Needs the bundled runtime on\n * this machine, as the paths beside the tree must resolve.\n */\nexport async function queryLocalWorldDataAcross(\n dir: string,\n entity: string,\n where: LocalQueryWhere,\n opts: LocalQueryOptions & { compare?: boolean },\n): Promise<LocalQueryAcrossResult> {\n const local = localRuntime();\n if (!local)\n throw new CliError(\n \"`--across` on a directory reads the linked worlds at their paths, so it needs the bundled runtime on this machine. \" +\n localRuntimeReason(),\n 1,\n );\n const payload = await localBridge<Record<string, unknown>>(\n {\n command: \"query\",\n world: path.resolve(dir),\n entity,\n across: true,\n ...(opts.compare ? { compare: true } : {}),\n ...(Object.keys(where).length ? { where } : {}),\n ...(opts.limit !== undefined ? { limit: opts.limit } : {}),\n ...(opts.offset !== undefined ? { offset: opts.offset } : {}),\n ...(opts.resolve ? { resolve: true } : {}),\n ...(opts.scenario ? { scenario: opts.scenario } : {}),\n },\n local,\n );\n const detail = detailFrom(payload);\n if (detail) throw new BridgeRejected(detail);\n return payload as unknown as LocalQueryAcrossResult;\n}\n\n// ---------------------------------------------------------------- tool calls\n\nexport type LocalIngestRefusal = { index: number | null; tool: string | null; reason: string; pointer?: string };\n\n/** One `[[sources]]` of a mapping in the report: what it saw and what it did not touch. */\nexport type LocalIngestSource = {\n name: string;\n kind: string;\n select: string;\n entity: string;\n records: number;\n items: number;\n rows: Record<string, number>;\n /** Source fields no line of the source reads, with a sample value. */\n unmapped_fields: Record<string, string>;\n /** Entity fields the source never sets, per entity it lands in. */\n unset_fields: Record<string, string[]>;\n};\n\n/** The bridge's `ingest-calls` report (the Python `ingest.ingest_records`). */\nexport type LocalIngestResult = {\n /** How the rows were produced: a declared mapping, the operations' projection, or rows as given. */\n via?: \"map\" | \"operations\" | \"rows\" | \"transform\";\n records: number;\n ingested: number;\n skipped: Record<string, number>;\n refusals: LocalIngestRefusal[];\n rows: Record<string, number>;\n /** The projected rows themselves, as the tools returned them (before any redaction). */\n projected?: Rows;\n /** `via: \"map\"`: each source's accounting. */\n sources?: LocalIngestSource[];\n /** `via: \"map\"` with `unmatched = \"skip\"`: records no source claimed, by tool name. */\n unmatched?: Record<string, number>;\n /** `via: \"operations\"`: that the rows came through the operation projection, not a mapping. */\n note?: string;\n dry_run: boolean;\n redact: \"off\" | \"apply\" | \"refuse\";\n changed: boolean;\n kind?: string;\n entity_counts?: Record<string, number>;\n batch?: string | null;\n};\n\n/**\n * Tool-call records into a world in a LOCAL directory, through the runtime's\n * `ingest-calls`: each record's tool resolves to an operation of the world's\n * `connector.toml`, its result goes through that operation's projection the\n * way a capture does, and the rows through the world's contract. An unknown\n * tool is a refusal in the report (nothing written); a row the contract\n * refuses surfaces as a BridgeRejected, as an import would. Redaction is\n * optional and off by default. With `dryRun` the tree is untouched.\n */\nexport async function ingestLocalToolCalls(\n dir: string,\n records: unknown[],\n opts: { redact?: \"off\" | \"apply\" | \"refuse\"; dryRun?: boolean; mode?: ImportMode; map?: string | Record<string, unknown> },\n creds: Credentials | null,\n): Promise<LocalIngestResult> {\n const res = await runtime<Partial<LocalIngestResult> & { files?: WorldFile[] }>(creds, {\n command: \"ingest-calls\",\n files: readWorldFiles(dir),\n records,\n mode: opts.mode ?? \"append\",\n ...(opts.dryRun ? { dry_run: true } : {}),\n ...(opts.redact && opts.redact !== \"off\" ? { redact: opts.redact } : {}),\n ...(opts.map !== undefined ? { map: opts.map } : {}),\n });\n if (!opts.dryRun && res.files?.length) writeWorldFiles(dir, res.files);\n if (res.changed) dropBuildOutputs(dir);\n return {\n ...(res.via ? { via: res.via } : {}),\n ...(res.sources ? { sources: res.sources } : {}),\n ...(res.unmatched ? { unmatched: res.unmatched } : {}),\n ...(res.note ? { note: res.note } : {}),\n records: res.records ?? records.length,\n ingested: res.ingested ?? 0,\n skipped: res.skipped ?? {},\n refusals: res.refusals ?? [],\n rows: res.rows ?? {},\n ...(res.projected ? { projected: res.projected } : {}),\n dry_run: Boolean(res.dry_run ?? opts.dryRun),\n redact: res.redact ?? opts.redact ?? \"off\",\n changed: Boolean(res.changed),\n ...(res.kind ? { kind: res.kind } : {}),\n ...(res.entity_counts ? { entity_counts: res.entity_counts } : {}),\n ...(res.batch !== undefined ? { batch: res.batch } : {}),\n };\n}\n","import { spawn } from \"node:child_process\";\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport { createRequire } from \"node:module\";\n\nimport { CliError } from \"../../router\";\nimport type { Rows } from \"../rows\";\n\n/**\n * `--transform`: the agent's own code turns records into rows (the Python\n * `schema.transform`, wrapper for wrapper). A script — `.py`, or `.ts` /\n * `.mjs` / `.js` / `.cjs` for node — either exports `transform(records) ->\n * {entity: [rows]}` (node: `transform` or the default export) or reads the\n * records as JSONL on stdin and prints the rows document on stdout.\n *\n * The script runs in a subprocess with a time limit, its stderr passed\n * through. The wrapper disables sockets (Python) and `net`/`tls`/`http`/\n * `dgram`/`fetch` (node) before the script loads, and the child gets no\n * `GATEWAY_*` or proxy variables. That is a guard, not a sandbox: a\n * transform is the agent's own code, run on the agent's own machine.\n */\n\nexport const DEFAULT_TRANSFORM_TIMEOUT_MS = 120_000;\nexport const NODE_SUFFIXES = [\".ts\", \".mts\", \".mjs\", \".js\", \".cjs\"];\nexport const PYTHON_SUFFIXES = [\".py\"];\nconst SCRUBBED = /^(GATEWAY_|HTTPS?_PROXY$|ALL_PROXY$|https?_proxy$|all_proxy$)/;\n\nexport const PY_WRAPPER = `\nimport io, json, runpy, socket, sys\n\ndef _deny(*args, **kwargs):\n raise RuntimeError(\"network is disabled in a transform\")\n\nclass _Denied(socket.socket):\n def __init__(self, *args, **kwargs):\n _deny()\n\nsocket.socket = _Denied\nsocket.SocketType = _Denied\nsocket.create_connection = _deny\nsocket.getaddrinfo = _deny\n\ntext = sys.stdin.read()\nrecords = [json.loads(line) for line in text.splitlines() if line.strip()]\nsys.stdin = io.StringIO(text)\ncaptured = io.StringIO()\nreal = sys.stdout\nsys.stdout = captured\ntry:\n namespace = runpy.run_path(sys.argv[1], run_name=\"__main__\")\nfinally:\n sys.stdout = real\nfn = namespace.get(\"transform\")\nif callable(fn):\n out = fn(records)\nelse:\n printed = captured.getvalue().strip()\n if not printed:\n sys.stderr.write(\"the transform defines no transform(records) and printed nothing\\\\n\")\n sys.exit(3)\n out = json.loads(printed)\nreal.write(json.dumps(out))\n`;\n\nexport const NODE_WRAPPER = `\nimport { pathToFileURL } from \"node:url\";\nimport net from \"node:net\";\nimport tls from \"node:tls\";\nimport http from \"node:http\";\nimport https from \"node:https\";\nimport dgram from \"node:dgram\";\n\nconst deny = () => { throw new Error(\"network is disabled in a transform\"); };\nnet.Socket.prototype.connect = deny;\nnet.connect = deny;\nnet.createConnection = deny;\ntls.connect = deny;\nhttp.request = deny;\nhttp.get = deny;\nhttps.request = deny;\nhttps.get = deny;\ndgram.createSocket = deny;\nglobalThis.fetch = deny;\n\nconst module = await import(pathToFileURL(process.argv[2]).href);\nconst fn = typeof module.transform === \"function\" ? module.transform : typeof module.default === \"function\" ? module.default : null;\nif (fn) {\n const chunks = [];\n for await (const chunk of process.stdin) chunks.push(chunk);\n const text = Buffer.concat(chunks).toString(\"utf8\");\n const records = text.split(\"\\\\n\").filter((line) => line.trim()).map((line) => JSON.parse(line));\n const out = await fn(records);\n process.stdout.write(JSON.stringify(out));\n}\n`;\n\nconst isObject = (value: unknown): value is Record<string, unknown> => typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/** `value` as the rows document `{entity: [rows]}`, or a CliError saying what shape it has instead. */\nexport function checkRows(value: unknown, where: string): Rows {\n if (!isObject(value)) throw new CliError(`${where} must return {entity: [rows]}; got ${value === null ? \"null\" : Array.isArray(value) ? \"an array\" : typeof value}`, 1);\n for (const [entity, listed] of Object.entries(value)) {\n if (!Array.isArray(listed)) throw new CliError(`${where}: ${entity} must be a list of rows; got ${listed === null ? \"null\" : typeof listed}`, 1);\n listed.forEach((row, index) => {\n if (!isObject(row)) throw new CliError(`${where}: ${entity}[${index}] is not an object`, 1);\n });\n }\n return value as Rows;\n}\n\n/**\n * How this node runs a `.ts` transform: built-in type stripping from Node\n * 22.6 on; before that, the `tsx` command-line entry when tsx is installed\n * beside the CLI (a dev dependency here, present on CI's Node 20); otherwise\n * a refusal that names both options instead of a stack trace from node.\n * Returns the argv prefix that goes in front of the wrapper.\n */\nfunction typescriptPrefix(): string[] {\n const [major, minor] = process.versions.node.split(\".\").map(Number);\n if (!process.env.GATEWAY_NODE && (major > 22 || (major === 22 && minor >= 6))) return [\"--experimental-strip-types\", \"--no-warnings\"];\n try {\n return [createRequire(import.meta.url).resolve(\"tsx/cli\")];\n } catch {\n throw new CliError(\n `a .ts transform needs Node 22.6 or newer (built-in type stripping; this is ${process.versions.node}) or the tsx package installed beside the CLI; write the transform as .mjs or .py, or set GATEWAY_NODE to a newer node`,\n 1,\n );\n }\n}\n\nfunction command(script: string, wrapperDir: string): { file: string; args: string[] } {\n const suffix = path.extname(script).toLowerCase();\n if (PYTHON_SUFFIXES.includes(suffix)) return { file: process.env.GATEWAY_PYTHON || \"python3\", args: [\"-c\", PY_WRAPPER, script] };\n if (NODE_SUFFIXES.includes(suffix)) {\n const wrapper = path.join(wrapperDir, \"transform-wrapper.mjs\");\n fs.writeFileSync(wrapper, NODE_WRAPPER);\n const flags = suffix === \".ts\" || suffix === \".mts\" ? typescriptPrefix() : [];\n return { file: process.env.GATEWAY_NODE || process.execPath, args: [...flags, wrapper, script] };\n }\n throw new CliError(`${path.basename(script)}: a transform script is .py, .ts, .mjs, .js or .cjs`, 1);\n}\n\nconst tail = (stderr: string, lines = 12): string => {\n const kept = stderr\n .split(\"\\n\")\n .filter((line) => line.trim())\n .slice(-lines);\n return kept.length ? \"\\n\" + kept.join(\"\\n\") : \"\";\n};\n\n/**\n * Run `script` over `records`: the rows document it returns and its stderr.\n * A non-zero exit, a timeout, or output that is not the rows document is a\n * CliError (exit 1) carrying the tail of the script's stderr.\n */\nexport async function runTransform(script: string, records: unknown[], opts: { timeoutMs?: number } = {}): Promise<{ rows: Rows; stderr: string }> {\n if (!fs.existsSync(script) || !fs.statSync(script).isFile()) throw new CliError(`no transform script at ${script}`, 1);\n const resolved = path.resolve(script);\n const name = path.basename(script);\n const timeoutMs = opts.timeoutMs ?? DEFAULT_TRANSFORM_TIMEOUT_MS;\n const scratch = fs.mkdtempSync(path.join(os.tmpdir(), \"gateway-transform-\"));\n try {\n const { file, args } = command(resolved, scratch);\n const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !SCRUBBED.test(key)));\n const done = await new Promise<{ code: number | null; stdout: string; stderr: string; timedOut: boolean }>((resolve, reject) => {\n const child = spawn(file, args, { cwd: path.dirname(resolved), env, stdio: [\"pipe\", \"pipe\", \"pipe\"] });\n let stdout = \"\";\n let stderr = \"\";\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n child.kill(\"SIGKILL\");\n }, timeoutMs);\n child.stdout.setEncoding(\"utf8\").on(\"data\", (chunk: string) => (stdout += chunk));\n child.stderr.setEncoding(\"utf8\").on(\"data\", (chunk: string) => (stderr += chunk));\n child.on(\"error\", (error) => {\n clearTimeout(timer);\n reject(new CliError(`${name}: cannot run ${file}: ${error.message}`, 1));\n });\n child.on(\"close\", (code) => {\n clearTimeout(timer);\n resolve({ code, stdout, stderr, timedOut });\n });\n child.stdin.on(\"error\", () => undefined);\n child.stdin.end(records.map((record) => JSON.stringify(record) + \"\\n\").join(\"\"));\n });\n if (done.timedOut) throw new CliError(`${name} timed out after ${timeoutMs / 1000}s${tail(done.stderr)}`, 1);\n if (done.code !== 0) throw new CliError(`${name} exited ${done.code ?? \"?\"}${tail(done.stderr)}`, 1);\n let value: unknown;\n try {\n value = done.stdout.trim() ? JSON.parse(done.stdout) : null;\n } catch {\n throw new CliError(`${name} printed something other than the rows document${tail(done.stderr)}`, 1);\n }\n return { rows: checkRows(value, name), stderr: done.stderr };\n } finally {\n fs.rmSync(scratch, { recursive: true, force: true });\n }\n}\n\n/** A transform given to the SDK: a function, or a script path run as above. */\nexport type TransformLike = string | ((records: unknown[]) => Rows | Promise<Rows>);\n\nexport async function transformRecords(transform: TransformLike, records: unknown[], opts: { timeoutMs?: number } = {}): Promise<{ rows: Rows; stderr: string }> {\n if (typeof transform === \"function\") return { rows: checkRows(await transform(records), \"transform(records)\"), stderr: \"\" };\n return runTransform(transform, records, opts);\n}\n","import { createHash } from \"node:crypto\";\nimport * as fs from \"node:fs\";\n\nimport { api, type Credentials } from \"../../config\";\nimport { CliError } from \"../../router\";\nimport type { BuiltChunk } from \"./chunker\";\nimport type { ManifestChunk } from \"./manifest\";\n\n/**\n * The batch protocol of `/api/public/worlds/{slug}/data` (contract §7): open\n * a batch, register each chunk by digest (the server hands back a presigned\n * PUT, or says it already holds that content), confirm the upload, complete,\n * then poll. Thin on purpose: the server owns validation and the ledger.\n */\n\nexport type Refusal = {\n chunk: number;\n index: number;\n entity: string | null;\n primaryKey: Record<string, unknown> | null;\n field: string | null;\n pointer: string;\n detail: string;\n};\n\nexport type BatchStatus = {\n batchId: string;\n state: string;\n mode?: string;\n merge?: string;\n atomic?: boolean;\n dryRun?: boolean;\n publish?: string;\n chunks?: number;\n uploadedChunks?: number;\n rows?: number;\n refusalCount?: number;\n refusals?: Refusal[];\n reportUrl?: string;\n progress?: { phase?: string; validatedChunks?: number; appliedRows?: number };\n entityCounts?: Record<string, number>;\n snapshotId?: string | null;\n batchDigest?: string | null;\n versionId?: string | null;\n error?: string | null;\n createdAt?: string;\n updatedAt?: string;\n};\n\nexport type OpenBatchBody = {\n mode: \"append\" | \"replace\";\n merge: \"upsert\" | \"fill\";\n redact?: \"off\" | \"apply\" | \"refuse\";\n atomic: boolean;\n dryRun: boolean;\n publish: \"now\" | \"later\";\n message?: string;\n expectedChunks?: number;\n entities?: string[];\n};\n\nexport type OpenedBatch = { batchId: string; state: string; limits?: { chunkBytes?: number; batchBytes?: number; inlineBytes?: number } };\n\nexport type RegisteredChunk = {\n chunkId: string;\n uploaded: boolean;\n uploadUrl?: string;\n /** Headers the presigned PUT was signed for (content-type, content-length, x-amz-checksum-sha256); sent exactly. */\n uploadHeaders?: Record<string, string>;\n expiresAt?: string;\n};\n\nexport const TERMINAL_STATES = new Set([\"applied\", \"refused\", \"published\", \"failed\"]);\n\nexport const sleepMs = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));\n\nexport class WorldDataApi {\n readonly base: string;\n constructor(\n readonly creds: Credentials,\n readonly slug: string,\n /** Injectable for tests: the pause between retries and polls. */\n readonly sleep: (ms: number) => Promise<void> = sleepMs,\n ) {\n this.base = `/api/public/worlds/${encodeURIComponent(slug)}/data`;\n }\n\n open(body: OpenBatchBody): Promise<OpenedBatch> {\n return api<OpenedBatch>(this.creds, \"POST\", `${this.base}/batches`, body);\n }\n\n register(batchId: string, chunk: { ordinal: number; digest: string; bytes: number; rows: number; entity: string | null }): Promise<RegisteredChunk> {\n return api<RegisteredChunk>(this.creds, \"POST\", `${this.base}/batches/${batchId}/chunks`, {\n ordinal: chunk.ordinal,\n digest: chunk.digest,\n bytes: chunk.bytes,\n rows: chunk.rows,\n ...(chunk.entity ? { entity: chunk.entity } : {}),\n });\n }\n\n markUploaded(batchId: string, chunkId: string): Promise<{ chunkId: string; uploaded: boolean; bytes: number }> {\n return api(this.creds, \"POST\", `${this.base}/batches/${batchId}/chunks/${chunkId}/uploaded`);\n }\n\n complete(batchId: string): Promise<{ batchId: string; state: string }> {\n return api(this.creds, \"POST\", `${this.base}/batches/${batchId}/complete`);\n }\n\n get(batchId: string): Promise<BatchStatus> {\n return api<BatchStatus>(this.creds, \"GET\", `${this.base}/batches/${batchId}`);\n }\n\n list(limit?: number, cursor?: string): Promise<{ batches: BatchStatus[]; nextCursor?: string }> {\n const params = new URLSearchParams();\n if (limit !== undefined) params.set(\"limit\", String(limit));\n if (cursor) params.set(\"cursor\", cursor);\n const q = params.toString();\n return api(this.creds, \"GET\", `${this.base}/batches${q ? `?${q}` : \"\"}`);\n }\n\n publish(message?: string): Promise<{ versionId: string; snapshotId: string; batchIds: string[] }> {\n return api(this.creds, \"POST\", `${this.base}/publish`, message ? { message } : {});\n }\n\n /**\n * PUT the gzipped chunk to its presigned URL with exactly the headers the\n * URL was signed for (the platform's `uploadHeaders`; the same three when it\n * sends none), with backoff on a dropped connection or a 5xx.\n */\n async put(uploadUrl: string, gz: Buffer, signed?: Record<string, string>): Promise<void> {\n const headers = signed ?? uploadHeadersFor(gz);\n const delays = [500, 1500, 4000];\n for (let attempt = 0; ; attempt++) {\n try {\n const res = await fetch(uploadUrl, { method: \"PUT\", body: new Uint8Array(gz), headers });\n if (res.ok) return;\n if (res.status < 500 || attempt >= delays.length) throw new CliError(`chunk upload -> ${res.status}: ${(await res.text()).slice(0, 300)}`, 1);\n } catch (error) {\n if (error instanceof CliError || attempt >= delays.length) throw error instanceof CliError ? error : new CliError(`chunk upload failed: ${(error as Error).message}`, 1);\n }\n await this.sleep(delays[attempt]!);\n }\n }\n\n /** Register, upload unless the server already holds the content, confirm. */\n async upload(batchId: string, chunk: BuiltChunk): Promise<ManifestChunk> {\n const registered = await this.register(batchId, chunk);\n if (!registered.uploaded) {\n if (!registered.uploadUrl) throw new CliError(`the server registered chunk ${chunk.ordinal} without an upload URL`, 1);\n await this.put(registered.uploadUrl, chunk.gz, registered.uploadHeaders);\n await this.markUploaded(batchId, registered.chunkId);\n }\n return { ordinal: chunk.ordinal, digest: chunk.digest, bytes: chunk.bytes, rows: chunk.rows, entity: chunk.entity, chunkId: registered.chunkId, uploaded: true };\n }\n}\n\n/** What a chunk's presigned PUT is signed for: its type, size and sha256 (base64, S3's spelling). */\nexport function uploadHeadersFor(gz: Buffer): Record<string, string> {\n return {\n \"content-type\": \"application/gzip\",\n \"content-length\": String(gz.length),\n \"x-amz-checksum-sha256\": createHash(\"sha256\").update(gz).digest(\"base64\"),\n };\n}\n\n/** Run `fn` over an async stream with at most `limit` in flight; results in input order. */\nexport async function forEachLimited<T>(items: AsyncIterable<T>, limit: number, fn: (item: T) => Promise<void>): Promise<void> {\n const inFlight = new Set<Promise<void>>();\n let failure: unknown = null;\n const track = (p: Promise<void>) => {\n const wrapped: Promise<void> = p.then(\n () => {\n inFlight.delete(wrapped);\n },\n (error) => {\n failure ??= error;\n inFlight.delete(wrapped);\n },\n );\n inFlight.add(wrapped);\n };\n for await (const item of items) {\n if (failure) break;\n track(fn(item));\n if (inFlight.size >= limit) await Promise.race(inFlight);\n }\n await Promise.all(inFlight);\n if (failure) throw failure;\n}\n\nexport type WaitOptions = {\n /** Called once per phase change with a printable line. */\n onPhase?: (line: string) => void;\n sleep?: (ms: number) => Promise<void>;\n /** The first pause between polls (default 1 s; GATEWAY_WORLD_DATA_POLL_MS in the CLI). */\n initialDelayMs?: number;\n};\n\n/** Poll until the batch settles; 1 s growing to 10 s between polls. */\nexport async function waitForBatch(client: WorldDataApi, batchId: string, opts: WaitOptions = {}): Promise<BatchStatus> {\n const sleep = opts.sleep ?? client.sleep;\n let delay = opts.initialDelayMs ?? 1000;\n let last = \"\";\n for (;;) {\n const status = await client.get(batchId);\n const phase = phaseLine(status);\n if (phase !== last) {\n opts.onPhase?.(phase);\n last = phase;\n }\n if (TERMINAL_STATES.has(status.state)) return status;\n await sleep(delay);\n delay = Math.min(10_000, Math.round(delay * 1.5));\n }\n}\n\n/** The Python CLI's progress line: `state`, with the job's phase in parentheses when it has one. */\nexport function phaseLine(status: BatchStatus): string {\n const phase = status.progress?.phase;\n return phase ? `${status.state} (${phase})` : status.state;\n}\n\n/**\n * The refusal report as JSONL: the server's full report when it has one\n * (`reportUrl`), else the records the status carries inline. Returns the\n * number of lines written.\n */\nexport async function writeRefusalReport(status: BatchStatus, file: string): Promise<number> {\n let text: string;\n if (status.reportUrl) {\n const res = await fetch(status.reportUrl);\n if (!res.ok) throw new CliError(`refusal report -> ${res.status}`, 1);\n text = await res.text();\n if (text && !text.endsWith(\"\\n\")) text += \"\\n\";\n } else text = (status.refusals ?? []).map((r) => JSON.stringify(r) + \"\\n\").join(\"\");\n fs.writeFileSync(file, text);\n return text ? text.split(\"\\n\").filter(Boolean).length : 0;\n}\n","import { createHash } from \"node:crypto\";\nimport { deflateRawSync } from \"node:zlib\";\n\nimport { dumps, type JsonObject } from \"./json\";\nimport type { TaggedRow } from \"./rowSource\";\n\n/**\n * Rows into chunks: gzip over JSONL, cut on row boundaries at `--chunk-rows`\n * or `--chunk-bytes` (uncompressed), content-addressed by the sha256 of the\n * gzipped bytes. The same rows with the same flags give the same content\n * digests (over the JSONL) in both CLIs and on every platform, and the same\n * gzip digests wherever the two zlibs deflate alike: lines are the Python\n * serialisation (`dumps`), the deflate stream is zlib's at level 9, and the\n * gzip header is written here rather than by zlib, as CPython's\n * `gzip.compress(…, mtime=0)` writes it — zlib would stamp the platform's OS\n * byte instead. Node 20 and 24 bundle Chromium's zlib, which deflates\n * differently from CPython's stock zlib, so a chunk's gzip digest can differ\n * between CLIs while its content digest agrees; `--resume` keys on the digest\n * of what this CLI wrote, so it is unaffected. See `zlibDeflatesLikeCPython`.\n */\n\nexport const DEFAULT_CHUNK_BYTES = 64 * 1024 * 1024;\nexport const GZIP_LEVEL = 9;\n\nexport type ChunkPlan = {\n /** Always bound: the Python CLI keeps 64 MiB even with --chunk-rows. */\n chunkBytes: number;\n chunkRows: number | null;\n /** When set, chunks are declared with this entity and lines are bare rows. */\n entity: string | null;\n};\n\nexport type BuiltChunk = {\n ordinal: number;\n /** sha256 of the gzipped bytes, hex. */\n digest: string;\n /** Gzipped size. */\n bytes: number;\n rows: number;\n entity: string | null;\n /** Uncompressed JSONL size (`contentBytes` in the shared manifest). */\n rawBytes: number;\n /** sha256 of the uncompressed JSONL: the cross-zlib parity check. */\n contentSha256: string;\n /** Index of the chunk's first row in the input stream. */\n firstRow: number;\n gz: Buffer;\n};\n\n/** One row as the line a chunk carries: tagged, or bare when the chunk declares its entity. */\nexport function chunkLine(row: TaggedRow, declared: string | null): string {\n if (declared !== null) return dumps(row.row) + \"\\n\";\n const tagged: JsonObject = new Map();\n tagged.set(\"entity\", row.entity);\n tagged.set(\"row\", row.row);\n return dumps(tagged) + \"\\n\";\n}\n\nexport async function* buildChunks(rows: AsyncIterable<TaggedRow>, plan: ChunkPlan): AsyncGenerator<BuiltChunk> {\n let lines: Buffer[] = [];\n let rawBytes = 0;\n let ordinal = 0;\n let seen = 0;\n const flush = (): BuiltChunk => {\n const raw = Buffer.concat(lines);\n const built = finishChunk(ordinal++, raw, lines.length, plan.entity, seen - lines.length);\n lines = [];\n rawBytes = 0;\n return built;\n };\n for await (const row of rows) {\n const line = Buffer.from(chunkLine(row, plan.entity), \"utf8\");\n const full =\n lines.length > 0 &&\n ((plan.chunkRows !== null && lines.length >= plan.chunkRows) ||\n rawBytes + line.length > plan.chunkBytes);\n if (full) yield flush();\n lines.push(line);\n rawBytes += line.length;\n seen++;\n }\n if (lines.length) yield flush();\n}\n\nexport function finishChunk(ordinal: number, raw: Buffer, rows: number, entity: string | null, firstRow = 0): BuiltChunk {\n const gz = gzipDeterministic(raw, { name: chunkName(ordinal) });\n return {\n ordinal,\n digest: createHash(\"sha256\").update(gz).digest(\"hex\"),\n bytes: gz.length,\n rows,\n entity,\n rawBytes: raw.length,\n contentSha256: createHash(\"sha256\").update(raw).digest(\"hex\"),\n firstRow,\n gz,\n };\n}\n\n/**\n * Whether this Node's zlib deflates as the CPython that wrote the fixtures\n * did. Deflate output is a property of the zlib build, not of the format:\n * the same input inflates everywhere, but a zlib-ng or a future Chromium\n * zlib may pick different matches, and then gzip digests differ across\n * CLIs while content digests (over the JSONL) still agree. The manifest\n * parity check is on the content; the gzip digest is informative.\n */\nexport function zlibDeflatesLikeCPython(): boolean {\n return deflateRawSync(Buffer.from(CPYTHON_PROBE_TEXT), { level: GZIP_LEVEL }).toString(\"hex\") === CPYTHON_PROBE_DEFLATE;\n}\n/**\n * Two tagged rows, as the chunker writes them, and CPython's deflate of them (zlib\n * 1.2.12, which also wrote the fixtures). The probe has to be this long: \"hello\\n\"\n * deflates identically on every zlib, so it proved nothing, while on this text\n * Node 20 and 24 (Chromium's zlib 1.3.1) pick different matches and land two\n * bytes shorter than Node 25 and CPython (stock zlib).\n */\nconst CPYTHON_PROBE_TEXT = '{\"entity\":\"customers\",\"row\":{\"id\":0,\"name\":\"n0\",\"score\":0.0,\"tags\":[\"a\"]}}\\n{\"entity\":\"customers\",\"row\":{\"id\":1,\"name\":\"n1\",\"score\":1.0,\"tags\":[\"a\"]}}\\n';\nconst CPYTHON_PROBE_DEFLATE = \"ab564acd2bc92ca954b2524a2e2d2ec9cf4d2d2a56d2512aca2f57b2aa56ca4c51b232d051ca4bcc4d052ac83300ca1427e7170139067a40f192c4f46225ab68a544a5d8da5aae6a824619228c3244186588691400\";\n\n/** The file name the Python CLI gives chunk N (`chunk-00007.jsonl.gz`), which\n * its `GzipFile` records in the gzip header, so it is part of the digest. */\nexport const chunkName = (ordinal: number): string => `chunk-${String(ordinal).padStart(5, \"0\")}.jsonl`;\n\n/**\n * Gzip as CPython's `gzip.GzipFile(fileobj, \"wb\", mtime=0)` writes it: mtime\n * 0, XFL for the level, OS \"unknown\" (0xff), and — when a name is given — the\n * FNAME field, exactly as GzipFile records the basename of the file it writes.\n */\nexport function gzipDeterministic(raw: Buffer, opts: { level?: number; name?: string } = {}): Buffer {\n const level = opts.level ?? GZIP_LEVEL;\n const name = opts.name ? Buffer.concat([Buffer.from(opts.name, \"latin1\"), Buffer.from([0])]) : Buffer.alloc(0);\n const header = Buffer.from([0x1f, 0x8b, 0x08, opts.name ? 0x08 : 0x00, 0, 0, 0, 0, level === 9 ? 0x02 : level === 1 ? 0x04 : 0x00, 0xff]);\n const body = deflateRawSync(raw, { level });\n const trailer = Buffer.alloc(8);\n trailer.writeUInt32LE(crc32(raw), 0);\n trailer.writeUInt32LE(raw.length >>> 0, 4);\n return Buffer.concat([header, name, body, trailer]);\n}\n\nlet table: Uint32Array | null = null;\n\n/** CRC-32 (IEEE), the gzip trailer's checksum. A table here keeps the CLI on Node 18. */\nexport function crc32(data: Buffer): number {\n if (!table) {\n table = new Uint32Array(256);\n for (let n = 0; n < 256; n++) {\n let c = n;\n for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;\n table[n] = c >>> 0;\n }\n }\n let crc = 0xffffffff;\n for (let i = 0; i < data.length; i++) crc = table[(crc ^ data[i]!) & 0xff]! ^ (crc >>> 8);\n return (crc ^ 0xffffffff) >>> 0;\n}\n\n/** The Python CLI's `_parse_size`: an integer and a unit — none, b, k, kib, kb, m, mib, mb, g, gib, gb. */\nexport function parseSize(text: string): number {\n const units: Record<string, number> = { \"\": 1, b: 1, k: 1024, kib: 1024, kb: 1000, m: 1024 ** 2, mib: 1024 ** 2, mb: 1000 ** 2, g: 1024 ** 3, gib: 1024 ** 3, gb: 1000 ** 3 };\n const raw = text.trim().toLowerCase().replace(/ /g, \"\");\n const m = /^(\\d+)([a-z]*)$/.exec(raw);\n if (!m || !(m[2]! in units)) throw new Error(`--chunk-bytes takes a size like 64MiB or 1000000, not '${text}'`);\n return Number(m[1]) * units[m[2]!]!;\n}\n","import type { Credentials } from \"../../config\";\nimport type { Rows } from \"../rows\";\nimport { forEachLimited, waitForBatch, WorldDataApi, type BatchStatus } from \"./batches\";\nimport { buildChunks, DEFAULT_CHUNK_BYTES } from \"./chunker\";\nimport { parseJson, type JsonObject } from \"./json\";\nimport type { TaggedRow } from \"./rowSource\";\n\n/**\n * Rows already in memory into a platform world through the batch lane —\n * open, chunk, upload, complete, wait — with none of the CLI's file, manifest\n * or resume machinery. What `ingestToolCalls` (the SDK) pushes after the\n * runtime projected a slug's records; the CLI keeps `data import`'s lane.\n * `redact` is optional and defaults to off: the platform stores the rows as\n * given unless asked to apply its `[redact]` policy.\n */\nexport async function pushRows(\n creds: Credentials,\n slug: string,\n rows: Rows,\n opts: {\n mode?: \"append\" | \"replace\";\n redact?: \"off\" | \"apply\" | \"refuse\";\n message?: string;\n publish?: \"now\" | \"later\";\n chunkBytes?: number;\n parallel?: number;\n dryRun?: boolean;\n sleep?: (ms: number) => Promise<void>;\n } = {},\n): Promise<BatchStatus> {\n const client = opts.sleep ? new WorldDataApi(creds, slug, opts.sleep) : new WorldDataApi(creds, slug);\n const opened = await client.open({\n mode: opts.mode ?? \"append\",\n merge: \"upsert\",\n ...(opts.redact && opts.redact !== \"off\" ? { redact: opts.redact } : {}),\n atomic: true,\n dryRun: Boolean(opts.dryRun),\n publish: opts.publish ?? \"now\",\n ...(opts.message ? { message: opts.message } : {}),\n });\n if (!opened.batchId) throw new Error(\"the platform opened no batch (no batchId in the answer)\");\n // The chunker speaks the file lane's JSON model (CPython-faithful numbers and\n // key order), so each row takes the same road a JSONL line does: serialized, parsed.\n const tagged = (async function* (): AsyncGenerator<TaggedRow> {\n for (const [entity, listed] of Object.entries(rows))\n for (let index = 0; index < listed.length; index++)\n yield { entity, row: parseJson(JSON.stringify(listed[index]!)) as JsonObject, where: `${entity}[${index}]` };\n })();\n const chunks = buildChunks(tagged, { chunkBytes: opts.chunkBytes ?? DEFAULT_CHUNK_BYTES, chunkRows: null, entity: null });\n await forEachLimited(chunks, Math.max(1, opts.parallel ?? 4), async (chunk) => {\n await client.upload(opened.batchId, chunk);\n });\n await client.complete(opened.batchId);\n return waitForBatch(client, opened.batchId, { initialDelayMs: pollMs() });\n}\n\nfunction pollMs(): number {\n const raw = Number(process.env.GATEWAY_WORLD_DATA_POLL_MS ?? 1000);\n return Number.isFinite(raw) && raw >= 0 ? raw : 1000;\n}\n","/**\n * Records into a world's rows — the record contract, an interceptor that\n * writes it, the conversion from TOOL observations, and the door in.\n *\n * A tool's response is not the entity's shape, and nothing here assumes it\n * is. The workflow with real data is: pull the raw tool calls, look at them,\n * then ingest them through the route you declare — {@link ingest} with a\n * `transform` (your own `transform(records) -> {entity: [rows]}`, a function\n * or a script), with a `map` (an `ingest.toml` mapping for shapes that need\n * no code), or with neither, when the world's own `ingest.toml` applies or\n * each record's tool is a connector operation whose result *is* the\n * operation's response body (its `[ingest]` projection in `connector.toml`).\n * Mappings and projections run in the schema runtime (Python, bundled with\n * the CLI or on the platform), never re-implemented here; a transform runs\n * where you are.\n *\n * The record, one JSON object per line:\n *\n * {\"tool\": \"list_users\", \"args\": {\"team\": \"t1\"}, \"result\": {\"users\": [...]},\n * \"at\": \"2026-09-15T10:00:00Z\", \"session\": \"optional\", \"source\": \"optional free text\"}\n *\n * A `gateway worlds session export` line (`{seq, kind, tool, args, result,\n * error, completedAt}`) is accepted as it is. Redaction is optional and OFF\n * by default everywhere here: rows land as the tools returned them unless\n * `redact: \"apply\"` (the world's `[redact]` policy) or `\"refuse\"` is asked for.\n *\n * - {@link captureToolCalls} wraps an agent's tool functions so every real\n * call is recorded — the agent changes nothing.\n * - {@link toolCallsFromObservations} turns a trace's TOOL observations into\n * records (the `--from traces` path of `gateway worlds data ingest`).\n * - {@link ingest} puts records into a world through a transform, a mapping\n * or the operations: a local directory through the bundled runtime, a\n * platform slug through the batch lane. {@link ingestToolCalls} is the same\n * door with neither transform nor mapping of your own.\n */\n\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\n\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\n\nexport type ToolCallRecord = {\n /** The operation name in the world's `connector.toml`. */\n tool: string;\n /** The call's arguments, by name: what `carry_args` reads. */\n args: Record<string, unknown>;\n /** The operation's response body, as the tool returned it. */\n result?: unknown;\n /** ISO time of the call. */\n at?: string;\n /** The session the call belongs to, when there is one. */\n session?: string;\n /** Free text: where the record came from. */\n source?: string;\n /** Set instead of `result` when the call threw; ingest skips it, counted. */\n error?: string;\n};\n\nexport type RedactMode = \"off\" | \"apply\" | \"refuse\";\nexport type IngestMode = \"append\" | \"replace\";\n\n// ---------------------------------------------------------------- the mapping\n\n/** How one entity field is set: an item path, or a table naming exactly one of `from`, `literal`, `template`, `hash`. */\nexport type IngestFieldSpec =\n | string\n | {\n /** Item path (`name`, `customer.id`, `emails[0]`); `$`-paths reach the record: `$tool`, `$at`, `$index`, `$session`, `$source`, `$source.id`, `$source.trace`, `$record.<path>`, `$parent.<path>`. */\n from?: string;\n literal?: string | number | boolean;\n /** `{path}` holes are filled from the item or the record; a hole with no value refuses the record. */\n template?: string;\n /** sha256 of the JSON array of these paths' values; unset when any is missing. */\n hash?: string[];\n /** A chain from the closed transform set, applied to `from` or `template`. */\n transform?: string[];\n /** Used when `from` is missing or null. */\n default?: string | number | boolean;\n /** Coerce the value; a CSV cell is text until this says otherwise. */\n type?: \"string\" | \"integer\" | \"number\" | \"boolean\";\n };\n\nexport type IngestExplode = {\n /** Item path to a list (or one object) of children. */\n path: string;\n entity: string;\n /** child field <- parent ENTITY field (after the parent's mapping). */\n carry?: Record<string, string>;\n fields?: Record<string, IngestFieldSpec>;\n};\n\nexport type IngestSource = {\n /** The tool name (or several), or `\"*\"` for rows and csv records. */\n name: string | string[];\n kind?: \"tool-call\" | \"rows\" | \"csv\";\n /** Path into the record: `result`, `result.data[*]`, `args`, `$record`. */\n select: string;\n /** All must hold on the selected item: a literal, or `{ present: true | false }`. */\n when?: Record<string, string | number | boolean | { present: boolean }>;\n entity: string;\n /** Item path that dates the row for `on_conflict`; default the record's `at`. */\n at?: string;\n fields?: Record<string, IngestFieldSpec>;\n explode?: IngestExplode[];\n};\n\n/** `ingest.toml`, parsed: the grammar the schema runtime's `mapping.py` checks and applies. */\nexport type IngestMapping = {\n ingest?: { on_conflict?: \"latest\" | \"first\"; unmatched?: \"refuse\" | \"skip\" };\n sources: IngestSource[];\n};\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n// ---------------------------------------------------------------- records\n\nexport type ParsedToolCall = {\n /** The record in the contract's shape, when it is a tool call with a result. */\n record: ToolCallRecord | null;\n /** Why a well-formed record carries no rows by design (a `seed` line, a failed call). */\n skip: string | null;\n /** What is wrong with the record. */\n refusal: string | null;\n};\n\n/**\n * One raw record — the contract's shape or a session-export line — judged the\n * way the runtime judges it (`ingest.normalize_record`): the same skips, the\n * same refusals, so a file checked here is what the runtime will accept.\n */\nexport function parseToolCallRecord(raw: unknown): ParsedToolCall {\n const none = { record: null, skip: null };\n if (!isObject(raw)) return { ...none, refusal: \"record is not an object\" };\n const kind = raw.kind;\n if (kind !== undefined && kind !== null && kind !== \"call\") return { record: null, skip: `kind ${String(kind)}`, refusal: null };\n const tool = raw.tool;\n if (typeof tool !== \"string\" || !tool) return { ...none, refusal: \"record has no tool name\" };\n if (raw.error !== undefined && raw.error !== null && raw.error !== \"\") return { record: null, skip: \"call failed\", refusal: null };\n const args = raw.args ?? {};\n if (!isObject(args)) return { ...none, refusal: `args of ${tool} is not an object` };\n if (!(\"result\" in raw)) return { ...none, refusal: `record of ${tool} has no result` };\n const at = raw.at ?? raw.completedAt;\n const record: ToolCallRecord = { tool, args, result: raw.result };\n if (typeof at === \"string\") record.at = at;\n if (typeof raw.session === \"string\") record.session = raw.session;\n if (typeof raw.source === \"string\") record.source = raw.source;\n return { record, skip: null, refusal: null };\n}\n\n/**\n * Raw records from files: JSONL (one object per line) or one JSON array, several\n * files concatenated in order. A line that is not JSON, or not an object, throws\n * naming the file and line. Each record's shape is judged later, per record, so\n * the report can point at the index.\n */\nexport function readToolCallRecords(paths: string[]): unknown[] {\n const records: unknown[] = [];\n for (const file of paths) records.push(...toolCallRecordsIn(fs.readFileSync(file, \"utf8\"), file));\n return records;\n}\n\n/** The records in one text, named `where` in a refusal. */\nexport function toolCallRecordsIn(text: string, where: string): unknown[] {\n const stripped = text.trim();\n if (!stripped) return [];\n if (stripped.startsWith(\"[\")) {\n const listed = JSON.parse(stripped) as unknown;\n if (!Array.isArray(listed)) throw new Error(`${where} is neither a JSON array nor JSON Lines`);\n listed.forEach((item, index) => {\n if (!isObject(item)) throw new Error(`${where}[${index}] is not an object`);\n });\n return listed;\n }\n const records: unknown[] = [];\n const lines = text.split(/\\r?\\n/);\n for (let index = 0; index < lines.length; index++) {\n const line = lines[index]!;\n if (!line.trim()) continue;\n let item: unknown;\n try {\n item = JSON.parse(line);\n } catch {\n throw new Error(`${where}:${index + 1} is not JSON`);\n }\n if (!isObject(item)) throw new Error(`${where}:${index + 1} is not an object`);\n records.push(item);\n }\n return records;\n}\n\n// ---------------------------------------------------------------- capture\n\n/**\n * Where {@link captureToolCalls} writes each record: an array (pushed), a file\n * path (JSONL, one record per line, appended), or a callback (awaited).\n */\nexport type ToolCallSink = ToolCallRecord[] | string | ((record: ToolCallRecord) => unknown | Promise<unknown>);\n\nexport type ToolFunctions = Record<string, (args: Record<string, unknown>) => Promise<unknown>>;\n\nasync function emit(sink: ToolCallSink, record: ToolCallRecord): Promise<void> {\n if (Array.isArray(sink)) {\n sink.push(record);\n return;\n }\n if (typeof sink === \"string\") {\n fs.appendFileSync(sink, JSON.stringify(record) + \"\\n\");\n return;\n }\n if (typeof sink === \"function\") {\n await sink(record);\n return;\n }\n throw new TypeError(\"sink must be an array, a file path, or a function\");\n}\n\n/**\n * Wrap a name → async function map — the shape the Vercel AI SDK's tools and a\n * `WorldToolkit`'s `impls` share — so every call is recorded as a tool-call\n * record into `sink`, and hand back the same map. The agent changes nothing:\n * each wrapped function returns what the original returned, and an error is\n * thrown through untouched (recorded with `error` and no `result`, which\n * ingest skips and counts). Nothing is redacted here; redaction is optional\n * and off by default on the ingest side.\n *\n * const tools = captureToolCalls({ list_users: realVendor.listUsers }, \"calls.jsonl\");\n * await runMyAgent(tools); // real vendor, every call recorded\n * await ingestToolCalls(\"acme-crm\", readToolCallRecords([\"calls.jsonl\"]));\n */\nexport function captureToolCalls<T extends ToolFunctions>(\n tools: T,\n sink: ToolCallSink,\n opts: { session?: string; source?: string } = {},\n): T {\n const wrapped: ToolFunctions = Object.create(null);\n for (const [name, fn] of Object.entries(tools)) {\n wrapped[name] = async (args: Record<string, unknown> = {}) => {\n const record: ToolCallRecord = { tool: name, args, at: new Date().toISOString() };\n if (opts.session) record.session = opts.session;\n if (opts.source) record.source = opts.source;\n let result: unknown;\n try {\n result = await fn(args);\n } catch (error) {\n record.error = error instanceof Error ? error.message || error.name : String(error);\n await emit(sink, record);\n throw error;\n }\n record.result = result;\n await emit(sink, record);\n return result;\n };\n }\n return wrapped as T;\n}\n\n// ---------------------------------------------------------------- observations\n\n/** What a TOOL observation carries, as `GET /api/public/observations` and\n * `GET /api/public/sessions/{id}?includeIO=true` return it. */\nexport type ObservationLike = {\n id?: string;\n traceId?: string | null;\n type?: string;\n name?: string | null;\n input?: unknown;\n output?: unknown;\n startTime?: string | Date;\n level?: string;\n statusMessage?: string | null;\n};\n\nexport type ObservationConversion = {\n records: ToolCallRecord[];\n /** TOOL observations whose name is not one of the world's operations, by name. */\n unknownTools: Record<string, number>;\n /** Observations that were not converted, by reason. */\n skipped: Record<string, number>;\n};\n\n/** A serialized value back to JSON when it parses; otherwise as it is. */\nfunction jsonish(value: unknown): unknown {\n if (typeof value !== \"string\") return value;\n try {\n return JSON.parse(value);\n } catch {\n return value;\n }\n}\n\nconst isoOf = (value: string | Date | undefined): string | undefined =>\n value instanceof Date ? value.toISOString() : typeof value === \"string\" ? value : undefined;\n\n/**\n * TOOL observations → tool-call records: `name` is the tool, `input` the args,\n * `output` the result, `startTime` the time, `trace:<traceId>/<id>` the source.\n * A serialized `input`/`output` (the SDK stores JSON text) is parsed back;\n * an `input` that is not an object leaves `args` empty rather than guessed.\n * Only `type: \"TOOL\"` converts. With `tools` (the world's operation names) an\n * observation for any other tool is counted in `unknownTools`, not converted.\n * An `ERROR`-level observation converts with `error` set, so ingest counts it\n * as a failed call instead of projecting its output.\n */\nexport function toolCallsFromObservations(\n observations: ObservationLike[],\n opts: { tools?: Iterable<string> | null; session?: string; since?: string } = {},\n): ObservationConversion {\n const known = opts.tools ? new Set(opts.tools) : null;\n const sinceMs = opts.since ? Date.parse(opts.since) : NaN;\n const out: ObservationConversion = { records: [], unknownTools: {}, skipped: {} };\n const skip = (reason: string) => {\n out.skipped[reason] = (out.skipped[reason] ?? 0) + 1;\n };\n for (const observation of observations) {\n if (observation.type !== \"TOOL\") {\n skip(`type ${observation.type ?? \"unknown\"}`);\n continue;\n }\n const tool = observation.name;\n if (typeof tool !== \"string\" || !tool) {\n skip(\"no name\");\n continue;\n }\n const at = isoOf(observation.startTime);\n if (!Number.isNaN(sinceMs) && at !== undefined && Date.parse(at) < sinceMs) {\n skip(\"before since\");\n continue;\n }\n if (known && !known.has(tool)) {\n out.unknownTools[tool] = (out.unknownTools[tool] ?? 0) + 1;\n continue;\n }\n const input = jsonish(observation.input);\n const record: ToolCallRecord = { tool, args: isObject(input) ? input : {} };\n if (observation.level === \"ERROR\") record.error = observation.statusMessage || \"ERROR\";\n else record.result = jsonish(observation.output);\n if (at !== undefined) record.at = at;\n if (opts.session) record.session = opts.session;\n record.source = `trace:${observation.traceId ?? \"?\"}/${observation.id ?? \"?\"}`;\n out.records.push(record);\n }\n return out;\n}\n\n// ---------------------------------------------------------------- the door\n\nexport type IngestRefusal = { index: number | null; tool: string | null; reason: string; pointer?: string };\n\n/** One `[[sources]]` of a mapping in the report. */\nexport type IngestSourceReport = {\n name: string;\n kind: string;\n select: string;\n entity: string;\n records: number;\n items: number;\n rows: Record<string, number>;\n /** Source fields no line of the source reads, with a sample value. */\n unmappedFields: Record<string, string>;\n /** Entity fields the source never sets, per entity. */\n unsetFields: Record<string, string[]>;\n};\n\nexport type IngestToolCallsReport = {\n world: string;\n /** How the rows were produced. */\n via?: \"transform\" | \"map\" | \"operations\" | \"rows\";\n /** `via: \"map\"`: each source's accounting. */\n sources?: IngestSourceReport[];\n /** `via: \"map\"` with `unmatched = \"skip\"`: records no source claimed, by tool name. */\n unmatched?: Record<string, number>;\n /** `via: \"operations\"`: that this was the operation projection, not a mapping. */\n note?: string;\n /** `via: \"transform\"`: what the script wrote to stderr. */\n stderr?: string;\n /** Records given. */\n records: number;\n /** Records that yielded rows. */\n ingested: number;\n /** Records that carried no rows by design, by reason. */\n skipped: Record<string, number>;\n /** What was wrong, per record; with any, nothing was written. */\n refusals: IngestRefusal[];\n /** Rows projected, per entity. */\n rows: Record<string, number>;\n dryRun: boolean;\n redact: RedactMode;\n changed: boolean;\n kind?: string;\n entityCounts?: Record<string, number>;\n /** A slug that was pushed: the batch's final status (`state`, `versionId`, …). */\n batch?: Record<string, unknown>;\n};\n\nexport type IngestToolCallsOptions = WorldsClientOptions & {\n /** Optional, default `\"off\"`: rows land as the tools returned them. */\n redact?: RedactMode;\n /** Project and prove the rows; write and upload nothing. */\n dryRun?: boolean;\n mode?: IngestMode;\n /** Change reason for the version a slug cuts. */\n message?: string;\n};\n\nexport type IngestReport = IngestToolCallsReport;\n\nexport type IngestOptions = IngestToolCallsOptions & {\n /** Your own `transform(records) -> {entity: [rows]}`: a function (run here) or a script path (`.py`, `.ts`, `.mjs`; a subprocess with a time limit and sockets disabled). */\n transform?: string | ((records: unknown[]) => Rows | Promise<Rows>);\n /** An `ingest.toml` mapping: its text, or the parsed table. Exclusive with `transform`. */\n map?: string | IngestMapping;\n /** For a script transform; default 120 000. */\n timeoutMs?: number;\n};\n\ntype Rows = Record<string, Record<string, unknown>[]>;\n\nfunction credentialsOf(options: WorldsClientOptions): { host: string; publicKey: string; secretKey: string } | null {\n const host = (options.host ?? process.env.GATEWAY_HOST ?? \"https://withgateway.ai\").replace(/\\/+$/, \"\");\n const publicKey = options.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;\n const secretKey = options.secretKey ?? process.env.GATEWAY_SECRET_KEY;\n return publicKey && secretKey ? { host, publicKey, secretKey } : null;\n}\n\n/**\n * Records into a world through the route you declare. `world` is a local\n * directory (written in place through the bundled schema runtime) or a\n * platform slug (pulled to a temporary directory, the rows produced and\n * proven there, then pushed through the chunked batch lane as a new version).\n *\n * With `transform` the rows are what your code returns; with `map` (or the\n * world's own `ingest.toml`) what the mapping declares; with neither, each\n * tool-call record's tool resolves to an operation of `connector.toml` and\n * its result goes through that operation's `[ingest]` projection (the report\n * says `via: \"operations\"`). A transform that fails or returns the wrong\n * shape throws. `redact` is optional and defaults to `\"off\"`.\n */\nexport async function ingest(world: string, records: unknown[], options: IngestOptions = {}): Promise<IngestReport> {\n const { ingestLocalToolCalls, importLocalWorldData, checkLocalWorldData } = await import(\"../cli/runtime/data\");\n if (options.transform !== undefined && options.map !== undefined) throw new Error(\"records go through one of transform, map\");\n const redact = options.redact ?? \"off\";\n const mode = options.mode ?? \"append\";\n const dryRun = Boolean(options.dryRun);\n const creds = credentialsOf(options);\n const local = fs.existsSync(world) && fs.statSync(world).isDirectory();\n const map = options.map === undefined ? undefined : options.map;\n\n let rows: Rows | null = null;\n let stderr = \"\";\n if (options.transform !== undefined) {\n const { transformRecords } = await import(\"../cli/platform/worldData/transform\");\n ({ rows, stderr } = await transformRecords(options.transform, records, { timeoutMs: options.timeoutMs }));\n }\n\n if (local) {\n if (rows === null) return reportOf(world, await ingestLocalToolCalls(world, records, { redact, dryRun, mode, map }, creds), redact);\n const landed = dryRun ? await checkLocalWorldData(world, rows, creds, { redact }) : await importLocalWorldData(world, rows, { mode, redact }, creds);\n return transformReport(world, records.length, rows, stderr, { dryRun, redact, changed: !dryRun && landed.changed, kind: landed.kind, entityCounts: landed.entity_counts });\n }\n if (!creds) throw new Error(\"Gateway keys missing: set GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY (or pass publicKey/secretKey).\");\n const { pull } = await import(\"./hub\");\n const slug = world.split(\"@\", 1)[0]!;\n const scratch = fs.mkdtempSync(path.join(os.tmpdir(), \"gateway-ingest-\"));\n try {\n const pulled = await pull(world, path.join(scratch, slug), options);\n // Produced and proven against the pulled contract; the platform's batch\n // lane checks every row again and redacts there, so this pass runs with\n // redaction off and hands the rows on as they were produced.\n let report: IngestReport;\n let projected: Rows;\n if (rows === null) {\n const proven = await ingestLocalToolCalls(pulled.dir, records, { redact: \"off\", dryRun: true, mode, map }, creds);\n report = reportOf(world, proven, redact);\n projected = proven.projected ?? {};\n } else {\n const proven = await checkLocalWorldData(pulled.dir, rows, creds);\n report = transformReport(world, records.length, rows, stderr, { dryRun, redact, changed: false, kind: proven.kind, entityCounts: proven.entity_counts });\n projected = rows;\n }\n report.dryRun = dryRun;\n if (dryRun || report.refusals.length || !Object.keys(projected).length) return report;\n const { pushRows } = await import(\"../cli/platform/worldData/push\");\n const status = await pushRows(creds, slug, projected, { mode, redact, message: options.message });\n report.batch = status;\n report.changed = status.state === \"applied\" || status.state === \"published\";\n if (status.entityCounts) report.entityCounts = status.entityCounts;\n return report;\n } finally {\n fs.rmSync(scratch, { recursive: true, force: true });\n }\n}\n\n/**\n * Tool-call records into a world with neither a transform nor a mapping of\n * your own: the world's `ingest.toml` when it has one, else each record's\n * tool through its operation's `[ingest]` projection (an unknown tool is a\n * refusal naming it and nothing is written). {@link ingest} with the same\n * options.\n */\nexport async function ingestToolCalls(world: string, records: unknown[], options: IngestToolCallsOptions = {}): Promise<IngestToolCallsReport> {\n return ingest(world, records, options);\n}\n\nfunction transformReport(\n world: string,\n records: number,\n rows: Rows,\n stderr: string,\n outcome: { dryRun: boolean; redact: RedactMode; changed: boolean; kind?: string; entityCounts?: Record<string, number> },\n): IngestReport {\n return {\n world,\n via: \"transform\",\n ...(stderr ? { stderr } : {}),\n records,\n ingested: records,\n skipped: {},\n refusals: [],\n rows: Object.fromEntries(Object.entries(rows).map(([entity, listed]) => [entity, listed.length])),\n dryRun: outcome.dryRun,\n redact: outcome.redact,\n changed: outcome.changed,\n ...(outcome.kind ? { kind: outcome.kind } : {}),\n ...(outcome.entityCounts ? { entityCounts: outcome.entityCounts } : {}),\n };\n}\n\nfunction reportOf(\n world: string,\n local: {\n via?: IngestReport[\"via\"];\n sources?: { name: string; kind: string; select: string; entity: string; records: number; items: number; rows: Record<string, number>; unmapped_fields: Record<string, string>; unset_fields: Record<string, string[]> }[];\n unmatched?: Record<string, number>;\n note?: string;\n records: number;\n ingested: number;\n skipped: Record<string, number>;\n refusals: IngestRefusal[];\n rows: Record<string, number>;\n dry_run: boolean;\n changed: boolean;\n kind?: string;\n entity_counts?: Record<string, number>;\n },\n redact: RedactMode,\n): IngestToolCallsReport {\n return {\n world,\n ...(local.via ? { via: local.via } : {}),\n ...(local.sources ? { sources: local.sources.map(({ unmapped_fields, unset_fields, ...rest }) => ({ ...rest, unmappedFields: unmapped_fields, unsetFields: unset_fields })) } : {}),\n ...(local.unmatched ? { unmatched: local.unmatched } : {}),\n ...(local.note ? { note: local.note } : {}),\n records: local.records,\n ingested: local.ingested,\n skipped: local.skipped,\n refusals: local.refusals,\n rows: local.rows,\n dryRun: local.dry_run,\n redact,\n changed: local.changed,\n ...(local.kind ? { kind: local.kind } : {}),\n ...(local.entity_counts ? { entityCounts: local.entity_counts } : {}),\n };\n}\n\n/** The TOOL observations of one session, every trace's, from `GET /api/public/sessions/{id}?includeIO=true`. */\nexport async function sessionToolObservations(sessionId: string, options: WorldsClientOptions = {}): Promise<ObservationLike[]> {\n const session = await apiRequest<{ traces?: { id?: string; observations?: ObservationLike[] }[] }>(\n options,\n \"GET\",\n `/api/public/sessions/${encodeURIComponent(sessionId)}?includeIO=true`,\n );\n const out: ObservationLike[] = [];\n for (const trace of session.traces ?? [])\n for (const observation of trace.observations ?? []) out.push({ traceId: trace.id ?? null, ...observation });\n return out;\n}\n","/**\n * Worlds from TypeScript: identity, tasks, and HOSTED execution.\n *\n * The same three-level model as the Python SDK — WorldSet → Task — with one\n * deliberate difference: a world's tools are Python modules, so TypeScript\n * does not materialize task environments in-process. What a TS agent\n * codebase needs is exactly what this module provides: resolve a world ref\n * to its pinned version, read its task list, and dispatch HOSTED runs\n * (parallelism included) that execute the world server-side and file graded,\n * version-pinned rollouts. Local in-process execution stays a Python\n * capability by design, not by omission.\n */\n\nimport type { WorldTaskIdRef } from \"./session\";\n\nexport type WorldsClientOptions = {\n host?: string;\n publicKey?: string;\n secretKey?: string;\n};\n\nexport type ResolvedWorldVersion = {\n versionId: string;\n semanticVersion: string | null;\n contentHash: string;\n state?: string;\n};\n\nexport type WorldTaskInfo = {\n name: string;\n variant: string | null;\n};\n\nexport type DispatchedRun = {\n model: string;\n runId: string;\n ok: boolean;\n error?: string;\n};\n\nfunction resolveEnv(options: WorldsClientOptions) {\n const host =\n options.host ?? process.env.GATEWAY_HOST ?? \"https://withgateway.ai\";\n const publicKey = options.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;\n const secretKey = options.secretKey ?? process.env.GATEWAY_SECRET_KEY;\n if (!publicKey || !secretKey) {\n throw new Error(\n \"Gateway keys missing: set GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY \" +\n \"(or pass publicKey/secretKey).\",\n );\n }\n return { host: host.replace(/\\/+$/, \"\"), publicKey, secretKey };\n}\n\n/** A platform answer outside 2xx, its status kept so a caller can act on one\n * code (a 409 on a name already taken) instead of parsing the message. */\nexport class ApiError extends Error {\n constructor(\n public readonly status: number,\n method: string,\n path: string,\n body: string,\n ) {\n super(`${method} ${path} -> ${status}: ${body}`);\n this.name = \"ApiError\";\n }\n}\n\n/** Authenticated JSON request against the platform API — the primitive the\n * worlds helpers and the TS CLI share. */\nexport async function apiRequest<T>(\n options: WorldsClientOptions,\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\",\n path: string,\n body?: unknown,\n): Promise<T> {\n const { host, publicKey, secretKey } = resolveEnv(options);\n const res = await fetch(`${host}${path}`, {\n method,\n headers: {\n \"content-type\": \"application/json\",\n authorization:\n \"Basic \" + Buffer.from(`${publicKey}:${secretKey}`).toString(\"base64\"),\n },\n ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n });\n const text = await res.text();\n if (!res.ok) throw new ApiError(res.status, method, path, text.slice(0, 400));\n return JSON.parse(text) as T;\n}\n\n/** Set (or rotate) one environment secret — write-only: no API returns it. */\nexport async function setEnvSecret(\n slug: string,\n key: string,\n value: string,\n options: WorldsClientOptions = {},\n): Promise<{ key: string; created: boolean }> {\n return apiRequest(\n options,\n \"PUT\",\n \"/api/public/benchmark-containers/secrets\",\n {\n slug,\n key,\n value,\n },\n );\n}\n\n/** Keys and rotation timestamps only — never values. */\nexport async function listEnvSecretKeys(\n slug: string,\n options: WorldsClientOptions = {},\n): Promise<{ key: string; updatedAt: string }[]> {\n const res = await apiRequest<{\n secrets: { key: string; updatedAt: string }[];\n }>(\n options,\n \"GET\",\n `/api/public/benchmark-containers/secrets?slug=${encodeURIComponent(slug)}`,\n );\n return res.secrets;\n}\n\nexport async function deleteEnvSecret(\n slug: string,\n key: string,\n options: WorldsClientOptions = {},\n): Promise<void> {\n await apiRequest(\n options,\n \"DELETE\",\n \"/api/public/benchmark-containers/secrets\",\n {\n slug,\n key,\n },\n );\n}\n\nexport type RunConfigSummary = {\n id: string;\n name: string;\n runType: string;\n createdAt: string;\n models: string[];\n parallelism: number;\n autoRunOnPush: boolean;\n agent: string | null;\n};\n\n/** Run configs in the project. CI resolves by NAME and dispatches by id. */\nexport async function listRunConfigs(\n options: WorldsClientOptions = {},\n): Promise<RunConfigSummary[]> {\n const res = await apiRequest<{ runConfigs: RunConfigSummary[] }>(\n options,\n \"GET\",\n \"/api/public/benchmark-containers/run-configs\",\n );\n return res.runConfigs;\n}\n\n/** What a run config selects for the runner to work through. A config runs\n * EITHER the bundle's own scenarios (`taskNames`, `taskSetDatasetId`) OR the\n * project's stored tasks (`worldTasks`, api worlds only) — never both. A\n * stored task ref without `version` runs the task's current version at\n * dispatch time; with it, that version forever. */\nexport type RunConfigInput = {\n id?: string;\n name: string;\n models: string[];\n parallelism?: number;\n numExamples?: number;\n rolloutsPerExample?: number;\n timeoutMinutes?: number;\n agent?: string;\n taskSetDatasetId?: string | null;\n taskNames?: string[];\n worldTasks?: WorldTaskIdRef[];\n autoRunOnPush?: boolean;\n};\n\n/** Create a run config, or update the one named by `id`. */\nexport async function upsertRunConfig(\n input: RunConfigInput,\n options: WorldsClientOptions = {},\n): Promise<RunConfigSummary> {\n return apiRequest<RunConfigSummary>(\n options,\n \"POST\",\n \"/api/public/benchmark-containers/run-configs\",\n input,\n );\n}\n\n/** `id[@version]` items (comma-separated or an array) → stored task refs;\n * the spelling `bench run-configs create --world-tasks` takes. */\nexport function parseWorldTaskRefs(spec: string | string[]): WorldTaskIdRef[] {\n const items = (Array.isArray(spec) ? spec : spec.split(\",\"))\n .map((s) => s.trim())\n .filter(Boolean);\n return items.map((item) => {\n const at = item.lastIndexOf(\"@\");\n if (at < 0) return { id: item };\n const id = item.slice(0, at);\n const version = Number(item.slice(at + 1));\n if (!id || !Number.isInteger(version) || version < 1)\n throw new Error(\n `stored task ref '${item}' is not <id> or <id>@<version> (version a positive integer)`,\n );\n return { id, version };\n });\n}\n\nexport type RunReport = {\n id: string;\n status: string;\n terminal: boolean;\n score: number | null;\n summary: string | null;\n model: string | null;\n versionLabel: string | null;\n parallelism: number;\n shardsCompleted: number | null;\n /** The run's page on the platform — what a PR comment should link. */\n url: string | null;\n evaluations: {\n id: string;\n status: string;\n avgReward: number | null;\n url: string | null;\n }[];\n samples: {\n task: string | null;\n reward: number | null;\n rewards: Record<string, unknown>;\n sessionId: string | null;\n }[];\n};\n\n/** The read half of dispatch: status, score, per-shard evaluations, and\n * per-task rewards — everything a CI gate needs. */\nexport async function getRun(\n runId: string,\n options: WorldsClientOptions = {},\n): Promise<RunReport> {\n return apiRequest(\n options,\n \"GET\",\n `/api/public/benchmark-containers/runs/${encodeURIComponent(runId)}`,\n );\n}\n\n/** Poll a run to terminal (default every 20s, up to `timeoutMinutes`). */\nexport async function waitForRun(\n runId: string,\n opts: {\n timeoutMinutes?: number;\n intervalSeconds?: number;\n onTick?: (run: RunReport) => void;\n options?: WorldsClientOptions;\n } = {},\n): Promise<RunReport> {\n const deadline = Date.now() + (opts.timeoutMinutes ?? 45) * 60_000;\n for (;;) {\n const run = await getRun(runId, opts.options ?? {});\n if (run.terminal) return run;\n if (Date.now() > deadline)\n throw new Error(\n `Run ${runId} still ${run.status} after the wait timeout.`,\n );\n opts.onTick?.(run);\n await new Promise((resolve) =>\n setTimeout(resolve, (opts.intervalSeconds ?? 20) * 1000),\n );\n }\n}\n\nexport type RunProvenance = {\n branch?: string;\n commit?: string;\n repoUrl?: string;\n actor?: { id?: string; name?: string; imageUrl?: string; kind?: string };\n};\n\n/**\n * Where a dispatch comes from, DETECTED rather than configured: the CI\n * checkout's branch/commit/actor under GitHub Actions, else the developer's\n * own git checkout. A run nobody can trace to a branch is a score with no\n * code attached, so every dispatch carries this unless overridden.\n */\nexport function detectProvenance(): RunProvenance {\n const env =\n (globalThis as { process?: { env?: Record<string, string | undefined> } })\n .process?.env ?? {};\n const out: RunProvenance = {};\n const ref = env.GITHUB_HEAD_REF || env.GITHUB_REF_NAME;\n if (ref) out.branch = ref;\n if (env.GITHUB_SHA) out.commit = env.GITHUB_SHA;\n const server = env.GITHUB_SERVER_URL ?? \"https://github.com\";\n if (env.GITHUB_REPOSITORY) out.repoUrl = `${server}/${env.GITHUB_REPOSITORY}`;\n if (env.GITHUB_ACTOR) {\n out.actor = {\n kind: \"ci\",\n id: env.GITHUB_ACTOR,\n name: env.GITHUB_ACTOR,\n // GitHub serves every account's avatar at /<login>.png.\n imageUrl: `${server}/${env.GITHUB_ACTOR}.png`,\n };\n }\n if (!out.branch || !out.commit) {\n try {\n const { execFileSync } =\n require(\"node:child_process\") as typeof import(\"node:child_process\");\n const git = (args: string[]) =>\n execFileSync(\"git\", args, {\n encoding: \"utf-8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n })\n .toString()\n .trim();\n out.branch = out.branch ?? git([\"rev-parse\", \"--abbrev-ref\", \"HEAD\"]);\n out.commit = out.commit ?? git([\"rev-parse\", \"HEAD\"]);\n if (!out.repoUrl) {\n const remote = git([\"config\", \"--get\", \"remote.origin.url\"]);\n if (remote) out.repoUrl = remote.replace(/\\.git$/, \"\");\n }\n if (!out.actor) {\n const name = git([\"config\", \"--get\", \"user.name\"]);\n if (name) out.actor = { kind: \"user\", name };\n }\n } catch {\n // No git here — dispatch without provenance rather than failing.\n }\n }\n return out;\n}\n\n/** One scenario of a world, as data. */\nexport class WorldTask {\n constructor(\n readonly world: WorldSet,\n readonly name: string,\n readonly variant: string | null,\n ) {}\n}\n\n/**\n * THE world, from a TS process: pinned identity + its tasks + hosted runs.\n *\n * const world = await openWorld(\"google-drive-sim@main\");\n * console.log(world.version.semanticVersion, world.tasks.length);\n * const runs = await world.dispatch(runConfigId);\n */\nexport class WorldSet {\n constructor(\n readonly slugRef: string,\n readonly slug: string,\n readonly ref: string | null,\n readonly version: ResolvedWorldVersion,\n public tasks: WorldTask[],\n private readonly options: WorldsClientOptions,\n ) {}\n\n task(variant: string): WorldTask {\n const hit = this.tasks.find(\n (t) => t.variant === variant || t.name.includes(variant),\n );\n if (!hit) {\n const known = this.tasks.map((t) => t.variant ?? t.name).join(\", \");\n throw new Error(`no task matches ${variant}; have: ${known}`);\n }\n return hit;\n }\n\n /**\n * Open a LIVE session against one of this world's tasks — a bundled task's\n * name or an inline `WorldTaskSpec`: the platform boots (or reuses) a warm\n * container, and your agent calls its tools through the platform. See\n * worlds/session.ts.\n */\n async open(\n task: import(\"./session\").WorldTaskRef,\n opts: {\n reuseWarm?: boolean;\n surfaces?: import(\"./browser\").WorldSurfaceKind[];\n } = {},\n ): Promise<import(\"./session\").WorldSession> {\n const { openSession } = await import(\"./session\");\n return openSession(this.slug, {\n task,\n versionId: this.version.versionId,\n reuseWarm: opts.reuseWarm,\n surfaces: opts.surfaces,\n options: this.options,\n });\n }\n\n /**\n * Start a HOSTED run of a run config against this world — the platform\n * executes the (Python) world in parallel containers per the config's\n * `parallelism` and files one graded run per model. Returns those runs.\n */\n async dispatch(\n runConfigId: string,\n opts: {\n containerId?: string;\n versionId?: string;\n /** Override the auto-detected branch/commit/actor. */\n provenance?: RunProvenance;\n } = {},\n ): Promise<{ versionLabel: string; runs: DispatchedRun[] }> {\n const provenance = opts.provenance ?? detectProvenance();\n return apiRequest(\n this.options,\n \"POST\",\n \"/api/public/benchmark-containers/run-configs/dispatch\",\n {\n runConfigId,\n ...(opts.containerId ? { containerId: opts.containerId } : {}),\n versionId: opts.versionId ?? this.version.versionId,\n ...provenance,\n },\n );\n }\n}\n\n/**\n * Resolve `slug` / `slug@branch|tag|semver|hash` to its pinned version and\n * task list. The task list comes from the version's file manifest\n * (`tasks/<name>/task.toml`), so it needs no bundle download.\n */\nexport async function openWorld(\n slugRef: string,\n options: WorldsClientOptions = {},\n): Promise<WorldSet> {\n const at = slugRef.indexOf(\"@\");\n const slug = at === -1 ? slugRef : slugRef.slice(0, at);\n const ref = at === -1 ? null : slugRef.slice(at + 1);\n\n const version = await apiRequest<\n ResolvedWorldVersion & { taskNames?: string[] }\n >(options, \"POST\", \"/api/public/benchmark-containers/resolve-version\", {\n slug,\n ...(ref ? { ref } : {}),\n });\n\n const world = new WorldSet(\n slugRef,\n slug,\n ref,\n {\n versionId: version.versionId,\n semanticVersion: version.semanticVersion ?? null,\n contentHash: version.contentHash,\n state: version.state,\n },\n [],\n options,\n );\n for (const name of version.taskNames ?? []) {\n const variant = /^[a-z0-9]+-([a-z0-9]+)-/.exec(name)?.[1] ?? null;\n world.tasks.push(new WorldTask(world, name, variant));\n }\n return world;\n}\n\n// The session surface completes the worlds module, so `@withgateway/sdk/worlds`\n// carries both halves: running a world locally, and driving one the platform\n// hosts. (session.ts imports apiRequest from here; the cycle is function-level\n// only, and the build below is what proves it resolves.)\nexport * from \"./session\";\n\n// Stored tasks: the task spec as a named, versioned project resource that\n// `openSession(world, { task: { id } })` opens on.\nexport * from \"./tasks\";\n\n// The computer-use half: surfaces, a Playwright browser on the world's UI,\n// and browser actions as model tools.\nexport * from \"./browser\";\n\n// The hub half: push, pull, propose and the content-hash primitives the CLI\n// runs on. These were reachable only from inside the package, so a consumer\n// could drive a world but never publish one.\nexport * from \"./hub\";\n\n// PR validation: push-dispatch-wait-gate as one composed call, for CI.\nexport * from \"./validate\";\n\n// Discovery: what a world holds and how each field is stored (`describeWorld`),\n// and the stored forms of a plaintext under the world's [redact] table\n// (`storedForms`, `redactionOf`) — the same digest rule as the Python runtime.\nexport * from \"./describe\";\nexport * from \"./redaction\";\nexport * from \"./transforms\";\n\n// Lookup: the rows of one entity matching a predicate (`queryRows`), by\n// stored value or — with `resolve` — by plaintext the runtime maps through\n// the same [redact] table.\nexport * from \"./query\";\n\n// Migration: a stored world into a schema world (`migrateWorld`), dry run by\n// default; the project's connector worlds at once (`migrateProjectWorlds`).\nexport * from \"./migrate\";\n\n// Tool calls into rows: the record contract, `captureToolCalls` (record an\n// agent's real calls), `toolCallsFromObservations` (from a trace) and\n// `ingestToolCalls` (into a directory or a slug). Redaction optional, off by default.\nexport * from \"./ingest\";\n","{\n \"name\": \"@withgateway/sdk\",\n \"version\": \"0.2.3\",\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 \"./cli\": {\n \"types\": \"./dist/cli.d.ts\",\n \"import\": \"./dist/cli.mjs\",\n \"require\": \"./dist/cli.js\"\n }\n },\n \"files\": [\n \"dist\",\n \"skills\",\n \"runtime\",\n \"README.md\"\n ],\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"scripts\": {\n \"prebuild\": \"node scripts/copy-skills.mjs && node scripts/copy-runtime.mjs\",\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"typecheck\": \"tsc --noEmit\",\n \"typecheck:examples\": \"tsc -p tsconfig.examples.json --noEmit\",\n \"test\": \"vitest\",\n \"test:run\": \"vitest run\",\n \"lint\": \"eslint src --ext .ts\",\n \"clean\": \"rm -rf dist\",\n \"example\": \"tsx examples/test-ab-experiment.ts\",\n \"test:crm\": \"tsx examples/test-crm-ab-experiment.ts\",\n \"test:crm:balanced\": \"tsx examples/test-crm-ab-experiment.ts --balanced\",\n \"test:crm:full\": \"tsx examples/test-crm-ab-experiment.ts --users 12 --all-tasks --concurrency 3\"\n },\n \"keywords\": [\n \"gateway\",\n \"ab-testing\",\n \"experiments\",\n \"opentelemetry\",\n \"tracing\",\n \"observability\",\n \"llm\"\n ],\n \"author\": \"Gateway Team\",\n \"license\": \"MIT\",\n \"engines\": {\n \"node\": \">=18.0.0\"\n },\n \"peerDependencies\": {\n \"@opentelemetry/api\": \"^1.0.0\",\n \"@opentelemetry/exporter-trace-otlp-http\": \">=0.50.0\",\n \"@opentelemetry/resources\": \">=1.0.0\",\n \"@opentelemetry/sdk-trace-base\": \">=1.0.0\",\n \"@opentelemetry/sdk-trace-node\": \">=1.0.0\",\n \"playwright\": \">=1.40.0\"\n },\n \"peerDependenciesMeta\": {\n \"@opentelemetry/api\": {\n \"optional\": true\n },\n \"@opentelemetry/sdk-trace-base\": {\n \"optional\": true\n },\n \"@opentelemetry/sdk-trace-node\": {\n \"optional\": true\n },\n \"@opentelemetry/exporter-trace-otlp-http\": {\n \"optional\": true\n },\n \"@opentelemetry/resources\": {\n \"optional\": true\n },\n \"playwright\": {\n \"optional\": true\n }\n },\n \"optionalDependencies\": {\n \"@arizeai/openinference-instrumentation-anthropic\": \"^0.1.15\",\n \"@arizeai/openinference-instrumentation-openai\": \"^4.1.5\"\n },\n \"devDependencies\": {\n \"@anthropic-ai/sdk\": \"^0.79.0\",\n \"@opentelemetry/api\": \"^1.9.0\",\n \"@opentelemetry/exporter-trace-otlp-http\": \"^0.212.0\",\n \"@opentelemetry/resources\": \"^2.6.0\",\n \"@opentelemetry/sdk-trace-base\": \"^1.30.1\",\n \"@opentelemetry/sdk-trace-node\": \"^2.6.0\",\n \"@opentelemetry/semantic-conventions\": \"^1.40.0\",\n \"@types/node\": \"^20.0.0\",\n \"openai\": \"^4.70.0\",\n \"tsup\": \"^8.0.0\",\n \"tsx\": \"^4.0.0\",\n \"typescript\": \"^5.0.0\",\n \"vitest\": \"^3.2.6\"\n },\n \"overrides\": {\n \"protobufjs\": \"^8.4.1\",\n \"vite@6\": \"^6.4.3\",\n \"postcss\": \"^8.5.18\",\n \"picomatch@4\": \"^4.0.4\"\n },\n \"pnpm\": {\n \"overrides\": {\n \"protobufjs\": \"^8.4.1\",\n \"vitest\": \"^3.2.6\",\n \"vite@6\": \"^6.4.3\",\n \"postcss\": \"^8.5.18\",\n \"picomatch@4\": \"^4.0.4\"\n }\n },\n \"bin\": {\n \"gateway\": \"./dist/cli.js\"\n }\n}\n","export * from \"./experiments/index\";\nexport * from \"./context/index\";\nexport * from \"./memory/index\";\nexport * from \"./personas/index\";\nexport * from \"./replay/index\";\nexport * from \"./security/index\";\nexport * from \"./sessions/index\";\nexport * from \"./users/index\";\nexport * from \"./scores/index\";\nexport * from \"./worlds/index\";\nexport * from \"./worlds/session\";\nexport * as files from \"./files/index\";\nexport * as traces from \"./traces/index\";\n\n// Agent build identity (\"the agent IS the manifest\") — defineTool wraps any\n// framework tool shape; registerPrompt joins code-shipped prompts to the\n// build; tracing.init({ agent }) assembles + registers the build.\nexport {\n defineTool,\n registerPrompt,\n registerSkill,\n registerArtifact,\n getRegisteredSkills,\n getRegisteredArtifacts,\n assembleManifest,\n computeBuildHash,\n canonicalJson,\n getRegisteredTools,\n getRegisteredPrompts,\n resetBuildRegistry,\n} from \"./build/index\";\nexport type {\n ToolEffects,\n ToolIdentity,\n ArtifactIdentity,\n RegisterArtifactOptions,\n AgentBuildManifest,\n DefineToolInput,\n} from \"./build/index\";\n\n// Top-level like the Python SDK's `gatewaysdk.identify` (lives in tracing/identity).\nexport { identify, resolveUserId } from \"./tracing/identity\";\nexport type { IdentifyOptions } from \"./tracing/identity\";\n\nimport * as _tracingModule from \"./tracing/index\";\nimport type { TracingConfig } from \"./tracing/types\";\nimport { ExperimentSpanProcessor } from \"./experiments/otel\";\n\n/**\n * Tracing module with automatic ExperimentSpanProcessor wiring.\n *\n * When imported from the main entry (\"@withgateway/sdk\"), init() automatically\n * adds ExperimentSpanProcessor so spans are tagged with experiment context.\n * Both modules share the same bundle, so the AsyncLocalStorage context is\n * shared — no cross-bundle duplication.\n */\nexport const tracing: typeof _tracingModule = {\n ..._tracingModule,\n init(config: TracingConfig = {}) {\n if (config.enableExperiments !== false) {\n const processors = [\n new ExperimentSpanProcessor(),\n ...(config.customSpanProcessors ?? []),\n ];\n return _tracingModule.init({\n ...config,\n customSpanProcessors: processors,\n });\n }\n return _tracingModule.init(config);\n },\n};\n","/**\n * Deterministic variant assignment for A/B experiments.\n *\n * Algorithm:\n * 1. Hash (experiment_key + user_id) → deterministic bucket [0, 1)\n * 2. If bucket >= traffic_percent/100 → user not in experiment\n * 3. Otherwise, normalize bucket within traffic and assign to variant by weight\n */\n\nimport { createHash } from \"crypto\";\nimport type { ExperimentConfig, Variant } from \"./types\";\n\nexport function computeHash(experimentKey: string, userId: string): number {\n const raw = createHash(\"sha256\")\n .update(`${experimentKey}:${userId}`)\n .digest(\"hex\");\n // Divide by 2³² to keep range strictly [0, 1)\n return parseInt(raw.slice(0, 8), 16) / 0x100000000;\n}\n\nexport function assignVariant(\n config: ExperimentConfig,\n userId: string,\n): Variant | null {\n if (!config.variants || config.variants.length === 0) {\n return null;\n }\n\n const bucket = computeHash(config.key, userId);\n const trafficThreshold = config.trafficPercent / 100;\n\n if (bucket >= trafficThreshold) {\n return null;\n }\n\n const normalizedBucket = bucket / trafficThreshold;\n const totalWeight = config.variants.reduce((sum, v) => sum + v.weight, 0);\n\n if (totalWeight <= 0) {\n return config.variants[0] ?? null;\n }\n\n let cumulative = 0;\n for (const variant of config.variants) {\n cumulative += variant.weight / totalWeight;\n if (normalizedBucket < cumulative) {\n return variant;\n }\n }\n\n return config.variants[config.variants.length - 1] ?? null;\n}\n","/**\n * Async context management for experiments.\n *\n * Uses AsyncLocalStorage.enterWith() to set context that persists for the\n * remainder of the current async execution context. This provides:\n *\n * - Request isolation in concurrent server environments\n * - Context that survives across async boundaries (streaming, etc.)\n * - No callback wrapper required\n *\n * The context persists until clearExperimentContext() is called or the\n * async context naturally ends (e.g., request completes).\n */\n\nimport { AsyncLocalStorage } from \"async_hooks\";\nimport type { ExperimentContext } from \"./types\";\n\n// AsyncLocalStorage for request-scoped context\nexport const experimentContextStorage =\n new AsyncLocalStorage<ExperimentContext>();\n\n/**\n * Get the current experiment context.\n */\nexport function getExperimentContext(): ExperimentContext | undefined {\n return experimentContextStorage.getStore();\n}\n\n/**\n * Set the experiment context for the current async execution.\n *\n * Uses enterWith() which sets context for the remainder of the current\n * async execution without requiring a callback wrapper. This means:\n * - Context persists across await boundaries\n * - Context is isolated per request in concurrent environments\n * - Context persists until clearExperimentContext() or request ends\n *\n * Called by getVariant() when a user is assigned to a variant.\n */\nexport function setExperimentContext(context: ExperimentContext): void {\n experimentContextStorage.enterWith(context);\n}\n\n/**\n * Clear the experiment context.\n *\n * Call this when you're done with an experiment session (e.g., after handling\n * a user request) to stop attributing spans to the experiment.\n *\n * Note: In most server frameworks, the async context naturally ends when the\n * request completes, so this is optional but recommended for explicit cleanup.\n */\nexport function clearExperimentContext(): void {\n // enterWith(undefined) effectively clears the context\n experimentContextStorage.enterWith(undefined as unknown as ExperimentContext);\n}\n\n/**\n * Run a function with experiment context (scoped).\n *\n * The context is automatically cleared when the function completes.\n * This is useful for synchronous operations or fully-contained async operations.\n *\n * For streaming/async patterns, prefer setExperimentContext() which persists\n * across async boundaries.\n */\nexport function runWithExperimentContext<T>(\n context: ExperimentContext,\n fn: () => T,\n): T {\n return experimentContextStorage.run(context, fn);\n}\n","/**\n * Batched asynchronous exposure logging.\n *\n * Collects exposure events in memory and flushes periodically\n * or when the batch size threshold is reached.\n */\n\nimport type { Exposure, ExposureLoggerConfig } from \"./types\";\n\nexport class ExposureLogger {\n private buffer: Exposure[] = [];\n private readonly batchSize: number;\n private readonly flushIntervalMs: number;\n private readonly apiUrl: string;\n private readonly apiKey: string;\n private readonly secretKey: string;\n private flushTimer: ReturnType<typeof setInterval> | null = null;\n private isFlushing = false;\n\n constructor(config: ExposureLoggerConfig) {\n this.apiUrl = config.apiUrl.replace(/\\/$/, \"\");\n this.apiKey = config.apiKey;\n this.secretKey = config.secretKey ?? \"\";\n this.batchSize = config.batchSize ?? 100;\n this.flushIntervalMs = config.flushIntervalMs ?? 5_000;\n\n this.flushTimer = setInterval(() => {\n this.flush().catch((err) => {\n console.error(\"[gateway] Exposure flush error:\", err);\n });\n }, this.flushIntervalMs);\n\n if (this.flushTimer.unref) {\n this.flushTimer.unref();\n }\n }\n\n log(exposure: Exposure): void {\n this.buffer.push(exposure);\n if (this.buffer.length >= this.batchSize) {\n this.flush().catch((err) => {\n console.error(\"[gateway] Exposure flush error:\", err);\n });\n }\n }\n\n async flush(): Promise<void> {\n if (this.isFlushing || this.buffer.length === 0) {\n return;\n }\n\n this.isFlushing = true;\n const batch = this.buffer.splice(0, this.buffer.length);\n\n try {\n const authHeader = this.secretKey\n ? `Basic ${Buffer.from(`${this.apiKey}:${this.secretKey}`).toString(\"base64\")}`\n : `Bearer ${this.apiKey}`;\n\n const response = await fetch(\n `${this.apiUrl}/api/public/experiments/exposures/batch`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: authHeader,\n },\n body: JSON.stringify({\n exposures: batch,\n }),\n },\n );\n if (!response.ok) {\n this.buffer.unshift(...batch);\n console.error(\n `[gateway] Failed to log exposures: ${response.status} ${response.statusText}`,\n );\n }\n } catch (error) {\n this.buffer.unshift(...batch);\n console.error(\"[gateway] Network error logging exposures:\", error);\n } finally {\n this.isFlushing = false;\n }\n }\n\n async shutdown(): Promise<void> {\n if (this.flushTimer) {\n clearInterval(this.flushTimer);\n this.flushTimer = null;\n }\n await this.flush();\n }\n}\n","/**\n * Main A/B experiment client for TypeScript.\n *\n * Mirrors the Python SDK's ExperimentClient in:\n * gatewaysdk/sdk/src/gatewaysdk/experiments/client.py\n */\n\nimport { assignVariant } from \"./assignment\";\nimport { runWithExperimentContext, setExperimentContext } from \"./context\";\nimport { ExposureLogger } from \"./exposure-logger\";\nimport type {\n ExperimentClientConfig,\n ExperimentConfig,\n GetVariantResult,\n RegisterExperimentInput,\n} from \"./types\";\n\nexport class ExperimentClient {\n private readonly apiUrl: string;\n private readonly apiKey: string;\n private readonly secretKey: string;\n private readonly projectId: string;\n private readonly configs = new Map<string, ExperimentConfig>();\n private readonly exposureLogger: ExposureLogger;\n\n constructor(config: ExperimentClientConfig) {\n this.apiUrl = config.apiUrl.replace(/\\/$/, \"\");\n this.apiKey = config.apiKey;\n this.secretKey = config.secretKey ?? \"\";\n this.projectId = config.projectId;\n this.exposureLogger = new ExposureLogger({\n apiUrl: this.apiUrl,\n apiKey: this.apiKey,\n secretKey: this.secretKey,\n batchSize: config.exposureLogger?.batchSize,\n flushIntervalMs: config.exposureLogger?.flushIntervalMs,\n });\n }\n\n async register(input: RegisterExperimentInput): Promise<void> {\n const config: ExperimentConfig = {\n key: input.key,\n trafficPercent: input.trafficPercent ?? 100,\n variants: input.variants.map((v) => ({\n key: v.key,\n weight: v.weight ?? 1,\n config: v.config ?? {},\n })),\n };\n\n this.configs.set(config.key, config);\n\n const syncToBackend = input.syncToBackend ?? true;\n if (syncToBackend) {\n this.syncToBackendAsync(config, input.evaluatorNames).catch((err) => {\n console.error(\n `[gateway] Failed to sync experiment ${config.key}:`,\n err,\n );\n });\n }\n }\n\n async fetch(experimentKeys?: string[]): Promise<void> {\n const url = new URL(`${this.apiUrl}/api/public/experiments`);\n if (experimentKeys && experimentKeys.length > 0) {\n url.searchParams.set(\"keys\", experimentKeys.join(\",\"));\n }\n\n const authHeader = this.secretKey\n ? `Basic ${Buffer.from(`${this.apiKey}:${this.secretKey}`).toString(\"base64\")}`\n : `Bearer ${this.apiKey}`;\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n headers: {\n Authorization: authHeader,\n },\n });\n\n if (!response.ok) {\n throw new Error(\n `Failed to fetch experiments: ${response.status} ${response.statusText}`,\n );\n }\n\n const data = (await response.json()) as {\n experiments: ExperimentConfig[];\n };\n for (const config of data.experiments) {\n this.configs.set(config.key, config);\n }\n }\n\n async getVariant(\n experimentKey: string,\n userId: string,\n options?: { fetchIfMissing?: boolean },\n ): Promise<GetVariantResult> {\n const fetchIfMissing = options?.fetchIfMissing ?? true;\n\n let config = this.configs.get(experimentKey);\n if (!config && fetchIfMissing) {\n try {\n await this.fetch([experimentKey]);\n config = this.configs.get(experimentKey);\n } catch (error) {\n console.error(\n `[gateway] Failed to fetch experiment ${experimentKey}:`,\n error,\n );\n }\n }\n\n if (!config) {\n return {\n variant: null,\n inExperiment: false,\n experimentKey,\n run: (fn) => fn(),\n };\n }\n\n const variant = assignVariant(config, userId);\n if (!variant) {\n return {\n variant: null,\n inExperiment: false,\n experimentKey,\n run: (fn) => fn(),\n };\n }\n\n this.exposureLogger.log({\n userId,\n experimentId: experimentKey,\n variantKey: variant.key,\n timestamp: new Date().toISOString(),\n });\n\n const context = {\n experimentId: experimentKey,\n variantKey: variant.key,\n userId,\n };\n\n // Set context via enterWith() so spans created anywhere in this async chain are tagged.\n // Context is automatically isolated per request - no cross-request contamination.\n setExperimentContext(context);\n\n return {\n variant,\n inExperiment: true,\n experimentKey,\n run: (fn) => runWithExperimentContext(context, fn),\n };\n }\n\n getConfig(experimentKey: string): ExperimentConfig | undefined {\n return this.configs.get(experimentKey);\n }\n\n async shutdown(): Promise<void> {\n await this.exposureLogger.shutdown();\n }\n\n private async syncToBackendAsync(\n config: ExperimentConfig,\n evaluatorNames?: string[],\n ): Promise<void> {\n const authHeader = this.secretKey\n ? `Basic ${Buffer.from(`${this.apiKey}:${this.secretKey}`).toString(\"base64\")}`\n : `Bearer ${this.apiKey}`;\n\n const response = await fetch(`${this.apiUrl}/api/public/experiments`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: authHeader,\n },\n body: JSON.stringify({\n key: config.key,\n trafficPercent: config.trafficPercent,\n variants: config.variants,\n evaluatorNames: evaluatorNames ?? [],\n }),\n });\n\n if (!response.ok) {\n const text = await response.text();\n throw new Error(\n `Failed to sync experiment: ${response.status} ${response.statusText} - ${text}`,\n );\n }\n\n console.log(`[gateway] Synced experiment '${config.key}' to backend`);\n }\n}\n","/**\n * OpenTelemetry integration for A/B experiments.\n *\n * Provides a SpanProcessor that automatically injects experiment\n * context into spans. Mirrors the Python SDK's TracingContextSpanProcessor.\n */\n\nimport type { Context } from \"@opentelemetry/api\";\nimport type {\n SpanProcessor,\n Span,\n ReadableSpan,\n} from \"@opentelemetry/sdk-trace-base\";\nimport { getExperimentContext } from \"./context\";\n\nexport const EXPERIMENT_ATTRIBUTES = {\n EXPERIMENT_ID: \"gateway.experiment.id\",\n VARIANT_KEY: \"gateway.variant.key\",\n USER_ID: \"gateway.experiment.user_id\",\n} as const;\n\nexport class ExperimentSpanProcessor implements SpanProcessor {\n onStart(span: Span, _parentContext: Context): void {\n const ctx = getExperimentContext();\n if (ctx) {\n span.setAttribute(EXPERIMENT_ATTRIBUTES.EXPERIMENT_ID, ctx.experimentId);\n span.setAttribute(EXPERIMENT_ATTRIBUTES.VARIANT_KEY, ctx.variantKey);\n span.setAttribute(EXPERIMENT_ATTRIBUTES.USER_ID, ctx.userId);\n }\n }\n\n onEnd(_span: ReadableSpan): void {}\n\n async shutdown(): Promise<void> {}\n\n async forceFlush(): Promise<void> {}\n}\n\nexport function addExperimentAttributes(\n span: Span,\n experimentId: string,\n variantKey: string,\n userId: string,\n): void {\n span.setAttribute(EXPERIMENT_ATTRIBUTES.EXPERIMENT_ID, experimentId);\n span.setAttribute(EXPERIMENT_ATTRIBUTES.VARIANT_KEY, variantKey);\n span.setAttribute(EXPERIMENT_ATTRIBUTES.USER_ID, userId);\n}\n","/**\n * Singleton experiment client for simple usage.\n *\n * This mirrors the Python SDK's `gateway.experiments` singleton pattern.\n * For advanced use cases, instantiate ExperimentClient directly.\n */\n\nimport { ExperimentClient } from \"./client\";\nimport { clearExperimentContext as clearContext } from \"./context\";\nimport type {\n ExperimentClientConfig,\n GetVariantResult,\n RegisterExperimentInput,\n} from \"./types\";\n\nlet client: ExperimentClient | null = null;\n\nexport interface InitConfig {\n apiKey: string;\n secretKey?: string;\n baseUrl: string;\n projectId?: string;\n}\n\n/**\n * Initialize the experiments singleton.\n * Must be called before using other methods.\n */\nexport function init(config: InitConfig): void {\n client = new ExperimentClient({\n apiUrl: config.baseUrl,\n apiKey: config.apiKey,\n secretKey: config.secretKey,\n projectId: config.projectId ?? \"\",\n });\n}\n\n/**\n * Register an experiment configuration.\n */\nexport async function register(input: RegisterExperimentInput): Promise<void> {\n if (!client) {\n throw new Error(\n \"Experiments not initialized. Call experiments.init() first.\",\n );\n }\n return client.register(input);\n}\n\n/**\n * Get variant for a user. Returns null if user is not in experiment.\n */\nexport async function getVariant(\n experimentKey: string,\n userId: string,\n options?: { fetchIfMissing?: boolean },\n): Promise<GetVariantResult> {\n if (!client) {\n throw new Error(\n \"Experiments not initialized. Call experiments.init() first.\",\n );\n }\n return client.getVariant(experimentKey, userId, options);\n}\n\n/**\n * Fetch experiment configurations from the backend.\n */\nexport async function fetch(experimentKeys?: string[]): Promise<void> {\n if (!client) {\n throw new Error(\n \"Experiments not initialized. Call experiments.init() first.\",\n );\n }\n return client.fetch(experimentKeys);\n}\n\n/**\n * Flush pending exposures and shut down the client.\n */\nexport async function shutdown(): Promise<void> {\n if (client) {\n await client.shutdown();\n client = null;\n }\n // Also clear any lingering experiment context\n clearContext();\n}\n\n/**\n * Clear the current experiment context.\n *\n * Call this when you're done with an experiment session (e.g., after handling\n * a user request) to stop attributing new spans to the experiment.\n *\n * This mirrors Python's `gateway.experiments.clear_current_experiment()`.\n */\nexport function clearExperimentContext(): void {\n clearContext();\n}\n\n/**\n * Get the underlying ExperimentClient instance.\n * Returns null if not initialized.\n */\nexport function getClient(): ExperimentClient | null {\n return client;\n}\n","type ContextRepoKind = \"agent\" | \"prompt\" | \"skill\" | \"memory\";\ntype ContextWritePolicy = \"read_only\" | \"propose\" | \"commit\";\n\ntype ContextFileEntry =\n | {\n type: \"file\";\n content: string;\n mimeType: string;\n mime_type: string;\n }\n | {\n type: \"agent\" | \"skill\";\n repoHandle: string;\n repo_handle: string;\n commitId?: string | null;\n commit_id?: string | null;\n };\n\ntype ContextRepo<TKind extends ContextRepoKind = ContextRepoKind> = {\n id: string;\n repoHandle: string;\n repo_handle: string;\n ownerHandle: string;\n owner_handle: string;\n kind: TKind;\n description: string;\n readme: string;\n tags: string[];\n writePolicy: ContextWritePolicy;\n write_policy: ContextWritePolicy;\n isPublic: boolean;\n is_public: boolean;\n isArchived: boolean;\n is_archived: boolean;\n url?: string;\n createdAt: string;\n created_at: string;\n updatedAt: string;\n updated_at: string;\n};\n\ntype ContextCommit = {\n id: string;\n commitHash: string;\n commit_hash: string;\n parentCommitHash: string | null;\n parent_commit_hash: string | null;\n createdAt: string;\n created_at: string;\n};\n\ntype ContextSnapshot<TKind extends ContextRepoKind = ContextRepoKind> = {\n repo: ContextRepo<TKind>;\n commit: ContextCommit;\n files: Record<string, ContextFileEntry>;\n};\n\ntype ContextListResponse<TKind extends ContextRepoKind = ContextRepoKind> = {\n repos: ContextRepo<TKind>[];\n limit: number;\n offset: number;\n total: number;\n};\n\ntype ContextPushResponse = {\n url: string;\n status: \"committed\" | \"proposed\";\n repoId: string;\n repo_id: string;\n commitId: string | null;\n commit_id: string | null;\n commitHash: string | null;\n commit_hash: string | null;\n proposalId?: string | null;\n proposal_id?: string | null;\n};\n\ntype ContextFileInput =\n | {\n content: string;\n mimeType?: string;\n mime_type?: string;\n }\n | {\n repoHandle?: string;\n repo_handle?: string;\n kind?: \"agent\" | \"skill\";\n type?: \"agent\" | \"skill\";\n commitId?: string | null;\n commit_id?: string | null;\n }\n | null;\n\ntype ContextRuntimeContext = {\n source?: \"sdk\" | \"agent\" | \"dream\" | \"api\" | \"platform\";\n actorType?: \"api_key\" | \"agent\" | \"process\" | \"user\";\n proposedBy?: string;\n agentId?: string;\n agentStableId?: string;\n processId?: string;\n traceId?: string;\n spanId?: string;\n sessionId?: string;\n userId?: string;\n teamId?: string;\n metadata?: Record<string, unknown>;\n};\n\ntype ContextPullOptions = {\n version?: string;\n};\n\ntype ContextListOptions = {\n query?: string;\n isPublic?: boolean;\n isArchived?: boolean;\n limit?: number;\n offset?: number;\n};\n\ntype ContextPushOptions = ContextRuntimeContext & {\n files: Record<string, ContextFileInput>;\n parentCommit?: string;\n description?: string;\n readme?: string;\n tags?: string[];\n isPublic?: boolean;\n writePolicy?: ContextWritePolicy;\n message?: string;\n};\n\ntype ContextRepoRef =\n | string\n | {\n identifier?: string;\n repoHandle?: string;\n repo_handle?: string;\n label?: string;\n version?: string;\n writable?: boolean;\n };\n\ntype ResolvedContextRef<TKind extends ContextRepoKind = ContextRepoKind> = {\n identifier: string;\n version?: string;\n writable?: boolean;\n snapshot: ContextSnapshot<TKind>;\n primaryPath: string | null;\n content: string;\n};\n\ntype ResolvedAgentContext = {\n agent: ContextSnapshot<\"agent\">;\n config: Record<string, unknown>;\n prompt: ResolvedContextRef<\"prompt\"> | null;\n prompts: ResolvedContextRef<\"prompt\">[];\n skills: ResolvedContextRef<\"skill\">[];\n memory: ResolvedContextRef<\"memory\">[];\n system: string;\n renderSystem: (options?: RenderSystemOptions) => string;\n provenance: ContextProvenance[];\n};\n\ntype ContextProvenance = {\n kind: ContextRepoKind;\n repoHandle: string;\n commitHash: string;\n label?: string;\n};\n\ntype RenderSystemOptions = {\n includeAgent?: boolean;\n includePrompts?: boolean;\n includeSkills?: boolean;\n includeMemory?: boolean;\n};\n\ntype GatewayContextConfig = {\n host: string;\n publicKey: string;\n secretKey: string;\n debug?: boolean;\n};\n\ntype GatewayContextFromEnvConfig = Partial<GatewayContextConfig>;\n\nexport class GatewayContextError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message);\n this.name = \"GatewayContextError\";\n this.cause = options?.cause;\n }\n}\n\nexport class GatewayContextConflictError extends GatewayContextError {\n readonly latestCommit: unknown;\n\n constructor(message: string, latestCommit: unknown) {\n super(message);\n this.name = \"GatewayContextConflictError\";\n this.latestCommit = latestCommit;\n }\n}\n\nexport class GatewayContext {\n private readonly host: string;\n private readonly publicKey: string;\n private readonly secretKey: string;\n private readonly debug: boolean;\n\n constructor(config: GatewayContextConfig) {\n this.host = config.host.replace(/\\/$/, \"\");\n this.publicKey = config.publicKey;\n this.secretKey = config.secretKey;\n this.debug = config.debug ?? false;\n }\n\n static fromEnv(config: GatewayContextFromEnvConfig = {}) {\n const host =\n config.host ?? process.env.GATEWAY_HOST ?? process.env.GATEWAY_HOST;\n const publicKey =\n config.publicKey ??\n process.env.GATEWAY_PUBLIC_KEY ??\n process.env.GATEWAY_PUBLIC_KEY;\n const secretKey =\n config.secretKey ??\n process.env.GATEWAY_SECRET_KEY ??\n 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 GatewayContextError(\n `Missing Gateway context configuration: ${missing.join(\", \")}`,\n );\n }\n\n return new GatewayContext({\n ...config,\n host: host!,\n publicKey: publicKey!,\n secretKey: secretKey!,\n });\n }\n\n pullAgent(identifier: string, options: ContextPullOptions = {}) {\n return this.pull(\"agent\", identifier, options);\n }\n\n pullPrompt(identifier: string, options: ContextPullOptions = {}) {\n return this.pull(\"prompt\", identifier, options);\n }\n\n pullSkill(identifier: string, options: ContextPullOptions = {}) {\n return this.pull(\"skill\", identifier, options);\n }\n\n pullMemory(identifier: string, options: ContextPullOptions = {}) {\n return this.pull(\"memory\", identifier, options);\n }\n\n pushAgent(identifier: string, options: ContextPushOptions) {\n return this.push(\"agent\", identifier, options);\n }\n\n pushPrompt(identifier: string, options: ContextPushOptions) {\n return this.push(\"prompt\", identifier, options);\n }\n\n pushSkill(identifier: string, options: ContextPushOptions) {\n return this.push(\"skill\", identifier, options);\n }\n\n pushMemory(identifier: string, options: ContextPushOptions) {\n return this.push(\"memory\", identifier, options);\n }\n\n listAgents(options: ContextListOptions = {}) {\n return this.list(\"agent\", options);\n }\n\n listPrompts(options: ContextListOptions = {}) {\n return this.list(\"prompt\", options);\n }\n\n listSkills(options: ContextListOptions = {}) {\n return this.list(\"skill\", options);\n }\n\n listMemory(options: ContextListOptions = {}) {\n return this.list(\"memory\", options);\n }\n\n agentExists(identifier: string) {\n return this.exists(\"agent\", identifier);\n }\n\n promptExists(identifier: string) {\n return this.exists(\"prompt\", identifier);\n }\n\n skillExists(identifier: string) {\n return this.exists(\"skill\", identifier);\n }\n\n memoryExists(identifier: string) {\n return this.exists(\"memory\", identifier);\n }\n\n deleteAgent(identifier: string) {\n return this.delete(\"agent\", identifier);\n }\n\n deletePrompt(identifier: string) {\n return this.delete(\"prompt\", identifier);\n }\n\n deleteSkill(identifier: string) {\n return this.delete(\"skill\", identifier);\n }\n\n deleteMemory(identifier: string) {\n return this.delete(\"memory\", identifier);\n }\n\n async resolveAgent(\n identifier: string,\n runtimeContext: ContextRuntimeContext = {},\n ): Promise<ResolvedAgentContext> {\n const agent = await this.pullAgent(identifier);\n const config = parseJsonFile(agent, \"config.json\");\n const prompts = await this.resolveRefs(\"prompt\", getPromptRefs(config));\n const skills = await this.resolveRefs(\"skill\", getRefList(config.skills));\n const memory = await this.resolveRefs(\"memory\", getRefList(config.memory));\n const bundleBase = {\n agent,\n config,\n prompt: prompts[0] ?? null,\n prompts,\n skills,\n memory,\n provenance: [\n provenanceFor(agent),\n ...prompts.map(({ snapshot, version }) => provenanceFor(snapshot, version)),\n ...skills.map(({ snapshot, version }) => provenanceFor(snapshot, version)),\n ...memory.map(({ snapshot, version }) => provenanceFor(snapshot, version)),\n ],\n };\n\n const renderSystem = (options: RenderSystemOptions = {}) =>\n renderAgentSystem(bundleBase, options);\n\n if (Object.keys(runtimeContext).length > 0) {\n this.log(\"resolveAgent runtime context %o\", runtimeContext);\n }\n\n return {\n ...bundleBase,\n system: renderSystem(),\n renderSystem,\n };\n }\n\n async pull<TKind extends ContextRepoKind>(\n kind: TKind,\n identifier: string,\n options: ContextPullOptions = {},\n ): Promise<ContextSnapshot<TKind>> {\n const query = new URLSearchParams();\n if (options.version) query.set(\"version\", options.version);\n const suffix = query.toString() ? `?${query.toString()}` : \"\";\n return this.requestJson<ContextSnapshot<TKind>>(\n \"GET\",\n `/api/public/context/${endpointForKind(kind)}/${encodeIdentifier(\n identifier,\n )}${suffix}`,\n );\n }\n\n async push<TKind extends ContextRepoKind>(\n kind: TKind,\n identifier: string,\n options: ContextPushOptions,\n ): Promise<ContextPushResponse> {\n return this.requestJson<ContextPushResponse>(\n \"POST\",\n `/api/public/context/${endpointForKind(kind)}/${encodeIdentifier(\n identifier,\n )}`,\n {\n files: options.files,\n ...(options.parentCommit ? { parentCommit: options.parentCommit } : {}),\n ...(options.description ? { description: options.description } : {}),\n ...(options.readme ? { readme: options.readme } : {}),\n ...(options.tags ? { tags: options.tags } : {}),\n ...(options.isPublic !== undefined ? { isPublic: options.isPublic } : {}),\n ...(options.writePolicy ? { writePolicy: options.writePolicy } : {}),\n ...(options.message ? { message: options.message } : {}),\n ...runtimeContextPayload(options),\n },\n );\n }\n\n async list<TKind extends ContextRepoKind>(\n kind: TKind,\n options: ContextListOptions = {},\n ): Promise<ContextListResponse<TKind>> {\n const query = new URLSearchParams();\n if (options.query) query.set(\"query\", options.query);\n if (options.isPublic !== undefined) query.set(\"isPublic\", String(options.isPublic));\n if (options.isArchived !== undefined)\n query.set(\"isArchived\", String(options.isArchived));\n if (options.limit !== undefined) query.set(\"limit\", String(options.limit));\n if (options.offset !== undefined) query.set(\"offset\", String(options.offset));\n const suffix = query.toString() ? `?${query.toString()}` : \"\";\n return this.requestJson<ContextListResponse<TKind>>(\n \"GET\",\n `/api/public/context/${endpointForKind(kind)}${suffix}`,\n );\n }\n\n async exists(kind: ContextRepoKind, identifier: string): Promise<boolean> {\n const query = new URLSearchParams({ exists: \"true\" });\n const response = await this.requestJson<{ exists: boolean }>(\n \"GET\",\n `/api/public/context/${endpointForKind(kind)}/${encodeIdentifier(\n identifier,\n )}?${query.toString()}`,\n );\n return response.exists;\n }\n\n async delete(kind: ContextRepoKind, identifier: string) {\n return this.requestJson<{ deleted: boolean; repoHandle: string; repo_handle: string }>(\n \"DELETE\",\n `/api/public/context/${endpointForKind(kind)}/${encodeIdentifier(identifier)}`,\n );\n }\n\n private async resolveRefs<TKind extends ContextRepoKind>(\n kind: TKind,\n refs: ContextRepoRef[],\n ): Promise<ResolvedContextRef<TKind>[]> {\n const resolved: ResolvedContextRef<TKind>[] = [];\n for (const ref of refs) {\n const normalized = normalizeRef(ref);\n if (!normalized) continue;\n const snapshot = await this.pull(kind, normalized.identifier, {\n version: normalized.version,\n });\n const primaryPath = primaryPathForKind(kind, snapshot);\n const content = primaryPath ? readFile(snapshot, primaryPath) ?? \"\" : \"\";\n resolved.push({\n ...normalized,\n snapshot,\n primaryPath,\n content,\n });\n }\n return resolved;\n }\n\n private async requestJson<TResponse>(\n method: \"GET\" | \"POST\" | \"DELETE\",\n path: string,\n payload?: Record<string, unknown>,\n ): Promise<TResponse> {\n const response = await fetch(`${this.host}${path}`, {\n method,\n headers: {\n Authorization: this.authHeader(),\n ...(payload ? { \"Content-Type\": \"application/json\" } : {}),\n },\n ...(payload ? { body: JSON.stringify(payload) } : {}),\n });\n\n const text = await response.text();\n const body = text ? safeJson(text) : {};\n if (!response.ok) {\n const message =\n typeof body.message === \"string\"\n ? body.message\n : `Gateway API ${response.status} on ${path}`;\n if (response.status === 409) {\n throw new GatewayContextConflictError(\n message,\n body.latestCommit ?? null,\n );\n }\n throw new GatewayContextError(message);\n }\n\n this.log(\"%s %s -> %s\", method, path, response.status);\n return body as TResponse;\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.context] ${message}`, ...args);\n }\n }\n}\n\nfunction renderAgentSystem(\n bundle: Omit<ResolvedAgentContext, \"system\" | \"renderSystem\">,\n options: RenderSystemOptions = {},\n) {\n const includeAgent = options.includeAgent ?? true;\n const includePrompts = options.includePrompts ?? true;\n const includeSkills = options.includeSkills ?? true;\n const includeMemory = options.includeMemory ?? false;\n const sections: string[] = [];\n\n if (includeAgent) {\n const agentContent = readFile(bundle.agent, \"AGENTS.md\");\n if (agentContent) sections.push(formatSection(\"Agent\", bundle.agent, agentContent));\n }\n\n if (includePrompts) {\n for (const prompt of bundle.prompts) {\n if (prompt.content) {\n sections.push(formatSection(\"Prompt\", prompt.snapshot, prompt.content));\n }\n }\n }\n\n if (includeSkills) {\n for (const skill of bundle.skills) {\n if (skill.content) {\n sections.push(formatSection(\"Skill\", skill.snapshot, skill.content));\n }\n }\n }\n\n if (includeMemory) {\n for (const memory of bundle.memory) {\n if (memory.content) {\n sections.push(formatSection(\"Memory\", memory.snapshot, memory.content));\n }\n }\n }\n\n return sections.join(\"\\n\\n---\\n\\n\");\n}\n\nfunction formatSection(\n title: string,\n snapshot: ContextSnapshot,\n content: string,\n) {\n return [\n `# ${title}: ${snapshot.repo.repoHandle}`,\n `<!-- commit: ${snapshot.commit.commitHash} -->`,\n \"\",\n content.trim(),\n ].join(\"\\n\");\n}\n\nfunction getPromptRefs(config: Record<string, unknown>): ContextRepoRef[] {\n const refs = [\n ...getRefList(config.prompt),\n ...getRefList(config.promptRef),\n ...getRefList(config.prompt_ref),\n ...getRefList(config.prompts),\n ];\n return dedupeRefs(refs);\n}\n\nfunction getRefList(value: unknown): ContextRepoRef[] {\n if (!value) return [];\n if (typeof value === \"string\") return [value];\n if (Array.isArray(value)) return value.filter(isContextRepoRef);\n if (isContextRepoRef(value)) return [value];\n return [];\n}\n\nfunction isContextRepoRef(value: unknown): value is ContextRepoRef {\n if (typeof value === \"string\") return true;\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n const record = value as Record<string, unknown>;\n return [\"identifier\", \"repoHandle\", \"repo_handle\"].some(\n (key) => typeof record[key] === \"string\",\n );\n}\n\nfunction dedupeRefs(refs: ContextRepoRef[]) {\n const seen = new Set<string>();\n return refs.filter((ref) => {\n const normalized = normalizeRef(ref);\n if (!normalized) return false;\n const key = `${normalized.identifier}:${normalized.version ?? \"\"}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n}\n\nfunction normalizeRef(ref: ContextRepoRef) {\n if (typeof ref === \"string\") {\n const identifier = ref.trim();\n return identifier ? { identifier } : null;\n }\n\n const identifier = (\n ref.identifier ??\n ref.repoHandle ??\n ref.repo_handle ??\n \"\"\n ).trim();\n if (!identifier) return null;\n\n return {\n identifier,\n version: ref.version ?? ref.label,\n writable: ref.writable,\n };\n}\n\nfunction primaryPathForKind(kind: ContextRepoKind, snapshot: ContextSnapshot) {\n const preferred =\n kind === \"agent\"\n ? \"AGENTS.md\"\n : kind === \"prompt\"\n ? \"PROMPT.md\"\n : kind === \"skill\"\n ? \"SKILL.md\"\n : \"MEMORY.md\";\n if (readFile(snapshot, preferred)) return preferred;\n return (\n Object.entries(snapshot.files).find(\n ([path, entry]) => entry.type === \"file\" && path.endsWith(\".md\"),\n )?.[0] ?? null\n );\n}\n\nfunction parseJsonFile(snapshot: ContextSnapshot, path: string) {\n const content = readFile(snapshot, path);\n if (!content) return {};\n try {\n const parsed = JSON.parse(content);\n return parsed && typeof parsed === \"object\" && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : {};\n } catch {\n return {};\n }\n}\n\nfunction readFile(snapshot: ContextSnapshot, path: string) {\n const entry = snapshot.files[path];\n return entry?.type === \"file\" ? entry.content : null;\n}\n\nfunction provenanceFor(\n snapshot: ContextSnapshot,\n label?: string,\n): ContextProvenance {\n return {\n kind: snapshot.repo.kind,\n repoHandle: snapshot.repo.repoHandle,\n commitHash: snapshot.commit.commitHash,\n ...(label ? { label } : {}),\n };\n}\n\nfunction endpointForKind(kind: ContextRepoKind) {\n return kind === \"memory\" ? \"memory\" : `${kind}s`;\n}\n\nfunction runtimeContextPayload(options: ContextRuntimeContext) {\n return {\n ...(options.source ? { source: options.source } : {}),\n ...(options.actorType ? { actorType: options.actorType } : {}),\n ...(options.proposedBy ? { proposedBy: options.proposedBy } : {}),\n ...(options.agentId ? { agentId: options.agentId } : {}),\n ...(options.agentStableId ? { agentStableId: options.agentStableId } : {}),\n ...(options.processId ? { processId: options.processId } : {}),\n ...(options.traceId ? { traceId: options.traceId } : {}),\n ...(options.spanId ? { spanId: options.spanId } : {}),\n ...(options.sessionId ? { sessionId: options.sessionId } : {}),\n ...(options.userId ? { userId: options.userId } : {}),\n ...(options.teamId ? { teamId: options.teamId } : {}),\n ...(options.metadata ? { metadata: options.metadata } : {}),\n };\n}\n\nfunction encodeIdentifier(identifier: string) {\n return identifier\n .split(\"/\")\n .filter(Boolean)\n .map((part) => encodeURIComponent(part))\n .join(\"/\");\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 context = {\n fromEnv: GatewayContext.fromEnv,\n};\n\nexport { renderAgentSystem };\n\nexport type {\n GatewayContextConfig,\n ContextCommit as GatewayContextCommit,\n ContextFileEntry as GatewayContextFileEntry,\n ContextFileInput as GatewayContextFileInput,\n ContextListOptions as GatewayContextListOptions,\n ContextListResponse as GatewayContextListResponse,\n ContextPullOptions as GatewayContextPullOptions,\n ContextPushOptions as GatewayContextPushOptions,\n ContextPushResponse as GatewayContextPushResponse,\n ContextRepo as GatewayContextRepo,\n ContextRepoKind as GatewayContextRepoKind,\n ContextRuntimeContext as GatewayContextRuntimeContext,\n ContextSnapshot as GatewayContextSnapshot,\n ContextWritePolicy as GatewayContextWritePolicy,\n RenderSystemOptions as GatewayRenderSystemOptions,\n ResolvedAgentContext as GatewayResolvedAgentContext,\n ResolvedContextRef as GatewayResolvedContextRef,\n};\n","type MemoryWritePolicy = \"read_only\" | \"propose\" | \"commit\";\n\ntype MemoryFileEntry =\n | {\n type: \"file\";\n content: string;\n mimeType: string;\n mime_type: string;\n }\n | {\n type: \"agent\" | \"skill\";\n repoHandle: string;\n repo_handle: string;\n commitId?: string | null;\n commit_id?: string | null;\n };\n\ntype MemoryRepo = {\n id: string;\n repoHandle: string;\n repo_handle: string;\n ownerHandle: string;\n owner_handle: string;\n kind: \"memory\";\n description: string;\n readme: string;\n tags: string[];\n writePolicy: MemoryWritePolicy;\n write_policy: MemoryWritePolicy;\n isPublic: boolean;\n is_public: boolean;\n isArchived: boolean;\n is_archived: boolean;\n url?: string;\n createdAt: string;\n created_at: string;\n updatedAt: string;\n updated_at: string;\n};\n\ntype MemoryCommit = {\n id: string;\n commitHash: string;\n commit_hash: string;\n parentCommitHash: string | null;\n parent_commit_hash: string | null;\n createdAt: string;\n created_at: string;\n};\n\ntype MemorySnapshot = {\n repo: MemoryRepo;\n commit: MemoryCommit;\n files: Record<string, MemoryFileEntry>;\n};\n\ntype MemoryPushResponse = {\n url: string;\n status: \"committed\" | \"proposed\";\n repoId: string;\n repo_id: string;\n commitId: string | null;\n commit_id: string | null;\n commitHash: string | null;\n commit_hash: string | null;\n proposalId?: string | null;\n proposal_id?: string | null;\n};\n\ntype MemoryRuntimeContext = {\n source?: \"sdk\" | \"agent\" | \"dream\" | \"api\" | \"platform\";\n actorType?: \"api_key\" | \"agent\" | \"process\" | \"user\";\n proposedBy?: string;\n agentId?: string;\n agentStableId?: string;\n processId?: string;\n traceId?: string;\n spanId?: string;\n sessionId?: string;\n userId?: string;\n teamId?: string;\n metadata?: Record<string, unknown>;\n};\n\ntype MemoryPullOptions = {\n version?: string;\n};\n\ntype MemoryWriteOptions = MemoryRuntimeContext & {\n parentCommit?: string;\n message?: string;\n mimeType?: string;\n};\n\ntype MemoryDeleteOptions = MemoryRuntimeContext & {\n parentCommit?: string;\n message?: string;\n};\n\ntype GatewayMemoryConfig = {\n host: string;\n publicKey: string;\n secretKey: string;\n debug?: boolean;\n};\n\ntype GatewayMemoryFromEnvConfig = Partial<GatewayMemoryConfig>;\n\nexport class GatewayMemoryError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message);\n this.name = \"GatewayMemoryError\";\n this.cause = options?.cause;\n }\n}\n\nexport class GatewayMemoryConflictError extends GatewayMemoryError {\n readonly latestCommit: unknown;\n\n constructor(message: string, latestCommit: unknown) {\n super(message);\n this.name = \"GatewayMemoryConflictError\";\n this.latestCommit = latestCommit;\n }\n}\n\nexport class GatewayMemory {\n private readonly host: string;\n private readonly publicKey: string;\n private readonly secretKey: string;\n private readonly debug: boolean;\n\n constructor(config: GatewayMemoryConfig) {\n this.host = config.host.replace(/\\/$/, \"\");\n this.publicKey = config.publicKey;\n this.secretKey = config.secretKey;\n this.debug = config.debug ?? false;\n }\n\n static fromEnv(config: GatewayMemoryFromEnvConfig = {}) {\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 GatewayMemoryError(\n `Missing Gateway memory configuration: ${missing.join(\", \")}`,\n );\n }\n\n return new GatewayMemory({\n ...config,\n host: host!,\n publicKey: publicKey!,\n secretKey: secretKey!,\n });\n }\n\n async pull(\n identifier: string,\n options: MemoryPullOptions = {},\n ): Promise<MemorySnapshot> {\n const query = new URLSearchParams();\n if (options.version) query.set(\"version\", options.version);\n const suffix = query.toString() ? `?${query.toString()}` : \"\";\n return this.requestJson<MemorySnapshot>(\n \"GET\",\n `/api/public/context/memory/${encodeIdentifier(identifier)}${suffix}`,\n );\n }\n\n async read(\n target: string | MemorySnapshot,\n path: string,\n options: MemoryPullOptions = {},\n ): Promise<string | null> {\n const snapshot =\n typeof target === \"string\" ? await this.pull(target, options) : target;\n const file = snapshot.files[path];\n return file?.type === \"file\" ? file.content : null;\n }\n\n async write(\n target: string | MemorySnapshot,\n path: string,\n content: string,\n options: MemoryWriteOptions = {},\n ) {\n const snapshot =\n typeof target === \"string\" ? await this.pull(target) : target;\n return this.push(snapshot.repo.repoHandle, {\n files: {\n [path]: {\n content,\n ...(options.mimeType ? { mimeType: options.mimeType } : {}),\n },\n },\n parentCommit: options.parentCommit ?? snapshot.commit.commitHash,\n message: options.message,\n ...runtimeContextPayload(options),\n });\n }\n\n async delete(\n target: string | MemorySnapshot,\n path: string,\n options: MemoryDeleteOptions = {},\n ) {\n const snapshot =\n typeof target === \"string\" ? await this.pull(target) : target;\n return this.push(snapshot.repo.repoHandle, {\n files: { [path]: null },\n parentCommit: options.parentCommit ?? snapshot.commit.commitHash,\n message: options.message,\n ...runtimeContextPayload(options),\n });\n }\n\n private async push(\n identifier: string,\n payload: Record<string, unknown>,\n ): Promise<MemoryPushResponse> {\n return this.requestJson<MemoryPushResponse>(\n \"POST\",\n `/api/public/context/memory/${encodeIdentifier(identifier)}`,\n payload,\n );\n }\n\n private async requestJson<TResponse>(\n method: \"GET\" | \"POST\",\n path: string,\n payload?: Record<string, unknown>,\n ): Promise<TResponse> {\n const response = await fetch(`${this.host}${path}`, {\n method,\n headers: {\n Authorization: this.authHeader(),\n ...(payload ? { \"Content-Type\": \"application/json\" } : {}),\n },\n ...(payload ? { body: JSON.stringify(payload) } : {}),\n });\n\n const text = await response.text();\n const body = text ? safeJson(text) : {};\n if (!response.ok) {\n const message =\n typeof body.message === \"string\"\n ? body.message\n : `Gateway API ${response.status} on ${path}`;\n if (response.status === 409) {\n throw new GatewayMemoryConflictError(\n message,\n body.latestCommit ?? null,\n );\n }\n throw new GatewayMemoryError(message);\n }\n\n this.log(\"%s %s -> %s\", method, path, response.status);\n return body as TResponse;\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.memory] ${message}`, ...args);\n }\n }\n}\n\nfunction runtimeContextPayload(options: MemoryRuntimeContext) {\n return {\n ...(options.source ? { source: options.source } : {}),\n ...(options.actorType ? { actorType: options.actorType } : {}),\n ...(options.proposedBy ? { proposedBy: options.proposedBy } : {}),\n ...(options.agentId ? { agentId: options.agentId } : {}),\n ...(options.agentStableId ? { agentStableId: options.agentStableId } : {}),\n ...(options.processId ? { processId: options.processId } : {}),\n ...(options.traceId ? { traceId: options.traceId } : {}),\n ...(options.spanId ? { spanId: options.spanId } : {}),\n ...(options.sessionId ? { sessionId: options.sessionId } : {}),\n ...(options.userId ? { userId: options.userId } : {}),\n ...(options.teamId ? { teamId: options.teamId } : {}),\n ...(options.metadata ? { metadata: options.metadata } : {}),\n };\n}\n\nfunction encodeIdentifier(identifier: string) {\n return identifier\n .split(\"/\")\n .filter(Boolean)\n .map((part) => encodeURIComponent(part))\n .join(\"/\");\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 memory = {\n fromEnv: GatewayMemory.fromEnv,\n};\n\nexport type {\n GatewayMemoryConfig,\n MemoryCommit as GatewayMemoryCommit,\n MemoryDeleteOptions as GatewayMemoryDeleteOptions,\n MemoryFileEntry as GatewayMemoryFileEntry,\n MemoryPullOptions as GatewayMemoryPullOptions,\n MemoryPushResponse as GatewayMemoryPushResponse,\n MemoryRepo as GatewayMemoryRepo,\n MemoryRuntimeContext as GatewayMemoryRuntimeContext,\n MemorySnapshot as GatewayMemorySnapshot,\n MemoryWriteOptions as GatewayMemoryWriteOptions,\n MemoryWritePolicy as GatewayMemoryWritePolicy,\n};\n","/**\n * Personas — simulated users served by the Gateway platform.\n *\n * A persona is a crafted user profile (usually derived from real sessions on\n * the platform) that Gateway serves as an endpoint. Use it to drive your agent\n * in tests: the persona plays the user, your agent plays itself.\n *\n * Example:\n * ```ts\n * import { PersonasClient } from \"@withgateway/sdk/personas\";\n *\n * const personas = PersonasClient.fromEnv();\n * const persona = await personas.get(\"persona_id\");\n *\n * const messages: PersonaMessage[] = [];\n * let reply = await persona.respond(messages); // persona opens the conversation\n * while (!reply.done) {\n * messages.push({ role: \"user\", content: reply.content });\n * const agentAnswer = await myAgent(messages); // your agent under test\n * messages.push({ role: \"assistant\", content: agentAnswer });\n * reply = await persona.respond(messages);\n * }\n * ```\n *\n * Message roles are from YOUR agent's perspective: `user` = the simulated\n * user's turns, `assistant` = your agent's turns.\n */\n\ntype PersonaMessage = {\n role: \"user\" | \"assistant\";\n content: string;\n};\n\n/** One simulated-user turn. */\ntype PersonaReply = {\n content: string;\n done: boolean;\n};\n\ntype PersonasClientConfig = {\n host: string;\n publicKey: string;\n secretKey: string;\n timeoutSeconds?: number;\n debug?: boolean;\n};\n\ntype PersonasClientFromEnvConfig = Partial<PersonasClientConfig>;\n\n/** Raised when the Gateway personas API cannot complete a request. */\nexport class PersonaError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message);\n this.name = \"PersonaError\";\n this.cause = options?.cause;\n }\n}\n\n/** A persona definition plus a bound `respond` helper. */\nexport class Persona {\n readonly id: string;\n readonly name: string;\n readonly description: string | null;\n readonly version: number;\n readonly instructions: string;\n readonly examples: string[];\n private readonly client: PersonasClient | null;\n\n constructor(fields: {\n id: string;\n name: string;\n description: string | null;\n version: number;\n instructions: string;\n examples?: string[];\n client?: PersonasClient | null;\n }) {\n this.id = fields.id;\n this.name = fields.name;\n this.description = fields.description;\n this.version = fields.version;\n this.instructions = fields.instructions;\n this.examples = fields.examples ?? [];\n this.client = fields.client ?? null;\n }\n\n /**\n * Get the persona's next user message for a conversation.\n *\n * `messages` use your agent's perspective: role `user` for the simulated\n * user's prior turns, `assistant` for your agent's turns.\n * `done` is true when the persona considers its goal met.\n */\n respond(messages: PersonaMessage[]): Promise<PersonaReply> {\n if (this.client === null) {\n throw new PersonaError(\"Persona is not bound to a client.\");\n }\n return this.client.chat(this.id, messages);\n }\n}\n\n/** Client for Gateway's persona endpoints (HTTP Basic project keys). */\nexport class PersonasClient {\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: PersonasClientConfig) {\n this.host = config.host.replace(/\\/$/, \"\");\n this.publicKey = config.publicKey;\n this.secretKey = config.secretKey;\n this.timeoutSeconds = config.timeoutSeconds ?? 120;\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: PersonasClientFromEnvConfig = {}) {\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 PersonaError(\n `Missing Gateway persona configuration: ${missing.join(\", \")}`,\n );\n }\n\n return new PersonasClient({\n ...config,\n host: host!,\n publicKey: publicKey!,\n secretKey: secretKey!,\n });\n }\n\n /** List the project's personas (without full instructions). */\n async list(): Promise<Persona[]> {\n const payload = await this.requestJson(\"GET\", \"/api/public/personas\");\n const items = Array.isArray(payload.data) ? payload.data : [];\n return items\n .filter(isRecord)\n .map(\n (item) =>\n new Persona({\n id: String(item.id),\n name: String(item.name),\n description: (item.description as string | null | undefined) ?? null,\n version: typeof item.version === \"number\" ? item.version : 1,\n instructions: \"\",\n client: this,\n }),\n );\n }\n\n /** Fetch a persona (full definition) bound to this client. */\n async get(personaId: string): Promise<Persona> {\n const item = await this.requestJson(\n \"GET\",\n `/api/public/personas/${encodeURIComponent(personaId)}/chat`,\n );\n return new Persona({\n id: String(item.id),\n name: String(item.name),\n description: (item.description as string | null | undefined) ?? null,\n version: typeof item.version === \"number\" ? item.version : 1,\n instructions: typeof item.instructions === \"string\" ? item.instructions : \"\",\n examples: Array.isArray(item.examples)\n ? item.examples.map((example) => String(example))\n : [],\n client: this,\n });\n }\n\n /** Play one persona turn. See {@link Persona.respond}. */\n async chat(\n personaId: string,\n messages: PersonaMessage[],\n ): Promise<PersonaReply> {\n const payload = await this.requestJson(\n \"POST\",\n `/api/public/personas/${encodeURIComponent(personaId)}/chat`,\n { messages },\n );\n return {\n content: typeof payload.content === \"string\" ? payload.content : \"\",\n done: Boolean(payload.done),\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 const reason = error instanceof Error ? error.message : String(error);\n throw new PersonaError(`${method} ${path} failed: ${reason}`, {\n cause: error,\n });\n }\n\n const text = await response.text();\n if (!response.ok) {\n const detail = text.slice(0, 500);\n throw new PersonaError(\n `${method} ${path} failed (${response.status}): ${detail}`,\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.personas] ${message}`, ...args);\n }\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction safeJson(value: string): Record<string, unknown> {\n try {\n const parsed = JSON.parse(value);\n return isRecord(parsed) ? parsed : {};\n } catch {\n return {};\n }\n}\n\nexport const personas = {\n fromEnv: PersonasClient.fromEnv,\n};\n\nexport type {\n PersonaMessage,\n PersonaReply,\n PersonasClientConfig,\n PersonasClientFromEnvConfig,\n};\n","/**\n * Load Gateway sessions for replay and test-fixture generation.\n *\n * The premier workflow: pull a real production session from the platform and\n * turn it into a regression test in your repo.\n *\n * ```typescript\n * import { loadSession } from \"@withgateway/sdk/sessions\";\n *\n * const session = await loadSession(\"session-id\"); // env-configured Gateway\n * for (const turn of session.turns()) { // (input, output) per trace\n * const result = await myAgent(turn.input);\n * assert.deepEqual(result, turn.output); // or fuzzier assertions\n * }\n *\n * session.toFixture(\"tests/fixtures/checkout_regression.json\");\n * ```\n *\n * Auth/config mirror the tracing exporter: GATEWAY_HOST, GATEWAY_PUBLIC_KEY,\n * GATEWAY_SECRET_KEY (or pass host/publicKey/secretKey explicitly). Data comes\n * from `GET /api/public/sessions/{id}?includeIO=true` — one call, full\n * untruncated input/output for every trace and observation.\n *\n * Mirrors the Python SDK's `gatewaysdk.sessions` module.\n */\n\nimport { mkdirSync, writeFileSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\n\nexport const ENV_GATEWAY_HOST = \"GATEWAY_HOST\";\nexport const ENV_GATEWAY_PUBLIC_KEY = \"GATEWAY_PUBLIC_KEY\";\nexport const ENV_GATEWAY_SECRET_KEY = \"GATEWAY_SECRET_KEY\";\n\nexport const DEFAULT_TIMEOUT_SECONDS = 30;\n\n/** Raised when a session cannot be loaded from Gateway. */\nexport class SessionLoadError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message);\n this.name = \"SessionLoadError\";\n this.cause = options?.cause;\n }\n}\n\n/** One observation (LLM generation, tool call, span) with full IO. */\nexport type SessionObservation = {\n id: string;\n type: string | null;\n name: string | null;\n level: string | null;\n statusMessage: string | null;\n model: string | null;\n input: unknown;\n output: unknown;\n metadata: unknown;\n parentObservationId: string | null;\n startTime: string | null;\n endTime: string | null;\n};\n\nexport function sessionObservationFromApi(\n raw: Record<string, unknown>,\n): SessionObservation {\n return {\n id: String(raw.id ?? \"\"),\n type: asStringOrNull(raw.type),\n name: asStringOrNull(raw.name),\n level: asStringOrNull(raw.level),\n statusMessage: asStringOrNull(raw.statusMessage),\n model: asStringOrNull(raw.model),\n input: raw.input,\n output: raw.output,\n metadata: raw.metadata ?? null,\n parentObservationId: asStringOrNull(raw.parentObservationId),\n startTime: raw.startTime ? String(raw.startTime) : null,\n endTime: raw.endTime ? String(raw.endTime) : null,\n };\n}\n\ntype SessionTraceFields = {\n id: string;\n name: string | null;\n timestamp: string | null;\n input: unknown;\n output: unknown;\n metadata?: unknown;\n tags?: string[];\n observations?: SessionObservation[];\n};\n\n/** One trace (agent turn) in the session, with full IO + observations. */\nexport class SessionTrace {\n readonly id: string;\n readonly name: string | null;\n readonly timestamp: string | null;\n readonly input: unknown;\n readonly output: unknown;\n readonly metadata: unknown;\n readonly tags: string[];\n readonly observations: SessionObservation[];\n\n constructor(fields: SessionTraceFields) {\n this.id = fields.id;\n this.name = fields.name;\n this.timestamp = fields.timestamp;\n this.input = fields.input;\n this.output = fields.output;\n this.metadata = fields.metadata ?? null;\n this.tags = fields.tags ?? [];\n this.observations = fields.observations ?? [];\n }\n\n get toolCalls(): SessionObservation[] {\n return this.observations.filter(\n (o) => (o.type ?? \"\").toUpperCase() === \"TOOL\",\n );\n }\n\n get generations(): SessionObservation[] {\n return this.observations.filter(\n (o) => (o.type ?? \"\").toUpperCase() === \"GENERATION\",\n );\n }\n\n /**\n * The user message that started this turn.\n *\n * Handles the common recorded shapes: a plain string input, an OpenAI\n * message list (last role=user entry wins — earlier ones are carried\n * history), or an object with a content/input field.\n */\n userMessage(): string | null {\n const value = this.input;\n if (typeof value === \"string\") {\n return value;\n }\n if (Array.isArray(value)) {\n for (let i = value.length - 1; i >= 0; i--) {\n const entry = value[i];\n if (isPlainObject(entry) && entry.role === \"user\") {\n const content = entry.content;\n if (typeof content === \"string\") {\n return content;\n }\n if (Array.isArray(content)) {\n // content-part lists\n const parts = content\n .filter(isPlainObject)\n .map((part) => (typeof part.text === \"string\" ? part.text : \"\"));\n return parts.join(\"\") || null;\n }\n }\n }\n return null;\n }\n if (isPlainObject(value)) {\n for (const key of [\"content\", \"input\", \"text\", \"message\"]) {\n if (typeof value[key] === \"string\") {\n return value[key] as string;\n }\n }\n }\n return null;\n }\n\n static fromApi(raw: Record<string, unknown>): SessionTrace {\n return new SessionTrace({\n id: String(raw.id ?? \"\"),\n name: asStringOrNull(raw.name),\n timestamp: raw.timestamp ? String(raw.timestamp) : null,\n input: raw.input,\n output: raw.output,\n metadata: raw.metadata ?? null,\n tags: Array.isArray(raw.tags) ? raw.tags.map(String) : [],\n observations: (Array.isArray(raw.observations) ? raw.observations : [])\n .filter(isPlainObject)\n .map(sessionObservationFromApi),\n });\n }\n}\n\ntype SessionRecordingFields = {\n sessionId: string;\n projectId: string | null;\n environment: string | null;\n traces?: SessionTrace[];\n};\n\ntype SelectFilter = {\n type?: string;\n name?: string;\n level?: string;\n};\n\n/** A fully-loaded session: every trace, every observation, full IO. */\nexport class SessionRecording {\n readonly sessionId: string;\n readonly projectId: string | null;\n readonly environment: string | null;\n readonly traces: SessionTrace[];\n\n constructor(fields: SessionRecordingFields) {\n this.sessionId = fields.sessionId;\n this.projectId = fields.projectId;\n this.environment = fields.environment;\n this.traces = fields.traces ?? [];\n }\n\n /** Traces in chronological order — one per agent turn. */\n turns(): SessionTrace[] {\n return [...this.traces].sort((a, b) => {\n const left = a.timestamp ?? \"\";\n const right = b.timestamp ?? \"\";\n return left < right ? -1 : left > right ? 1 : 0;\n });\n }\n\n /** The nth chronological turn (negative indices allowed). */\n turn(index: number): SessionTrace {\n const ordered = this.turns();\n const found = ordered.at(index);\n if (!found) {\n throw new RangeError(\n `Turn index ${index} out of range (session has ${ordered.length} turns)`,\n );\n }\n return found;\n }\n\n /**\n * The user message of each turn, in order — feed these back to an agent\n * to re-drive the recorded conversation.\n */\n userMessages(): Array<string | null> {\n return this.turns().map((trace) => trace.userMessage());\n }\n\n /** Output of the last chronological turn (null when empty). */\n finalOutput(): unknown {\n const ordered = this.turns();\n return ordered.length > 0 ? ordered[ordered.length - 1].output : null;\n }\n\n /** Every TOOL observation across the session, chronological. */\n toolCalls(): SessionObservation[] {\n return this.select({ type: \"TOOL\" });\n }\n\n /** Every GENERATION observation across the session, chronological. */\n generations(): SessionObservation[] {\n return this.select({ type: \"GENERATION\" });\n }\n\n /** Filter observations across all turns (chronological order). */\n select(filter: SelectFilter = {}): SessionObservation[] {\n const selected: SessionObservation[] = [];\n for (const trace of this.turns()) {\n for (const observation of trace.observations) {\n if (\n filter.type &&\n (observation.type ?? \"\").toUpperCase() !== filter.type.toUpperCase()\n ) {\n continue;\n }\n if (filter.name && observation.name !== filter.name) {\n continue;\n }\n if (\n filter.level &&\n (observation.level ?? \"\").toUpperCase() !== filter.level.toUpperCase()\n ) {\n continue;\n }\n selected.push(observation);\n }\n }\n return selected;\n }\n\n toJSON(): Record<string, unknown> {\n return {\n sessionId: this.sessionId,\n projectId: this.projectId,\n environment: this.environment,\n traces: this.turns().map((trace) => ({\n id: trace.id,\n name: trace.name,\n timestamp: trace.timestamp,\n input: trace.input,\n output: trace.output,\n metadata: trace.metadata,\n tags: trace.tags,\n observations: trace.observations.map((o) => ({ ...o })),\n })),\n };\n }\n\n /** Dump the full session as a JSON fixture (for regression tests). */\n toFixture(path: string): string {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, JSON.stringify(this.toJSON(), null, 2), \"utf-8\");\n return path;\n }\n\n static fromApi(raw: Record<string, unknown>): SessionRecording {\n return new SessionRecording({\n sessionId: String(raw.id ?? \"\"),\n projectId: asStringOrNull(raw.projectId),\n environment: asStringOrNull(raw.environment),\n traces: (Array.isArray(raw.traces) ? raw.traces : [])\n .filter(isPlainObject)\n .map(SessionTrace.fromApi),\n });\n }\n}\n\nexport type LoadSessionOptions = {\n host?: string;\n publicKey?: string;\n secretKey?: string;\n timeoutSeconds?: number;\n};\n\n/**\n * Load a full session (all traces + observations, untruncated IO).\n *\n * Credentials default to the same environment variables the tracing\n * exporter uses: GATEWAY_HOST, GATEWAY_PUBLIC_KEY, GATEWAY_SECRET_KEY.\n */\nexport async function loadSession(\n sessionId: string,\n options: LoadSessionOptions = {},\n): Promise<SessionRecording> {\n const host = (options.host ?? process.env[ENV_GATEWAY_HOST] ?? \"\").replace(\n /\\/+$/,\n \"\",\n );\n const publicKey =\n options.publicKey ?? process.env[ENV_GATEWAY_PUBLIC_KEY] ?? \"\";\n const secretKey =\n options.secretKey ?? process.env[ENV_GATEWAY_SECRET_KEY] ?? \"\";\n const timeoutSeconds = options.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS;\n if (!host || !publicKey || !secretKey) {\n throw new SessionLoadError(\n \"Gateway is not configured — set GATEWAY_HOST, GATEWAY_PUBLIC_KEY \" +\n \"and GATEWAY_SECRET_KEY (or pass host/publicKey/secretKey).\",\n );\n }\n\n const url = `${host}/api/public/sessions/${encodeURIComponent(sessionId)}?includeIO=true`;\n let response: Response;\n try {\n response = await fetch(url, {\n method: \"GET\",\n headers: { Authorization: basicAuthHeader(publicKey, secretKey) },\n signal: AbortSignal.timeout(timeoutSeconds * 1000),\n });\n } catch (error) {\n throw new SessionLoadError(\n `Failed to load session ${sessionId}: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n if (response.status === 404) {\n throw new SessionLoadError(`Session not found: ${sessionId}`);\n }\n const text = await response.text();\n if (!response.ok) {\n throw new SessionLoadError(\n `Failed to load session ${sessionId}: HTTP ${response.status} — ${text.slice(0, 300)}`,\n );\n }\n let payload: unknown;\n try {\n payload = JSON.parse(text);\n } catch (error) {\n throw new SessionLoadError(\n `Failed to load session ${sessionId}: response is not valid JSON`,\n { cause: error },\n );\n }\n return SessionRecording.fromApi(\n isPlainObject(payload) ? payload : {},\n );\n}\n\nexport function basicAuthHeader(publicKey: string, secretKey: string): string {\n return `Basic ${Buffer.from(`${publicKey}:${secretKey}`).toString(\"base64\")}`;\n}\n\nfunction asStringOrNull(value: unknown): string | null {\n return typeof value === \"string\" ? value : null;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nexport const sessions = {\n load: loadSession,\n};\n","/**\n * Regression suites replayed from platform task sets.\n *\n * A TASK SET on the platform (filed by the dream agent or a human) is a\n * runnable regression suite: each task carries its prompt, expected behavior,\n * and provenance to the RECORDED SESSION that motivated it. This module turns\n * that into tests:\n *\n * ```typescript\n * import { suite } from \"@withgateway/sdk/replay\";\n *\n * const regressions = await suite(\"groceat-regressions\");\n * for (const testCase of regressions) {\n * const stubs = await testCase.stubs(); // the recorded world\n * const out = await myAgent(testCase.prompt, stubs.asRegistry());\n * const result = testCase.check(out, { calledTools: stubs.calledNames() });\n * assert.ok(result.passed, result.explain());\n * }\n * ```\n *\n * Three layers pin three different things:\n * - tool stubs pin THE WORLD (recorded tool outputs → deterministic replay)\n * - invariants pin THE CONTRACT (must/must-not tool calls)\n * - your own assertions / platform judges pin THE SEMANTICS\n *\n * Case triage is three-way: PASS, FAIL (real regression — the world simulated\n * fine and the contract broke), and DRIFT (the recorded world no longer\n * matches the system — stub misses, renamed tools; the TEST is stale, not the\n * agent).\n *\n * Mirrors the Python SDK's `gatewaysdk.replay` package.\n */\n\nimport {\n DEFAULT_TIMEOUT_SECONDS,\n ENV_GATEWAY_HOST,\n ENV_GATEWAY_PUBLIC_KEY,\n ENV_GATEWAY_SECRET_KEY,\n SessionLoadError,\n type SessionObservation,\n SessionRecording,\n basicAuthHeader,\n loadSession,\n} from \"../sessions/index\";\nimport { join } from \"node:path\";\n\n/** Base error for replay loading/config problems. */\nexport class ReplayError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message);\n this.name = \"ReplayError\";\n this.cause = options?.cause;\n }\n}\n\n/** Strict-mode stub lookup failed — the recorded world has no answer. */\nexport class StubMissError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"StubMissError\";\n }\n}\n\n/** The recorded session no longer matches the system (re-baseline the case). */\nexport class DriftError extends ReplayError {\n constructor(message: string) {\n super(message);\n this.name = \"DriftError\";\n }\n}\n\n// ---------------------------------------------------------------------------\n// World simulation: recorded tool stubs\n// ---------------------------------------------------------------------------\n\n// Single-key envelopes that auto-instrumentors wrap tool inputs in (e.g. the\n// OpenInference openai-agents instrumentor records {\"args_json\": \"<json>\"},\n// agent-as-tool records {\"input\": \"...\"}). Recorded inputs must compare equal\n// to the args a live agent passes, so both sides are unwrapped before match.\nconst WRAPPER_KEYS = [\"args_json\", \"arguments\", \"kwargs\", \"args\", \"input\"];\n\nfunction canonicalize(value: unknown): unknown {\n if (typeof value === \"string\") {\n const stripped = value.trim();\n if (stripped.startsWith(\"{\") || stripped.startsWith(\"[\")) {\n try {\n return canonicalize(JSON.parse(stripped));\n } catch {\n return value;\n }\n }\n return value;\n }\n if (Array.isArray(value)) {\n return value.map(canonicalize);\n }\n if (isPlainObject(value)) {\n const entries = Object.entries(value);\n if (entries.length === 1 && WRAPPER_KEYS.includes(entries[0][0])) {\n return canonicalize(entries[0][1]);\n }\n return Object.fromEntries(\n entries.map(([key, inner]) => [key, canonicalize(inner)]),\n );\n }\n return value;\n}\n\nfunction sortKeysDeep(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(sortKeysDeep);\n }\n if (isPlainObject(value)) {\n const sorted: Record<string, unknown> = {};\n for (const key of Object.keys(value).sort()) {\n sorted[key] = sortKeysDeep(value[key]);\n }\n return sorted;\n }\n return value;\n}\n\nfunction normalizeInput(value: unknown): string {\n try {\n return (\n JSON.stringify(sortKeysDeep(canonicalize(value ?? null))) ?? \"null\"\n );\n } catch {\n return String(value);\n }\n}\n\nexport type RecordedToolCall = {\n name: string;\n input: unknown;\n output: unknown;\n observationId: string;\n};\n\nexport type MissPolicy = \"error\" | \"reuse\" | \"passthrough\";\nexport type StubMatch =\n | \"local\"\n | \"exact\"\n | \"exact-repeat\"\n | \"ordinal\"\n | \"reuse\"\n | \"miss\";\nexport type StubCallLogEntry = {\n tool: string;\n match: StubMatch;\n input: unknown;\n};\nexport type StubFallback = (toolName: string, toolInput: unknown) => unknown;\nexport type LocalTool = (toolInput: unknown) => unknown;\nexport type ToolStub = (toolInput?: unknown) => unknown;\n\n/**\n * Tool registry that synthesizes stubs for unknown names (see\n * `ToolStubRegistry.asRegistry`). Indexing an unknown name returns a callable\n * that routes through `lookup()`, so the call is LOGGED and follows the miss\n * policy instead of dying on an undefined-is-not-a-function error.\n */\nexport type StubRegistryMapping = Record<string, ToolStub>;\n\ntype StubRegistryOptions = {\n missPolicy?: MissPolicy;\n fallback?: StubFallback;\n local?: Record<string, LocalTool>;\n};\n\n/**\n * Replays recorded tool outputs from a case's recorded session.\n *\n * Match strategies (tried in order):\n * local — the tool was declared `local`: run its live impl (new\n * or deterministic tools that never need recordings)\n * exact — normalized-JSON equality of the tool input\n * exact-repeat — same (name, input) already replayed: return that output\n * again (idempotent world reads never exhaust)\n * ordinal — nth un-consumed recording for that tool name (robust to\n * arg phrasing drift across models/prompts)\n *\n * Miss policy:\n * \"error\" — throw StubMissError (strict replay; recorded as drift).\n * NOTE: most agent frameworks catch tool errors and feed\n * them to the model as error output, so this does NOT\n * hard-stop such runs — the drift still lands in the\n * report either way.\n * \"reuse\" — exhausted a tool's recordings? replay the LAST recorded\n * output for that name again (drift recorded). Keeps\n * research-heavy agents running when they make more calls\n * than the recording holds. Never-recorded names still\n * throw (or hit `fallback` when provided).\n * \"passthrough\" — call the `fallback` callable (live tool) and record the\n * miss as drift for the report\n */\nexport class ToolStubRegistry {\n readonly callLog: StubCallLogEntry[] = [];\n readonly driftEvents: string[] = [];\n\n private readonly recorded: RecordedToolCall[];\n private readonly consumed = new Set<number>();\n private readonly consumptionOrder: number[] = [];\n private missPolicy: MissPolicy;\n private fallback: StubFallback | null;\n private readonly local: Record<string, LocalTool>;\n\n constructor(calls: RecordedToolCall[], options: StubRegistryOptions = {}) {\n const missPolicy = options.missPolicy ?? \"error\";\n if (![\"error\", \"reuse\", \"passthrough\"].includes(missPolicy)) {\n throw new ReplayError(`Unknown missPolicy: ${missPolicy}`);\n }\n this.recorded = calls;\n this.missPolicy = missPolicy;\n this.fallback = options.fallback ?? null;\n this.local = { ...(options.local ?? {}) };\n }\n\n static fromSession(\n session: SessionRecording,\n options: StubRegistryOptions = {},\n ): ToolStubRegistry {\n const calls = session.toolCalls().map(\n (observation: SessionObservation): RecordedToolCall => ({\n name: observation.name ?? \"\",\n input: observation.input,\n output: observation.output,\n observationId: observation.id,\n }),\n );\n return new ToolStubRegistry(calls, options);\n }\n\n /** Resolve a tool call against the recorded world. */\n lookup(toolName: string, toolInput: unknown = null): unknown {\n // declared-local tool: always run live, logged but never drift\n if (toolName in this.local) {\n this.callLog.push({ tool: toolName, match: \"local\", input: toolInput });\n return this.local[toolName](toolInput);\n }\n const normalized = normalizeInput(toolInput);\n // exact match first\n for (let index = 0; index < this.recorded.length; index++) {\n const record = this.recorded[index];\n if (\n !this.consumed.has(index) &&\n record.name === toolName &&\n normalizeInput(record.input) === normalized\n ) {\n this.consumed.add(index);\n this.consumptionOrder.push(index);\n this.callLog.push({ tool: toolName, match: \"exact\", input: toolInput });\n return record.output;\n }\n }\n // exact-repeat: the same (name, input) was already replayed — treat the\n // recorded pair as a stable world fact and serve it again rather than\n // exhausting into ordinal/miss on idempotent re-reads\n for (let index = this.recorded.length - 1; index >= 0; index--) {\n const record = this.recorded[index];\n if (record.name === toolName && normalizeInput(record.input) === normalized) {\n this.callLog.push({\n tool: toolName,\n match: \"exact-repeat\",\n input: toolInput,\n });\n return record.output;\n }\n }\n // ordinal fallback: next un-consumed recording for this tool name\n for (let index = 0; index < this.recorded.length; index++) {\n const record = this.recorded[index];\n if (!this.consumed.has(index) && record.name === toolName) {\n this.consumed.add(index);\n this.consumptionOrder.push(index);\n this.callLog.push({\n tool: toolName,\n match: \"ordinal\",\n input: toolInput,\n });\n return record.output;\n }\n }\n // reuse: recordings for this name exist but are exhausted — replay the\n // last one again so over-calling agents (extra searches, retries) finish\n // the run; the drift below still tells the truth in triage\n if (this.missPolicy === \"reuse\") {\n for (let index = this.recorded.length - 1; index >= 0; index--) {\n const record = this.recorded[index];\n if (record.name === toolName) {\n this.driftEvents.push(\n `recordings for tool '${toolName}' exhausted — ` +\n \"replayed the last one again (reuse policy)\",\n );\n this.callLog.push({\n tool: toolName,\n match: \"reuse\",\n input: toolInput,\n });\n return record.output;\n }\n }\n }\n // miss\n const recordedNames = [...new Set(this.recorded.map((r) => r.name))].sort();\n const drift = `no recording for tool '${toolName}' (recorded tools: ${JSON.stringify(recordedNames)})`;\n this.driftEvents.push(drift);\n this.callLog.push({ tool: toolName, match: \"miss\", input: toolInput });\n if (\n this.fallback !== null &&\n (this.missPolicy === \"passthrough\" || this.missPolicy === \"reuse\")\n ) {\n return this.fallback(toolName, toolInput);\n }\n throw new StubMissError(drift);\n }\n\n /**\n * Mapping of toolName → callable, drop-in for most agent tool layers.\n *\n * `local` merges in tools that should ALWAYS run live (new tools the\n * recording predates, or deterministic/pure helpers) — they're logged for\n * the contract check but never count as drift.\n *\n * UNKNOWN tool names also resolve (to a stub that routes through\n * `lookup()`), so a call to an un-recorded tool is LOGGED and follows the\n * miss policy instead of dying on an undefined lookup — that log is what\n * lets `check()` classify a forbidden-but-unrecorded call as FAIL.\n */\n asRegistry(\n options: {\n fallback?: StubFallback;\n local?: Record<string, LocalTool>;\n } = {},\n ): StubRegistryMapping {\n if (options.fallback) {\n this.fallback = options.fallback;\n this.missPolicy = \"passthrough\";\n }\n if (options.local) {\n Object.assign(this.local, options.local);\n }\n\n const make =\n (name: string): ToolStub =>\n (toolInput?: unknown) =>\n this.lookup(name, toolInput === undefined ? {} : toolInput);\n\n const target: Record<string, ToolStub> = {};\n const names = new Set([\n ...this.recorded.map((record) => record.name),\n ...Object.keys(this.local),\n ]);\n for (const name of names) {\n if (name) {\n target[name] = make(name);\n }\n }\n return new Proxy(target, {\n get(current, prop, receiver) {\n if (typeof prop !== \"string\" || prop in current) {\n return Reflect.get(current, prop, receiver);\n }\n return make(prop);\n },\n });\n }\n\n calledNames(): string[] {\n return this.callLog.map((entry) => entry.tool);\n }\n\n /**\n * 1:1 comparison of this replay against the recorded trace.\n *\n * The recording is the expectation: every recorded tool call should be\n * replayed exactly once, in order, with nothing extra. Use for strict\n * did-it-do-everything-the-original-did checks (`mode: \"exact\"`).\n *\n * `includeLocal`: count local-tool calls as extras (default false — local\n * tools are declared live on purpose; their recorded calls are likewise\n * excluded from \"missing\", since local bypasses recordings).\n */\n compare(options: { includeLocal?: boolean } = {}): TraceDiff {\n const includeLocal = options.includeLocal ?? false;\n const missing = this.recorded\n .map((record, index) => ({ record, index }))\n .filter(\n ({ record, index }) =>\n !this.consumed.has(index) &&\n (includeLocal || !(record.name in this.local)),\n )\n .map(({ record }) => `${record.name}(${normalizeInput(record.input)})`);\n const extra: string[] = [];\n for (const entry of this.callLog) {\n if (\n [\"miss\", \"reuse\", \"exact-repeat\"].includes(entry.match) ||\n (includeLocal && entry.match === \"local\")\n ) {\n extra.push(\n `${entry.tool}(${normalizeInput(entry.input)}) [${entry.match}]`,\n );\n }\n }\n const outOfOrder: string[] = [];\n let last = -1;\n for (const index of this.consumptionOrder) {\n if (index < last) {\n const record = this.recorded[index];\n outOfOrder.push(`${record.name}(${normalizeInput(record.input)})`);\n } else {\n last = index;\n }\n }\n const matched = this.consumptionOrder.map(\n (index) => this.recorded[index].name,\n );\n return new TraceDiff({ matched, missing, extra, outOfOrder });\n }\n\n get drifted(): boolean {\n return this.driftEvents.length > 0;\n }\n}\n\n/** Replayed-vs-recorded trace comparison (see `ToolStubRegistry.compare`). */\nexport class TraceDiff {\n readonly matched: string[];\n readonly missing: string[];\n readonly extra: string[];\n readonly outOfOrder: string[];\n\n constructor(\n fields: {\n matched?: string[];\n missing?: string[];\n extra?: string[];\n outOfOrder?: string[];\n } = {},\n ) {\n this.matched = fields.matched ?? [];\n this.missing = fields.missing ?? [];\n this.extra = fields.extra ?? [];\n this.outOfOrder = fields.outOfOrder ?? [];\n }\n\n get identical(): boolean {\n return (\n this.missing.length === 0 &&\n this.extra.length === 0 &&\n this.outOfOrder.length === 0\n );\n }\n\n explain(): string {\n if (this.identical) {\n return `1:1 replay — all ${this.matched.length} recorded tool calls reproduced in order`;\n }\n const lines = [\n `trace diverges from recording (${this.matched.length} matched):`,\n ];\n lines.push(...this.missing.map((item) => ` not reproduced: ${item}`));\n lines.push(...this.extra.map((item) => ` extra call: ${item}`));\n lines.push(...this.outOfOrder.map((item) => ` out of order: ${item}`));\n return lines.join(\"\\n\");\n }\n}\n\n// ---------------------------------------------------------------------------\n// Tasks, cases, checks\n// ---------------------------------------------------------------------------\n\ntype ReplayTaskFields = {\n id: string;\n name?: string | null;\n prompt?: unknown;\n expectedOutput?: unknown;\n metadata?: Record<string, unknown>;\n};\n\n/** One task-set item as served by GET /task-sets/{id}/tasks. */\nexport class ReplayTask {\n readonly id: string;\n readonly name: string | null;\n readonly prompt: unknown;\n readonly expectedOutput: unknown;\n readonly metadata: Record<string, unknown>;\n\n constructor(fields: ReplayTaskFields) {\n this.id = fields.id;\n this.name = fields.name ?? null;\n this.prompt = fields.prompt;\n this.expectedOutput = fields.expectedOutput;\n this.metadata = fields.metadata ?? {};\n }\n\n get sourceSessionId(): string | null {\n const value = this.metadata.sourceSessionId;\n return value ? String(value) : null;\n }\n\n get sourceTraceId(): string | null {\n const value = this.metadata.sourceTraceId;\n return value ? String(value) : null;\n }\n\n static fromApi(raw: Record<string, unknown>): ReplayTask {\n const metadata = raw.metadata;\n return new ReplayTask({\n id: String(raw.id ?? \"\"),\n name: typeof raw.name === \"string\" ? raw.name : null,\n prompt: raw.prompt,\n expectedOutput: raw.expectedOutput,\n metadata: isPlainObject(metadata) ? { ...metadata } : {},\n });\n }\n}\n\nexport type ReplayStatus = \"PASS\" | \"FAIL\" | \"DRIFT\";\n\n/** Triage result: PASS | FAIL | DRIFT (+ human-readable reasons). */\nexport class ReplayCheck {\n readonly status: ReplayStatus;\n readonly failures: string[];\n readonly drift: string[];\n readonly traceDiff: TraceDiff | null;\n\n constructor(\n status: ReplayStatus,\n fields: {\n failures?: string[];\n drift?: string[];\n traceDiff?: TraceDiff | null;\n } = {},\n ) {\n this.status = status;\n this.failures = fields.failures ?? [];\n this.drift = fields.drift ?? [];\n this.traceDiff = fields.traceDiff ?? null;\n }\n\n get passed(): boolean {\n return this.status === \"PASS\";\n }\n\n get drifted(): boolean {\n return this.status === \"DRIFT\";\n }\n\n explain(): string {\n if (this.status === \"PASS\") {\n return \"PASS\";\n }\n const lines: string[] = [this.status];\n lines.push(...this.failures.map((failure) => ` FAIL: ${failure}`));\n for (const event of this.drift) {\n if (event.includes(\"reuse policy\")) {\n // exhausted-then-reused recordings = the agent explored more than\n // the recording holds, not necessarily a stale test\n lines.push(\n ` DRIFT: ${event} — recording under-covers this run; ` +\n \"re-record for exact coverage or keep the reuse policy.\",\n );\n } else {\n lines.push(\n ` DRIFT: ${event} — the test is stale, not the agent; ` +\n \"re-record the session (or declare the tool local).\",\n );\n }\n }\n return lines.join(\"\\n\");\n }\n}\n\nexport type SessionLoader = (\n sessionId: string,\n) => SessionRecording | Promise<SessionRecording>;\n\nexport type ReplayMode = \"contract\" | \"exact\";\n\ntype CheckOptions = {\n calledTools?: string[];\n stubs?: ToolStubRegistry;\n mode?: ReplayMode;\n};\n\n/** One regression case: a task bound to the session it was filed from. */\nexport class ReplayCase {\n readonly task: ReplayTask;\n private readonly loader: SessionLoader;\n private _recording: SessionRecording | null = null;\n private _stubs: ToolStubRegistry | null = null;\n\n constructor(task: ReplayTask, options: { loader: SessionLoader }) {\n this.task = task;\n this.loader = options.loader;\n }\n\n // -- identity ------------------------------------------------------------\n get id(): string {\n return this.task.id;\n }\n\n get name(): string {\n return this.task.name ?? this.task.id;\n }\n\n get prompt(): unknown {\n return this.task.prompt;\n }\n\n get expected(): unknown {\n return this.task.expectedOutput;\n }\n\n // -- recorded source session ----------------------------------------------\n /** The full recorded session this case was filed from. */\n async recording(): Promise<SessionRecording> {\n if (this._recording === null) {\n const source = this.task.sourceSessionId;\n if (!source) {\n throw new DriftError(\n `Task ${this.name} has no sourceSessionId provenance — ` +\n \"file it from a session (add_session_to_task_set) or set \" +\n \"metadata.sourceSessionId.\",\n );\n }\n this._recording = await this.loader(source);\n }\n return this._recording;\n }\n\n async stubs(options: StubRegistryOptions = {}): Promise<ToolStubRegistry> {\n this._stubs = ToolStubRegistry.fromSession(await this.recording(), options);\n return this._stubs;\n }\n\n /**\n * The recorded conversation's user messages, one per turn — feed them to\n * your agent in order to re-drive the full session (each turn was one\n * trace in the recording).\n */\n async conversation(): Promise<string[]> {\n const messages = (await this.recording()).userMessages();\n const found = messages.filter(\n (message): message is string => Boolean(message),\n );\n return found.length > 0 ? found : [String(this.prompt)];\n }\n\n // -- grading ---------------------------------------------------------------\n /**\n * Contract invariants + drift triage.\n *\n * Invariants come from task metadata (the workbench-style contract):\n * metadata.expectTools — every listed tool MUST have been called\n * metadata.mustNotCall — none of these may have been called\n * Semantic grading stays with the caller (assert on `output` /\n * `case.expected`, or run a platform judge on the replay trace).\n *\n * `mode` (or task `metadata.replayMode`):\n * \"contract\" (default) — grade only the invariants above\n * \"exact\" — true 1:1 replay: the agent must reproduce EVERY\n * recorded tool call, in order, with nothing extra\n * (see TraceDiff); any divergence is a FAIL. The\n * full diff lands in the failure reasons and\n * `traceDiff`.\n */\n check(output: unknown = undefined, options: CheckOptions = {}): ReplayCheck {\n const registry = options.stubs ?? this._stubs;\n const drift = registry ? [...registry.driftEvents] : [];\n const called =\n options.calledTools ?? (registry ? registry.calledNames() : []);\n\n // VIOLATIONS are positive evidence the contract broke (a forbidden call\n // happened, produced output contradicts an exact expectation) — they\n // FAIL even on a drifted world. OMISSIONS (an expected tool never\n // called) only FAIL on a CLEAN world: when the run drifted (stub miss\n // aborted it, tools were renamed), the drift explains the omission and\n // the right verdict is DRIFT → re-record, not \"agent regressed\".\n const violations: string[] = [];\n const omissions: string[] = [];\n const expectTools = this.task.metadata.expectTools;\n if (Array.isArray(expectTools)) {\n for (const toolName of expectTools) {\n if (!called.includes(toolName)) {\n omissions.push(`expected tool not called: ${toolName}`);\n }\n }\n }\n const mustNot = this.task.metadata.mustNotCall;\n if (Array.isArray(mustNot)) {\n for (const toolName of mustNot) {\n if (called.includes(toolName)) {\n violations.push(`must_not_call violated: ${toolName}`);\n }\n }\n }\n if (\n typeof this.expected === \"string\" &&\n this.expected.trim() &&\n typeof output === \"string\" &&\n this.task.metadata.outputExact === true &&\n output.trim() !== this.expected.trim()\n ) {\n violations.push(\"output does not exactly match expectedOutput\");\n }\n\n const replayMode = (options.mode ??\n this.task.metadata.replayMode ??\n \"contract\") as ReplayMode;\n let traceDiff: TraceDiff | null = null;\n if (registry) {\n traceDiff = registry.compare();\n }\n if (replayMode === \"exact\" && traceDiff && !traceDiff.identical) {\n violations.push(\n ...[\n ...traceDiff.missing.map((item) => `not reproduced: ${item}`),\n ...traceDiff.extra.map((item) => `extra call: ${item}`),\n ...traceDiff.outOfOrder.map((item) => `out of order: ${item}`),\n ].map((line) => `1:1 replay diverged — ${line}`),\n );\n }\n\n if (violations.length > 0) {\n return new ReplayCheck(\"FAIL\", {\n failures: [...violations, ...(drift.length > 0 ? [] : omissions)],\n drift,\n traceDiff,\n });\n }\n if (drift.length > 0) {\n return new ReplayCheck(\"DRIFT\", { drift, traceDiff });\n }\n if (omissions.length > 0) {\n return new ReplayCheck(\"FAIL\", { failures: omissions, traceDiff });\n }\n return new ReplayCheck(\"PASS\", { traceDiff });\n }\n}\n\n// ---------------------------------------------------------------------------\n// Suite loading (platform task sets)\n// ---------------------------------------------------------------------------\n\nexport type ReplayCredentials = {\n host: string;\n publicKey: string;\n secretKey: string;\n timeoutSeconds?: number;\n};\n\nexport type ReplaySuiteLoadOptions = {\n host?: string;\n publicKey?: string;\n secretKey?: string;\n timeoutSeconds?: number;\n};\n\ntype ReplaySuiteFields = {\n taskSetId: string;\n taskSetName: string;\n cases: ReplayCase[];\n /** Platform credentials for recording replay runs back to the task set. */\n credentials?: ReplayCredentials | null;\n};\n\n/** All cases of one task set, iterable and indexable by name or id. */\nexport class ReplaySuite implements Iterable<ReplayCase> {\n readonly taskSetId: string;\n readonly taskSetName: string;\n readonly cases: ReplayCase[];\n /** Credentials for recording replay runs back to the platform. */\n readonly credentials: ReplayCredentials | null;\n\n constructor(fields: ReplaySuiteFields) {\n this.taskSetId = fields.taskSetId;\n this.taskSetName = fields.taskSetName;\n this.cases = fields.cases;\n this.credentials = fields.credentials ?? null;\n }\n\n [Symbol.iterator](): Iterator<ReplayCase> {\n return this.cases[Symbol.iterator]();\n }\n\n get length(): number {\n return this.cases.length;\n }\n\n /** Look up a case by id or name (throws when absent). */\n get(key: string): ReplayCase {\n for (const testCase of this.cases) {\n if (testCase.id === key || testCase.name === key) {\n return testCase;\n }\n }\n throw new ReplayError(\n `No case '${key}' in task set ${this.taskSetName} ` +\n `(cases: ${JSON.stringify(this.cases.map((c) => c.name))})`,\n );\n }\n\n static async fromTaskSet(\n nameOrId: string,\n options: ReplaySuiteLoadOptions = {},\n ): Promise<ReplaySuite> {\n const host = (options.host ?? process.env[ENV_GATEWAY_HOST] ?? \"\").replace(\n /\\/+$/,\n \"\",\n );\n const publicKey =\n options.publicKey ?? process.env[ENV_GATEWAY_PUBLIC_KEY] ?? \"\";\n const secretKey =\n options.secretKey ?? process.env[ENV_GATEWAY_SECRET_KEY] ?? \"\";\n const timeoutSeconds = options.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS;\n if (!host || !publicKey || !secretKey) {\n throw new SessionLoadError(\n \"Gateway is not configured — set GATEWAY_HOST, \" +\n \"GATEWAY_PUBLIC_KEY and GATEWAY_SECRET_KEY.\",\n );\n }\n const headers = { Authorization: basicAuthHeader(publicKey, secretKey) };\n\n const fetchTasks = async (\n datasetId: string,\n ): Promise<Array<Record<string, unknown>> | null> => {\n const tasks: Array<Record<string, unknown>> = [];\n let page = 0;\n for (;;) {\n const response = await fetch(\n `${host}/api/public/task-sets/${encodeURIComponent(datasetId)}/tasks?page=${page}&limit=200`,\n { headers, signal: AbortSignal.timeout(timeoutSeconds * 1000) },\n );\n if (response.status === 404) {\n return null;\n }\n const text = await response.text();\n if (!response.ok) {\n throw new ReplayError(\n `Failed to list tasks for ${datasetId}: ` +\n `HTTP ${response.status} — ${text.slice(0, 300)}`,\n );\n }\n const payload = parseJsonObject(text);\n const pageTasks = Array.isArray(payload.tasks) ? payload.tasks : [];\n tasks.push(...pageTasks.filter(isPlainObject));\n if (tasks.length >= Number(payload.totalTasks ?? 0)) {\n return tasks;\n }\n page += 1;\n }\n };\n\n // Try as an id first, then resolve as a name.\n let taskSetId = nameOrId;\n let taskSetName = nameOrId;\n let rawTasks = await fetchTasks(nameOrId);\n if (rawTasks === null) {\n const response = await fetch(\n `${host}/api/public/task-sets?name=${encodeURIComponent(nameOrId)}`,\n { headers, signal: AbortSignal.timeout(timeoutSeconds * 1000) },\n );\n const text = await response.text();\n if (!response.ok) {\n throw new ReplayError(\n `Failed to resolve task set '${nameOrId}': ` +\n `HTTP ${response.status} — ${text.slice(0, 300)}`,\n );\n }\n const payload = parseJsonObject(text);\n const matches = Array.isArray(payload.taskSets)\n ? payload.taskSets.filter(isPlainObject)\n : [];\n if (matches.length === 0) {\n throw new ReplayError(`Task set not found: ${nameOrId}`);\n }\n taskSetId = String(matches[0].datasetId);\n taskSetName = String(matches[0].name);\n rawTasks = (await fetchTasks(taskSetId)) ?? [];\n }\n\n const loader: SessionLoader = (sessionId) =>\n loadSession(sessionId, { host, publicKey, secretKey, timeoutSeconds });\n const cases = rawTasks.map(\n (raw) => new ReplayCase(ReplayTask.fromApi(raw), { loader }),\n );\n return new ReplaySuite({\n taskSetId,\n taskSetName,\n cases,\n credentials: { host, publicKey, secretKey, timeoutSeconds },\n });\n }\n\n /** Run the whole suite against `agent` — see `runSuite()`. */\n run(agent: ReplayAgent, options: RunSuiteOptions = {}): Promise<ReplayReport> {\n return runSuite(this, agent, options);\n }\n\n /** Pin every case's recorded session into the repo as JSON fixtures. */\n async snapshot(directory: string): Promise<string[]> {\n const written: string[] = [];\n for (const testCase of this.cases) {\n if (!testCase.task.sourceSessionId) {\n continue;\n }\n const recording = await testCase.recording();\n written.push(\n recording.toFixture(join(directory, `${testCase.name}.recording.json`)),\n );\n }\n return written;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Runner\n// ---------------------------------------------------------------------------\n\n/**\n * The agent under test. Always invoked as `agent(prompt, tools, replayCase)`\n * — declare only the parameters you need (this replaces the Python SDK's\n * signature sniffing with idiomatic JavaScript):\n *\n * `(prompt) => ...` — prompt-only agents\n * `(prompt, tools) => ...` — the common shape\n * `(prompt, tools, replayCase) => ...` — full case access\n * (rebuild stubs via `replayCase.stubs()`)\n */\nexport type ReplayAgent = (\n prompt: unknown,\n tools: StubRegistryMapping,\n replayCase: ReplayCase,\n) => unknown | Promise<unknown>;\n\nexport class ReplayReport {\n readonly results: Record<string, ReplayCheck>;\n readonly runName: string | null;\n readonly recordingErrors: string[];\n\n constructor(\n results: Record<string, ReplayCheck>,\n fields: { runName?: string | null; recordingErrors?: string[] } = {},\n ) {\n this.results = results;\n this.runName = fields.runName ?? null;\n this.recordingErrors = fields.recordingErrors ?? [];\n }\n\n get passed(): number {\n return this.count(\"PASS\");\n }\n\n get failed(): number {\n return this.count(\"FAIL\");\n }\n\n get drifted(): number {\n return this.count(\"DRIFT\");\n }\n\n /** True when nothing FAILED (drift is stale-test signal, not failure). */\n get ok(): boolean {\n return this.failed === 0;\n }\n\n explain(): string {\n const lines = [\n `${this.passed} PASS · ${this.failed} FAIL · ${this.drifted} DRIFT` +\n (this.runName ? ` · run '${this.runName}'` : \"\"),\n ];\n for (const [name, check] of Object.entries(this.results)) {\n if (check.status !== \"PASS\") {\n lines.push(`${name}: ${check.explain()}`);\n }\n }\n for (const error of this.recordingErrors) {\n lines.push(`recording: ${error}`);\n }\n return lines.join(\"\\n\");\n }\n\n private count(status: ReplayStatus): number {\n return Object.values(this.results).filter(\n (check) => check.status === status,\n ).length;\n }\n}\n\n/**\n * Replay traffic records under this environment — the platform hides it from\n * the sessions/traces tables by default (users opt back in via the\n * environment filter), so regression runs never pollute real usage views.\n */\nexport const REPLAY_ENVIRONMENT = \"gateway-replay\";\n\n/**\n * File one dataset-run item so the replay run shows on the task set.\n *\n * Retries on 404: a replay trace reaches ClickHouse asynchronously after\n * flush, and the endpoint rejects items whose trace does not exist yet.\n * Returns an error string on final failure (recording never throws).\n */\nasync function recordRunItem(\n suiteToRecord: ReplaySuite,\n testCase: ReplayCase,\n runName: string,\n traceId: string | null,\n triage: ReplayCheck,\n options: { retries?: number; retryDelaySeconds?: number } = {},\n): Promise<string | null> {\n const retries = options.retries ?? 10;\n const retryDelaySeconds = options.retryDelaySeconds ?? 3;\n const credentials = suiteToRecord.credentials;\n if (!credentials) {\n return \"suite has no platform credentials\";\n }\n const payload = {\n runName,\n runDescription: `gatewaysdk.replay run over '${suiteToRecord.taskSetName}'`,\n datasetItemId: testCase.id,\n traceId: traceId ?? randomHex(),\n metadata: {\n replay: true,\n status: triage.status,\n failures: triage.failures,\n drift: triage.drift,\n sourceSessionId: testCase.task.sourceSessionId,\n },\n };\n let lastError = \"unknown\";\n for (let attempt = 0; attempt < retries; attempt++) {\n try {\n const response = await fetch(\n `${credentials.host}/api/public/dataset-run-items`,\n {\n method: \"POST\",\n headers: {\n Authorization: basicAuthHeader(\n credentials.publicKey,\n credentials.secretKey,\n ),\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(payload),\n signal: AbortSignal.timeout(DEFAULT_TIMEOUT_SECONDS * 1000),\n },\n );\n if (response.status === 200) {\n return null;\n }\n const text = await response.text();\n lastError = `HTTP ${response.status}: ${text.slice(0, 200)}`;\n // 404 = trace not ingested yet — wait and retry; anything else is final.\n if (response.status !== 404) {\n return lastError;\n }\n } catch (error) {\n lastError = error instanceof Error ? error.message : String(error);\n }\n if (attempt < retries - 1) {\n await sleep(retryDelaySeconds * 1000);\n }\n }\n return lastError;\n}\n\nexport type RunSuiteOptions = {\n missPolicy?: MissPolicy;\n record?: boolean;\n runName?: string;\n};\n\n/**\n * Run every case and triage. The agent is invoked as\n * `agent(prompt, tools, replayCase)` — declare only what you need.\n *\n * Recording (`record` undefined → auto when the suite was loaded from the\n * platform): each case is filed as a dataset-run item on the task set, so\n * the replay run shows up in the task set's runs with per-case status.\n *\n * NOTE: unlike the Python SDK, cases are not auto-wrapped in a traced span —\n * the TypeScript tracing module has no per-trace context primitive yet. Run\n * items are filed with a synthetic trace id, exactly like a Python run\n * without tracing configured.\n */\nexport async function runSuite(\n suiteToRun: ReplaySuite,\n agent: ReplayAgent,\n options: RunSuiteOptions = {},\n): Promise<ReplayReport> {\n const missPolicy = options.missPolicy ?? \"error\";\n const record = options.record ?? Boolean(suiteToRun.credentials);\n const runName = options.runName ?? `replay-${randomHex().slice(0, 8)}`;\n\n const results: Record<string, ReplayCheck> = {};\n const pendingRecords: Array<[ReplayCase, string | null, ReplayCheck]> = [];\n for (const testCase of suiteToRun) {\n try {\n const stubs = await testCase.stubs({ missPolicy });\n const output = await agent(\n testCase.prompt,\n stubs.asRegistry(),\n testCase,\n );\n // Triage with the case's LATEST registry — a case-driven agent may\n // have rebuilt stubs via replayCase.stubs() inside its own body.\n results[testCase.name] = testCase.check(output);\n } catch (error) {\n if (error instanceof StubMissError) {\n // The world was missing an answer — but the CONTRACT may also have\n // been violated by that very call (e.g. a forbidden tool that was\n // never recorded because the original agent never called it). Run\n // the check: FAIL dominates drift.\n let triage = testCase.check();\n if (triage.status !== \"FAIL\") {\n triage = new ReplayCheck(\"DRIFT\", {\n drift: triage.drift.length > 0 ? triage.drift : [error.message],\n });\n }\n results[testCase.name] = triage;\n } else if (error instanceof DriftError) {\n results[testCase.name] = new ReplayCheck(\"DRIFT\", {\n drift: [error.message],\n });\n } else {\n throw error;\n }\n }\n\n if (record) {\n pendingRecords.push([testCase, null, results[testCase.name]]);\n }\n }\n\n const recordingErrors: string[] = [];\n for (const [testCase, traceId, triage] of pendingRecords) {\n const error = await recordRunItem(\n suiteToRun,\n testCase,\n runName,\n traceId,\n triage,\n );\n if (error) {\n recordingErrors.push(`${testCase.name}: ${error}`);\n }\n }\n\n return new ReplayReport(results, {\n runName: record ? runName : null,\n recordingErrors,\n });\n}\n\n/**\n * Shorthand for `ReplaySuite.fromTaskSet` — the intuitive entrypoint:\n *\n * ```typescript\n * import * as replay from \"@withgateway/sdk/replay\";\n * const report = await (await replay.suite(\"checkout-regressions\")).run(myAgent);\n * ```\n */\nexport function suite(\n nameOrId: string,\n options: ReplaySuiteLoadOptions = {},\n): Promise<ReplaySuite> {\n return ReplaySuite.fromTaskSet(nameOrId, options);\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction parseJsonObject(text: string): Record<string, unknown> {\n try {\n const parsed = JSON.parse(text);\n return isPlainObject(parsed) ? parsed : {};\n } catch {\n return {};\n }\n}\n\nfunction randomHex(): string {\n return crypto.randomUUID().replace(/-/g, \"\");\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport const replay = {\n suite,\n run: runSuite,\n};\n","type AgentDescriptor = {\n id?: string;\n name?: string;\n version?: string;\n};\n\ntype SecurityContext = {\n executionId?: string;\n userId?: string;\n teamId?: string;\n environment?: string;\n contextLabel?: string;\n contextBundleHash?: string;\n traceId?: string;\n sessionId?: string;\n spanId?: string;\n metadata?: Record<string, unknown>;\n};\n\ntype ToolDescriptor = {\n id: string;\n name?: string;\n description?: string;\n metadata?: Record<string, unknown>;\n};\n\ntype ToolsetResolveResponse = {\n toolsetId: string;\n mode: \"observe\" | \"filter\" | \"enforce\";\n policyVersion: number;\n ttlSeconds: number;\n allowedToolIds: string[];\n blockedToolIds: string[];\n approvalToolIds: string[];\n secretBindings: Record<string, string[]>;\n failMode: \"open\" | \"closed\";\n};\n\ntype ToolCallAuthorizeResponse = {\n decisionId: string;\n outcome: \"allow\" | \"flag\" | \"block\" | \"approval_required\";\n reasonCode: string;\n message: string;\n policyVersion: number;\n};\n\ntype ToolObject = {\n description?: string;\n execute?: (...args: unknown[]) => unknown;\n [key: string]: unknown;\n};\n\ntype ToolCollection = Record<\n string,\n ToolObject | ((...args: unknown[]) => unknown)\n>;\n\ntype SecureToolsOptions<TTools extends ToolCollection> = {\n toolsetId: string;\n toolsetName?: string;\n provider?: string;\n tools: TTools;\n context?: SecurityContext;\n toolIds?: Partial<Record<keyof TTools & string, string>>;\n toolMetadata?: Partial<\n Record<keyof TTools & string, Record<string, unknown>>\n >;\n};\n\ntype GatewaySecurityConfig = {\n host: string;\n publicKey: string;\n secretKey: string;\n agent?: AgentDescriptor;\n debug?: boolean;\n failOpen?: boolean;\n};\n\ntype GatewaySecurityFromEnvConfig = Partial<\n Pick<GatewaySecurityConfig, \"host\" | \"publicKey\" | \"secretKey\">\n> &\n Pick<GatewaySecurityConfig, \"agent\" | \"debug\" | \"failOpen\">;\n\nconst SECURITY_ATTRIBUTES = {\n AGENT_ID: \"gateway.agent.id\",\n AGENT_NAME: \"gateway.agent.name\",\n AGENT_VERSION: \"gateway.agent.version\",\n TOOLSET_ID: \"gateway.toolset.id\",\n TOOL_ID: \"gateway.tool.id\",\n SECURITY_MODE: \"gateway.security.mode\",\n POLICY_VERSION: \"gateway.security.policy_version\",\n DECISION_OUTCOME: \"gateway.decision.outcome\",\n DECISION_REASON_CODE: \"gateway.decision.reason_code\",\n} as const;\n\nexport class GatewaySecurityError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message);\n this.name = \"GatewaySecurityError\";\n this.cause = options?.cause;\n }\n}\n\nexport class GatewayToolBlockedError extends GatewaySecurityError {\n readonly decision: ToolCallAuthorizeResponse;\n readonly toolId: string;\n\n constructor(toolId: string, decision: ToolCallAuthorizeResponse) {\n super(decision.message || `Gateway blocked tool ${toolId}`);\n this.name = \"GatewayToolBlockedError\";\n this.toolId = toolId;\n this.decision = decision;\n }\n}\n\n/**\n * Thrown when Gateway's policy returns `approval_required` for a tool call.\n * The SDK does NOT execute the tool — a human/system approval is needed first\n * (the server engine and the runtime MCP PEP both honor this; this closes the\n * SDK leg of the step-up gate so an approval decision can't be silently run).\n */\nexport class GatewayToolApprovalRequiredError extends GatewaySecurityError {\n readonly decision: ToolCallAuthorizeResponse;\n readonly toolId: string;\n\n constructor(toolId: string, decision: ToolCallAuthorizeResponse) {\n super(decision.message || `Gateway requires approval for tool ${toolId}`);\n this.name = \"GatewayToolApprovalRequiredError\";\n this.toolId = toolId;\n this.decision = decision;\n }\n}\n\nexport class GatewaySecurity {\n private readonly host: string;\n private readonly publicKey: string;\n private readonly secretKey: string;\n private readonly agent: AgentDescriptor;\n private readonly debug: boolean;\n private readonly failOpen: boolean;\n\n constructor(config: GatewaySecurityConfig) {\n this.host = config.host.replace(/\\/$/, \"\");\n this.publicKey = config.publicKey;\n this.secretKey = config.secretKey;\n this.agent = config.agent ?? {};\n this.debug = config.debug ?? false;\n this.failOpen = config.failOpen ?? false;\n }\n\n static fromEnv(config: GatewaySecurityFromEnvConfig = {}) {\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 GatewaySecurityError(\n `Missing Gateway security configuration: ${missing.join(\", \")}`,\n );\n }\n\n return new GatewaySecurity({\n ...config,\n host: host!,\n publicKey: publicKey!,\n secretKey: secretKey!,\n });\n }\n\n async secureTools<TTools extends ToolCollection>(\n options: SecureToolsOptions<TTools>,\n ): Promise<TTools> {\n const entries = Object.entries(options.tools);\n const descriptors = entries.map(([key, tool]) =>\n this.describeTool(key, tool, options),\n );\n const resolve = await this.resolveToolset({\n agent: this.agent,\n toolsetId: options.toolsetId,\n toolsetName: options.toolsetName,\n provider: options.provider,\n tools: descriptors,\n context: this.normalizeContext(options.context),\n });\n\n const securedEntries = entries.flatMap(([key, tool]) => {\n const descriptor = descriptors.find((item) => item.name === key)!;\n if (!this.shouldExposeTool(resolve, descriptor.id)) {\n this.log(\"Hiding tool %s in %s mode\", descriptor.id, resolve.mode);\n return [];\n }\n\n return [\n [\n key,\n this.wrapTool(tool, {\n toolId: descriptor.id,\n toolsetId: options.toolsetId,\n context: this.normalizeContext(options.context),\n resolve,\n }),\n ],\n ];\n });\n\n return Object.fromEntries(securedEntries) as TTools;\n }\n\n private async resolveToolset(input: {\n agent: AgentDescriptor;\n toolsetId: string;\n toolsetName?: string;\n provider?: string;\n tools: ToolDescriptor[];\n context: SecurityContext;\n }) {\n return this.postJson<ToolsetResolveResponse>(\n \"/api/public/security/toolsets/resolve\",\n input,\n );\n }\n\n private async authorizeToolCall(input: {\n toolsetId: string;\n toolId: string;\n context: SecurityContext;\n inputMetadata: Record<string, unknown>;\n }) {\n return this.postJson<ToolCallAuthorizeResponse>(\n \"/api/public/security/tool-calls/authorize\",\n {\n agent: this.agent,\n toolsetId: input.toolsetId,\n toolId: input.toolId,\n context: input.context,\n inputMetadata: input.inputMetadata,\n },\n );\n }\n\n private wrapTool(\n tool: ToolObject | ((...args: unknown[]) => unknown),\n input: {\n toolId: string;\n toolsetId: string;\n context: SecurityContext;\n resolve: ToolsetResolveResponse;\n },\n ) {\n if (typeof tool === \"function\") {\n return this.wrapExecute(tool, input);\n }\n\n if (typeof tool.execute !== \"function\") {\n return tool;\n }\n\n return {\n ...tool,\n execute: this.wrapExecute(tool.execute.bind(tool), input),\n };\n }\n\n private wrapExecute(\n execute: (...args: unknown[]) => unknown,\n input: {\n toolId: string;\n toolsetId: string;\n context: SecurityContext;\n resolve: ToolsetResolveResponse;\n },\n ) {\n return async (...args: unknown[]) => {\n this.setSpanAttributes({\n [SECURITY_ATTRIBUTES.AGENT_ID]: this.agent.id,\n [SECURITY_ATTRIBUTES.AGENT_NAME]: this.agent.name,\n [SECURITY_ATTRIBUTES.AGENT_VERSION]: this.agent.version,\n [SECURITY_ATTRIBUTES.TOOLSET_ID]: input.toolsetId,\n [SECURITY_ATTRIBUTES.TOOL_ID]: input.toolId,\n [SECURITY_ATTRIBUTES.SECURITY_MODE]: input.resolve.mode,\n [SECURITY_ATTRIBUTES.POLICY_VERSION]: input.resolve.policyVersion,\n });\n\n const decision = await this.authorizeOrFallback({\n toolsetId: input.toolsetId,\n toolId: input.toolId,\n context: input.context,\n inputMetadata: { args },\n });\n\n this.setSpanAttributes({\n [SECURITY_ATTRIBUTES.DECISION_OUTCOME]: decision.outcome,\n [SECURITY_ATTRIBUTES.DECISION_REASON_CODE]: decision.reasonCode,\n [SECURITY_ATTRIBUTES.POLICY_VERSION]: decision.policyVersion,\n });\n\n if (decision.outcome === \"block\") {\n throw new GatewayToolBlockedError(input.toolId, decision);\n }\n if (decision.outcome === \"approval_required\") {\n // Enforce the step-up gate: do NOT execute until approved. The tool\n // stays callable (so the approval flow can be triggered), but a call\n // is refused with a typed error rather than running unapproved.\n throw new GatewayToolApprovalRequiredError(input.toolId, decision);\n }\n\n return execute(...args);\n };\n }\n\n private async authorizeOrFallback(input: {\n toolsetId: string;\n toolId: string;\n context: SecurityContext;\n inputMetadata: Record<string, unknown>;\n }) {\n try {\n return await this.authorizeToolCall(input);\n } catch (error) {\n if (this.failOpen) {\n this.log(\"Authorization failed open for tool %s\", input.toolId, error);\n return {\n decisionId: \"local-fail-open\",\n outcome: \"flag\" as const,\n reasonCode: \"authorization_unavailable_fail_open\",\n message:\n \"Gateway authorization was unavailable; failOpen allowed execution.\",\n policyVersion: 0,\n };\n }\n throw new GatewaySecurityError(\n `Gateway authorization failed for tool ${input.toolId}`,\n { cause: error },\n );\n }\n }\n\n private async postJson<TResponse>(\n path: string,\n payload: Record<string, unknown>,\n ): Promise<TResponse> {\n const response = await fetch(`${this.host}${path}`, {\n method: \"POST\",\n headers: {\n Authorization: this.authHeader(),\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const body = await response.text();\n throw new GatewaySecurityError(\n `Gateway API ${response.status} on ${path}: ${body || response.statusText}`,\n );\n }\n\n return (await response.json()) as TResponse;\n }\n\n private describeTool<TTools extends ToolCollection>(\n key: string,\n tool: ToolObject | ((...args: unknown[]) => unknown),\n options: SecureToolsOptions<TTools>,\n ): ToolDescriptor & { name: string } {\n const toolObject = typeof tool === \"function\" ? undefined : tool;\n const id =\n options.toolIds?.[key] ?? `${options.toolsetId}.${toSnakeCase(key)}`;\n return {\n id,\n name: key,\n description:\n typeof toolObject?.description === \"string\"\n ? toolObject.description\n : undefined,\n metadata: options.toolMetadata?.[key] ?? {},\n };\n }\n\n private shouldExposeTool(resolve: ToolsetResolveResponse, toolId: string) {\n if (resolve.mode === \"observe\") return true;\n if (resolve.blockedToolIds.includes(toolId)) return false;\n return true;\n }\n\n private normalizeContext(context?: SecurityContext): SecurityContext {\n return {\n ...(context ?? {}),\n metadata: context?.metadata ?? {},\n };\n }\n\n private authHeader() {\n return `Basic ${Buffer.from(`${this.publicKey}:${this.secretKey}`).toString(\n \"base64\",\n )}`;\n }\n\n private setSpanAttributes(attributes: Record<string, unknown>) {\n const span = getActiveSpan();\n if (!span) return;\n\n for (const [key, value] of Object.entries(attributes)) {\n if (value === undefined || value === null) continue;\n span.setAttribute(key, value);\n }\n }\n\n private log(message: string, ...args: unknown[]) {\n if (this.debug) {\n console.log(`[gateway.security] ${message}`, ...args);\n }\n }\n}\n\nfunction getActiveSpan(): {\n setAttribute: (key: string, value: unknown) => void;\n} | null {\n try {\n // Optional peer dependency. Avoid making security unusable without tracing.\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const otel = require(\"@opentelemetry/api\") as {\n trace?: {\n getActiveSpan?: () =>\n | { setAttribute: (key: string, value: unknown) => void }\n | undefined;\n };\n };\n return otel.trace?.getActiveSpan?.() ?? null;\n } catch {\n return null;\n }\n}\n\nfunction toSnakeCase(value: string) {\n return value\n .replace(/([a-z0-9])([A-Z])/g, \"$1_$2\")\n .replace(/[\\s-]+/g, \"_\")\n .toLowerCase();\n}\n\nexport const gateway = {\n fromEnv: GatewaySecurity.fromEnv,\n};\n\nexport type {\n AgentDescriptor as GatewayAgentDescriptor,\n GatewaySecurityConfig,\n SecurityContext as GatewaySecurityContext,\n SecureToolsOptions,\n ToolCallAuthorizeResponse as GatewayToolCallAuthorizeResponse,\n ToolDescriptor as GatewayToolDescriptor,\n ToolsetResolveResponse as GatewayToolsetResolveResponse,\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 * 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 * The project's file drive from code: the same routes the dashboard, the MCP\n * tools (list_files, get_file, request_file_upload, confirm_file_upload,\n * delete_file, move_file, create_folder) and `gateway files …` use.\n *\n * GET /api/public/files?prefix=&page=&limit= list a folder\n * POST /api/public/files presigned PUT, then\n * POST /api/public/files/confirm mark it ready\n * GET /api/public/files/download?path= presigned GET + metadata\n * DELETE /api/public/files?path= a file, or a folder subtree\n * POST /api/public/files/move { fromPath, toPath }\n * POST /api/public/files/folders { path }\n *\n * Bytes go straight to storage: an upload is a PUT to the presigned URL with\n * the SHA-256 S3 enforces, a download a GET from one. The app never proxies\n * them, so a file of any size the project allows moves at storage speed. Files\n * are addressed by PATH; the API returns a fileId on upload only to confirm it.\n */\n\nimport { createHash } from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { Readable, Transform } from \"node:stream\";\nimport { pipeline } from \"node:stream/promises\";\n\nimport { apiRequest, type WorldsClientOptions } from \"../worlds/index\";\n\nexport type DriveFile = {\n path: string;\n name: string;\n sizeBytes: number | null;\n contentType: string | null;\n sha256: string | null;\n author: string | null;\n authorLabel: string;\n updatedAt: string;\n};\n\nexport type DriveFolder = { name: string; path: string };\n\nexport type DriveListing = {\n prefix: string;\n folders: DriveFolder[];\n files: DriveFile[];\n totalFiles: number;\n page: number;\n limit: number;\n};\n\n/** What `GET /files/download` answers: the file's metadata and a time-limited URL for its bytes. */\nexport type DriveDownload = {\n path: string;\n url: string;\n urlExpiry: string;\n sizeBytes: number | null;\n contentType: string | null;\n sha256: string | null;\n};\n\nexport type UploadResult = { path: string; fileId: string; sizeBytes: number; sha256: string; contentType: string };\n\nexport type UploadOptions = {\n contentType?: string;\n /** Replace a READY file at the same path. Default false: the platform refuses a taken path. */\n overwrite?: boolean;\n /** Bytes sent so far, called as the PUT streams. */\n onProgress?: (sent: number, total: number) => void;\n};\n\n/** The spelling that names a drive file where a local path would go: `drive:<path>`. */\nexport const DRIVE_PREFIX = \"drive:\";\n\nexport function isDriveRef(value: string): boolean {\n return value.startsWith(DRIVE_PREFIX);\n}\n\n/** `drive:corpora/x.jsonl` → `corpora/x.jsonl`; a leading slash is dropped, the platform keys paths without one. */\nexport function drivePath(ref: string): string {\n const raw = isDriveRef(ref) ? ref.slice(DRIVE_PREFIX.length) : ref;\n const trimmed = raw.replace(/^\\/+/, \"\");\n if (!trimmed) throw new Error(`${ref} names no file in the drive`);\n return trimmed;\n}\n\nconst PAGE_LIMIT = 200;\nconst BASE = \"/api/public/files\";\n\nfunction qs(params: Record<string, string | number | undefined>): string {\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) if (value !== undefined && value !== \"\") search.set(key, String(value));\n const text = search.toString();\n return text ? `?${text}` : \"\";\n}\n\nexport async function listFiles(\n options: WorldsClientOptions = {},\n params: { prefix?: string; page?: number; limit?: number } = {},\n): Promise<DriveListing> {\n return apiRequest<DriveListing>(options, \"GET\", `${BASE}${qs({ prefix: params.prefix, page: params.page, limit: params.limit })}`);\n}\n\n/** Every file directly under a folder, paging until the listing is exhausted. */\nexport async function* iterateFiles(options: WorldsClientOptions = {}, prefix?: string): AsyncGenerator<DriveFile> {\n for (let page = 0; ; page++) {\n const listing = await listFiles(options, { prefix, page, limit: PAGE_LIMIT });\n yield* listing.files;\n const seen = (page + 1) * listing.limit;\n if (!listing.files.length || seen >= listing.totalFiles) return;\n }\n}\n\n/** Metadata plus a presigned URL for one file; a 404 names the path. */\nexport async function getFile(options: WorldsClientOptions = {}, filePath: string): Promise<DriveDownload> {\n return apiRequest<DriveDownload>(options, \"GET\", `${BASE}/download${qs({ path: drivePath(filePath) })}`);\n}\n\nasync function openDownload(url: string): Promise<Response> {\n const res = await fetch(url);\n if (!res.ok || !res.body) throw new Error(`download failed: storage answered HTTP ${res.status}`);\n return res;\n}\n\n/** The whole file in memory — for text, configs, anything you would `cat`. */\nexport async function readFile(options: WorldsClientOptions = {}, filePath: string): Promise<Buffer> {\n const file = await getFile(options, filePath);\n const res = await openDownload(file.url);\n return Buffer.from(await res.arrayBuffer());\n}\n\n/** Stream one file to a local path; the parent directory is created. */\nexport async function downloadFile(\n options: WorldsClientOptions = {},\n filePath: string,\n outPath: string,\n onProgress?: (received: number, total: number | null) => void,\n): Promise<DriveDownload & { out: string }> {\n const file = await getFile(options, filePath);\n const res = await openDownload(file.url);\n fs.mkdirSync(path.dirname(path.resolve(outPath)), { recursive: true });\n const source = Readable.fromWeb(res.body as never);\n await pipeline(source, counting((n) => onProgress?.(n, file.sizeBytes)), fs.createWriteStream(outPath));\n return { ...file, out: outPath };\n}\n\nexport async function requestUpload(\n options: WorldsClientOptions = {},\n body: { path: string; contentLength: number; contentType: string; sha256: string; overwrite?: boolean },\n): Promise<{ fileId: string; uploadUrl: string; path: string }> {\n return apiRequest(options, \"POST\", BASE, body);\n}\n\nexport async function confirmUpload(options: WorldsClientOptions = {}, fileId: string, ok = true): Promise<{ path: string }> {\n return apiRequest(options, \"POST\", `${BASE}/confirm`, { fileId, ok });\n}\n\n/** The base64 SHA-256 the platform hands to S3 (`x-amz-checksum-sha256`), computed by streaming. */\nexport async function sha256Base64(localPath: string): Promise<string> {\n const hash = createHash(\"sha256\");\n for await (const chunk of fs.createReadStream(localPath)) hash.update(chunk as Buffer);\n return hash.digest(\"base64\");\n}\n\nconst CONTENT_TYPES: Record<string, string> = {\n \".json\": \"application/json\",\n \".jsonl\": \"application/x-ndjson\",\n \".ndjson\": \"application/x-ndjson\",\n \".csv\": \"text/csv\",\n \".tsv\": \"text/tab-separated-values\",\n \".txt\": \"text/plain\",\n \".md\": \"text/markdown\",\n \".toml\": \"application/toml\",\n \".yaml\": \"application/yaml\",\n \".yml\": \"application/yaml\",\n \".xml\": \"application/xml\",\n \".html\": \"text/html\",\n \".sql\": \"application/sql\",\n \".py\": \"text/x-python\",\n \".ts\": \"text/plain\",\n \".js\": \"text/javascript\",\n \".pdf\": \"application/pdf\",\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".gif\": \"image/gif\",\n \".webp\": \"image/webp\",\n \".svg\": \"image/svg+xml\",\n \".zip\": \"application/zip\",\n \".gz\": \"application/gzip\",\n \".tar\": \"application/x-tar\",\n \".parquet\": \"application/vnd.apache.parquet\",\n \".wav\": \"audio/wav\",\n \".mp3\": \"audio/mpeg\",\n \".mp4\": \"video/mp4\",\n};\n\n/** A MIME type from the extension; `application/octet-stream` when none is known. */\nexport function contentTypeFor(name: string): string {\n return CONTENT_TYPES[path.extname(name).toLowerCase()] ?? \"application/octet-stream\";\n}\n\n/** A transform that reports the bytes that passed through it. */\nfunction counting(report: (n: number) => void): Transform {\n let seen = 0;\n return new Transform({\n transform(chunk, _encoding, callback) {\n seen += (chunk as Buffer).length;\n report(seen);\n callback(null, chunk);\n },\n });\n}\n\nasync function putPresigned(\n uploadUrl: string,\n body: BodyInit,\n headers: { contentType: string; contentLength: number; sha256: string },\n): Promise<void> {\n const res = await fetch(uploadUrl, {\n method: \"PUT\",\n headers: {\n \"content-type\": headers.contentType,\n \"content-length\": String(headers.contentLength),\n \"x-amz-checksum-sha256\": headers.sha256,\n },\n body,\n // A streamed request body needs the half-duplex declaration (Node's fetch).\n duplex: \"half\",\n } as RequestInit);\n if (!res.ok) throw new Error(`upload failed: storage answered HTTP ${res.status}: ${(await res.text()).slice(0, 300)}`);\n}\n\n/**\n * Request, PUT, confirm — the three-step presigned upload as one call. The\n * bytes stream from disk; a failed PUT is confirmed with ok=false so no\n * PENDING placeholder is left behind, then the error is rethrown.\n */\nexport async function uploadFile(\n options: WorldsClientOptions = {},\n localPath: string,\n targetPath: string,\n upload: UploadOptions = {},\n): Promise<UploadResult> {\n const stat = fs.statSync(localPath);\n if (!stat.isFile()) throw new Error(`${localPath} is not a file`);\n if (stat.size === 0) throw new Error(`${localPath} is empty; the drive refuses zero-byte uploads`);\n const contentType = upload.contentType ?? contentTypeFor(localPath);\n const sha256 = await sha256Base64(localPath);\n const target = drivePath(targetPath);\n const granted = await requestUpload(options, { path: target, contentLength: stat.size, contentType, sha256, ...(upload.overwrite ? { overwrite: true } : {}) });\n try {\n const stream = fs.createReadStream(localPath).pipe(counting((n) => upload.onProgress?.(n, stat.size)));\n await putPresigned(granted.uploadUrl, Readable.toWeb(stream) as unknown as BodyInit, { contentType, contentLength: stat.size, sha256 });\n } catch (error) {\n await confirmUpload(options, granted.fileId, false).catch(() => undefined);\n throw error;\n }\n const confirmed = await confirmUpload(options, granted.fileId, true);\n return { path: confirmed.path, fileId: granted.fileId, sizeBytes: stat.size, sha256, contentType };\n}\n\n/** The same three steps for bytes already in memory (a fetched URL, a generated export). */\nexport async function uploadBytes(\n options: WorldsClientOptions = {},\n bytes: Buffer,\n targetPath: string,\n upload: Omit<UploadOptions, \"onProgress\"> = {},\n): Promise<UploadResult> {\n if (!bytes.length) throw new Error(\"nothing to upload: the content is empty\");\n const target = drivePath(targetPath);\n const contentType = upload.contentType ?? contentTypeFor(target);\n const sha256 = createHash(\"sha256\").update(bytes).digest(\"base64\");\n const granted = await requestUpload(options, { path: target, contentLength: bytes.length, contentType, sha256, ...(upload.overwrite ? { overwrite: true } : {}) });\n try {\n await putPresigned(granted.uploadUrl, new Uint8Array(bytes), { contentType, contentLength: bytes.length, sha256 });\n } catch (error) {\n await confirmUpload(options, granted.fileId, false).catch(() => undefined);\n throw error;\n }\n const confirmed = await confirmUpload(options, granted.fileId, true);\n return { path: confirmed.path, fileId: granted.fileId, sizeBytes: bytes.length, sha256, contentType };\n}\n\n/** Delete a file, or a folder and everything under it. Answers how many entries went. */\nexport async function deleteFile(options: WorldsClientOptions = {}, filePath: string): Promise<{ deleted: number }> {\n return apiRequest(options, \"DELETE\", `${BASE}${qs({ path: drivePath(filePath) })}`);\n}\n\n/** Rename or move a file or a whole folder; metadata only, no bytes re-copied. */\nexport async function moveFile(options: WorldsClientOptions = {}, fromPath: string, toPath: string): Promise<{ moved: number }> {\n return apiRequest(options, \"POST\", `${BASE}/move`, { fromPath: drivePath(fromPath), toPath: drivePath(toPath) });\n}\n\n/** Create an (empty) folder. Idempotent. */\nexport async function createFolder(options: WorldsClientOptions = {}, folderPath: string): Promise<{ path: string }> {\n return apiRequest(options, \"POST\", `${BASE}/folders`, { path: drivePath(folderPath) });\n}\n\nexport type FileConnector = {\n id: string;\n name: string;\n kind: string;\n connectionId: string | null;\n targetPrefix: string;\n lastSyncAt: string | null;\n lastStatus: string | null;\n};\n\n/** The connectors a human shared with agents — `GET /api/public/files/connectors`. */\nexport async function listFileConnectors(options: WorldsClientOptions = {}): Promise<{ connectors: FileConnector[] }> {\n return apiRequest(options, \"GET\", `${BASE}/connectors`);\n}\n\n/** Run one connector's sync now — `POST /api/public/files/connectors/sync`. */\nexport async function syncFileConnector(options: WorldsClientOptions = {}, connectorId: string): Promise<Record<string, unknown>> {\n return apiRequest(options, \"POST\", `${BASE}/connectors/sync`, { connectorId });\n}\n","/**\n * Read the project's traces, observations and trace sessions — the public\n * API behind `gateway traces …` and the MCP tools get_trace / get_observations\n * / get_session. Everything here is read-only.\n *\n * GET /api/public/traces?… a page of traces (page 1-based, limit ≤ 100)\n * GET /api/public/traces/{traceId} one trace with its observations and scores\n * GET /api/public/observations?… a page of observations (type, traceId, time window)\n * GET /api/public/sessions?… a page of trace sessions\n * GET /api/public/sessions/{sessionId} one session; includeIO=true attaches every trace's observations\n */\n\nimport { apiRequest, type WorldsClientOptions } from \"../worlds/index\";\n\nexport type TraceFilters = {\n fromTimestamp?: string;\n toTimestamp?: string;\n sessionId?: string;\n userId?: string;\n name?: string;\n tags?: string[];\n environment?: string;\n version?: string;\n release?: string;\n /** `timestamp.asc`, `timestamp.desc` (the default), … */\n orderBy?: string;\n};\n\nexport type ObservationFilters = {\n traceId?: string;\n type?: string;\n name?: string;\n userId?: string;\n level?: string;\n parentObservationId?: string;\n environment?: string;\n version?: string;\n fromStartTime?: string;\n toStartTime?: string;\n};\n\nexport type SessionFilters = { fromTimestamp?: string; toTimestamp?: string; environment?: string };\n\nexport type PageMeta = { page: number; limit: number; totalItems: number; totalPages: number };\nexport type Page<T> = { data: T[]; meta: PageMeta };\n\nexport type Trace = {\n id: string;\n timestamp: string;\n name: string | null;\n sessionId: string | null;\n userId: string | null;\n tags: string[];\n environment?: string;\n [key: string]: unknown;\n};\n\nexport type Observation = {\n id: string;\n traceId: string | null;\n type: string;\n name: string | null;\n startTime: string;\n endTime?: string | null;\n level?: string;\n [key: string]: unknown;\n};\n\nexport type TraceDetail = Trace & { observations: Observation[]; scores: unknown[]; latency?: number; totalCost?: number };\n\nexport type TraceSession = { id: string; createdAt: string; projectId: string; environment: string };\nexport type TraceSessionDetail = TraceSession & { traces: (Trace & { observations?: Observation[] })[] };\n\n/** The platform caps a page at 100. */\nexport const PAGE_LIMIT = 100;\n\ntype Scalar = string | number | boolean | undefined | null;\n\nfunction qs(params: Record<string, Scalar | string[]>): string {\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined || value === null || value === \"\") continue;\n if (Array.isArray(value)) for (const item of value) search.append(key, item);\n else search.set(key, String(value));\n }\n const text = search.toString();\n return text ? `?${text}` : \"\";\n}\n\nexport async function listTraces(\n options: WorldsClientOptions = {},\n filters: TraceFilters = {},\n page: { page?: number; limit?: number; fields?: string } = {},\n): Promise<Page<Trace>> {\n const { tags, ...rest } = filters;\n return apiRequest<Page<Trace>>(options, \"GET\", `/api/public/traces${qs({ ...rest, tags, page: page.page ?? 1, limit: page.limit ?? 50, fields: page.fields })}`);\n}\n\n/** Page through matching traces, newest first unless `orderBy` says otherwise; `max` stops early. */\nexport async function* iterateTraces(\n options: WorldsClientOptions = {},\n filters: TraceFilters = {},\n limits: { max?: number; fields?: string } = {},\n): AsyncGenerator<Trace> {\n yield* paged((page) => listTraces(options, filters, { page, limit: PAGE_LIMIT, fields: limits.fields }), limits.max);\n}\n\n/** One trace with its observations (input/output included) and scores. */\nexport async function getTrace(options: WorldsClientOptions = {}, traceId: string): Promise<TraceDetail> {\n return apiRequest<TraceDetail>(options, \"GET\", `/api/public/traces/${encodeURIComponent(traceId)}`);\n}\n\nexport async function listObservations(\n options: WorldsClientOptions = {},\n filters: ObservationFilters = {},\n page: { page?: number; limit?: number } = {},\n): Promise<Page<Observation>> {\n return apiRequest<Page<Observation>>(options, \"GET\", `/api/public/observations${qs({ ...filters, page: page.page ?? 1, limit: page.limit ?? 50 })}`);\n}\n\nexport async function* iterateObservations(\n options: WorldsClientOptions = {},\n filters: ObservationFilters = {},\n limits: { max?: number } = {},\n): AsyncGenerator<Observation> {\n yield* paged((page) => listObservations(options, filters, { page, limit: PAGE_LIMIT }), limits.max);\n}\n\nexport async function listSessions(\n options: WorldsClientOptions = {},\n filters: SessionFilters = {},\n page: { page?: number; limit?: number } = {},\n): Promise<Page<TraceSession>> {\n return apiRequest<Page<TraceSession>>(options, \"GET\", `/api/public/sessions${qs({ ...filters, page: page.page ?? 1, limit: page.limit ?? 50 })}`);\n}\n\nexport async function* iterateSessions(\n options: WorldsClientOptions = {},\n filters: SessionFilters = {},\n limits: { max?: number } = {},\n): AsyncGenerator<TraceSession> {\n yield* paged((page) => listSessions(options, filters, { page, limit: PAGE_LIMIT }), limits.max);\n}\n\n/** One trace session and its traces; `includeIO` attaches every trace's full observations. */\nexport async function getSession(\n options: WorldsClientOptions = {},\n sessionId: string,\n detail: { includeIO?: boolean } = {},\n): Promise<TraceSessionDetail> {\n return apiRequest<TraceSessionDetail>(options, \"GET\", `/api/public/sessions/${encodeURIComponent(sessionId)}${qs({ includeIO: detail.includeIO ? \"true\" : undefined })}`);\n}\n\nexport type ExportOptions = {\n /** Attach each trace's observations (one GET /traces/{id} per trace). */\n observations?: boolean;\n /** With `observations`: keep only this observation type (TOOL, GENERATION, SPAN, …). */\n type?: string;\n /** Stop after this many traces. */\n max?: number;\n};\n\nexport type ExportSummary = { traces: number; observations: number };\n\n/**\n * Every matching trace as one JSON object handed to `write`, ids and\n * timestamps exactly as the API returns them. With `observations`, each object\n * carries its `observations` array (filtered by `type` when given) and the\n * trace's `scores`, from `GET /traces/{id}`.\n */\nexport async function exportTraces(\n options: WorldsClientOptions = {},\n filters: TraceFilters = {},\n exportOptions: ExportOptions = {},\n write: (record: Record<string, unknown>) => void,\n): Promise<ExportSummary> {\n const summary: ExportSummary = { traces: 0, observations: 0 };\n const wantedType = exportOptions.type?.toUpperCase();\n for await (const trace of iterateTraces(options, filters, { max: exportOptions.max })) {\n let record: Record<string, unknown> = trace;\n if (exportOptions.observations) {\n const detail = await getTrace(options, trace.id);\n const observations = wantedType ? detail.observations.filter((o) => o.type?.toUpperCase() === wantedType) : detail.observations;\n summary.observations += observations.length;\n record = { ...detail, observations };\n }\n summary.traces++;\n write(record);\n }\n return summary;\n}\n\nasync function* paged<T>(fetchPage: (page: number) => Promise<Page<T>>, max?: number): AsyncGenerator<T> {\n let yielded = 0;\n for (let page = 1; ; page++) {\n const answer = await fetchPage(page);\n for (const item of answer.data) {\n if (max !== undefined && yielded >= max) return;\n yielded++;\n yield item;\n }\n const totalPages = answer.meta?.totalPages ?? (answer.data.length < PAGE_LIMIT ? page : page + 1);\n if (!answer.data.length || page >= totalPages) return;\n }\n}\n","/**\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 * 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 * Tracing module for GatewaySDK TypeScript SDK.\n *\n * Provides a simple init() function that configures OpenTelemetry with\n * Gateway, mirroring the Python SDK's tracing.init() experience.\n *\n * @example\n * ```typescript\n * import { tracing } from \"@withgateway/sdk\";\n *\n * // Initialize with environment variables\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 * });\n *\n * // Ensure cleanup on shutdown\n * process.on(\"SIGTERM\", () => tracing.shutdown());\n * ```\n */\n\nexport type { TracingConfig, TracingState } from \"./types\";\n\nexport {\n init,\n initIsolated,\n shutdown,\n flush,\n isInitialized,\n isGatewayConfigured,\n} from \"./init\";\nexport type { TracingHandle } from \"./init\";\n\nexport {\n identify,\n resolveUserId,\n resetAmbientUser,\n IdentitySpanProcessor,\n USER_ID_ATTRIBUTE,\n} from \"./identity\";\nexport type { IdentifyOptions } from \"./identity\";\n\nexport { observe } from \"./observe\";\nexport type { ObserveOptions, ObservationKind } from \"./observe\";\n\nexport { observeOpenAI, observeAnthropic } from \"./instrument\";\n\nexport { observeClaude } from \"./claude\";\nexport type { ObserveClaudeOptions } from \"./claude\";\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 { 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 ?? semconv.SEMRESATTRS_SERVICE_NAME ?? \"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 // 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","/**\n * observe() — group a unit of work (an agent run, a tool call) into a single\n * span so nested LLM/tool spans attach to it and the whole thing is one trace.\n *\n * Mirrors Langfuse's `observe()` / `startActiveObservation()`. This is what an\n * app uses to define a trace boundary when it drives a raw client loop (which\n * has no framework root span of its own): the callback runs inside the span's\n * OpenTelemetry context, so any auto-instrumented calls (see observeOpenAI) and\n * any nested observe() calls become children of it.\n *\n * The span carries OpenInference attributes (openinference.span.kind, input.value,\n * output.value), and Gateway maps a root span's input.value/output.value to the\n * trace-level input/output — so the trace shows the user input and final output.\n */\nimport { trace, context, SpanStatusCode } from \"@opentelemetry/api\";\nimport type { Tracer } from \"@opentelemetry/api\";\n\nexport type ObservationKind = \"AGENT\" | \"CHAIN\" | \"TOOL\" | \"LLM\" | \"RETRIEVER\";\n\nexport interface ObserveOptions {\n /** Recorded as input.value on the span (JSON-stringified if not a string). */\n input?: unknown;\n /** OpenInference span kind. Defaults to \"AGENT\" for the outer run. */\n kind?: ObservationKind;\n /**\n * When true (default), the callback's return value is recorded as\n * output.value. Set false if the return value is large/uninteresting.\n */\n captureOutput?: boolean;\n /**\n * Tracer to start the span from. Defaults to the GLOBAL tracer (set up by\n * tracing.init()). Pass an initIsolated() handle's tracer to route this\n * observation to that handle's Gateway project instead.\n */\n tracer?: Tracer;\n /**\n * Extra attributes for the span — e.g. gateway.session.id /\n * gateway.user.id to group runs into a session and attribute them to a user.\n */\n attributes?: Record<string, string>;\n}\n\nfunction asAttr(value: unknown): string {\n return typeof value === \"string\" ? value : JSON.stringify(value);\n}\n\n/**\n * Run `fn` inside a span named `name`. Anything traced inside (auto-instrumented\n * client calls, nested observe() calls) nests under it, forming one trace.\n *\n * @example\n * ```ts\n * const result = await observe(\"my-agent.run\", async () => {\n * // client.chat.completions.create(...) here becomes a child GENERATION\n * return finalText;\n * }, { input: prompt });\n * ```\n */\nexport async function observe<T>(\n name: string,\n fn: () => Promise<T>,\n options: ObserveOptions = {},\n): Promise<T> {\n const tracer = options.tracer ?? trace.getTracer(\"@withgateway/sdk\");\n const span = tracer.startSpan(name, {\n attributes: {\n \"openinference.span.kind\": options.kind ?? \"AGENT\",\n ...(options.input !== undefined\n ? { \"input.value\": asAttr(options.input) }\n : {}),\n ...(options.attributes ?? {}),\n },\n });\n\n try {\n const result = await context.with(\n trace.setSpan(context.active(), span),\n fn,\n );\n if (options.captureOutput !== false && result !== undefined) {\n span.setAttribute(\"output.value\", asAttr(result));\n }\n span.setStatus({ code: SpanStatusCode.OK });\n return result;\n } catch (error) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: error instanceof Error ? error.message : String(error),\n });\n throw error;\n } finally {\n span.end();\n }\n}\n","/**\n * Client wrappers that turn an SDK's calls into spans on the Gateway provider.\n *\n * Node ESM can't retroactively patch a module the app already imported, so — as\n * Langfuse does with `observeOpenAI` — the app hands us the client and we\n * instrument it explicitly. One SDK call, no OpenTelemetry in the app.\n *\n * The OpenInference instrumentations are bundled optional deps of this package;\n * we load them with require() (the ESM build injects a real createRequire).\n */\n/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-require-imports */\n\nfunction warn(message: string, ...args: unknown[]): void {\n console.warn(`[gatewaysdk.tracing] ${message}`, ...args);\n}\n\n/**\n * Instrument an OpenAI client so its requests become GENERATION spans on the\n * Gateway provider. Returns the same client (its class prototype is patched, so\n * this and every other instance of that client are traced).\n *\n * @example\n * ```ts\n * import OpenAI from \"openai\";\n * import { init, observeOpenAI } from \"@withgateway/sdk/tracing\";\n * init();\n * const client = observeOpenAI(new OpenAI());\n * ```\n */\nexport function observeOpenAI<T extends object>(client: T): T {\n try {\n const {\n OpenAIInstrumentation,\n } = require(\"@arizeai/openinference-instrumentation-openai\");\n // OpenInference patches `module.OpenAI.Chat.Completions.prototype`, so it\n // needs an object shaped like the openai module. Reconstruct it from the\n // instance's class (client.constructor === the OpenAI class).\n const OpenAIClass = (client as { constructor: unknown }).constructor;\n new OpenAIInstrumentation().manuallyInstrument({ OpenAI: OpenAIClass });\n } catch (error) {\n warn(\n \"observeOpenAI: could not load @arizeai/openinference-instrumentation-openai — OpenAI calls will not be traced.\",\n error,\n );\n }\n return client;\n}\n\n/**\n * Instrument an Anthropic client so its requests become GENERATION spans.\n *\n * @example\n * ```ts\n * import Anthropic from \"@anthropic-ai/sdk\";\n * import { init, observeAnthropic } from \"@withgateway/sdk/tracing\";\n * init();\n * const client = observeAnthropic(new Anthropic());\n * ```\n */\nexport function observeAnthropic<T extends object>(client: T): T {\n try {\n const {\n AnthropicInstrumentation,\n } = require(\"@arizeai/openinference-instrumentation-anthropic\");\n // The instrumentor patches `module.Messages.prototype.create`, so it wants\n // an object whose `Messages` is the Anthropic client's Messages class (a\n // static on the class). `client.messages` resolves `create` through that\n // prototype, so patching it traces this client and every other instance.\n const AnthropicClass = (client as { constructor: { Messages?: unknown } })\n .constructor;\n new AnthropicInstrumentation().manuallyInstrument({\n Messages: AnthropicClass.Messages,\n });\n } catch (error) {\n warn(\n \"observeAnthropic: could not load @arizeai/openinference-instrumentation-anthropic — Anthropic calls will not be traced.\",\n error,\n );\n }\n return client;\n}\n","/**\n * observeClaude() — trace a Claude Agent SDK run.\n *\n * The Claude Agent SDK runs the agent in a separate `claude` CLI subprocess, so\n * there's nothing in-process to patch. What the app has is the message stream it\n * iterates. Wrap that stream with observeClaude() and it yields the same\n * messages unchanged while emitting spans on the Gateway provider.\n *\n * Default (one trace per run):\n *\n * AGENT (root)\n * ├─ GENERATION per assistant turn (with per-turn token usage)\n * └─ TOOL per tool call (input from tool_use, output from the\n * matching tool_result, matched by id)\n *\n * With `perTurn: true` (one trace PER ASSISTANT TURN — long agent runs read as\n * a session of turn traces, the way a chat thread does):\n *\n * AGENT \"<name> · turn N\" (detached root; session/user attributes on every turn)\n * ├─ GENERATION (that turn's usage + text)\n * └─ TOOL per tool call in the turn\n *\n * The TS equivalent of the Python SDK's claude-agent-sdk instrumentor.\n *\n * @example\n * ```ts\n * const stream = query({ prompt, options });\n * for await (const message of observeClaude(stream, { name, input: prompt })) {\n * // ...consume messages as usual\n * }\n * ```\n */\nimport {\n trace,\n context,\n SpanStatusCode,\n type Span,\n type Context,\n type Tracer,\n} from \"@opentelemetry/api\";\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nexport interface ObserveClaudeOptions {\n /** Root span name (becomes the trace name; per-turn mode appends `· turn N`). */\n name: string;\n /** Recorded as input.value on the root span → trace-level input. */\n input?: string;\n /** Model label for the generation spans. */\n model?: string;\n /**\n * Tracer to start spans from. Defaults to the GLOBAL tracer (set up by\n * tracing.init()). Pass an initIsolated() handle's tracer to route this\n * run to that handle's Gateway project instead.\n */\n tracer?: Tracer;\n /**\n * Extra attributes for the root span(s) — e.g. gateway.session.id /\n * gateway.user.id to group runs into a session and attribute them to a user.\n * In per-turn mode these ride EVERY turn root, so each turn trace maps to\n * the session.\n */\n attributes?: Record<string, string>;\n /**\n * Emit one TRACE PER ASSISTANT TURN instead of a single trace for the whole\n * run. Each turn's trace carries that turn's generation and tool calls; the\n * turn's input is the run input (turn 1) or the tool results that fed it\n * (later turns). Turn roots are detached (`root: true`), so they never nest\n * under ambient spans. Combine with `attributes.gateway.session.id` to read\n * a whole run as a session of turns.\n */\n perTurn?: boolean;\n}\n\n/** Strip the `mcp__<server>__` prefix so tool names read cleanly. */\nfunction cleanToolName(name: string): string {\n return name.replace(/^mcp__[^_]+__/, \"\");\n}\n\nfunction toolResultText(content: unknown): string {\n if (typeof content === \"string\") return content;\n if (Array.isArray(content))\n return content\n .map((b) =>\n b && typeof b === \"object\" && \"text\" in b\n ? String((b as { text: unknown }).text)\n : JSON.stringify(b),\n )\n .join(\"\");\n return JSON.stringify(content ?? \"\");\n}\n\nconst TURN_INPUT_MAX = 4000;\n\nexport async function* observeClaude(\n stream: AsyncIterable<any>,\n options: ObserveClaudeOptions,\n): AsyncGenerator<any> {\n const tracer = options.tracer ?? trace.getTracer(\"@withgateway/sdk\");\n const model = options.model ?? \"claude\";\n const openTools = new Map<string, Span>();\n\n // Single-trace mode: one root for the whole run.\n let root: Span | null = null;\n let rootCtx: Context | null = null;\n if (!options.perTurn) {\n root = tracer.startSpan(options.name, {\n attributes: {\n \"openinference.span.kind\": \"AGENT\",\n ...(options.input !== undefined\n ? { \"input.value\": options.input }\n : {}),\n ...(options.attributes ?? {}),\n },\n });\n rootCtx = trace.setSpan(context.active(), root);\n }\n\n // Per-turn mode: the current turn's root, rotated on each assistant message.\n let turnRoot: Span | null = null;\n let turnCtx: Context | null = null;\n let turnIndex = 0;\n let turnText = \"\";\n // What fed the CURRENT turn: the run input for turn 1, then the tool results\n // produced since the previous assistant message.\n let pendingTurnInput = options.input ?? \"\";\n\n let finalText = \"\";\n\n const endTurn = () => {\n if (!turnRoot) return;\n if (turnText) turnRoot.setAttribute(\"output.value\", turnText);\n turnRoot.setStatus({ code: SpanStatusCode.OK });\n turnRoot.end();\n turnRoot = null;\n turnCtx = null;\n };\n\n try {\n for await (const message of stream) {\n if (message?.type === \"assistant\") {\n if (options.perTurn) {\n // A new assistant message starts a new turn: any tools still open\n // belong to the previous turn — settle them, then rotate the root.\n for (const span of openTools.values()) span.end();\n openTools.clear();\n endTurn();\n turnIndex += 1;\n turnText = \"\";\n turnRoot = tracer.startSpan(`${options.name} · turn ${turnIndex}`, {\n root: true,\n attributes: {\n \"openinference.span.kind\": \"AGENT\",\n ...(pendingTurnInput\n ? { \"input.value\": pendingTurnInput.slice(0, TURN_INPUT_MAX) }\n : {}),\n ...(options.attributes ?? {}),\n },\n });\n turnCtx = trace.setSpan(context.active(), turnRoot);\n pendingTurnInput = \"\";\n }\n const childCtx = (options.perTurn ? turnCtx : rootCtx)!;\n\n let text = \"\";\n const toolUses: Array<{ id: string; name: string; input: unknown }> =\n [];\n for (const block of message.message?.content ?? []) {\n if (block?.type === \"text\") {\n finalText += block.text;\n text += block.text;\n }\n if (block?.type === \"tool_use\") {\n toolUses.push({\n id: block.id,\n name: block.name,\n input: block.input,\n });\n }\n }\n turnText += text;\n\n const gen = tracer.startSpan(\n \"assistant\",\n {\n attributes: {\n \"openinference.span.kind\": \"LLM\",\n \"llm.model_name\": model,\n \"llm.provider\": \"anthropic\",\n \"output.value\":\n text ||\n toolUses.map((t) => `→ ${cleanToolName(t.name)}`).join(\", \"),\n },\n },\n childCtx,\n );\n const usage = message.message?.usage;\n if (usage?.input_tokens != null)\n gen.setAttribute(\"llm.token_count.prompt\", usage.input_tokens);\n if (usage?.output_tokens != null)\n gen.setAttribute(\"llm.token_count.completion\", usage.output_tokens);\n gen.end();\n\n for (const t of toolUses) {\n const span = tracer.startSpan(\n `tool.${cleanToolName(t.name)}`,\n {\n attributes: {\n \"openinference.span.kind\": \"TOOL\",\n \"tool.name\": cleanToolName(t.name),\n \"input.value\": JSON.stringify(t.input),\n },\n },\n childCtx,\n );\n openTools.set(t.id, span);\n }\n }\n\n // tool_result (in a `user` message) closes the matching TOOL span, and in\n // per-turn mode also becomes part of the NEXT turn's input.\n if (message?.type === \"user\") {\n const content = message.message?.content;\n if (Array.isArray(content)) {\n for (const block of content) {\n if (block?.type === \"tool_result\") {\n const resultText = toolResultText(block.content);\n const span = openTools.get(block.tool_use_id);\n if (span) {\n span.setAttribute(\"output.value\", resultText);\n span.setStatus({ code: SpanStatusCode.OK });\n span.end();\n openTools.delete(block.tool_use_id);\n }\n if (\n options.perTurn &&\n pendingTurnInput.length < TURN_INPUT_MAX\n ) {\n pendingTurnInput +=\n (pendingTurnInput ? \"\\n\" : \"\") +\n resultText.slice(0, TURN_INPUT_MAX - pendingTurnInput.length);\n }\n }\n }\n }\n }\n\n yield message;\n }\n } finally {\n for (const span of openTools.values()) span.end();\n openTools.clear();\n if (options.perTurn) {\n endTurn();\n } else if (root) {\n root.setAttribute(\"output.value\", finalText);\n root.setStatus({ code: SpanStatusCode.OK });\n root.end();\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoGO,SAAS,aAAa,GAAwC;AACnE,QAAM,QAA4B,CAAC,OAAO;AAC1C,MAAI,EAAE,IAAK,OAAM,KAAK,KAAK;AAC3B,MAAI,EAAE,GAAI,OAAM,KAAK,IAAI;AACzB,MAAI,EAAE,QAAS,OAAM,KAAK,SAAS;AACnC,SAAO;AACT;AAOO,SAAS,MACd,IACAA,OACQ;AACR,QAAM,OAAO,GAAG,IAAI,QAAQ,QAAQ,EAAE;AACtC,QAAM,MAAMA,MAAK,WAAW,GAAG,IAAIA,QAAO,IAAIA,KAAI;AAClD,MAAI,CAAC,GAAG,MAAO,QAAO,OAAO;AAC7B,QAAM,CAAC,YAAY,IAAI,IAAI,UAAU,GAAG;AACxC,QAAM,SAAS,WAAW,SAAS,GAAG,IAAI,MAAM;AAChD,QAAM,QAAQ,GAAG,cAAc,IAAI,mBAAmB,GAAG,KAAK,CAAC;AAC/D,SAAO,OAAO,aAAa,SAAS,QAAQ;AAC9C;AAEO,SAAS,WAAW,IAAgD;AACzE,SAAO,MAAM,IAAI,GAAG,SAAS,GAAG;AAClC;AAGO,SAAS,eAAe,KAAqB;AAClD,QAAM,CAAC,YAAY,IAAI,IAAI,UAAU,GAAG;AACxC,QAAM,IAAI,WAAW,QAAQ,GAAG;AAChC,MAAI,IAAI,EAAG,QAAO;AAClB,QAAM,OAAO,WACV,MAAM,IAAI,CAAC,EACX,MAAM,GAAG,EACT,OA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,CAAC,GAAG;AAC/B,QAAI,OAAO,sBAAsB,OAAO;AACtC,YAAM,aAAa;AAAA,QACjB,IAAI,wBAAwB;AAAA,QAC5B,GAAI,OAAO,wBAAwB,CAAC;AAAA,MACtC;AACA,aAAsBC,MAAK;AAAA,QACzB,GAAG;AAAA,QACH,sBAAsB;AAAA,MACxB,CAAC;AAAA,IACH;AACA,WAAsBA,MAAK,MAAM;AAAA,EACnC;AACF;","names":["path","context","observe","text","resolve","sleep","state","openWorld","sleep","api","path","pollMs","pad","text","resolve","state","import_node_crypto","text","hex","import_node_crypto","text","import_node_crypto","init","text","fs","path","resolve","text","fs","path","SKIP_DIRS","text","fs","path","BUILD_OUTPUT","fs","path","resolve","import_node_child_process","fs","os","path","client","sleep","import_node_crypto","fs","resolve","flush","import_node_crypto","import_node_zlib","client","isObject","text","ingestLocalToolCalls","importLocalWorldData","checkLocalWorldData","transformRecords","pull","pushRows","trace","fs","os","path","ApiError","path","text","resolve","openSession","exports","module","ApiError","context","context","text","clearExperimentContext","fetch","fetch","clearExperimentContext","memory","path","text","identifier","encodeIdentifier","path","runtimeContextPayload","text","safeJson","path","text","safeJson","trace","path","text","import_node_path","isPlainObject","text","resolve","resolve","path","context","qs","path","text","safeJson","path","text","client","readFile","import_node_crypto","fs","path","text","sha256","PAGE_LIMIT","qs","text","trace","import_node_crypto","text","context","import_async_hooks","import_api","init","shutdown","init","debugLog","scores","shutdown","import_api","warn","client","import_api","text","init"]}
|