@withgateway/sdk 0.6.0 → 0.9.1
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/agents/index.d.mts +573 -0
- package/dist/agents/index.d.ts +573 -0
- package/dist/agents/index.js +1443 -0
- package/dist/agents/index.js.map +1 -0
- package/dist/agents/index.mjs +1394 -0
- package/dist/agents/index.mjs.map +1 -0
- package/dist/apiError-DHpfbmdx.d.mts +17 -0
- package/dist/apiError-DHpfbmdx.d.ts +17 -0
- package/dist/cli.js +5019 -1599
- package/dist/cli.js.map +1 -1
- package/dist/cli.mjs +5003 -1584
- package/dist/cli.mjs.map +1 -1
- package/dist/files/index.d.mts +3 -1
- package/dist/files/index.d.ts +3 -1
- package/dist/files/index.js +371 -102
- package/dist/files/index.js.map +1 -1
- package/dist/files/index.mjs +371 -102
- package/dist/files/index.mjs.map +1 -1
- package/dist/hooks/index.js +346 -136
- package/dist/hooks/index.js.map +1 -1
- package/dist/hooks/index.mjs +346 -136
- package/dist/hooks/index.mjs.map +1 -1
- package/dist/{index-LA-PMRJT.d.ts → index-DIN14Lhg.d.ts} +1 -1
- package/dist/{index-Di9nNqOY.d.mts → index-DuB-eQ0Z.d.mts} +1 -1
- package/dist/index.d.mts +7 -4
- package/dist/index.d.ts +7 -4
- package/dist/index.js +2689 -401
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +2650 -394
- package/dist/index.mjs.map +1 -1
- package/dist/media-CQUC7TkS.d.mts +39 -0
- package/dist/media-DQnBloaX.d.ts +39 -0
- package/dist/traces/index.d.mts +3 -1
- package/dist/traces/index.d.ts +3 -1
- package/dist/traces/index.js +371 -102
- package/dist/traces/index.js.map +1 -1
- package/dist/traces/index.mjs +371 -102
- package/dist/traces/index.mjs.map +1 -1
- package/dist/tracing/index.d.mts +3 -2
- package/dist/tracing/index.d.ts +3 -2
- package/dist/tracing/index.js +257 -16
- package/dist/tracing/index.js.map +1 -1
- package/dist/tracing/index.mjs +257 -16
- package/dist/tracing/index.mjs.map +1 -1
- package/dist/transport-CpRe7zgd.d.mts +123 -0
- package/dist/transport-CpRe7zgd.d.ts +123 -0
- package/dist/worlds/index.d.mts +1983 -1745
- package/dist/worlds/index.d.ts +1983 -1745
- package/dist/worlds/index.js +1295 -226
- package/dist/worlds/index.js.map +1 -1
- package/dist/worlds/index.mjs +1290 -222
- package/dist/worlds/index.mjs.map +1 -1
- package/package.json +6 -1
- package/runtime/gatewaysdk/environment/bundle_manifest.py +243 -0
- package/runtime/gatewaysdk/environment/schema/__main__.py +2 -2
- package/runtime/gatewaysdk/environment/schema/_slack_fidelity.py +8 -23
- package/runtime/gatewaysdk/environment/schema/api.py +3 -4
- package/runtime/gatewaysdk/environment/schema/assertions.py +7 -1
- package/runtime/gatewaysdk/environment/schema/bundle_runtime.py +1 -0
- package/runtime/gatewaysdk/environment/schema/call_log.py +20 -0
- package/runtime/gatewaysdk/environment/schema/database/base.py +2 -2
- package/runtime/gatewaysdk/environment/schema/host.py +74 -11
- package/runtime/gatewaysdk/environment/schema/host_browser.py +48 -0
- package/runtime/gatewaysdk/environment/schema/host_control.py +33 -2
- package/runtime/gatewaysdk/environment/schema/host_handoff.py +4 -1
- package/runtime/gatewaysdk/environment/schema/host_requests.py +14 -0
- package/runtime/gatewaysdk/environment/schema/host_session.py +13 -2
- package/runtime/gatewaysdk/environment/schema/host_surfaces.py +6 -0
- package/runtime/gatewaysdk/environment/schema/host_versions.py +96 -19
- package/runtime/gatewaysdk/environment/schema/journal.py +7 -2
- package/runtime/gatewaysdk/environment/schema/local.py +32 -7
- package/runtime/gatewaysdk/environment/schema/page_checks.py +123 -0
- package/runtime/gatewaysdk/environment/schema/platform.py +23 -267
- package/runtime/gatewaysdk/environment/schema/platform_templates.py +332 -0
- package/runtime/gatewaysdk/environment/schema/request_ledger.py +4 -1
- package/runtime/gatewaysdk/environment/schema/run_parameters.py +25 -0
- package/runtime/gatewaysdk/environment/schema/runtime.py +43 -5
- package/runtime/gatewaysdk/environment/schema/scaffold.py +367 -217
- package/runtime/gatewaysdk/environment/schema/session_files.py +13 -2
- package/runtime/gatewaysdk/environment/schema/skills/benchmarks-getting-started/SKILL.md +1 -1
- package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/SKILL.md +1 -2
- package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/SKILL.md +4 -2
- package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/SKILL.md +7 -7
- package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/cli-mcp-map.md +32 -2
- package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/gotchas.md +6 -6
- package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/journal-checks.md +17 -2
- package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/new-world-sandbox.md +1 -1
- package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/ui-map.md +3 -2
- package/runtime/gatewaysdk/environment/schema/slack.py +55 -10
- package/runtime/gatewaysdk/environment/schema/snapshot.py +28 -2
- package/runtime/gatewaysdk/environment/schema/tasks.py +25 -2
- package/runtime/gatewaysdk/environment/schema/template_record.py +131 -0
- package/runtime/gatewaysdk/environment/schema/tools_world.py +7 -5
- package/runtime/gatewaysdk/environment/schema/ui.py +54 -33
- package/runtime/gatewaysdk/environment/schema/ui_interactions.py +419 -0
- package/runtime/gatewaysdk/environment/schema/ui_recorder.js +895 -0
- package/runtime/gatewaysdk/environment/schema/ui_replay.py +366 -0
- package/runtime/gatewaysdk/environment/schema/ui_replay_record.LICENSE +25 -0
- package/runtime/gatewaysdk/environment/schema/ui_replay_record.js +109 -0
- package/runtime/gatewaysdk/environment/schema/validation.py +10 -1
- package/runtime/gatewaysdk/environment/schema/worker.py +5 -1
- package/runtime/gatewaysdk/environment/schema/workers.py +8 -1
- package/runtime/gatewaysdk/environment/schema/world_host.py +44 -15
- package/runtime/gatewaysdk/environment/secret_values.py +1 -1
- package/runtime/gatewaysdk/environment/world.py +34 -43
- package/runtime/gatewaysdk/environment/world_session_contract.py +7 -34
- package/skills/benchmarks-getting-started/SKILL.md +1 -1
- package/skills/connector-schema-authoring/SKILL.md +1 -2
- package/skills/connector-schema-authoring/connector-worlds.md +2 -2
- package/skills/connector-schema-authoring/world-schema.md +29 -23
- package/skills/world-data-ingestion/SKILL.md +4 -2
- package/skills/worlds-getting-started/SKILL.md +7 -7
- package/skills/worlds-getting-started/references/cli-mcp-map.md +32 -2
- package/skills/worlds-getting-started/references/gotchas.md +6 -6
- package/skills/worlds-getting-started/references/journal-checks.md +17 -2
- package/skills/worlds-getting-started/references/new-world-sandbox.md +1 -1
- package/skills/worlds-getting-started/references/ui-map.md +3 -2
- package/dist/media-BIApiPzS.d.mts +0 -102
- package/dist/media-BIApiPzS.d.ts +0 -102
package/dist/traces/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/worlds/platformEndpoint.ts","../../src/worlds/transport.ts","../../src/worlds/browserReconnect.ts","../../src/worlds/browser.ts","../../src/worlds/nativeComputer/actions.ts","../../src/worlds/nativeComputer/display.ts","../../src/worlds/nativeComputer/screen.ts","../../src/tracing/media.ts","../../src/worlds/nativeComputer/trace.ts","../../src/worlds/nativeComputer/base.ts","../../src/worlds/nativeComputer/keys.ts","../../src/worlds/nativeComputer/anthropic.ts","../../src/worlds/nativeComputer/openai.ts","../../src/worlds/nativeComputer/index.ts","../../src/worlds/sessionContract.ts","../../src/worlds/toolSchema.ts","../../src/worlds/requestLedger.ts","../../src/worlds/sessionReadiness.ts","../../src/tracing/session.ts","../../src/worlds/taskRef.ts","../../src/worlds/worldNotice.ts","../../src/worlds/grade.ts","../../src/worlds/session.ts","../../src/worlds/sessionList.ts","../../src/worlds/tasks.ts","../../src/worlds/taskGrades.ts","../../src/worlds/surfaceDescriptor.ts","../../src/worlds/taskSessions.ts","../../src/worlds/evals.ts","../../src/worlds/runSignals.ts","../../src/worlds/taskRunDir.ts","../../src/worlds/taskRunOutcome.ts","../../src/tracing/prerequisites.ts","../../src/worlds/taskTracing.ts","../../src/worlds/taskRun.ts","../../src/worlds/checkoutProvenance.ts","../../src/worlds/setRun.ts","../../src/worlds/requestLog.ts","../../src/worlds/webhooks.ts","../../src/worlds/checkoutTarget.ts","../../src/worlds/worldDir.ts","../../src/worlds/tar.ts","../../src/worlds/hub.ts","../../src/worlds/validate.ts","../../src/worlds/sandbox.ts","../../src/worlds/describe.ts","../../src/cli/platform/worldData/json.ts","../../src/worlds/transforms.ts","../../src/worlds/redaction.ts","../../src/worlds/query.ts","../../src/worlds/migrate.ts","../../src/worlds/ingest.ts","../../src/worlds/editSessions.ts","../../src/worlds/dryRun.ts","../../src/worlds/index.ts","../../src/traces/index.ts"],"sourcesContent":["import type { PlatformEndpoint } from \"./transport\";\n\nconst DEFAULT_HOST = \"https://withgateway.ai\";\n\nexport const GATEWAY_KEYS_MISSING =\n \"Gateway keys missing: set GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY (or pass publicKey/secretKey).\";\n\nexport function platformEndpoint(options: Partial<PlatformEndpoint>): PlatformEndpoint | null {\n const publicKey = options.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;\n const secretKey = options.secretKey ?? process.env.GATEWAY_SECRET_KEY;\n if (!publicKey || !secretKey) return null;\n const host = options.host ?? process.env.GATEWAY_HOST ?? DEFAULT_HOST;\n return { host: host.replace(/\\/+$/, \"\"), publicKey, secretKey };\n}\n\nexport function requirePlatformEndpoint(options: Partial<PlatformEndpoint>): PlatformEndpoint {\n const endpoint = platformEndpoint(options);\n if (!endpoint) throw new Error(GATEWAY_KEYS_MISSING);\n return endpoint;\n}\n","export const PLATFORM_TIMEOUT_ENV = \"GATEWAY_TIMEOUT_MS\";\n\n/** How long one platform request may go unanswered before it is abandoned; `GATEWAY_TIMEOUT_MS` overrides it. */\nexport const PLATFORM_TIMEOUT_DEFAULT_MS = 120_000;\n\nexport type PlatformEndpoint = { host: string; publicKey: string; secretKey: string };\n\nexport type PlatformMethod = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n\nexport type PlatformReply = { status: number; ok: boolean; text: string };\n\n/** The request budget in force: `GATEWAY_TIMEOUT_MS` when set, else the default. */\nexport function platformTimeoutMs(env: NodeJS.ProcessEnv = process.env): number {\n const raw = env[PLATFORM_TIMEOUT_ENV];\n if (raw === undefined || raw === \"\") return PLATFORM_TIMEOUT_DEFAULT_MS;\n const value = Number(raw);\n if (Number.isInteger(value) && value > 0) return value;\n throw new Error(`${PLATFORM_TIMEOUT_ENV} must be a positive whole number of milliseconds, not \\`${raw}\\`.`);\n}\n\nconst CHECK_HOST = \"Check GATEWAY_HOST (or --host) points at a running platform, then retry.\";\nconst RETRY = \"Retry; if it repeats, check the network between here and the platform.\";\nconst FETCH_LIMIT = {\n reason: \"Node's fetch stopped waiting after 300 s\",\n next: \"The platform may still be running it: check what it changed before you retry.\",\n};\n\nconst CAUSES: Record<string, { reason: string; next: string }> = {\n UND_ERR_HEADERS_TIMEOUT: FETCH_LIMIT,\n UND_ERR_BODY_TIMEOUT: FETCH_LIMIT,\n ECONNREFUSED: { reason: \"connection refused\", next: CHECK_HOST },\n ENOTFOUND: { reason: \"DNS lookup failed\", next: CHECK_HOST },\n EAI_AGAIN: { reason: \"DNS lookup failed\", next: CHECK_HOST },\n ETIMEDOUT: { reason: \"connect timed out\", next: CHECK_HOST },\n UND_ERR_CONNECT_TIMEOUT: { reason: \"connect timed out\", next: CHECK_HOST },\n EHOSTUNREACH: { reason: \"host unreachable\", next: CHECK_HOST },\n ENETUNREACH: { reason: \"network unreachable\", next: RETRY },\n ECONNRESET: { reason: \"connection dropped\", next: RETRY },\n UND_ERR_SOCKET: { reason: \"connection dropped\", next: RETRY },\n EPIPE: { reason: \"connection dropped\", next: RETRY },\n};\n\nconst UNKNOWN_CAUSE = { reason: \"network error\", next: CHECK_HOST };\n\n/** Why a request got no answer, from the socket-level error undici hides under `fetch failed`. */\nexport class TransportCause {\n private constructor(\n readonly reason: string,\n readonly detail: string | null,\n readonly next: string,\n ) {}\n\n static timeout(timeoutMs: number): TransportCause {\n return new TransportCause(\n `timed out after ${timeoutMs / 1000}s`,\n null,\n `Retry; if the platform is slow, raise ${PLATFORM_TIMEOUT_ENV} (milliseconds per request).`,\n );\n }\n\n static of(error: unknown): TransportCause {\n const cause = error instanceof Error && error.cause instanceof Error ? error.cause : undefined;\n const code = cause && \"code\" in cause && typeof cause.code === \"string\" ? cause.code : null;\n const message = cause?.message ?? (error instanceof Error ? error.message : String(error));\n const known = (code && CAUSES[code]) || UNKNOWN_CAUSE;\n return new TransportCause(known.reason, code ? `${code}: ${message}` : message, known.next);\n }\n\n describe(): string {\n return this.detail === null ? this.reason : `${this.reason} (${this.detail})`;\n }\n}\n\n/** A platform request that never got an answer: one line naming the request, the host, the cause and the next step. */\nexport class UnreachableError extends Error {\n constructor(\n readonly host: string,\n readonly method: string,\n readonly route: string,\n readonly failure: TransportCause,\n ) {\n super(`${method} ${route}: no answer from ${host}: ${failure.describe()}. ${failure.next}`);\n this.name = \"UnreachableError\";\n }\n}\n\nconst sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));\n\n/**\n * Another attempt after a gateway 5xx (502, 503, 504) or no answer at all, for a request whose repeat is harmless: a\n * keyed filing step, which the platform answers with the first filing. Every other request gets one attempt (`NONE`).\n */\nexport class RetryPolicy {\n static readonly NONE = new RetryPolicy([]);\n /** A platform restart or a short edge outage: no wait starts that would end past five minutes, so a step ends\n * within the budget plus one request timeout. */\n static readonly FILING = new RetryPolicy([250, 500, 1_000, 2_000, 4_000, 8_000, 16_000, 30_000], sleep, 300_000);\n static readonly TRANSIENT_STATUSES: ReadonlySet<number> = new Set([502, 503, 504]);\n\n constructor(\n readonly delaysMs: readonly number[],\n private readonly wait: (ms: number) => Promise<void> = sleep,\n readonly budgetMs: number = Number.POSITIVE_INFINITY,\n private readonly now: () => number = Date.now,\n ) {}\n\n async run(attempt: () => Promise<PlatformReply>): Promise<PlatformReply> {\n const started = this.now();\n for (let tries = 0; ; tries += 1) {\n const outcome = await Attempt.of(attempt);\n const delayMs = this.delaysMs[tries];\n const spent = delayMs === undefined || this.now() - started + delayMs >= this.budgetMs;\n if (!outcome.transient || spent) return outcome.settle();\n await this.wait(delayMs);\n }\n }\n}\n\nclass Attempt {\n private constructor(\n private readonly reply: PlatformReply | null,\n private readonly error: unknown,\n readonly transient: boolean,\n ) {}\n\n static async of(attempt: () => Promise<PlatformReply>): Promise<Attempt> {\n try {\n const reply = await attempt();\n return new Attempt(reply, null, RetryPolicy.TRANSIENT_STATUSES.has(reply.status));\n } catch (error) {\n return new Attempt(null, error, error instanceof UnreachableError);\n }\n }\n\n settle(): PlatformReply {\n if (this.reply) return this.reply;\n throw this.error;\n }\n}\n\n/** The one door every CLI and SDK request to the platform goes through: Basic auth with the project key, a per-request timeout, and a transport failure turned into an `UnreachableError`. */\nexport class PlatformTransport {\n constructor(\n private readonly endpoint: PlatformEndpoint,\n private readonly timeoutMs: number = platformTimeoutMs(),\n ) {}\n\n /** A request that legitimately takes longer (a sandbox exec, a world create) waits its own budget; every other one waits the default. */\n budget(ownMs?: number): number {\n return Math.max(ownMs ?? 0, this.timeoutMs);\n }\n\n async send(\n method: PlatformMethod,\n route: string,\n body?: unknown,\n opts: { timeoutMs?: number; retry?: RetryPolicy } = {},\n ): Promise<PlatformReply> {\n const timeoutMs = this.budget(opts.timeoutMs);\n return (opts.retry ?? RetryPolicy.NONE).run(() => this.once(method, route, body, timeoutMs));\n }\n\n private async once(method: PlatformMethod, route: string, body: unknown, timeoutMs: number): Promise<PlatformReply> {\n const payload = body === undefined ? {} : { body: JSON.stringify(body) };\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n try {\n const res = await fetch(`${this.endpoint.host}${route}`, {\n method,\n headers: {\n \"content-type\": \"application/json\",\n accept: \"application/json\",\n authorization:\n \"Basic \" + Buffer.from(`${this.endpoint.publicKey}:${this.endpoint.secretKey}`).toString(\"base64\"),\n },\n ...payload,\n signal: controller.signal,\n });\n return { status: res.status, ok: res.ok, text: await res.text() };\n } catch (error) {\n const cause = controller.signal.aborted ? TransportCause.timeout(timeoutMs) : TransportCause.of(error);\n throw new UnreachableError(this.endpoint.host, method, route, cause);\n } finally {\n clearTimeout(timer);\n }\n }\n}\n","import type { BrowserPage, PlaywrightBrowserLike } from \"./browser\";\n\n/**\n * A HOSTED BROWSER THAT COMES BACK. A World Host session's browser is a pool\n * pod; on the `standard` tier it runs on spot capacity and can be reclaimed\n * with two minutes' notice. The browser dies, the world does not, and the\n * platform can put a new browser behind the SAME `surfaces.browser.wsUrl`.\n *\n * `BrowserReconnector` is the client half of that repair: on a lost\n * connection it asks the platform to repair (`POST .../browser-repair`),\n * waits while a browser starts, reconnects to the same address and hands the\n * new connection to its owner to restore the page. It knows nothing of HTTP\n * or Playwright — both come in as collaborators, so tests drive it with\n * fakes. Twin of `gatewaysdk/world_browser_reconnect.py`, call for call.\n */\n\n/** What the platform answers a repair with. `healthy`: the browser is alive,\n * reconnect now. `replaced`: a new, blank browser; reconnect and reopen the\n * page. `starting`: a browser is coming up; ask again in `retryAfterMs`. */\nexport type RepairAnswer = {\n outcome: \"healthy\" | \"replaced\" | \"starting\";\n retryAfterMs: number | null;\n};\n\ntype BrowserContextLike = Awaited<\n ReturnType<PlaywrightBrowserLike[\"newContext\"]>\n>;\n\n/** One live attachment to the session's browser. */\nexport type BrowserConnection = {\n browser: PlaywrightBrowserLike;\n context: BrowserContextLike;\n page: BrowserPage;\n};\n\nexport async function closeConnection(c: BrowserConnection): Promise<void> {\n await c.context.close();\n await c.browser.close();\n}\n\n/** Close a connection whose browser is already gone: it only frees the\n * handle, so a failure is ignored. */\nexport async function releaseConnection(c: BrowserConnection): Promise<void> {\n await closeConnection(c).catch(() => undefined);\n}\n\nexport const RECOVER_BUDGET_MS = 90_000;\nconst BACKOFF_BASE_MS = 1_000;\nconst BACKOFF_CAP_MS = 5_000;\n\n/** What Playwright says when the browser or its connection is gone, as\n * opposed to an action that failed on a live page. Matched case-insensitively\n * against the error message; nothing else triggers a reconnect. */\nexport const BROWSER_GONE_PATTERNS: readonly RegExp[] = [\n /target page, context or browser has been closed/i,\n /\\bbrowser has been (closed|disconnected)\\b/i,\n /\\bbrowser (has )?disconnected\\b/i,\n /\\btarget closed\\b/i,\n /\\bwebsocket is not open\\b/i,\n /\\bconnection closed\\b/i,\n];\n\n/** A failed page load (`net::ERR_INTERNET_DISCONNECTED`,\n * `net::ERR_CONNECTION_CLOSED`) is the world UI's network, not the browser:\n * the browser is alive, and repairing it would throw away a live page. */\nconst PAGE_NETWORK_ERROR = /net::ERR_/i;\n\nexport function isBrowserGone(error: unknown): boolean {\n const message = error instanceof Error ? error.message : String(error);\n if (PAGE_NETWORK_ERROR.test(message)) return false;\n return BROWSER_GONE_PATTERNS.some((p) => p.test(message));\n}\n\nconst REDACTED = \"<redacted>\";\nconst TOKEN_QUERY_VALUE = /([?&]token=)[^&#\\s\"')]*/gi;\n\n/**\n * Takes a session's credentials out of text that leaves the process — an\n * error recorded into the browser timeline, a recovery's reason. A browser\n * error quotes the URL it failed on, and those URLs carry the session: the\n * hosted browser's `wsUrl` (its path is the credential), the UI's token, and\n * any `?token=` a landing URL presents. Each becomes `<redacted>`.\n */\nexport class SecretScrubber {\n private readonly secrets: string[];\n\n constructor(secrets: readonly (string | null | undefined)[]) {\n const known = secrets.filter((s): s is string => Boolean(s));\n // Longest first, so a wsUrl goes whole before a token inside it.\n this.secrets = [\n ...new Set([...known, ...known.map((s) => encodeURIComponent(s))]),\n ].sort((a, b) => b.length - a.length);\n }\n\n scrub(text: string): string {\n const bare = this.secrets.reduce(\n (out, secret) => out.split(secret).join(REDACTED),\n text,\n );\n return bare.replace(TOKEN_QUERY_VALUE, `$1${REDACTED}`);\n }\n}\n\n/** A mutating action (click, type, press, back, scroll) lost its browser.\n * The browser was repaired and the page reopened at `restoredUrl`, but the\n * action is NOT replayed: its input may already have reached the world.\n * `cause` is the error the action failed with. */\nexport class BrowserReconnected extends Error {\n constructor(\n readonly outcome: RecoveryResult[\"outcome\"],\n readonly restoredUrl: string | null,\n cause: unknown,\n ) {\n super(\n `the browser was lost mid-action and reconnected (${outcome}); ` +\n (restoredUrl\n ? `the page was reopened at ${restoredUrl}. `\n : \"it is on a blank page. \") +\n \"The action may or may not have taken effect — look at the page before acting again.\",\n { cause },\n );\n this.name = \"BrowserReconnected\";\n }\n}\n\n/** The session's browser stayed gone for the whole budget. `cause` is the\n * error the action first failed with. */\nexport class BrowserUnrecoverable extends Error {\n constructor(message: string, cause: unknown) {\n super(message, { cause });\n this.name = \"BrowserUnrecoverable\";\n }\n}\n\n/** A repair refusal worth waiting out: no answer at all (the network), the\n * platform's own failure, or a full pool. Anything else (a 404 for a session\n * that is not open with a browser) ends the recovery. */\nfunction refusalIsTransient(error: unknown): boolean {\n const { status, code } = error as { status?: unknown; code?: unknown };\n if (typeof status !== \"number\") return true;\n if (status >= 500) return true;\n return status === 400 && code === \"browser_capacity\";\n}\n\nfunction describe(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\ntype Step =\n | { kind: \"recovered\"; outcome: RecoveryResult[\"outcome\"] }\n | { kind: \"stop\" }\n | { kind: \"wait\"; reason: string; waitMs: number | null };\n\nexport type RecoveryResult = {\n outcome: \"healthy\" | \"replaced\";\n attempts: number;\n};\n\nexport class BrowserReconnector {\n private readonly sleep: (ms: number) => Promise<void>;\n private readonly now: () => number;\n private readonly scrub: (text: string) => string;\n readonly budgetMs: number;\n\n constructor(\n private readonly repair: () => Promise<RepairAnswer>,\n private readonly connect: () => Promise<BrowserConnection>,\n opts: {\n sleep?: (ms: number) => Promise<void>;\n now?: () => number;\n budgetMs?: number;\n /** Takes credentials out of a reason before it is thrown. */\n scrub?: (text: string) => string;\n } = {},\n ) {\n this.sleep =\n opts.sleep ?? ((ms) => new Promise<void>((r) => setTimeout(r, ms)));\n this.now = opts.now ?? Date.now;\n this.budgetMs = opts.budgetMs ?? RECOVER_BUDGET_MS;\n this.scrub = opts.scrub ?? ((text) => text);\n }\n\n /**\n * Repair, reconnect and `restore` until it works or the budget runs out.\n * `restore` receives each new connection (the owner adopts it and reopens\n * its page); a restore that fails counts as a failed reconnect, because the\n * browser may have died again. A repair the platform refuses for good\n * rethrows `cause` untouched.\n */\n async recover(\n cause: unknown,\n restore: (connection: BrowserConnection) => Promise<void>,\n ): Promise<RecoveryResult> {\n const deadline = this.now() + this.budgetMs;\n let reason = describe(cause);\n for (let attempt = 1; ; attempt++) {\n const step = await this.attempt(restore);\n if (step.kind === \"recovered\")\n return { outcome: step.outcome, attempts: attempt };\n if (step.kind === \"stop\") throw cause;\n reason = step.reason;\n const remaining = deadline - this.now();\n if (remaining <= 0) break;\n const backoff = Math.min(\n BACKOFF_BASE_MS * 2 ** (attempt - 1),\n BACKOFF_CAP_MS,\n );\n await this.sleep(Math.min(step.waitMs ?? backoff, remaining));\n }\n throw new BrowserUnrecoverable(\n `the session's browser could not be recovered within ${Math.round(this.budgetMs / 1000)}s: ${this.scrub(reason)}`,\n cause,\n );\n }\n\n private async attempt(\n restore: (connection: BrowserConnection) => Promise<void>,\n ): Promise<Step> {\n let answer: RepairAnswer;\n try {\n answer = await this.repair();\n } catch (error) {\n if (!refusalIsTransient(error)) return { kind: \"stop\" };\n return {\n kind: \"wait\",\n reason: `repair failed: ${describe(error)}`,\n waitMs: null,\n };\n }\n const outcome = answer.outcome;\n if (outcome === \"starting\")\n return {\n kind: \"wait\",\n reason: \"a new browser is still starting\",\n waitMs: answer.retryAfterMs,\n };\n try {\n await restore(await this.connect());\n } catch (error) {\n return {\n kind: \"wait\",\n reason: `reconnect failed: ${describe(error)}`,\n waitMs: null,\n };\n }\n return { kind: \"recovered\", outcome };\n }\n}\n","import { schemaFromSignature, type WorldToolkit } from \"./session\";\nimport {\n BrowserReconnected,\n BrowserReconnector,\n SecretScrubber,\n closeConnection,\n isBrowserGone,\n releaseConnection,\n type BrowserConnection,\n type RecoveryResult,\n type RepairAnswer,\n} from \"./browserReconnect\";\n\n/**\n * A BROWSER ON A WORLD'S UI — the computer-use half of a live session.\n *\n * A session answers on SURFACES. `tools` is always there (the world's own\n * operations over the rendezvous). An api-type world may also answer on\n * `api` (the service itself), `ui` (its dashboard, over the same state) and\n * `browser` — a headless Chromium the platform runs NEXT TO that UI, which\n * an agent drives through Playwright. This file is the TS client for the\n * last two, call for call with `gatewaysdk/world_browser.py`.\n *\n * const s = await openSession(\"payments-like\", \"refund-dispute\", {\n * surfaces: [\"ui\", \"browser\"],\n * });\n * await s.ready();\n * const b = await s.browser(); // hosted, next to the world\n * await b.goto(); // the UI's entry page\n * await b.click(\"text=Refund\");\n * const tools = computerUseToolkit(b); // the same actions as model tools\n * await b.close();\n *\n * Playwright is an OPTIONAL peer: nothing here imports it until a browser is\n * opened, so sessions that never touch a UI never load it.\n *\n * MODES. `hosted` connects to the session's own browser (a Playwright server\n * the pod exposes over an authenticated websocket). `local` launches Chromium\n * on this machine and points it at the UI — a laptop against a hosted twin,\n * or a test. `auto` prefers hosted. Asking for a mode the session cannot\n * serve throws `WorldSurfaceUnavailable`; there is no silent fallback to a\n * browser other than the one the episode is judged on.\n *\n * OBSERVABILITY. Every action a `WorldBrowser` takes (goto, click, type,\n * press, scroll, back) is reported to the platform as one event — what was\n * done, whether it worked, where the page ended up, and a JPEG of the screen\n * after — through a `BrowserActionRecorder`. Reporting is fire-and-forget\n * and never fails the action; the platform renders it as the session's\n * browser timeline. Text typed into secret-looking fields is redacted before\n * it leaves the process.\n *\n * RECONNECT. A World Host browser on the `standard` tier can be reclaimed\n * mid-session. When an action fails because the browser or its connection is\n * gone, a hosted `cdp` browser asks the platform to repair it, reconnects to\n * the same address and reopens the page it was on (see `browserReconnect.ts`).\n * A read or a `goto` then runs once more; a click, type, press, back or scroll\n * is NOT replayed — its input may already have reached the world — and throws\n * `BrowserReconnected` so the agent looks at the page again. Local and\n * `playwright`-protocol browsers never reconnect.\n */\n\nexport const SURFACE_KINDS = [\"tools\", \"api\", \"ui\", \"browser\"] as const;\nexport type WorldSurfaceKind = (typeof SURFACE_KINDS)[number];\n\n/** The platform's own header for a session's token, which a World Host takes on\n * every world whatever its vendor's auth; no vendor's client sends it. */\nexport const PLATFORM_SESSION_HEADER = \"X-World-Session\";\n\nexport const SESSION_AUTH_MODES = [\"vendor\", \"open\"] as const;\n/** `open`: the session asks for no credential, reached on its capability\n * hostname alone; `vendor`: the session's token, the way the world's `[auth]`\n * says its vendor takes a key. Unset, the world's `[auth] mode`. */\nexport type SessionAuthMode = (typeof SESSION_AUTH_MODES)[number];\n\nexport function assertSessionAuthMode(value: unknown): asserts value is SessionAuthMode {\n if ((SESSION_AUTH_MODES as readonly unknown[]).includes(value)) return;\n throw new Error(\n `Unknown session auth: ${String(value)}; choose from ${SESSION_AUTH_MODES.join(\", \")}`,\n );\n}\n\n/** Capacity behind a World Host session's browser. `standard` runs on spot\n * capacity first (about half the price) and may be reclaimed with two\n * minutes' notice, ending the browser but never the world; `premium` is\n * on-demand and never spot-reclaimed. Unset, the organization's default applies. */\nexport const BROWSER_TIERS = [\"standard\", \"premium\"] as const;\nexport type BrowserTier = (typeof BROWSER_TIERS)[number];\n\n/** Refuse a tier the platform does not know, before any request is sent. */\nexport function assertBrowserTier(value: unknown): asserts value is BrowserTier {\n if ((BROWSER_TIERS as readonly unknown[]).includes(value)) return;\n throw new Error(\n `Unknown browser tier: ${String(value)}; choose from ${BROWSER_TIERS.join(\", \")}`,\n );\n}\n\nexport const DEFAULT_VIEWPORT = { width: 1280, height: 800 };\nconst SETTLE_TIMEOUT_MS = 5_000;\nconst SETTLE_QUIET_MS = 150;\nconst SETTLE_POLL_MS = 25;\n\nexport const EVENT_BATCH_SIZE = 10;\nexport const EVENT_FLUSH_INTERVAL_MS = 1_000;\nexport const EVENT_MAX_RETRIES = 3;\nconst EVENT_SCREENSHOT_QUALITY = 60;\nconst EVENT_MAX_STRING = 500;\n\nexport const SECRET_KEY =\n /pass(word|wd)?|secret|token|api[-_]?key|authorization|cookie|(^|[-_ #.\\[\"'=])(otp|pin|cvv|ssn)([-_ \\]\"']|$)/i;\n/** What a call that lost its browser does once the browser is back: a read or\n * a navigation runs again (`retry`); an action that may already have reached\n * the world is not replayed, and the agent is told (`report`). */\ntype OnBrowserLoss = \"retry\" | \"report\";\n\nconst SECRET_VALUE =\n /^((sk|pk|ghp|xox[abp])[-_][-_A-Za-z0-9]{8,}|AKIA[0-9A-Z]{12,}|Bearer [-_.A-Za-z0-9]{8,})/;\n\n/** The `surfaces` block of a session descriptor, as the platform sends it. */\nexport type SessionSurfaces = {\n tools: { kind: \"rendezvous\" };\n api?: {\n url: string;\n /** Per-session credential of a World Host session: send it in the\n * platform's `X-World-Session` header (`apiHeaders()`), or the way the\n * world's `[auth]` says its vendor takes a key. Absent when the world\n * itself answers with its declared auth (a pod or a customer-hosted twin),\n * and for an open session, whose url is its secret. */\n token?: string;\n /** `open`: `url` is the session's capability hostname; send no credential. */\n auth?: \"open\";\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 and\n * open sessions. */\n token?: string;\n auth?: \"open\";\n };\n browser?: {\n wsUrl: string;\n /** `cdp`: the platform's Chromium relay (any number of agents share one\n * browser, each in its own context). `playwright`: a `run-server` endpoint. */\n protocol: \"cdp\" | \"playwright\";\n viewport: { width: number; height: number };\n /** The capacity tier the browser runs on; present for World Host sessions. */\n tier?: BrowserTier;\n };\n};\n\nexport class WorldSurfaceUnavailable extends Error {\n constructor(\n readonly surface: WorldSurfaceKind,\n reason: string,\n ) {\n super(`World surface '${surface}' is unavailable: ${reason}`);\n }\n}\n\nexport function surfaceKinds(s: SessionSurfaces): WorldSurfaceKind[] {\n const kinds: WorldSurfaceKind[] = [\"tools\"];\n if (s.api) kinds.push(\"api\");\n if (s.ui) kinds.push(\"ui\");\n if (s.browser) kinds.push(\"browser\");\n return kinds;\n}\n\nconst UI_TOKEN_QUERY = \"token\";\n\n/** The URL of `path` on a UI surface, carrying the session token when the\n * surface has one. `path` may already have a query string; the token is\n * appended to it. */\nexport function uiUrl(\n ui: NonNullable<SessionSurfaces[\"ui\"]>,\n path: string,\n): string {\n const base = ui.url.replace(/\\/+$/, \"\");\n const rel = path.startsWith(\"/\") ? path : `/${path}`;\n if (!ui.token) return base + rel;\n const [beforeHash, hash] = splitHash(rel);\n const joiner = beforeHash.includes(\"?\") ? \"&\" : \"?\";\n const query = `${UI_TOKEN_QUERY}=${encodeURIComponent(ui.token)}`;\n return base + beforeHash + joiner + query + hash;\n}\n\nexport function uiEntryUrl(ui: NonNullable<SessionSurfaces[\"ui\"]>): string {\n return uiUrl(ui, ui.entry || \"/\");\n}\n\n/** `url` without its `token` query parameter: what may be logged or shown. */\nexport function withoutUiToken(url: string): string {\n const [beforeHash, hash] = splitHash(url);\n const q = beforeHash.indexOf(\"?\");\n if (q < 0) return url;\n const kept = beforeHash\n .slice(q + 1)\n .split(\"&\")\n .filter((pair) => pair !== \"\" && pair.split(\"=\")[0] !== UI_TOKEN_QUERY);\n return (\n beforeHash.slice(0, q) + (kept.length ? `?${kept.join(\"&\")}` : \"\") + hash\n );\n}\n\nfunction splitHash(url: string): [string, string] {\n const h = url.indexOf(\"#\");\n return h < 0 ? [url, \"\"] : [url.slice(0, h), url.slice(h)];\n}\n\n/** The slice of a Playwright `Page` this module drives. */\nexport type BrowserPage = {\n url(): string;\n goto(url: string, opts?: { waitUntil?: \"load\" }): Promise<unknown>;\n click(selector: string): Promise<void>;\n fill(selector: string, value: string): Promise<void>;\n screenshot(opts?: {\n type?: \"png\" | \"jpeg\";\n quality?: number;\n fullPage?: boolean;\n }): Promise<Buffer>;\n innerText(selector: string): Promise<string>;\n content(): Promise<string>;\n goBack(opts?: { waitUntil?: \"load\" }): Promise<unknown>;\n waitForLoadState(state?: \"load\"): Promise<void>;\n waitForTimeout(ms: number): Promise<void>;\n on(\n event: \"request\" | \"requestfinished\" | \"requestfailed\",\n handler: (request: unknown) => void,\n ): unknown;\n title(): Promise<string>;\n keyboard: { press(key: string): Promise<void> };\n mouse: { wheel(dx: number, dy: number): Promise<void> };\n};\n\nexport type BrowserMode = \"auto\" | \"hosted\" | \"local\";\n\n/** 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. */\nconst CAPABILITY_HOST = /^o-[a-z0-9]+-([a-z2-7]{26})(?:-api)?\\./;\n\n/** The secret label of an open session's capability hostname in `url`\n * (`o-<sid>-<label>[-api].<domain>`), else null: a credential, scrubbed from\n * everything a browser records. Twin of the Python `capability_label`. */\nexport function capabilityLabel(url: string | null | undefined): string | null {\n let host = \"\";\n try {\n host = url ? new URL(url).hostname : \"\";\n } catch {\n return null;\n }\n return CAPABILITY_HOST.exec(host)?.[1] ?? null;\n}\n\nexport function redactActionArgs(\n action: string,\n args: Record<string, unknown>,\n): Record<string, unknown> {\n const secretField =\n action === \"browser_type\" && SECRET_KEY.test(String(args.selector ?? \"\"));\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(args)) {\n if (value === null || value === undefined) out[key] = null;\n else if (typeof value === \"boolean\" || typeof value === \"number\")\n out[key] = value;\n else if (typeof value === \"string\") {\n if (\n SECRET_KEY.test(key) ||\n SECRET_VALUE.test(value) ||\n (secretField && key === \"text\")\n )\n out[key] = \"[redacted]\";\n else\n out[key] =\n value.length <= EVENT_MAX_STRING\n ? value\n : value.slice(0, EVENT_MAX_STRING) + \"…\";\n } else out[key] = \"[omitted]\";\n }\n return out;\n}\n\n/**\n * Ships browser action events to the platform, off the action's hot path.\n *\n * `post` receives a batch of events (the request body's `events`). Events\n * are numbered here, so ordering survives batching and retries — the\n * platform dedups on `(agentId, seq)`. A batch that keeps failing is dropped\n * with a warning: telemetry must never stall or fail the agent.\n *\n * Numbering is durable across recorders: `nextSeq()` hands out a position\n * within this recorder, and the first send adds the base `resumeFrom`\n * reports — the platform's next free seq for this agent — so an agent id\n * reopened in a later process appends to its timeline instead of colliding\n * with (and being deduplicated against) what it already recorded. The base\n * is fixed once resolved, which keeps retries idempotent.\n */\nexport class BrowserActionRecorder {\n private seq = 0;\n private base: Promise<number> | null = null;\n private queue: BrowserActionEvent[] = [];\n private timer: ReturnType<typeof setTimeout> | null = null;\n private inflight: Promise<void> = Promise.resolve();\n sent = 0;\n dropped = 0;\n\n constructor(\n private readonly post: (events: BrowserActionEvent[]) => Promise<void>,\n readonly agentId: string,\n private readonly opts: {\n /** The platform's next free seq for `agentId`; 0 when not given. */\n resumeFrom?: () => Promise<number>;\n batchSize?: number;\n flushIntervalMs?: number;\n maxRetries?: number;\n sleep?: (ms: number) => Promise<void>;\n warn?: (message: string) => void;\n } = {},\n ) {}\n\n /** This recorder's next position; the wire seq is `resumeFrom() + this`. */\n nextSeq(): number {\n return this.seq++;\n }\n\n private resolveBase(): Promise<number> {\n if (this.base === null) {\n const resolve = this.opts.resumeFrom ?? (async () => 0);\n this.base = resolve().then((n) => {\n if (!Number.isInteger(n) || n < 0)\n throw new Error(\n `browser event base seq must be a non-negative integer, got ${String(n)}`,\n );\n return n;\n });\n // A failed lookup is retried with the batch, not remembered.\n this.base.catch(() => {\n this.base = null;\n });\n }\n return this.base;\n }\n\n record(event: BrowserActionEvent): void {\n this.queue.push(event);\n if (this.queue.length >= (this.opts.batchSize ?? EVENT_BATCH_SIZE)) {\n this.drain();\n } else if (this.timer === null) {\n this.timer = setTimeout(\n () => this.drain(),\n this.opts.flushIntervalMs ?? EVENT_FLUSH_INTERVAL_MS,\n );\n if (typeof this.timer === \"object\" && \"unref\" in this.timer)\n this.timer.unref();\n }\n }\n\n /** Resolve once everything recorded so far has been posted (or dropped). */\n async flush(): Promise<void> {\n this.drain();\n await this.inflight;\n }\n\n async close(): Promise<void> {\n await this.flush();\n }\n\n private drain(): void {\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n if (this.queue.length === 0) return;\n const batch = this.queue;\n this.queue = [];\n this.inflight = this.inflight.then(() => this.send(batch));\n }\n\n private async send(batch: BrowserActionEvent[]): Promise<void> {\n const retries = this.opts.maxRetries ?? EVENT_MAX_RETRIES;\n const sleep =\n this.opts.sleep ??\n ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));\n for (let attempt = 0; attempt < retries; attempt++) {\n try {\n const base = await this.resolveBase();\n await this.post(\n base === 0 ? batch : batch.map((e) => ({ ...e, seq: base + e.seq })),\n );\n this.sent += batch.length;\n return;\n } catch (error) {\n if (attempt + 1 === retries) {\n this.dropped += batch.length;\n (this.opts.warn ?? console.warn)(\n `dropping ${batch.length} browser events after ${attempt + 1} attempts: ${String(error)}`,\n );\n return;\n }\n await sleep(500 * 2 ** attempt);\n }\n }\n }\n}\n\n/**\n * One Playwright page on the session's UI. Thin on purpose — `page` is the\n * real Playwright page for anything this wrapper does not cover.\n */\nexport class WorldBrowser {\n private current: BrowserPage;\n private inflight = 0;\n private lastNetwork = Date.now();\n /** Where the page last was after an action, token stripped: what a\n * reconnect reopens. Null until the page has left `about:blank`. */\n private lastUrl: string | null = null;\n\n constructor(\n page: BrowserPage,\n readonly ui: SessionSurfaces[\"ui\"] | undefined,\n readonly mode: Exclude<BrowserMode, \"auto\">,\n private readonly teardown: () => Promise<void>,\n readonly viewport: { width: number; height: number } = DEFAULT_VIEWPORT,\n readonly recorder: BrowserActionRecorder | null = null,\n private readonly reconnector: BrowserReconnector | null = null,\n /** Takes session credentials out of every error this browser records. */\n private readonly scrubber: SecretScrubber = new SecretScrubber([\n ui?.token,\n capabilityLabel(ui?.url),\n ]),\n ) {\n this.current = page;\n this.watchNetwork(page);\n }\n\n /** The live Playwright page; a new object after a reconnect. */\n get page(): BrowserPage {\n return this.current;\n }\n\n get agentId(): string | null {\n return this.recorder?.agentId ?? null;\n }\n\n /** `text` with this session's credentials (UI token, browser address) removed. */\n scrub(text: string): string {\n return this.scrubber.scrub(text);\n }\n\n private watchNetwork(page: BrowserPage): void {\n page.on(\"request\", () => {\n this.inflight += 1;\n this.lastNetwork = Date.now();\n });\n const done = () => {\n this.inflight = Math.max(0, this.inflight - 1);\n this.lastNetwork = Date.now();\n };\n page.on(\"requestfinished\", done);\n page.on(\"requestfailed\", done);\n }\n\n /** Run `fn` against the page. If it fails because the browser is gone,\n * recover; then `retry` runs it ONCE more and `report` throws\n * `BrowserReconnected` instead of replaying it. Any other error, and a\n * second loss during the retry, propagate unchanged. */\n private async resilient<T>(\n fn: () => Promise<T>,\n onLoss: OnBrowserLoss,\n ): Promise<T> {\n try {\n return this.remember(await fn());\n } catch (error) {\n if (!this.reconnector || !isBrowserGone(error)) throw error;\n const recovered = await this.recover(this.reconnector, error);\n if (onLoss === \"report\")\n throw new BrowserReconnected(\n recovered.outcome,\n recovered.restoredUrl,\n error,\n );\n }\n return this.remember(await fn());\n }\n\n private remember<T>(result: T): T {\n this.lastUrl = this.openedUrl() ?? this.lastUrl;\n return result;\n }\n\n /** The page's URL less its token; null while it is blank. */\n private openedUrl(): string | null {\n const url = this.page.url();\n return url && url !== \"about:blank\" ? withoutUiToken(url) : null;\n }\n\n private async recover(\n reconnector: BrowserReconnector,\n cause: unknown,\n ): Promise<RecoveryResult & { restoredUrl: string | null }> {\n const started = Date.now();\n const message = cause instanceof Error ? cause.message : String(cause);\n const args = { cause: this.scrubber.scrub(message).slice(0, 200) };\n let result: RecoveryResult;\n try {\n result = await reconnector.recover(cause, (c) => this.adopt(c));\n } catch (error) {\n await this.report(\"browser_reconnect\", args, started, error);\n throw error;\n }\n const restoredUrl = this.openedUrl();\n await this.report(\n \"browser_reconnect\",\n { ...args, ...result, restoredUrl },\n started,\n null,\n );\n return { ...result, restoredUrl };\n }\n\n /** Take over a new connection's page and reopen the page the agent was on\n * (`openBrowser` owns the connection itself). A new browser has no session\n * cookie, so a World Host UI is first loaded with its token, exactly as\n * `goto()` loads the entry page. */\n private async adopt(connection: BrowserConnection): Promise<void> {\n this.current = connection.page;\n this.inflight = 0;\n this.watchNetwork(connection.page);\n const last = this.lastUrl;\n if (!last) return;\n if (this.ui?.token)\n await this.page.goto(uiEntryUrl(this.ui), { waitUntil: \"load\" });\n if (withoutUiToken(this.page.url()) !== last)\n await this.page.goto(last, { waitUntil: \"load\" });\n await this.settle();\n }\n\n /** Run one action and report it: the event carries what was asked,\n * whether it worked, and the screen after — for failures too, so a\n * reviewer sees what the agent saw when the selector did not match. */\n async act<T>(\n action: string,\n args: Record<string, unknown>,\n fn: () => Promise<T>,\n onLoss: OnBrowserLoss = \"report\",\n ): Promise<T> {\n const started = Date.now();\n try {\n const result = await this.resilient(fn, onLoss);\n await this.report(action, args, started, null);\n return result;\n } catch (error) {\n await this.report(action, args, started, error);\n throw error;\n }\n }\n\n /** One event on the recorder, if there is one; `failure` null means ok. */\n private async report(\n action: string,\n args: Record<string, unknown>,\n started: number,\n failure: unknown,\n ): Promise<void> {\n const recorder = this.recorder;\n if (!recorder) return;\n const error =\n failure === null\n ? null\n : this.scrubber\n .scrub(\n failure instanceof Error\n ? `${failure.name}: ${failure.message}`\n : String(failure),\n )\n .slice(0, 4000);\n recorder.record({\n agentId: recorder.agentId,\n seq: recorder.nextSeq(),\n ts: new Date().toISOString(),\n action,\n args: redactActionArgs(\n action,\n Object.fromEntries(\n Object.entries(args).map(([key, value]) => [\n key,\n typeof value === \"string\" ? this.scrubber.scrub(value) : value,\n ]),\n ),\n ),\n ok: failure === null,\n error,\n durationMs: Date.now() - started,\n mode: this.mode,\n viewport: { ...this.viewport },\n ...(await this.observeForEvent()),\n });\n }\n\n private async observeForEvent(): Promise<\n Pick<BrowserActionEvent, \"url\" | \"title\" | \"screenshot\">\n > {\n const out: Pick<BrowserActionEvent, \"url\" | \"title\" | \"screenshot\"> = {\n url: null,\n title: null,\n screenshot: null,\n };\n try {\n out.url = this.scrubber.scrub(this.page.url());\n out.title = this.scrubber.scrub(await this.page.title());\n const jpeg = await this.page.screenshot({\n type: \"jpeg\",\n quality: EVENT_SCREENSHOT_QUALITY,\n });\n out.screenshot = jpeg.toString(\"base64\");\n } catch {\n // a closed page still gets its event\n }\n return out;\n }\n\n /** Open a UI path (`/customers`), a full URL, or — with no argument — the\n * UI's declared entry page. */\n async goto(pathOrUrl?: string): Promise<string> {\n let target: string;\n if (pathOrUrl === undefined) {\n if (!this.ui)\n throw new WorldSurfaceUnavailable(\n \"ui\",\n \"this session has no UI to navigate to\",\n );\n target = uiEntryUrl(this.ui);\n } else if (/^https?:\\/\\//.test(pathOrUrl)) {\n target = pathOrUrl;\n } else {\n if (!this.ui)\n throw new WorldSurfaceUnavailable(\n \"ui\",\n \"relative paths need a UI surface\",\n );\n target = uiUrl(this.ui, pathOrUrl);\n }\n return this.act(\n \"browser_goto\",\n { path: pathOrUrl ?? null, url: withoutUiToken(target) },\n async () => {\n await this.page.goto(target, { waitUntil: \"load\" });\n await this.settle();\n return this.page.url();\n },\n // Navigating again lands on the same page: safe to replay.\n \"retry\",\n );\n }\n\n async back(): Promise<string> {\n return this.act(\"browser_back\", {}, async () => {\n await this.page.goBack({ waitUntil: \"load\" });\n await this.settle();\n return this.page.url();\n });\n }\n\n /** Wait for the page to finish reacting to an action. `load` alone is not\n * enough for client-rendered UIs (React et al.): a click returns before the\n * fetch that re-renders the page, so an agent would read stale text.\n * Playwright's `networkidle` is per navigation and resolves at once after\n * the first one, so this tracks requests itself: done when nothing is in\n * flight and the network has been quiet for `SETTLE_QUIET_MS`, bounded so\n * long-polling UIs cannot hang us. */\n async settle(): Promise<void> {\n await this.page.waitForLoadState(\"load\");\n const deadline = Date.now() + SETTLE_TIMEOUT_MS;\n while (Date.now() < deadline) {\n const quiet = Date.now() - this.lastNetwork >= SETTLE_QUIET_MS;\n if (this.inflight === 0 && quiet) return;\n await this.page.waitForTimeout(SETTLE_POLL_MS);\n }\n }\n\n async click(selector: string): Promise<void> {\n await this.act(\"browser_click\", { selector }, async () => {\n await this.page.click(selector);\n await this.settle();\n });\n }\n\n async type(selector: string, text: string): Promise<void> {\n await this.act(\"browser_type\", { selector, text }, () =>\n this.page.fill(selector, text),\n );\n }\n\n async press(key: string): Promise<void> {\n await this.act(\"browser_press\", { key }, async () => {\n await this.page.keyboard.press(key);\n await this.settle();\n });\n }\n\n async scroll(dy: number): Promise<void> {\n await this.act(\"browser_scroll\", { dy }, () =>\n this.page.mouse.wheel(0, dy),\n );\n }\n\n async screenshot(fullPage = false): Promise<Buffer> {\n return this.resilient(\n () => this.page.screenshot({ type: \"png\", fullPage }),\n \"retry\",\n );\n }\n\n async screenshotBase64(fullPage = false): Promise<string> {\n return (await this.screenshot(fullPage)).toString(\"base64\");\n }\n\n async text(selector = \"body\"): Promise<string> {\n return this.resilient(() => this.page.innerText(selector), \"retry\");\n }\n\n async html(): Promise<string> {\n return this.resilient(() => this.page.content(), \"retry\");\n }\n\n get url(): string {\n return this.page.url();\n }\n\n async title(): Promise<string> {\n return this.resilient(() => this.page.title(), \"retry\");\n }\n\n async close(): Promise<void> {\n try {\n await this.teardown();\n } finally {\n await this.recorder?.close();\n }\n }\n}\n\n/** The Playwright entry points this module needs, so tests can inject a fake. */\nexport type PlaywrightLike = {\n chromium: {\n connect(wsEndpoint: string): Promise<PlaywrightBrowserLike>;\n connectOverCDP(endpointURL: string): Promise<PlaywrightBrowserLike>;\n launch(opts?: { headless?: boolean }): Promise<PlaywrightBrowserLike>;\n };\n};\n\nexport type PlaywrightBrowserLike = {\n newContext(opts?: {\n viewport?: { width: number; height: number };\n }): Promise<{ newPage(): Promise<BrowserPage>; close(): Promise<void> }>;\n close(): Promise<void>;\n};\n\nasync function loadPlaywright(): Promise<PlaywrightLike> {\n try {\n // A string specifier keeps bundlers from resolving the optional peer.\n const name = \"playwright\";\n return (await import(name)) as PlaywrightLike;\n } catch (error) {\n throw new Error(\n \"Driving a world UI needs Playwright: npm install playwright \" +\n \"(and `npx playwright install chromium` for local mode).\",\n { cause: error },\n );\n }\n}\n\nexport function resolveBrowserMode(\n surfaces: SessionSurfaces,\n mode: BrowserMode,\n): Exclude<BrowserMode, \"auto\"> {\n if (!surfaces.ui && !surfaces.browser)\n throw new WorldSurfaceUnavailable(\n \"ui\",\n \"open the session with surfaces: ['ui'] on a world that declares [ui]\",\n );\n const resolved =\n mode === \"auto\" ? (surfaces.browser ? \"hosted\" : \"local\") : mode;\n if (resolved === \"hosted\" && !surfaces.browser)\n throw new WorldSurfaceUnavailable(\n \"browser\",\n \"open the session with surfaces: ['browser'] to get a hosted browser\",\n );\n return resolved;\n}\n\n/** Open a browser on the session's UI in `hosted`, `local` or `auto` mode. */\nexport async function openBrowser(\n surfaces: SessionSurfaces,\n opts: {\n mode?: BrowserMode;\n headless?: boolean;\n playwright?: PlaywrightLike;\n recorder?: BrowserActionRecorder | null;\n /** The session's repair call (`session.repairBrowser`). Given, a hosted\n * `cdp` browser reconnects on its own when the browser is lost. */\n repair?: () => Promise<RepairAnswer>;\n } = {},\n): Promise<WorldBrowser> {\n const mode = resolveBrowserMode(surfaces, opts.mode ?? \"auto\");\n const pw = opts.playwright ?? (await loadPlaywright());\n const viewport = surfaces.browser?.viewport ?? DEFAULT_VIEWPORT;\n const attach = async (): Promise<BrowserConnection> => {\n const browser =\n mode === \"hosted\"\n ? surfaces.browser!.protocol === \"playwright\"\n ? await pw.chromium.connect(surfaces.browser!.wsUrl)\n : await pw.chromium.connectOverCDP(surfaces.browser!.wsUrl)\n : await pw.chromium.launch({ headless: opts.headless ?? true });\n const context = await browser.newContext({ viewport });\n return { browser, context, page: await context.newPage() };\n };\n let live = await attach();\n /** The same address again; the lost connection is released once a new one\n * stands. */\n const reattach = async (): Promise<BrowserConnection> => {\n const fresh = await attach();\n await releaseConnection(live);\n live = fresh;\n return fresh;\n };\n // A browser error quotes the URL it failed on; these carry the session.\n const scrubber = new SecretScrubber([\n surfaces.browser?.wsUrl,\n surfaces.ui?.token,\n capabilityLabel(surfaces.ui?.url),\n capabilityLabel(surfaces.api?.url),\n ]);\n // Only the platform's relay can be repaired behind the same address.\n const reconnector =\n mode === \"hosted\" && surfaces.browser!.protocol === \"cdp\" && opts.repair\n ? new BrowserReconnector(opts.repair, reattach, {\n scrub: (text) => scrubber.scrub(text),\n })\n : null;\n return new WorldBrowser(\n live.page,\n surfaces.ui,\n mode,\n () => closeConnection(live),\n viewport,\n opts.recorder ?? null,\n reconnector,\n scrubber,\n );\n}\n\nexport const COMPUTER_USE_SPECS = [\n {\n name: \"browser_goto\",\n signature: \"browser_goto(path=None)\",\n doc: \"Open a page of the world's UI. `path` is a UI path like /customers, a full URL, or omitted for the entry page. Returns the URL and page text.\",\n },\n {\n name: \"browser_click\",\n signature: \"browser_click(selector)\",\n doc: \"Click an element by Playwright selector (CSS, `text=Refund`, `role=button[name=Save]`). Returns the page text after the click.\",\n },\n {\n name: \"browser_type\",\n signature: \"browser_type(selector, text)\",\n doc: \"Replace the value of an input/textarea found by selector with `text`.\",\n },\n {\n name: \"browser_press\",\n signature: \"browser_press(key)\",\n doc: \"Press a key (Enter, Tab, Escape, ArrowDown, ...). Returns the page text after.\",\n },\n {\n name: \"browser_scroll\",\n signature: \"browser_scroll(dy=600)\",\n doc: \"Scroll the page vertically by `dy` pixels (negative scrolls up).\",\n },\n {\n name: \"browser_screenshot\",\n signature: \"browser_screenshot(full_page=False)\",\n doc: \"Take a PNG screenshot; returns {image_base64, url}.\",\n },\n {\n name: \"browser_read\",\n signature: \"browser_read(selector='body')\",\n doc: \"Return the visible text of an element (default: whole page) plus the URL and title.\",\n },\n {\n name: \"browser_back\",\n signature: \"browser_back()\",\n doc: \"Go back one page in history.\",\n },\n] as const;\n\nconst str = (v: unknown, fallback: string): string =>\n typeof v === \"string\" && v.length > 0 ? v : fallback;\n\n/**\n * The browser as model tools, in the same `WorldToolkit` shape the world's\n * own tools come in — so an agent loop that already dispatches\n * `toolkit().impls` merges `computerUseToolkit(b).impls` and gains a screen\n * without a second dispatch path.\n */\nexport function computerUseToolkit(\n browser: WorldBrowser,\n opts: { maxText?: number } = {},\n): WorldToolkit {\n const maxText = opts.maxText ?? 20_000;\n const observe = async (selector = \"body\") => {\n const text = await browser.text(selector);\n return {\n url: browser.url,\n title: await browser.title(),\n text: text.slice(0, maxText),\n truncated: text.length > maxText,\n };\n };\n\n const impls: WorldToolkit[\"impls\"] = {\n browser_goto: async (a) => {\n await browser.goto(typeof a.path === \"string\" ? a.path : undefined);\n return observe();\n },\n browser_click: async (a) => {\n await browser.click(str(a.selector, \"\"));\n return observe();\n },\n browser_type: async (a) => {\n await browser.type(str(a.selector, \"\"), String(a.text ?? \"\"));\n return { ok: true, url: browser.url };\n },\n browser_press: async (a) => {\n await browser.press(str(a.key, \"Enter\"));\n return observe();\n },\n browser_scroll: async (a) => {\n await browser.scroll(typeof a.dy === \"number\" ? a.dy : 600);\n return { ok: true, url: browser.url };\n },\n browser_screenshot: async (a) => ({\n image_base64: await browser.screenshotBase64(a.full_page === true),\n url: browser.url,\n }),\n browser_read: async (a) => observe(str(a.selector, \"body\")),\n browser_back: async () => {\n await browser.back();\n return observe();\n },\n };\n\n const specs = COMPUTER_USE_SPECS.map((s) => ({ ...s }));\n return {\n schemas: specs.map((spec) => schemaFromSignature(spec)),\n impls,\n specs,\n };\n}\n","/**\n * The provider-neutral action vocabulary every native computer executes.\n * Coordinates are in the MODEL's pixel space; the screen maps them to the page.\n * Twin of `gatewaysdk/native_computer/actions.py`.\n */\n\nexport const ACTION_NAMES = [\n \"screenshot\",\n \"zoom\",\n \"click\",\n \"move\",\n \"mouse_down\",\n \"mouse_up\",\n \"drag\",\n \"scroll\",\n \"type\",\n \"key\",\n \"hold_key\",\n \"wait\",\n \"cursor_position\",\n \"history\",\n] as const;\n\nexport type ActionName = (typeof ACTION_NAMES)[number];\nexport type Point = [number, number];\nexport type MouseButton = \"left\" | \"right\" | \"middle\";\n\nexport const SECRET_TEXT = \"[redacted]\";\n\n/** A finite JSON number from model output; anything else (null, text, a\n * list, a boolean, NaN) is refused. The Python twin is `to_number`. */\nexport function toNumber(value: unknown): number {\n if (typeof value !== \"number\" || !Number.isFinite(value))\n throw new Error(`not a number: ${JSON.stringify(value) ?? String(value)}`);\n return value;\n}\n\n/** `toNumber`, truncated like Python's `int()`. */\nexport function toInt(value: unknown): number {\n return Math.trunc(toNumber(value));\n}\n\n/** Model-controlled numbers an action may carry, inclusive. */\nexport const BOUNDS: Readonly<Record<string, [number, number]>> = {\n seconds: [0, 300],\n repeat: [1, 100],\n count: [1, 3],\n dx: [-10_000, 10_000],\n dy: [-10_000, 10_000],\n};\n\n/** Arguments by action:\n * `click` x?, y?, button, count, modifiers · `move` x, y, modifiers? ·\n * `mouse_down`/`mouse_up` button · `drag` path, modifiers ·\n * `scroll` x?, y?, dx, dy, modifiers · `type` text · `key` keys, repeat ·\n * `hold_key` keys, seconds · `wait` seconds · `zoom` region ·\n * `history` direction · `screenshot`/`cursor_position` none. */\nexport type ActionArgs = {\n x?: number;\n y?: number;\n button?: MouseButton;\n count?: number;\n modifiers?: string[];\n path?: Point[];\n dx?: number;\n dy?: number;\n text?: string;\n keys?: string[];\n repeat?: number;\n seconds?: number;\n region?: [number, number, number, number];\n direction?: \"back\" | \"forward\";\n};\n\nexport class ComputerAction {\n constructor(\n readonly name: ActionName,\n readonly args: ActionArgs = {},\n ) {\n if (!(ACTION_NAMES as readonly string[]).includes(name))\n throw new Error(`unknown computer action: ${name}`);\n for (const [key, [low, high]] of Object.entries(BOUNDS)) {\n const value = (args as Record<string, unknown>)[key];\n if (\n value !== undefined &&\n !(Number(value) >= low && Number(value) <= high)\n )\n throw new Error(\n `${name} ${key} must be between ${low} and ${high}, got ${String(value)}`,\n );\n }\n }\n\n /** Flat arguments for the browser timeline and the trace: lists become\n * `\"x,y\"` strings, and typed text is withheld when it went into a\n * credential field. */\n recordArgs(secretText: boolean): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(this.args))\n out[key] = Array.isArray(value) ? value.flat().join(\",\") : value;\n if (secretText && \"text\" in out) out.text = SECRET_TEXT;\n return out;\n }\n}\n\n/** What an action gave back: a PNG (`screenshot`, `zoom`), a line of text\n * (`cursor_position`), or neither. */\nexport type ActionResult = { image?: Buffer; text?: string };\n","/**\n * The model's pixel space versus the page's. Unscaled by default; when a\n * provider's image limits (or the caller) ask for a smaller display,\n * screenshots are captured downscaled and coordinates mapped back.\n * Twin of `gatewaysdk/native_computer/display.py`.\n */\n\nexport type Fits = (width: number, height: number) => boolean;\n\nconst FIT_STEP = 0.98;\n\nexport class Display {\n constructor(\n readonly width: number,\n readonly height: number,\n readonly viewportWidth: number,\n readonly viewportHeight: number,\n ) {}\n\n /** `size` when the caller names one; otherwise the largest downscale of the\n * viewport (at most 1:1) that `fits` the provider's limits. */\n static forViewport(\n viewport: { width: number; height: number },\n size?: [number, number],\n fits: Fits = () => true,\n ): Display {\n const { width, height } = viewport;\n if (size) return Display.sized(size[0], size[1], width, height);\n let scale = 1;\n while (!fits(Math.round(width * scale), Math.round(height * scale)))\n scale *= FIT_STEP;\n return new Display(\n Math.round(width * scale),\n Math.round(height * scale),\n width,\n height,\n );\n }\n\n /** A caller's display keeps the viewport's shape: screenshots are scaled\n * uniformly, so another aspect ratio would map clicks off the image. */\n private static sized(\n width: number,\n height: number,\n viewportWidth: number,\n viewportHeight: number,\n ): Display {\n if (width <= 0 || height <= 0)\n throw new Error(`display ${width}x${height} must be positive`);\n const sameShape = (width * viewportHeight) / viewportWidth;\n if (Math.abs(sameShape - height) > 1)\n throw new Error(\n `display ${width}x${height} must keep the viewport's aspect ratio ` +\n `(${viewportWidth}x${viewportHeight}); try ${width}x${Math.round(sameShape)}`,\n );\n return new Display(width, height, viewportWidth, viewportHeight);\n }\n\n get scaled(): boolean {\n return (\n this.width !== this.viewportWidth || this.height !== this.viewportHeight\n );\n }\n\n get scale(): number {\n return Math.min(\n this.width / this.viewportWidth,\n this.height / this.viewportHeight,\n );\n }\n\n toPage(x: number, y: number): [number, number] {\n return [\n (x * this.viewportWidth) / this.width,\n (y * this.viewportHeight) / this.height,\n ];\n }\n}\n","/**\n * Pixels and keys on a `WorldBrowser` page. Every provider's actions land here\n * as `ComputerAction` values and run as Playwright mouse and keyboard calls.\n * The cursor is tracked in the model's pixel space so a click without\n * coordinates lands where the pointer is. Twin of `native_computer/screen.py`.\n */\nimport { SECRET_KEY, type BrowserPage } from \"../browser\";\nimport type { ActionResult, ComputerAction, Point } from \"./actions\";\nimport type { Display } from \"./display\";\n\ntype CdpSession = {\n send(\n method: string,\n params: Record<string, unknown>,\n ): Promise<{ data: string }>;\n detach(): Promise<void>;\n};\n\n/** The Playwright page surface pixel-level control needs, beyond `BrowserPage`. */\nexport type NativePage = {\n mouse: {\n move(x: number, y: number, opts?: { steps?: number }): Promise<void>;\n click(\n x: number,\n y: number,\n opts?: { button?: string; clickCount?: number },\n ): Promise<void>;\n down(opts?: { button?: string }): Promise<void>;\n up(opts?: { button?: string }): Promise<void>;\n wheel(dx: number, dy: number): Promise<void>;\n };\n keyboard: {\n down(key: string): Promise<void>;\n up(key: string): Promise<void>;\n press(key: string): Promise<void>;\n type(text: string): Promise<void>;\n };\n screenshot(opts?: { type?: \"png\" }): Promise<Buffer>;\n waitForTimeout(ms: number): Promise<void>;\n goBack(): Promise<unknown>;\n goForward(): Promise<unknown>;\n evaluate(expression: string): Promise<unknown>;\n context(): { newCDPSession(page: unknown): Promise<CdpSession> };\n};\n\n/** The slice of `WorldBrowser` a native computer drives. */\nexport type ScreenBrowser = {\n readonly page: BrowserPage;\n readonly viewport: { width: number; height: number };\n act<T>(\n action: string,\n args: Record<string, unknown>,\n fn: () => Promise<T>,\n onLoss?: \"retry\" | \"report\",\n ): Promise<T>;\n settle(): Promise<void>;\n scrub(text: string): string;\n};\n\nconst FOCUSED_FIELD_JS =\n \"(() => { let e = document.activeElement;\" +\n \" const inner = (el) => (el.shadowRoot && el.shadowRoot.activeElement)\" +\n \" || (el.contentDocument && el.contentDocument.activeElement);\" +\n \" while (e && inner(e)) e = inner(e);\" +\n \" if (!e) return '';\" +\n \" if (e.tagName === 'IFRAME' || e.tagName === 'FRAME') return 'frame';\" +\n \" if (!(e.tagName === 'INPUT' || e.tagName === 'TEXTAREA' || e.isContentEditable)) return 'opaque';\" +\n \" return [e.type, e.name, e.id, e.getAttribute('autocomplete')].filter(Boolean).join(' '); })()\";\nconst SECRET_FOCUS = [\"password\", \"frame\", \"opaque\"];\nconst DRAG_STEPS = 5;\nconst PNG_SIGNATURE = Buffer.from([\n 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,\n]);\n\ntype Clip = { x: number; y: number; width: number; height: number };\n\n/** The width in a PNG's header, or null for bytes that are not a PNG. */\nexport function pngWidth(png: Buffer): number | null {\n if (png.length < 24 || !png.subarray(0, 8).equals(PNG_SIGNATURE)) return null;\n return png.readUInt32BE(16);\n}\nconst NATIVE_METHODS = [\"move\", \"click\", \"down\", \"up\", \"wheel\"] as const;\n\nfunction isNativePage(page: unknown): page is NativePage {\n const candidate = page as Partial<NativePage> | null;\n const mouse = candidate?.mouse as Record<string, unknown> | undefined;\n return (\n typeof candidate?.context === \"function\" &&\n NATIVE_METHODS.every((m) => typeof mouse?.[m] === \"function\")\n );\n}\n\ntype Handler = (action: ComputerAction) => Promise<ActionResult>;\n\nexport class Screen {\n cursor: Point = [0, 0];\n private pixelRatio = 1;\n private readonly handlers: Record<ComputerAction[\"name\"], Handler> = {\n screenshot: async () => ({ image: await this.screenshot() }),\n zoom: (a) => this.zoom(a),\n click: (a) => this.click(a),\n move: (a) =>\n this.held(a.args.modifiers ?? [], () => this.moveTo(this.point(a))),\n mouse_down: async (a) => {\n await this.page.mouse.down({ button: a.args.button ?? \"left\" });\n return {};\n },\n mouse_up: async (a) => {\n await this.page.mouse.up({ button: a.args.button ?? \"left\" });\n return {};\n },\n drag: (a) => this.drag(a),\n scroll: (a) => this.scroll(a),\n type: async (a) => {\n await this.page.keyboard.type(a.args.text ?? \"\");\n return {};\n },\n key: (a) => this.key(a),\n hold_key: (a) =>\n this.held(a.args.keys ?? [], () =>\n this.page.waitForTimeout((a.args.seconds ?? 0) * 1000),\n ),\n wait: async (a) => {\n await this.page.waitForTimeout((a.args.seconds ?? 0) * 1000);\n return {};\n },\n cursor_position: async () => ({\n text: `X=${this.cursor[0]}, Y=${this.cursor[1]}`,\n }),\n history: async (a) => {\n const navigate = {\n back: () => this.page.goBack(),\n forward: () => this.page.goForward(),\n };\n await navigate[a.args.direction ?? \"back\"]();\n return {};\n },\n };\n\n constructor(\n readonly browser: ScreenBrowser,\n readonly display: Display,\n ) {}\n\n /** The live page (a new object after a reconnect), as pixel-level Playwright. */\n get page(): NativePage {\n const page: unknown = this.browser.page;\n if (!isNativePage(page))\n throw new Error(\n \"native computer use needs a Playwright page (mouse.move/click/down/up/wheel, context())\",\n );\n return page;\n }\n\n run(action: ComputerAction): Promise<ActionResult> {\n return this.handlers[action.name](action);\n }\n\n /** A PNG of the viewport at the model's display size. */\n async screenshot(): Promise<Buffer> {\n if (!this.display.scaled) return this.page.screenshot({ type: \"png\" });\n const { viewportWidth: width, viewportHeight: height } = this.display;\n return this.capture({ x: 0, y: 0, width, height }, this.display.scale);\n }\n\n /** Whether keystrokes go to a credential field (a password input, or one\n * named like a token, key or PIN), looking through shadow roots and\n * same-origin frames. An unreadable page, a cross-origin frame or a focus\n * that is not a text field (a closed shadow root's host) counts as one. */\n async focusedFieldIsSecret(): Promise<boolean> {\n let described: string;\n try {\n described = String((await this.page.evaluate(FOCUSED_FIELD_JS)) ?? \"\");\n } catch {\n return true;\n }\n return (\n SECRET_FOCUS.some((prefix) => described.startsWith(prefix)) ||\n SECRET_KEY.test(described)\n );\n }\n\n /** CDP renders a clip at the page's device pixel ratio as well as its\n * `scale` (a Retina host doubles it), so a capture of the wrong width\n * measures that ratio and is taken once more, corrected. */\n private async capture(clip: Clip, scale: number): Promise<Buffer> {\n const wanted = Math.round(clip.width * scale);\n const png = await this.cdpCapture(clip, scale / this.pixelRatio);\n const width = pngWidth(png);\n if (width === null || Math.abs(width - wanted) <= 1) return png;\n this.pixelRatio *= width / wanted;\n return this.cdpCapture(clip, scale / this.pixelRatio);\n }\n\n private async cdpCapture(clip: Clip, scale: number): Promise<Buffer> {\n const page = this.page;\n const session = await page.context().newCDPSession(page);\n try {\n const shot = await session.send(\"Page.captureScreenshot\", {\n format: \"png\",\n clip: { ...clip, scale },\n });\n return Buffer.from(shot.data, \"base64\");\n } finally {\n await session.detach();\n }\n }\n\n private point(action: ComputerAction): Point {\n const { x, y } = action.args;\n return x === undefined || y === undefined ? this.cursor : [x, y];\n }\n\n private async moveTo(point: Point, steps = 1): Promise<void> {\n const [x, y] = this.display.toPage(point[0], point[1]);\n await this.page.mouse.move(x, y, { steps });\n this.cursor = point;\n }\n\n private async held(\n modifiers: readonly string[],\n fn: () => Promise<unknown>,\n ): Promise<ActionResult> {\n for (const key of modifiers) await this.page.keyboard.down(key);\n try {\n await fn();\n } finally {\n for (const key of [...modifiers].reverse())\n await this.page.keyboard.up(key);\n }\n return {};\n }\n\n private async zoom(action: ComputerAction): Promise<ActionResult> {\n const [x0, y0, x1, y1] = action.args.region ?? [0, 0, 0, 0];\n const [left, top] = this.display.toPage(x0, y0);\n const [right, bottom] = this.display.toPage(x1, y1);\n if (right <= left || bottom <= top)\n throw new Error(\"zoom region must have x1 > x0 and y1 > y0\");\n const width = right - left;\n const height = bottom - top;\n const scale = Math.min(\n this.display.width / width,\n this.display.height / height,\n );\n return {\n image: await this.capture({ x: left, y: top, width, height }, scale),\n };\n }\n\n private async click(action: ComputerAction): Promise<ActionResult> {\n const point = this.point(action);\n return this.held(action.args.modifiers ?? [], async () => {\n await this.moveTo(point);\n const [x, y] = this.display.toPage(point[0], point[1]);\n await this.page.mouse.click(x, y, {\n button: action.args.button ?? \"left\",\n clickCount: action.args.count ?? 1,\n });\n });\n }\n\n private async drag(action: ComputerAction): Promise<ActionResult> {\n const path = action.args.path ?? [];\n if (path.length < 2) throw new Error(\"a drag needs at least two points\");\n return this.held(action.args.modifiers ?? [], async () => {\n await this.moveTo(path[0]);\n await this.page.mouse.down({ button: \"left\" });\n try {\n for (const point of path.slice(1)) await this.moveTo(point, DRAG_STEPS);\n } finally {\n await this.page.mouse.up({ button: \"left\" });\n }\n });\n }\n\n private async scroll(action: ComputerAction): Promise<ActionResult> {\n await this.moveTo(this.point(action));\n const scale = this.display.scale;\n return this.held(action.args.modifiers ?? [], () =>\n this.page.mouse.wheel(\n (action.args.dx ?? 0) / scale,\n (action.args.dy ?? 0) / scale,\n ),\n );\n }\n\n private async key(action: ComputerAction): Promise<ActionResult> {\n const combo = (action.args.keys ?? []).join(\"+\");\n for (let i = 0; i < (action.args.repeat ?? 1); i += 1)\n await this.page.keyboard.press(combo);\n return {};\n }\n}\n","/**\n * Attach an image (or any media) to a span: upload the bytes to the\n * platform's media store and put the returned reference into the span's\n * input or output. The trace view renders the reference inline:\n *\n * @@@langfuseMedia:type=image/png|id=<mediaId>|source=bytes@@@\n *\n * Three steps against `/api/public/media`: ask for a presigned URL (the\n * platform links the media to the trace and observation), PUT the bytes, then\n * report the upload's status. The presigned URL is a credential and never\n * reaches a log or an error. Python twin: `gatewaysdk/tracing/media.py`.\n * No OpenTelemetry import here, so the worlds entry can use it.\n */\nimport { createHash } from \"node:crypto\";\n\nimport { PlatformTransport, type PlatformMethod } from \"../worlds/transport\";\n\nexport const MEDIA_PATH = \"/api/public/media\";\nexport const MAX_MEDIA_BYTES = 5 * 1024 * 1024;\nconst PUT_TIMEOUT_MS = 30_000;\nconst MAX_UPLOAD_ERROR = 500;\nconst NETWORK_FAILURE_STATUS = 599;\n\nexport type MediaField = \"input\" | \"output\" | \"metadata\";\n\nexport class MediaUploadError extends Error {\n constructor(\n message: string,\n readonly status?: number,\n ) {\n super(message);\n this.name = \"MediaUploadError\";\n }\n}\n\nexport class MediaReference {\n constructor(\n readonly mediaId: string,\n readonly contentType: string,\n ) {}\n\n toString(): string {\n return `@@@langfuseMedia:type=${this.contentType}|id=${this.mediaId}|source=bytes@@@`;\n }\n}\n\nexport type PutBytes = (\n url: string,\n data: Buffer,\n headers: Record<string, string>,\n) => Promise<{ status: number; error: string | null }>;\n\n/** PUT to a presigned URL; a network failure is status 599 with the error's\n * name only, so the URL never travels. */\nexport async function putBytes(\n url: string,\n data: Buffer,\n headers: Record<string, string>,\n): Promise<{ status: number; error: string | null }> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), PUT_TIMEOUT_MS);\n try {\n const res = await fetch(url, {\n method: \"PUT\",\n body: new Uint8Array(data),\n headers,\n signal: controller.signal,\n });\n return {\n status: res.status,\n error: res.ok ? null : (await res.text()).slice(0, MAX_UPLOAD_ERROR),\n };\n } catch (error) {\n return {\n status: NETWORK_FAILURE_STATUS,\n error: error instanceof Error ? error.name : \"Error\",\n };\n } finally {\n clearTimeout(timer);\n }\n}\n\n/** Uploads media for one project (the key pair's). */\nexport class MediaUploader {\n constructor(\n private readonly transport: PlatformTransport,\n private readonly put: PutBytes = putBytes,\n public maxBytes: number = MAX_MEDIA_BYTES,\n ) {}\n\n /** The uploader for `GATEWAY_HOST` / `GATEWAY_PUBLIC_KEY` /\n * `GATEWAY_SECRET_KEY` only; null when any is unset, so a run traced with a saved login uploads none. */\n static fromEnv(env: NodeJS.ProcessEnv = process.env): MediaUploader | null {\n const host = env.GATEWAY_HOST;\n const publicKey = env.GATEWAY_PUBLIC_KEY;\n const secretKey = env.GATEWAY_SECRET_KEY;\n if (!host || !publicKey || !secretKey) return null;\n return new MediaUploader(\n new PlatformTransport({\n host: host.replace(/\\/$/, \"\"),\n publicKey,\n secretKey,\n }),\n );\n }\n\n /** Store `data` linked to the trace (and observation) and return its reference. */\n async upload(\n data: Buffer,\n link: {\n contentType: string;\n traceId: string;\n observationId: string | null;\n field: MediaField;\n },\n ): Promise<MediaReference> {\n if (data.length > this.maxBytes)\n throw new MediaUploadError(\n `media is ${data.length} bytes, over the ${this.maxBytes}-byte cap`,\n );\n const sha256Hash = createHash(\"sha256\").update(data).digest(\"base64\");\n const answer = (await this.send(\"POST\", MEDIA_PATH, {\n traceId: link.traceId,\n observationId: link.observationId,\n contentType: link.contentType,\n contentLength: data.length,\n sha256Hash,\n field: link.field,\n })) as { mediaId: string; uploadUrl?: string | null };\n if (typeof answer.mediaId !== \"string\" || !answer.mediaId)\n throw new MediaUploadError(\n \"POST /api/public/media answered without a mediaId\",\n );\n const reference = new MediaReference(answer.mediaId, link.contentType);\n if (answer.uploadUrl)\n await this.store(reference, answer.uploadUrl, data, sha256Hash);\n return reference;\n }\n\n private async store(\n reference: MediaReference,\n url: string,\n data: Buffer,\n sha256Hash: string,\n ): Promise<void> {\n const started = Date.now();\n const { status, error } = await this.put(url, data, {\n \"Content-Type\": reference.contentType,\n \"x-amz-checksum-sha256\": sha256Hash,\n \"x-ms-blob-type\": \"BlockBlob\",\n });\n await this.send(\n \"PATCH\",\n `${MEDIA_PATH}/${encodeURIComponent(reference.mediaId)}`,\n {\n uploadedAt: new Date().toISOString(),\n uploadHttpStatus: status,\n uploadHttpError: error,\n uploadTimeMs: Date.now() - started,\n },\n );\n if (status < 200 || status >= 300)\n throw new MediaUploadError(\n `media storage refused the upload (HTTP ${status})`,\n status,\n );\n }\n\n private async send(\n method: PlatformMethod,\n route: string,\n body: unknown,\n ): Promise<unknown> {\n const reply = await this.transport.send(method, route, body);\n if (!reply.ok)\n throw new MediaUploadError(\n `${method} ${route} -> ${reply.status}`,\n reply.status,\n );\n return reply.text ? JSON.parse(reply.text) : {};\n }\n}\n","/**\n * One span per native-computer action, with the screen after it attached.\n * Each action runs inside a `computer.<action>` tool span whose input is the\n * action and whose output carries a media reference to the post-action\n * screenshot. With no tracer provider registered (tracing not initialized)\n * the span does not record and nothing is captured or uploaded; without\n * `@opentelemetry/api` installed the action runs with no span (CJS entries\n * and the bundled CLI; the ESM entries still import it through\n * `tracing/identity` and `scores`). A failed\n * upload never fails the action: it is warned about once.\n * Twin of `gatewaysdk/native_computer/trace.py`.\n */\nimport type { Span } from \"@opentelemetry/api\";\n\nimport { MediaUploader } from \"../../tracing/media\";\nimport type { ActionResult, ComputerAction } from \"./actions\";\n\nexport const SPAN_PREFIX = \"computer.\";\nconst MAX_UPLOAD_FAILURES = 3;\nconst TRACER_NAME = \"@withgateway/sdk\";\nconst MAX_ERROR = 1000;\n\ntype OtelApi = typeof import(\"@opentelemetry/api\");\n\nlet otelApi: OtelApi | null | undefined;\n\n/** `@opentelemetry/api` is an optional peer, and the bundled CLI reaches this\n * module at startup without it: load it on the first action, never at import. */\nfunction loadOtelApi(): OtelApi | null {\n if (otelApi !== undefined) return otelApi;\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n otelApi = require(\"@opentelemetry/api\") as OtelApi;\n } catch {\n otelApi = null;\n }\n return otelApi;\n}\n\nexport class ActionTracer {\n private failures = 0;\n private warned = false;\n\n constructor(\n readonly media: MediaUploader | null,\n private readonly warn: (message: string) => void = (m) => console.warn(m),\n ) {}\n\n static fromEnv(): ActionTracer {\n return new ActionTracer(MediaUploader.fromEnv());\n }\n\n /** `args` are already redacted. A failure's status goes through `scrub`:\n * browser errors quote the session's ws URL and UI token. */\n async span(\n action: ComputerAction,\n args: Record<string, unknown>,\n run: () => Promise<ActionResult>,\n capture: () => Promise<Buffer>,\n scrub: (text: string) => string,\n ): Promise<ActionResult> {\n const otel = loadOtelApi();\n if (!otel) return run();\n const { SpanStatusCode, trace } = otel;\n const attributes = {\n \"gateway.observation.type\": \"tool\",\n \"tool.name\": SPAN_PREFIX + action.name,\n \"gateway.observation.input\": JSON.stringify({\n action: action.name,\n ...args,\n }),\n };\n return trace\n .getTracer(TRACER_NAME)\n .startActiveSpan(\n SPAN_PREFIX + action.name,\n { attributes },\n async (span) => {\n try {\n const result = await run();\n await this.finish(span, result, capture);\n span.setStatus({ code: SpanStatusCode.OK });\n return result;\n } catch (error) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: scrub(errorText(error)).slice(0, MAX_ERROR),\n });\n throw error;\n } finally {\n span.end();\n }\n },\n );\n }\n\n private async finish(\n span: Span,\n result: ActionResult,\n capture: () => Promise<Buffer>,\n ): Promise<void> {\n if (!span.isRecording()) return;\n const output: Record<string, string> = {\n screenshot: await this.screenshot(span, result, capture),\n };\n if (result.text !== undefined) output.text = result.text;\n span.setAttribute(\"gateway.observation.output\", JSON.stringify(output));\n }\n\n private async screenshot(\n span: Span,\n result: ActionResult,\n capture: () => Promise<Buffer>,\n ): Promise<string> {\n let png: Buffer;\n try {\n png = result.image ?? (await capture());\n } catch (error) {\n return `[screenshot unavailable: ${errorName(error)}]`;\n }\n return this.reference(png, span);\n }\n\n private async reference(png: Buffer, span: Span): Promise<string> {\n if (!this.media)\n return \"[screenshot not uploaded: GATEWAY_HOST / GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY unset]\";\n if (this.failures >= MAX_UPLOAD_FAILURES)\n return \"[screenshot not uploaded: uploads disabled after repeated failures]\";\n const { traceId, spanId } = span.spanContext();\n try {\n const reference = await this.media.upload(png, {\n contentType: \"image/png\",\n traceId,\n observationId: spanId,\n field: \"output\",\n });\n this.failures = 0;\n return reference.toString();\n } catch (error) {\n return this.failed(error);\n }\n }\n\n private failed(error: unknown): string {\n this.failures += 1;\n if (!this.warned) {\n this.warned = true;\n this.warn(\n `native computer: screenshot upload failed (${errorName(error)}: ${error instanceof Error ? error.message : String(error)}); spans keep going without it`,\n );\n }\n return `[screenshot not uploaded: ${errorName(error)}]`;\n }\n}\n\nfunction errorText(error: unknown): string {\n return error instanceof Error\n ? `${error.name}: ${error.message}`\n : String(error);\n}\n\nfunction errorName(error: unknown): string {\n return error instanceof Error ? error.name : \"Error\";\n}\n","/**\n * A provider kind (a subclass) knows only its wire format;\n * `NativeComputer.forProvider` is the one place a kind is chosen.\n * Twin of `gatewaysdk/native_computer/base.py`.\n */\nimport { redactActionArgs } from \"../browser\";\nimport { ComputerAction, type ActionResult } from \"./actions\";\nimport { Display } from \"./display\";\nimport { Screen, type ScreenBrowser } from \"./screen\";\nimport { ActionTracer } from \"./trace\";\n\nconst REPLAYABLE = new Set([\"screenshot\", \"zoom\", \"cursor_position\", \"wait\"]);\nconst SETTLING = new Set([\"click\", \"mouse_up\", \"drag\", \"key\", \"history\"]);\nconst EVENT_PREFIX = \"computer_\";\n\nexport type NativeComputerOptions = {\n /** The pixel size the model sees; default the viewport, or the largest\n * downscale that fits the provider's image limits. */\n display?: [number, number];\n /** Records one span per action with the screen after it; default uploads\n * screenshots with the `GATEWAY_*` keys when tracing is initialized. */\n tracer?: ActionTracer;\n};\n\n/** The major version of the `ai` package the tools are handed to. */\nexport type AiSdkMajor = 6 | 7;\n\nexport type AiSdkOptions<V extends AiSdkMajor = 6> = {\n /** The Anthropic kinds' screenshot part. Default 6: `image-data`, which\n * AI SDK 7 still accepts with a deprecation warning. 7: the `file` part with\n * `{ type: \"data\", data }`, which AI SDK 6 does not accept. The OpenAI kinds\n * return the provider's own `computer_screenshot` output and ignore it. */\n version?: V;\n};\n\ntype Kind = new (\n browser: ScreenBrowser,\n options?: NativeComputerOptions,\n) => NativeComputer;\n\n/** `item[name]` for the first spelling that is set (`scroll_x`, `scrollX`). */\nexport function readField(item: unknown, ...names: string[]): unknown {\n const record = (item ?? {}) as Record<string, unknown>;\n return names\n .map((name) => record[name])\n .find((value) => value !== undefined && value !== null);\n}\n\nexport abstract class NativeComputer {\n private static readonly kinds = new Map<string, Kind>();\n\n readonly display: Display;\n readonly screen: Screen;\n readonly tracer: ActionTracer;\n private queue: Promise<unknown> = Promise.resolve();\n\n static register(provider: string, kind: Kind): void {\n NativeComputer.kinds.set(provider, kind);\n }\n\n static get providers(): string[] {\n return [...NativeComputer.kinds.keys()].sort();\n }\n\n static forProvider(\n provider: string,\n browser: ScreenBrowser,\n options: NativeComputerOptions = {},\n ): NativeComputer {\n const Kind = NativeComputer.kinds.get(provider);\n if (!Kind)\n throw new Error(\n `unknown computer-use provider '${provider}'; choose from ${NativeComputer.providers.join(\", \")}`,\n );\n return new Kind(browser, options);\n }\n\n constructor(\n readonly browser: ScreenBrowser,\n options: NativeComputerOptions = {},\n ) {\n const kind = this.constructor as typeof NativeComputer;\n this.display = Display.forViewport(\n browser.viewport,\n options.display,\n (w, h) => kind.fits(w, h),\n );\n this.screen = new Screen(browser, this.display);\n this.tracer = options.tracer ?? ActionTracer.fromEnv();\n }\n\n /** Whether a screenshot of this size is within the provider's limits. */\n static fits(_width: number, _height: number): boolean {\n return true;\n }\n\n /** The tool definition to send the model. */\n abstract tool(): Record<string, unknown>;\n\n /** One action in the provider's own shape, as a `ComputerAction`. */\n abstract parse(raw: unknown): ComputerAction;\n\n /** The options to spread into the Vercel AI SDK's provider-defined computer\n * tool (`execute` and its companions), backed by this computer. */\n abstract aiSdk(options?: AiSdkOptions<AiSdkMajor>): object;\n\n /** Run one provider-shaped action (an OpenAI action object, or an Anthropic\n * `{ action: \"left_click\", ... }` input) and return what it produced: the\n * door for any agent framework that hands actions over one at a time. */\n executeAction(raw: unknown): Promise<ActionResult> {\n return this.perform(this.parse(raw));\n }\n\n /** Run one action on the page: reported on the session's browser timeline\n * and, when tracing is on, as a span with the screen after. */\n async perform(action: ComputerAction): Promise<ActionResult> {\n const secret =\n action.name === \"type\" && (await this.screen.focusedFieldIsSecret());\n const event = EVENT_PREFIX + action.name;\n const args = redactActionArgs(event, action.recordArgs(secret));\n return this.tracer.span(\n action,\n args,\n () =>\n this.browser.act(\n event,\n args,\n () => this.runOnScreen(action),\n this.onLoss(action),\n ),\n () => this.screen.screenshot(),\n (text) => this.browser.scrub(text),\n );\n }\n\n async performAll(\n actions: readonly ComputerAction[],\n ): Promise<ActionResult[]> {\n const results: ActionResult[] = [];\n for (const action of actions) results.push(await this.perform(action));\n return results;\n }\n\n /** The screen as the model sees it, as a traced `screenshot` action. */\n async screenshot(): Promise<Buffer> {\n return (\n (await this.perform(new ComputerAction(\"screenshot\"))).image ??\n Buffer.alloc(0)\n );\n }\n\n /** Run `fn` after every earlier call made through here: the AI SDK starts a\n * step's tool calls concurrently, but one screen takes one action at a time. */\n protected serial<T>(fn: () => Promise<T>): Promise<T> {\n const next = this.queue.then(fn, fn);\n this.queue = next.catch(() => undefined);\n return next;\n }\n\n private async runOnScreen(action: ComputerAction): Promise<ActionResult> {\n const result = await this.screen.run(action);\n if (SETTLING.has(action.name)) await this.browser.settle();\n return result;\n }\n\n private onLoss(action: ComputerAction): \"retry\" | \"report\" {\n return REPLAYABLE.has(action.name) ? \"retry\" : \"report\";\n }\n}\n","/**\n * Key names from each provider's vocabulary, mapped once to Playwright's.\n * Anthropic sends xdotool-style chords (`ctrl+a`, `Return`); OpenAI sends\n * arrays of upper-case names (`[\"CTRL\", \"A\"]`). Twin of\n * `gatewaysdk/native_computer/keys.py`; `conformance/native-computer.json` pins both.\n */\n\nconst F_KEYS = Object.fromEntries(\n Array.from({ length: 12 }, (_, i) => [`f${i + 1}`, `F${i + 1}`]),\n);\n\nexport const KEY_NAMES: Readonly<Record<string, string>> = {\n return: \"Enter\",\n enter: \"Enter\",\n kp_enter: \"Enter\",\n esc: \"Escape\",\n escape: \"Escape\",\n tab: \"Tab\",\n space: \"Space\",\n backspace: \"Backspace\",\n delete: \"Delete\",\n del: \"Delete\",\n insert: \"Insert\",\n home: \"Home\",\n end: \"End\",\n pageup: \"PageUp\",\n page_up: \"PageUp\",\n prior: \"PageUp\",\n pagedown: \"PageDown\",\n page_down: \"PageDown\",\n next: \"PageDown\",\n up: \"ArrowUp\",\n arrowup: \"ArrowUp\",\n down: \"ArrowDown\",\n arrowdown: \"ArrowDown\",\n left: \"ArrowLeft\",\n arrowleft: \"ArrowLeft\",\n right: \"ArrowRight\",\n arrowright: \"ArrowRight\",\n ctrl: \"Control\",\n control: \"Control\",\n shift: \"Shift\",\n alt: \"Alt\",\n option: \"Alt\",\n super: \"Meta\",\n meta: \"Meta\",\n cmd: \"Meta\",\n command: \"Meta\",\n win: \"Meta\",\n capslock: \"CapsLock\",\n caps_lock: \"CapsLock\",\n plus: \"+\",\n minus: \"-\",\n ...F_KEYS,\n};\n\n/** One provider key name as Playwright names it; an unknown name passes through. */\nexport function playwrightKey(token: string): string {\n return KEY_NAMES[token.toLowerCase()] ?? token;\n}\n\nfunction letterOrName(key: string): string {\n return /^[a-zA-Z]$/.test(key) ? key.toLowerCase() : playwrightKey(key);\n}\n\n/** Keys pressed together, in Playwright's names (`[\"Control\", \"a\"]`). */\nexport class KeyChord {\n private constructor(readonly keys: readonly string[]) {\n if (keys.length === 0)\n throw new Error(\"a key action needs at least one key\");\n }\n\n /** `ctrl+shift+t` / `Return`: Anthropic's vocabulary, case kept. */\n static fromXdotool(text: string): KeyChord {\n return new KeyChord(\n text.trim().split(\"+\").filter(Boolean).map(playwrightKey),\n );\n }\n\n /** `[\"CTRL\", \"A\"]`: OpenAI's vocabulary. A lone letter is the unshifted key. */\n static fromKeys(keys: readonly string[]): KeyChord {\n return new KeyChord(keys.map(letterOrName));\n }\n\n /** What `page.keyboard.press` takes: `Control+a`. */\n get combo(): string {\n return this.keys.join(\"+\");\n }\n}\n\n/** The modifiers an Anthropic click/scroll holds (`text: \"ctrl+shift\"`). */\nexport function modifierChord(text: unknown): string[] {\n return typeof text === \"string\" && text\n ? [...KeyChord.fromXdotool(text).keys]\n : [];\n}\n\n/** The modifiers an OpenAI mouse action holds (`keys: [\"SHIFT\"]`). */\nexport function modifierKeys(keys: unknown): string[] {\n return Array.isArray(keys) && keys.length > 0\n ? [...KeyChord.fromKeys(keys.map(String)).keys]\n : [];\n}\n","/**\n * Docs: https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool\n * Twin of `gatewaysdk/native_computer/anthropic.py`.\n */\nimport {\n ComputerAction,\n toInt,\n toNumber,\n type ActionResult,\n type MouseButton,\n type Point,\n} from \"./actions\";\nimport {\n NativeComputer,\n readField,\n type AiSdkMajor,\n type AiSdkOptions,\n} from \"./base\";\nimport { KeyChord, modifierChord } from \"./keys\";\n\nconst SCROLL_STEP_PX = 100;\nexport const NOT_EXECUTED =\n \"Not executed: an earlier computer action in this turn failed.\";\nconst MAX_ERROR = 1000;\nconst SCROLL_DIRECTIONS: Record<string, Point> = {\n up: [0, -1],\n down: [0, 1],\n left: [-1, 0],\n right: [1, 0],\n};\n\ntype Raw = Record<string, unknown>;\n\nexport type AiSdkAnthropicOutput = { type: \"image\"; data: string } | string;\ntype ImageParts = {\n 6: { type: \"image-data\"; data: string; mediaType: \"image/png\" };\n 7: {\n type: \"file\";\n mediaType: \"image/png\";\n data: { type: \"data\"; data: string };\n };\n};\nexport type AiSdkImagePart<V extends AiSdkMajor = AiSdkMajor> = ImageParts[V];\nexport type AiSdkModelOutput<V extends AiSdkMajor = 6> =\n | { type: \"text\"; value: string }\n | { type: \"content\"; value: AiSdkImagePart<V>[] };\n\nconst IMAGE_PARTS: {\n [V in AiSdkMajor]: (data: string) => AiSdkImagePart<V>;\n} = {\n 6: (data) => ({ type: \"image-data\", data, mediaType: \"image/png\" }),\n 7: (data) => ({\n type: \"file\",\n mediaType: \"image/png\",\n data: { type: \"data\", data },\n }),\n};\n\nexport type AnthropicContent =\n | { type: \"text\"; text: string }\n | {\n type: \"image\";\n source: { type: \"base64\"; media_type: \"image/png\"; data: string };\n };\n\nexport type AnthropicToolResult = {\n type: \"tool_result\";\n tool_use_id: string;\n toolset_name?: string;\n content: AnthropicContent[] | string;\n is_error?: true;\n};\n\nfunction required(raw: Raw, key: string): unknown {\n const value = raw[key];\n if (value === undefined || value === null)\n throw new Error(`${String(raw.action)} needs ${key}`);\n return value;\n}\n\nfunction pair(raw: Raw, key: string): Point {\n const value = required(raw, key) as unknown[];\n return [toInt(value[0]), toInt(value[1])];\n}\n\nfunction point(raw: Raw): { x?: number; y?: number } {\n if (raw.coordinate === undefined || raw.coordinate === null) return {};\n const [x, y] = pair(raw, \"coordinate\");\n return { x, y };\n}\n\nfunction chord(raw: Raw): string[] {\n return [...KeyChord.fromXdotool(String(required(raw, \"text\"))).keys];\n}\n\nfunction click(button: MouseButton, count: number) {\n return (raw: Raw) =>\n new ComputerAction(\"click\", {\n ...point(raw),\n button,\n count,\n modifiers: modifierChord(raw.text),\n });\n}\n\nconst MEMBERS: Record<string, (raw: Raw) => ComputerAction> = {\n screenshot: () => new ComputerAction(\"screenshot\"),\n zoom: (raw) =>\n new ComputerAction(\"zoom\", {\n region: (required(raw, \"region\") as unknown[]).map(toInt) as [\n number,\n number,\n number,\n number,\n ],\n }),\n left_click: click(\"left\", 1),\n right_click: click(\"right\", 1),\n middle_click: click(\"middle\", 1),\n double_click: click(\"left\", 2),\n triple_click: click(\"left\", 3),\n left_click_drag: (raw) =>\n new ComputerAction(\"drag\", {\n path: [pair(raw, \"start_coordinate\"), pair(raw, \"coordinate\")],\n modifiers: modifierChord(raw.text),\n }),\n mouse_move: (raw) => {\n const [x, y] = pair(raw, \"coordinate\");\n return new ComputerAction(\"move\", { x, y });\n },\n left_mouse_down: () => new ComputerAction(\"mouse_down\", { button: \"left\" }),\n left_mouse_up: () => new ComputerAction(\"mouse_up\", { button: \"left\" }),\n cursor_position: () => new ComputerAction(\"cursor_position\"),\n scroll: (raw) => {\n const direction = String(raw.scroll_direction ?? \"down\");\n if (!Object.hasOwn(SCROLL_DIRECTIONS, direction))\n throw new Error(\n `scroll_direction must be one of ${Object.keys(SCROLL_DIRECTIONS).join(\", \")}`,\n );\n const [dx, dy] = SCROLL_DIRECTIONS[direction];\n const amount = toInt(raw.scroll_amount ?? 1) * SCROLL_STEP_PX;\n return new ComputerAction(\"scroll\", {\n ...point(raw),\n dx: dx * amount,\n dy: dy * amount,\n modifiers: modifierChord(raw.text),\n });\n },\n type: (raw) =>\n new ComputerAction(\"type\", { text: String(required(raw, \"text\")) }),\n key: (raw) =>\n new ComputerAction(\"key\", {\n keys: chord(raw),\n repeat: toInt(raw.repeat ?? 1),\n }),\n hold_key: (raw) =>\n new ComputerAction(\"hold_key\", {\n keys: chord(raw),\n seconds: toNumber(required(raw, \"duration\")),\n }),\n wait: (raw) =>\n new ComputerAction(\"wait\", { seconds: toNumber(raw.duration ?? 1) }),\n};\n\n/** `computer_toolset_20260801` for Claude 5-family models (claude-sonnet-5-5,\n * claude-opus-5-5, ...): send `tool()` in `tools`, pass each response's\n * `content` to `execute`, and send the returned blocks back as the next user\n * message. */\nexport class AnthropicComputer extends NativeComputer {\n static readonly TOOL_TYPE: string = \"computer_toolset_20260801\";\n static readonly TOOLSET = \"computer\";\n static readonly BETA: string | null = null;\n static readonly MAX_LONG_EDGE: number = 2576;\n static readonly MAX_VISUAL_TOKENS = 4784;\n static readonly PATCH_PX = 28;\n\n static fits(width: number, height: number): boolean {\n const tokens =\n Math.ceil(width / this.PATCH_PX) * Math.ceil(height / this.PATCH_PX);\n return (\n Math.max(width, height) <= this.MAX_LONG_EDGE &&\n tokens <= this.MAX_VISUAL_TOKENS\n );\n }\n\n tool(): Record<string, unknown> {\n return { type: AnthropicComputer.TOOL_TYPE };\n }\n\n /** Whether a content block is a call to this computer. */\n owns(block: unknown): boolean {\n return (\n readField(block, \"type\") === \"tool_use\" &&\n readField(block, \"toolset_name\") === AnthropicComputer.TOOLSET\n );\n }\n\n member(block: unknown): [string, Raw] {\n return [\n String(readField(block, \"name\")),\n { ...((readField(block, \"input\") as Raw) ?? {}) },\n ];\n }\n\n parse(raw: unknown): ComputerAction {\n const name = String(readField(raw, \"action\"));\n const parser = Object.hasOwn(MEMBERS, name) ? MEMBERS[name] : undefined;\n if (!parser) throw new Error(`unknown computer action: ${name}`);\n return parser(raw as Raw);\n }\n\n /** Run every computer `tool_use` in a response's content, in order, and\n * return one `tool_result` per block. Other blocks are skipped. */\n async execute(content: Iterable<unknown>): Promise<AnthropicToolResult[]> {\n const results: AnthropicToolResult[] = [];\n let failed = false;\n for (const block of content) {\n if (!this.owns(block)) continue;\n if (failed) {\n results.push(this.envelope(block, NOT_EXECUTED, true));\n continue;\n }\n const [result, blockFailed] = await this.runBlock(block);\n results.push(result);\n failed = blockFailed;\n }\n return results;\n }\n\n /** The content an `ActionResult` goes back to the model as. */\n static content(result: ActionResult): AnthropicContent[] {\n if (result.image)\n return [\n {\n type: \"image\",\n source: {\n type: \"base64\",\n media_type: \"image/png\",\n data: result.image.toString(\"base64\"),\n },\n },\n ];\n return [{ type: \"text\", text: result.text ?? \"OK\" }];\n }\n\n /** For `anthropic.tools.computerToolset_20260801(computer.aiSdk({ version: 7 }))`\n * (AI SDK 7 only), or `computer_20251124` with the legacy kind (AI SDK 6\n * and 7): `execute` runs one action and returns `{ type: \"image\", data }` or\n * text; `toModelOutput` turns that into the tool result in the part shape\n * of `options.version`. Calls run one at a time, and once a call fails the\n * rest of that step's calls answer as not executed. */\n aiSdk<V extends AiSdkMajor = 6>(\n options: AiSdkOptions<V> = {},\n ): {\n execute: (\n input: unknown,\n options?: { messages?: readonly unknown[] },\n ) => Promise<AiSdkAnthropicOutput>;\n toModelOutput: (options: {\n output: AiSdkAnthropicOutput;\n }) => AiSdkModelOutput<V>;\n } {\n const imagePart = AnthropicComputer.imagePart(options);\n let failedStep: number | undefined;\n const execute = (\n input: unknown,\n options?: { messages?: readonly unknown[] },\n ) =>\n this.serial(async () => {\n const step = options?.messages?.length;\n if (step !== undefined && step === failedStep)\n throw new Error(NOT_EXECUTED);\n try {\n return AnthropicComputer.aiSdkOutput(await this.executeAction(input));\n } catch (error) {\n failedStep = step;\n throw error instanceof Error\n ? new Error(this.browser.scrub(error.message))\n : error;\n }\n });\n return {\n execute,\n toModelOutput: ({ output }) =>\n AnthropicComputer.modelOutput(output, imagePart),\n };\n }\n\n static aiSdkOutput(result: ActionResult): AiSdkAnthropicOutput {\n if (result.image)\n return { type: \"image\", data: result.image.toString(\"base64\") };\n return result.text ?? \"OK\";\n }\n\n /** A screenshot as the image part of AI SDK `options.version`:\n * `image-data` for 6 (the default), `file` with `{ type: \"data\", data }`\n * for 7. */\n static aiSdkModelOutput<V extends AiSdkMajor = 6>(\n output: AiSdkAnthropicOutput,\n options: AiSdkOptions<V> = {},\n ): AiSdkModelOutput<V> {\n return AnthropicComputer.modelOutput(\n output,\n AnthropicComputer.imagePart(options),\n );\n }\n\n private static imagePart<V extends AiSdkMajor>({\n version = 6 as V,\n }: AiSdkOptions<V>): (data: string) => AiSdkImagePart<V> {\n if (Object.hasOwn(IMAGE_PARTS, version)) return IMAGE_PARTS[version];\n throw new Error(\n `unsupported AI SDK version ${version}; choose ${Object.keys(IMAGE_PARTS).join(\" or \")}`,\n );\n }\n\n private static modelOutput<V extends AiSdkMajor>(\n output: AiSdkAnthropicOutput,\n imagePart: (data: string) => AiSdkImagePart<V>,\n ): AiSdkModelOutput<V> {\n if (typeof output === \"string\") return { type: \"text\", value: output };\n return { type: \"content\", value: [imagePart(output.data)] };\n }\n\n protected envelope(\n block: unknown,\n content: AnthropicContent[] | string,\n isError = false,\n ): AnthropicToolResult {\n return {\n type: \"tool_result\",\n tool_use_id: String(readField(block, \"id\")),\n toolset_name: AnthropicComputer.TOOLSET,\n content,\n ...(isError ? { is_error: true as const } : {}),\n };\n }\n\n private async runBlock(\n block: unknown,\n ): Promise<[AnthropicToolResult, boolean]> {\n const [name, payload] = this.member(block);\n try {\n const result = await this.executeAction({ ...payload, action: name });\n return [this.envelope(block, AnthropicComputer.content(result)), false];\n } catch (error) {\n const detail =\n error instanceof Error\n ? `${error.name}: ${error.message}`\n : String(error);\n return [\n this.envelope(\n block,\n this.browser.scrub(`Error: ${detail}`).slice(0, MAX_ERROR),\n true,\n ),\n true,\n ];\n }\n }\n}\n\n/** The `computer_20251124` tool (beta header `computer-use-2025-11-24`) for\n * models before the toolset, and Claude 5.5 on Amazon Bedrock: one tool named\n * `computer` whose input carries `action`. */\nexport class AnthropicComputer20251124 extends AnthropicComputer {\n static readonly TOOL_TYPE = \"computer_20251124\";\n static readonly BETA = \"computer-use-2025-11-24\";\n static readonly MAX_LONG_EDGE = 1568;\n static readonly MAX_PIXELS = 1_150_000;\n\n static fits(width: number, height: number): boolean {\n return (\n Math.max(width, height) <= this.MAX_LONG_EDGE &&\n width * height <= this.MAX_PIXELS\n );\n }\n\n tool(): Record<string, unknown> {\n return {\n type: AnthropicComputer20251124.TOOL_TYPE,\n name: AnthropicComputer.TOOLSET,\n display_width_px: this.display.width,\n display_height_px: this.display.height,\n enable_zoom: true,\n };\n }\n\n owns(block: unknown): boolean {\n return (\n readField(block, \"type\") === \"tool_use\" &&\n readField(block, \"name\") === AnthropicComputer.TOOLSET\n );\n }\n\n member(block: unknown): [string, Raw] {\n const { action, ...payload } = (readField(block, \"input\") as Raw) ?? {};\n return [String(action ?? \"\"), payload];\n }\n\n protected envelope(\n block: unknown,\n content: AnthropicContent[] | string,\n isError = false,\n ): AnthropicToolResult {\n const { toolset_name: _dropped, ...rest } = super.envelope(\n block,\n content,\n isError,\n );\n return rest;\n }\n}\n\nNativeComputer.register(\"anthropic\", AnthropicComputer);\nNativeComputer.register(\n \"anthropic-computer-20251124\",\n AnthropicComputer20251124,\n);\n","/**\n * OpenAI's computer use: the Responses API `computer` tool (GA), and the\n * legacy `computer_use_preview` tool as a second kind. Each `computer_call`\n * carries an ordered batch of `actions` (the preview carried one `action`);\n * they run in order, then the screen goes back as a `computer_call_output`.\n * A call with `pending_safety_checks` is not executed until the caller passes\n * them back as `acknowledged`.\n * Docs: https://developers.openai.com/api/docs/guides/tools-computer-use\n * Twin of `gatewaysdk/native_computer/openai.py`.\n */\nimport { ComputerAction, toInt, type MouseButton, type Point } from \"./actions\";\nimport { NativeComputer, readField } from \"./base\";\nimport { KeyChord, modifierKeys } from \"./keys\";\n\nconst WAIT_SECONDS = 1;\nconst BUTTONS: Record<string, MouseButton> = {\n left: \"left\",\n right: \"right\",\n wheel: \"middle\",\n middle: \"middle\",\n};\nconst HISTORY_BUTTONS = new Set([\"back\", \"forward\"]);\n\nexport type SafetyCheck = { id: string; code?: string; message?: string };\n\nexport type ComputerCallOutput = {\n type: \"computer_call_output\";\n call_id: string;\n output: {\n type: \"computer_screenshot\";\n image_url: string;\n detail: \"original\";\n };\n acknowledged_safety_checks?: SafetyCheck[];\n};\n\nexport type AiSdkComputerCall = {\n actions?: unknown[];\n pendingSafetyChecks?: unknown[];\n};\nexport type AiSdkComputerOutput = {\n output: { type: \"computer_screenshot\"; imageUrl: string };\n acknowledgedSafetyChecks?: SafetyCheck[];\n};\n\n/** The model flagged this call; nothing ran. Show `checks` to a person, then\n * `execute(call, checks)` to run it anyway. */\nexport class PendingSafetyChecks extends Error {\n constructor(\n readonly callId: string,\n readonly checks: SafetyCheck[],\n ) {\n const listed = checks\n .map((c) => `${c.code ?? \"check\"}: ${c.message ?? \"\"}`.trim())\n .join(\"; \");\n super(\n `computer_call ${callId} needs ${checks.length} safety check(s) acknowledged: ${listed}`,\n );\n this.name = \"PendingSafetyChecks\";\n }\n}\n\nexport function safetyCheck(raw: unknown): SafetyCheck {\n const check: SafetyCheck = { id: String(readField(raw, \"id\") ?? \"\") };\n const code = readField(raw, \"code\");\n const message = readField(raw, \"message\");\n if (code !== undefined) check.code = String(code);\n if (message !== undefined) check.message = String(message);\n return check;\n}\n\nexport function dataUrl(png: Buffer): string {\n return `data:image/png;base64,${png.toString(\"base64\")}`;\n}\n\nfunction xy(raw: unknown): { x: number; y: number } {\n return {\n x: toInt(readField(raw, \"x\") ?? 0),\n y: toInt(readField(raw, \"y\") ?? 0),\n };\n}\n\nfunction held(raw: unknown): string[] {\n return modifierKeys(readField(raw, \"keys\"));\n}\n\nconst ACTIONS: Record<string, (raw: unknown) => ComputerAction> = {\n click: (raw) => {\n const button = String(readField(raw, \"button\") ?? \"left\");\n if (HISTORY_BUTTONS.has(button))\n return new ComputerAction(\"history\", {\n direction: button as \"back\" | \"forward\",\n });\n if (!Object.hasOwn(BUTTONS, button))\n throw new Error(`unknown mouse button: ${button}`);\n return new ComputerAction(\"click\", {\n ...xy(raw),\n button: BUTTONS[button],\n count: 1,\n modifiers: held(raw),\n });\n },\n double_click: (raw) =>\n new ComputerAction(\"click\", {\n ...xy(raw),\n button: \"left\",\n count: 2,\n modifiers: held(raw),\n }),\n drag: (raw) =>\n new ComputerAction(\"drag\", {\n path: ((readField(raw, \"path\") as unknown[]) ?? []).map(\n (p): Point => [toInt(readField(p, \"x\")), toInt(readField(p, \"y\"))],\n ),\n modifiers: held(raw),\n }),\n keypress: (raw) =>\n new ComputerAction(\"key\", {\n keys: [\n ...KeyChord.fromKeys((readField(raw, \"keys\") as string[]) ?? []).keys,\n ],\n repeat: 1,\n }),\n move: (raw) =>\n new ComputerAction(\"move\", { ...xy(raw), modifiers: held(raw) }),\n scroll: (raw) =>\n new ComputerAction(\"scroll\", {\n ...xy(raw),\n dx: toInt(readField(raw, \"scroll_x\", \"scrollX\") ?? 0),\n dy: toInt(readField(raw, \"scroll_y\", \"scrollY\") ?? 0),\n modifiers: held(raw),\n }),\n type: (raw) =>\n new ComputerAction(\"type\", { text: String(readField(raw, \"text\") ?? \"\") }),\n wait: () => new ComputerAction(\"wait\", { seconds: WAIT_SECONDS }),\n screenshot: () => new ComputerAction(\"screenshot\"),\n};\n\n/** The GA `computer` tool (gpt-5.5, gpt-5.6-sol and the other models whose\n * page lists computer use): send `tool()` in `tools`, pass each\n * `computer_call` item to `execute`, and send the returned\n * `computer_call_output` back with `previous_response_id`. */\nexport class OpenAIComputer extends NativeComputer {\n tool(): Record<string, unknown> {\n return { type: \"computer\" };\n }\n\n owns(item: unknown): boolean {\n return readField(item, \"type\") === \"computer_call\";\n }\n\n parse(raw: unknown): ComputerAction {\n const kind = String(readField(raw, \"type\"));\n const parser = Object.hasOwn(ACTIONS, kind) ? ACTIONS[kind] : undefined;\n if (!parser) throw new Error(`unknown computer action: ${kind}`);\n return parser(raw);\n }\n\n static actionsOf(call: unknown): unknown[] {\n const batch = readField(call, \"actions\");\n if (Array.isArray(batch)) return batch;\n const single = readField(call, \"action\");\n return single === undefined ? [] : [single];\n }\n\n /** Run a `computer_call`'s actions and return its `computer_call_output`.\n * Throws `PendingSafetyChecks` (before anything runs) while a check the\n * model raised is not in `acknowledged`. */\n async execute(\n call: unknown,\n acknowledged: readonly unknown[] = [],\n ): Promise<ComputerCallOutput> {\n const callId = String(readField(call, \"call_id\", \"callId\"));\n const checks = (\n (readField(\n call,\n \"pending_safety_checks\",\n \"pendingSafetyChecks\",\n ) as unknown[]) ?? []\n ).map(safetyCheck);\n const png = await this.runCall(\n callId,\n OpenAIComputer.actionsOf(call),\n checks,\n acknowledged,\n );\n return {\n type: \"computer_call_output\",\n call_id: callId,\n output: {\n type: \"computer_screenshot\",\n image_url: dataUrl(png),\n detail: \"original\",\n },\n ...(checks.length > 0 ? { acknowledged_safety_checks: checks } : {}),\n };\n }\n\n /** For `openai.tools.computer({ ...computer.aiSdk() })`: `execute` runs a\n * call's `actions` and returns the screenshot output. A call with pending\n * safety checks asks for approval first (`needsApproval`), so the AI SDK's\n * approval flow puts them in front of a person; once approved, `execute`\n * acknowledges them. */\n aiSdk(): {\n execute: (input: AiSdkComputerCall) => Promise<AiSdkComputerOutput>;\n needsApproval: (input: AiSdkComputerCall) => boolean;\n } {\n return {\n needsApproval: (input) => (input.pendingSafetyChecks ?? []).length > 0,\n execute: (input) =>\n this.serial(async () => {\n const checks = (input.pendingSafetyChecks ?? []).map(safetyCheck);\n const png = await this.runCall(\n \"ai-sdk\",\n input.actions ?? [],\n checks,\n checks,\n );\n return {\n output: { type: \"computer_screenshot\", imageUrl: dataUrl(png) },\n ...(checks.length > 0 ? { acknowledgedSafetyChecks: checks } : {}),\n };\n }),\n };\n }\n\n /** The batch's actions, run after the safety checks clear; the screen after them. */\n async runCall(\n callId: string,\n rawActions: readonly unknown[],\n checks: readonly SafetyCheck[],\n acknowledged: readonly unknown[],\n ): Promise<Buffer> {\n const cleared = new Set(acknowledged.map((c) => safetyCheck(c).id));\n const waiting = checks.filter((c) => !c.id || !cleared.has(c.id));\n if (waiting.length > 0) throw new PendingSafetyChecks(callId, waiting);\n const actions = rawActions.map((raw) => this.parse(raw));\n const results = await this.performAll(actions);\n const last = actions.at(-1);\n if (last?.name === \"screenshot\")\n return results.at(-1)?.image ?? Buffer.alloc(0);\n return this.screenshot();\n }\n}\n\n/** The legacy `computer_use_preview` tool for the `computer-use-preview`\n * model: it declares the display size and `environment: \"browser\"`. */\nexport class OpenAIPreviewComputer extends OpenAIComputer {\n tool(): Record<string, unknown> {\n return {\n type: \"computer_use_preview\",\n display_width: this.display.width,\n display_height: this.display.height,\n environment: \"browser\",\n };\n }\n}\n\nNativeComputer.register(\"openai\", OpenAIComputer);\nNativeComputer.register(\"openai-preview\", OpenAIPreviewComputer);\n","/** Python twin: `gatewaysdk/native_computer/`. */\nexport {\n ComputerAction,\n ACTION_NAMES,\n type ActionResult,\n type ActionArgs,\n} from \"./actions\";\nexport {\n NativeComputer,\n readField,\n type AiSdkMajor,\n type AiSdkOptions,\n type NativeComputerOptions,\n} from \"./base\";\nexport { Display } from \"./display\";\nexport { KEY_NAMES, KeyChord, playwrightKey } from \"./keys\";\nexport { Screen, type NativePage, type ScreenBrowser } from \"./screen\";\nexport { ActionTracer, SPAN_PREFIX } from \"./trace\";\nexport {\n AnthropicComputer,\n AnthropicComputer20251124,\n NOT_EXECUTED,\n type AiSdkAnthropicOutput,\n type AiSdkImagePart,\n type AiSdkModelOutput,\n type AnthropicToolResult,\n} from \"./anthropic\";\nimport type { AnthropicComputer, AnthropicComputer20251124 } from \"./anthropic\";\nimport type { OpenAIComputer, OpenAIPreviewComputer } from \"./openai\";\n\n/** The class each provider name builds, so a caller gets the kind's own\n * `execute` without a cast. */\nexport type NativeComputerKinds = {\n anthropic: AnthropicComputer;\n \"anthropic-computer-20251124\": AnthropicComputer20251124;\n openai: OpenAIComputer;\n \"openai-preview\": OpenAIPreviewComputer;\n};\nexport type NativeComputerProvider = keyof NativeComputerKinds;\n\nexport {\n OpenAIComputer,\n OpenAIPreviewComputer,\n PendingSafetyChecks,\n type AiSdkComputerCall,\n type AiSdkComputerOutput,\n type ComputerCallOutput,\n type SafetyCheck,\n} from \"./openai\";\n","/**\n * The platform declares these once in\n * `gateway/packages/shared/src/server/services/worldSessionContract.ts`; this\n * module and `gatewaysdk/environment/world_session_contract.py` repeat them, and each is\n * pinned to `conformance/world-sessions.json` by a test, so the route, the\n * World Host and the two CLIs cannot drift apart.\n */\n\n/** The largest body `POST world-sessions/{id}/calls` accepts. The SDK\n * measures the serialized body against the byte count and refuses before\n * sending; the label is what help and the refusal name. */\nexport const CALL_BODY_LIMIT_BYTES = 4 * 1024 * 1024;\nexport const CALL_BODY_LIMIT_LABEL = \"4mb\";\n\n/** `session status` warns once an unpinned session has less than this left. */\nexport const IDLE_WARNING_MINUTES = 5;\n\n/** The most entries one page of a world's request ledger holds. */\nexport const REQUEST_LOG_PAGE_MAX = 200;\n\n/** How much of each body the request ledger keeps: the first this many bytes of its text. */\nexport const REQUEST_BODY_CAPTURE_BYTES = 64 * 1024;\n\n/** The code a session the World Host did not serve answers its request ledger read with. */\nexport const REQUESTS_NOT_RECORDED = \"requests_not_recorded\";\n\n/** The task an exploratory session runs on when the caller names none, and\n * the `task.source` the platform reports for it. */\nexport const EXPLORATORY_TASK = Object.freeze({\n instruction: \"exploratory session\",\n});\nexport const EXPLORATORY_TASK_SOURCE = \"none\";\n\n/** What a session that has no grader answers `grade` with, beside\n * `reward: null`. */\nexport const NO_GRADER_REASON = \"no grader\";\n\n/** The call's body exceeds the platform's limit: nothing was sent. `limit`\n * is the label the route enforces (`4mb`), `size` the body's bytes. */\nexport class WorldCallTooLarge extends Error {\n readonly code = \"payload_too_large\";\n\n constructor(\n readonly size: number,\n readonly limitBytes: number = CALL_BODY_LIMIT_BYTES,\n readonly limit: string = CALL_BODY_LIMIT_LABEL,\n ) {\n super(\n `call body is ${size} bytes; the platform accepts at most ${limit} (${limitBytes} bytes)`,\n );\n this.name = \"WorldCallTooLarge\";\n }\n\n /** The structured refusal the CLIs print. */\n toJSON(): {\n status: \"error\";\n code: \"payload_too_large\";\n limit: string;\n size: number;\n } {\n return {\n status: \"error\",\n code: this.code,\n limit: this.limit,\n size: this.size,\n };\n }\n}\n\n/** Measure a call body the way the route will and refuse an oversized one\n * before it leaves the machine. Returns the serialized body. */\nexport function serializeCallBody(body: unknown): string {\n const text = JSON.stringify(body);\n const size = Buffer.byteLength(text, \"utf8\");\n if (size > CALL_BODY_LIMIT_BYTES) throw new WorldCallTooLarge(size);\n return text;\n}\n\n/** What `session open` adds when its wait ran out: the session keeps opening. */\nexport const stillStartingHint = (sessionId: string): string =>\n `It keeps opening: poll \\`gateway worlds session status ${sessionId}\\` until ready, ` +\n `or end it with \\`gateway worlds session close ${sessionId}\\`.`;\n\n/** The line `session status` prints when an unpinned session has under\n * `IDLE_WARNING_MINUTES` left, else null. `now` is for tests. */\nexport function idleWarning(\n idleExpiresAt: string | null | undefined,\n now: Date = new Date(),\n): string | null {\n if (!idleExpiresAt) return null;\n const leftMs = new Date(idleExpiresAt).getTime() - now.getTime();\n if (leftMs >= IDLE_WARNING_MINUTES * 60_000) return null;\n const minutes = Math.max(0, Math.floor(leftMs / 60_000));\n return (\n `warning: session expires in ${minutes}m (idle TTL); ` +\n \"call a tool to extend it or `gateway worlds session pin` to keep it\"\n );\n}\n","import type { WorldToolSpec } from \"./session\";\n\nexport const modelToolName = (name: string): string =>\n name.replace(/[^A-Za-z0-9_-]/g, \"_\").slice(0, 64) || \"tool\";\n\n/**\n * Turn a world's Python signature into a JSON schema the model can call.\n *\n * `crm_update_deal(id, stage=None, owner=None, amount=None)` becomes an\n * object with `id` required and the rest optional. Types are read from the\n * DEFAULTS the world declares — a numeric default means a number, a boolean\n * default a boolean — because that is the only type information a signature\n * actually carries. Everything else is a string, which is what a tool CLI\n * receives anyway.\n */\nexport function schemaFromSignature(spec: WorldToolSpec): {\n type: \"function\";\n function: {\n name: string;\n description: string;\n parameters: Record<string, unknown>;\n };\n} {\n if (spec.inputSchema)\n return {\n type: \"function\",\n function: {\n name: modelToolName(spec.name),\n description: spec.doc ?? spec.name,\n parameters: spec.inputSchema,\n },\n };\n const inside = /\\(([\\s\\S]*)\\)\\s*$/.exec(spec.signature.trim())?.[1] ?? \"\";\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n // Split on top-level commas only: a default like `{\"a\": 1}` has its own.\n const params: string[] = [];\n let depth = 0;\n let current = \"\";\n for (const ch of inside) {\n if (\"([{\".includes(ch)) depth++;\n if (\")]}\".includes(ch)) depth--;\n if (ch === \",\" && depth === 0) {\n params.push(current);\n current = \"\";\n } else current += ch;\n }\n if (current.trim()) params.push(current);\n\n for (const raw of params) {\n const param = raw.trim();\n if (!param || param.startsWith(\"*\") || param === \"self\") continue;\n const eq = param.indexOf(\"=\");\n const name = (eq === -1 ? param : param.slice(0, eq)).split(\":\")[0].trim();\n if (!name) continue;\n if (eq === -1) {\n properties[name] = { type: \"string\" };\n required.push(name);\n continue;\n }\n const value = param.slice(eq + 1).trim();\n if (/^-?\\d+(\\.\\d+)?$/.test(value)) properties[name] = { type: \"number\" };\n else if (value === \"True\" || value === \"False\")\n properties[name] = { type: \"boolean\" };\n else properties[name] = { type: \"string\" };\n }\n return {\n type: \"function\",\n function: {\n name: modelToolName(spec.name),\n description: spec.doc ?? spec.name,\n parameters: { type: \"object\", properties, required },\n },\n };\n}\n","import { ApiError, apiRequest, type WorldsClientOptions } from \"./index\";\nimport type { WorldRequest, WorldRequestPage } from \"./requestLog\";\nimport { REQUESTS_NOT_RECORDED } from \"./sessionContract\";\n\nexport const WORLD_REQUEST_VIAS = [\"api\", \"ui\", \"tool\", \"webhook\"] as const;\n\n/** One request with its exchange: the request's headers (credentials `[redacted]`) and the first 64 KB of each body, `null` for a body that is not text. */\nexport type WorldRequestEntry = Omit<WorldRequest, \"request\" | \"response\"> & {\n request: WorldRequest[\"request\"] & { headers: Record<string, string>; body: string | null };\n response: WorldRequest[\"response\"] & { body: string | null };\n};\n\nexport type WorldRequestFilter = {\n session?: string;\n version?: string;\n via?: string;\n operation?: string;\n status?: string;\n since?: string;\n until?: string;\n cursor?: string;\n limit?: number;\n};\n\nexport class WorldRequestFilterError extends Error {}\n\nconst NOT_RECORDED = \"This session's engine records no requests; only hosted World Host sessions do.\";\n\n/** The platform's 409 `requests_not_recorded`: the session's engine keeps no request ledger, only World Host\n * sessions record requests. Its message is the platform's own sentence. */\nexport class WorldRequestsNotRecorded extends Error {\n static from(error: unknown): unknown {\n if (!(error instanceof ApiError) || error.code !== REQUESTS_NOT_RECORDED) return error;\n return new WorldRequestsNotRecorded(platformMessage(error.text) || NOT_RECORDED);\n }\n\n static async mapped<T>(read: Promise<T>): Promise<T> {\n try {\n return await read;\n } catch (error) {\n throw WorldRequestsNotRecorded.from(error);\n }\n }\n}\n\nfunction platformMessage(text: string): string | null {\n try {\n const { message } = JSON.parse(text) as { message?: unknown };\n return typeof message === \"string\" ? message : null;\n } catch {\n return null;\n }\n}\n\nconst STATUS = /^(?:[1-5]\\d\\d|[1-5]xx)$/;\nconst INSTANT = /^(\\d{4})-(\\d{2})-(\\d{2})(?:T(\\d{2}):(\\d{2})(?::(\\d{2})(?:\\.(\\d{1,3}))?)?(Z|[+-]\\d{2}:\\d{2})?)?$/;\nconst WORLDS = \"/api/public/worlds\";\nconst SESSIONS = \"/api/public/world-sessions\";\n\nclass Instant {\n static parse(flag: string, raw: string): number {\n const match = INSTANT.exec(raw);\n const millis = match ? Instant.fromParts(match) : null;\n if (millis === null)\n throw new WorldRequestFilterError(\n `--${flag} must be an ISO 8601 date or time (2026-10-05, 2026-10-05T14:30:00Z), not \\`${raw}\\`.`,\n );\n return millis;\n }\n\n private static fromParts(match: RegExpExecArray): number | null {\n const [year, month, day, hour, minute, second] = [1, 2, 3, 4, 5, 6].map((i) => Number(match[i] ?? 0));\n const offset = Instant.offsetMinutes(match[8]);\n if (offset === null || year < 1 || hour > 23 || minute > 59 || second > 59) return null;\n const date = new Date(0);\n date.setUTCFullYear(year, month - 1, day);\n if (date.getUTCFullYear() !== year || date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day) return null;\n date.setUTCHours(hour, minute, second, Number((match[7] ?? \"\").padEnd(3, \"0\")));\n const utc = date.getTime() - offset * 60_000;\n const utcYear = new Date(utc).getUTCFullYear();\n return utcYear < 1 || utcYear > 9999 ? null : utc;\n }\n\n private static offsetMinutes(zone: string | undefined): number | null {\n if (zone === undefined || zone === \"Z\") return 0;\n const hours = Number(zone.slice(1, 3));\n const minutes = Number(zone.slice(4, 6));\n if (hours > 23 || minutes > 59) return null;\n return (zone.startsWith(\"-\") ? -1 : 1) * (hours * 60 + minutes);\n }\n}\n\n/** The filters of a request-ledger read, checked and put in the platform's form: `via` and `status` lower-cased,\n * `since`/`until` as UTC instants (a date alone is its midnight, a time without a zone is UTC). Twin of\n * `gatewaysdk.world_requests.WorldRequestQuery`; both run `conformance/world-request-cli.json`. */\nexport class WorldRequestQuery {\n private constructor(private readonly entries: [string, string][]) {}\n\n static parse(filter: WorldRequestFilter = {}): WorldRequestQuery {\n const via = WorldRequestQuery.via(filter.via);\n const status = WorldRequestQuery.status(filter.status);\n const since = filter.since === undefined ? undefined : Instant.parse(\"since\", filter.since);\n const until = filter.until === undefined ? undefined : Instant.parse(\"until\", filter.until);\n if (since !== undefined && until !== undefined && since > until)\n throw new WorldRequestFilterError(\"--since must not be after --until.\");\n const values: [string, string | undefined][] = [\n [\"session\", filter.session],\n [\"version\", filter.version],\n [\"via\", via],\n [\"operation\", filter.operation],\n [\"status\", status],\n [\"since\", since === undefined ? undefined : new Date(since).toISOString()],\n [\"until\", until === undefined ? undefined : new Date(until).toISOString()],\n [\"limit\", filter.limit === undefined ? undefined : String(filter.limit)],\n [\"cursor\", filter.cursor],\n ];\n return new WorldRequestQuery(values.filter((entry): entry is [string, string] => entry[1] !== undefined));\n }\n\n private static via(value: string | undefined): string | undefined {\n if (value === undefined) return undefined;\n const lower = value.toLowerCase();\n if ((WORLD_REQUEST_VIAS as readonly string[]).includes(lower)) return lower;\n throw new WorldRequestFilterError(`--via must be one of ${WORLD_REQUEST_VIAS.join(\", \")}, not \\`${value}\\`.`);\n }\n\n private static status(value: string | undefined): string | undefined {\n if (value === undefined) return undefined;\n const lower = value.toLowerCase();\n if (STATUS.test(lower)) return lower;\n throw new WorldRequestFilterError(`--status must be a code (200) or a class (2xx), not \\`${value}\\`.`);\n }\n\n get filtered(): boolean {\n return this.entries.some(([key]) => key !== \"limit\");\n }\n\n params(): [string, string][] {\n return this.entries.map(([key, value]) => [key, value]);\n }\n\n search(): string {\n return this.entries.length ? `?${new URLSearchParams(this.entries).toString()}` : \"\";\n }\n}\n\n/** A world's request ledger: every request the world received, from every session and version, through every\n * door (`via`: api, ui, tool, webhook), kept for the world's life. Reading it records nothing. Twin of\n * `gatewaysdk.world_requests.WorldRequestLedger`. */\nexport class WorldRequestLedger {\n constructor(private readonly options: WorldsClientOptions = {}) {}\n\n /** A page of the world's requests, newest first; `nextCursor` reads the page after it. Narrowed to a session\n * whose engine records none: `WorldRequestsNotRecorded`. */\n list(slug: string, query: WorldRequestQuery = WorldRequestQuery.parse()): Promise<WorldRequestPage> {\n return WorldRequestsNotRecorded.mapped(\n apiRequest<WorldRequestPage>(\n this.options,\n \"GET\",\n `${WORLDS}/${encodeURIComponent(slug)}/requests${query.search()}`,\n ),\n );\n }\n\n /** One of the world's requests, with its headers and bodies. */\n get(slug: string, requestId: string): Promise<WorldRequestEntry> {\n return apiRequest(\n this.options,\n \"GET\",\n `${WORLDS}/${encodeURIComponent(slug)}/requests/${encodeURIComponent(requestId)}`,\n );\n }\n\n /** A page of one session's requests, newest first; `WorldRequestsNotRecorded` when its engine records none. */\n forSession(sessionId: string, query: WorldRequestQuery = WorldRequestQuery.parse()): Promise<WorldRequestPage> {\n return WorldRequestsNotRecorded.mapped(\n apiRequest<WorldRequestPage>(\n this.options,\n \"GET\",\n `${SESSIONS}/${encodeURIComponent(sessionId)}/requests${query.search()}`,\n ),\n );\n }\n}\n","export type SessionStatus = {\n state: string;\n ready: boolean;\n failure?: { code: string | null; message: string } | null;\n};\n\n/** How long `ready()` waits unless told otherwise, and how often it asks. */\nexport const READY_TIMEOUT_MS = 10 * 60_000;\nconst READY_POLL_MS = 2_000;\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\nexport class WorldSessionTimeout extends Error {}\nexport class WorldSessionCallError extends Error {}\n\n/** The session ended before it was ready: it FAILED to open, or was STOPPED.\n * `code` is the platform's when it named one; `browser_capacity` and\n * `host_unavailable` are worth opening again. */\nexport class WorldSessionOpenFailed extends WorldSessionCallError {\n constructor(\n readonly sessionId: string,\n readonly state: string,\n readonly code: string | null,\n reason: string | null,\n ) {\n super(\n reason === null\n ? `World session ${sessionId} ${state.toLowerCase()} before it was ready.`\n : `World session ${sessionId} failed to open: ${reason}${code ? ` (${code})` : \"\"}`,\n );\n this.name = \"WorldSessionOpenFailed\";\n }\n}\n\nconst ENDED = new Set([\"FAILED\", \"STOPPED\"]);\n\n/** Waits on a session's status until it answers calls, ends, or the wait runs\n * out; it never sleeps past its deadline. */\nexport class SessionReadiness<T extends SessionStatus> {\n constructor(\n private readonly sessionId: string,\n private readonly status: () => Promise<T>,\n ) {}\n\n async wait(timeoutMs: number = READY_TIMEOUT_MS): Promise<T> {\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n const state = await this.status();\n if (state.ready) return state;\n if (ENDED.has(state.state))\n throw new WorldSessionOpenFailed(\n this.sessionId,\n state.state,\n state.failure?.code ?? null,\n state.failure?.message ?? null,\n );\n const left = deadline - Date.now();\n if (left <= 0)\n throw new WorldSessionTimeout(\n `World session ${this.sessionId} still ${state.state} after ${Math.round(timeoutMs / 1000)}s.`,\n );\n await sleep(Math.min(READY_POLL_MS, left));\n }\n }\n}\n","import { AsyncLocalStorage } from \"async_hooks\";\nimport type { Context } from \"@opentelemetry/api\";\nimport type {\n ReadableSpan,\n Span,\n SpanProcessor,\n} from \"@opentelemetry/sdk-trace-base\";\n\nexport const SESSION_ID_ATTRIBUTE = \"gateway.session.id\";\nexport const WORLD_SESSION_ID_ATTRIBUTE =\n \"gateway.trace.metadata.world_session_id\";\n\n// AsyncLocalStorage so concurrent runs or requests never bleed into each other.\n// Held on globalThis: tsup inlines this module into every published entry\n// (splitting: false), and `worlds` must write the store `tracing` reads.\n// Every SDK copy in the process shares the key and the string value; never\n// rename or reshape them.\nconst processStorage = (name: string): AsyncLocalStorage<string> => {\n const key = Symbol.for(`@withgateway/sdk/${name}`);\n const slots = globalThis as Record<symbol, AsyncLocalStorage<string>>;\n slots[key] ??= new AsyncLocalStorage<string>();\n return slots[key];\n};\nconst currentSessionStorage = processStorage(\"session-storage\");\nconst currentWorldSessionStorage = processStorage(\"world-session-storage\");\n\n/** The session id set by the innermost enclosing `withSession()`, or `undefined`. */\nexport function getAmbientSessionId(): string | undefined {\n return currentSessionStorage.getStore();\n}\n\n/** The live world session the current code is working in, or `undefined`. */\nexport function getCurrentWorldSessionId(): string | undefined {\n return currentWorldSessionStorage.getStore();\n}\n\nfunction runIn<T>(\n storage: AsyncLocalStorage<string>,\n value: string,\n fn: () => T | Promise<T>,\n): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n storage.run(value, () => {\n Promise.resolve().then(fn).then(resolve, reject);\n });\n });\n}\n\n/**\n * Group every trace recorded inside `fn` under one session id — the twin of\n * the Python SDK's `with tracing.session(session_id): ...`. Auto-instrumented\n * spans are grouped too; the innermost session wins.\n *\n * ```typescript\n * await withSession(\"checkout-regression-001\", async () => {\n * await observe(\"turn-1\", async () => { ... });\n * });\n * ```\n */\nexport function withSession<T>(\n sessionId: string,\n fn: () => T | Promise<T>,\n): Promise<T> {\n return runIn(currentSessionStorage, sessionId, fn);\n}\n\n/**\n * Trace `fn` as work inside one live world session: spans take the world\n * session's id as their session id and carry `world_session_id` trace\n * metadata. A `withSession()` block inside still wins for the session id;\n * the metadata stays. Without `tracing.init()` nothing is recorded. Twin of\n * Python's `tracing.context.world_session`; callers use\n * `WorldSession.withTraceContext(fn)`.\n */\nexport function withWorldSession<T>(\n worldSessionId: string,\n fn: () => T | Promise<T>,\n): Promise<T> {\n return runIn(currentWorldSessionStorage, worldSessionId, () =>\n withSession(worldSessionId, fn),\n );\n}\n\n/**\n * Stamps the session id and world session id on every span at start.\n * Registered by `tracing.init()`/`initIsolated()`. A session id the span was\n * started with (or is given after it starts) wins over the innermost\n * `withSession()` / `withWorldSession()` block, as in the Python SDK.\n */\nexport class SessionSpanProcessor implements SpanProcessor {\n onStart(span: Span, _parentContext: Context): void {\n const worldSessionId = getCurrentWorldSessionId();\n if (worldSessionId)\n span.setAttribute(WORLD_SESSION_ID_ATTRIBUTE, worldSessionId);\n const sessionId = getAmbientSessionId();\n if (!sessionId || span.attributes?.[SESSION_ID_ATTRIBUTE] !== undefined)\n return;\n span.setAttribute(SESSION_ID_ATTRIBUTE, sessionId);\n }\n\n onEnd(_span: ReadableSpan): void {}\n\n async shutdown(): Promise<void> {}\n\n async forceFlush(): Promise<void> {}\n}\n","import type {\n WorldSessionTask,\n WorldTaskIdRef,\n WorldTaskRef,\n WorldTaskSpec,\n} from \"./taskSpec\";\n\n/**\n * The three shapes a task reaches `openSession` in — a bundled scenario's\n * name, a stored task's `{ id, version? }`, an inline spec — and how each is\n * told apart, labelled and checked. No task at all (`undefined`) is the\n * fourth case, an exploratory session, and is not a ref.\n */\n\nexport const isTaskIdRef = (task: WorldTaskRef): task is WorldTaskIdRef =>\n typeof task === \"object\" && task !== null && \"id\" in task;\n\nexport const isTaskSpec = (task: WorldTaskRef): task is WorldTaskSpec =>\n typeof task === \"object\" && task !== null && \"instruction\" in task;\n\n/** The label a task goes by in results: its name, `inline:<hash>` for an\n * unnamed inline task once the platform has hashed it, or the stored task's\n * name (its id until the platform has answered). */\nexport const taskLabel = (\n task: WorldTaskRef,\n info?: WorldSessionTask | null,\n): string => {\n if (typeof task === \"string\") return task;\n if (isTaskIdRef(task)) return info?.name ?? task.id;\n if (task.name) return task.name;\n return info?.hash ? `inline:${info.hash.slice(0, 12)}` : \"inline\";\n};\n\n/** A task given to `openSession` must be one of the three shapes. */\nexport const assertTaskRef = (task: WorldTaskRef): void => {\n const malformed =\n task === null ||\n (typeof task === \"string\" && !task) ||\n (isTaskIdRef(task) && !task.id) ||\n (isTaskSpec(task) && !task.instruction) ||\n (typeof task === \"object\" && !isTaskIdRef(task) && !isTaskSpec(task));\n if (malformed)\n throw new Error(\n \"openSession needs a task: a bundled task name, a stored task { id, version? } or { instruction, seed?, grader?, metadata? } — or none at all for an exploratory session\",\n );\n};\n","import type { WorldDeprecation } from \"./session\";\n\nexport const TOOL_CONTRACT_UNREAD = \"tool-contract-unread\";\n\ntype NoticeKind = { label: string; next: string; refusesRun: boolean };\n\nconst DEPRECATION: NoticeKind = { label: \"deprecated\", next: \"Instead\", refusesRun: false };\n\nconst NOTICE_KINDS = new Map<string, NoticeKind>([\n [TOOL_CONTRACT_UNREAD, { label: \"warning\", next: \"Then\", refusesRun: true }],\n]);\n\n/** One notice from a world answer's `deprecations`, as the CLI prints it (`fixtures/tasks/world-notice-vectors.json`). */\nexport class WorldNotice {\n private constructor(\n readonly notice: WorldDeprecation,\n private readonly kind: NoticeKind,\n ) {}\n\n static of(notice: WorldDeprecation): WorldNotice {\n return new WorldNotice(notice, NOTICE_KINDS.get(notice.code) ?? DEPRECATION);\n }\n\n get refusesRun(): boolean {\n return this.kind.refusesRun;\n }\n\n line(): string {\n const { code, message, replacement } = this.notice;\n return `${this.kind.label} (${code}): ${message} ${this.kind.next}: ${replacement}`;\n }\n}\n\n/** A run refused before its agent started: the platform could not read a world's tools. */\nexport class WorldToolsUnread extends Error {\n readonly code: string;\n\n constructor(\n readonly world: string,\n readonly notice: WorldNotice,\n ) {\n super(\n `refused before the agent ran, nothing filed: world ${world} has no readable tools: ` +\n `${notice.notice.message} Then: ${notice.notice.replacement}`,\n );\n this.name = \"WorldToolsUnread\";\n this.code = notice.notice.code;\n }\n\n static refuse(world: string, notices: WorldDeprecation[]): void {\n const refusing = notices.map((notice) => WorldNotice.of(notice)).find((notice) => notice.refusesRun);\n if (refusing) throw new WorldToolsUnread(world, refusing);\n }\n}\n","/**\n * A world's grade as the SDK reads it, by the one score rule every grader\n * answers by: a finite number from 0 to 1, a passed check 1, a failed one 0,\n * null ungraded. The World Host's twin is `gatewaysdk/environment/score.py`;\n * both are pinned by `gatewaysdk/fixtures/tasks/grade-vectors.json`.\n */\n\nexport const messageOf = (error: unknown): string =>\n (error instanceof Error ? error.message || error.name : String(error)) ||\n \"Error\";\n\nexport type GradeResult = {\n reward: number | null;\n rewards: Record<string, number>;\n /** Why there is no reward: `no grader` on an exploratory session. */\n reason?: string;\n /** Why this world could not grade; the task's grade is then that error. */\n error?: string;\n /** The task's cross-world verifiers anchored on this session, by name:\n * each its own reward and named rewards, or `error` when it could not\n * grade (evidence missing, verify.py failed) — null, never zero. */\n verifiers?: Record<string, VerifierGrade>;\n raw: unknown;\n};\n\nexport type VerifierGrade = {\n reward: number | null;\n rewards: Record<string, number>;\n error?: string;\n};\n\nexport class Score {\n static readonly RULE = \"a score is a number from 0 to 1\";\n\n static admits(value: number): boolean {\n return Number.isFinite(value) && value >= 0 && value <= 1;\n }\n\n /** Every number among `scores` that is not a score, as `'<key>' = <value>`\n * and the rule, or null when all of them are. Pairs, not a map, so that no\n * key hides another. */\n static problem(scores: Iterable<[string, unknown]>): string | null {\n const refused = [...scores].flatMap(([key, value]) =>\n typeof value === \"number\" && !Score.admits(value)\n ? [`'${key}' = ${String(value)}`]\n : [],\n );\n return refused.length ? `${refused.join(\", \")}; ${Score.RULE}` : null;\n }\n}\n\n/** A world's grade that is never filed: it is not an object, a number in it\n * is not a score (a World Host older than the rule), a check is named both\n * beside and inside its rewards, or its rewards or verifiers are not objects\n * by name. */\nexport class GradeRefused extends Error {\n readonly name = \"GradeRefused\";\n}\n\ntype Numbers = { reward: number | null; rewards: Record<string, number> };\n\nexport class GradePayload {\n /** A grade payload's numbers, checked: every number in it must be a score,\n * and its rewards and verifiers objects by name, or the grade is refused; a\n * cross-world verifier's grade that breaks either rule is that verifier's\n * error, the way the World Host answers one that could not grade. */\n static read(raw: unknown): Omit<GradeResult, \"raw\"> {\n if (!GradePayload.objectOrAbsent(raw))\n throw new GradeRefused(\"the grade is not an object\");\n const record = GradePayload.record(raw);\n const problem =\n GradePayload.problem(record) ??\n GradePayload.verifiersProblem(record.verifiers);\n if (problem) throw new GradeRefused(problem);\n const verifiers = GradePayload.verifiers(record.verifiers);\n return {\n ...GradePayload.numbers(record),\n ...(typeof record.reason === \"string\" ? { reason: record.reason } : {}),\n ...(typeof record.error === \"string\" ? { error: record.error } : {}),\n ...(verifiers ? { verifiers } : {}),\n };\n }\n\n /** A world whose grade call failed (the platform refused it, the host had\n * lost the session): that world's error, never a score. */\n static failedCall(error: unknown): GradeResult {\n return { ...GradePayload.failed(messageOf(error)), raw: null };\n }\n\n private static problem(record: Record<string, unknown>): string | null {\n if (!GradePayload.objectOrAbsent(record.rewards))\n return \"the grade's rewards are not an object\";\n const scores = Score.problem(GradePayload.scores(record));\n if (scores) return `the grade answered ${scores}`;\n const twice = GradePayload.twice(record);\n return twice.length\n ? `the grade answered ${twice.map((key) => `'${key}'`).join(\", \")} both beside and inside rewards`\n : null;\n }\n\n private static twice(record: Record<string, unknown>): string[] {\n return Object.entries(GradePayload.record(record.rewards))\n .filter(\n ([key, value]) =>\n key !== \"reward\" &&\n typeof value === \"number\" &&\n typeof record[key] === \"number\",\n )\n .map(([key]) => key);\n }\n\n private static verifiersProblem(value: unknown): string | null {\n return GradePayload.objectOrAbsent(value)\n ? null\n : \"the grade's verifiers are not an object\";\n }\n\n private static scores(record: Record<string, unknown>): [string, unknown][] {\n return [\n [\"reward\", record.reward],\n ...Object.entries(GradePayload.record(record.rewards)),\n ...Object.entries(record).filter(\n ([key]) => key !== \"reward\" && key !== \"rewards\",\n ),\n ];\n }\n\n private static isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n }\n\n private static objectOrAbsent(value: unknown): boolean {\n return value === undefined || value === null || GradePayload.isRecord(value);\n }\n\n private static record(value: unknown): Record<string, unknown> {\n return GradePayload.isRecord(value) ? value : {};\n }\n\n /** `reward`, and every numeric key under `rewards` (the host's shape) or at\n * the top level (a bundled verifier's). */\n private static numbers(record: Record<string, unknown>): Numbers {\n const rewards: Record<string, number> = {};\n for (const [key, value] of Object.entries(\n GradePayload.record(record.rewards),\n ))\n if (typeof value === \"number\") rewards[key] = value;\n for (const [key, value] of Object.entries(record))\n if (key !== \"reward\" && typeof value === \"number\") rewards[key] = value;\n return {\n reward: typeof record.reward === \"number\" ? record.reward : null,\n rewards,\n };\n }\n\n private static verifiers(\n value: unknown,\n ): Record<string, VerifierGrade> | undefined {\n if (!GradePayload.isRecord(value)) return undefined;\n return Object.fromEntries(\n Object.entries(value).map(([name, grade]) => [\n name,\n GradePayload.verifier(name, grade),\n ]),\n );\n }\n\n private static verifier(name: string, grade: unknown): VerifierGrade {\n if (!GradePayload.isRecord(grade))\n return GradePayload.failed(`the grade's verifier '${name}' is not an object`);\n const problem = GradePayload.problem(grade);\n if (problem) return GradePayload.failed(problem);\n return {\n ...GradePayload.numbers(grade),\n ...(typeof grade.error === \"string\" ? { error: grade.error } : {}),\n };\n }\n\n private static failed(error: string): VerifierGrade {\n return { reward: null, rewards: {}, error };\n }\n}\n","import { randomUUID } from \"node:crypto\";\n\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\nimport {\n BrowserActionRecorder,\n PLATFORM_SESSION_HEADER,\n SURFACE_KINDS,\n WorldSurfaceUnavailable,\n assertBrowserTier,\n assertSessionAuthMode,\n computerUseToolkit,\n openBrowser,\n uiEntryUrl,\n type BrowserActionEvent,\n type BrowserMode,\n type BrowserTier,\n type SessionAuthMode,\n type PlaywrightLike,\n type SessionSurfaces,\n type WorldBrowser,\n type WorldSurfaceKind,\n} from \"./browser\";\nimport type { RepairAnswer } from \"./browserReconnect\";\nimport {\n NativeComputer,\n type NativeComputerKinds,\n type NativeComputerOptions,\n type NativeComputerProvider,\n} from \"./nativeComputer\";\nimport type { WorldTaskSummary } from \"./tasks\";\nimport { REQUEST_LOG_PAGE_MAX, serializeCallBody } from \"./sessionContract\";\nimport { modelToolName, schemaFromSignature } from \"./toolSchema\";\nimport type { WorldRequestPage } from \"./requestLog\";\nimport { WorldRequestLedger, WorldRequestQuery } from \"./requestLedger\";\nimport {\n SessionReadiness,\n WorldSessionCallError,\n WorldSessionTimeout,\n} from \"./sessionReadiness\";\nimport { withWorldSession } from \"../tracing/session\";\nimport { assertTaskRef, isTaskIdRef, isTaskSpec, taskLabel } from \"./taskRef\";\nimport { WorldToolsUnread } from \"./worldNotice\";\nimport { GradePayload, type GradeResult } from \"./grade\";\nimport type {\n WorldTaskSpec,\n WorldTaskRef,\n WorldSessionTask,\n} from \"./taskSpec\";\n\nexport { isTaskIdRef, isTaskSpec, taskLabel } from \"./taskRef\";\n\n/**\n * LIVE WORLD SESSIONS from TypeScript: your agent, the platform's container.\n *\n * The other two ways of running a world each give up something. Pulling the\n * bundle and executing it locally tests your agent against a COPY — your\n * python, your sqlite, your machine's idea of the environment. Dispatching a\n * hosted run gives you the real container but runs the platform's agent\n * inside it, so your agent never touches the world.\n *\n * A session is both: the platform boots the task's container and holds it\n * warm, and every `call()` here executes inside THAT container. Your agent\n * stays where it is — this file is just the wire.\n *\n * const world = await openWorld(\"revenue-ops-sim@main\");\n * const session = await openSession(world.slug, { task: \"revops-mara-dedupe-contacts\" });\n * await session.ready(); // wait for the container\n * await session.call(\"crm_search\", { entity: \"deals\" });\n * await session.withTraceContext(() => myAgent(session)); // traced under session.sessionId\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\nexport type * from \"./taskSpec\";\n\nexport type SeedResult = {\n seeded: number;\n mode: \"append\" | \"replace\";\n entity_counts: Record<string, number>;\n};\n\n/** One row of the session's call log. */\nexport type WorldSessionCall = {\n seq: number;\n kind: string;\n tool: string | null;\n args: unknown;\n result: unknown;\n error: string | null;\n completedAt: string | null;\n};\n\nexport type WorldSessionState = {\n sessionId: string;\n state: string;\n ready: boolean;\n versionId: string;\n contentHash: string;\n taskName: string | null;\n /** Where the task came from and what it is; absent on platforms that\n * predate session tasks, in which case it is derived from `taskName`. */\n task?: WorldSessionTask;\n /** The task's objective — present when the session was opened (not on a\n * bare status read), so a client never needs the bundle on disk. */\n instruction?: string | null;\n /** The tools this task serves. */\n tools?: WorldToolSpec[];\n /** When the fleet reaps this session unless a call lands first; null for\n * a pinned session (never reaped). Absent on platforms that predate it. */\n idleExpiresAt?: string | null;\n pinned?: boolean;\n /** Where the session answers besides `tools` — see worlds/browser.ts. */\n surfaces?: SessionSurfaces;\n /** Notices about the world's shape (an api bundle is a deprecated layout;\n * schema worlds are the supported shape), with what to run instead. Empty\n * for a schema world; absent on platforms that predate the notice. */\n deprecations?: WorldDeprecation[];\n /** Why a FAILED session failed to open, when the platform named it. */\n failure?: { code: string | null; message: string } | null;\n};\n\n/** A request the old world received has an `at` before `boundaryAt`; one the new world received, after it. */\nexport type WorldSessionRestart = {\n previousVersionId: string;\n versionId: string;\n pin: { ref: string | null; versionId: string | null };\n boundarySeq: number;\n boundaryAt: string;\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, VerifierGrade } from \"./grade\";\nexport {\n WorldSessionCallError,\n WorldSessionOpenFailed,\n WorldSessionTimeout,\n} from \"./sessionReadiness\";\nexport { modelToolName, schemaFromSignature };\n\n/** How long one call may take end to end (container claim + execution). */\nconst CALL_TIMEOUT_MS = 3 * 60_000;\nconst CALL_POLL_MS = 400;\n/** How long a grade the platform's judge finalizes may take: the model's own\n * timeout and retries, plus the worker's queue backoff. Polled slowly. */\nconst JUDGED_GRADE_TIMEOUT_MS = 15 * 60_000;\nconst JUDGED_GRADE_POLL_MS = 2_000;\nconst EXPORT_PAGE = 500;\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\nexport class WorldSession {\n constructor(\n readonly sessionId: string,\n private current: WorldSessionState,\n private readonly options: WorldsClientOptions,\n ) {}\n\n /** The task's display name: a bundled scenario's, or the inline spec's\n * `name` (null when the spec was unnamed). `task` is the same. */\n get taskName(): string | null {\n return this.current.taskName;\n }\n get task(): string | null {\n return this.taskName;\n }\n\n /** `{idleExpiresAt, pinned}` as of the last state read: when the fleet\n * reaps the session (null once pinned), and whether it is pinned. */\n get idle(): { idleExpiresAt: string | null; pinned: boolean } {\n return {\n idleExpiresAt: this.current.idleExpiresAt ?? null,\n pinned: this.current.pinned ?? false,\n };\n }\n\n /** The platform's notices about the world this session runs on (empty\n * for a schema world). Printed by the CLI on stderr at open. */\n get deprecations(): WorldDeprecation[] {\n return this.current.deprecations ?? [];\n }\n\n /** The task this session runs: bundled scenario, stored task or inline\n * spec, its name, hash and the caller's metadata. */\n get taskInfo(): WorldSessionTask {\n return (\n this.current.task ?? {\n source: \"bundled\",\n name: this.current.taskName,\n hash: null,\n metadata: {},\n }\n );\n }\n\n /** What this task asks for — the bundle's instruction.md, or the inline\n * spec's `instruction`. */\n get instruction(): string | null {\n return this.current.instruction ?? null;\n }\n\n get versionId(): string {\n return this.current.versionId;\n }\n\n /** Whether the session answered ready as of the last state read (the open,\n * a `status()`, or the poll inside `ready()`); no request is made. */\n get isReady(): boolean {\n return this.current.ready;\n }\n\n /** `api` / `ui` / `browser` are present exactly when the world declares\n * them AND the session was opened asking for them. */\n async surfaces(): Promise<SessionSurfaces> {\n if (!this.current.surfaces) await this.status();\n return this.current.surfaces ?? { tools: { kind: \"rendezvous\" } };\n }\n\n /** Base URL of the world's own HTTP API for this session. */\n async api(): Promise<string> {\n const { api } = await this.surfaces();\n if (!api)\n throw new WorldSurfaceUnavailable(\n \"api\",\n \"open the session with surfaces: ['api'] on an api-type world\",\n );\n return api.url;\n }\n\n /** Headers every request to `api()` needs: a World Host session's token in the\n * platform's `X-World-Session` header, which every world takes; `{}` for a pod\n * or hosted twin, which answers with the world's own declared auth. */\n async apiHeaders(): Promise<Record<string, string>> {\n const { api } = await this.surfaces();\n return api?.token ? { [PLATFORM_SESSION_HEADER]: api.token } : {};\n }\n\n /** URL of the world's UI entry page for this session. */\n async ui(): Promise<string> {\n const { ui } = await this.surfaces();\n if (!ui)\n throw new WorldSurfaceUnavailable(\n \"ui\",\n \"open the session with surfaces: ['ui'] on a world that declares [ui]\",\n );\n return uiEntryUrl(ui);\n }\n\n /** A Playwright browser on this session's UI: `hosted` drives the one the\n * platform runs next to the world, `local` launches one here, `auto`\n * prefers hosted. Call `close()` when done.\n *\n * Every action is reported to the platform under `agentId` (default:\n * `GATEWAY_AGENT_ID` or a fresh `agent-<hex>`) so the session page shows\n * this agent's own timeline — several agents may share one session and\n * one hosted browser. `record: false` opts out. */\n async browser(\n opts: {\n mode?: BrowserMode;\n headless?: boolean;\n playwright?: PlaywrightLike;\n agentId?: string;\n record?: boolean;\n } = {},\n ): Promise<WorldBrowser> {\n const { agentId, record = true, ...rest } = opts;\n return openBrowser(await this.surfaces(), {\n ...rest,\n recorder: record ? this.browserRecorder(agentId) : null,\n repair: () => this.repairBrowser(),\n });\n }\n\n /** Ask the platform to make this session's hosted browser reachable again\n * after its connection dropped: `healthy` (reconnect now), `replaced` (a new,\n * blank browser behind the same wsUrl; reconnect and reopen your page) or\n * `starting` (ask again in `retryAfterMs`). `browser()` does this on its\n * own; call it when you drive your own Playwright against `wsUrl`. */\n async repairBrowser(): Promise<RepairAnswer> {\n return apiRequest<RepairAnswer>(\n this.options,\n \"POST\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/browser-repair`,\n {},\n );\n }\n\n /** The reporter `browser()` uses; exposed for a page you drive yourself. */\n browserRecorder(agentId?: string): BrowserActionRecorder {\n const path = `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/browser-events`;\n const id =\n agentId ??\n process.env.GATEWAY_AGENT_ID ??\n `agent-${randomUUID().replace(/-/g, \"\").slice(0, 8)}`;\n return new BrowserActionRecorder(\n async (events: BrowserActionEvent[]) => {\n await apiRequest(this.options, \"POST\", path, { events });\n },\n id,\n {\n // Continue this agent's timeline where the platform has it, so a reopened id 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 browser as a provider's own pixel-based computer-use tool: `anthropic`\n * (`computer_toolset_20260801`), `openai` (Responses `computer`),\n * `anthropic-computer-20251124` or `openai-preview`. See `nativeComputer/`. */\n nativeComputer<P extends NativeComputerProvider = \"anthropic\">(\n browser: WorldBrowser,\n provider: P = \"anthropic\" as P,\n options: NativeComputerOptions = {},\n ): NativeComputerKinds[P] {\n return NativeComputer.forProvider(provider, browser, options) as NativeComputerKinds[P];\n }\n\n /** The session's latest platform state (one request, no waiting). */\n async status(): Promise<WorldSessionState> {\n return this.refresh(\n await apiRequest<WorldSessionState>(\n this.options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}`,\n ),\n );\n }\n\n /** The world started over under the same id, URLs and token, on what its pin (or `version`, which becomes\n * its pin) resolves to now: base data plus the task's seed. A grade then reads only the new world's requests. */\n async restart(\n opts: { version?: string } = {},\n ): Promise<WorldSessionState & { restart: WorldSessionRestart }> {\n const fresh = await apiRequest<\n WorldSessionState & { restart: WorldSessionRestart }\n >(\n this.options,\n \"POST\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/restart`,\n opts.version ? { version: opts.version } : {},\n );\n this.refresh(fresh);\n return fresh;\n }\n\n // A status read carries neither the objective nor the open's notices; keep the ones we opened with.\n private refresh(fresh: WorldSessionState): WorldSessionState {\n this.current = {\n instruction: this.current.instruction,\n tools: this.current.tools,\n surfaces: this.current.surfaces,\n task: this.current.task,\n deprecations: this.current.deprecations,\n ...fresh,\n };\n return this.current;\n }\n\n /**\n * Wait until the session answers calls: a World Host holds it, or the\n * process inside a pod has asked the platform for work. Throws\n * `WorldSessionOpenFailed` (with the platform's reason) when it ended\n * first, and `WorldSessionTimeout` when `timeoutMs` (default ten minutes)\n * ran out while it was still starting.\n */\n async ready(opts: { timeoutMs?: number } = {}): Promise<WorldSessionState> {\n return new SessionReadiness(this.sessionId, () => this.status()).wait(\n opts.timeoutMs,\n );\n }\n\n /** Enqueue one interaction and wait for the container's answer. */\n private async exchange(\n body: {\n kind?: \"call\" | \"grade\" | \"reset\" | \"state\" | \"seed\" | \"close\";\n tool?: string;\n args?: unknown;\n /** Grade only: the agent's report, for a rubric judge. */\n report?: string;\n },\n timeoutMs?: number,\n ): Promise<unknown> {\n // Measured the way the route measures it; over the limit nothing is sent.\n serializeCallBody(body);\n const enqueued = await apiRequest<{\n callId: string;\n seq: number;\n /** The platform's worker finalizes this call (a rubric grade). */\n pending?: boolean;\n }>(\n this.options,\n \"POST\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/calls`,\n body,\n );\n const { callId } = enqueued;\n const judged = enqueued.pending === true;\n const budgetMs =\n timeoutMs ?? (judged ? JUDGED_GRADE_TIMEOUT_MS : CALL_TIMEOUT_MS);\n const pollMs = judged ? JUDGED_GRADE_POLL_MS : CALL_POLL_MS;\n const deadline = Date.now() + budgetMs;\n for (;;) {\n const call = await apiRequest<{\n done: boolean;\n state: string;\n result: unknown;\n error: string | null;\n }>(\n this.options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/calls/${encodeURIComponent(callId)}`,\n );\n if (call.done) {\n if (call.error) throw new WorldSessionCallError(call.error);\n return call.result;\n }\n if (Date.now() > deadline)\n throw new WorldSessionTimeout(\n judged\n ? `Grade ${callId} still ${call.state} after ${Math.round(budgetMs / 1000)}s — the judge has not answered; the platform finalizes the call on its own, read it back with export().`\n : `Call ${callId} still ${call.state} after ${Math.round(budgetMs / 1000)}s — the container may have died.`,\n );\n await sleep(pollMs);\n }\n }\n\n /**\n * Run one of the world's tools INSIDE the container. The arguments and the\n * result are the world's own contract — this layer neither validates nor\n * reshapes them, so a tool error reads exactly as it would in a hosted run.\n */\n async call(\n tool: string,\n args: Record<string, unknown> = {},\n opts: { timeoutMs?: number } = {},\n ): Promise<unknown> {\n return this.exchange({ kind: \"call\", tool, args }, opts.timeoutMs);\n }\n\n /**\n * THE WORLD'S TOOLS, READY TO HAND TO A MODEL. Schemas come from the\n * world's own signatures and implementations call into this session, so a\n * caller never writes — and never has to re-sync — a tool map of their own:\n *\n * const { schemas, impls } = await session.toolkit();\n * await runMyAgent(impls, schemas, session.instruction);\n *\n * A tool added to the world shows up here on the next run; a tool renamed\n * in the world renames here too, instead of failing at call time against a\n * hand-written map that still remembers the old name.\n */\n async toolkit(): Promise<WorldToolkit> {\n let specs = this.current.tools;\n if (!specs) specs = (await this.status()).tools ?? [];\n const impls: WorldToolkit[\"impls\"] = Object.create(null);\n for (const spec of specs) {\n const alias = modelToolName(spec.name);\n if (Object.hasOwn(impls, alias))\n throw new WorldSessionCallError(`Model tool name collision: ${alias}`);\n impls[alias] = (args: Record<string, unknown> = {}) =>\n this.call(spec.name, args);\n }\n return { schemas: specs.map(schemaFromSignature), impls, specs };\n }\n\n /** Run the task's grader against the container's END STATE. Graders answer\n * in one of two shapes: the scalar with named rewards beside it\n * (`{reward, check_a, check_b}`, a task's own `grade.py`), or the named\n * rewards nested under `rewards` (the api, mock-tools and World Host\n * runners). Both land in `rewards`.\n *\n * A rubric grade is finalized by the platform's judge, not the container:\n * the platform answers the enqueue with `pending: true`, and this waits on\n * the judge's budget (15 min) instead of a call's. `timeoutMs` overrides\n * either. `report` is the agent's own account of what it did and found,\n * handed to the judge as its claim beside the evidence (the state and the\n * calls); assertions and python graders ignore it. `worlds` names the\n * task's other sessions by alias (`{alias: sessionId}`): the platform\n * reads each one's evidence and hands it to the cross-world verifiers\n * anchored on this session, whose grades come back under `verifiers`. A\n * score that is not a number from 0 to 1 is refused by key and value\n * (`GradeRefused`); a verifier's is that verifier's `error`. */\n async grade(\n opts: {\n timeoutMs?: number;\n report?: string;\n worlds?: Record<string, string>;\n } = {},\n ): Promise<GradeResult> {\n const raw = (await this.exchange(\n {\n kind: \"grade\",\n ...(opts.report !== undefined ? { report: opts.report } : {}),\n ...(opts.worlds && Object.keys(opts.worlds).length > 0\n ? { worlds: opts.worlds }\n : {}),\n },\n opts.timeoutMs,\n )) as Record<string, unknown> | null;\n return { ...GradePayload.read(raw), raw };\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 /** One page of the session's entries in its world's request ledger, newest\n * first and without bodies: at most `limit` after `cursor` (the last page's\n * `nextCursor`). Reading it records nothing in the session. */\n async requests(\n opts: { cursor?: string; limit?: number } = {},\n ): Promise<WorldRequestPage> {\n return new WorldRequestLedger(this.options).forSession(\n this.sessionId,\n WorldRequestQuery.parse({ cursor: opts.cursor, limit: opts.limit ?? REQUEST_LOG_PAGE_MAX }),\n );\n }\n\n private page<T>(route: string, limit: number, cursor?: string): Promise<T> {\n const query = new URLSearchParams({ limit: String(limit) });\n if (cursor) query.set(\"cursor\", cursor);\n return apiRequest<T>(\n this.options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/${route}?${query.toString()}`,\n );\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 page = await this.page<{\n calls: Record<string, unknown>[];\n nextCursor?: string | null;\n }>(\"calls\", EXPORT_PAGE, cursor);\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 * Run `fn` as work inside this session: spans it records take `sessionId`\n * as their session id and carry `world_session_id` trace metadata, so the\n * agent's traces land in the same session as the platform's traces of this\n * session's tool calls. A `withSession()` block inside still wins for the\n * session id. No effect before `tracing.init()`. `runSessions` wraps each\n * agent call in it.\n *\n * ```typescript\n * await session.withTraceContext(() => myAgent(toolkit, session.instruction));\n * ```\n */\n withTraceContext<T>(fn: () => T | Promise<T>): Promise<T> {\n return withWorldSession(this.sessionId, fn);\n }\n}\n\n/**\n * Attach to a session that already exists — resuming after a crash, or\n * driving a session someone else opened (a container started by hand on a\n * self-hosted install, a session opened by CI and handed to a developer).\n */\nexport async function attachSession(\n sessionId: string,\n options: WorldsClientOptions = {},\n): Promise<WorldSession> {\n const state = await apiRequest<WorldSessionState>(\n options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(sessionId)}`,\n );\n return new WorldSession(sessionId, state, options);\n}\n\nexport type OpenSessionOptions = {\n versionId?: string;\n reuseWarm?: boolean;\n /** More than `tools`: `[\"api\"]`, `[\"ui\"]`, `[\"browser\"]`. The platform\n * refuses (HTTP 400) rather than quietly serving less than asked. */\n surfaces?: WorldSurfaceKind[];\n /** Capacity for a World Host session's browser: `standard` (spot, may be\n * reclaimed) or `premium` (on-demand). Unset, the organization's default. */\n browserTier?: BrowserTier;\n /** `open`: the session asks for no credential; its api and ui answer on a\n * capability hostname whose url is the secret. Unset, the world's\n * `[auth] mode`. World Host sessions only. */\n auth?: SessionAuthMode;\n options?: WorldsClientOptions;\n};\n\nconst OPEN_SESSION_OPTION_KEYS: ReadonlySet<string> = new Set([\n \"task\",\n \"versionId\",\n \"reuseWarm\",\n \"surfaces\",\n \"browserTier\",\n \"auth\",\n \"options\",\n]);\n\n/** The second argument is an options bag only when every key is one of\n * `OpenSessionOptions` (+ `task`); any other object is the positional task\n * and is validated as one, so a misspelt spec is refused, not opened bare. */\nconst isOpenSessionOptions = (\n value: unknown,\n): value is OpenSessionOptions & { task?: WorldTaskRef } =>\n typeof value === \"object\" &&\n value !== null &&\n Object.keys(value).every((key) => OPEN_SESSION_OPTION_KEYS.has(key));\n\n/**\n * Open a live session on a world. Returns as soon as the platform has\n * accepted it — call `ready()` to wait for the container.\n *\n * `task` is a bundled scenario's name, a stored task's `{ id, version? }`\n * or an inline `WorldTaskSpec` (the latter two need a host engine world — the\n * platform answers 400 for a pod world). Omitted, the session is EXPLORATORY:\n * the platform records an inline `{instruction: \"exploratory session\"}` with\n * no grader as `task.source: \"none\"`, and `grade()` answers\n * `{reward: null, reason: \"no grader\"}`. The older positional form\n * `openSession(slug, \"task-name\", opts)` still works.\n */\nexport async function openSession(\n slugOrRef: string,\n task?: OpenSessionOptions & { task?: WorldTaskRef },\n): Promise<WorldSession>;\nexport async function openSession(\n slugOrRef: string,\n task: WorldTaskRef,\n opts?: OpenSessionOptions,\n): Promise<WorldSession>;\nexport async function openSession(\n slugOrRef: string,\n taskOrOpts:\n WorldTaskRef | (OpenSessionOptions & { task?: WorldTaskRef }) = {},\n positionalOpts: OpenSessionOptions = {},\n): Promise<WorldSession> {\n const { task, ...opts } = isOpenSessionOptions(taskOrOpts)\n ? taskOrOpts\n : { task: taskOrOpts as WorldTaskRef, ...positionalOpts };\n if (task !== undefined) assertTaskRef(task);\n const options = opts.options ?? {};\n const unknown = (opts.surfaces ?? []).filter(\n (s) => !(SURFACE_KINDS as readonly string[]).includes(s),\n );\n if (unknown.length)\n throw new Error(\n `Unknown world surfaces: ${unknown.join(\", \")}; choose from ${SURFACE_KINDS.join(\", \")}`,\n );\n if (opts.browserTier !== undefined) assertBrowserTier(opts.browserTier);\n if (opts.auth !== undefined) assertSessionAuthMode(opts.auth);\n const at = slugOrRef.indexOf(\"@\");\n const slug = at === -1 ? slugOrRef : slugOrRef.slice(0, at);\n const ref = at === -1 ? \"\" : slugOrRef.slice(at + 1);\n const state = await apiRequest<WorldSessionState & { reusedWarm: boolean }>(\n options,\n \"POST\",\n \"/api/public/world-sessions\",\n {\n ...(opts.versionId\n ? { versionId: opts.versionId }\n : { slug, ...(ref && { ref }) }),\n ...(task === undefined ? {} : { task }),\n ...(opts.reuseWarm === undefined ? {} : { reuseWarm: opts.reuseWarm }),\n ...(opts.surfaces?.length ? { surfaces: opts.surfaces } : {}),\n ...(opts.browserTier === undefined\n ? {}\n : { browserTier: opts.browserTier }),\n ...(opts.auth === undefined ? {} : { auth: opts.auth }),\n },\n );\n return new WorldSession(state.sessionId, state, options);\n}\n\nexport type SessionRunResult = {\n /** The task's name, or `inline:<hash>` for an unnamed inline task. */\n task: string;\n sessionId: string;\n reward: number | null;\n rewards: Record<string, number>;\n /** Set when the task threw instead of grading. */\n error?: string;\n};\n\nexport type SessionRunReport = {\n results: SessionRunResult[];\n /** Mean reward over every task, counting failures as 0. */\n mean: number;\n /** Tasks that never graded: the session did not open or become ready, the\n * agent threw, or grading failed. Any failure fails the run — a 0 an agent\n * earned and a session that never opened are not the same result. */\n failed: number;\n /** True when no task failed and `mean >= failUnder` (or no gate was set). */\n passed: boolean;\n};\n\n/**\n * RUN MANY TASKS IN PARALLEL, one warm container each.\n *\n * Parallelism against live worlds is the normal case — a suite is a dozen\n * tasks and each needs its own container, because two agents sharing one\n * world state would corrupt both episodes. Every caller was writing the same\n * pool, the same per-task open/ready/toolkit/grade/close, and the same\n * \"don't let one failure kill the run\" logic, so it belongs here:\n *\n * const report = await runSessions({\n * world: \"revenue-ops-sim@main\",\n * tasks, // default: every task in the world\n * concurrency: 4,\n * failUnder: 0.7,\n * agent: async ({ toolkit, instruction }) =>\n * myAgent(toolkit.impls, toolkit.schemas, instruction),\n * });\n *\n * The handler gets a ready session with its toolkit already bound, and runs\n * inside `session.withTraceContext`; grading, closing (warm) and aggregation\n * are handled. A task that throws scores 0 and records why — the tasks that\n * 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 (a pinned one's own task list, never\n // the tip's), so a push mid-suite cannot split the results across two worlds.\n const { openWorld, openWorldVersion } = await import(\"./index\");\n const world = versionId\n ? await openWorldVersion(opts.world.split(\"@\", 1)[0]!, versionId, options)\n : await openWorld(opts.world, options);\n tasks = tasks ?? world.tasks.map((t) => t.name);\n versionId = versionId ?? world.version.versionId;\n }\n\n const results: SessionRunResult[] = [];\n let next = 0;\n await Promise.all(\n Array.from({ length: Math.min(concurrency, tasks.length) }, async () => {\n while (next < tasks!.length) {\n const taskRef = tasks![next++];\n let task = taskLabel(taskRef);\n let session: WorldSession | null = null;\n let keepWarm = opts.keepWarm ?? true;\n try {\n session = await openSession(opts.world, {\n task: taskRef,\n versionId,\n options,\n });\n task = taskLabel(taskRef, session.taskInfo);\n WorldToolsUnread.refuse(opts.world.split(\"@\", 1)[0]!, session.deprecations);\n await session.ready();\n const toolkit = await session.toolkit();\n const live = session;\n await live.withTraceContext(() =>\n opts.agent({\n session: live,\n toolkit,\n instruction:\n live.instruction ??\n (isTaskSpec(taskRef) ? taskRef.instruction : task),\n task,\n taskRef,\n }),\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 if (error instanceof WorldToolsUnread) keepWarm = false;\n const result: SessionRunResult = {\n task,\n sessionId: session?.sessionId ?? \"\",\n reward: 0,\n rewards: {},\n // An empty message reads as \"no error\" to a truthiness check; 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 fleet's idle TTL reaps it.\n await session\n ?.close({ keepWarm })\n .catch(() => undefined);\n }\n }\n }),\n );\n\n const mean =\n results.reduce((sum, r) => sum + (r.reward ?? 0), 0) /\n (results.length || 1);\n const failed = results.filter((r) => r.error).length;\n return {\n results: results.sort((a, b) => a.task.localeCompare(b.task)),\n mean,\n failed,\n passed:\n failed === 0 && (opts.failUnder === undefined || mean >= opts.failUnder),\n };\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\n\n/** Mirrors `WorldSessionListItemSchema` (web/features/public-api/types/world-sessions.ts). */\nexport type WorldSessionListItem = {\n sessionId: string;\n slug: string;\n containerId: string;\n state: string;\n ready: boolean;\n versionId: string;\n contentHash: string;\n taskName: string | null;\n engine: string;\n pinned: boolean;\n surfaces: string[];\n createdAt: string;\n lastUsedAt: string;\n};\n\n/** A World Host session's states (`SessionState` in shared `worldSessions.ts`). */\nexport const SESSION_STATES = [\n \"PROVISIONING\",\n \"RUNNING\",\n \"IDLE\",\n \"STOPPING\",\n \"STOPPED\",\n \"FAILED\",\n \"LOST\",\n] as const;\n\nexport type ListSessionsFilter = {\n /** One of SESSION_STATES. */\n state?: string;\n slug?: string;\n limit?: number;\n};\n\n/** The project's sessions in every state, newest first; `state` narrows to one. */\nexport async function listSessions(\n filter: ListSessionsFilter = {},\n options: WorldsClientOptions = {},\n): Promise<WorldSessionListItem[]> {\n const params = new URLSearchParams();\n if (filter.state) params.set(\"state\", filter.state);\n if (filter.slug) params.set(\"slug\", filter.slug);\n if (filter.limit !== undefined) params.set(\"limit\", String(filter.limit));\n const qs = params.toString();\n const res = await apiRequest<{ sessions: WorldSessionListItem[] }>(\n options,\n \"GET\",\n `/api/public/world-sessions${qs ? `?${qs}` : \"\"}`,\n );\n return res.sessions;\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\nimport type { WorldTaskSpec } from \"./session\";\n\n/**\n * STORED WORLD TASKS: a task spec kept by the project, outside any bundle.\n *\n * An inline task (`openSession(world, { task: { instruction, … } })`) belongs\n * to one session. A stored task is the same spec as a named, versioned\n * project resource: create it once, open as many sessions on it as you like\n * with `{ task: { id } }`, and every grade attributes back to the task and\n * its version. Updating the spec never rewrites history — it appends a\n * version, and a session opened on `{ id, version: 2 }` keeps running v2\n * after v3 exists.\n *\n * const task = await createTask({\n * name: \"refund-late-invoice\",\n * world: \"acme-billing\",\n * spec: { instruction: \"…\", seed: {…}, grader: {…} },\n * });\n * const session = await openSession(\"acme-billing\", { task: { id: task.id } });\n *\n * Tasks are project-scoped: another project's task id is not found (404),\n * never forbidden. `world` pins a task to one world's slug (validated against\n * that world's contract); null leaves it usable with any world.\n */\n\nexport type WorldTaskSummary = {\n id: string;\n name: string;\n world: string | null;\n version: number;\n hash: string;\n spec: WorldTaskSpec;\n /** A multi-world task's aliases in spec order; empty for a single world. */\n aliases: string[];\n /** Listed by world: the aliases that world plays in this task; else empty. */\n aliasesHere: string[];\n /** What grades the task, one row per check or verifier: its reward key,\n * the aliases it judges, what it checks in plain words, its source. */\n verifiers: WorldTaskVerifierRow[];\n createdAt: string;\n updatedAt: string;\n createdBy: string;\n updatedBy: string;\n /** On create, when the task is pinned to a world of a deprecated shape (an\n * api bundle): what to run instead. A retired shape is refused. */\n deprecations?: { code: string; message: string; replacement: string }[];\n};\n\nexport type WorldTaskVersionSummary = {\n version: number;\n hash: string;\n createdAt: string;\n createdBy: string;\n message: string | null;\n};\n\nexport type WorldTaskVerifierRow = {\n key: string;\n aliases: string[];\n kind: \"assertions\" | \"python\" | \"rubric\";\n description: string | null;\n source: string | null;\n sourceLanguage: \"python\" | \"text\" | null;\n};\n\nexport type WorldTaskDetail = WorldTaskSummary & {\n versions: WorldTaskVersionSummary[];\n};\n\nexport type WorldTaskPage = {\n tasks: WorldTaskSummary[];\n meta: {\n page: number;\n limit: number;\n totalItems: number;\n totalPages: number;\n /** Listed by world: the scan for multi-world tasks naming it filled its\n * bound, so `totalItems` is a floor. */\n scanTruncated?: true;\n };\n};\n\nexport type WorldTaskWorldValidation = {\n slug: string;\n ref: string;\n versionId: string;\n ok: boolean;\n checked: \"entities\" | \"none\";\n problems: string[];\n entities: string[] | null;\n};\n\nexport type WorldTaskValidation = {\n taskId: string;\n version: number;\n /** The world version the task was checked against; null for a task with\n * `worlds`, whose versions are per alias under `worlds`. */\n versionId: string | null;\n ok: boolean;\n /** `entities` when the world's contract was read and every seed and check\n * entity was matched against it; `none` when the version has no contract\n * to check (a mock-tools world), in which case `ok` says only that the\n * version exists and is READY; `worlds` for a multi-world task, checked\n * alias by alias against the ref each names. */\n checked: \"entities\" | \"none\" | \"worlds\";\n /** For a multi-world task each problem is prefixed with its alias. */\n problems: string[];\n entities: string[] | null;\n worlds?: Record<string, WorldTaskWorldValidation>;\n};\n\nconst TASKS = \"/api/public/world-tasks\";\nconst taskRoute = (id: string) => `${TASKS}/${encodeURIComponent(id)}`;\n\nconst compact = (body: Record<string, unknown>) =>\n Object.fromEntries(Object.entries(body).filter(([, v]) => v !== undefined));\n\n/** Store a task. `name` defaults to `spec.name`; one of the two is needed. */\nexport async function createTask(\n input: {\n spec: WorldTaskSpec;\n name?: string;\n world?: string | null;\n message?: string;\n },\n options: WorldsClientOptions = {},\n): Promise<WorldTaskSummary> {\n return apiRequest<WorldTaskSummary>(\n options,\n \"POST\",\n TASKS,\n compact({\n spec: input.spec,\n name: input.name,\n world: input.world,\n message: input.message,\n }),\n );\n}\n\n/** Change a task. A new `spec` becomes the next version (the old ones stay\n * readable and openable); `name` and `world` change in place. */\nexport async function updateTask(\n taskId: string,\n input: {\n spec?: WorldTaskSpec;\n name?: string;\n world?: string | null;\n message?: string;\n },\n options: WorldsClientOptions = {},\n): Promise<WorldTaskSummary> {\n if (\n input.spec === undefined &&\n input.name === undefined &&\n input.world === undefined\n )\n throw new Error(\"updateTask: nothing to update — pass spec, name or world\");\n return apiRequest<WorldTaskSummary>(\n options,\n \"PATCH\",\n taskRoute(taskId),\n compact({\n spec: input.spec,\n name: input.name,\n world: input.world,\n message: input.message,\n }),\n );\n}\n\n/** The project's tasks, newest change first. `world` keeps only tasks\n * that run against that slug (pinned to it, or naming it under an alias); `metadata` keeps tasks whose spec metadata carries\n * every given key/value (`{ externalUserId: \"u_42\" }`). */\nexport async function listTasks(\n filter: {\n world?: string;\n metadata?: Record<string, string>;\n page?: number;\n limit?: number;\n } = {},\n options: WorldsClientOptions = {},\n): Promise<WorldTaskPage> {\n const params = new URLSearchParams();\n if (filter.world) params.set(\"world\", filter.world);\n if (filter.page !== undefined) params.set(\"page\", String(filter.page));\n if (filter.limit !== undefined) params.set(\"limit\", String(filter.limit));\n for (const [key, value] of Object.entries(filter.metadata ?? {}))\n params.set(`metadata.${key}`, value);\n const query = params.toString();\n return apiRequest<WorldTaskPage>(\n options,\n \"GET\",\n query ? `${TASKS}?${query}` : TASKS,\n );\n}\n\n/** One task with its version history; `version` reads that version's spec\n * instead of the current one. */\nexport async function getTask(\n taskId: string,\n opts: { version?: number } = {},\n options: WorldsClientOptions = {},\n): Promise<WorldTaskDetail> {\n const query =\n opts.version === undefined ? \"\" : `?version=${String(opts.version)}`;\n return apiRequest<WorldTaskDetail>(\n options,\n \"GET\",\n `${taskRoute(taskId)}${query}`,\n );\n}\n\n/** Remove a task and every version. Sessions already opened on it keep\n * their copy of the spec. */\nexport async function deleteTask(\n taskId: string,\n options: WorldsClientOptions = {},\n): Promise<{ id: string; name: string }> {\n return apiRequest(options, \"DELETE\", taskRoute(taskId));\n}\n\n/** Check a task against a world version without opening a session: every\n * seed entity and every check's entity must exist in the world's contract.\n * `slug` checks against that world's head, `versionId` against an exact\n * version, neither against the task's own `world` pin. */\nexport async function validateTask(\n taskId: string,\n target: { version?: number; slug?: string; versionId?: string } = {},\n options: WorldsClientOptions = {},\n): Promise<WorldTaskValidation> {\n return apiRequest<WorldTaskValidation>(\n options,\n \"POST\",\n `${taskRoute(taskId)}/validate`,\n compact({\n version: target.version,\n slug: target.slug,\n versionId: target.versionId,\n }),\n );\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\nimport { type WorldTaskSpec } from \"./session\";\n\nexport type TaskTrialRequest = {\n seq: number;\n at: string;\n via: string | null;\n operation: string | null;\n method: string | null;\n path: string | null;\n status: number;\n};\n\nexport type TaskTrialCheck = {\n passed: boolean;\n reason?: string;\n matched: TaskTrialRequest[];\n maybe: TaskTrialRequest[];\n};\n\nexport type GradedJournal = {\n complete: boolean;\n reason: string | null;\n requests: number;\n throughSeq: number | null;\n};\n\n/** A task's grader over one stored World Host session, filed nowhere. */\nexport type TaskTrial = {\n sessionId: string;\n taskId: string | null;\n version: number | null;\n graded: \"live\" | \"checkpoint\" | \"journal\";\n reward: number | null;\n rewards: Record<string, number | null>;\n reasons: Record<string, string>;\n reason: string | null;\n checks: Record<string, TaskTrialCheck>;\n journal: GradedJournal | null;\n summary: {\n via: string | null;\n operation: string | null;\n method: string | null;\n status: number;\n count: number;\n path: string | null;\n }[];\n};\n\nexport type RegradedRollout = {\n sampleId: string;\n sessionId: string | null;\n state: \"regraded\" | \"skipped\";\n reward: number | null;\n previous: { reward: number | null; verifierVersion: number | null };\n reason?: string;\n graded?: TaskTrial[\"graded\"];\n rewards?: Record<string, number | null>;\n reasons?: Record<string, string>;\n};\n\nexport type TaskRegrade = {\n taskId: string;\n version: number;\n runs: {\n evaluationId: string;\n verifierVersions: number[];\n verifiers: string | null;\n reward: number | null;\n rollouts: RegradedRollout[];\n }[];\n regraded: number;\n skipped: number;\n};\n\nexport type TaskTrialTarget =\n | { taskId: string; version?: number }\n | { spec: WorldTaskSpec };\n\nexport type TaskRegradeScope = {\n version?: number;\n runs?: string[];\n allRuns?: boolean;\n sessions?: string[];\n limit?: number;\n};\n\nconst TASKS = \"/api/public/world-tasks\";\n\nconst compact = (body: Record<string, unknown>) =>\n Object.fromEntries(Object.entries(body).filter(([, v]) => v !== undefined));\n\n/**\n * A stored task's grader over stored World Host sessions: `try` grades one\n * session and files nothing (each check with the journal requests it\n * matched), `regrade` grades a task's past runs again by one of its versions\n * and files the grades in place. Twin of the Python `TaskGrades`.\n */\nexport class TaskGrades {\n constructor(private readonly options: WorldsClientOptions = {}) {}\n\n try(sessionId: string, target: TaskTrialTarget): Promise<TaskTrial> {\n return apiRequest<TaskTrial>(\n this.options,\n \"POST\",\n `${TASKS}/try`,\n compact({ sessionId, ...target }),\n );\n }\n\n regrade(taskId: string, scope: TaskRegradeScope = {}): Promise<TaskRegrade> {\n return apiRequest<TaskRegrade>(\n this.options,\n \"POST\",\n `${TASKS}/${encodeURIComponent(taskId)}/regrade`,\n compact({ ...scope }),\n );\n }\n}\n","import {\n surfaceKinds,\n uiEntryUrl,\n type BrowserTier,\n type SessionSurfaces,\n type WorldSurfaceKind,\n} from \"./browser\";\n\n/** Where a session answers, in the shape `session open` prints and a\n * `task up` manifest keeps per world. */\nexport type SurfaceDescriptor = {\n surfaces: WorldSurfaceKind[];\n api?: { url: string; token?: string; auth?: \"open\" };\n ui?: { url: string; entry: string; apiPath: string | null };\n browser?: {\n wsUrl: string;\n viewport?: unknown;\n tier?: BrowserTier;\n };\n};\n\nexport function surfaceDescriptor(s: SessionSurfaces): SurfaceDescriptor {\n return {\n surfaces: surfaceKinds(s),\n ...(s.api\n ? {\n api: {\n url: s.api.url,\n ...(s.api.token ? { token: s.api.token } : {}),\n ...(s.api.auth ? { auth: s.api.auth } : {}),\n },\n }\n : {}),\n ...(s.ui\n ? { ui: { url: s.ui.url, entry: uiEntryUrl(s.ui), apiPath: s.ui.apiPath ?? null } }\n : {}),\n ...(s.browser\n ? {\n browser: {\n wsUrl: s.browser.wsUrl,\n viewport: s.browser.viewport,\n ...(s.browser.tier ? { tier: s.browser.tier } : {}),\n },\n }\n : {}),\n };\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\nimport {\n assertBrowserTier,\n type BrowserTier,\n type SessionSurfaces,\n type WorldSurfaceKind,\n} from \"./browser\";\nimport { GradePayload } from \"./grade\";\nimport { surfaceDescriptor, type SurfaceDescriptor } from \"./surfaceDescriptor\";\nimport {\n WorldSession,\n attachSession,\n isTaskIdRef,\n type GradeResult,\n type VerifierGrade,\n type WorldSessionCall,\n type WorldSessionState,\n type WorldTaskIdRef,\n type WorldTaskSpec,\n} from \"./session\";\n\nconst TASK_SESSIONS = \"/api/public/world-task-sessions\";\n\n/** The per-world entry of a `WorldTaskSpec.worlds` table. */\nexport type WorldTaskWorld = {\n slug: string;\n ref?: string;\n seed?: WorldTaskSpec[\"seed\"];\n grader?: WorldTaskSpec[\"grader\"];\n tools?: string[];\n};\n\n/** One world's session as the platform answered it at up. */\nexport type TaskWorldSessionState = WorldSessionState & {\n alias: string;\n slug: string;\n ref: string;\n reusedWarm: boolean;\n};\n\n/** Which world an alias is, as recorded at up or attach. */\nexport type TaskWorldRef = {\n slug: string;\n ref: string | null;\n};\n\n/** What `POST /world-task-sessions` answers. */\nexport type TaskSessionsResponse = {\n taskId: string | null;\n taskVersion: number | null;\n name: string | null;\n hash: string;\n instruction: string;\n sessions: Record<string, TaskWorldSessionState>;\n};\n\n/** One world in the manifest: where it answers, in the shape\n * `gateway worlds session open` prints for a single session. */\nexport type TaskManifestSession = {\n slug: string;\n ref: string | null;\n versionId: string;\n sessionId: string;\n ready: boolean;\n state: string;\n} & SurfaceDescriptor;\n\n/** The manifest: every session of the task, keyed by alias. The file\n * `task up --out` writes and `task down|status|grade|export` read. */\nexport type TaskManifest = {\n taskId: string | null;\n taskVersion: number | null;\n name: string | null;\n instruction: string | null;\n sessions: Record<string, TaskManifestSession>;\n};\n\n/** A stored task's live sessions, as `GET /world-task-sessions` lists them. */\nexport type LiveTaskSession = {\n alias: string | null;\n slug: string | null;\n sessionId: string;\n state: string;\n ready: boolean;\n versionId: string;\n taskVersion: number | null;\n createdAt: string;\n};\n\n/** The task's grade: every world's own `GradeResult` under its alias, the\n * task's cross-world verifiers by name (lifted from the world each is\n * anchored on), and the aggregate. `reward` is the mean of the worlds' and\n * verifiers' numeric rewards — null when none answered one (no grader\n * anywhere, or a judge still pending); a world or verifier with no reward\n * is listed under `ungraded` (a verifier as `x.<name>`), never counted as\n * 0. `rewards` flattens each world's named rewards as `<alias>.<key>`\n * beside `<alias>` for the world's own reward, and a verifier's as\n * `x.<name>` / `x.<name>.<key>`. `errors` names, by key, each world or\n * verifier that could not grade and each key two rewards claimed; any error\n * makes `reward` null, never the mean of the rest. */\nexport type TaskGrade = {\n reward: number | null;\n rewards: Record<string, number>;\n worlds: Record<string, GradeResult>;\n ungraded: string[];\n verifiers: Record<string, VerifierGrade>;\n errors: Record<string, string>;\n};\n\n/** A cross-world verifier's rewards flatten under `x.<name>`. The platform\n * refuses `x` and `x.<…>` as a world alias, and the fold refuses a key two\n * rewards claim, so a world's check never scores as a verifier. */\nexport const VERIFIER_REWARD_PREFIX = \"x.\";\n\n/** Every world's call log, keyed by alias. */\nexport type TaskExport = Record<string, WorldSessionCall[]>;\n\nconst manifestSession = (\n s: SessionSurfaces,\n state: {\n sessionId: string;\n ready: boolean;\n state: string;\n versionId: string;\n },\n world: TaskWorldRef,\n): TaskManifestSession => ({\n slug: world.slug,\n ref: world.ref,\n versionId: state.versionId,\n sessionId: state.sessionId,\n ready: state.ready,\n state: state.state,\n ...surfaceDescriptor(s),\n});\n\nclass TaskGradeFold {\n readonly rewards: Record<string, number> = {};\n readonly ungraded: string[] = [];\n readonly errors: Record<string, string> = {};\n private readonly sources = new Map<string, string>();\n private readonly graded: number[] = [];\n\n add(key: string, grade: VerifierGrade, source: string): void {\n if (grade.error) this.errors[key] = grade.error;\n if (typeof grade.reward === \"number\") {\n this.put(key, grade.reward, source);\n this.graded.push(grade.reward);\n } else this.ungraded.push(key);\n for (const [name, value] of Object.entries(grade.rewards))\n this.put(`${key}.${name}`, value, source);\n }\n\n reward(): number | null {\n if (Object.keys(this.errors).length > 0 || !this.graded.length)\n return null;\n return this.graded.reduce((a, b) => a + b, 0) / this.graded.length;\n }\n\n private put(key: string, value: number, source: string): void {\n const first = this.sources.get(key) ?? source;\n this.sources.set(key, first);\n if (first !== source) {\n this.errors[key] =\n `two rewards are named ${key} (${first} and ${source}); rename one of them`;\n return;\n }\n this.rewards[key] = value;\n }\n}\n\n/** Combine per-world grades into the task's. Pure, so the CLI and the tests\n * share it with `TaskSessions.grade()`. */\nexport function aggregateTaskGrade(\n worlds: Record<string, GradeResult>,\n): TaskGrade {\n const fold = new TaskGradeFold();\n const verifiers: Record<string, VerifierGrade> = {};\n for (const [alias, grade] of Object.entries(worlds)) {\n fold.add(alias, grade, `world ${alias}`);\n Object.assign(verifiers, grade.verifiers ?? {});\n }\n for (const [name, grade] of Object.entries(verifiers))\n fold.add(`${VERIFIER_REWARD_PREFIX}${name}`, grade, `verifier ${name}`);\n return {\n reward: fold.reward(),\n rewards: fold.rewards,\n worlds,\n ungraded: fold.ungraded,\n verifiers,\n errors: fold.errors,\n };\n}\n\n/** Every error of a task's grade on one line (`<key>: <why>; …`), or null. */\nexport function taskGradeError(grade: TaskGrade): string | null {\n const lines = Object.entries(grade.errors).map(\n ([key, why]) => `${key}: ${why}`,\n );\n return lines.length ? lines.join(\"; \") : null;\n}\n\nexport class TaskSessions {\n constructor(\n /** The stored task's id, or null for a task given as a spec. */\n readonly taskId: string | null,\n readonly taskVersion: number | null,\n readonly name: string | null,\n /** The instruction every world's session shares. */\n readonly instruction: string | null,\n /** One live session per alias, in the spec's order. */\n readonly sessions: Record<string, WorldSession>,\n private readonly worlds: Record<string, TaskWorldRef>,\n /** The spec's content hash — set only by `openTask` (the raw platform\n * response carries it); null for a `TaskSessions` rebuilt with\n * `attachManifest`/`attachTask`, which have no spec to hash. */\n readonly hash: string | null = null,\n ) {}\n\n /** This alias's world as recorded at open/attach — what a `TaskRun`\n * filing needs to name, without exposing the whole map. */\n worldRef(alias: string): TaskWorldRef {\n return this.worlds[alias] ?? { slug: \"\", ref: null };\n }\n\n /** The aliases, in the spec's order. */\n get aliases(): string[] {\n return Object.keys(this.sessions);\n }\n\n /** The alias's session, or a clear error naming the aliases there are. */\n session(alias: string): WorldSession {\n const session = this.sessions[alias];\n if (!session)\n throw new Error(\n `task has no world '${alias}'; its worlds are ${this.aliases.join(\", \")}`,\n );\n return session;\n }\n\n private async each<T>(\n fn: (session: WorldSession, alias: string) => Promise<T>,\n ): Promise<Record<string, T>> {\n const entries = await Promise.all(\n Object.entries(this.sessions).map(\n async ([alias, session]) => [alias, await fn(session, alias)] as const,\n ),\n );\n return Object.fromEntries(entries);\n }\n\n /** Wait until every world answers ready. A world that never does throws\n * `WorldSessionTimeout` naming it; the others are left up. */\n async ready(opts: { timeoutMs?: number } = {}): Promise<void> {\n await this.each((session) => session.ready(opts));\n }\n\n /** Every world's current state, keyed by alias. */\n async status(): Promise<Record<string, WorldSessionState>> {\n return this.each((session) => session.status());\n }\n\n /** The manifest: where every world answers, keyed by alias. */\n async manifest(): Promise<TaskManifest> {\n const sessions = await this.each(async (session, alias) =>\n manifestSession(\n await session.surfaces(),\n {\n sessionId: session.sessionId,\n ready: session.isReady,\n state: (await session.status()).state,\n versionId: session.versionId,\n },\n this.worlds[alias]!,\n ),\n );\n return {\n taskId: this.taskId,\n taskVersion: this.taskVersion,\n name: this.name,\n instruction: this.instruction,\n sessions,\n };\n }\n\n /** Grade every world and aggregate — see `TaskGrade`. One `report` (the\n * agent's own account of the whole investigation) goes to every world's\n * judge; a world graded by assertions or python ignores it. Each grade\n * names the task's other sessions by alias, so the cross-world verifiers\n * anchored on that world can read them. A world whose grade call fails is\n * that world's error: the task's grade names it and keeps every other\n * world's grade. */\n async grade(\n opts: { timeoutMs?: number; report?: string } = {},\n ): Promise<TaskGrade> {\n return aggregateTaskGrade(\n await this.each((session, alias) =>\n session\n .grade({ ...opts, worlds: this.otherSessions(alias) })\n .catch((error: unknown) => GradePayload.failedCall(error)),\n ),\n );\n }\n\n /** The task's other sessions by alias: what a grade names. */\n private otherSessions(alias: string): Record<string, string> {\n return Object.fromEntries(\n Object.entries(this.sessions)\n .filter(([other]) => other !== alias)\n .map(([other, session]) => [other, session.sessionId]),\n );\n }\n\n /** Every world's call log, keyed by alias. */\n async export(): Promise<TaskExport> {\n return this.each((session) => session.export());\n }\n\n /** Close every world. Closes are attempted for all of them even when one\n * fails; the error then names every world that did not close. */\n async close(\n opts: { keepWarm?: boolean } = {},\n ): Promise<Record<string, { state: string }>> {\n const settled = await Promise.allSettled(\n Object.entries(this.sessions).map(\n async ([alias, session]) => [alias, await session.close(opts)] as const,\n ),\n );\n const failed: string[] = [];\n const closed: Record<string, { state: string }> = {};\n settled.forEach((result, i) => {\n const alias = this.aliases[i]!;\n if (result.status === \"fulfilled\") closed[alias] = result.value[1];\n else\n failed.push(\n `${alias}: ${result.reason instanceof Error ? result.reason.message : String(result.reason)}`,\n );\n });\n if (failed.length > 0)\n throw new Error(\n `${failed.length} of ${this.aliases.length} worlds did not close — ${failed.join(\"; \")}`,\n );\n return closed;\n }\n}\n\nexport type OpenTaskOptions = {\n /** With a task id: open that version of the task instead of the current. */\n version?: number;\n /** Asked of every world; the platform refuses (400) rather than serving\n * fewer surfaces than asked, and then nothing is up. */\n surfaces?: WorldSurfaceKind[];\n reuseWarm?: boolean;\n /** Browser capacity for every world the task opens: `standard` (spot, may\n * be reclaimed) or `premium` (on-demand). Unset, the organization's default. */\n browserTier?: BrowserTier;\n options?: WorldsClientOptions;\n};\n\nfunction fromResponse(\n answer: TaskSessionsResponse,\n options: WorldsClientOptions,\n): TaskSessions {\n const sessions: Record<string, WorldSession> = {};\n const worlds: Record<string, TaskWorldRef> = {};\n for (const [alias, state] of Object.entries(answer.sessions)) {\n sessions[alias] = new WorldSession(state.sessionId, state, options);\n worlds[alias] = {\n slug: state.slug,\n ref: state.ref,\n };\n }\n return new TaskSessions(\n answer.taskId,\n answer.taskVersion,\n answer.name,\n answer.instruction,\n sessions,\n worlds,\n answer.hash ?? null,\n );\n}\n\n/**\n * Bring every world of a task up. `ref` is a stored task's id, its\n * `{ id, version? }`, or the spec itself (one with `worlds`). Returns as\n * soon as the platform has opened every session — `ready()` waits for the\n * containers. All or nothing: a world that fails to open closes the rest\n * and the error names it.\n */\nexport async function openTask(\n ref: string | WorldTaskIdRef | WorldTaskSpec,\n opts: OpenTaskOptions = {},\n): Promise<TaskSessions> {\n const options = opts.options ?? {};\n const task: WorldTaskIdRef | WorldTaskSpec =\n typeof ref === \"string\"\n ? {\n id: ref,\n ...(opts.version !== undefined ? { version: opts.version } : {}),\n }\n : isTaskIdRef(ref) && opts.version !== undefined\n ? { ...ref, version: opts.version }\n : ref;\n if (isTaskIdRef(task) ? !task.id : !task.instruction)\n throw new Error(\n \"openTask needs a task: a stored task id, { id, version? } or a spec with worlds\",\n );\n if (!isTaskIdRef(task) && !task.worlds)\n throw new Error(\n \"openTask needs a spec that names its worlds; a single-world spec opens with openSession\",\n );\n if (opts.browserTier !== undefined) assertBrowserTier(opts.browserTier);\n const answer = await apiRequest<TaskSessionsResponse>(\n options,\n \"POST\",\n TASK_SESSIONS,\n {\n task,\n ...(opts.reuseWarm === undefined ? {} : { reuseWarm: opts.reuseWarm }),\n ...(opts.surfaces?.length ? { surfaces: opts.surfaces } : {}),\n ...(opts.browserTier === undefined\n ? {}\n : { browserTier: opts.browserTier }),\n },\n );\n return fromResponse(answer, options);\n}\n\n/** A stored task's live sessions, newest first — every session the project\n * has opened on it that is not stopped or failed. */\nexport async function listTaskSessions(\n taskId: string,\n options: WorldsClientOptions = {},\n): Promise<LiveTaskSession[]> {\n const answer = await apiRequest<{\n taskId: string;\n sessions: LiveTaskSession[];\n }>(options, \"GET\", `${TASK_SESSIONS}?taskId=${encodeURIComponent(taskId)}`);\n return answer.sessions;\n}\n\n/**\n * Attach to the sessions a stored task has up — after a crash, or from a\n * process other than the one that ran `up`. Refuses when an alias is live\n * more than once (two `up`s of the same task): which set is meant is not\n * knowable, so pass the manifest (`attachManifest`) or close the extras.\n */\nexport async function attachTask(\n taskId: string,\n options: WorldsClientOptions = {},\n): Promise<TaskSessions> {\n const live = await listTaskSessions(taskId, options);\n if (live.length === 0)\n throw new Error(\n `task ${taskId} has no live sessions; run \\`task up\\` first`,\n );\n const byAlias = new Map<string, LiveTaskSession[]>();\n for (const session of live) {\n const alias = session.alias ?? session.sessionId;\n byAlias.set(alias, [...(byAlias.get(alias) ?? []), session]);\n }\n const doubled = [...byAlias.entries()].filter(([, rows]) => rows.length > 1);\n if (doubled.length > 0)\n throw new Error(\n `task ${taskId} has more than one live session for ${doubled\n .map(\n ([alias, rows]) =>\n `'${alias}' (${rows.map((r) => r.sessionId).join(\", \")})`,\n )\n .join(\", \")}; pass the manifest from \\`task up\\`, or close the extras`,\n );\n return attachManifest(\n {\n taskId,\n taskVersion: live[0]!.taskVersion,\n name: null,\n instruction: null,\n sessions: Object.fromEntries(\n [...byAlias.entries()].map(([alias, [row]]) => [\n alias,\n {\n slug: row!.slug ?? \"\",\n ref: null,\n versionId: row!.versionId,\n sessionId: row!.sessionId,\n ready: row!.ready,\n state: row!.state,\n surfaces: [\"tools\"] as WorldSurfaceKind[],\n },\n ]),\n ),\n },\n options,\n );\n}\n\n/** Attach to the sessions a manifest names — the file `task up --out`\n * wrote. Each session is read back from the platform, so a closed one is a\n * clear error rather than a stale handle. */\nexport async function attachManifest(\n manifest: TaskManifest,\n options: WorldsClientOptions = {},\n): Promise<TaskSessions> {\n const entries = await Promise.all(\n Object.entries(manifest.sessions).map(\n async ([alias, entry]) =>\n [alias, await attachSession(entry.sessionId, options)] as const,\n ),\n );\n const sessions = Object.fromEntries(entries);\n const instruction =\n manifest.instruction ?? entries[0]?.[1].instruction ?? null;\n return new TaskSessions(\n manifest.taskId,\n manifest.taskVersion,\n manifest.name,\n instruction,\n sessions,\n Object.fromEntries(\n Object.entries(manifest.sessions).map(([alias, entry]) => [\n alias,\n { slug: entry.slug, ref: entry.ref },\n ]),\n ),\n );\n}\n\n/** Whether a parsed JSON value is a task manifest (what `task up` wrote)\n * rather than a task spec. */\nexport function isTaskManifest(value: unknown): value is TaskManifest {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n typeof (value as { sessions?: unknown }).sessions === \"object\" &&\n (value as { sessions?: unknown }).sessions !== null &&\n !(\"instruction\" in value && \"worlds\" in value)\n );\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\nimport { RetryPolicy } from \"./transport\";\n\n/** TS twin of the Python SDK's GatewayEvalsClient (gatewaysdk/benchmark_hub/evals.py). */\n\nconst EVALUATIONS = \"/api/public/benchmark-containers/evaluations\";\n\nexport type EvalSample = {\n exampleId: string;\n task?: string;\n rolloutIndex?: number;\n prompt?: unknown;\n completion?: unknown;\n reward?: number;\n score?: number;\n correct?: boolean;\n /** A number, or null for a check that answered nothing; the platform refuses anything else. */\n rewards?: Record<string, number | null>;\n info?: Record<string, unknown>;\n};\n\nexport type CreateEvaluationOptions = {\n model?: string;\n /** A set run to file under; the platform refuses a run that does not admit this result. */\n runId?: string;\n rolloutsPerExample?: number;\n metadata?: Record<string, unknown>;\n /** Keys the filing: a repeated create answers the first evaluation, and every step of it is retried on a gateway\n * 5xx or no answer, since the platform answers a repeated step with the first one. */\n idempotencyKey?: string;\n};\n\nexport type FinalizeEvaluationOptions = {\n status?: \"COMPLETED\" | \"FAILED\";\n metrics?: Record<string, unknown>;\n};\n\nexport class GatewayEvalsClient {\n private readonly keyed = new Set<string>();\n\n constructor(\n private readonly options: WorldsClientOptions = {},\n private readonly retry: RetryPolicy = RetryPolicy.FILING,\n ) {}\n\n async createEvaluation(\n versionId: string,\n opts: CreateEvaluationOptions = {},\n ): Promise<string> {\n const body: Record<string, unknown> = { versionId };\n if (opts.model !== undefined) body.model = opts.model;\n if (opts.runId !== undefined) body.runId = opts.runId;\n if (opts.rolloutsPerExample !== undefined)\n body.rolloutsPerExample = opts.rolloutsPerExample;\n if (opts.metadata !== undefined) body.metadata = opts.metadata;\n if (opts.idempotencyKey !== undefined)\n body.idempotencyKey = opts.idempotencyKey;\n const answer = await apiRequest<{ evaluationId: string }>(\n this.options,\n \"POST\",\n EVALUATIONS,\n body,\n {\n retry:\n opts.idempotencyKey === undefined ? RetryPolicy.NONE : this.retry,\n },\n );\n if (opts.idempotencyKey !== undefined) this.keyed.add(answer.evaluationId);\n return answer.evaluationId;\n }\n\n async pushSamples(\n evaluationId: string,\n samples: EvalSample[],\n ): Promise<number> {\n const answer = await apiRequest<{ inserted?: number }>(\n this.options,\n \"POST\",\n `${EVALUATIONS}/${encodeURIComponent(evaluationId)}/samples`,\n { samples },\n { retry: this.retryFor(evaluationId) },\n );\n return answer.inserted ?? samples.length;\n }\n\n async finalizeEvaluation(\n evaluationId: string,\n opts: FinalizeEvaluationOptions = {},\n ): Promise<string> {\n const body: Record<string, unknown> = {\n status: opts.status ?? \"COMPLETED\",\n };\n if (opts.metrics !== undefined) body.metrics = opts.metrics;\n const answer = await apiRequest<{ status: string }>(\n this.options,\n \"POST\",\n `${EVALUATIONS}/${encodeURIComponent(evaluationId)}/finalize`,\n body,\n { retry: this.retryFor(evaluationId) },\n );\n return answer.status;\n }\n\n private retryFor(evaluationId: string): RetryPolicy {\n return this.keyed.has(evaluationId) ? this.retry : RetryPolicy.NONE;\n }\n}\n","import { constants } from \"node:os\";\n\nexport type RunSignal = \"SIGINT\" | \"SIGTERM\";\n\nexport interface SignalTarget {\n on(signal: RunSignal, listener: (signal: RunSignal) => void): unknown;\n off(signal: RunSignal, listener: (signal: RunSignal) => void): unknown;\n listeners(signal: RunSignal): unknown[];\n listenerCount(signal: RunSignal): number;\n exit(code: number): void;\n}\n\ntype Cleanup = (signal: RunSignal, urgent: boolean) => Promise<void>;\n\nconst OWNER = Symbol(\"RunSignals\");\n\n/** While a run holds platform sessions, SIGINT and SIGTERM run its cleanups,\n * innermost first and one at a time (a task closes its sessions, and lets a\n * filing in flight finish, before the set run around it closes), then the\n * process exits 128 + the signal's number, the code a shell reports for a\n * process the signal ended. A hold opened inside another joins it. When a\n * listener someone else added holds the same signal, the exit is theirs. A\n * second signal runs every cleanup again as urgent (close without waiting for\n * an open or a filing in flight), then exits; a third exits at once. Python\n * twin: `gatewaysdk.run_signals.RunSignals`. */\nexport class RunSignals {\n static readonly SIGNALS: readonly RunSignal[] = [\"SIGINT\", \"SIGTERM\"];\n\n private readonly cleanups: Cleanup[] = [];\n private heardSignal: RunSignal | null = null;\n private heardCount = 0;\n private listening = false;\n private left = false;\n private readonly listener = Object.assign(\n (signal: RunSignal): void => this.heard(signal),\n { [OWNER]: this },\n );\n\n constructor(private readonly target: SignalTarget = process) {}\n\n /** The signal that arrived, once one has: start nothing new. */\n get signal(): RunSignal | null {\n return this.owner().heardSignal;\n }\n\n async during<T>(cleanup: Cleanup, work: () => Promise<T>): Promise<T> {\n return this.owner().hold(cleanup, work);\n }\n\n private owner(): RunSignals {\n const owners = this.target\n .listeners(\"SIGINT\")\n .map((listener) => (listener as { [OWNER]?: RunSignals })[OWNER]);\n return owners.find((owner) => owner !== undefined) ?? this;\n }\n\n private async hold<T>(cleanup: Cleanup, work: () => Promise<T>): Promise<T> {\n this.listen();\n this.cleanups.push(cleanup);\n try {\n return await work();\n } finally {\n this.cleanups.splice(this.cleanups.indexOf(cleanup), 1);\n if (!this.cleanups.length && this.heardSignal === null) this.unlisten();\n }\n }\n\n private heard(signal: RunSignal): void {\n this.heardCount += 1;\n if (this.heardCount > 2) return this.leave(signal);\n this.heardSignal ??= signal;\n void this.cleanUp(signal, this.heardCount === 2).finally(() => this.leave(signal));\n }\n\n private async cleanUp(signal: RunSignal, urgent: boolean): Promise<void> {\n for (const cleanup of [...this.cleanups].reverse())\n await Promise.resolve()\n .then(() => cleanup(signal, urgent))\n .catch(() => undefined);\n }\n\n private leave(signal: RunSignal): void {\n if (this.left) return;\n this.left = true;\n this.unlisten();\n if (this.target.listenerCount(signal) === 0)\n this.target.exit(128 + constants.signals[signal]);\n }\n\n private listen(): void {\n if (this.listening) return;\n this.listening = true;\n for (const signal of RunSignals.SIGNALS)\n this.target.on(signal, this.listener);\n }\n\n private unlisten(): void {\n this.listening = false;\n for (const signal of RunSignals.SIGNALS)\n this.target.off(signal, this.listener);\n }\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport { withoutUiToken } from \"./browser\";\nimport type { TaskManifest, TaskManifestSession } from \"./taskSessions\";\n\ntype BrowserDescriptor = NonNullable<TaskManifestSession[\"browser\"]>;\n\n/** `<outDir>/<runId>/` of a task run. The folder is made by its first file, so a refused run leaves\n * nothing behind; the manifest keeps ids, token-free URLs and surfaces, never a session credential.\n * Python twin: `gatewaysdk.world_task_run_dir.TaskRunDir`. */\nexport class TaskRunDir {\n constructor(readonly path: string) {}\n\n writeManifest(manifest: TaskManifest): void {\n this.writeJson(\"manifest.json\", {\n ...manifest,\n sessions: Object.fromEntries(\n Object.entries(manifest.sessions).map(([alias, session]) => [\n alias,\n sessionRecord(session),\n ]),\n ),\n });\n }\n\n writeJson(name: string, value: unknown): void {\n this.write(name, JSON.stringify(value, null, 2));\n }\n\n write(name: string, text: string): void {\n fs.mkdirSync(this.path, { recursive: true });\n fs.writeFileSync(path.join(this.path, name), text);\n }\n}\n\nconst browserRecord = ({ viewport, tier }: BrowserDescriptor) => ({\n viewport,\n ...(tier ? { tier } : {}),\n});\n\nfunction sessionRecord({ api, ui, browser, ...session }: TaskManifestSession) {\n return {\n ...session,\n ...(api ? { api: { url: api.url } } : {}),\n ...(ui ? { ui: { ...ui, entry: withoutUiToken(ui.entry) } } : {}),\n ...(browser ? { browser: browserRecord(browser) } : {}),\n };\n}\n","import type { EvalSample, FinalizeEvaluationOptions, GatewayEvalsClient } from \"./evals\";\nimport { messageOf } from \"./grade\";\nimport { taskGradeError, type TaskGrade, type TaskSessions } from \"./taskSessions\";\n\nexport type RunTaskSummary = {\n runId: string;\n taskId: string | null;\n taskVersion: number | null;\n name: string | null;\n instruction: string;\n model: string;\n aliases: string[];\n reward: number | null;\n rewards: Record<string, number>;\n ungraded: string[];\n agentError: string | null;\n /** Why the run stopped short of a grade (a world that never came up, an interrupt); filed FAILED with it. */\n runError: string | null;\n /** The grade's errors on one line (a world or verifier that could not grade, two rewards under one key); filed FAILED with it. */\n gradeError: string | null;\n /** Why the evaluation could not be filed; `filed` is then false. */\n fileError: string | null;\n /** The status the platform settled the filed evaluation at; null when nothing was filed. */\n evaluationStatus: string | null;\n report: string | null;\n traced: boolean;\n runDir: string;\n durationSeconds: number;\n notes: Record<string, unknown>;\n filed: boolean;\n evaluationId?: string;\n [extra: string]: unknown;\n};\n\n/** A failure is filed FAILED with its reason and no reward it did not earn. Python twin: `gatewaysdk.world_task_outcome.TaskRunOutcome`. */\nexport class TaskRunOutcome {\n report: string | null = null;\n extra: Record<string, unknown> = {};\n notes: Record<string, unknown> = {};\n agentError: string | null = null;\n grade: TaskGrade | null = null;\n traced = false;\n private runError: string | null = null;\n private fileError: string | null = null;\n private evaluationId: string | undefined;\n private evaluationStatus: string | null = null;\n private readonly started = Date.now();\n\n constructor(\n readonly runId: string,\n private readonly live: TaskSessions,\n private readonly model: string,\n private readonly runDir: string,\n ) {}\n\n stopped(error: unknown): void {\n this.runError ??= messageOf(error).slice(0, 2000);\n }\n\n agentRaised(error: unknown): void {\n this.agentError = messageOf(error).slice(0, 2000);\n }\n\n failure(): string | null {\n const reasons = [\n this.agentError === null ? null : `agent raised: ${this.agentError}`,\n this.runError === null ? null : `the run stopped: ${this.runError}`,\n this.gradeError(),\n this.grade === null && this.runError === null ? \"the run stopped before it was graded\" : null,\n ].filter((reason): reason is string => reason !== null);\n return reasons.length ? reasons.join(\"; \") : null;\n }\n\n async file(evals: GatewayEvalsClient, setRunId?: string): Promise<void> {\n let created: string | undefined;\n try {\n created = await evals.createEvaluation(this.ref(this.live.aliases[0]!).versionId, {\n model: this.model,\n rolloutsPerExample: 1,\n idempotencyKey: this.runId,\n ...(setRunId ? { runId: setRunId } : {}),\n metadata: this.metadata(),\n });\n await evals.pushSamples(created, [this.sample()]);\n this.evaluationStatus = await evals.finalizeEvaluation(created, this.finalized());\n this.evaluationId = created;\n } catch (error) {\n this.fileError = created ? `evaluation ${created}: ${messageOf(error)}` : messageOf(error);\n if (created)\n await evals\n .finalizeEvaluation(created, { status: \"FAILED\", metrics: { error: this.fileError } })\n .catch(() => undefined);\n }\n }\n\n summary(): RunTaskSummary {\n const live = this.live;\n const { evaluationId: _agentEvaluationId, ...extra } = this.extra;\n return {\n ...extra,\n runId: this.runId,\n taskId: live.taskId,\n taskVersion: live.taskVersion,\n name: live.name,\n instruction: live.instruction ?? \"\",\n model: this.model,\n aliases: live.aliases,\n reward: this.grade?.reward ?? null,\n rewards: this.grade?.rewards ?? {},\n ungraded: this.grade?.ungraded ?? live.aliases,\n agentError: this.agentError,\n runError: this.runError,\n gradeError: this.gradeError(),\n fileError: this.fileError,\n evaluationStatus: this.evaluationStatus,\n report: this.report,\n traced: this.traced,\n runDir: this.runDir,\n durationSeconds: Math.round((Date.now() - this.started) / 10) / 100,\n notes: this.notes,\n filed: this.evaluationId !== undefined,\n ...(this.evaluationId ? { evaluationId: this.evaluationId } : {}),\n };\n }\n\n private gradeError(): string | null {\n return this.grade ? taskGradeError(this.grade) : null;\n }\n\n private ref(alias: string) {\n const { slug, ref } = this.live.worldRef(alias);\n const session = this.live.sessions[alias]!;\n return { slug, ref, versionId: session.versionId, sessionId: session.sessionId };\n }\n\n private metadata(): Record<string, unknown> {\n const live = this.live;\n return {\n source: \"worlds-task-run\",\n task: { id: live.taskId, version: live.taskVersion, name: live.name, hash: live.hash },\n anchor: live.aliases[0],\n worlds: Object.fromEntries(live.aliases.map((alias) => [alias, this.ref(alias)])),\n runId: this.runId,\n };\n }\n\n private sample(): EvalSample {\n const live = this.live;\n const reward = this.grade?.reward ?? null;\n const gradeError = this.gradeError();\n const sample: Record<string, unknown> = {\n exampleId: live.name ?? live.taskId ?? this.runId,\n task: live.name ?? live.taskId ?? this.runId,\n rolloutIndex: 0,\n prompt: live.instruction,\n ...(this.report === null ? {} : { completion: this.report }),\n rewards: this.grade?.rewards ?? {},\n info: {\n sessionId: this.runId,\n worlds: Object.fromEntries(\n live.aliases.map((alias) => [\n alias,\n { ...this.ref(alias), reward: this.grade?.worlds[alias]?.reward ?? null },\n ]),\n ),\n ungraded: this.grade?.ungraded ?? live.aliases,\n verifierVersion: live.taskVersion,\n traced: this.traced,\n runDir: this.runDir,\n ...(this.agentError ? { agentError: this.agentError } : {}),\n ...(this.runError ? { runError: this.runError } : {}),\n ...(gradeError ? { verifyError: gradeError } : {}),\n },\n };\n if (typeof reward === \"number\")\n Object.assign(sample, { reward, score: reward, correct: reward >= 1.0 });\n return sample as unknown as EvalSample;\n }\n\n private finalized(): FinalizeEvaluationOptions {\n const reward = this.grade?.reward ?? null;\n const failure = this.failure();\n return {\n status: failure ? \"FAILED\" : \"COMPLETED\",\n metrics: {\n ...(typeof reward === \"number\" ? { avg_reward: reward } : {}),\n reward,\n ...Object.fromEntries(\n Object.entries(this.grade?.rewards ?? {}).map(([key, value]) => [`rewards.${key}`, value]),\n ),\n ...(failure ? { error: failure } : {}),\n },\n };\n }\n}\n","export const GATEWAY_ENV = {\n HOST: \"GATEWAY_HOST\",\n PUBLIC_KEY: \"GATEWAY_PUBLIC_KEY\",\n SECRET_KEY: \"GATEWAY_SECRET_KEY\",\n API_KEY: \"GATEWAY_API_KEY\",\n ENDPOINT: \"GATEWAY_OTLP_ENDPOINT\",\n} as const;\n\nexport const OTLP_TRACES_PATH = \"/api/public/otel/v1/traces\";\n\nexport const OPENTELEMETRY_PEERS = {\n \"@opentelemetry/api\": \"1.9.0\",\n \"@opentelemetry/exporter-trace-otlp-http\": \"0.222.0\",\n \"@opentelemetry/resources\": \"2.11.0\",\n \"@opentelemetry/sdk-trace-base\": \"2.11.0\",\n \"@opentelemetry/sdk-trace-node\": \"2.11.0\",\n} as const;\n\nconst PINNED_PEERS = Object.entries(OPENTELEMETRY_PEERS)\n .map(([name, version]) => `${name}@${version}`)\n .join(\" \");\n\nconst MODULE_NOT_FOUND = new Set([\"MODULE_NOT_FOUND\", \"ERR_MODULE_NOT_FOUND\"]);\n\nexport function getEnv(key: string): string | undefined {\n const value = process.env[key];\n return value ? value : undefined;\n}\n\n/**\n * Check if Gateway is configured via environment variables.\n */\nexport function isGatewayConfigured(): boolean {\n return !!(\n getEnv(GATEWAY_ENV.HOST) &&\n getEnv(GATEWAY_ENV.PUBLIC_KEY) &&\n getEnv(GATEWAY_ENV.SECRET_KEY)\n );\n}\n\nexport class OpenTelemetryMissing extends Error {\n constructor() {\n super(\n \"OpenTelemetry packages not found. Install them next to @withgateway/sdk, at the versions it is tested with:\\n\" +\n ` npm install ${PINNED_PEERS}\\n` +\n ` npm install -g ${PINNED_PEERS} (the gateway CLI, when it was installed with npm install -g)`,\n );\n this.name = \"OpenTelemetryMissing\";\n }\n\n static explains(error: unknown): boolean {\n if (error instanceof OpenTelemetryMissing) return true;\n const { code, message } = (error ?? {}) as {\n code?: unknown;\n message?: unknown;\n };\n return (\n MODULE_NOT_FOUND.has(String(code)) &&\n String(message).includes(\"@opentelemetry/\")\n );\n }\n}\n","import {\n GATEWAY_ENV,\n getEnv,\n OpenTelemetryMissing,\n OTLP_TRACES_PATH,\n} from \"../tracing/prerequisites\";\nimport type { TracingConfig } from \"../tracing/types\";\nimport type { WorldsClientOptions } from \"./index\";\nimport { GATEWAY_KEYS_MISSING, platformEndpoint } from \"./platformEndpoint\";\nimport type { PlatformEndpoint } from \"./transport\";\n\ntype TracingInit = Pick<typeof import(\"../tracing/init\"), \"init\" | \"isInitialized\">;\n\nconst HOST_WITH_AUTHORITY = /^[a-z][a-z0-9+.-]*:\\/\\/[^/\\\\?#@\\s]+(\\/|$)/i;\n\nexport const TRACING_HELD_ELSEWHERE =\n \"Tracing in this process already sends spans to another destination or with other keys (an earlier \" +\n \"run, or the agent's own tracing.init()), so this run's spans would not reach its own project.\";\n\nexport class TaskTracing {\n private static warned = false;\n private static target: string | null = null;\n\n constructor(\n private readonly load: () => Promise<TracingInit> = () =>\n import(\"../tracing/init\"),\n ) {}\n\n async start(requested: boolean, options: WorldsClientOptions): Promise<boolean> {\n if (!requested) return false;\n const endpoint = platformEndpoint(options);\n try {\n await this.initOnce(TaskTracing.config(endpoint));\n return true;\n } catch (error) {\n TaskTracing.warnOnce(TaskTracing.reason(error, endpoint));\n return false;\n }\n }\n\n // init() keeps the first provider for the whole process and ignores later calls, so a later run is\n // traced only when it exports to the same place with the same keys.\n private async initOnce(config: TracingConfig): Promise<void> {\n const tracing = await this.load();\n const target = JSON.stringify([config.endpoint, config.publicKey, config.secretKey]);\n if (!tracing.isInitialized()) {\n tracing.init(config);\n TaskTracing.target = target;\n return;\n }\n if (TaskTracing.target !== target) throw new Error(TRACING_HELD_ELSEWHERE);\n }\n\n private static config(endpoint: PlatformEndpoint | null): TracingConfig {\n if (!endpoint) throw new Error(GATEWAY_KEYS_MISSING);\n return { ...endpoint, endpoint: TaskTracing.destination(endpoint) };\n }\n\n // B1: a saved login's keys go to their own host only. The redirect is compared as text, never parsed:\n // a fixed \"<host>/\" prefix leaves no URL parser room to read another host into it.\n private static destination(endpoint: PlatformEndpoint): string {\n const redirect = getEnv(GATEWAY_ENV.ENDPOINT);\n if (!redirect) return `${endpoint.host}${OTLP_TRACES_PATH}`;\n if (TaskTracing.underHost(redirect, endpoint.host) || TaskTracing.environmentKeys(endpoint)) return redirect;\n throw new Error(\n `GATEWAY_OTLP_ENDPOINT is not under ${endpoint.host}, and this run's keys are not ` +\n `GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY: they are sent to ${endpoint.host} only. ` +\n \"Unset GATEWAY_OTLP_ENDPOINT, or set both keys in the environment.\",\n );\n }\n\n private static underHost(redirect: string, host: string): boolean {\n return HOST_WITH_AUTHORITY.test(host) && redirect.startsWith(`${host}/`);\n }\n\n private static environmentKeys(endpoint: PlatformEndpoint): boolean {\n const secretKey = getEnv(GATEWAY_ENV.SECRET_KEY) ?? getEnv(GATEWAY_ENV.API_KEY);\n return endpoint.publicKey === getEnv(GATEWAY_ENV.PUBLIC_KEY) && endpoint.secretKey === secretKey;\n }\n\n private static warnOnce(reason: string): void {\n if (TaskTracing.warned) return;\n TaskTracing.warned = true;\n console.warn(\n `[gatewaysdk.tracing] Task runs in this process are not traced. ${reason}\\n` +\n \"Pass --no-trace (trace: false) to run untraced without this warning.\",\n );\n }\n\n private static reason(error: unknown, endpoint: PlatformEndpoint | null): string {\n if (OpenTelemetryMissing.explains(error)) return new OpenTelemetryMissing().message;\n const message = error instanceof Error ? error.message : String(error);\n const keys = endpoint ? [endpoint.publicKey, endpoint.secretKey] : [];\n return keys.reduce((text, key) => text.split(key).join(\"[redacted]\"), message);\n }\n}\n","import { randomBytes } from \"node:crypto\";\nimport * as path from \"node:path\";\n\nimport type { BrowserTier, WorldSurfaceKind } from \"./browser\";\nimport { WorldSurfaceUnavailable } from \"./browser\";\nimport { GatewayEvalsClient } from \"./evals\";\nimport type { WorldsClientOptions } from \"./index\";\nimport { RunSignals, type RunSignal } from \"./runSignals\";\nimport {\n modelToolName,\n schemaFromSignature,\n WorldSession,\n type WorldTaskIdRef,\n type WorldTaskSpec,\n type WorldToolkit,\n type WorldToolSpec,\n} from \"./session\";\nimport { openTask, TaskSessions, type TaskManifest } from \"./taskSessions\";\nimport { TaskRunDir } from \"./taskRunDir\";\nimport { TaskRunOutcome, type RunTaskSummary } from \"./taskRunOutcome\";\nimport { TaskTracing } from \"./taskTracing\";\nimport { WorldToolsUnread } from \"./worldNotice\";\n\nexport type { RunTaskSummary } from \"./taskRunOutcome\";\n\nexport class TaskRun {\n readonly notes: Record<string, unknown> = {};\n\n constructor(\n readonly runId: string,\n readonly instruction: string,\n readonly model: string,\n readonly sessions: Record<string, WorldSession>,\n readonly manifest: TaskManifest,\n ) {}\n\n session(alias: string): WorldSession {\n const session = this.sessions[alias];\n if (!session)\n throw new Error(\n `task run has no world '${alias}'; its worlds are ${Object.keys(this.sessions).join(\", \")}`,\n );\n return session;\n }\n\n /** Raises when the session was not opened with `surfaces: [\"api\"]`. */\n async api(alias: string): Promise<{ url: string; token?: string }> {\n const surfaces = await this.session(alias).surfaces();\n if (!surfaces.api)\n throw new WorldSurfaceUnavailable(\n \"api\",\n `open '${alias}' with surfaces: ['api']`,\n );\n return { url: surfaces.api.url, token: surfaces.api.token };\n }\n\n /** Each tool is prefixed `<alias>.<tool>` so a model can tell which world a call goes to. */\n async toolkit(): Promise<WorldToolkit> {\n const schemas: WorldToolkit[\"schemas\"] = [];\n const impls: WorldToolkit[\"impls\"] = {};\n const specs: WorldToolSpec[] = [];\n for (const [alias, session] of Object.entries(this.sessions)) {\n const kit = await session.toolkit();\n if (!kit.specs.length) continue;\n for (const spec of kit.specs) {\n const name = `${alias}.${spec.name}`;\n const prefixed: WorldToolSpec = {\n name,\n signature: spec.signature,\n doc: spec.doc,\n inputSchema: spec.inputSchema,\n };\n specs.push(prefixed);\n const schema = schemaFromSignature(prefixed);\n schema.function.name = name;\n schemas.push(schema);\n impls[name] = kit.impls[modelToolName(spec.name)]!;\n }\n }\n return { schemas, impls, specs };\n }\n\n /** Merged into `run.json` under `notes`; a later call overrides an earlier key. */\n record(notes: Record<string, unknown>): void {\n Object.assign(this.notes, notes);\n }\n}\n\nexport type RunTaskOptions = {\n model: string;\n surfaces?: WorldSurfaceKind[];\n /** Directory the run's own `<runId>/` folder is created under. Default `\"runs\"`. */\n outDir?: string;\n /**\n * Trace the agent's own spans with the host and keys the run's requests use (`options`, then\n * `GATEWAY_*`). Default `true`. A `GATEWAY_OTLP_ENDPOINT` on another host is followed only with the\n * environment's own keys. When tracing cannot start (the optional `@opentelemetry/*` peers are\n * missing, or a redirect would carry other keys), the run goes on untraced and the process warns once.\n */\n trace?: boolean;\n /** File one rollout when the run ends. Default `true`. */\n file?: boolean;\n /** Leave every session up instead of closing it when the run ends. Default `false`. */\n keepUp?: boolean;\n reuseWarm?: boolean;\n browserTier?: BrowserTier;\n /** File the rollout under this set run (`runSet` sets it). */\n setRunId?: string;\n options?: WorldsClientOptions;\n};\n\nconst FILING_UNFINISHED = \"the filing did not finish\";\n\n/** The line a CLI prints before exiting 1 on a task run: the agent raised,\n * the run stopped short of a grade, the task could not be graded, the run\n * could not be filed, or the platform settled it failed; null when none. */\nexport function taskRunFailure(summary: RunTaskSummary): string | null {\n if (summary.agentError !== null) return `agent raised: ${summary.agentError}`;\n if (summary.runError !== null) return `the run stopped: ${summary.runError}`;\n if (summary.gradeError !== null)\n return `the task could not be graded: ${summary.gradeError}`;\n if (summary.fileError !== null)\n return `the run could not be filed: ${summary.fileError}`;\n if (summary.filed && summary.evaluationStatus !== \"COMPLETED\")\n return `the platform settled evaluation ${summary.evaluationId} as ${summary.evaluationStatus}`;\n return null;\n}\n\nexport type TaskRunResult =\n | string\n | { report?: unknown; [key: string]: unknown }\n | null\n | undefined;\n\nconst describeValue = (value: unknown): string =>\n Array.isArray(value) ? \"array\" : value === null ? \"null\" : typeof value;\n\nconst RESULT_CONTRACT =\n \"return a string report, an object {report?: string, ...} or nothing\";\n\nfunction reportFromResult(result: TaskRunResult): {\n report: string | null;\n extra: Record<string, unknown>;\n} {\n if (result === undefined || result === null)\n return { report: null, extra: {} };\n if (typeof result === \"string\") return { report: result, extra: {} };\n if (typeof result !== \"object\" || Array.isArray(result))\n throw new Error(\n `agent returned ${describeValue(result)}; ${RESULT_CONTRACT}`,\n );\n const { report, ...extra } = result as Record<string, unknown>;\n if (report === undefined || report === null) return { report: null, extra };\n if (typeof report !== \"string\")\n throw new Error(\n `agent returned a report of type ${describeValue(report)}; ${RESULT_CONTRACT}`,\n );\n return { report, extra };\n}\n\nasync function refuseUnreadTools(live: TaskSessions): Promise<void> {\n try {\n for (const alias of live.aliases)\n WorldToolsUnread.refuse(`${live.worldRef(alias).slug} (alias ${alias})`, live.session(alias).deprecations);\n } catch (error) {\n await live.close({ keepWarm: false }).catch(() => undefined);\n throw error;\n }\n}\n\ntype TaskAgent = (run: TaskRun) => TaskRunResult | Promise<TaskRunResult>;\n\n/** One run of a task whose sessions are up: play it, file it, write its\n * record and close, whatever stage it stopped at. An interrupt before the\n * grade closes the sessions, writes the record and files nothing; one after\n * it lets the filing in flight finish first. */\nclass LiveTaskRun {\n private readonly files: TaskRunDir;\n private readonly outcome: TaskRunOutcome;\n private played = false;\n private interrupted = false;\n private filing: Promise<void> | null = null;\n private ending: Promise<void> | null = null;\n\n constructor(\n runId: string,\n private readonly live: TaskSessions,\n private readonly opts: RunTaskOptions,\n private readonly options: WorldsClientOptions,\n ) {\n this.files = new TaskRunDir(path.join(opts.outDir ?? \"runs\", runId));\n this.outcome = new TaskRunOutcome(runId, live, opts.model, this.files.path);\n }\n\n async complete(agent: TaskAgent): Promise<RunTaskSummary> {\n try {\n await this.play(agent).catch((error: unknown) => this.outcome.stopped(error));\n this.played = true;\n await this.file();\n return this.record();\n } finally {\n await this.end();\n }\n }\n\n async interrupt(signal: RunSignal, urgent = false): Promise<void> {\n const sessions = this.opts.keepUp ? \"leaving its sessions up\" : \"closing its sessions\";\n const how = urgent ? \" now, without waiting\" : \"\";\n process.stderr.write(`${this.outcome.runId} interrupted by ${signal}; ${sessions}${how}\\n`);\n if (!this.played) this.outcome.stopped(`interrupted by ${signal}`);\n this.interrupted = true;\n try {\n if (!urgent) await this.filing;\n this.record();\n } catch (error) {\n const why = error instanceof Error ? error.message : String(error);\n process.stderr.write(`${this.outcome.runId}: run.json not written: ${why}\\n`);\n } finally {\n await this.end();\n }\n }\n\n summary(): RunTaskSummary {\n return this.outcome.summary();\n }\n\n private async play(agent: TaskAgent): Promise<void> {\n await this.live.ready();\n this.outcome.traced = await new TaskTracing().start(this.opts.trace !== false, this.options);\n const run = new TaskRun(\n this.outcome.runId,\n this.live.instruction ?? \"\",\n this.opts.model,\n this.live.sessions,\n await this.live.manifest(),\n );\n this.outcome.notes = run.notes;\n this.files.writeManifest(run.manifest);\n await this.callAgent(agent, run);\n const report = this.outcome.report;\n this.outcome.grade = await this.live.grade(report !== null ? { report } : {});\n this.files.writeJson(\"grades.json\", this.outcome.grade);\n if (report) this.files.write(\"report.md\", report);\n }\n\n private async callAgent(agent: TaskAgent, run: TaskRun): Promise<void> {\n try {\n const invoke = () => agent(run);\n const result = this.outcome.traced\n ? await (await import(\"../tracing/session\")).withSession(run.runId, invoke)\n : await invoke();\n ({ report: this.outcome.report, extra: this.outcome.extra } = reportFromResult(result));\n } catch (error) {\n this.outcome.agentRaised(error);\n }\n if (this.outcome.traced)\n await import(\"../tracing/init\")\n .then((tracing) => tracing.flush())\n .catch(() => undefined);\n }\n\n private async file(): Promise<void> {\n if (this.opts.file === false || this.interrupted) return;\n this.files.writeJson(\"run.json\", { ...this.outcome.summary(), fileError: FILING_UNFINISHED });\n this.filing = this.outcome.file(new GatewayEvalsClient(this.options), this.opts.setRunId);\n await this.filing;\n }\n\n private record(): RunTaskSummary {\n const summary = this.outcome.summary();\n this.files.writeJson(\"run.json\", summary);\n return summary;\n }\n\n private end(): Promise<void> {\n this.ending ??= this.opts.keepUp\n ? Promise.resolve()\n : this.live.close({ keepWarm: false }).then(\n () => undefined,\n () => undefined,\n );\n return this.ending;\n }\n}\n\n/** A run whose sessions the platform is still opening. A signal before it\n * answers waits for the answer, then closes what it opened; the agent never\n * starts. An urgent signal closes only what has already opened. */\nclass TaskOpening {\n private interrupting: Promise<void> | null = null;\n private run: LiveTaskRun | null = null;\n private readonly opened: Promise<LiveTaskRun>;\n\n constructor(opening: Promise<LiveTaskRun>) {\n this.opened = opening.then((run) => (this.run = run));\n }\n\n async complete(agent: TaskAgent): Promise<RunTaskSummary> {\n const run = await this.opened;\n if (!this.interrupting) return run.complete(agent);\n await this.interrupting;\n return run.summary();\n }\n\n interrupt(signal: RunSignal, urgent = false): Promise<void> {\n if (urgent) return this.run?.interrupt(signal, true) ?? Promise.resolve();\n this.interrupting ??= this.opened.then(\n (run) => run.interrupt(signal),\n () => undefined,\n );\n return this.interrupting;\n }\n}\n\n/** Mirrors `gatewaysdk.world_tasks.run_task`. Every run whose sessions opened\n * writes `run.json` and, unless `file: false`, files one evaluation: FAILED\n * with the reason when the agent raised, a world never came up, or the task\n * could not be graded; a failure that stops filing is `fileError`. Sessions\n * close unless `keepUp: true`. SIGINT or SIGTERM, from the open on, closes\n * them first (a signal during the open waits for the platform's answer) and\n * exits 128 + the signal's number. A world whose tools the platform could not\n * read throws `WorldToolsUnread` before the agent runs, and nothing is filed. */\nexport async function runTask(\n ref: string | WorldTaskIdRef | WorldTaskSpec,\n agent: (run: TaskRun) => TaskRunResult | Promise<TaskRunResult>,\n opts: RunTaskOptions,\n): Promise<RunTaskSummary> {\n const runId = `wtr-${randomBytes(6).toString(\"hex\")}`;\n const options = opts.options ?? {};\n const opening = new TaskOpening(\n openTask(ref, {\n surfaces: opts.surfaces,\n reuseWarm: opts.reuseWarm,\n browserTier: opts.browserTier,\n options,\n }).then(async (live) => {\n await refuseUnreadTools(live);\n return new LiveTaskRun(runId, live, opts, options);\n }),\n );\n return new RunSignals().during(\n (signal, urgent) => opening.interrupt(signal, urgent),\n () => opening.complete(agent),\n );\n}\n","import { execFileSync } from \"node:child_process\";\n\nexport type Checkout = {\n branch?: string;\n commit?: string;\n repoUrl?: string;\n pr?: { number: number; url: string; title?: string };\n};\n\ntype Env = Record<string, string | undefined>;\n\n/** Labels for the reader, never used to authorize. The PR comes from `GATEWAY_PR_URL`\n * (+ `GATEWAY_PR_TITLE`), else GitHub Actions' `GITHUB_REF=refs/pull/<n>/merge`. */\nexport class CheckoutProvenance {\n constructor(\n private readonly cwd: string,\n private readonly env: Env,\n ) {}\n\n static read(cwd: string = process.cwd(), env: Env = process.env): Checkout {\n return new CheckoutProvenance(cwd, env).checkout();\n }\n\n checkout(): Checkout {\n const commit = this.git(\"rev-parse\", \"HEAD\");\n if (!commit) return this.withPr({});\n const branch =\n this.env.GITHUB_HEAD_REF || this.git(\"rev-parse\", \"--abbrev-ref\", \"HEAD\");\n const remote = this.git(\"config\", \"--get\", \"remote.origin.url\");\n return this.withPr({\n commit,\n ...(branch && branch !== \"HEAD\" ? { branch } : {}),\n ...(remote ? { repoUrl: CheckoutProvenance.withoutCredentials(remote) } : {}),\n });\n }\n\n /** Security: credentials are stripped; scp-style `git@host:org/repo` has none and is kept. */\n static withoutCredentials(url: string): string {\n return url.replace(/^([a-z][a-z0-9+.-]*:\\/\\/)[^@/]+@/i, \"$1\");\n }\n\n private withPr(checkout: Checkout): Checkout {\n const pr = this.pullRequest();\n return pr ? { ...checkout, pr } : checkout;\n }\n\n private pullRequest(): Checkout[\"pr\"] | undefined {\n const url = this.env.GATEWAY_PR_URL;\n const fromUrl = url ? /\\/pull\\/(\\d+)/.exec(url)?.[1] : undefined;\n if (url && fromUrl)\n return {\n number: Number(fromUrl),\n url,\n ...(this.env.GATEWAY_PR_TITLE ? { title: this.env.GATEWAY_PR_TITLE } : {}),\n };\n const number = /^refs\\/pull\\/(\\d+)\\//.exec(this.env.GITHUB_REF ?? \"\")?.[1];\n const server = this.env.GITHUB_SERVER_URL;\n const repo = this.env.GITHUB_REPOSITORY;\n if (!number || !server || !repo) return undefined;\n return { number: Number(number), url: `${server}/${repo}/pull/${number}` };\n }\n\n private git(...args: string[]): string | undefined {\n try {\n const out = execFileSync(\"git\", args, {\n cwd: this.cwd,\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n timeout: 5_000,\n })\n .toString()\n .trim();\n return out || undefined;\n } catch {\n return undefined;\n }\n }\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\nimport type { BrowserTier, WorldSurfaceKind } from \"./browser\";\nimport { CheckoutProvenance, type Checkout } from \"./checkoutProvenance\";\nimport { RunSignals, type RunSignal } from \"./runSignals\";\nimport type { ActingUser } from \"./editSessions\";\nimport {\n runTask,\n taskRunFailure,\n type RunTaskSummary,\n type TaskRun,\n type TaskRunResult,\n} from \"./taskRun\";\n\nconst SET_RUNS = \"/api/public/set-runs\";\n\nexport type SetRunDoc = {\n id: string;\n status: \"running\" | \"completed\" | \"failed\";\n model: string | null;\n source: string | null;\n taskSetDatasetId: string | null;\n actor: { kind: string; id: string; actingUser: ActingUser | null } | null;\n git: Checkout | null;\n progress: { done: number; planned: number };\n score: { mean: number | null; gradedTasks: number; ungradedTasks: number };\n tasks: Array<{\n worldTaskId: string;\n datasetItemId: string;\n name: string;\n evaluationId: string | null;\n sampleId: string | null;\n status: \"pending\" | \"completed\" | \"failed\";\n reward: number | null;\n /** Why a failed task failed: its filing's error, or the reason this run\n * gave when it closed for a task that filed nothing. */\n error: string | null;\n checks: Array<{\n key: string;\n outcome: \"passed\" | \"failed\" | \"ungraded\";\n value: number | null;\n }>;\n }>;\n};\n\nexport type RunSetOptions = {\n model: string;\n /** Default `\"sdk\"`; the CLI passes `\"cli\"`. */\n source?: \"cli\" | \"sdk\";\n /** Default: read from the working directory; `null` records none. */\n git?: Checkout | null;\n surfaces?: WorldSurfaceKind[];\n browserTier?: BrowserTier;\n outDir?: string;\n trace?: boolean;\n onTask?: (summary: RunTaskSummary) => void;\n options?: WorldsClientOptions;\n};\n\n/** `failed`: an agent raised, a task could not run or be graded, or the platform stored the run as anything but completed. */\nexport type RunSetResult = {\n setRun: SetRunDoc;\n tasks: RunTaskSummary[];\n failed: boolean;\n closedAsRequested: boolean;\n};\n\n/** A low or missing reward is a result, not a failure; every task runs even after one fails. */\nexport async function runSet(\n datasetId: string,\n agent: (run: TaskRun) => TaskRunResult | Promise<TaskRunResult>,\n opts: RunSetOptions,\n): Promise<RunSetResult> {\n const options = opts.options ?? {};\n const git = opts.git === undefined ? CheckoutProvenance.read() : opts.git;\n const opened = await apiRequest<SetRunDoc>(options, \"POST\", SET_RUNS, {\n datasetId,\n model: opts.model,\n source: opts.source ?? \"sdk\",\n ...(git && Object.keys(git).length ? { git } : {}),\n });\n return new SetRunner(opened, agent, opts, options).run();\n}\n\n/** Why a planned task filed nothing, sent when the run closes; the platform\n * keeps one bounded reason per task. */\ntype TaskFailure = { worldTaskId: string; reason: string };\n\n/** One set run: its tasks in order, then its close. A task that fails never\n * stops the rest. SIGINT or SIGTERM starts no further task: the task in\n * flight closes its own sessions and the set run is closed failed, naming it.\n * Python twin: `gatewaysdk.world_set_runs.SetRunner`. */\nclass SetRunner {\n private readonly tasks: RunTaskSummary[] = [];\n private readonly failures: TaskFailure[] = [];\n private failed = false;\n private current: string | null = null;\n private interrupted: Promise<SetRunDoc> | null = null;\n private readonly signals = new RunSignals();\n\n constructor(\n private readonly opened: SetRunDoc,\n private readonly agent: (run: TaskRun) => TaskRunResult | Promise<TaskRunResult>,\n private readonly opts: RunSetOptions,\n private readonly options: WorldsClientOptions,\n ) {}\n\n async run(): Promise<RunSetResult> {\n await this.signals.during(\n (signal) => this.interrupt(signal).then(() => undefined),\n () => this.runTasks(),\n );\n const signal = this.signals.signal;\n if (signal !== null) return this.result(await this.interrupt(signal), \"failed\");\n const requested = this.failed ? \"failed\" : \"completed\";\n return this.result(await this.close(requested, this.failures), requested);\n }\n\n private interrupt(signal: RunSignal): Promise<SetRunDoc> {\n const stopped = this.current\n ? [{ worldTaskId: this.current, reason: `interrupted by ${signal}` }]\n : [];\n this.interrupted ??= this.close(\"failed\", [...this.failures, ...stopped]);\n return this.interrupted;\n }\n\n private async runTasks(): Promise<void> {\n for (const task of this.opened.tasks) {\n if (this.signals.signal !== null) return;\n this.current = task.worldTaskId;\n await this.runOne(task);\n }\n this.current = null;\n }\n\n private async runOne(task: SetRunDoc[\"tasks\"][number]): Promise<void> {\n try {\n const summary = await runTask(task.worldTaskId, this.agent, {\n model: this.opts.model,\n surfaces: this.opts.surfaces,\n browserTier: this.opts.browserTier,\n outDir: this.opts.outDir,\n trace: this.opts.trace,\n setRunId: this.opened.id,\n options: this.options,\n });\n this.tasks.push(summary);\n this.failed ||= taskRunFailure(summary) !== null;\n if (summary.fileError !== null)\n this.failures.push({ worldTaskId: task.worldTaskId, reason: summary.fileError });\n this.opts.onTask?.(summary);\n } catch (error) {\n this.failed = true;\n const message = error instanceof Error ? error.message : String(error);\n process.stderr.write(`task ${task.name} could not run: ${message}\\n`);\n this.failures.push({\n worldTaskId: task.worldTaskId,\n reason: message || (error instanceof Error ? error.name : \"Error\"),\n });\n }\n }\n\n private close(status: \"failed\" | \"completed\", failures: TaskFailure[] = []): Promise<SetRunDoc> {\n return apiRequest<SetRunDoc>(\n this.options,\n \"POST\",\n `${SET_RUNS}/${encodeURIComponent(this.opened.id)}/close`,\n { status, ...(failures.length ? { failures } : {}) },\n );\n }\n\n private result(setRun: SetRunDoc, requested: \"failed\" | \"completed\"): RunSetResult {\n return {\n setRun,\n tasks: this.tasks,\n failed: this.failed || setRun.status !== \"completed\",\n closedAsRequested: setRun.status === requested,\n };\n }\n}\n","import { WORLD_REQUEST_VIAS, WorldRequestsNotRecorded } from \"./requestLedger\";\nimport type { WorldSession, WorldSessionCall } from \"./session\";\n\n/** One entry of a world's request ledger as a list carries it: what was asked\n * and what came back, without its headers and bodies. */\nexport type WorldRequest = {\n id: string;\n seq: number;\n at: string;\n durationMs: number | null;\n worldSlug: string;\n sessionId: string;\n versionId: string;\n via: (typeof WORLD_REQUEST_VIAS)[number] | null;\n operation: string | null;\n method: string | null;\n path: string | null;\n query: Record<string, unknown>;\n request: { bodyBytes: number | null; truncated: boolean; contentType: string | null };\n response: {\n status: number;\n bodyBytes: number | null;\n truncated: boolean;\n contentType: string | null;\n };\n rows: number | null;\n found: boolean | null;\n};\n\n/** One page of a ledger list, newest first, with what its scope did not record: `shed` requests kept without\n * their headers and bodies, `lost` requests a host counted as never recorded or the platform refused, and\n * `hostsLost` hosts lost before they stored every request, whose unsent requests no count holds; none of them on\n * a page whose filters narrow past its world, session or version. */\nexport type WorldRequestPage = {\n requests: WorldRequest[];\n nextCursor: string | null;\n shed?: number;\n lost?: number;\n hostsLost?: number;\n};\n\nconst UNRECORDED = [\n [\"lost\", \"{n} request\", \"{n} requests\"],\n [\"shed\", \"{n} request's headers and bodies\", \"{n} requests' headers and bodies\"],\n [\"hostsLost\", \"the requests {n} lost host held\", \"the requests {n} lost hosts held\"],\n] as const;\n\n/** The one line every reader shows for a page's `shed`, `lost` and `hostsLost`, none when all are 0; twin of\n * `worldRequestsUnrecorded` in the platform and `unrecorded` in `gatewaysdk/world_requests.py`, all pinned to\n * `conformance/world-request-log.json` `unrecorded`. */\nexport function worldRequestsUnrecorded(counts: {\n shed?: unknown;\n lost?: unknown;\n hostsLost?: unknown;\n}): string | null {\n const parts = UNRECORDED.map(([field, one, many]) => [counted(counts[field]), one, many] as const)\n .filter(([count]) => count > 0)\n .map(([count, one, many]) => (count === 1 ? one : many).replace(\"{n}\", String(count)));\n return parts.length > 0 ? `Not recorded: ${parts.join(\", \")}` : null;\n}\n\nfunction counted(value: unknown): number {\n return typeof value === \"number\" && Number.isSafeInteger(value) && value > 0 ? value : 0;\n}\n\n/**\n * A session's entries in its world's request ledger: every request the world\n * received, through every door (`via`: api, ui, tool, webhook), kept for the life of\n * the world. Read page by page without recording anything in the session; the\n * platform's call ledger (`export()`) holds what it brokered — tool calls,\n * seeds, grades. One entry's headers and bodies are `GET\n * worlds/{slug}/requests/{requestId}`.\n */\nexport class WorldRequestLog {\n private constructor(\n readonly requests: WorldRequest[],\n readonly notRecorded: string | null = null,\n readonly unrecorded: string | null = null,\n ) {}\n\n /** Every entry the ledger holds for the session, oldest first, and the line for what it did not record;\n * for a session the World Host did not serve, none, and `notRecorded` says why. */\n static async load(session: WorldSession): Promise<WorldRequestLog> {\n try {\n return await WorldRequestLog.pages(session);\n } catch (error) {\n const refused = WorldRequestsNotRecorded.from(error);\n if (!(refused instanceof WorldRequestsNotRecorded)) throw error;\n return new WorldRequestLog([], refused.message);\n }\n }\n\n private static async pages(session: WorldSession): Promise<WorldRequestLog> {\n const requests: WorldRequest[] = [];\n let cursor: string | undefined;\n for (;;) {\n const page = await session.requests(cursor ? { cursor } : {});\n requests.push(...page.requests);\n if (!page.nextCursor || page.requests.length === 0)\n return new WorldRequestLog(requests.reverse(), null, worldRequestsUnrecorded(page));\n cursor = page.nextCursor;\n }\n }\n\n /** Each entry in the shape of a ledger line, `kind: \"request\"`, so one JSONL\n * file holds both: `args` what was asked, `result` what came back under the\n * entry's `requestId`. */\n asCalls(): WorldSessionCall[] {\n return this.requests.map((r) => ({\n seq: r.seq,\n kind: \"request\",\n tool: r.operation,\n args: {\n method: r.method,\n path: r.path,\n query: r.query,\n via: r.via,\n contentType: r.request.contentType,\n bodyBytes: r.request.bodyBytes,\n truncated: r.request.truncated,\n },\n result: {\n requestId: r.id,\n status: r.response.status,\n rows: r.rows,\n found: r.found,\n durationMs: r.durationMs,\n contentType: r.response.contentType,\n bodyBytes: r.response.bodyBytes,\n truncated: r.response.truncated,\n },\n error: null,\n completedAt: r.at,\n }));\n }\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\n\nexport const WORLD_WEBHOOK_PAGE_MAX = 100;\nconst FORWARD_TIMEOUT_MS = 10_000;\nconst ERROR_CHARS = 500;\n\nexport type WorldWebhookSubscription = {\n key: Record<string, unknown>;\n url: string | null;\n events: string[];\n scope: Record<string, string[]>;\n enabled: boolean;\n /** Deliveries this subscription was sent since the session's feed began. */\n sent: number;\n};\n\nexport type WorldWebhookDelivery = {\n seq: number;\n id: string;\n eventId: string;\n eventType: string;\n subscription: Record<string, unknown>;\n url: string;\n headers: Record<string, string>;\n payload: string;\n at: number;\n};\n\nexport type WorldWebhookPage = {\n declared: boolean;\n subscriptions: WorldWebhookSubscription[];\n truncated: boolean;\n epoch: string;\n reset: boolean;\n deliveries: WorldWebhookDelivery[];\n next: number;\n more: boolean;\n missed: number;\n answered: number;\n};\n\n/** A page as the read key sees it: which event went to which subscription and when. */\nexport type WorldWebhookListing = Omit<WorldWebhookPage, \"deliveries\"> & {\n deliveries: Pick<WorldWebhookDelivery, \"seq\" | \"id\" | \"eventType\" | \"subscription\" | \"at\">[];\n};\n\nexport type WorldWebhookAnswer = {\n id: string;\n status: number;\n durationMs: number;\n error: string | null;\n};\n\nexport type ForwardedDelivery = { delivery: WorldWebhookDelivery; answer: WorldWebhookAnswer };\n\nconst route = (sessionId: string) => `/api/public/world-sessions/${encodeURIComponent(sessionId)}/webhooks`;\n\n/** The webhooks a World Host session's world declares and has sent, without their signed headers. */\nexport async function listWebhooks(\n options: WorldsClientOptions,\n sessionId: string,\n page: { after?: number; limit?: number; epoch?: string; tail?: boolean } = {},\n): Promise<WorldWebhookListing> {\n const query = new URLSearchParams({\n after: String(page.after ?? 0),\n limit: String(page.limit ?? WORLD_WEBHOOK_PAGE_MAX),\n tail: String(page.tail ?? false),\n });\n if (page.epoch) query.set(\"epoch\", page.epoch);\n return apiRequest<WorldWebhookListing>(options, \"GET\", `${route(sessionId)}?${query.toString()}`);\n}\n\n/**\n * The forward lane: polls a session's deliveries (secret key), replays each to `forwardTo` exactly as signed,\n * so a receiver on this machine verifies it as it would the vendor's, and hands each receiver's answer back\n * on the next poll, where the world's request ledger keeps it beside the delivery.\n */\nexport class WorldWebhookForwarder {\n private after = 0;\n private epoch: string | null = null;\n private answers: WorldWebhookAnswer[] = [];\n private readonly send: typeof fetch;\n\n constructor(\n private readonly options: WorldsClientOptions,\n private readonly sessionId: string,\n private readonly forwardTo: string,\n opts: { fetch?: typeof fetch } = {},\n ) {\n this.send = opts.fetch ?? fetch;\n }\n\n get cursor(): number {\n return this.after;\n }\n\n /** Where forwarding begins: the deliveries the session still holds (`replay`), or only those it sends from now. */\n async start(replay: boolean): Promise<WorldWebhookPage | null> {\n if (replay) return null;\n const page = await this.poll([], { tail: true, limit: 1 });\n this.follow(page);\n return page;\n }\n\n /** One poll: the answers held so far sent, the next page forwarded. A poll that fails keeps its answers for the next. */\n async round(): Promise<{ page: WorldWebhookPage; forwarded: ForwardedDelivery[] }> {\n const page = await this.withAnswers((answers) => this.poll(answers));\n const forwarded: ForwardedDelivery[] = [];\n for (const delivery of page.deliveries) {\n const answer = await this.forward(delivery);\n this.answers.push(answer);\n forwarded.push({ delivery, answer });\n }\n this.follow(page);\n return { page, forwarded };\n }\n\n /** Sends the answers still held; the cursor stays, so a delivery this poll returns is forwarded by the next round. */\n async settle(): Promise<number> {\n if (this.answers.length === 0) return 0;\n const page = await this.withAnswers((answers) => this.poll(answers, { limit: 1 }));\n return page.answered;\n }\n\n private follow(page: WorldWebhookPage): void {\n this.after = page.next;\n this.epoch = page.epoch;\n }\n\n private async withAnswers(poll: (answers: WorldWebhookAnswer[]) => Promise<WorldWebhookPage>): Promise<WorldWebhookPage> {\n const answers = this.answers.splice(0, WORLD_WEBHOOK_PAGE_MAX);\n try {\n return await poll(answers);\n } catch (error) {\n this.answers.unshift(...answers);\n throw error;\n }\n }\n\n private poll(\n answers: WorldWebhookAnswer[],\n opts: { tail?: boolean; limit?: number } = {},\n ): Promise<WorldWebhookPage> {\n return apiRequest<WorldWebhookPage>(this.options, \"POST\", route(this.sessionId), {\n after: this.after,\n epoch: this.epoch,\n tail: opts.tail ?? false,\n limit: opts.limit ?? WORLD_WEBHOOK_PAGE_MAX,\n subscriptions: false,\n answers,\n });\n }\n\n private async forward(delivery: WorldWebhookDelivery): Promise<WorldWebhookAnswer> {\n const started = Date.now();\n try {\n const reply = await this.send(this.forwardTo, {\n method: \"POST\",\n headers: delivery.headers,\n body: delivery.payload,\n redirect: \"manual\",\n signal: AbortSignal.timeout(FORWARD_TIMEOUT_MS),\n });\n await reply.arrayBuffer().catch(() => undefined);\n if (reply.status < 100 || reply.status > 599) throw new Error(\"the receiver answered an invalid HTTP status\");\n return { id: delivery.id, status: reply.status, durationMs: Date.now() - started, error: null };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return { id: delivery.id, status: 0, durationMs: Date.now() - started, error: message.slice(0, ERROR_CHARS) };\n }\n }\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\n/** What `localTreeState(dir)` reports: the tracked meta and the edits since its base. */\nexport type TreeState = {\n meta: { slug?: string; baseFiles?: Record<string, string> } | null;\n dirty: string[];\n clean: boolean;\n};\n\nexport class CheckoutRefusedError extends Error {\n constructor(message: string) {\n super(`checkout refused: ${message}`);\n this.name = \"CheckoutRefusedError\";\n }\n}\n\nconst NAMED_EDITS = 3;\n\n/**\n * Where a pull lands, decided before a byte is downloaded (P-20).\n *\n * - No target: `./<slug>`, de-duplicated with `-1`/`-2`; an existing dir is\n * never entered.\n * - Explicit target: absent or empty → used as-is; a clean checkout of the\n * same world → replaced (its base files are cleared first so files the new\n * version dropped do not linger); local edits, another world's checkout or\n * an untracked non-empty dir → refused unless `force`, which discards the\n * checkout's base files *and* its local edits (added files included) so the\n * result is the pulled version, nothing else the archive would see.\n * - A relative target stays under the current directory; one that escapes it\n * (`../x`) is refused — an absolute path is the explicit way elsewhere (P-21).\n *\n * Python twin: `gatewaysdk.benchmark_hub.checkout.CheckoutTarget`.\n */\nexport class CheckoutTarget {\n private constructor(\n readonly dir: string,\n /** Files of the checkout being replaced (its base + its local edits); removed by `clear()`. */\n readonly replaces: string[],\n ) {}\n\n static resolve(\n slug: string,\n target: string | undefined,\n opts: { cwd: string; force: boolean; state: (dir: string) => TreeState },\n ): CheckoutTarget {\n if (target === undefined) return CheckoutTarget.fresh(slug, opts.cwd);\n return CheckoutTarget.explicit(\n CheckoutTarget.confined(target, opts.cwd),\n slug,\n opts,\n );\n }\n\n /** The absolute destination; a relative target may not resolve above `cwd`. */\n private static confined(target: string, cwd: string): string {\n const dir = path.resolve(cwd, target);\n if (path.isAbsolute(target)) return dir;\n const rel = path.relative(cwd, dir);\n if (rel === \"\" || (!rel.startsWith(\"..\") && !path.isAbsolute(rel)))\n return dir;\n throw new CheckoutRefusedError(\n `--target ${target} resolves outside the current directory (${cwd}) — run from that directory, or pass an absolute path`,\n );\n }\n\n private static fresh(slug: string, cwd: string): CheckoutTarget {\n const base = path.join(cwd, slug);\n let dir = base;\n let i = 1;\n while (fs.existsSync(dir)) dir = `${base}-${i++}`;\n return new CheckoutTarget(dir, []);\n }\n\n private static explicit(\n dir: string,\n slug: string,\n opts: { force: boolean; state: (dir: string) => TreeState },\n ): CheckoutTarget {\n if (!fs.existsSync(dir)) return new CheckoutTarget(dir, []);\n if (!fs.statSync(dir).isDirectory())\n throw new CheckoutRefusedError(`${dir} is a file`);\n if (fs.readdirSync(dir).length === 0) return new CheckoutTarget(dir, []);\n const state = opts.state(dir);\n const refusal = CheckoutTarget.refusal(dir, slug, state);\n if (refusal === null || opts.force)\n return new CheckoutTarget(dir, CheckoutTarget.tracked(state));\n throw new CheckoutRefusedError(refusal);\n }\n\n /** Base files plus local edits — everything the archive would see in the old\n * checkout. `.env-metadata.json` is local input: a key that would leave the\n * checkout (`../x`, `/etc/x`) is dropped, never removed. */\n private static tracked(state: TreeState): string[] {\n if (!state.meta?.baseFiles) return [];\n return [\n ...new Set([...Object.keys(state.meta.baseFiles), ...state.dirty]),\n ]\n .filter(CheckoutTarget.confinedRel)\n .sort();\n }\n\n private static confinedRel(rel: string): boolean {\n if (rel === \"\" || path.isAbsolute(rel)) return false;\n return !rel.split(/[\\\\/]/).includes(\"..\");\n }\n\n /** Why `dir` cannot be overwritten, or null when it is a clean checkout of `slug`. */\n private static refusal(\n dir: string,\n slug: string,\n state: TreeState,\n ): string | null {\n if (!state.meta?.baseFiles)\n return `${dir} is not empty and is not a checkout of \"${slug}\" — pick an empty --target, or pass --force to overwrite it`;\n if (state.meta.slug !== undefined && state.meta.slug !== slug)\n return `${dir} tracks \"${state.meta.slug}\", not \"${slug}\" — pick another --target, or pass --force to replace it`;\n if (state.clean) return null;\n const n = state.dirty.length;\n const named = state.dirty.slice(0, NAMED_EDITS).join(\", \");\n const more = n > NAMED_EDITS ? `, +${n - NAMED_EDITS} more` : \"\";\n return `${dir} has ${n} local edit${n === 1 ? \"\" : \"s\"} not pushed (${named}${more}) — push or propose them first, or pass --force to discard them`;\n }\n\n /** Remove the replaced checkout's files (and the dirs they leave empty). */\n clear(): void {\n for (const rel of this.replaces) {\n const abs = path.join(this.dir, rel);\n fs.rmSync(abs, { force: true });\n this.pruneEmptyParents(path.dirname(abs));\n }\n }\n\n private pruneEmptyParents(from: string): void {\n let cur = from;\n while (cur !== this.dir && cur.startsWith(this.dir)) {\n if (fs.existsSync(cur) && fs.readdirSync(cur).length > 0) return;\n fs.rmSync(cur, { recursive: true, force: true });\n cur = path.dirname(cur);\n }\n }\n}\n","/**\n * What a directory IS, decided once for the TS SDK.\n *\n * `WorldDir.open(dir)` is the one detector this package has: the benchmark\n * front door (`classifyTree`, `detectEnvKind`, `harborTaskDirs`,\n * `verifiersPackage` in ../benchmarks) and the hub client (`collectArchiveRelPaths`,\n * `computeContentHash`, the contract-version lookup in ./hub.ts) are facades\n * over it. Twin of `gatewaysdk.environment.world.World` (Python) and\n * `packages/shared/src/world` (the platform); the corpus under\n * `conformance/worlds/` pins all three to the same answers.\n */\nimport { createHash } from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nexport const WORLD_MANIFEST = \"gateway-env.toml\";\nexport const API_BUNDLE_MANIFEST = \"gateway-api-world.toml\";\nexport const BUNDLED_WORLD_PREFIX = \"server/world/\";\nexport const CONNECTOR_SPEC = \"connector.toml\";\nexport const PYPROJECT = \"pyproject.toml\";\nexport const BENCHMARK_CONFIG = \"benchmark.json\";\nexport const WORLD_SCHEMA_MARKERS = [\"schema/world.json\", \"schema/runtime.json\", \"schema/lock.json\"];\nconst WORLD_ROOT_MARKERS = [CONNECTOR_SPEC, ...WORLD_SCHEMA_MARKERS];\n/** Root markers that widen the archive to every ordinary root file: a world's\n * executable contract and a benchmark's config/fixtures live at the root. */\nconst BROAD_ROOT_MARKERS = [WORLD_MANIFEST, API_BUNDLE_MANIFEST, BENCHMARK_CONFIG];\nconst SKIPPED_DIRS = new Set([\"dist\", \"build\", \"outputs\", \"__pycache__\", \"node_modules\"]);\n\n/** One entry the archive rules dropped: a whole directory (`name/`, `files`\n * counted) or a single file. */\nexport type Exclusion = { path: string; files: number };\n\n/** The runner's kind: what the dispatcher executes a pushed tree as. */\nexport type EnvKind = \"api\" | \"mock-tools\" | \"harbor\" | \"verifiers-v1\" | \"verifiers\";\n\n// The `verifiers.v1` namespace first shipped in verifiers 0.2.0: a v1 package\n// pins verifiers>=0.2 (or ~=0.2 / ==0.2.* / >=1 / ==1.*) in pyproject and/or\n// imports the namespace or subclasses Taskset alongside a v1-style `__all__`.\nconst V1_DEP = /[\"']verifiers\\s*(?:\\[[^\\]]*\\])?\\s*(?:>=|~=|==|>)\\s*(?:0\\.(?:[2-9]\\d*|[1-9]\\d+)|[1-9]\\d*)/;\nconst V1_IMPORT = /^\\s*(?:from\\s+verifiers\\.v1\\s+import\\b|from\\s+verifiers\\s+import\\s+v1\\b|import\\s+verifiers\\.v1\\b)/m;\nconst V1_TASKSET = /class\\s+\\w+\\s*\\(\\s*(?:(?:vf|v1|verifiers(?:\\.v1)?)\\.)?Taskset\\s*[,)]/;\nconst HARBOR_TASK = /^(?:tasks\\/)?([^/]+)\\/task\\.toml$/;\n\nconst skippedDir = (name: string): boolean =>\n name.startsWith(\".\") || SKIPPED_DIRS.has(name) || name.endsWith(\".egg-info\");\n\n/** Python's `sorted()` order for relpaths: code points, not UTF-16 units. */\nconst byCodePoint = (a: string, b: string): number => Buffer.compare(Buffer.from(a, \"utf-8\"), Buffer.from(b, \"utf-8\"));\n\nexport class WorldDir {\n private pathsMemo: string[] | undefined;\n\n private constructor(\n readonly dir: string,\n /** Where the authored world lives: `\"\"` for a world stored as itself,\n * `server/world/` for one stored as its api bundle. */\n readonly worldRoot: \"\" | typeof BUNDLED_WORLD_PREFIX,\n ) {}\n\n static open(dir: string): WorldDir {\n const present = (rel: string) => fs.existsSync(path.join(dir, rel));\n const bundled = present(API_BUNDLE_MANIFEST) && WORLD_ROOT_MARKERS.some((m) => present(BUNDLED_WORLD_PREFIX + m));\n return new WorldDir(dir, bundled ? BUNDLED_WORLD_PREFIX : \"\");\n }\n\n // ── Files ──────────────────────────────────────────────────────────────\n\n has(rel: string): boolean {\n return fs.existsSync(path.join(this.dir, rel));\n }\n\n text(rel: string): string | null {\n try {\n return fs.readFileSync(path.join(this.dir, rel), \"utf-8\");\n } catch {\n return null;\n }\n }\n\n /** A path under the authored world's root. */\n worldPath(rel: string): string {\n return this.worldRoot + rel;\n }\n\n /** Every regular file the archive rules keep (`_archive.py`: no hidden,\n * dist, build, outputs, pycache, node_modules or egg-info directories), as\n * sorted relpaths. Root files enter only when a Gateway manifest or\n * benchmark.json widens the root, or they are README.md, pyproject.toml or\n * Python. */\n get archivePaths(): string[] {\n if (this.pathsMemo) return this.pathsMemo;\n const broad = BROAD_ROOT_MARKERS.some((m) => this.has(m));\n const out: string[] = [];\n const walk = (rel: string) => {\n for (const entry of fs.readdirSync(rel ? path.join(this.dir, rel) : this.dir, { withFileTypes: true })) {\n const child = rel ? `${rel}/${entry.name}` : entry.name;\n if (entry.isDirectory()) {\n if (!skippedDir(entry.name)) walk(child);\n } else if (entry.isFile() && !entry.name.startsWith(\".\")) {\n const rootKept =\n broad || [\"README.md\", PYPROJECT, ...BROAD_ROOT_MARKERS].includes(entry.name) || entry.name.endsWith(\".py\");\n if (rel || rootKept) out.push(child);\n }\n }\n };\n walk(\"\");\n return (this.pathsMemo = out.sort(byCodePoint));\n }\n\n /** What the archive rules leave out, collapsed to the entry that decided\n * it: a pruned directory counts its files once, a dropped root file is\n * named. Dot entries (`.git/`, `.gateway/`, `.gitignore`) are the one\n * universal convention and stay unreported. `push` prints the rest so\n * nothing disappears silently. */\n get exclusions(): Exclusion[] {\n const kept = new Set(this.archivePaths);\n const out: Exclusion[] = [];\n const filesUnder = (rel: string): string[] =>\n fs.readdirSync(path.join(this.dir, rel), { withFileTypes: true }).flatMap((entry) => {\n const child = `${rel}/${entry.name}`;\n if (entry.isDirectory()) return filesUnder(child);\n return entry.isFile() ? [child] : [];\n });\n for (const entry of fs.readdirSync(this.dir, { withFileTypes: true }).sort((a, b) => byCodePoint(a.name, b.name))) {\n if (entry.name.startsWith(\".\")) continue;\n if (entry.isDirectory()) {\n const all = filesUnder(entry.name);\n const missing = all.filter((rel) => !kept.has(rel));\n if (missing.length === 0) continue;\n const whole = missing.length === all.length;\n out.push(...(whole ? [{ path: `${entry.name}/`, files: missing.length }] : missing.map((p) => ({ path: p, files: 1 }))));\n continue;\n }\n // A file, or a symlink to anything: the archive never follows a link.\n if (!kept.has(entry.name)) out.push({ path: entry.name, files: 1 });\n }\n return out;\n }\n\n /** A root `.gitignore` is present: the Python SDK honours it when\n * collecting, this package does not reimplement gitignore. */\n get hasRootGitignore(): boolean {\n return this.has(\".gitignore\");\n }\n\n /** SHA-256 over `utf8(\"file:\" + relpath)` + bytes per archive path in\n * sorted order: the version's identity, byte-compatible with\n * `_archive.compute_content_hash` and Prime Intellect. */\n get contentHash(): string {\n const hasher = createHash(\"sha256\");\n for (const rel of this.archivePaths) {\n hasher.update(Buffer.from(`file:${rel}`, \"utf-8\"));\n hasher.update(fs.readFileSync(path.join(this.dir, rel)));\n }\n return hasher.digest(\"hex\");\n }\n\n // ── Markers ────────────────────────────────────────────────────────────\n\n get isApiBundle(): boolean {\n return this.has(API_BUNDLE_MANIFEST);\n }\n\n get hasManifest(): boolean {\n return this.has(this.worldPath(WORLD_MANIFEST));\n }\n\n get hasSchemaMarker(): boolean {\n return WORLD_SCHEMA_MARKERS.some((m) => this.has(this.worldPath(m)));\n }\n\n /** Harbor task dirs, relative to the tree: `tasks/<name>` when a `tasks/`\n * dir holds them, else the root `<name>` dirs. */\n taskDirs(): string[] {\n const names = new Set<string>();\n for (const rel of this.archivePaths) {\n const m = HARBOR_TASK.exec(rel);\n if (m) names.add(rel.startsWith(\"tasks/\") ? `tasks/${m[1]}` : m[1]!);\n }\n const under = [...names].filter((n) => n.startsWith(\"tasks/\"));\n return (under.length ? under : [...names]).sort();\n }\n\n /** The Python package of a verifiers tree (`<pkg>/__init__.py` or\n * `src/<pkg>/__init__.py`), or null. */\n pythonPackage(): { name: string; init: string } | null {\n if (!this.has(PYPROJECT)) return null;\n for (const base of [\"\", \"src/\"]) {\n const init = this.archivePaths.find((rel) => {\n const m = /^([^/]+)\\/__init__\\.py$/.exec(rel.startsWith(base) ? rel.slice(base.length) : \"\");\n return m !== null && m[1] !== \"tests\";\n });\n if (init) return { name: init.slice(base.length).split(\"/\")[0]!, init };\n }\n return null;\n }\n\n /** The package targets the `verifiers.v1` API: read from the root\n * pyproject and every archived Python module. */\n get isVerifiersV1(): boolean {\n for (const rel of this.archivePaths) {\n if (rel !== PYPROJECT && !rel.endsWith(\".py\")) continue;\n const text = this.text(rel);\n if (text === null) continue;\n if (rel === PYPROJECT ? V1_DEP.test(text) : V1_IMPORT.test(text) || (text.includes(\"__all__\") && V1_TASKSET.test(text)))\n return true;\n }\n return false;\n }\n\n // ── The answer ─────────────────────────────────────────────────────────\n\n /** The runner's kind (`detect_env_kind`): api / mock-tools win over\n * everything, a harbor task tree next, then the verifiers API version. */\n get kind(): EnvKind {\n if (this.isApiBundle) return \"api\";\n if (this.has(WORLD_MANIFEST)) return \"mock-tools\";\n if (this.taskDirs().length) return \"harbor\";\n return this.isVerifiersV1 ? \"verifiers-v1\" : \"verifiers\";\n }\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { gunzipSync } from \"node:zlib\";\n\n/**\n * The sdk-ts reader of a world's gzipped tar bundle — the twin of the\n * platform's `packages/shared/src/server/worlds/tar.ts` walker. A bundle\n * `pull`/`checkout` downloads may have been written by any of the three\n * writers on the platform, so the walk understands every way a name can\n * travel:\n * • the 100-byte ustar `name` field, UTF-8 (this SDK's own writer),\n * • a GNU `L` long-name member naming the member that follows,\n * • a PAX `x` header whose `path=` record overrides the next name — what\n * Python's `tarfile` (the Python SDK's writer) emits for every\n * non-ASCII or >100-byte name, leaving a `?`-replaced ASCII fallback in\n * the ustar field,\n * • the POSIX ustar `prefix` field (bytes 345–500) joined as `prefix/name`.\n * Reading only the ustar field silently corrupts the other three (cold-batch\n * P-05: `ünïcödé ✓.txt` pulled as `?n?c?d? ?.txt`).\n */\n\nexport const TAR_FILE_MODE = 0o644;\nexport const TAR_EXEC_MODE = 0o755;\n\n/** The only mode detail a world keeps: executable or not. */\nexport function archiveMode(mode: number): number {\n return (mode & 0o111) !== 0 ? TAR_EXEC_MODE : TAR_FILE_MODE;\n}\n\nexport type TarMember = {\n name: string;\n bytes: Buffer;\n typeflag: string;\n mode: number;\n};\n\nfunction field(header: Buffer, start: number, end: number): string {\n return header.subarray(start, end).toString(\"utf-8\").replace(/\\0.*$/, \"\");\n}\n\nfunction octalField(header: Buffer, start: number, end: number): number {\n return parseInt(field(header, start, end).trim(), 8);\n}\n\n/** `path=` from a PAX extended-header payload (`LEN key=value\\n` records). */\nfunction paxPath(body: Buffer): string | null {\n let off = 0;\n let found: string | null = null;\n while (off < body.length) {\n const sp = body.indexOf(0x20, off);\n if (sp === -1) break;\n const len = parseInt(body.subarray(off, sp).toString(\"ascii\"), 10);\n if (!Number.isFinite(len) || len <= 0) break;\n const record = body.subarray(sp + 1, off + len);\n const eq = record.indexOf(0x3d);\n const key = eq === -1 ? \"\" : record.subarray(0, eq).toString(\"utf-8\");\n if (key === \"path\")\n found = record\n .subarray(eq + 1)\n .toString(\"utf-8\")\n .replace(/\\n$/, \"\");\n off += len;\n }\n return found;\n}\n\nexport class TarArchive {\n private constructor(private readonly tar: Buffer) {}\n\n static fromGzip(bundle: Buffer): TarArchive {\n return new TarArchive(gunzipSync(bundle));\n }\n\n static fromTar(tar: Buffer): TarArchive {\n return new TarArchive(tar);\n }\n\n /** Every member, names fully resolved; metadata members are consumed. */\n *members(): Generator<TarMember> {\n const tar = this.tar;\n let offset = 0;\n let pendingName: string | null = null;\n while (offset + 512 <= tar.length) {\n const header = tar.subarray(offset, offset + 512);\n offset += 512;\n if (header.every((b) => b === 0)) break;\n const size = octalField(header, 124, 136) || 0;\n const mode = octalField(header, 100, 108) || TAR_FILE_MODE;\n const typeflag = String.fromCharCode(header[156] ?? 0);\n const bytes = tar.subarray(offset, offset + size);\n offset += Math.ceil(size / 512) * 512;\n if (typeflag === \"L\") {\n pendingName = bytes.toString(\"utf-8\").replace(/\\0.*$/, \"\");\n continue;\n }\n if (typeflag === \"x\") {\n pendingName = paxPath(bytes) ?? pendingName;\n continue;\n }\n if (typeflag === \"K\" || typeflag === \"g\") continue;\n const name = pendingName ?? TarArchive.ustarName(header);\n pendingName = null;\n yield { name: name.replace(/^\\.\\//, \"\"), bytes, typeflag, mode };\n }\n }\n\n private static ustarName(header: Buffer): string {\n const name = field(header, 0, 100);\n const magic = header.subarray(257, 262).toString(\"ascii\");\n const prefix = magic === \"ustar\" ? field(header, 345, 500) : \"\";\n return prefix ? `${prefix}/${name}` : name;\n }\n\n /** Regular files only, confined to `dir` (absolute or `..` names are\n * skipped, never written). Returns the number of files written. */\n extractTo(dir: string): number {\n let written = 0;\n for (const member of this.members()) {\n if (member.typeflag !== \"0\" && member.typeflag !== \"\\0\") continue;\n if (!TarArchive.isConfined(member.name)) continue;\n const target = path.join(dir, member.name);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n const mode = archiveMode(member.mode);\n fs.writeFileSync(target, member.bytes, { mode });\n fs.chmodSync(target, mode);\n written++;\n }\n return written;\n }\n\n private static isConfined(name: string): boolean {\n if (name === \"\" || name.startsWith(\"/\")) return false;\n return !name.split(\"/\").includes(\"..\");\n }\n}\n","import { createHash } from \"node:crypto\";\nimport { gzipSync } from \"node:zlib\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\nimport { CheckoutTarget } from \"./checkoutTarget\";\nimport { WorldDir, type Exclusion } from \"./worldDir\";\nimport { TarArchive, TAR_FILE_MODE, archiveMode } from \"./tar\";\n\n/**\n * The working-dir half of the TS CLI: push / pull / checkout / status /\n * branch / tag / propose — a faithful port of the Python client\n * (`gatewaysdk/benchmark_hub/client.py` + `_archive.py`).\n *\n * The content hash is the version's identity and is byte-compatible with\n * Prime Intellect: `WorldDir.contentHash` (./worldDir.ts) computes it here,\n * `WorldTree.contentHash` on the platform and `_archive.compute_content_hash`\n * in the Python SDK; the conformance corpus pins the three to the same bytes.\n *\n * One deliberate refusal, same policy as the web upload path: a bundle with\n * a ROOT `.gitignore` is refused rather than mis-hashed — the Python CLI\n * honors it via `gitignore_parser`, and an imperfect reimplementation here\n * would produce a wrong, Prime-incompatible hash silently.\n */\n\nexport const DEFAULT_BRANCH = \"main\";\nconst META_RELPATH = path.join(\".gateway\", \".env-metadata.json\");\n\n/** The archive-visible files of a working dir, as sorted relpaths\n * (`WorldDir.archivePaths`). Throws on a root .gitignore (see the header). */\nexport function collectArchiveRelPaths(dir: string): string[] {\n const world = WorldDir.open(dir);\n if (world.hasRootGitignore) {\n throw new Error(\n \"This bundle has a root .gitignore, which the Python CLI honors via \" +\n \"gitignore_parser. Reimplementing that imperfectly here would \" +\n \"silently produce a different content hash, so the TS CLI refuses. \" +\n \"Remove the .gitignore (or bake its effect into the tree) and retry.\",\n );\n }\n return world.archivePaths;\n}\n\nexport function computeContentHash(dir: string): string {\n collectArchiveRelPaths(dir);\n return WorldDir.open(dir).contentHash;\n}\n\nfunction octal(value: number, length: number): Buffer {\n return Buffer.from(\n value.toString(8).padStart(length - 1, \"0\") + \"\\0\",\n \"ascii\",\n );\n}\n\n/** The two modes a stored world file can have: the tar (and `pull`) keep\n * only whether a file is executable — `tests/test.sh` in a harbor tree must\n * still run after a round trip. Owner/mtime are cleared for determinism. */\nconst FILE_MODE = TAR_FILE_MODE;\nexport { archiveMode };\n\nfunction tarHeader(name: string, size: number, mode = FILE_MODE): Buffer {\n const header = Buffer.alloc(512);\n header.write(name, 0, 100, \"utf-8\");\n octal(mode, 8).copy(header, 100);\n octal(0, 8).copy(header, 108);\n octal(0, 8).copy(header, 116);\n octal(size, 12).copy(header, 124);\n octal(0, 12).copy(header, 136);\n header.write(\" \", 148, \"ascii\");\n header.write(\"0\", 156, \"ascii\");\n header.write(\"ustar\", 257, \"ascii\");\n header.write(\"00\", 263, \"ascii\");\n let sum = 0;\n for (const byte of header) sum += byte;\n header.write(sum.toString(8).padStart(6, \"0\") + \"\\0 \", 148, \"ascii\");\n return header;\n}\n\nfunction tarMember(name: string, payload: Buffer, mode: number): Buffer[] {\n const parts: Buffer[] = [];\n const nameBytes = Buffer.byteLength(name, \"utf-8\");\n if (nameBytes > 100) {\n // GNU long name: an 'L' member whose body is the real name.\n const body = Buffer.from(name + \"\\0\", \"utf-8\");\n const lHeader = tarHeader(\"././@LongLink\", body.length);\n lHeader.write(\"L\", 156, \"ascii\");\n let sum = 0;\n lHeader.write(\" \", 148, \"ascii\");\n for (const byte of lHeader) sum += byte;\n lHeader.write(sum.toString(8).padStart(6, \"0\") + \"\\0 \", 148, \"ascii\");\n parts.push(lHeader, body);\n const pad = body.length % 512 === 0 ? 0 : 512 - (body.length % 512);\n if (pad) parts.push(Buffer.alloc(pad));\n parts.push(tarHeader(name.slice(0, 100), payload.length, mode));\n } else {\n parts.push(tarHeader(name, payload.length, mode));\n }\n parts.push(payload);\n const pad = payload.length % 512 === 0 ? 0 : 512 - (payload.length % 512);\n if (pad) parts.push(Buffer.alloc(pad));\n return parts;\n}\n\n/** A deterministic .tar.gz of the source files (node's gzip stamps no mtime,\n * matching the Python's mtime=0 gzip). */\nexport function buildSourceTarball(dir: string): Buffer {\n const parts: Buffer[] = [];\n for (const relPath of collectArchiveRelPaths(dir)) {\n const abs = path.join(dir, relPath);\n parts.push(\n ...tarMember(\n relPath,\n fs.readFileSync(abs),\n archiveMode(fs.statSync(abs).mode),\n ),\n );\n }\n parts.push(Buffer.alloc(1024));\n return gzipSync(Buffer.concat(parts), { level: 9 });\n}\n\nexport type LocalMeta = Record<string, unknown> & {\n slug?: string;\n /** Branch the checkout tracks; absent on a tag (detached) checkout. */\n branch?: string;\n /** Tag the checkout was taken from: immutable, so `push` refuses to move it. */\n tag?: string;\n versionId?: string;\n contentHash?: string;\n baseFiles?: Record<string, string>;\n};\n\nexport function readLocalMeta(dir: string): LocalMeta | null {\n try {\n const raw = fs.readFileSync(path.join(dir, META_RELPATH), \"utf-8\");\n const parsed = JSON.parse(raw);\n return parsed && typeof parsed === \"object\" ? (parsed as LocalMeta) : null;\n } catch {\n return null;\n }\n}\n\n/** The slug a push of `dir` lands on: an explicit one, else the slug the dir\n * was pushed to or pulled from (its `.gateway` meta), else the pyproject\n * name, else the directory's name — so a tracked checkout never creates a\n * second world named after its folder. */\nexport function pushSlug(dir: string, explicit?: string): string {\n return resolvePushSlug(dir, { explicit }).slug;\n}\n\nexport type SlugDeclaration = { source: string; slug: string };\n\nexport type PushSlugResolution = {\n slug: string;\n /** Where the slug came from (`--slug`, `.gateway metadata`, `benchmark.json`, `pyproject.toml`, `directory name`). */\n source: string;\n /** The slug the dir's `.gateway/.env-metadata.json` tracks from an earlier push or pull, if any. */\n tracked: string | null;\n /** What the tree itself declares (a caller's benchmark.json, then pyproject.toml), in precedence order. */\n declared: SlugDeclaration[];\n /** A declaration the tracked slug does not match — set only when the tracked slug won without `--slug`. */\n conflict: SlugDeclaration | null;\n};\n\nconst MINTED_SUFFIX = /^-\\d+$/;\n\n/** `pushSlug` with its provenance. `declared` are the caller's own slug sources\n * (e.g. `{ \"benchmark.json\": \"x\" }`), consulted before pyproject. A tracked slug\n * that disagrees with what the tree declares is reported as `conflict` so a\n * front door can refuse: that is how a directory pushed once with `--slug X`\n * silently landed every later push on X while its benchmark.json said Y. The\n * platform's collision suffix (`acme-2` minted for a taken `acme`) is not a\n * conflict; any other difference is (`acme-e2e` for `acme` was the mix-up). */\nexport function resolvePushSlug(\n dir: string,\n opts: { explicit?: string; declared?: Record<string, string | null | undefined> } = {},\n): PushSlugResolution {\n const meta = readLocalMeta(dir);\n const tracked = typeof meta?.slug === \"string\" && meta.slug ? meta.slug : null;\n const declared = Object.entries({ ...(opts.declared ?? {}), \"pyproject.toml\": readPyproject(dir).name })\n .filter((entry): entry is [string, string] => typeof entry[1] === \"string\" && entry[1] !== \"\")\n .map(([source, slug]) => ({ source, slug }));\n const base = { tracked, declared, conflict: null };\n if (opts.explicit) return { ...base, slug: opts.explicit, source: \"--slug\" };\n if (tracked) {\n const minted = (d: SlugDeclaration) => tracked.startsWith(d.slug) && MINTED_SUFFIX.test(tracked.slice(d.slug.length));\n const conflict = declared.find((d) => d.slug !== tracked && !minted(d)) ?? null;\n return { ...base, slug: tracked, source: \".gateway metadata\", conflict };\n }\n const first = declared[0];\n if (first) return { ...base, slug: first.slug, source: first.source };\n return { ...base, slug: path.basename(path.resolve(dir)), source: \"directory name\" };\n}\n\n/** The refusal a front door raises on `PushSlugResolution.conflict`: both slugs, both sources, every way out. */\nexport class PushSlugConflict extends Error {\n constructor(\n public readonly dir: string,\n public readonly tracked: string,\n public readonly declared: SlugDeclaration,\n ) {\n super(\n `${dir} tracks slug \\`${tracked}\\` (${META_RELPATH}, from an earlier push) but its ${declared.source} says \\`${declared.slug}\\`. ` +\n `Nothing was pushed. Pass --slug ${declared.slug} to push there (and retrack the dir), --slug ${tracked} to keep pushing to \\`${tracked}\\`, ` +\n `or delete ${META_RELPATH} to forget the earlier push.`,\n );\n this.name = \"PushSlugConflict\";\n }\n}\n\nexport function writeLocalMeta(dir: string, meta: LocalMeta): void {\n fs.mkdirSync(path.join(dir, \".gateway\"), { recursive: true });\n fs.writeFileSync(path.join(dir, META_RELPATH), JSON.stringify(meta, null, 2));\n}\n\nexport function snapshotTreeHashes(dir: string): Record<string, string> {\n const out: Record<string, string> = {};\n for (const relPath of collectArchiveRelPaths(dir)) {\n out[relPath] = createHash(\"sha256\")\n .update(fs.readFileSync(path.join(dir, relPath)))\n .digest(\"hex\");\n }\n return out;\n}\n\nexport function localTreeState(dir: string): {\n meta: LocalMeta | null;\n dirty: string[];\n clean: boolean;\n} {\n const meta = readLocalMeta(dir);\n const base = meta?.baseFiles;\n if (!base || typeof base !== \"object\") {\n return { meta, dirty: [], clean: false };\n }\n const now = snapshotTreeHashes(dir);\n const dirty = new Set<string>();\n for (const [p, h] of Object.entries(now)) if (base[p] !== h) dirty.add(p);\n for (const p of Object.keys(base)) if (!(p in now)) dirty.add(p);\n return { meta, dirty: [...dirty].sort(), clean: dirty.size === 0 };\n}\n\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 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\nfunction readWorldContractVersion(dir: string): {\n name?: string;\n version?: string;\n} {\n const world = WorldDir.open(dir);\n try {\n const parsed = JSON.parse(\n world.text(world.worldPath(\"schema/world.json\")) ?? \"\",\n ) as {\n \"x-gateway\"?: { package?: { id?: string; version?: string } };\n };\n const pkg = parsed[\"x-gateway\"]?.package;\n if (pkg?.version) return { name: pkg.id, version: pkg.version };\n } catch {\n // Not a schema world: it has no package block to read.\n }\n return {};\n}\n\n/** The rows the platform previews for a pushed DRAFT: the archive set, one\n * entry per file the content hash covers, so hash, tarball, manifest and\n * `pull` agree on what the world is. Finalize replaces them with rows\n * derived from the stored bytes. */\nexport function buildFileManifest(\n dir: string,\n): { path: string; isDirectory: boolean; size: number; sha256: string }[] {\n return collectArchiveRelPaths(dir).map((relPath) => {\n const payload = fs.readFileSync(path.join(dir, relPath));\n return {\n path: relPath,\n isDirectory: false,\n size: payload.length,\n sha256: createHash(\"sha256\").update(payload).digest(\"hex\"),\n };\n });\n}\n\nasync function putObject(\n url: string,\n data: Buffer,\n shaB64: string,\n): Promise<void> {\n const resp = await fetch(url, {\n method: \"PUT\",\n headers: {\n \"Content-Type\": \"application/gzip\",\n \"x-amz-checksum-sha256\": shaB64,\n },\n body: new Uint8Array(data),\n });\n if (!resp.ok) {\n throw new Error(\n `object PUT -> ${resp.status}: ${(await resp.text()).slice(0, 300)}`,\n );\n }\n}\n\nexport class DetachedPushError extends Error {\n constructor(dir: string, tag: string) {\n super(\n `push refused: ${dir} is a checkout of tag \"${tag}\" (tags are immutable). ` +\n `Nothing was pushed. Pass --branch <name> to land these files on a branch, or checkout a branch first.`,\n );\n this.name = \"DetachedPushError\";\n }\n}\n\n/** The branch a push of `dir` moves: an explicit --branch, else the tracked\n * branch, else main — never a tag. */\nexport function pushBranch(dir: string, localMeta: LocalMeta, explicit: string | undefined): string {\n if (explicit) return explicit;\n if (typeof localMeta.tag === \"string\" && localMeta.tag) throw new DetachedPushError(dir, localMeta.tag);\n return (localMeta.branch as string | undefined) ?? DEFAULT_BRANCH;\n}\n\nexport async function push(\n dir: string,\n opts: {\n slug?: string;\n branch?: string;\n force?: boolean;\n message?: string;\n author?: string;\n /** Push on top of this version instead of the local meta's base — what a\n * CI checkout (which has no local meta) passes after resolving the\n * branch tip, so re-validating a PR replaces its own previous push\n * instead of 409ing against it. */\n baseVersionId?: string | null;\n /** Container metadata recorded on resolve — the Python CLI's --name,\n * --description, --tag and --visibility. */\n name?: string;\n description?: string;\n tags?: string[];\n visibility?: string;\n /** Pre-built OCI image ref for image/agentic envs (recorded on the version). */\n imageRef?: string;\n options?: WorldsClientOptions;\n } = {},\n): Promise<{\n containerId: string;\n slug: string;\n versionId: string;\n contentHash: string;\n branch: string;\n state: string | null;\n alreadyUploaded: boolean;\n /** The edit session the push joined (`gateway worlds edit close <slug>` moves main); null when the platform landed it on main directly. */\n editSessionId: string | null;\n /** Files the archive rules kept (what the hash, manifest and tarball cover). */\n filesKept: number;\n /** What the archive rules left out, so nothing disappears silently. */\n excluded: Exclusion[];\n}> {\n const options = opts.options ?? {};\n if (!fs.statSync(dir).isDirectory())\n throw new Error(`Not a directory: ${dir}`);\n const localMeta = readLocalMeta(dir) ?? {};\n const branch = pushBranch(dir, localMeta, opts.branch);\n const baseVersionId = opts.baseVersionId ?? localMeta.versionId ?? null;\n\n const world = WorldDir.open(dir);\n const fileManifest = buildFileManifest(dir);\n if (fileManifest.length === 0)\n throw new Error(\n `Nothing to push: ${dir} has no files the archive rules keep (a world root marker, README.md, pyproject.toml, *.py, or any file below a subdirectory).`,\n );\n const contentHash = world.contentHash;\n const pyproject = readPyproject(dir);\n const contractVersion = pyproject.version\n ? undefined\n : readWorldContractVersion(dir).version;\n if (contractVersion) pyproject.version = contractVersion;\n // A dir that tracks a world (created, pulled or pushed before) pushes back\n // to THAT world: its recorded slug wins over the package name, so a world\n // created as `acme-f7` is not re-published as pyproject's `acme` — which is\n // how `worlds ci` minted an unsuffixed twin of every suffixed world.\n const slug =\n opts.slug ??\n localMeta.slug ??\n pyproject.name ??\n path.basename(path.resolve(dir));\n\n // Sent twice on purpose: resolve records it on a container it CREATES,\n // finalize refreshes an existing one — only when the push actually lands.\n // An omitted field leaves the container's value alone; an explicit one\n // replaces it, so `\"\"` clears the description and `[]` clears the tags.\n const metadata = {\n ...(opts.name !== undefined ? { name: opts.name } : {}),\n ...(opts.description !== undefined\n ? { description: opts.description }\n : {}),\n ...(opts.tags !== undefined ? { tags: opts.tags } : {}),\n ...(opts.visibility ? { visibility: opts.visibility } : {}),\n };\n const resolve = await apiRequest<{ containerId: string }>(\n options,\n \"POST\",\n \"/api/public/benchmark-containers/resolve\",\n { slug, ...metadata },\n );\n\n const tarball = buildSourceTarball(dir);\n const bundleSha256 = sha256b64(tarball);\n\n const version = await apiRequest<{\n versionId: string;\n uploadUrl?: string;\n alreadyUploaded?: boolean;\n }>(options, \"POST\", \"/api/public/benchmark-containers/versions\", {\n containerId: resolve.containerId,\n contentHash,\n bundleSha256,\n bundleSizeBytes: tarball.length,\n ...(pyproject.version ? { semanticVersion: pyproject.version } : {}),\n pyprojectMeta: pyproject,\n fileManifest,\n branch,\n baseVersionId,\n ...(opts.force ? { force: true } : {}),\n ...(opts.message ? { changeReason: opts.message } : {}),\n ...(opts.author ? { author: opts.author } : {}),\n ...(opts.imageRef ? { imageRef: opts.imageRef } : {}),\n });\n\n if (version.uploadUrl)\n await putObject(version.uploadUrl, tarball, bundleSha256);\n\n const final = await apiRequest<{ state?: string; branch?: string; editSessionId?: string }>(\n options,\n \"POST\",\n `/api/public/benchmark-containers/versions/${version.versionId}/finalize`,\n {\n branch,\n baseVersionId,\n ...(opts.force ? { force: true } : {}),\n ...metadata,\n },\n );\n\n writeLocalMeta(dir, {\n ...localMeta,\n slug,\n ref: branch,\n branch,\n versionId: version.versionId,\n contentHash,\n semanticVersion: pyproject.version,\n forkedFromVersionId: baseVersionId,\n baseFiles: snapshotTreeHashes(dir),\n });\n return {\n containerId: resolve.containerId,\n slug,\n versionId: version.versionId,\n contentHash,\n branch: final.branch ?? branch,\n state: final.state ?? null,\n alreadyUploaded: Boolean(version.alreadyUploaded),\n editSessionId: final.editSessionId ?? null,\n filesKept: fileManifest.length,\n excluded: world.exclusions,\n };\n}\n\n/** Extract a downloaded bundle into `dir` (paths confined, executable bit\n * kept; every name encoding the platform's writers emit — see ./tar.ts). */\nexport function extractBundle(bundle: Buffer, dir: string): number {\n return TarArchive.fromGzip(bundle).extractTo(dir);\n}\n\n/** What a checkout tracks after a pull: the branch that answered the ref, or\n * the tag it was taken from (detached). Older servers name neither: latest\n * and semver/hash pins land on main; any other ref was a branch. */\nexport function checkoutIdentity(\n ref: string,\n resolved: { branch?: string | null; tag?: string | null },\n): { branch?: string; tag?: string } {\n if (resolved.tag) return { tag: resolved.tag };\n if (resolved.branch) return { branch: resolved.branch };\n const pinned = ref === \"latest\" || /^\\d|^[0-9a-f]{8,}$/.test(ref);\n return { branch: pinned ? DEFAULT_BRANCH : ref };\n}\n\nexport async function pull(\n slugRef: string,\n target?: string,\n options: WorldsClientOptions = {},\n opts: { force?: boolean } = {},\n): Promise<{ slug: string; dir: string; versionId: string; files: number }> {\n const at = slugRef.indexOf(\"@\");\n const slug = at === -1 ? slugRef : slugRef.slice(0, at);\n const asked = at === -1 ? undefined : slugRef.slice(at + 1);\n const ref = asked ?? \"latest\";\n // Decided first: a refused target costs no request and touches no file.\n const landing = CheckoutTarget.resolve(slug, target, {\n cwd: process.cwd(),\n force: opts.force ?? false,\n state: localTreeState,\n });\n\n const details = await apiRequest<{\n versionId: string;\n contentHash: string;\n semanticVersion?: string | null;\n branch?: string | null;\n tag?: string | null;\n downloadUrl?: string;\n bundleSha256?: string;\n }>(options, \"POST\", \"/api/public/benchmark-containers/resolve-version\", {\n slug,\n ...(asked ? { ref: asked } : {}),\n });\n if (!details.downloadUrl) {\n throw new Error(`${slug}@${ref} resolved but has no uploaded bundle`);\n }\n\n const resp = await fetch(details.downloadUrl);\n if (!resp.ok) throw new Error(`bundle download -> ${resp.status}`);\n const bundle = Buffer.from(await resp.arrayBuffer());\n if (details.bundleSha256 && sha256b64(bundle) !== details.bundleSha256) {\n throw new Error(\n `bundle integrity check failed for ${slug}@${ref}: downloaded sha256 != recorded bundleSha256`,\n );\n }\n\n const dir = landing.dir;\n fs.mkdirSync(dir, { recursive: true });\n landing.clear();\n const files = extractBundle(bundle, dir);\n writeLocalMeta(dir, {\n slug,\n ref,\n ...checkoutIdentity(ref, details),\n versionId: details.versionId,\n contentHash: details.contentHash,\n semanticVersion: details.semanticVersion ?? undefined,\n baseFiles: snapshotTreeHashes(dir),\n });\n return { slug, dir, versionId: details.versionId, files };\n}\n\nexport async function propose(\n dir: string,\n opts: {\n title: string;\n reason: string;\n targetBranch?: string;\n options?: WorldsClientOptions;\n },\n): Promise<{ proposalId: string }> {\n const meta = readLocalMeta(dir);\n if (!meta?.slug || !meta.baseFiles) {\n throw new Error(\n \"This dir has no pull/push base — run pull first, then edit, then propose.\",\n );\n }\n const state = localTreeState(dir);\n if (state.clean)\n throw new Error(\"Nothing to propose — the tree matches its base.\");\n const changes = state.dirty.map((relPath) => {\n const abs = path.join(dir, relPath);\n if (!fs.existsSync(abs))\n return { path: relPath, action: \"delete\" as const };\n return {\n path: relPath,\n action: \"write\" as const,\n newContent: fs.readFileSync(abs, \"utf-8\"),\n };\n });\n const res = await apiRequest<{ proposalId: string }>(\n opts.options ?? {},\n \"POST\",\n \"/api/public/benchmark-containers/proposals\",\n {\n slug: meta.slug,\n title: opts.title,\n changeReason: opts.reason,\n baseVersionId: meta.versionId,\n ...(opts.targetBranch ? { targetBranch: opts.targetBranch } : {}),\n changes,\n },\n );\n return res;\n}\n\nexport async function createRef(\n slug: string,\n name: string,\n kind: \"branch\" | \"tag\",\n versionId?: string,\n options: WorldsClientOptions = {},\n): Promise<{ name: string; kind: string; versionId: string }> {\n return apiRequest(options, \"POST\", \"/api/public/benchmark-containers/refs\", {\n slug,\n name,\n kind,\n ...(versionId ? { versionId } : {}),\n });\n}\n","/**\n * PR validation: push the checkout's world source, run it, gate on the graded\n * result — one composed call, because CI should not have to re-derive the\n * choreography from primitives.\n *\n * The differentiating property, stated so it stays true: validation runs the\n * PULL REQUEST'S OWN world source. The push files the checkout as a version on\n * the PR's branch (content-hash dedup makes re-runs cheap), the dispatch pins\n * that version, and the platform resolves the branch back to its open PR — so\n * the run page names the PR and the PR comment names the run. Nothing here\n * validates a standing deployment while pretending to validate the change.\n */\n\nimport {\n apiRequest,\n detectProvenance,\n listRunConfigs,\n waitForRun,\n type RunReport,\n type WorldsClientOptions,\n} from \"./index\";\nimport { DEFAULT_BRANCH, push, pushSlug } from \"./hub\";\n\nexport type ValidatedRun = {\n model: string;\n runId: string;\n report: RunReport | null;\n /** Why this run fails the gate, or null when it passes. */\n failure: string | null;\n};\n\nexport type ValidateReport = {\n ok: boolean;\n slug: string;\n branch: string;\n versionId: string;\n contentHash: string;\n runConfig: { id: string; name: string };\n runs: ValidatedRun[];\n /** A PR-comment-ready summary of the whole validation. */\n markdown: string;\n};\n\nfunction fmtScore(score: number | null): string {\n return score === null ? \"no score\" : score.toFixed(3);\n}\n\nfunction buildMarkdown(\n report: Omit<ValidateReport, \"markdown\">,\n minScore: number | null,\n source?: { repoUrl?: string; commit?: string },\n): string {\n const lines: string[] = [];\n lines.push(\n `### World validation ${report.ok ? \"passed\" : \"failed\"} — \\`${report.slug}@${report.branch}\\``,\n );\n lines.push(\"\");\n 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 if (taskRows.length > 0) {\n const fold = taskRows.length > 12;\n lines.push(\"\");\n if (fold) {\n lines.push(\n `<details><summary>Per-scenario rewards (${taskRows.length})</summary>`,\n );\n lines.push(\"\");\n } else {\n lines.push(`**Scenarios (${taskRows.length})**`);\n lines.push(\"\");\n }\n lines.push(\"| Scenario | Model | Reward |\");\n lines.push(\"| --- | --- | ---: |\");\n for (const row of taskRows) {\n lines.push(\n `| ${row.task} | \\`${row.model}\\` | ${row.reward === null ? \"no score\" : row.reward.toFixed(2)} |`,\n );\n }\n if (fold) {\n lines.push(\"\");\n lines.push(\"</details>\");\n }\n }\n return lines.join(\"\\n\");\n}\n\n/**\n * Push `dir` on the current (or given) branch, dispatch the named run config\n * against the pushed version, wait for every run, and gate.\n *\n * The gate: every dispatch accepted, every run terminal COMPLETED, and — when\n * `minScore` is set — every run's score meets it. A run with NO score fails a\n * score gate rather than passing it: null is \"not scored\", never 0 and never\n * fine.\n */\nexport async function validateWorld(\n dir: string,\n opts: {\n slug?: string;\n runConfig: string;\n branch?: string;\n minScore?: number | null;\n timeoutMinutes?: number;\n onProgress?: (line: string) => void;\n options?: WorldsClientOptions;\n },\n): Promise<ValidateReport> {\n const options = opts.options ?? {};\n const progress = opts.onProgress ?? (() => {});\n const minScore = opts.minScore ?? null;\n\n const provenance = detectProvenance();\n const branch = opts.branch ?? provenance.branch;\n if (!branch)\n throw new Error(\n \"No branch to validate on: pass --branch or run inside a git checkout / GitHub Actions.\",\n );\n\n const slug = pushSlug(dir, opts.slug);\n progress(`pushing ${dir} as ${slug}@${branch}…`);\n // CI checkouts carry no local push meta, so a re-validation would 409\n // against the branch tip its own previous run created. Validation's\n // semantics are \"this branch's tip BECOMES the PR's source\": resolve the\n // current tip and push on top of it. A branch that does not exist yet\n // resolves to no base, which is a fresh branch — also correct.\n let tipVersionId: string | null = null;\n try {\n const tip = await apiRequest<{ versionId?: string }>(\n options,\n \"POST\",\n \"/api/public/benchmark-containers/resolve-version\",\n { slug, ...(branch === DEFAULT_BRANCH ? {} : { ref: branch }) },\n );\n tipVersionId = tip.versionId ?? null;\n } catch {\n tipVersionId = null;\n }\n const pushed = await push(dir, {\n slug,\n branch,\n baseVersionId: tipVersionId,\n message: `PR validation push (${provenance.commit?.slice(0, 12) ?? \"local\"})`,\n ...(provenance.actor?.name ? { author: provenance.actor.name } : {}),\n options,\n });\n progress(`pushed version ${pushed.versionId} (${pushed.contentHash.slice(0, 12)})`);\n\n const configs = await listRunConfigs(options);\n const runConfig =\n configs.find((c) => c.id === opts.runConfig) ??\n configs.find((c) => c.name === opts.runConfig);\n if (!runConfig) {\n const known = configs.map((c) => c.name).join(\", \") || \"(none)\";\n throw new Error(\n `Run config \"${opts.runConfig}\" not found in this project. Have: ${known}`,\n );\n }\n\n progress(`dispatching run config \"${runConfig.name}\" (${runConfig.models.join(\", \")})…`);\n const dispatched = await apiRequest<{\n versionLabel: string;\n runs: { model: string; runId: string; ok: boolean; error?: string }[];\n }>(options, \"POST\", \"/api/public/benchmark-containers/run-configs/dispatch\", {\n runConfigId: runConfig.id,\n versionId: pushed.versionId,\n ...provenance,\n });\n\n // The run's platform page. New deployments return it on the run report\n // (`url`); against an older deployment we build the same page from the\n // evaluation id, because a PR comment that cannot link the run defeats\n // the point of the comment.\n const host = (\n options.host ??\n process.env.GATEWAY_HOST ??\n \"https://withgateway.ai\"\n ).replace(/\\/+$/, \"\");\n let projectId: string | null = null;\n try {\n const projects = await apiRequest<{ data?: { id?: string }[] }>(\n options,\n \"GET\",\n \"/api/public/projects\",\n );\n projectId = projects.data?.[0]?.id ?? null;\n } catch {\n projectId = null;\n }\n const fallbackUrl = (report: RunReport): string | null => {\n if (report.url) return report.url;\n const evaluationId = report.evaluations[0]?.id;\n return projectId && evaluationId\n ? `${host}/project/${projectId}/environment/runs/${encodeURIComponent(evaluationId)}`\n : null;\n };\n\n const runs: ValidatedRun[] = [];\n for (const run of dispatched.runs) {\n if (!run.ok) {\n runs.push({\n model: run.model,\n runId: run.runId,\n report: null,\n failure: `dispatch failed: ${run.error ?? \"unknown error\"}`,\n });\n continue;\n }\n progress(`waiting on ${run.model} (run ${run.runId})…`);\n let report: RunReport | null = null;\n let failure: string | null = null;\n try {\n report = await waitForRun(run.runId, {\n timeoutMinutes: opts.timeoutMinutes ?? 45,\n options,\n onTick: (r) =>\n progress(\n `…${run.model}: ${r.status.toLowerCase()} (${r.shardsCompleted ?? 0}/${r.parallelism} shards)`,\n ),\n });\n report = { ...report, url: fallbackUrl(report) };\n if (report.status.toUpperCase() !== \"COMPLETED\") {\n failure = report.status;\n } else if (minScore !== null) {\n if (report.score === null) failure = \"completed without a score\";\n else if (report.score < minScore)\n failure = `score ${fmtScore(report.score)} < ${minScore}`;\n }\n } catch (error) {\n failure = error instanceof Error ? error.message : String(error);\n }\n runs.push({ model: run.model, runId: run.runId, report, failure });\n }\n\n const base = {\n ok: runs.length > 0 && runs.every((r) => r.failure === null),\n slug: pushed.slug,\n branch,\n versionId: pushed.versionId,\n contentHash: pushed.contentHash,\n runConfig: { id: runConfig.id, name: runConfig.name },\n runs,\n };\n return {\n ...base,\n markdown: buildMarkdown(base, minScore, {\n repoUrl: provenance.repoUrl,\n commit: provenance.commit,\n }),\n };\n}\n","import { createHash, randomUUID } from \"node:crypto\";\n\nimport { ApiError, apiRequest, type WorldsClientOptions } from \"./index\";\nimport type { PlatformMethod } from \"./transport\";\n\n/**\n * The CLI sandbox: a server-side workspace opened on a READY version of a\n * world (`/workspace/env` in the console agent's sandbox) — or, with\n * `{ new, from }`, on a world that does not exist yet, seeded from the\n * `schema init` scaffold or a shipped template and created by its first\n * commit — edited and run there, and committed straight into the version\n * service; the source never lands on the caller's disk. `importData` is the\n * data door beside `commit`: a rows file in the sandbox tree into the platform\n * world's data ledger, read out by the platform (no credential enters the\n * sandbox, nothing passes through this machine). One client under\n * both `gateway worlds sandbox …` and `gateway bench sandbox …`; the\n * Python twin is `gatewaysdk.benchmark_hub.sandbox.WorldSandboxClient`.\n */\n\n/** Mirrors `SandboxSummaryResponse` (web/features/public-api/types/world-sandboxes.ts). */\nexport type SandboxSummary = {\n sandboxId: string;\n slug: string;\n /** null while a new-world sandbox awaits its first commit. */\n containerId: string | null;\n /** The version the next commit is validated against; advances on commit. null before the first commit of a new world. */\n baseVersionId: string | null;\n /** Set on a new-world sandbox until its first commit creates the world. */\n pendingSlug: string | null;\n status: \"open\" | \"closed\";\n lastCommitVersionId: string | null;\n pendingBatchId?: string | null;\n createdAt: string;\n};\n\nexport type SandboxOpened = SandboxSummary & {\n /** null for a new-world sandbox (no base). */\n baseContentHash: string | null;\n branch: string;\n dataSnapshotId: string | null;\n fileCount: number;\n workdir: string;\n /** The `gateway` CLI `exec` finds on PATH (the platform's version, staged runtime digest); null when the image cannot host it — `warnings` says why. */\n cli: { version: string; digest: string } | null;\n warnings: string[];\n};\n\nexport type SandboxExecResult = {\n exitCode: number;\n stdout: string;\n stderr: string;\n timedOut: boolean;\n truncated: boolean;\n durationMs: number;\n /** Why `gateway`/`sqlite3` were not on PATH for this command; empty when the runtime is staged. */\n warnings: string[];\n};\n\n/** A command still running after the request's `waitMs` (202); wait on it with `execId`. */\nexport type SandboxExecRunning = { state: \"running\"; execId: string; warnings: string[] };\n\nexport type SandboxChanges = {\n added: string[];\n modified: string[];\n removed: string[];\n};\n\nexport type SandboxCheckResult = {\n ok: boolean;\n contentHash: string | null;\n noChange: boolean;\n fileCount: number;\n changes: SandboxChanges;\n /** Working-tree paths left out of the version: `.gatewayignore`, default scratch, credential-shaped files, links. */\n ignored: string[];\n /** Why a listed path was held back (credential-shaped, a link), a data migration the commit will run, or a rehash; paths only. */\n warnings: string[];\n error: string | null;\n baseMoved?: { baseVersionId: string; tipVersionId: string } | null;\n pendingBatch?: { batchId: string; kind: string; state: string } | null;\n};\n\nexport type SandboxCommitResult = {\n /** The world the commit landed on. */\n slug: string;\n versionId: string;\n contentHash: string;\n branch: string;\n deduped: boolean;\n noChange: boolean;\n changes: SandboxChanges;\n ignored: string[];\n /** The same warnings `check` gives, so a commit never hides what it left out. */\n warnings: string[];\n /** The API key's edit session the commit joined; `gateway worlds edit close <slug>` moves main. */\n editSessionId?: string;\n rebasedOnto?: string | null;\n batchId?: string;\n};\n\nexport type SandboxCommitPending = {\n slug: string;\n batchId: string;\n state: string;\n migration: { fromSnapshotId: string; adds: string[] };\n changes: SandboxChanges;\n ignored: string[];\n warnings: string[];\n rebasedOnto: string | null;\n hint: string;\n};\n\nexport const isSandboxCommitPending = (\n answer: SandboxCommitResult | SandboxCommitPending,\n): answer is SandboxCommitPending => !(\"versionId\" in answer);\n\n/** Mirrors `PostSandboxImportBody`. */\nexport type SandboxImportInput = {\n /** A .json/.jsonl/.ndjson/.csv/.tsv (optionally .gz) relative to the world root. */\n path: string;\n entity?: string;\n /** One character (a real tab for TSV); defaults by extension. */\n delimiter?: string;\n mode?: \"append\" | \"replace\";\n merge?: \"upsert\" | \"fill\";\n redact?: \"off\" | \"apply\" | \"refuse\";\n atomic?: boolean;\n dryRun?: boolean;\n message?: string;\n};\n\n/** Mirrors `PostSandboxImportResponse` (201). */\nexport type SandboxImportResult = {\n containerId: string;\n slug: string;\n batchId: string | null;\n state: string;\n versionId: string | null;\n baseVersionId: string;\n contentHash: string | null;\n deduped: boolean;\n entityCounts: Record<string, number>;\n kind: string | null;\n dryRun: boolean;\n refusalCount: number;\n rowCount: number;\n chunkCount: number;\n /** `sandbox:<id>/<path>`. */\n source: string;\n warnings?: string[];\n};\n\n/** Mirrors `PostSandboxImportPendingResponse` (202): poll `worlds data batches`. */\nexport type SandboxImportPending = {\n batchId: string;\n state: string;\n rowCount: number;\n chunkCount: number;\n source: string;\n warnings?: string[];\n};\n\nexport const isSandboxImportPending = (\n answer: SandboxImportResult | SandboxImportPending,\n): answer is SandboxImportPending => !(\"versionId\" in answer);\n\n/** Mirrors `PostSandboxOpenBody`: an existing world at a ref, or a new world seeded from a template. */\nexport type SandboxOpenExisting = { slug: string; ref?: string };\nexport type SandboxOpenNew = { new: string; from: string };\nexport type SandboxOpenTarget = SandboxOpenExisting | SandboxOpenNew;\n\n/** `slug` or `slug@ref` → the open body; a bare slug opens the latest READY version. */\nexport function parseSlugRef(slugRef: string): SandboxOpenExisting {\n const at = slugRef.indexOf(\"@\");\n if (at === -1) return { slug: slugRef };\n return { slug: slugRef.slice(0, at), ref: slugRef.slice(at + 1) };\n}\n\nconst sid = encodeURIComponent;\n\nconst SANDBOXES = \"/api/public/benchmark-containers/sandboxes\";\n\n/** How long one sandbox request waits for its answer: under the 300 s Node's fetch waits before it cuts a request, so\n * this budget, not fetch, ends a slow one. The Python twin and both MCP proxies wait the same\n * (`conformance/world-sandbox-limits.json`). */\nexport const SANDBOX_REQUEST_TIMEOUT_MS = 290_000;\n\n/** The most one write request carries (`WORLD_SANDBOX_WRITE_CHUNK_BYTES`); a larger file goes up in parts of this size. */\nexport const SANDBOX_WRITE_CHUNK_BYTES = 4 * 1024 * 1024;\n\n/** The largest file a sandbox write lands (`WORLD_SANDBOX_FILE_MAX_BYTES`). */\nexport const SANDBOX_FILE_MAX_BYTES = 256 * 1024 * 1024;\n\n/** What writing a directory never uploads: a checkout's metadata and the scratch the platform never versions\n * (`conformance/world-ignore-defaults.json`). A name with a trailing slash is a directory at any depth, any\n * other a file name glob. */\nexport const SANDBOX_WRITE_SKIPPED: readonly string[] = [\n \".git/\",\n \".gateway/\",\n \"scratch/\",\n \".scratch/\",\n \"__pycache__/\",\n \"*.pyc\",\n \".pytest_cache/\",\n \".mypy_cache/\",\n \".ruff_cache/\",\n \"node_modules/\",\n \".venv/\",\n \"venv/\",\n \".DS_Store\",\n \"*.swp\",\n];\n\n/** Which directory entries writing a directory leaves out, by `SANDBOX_WRITE_SKIPPED`. */\nexport class WriteTreeFilter {\n private readonly directories = new Set(\n SANDBOX_WRITE_SKIPPED.filter((pattern) => pattern.endsWith(\"/\")).map((pattern) => pattern.slice(0, -1)),\n );\n private readonly files = SANDBOX_WRITE_SKIPPED.filter((pattern) => !pattern.endsWith(\"/\")).map(nameGlob);\n\n skipsDirectory(name: string): boolean {\n return this.directories.has(name);\n }\n\n skipsFile(name: string): boolean {\n return this.files.some((glob) => glob.test(name));\n }\n}\n\nfunction nameGlob(pattern: string): RegExp {\n const literal = (part: string) => part.replace(/[.+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n return new RegExp(`^${pattern.split(\"*\").map(literal).join(\".*\")}$`);\n}\n\ntype WriteAnswer = { path: string; size: number } | { path: string; received: number };\n\n/** How long one exec request waits on its command before the platform answers `running`; a longer command is\n * waited on again by `execId`, so no request outlives the edge in front of the platform. */\nexport const SANDBOX_EXEC_WAIT_MS = 40_000;\n\n/** The longest timeout an exec may ask for (`WORLD_SANDBOX_EXEC_TIMEOUT_MAX_MS`); a longer one is refused, never clamped. */\nexport const SANDBOX_EXEC_TIMEOUT_MAX_S = 600;\n\n/** How long past its timeout a command may go without a result before the client stops waiting on it. */\nexport const SANDBOX_EXEC_REPORT_MARGIN_MS = 35_000;\n\n/** How many times a start the platform deferred (`sandbox_exec_deferred`: nothing ran) is sent. */\nexport const SANDBOX_EXEC_START_ATTEMPTS = 3;\n\n/** Mirrors `PostSandboxCommitBody`: `rebase` replays the sandbox's edits onto the branch head when the base moved. */\nexport type SandboxCommitInput = {\n message: string;\n branch?: string;\n rebase?: boolean;\n};\n\n/** One path a rebase refused, as the 409 body's `conflicts[]` names it. */\nexport type RebaseConflictPath = { path: string; reason: string };\n\n/** A 409 from `commit --rebase`: the paths both sides changed and why each was refused. Null for any other failure. */\nexport function rebaseConflicts(error: unknown): RebaseConflictPath[] | null {\n if (!(error instanceof ApiError) || error.status !== 409) return null;\n let body: unknown;\n try {\n body = JSON.parse(error.text);\n } catch {\n return null;\n }\n const conflicts = (body as { conflicts?: unknown } | null)?.conflicts;\n if (!Array.isArray(conflicts)) return null;\n return conflicts\n .filter(isConflictPath)\n .map(({ path, reason }) => ({ path, reason }));\n}\n\nfunction isConflictPath(value: unknown): value is RebaseConflictPath {\n const entry = value as Partial<RebaseConflictPath> | null;\n return typeof entry?.path === \"string\" && typeof entry.reason === \"string\";\n}\n\n/** A 409 `sandbox_uncommitted` from `close`: the paths a commit would keep. Null for any other failure. */\nexport function uncommittedPaths(error: unknown): string[] | null {\n if (\n !(error instanceof ApiError) ||\n error.status !== 409 ||\n error.code !== \"sandbox_uncommitted\"\n )\n return null;\n let body: unknown;\n try {\n body = JSON.parse(error.text);\n } catch {\n return null;\n }\n const uncommitted = (body as { uncommitted?: unknown } | null)?.uncommitted;\n if (!Array.isArray(uncommitted)) return null;\n return uncommitted.filter((p): p is string => typeof p === \"string\");\n}\n\nconst carried = new WeakMap<object, string[]>();\n\n/**\n * The warnings an exec had collected before it failed (a deferral's, a running answer's) and the failing answer's\n * own, which its message holds only up to the detail's cut: no later call reports them. Those the message already\n * shows whole are left out, so each is printed once.\n */\nexport function carriedWarnings(error: unknown): string[] {\n const kept = typeof error === \"object\" && error !== null ? (carried.get(error) ?? []) : [];\n const shown = error instanceof Error ? error.message : \"\";\n return unique([...kept, ...bodyWarnings(error)]).filter((warning) => !shown.includes(warning));\n}\n\nfunction carrying(error: unknown, warnings: string[]): unknown {\n if (warnings.length > 0 && typeof error === \"object\" && error !== null)\n carried.set(error, unique([...(carried.get(error) ?? []), ...warnings]));\n return error;\n}\n\nfunction unique(warnings: string[]): string[] {\n return [...new Set(warnings)];\n}\n\nfunction bodyWarnings(error: unknown): string[] {\n if (!(error instanceof ApiError)) return [];\n let body: unknown;\n try {\n body = JSON.parse(error.text);\n } catch {\n return [];\n }\n const warnings = (body as { warnings?: unknown } | null)?.warnings;\n if (!Array.isArray(warnings)) return [];\n return warnings.filter((w): w is string => typeof w === \"string\");\n}\n\nfunction deferredWarnings(error: unknown): string[] | null {\n if (!(error instanceof ApiError) || error.status !== 409 || error.code !== \"sandbox_exec_deferred\") return null;\n return bodyWarnings(error);\n}\n\n/** A 400 `rows_refused` from `import`: the summary, every refusal counted, the first records and the full report. */\nexport type RowsRefusal = {\n message: string;\n batchId: string;\n refusalCount: number;\n refusals: Record<string, unknown>[];\n reportUrl: string | null;\n};\n\n/** The refusal a sandbox import answered, or null for any other failure. */\nexport function rowsRefusal(error: unknown): RowsRefusal | null {\n if (!(error instanceof ApiError) || error.status !== 400 || error.code !== \"rows_refused\") return null;\n let body: Record<string, unknown>;\n try {\n body = JSON.parse(error.text) as Record<string, unknown>;\n } catch {\n return null;\n }\n const { message, batchId, refusalCount, refusals, reportUrl } = body;\n if (typeof batchId !== \"string\" || typeof refusalCount !== \"number\" || !Array.isArray(refusals)) return null;\n return {\n message: typeof message === \"string\" ? message : \"\",\n batchId,\n refusalCount,\n refusals: refusals.filter((r): r is Record<string, unknown> => typeof r === \"object\" && r !== null),\n reportUrl: typeof reportUrl === \"string\" ? reportUrl : null,\n };\n}\n\n/** `sandbox list` narrows: status, world, count (newest first). */\nexport type SandboxListFilter = {\n status?: \"open\" | \"closed\";\n slug?: string;\n limit?: number;\n};\n\nfunction listQuery(filter: SandboxListFilter): string {\n const params = new URLSearchParams();\n if (filter.status) params.set(\"status\", filter.status);\n if (filter.slug) params.set(\"slug\", filter.slug);\n if (filter.limit !== undefined) params.set(\"limit\", String(filter.limit));\n const qs = params.toString();\n return qs ? `?${qs}` : \"\";\n}\n\nexport class WorldSandboxClient {\n constructor(private readonly options: WorldsClientOptions = {}) {}\n\n private request<T>(\n method: PlatformMethod,\n path: string,\n body?: unknown,\n ): Promise<T> {\n return apiRequest<T>(this.options, method, path, body, {\n timeoutMs: SANDBOX_REQUEST_TIMEOUT_MS,\n });\n }\n\n /**\n * `{ slug, ref? }` opens a READY version; `{ new, from }` opens a sandbox on\n * a world that does not exist yet (409 `world_exists` if the slug is taken,\n * 400 naming the shipped templates if `from` is unknown). Its first commit\n * creates the world on `main`.\n */\n open(target: SandboxOpenTarget): Promise<SandboxOpened> {\n return this.request(\"POST\", `${SANDBOXES}`, target);\n }\n\n status(sandboxId: string): Promise<SandboxSummary> {\n return this.request(\"GET\", `${SANDBOXES}/${sid(sandboxId)}`);\n }\n\n /** The project's sandboxes, newest first — how an agent finds one it left open. */\n async list(filter: SandboxListFilter = {}): Promise<SandboxSummary[]> {\n const res = await this.request<{ sandboxes: SandboxSummary[] }>(\n \"GET\",\n `${SANDBOXES}${listQuery(filter)}`,\n );\n return res.sandboxes;\n }\n\n async read(\n sandboxId: string,\n filePath: string,\n ): Promise<{ path: string; size: number; bytes: Buffer }> {\n const res = await this.request<{\n path: string;\n size: number;\n contentBase64: string;\n }>(\n \"GET\",\n `${SANDBOXES}/${sid(sandboxId)}/file?path=${encodeURIComponent(filePath)}`,\n );\n return {\n path: res.path,\n size: res.size,\n bytes: Buffer.from(res.contentBase64, \"base64\"),\n };\n }\n\n /** A file past one chunk goes up in parts under one upload id; the platform lands it whole once the last part's\n * size and SHA-256 check out. */\n async write(sandboxId: string, filePath: string, bytes: Buffer): Promise<{ path: string; size: number }> {\n if (bytes.length <= SANDBOX_WRITE_CHUNK_BYTES)\n return this.putFile(sandboxId, { path: filePath, contentBase64: bytes.toString(\"base64\") }) as Promise<{\n path: string;\n size: number;\n }>;\n const whole = { upload: randomUUID(), size: bytes.length, sha256: createHash(\"sha256\").update(bytes).digest(\"hex\") };\n let answer: WriteAnswer = { path: filePath, received: 0 };\n for (let offset = 0; offset < bytes.length; offset += SANDBOX_WRITE_CHUNK_BYTES) {\n const part = bytes.subarray(offset, offset + SANDBOX_WRITE_CHUNK_BYTES);\n answer = await this.putFile(sandboxId, {\n path: filePath,\n contentBase64: part.toString(\"base64\"),\n ...whole,\n offset,\n last: offset + part.length === bytes.length,\n });\n }\n return answer as { path: string; size: number };\n }\n\n private putFile(sandboxId: string, body: object): Promise<WriteAnswer> {\n return this.request(\"PUT\", `${SANDBOXES}/${sid(sandboxId)}/file`, body);\n }\n\n /** Runs as a job on the platform: a command that outlasts one request is waited on again until its result. */\n async exec(\n sandboxId: string,\n input: { command: string; cwd?: string; timeoutMs?: number },\n ): Promise<SandboxExecResult> {\n const budgetMs = (input.timeoutMs ?? SANDBOX_EXEC_TIMEOUT_MAX_S * 1000) + SANDBOX_EXEC_REPORT_MARGIN_MS;\n let answer = await this.startExec(sandboxId, { ...input, waitMs: SANDBOX_EXEC_WAIT_MS });\n const deadline = Date.now() + budgetMs;\n const warnings = [...(answer.warnings ?? [])];\n try {\n while (\"state\" in answer) {\n if (Date.now() >= deadline)\n throw new Error(\n `exec ${answer.execId} in sandbox ${sandboxId} has not reported back within ${budgetMs / 1000} s, past its timeout: ` +\n \"the sandbox may have restarted. Check the sandbox's status, then run the command again.\",\n );\n answer = await this.execStep(sandboxId, { execId: answer.execId, waitMs: SANDBOX_EXEC_WAIT_MS });\n warnings.push(...(answer.warnings ?? []));\n }\n } catch (error) {\n throw carrying(error, warnings);\n }\n return { ...answer, warnings };\n }\n\n // A deferred start ran nothing (the platform was still getting the sandbox ready), so starting again is safe. What\n // getting ready found rides on the deferral alone (no later call reports it), so it is kept for the answer, or for\n // the error when a later attempt fails.\n private async startExec(sandboxId: string, body: object): Promise<SandboxExecResult | SandboxExecRunning> {\n const kept: string[] = [];\n for (let attempt = 1; ; attempt += 1) {\n try {\n const answer = await this.execStep(sandboxId, body);\n return { ...answer, warnings: unique([...kept, ...(answer.warnings ?? [])]) };\n } catch (error) {\n const warnings = deferredWarnings(error);\n if (warnings === null || attempt === SANDBOX_EXEC_START_ATTEMPTS) throw carrying(error, kept);\n kept.push(...warnings);\n }\n }\n }\n\n private execStep(sandboxId: string, body: object): Promise<SandboxExecResult | SandboxExecRunning> {\n return this.request(\"POST\", `${SANDBOXES}/${sid(sandboxId)}/exec`, body);\n }\n\n check(sandboxId: string): Promise<SandboxCheckResult> {\n return this.request(\"POST\", `${SANDBOXES}/${sid(sandboxId)}/check`, {});\n }\n\n /** With `rebase`, a moved base is replayed onto; a 409 then names the conflicting paths (`rebaseConflicts`). */\n commit(\n sandboxId: string,\n input: SandboxCommitInput,\n ): Promise<SandboxCommitResult | SandboxCommitPending> {\n const { rebase, ...rest } = input;\n return this.request(\n \"POST\",\n `${SANDBOXES}/${sid(sandboxId)}/commit`,\n rebase ? { ...rest, rebase: true } : rest,\n );\n }\n\n /**\n * A rows file already in the sandbox tree into the PLATFORM world the\n * sandbox was opened on (201 with the version, 202 with the batch to poll,\n * 400 naming a refused row). Not `commit`: a commit versions the source\n * tree and never carries data.\n */\n importData(\n sandboxId: string,\n input: SandboxImportInput,\n ): Promise<SandboxImportResult | SandboxImportPending> {\n return this.request(\"POST\", `${SANDBOXES}/${sid(sandboxId)}/import`, input);\n }\n\n /** Uncommitted work is a 409 (`uncommittedPaths`) unless `force` discards it. */\n close(\n sandboxId: string,\n opts: { force?: boolean } = {},\n ): Promise<SandboxSummary> {\n return this.request(\n \"DELETE\",\n `${SANDBOXES}/${sid(sandboxId)}`,\n opts.force ? { force: true } : undefined,\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\";\nimport { parseSlugRef } from \"./sandbox\";\n\nexport type WorldField = {\n name: string;\n type: string | null;\n required: boolean;\n /** How the store holds it; null means in the clear (queryable by plaintext as given). */\n redaction: Redaction | null;\n /** The values the schema allows; absent when it lists none. */\n enum?: unknown[];\n};\n\nexport type WorldRelationship = {\n fields: string[];\n target: string;\n on_delete?: string;\n};\n\nexport type WorldEntityMapping = {\n localEntity: string;\n localField: string;\n depEntity: string;\n depField: string;\n /** A closed set, applied left to right before each world's own redaction. */\n transform: string[];\n};\n\nexport type WorldDependency = {\n alias: string;\n dependsOn: { slug: string | null; versionId: string };\n task: string | null;\n tools: string[];\n entities: WorldEntityMapping[];\n};\n\nexport type WorldEntity = {\n name: string;\n primaryKey: string[];\n unique: string[][];\n relationships: WorldRelationship[];\n /** Rows in the head version; null when the platform does not count this kind. */\n rowCount: number | null;\n fields: WorldField[];\n};\n\nexport type WorldDescription = {\n slug: string;\n name: string;\n description: string | null;\n kind: string;\n version: { id: string; contentHash: string; semanticVersion: string | null };\n url: string;\n hostedUrl: string | null;\n tools: { name: string; signature: string; doc: string | null }[];\n taskCount: number;\n links: { tasks: string; sessions: string };\n /** World-to-world links from `[dependencies]`, resolved at commit, with the\n * entity mappings `--across` follows. */\n dependencies?: WorldDependency[];\n entities: WorldEntity[];\n redact: RedactPolicy | null;\n};\n\n/** The world at `slug@ref`, described — `ref` is the one grammar shared with\n * pull/checkout/sandbox (`latest` | branch | tag | semver | version id | hash\n * prefix); a bare slug describes the head of `main`. An unknown ref is the\n * route's 404, never the head. */\nexport async function describeWorld(\n slugRef: string,\n options: WorldsClientOptions = {},\n): Promise<WorldDescription> {\n const { slug, ref } = parseSlugRef(slugRef);\n const query = ref === undefined ? \"\" : `?ref=${encodeURIComponent(ref)}`;\n return apiRequest<WorldDescription>(\n options,\n \"GET\",\n `/api/public/worlds/${encodeURIComponent(slug)}${query}`,\n );\n}\n","/**\n * JSON as the Python CLI sees it, so both CLIs write the same bytes.\n *\n * `JSON.parse` + `JSON.stringify` are not enough for parity with\n * `json.loads` + `json.dumps(separators=(\",\", \":\"), ensure_ascii=False)`:\n * JavaScript loses `1.0` vs `1` (Python keeps the float), rounds integers past\n * 2^53, moves integer-like keys to the front of an object, and spells\n * exponents differently (`1e-7` vs `1e-07`). Here a number keeps its source\n * text and its Python type, an object is a Map (insertion order, always), and\n * `dumps` renders exactly what CPython renders.\n */\n\nexport class JsonNumber {\n /** The lexeme as it appeared, e.g. \"1.0\", \"-0\", \"1e21\". */\n constructor(readonly text: string) {}\n /** A float in Python's eyes: a fraction, an exponent, or a non-finite literal. */\n get isFloat(): boolean {\n return /[.eE]/.test(this.text) || /[nN]/.test(this.text);\n }\n get value(): number {\n return Number(this.text);\n }\n}\n\nexport type JsonObject = Map<string, JsonValue>;\nexport type JsonValue = null | boolean | string | JsonNumber | JsonValue[] | JsonObject;\n\nexport class JsonSyntaxError extends Error {}\n\nexport const isObject = (value: JsonValue | undefined): value is JsonObject => value instanceof Map;\n\n// ------------------------------------------------------------------ parsing\n\n/** Parse one JSON text (a line, a row, a document) into the model above.\n * Accepts what `json.loads` accepts, including NaN/Infinity literals. */\nexport function parseJson(text: string): JsonValue {\n const p = new Parser(text);\n p.skipWs();\n const value = p.value();\n p.skipWs();\n if (p.i < text.length) throw new JsonSyntaxError(`Extra data at ${p.i}`);\n return value;\n}\n\nclass Parser {\n i = 0;\n constructor(readonly s: string) {}\n\n skipWs(): void {\n const s = this.s;\n while (this.i < s.length) {\n const c = s.charCodeAt(this.i);\n if (c === 0x20 || c === 0x0a || c === 0x0d || c === 0x09) this.i++;\n else break;\n }\n }\n\n fail(what: string): never {\n throw new JsonSyntaxError(`${what} at ${this.i}`);\n }\n\n value(): JsonValue {\n const s = this.s;\n if (this.i >= s.length) this.fail(\"Expecting value\");\n const c = s[this.i]!;\n if (c === \"{\") return this.object();\n if (c === \"[\") return this.array();\n if (c === '\"') return this.string();\n if (c === \"t\") return this.literal(\"true\", true);\n if (c === \"f\") return this.literal(\"false\", false);\n if (c === \"n\") return this.literal(\"null\", null);\n if (c === \"N\") return this.literal(\"NaN\", new JsonNumber(\"NaN\"));\n if (c === \"I\") return this.literal(\"Infinity\", new JsonNumber(\"Infinity\"));\n return this.number();\n }\n\n literal<T extends JsonValue>(word: string, value: T): T {\n if (!this.s.startsWith(word, this.i)) this.fail(\"Expecting value\");\n this.i += word.length;\n return value;\n }\n\n number(): JsonNumber {\n const s = this.s;\n const start = this.i;\n if (s[this.i] === \"-\") {\n this.i++;\n if (s.startsWith(\"Infinity\", this.i)) {\n this.i += 8;\n return new JsonNumber(\"-Infinity\");\n }\n }\n const intStart = this.i;\n if (s[this.i] === \"0\") this.i++;\n else {\n while (this.i < s.length && isDigit(s.charCodeAt(this.i))) this.i++;\n if (this.i === intStart) this.fail(\"Expecting value\");\n }\n if (s[this.i] === \".\") {\n this.i++;\n const fracStart = this.i;\n while (this.i < s.length && isDigit(s.charCodeAt(this.i))) this.i++;\n if (this.i === fracStart) this.fail(\"Invalid number\");\n }\n if (s[this.i] === \"e\" || s[this.i] === \"E\") {\n this.i++;\n if (s[this.i] === \"+\" || s[this.i] === \"-\") this.i++;\n const expStart = this.i;\n while (this.i < s.length && isDigit(s.charCodeAt(this.i))) this.i++;\n if (this.i === expStart) this.fail(\"Invalid number\");\n }\n return new JsonNumber(s.slice(start, this.i));\n }\n\n string(): string {\n const s = this.s;\n this.i++; // opening quote\n let out = \"\";\n let runStart = this.i;\n for (;;) {\n if (this.i >= s.length) this.fail(\"Unterminated string\");\n const c = s.charCodeAt(this.i);\n if (c === 0x22) {\n out += s.slice(runStart, this.i);\n this.i++;\n return out;\n }\n if (c < 0x20) this.fail(\"Invalid control character\");\n if (c !== 0x5c) {\n this.i++;\n continue;\n }\n out += s.slice(runStart, this.i);\n this.i++;\n const e = s[this.i];\n switch (e) {\n case '\"':\n case \"\\\\\":\n case \"/\":\n out += e;\n break;\n case \"b\":\n out += \"\\b\";\n break;\n case \"f\":\n out += \"\\f\";\n break;\n case \"n\":\n out += \"\\n\";\n break;\n case \"r\":\n out += \"\\r\";\n break;\n case \"t\":\n out += \"\\t\";\n break;\n case \"u\": {\n const hex = s.slice(this.i + 1, this.i + 5);\n if (!/^[0-9a-fA-F]{4}$/.test(hex)) this.fail(\"Invalid \\\\u escape\");\n out += String.fromCharCode(parseInt(hex, 16));\n this.i += 4;\n break;\n }\n default:\n this.fail(\"Invalid escape\");\n }\n this.i++;\n runStart = this.i;\n }\n }\n\n array(): JsonValue[] {\n this.i++;\n const out: JsonValue[] = [];\n this.skipWs();\n if (this.s[this.i] === \"]\") {\n this.i++;\n return out;\n }\n for (;;) {\n this.skipWs();\n out.push(this.value());\n this.skipWs();\n const c = this.s[this.i];\n if (c === \",\") {\n this.i++;\n continue;\n }\n if (c === \"]\") {\n this.i++;\n return out;\n }\n this.fail(\"Expecting ',' delimiter\");\n }\n }\n\n object(): JsonObject {\n this.i++;\n const out: JsonObject = new Map();\n this.skipWs();\n if (this.s[this.i] === \"}\") {\n this.i++;\n return out;\n }\n for (;;) {\n this.skipWs();\n if (this.s[this.i] !== '\"') this.fail(\"Expecting property name enclosed in double quotes\");\n const key = this.string();\n this.skipWs();\n if (this.s[this.i] !== \":\") this.fail(\"Expecting ':' delimiter\");\n this.i++;\n this.skipWs();\n out.set(key, this.value());\n this.skipWs();\n const c = this.s[this.i];\n if (c === \",\") {\n this.i++;\n continue;\n }\n if (c === \"}\") {\n this.i++;\n return out;\n }\n this.fail(\"Expecting ',' delimiter\");\n }\n }\n}\n\nconst isDigit = (c: number): boolean => c >= 0x30 && c <= 0x39;\n\n// ------------------------------------------------------------ serialising\n\n/** `json.dumps(value, separators=(\",\", \":\"), ensure_ascii=False)`, byte for byte. */\nexport function dumps(value: JsonValue): string {\n if (value === null) return \"null\";\n if (value === true) return \"true\";\n if (value === false) return \"false\";\n if (typeof value === \"string\") return JSON.stringify(value);\n if (value instanceof JsonNumber) return numberText(value);\n if (Array.isArray(value)) return \"[\" + value.map(dumps).join(\",\") + \"]\";\n const parts: string[] = [];\n for (const [key, item] of value) parts.push(JSON.stringify(key) + \":\" + dumps(item));\n return \"{\" + parts.join(\",\") + \"}\";\n}\n\n/** How `json.dumps` spells a parsed number: ints verbatim (`-0` becomes `0`),\n * floats through `float.__repr__`, non-finite as NaN/Infinity. */\nexport function numberText(n: JsonNumber): string {\n if (!n.isFloat) return /^-0+$/.test(n.text) ? \"0\" : n.text;\n const value = n.value;\n if (Number.isNaN(value)) return \"NaN\";\n if (value === Infinity) return \"Infinity\";\n if (value === -Infinity) return \"-Infinity\";\n return pyFloatRepr(value);\n}\n\n/** `str(value)` for the values the redaction digest sees: str, int, float, bool. */\nexport function pyStr(value: string | boolean | JsonNumber): string {\n if (typeof value === \"string\") return value;\n if (typeof value === \"boolean\") return value ? \"True\" : \"False\";\n if (!value.isFloat) return numberText(value);\n const v = value.value;\n if (Number.isNaN(v)) return \"nan\";\n if (v === Infinity) return \"inf\";\n if (v === -Infinity) return \"-inf\";\n return pyFloatRepr(v);\n}\n\n/**\n * CPython's `repr(float)`: the shortest digits that round-trip (which\n * JavaScript's `String(x)` also produces), laid out Python's way — a\n * trailing `.0` on integral values, scientific notation only below 1e-4 or\n * from 1e16, and exponents of at least two digits with a sign.\n */\nexport function pyFloatRepr(x: number): string {\n if (x === 0) return Object.is(x, -0) ? \"-0.0\" : \"0.0\";\n const sign = x < 0 ? \"-\" : \"\";\n const js = String(Math.abs(x));\n const [mantissa, exponentPart] = js.split(\"e\");\n let exponent = exponentPart ? Number(exponentPart) : 0;\n const [intPart, fracPart = \"\"] = mantissa!.split(\".\");\n let digits = intPart! + fracPart;\n // decpt: how many digits sit before the decimal point (may be <= 0 or > length).\n let decpt = intPart!.length + exponent;\n const leading = digits.match(/^0*/)![0].length;\n digits = digits.slice(leading);\n decpt -= leading;\n digits = digits.replace(/0+$/, \"\");\n if (digits === \"\") return sign + \"0.0\";\n const sci = decpt - 1;\n if (sci >= -4 && sci < 16) {\n if (decpt <= 0) return sign + \"0.\" + \"0\".repeat(-decpt) + digits;\n if (decpt >= digits.length) return sign + digits + \"0\".repeat(decpt - digits.length) + \".0\";\n return sign + digits.slice(0, decpt) + \".\" + digits.slice(decpt);\n }\n exponent = sci;\n const mag = String(Math.abs(exponent)).padStart(2, \"0\");\n return sign + digits[0] + (digits.length > 1 ? \".\" + digits.slice(1) : \"\") + \"e\" + (exponent < 0 ? \"-\" : \"+\") + mag;\n}\n\n/**\n * Python's `round(x, ndigits)` for the redaction policy: an int is returned\n * unchanged, a float is correctly rounded on its exact binary value with ties\n * to even (`round(0.125, 2) == 0.12`), then re-read as the nearest double.\n */\nexport function pyRound(n: JsonNumber, ndigits: number): JsonNumber {\n if (!n.isFloat) return n;\n const x = n.value;\n if (!Number.isFinite(x)) return n;\n const sign = x < 0 ? -1 : 1;\n const magnitude = Math.abs(x);\n // Every double at or above 2^53 is an integer already.\n if (magnitude >= 9007199254740992) return new JsonNumber(pyFloatRepr(x));\n const { m, k } = exactFraction(magnitude); // magnitude = m / 2^k, m odd (or zero)\n let rounded: number;\n if (k <= ndigits) rounded = magnitude; // exact at this precision\n else if (k !== ndigits + 1) rounded = Number(magnitude.toFixed(ndigits)); // no tie possible: correctly rounded\n else {\n // Exactly k = ndigits + 1 fractional digits, the last one a 5: a tie. Half to even.\n const scaled = m * 5n ** BigInt(k); // magnitude * 10^k, an integer\n let kept = scaled / 10n; // magnitude * 10^ndigits, truncated\n if (kept % 2n === 1n) kept += 1n;\n const text = kept.toString().padStart(ndigits + 1, \"0\");\n rounded = ndigits === 0 ? Number(text) : Number(text.slice(0, -ndigits) + \".\" + text.slice(-ndigits));\n }\n return new JsonNumber(pyFloatRepr(sign * rounded));\n}\n\n/** A finite non-negative double as m / 2^k with m odd (m = 0, k = 0 for zero). */\nfunction exactFraction(x: number): { m: bigint; k: number } {\n if (x === 0) return { m: 0n, k: 0 };\n const view = new DataView(new ArrayBuffer(8));\n view.setFloat64(0, x);\n const bits = view.getBigUint64(0);\n const exponent = Number((bits >> 52n) & 0x7ffn);\n let mantissa = bits & ((1n << 52n) - 1n);\n let e: number;\n if (exponent === 0) e = -1074;\n else {\n mantissa |= 1n << 52n;\n e = exponent - 1075;\n }\n while (mantissa !== 0n && (mantissa & 1n) === 0n) {\n mantissa >>= 1n;\n e += 1;\n }\n if (e >= 0) return { m: mantissa << BigInt(e), k: 0 };\n return { m: mantissa, k: -e };\n}\n","/**\n * Named plaintext transforms for cross-world entity mappings.\n *\n * A mapping between two worlds' fields is rarely a raw equality: SpyCloud\n * keeps `phone` as bare digits where a Torchlight client sends\n * `+1 (559) 779-1433`; one world keys people by `email`, another by\n * `email_username`. A transform normalises the plaintext on BOTH sides of a\n * mapping before `storedForms` salts it under each world's slug, so a\n * cross-world query is answerable from the plaintext alone, with no stored\n * join.\n *\n * The set is closed and named — no expressions, no user code — because any\n * client must reproduce a transform from the manifest by itself. This is the\n * TypeScript twin of the Python runtime's `environment/schema/transforms.py`;\n * the golden vectors in `__tests__/transforms.test.ts` and the Python\n * `tests/environment/test_schema_transforms.py` pin the two to each other,\n * byte for byte.\n *\n * Whitespace, for `trim` and `collapse_ws`, is the ASCII set `\" \\t\\n\\r\\f\\v\"`\n * by definition (Python's `str.split()` and JavaScript's `\\s` disagree at the\n * edges of Unicode; `nfkc` first folds a no-break space into a plain one).\n */\n\nimport { createHash } from \"node:crypto\";\n\nimport { pyFloatRepr } from \"../cli/platform/worldData/json\";\n\nexport type Transform = (value: string) => string;\n\nexport const WHITESPACE = \" \\t\\n\\r\\f\\v\";\nconst WHITESPACE_EDGES = new RegExp(`^[${WHITESPACE}]+|[${WHITESPACE}]+$`, \"g\");\nconst WHITESPACE_RUN = new RegExp(`[${WHITESPACE}]+`, \"g\");\nconst NOT_DIGIT = /[^0-9]/g;\n\nexport const STRIP_PREFIX = \"strip_prefix\";\n\nconst trim = (value: string): string => value.replace(WHITESPACE_EDGES, \"\");\n\nconst emailLocalPart = (value: string): string => {\n const at = value.lastIndexOf(\"@\");\n return at === -1 ? value : value.slice(0, at);\n};\n\nconst emailDomain = (value: string): string => {\n const at = value.lastIndexOf(\"@\");\n return at === -1 ? \"\" : value.slice(at + 1).toLowerCase();\n};\n\nconst stripPrefix =\n (prefix: string): Transform =>\n (value) =>\n value.startsWith(prefix) ? value.slice(prefix.length) : value;\n\nconst hex = (algorithm: \"sha1\" | \"sha256\", value: string): string =>\n createHash(algorithm).update(value, \"utf8\").digest(\"hex\");\n\nconst SIMPLE: Record<string, Transform> = {\n lower: (value) => value.toLowerCase(),\n upper: (value) => value.toUpperCase(),\n trim,\n collapse_ws: (value) => trim(value).replace(WHITESPACE_RUN, \" \"),\n nfkc: (value) => value.normalize(\"NFKC\"),\n digits: (value) => value.replace(NOT_DIGIT, \"\"),\n email_local_part: emailLocalPart,\n email_domain: emailDomain,\n // Vendor-style digests: lowercase hex of the utf-8 bytes, unsalted. This is\n // how SpyCloud accepts a hashed selector (`_digests` in its api_handlers).\n sha1: (value) => hex(\"sha1\", value),\n sha256: (value) => hex(\"sha256\", value),\n};\n\n/** The closed set, as a manifest spells it. `strip_prefix` takes its parameter\n * after a colon; the parameter may hold any character but `,`. */\nexport const TRANSFORMS: readonly string[] = [...Object.keys(SIMPLE), `${STRIP_PREFIX}:<prefix>`];\n\n/** The function a transform name denotes; throws when the name is not in the set. */\nexport function parseTransform(name: string): Transform {\n const simple = Object.prototype.hasOwnProperty.call(SIMPLE, name) ? SIMPLE[name] : undefined;\n if (simple) return simple;\n const colon = name.indexOf(\":\");\n if (colon !== -1) {\n const head = name.slice(0, colon);\n const prefix = name.slice(colon + 1);\n if (head === STRIP_PREFIX && prefix && !prefix.includes(\",\")) return stripPrefix(prefix);\n }\n throw new Error(`Unknown transform '${name}'; choose one of ${TRANSFORMS.join(\", \")}`);\n}\n\n/** `str(value)` as the Python runtime spells a number: an integral number is an\n * int, any other its float repr. */\nconst text = (value: string | number): string => {\n if (typeof value === \"string\") return value;\n return Number.isInteger(value) ? String(value) : pyFloatRepr(value);\n};\n\n/**\n * Compose `chain` left to right over `value`.\n *\n * A number is written as Python's `str()` first, the way `_digest` salts one,\n * so a number keyed on one side and a string on the other transform alike. The\n * whole chain is parsed before any step runs: a bad name at the end refuses\n * the mapping outright rather than after a partial result. An empty chain is\n * the identity.\n */\nexport function applyTransforms(value: string | number, chain: readonly string[]): string {\n const steps = chain.map(parseTransform);\n let out = text(value);\n for (const step of steps) out = step(out);\n return out;\n}\n","/**\n * Stored forms: what a world's store holds for a field given its plaintext.\n *\n * A schema world's `[redact]` table (connector.toml) rewrites named fields\n * before they reach disk — `hash` to a slug-salted sha256, `preserve` to a\n * shape-preserving digest, `round` to fewer decimals, `drop` to nothing. A\n * lookup by plaintext therefore has to compute the same form the store did.\n * This module is the TypeScript twin of the Python runtime's `_digest`,\n * `_shaped`, `redaction_of` and `stored_forms` (environment/schema/connector.py):\n * the rule is `\"sha256:\" + sha256(\"<slug>:<plaintext>\")`, no lowercasing, no\n * trimming, no other salt, and the golden vectors in redaction.test.ts pin the\n * two implementations to each other.\n */\n\nimport { createHash } from \"node:crypto\";\n\nimport { JsonNumber, pyFloatRepr, pyRound } from \"../cli/platform/worldData/json\";\nimport { applyTransforms } from \"./transforms\";\n\n/** The `[redact]` table as `describe` reports it (`connection.redact`, and\n * `redact` on `GET /api/public/worlds/{slug}`). */\nexport type RedactPolicy = {\n /** The digest salt: the connector's slug from connector.toml. It can differ\n * from the platform world slug (`spycloud` vs `spycloud-world`); `storedForms`\n * prefers it and falls back to the world slug only when it is absent. */\n slug?: string;\n hash: string[];\n drop: string[];\n preserve: string[];\n round: Record<string, number>;\n};\n\n/** The policy one field is stored under; null when it is stored in the clear. */\nexport type Redaction = \"hash\" | \"drop\" | \"preserve\" | `round:${number}`;\n\n/**\n * A value as the Python runtime would see it. JavaScript has one number\n * type, so an integral number takes Python's `int` path and any other number\n * its `float` path (`100` is `100`, never `100.0`); integers stay exact within\n * the safe range only.\n */\nexport type Plaintext = string | number;\n\nconst isInt = (value: Plaintext): value is number => typeof value === \"number\" && Number.isInteger(value);\n\n/** `str(value)` for an int or str, `repr(value)` for a float — the text the\n * Python runtime salts and shapes. */\nexport function pyText(value: Plaintext): string {\n if (typeof value === \"string\") return value;\n if (Number.isInteger(value)) return String(value);\n if (Number.isNaN(value)) return \"nan\";\n if (!Number.isFinite(value)) return value > 0 ? \"inf\" : \"-inf\";\n return pyFloatRepr(value);\n}\n\n/** The `hash` form: `\"sha256:\" + sha256(\"<slug>:<plaintext>\")` as hex. */\nexport function hashForm(slug: string, plaintext: Plaintext): string {\n return \"sha256:\" + createHash(\"sha256\").update(`${slug}:${pyText(plaintext)}`, \"utf8\").digest(\"hex\");\n}\n\n/**\n * The `preserve` form, the Python `_shaped`: the same length, every ASCII\n * digit still a digit, every ASCII letter still a letter of the same case,\n * everything else (separators, punctuation, non-ASCII) left in place. The\n * bytes come from sha256 of the seed `\"<slug>:<text>\"`, re-keyed as\n * sha256(digest + seed) once the 32 bytes are spent. A number keeps its type:\n * an int keeps its digit count (a leading zero is replaced), a float is re-read.\n */\nexport function preserveForm(slug: string, plaintext: Plaintext): Plaintext {\n const kind = typeof plaintext === \"string\" ? \"str\" : isInt(plaintext) ? \"int\" : \"float\";\n const shaped = shapeText(slug, pyText(plaintext), kind);\n return kind === \"str\" ? shaped : Number(shaped);\n}\n\n/** The shaping itself, on text: `kind` says which of Python's rules apply\n * (letters are re-lettered for a str only; an int keeps its digit count). */\nexport function shapeText(slug: string, text: string, kind: \"str\" | \"int\" | \"float\"): string {\n const seed = Buffer.from(`${slug}:${text}`, \"utf8\");\n let digest = createHash(\"sha256\").update(seed).digest();\n let cursor = 0;\n const out: string[] = [];\n for (const char of text) {\n if (cursor === digest.length) {\n digest = createHash(\"sha256\").update(Buffer.concat([digest, seed])).digest();\n cursor = 0;\n }\n const byte = digest[cursor]!;\n cursor += 1;\n if (char >= \"0\" && char <= \"9\") out.push(String(byte % 10));\n else if (kind === \"str\" && char >= \"a\" && char <= \"z\") out.push(String.fromCharCode(97 + (byte % 26)));\n else if (kind === \"str\" && char >= \"A\" && char <= \"Z\") out.push(String.fromCharCode(65 + (byte % 26)));\n else out.push(char);\n }\n // An int keeps its digit count; int() would drop a leading zero.\n if (kind === \"int\" && out.length > 1 && out[0] === \"0\") out[0] = String(1 + (digest[0]! % 9));\n return out.join(\"\");\n}\n\n/** The `round` form: Python's `round(value, decimals)` — an int unchanged, a\n * float correctly rounded with ties to even; a string is not a number and\n * passes through as the runtime leaves it. */\nexport function roundForm(plaintext: Plaintext, decimals: number): Plaintext {\n if (typeof plaintext === \"string\" || isInt(plaintext) || !Number.isFinite(plaintext)) return plaintext;\n return pyRound(new JsonNumber(pyFloatRepr(plaintext)), decimals).value;\n}\n\n/**\n * The policy a field of this name falls under, ranked as the runtime applies\n * them (drop, hash, preserve, round). Read without a path: a bare name in the\n * table counts, and so does a dotted path whose last segment is the field.\n */\nexport function redactionOf(redact: RedactPolicy | null | undefined, field: string): Redaction | null {\n if (!redact) return null;\n const named = (names: string[] | undefined) =>\n (names ?? []).some((name) => name === field || name.slice(name.lastIndexOf(\".\") + 1) === field);\n if (named(redact.drop)) return \"drop\";\n if (named(redact.hash)) return \"hash\";\n if (named(redact.preserve)) return \"preserve\";\n const decimals = redact.round?.[field];\n if (typeof decimals === \"number\") return `round:${decimals}`;\n return null;\n}\n\n/**\n * Every value the store may hold for `field` given this plaintext:\n *\n * clear field -> [plaintext]\n * hash -> [\"sha256:<hex>\"]\n * preserve -> [the shape-preserving digest]\n * round -> [round(plaintext, decimals)] for a number, [plaintext] otherwise\n * drop -> [] (the field is not on disk: a documented miss, not an error)\n *\n * `world` is what `describeWorld` / the bridge's `describe` return: the slug\n * is the salt, `redact` the table.\n *\n * `transform` — a cross-world mapping's chain (`./transforms`) — runs over the\n * plaintext FIRST, so `hash` and `preserve` salt the normalised text; omitted\n * (or empty) is today's behaviour, byte for byte.\n */\nexport function storedForms(\n world: { slug: string; redact?: RedactPolicy | null },\n field: string,\n plaintext: Plaintext,\n transform?: readonly string[],\n): Plaintext[] {\n if (transform?.length) plaintext = applyTransforms(plaintext, transform);\n const policy = redactionOf(world.redact, field);\n const salt = world.redact?.slug ?? world.slug;\n if (policy === \"drop\") return [];\n if (policy === \"hash\") return [hashForm(salt, plaintext)];\n if (policy === \"preserve\") return [preserveForm(salt, plaintext)];\n if (policy !== null) return [roundForm(plaintext, world.redact!.round[field]!)];\n return [plaintext];\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\nimport type { Plaintext } from \"./redaction\";\n\nexport type WorldQueryWhere = Record<string, Plaintext | Plaintext[]>;\n\nexport type WorldQueryOptions = {\n where?: WorldQueryWhere;\n /** The `where` values are plaintext: resolve each to its stored form before matching. */\n resolve?: boolean;\n limit?: number;\n offset?: number;\n /** Query the linked worlds too; the answer becomes groups. */\n across?: boolean;\n /** With `across`: add the parity report. */\n compare?: boolean;\n};\n\n/** The options that make `queryRows` answer {@link WorldQueryAcrossResult}. */\nexport type WorldQueryAcrossOptions = WorldQueryOptions & { across: true };\n\nexport type WorldQueryResult = {\n slug: string;\n versionId: string;\n kind: string | null;\n entity: string;\n rows: Record<string, unknown>[];\n /** Rows in this page. */\n count: number;\n /** Rows matching in all; null when the store does not count them. */\n total: number | null;\n limit: number;\n offset: number;\n /** With `resolve`: the stored forms each `where` field was matched against\n * (`[]` for a dropped field, which is why such a query matches nothing). */\n resolved?: Record<string, Plaintext[]>;\n entityCounts: Record<string, number>;\n snapshot: WorldQuerySnapshot | null;\n};\n\nexport type WorldQuerySnapshot = {\n snapshotId: string;\n contractHash: string;\n batchDigest: string;\n bytes: number;\n};\n\n/** One world's page inside an across answer: the root (`alias: null`, no\n * `mapping`) or a linked world with the mappings that carried the root's\n * `where` fields into its own entity. */\nexport type WorldQueryGroup = {\n world: { slug: string; alias: string | null; versionId: string };\n entity: string;\n rows: Record<string, unknown>[];\n count: number;\n total: number | null;\n limit: number;\n offset: number;\n resolved?: Record<string, Plaintext[]>;\n mapping?: { field: string; depField: string; transform: string[] }[];\n};\n\nexport type WorldQueryCompareStatus = \"matched\" | \"no match\" | \"unmapped\";\n\n/** Per `where` field, per world: whether the field reached the world and\n * whether any row matched there; `present`/`absent` list the worlds by slug. */\nexport type WorldQueryCompare = {\n present: string[];\n absent: string[];\n perField: {\n field: string;\n worlds: {\n world: string;\n alias: string | null;\n status: WorldQueryCompareStatus;\n /** `<depEntity>.<depField>` and the transform applied (mapped worlds only). */\n depField?: string;\n transform?: string[];\n }[];\n }[];\n};\n\nexport type WorldQueryAcrossResult = {\n slug: string;\n versionId: string;\n kind: string | null;\n entity: string;\n /** The root world first, then one per linked world that was queried. */\n groups: WorldQueryGroup[];\n compare?: WorldQueryCompare;\n entityCounts: Record<string, number>;\n snapshot: WorldQuerySnapshot | null;\n};\n\n/** The query string the route reads; `where` travels as URL-encoded JSON and\n * `ref` (the `@ref` of `slug@ref`) picks the version. */\nexport function queryRowsSearch(entity: string, opts: WorldQueryOptions = {}, ref?: string): string {\n const search = new URLSearchParams();\n if (ref) search.set(\"ref\", ref);\n search.set(\"entity\", entity);\n if (opts.where && Object.keys(opts.where).length) search.set(\"where\", JSON.stringify(opts.where));\n if (opts.limit !== undefined) search.set(\"limit\", String(opts.limit));\n if (opts.offset !== undefined) search.set(\"offset\", String(opts.offset));\n if (opts.resolve) search.set(\"resolve\", \"true\");\n if (opts.across) search.set(\"across\", \"true\");\n if (opts.compare) search.set(\"compare\", \"true\");\n return `?${search.toString()}`;\n}\n\n/** One version of the world, queried: the main tip for a bare slug, or the\n * version `slug@ref` names (branch, tag, semver pin or hash prefix — the\n * `bench pull` grammar; a ref nothing answers to is the platform's 404, never\n * the head). With `across: true` the answer is the groups shape. */\nexport async function queryRows(\n slug: string,\n entity: string,\n opts: WorldQueryAcrossOptions,\n options?: WorldsClientOptions,\n): Promise<WorldQueryAcrossResult>;\nexport async function queryRows(\n slug: string,\n entity: string,\n opts?: WorldQueryOptions,\n options?: WorldsClientOptions,\n): Promise<WorldQueryResult>;\nexport async function queryRows(\n slugRef: string,\n entity: string,\n opts: WorldQueryOptions = {},\n options: WorldsClientOptions = {},\n): Promise<WorldQueryResult | WorldQueryAcrossResult> {\n const [slug, ref] = slugRef.split(\"@\", 2) as [string, string | undefined];\n if (!slug || ref === \"\") throw new Error(`queryRows needs a slug, optionally slug@ref (got ${slugRef})`);\n if (!entity) throw new Error(\"queryRows needs an entity\");\n if (opts.compare && !opts.across) throw new Error(\"queryRows: compare needs across\");\n return apiRequest<WorldQueryResult | WorldQueryAcrossResult>(\n options,\n \"GET\",\n `/api/public/worlds/${encodeURIComponent(slug)}/data${queryRowsSearch(entity, opts, ref)}`,\n );\n}\n\nexport type WorldSqlOptions = {\n limit?: number;\n scenario?: string;\n};\n\nexport type WorldSqlResult = {\n slug: string;\n versionId: string;\n kind: string | null;\n engine: string;\n columns: string[];\n rows: unknown[][];\n count: number;\n limit: number;\n truncated: boolean;\n};\n\nexport async function sqlRows(\n slugRef: string,\n sql: string,\n opts: WorldSqlOptions = {},\n options: WorldsClientOptions = {},\n): Promise<WorldSqlResult> {\n const [slug, ref] = slugRef.split(\"@\", 2) as [string, string | undefined];\n if (!slug || ref === \"\") throw new Error(`sqlRows needs a slug, optionally slug@ref (got ${slugRef})`);\n if (!sql.trim()) throw new Error(\"sqlRows needs one SQL statement\");\n return apiRequest<WorldSqlResult>(options, \"POST\", `/api/public/worlds/${encodeURIComponent(slug)}/data/sql`, {\n sql,\n ...(ref ? { ref } : {}),\n ...(opts.limit !== undefined ? { limit: opts.limit } : {}),\n ...(opts.scenario ? { scenario: opts.scenario } : {}),\n });\n}\n","/**\n * `migrateWorld(slug)` — convert a stored world into a schema world, from\n * `POST /api/public/worlds/{slug}/migrate`; `migrateProjectWorlds()` plans\n * (or migrates) every connector world in the project from\n * `POST /api/public/worlds/migrate`. Dry run by default: the report says\n * what the version is, what the conversion does, or why it cannot; `apply`\n * commits the migrated tree as the next version (\"Migrated to a schema\n * world\"). Targets are the platform's connector worlds; a hand-built world\n * needs `force`. The CLI twin is `gateway worlds migrate`.\n */\n\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\n\nexport type WorldMigrationRefusal = {\n code: string;\n message: string;\n /** Paths the conversion needed and did not find. */\n missing: string[];\n};\n\nexport type WorldMigrationReport = {\n slug: string;\n containerId: string;\n versionId: string;\n /** True when the container was created from a connector template. */\n connectorWorld: boolean;\n /** schema | api-bundle | legacy-tools | harbor | verifiers */\n shape: string;\n target: \"schema\";\n /** True when the world already is a schema world. */\n unchanged: boolean;\n /** The dry-run report, one sentence each. */\n actions: string[];\n /** Files the migrated tree holds; 0 on a refusal. */\n files: number;\n refusal: WorldMigrationRefusal | null;\n /** True when this call committed the migrated tree. */\n applied: boolean;\n version: { id: string; contentHash: string } | null;\n};\n\nexport type MigrateWorldOptions = {\n /** Commit the migrated tree as the next version. Default false: dry run. */\n apply?: boolean;\n /** Migrate a world that was not created from a connector template. */\n force?: boolean;\n};\n\nexport async function migrateWorld(\n slug: string,\n input: MigrateWorldOptions = {},\n options: WorldsClientOptions = {},\n): Promise<WorldMigrationReport> {\n if (slug.includes(\"@\"))\n throw new Error(\n `migrateWorld converts a world's head version: pass the slug without @ref (got ${slug})`,\n );\n return apiRequest<WorldMigrationReport>(\n options,\n \"POST\",\n `/api/public/worlds/${encodeURIComponent(slug)}/migrate`,\n {\n ...(input.apply === undefined ? {} : { apply: input.apply }),\n ...(input.force === undefined ? {} : { force: input.force }),\n },\n );\n}\n\n/** Every connector world in the project, one report each. */\nexport async function migrateProjectWorlds(\n input: { apply?: boolean } = {},\n options: WorldsClientOptions = {},\n): Promise<{ worlds: WorldMigrationReport[]; applied: boolean }> {\n return apiRequest<{ worlds: WorldMigrationReport[]; applied: boolean }>(\n options,\n \"POST\",\n \"/api/public/worlds/migrate\",\n input.apply === undefined ? {} : { apply: input.apply },\n );\n}\n","/**\n * Records into a world's rows — the record contract, an interceptor that\n * writes it, the conversion from TOOL observations, and the door in.\n *\n * A tool's response is not the entity's shape, and nothing here assumes it\n * is. The workflow with real data is: pull the raw tool calls, look at them,\n * then ingest them through the route you declare — {@link ingest} with a\n * `transform` (your own `transform(records) -> {entity: [rows]}`, a function\n * or a script), with a `map` (an `ingest.toml` mapping for shapes that need\n * no code), or with neither, when the world's own `ingest.toml` applies or\n * each record's tool is a connector operation whose result *is* the\n * operation's response body (its `[ingest]` projection in `connector.toml`).\n * Mappings and projections run in the schema runtime (Python, bundled with\n * the CLI or on the platform), never re-implemented here; a transform runs\n * where you are.\n *\n * The record, one JSON object per line:\n *\n * {\"tool\": \"list_users\", \"args\": {\"team\": \"t1\"}, \"result\": {\"users\": [...]},\n * \"at\": \"2026-09-15T10:00:00Z\", \"session\": \"optional\", \"source\": \"optional free text\"}\n *\n * A `gateway worlds session export` line (`{seq, kind, tool, args, result,\n * error, completedAt}`) is accepted as it is. Redaction is optional and OFF\n * by default everywhere here: rows land as the tools returned them unless\n * `redact: \"apply\"` (the world's `[redact]` policy) or `\"refuse\"` is asked for.\n *\n * - {@link captureToolCalls} wraps an agent's tool functions so every real\n * call is recorded — the agent changes nothing.\n * - {@link toolCallsFromObservations} turns a trace's TOOL observations into\n * records (the `--from traces` path of `gateway worlds data ingest`).\n * - {@link ingest} puts records into a world through a transform, a mapping\n * or the operations: a local directory through the bundled runtime, a\n * platform slug through the batch lane. {@link ingestToolCalls} is the same\n * door with neither transform nor mapping of your own.\n */\n\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\n\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\nimport { GATEWAY_KEYS_MISSING, platformEndpoint } from \"./platformEndpoint\";\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/** 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\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/**\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/** What a TOOL observation carries, as `GET /api/public/observations` and\n * `GET /api/public/sessions/{id}?includeIO=true` return it. Both routes decode\n * stored JSON text once on the way out (`parseIoAsJson` defaults to true on the\n * v1 route; the session route renders with the same default), so `input` and\n * `output` arrive as the values the tool saw — an object, or a string when the\n * tool really produced text. Nothing here parses them again. */\nexport type ObservationLike = {\n id?: string;\n traceId?: string | null;\n type?: string;\n name?: string | null;\n input?: unknown;\n output?: unknown;\n startTime?: string | Date;\n level?: string;\n statusMessage?: string | null;\n};\n\nexport type ObservationConversion = {\n records: ToolCallRecord[];\n /** TOOL observations whose name is not one of the world's operations, by name. */\n unknownTools: Record<string, number>;\n /** Observations that were not converted, by reason. */\n skipped: Record<string, number>;\n};\n\nconst isoOf = (value: string | Date | undefined): string | undefined =>\n value instanceof Date ? value.toISOString() : typeof value === \"string\" ? value : undefined;\n\n/**\n * TOOL observations → tool-call records: `name` is the tool, `input` the args,\n * `output` the result, `startTime` the time, `trace:<traceId>/<id>` the source.\n * `input`/`output` arrive from the public API already decoded (it parses the\n * stored text once), so they are taken as they are: a string `output` stays a\n * string even when it looks like JSON; an `input` that is not an object leaves\n * `args` empty rather than guessed.\n * Only `type: \"TOOL\"` converts. With `tools` (the world's operation names) an\n * observation for any other tool is counted in `unknownTools`, not converted.\n * An `ERROR`-level observation converts with `error` set, so ingest counts it\n * as a failed call instead of projecting its output.\n */\nexport function toolCallsFromObservations(\n observations: ObservationLike[],\n opts: { tools?: Iterable<string> | null; session?: string; since?: string } = {},\n): ObservationConversion {\n const known = opts.tools ? new Set(opts.tools) : null;\n const sinceMs = opts.since ? Date.parse(opts.since) : NaN;\n const out: ObservationConversion = { records: [], unknownTools: {}, skipped: {} };\n const skip = (reason: string) => {\n out.skipped[reason] = (out.skipped[reason] ?? 0) + 1;\n };\n for (const observation of observations) {\n if (observation.type !== \"TOOL\") {\n skip(`type ${observation.type ?? \"unknown\"}`);\n continue;\n }\n const tool = observation.name;\n if (typeof tool !== \"string\" || !tool) {\n skip(\"no name\");\n continue;\n }\n const at = isoOf(observation.startTime);\n if (!Number.isNaN(sinceMs) && at !== undefined && Date.parse(at) < sinceMs) {\n skip(\"before since\");\n continue;\n }\n if (known && !known.has(tool)) {\n out.unknownTools[tool] = (out.unknownTools[tool] ?? 0) + 1;\n continue;\n }\n const record: ToolCallRecord = { tool, args: isObject(observation.input) ? observation.input : {} };\n if (observation.level === \"ERROR\") record.error = observation.statusMessage || \"ERROR\";\n else record.result = observation.output;\n if (at !== undefined) record.at = at;\n if (opts.session) record.session = opts.session;\n record.source = `trace:${observation.traceId ?? \"?\"}/${observation.id ?? \"?\"}`;\n out.records.push(record);\n }\n return out;\n}\n\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\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 = platformEndpoint(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);\n const { pull } = await import(\"./hub\");\n const slug = world.split(\"@\", 1)[0]!;\n const scratch = fs.mkdtempSync(path.join(os.tmpdir(), \"gateway-ingest-\"));\n try {\n const pulled = await pull(world, path.join(scratch, slug), options);\n // Produced and proven against the pulled contract; the platform's batch\n // lane checks every row again and redacts there, so this pass runs with\n // redaction off and hands the rows on as they were produced.\n let report: IngestReport;\n let projected: Rows;\n if (rows === null) {\n const proven = await ingestLocalToolCalls(pulled.dir, records, { redact: \"off\", dryRun: true, mode, map }, creds);\n report = reportOf(world, proven, redact);\n projected = proven.projected ?? {};\n } else {\n const proven = await checkLocalWorldData(pulled.dir, rows, creds);\n report = transformReport(world, records.length, rows, stderr, { dryRun, redact, changed: false, kind: proven.kind, entityCounts: proven.entity_counts });\n projected = rows;\n }\n report.dryRun = dryRun;\n if (dryRun || report.refusals.length || !Object.keys(projected).length) return report;\n const { pushRows } = await import(\"../cli/platform/worldData/push\");\n const status = await pushRows(creds, slug, projected, { mode, redact, message: options.message });\n report.batch = status;\n report.changed = status.state === \"applied\" || status.state === \"published\";\n if (status.entityCounts) report.entityCounts = status.entityCounts;\n return report;\n } finally {\n fs.rmSync(scratch, { recursive: true, force: true });\n }\n}\n\n/**\n * Tool-call records into a world with neither a transform nor a mapping of\n * your own: the world's `ingest.toml` when it has one, else each record's\n * tool through its operation's `[ingest]` projection (an unknown tool is a\n * refusal naming it and nothing is written). {@link ingest} with the same\n * options.\n */\nexport async function ingestToolCalls(world: string, records: unknown[], options: IngestToolCallsOptions = {}): Promise<IngestToolCallsReport> {\n return ingest(world, records, options);\n}\n\nfunction transformReport(\n world: string,\n records: number,\n rows: Rows,\n stderr: string,\n outcome: { dryRun: boolean; redact: RedactMode; changed: boolean; kind?: string; entityCounts?: Record<string, number> },\n): IngestReport {\n return {\n world,\n via: \"transform\",\n ...(stderr ? { stderr } : {}),\n records,\n ingested: records,\n skipped: {},\n refusals: [],\n rows: Object.fromEntries(Object.entries(rows).map(([entity, listed]) => [entity, listed.length])),\n dryRun: outcome.dryRun,\n redact: outcome.redact,\n changed: outcome.changed,\n ...(outcome.kind ? { kind: outcome.kind } : {}),\n ...(outcome.entityCounts ? { entityCounts: outcome.entityCounts } : {}),\n };\n}\n\nfunction reportOf(\n world: string,\n local: {\n via?: IngestReport[\"via\"];\n sources?: { name: string; kind: string; select: string; entity: string; records: number; items: number; rows: Record<string, number>; unmapped_fields: Record<string, string>; unset_fields: Record<string, string[]> }[];\n unmatched?: Record<string, number>;\n note?: string;\n records: number;\n ingested: number;\n skipped: Record<string, number>;\n refusals: IngestRefusal[];\n rows: Record<string, number>;\n dry_run: boolean;\n changed: boolean;\n kind?: string;\n entity_counts?: Record<string, number>;\n },\n redact: RedactMode,\n): IngestToolCallsReport {\n return {\n world,\n ...(local.via ? { via: local.via } : {}),\n ...(local.sources ? { sources: local.sources.map(({ unmapped_fields, unset_fields, ...rest }) => ({ ...rest, unmappedFields: unmapped_fields, unsetFields: unset_fields })) } : {}),\n ...(local.unmatched ? { unmatched: local.unmatched } : {}),\n ...(local.note ? { note: local.note } : {}),\n records: local.records,\n ingested: local.ingested,\n skipped: local.skipped,\n refusals: local.refusals,\n rows: local.rows,\n dryRun: local.dry_run,\n redact,\n changed: local.changed,\n ...(local.kind ? { kind: local.kind } : {}),\n ...(local.entity_counts ? { entityCounts: local.entity_counts } : {}),\n };\n}\n\n/** The TOOL observations of one session, every trace's, from `GET /api/public/sessions/{id}?includeIO=true`. */\nexport async function sessionToolObservations(sessionId: string, options: WorldsClientOptions = {}): Promise<ObservationLike[]> {\n const session = await apiRequest<{ traces?: { id?: string; observations?: ObservationLike[] }[] }>(\n options,\n \"GET\",\n `/api/public/sessions/${encodeURIComponent(sessionId)}?includeIO=true`,\n );\n const out: ObservationLike[] = [];\n for (const trace of session.traces ?? [])\n for (const observation of trace.observations ?? []) out.push({ traceId: trace.id ?? null, ...observation });\n return out;\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\nimport type { WorldTaskIdRef, WorldTaskSpec } from \"./session\";\n\n/**\n * Edit sessions: the version control unit for a world. Every write this\n * credential makes to a world (push, sandbox commit, data import, MCP, the\n * console editor) joins ONE open session per world per credential and lands\n * on that session's private branch; `close` seals the session into a version\n * on `main`, and a session nobody touches for an hour seals itself. Sessions\n * replace product-level proposals/PRs: `rollback` undoes a sealed session\n * (source + data together) as a new, itself-reversible session.\n *\n * One client under both `gateway worlds edit …` and `gateway bench edit …`;\n * the Python twin is `gatewaysdk.benchmark_hub.edit_sessions.WorldEditClient`.\n */\n\n/** The person behind a credential: named while a member of the organization, otherwise a former member with no id. */\nexport type ActingUser =\n | { status: \"member\"; id: string; name: string | null }\n | { status: \"former\" };\n\n/** Mirrors `WorldEditSessionSchema` (web/features/public-api/types/world-edits.ts). */\nexport type EditSessionSummary = {\n id: string;\n containerId: string;\n /** `apikey:<id>` for CLI/sandbox/MCP, `user:<id>` for the console, `agent:<id>` for the platform agent. */\n actor: string;\n /** The person behind `actor`, for a secret key or a member; null for a public key or when unknown. */\n actingUser: ActingUser | null;\n door: string;\n status: \"open\" | \"sealing\" | \"sealed\" | \"conflict\" | \"expired\" | \"discarded\" | string;\n baseVersionId: string | null;\n tipVersionId: string | null;\n sealedVersionId: string | null;\n editCount: number;\n startedAt: string;\n lastEditAt: string;\n expiresAt: string;\n closedAt: string | null;\n closeReason: string | null;\n conflictPaths: string[] | null;\n rollbackOfId: string | null;\n message: string | null;\n /** Set when `task edit close` sealed this session together with a task's other worlds. */\n sealGroupId: string | null;\n};\n\nexport type EditSessionList = {\n slug: string;\n containerId: string;\n /** This credential's open session, or null. */\n current: EditSessionSummary | null;\n sessions: EditSessionSummary[];\n};\n\n/** What close/discard/rollback return. */\nexport type EditSessionResult = { slug: string; session: EditSessionSummary };\n\nexport type EditSessionListQuery = { status?: string; limit?: number };\nexport type EditSessionCloseInput = { sessionId?: string; force?: boolean; message?: string };\nexport type EditSessionRollbackInput = { sessionId: string; force?: boolean; message?: string };\n\nconst WORLDS = \"/api/public/worlds\";\nexport class WorldEditClient {\n constructor(private readonly options: WorldsClientOptions = {}) {}\n\n /** The credential's current session and the world's newest-first sessions. */\n list(slug: string, query: EditSessionListQuery = {}): Promise<EditSessionList> {\n const qs = new URLSearchParams();\n if (query.status) qs.set(\"status\", query.status);\n if (query.limit !== undefined) qs.set(\"limit\", String(query.limit));\n const suffix = qs.size ? `?${qs.toString()}` : \"\";\n return apiRequest(this.options, \"GET\", `${WORLDS}/${encodeURIComponent(slug)}/edits${suffix}`);\n }\n\n /** Seal a session into a version on main (the credential's current one when `sessionId` is omitted). */\n close(slug: string, input: EditSessionCloseInput = {}): Promise<EditSessionResult> {\n return apiRequest(this.options, \"POST\", `${WORLDS}/${encodeURIComponent(slug)}/edits/close`, input);\n }\n\n /** Drop the session's private branch without making a version. */\n discard(slug: string, input: { sessionId?: string } = {}): Promise<EditSessionResult> {\n return apiRequest(this.options, \"POST\", `${WORLDS}/${encodeURIComponent(slug)}/edits/discard`, input);\n }\n\n /** Undo a sealed session (source and data) as a new sealed session. */\n rollback(slug: string, input: EditSessionRollbackInput): Promise<EditSessionResult> {\n return apiRequest(this.options, \"POST\", `${WORLDS}/${encodeURIComponent(slug)}/edits/rollback`, input);\n }\n}\n\n/** A stored task (`{id, version?}`) or a spec with `worlds`, as `task up` takes it. */\nexport type TaskEditTarget = WorldTaskIdRef | WorldTaskSpec;\n\n/** The task the platform resolved: stored id and version, or the spec's hash. */\nexport type TaskEditTaskRef = {\n taskId: string | null;\n taskVersion: number | null;\n name: string | null;\n hash: string;\n};\n\n/** Mirrors `TaskEditStatusResponseSchema` (web/features/public-api/types/world-task-edits.ts). */\nexport type TaskEditStatus = {\n task: TaskEditTaskRef;\n worlds: Record<\n string,\n {\n slug: string;\n ref: string;\n problem: string | null;\n session: EditSessionSummary | null;\n /** This credential's sessions parked in `conflict` on the world: unsealed too. */\n parked: EditSessionSummary[];\n mainVersionId: string | null;\n sealNow: \"fast-forward\" | \"rebase\" | \"conflict\" | null;\n conflictPaths: string[];\n }\n >;\n /** Aliases whose world holds edits only this credential sees. */\n unsealed: string[];\n hint: string | null;\n};\n\nexport type TaskEditSealed = { slug: string; session: EditSessionSummary };\n\nexport type TaskEditCloseResult = {\n task: TaskEditTaskRef;\n groupId: string | null;\n worlds: Record<string, TaskEditSealed>;\n skipped: Record<string, { slug: string; reason: string }>;\n};\n\nexport type TaskEditRollbackResult = {\n task: TaskEditTaskRef;\n groupId: string;\n rollbackOf: string;\n worlds: Record<string, TaskEditSealed>;\n /** Members whose seal left `main` where it was: nothing to undo there. */\n skipped: Record<string, { slug: string; reason: string }>;\n};\n\nexport type TaskEditCloseInput = { requireAll?: boolean; force?: boolean; message?: string };\nexport type TaskEditRollbackInput = { groupId: string; force?: boolean; message?: string };\n\nconst TASK_EDITS = \"/api/public/world-task-edits\";\n\n/**\n * This credential's edit sessions on every world a task names, together:\n * `close` seals them onto their mains in ONE platform transaction (all or\n * none), `rollback` undoes the seal group as one. Python twin:\n * `gatewaysdk.benchmark_hub.edit_sessions.TaskEditClient`.\n */\nexport class TaskEditClient {\n constructor(private readonly options: WorldsClientOptions = {}) {}\n\n status(task: TaskEditTarget): Promise<TaskEditStatus> {\n return apiRequest(this.options, \"POST\", `${TASK_EDITS}/status`, { task });\n }\n\n close(task: TaskEditTarget, input: TaskEditCloseInput = {}): Promise<TaskEditCloseResult> {\n return apiRequest(this.options, \"POST\", `${TASK_EDITS}/close`, { task, ...input });\n }\n\n rollback(task: TaskEditTarget, input: TaskEditRollbackInput): Promise<TaskEditRollbackResult> {\n return apiRequest(this.options, \"POST\", `${TASK_EDITS}/rollback`, { task, ...input });\n }\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\n\n/**\n * The hosted one-task dry run: `POST /api/public/environments/{id}/dry-run`\n * and the run-status read that settles it. The runner runs ONE named task of a\n * harbor tree through harbor's `oracle` (the task's own `solution/solve.sh`)\n * with the real image rule (`[environment] docker_image` → pull, never build;\n * else build the Dockerfile). No model, no model key. The run is marked\n * `kind: \"dry-run\"` and never counts as a benchmark result.\n *\n * The caps are the server's: one task, one example, one rollout, the oracle.\n * The body carries the task name and, optionally, a pinned versionId; a body\n * that tries to widen the run (models, task lists, rollouts) is a 400.\n */\n\nexport const DRY_RUN_KIND = \"dry-run\" as const;\nexport const DRY_RUN_AGENT = \"oracle\" as const;\n\nexport type HostedDryRunDispatch = {\n runId: string;\n versionId: string;\n versionLabel: string;\n containerSlug: string;\n task: string;\n kind: typeof DRY_RUN_KIND;\n agent: typeof DRY_RUN_AGENT;\n evidence: false;\n where: \"hosted\";\n};\n\n/** The image decision the runner took — the SAME rule a real run applies. */\nexport type DryRunImageDecision = {\n source: \"prebuilt\" | \"dockerfile\";\n ref: string | null;\n};\n\n/** What the runner reported about the one trial (the Python twin is `benchmark_hub.dry_run.DryRunSettlement`). */\nexport type DryRunSettlement = {\n task: string;\n agent: typeof DRY_RUN_AGENT;\n image: DryRunImageDecision | null;\n command: string | null;\n reward: number | null;\n rewardFile: { name: string; content: unknown } | null;\n exitCode: number | null;\n errorTail: string | null;\n};\n\nexport type HostedDryRunStatus = {\n kind: typeof DRY_RUN_KIND;\n evidence: false;\n where: \"hosted\";\n agent: typeof DRY_RUN_AGENT;\n task: string | null;\n evaluationId: string | null;\n url: string | null;\n settlement: DryRunSettlement | null;\n};\n\n/** The run-status answer (`GET …/environments/runs/{runId}`) as a dry run reads it. */\nexport type HostedDryRunVerdict = {\n status: string;\n settled: boolean;\n progress: {\n harvested: number;\n planned: number | null;\n startedAt: string | null;\n completedAt: string | null;\n elapsedSeconds: number | null;\n } | null;\n dryRun: HostedDryRunStatus | null;\n};\n\n/** The server blocks a status read for at most this long; longer waits poll. */\nexport const STATUS_WAIT_CAP_SECONDS = 50;\n\nexport type SettleOptions = {\n /** Give up (return the last verdict, unsettled) after this long. */\n timeoutSeconds: number;\n /** Called once per unsettled poll with the verdict so far. */\n onProgress?: (verdict: HostedDryRunVerdict) => void;\n /** Injected for tests: the clock and the pause between empty polls. */\n now?: () => number;\n sleep?: (ms: number) => Promise<void>;\n};\n\nconst cid = (id: string) =>\n `/api/public/environments/${encodeURIComponent(id)}`;\n\n/** The client a `gateway benchmarks dry-run --hosted` is built on. */\nexport class HostedDryRunClient {\n constructor(private readonly options: WorldsClientOptions = {}) {}\n\n /** Dispatch ONE oracle job for `task` on `containerId` (a container id, not a slug); pins `versionId` when given. */\n dispatch(target: {\n containerId: string;\n task: string;\n versionId?: string;\n }): Promise<HostedDryRunDispatch> {\n return apiRequest(\n this.options,\n \"POST\",\n `${cid(target.containerId)}/dry-run`,\n {\n task: target.task,\n ...(target.versionId ? { versionId: target.versionId } : {}),\n },\n );\n }\n\n /** One status read, blocking server-side for up to `waitSeconds` (capped). */\n status(runId: string, waitSeconds = 0): Promise<HostedDryRunVerdict> {\n const wait = Math.max(\n 0,\n Math.min(Math.floor(waitSeconds), STATUS_WAIT_CAP_SECONDS),\n );\n const suffix = wait ? `?waitSeconds=${wait}` : \"\";\n return apiRequest(\n this.options,\n \"GET\",\n `/api/public/environments/runs/${encodeURIComponent(runId)}${suffix}`,\n );\n }\n\n /** Poll until the run settles or `timeoutSeconds` pass; the last verdict either way. */\n async settle(\n runId: string,\n opts: SettleOptions,\n ): Promise<HostedDryRunVerdict> {\n const now = opts.now ?? Date.now;\n const sleep =\n opts.sleep ??\n ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));\n const deadline = now() + opts.timeoutSeconds * 1000;\n for (;;) {\n const budget = Math.floor(\n Math.min(45, Math.max(0, (deadline - now()) / 1000)),\n );\n const asked = now();\n const verdict = await this.status(runId, budget);\n if (verdict.settled || now() >= deadline) return verdict;\n opts.onProgress?.(verdict);\n // A server that answered at once (no long poll behind it) must not be hammered.\n if (now() - asked < 1000) await sleep(1000);\n }\n }\n}\n\n/** The one exit-code decision, shared by the CLI twins: 0 only when the oracle scored exactly 1.0. */\nexport class DryRunOutcome {\n constructor(readonly verdict: HostedDryRunVerdict) {}\n\n get settlement(): DryRunSettlement | null {\n return this.verdict.dryRun?.settlement ?? null;\n }\n\n /** Why the dry run did not pass, or null when it did. */\n reason(): string | null {\n if (!this.verdict.settled) return `still running after the wait`;\n const settlement = this.settlement;\n if (!settlement)\n return `the runner filed no settlement (${this.verdict.status})`;\n const lastErrorLine =\n settlement.errorTail?.trim().split(\"\\n\").at(-1) || null;\n // A non-zero harbor exit is a failure whatever the reward file says: a\n // 1.0 written before the harness died is not a pass.\n if (settlement.exitCode !== null && settlement.exitCode !== 0)\n return `the runner failed (exit ${settlement.exitCode}): ${lastErrorLine ?? \"harbor exited non-zero\"}`;\n if (settlement.reward === null && lastErrorLine)\n return `the runner failed (exit ?): ${lastErrorLine}`;\n if (settlement.reward === null)\n return \"ungraded: the grader ran but wrote no reward\";\n if (settlement.reward !== 1)\n return `the reference solution scored ${settlement.reward}, not 1.0`;\n return null;\n }\n\n passed(): boolean {\n return this.reason() === null;\n }\n}\n","import { requirePlatformEndpoint } from \"./platformEndpoint\";\nimport type { WorldTaskIdRef } from \"./session\";\nimport { PlatformTransport, type PlatformMethod, type RetryPolicy } from \"./transport\";\n\nexport type WorldsClientOptions = {\n host?: string;\n publicKey?: string;\n secretKey?: string;\n};\n\nexport type ResolvedWorldVersion = {\n versionId: string;\n semanticVersion: string | null;\n contentHash: string;\n state?: string;\n};\n\nexport type WorldTaskInfo = {\n name: string;\n variant: string | null;\n};\n\nexport type DispatchedRun = {\n model: string;\n runId: string;\n ok: boolean;\n error?: string;\n};\n\n/** A non-2xx platform answer: act on `status` or the stable public `code` (never the server's error class) rather than parsing the message. */\nexport class ApiError extends Error {\n public readonly code: string | null;\n\n constructor(\n public readonly status: number,\n method: string,\n path: string,\n public readonly text: string,\n ) {\n const parsed = parseErrorBody(text, status);\n super(`${method} ${path} -> ${status}: ${parsed.detail}`);\n this.name = \"ApiError\";\n this.code = parsed.code;\n }\n}\n\nconst DETAIL_LIMIT = 600;\n\nconst EDGE_ANSWERS: Readonly<Record<number, string>> = {\n 502: \"Bad Gateway from the load balancer in front of the platform, not the platform's answer: the web server dropped the connection or restarted mid-request. Retry; if it repeats, the platform is restarting or overloaded.\",\n 503: \"Service Unavailable from the load balancer in front of the platform, not the platform's answer: no web server was ready to take the request (a deploy or a restart). Retry in a minute.\",\n 504: \"Gateway Time-out from the load balancer in front of the platform, not the platform's answer: the request sent nothing back within the load balancer's idle timeout (60 s unless the deployment raises it: Helm ingress.idleTimeoutSeconds) and was cut there, though the platform may still be running it. Check what it changed before you retry.\",\n};\nconst EDGE_FAILURE =\n \"The platform failed without its JSON error body: a proxy in front of it answered, or the server stopped before its error handler ran. Retry; if it repeats, report the request and the time.\";\nconst EDGE_PAGE =\n \"An HTML page answered instead of the platform's JSON: a proxy in front of the platform, or the configured host is not the platform.\";\n\nfunction edgeAnswer(text: string, status: number | undefined): string | null {\n if (status !== undefined && status >= 500) return EDGE_ANSWERS[status] ?? EDGE_FAILURE;\n return /^\\s*</.test(text) ? EDGE_PAGE : null;\n}\n\n/** The detail and stable code of a non-2xx body; an HTML page or a bare 5xx is named, never printed.\n * Python twin: `gatewaysdk.api_errors.error_detail`; both run `conformance/platform-error-bodies.json`. */\nexport function parseErrorBody(text: string, status?: number): { detail: string; code: string | null } {\n const raw = { detail: text.slice(0, DETAIL_LIMIT), code: null };\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return { detail: (edgeAnswer(text, status) ?? text).slice(0, DETAIL_LIMIT), code: null };\n }\n if (parsed === null || typeof parsed !== \"object\") return raw;\n const { message, code, error } = parsed as { message?: unknown; code?: unknown; error?: unknown };\n const stableCode = typeof code === \"string\" ? code : null;\n if (typeof message !== \"string\") return { ...raw, code: stableCode };\n const fields = invalidFields(error);\n const said = fields ? `${message}: ${fields}` : message;\n if (stableCode === null) return { detail: said.slice(0, DETAIL_LIMIT), code: null };\n return {\n detail: `${said} (${stableCode})`.slice(0, DETAIL_LIMIT),\n code: stableCode,\n };\n}\n\n/** `<path>: <message>` per issue of a validation error; empty when it carries none. Python twin: `gatewaysdk.api_errors.invalid_fields`. */\nexport function invalidFields(error: unknown): string {\n const issues = Array.isArray(error) ? error : [];\n return issues\n .filter((issue): issue is { path?: unknown; message: string } =>\n issue !== null && typeof issue === \"object\" && typeof (issue as { message?: unknown }).message === \"string\",\n )\n .map((issue) => {\n const path = Array.isArray(issue.path) ? issue.path.map(String).join(\".\") : \"\";\n return path ? `${path}: ${issue.message}` : issue.message;\n })\n .join(\"; \");\n}\n\n/** Authenticated JSON request to the platform API. `init.timeoutMs` replaces the `GATEWAY_TIMEOUT_MS` budget for a request that\n * legitimately outlasts it; `init.retry` is only for a request whose repeat is harmless. */\nexport async function apiRequest<T>(\n options: WorldsClientOptions,\n method: PlatformMethod,\n path: string,\n body?: unknown,\n init: { timeoutMs?: number; retry?: RetryPolicy } = {},\n): Promise<T> {\n const reply = await new PlatformTransport(requirePlatformEndpoint(options)).send(method, path, body, init);\n if (!reply.ok) throw new ApiError(reply.status, method, path, reply.text);\n return JSON.parse(reply.text) as T;\n}\n\n/** Set (or rotate) one environment secret — write-only: no API returns it. */\nexport async function setEnvSecret(\n slug: string,\n key: string,\n value: string,\n options: WorldsClientOptions = {},\n): Promise<{ key: string; created: boolean }> {\n return apiRequest(\n options,\n \"PUT\",\n \"/api/public/benchmark-containers/secrets\",\n {\n slug,\n key,\n value,\n },\n );\n}\n\n/** Keys and rotation timestamps only — never values. */\nexport async function listEnvSecretKeys(\n slug: string,\n options: WorldsClientOptions = {},\n): Promise<{ key: string; updatedAt: string }[]> {\n const res = await apiRequest<{\n secrets: { key: string; updatedAt: string }[];\n }>(\n options,\n \"GET\",\n `/api/public/benchmark-containers/secrets?slug=${encodeURIComponent(slug)}`,\n );\n return res.secrets;\n}\n\nexport async function deleteEnvSecret(\n slug: string,\n key: string,\n options: WorldsClientOptions = {},\n): Promise<void> {\n await apiRequest(\n options,\n \"DELETE\",\n \"/api/public/benchmark-containers/secrets\",\n {\n slug,\n key,\n },\n );\n}\n\nexport type RunConfigSummary = {\n id: string;\n name: string;\n runType: string;\n createdAt: string;\n models: string[];\n parallelism: number;\n autoRunOnPush: boolean;\n agent: string | null;\n};\n\n/** The project's run configs; CI resolves one by name and dispatches it 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/** Either the bundle's own scenarios (`taskNames`, `taskSetDatasetId`) or stored tasks (`worldTasks`, schema worlds only), never both;\n * a stored task ref without `version` runs the task's current version at 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, as `bench run-configs create --world-tasks` takes them. */\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 per-task rewards. */\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/** A run as `bench runs list` prints it: no logs, samples or links (`getRun` has those). */\nexport type RunSummary = {\n id: string;\n status: string;\n terminal: boolean;\n score: number | null;\n summary: string | null;\n createdAt: string;\n completedAt: string | null;\n model: string | null;\n versionId: string | null;\n versionLabel: string | null;\n runConfigId: string | null;\n runConfigName: string | null;\n parallelism: number;\n exitCode: number | null;\n};\n\nexport type ListRunsFilter = {\n /** Only runs of this world/benchmark; a slug the project lacks lists nothing. */\n slug?: string;\n /** Case-insensitive run status (RUNNING, completed, …). */\n status?: string;\n limit?: number;\n};\n\n/** The project's runs, newest first. */\nexport async function listRuns(\n filter: ListRunsFilter = {},\n options: WorldsClientOptions = {},\n): Promise<RunSummary[]> {\n const params = new URLSearchParams();\n if (filter.slug) params.set(\"slug\", filter.slug);\n if (filter.status) params.set(\"status\", filter.status);\n if (filter.limit !== undefined) params.set(\"limit\", String(filter.limit));\n const qs = params.toString();\n const res = await apiRequest<{ runs: RunSummary[] }>(\n options,\n \"GET\",\n `/api/public/benchmark-containers/runs${qs ? `?${qs}` : \"\"}`,\n );\n return res.runs;\n}\n\n/** Poll a run to terminal every `intervalSeconds` (default 20) for up to `timeoutMinutes` (default 45). */\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/** A dispatch's branch, commit and actor: from GitHub Actions under CI, else the local git checkout; every dispatch carries it unless overridden. */\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 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/** A world pinned to one version, with its tasks and hosted runs, as `openWorld` and `openWorldVersion` return it. */\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 /** Open a live session on a bundled task's name or an inline `WorldTaskSpec`; the platform boots or reuses a warm container. */\n async open(\n task: import(\"./session\").WorldTaskRef,\n opts: {\n reuseWarm?: boolean;\n surfaces?: import(\"./browser\").WorldSurfaceKind[];\n browserTier?: import(\"./browser\").BrowserTier;\n } = {},\n ): Promise<import(\"./session\").WorldSession> {\n const { openSession } = await import(\"./session\");\n return openSession(this.slug, {\n task,\n versionId: this.version.versionId,\n reuseWarm: opts.reuseWarm,\n surfaces: opts.surfaces,\n browserTier: opts.browserTier,\n options: this.options,\n });\n }\n\n /** Start a hosted run of a run config on this version (or `opts.versionId`): one graded run per model, provenance detected unless given. */\n async dispatch(\n runConfigId: string,\n opts: {\n containerId?: string;\n versionId?: string;\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/** Resolve `slug` or `slug@branch|tag|semver|hash` to its pinned version and task list, without downloading the bundle. */\nexport async function openWorld(\n slugRef: string,\n options: WorldsClientOptions = {},\n): Promise<WorldSet> {\n const at = slugRef.indexOf(\"@\");\n const slug = at === -1 ? slugRef : slugRef.slice(0, at);\n const ref = at === -1 ? null : slugRef.slice(at + 1);\n return resolveWorld(slugRef, slug, ref, ref ? { ref } : {}, options);\n}\n\n/** Resolve `slug` at one READY `versionId`, with that version's task list; another world's version, a draft or an unknown id is a 404, never the head. */\nexport async function openWorldVersion(\n slug: string,\n versionId: string,\n options: WorldsClientOptions = {},\n): Promise<WorldSet> {\n return resolveWorld(\n `${slug}@${versionId}`,\n slug,\n null,\n { versionId },\n options,\n );\n}\n\nasync function resolveWorld(\n slugRef: string,\n slug: string,\n ref: string | null,\n pin: { ref?: string; versionId?: string },\n options: WorldsClientOptions,\n): Promise<WorldSet> {\n const version = await apiRequest<\n ResolvedWorldVersion & { taskNames?: string[] }\n >(options, \"POST\", \"/api/public/benchmark-containers/resolve-version\", {\n slug,\n ...pin,\n });\n\n const world = new WorldSet(\n slugRef,\n slug,\n ref,\n {\n versionId: version.versionId,\n semanticVersion: version.semanticVersion ?? null,\n contentHash: version.contentHash,\n state: version.state,\n },\n [],\n options,\n );\n for (const name of version.taskNames ?? []) {\n const variant = /^[a-z0-9]+-([a-z0-9]+)-/.exec(name)?.[1] ?? null;\n world.tasks.push(new WorldTask(world, name, variant));\n }\n return world;\n}\n\n// session.ts imports apiRequest from here; the cycle is function-level only.\nexport * from \"./transport\";\nexport * from \"./session\";\nexport * from \"./grade\";\nexport * from \"./sessionList\";\nexport * from \"./sessionContract\";\nexport * from \"./taskRef\";\nexport * from \"./tasks\";\nexport * from \"./taskGrades\";\nexport * from \"./taskSessions\";\nexport * from \"./taskRun\";\nexport * from \"./setRun\";\nexport * from \"./checkoutProvenance\";\nexport * from \"./evals\";\nexport * from \"./browser\";\nexport * from \"./surfaceDescriptor\";\nexport * from \"./requestLog\";\nexport * from \"./requestLedger\";\nexport * from \"./webhooks\";\nexport * from \"./browserReconnect\";\nexport * from \"./nativeComputer\";\nexport * from \"./hub\";\nexport * from \"./validate\";\nexport * from \"./describe\";\nexport * from \"./redaction\";\nexport * from \"./transforms\";\nexport * from \"./query\";\nexport * from \"./migrate\";\nexport * from \"./ingest\";\nexport * from \"./sandbox\";\nexport * from \"./editSessions\";\nexport * from \"./dryRun\";\nexport * from \"./worldNotice\";\n","/**\n * Read the project's traces, observations and trace sessions — the public\n * API behind `gateway traces …` and the MCP tools get_trace / get_observations\n * / get_session. Everything here is read-only.\n *\n * GET /api/public/traces?… a page of traces (page 1-based, limit ≤ 100)\n * GET /api/public/traces/{traceId} one trace with its observations and scores\n * GET /api/public/observations?… a page of observations (type, traceId, time window)\n * GET /api/public/sessions?… a page of trace sessions\n * GET /api/public/sessions/{sessionId} one session; includeIO=true attaches every trace's observations\n */\n\nimport { apiRequest, type WorldsClientOptions } from \"../worlds/index\";\n\nexport type TraceFilters = {\n fromTimestamp?: string;\n toTimestamp?: string;\n sessionId?: string;\n userId?: string;\n name?: string;\n tags?: string[];\n environment?: string;\n version?: string;\n release?: string;\n /** `timestamp.asc`, `timestamp.desc` (the default), … */\n orderBy?: string;\n};\n\nexport type ObservationFilters = {\n traceId?: string;\n type?: string;\n name?: string;\n userId?: string;\n level?: string;\n parentObservationId?: string;\n environment?: string;\n version?: string;\n fromStartTime?: string;\n toStartTime?: string;\n};\n\nexport type SessionFilters = { fromTimestamp?: string; toTimestamp?: string; environment?: string };\n\nexport type PageMeta = { page: number; limit: number; totalItems: number; totalPages: number };\nexport type Page<T> = { data: T[]; meta: PageMeta };\n\nexport type Trace = {\n id: string;\n timestamp: string;\n name: string | null;\n sessionId: string | null;\n userId: string | null;\n tags: string[];\n environment?: string;\n [key: string]: unknown;\n};\n\nexport type Observation = {\n id: string;\n traceId: string | null;\n type: string;\n name: string | null;\n startTime: string;\n endTime?: string | null;\n level?: string;\n [key: string]: unknown;\n};\n\nexport type TraceDetail = Trace & { observations: Observation[]; scores: unknown[]; latency?: number; totalCost?: number };\n\nexport type TraceSession = { id: string; createdAt: string; projectId: string; environment: string };\nexport type TraceSessionDetail = TraceSession & { traces: (Trace & { observations?: Observation[] })[] };\n\n/** The platform caps a page at 100. */\nexport const PAGE_LIMIT = 100;\n\ntype Scalar = string | number | boolean | undefined | null;\n\nfunction qs(params: Record<string, Scalar | string[]>): string {\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined || value === null || value === \"\") continue;\n if (Array.isArray(value)) for (const item of value) search.append(key, item);\n else search.set(key, String(value));\n }\n const text = search.toString();\n return text ? `?${text}` : \"\";\n}\n\nexport async function listTraces(\n options: WorldsClientOptions = {},\n filters: TraceFilters = {},\n page: { page?: number; limit?: number; fields?: string } = {},\n): Promise<Page<Trace>> {\n const { tags, ...rest } = filters;\n return apiRequest<Page<Trace>>(options, \"GET\", `/api/public/traces${qs({ ...rest, tags, page: page.page ?? 1, limit: page.limit ?? 50, fields: page.fields })}`);\n}\n\n/** Page through matching traces, newest first unless `orderBy` says otherwise; `max` stops early. */\nexport async function* iterateTraces(\n options: WorldsClientOptions = {},\n filters: TraceFilters = {},\n limits: { max?: number; fields?: string } = {},\n): AsyncGenerator<Trace> {\n yield* paged((page) => listTraces(options, filters, { page, limit: PAGE_LIMIT, fields: limits.fields }), limits.max);\n}\n\n/** One trace with its observations (input/output included) and scores. */\nexport async function getTrace(options: WorldsClientOptions = {}, traceId: string): Promise<TraceDetail> {\n return apiRequest<TraceDetail>(options, \"GET\", `/api/public/traces/${encodeURIComponent(traceId)}`);\n}\n\nexport async function listObservations(\n options: WorldsClientOptions = {},\n filters: ObservationFilters = {},\n page: { page?: number; limit?: number } = {},\n): Promise<Page<Observation>> {\n return apiRequest<Page<Observation>>(options, \"GET\", `/api/public/observations${qs({ ...filters, page: page.page ?? 1, limit: page.limit ?? 50 })}`);\n}\n\nexport async function* iterateObservations(\n options: WorldsClientOptions = {},\n filters: ObservationFilters = {},\n limits: { max?: number } = {},\n): AsyncGenerator<Observation> {\n yield* paged((page) => listObservations(options, filters, { page, limit: PAGE_LIMIT }), limits.max);\n}\n\nexport async function listSessions(\n options: WorldsClientOptions = {},\n filters: SessionFilters = {},\n page: { page?: number; limit?: number } = {},\n): Promise<Page<TraceSession>> {\n return apiRequest<Page<TraceSession>>(options, \"GET\", `/api/public/sessions${qs({ ...filters, page: page.page ?? 1, limit: page.limit ?? 50 })}`);\n}\n\nexport async function* iterateSessions(\n options: WorldsClientOptions = {},\n filters: SessionFilters = {},\n limits: { max?: number } = {},\n): AsyncGenerator<TraceSession> {\n yield* paged((page) => listSessions(options, filters, { page, limit: PAGE_LIMIT }), limits.max);\n}\n\n/** One trace session and its traces; `includeIO` attaches every trace's full observations. */\nexport async function getSession(\n options: WorldsClientOptions = {},\n sessionId: string,\n detail: { includeIO?: boolean } = {},\n): Promise<TraceSessionDetail> {\n return apiRequest<TraceSessionDetail>(options, \"GET\", `/api/public/sessions/${encodeURIComponent(sessionId)}${qs({ includeIO: detail.includeIO ? \"true\" : undefined })}`);\n}\n\nexport type ExportOptions = {\n /** Attach each trace's observations (one GET /traces/{id} per trace). */\n observations?: boolean;\n /** With `observations`: keep only this observation type (TOOL, GENERATION, SPAN, …). */\n type?: string;\n /** Stop after this many traces. */\n max?: number;\n};\n\nexport type ExportSummary = { traces: number; observations: number };\n\n/**\n * Every matching trace as one JSON object handed to `write`, ids and\n * timestamps exactly as the API returns them. With `observations`, each object\n * carries its `observations` array (filtered by `type` when given) and the\n * trace's `scores`, from `GET /traces/{id}`.\n */\nexport async function exportTraces(\n options: WorldsClientOptions = {},\n filters: TraceFilters = {},\n exportOptions: ExportOptions = {},\n write: (record: Record<string, unknown>) => void,\n): Promise<ExportSummary> {\n const summary: ExportSummary = { traces: 0, observations: 0 };\n const wantedType = exportOptions.type?.toUpperCase();\n for await (const trace of iterateTraces(options, filters, { max: exportOptions.max })) {\n let record: Record<string, unknown> = trace;\n if (exportOptions.observations) {\n const detail = await getTrace(options, trace.id);\n const observations = wantedType ? detail.observations.filter((o) => o.type?.toUpperCase() === wantedType) : detail.observations;\n summary.observations += observations.length;\n record = { ...detail, observations };\n }\n summary.traces++;\n write(record);\n }\n return summary;\n}\n\nasync function* paged<T>(fetchPage: (page: number) => Promise<Page<T>>, max?: number): AsyncGenerator<T> {\n let yielded = 0;\n for (let page = 1; ; page++) {\n const answer = await fetchPage(page);\n for (const item of answer.data) {\n if (max !== undefined && yielded >= max) return;\n yielded++;\n yield item;\n }\n const totalPages = answer.meta?.totalPages ?? (answer.data.length < PAGE_LIMIT ? page : page + 1);\n if (!answer.data.length || page >= totalPages) return;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAOO,SAAS,iBAAiB,SAA6D;AAC5F,QAAM,YAAY,QAAQ,aAAa,QAAQ,IAAI;AACnD,QAAM,YAAY,QAAQ,aAAa,QAAQ,IAAI;AACnD,MAAI,CAAC,aAAa,CAAC,UAAW,QAAO;AACrC,QAAM,OAAO,QAAQ,QAAQ,QAAQ,IAAI,gBAAgB;AACzD,SAAO,EAAE,MAAM,KAAK,QAAQ,QAAQ,EAAE,GAAG,WAAW,UAAU;AAChE;AAEO,SAAS,wBAAwB,SAAsD;AAC5F,QAAM,WAAW,iBAAiB,OAAO;AACzC,MAAI,CAAC,SAAU,OAAM,IAAI,MAAM,oBAAoB;AACnD,SAAO;AACT;AAnBA,IAEM,cAEO;AAJb;AAAA;AAAA;AAEA,IAAM,eAAe;AAEd,IAAM,uBACX;AAAA;AAAA;;;ACOK,SAAS,kBAAkB,MAAyB,QAAQ,KAAa;AAC9E,QAAM,MAAM,IAAI,oBAAoB;AACpC,MAAI,QAAQ,UAAa,QAAQ,GAAI,QAAO;AAC5C,QAAM,QAAQ,OAAO,GAAG;AACxB,MAAI,OAAO,UAAU,KAAK,KAAK,QAAQ,EAAG,QAAO;AACjD,QAAM,IAAI,MAAM,GAAG,oBAAoB,2DAA2D,GAAG,KAAK;AAC5G;AAlBA,IAAa,sBAGA,6BAiBP,YACA,OACA,aAKA,QAeA,eAGO,gBA6BA,kBAYP,OAMO,aA0BP,SAuBO;AA7Ib;AAAA;AAAA;AAAO,IAAM,uBAAuB;AAG7B,IAAM,8BAA8B;AAiB3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,CAAC,GAAG,GAAG,EAAE,WAAW,OAAO,YAAY,SAAS,OAAU,CAAC,CAAC,EAAE;AAC1K;AAmBA,eAAsB,aACpB,UAA+B,CAAC,GAChC,UAAwB,CAAC,GACzB,gBAA+B,CAAC,GAChC,OACwB;AACxB,QAAM,UAAyB,EAAE,QAAQ,GAAG,cAAc,EAAE;AAC5D,QAAM,aAAa,cAAc,MAAM,YAAY;AACnD,mBAAiB,SAAS,cAAc,SAAS,SAAS,EAAE,KAAK,cAAc,IAAI,CAAC,GAAG;AACrF,QAAI,SAAkC;AACtC,QAAI,cAAc,cAAc;AAC9B,YAAM,SAAS,MAAM,SAAS,SAAS,MAAM,EAAE;AAC/C,YAAM,eAAe,aAAa,OAAO,aAAa,OAAO,CAAC,MAAM,EAAE,MAAM,YAAY,MAAM,UAAU,IAAI,OAAO;AACnH,cAAQ,gBAAgB,aAAa;AACrC,eAAS,EAAE,GAAG,QAAQ,aAAa;AAAA,IACrC;AACA,YAAQ;AACR,UAAM,MAAM;AAAA,EACd;AACA,SAAO;AACT;AAEA,gBAAgB,MAAS,WAA+C,KAAiC;AACvG,MAAI,UAAU;AACd,WAAS,OAAO,KAAK,QAAQ;AAC3B,UAAM,SAAS,MAAM,UAAU,IAAI;AACnC,eAAW,QAAQ,OAAO,MAAM;AAC9B,UAAI,QAAQ,UAAa,WAAW,IAAK;AACzC;AACA,YAAM;AAAA,IACR;AACA,UAAM,aAAa,OAAO,MAAM,eAAe,OAAO,KAAK,SAAS,aAAa,OAAO,OAAO;AAC/F,QAAI,CAAC,OAAO,KAAK,UAAU,QAAQ,WAAY;AAAA,EACjD;AACF;","names":["resolve","init_session","point","path","MAX_ERROR","options","import_node_crypto","init_session","init_session","import_node_crypto","path","init_session","fs","path","import_node_crypto","fs","path","fs","path","import_node_crypto","import_node_zlib","fs","path","import_node_crypto","import_node_crypto","import_node_crypto","fs","path","path","init_session"]}
|
|
1
|
+
{"version":3,"sources":["../../src/worlds/personalToken.ts","../../src/worlds/platformEndpoint.ts","../../src/worlds/apiError.ts","../../src/worlds/transport.ts","../../src/worlds/credentialField.ts","../../src/worlds/browserReconnect.ts","../../src/worlds/browser.ts","../../src/worlds/pageState.ts","../../src/worlds/browserTools.ts","../../src/worlds/nativeComputer/actions.ts","../../src/worlds/nativeComputer/display.ts","../../src/worlds/nativeComputer/screen.ts","../../src/tracing/media.ts","../../src/worlds/nativeComputer/trace.ts","../../src/worlds/nativeComputer/base.ts","../../src/worlds/nativeComputer/keys.ts","../../src/worlds/nativeComputer/anthropic.ts","../../src/worlds/nativeComputer/openai.ts","../../src/worlds/nativeComputer/index.ts","../../src/worlds/sessionContract.ts","../../src/worlds/toolSchema.ts","../../src/worlds/requestLedger.ts","../../src/worlds/sessionReadiness.ts","../../src/tracing/session.ts","../../src/worlds/taskRef.ts","../../src/worlds/worldNotice.ts","../../src/worlds/grade.ts","../../src/worlds/session.ts","../../src/worlds/sessionList.ts","../../src/worlds/tasks.ts","../../src/worlds/taskGrades.ts","../../src/worlds/surfaceDescriptor.ts","../../src/worlds/taskSessions.ts","../../src/worlds/evals.ts","../../src/worlds/runSignals.ts","../../src/worlds/taskRunDir.ts","../../src/worlds/taskRunOutcome.ts","../../src/tracing/prerequisites.ts","../../src/worlds/taskTracing.ts","../../src/worlds/taskRun.ts","../../src/worlds/checkoutProvenance.ts","../../src/worlds/setRun.ts","../../src/worlds/requestLog.ts","../../src/worlds/webhooks.ts","../../src/worlds/checkoutTarget.ts","../../src/worlds/worldDir.ts","../../src/worlds/tar.ts","../../src/worlds/hub.ts","../../src/worlds/validate.ts","../../src/worlds/sandbox.ts","../../src/worlds/describe.ts","../../src/cli/platform/worldData/json.ts","../../src/worlds/transforms.ts","../../src/worlds/redaction.ts","../../src/worlds/query.ts","../../src/worlds/migrate.ts","../../src/worlds/ingest.ts","../../src/worlds/editSessions.ts","../../src/worlds/states.ts","../../src/worlds/dryRun.ts","../../src/worlds/index.ts","../../src/traces/index.ts"],"sourcesContent":["export const TOKEN_NOT_PERSONAL =\n \"GATEWAY_TOKEN takes a personal access token: pat_ followed by letters and digits only.\";\nexport const TOKEN_NEEDS_PROJECT =\n \"GATEWAY_TOKEN acts in the project GATEWAY_PROJECT_ID names: set it to the official project's id (letters, digits, - and _).\";\nexport const TOKEN_NEEDS_HOST = \"GATEWAY_TOKEN goes only to the host GATEWAY_HOST names: set GATEWAY_HOST.\";\nexport const TOKEN_OTHER_HOST =\n \"GATEWAY_TOKEN goes only to the host GATEWAY_HOST names, and this call names another host: point the call at GATEWAY_HOST or unset GATEWAY_TOKEN.\";\nexport const TOKEN_BESIDE_KEYS =\n \"GATEWAY_TOKEN is set beside a project key (GATEWAY_PUBLIC_KEY, GATEWAY_SECRET_KEY, GATEWAY_API_KEY or a key passed in): unset one of them. Neither replaces the other.\";\nexport const TOKEN_FILING =\n \"Filing an evaluation takes your project's key pair, not GATEWAY_TOKEN: unset it (an official world runs once copied into your own project).\";\nexport const TOKEN_KEYS_ONLY =\n \"Task-run tracing exports with a project key pair (GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY), not GATEWAY_TOKEN.\";\n\nconst PERSONAL = /^pat_[A-Za-z0-9]+$/;\nconst PROJECT = /^[A-Za-z0-9_-]+$/;\nconst ENV_KEYS = [\"GATEWAY_PUBLIC_KEY\", \"GATEWAY_SECRET_KEY\", \"GATEWAY_API_KEY\"];\n\nexport type TokenRequest = { host?: string; keys?: boolean };\n\nexport class PersonalTokenRefused extends Error {}\n\nconst bare = (host: string) => host.replace(/\\/+$/, \"\");\n\nexport class PersonalToken {\n private constructor(\n readonly value: string,\n readonly project: string,\n readonly host: string,\n ) {}\n\n static fromEnv(env: NodeJS.ProcessEnv, request: TokenRequest = {}): PersonalToken | null {\n const value = env.GATEWAY_TOKEN;\n if (!value) return null;\n if (request.keys || ENV_KEYS.some((name) => env[name])) throw new PersonalTokenRefused(TOKEN_BESIDE_KEYS);\n const host = bare(env.GATEWAY_HOST ?? \"\");\n if (!host) throw new PersonalTokenRefused(TOKEN_NEEDS_HOST);\n if (request.host && bare(request.host) !== host) throw new PersonalTokenRefused(TOKEN_OTHER_HOST);\n if (!PERSONAL.test(value)) throw new PersonalTokenRefused(TOKEN_NOT_PERSONAL);\n const project = env.GATEWAY_PROJECT_ID ?? \"\";\n if (!PROJECT.test(project)) throw new PersonalTokenRefused(TOKEN_NEEDS_PROJECT);\n return new PersonalToken(value, project, host);\n }\n\n toJSON(): { project: string; host: string } {\n return { project: this.project, host: this.host };\n }\n\n [Symbol.for(\"nodejs.util.inspect.custom\")](): string {\n return `PersonalToken { project: ${this.project}, host: ${this.host} }`;\n }\n\n static scrubbed(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n return Object.fromEntries(Object.entries(env).filter(([key]) => key !== \"GATEWAY_TOKEN\"));\n }\n}\n","import { PersonalToken } from \"./personalToken\";\nimport type { PlatformEndpoint } from \"./transport\";\n\nconst DEFAULT_HOST = \"https://withgateway.ai\";\n\nexport const GATEWAY_KEYS_MISSING =\n \"Gateway keys missing: set GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY (or pass publicKey/secretKey).\";\n\nexport function platformEndpoint(options: Partial<PlatformEndpoint>): PlatformEndpoint | null {\n if (options.token)\n return {\n host: (options.host ?? options.token.host).replace(/\\/+$/, \"\"),\n publicKey: options.publicKey ?? \"\",\n secretKey: options.secretKey ?? \"\",\n token: options.token,\n };\n const token = PersonalToken.fromEnv(process.env, {\n host: options.host,\n keys: Boolean(options.publicKey || options.secretKey),\n });\n if (token) return { host: token.host, publicKey: \"\", secretKey: \"\", token };\n const host = (options.host ?? process.env.GATEWAY_HOST ?? DEFAULT_HOST).replace(/\\/+$/, \"\");\n const publicKey = options.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;\n const secretKey = options.secretKey ?? process.env.GATEWAY_SECRET_KEY;\n if (!publicKey || !secretKey) return null;\n return { host, publicKey, secretKey };\n}\n\nexport function requirePlatformEndpoint(options: Partial<PlatformEndpoint>): PlatformEndpoint {\n const endpoint = platformEndpoint(options);\n if (!endpoint) throw new Error(GATEWAY_KEYS_MISSING);\n return endpoint;\n}\n","/** A non-2xx platform answer: act on `status` or the stable public `code` (never the server's error class) rather than parsing the message. */\nexport class ApiError extends Error {\n public readonly code: string | null;\n\n constructor(\n public readonly status: number,\n method: string,\n path: string,\n public readonly text: string,\n ) {\n const parsed = parseErrorBody(text, status);\n super(`${method} ${path} -> ${status}: ${parsed.detail}`);\n this.name = \"ApiError\";\n this.code = parsed.code;\n }\n}\n\nconst DETAIL_LIMIT = 600;\n\nconst EDGE_ANSWERS: Readonly<Record<number, string>> = {\n 502: \"Bad Gateway from the load balancer in front of the platform, not the platform's answer: the web server dropped the connection or restarted mid-request. Retry; if it repeats, the platform is restarting or overloaded.\",\n 503: \"Service Unavailable from the load balancer in front of the platform, not the platform's answer: no web server was ready to take the request (a deploy or a restart). Retry in a minute.\",\n 504: \"Gateway Time-out from the load balancer in front of the platform, not the platform's answer: the request sent nothing back within the load balancer's idle timeout (60 s unless the deployment raises it: Helm ingress.idleTimeoutSeconds) and was cut there, though the platform may still be running it. Check what it changed before you retry.\",\n};\nconst EDGE_FAILURE =\n \"The platform failed without its JSON error body: a proxy in front of it answered, or the server stopped before its error handler ran. Retry; if it repeats, report the request and the time.\";\nconst EDGE_PAGE =\n \"An HTML page answered instead of the platform's JSON: a proxy in front of the platform, or the configured host is not the platform.\";\n\nfunction edgeAnswer(text: string, status: number | undefined): string | null {\n if (status !== undefined && status >= 500) return EDGE_ANSWERS[status] ?? EDGE_FAILURE;\n return /^\\s*</.test(text) ? EDGE_PAGE : null;\n}\n\n/** The detail and stable code of a non-2xx body; an HTML page or a bare 5xx is named, never printed.\n * Python twin: `gatewaysdk.api_errors.error_detail`; both run `conformance/platform-error-bodies.json`. */\nexport function parseErrorBody(text: string, status?: number): { detail: string; code: string | null } {\n const raw = { detail: text.slice(0, DETAIL_LIMIT), code: null };\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return { detail: (edgeAnswer(text, status) ?? text).slice(0, DETAIL_LIMIT), code: null };\n }\n if (parsed === null || typeof parsed !== \"object\") return raw;\n const { message, code, error } = parsed as { message?: unknown; code?: unknown; error?: unknown };\n const stableCode = typeof code === \"string\" ? code : null;\n if (typeof message !== \"string\") return { ...raw, code: stableCode };\n const fields = invalidFields(error);\n const said = fields ? `${message}: ${fields}` : message;\n if (stableCode === null) return { detail: said.slice(0, DETAIL_LIMIT), code: null };\n return {\n detail: `${said} (${stableCode})`.slice(0, DETAIL_LIMIT),\n code: stableCode,\n };\n}\n\n/** `<path>: <message>` per issue of a validation error; empty when it carries none. Python twin: `gatewaysdk.api_errors.invalid_fields`. */\nexport function invalidFields(error: unknown): string {\n const issues = Array.isArray(error) ? error : [];\n return issues\n .filter((issue): issue is { path?: unknown; message: string } =>\n issue !== null && typeof issue === \"object\" && typeof (issue as { message?: unknown }).message === \"string\",\n )\n .map((issue) => {\n const path = Array.isArray(issue.path) ? issue.path.map(String).join(\".\") : \"\";\n return path ? `${path}: ${issue.message}` : issue.message;\n })\n .join(\"; \");\n}\n","import { ApiError } from \"./apiError\";\nimport { type PersonalToken, PersonalTokenRefused, TOKEN_BESIDE_KEYS, TOKEN_OTHER_HOST } from \"./personalToken\";\n\nexport const PLATFORM_TIMEOUT_ENV = \"GATEWAY_TIMEOUT_MS\";\n\nexport const PLATFORM_TIMEOUT_DEFAULT_MS = 120_000;\n\nexport type PlatformEndpoint = { host: string; publicKey: string; secretKey: string; token?: PersonalToken };\n\nexport type PlatformMethod = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n\nexport type PlatformReply = { status: number; ok: boolean; text: string };\n\nexport type PlatformSendOptions = { timeoutMs?: number; retry?: RetryPolicy; signal?: AbortSignal };\n\n/** The request budget in force: `GATEWAY_TIMEOUT_MS` when set, else the default. */\nexport function platformTimeoutMs(env: NodeJS.ProcessEnv = process.env): number {\n const raw = env[PLATFORM_TIMEOUT_ENV];\n if (raw === undefined || raw === \"\") return PLATFORM_TIMEOUT_DEFAULT_MS;\n const value = Number(raw);\n if (Number.isInteger(value) && value > 0) return value;\n throw new Error(`${PLATFORM_TIMEOUT_ENV} must be a positive whole number of milliseconds, not \\`${raw}\\`.`);\n}\n\nconst CHECK_HOST = \"Check GATEWAY_HOST (or --host) points at a running platform, then retry.\";\nconst RETRY = \"Retry; if it repeats, check the network between here and the platform.\";\nconst FETCH_LIMIT = {\n reason: \"Node's fetch stopped waiting after 300 s\",\n next: \"The platform may still be running it: check what it changed before you retry.\",\n};\n\nconst CAUSES: Record<string, { reason: string; next: string }> = {\n UND_ERR_HEADERS_TIMEOUT: FETCH_LIMIT,\n UND_ERR_BODY_TIMEOUT: FETCH_LIMIT,\n ECONNREFUSED: { reason: \"connection refused\", next: CHECK_HOST },\n ENOTFOUND: { reason: \"DNS lookup failed\", next: CHECK_HOST },\n EAI_AGAIN: { reason: \"DNS lookup failed\", next: CHECK_HOST },\n ETIMEDOUT: { reason: \"connect timed out\", next: CHECK_HOST },\n UND_ERR_CONNECT_TIMEOUT: { reason: \"connect timed out\", next: CHECK_HOST },\n EHOSTUNREACH: { reason: \"host unreachable\", next: CHECK_HOST },\n ENETUNREACH: { reason: \"network unreachable\", next: RETRY },\n ECONNRESET: { reason: \"connection dropped\", next: RETRY },\n UND_ERR_SOCKET: { reason: \"connection dropped\", next: RETRY },\n EPIPE: { reason: \"connection dropped\", next: RETRY },\n};\n\nconst UNKNOWN_CAUSE = { reason: \"network error\", next: CHECK_HOST };\n\n/** Why a request got no answer, from the socket-level error undici hides under `fetch failed`. */\nexport class TransportCause {\n private constructor(\n readonly reason: string,\n readonly detail: string | null,\n readonly next: string,\n ) {}\n\n static timeout(timeoutMs: number): TransportCause {\n return new TransportCause(\n `timed out after ${timeoutMs / 1000}s`,\n null,\n `Retry; if the platform is slow, raise ${PLATFORM_TIMEOUT_ENV} (milliseconds per request).`,\n );\n }\n\n static idle(idleMs: number): TransportCause {\n return new TransportCause(\n `no data for ${idleMs / 1000}s`,\n null,\n \"The stream resumes from its last event; if it repeats, check the network between here and the platform.\",\n );\n }\n\n static of(error: unknown): TransportCause {\n const cause = error instanceof Error && error.cause instanceof Error ? error.cause : undefined;\n const code = cause && \"code\" in cause && typeof cause.code === \"string\" ? cause.code : null;\n const message = cause?.message ?? (error instanceof Error ? error.message : String(error));\n const known = (code && CAUSES[code]) || UNKNOWN_CAUSE;\n return new TransportCause(known.reason, code ? `${code}: ${message}` : message, known.next);\n }\n\n describe(): string {\n return this.detail === null ? this.reason : `${this.reason} (${this.detail})`;\n }\n}\n\nexport class UnreachableError extends Error {\n constructor(\n readonly host: string,\n readonly method: string,\n readonly route: string,\n readonly failure: TransportCause,\n ) {\n super(`${method} ${route}: no answer from ${host}: ${failure.describe()}. ${failure.next}`);\n this.name = \"UnreachableError\";\n }\n}\n\nconst sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));\n\n/**\n * Another attempt after a gateway 5xx (502, 503, 504) or no answer at all, for a request whose repeat is harmless: a\n * keyed filing step, which the platform answers with the first filing. Every other request gets one attempt (`NONE`).\n */\nexport class RetryPolicy {\n static readonly NONE = new RetryPolicy([]);\n /** A platform restart or a short edge outage: no wait starts that would end past five minutes, so a step ends\n * within the budget plus one request timeout. */\n static readonly FILING = new RetryPolicy([250, 500, 1_000, 2_000, 4_000, 8_000, 16_000, 30_000], sleep, 300_000);\n static readonly TRANSIENT_STATUSES: ReadonlySet<number> = new Set([502, 503, 504]);\n\n constructor(\n readonly delaysMs: readonly number[],\n private readonly wait: (ms: number) => Promise<void> = sleep,\n readonly budgetMs: number = Number.POSITIVE_INFINITY,\n private readonly now: () => number = Date.now,\n ) {}\n\n async run(attempt: () => Promise<PlatformReply>): Promise<PlatformReply> {\n const started = this.now();\n for (let tries = 0; ; tries += 1) {\n const outcome = await Attempt.of(attempt);\n const delayMs = this.delaysMs[tries];\n const spent = delayMs === undefined || this.now() - started + delayMs >= this.budgetMs;\n if (!outcome.transient || spent) return outcome.settle();\n await this.wait(delayMs);\n }\n }\n}\n\nclass Attempt {\n private constructor(\n private readonly reply: PlatformReply | null,\n private readonly error: unknown,\n readonly transient: boolean,\n ) {}\n\n static async of(attempt: () => Promise<PlatformReply>): Promise<Attempt> {\n try {\n const reply = await attempt();\n return new Attempt(reply, null, RetryPolicy.TRANSIENT_STATUSES.has(reply.status));\n } catch (error) {\n return new Attempt(null, error, error instanceof UnreachableError);\n }\n }\n\n settle(): PlatformReply {\n if (this.reply) return this.reply;\n throw this.error;\n }\n}\n\n/** How long an open event stream may stay silent (no event and no keepalive) before it counts as dropped. */\nexport const PLATFORM_STREAM_IDLE_MS = 60_000;\n\nexport type PlatformStreamOptions = { after?: string | null; signal?: AbortSignal; idleMs?: number };\n\nconst REFUSAL_TEXT_LIMIT = 64 * 1024;\n\n// No route the SDK calls redirects: a 3xx is answered as the refusal it is, so the key never rides a hop to any host, whatever the runtime's fetch does with Authorization.\nconst KEYED_REDIRECTS: RequestRedirect = \"manual\";\n\nexport function platformAuthorization(endpoint: PlatformEndpoint, url: string): Record<string, string> {\n const { token } = endpoint;\n if (!token)\n return { authorization: \"Basic \" + Buffer.from(`${endpoint.publicKey}:${endpoint.secretKey}`).toString(\"base64\") };\n if (endpoint.publicKey || endpoint.secretKey) throw new PersonalTokenRefused(TOKEN_BESIDE_KEYS);\n if (!url.startsWith(`${token.host}/`)) throw new PersonalTokenRefused(TOKEN_OTHER_HOST);\n return { authorization: `Bearer ${token.value}`, \"x-gateway-project\": token.project };\n}\n\n/** The one door every CLI and SDK request to the platform goes through: Basic auth with the project key, a per-request timeout, and a transport failure turned into an `UnreachableError`. */\nexport class PlatformTransport {\n readonly #endpoint: PlatformEndpoint;\n readonly #timeoutMs: number;\n\n constructor(endpoint: PlatformEndpoint, timeoutMs: number = platformTimeoutMs()) {\n this.#endpoint = endpoint;\n this.#timeoutMs = timeoutMs;\n }\n\n /** A request that legitimately takes longer (a sandbox exec, a world create) waits its own budget; every other one waits the default. */\n budget(ownMs?: number): number {\n return Math.max(ownMs ?? 0, this.#timeoutMs);\n }\n\n /** One request; the caller's `signal` aborts it in flight and throws the signal's reason, never an `UnreachableError`. */\n async send(\n method: PlatformMethod,\n route: string,\n body?: unknown,\n opts: PlatformSendOptions = {},\n ): Promise<PlatformReply> {\n const timeoutMs = this.budget(opts.timeoutMs);\n return (opts.retry ?? RetryPolicy.NONE).run(() => this.once(method, route, body, timeoutMs, opts.signal));\n }\n\n /** `send`, then the 2xx body as JSON; any other answer throws `ApiError` with its status and stable `code`. */\n async json<T>(method: PlatformMethod, route: string, body?: unknown, opts: PlatformSendOptions = {}): Promise<T> {\n const reply = await this.send(method, route, body, opts);\n if (!reply.ok) throw new ApiError(reply.status, method, route, reply.text);\n return JSON.parse(reply.text) as T;\n }\n\n /** The streaming twin of `send` for a `GET` event stream: nothing is buffered, `after` travels as `Last-Event-ID`, and each wait for the platform (the headers, every chunk) may last `idleMs` (default 60 s) instead of the request budget. */\n async stream(route: string, opts: PlatformStreamOptions = {}): Promise<PlatformStream> {\n const watch = new StreamWatch(opts.signal, opts.idleMs ?? PLATFORM_STREAM_IDLE_MS, this.#endpoint.host, route);\n const headers = this.headers(route, \"text/event-stream\", opts.after ? { \"last-event-id\": opts.after } : {});\n try {\n const response = await watch.within(() =>\n fetch(this.url(route), { method: \"GET\", headers, signal: watch.signal, redirect: KEYED_REDIRECTS }),\n );\n return new PlatformStream(response, watch);\n } catch (error) {\n watch.close();\n throw error;\n }\n }\n\n private url(route: string): string {\n return `${this.#endpoint.host}${route}`;\n }\n\n private headers(route: string, accept: string, extra: Record<string, string> = {}): Record<string, string> {\n return {\n \"content-type\": \"application/json\",\n accept,\n ...platformAuthorization(this.#endpoint, this.url(route)),\n ...extra,\n };\n }\n\n private async once(\n method: PlatformMethod,\n route: string,\n body: unknown,\n timeoutMs: number,\n caller?: AbortSignal,\n ): Promise<PlatformReply> {\n if (caller?.aborted) throw caller.reason;\n const payload = body === undefined ? {} : { body: JSON.stringify(body) };\n const headers = this.headers(route, \"application/json\");\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n const relay = (): void => controller.abort(caller?.reason);\n caller?.addEventListener(\"abort\", relay, { once: true });\n try {\n const res = await fetch(this.url(route), {\n method,\n headers,\n ...payload,\n signal: controller.signal,\n redirect: KEYED_REDIRECTS,\n });\n return { status: res.status, ok: res.ok, text: await res.text() };\n } catch (error) {\n if (caller?.aborted) throw caller.reason;\n const cause = controller.signal.aborted ? TransportCause.timeout(timeoutMs) : TransportCause.of(error);\n throw new UnreachableError(this.#endpoint.host, method, route, cause);\n } finally {\n clearTimeout(timer);\n caller?.removeEventListener(\"abort\", relay);\n }\n }\n}\n\nclass StreamWatch {\n readonly #controller = new AbortController();\n readonly #caller: AbortSignal | undefined;\n readonly #relay = (): void => this.#controller.abort(this.#caller?.reason);\n #idled = false;\n\n constructor(\n caller: AbortSignal | undefined,\n readonly idleMs: number,\n private readonly host: string,\n private readonly route: string,\n ) {\n this.#caller = caller;\n caller?.addEventListener(\"abort\", this.#relay, { once: true });\n if (caller?.aborted) this.#relay();\n }\n\n get signal(): AbortSignal {\n return this.#controller.signal;\n }\n\n async within<T>(wait: () => Promise<T>): Promise<T> {\n const timer = setTimeout(() => this.idle(), this.idleMs);\n try {\n return await wait();\n } catch (error) {\n throw this.failure(error);\n } finally {\n clearTimeout(timer);\n }\n }\n\n close(): void {\n this.#caller?.removeEventListener(\"abort\", this.#relay);\n this.#controller.abort();\n }\n\n private idle(): void {\n this.#idled = true;\n this.#controller.abort();\n }\n\n private failure(error: unknown): unknown {\n if (this.#caller?.aborted) return this.#caller.reason;\n const cause = this.#idled ? TransportCause.idle(this.idleMs) : TransportCause.of(error);\n return new UnreachableError(this.host, \"GET\", this.route, cause);\n }\n}\n\n/** An open event stream: its status, then its body as it arrives. A silence past the idle budget or a dropped connection throws `UnreachableError`; the caller's abort throws its reason. */\nexport class PlatformStream {\n readonly #response: Response;\n readonly #watch: StreamWatch;\n\n constructor(response: Response, watch: StreamWatch) {\n this.#response = response;\n this.#watch = watch;\n }\n\n get status(): number {\n return this.#response.status;\n }\n\n get ok(): boolean {\n return this.#response.ok;\n }\n\n /** The body as text, for a refusal: at most the first 64 KiB of characters; closes the stream. */\n async text(): Promise<string> {\n const decoder = new TextDecoder();\n let text = \"\";\n for await (const chunk of this.chunks()) {\n text += decoder.decode(chunk, { stream: true });\n if (text.length >= REFUSAL_TEXT_LIMIT) return text.slice(0, REFUSAL_TEXT_LIMIT);\n }\n return text + decoder.decode();\n }\n\n /** The body's bytes as they arrive; the idle budget runs only while waiting for the platform, never while the caller holds a chunk. */\n async *chunks(): AsyncGenerator<Uint8Array, void, undefined> {\n const reader = this.#response.body?.getReader();\n try {\n for (;;) {\n const next = reader ? await this.#watch.within(() => reader.read()) : { done: true as const };\n if (next.done) return;\n yield next.value;\n }\n } finally {\n this.close();\n }\n }\n\n close(): void {\n this.#watch.close();\n }\n}\n","export const SECRET_KEY =\n /pass(word|wd|code|phrase)|pass(?![a-z])|secret|token(?!s)|(api|private)[-_ ]?key|authorization|cookie|one[-_ ]?time[-_ ]?(code|password)|(verification|security|recovery|backup)[-_ ]?codes?|security[-_ ]?answers?|social[-_ ]?security|(card|account|routing)[-_ ]?(number|no\\b)|cc-(number|csc|exp)|(^|[-_ #.\\[\"'=(])(otp|totp|mfa|2fa|pin|cvv|cvc|ssn|iban)([-_ \\]\"'):.,*]|$)/i;\n\nexport const DESCRIBE_FIELD_JS =\n \"(e) => { if (!e) return '';\" +\n \" if (e.tagName === 'IFRAME' || e.tagName === 'FRAME') return 'frame';\" +\n \" const root = e.getRootNode();\" +\n \" const byIds = (at) => (at.getAttribute('aria-labelledby') || '').split(/\\\\s+/)\" +\n \".map((id) => (id && root.getElementById ? root.getElementById(id) : null))\" +\n \".map((label) => (label ? label.textContent : '')).join(' ');\" +\n \" const labels = e.labels ? [...e.labels].map((label) => label.textContent) : [];\" +\n \" const context = [];\" +\n \" for (let at = e.parentElement; at; at = at.parentElement) {\" +\n \" const legend = at.tagName === 'FIELDSET' ? at.querySelector('legend') : null;\" +\n \" context.push(at.getAttribute('aria-label'), byIds(at), legend ? legend.textContent : ''); }\" +\n \" const names = [e.getAttribute('aria-label'), byIds(e), ...labels, e.getAttribute('placeholder'),\" +\n \" e.getAttribute('title'), ...context];\" +\n \" if (e.tagName === 'SELECT') return ['select', e.name, e.id, ...names].filter(Boolean).join(' ');\" +\n \" if (!(e.tagName === 'INPUT' || e.tagName === 'TEXTAREA' || e.isContentEditable)) return 'opaque';\" +\n \" return [e.type, e.name, e.id, e.getAttribute('autocomplete'), ...names].filter(Boolean).join(' '); }\";\n\nexport const FIELD_VALUE_JS =\n \"(e) => { if (e.tagName === 'SELECT') return [...e.selectedOptions].map((o) => o.text).join('\\\\n');\" +\n \" if (e.tagName === 'INPUT' || e.tagName === 'TEXTAREA') return e.value;\" +\n \" return e.isContentEditable ? e.innerText : null; }\";\n\nexport const FIELDS =\n \"input:not([type=button]):not([type=submit]):not([type=reset]):not([type=image]):not([type=checkbox])\" +\n \":not([type=radio]):not([type=file]), textarea, select, [contenteditable]:not([contenteditable=false])\";\n\nconst SHORTEST_WITHHELD = 4;\nconst WITHHELD_TEXT = \"[redacted]\";\nconst SPACES = /[ \\t\\n\\r\\f\\v]+/g;\nconst LINE_BREAK = /\\r\\n|\\r|\\n/;\nconst TRIM = /^[ \\t\\n\\r\\f\\v]+|[ \\t\\n\\r\\f\\v]+$/g;\n\n// Playwright's JS client runs a string pageFunction as an expression and never calls it with the\n// element, so a locator gets the probe as a function built from the one shared source.\nexport const describeField = new Function(\n \"e\",\n `return (${DESCRIBE_FIELD_JS})(e);`,\n) as (element: unknown) => string;\n\n// Like `describeField`: what a field holds, and each field's description with it.\nexport const readFieldValue = new Function(\n \"e\",\n `return (${FIELD_VALUE_JS})(e);`,\n) as (element: unknown) => string | null;\n\nexport const readEditables = new Function(\n \"elements\",\n `return elements.map((e) => [(${DESCRIBE_FIELD_JS})(e), (${FIELD_VALUE_JS})(e)]);`,\n) as (elements: unknown[]) => [string, string | null][];\n\nexport const UNREADABLE = \"unreadable\";\nconst SECRET_FIELD = [\"password\", \"frame\", \"opaque\", UNREADABLE];\nconst NOT_TEXT = [\"opaque\", \"frame\", \"select\"];\n\n/** Whether a field `DESCRIBE_FIELD_JS` described takes a credential: a\n * password input, one whose attributes, label or placeholder name a token,\n * key, PIN, one-time code or card, or anything that is not a text field or a\n * select (its text is withheld). Runs of whitespace count as one space, so a\n * label on its own line reads as its words. Twin of\n * `credential_field.is_credential_field`. */\nexport function isCredentialField(described: string): boolean {\n const words = described.replace(SPACES, \" \").replace(/^ | $/g, \"\");\n return (\n SECRET_FIELD.some((prefix) => words.startsWith(prefix)) ||\n SECRET_KEY.test(words)\n );\n}\n\n/** What each field `readEditables` read (an input, textarea, select or\n * contenteditable) holds, when it takes a credential. Twin of\n * `credential_field.credential_texts`. */\nexport function credentialTexts(\n pairs: readonly (readonly [unknown, unknown])[],\n): string[] {\n return pairs\n .filter(([, text]) => text !== null && text !== undefined)\n .filter(([described]) => isCredentialField(String(described)))\n .map(([, text]) => String(text));\n}\n\n/** Whether `DESCRIBE_FIELD_JS` described something that holds typed text: an\n * input, a textarea or a contenteditable. One that could not be read counts.\n * Twin of `credential_field.is_text_field`. */\nexport function isTextField(described: string): boolean {\n return (\n described !== \"\" && !NOT_TEXT.some((prefix) => described.startsWith(prefix))\n );\n}\n\nconst escapeRegExp = (text: string) =>\n text.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\nconst urlForms = (text: string): string[] => {\n let component: string;\n try {\n component = encodeURIComponent(text);\n } catch {\n return [];\n }\n const form = component\n .replace(\n /[!'()~]/g,\n (c) => \"%\" + c.charCodeAt(0).toString(16).toUpperCase(),\n )\n .replace(/%20/g, \"+\");\n return [component, component.replace(/%20/g, \"+\"), form];\n};\n\nconst forms = (text: string): string[] => {\n const written = [\n text,\n text.replace(SPACES, \" \"),\n JSON.stringify(text).slice(1, -1),\n ];\n return [\n ...written,\n ...written.map((form) => form.replaceAll(\"'\", \"''\")),\n ...urlForms(text),\n ];\n};\n\n/** Credentials that must not show in page text, a snapshot, a URL or an\n * event: field values, what credential fields hold, and text typed into\n * credential fields. Each of at least `SHORTEST_WITHHELD` code points, whole\n * and line by line, is withheld as written, with its whitespace collapsed (as\n * a snapshot names it), JSON-escaped and with `'` doubled (as a snapshot\n * quotes it), and as a URL carries it (`encodeURIComponent` and form\n * encoding), wherever it does not touch a letter or digit. A shorter secret is\n * withheld only on its own field's line and in its event, so a one-digit code\n * box does not blank every digit. Twin of `credential_field.CredentialText`. */\nexport class CredentialText {\n private readonly pattern: RegExp | null;\n\n constructor(secrets: readonly string[]) {\n const texts = secrets.map((secret) => String(secret).replace(TRIM, \"\"));\n const lines = texts.flatMap((text) =>\n text.split(LINE_BREAK).map((line) => line.replace(TRIM, \"\")),\n );\n const whole = new Set(\n [...texts, ...lines].filter(\n (text) => [...text].length >= SHORTEST_WITHHELD,\n ),\n );\n const withheld = [\n ...new Set([...whole].flatMap((text) => forms(text))),\n ].sort((a, b) => b.length - a.length);\n this.pattern =\n withheld.length === 0\n ? null\n : new RegExp(\n `(?<![A-Za-z0-9])(?:${withheld.map(escapeRegExp).join(\"|\")})(?![A-Za-z0-9])`,\n \"g\",\n );\n }\n\n withhold(text: string): string {\n return this.pattern === null\n ? text\n : text.replace(this.pattern, WITHHELD_TEXT);\n }\n}\n\nconst EVENT_MAX_STRING = 500;\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/** What of an action's arguments may leave the process. Selectors, paths and\n * keys are what a reviewer needs; anything keyed like a credential, or typed\n * into a field whose selector names one, or shaped like a known key, is\n * replaced. Strings are capped, nested values dropped. Twin of\n * `credential_field.redact_action_args`. */\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 return Object.fromEntries(\n Object.entries(args).map(([key, value]) => [\n key,\n redactedArg(key, value, secretField),\n ]),\n );\n}\n\nfunction redactedArg(\n key: string,\n value: unknown,\n secretField: boolean,\n): unknown {\n if (value === null || value === undefined) return null;\n if (typeof value === \"boolean\" || typeof value === \"number\") return value;\n if (typeof value !== \"string\") return \"[omitted]\";\n if (\n SECRET_KEY.test(key) ||\n SECRET_VALUE.test(value) ||\n (secretField && key === \"text\")\n )\n return \"[redacted]\";\n return value.length <= EVENT_MAX_STRING\n ? value\n : value.slice(0, EVENT_MAX_STRING) + \"…\";\n}\n","import type { BrowserPage, PlaywrightBrowserLike } from \"./browser\";\n\n/**\n * A HOSTED BROWSER THAT COMES BACK. A World Host session's browser is a pool\n * pod; on the `standard` tier it runs on spot capacity and can be reclaimed\n * with two minutes' notice. The browser dies, the world does not, and the\n * platform can put a new browser behind the SAME `surfaces.browser.wsUrl`.\n *\n * `BrowserReconnector` is the client half of that repair: on a lost\n * connection it asks the platform to repair (`POST .../browser-repair`),\n * waits while a browser starts, reconnects to the same address and hands the\n * new connection to its owner to restore the page. It knows nothing of HTTP\n * or Playwright — both come in as collaborators, so tests drive it with\n * fakes. Twin of `gatewaysdk/world_browser_reconnect.py`, call for call.\n */\n\n/** What the platform answers a repair with. `healthy`: the browser is alive,\n * reconnect now. `replaced`: a new, blank browser; reconnect and reopen the\n * page. `starting`: a browser is coming up; ask again in `retryAfterMs`. */\nexport type RepairAnswer = {\n outcome: \"healthy\" | \"replaced\" | \"starting\";\n retryAfterMs: number | null;\n};\n\ntype BrowserContextLike = Awaited<\n ReturnType<PlaywrightBrowserLike[\"newContext\"]>\n>;\n\n/** One live attachment to the session's browser. */\nexport type BrowserConnection = {\n browser: PlaywrightBrowserLike;\n context: BrowserContextLike;\n page: BrowserPage;\n};\n\nexport async function closeConnection(c: BrowserConnection): Promise<void> {\n await c.context.close();\n await c.browser.close();\n}\n\n/** Close a connection whose browser is already gone: it only frees the\n * handle, so a failure is ignored. */\nexport async function releaseConnection(c: BrowserConnection): Promise<void> {\n await closeConnection(c).catch(() => undefined);\n}\n\nexport const RECOVER_BUDGET_MS = 90_000;\nconst BACKOFF_BASE_MS = 1_000;\nconst BACKOFF_CAP_MS = 5_000;\n\n/** What Playwright says when the browser or its connection is gone, as\n * opposed to an action that failed on a live page. Matched case-insensitively\n * against the error message; nothing else triggers a reconnect. */\nexport const BROWSER_GONE_PATTERNS: readonly RegExp[] = [\n /target page, context or browser has been closed/i,\n /\\bbrowser has been (closed|disconnected)\\b/i,\n /\\bbrowser (has )?disconnected\\b/i,\n /\\btarget closed\\b/i,\n /\\bwebsocket is not open\\b/i,\n /\\bconnection closed\\b/i,\n];\n\n/** A failed page load (`net::ERR_INTERNET_DISCONNECTED`,\n * `net::ERR_CONNECTION_CLOSED`) is the world UI's network, not the browser:\n * the browser is alive, and repairing it would throw away a live page. */\nconst PAGE_NETWORK_ERROR = /net::ERR_/i;\n\nexport function isBrowserGone(error: unknown): boolean {\n const message = error instanceof Error ? error.message : String(error);\n if (PAGE_NETWORK_ERROR.test(message)) return false;\n return BROWSER_GONE_PATTERNS.some((p) => p.test(message));\n}\n\nconst REDACTED = \"<redacted>\";\nconst TOKEN_QUERY_VALUE = /([?&]token=)[^&#\\s\"')]*/gi;\n\n/**\n * Takes a session's credentials out of text that leaves the process — an\n * error recorded into the browser timeline, a recovery's reason. A browser\n * error quotes the URL it failed on, and those URLs carry the session: the\n * hosted browser's `wsUrl` (its path is the credential), the UI's token, and\n * any `?token=` a landing URL presents. Each becomes `<redacted>`.\n */\nexport class SecretScrubber {\n private readonly secrets: string[];\n\n constructor(secrets: readonly (string | null | undefined)[]) {\n const known = secrets.filter((s): s is string => Boolean(s));\n // Longest first, so a wsUrl goes whole before a token inside it.\n this.secrets = [\n ...new Set([...known, ...known.map((s) => encodeURIComponent(s))]),\n ].sort((a, b) => b.length - a.length);\n }\n\n scrub(text: string): string {\n const bare = this.secrets.reduce(\n (out, secret) => out.split(secret).join(REDACTED),\n text,\n );\n return bare.replace(TOKEN_QUERY_VALUE, `$1${REDACTED}`);\n }\n\n /** Scrub `error` and the errors it was raised from, in place: the message,\n * the stack and every other own text property, Playwright's `log` call log\n * included. */\n scrubError(error: unknown): void {\n scrubError(error, (text) => this.scrub(text));\n }\n}\n\n/** Apply `scrub` to `error` and the errors it was raised from, in place: the\n * message, the stack and every other own text property, Playwright's `log`\n * call log included. Twin of `world_browser_reconnect.scrub_error`. */\nexport function scrubError(\n error: unknown,\n scrub: (text: string) => string,\n): void {\n const seen = new Set<unknown>();\n let at = error;\n while (at instanceof Error && !seen.has(at)) {\n seen.add(at);\n at.message = scrub(at.message);\n at.stack = at.stack && scrub(at.stack);\n scrubOwnText(at as unknown as Record<string, unknown>, scrub);\n at = at.cause;\n }\n}\n\nfunction scrubOwnText(\n error: Record<string, unknown>,\n scrub: (text: string) => string,\n): void {\n for (const key of Object.keys(error)) {\n const value = error[key];\n if (typeof value === \"string\") error[key] = scrub(value);\n if (Array.isArray(value) && value.every((item) => typeof item === \"string\"))\n error[key] = value.map((item: string) => scrub(item));\n }\n}\n\n/** A mutating action (click, type, press, back, scroll) lost its browser.\n * The browser was repaired and the page reopened at `restoredUrl`, but the\n * action is NOT replayed: its input may already have reached the world.\n * `cause` is the error the action failed with. */\nexport class BrowserReconnected extends Error {\n constructor(\n readonly outcome: RecoveryResult[\"outcome\"],\n readonly restoredUrl: string | null,\n cause: unknown,\n ) {\n super(\n `the browser was lost mid-action and reconnected (${outcome}); ` +\n (restoredUrl\n ? `the page was reopened at ${restoredUrl}. `\n : \"it is on a blank page. \") +\n \"The action may or may not have taken effect — look at the page before acting again.\",\n { cause },\n );\n this.name = \"BrowserReconnected\";\n }\n}\n\n/** The session's browser stayed gone for the whole budget. `cause` is the\n * error the action first failed with. */\nexport class BrowserUnrecoverable extends Error {\n constructor(message: string, cause: unknown) {\n super(message, { cause });\n this.name = \"BrowserUnrecoverable\";\n }\n}\n\n/** A repair refusal worth waiting out: no answer at all (the network), the\n * platform's own failure, or a full pool. Anything else (a 404 for a session\n * that is not open with a browser) ends the recovery. */\nfunction refusalIsTransient(error: unknown): boolean {\n const { status, code } = error as { status?: unknown; code?: unknown };\n if (typeof status !== \"number\") return true;\n if (status >= 500) return true;\n return status === 400 && code === \"browser_capacity\";\n}\n\nfunction describe(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\ntype Step =\n | { kind: \"recovered\"; outcome: RecoveryResult[\"outcome\"] }\n | { kind: \"stop\" }\n | { kind: \"wait\"; reason: string; waitMs: number | null };\n\nexport type RecoveryResult = {\n outcome: \"healthy\" | \"replaced\";\n attempts: number;\n};\n\nexport class BrowserReconnector {\n private readonly sleep: (ms: number) => Promise<void>;\n private readonly now: () => number;\n private readonly scrub: (text: string) => string;\n readonly budgetMs: number;\n\n constructor(\n private readonly repair: () => Promise<RepairAnswer>,\n private readonly connect: () => Promise<BrowserConnection>,\n opts: {\n sleep?: (ms: number) => Promise<void>;\n now?: () => number;\n budgetMs?: number;\n /** Takes credentials out of a reason before it is thrown. */\n scrub?: (text: string) => string;\n } = {},\n ) {\n this.sleep =\n opts.sleep ?? ((ms) => new Promise<void>((r) => setTimeout(r, ms)));\n this.now = opts.now ?? Date.now;\n this.budgetMs = opts.budgetMs ?? RECOVER_BUDGET_MS;\n this.scrub = opts.scrub ?? ((text) => text);\n }\n\n /**\n * Repair, reconnect and `restore` until it works or the budget runs out.\n * `restore` receives each new connection (the owner adopts it and reopens\n * its page); a restore that fails counts as a failed reconnect, because the\n * browser may have died again. A repair the platform refuses for good\n * rethrows `cause` untouched.\n */\n async recover(\n cause: unknown,\n restore: (connection: BrowserConnection) => Promise<void>,\n ): Promise<RecoveryResult> {\n const deadline = this.now() + this.budgetMs;\n let reason = describe(cause);\n for (let attempt = 1; ; attempt++) {\n const step = await this.attempt(restore);\n if (step.kind === \"recovered\")\n return { outcome: step.outcome, attempts: attempt };\n if (step.kind === \"stop\") throw cause;\n reason = step.reason;\n const remaining = deadline - this.now();\n if (remaining <= 0) break;\n const backoff = Math.min(\n BACKOFF_BASE_MS * 2 ** (attempt - 1),\n BACKOFF_CAP_MS,\n );\n await this.sleep(Math.min(step.waitMs ?? backoff, remaining));\n }\n throw new BrowserUnrecoverable(\n `the session's browser could not be recovered within ${Math.round(this.budgetMs / 1000)}s: ${this.scrub(reason)}`,\n cause,\n );\n }\n\n private async attempt(\n restore: (connection: BrowserConnection) => Promise<void>,\n ): Promise<Step> {\n let answer: RepairAnswer;\n try {\n answer = await this.repair();\n } catch (error) {\n if (!refusalIsTransient(error)) return { kind: \"stop\" };\n return {\n kind: \"wait\",\n reason: `repair failed: ${describe(error)}`,\n waitMs: null,\n };\n }\n const outcome = answer.outcome;\n if (outcome === \"starting\")\n return {\n kind: \"wait\",\n reason: \"a new browser is still starting\",\n waitMs: answer.retryAfterMs,\n };\n try {\n await restore(await this.connect());\n } catch (error) {\n return {\n kind: \"wait\",\n reason: `reconnect failed: ${describe(error)}`,\n waitMs: null,\n };\n }\n return { kind: \"recovered\", outcome };\n }\n}\n","import {\n CredentialText,\n FIELDS,\n SECRET_KEY,\n UNREADABLE,\n credentialTexts,\n readEditables,\n readFieldValue,\n describeField,\n isCredentialField,\n redactActionArgs,\n} from \"./credentialField\";\nimport {\n BrowserReconnected,\n BrowserReconnector,\n SecretScrubber,\n closeConnection,\n isBrowserGone,\n scrubError,\n releaseConnection,\n type BrowserConnection,\n type RecoveryResult,\n type RepairAnswer,\n} from \"./browserReconnect\";\n\n/**\n * A BROWSER ON A WORLD'S UI — the computer-use half of a live session.\n *\n * A session answers on SURFACES. `tools` is always there (the world's own\n * operations over the rendezvous). An api-type world may also answer on\n * `api` (the service itself), `ui` (its dashboard, over the same state) and\n * `browser` — a headless Chromium the platform runs NEXT TO that UI, which\n * an agent drives through Playwright. This file is the TS client for the\n * last two, call for call with `gatewaysdk/world_browser.py`.\n *\n * const s = await openSession(\"payments-like\", \"refund-dispute\", {\n * surfaces: [\"ui\", \"browser\"],\n * });\n * await s.ready();\n * const b = await s.browser(); // hosted, next to the world\n * await b.goto(); // the UI's entry page\n * await b.click(\"text=Refund\");\n * const tools = computerUseToolkit(b); // the same actions as model tools\n * await b.close();\n *\n * Playwright is an OPTIONAL peer: nothing here imports it until a browser is\n * opened, so sessions that never touch a UI never load it.\n *\n * MODES. `hosted` connects to the session's own browser (a Playwright server\n * the pod exposes over an authenticated websocket). `local` launches Chromium\n * on this machine and points it at the UI — a laptop against a hosted twin,\n * or a test. `auto` prefers hosted. Asking for a mode the session cannot\n * serve throws `WorldSurfaceUnavailable`; there is no silent fallback to a\n * browser other than the one the episode is judged on.\n *\n * OBSERVABILITY. Every action a `WorldBrowser` takes (goto, click, type,\n * press, scroll, back) is reported to the platform as one event — what was\n * done, whether it worked, where the page ended up, and a JPEG of the screen\n * after — through a `BrowserActionRecorder`. Reporting is fire-and-forget\n * and never fails the action; the platform renders it as the session's\n * browser timeline. Text typed into secret-looking fields is redacted before\n * it leaves the process.\n *\n * RECONNECT. A World Host browser on the `standard` tier can be reclaimed\n * mid-session. When an action fails because the browser or its connection is\n * gone, a hosted `cdp` browser asks the platform to repair it, reconnects to\n * the same address and reopens the page it was on (see `browserReconnect.ts`).\n * A read or a `goto` then runs once more; a click, type, press, back or scroll\n * is NOT replayed — its input may already have reached the world — and throws\n * `BrowserReconnected` so the agent looks at the page again. Local and\n * `playwright`-protocol browsers never reconnect.\n */\n\nexport const SURFACE_KINDS = [\"tools\", \"api\", \"ui\", \"browser\"] as const;\nexport type WorldSurfaceKind = (typeof SURFACE_KINDS)[number];\n\nexport { SECRET_KEY, redactActionArgs };\nconst FIELD_PROBE_TIMEOUT_MS = 2_000;\n\n/** The platform's own header for a session's token, which a World Host takes on\n * every world whatever its vendor's auth; no vendor's client sends it. */\nexport const PLATFORM_SESSION_HEADER = \"X-World-Session\";\n\nexport const SESSION_AUTH_MODES = [\"vendor\", \"open\"] as const;\n/** `open`: the session asks for no credential, reached on its capability\n * hostname alone; `vendor`: the session's token, the way the world's `[auth]`\n * says its vendor takes a key. Unset, the world's `[auth] mode`. */\nexport type SessionAuthMode = (typeof SESSION_AUTH_MODES)[number];\n\nexport function assertSessionAuthMode(value: unknown): asserts value is SessionAuthMode {\n if ((SESSION_AUTH_MODES as readonly unknown[]).includes(value)) return;\n throw new Error(\n `Unknown session auth: ${String(value)}; choose from ${SESSION_AUTH_MODES.join(\", \")}`,\n );\n}\n\n/** Capacity behind a World Host session's browser. `standard` runs on spot\n * capacity first (about half the price) and may be reclaimed with two\n * minutes' notice, ending the browser but never the world; `premium` is\n * on-demand and never spot-reclaimed. Unset, the organization's default applies. */\nexport const BROWSER_TIERS = [\"standard\", \"premium\"] as const;\nexport type BrowserTier = (typeof BROWSER_TIERS)[number];\n\n/** Refuse a tier the platform does not know, before any request is sent. */\nexport function assertBrowserTier(value: unknown): asserts value is BrowserTier {\n if ((BROWSER_TIERS as readonly unknown[]).includes(value)) return;\n throw new Error(\n `Unknown browser tier: ${String(value)}; choose from ${BROWSER_TIERS.join(\", \")}`,\n );\n}\n\nexport const DEFAULT_VIEWPORT = { width: 1280, height: 800 };\nconst SETTLE_TIMEOUT_MS = 5_000;\nconst SETTLE_QUIET_MS = 150;\nconst SETTLE_POLL_MS = 25;\n\nexport const EVENT_BATCH_SIZE = 10;\nexport const EVENT_FLUSH_INTERVAL_MS = 1_000;\nexport const EVENT_MAX_RETRIES = 3;\nconst EVENT_SCREENSHOT_QUALITY = 60;\n\n/** What a call that lost its browser does once the browser is back: a read or\n * a navigation runs again (`retry`); an action that may already have reached\n * the world is not replayed, and the agent is told (`report`). */\ntype OnBrowserLoss = \"retry\" | \"report\";\n\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 in the\n * platform's `X-World-Session` header (`apiHeaders()`), or the way the\n * world's `[auth]` says its vendor takes a key. Absent when the world\n * itself answers with its declared auth (a pod or a customer-hosted twin),\n * and for an open session, whose url is its secret. */\n token?: string;\n /** `open`: `url` is the session's capability hostname; send no credential. */\n auth?: \"open\";\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 and\n * open sessions. */\n token?: string;\n auth?: \"open\";\n };\n browser?: {\n wsUrl: string;\n /** `cdp`: the platform's Chromium relay (any number of agents share one\n * browser, each in its own context). `playwright`: a `run-server` endpoint. */\n protocol: \"cdp\" | \"playwright\";\n viewport: { width: number; height: number };\n /** The capacity tier the browser runs on; present for World Host sessions. */\n tier?: BrowserTier;\n };\n};\n\nexport class WorldSurfaceUnavailable extends Error {\n constructor(\n readonly surface: WorldSurfaceKind,\n reason: string,\n ) {\n super(`World surface '${surface}' is unavailable: ${reason}`);\n }\n}\n\nexport function surfaceKinds(s: SessionSurfaces): WorldSurfaceKind[] {\n const kinds: WorldSurfaceKind[] = [\"tools\"];\n if (s.api) kinds.push(\"api\");\n if (s.ui) kinds.push(\"ui\");\n if (s.browser) kinds.push(\"browser\");\n return kinds;\n}\n\nconst UI_TOKEN_QUERY = \"token\";\n\n/** The URL of `path` on a UI surface, carrying the session token when the\n * surface has one. `path` may already have a query string; the token is\n * appended to it. */\nexport function uiUrl(\n ui: NonNullable<SessionSurfaces[\"ui\"]>,\n path: string,\n): string {\n const base = ui.url.replace(/\\/+$/, \"\");\n const rel = path.startsWith(\"/\") ? path : `/${path}`;\n if (!ui.token) return base + rel;\n const [beforeHash, hash] = splitHash(rel);\n const joiner = beforeHash.includes(\"?\") ? \"&\" : \"?\";\n const query = `${UI_TOKEN_QUERY}=${encodeURIComponent(ui.token)}`;\n return base + beforeHash + joiner + query + hash;\n}\n\nexport function uiEntryUrl(ui: NonNullable<SessionSurfaces[\"ui\"]>): string {\n return uiUrl(ui, ui.entry || \"/\");\n}\n\n/** `url` without its `token` query parameter: what may be logged or shown. */\nexport function withoutUiToken(url: string): string {\n const [beforeHash, hash] = splitHash(url);\n const q = beforeHash.indexOf(\"?\");\n if (q < 0) return url;\n const kept = beforeHash\n .slice(q + 1)\n .split(\"&\")\n .filter((pair) => pair !== \"\" && pair.split(\"=\")[0] !== UI_TOKEN_QUERY);\n return (\n beforeHash.slice(0, q) + (kept.length ? `?${kept.join(\"&\")}` : \"\") + hash\n );\n}\n\nfunction splitHash(url: string): [string, string] {\n const h = url.indexOf(\"#\");\n return h < 0 ? [url, \"\"] : [url.slice(0, h), url.slice(h)];\n}\n\n/** The slice of a Playwright `Page` this module drives. */\nexport type BrowserPage = {\n url(): string;\n goto(url: string, opts?: { waitUntil?: \"load\" }): Promise<unknown>;\n click(selector: string, opts?: { timeout?: number }): Promise<void>;\n fill(\n selector: string,\n value: string,\n opts?: { timeout?: number },\n ): 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 ariaSnapshot?(opts: { mode: \"ai\" }): Promise<string>;\n locator(selector: string): {\n click(opts: { trial: true }): Promise<void>;\n evaluateAll(\n pageFunction: (elements: unknown[]) => unknown,\n ): Promise<unknown>;\n evaluate(\n pageFunction: (element: unknown) => unknown,\n arg?: unknown,\n opts?: { timeout?: number },\n ): Promise<unknown>;\n };\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/** 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. */\nconst CAPABILITY_HOST = /^o-[a-z0-9]+-([a-z2-7]{26})(?:-api)?\\./;\n\n/** The secret label of an open session's capability hostname in `url`\n * (`o-<sid>-<label>[-api].<domain>`), else null: a credential, scrubbed from\n * everything a browser records. Twin of the Python `capability_label`. */\nexport function capabilityLabel(url: string | null | undefined): string | null {\n let host = \"\";\n try {\n host = url ? new URL(url).hostname : \"\";\n } catch {\n return null;\n }\n return CAPABILITY_HOST.exec(host)?.[1] ?? null;\n}\n\n/**\n * Ships browser action events to the platform, off the action's hot path.\n *\n * `post` receives a batch of events (the request body's `events`). Events\n * are numbered here, so ordering survives batching and retries — the\n * platform dedups on `(agentId, seq)`. A batch that keeps failing is dropped\n * with a warning: telemetry must never stall or fail the agent.\n *\n * Numbering is durable across recorders: `nextSeq()` hands out a position\n * within this recorder, and the first send adds the base `resumeFrom`\n * reports — the platform's next free seq for this agent — so an agent id\n * reopened in a later process appends to its timeline instead of colliding\n * with (and being deduplicated against) what it already recorded. The base\n * is fixed once resolved, which keeps retries idempotent.\n */\nexport class BrowserActionRecorder {\n private seq = 0;\n private base: Promise<number> | null = null;\n private queue: BrowserActionEvent[] = [];\n private timer: ReturnType<typeof setTimeout> | null = null;\n private inflight: Promise<void> = Promise.resolve();\n sent = 0;\n dropped = 0;\n\n constructor(\n private readonly post: (events: BrowserActionEvent[]) => Promise<void>,\n readonly agentId: string,\n private readonly opts: {\n /** The platform's next free seq for `agentId`; 0 when not given. */\n resumeFrom?: () => Promise<number>;\n batchSize?: number;\n flushIntervalMs?: number;\n maxRetries?: number;\n sleep?: (ms: number) => Promise<void>;\n warn?: (message: string) => void;\n } = {},\n ) {}\n\n /** This recorder's next position; the wire seq is `resumeFrom() + this`. */\n nextSeq(): number {\n return this.seq++;\n }\n\n private resolveBase(): Promise<number> {\n if (this.base === null) {\n const resolve = this.opts.resumeFrom ?? (async () => 0);\n this.base = resolve().then((n) => {\n if (!Number.isInteger(n) || n < 0)\n throw new Error(\n `browser event base seq must be a non-negative integer, got ${String(n)}`,\n );\n return n;\n });\n // A failed lookup is retried with the batch, not remembered.\n this.base.catch(() => {\n this.base = null;\n });\n }\n return this.base;\n }\n\n record(event: BrowserActionEvent): void {\n this.queue.push(event);\n if (this.queue.length >= (this.opts.batchSize ?? EVENT_BATCH_SIZE)) {\n this.drain();\n } else if (this.timer === null) {\n this.timer = setTimeout(\n () => this.drain(),\n this.opts.flushIntervalMs ?? EVENT_FLUSH_INTERVAL_MS,\n );\n if (typeof this.timer === \"object\" && \"unref\" in this.timer)\n this.timer.unref();\n }\n }\n\n /** Resolve once everything recorded so far has been posted (or dropped). */\n async flush(): Promise<void> {\n this.drain();\n await this.inflight;\n }\n\n async close(): Promise<void> {\n await this.flush();\n }\n\n private drain(): void {\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n if (this.queue.length === 0) return;\n const batch = this.queue;\n this.queue = [];\n this.inflight = this.inflight.then(() => this.send(batch));\n }\n\n private async send(batch: BrowserActionEvent[]): Promise<void> {\n const retries = this.opts.maxRetries ?? EVENT_MAX_RETRIES;\n const sleep =\n this.opts.sleep ??\n ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));\n for (let attempt = 0; attempt < retries; attempt++) {\n try {\n const base = await this.resolveBase();\n await this.post(\n base === 0 ? batch : batch.map((e) => ({ ...e, seq: base + e.seq })),\n );\n this.sent += batch.length;\n return;\n } catch (error) {\n if (attempt + 1 === retries) {\n this.dropped += batch.length;\n (this.opts.warn ?? console.warn)(\n `dropping ${batch.length} browser events after ${attempt + 1} attempts: ${String(error)}`,\n );\n return;\n }\n await sleep(500 * 2 ** attempt);\n }\n }\n }\n}\n\n/**\n * One Playwright page on the session's UI. Thin on purpose — `page` is the\n * real Playwright page for anything this wrapper does not cover.\n */\nexport class WorldBrowser {\n private typed: string[] = [];\n private typedText = new CredentialText([]);\n private current: BrowserPage;\n private inflight = 0;\n private lastNetwork = Date.now();\n /** Where the page last was after an action, token stripped: what a\n * reconnect reopens. Null until the page has left `about:blank`. */\n private lastUrl: string | null = null;\n\n constructor(\n page: BrowserPage,\n readonly ui: SessionSurfaces[\"ui\"] | undefined,\n readonly mode: Exclude<BrowserMode, \"auto\">,\n private readonly teardown: () => Promise<void>,\n readonly viewport: { width: number; height: number } = DEFAULT_VIEWPORT,\n readonly recorder: BrowserActionRecorder | null = null,\n private readonly reconnector: BrowserReconnector | null = null,\n /** Takes session credentials out of every error this browser records. */\n private readonly scrubber: SecretScrubber = new SecretScrubber([\n ui?.token,\n capabilityLabel(ui?.url),\n ]),\n ) {\n this.current = page;\n this.watchNetwork(page);\n }\n\n /** The live Playwright page; a new object after a reconnect. */\n get page(): BrowserPage {\n return this.current;\n }\n\n get agentId(): string | null {\n return this.recorder?.agentId ?? null;\n }\n\n /** `text` with this session's credentials (UI token, browser address) and\n * the credentials typed into it removed. */\n scrub(text: string): string {\n return this.typedText.withhold(this.scrubber.scrub(text));\n }\n\n /** `text` with this session's credentials removed and nothing else\n * changed: for text that is compared and never leaves the process. */\n scrubSession(text: string): string {\n return this.scrubber.scrub(text);\n }\n\n /** Every credential typed into this browser by `type`. */\n get typedCredentials(): string[] {\n return [...this.typed];\n }\n\n private watchNetwork(page: BrowserPage): void {\n page.on(\"request\", () => {\n this.inflight += 1;\n this.lastNetwork = Date.now();\n });\n const done = () => {\n this.inflight = Math.max(0, this.inflight - 1);\n this.lastNetwork = Date.now();\n };\n page.on(\"requestfinished\", done);\n page.on(\"requestfailed\", done);\n }\n\n /** Run `fn` against the page. If it fails because the browser is gone,\n * recover; then `retry` runs it ONCE more and `report` throws\n * `BrowserReconnected` instead of replaying it. Any other error, and a\n * second loss during the retry, propagate unchanged. */\n private async resilient<T>(\n fn: () => Promise<T>,\n onLoss: OnBrowserLoss,\n ): Promise<T> {\n try {\n return this.remember(await fn());\n } catch (error) {\n if (!this.reconnector || !isBrowserGone(error)) throw error;\n const recovered = await this.recover(this.reconnector, error);\n if (onLoss === \"report\")\n throw new BrowserReconnected(\n recovered.outcome,\n recovered.restoredUrl,\n error,\n );\n }\n return this.remember(await fn());\n }\n\n private remember<T>(result: T): T {\n this.lastUrl = this.openedUrl() ?? this.lastUrl;\n return result;\n }\n\n /** The page's URL less its token; null while it is blank. */\n private openedUrl(): string | null {\n const url = this.page.url();\n return url && url !== \"about:blank\" ? withoutUiToken(url) : null;\n }\n\n private async recover(\n reconnector: BrowserReconnector,\n cause: unknown,\n ): Promise<RecoveryResult & { restoredUrl: string | null }> {\n const started = Date.now();\n const message = cause instanceof Error ? cause.message : String(cause);\n const args = { cause: this.scrub(message).slice(0, 200) };\n let result: RecoveryResult;\n try {\n result = await reconnector.recover(cause, (c) => this.adopt(c));\n } catch (error) {\n await this.report(\"browser_reconnect\", args, started, error);\n throw error;\n }\n const restoredUrl = this.openedUrl();\n await this.report(\n \"browser_reconnect\",\n { ...args, ...result, restoredUrl },\n started,\n null,\n );\n return { ...result, restoredUrl };\n }\n\n /** Take over a new connection's page and reopen the page the agent was on\n * (`openBrowser` owns the connection itself). A new browser has no session\n * cookie, so a World Host UI is first loaded with its token, exactly as\n * `goto()` loads the entry page. */\n private async adopt(connection: BrowserConnection): Promise<void> {\n this.current = connection.page;\n this.inflight = 0;\n this.watchNetwork(connection.page);\n const last = this.lastUrl;\n if (!last) return;\n if (this.ui?.token)\n await this.page.goto(uiEntryUrl(this.ui), { waitUntil: \"load\" });\n if (withoutUiToken(this.page.url()) !== last)\n await this.page.goto(last, { waitUntil: \"load\" });\n await this.settle();\n }\n\n /** Run one action and report it: the event carries what was asked,\n * whether it worked, and the screen after — for failures too, so a\n * reviewer sees what the agent saw when the selector did not match. The\n * error it throws keeps no session credential and no credential typed into\n * this browser, which Playwright's call log would quote. */\n async act<T>(\n action: string,\n args: Record<string, unknown>,\n fn: () => Promise<T>,\n onLoss: OnBrowserLoss = \"report\",\n ): Promise<T> {\n const started = Date.now();\n try {\n const result = await this.resilient(fn, onLoss);\n await this.report(action, args, started, null);\n return result;\n } catch (error) {\n this.scrubError(error);\n await this.report(action, args, started, error);\n throw error;\n }\n }\n\n /** One event on the recorder, if there is one; `failure` null means ok. */\n private async report(\n action: string,\n args: Record<string, unknown>,\n started: number,\n failure: unknown,\n ): Promise<void> {\n const recorder = this.recorder;\n if (!recorder) return;\n const error =\n failure === null\n ? null\n : this\n .scrub(\n failure instanceof Error\n ? `${failure.name}: ${failure.message}`\n : String(failure),\n )\n .slice(0, 4000);\n recorder.record({\n agentId: recorder.agentId,\n seq: recorder.nextSeq(),\n ts: new Date().toISOString(),\n action,\n args: redactActionArgs(\n action,\n Object.fromEntries(\n Object.entries(args).map(([key, value]) => [\n key,\n typeof value === \"string\" ? this.scrub(value) : value,\n ]),\n ),\n ),\n ok: failure === null,\n error,\n durationMs: Date.now() - started,\n mode: this.mode,\n viewport: { ...this.viewport },\n ...(await this.observeForEvent()),\n });\n }\n\n private async observeForEvent(): Promise<\n Pick<BrowserActionEvent, \"url\" | \"title\" | \"screenshot\">\n > {\n const out: Pick<BrowserActionEvent, \"url\" | \"title\" | \"screenshot\"> = {\n url: null,\n title: null,\n screenshot: null,\n };\n try {\n out.url = this.scrub(this.page.url());\n out.title = this.scrub(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.url;\n },\n // Navigating again lands on the same page: safe to replay.\n \"retry\",\n );\n }\n\n async back(): Promise<string> {\n return this.act(\"browser_back\", {}, async () => {\n await this.page.goBack({ waitUntil: \"load\" });\n await this.settle();\n return this.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 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(\n selector: string,\n opts: { timeoutMs?: number } = {},\n ): Promise<void> {\n await this.act(\"browser_click\", { selector }, async () => {\n await this.page.click(selector, { timeout: opts.timeoutMs });\n await this.settle();\n });\n }\n\n /** Replace the field's value with `text`. `opts.credential` is whether the\n * field takes one, when the caller already probed it; a credential is\n * withheld from the event and from any error. */\n async type(\n selector: string,\n text: string,\n opts: { timeoutMs?: number; credential?: boolean } = {},\n ): Promise<void> {\n const secret = opts.credential ?? (await this.credentialField(selector));\n if (secret) this.typed.push(text);\n this.typedText = new CredentialText(this.typed);\n await this.act(\n \"browser_type\",\n { selector, text: secret ? \"[redacted]\" : text },\n () => this.page.fill(selector, text, { timeout: opts.timeoutMs }),\n );\n }\n\n /** `DESCRIBE_FIELD_JS` of the element `selector` finds, or `UNREADABLE`. */\n async describeField(selector: string): Promise<string> {\n try {\n const described = await this.page\n .locator(selector)\n .evaluate(describeField, undefined, { timeout: FIELD_PROBE_TIMEOUT_MS });\n return String(described ?? \"\");\n } catch {\n return UNREADABLE;\n }\n }\n\n /** Whether the field `selector` finds takes a credential; one it cannot\n * read counts. */\n async credentialField(selector: string): Promise<boolean> {\n return isCredentialField(await this.describeField(selector));\n }\n\n /** What the field `selector` finds holds (`FIELD_VALUE_JS`), or null when\n * it cannot be read. */\n async fieldValue(selector: string): Promise<string | null> {\n try {\n const value = await this.page\n .locator(selector)\n .evaluate(readFieldValue, undefined, { timeout: FIELD_PROBE_TIMEOUT_MS });\n return value === null || value === undefined ? null : String(value);\n } catch {\n return null;\n }\n }\n\n /** Take this session's credentials out of `error` and the errors it came\n * from, in place. */\n scrubError(error: unknown): void {\n scrubError(error, (text) => this.scrub(text));\n }\n\n async press(key: string): Promise<void> {\n await this.act(\"browser_press\", { key }, async () => {\n await this.page.keyboard.press(key);\n await this.settle();\n });\n }\n\n async scroll(dy: number): Promise<void> {\n await this.act(\"browser_scroll\", { dy }, () =>\n this.page.mouse.wheel(0, dy),\n );\n }\n\n async screenshot(fullPage = false): Promise<Buffer> {\n return this.resilient(\n () => this.page.screenshot({ type: \"png\", fullPage }),\n \"retry\",\n );\n }\n\n async screenshotBase64(fullPage = false): Promise<string> {\n return (await this.screenshot(fullPage)).toString(\"base64\");\n }\n\n /** The visible text of `selector`'s element, without what any field on the\n * page that takes a credential holds. */\n async text(selector = \"body\"): Promise<string> {\n const withheld = new CredentialText(await this.credentialTexts());\n return withheld.withhold(\n await this.resilient(() => this.page.innerText(selector), \"retry\"),\n );\n }\n\n /** What each field on the page that takes a credential holds: an input's\n * or textarea's value, a select's chosen option, a contenteditable's text. */\n async credentialTexts(): Promise<string[]> {\n return this.resilient(async () => {\n const pairs = (await this.page\n .locator(FIELDS)\n .evaluateAll(readEditables)) as [string, string | null][];\n return credentialTexts(pairs);\n }, \"retry\");\n }\n\n /** Wait until the element `selector` finds could be clicked, without\n * clicking it. */\n async actionable(selector: string): Promise<void> {\n await this.resilient(() => this.page.locator(selector).click({ trial: true }), \"retry\");\n }\n\n async ariaSnapshot(): Promise<string> {\n return this.resilient(async () => {\n if (!this.page.ariaSnapshot)\n throw new TypeError(\"this Playwright has no page.ariaSnapshot\");\n return this.page.ariaSnapshot({ mode: \"ai\" });\n }, \"retry\");\n }\n\n async html(): Promise<string> {\n return this.resilient(() => this.page.content(), \"retry\");\n }\n\n get url(): string {\n return withoutUiToken(this.page.url());\n }\n\n async title(): Promise<string> {\n return this.resilient(() => this.page.title(), \"retry\");\n }\n\n async close(): Promise<void> {\n try {\n await this.teardown();\n } finally {\n await this.recorder?.close();\n }\n }\n}\n\n/** The Playwright entry points this module needs, so tests can inject a fake. */\nexport type PlaywrightLike = {\n chromium: {\n connect(wsEndpoint: string): Promise<PlaywrightBrowserLike>;\n connectOverCDP(endpointURL: string): Promise<PlaywrightBrowserLike>;\n launch(opts?: { headless?: boolean }): Promise<PlaywrightBrowserLike>;\n };\n};\n\nexport type PlaywrightBrowserLike = {\n newContext(opts?: {\n viewport?: { width: number; height: number };\n }): Promise<{ newPage(): Promise<BrowserPage>; close(): Promise<void> }>;\n close(): Promise<void>;\n};\n\nasync function loadPlaywright(): Promise<PlaywrightLike> {\n try {\n // A string specifier keeps bundlers from resolving the optional peer.\n const name = \"playwright\";\n return (await import(name)) as PlaywrightLike;\n } catch (error) {\n throw new Error(\n \"Driving a world UI needs Playwright: npm install playwright \" +\n \"(and `npx playwright install chromium` for local mode).\",\n { cause: error },\n );\n }\n}\n\nexport function resolveBrowserMode(\n surfaces: SessionSurfaces,\n mode: BrowserMode,\n): Exclude<BrowserMode, \"auto\"> {\n if (!surfaces.ui && !surfaces.browser)\n throw new WorldSurfaceUnavailable(\n \"ui\",\n \"open the session with surfaces: ['ui'] on a world that declares [ui]\",\n );\n const resolved =\n mode === \"auto\" ? (surfaces.browser ? \"hosted\" : \"local\") : mode;\n if (resolved === \"hosted\" && !surfaces.browser)\n throw new WorldSurfaceUnavailable(\n \"browser\",\n \"open the session with surfaces: ['browser'] to get a hosted browser\",\n );\n return resolved;\n}\n\n/** Open a browser on the session's UI in `hosted`, `local` or `auto` mode. */\nexport async function openBrowser(\n surfaces: SessionSurfaces,\n opts: {\n mode?: BrowserMode;\n headless?: boolean;\n playwright?: PlaywrightLike;\n recorder?: BrowserActionRecorder | null;\n /** The session's repair call (`session.repairBrowser`). Given, a hosted\n * `cdp` browser reconnects on its own when the browser is lost. */\n repair?: () => Promise<RepairAnswer>;\n } = {},\n): Promise<WorldBrowser> {\n const mode = resolveBrowserMode(surfaces, opts.mode ?? \"auto\");\n const pw = opts.playwright ?? (await loadPlaywright());\n const viewport = surfaces.browser?.viewport ?? DEFAULT_VIEWPORT;\n const attach = async (): Promise<BrowserConnection> => {\n const browser =\n mode === \"hosted\"\n ? surfaces.browser!.protocol === \"playwright\"\n ? await pw.chromium.connect(surfaces.browser!.wsUrl)\n : await pw.chromium.connectOverCDP(surfaces.browser!.wsUrl)\n : await pw.chromium.launch({ headless: opts.headless ?? true });\n const context = await browser.newContext({ viewport });\n return { browser, context, page: await context.newPage() };\n };\n let live = await attach();\n /** The same address again; the lost connection is released once a new one\n * stands. */\n const reattach = async (): Promise<BrowserConnection> => {\n const fresh = await attach();\n await releaseConnection(live);\n live = fresh;\n return fresh;\n };\n // A browser error quotes the URL it failed on; these carry the session.\n const scrubber = new SecretScrubber([\n surfaces.browser?.wsUrl,\n surfaces.ui?.token,\n capabilityLabel(surfaces.ui?.url),\n capabilityLabel(surfaces.api?.url),\n ]);\n // Only the platform's relay can be repaired behind the same address.\n const reconnector =\n mode === \"hosted\" && surfaces.browser!.protocol === \"cdp\" && opts.repair\n ? new BrowserReconnector(opts.repair, reattach, {\n scrub: (text) => scrubber.scrub(text),\n })\n : null;\n return new WorldBrowser(\n live.page,\n surfaces.ui,\n mode,\n () => closeConnection(live),\n viewport,\n opts.recorder ?? null,\n reconnector,\n scrubber,\n );\n}\n","import type { WorldBrowser } from \"./browser\";\nimport {\n CredentialText,\n SECRET_KEY,\n isCredentialField,\n isTextField,\n} from \"./credentialField\";\n\nexport const DEFAULT_MAX_CHARS = 20_000;\nexport const REF_ACT_TIMEOUT_MS = 2_000;\nconst STEADY_READS = 4;\nconst NEEDS_PLAYWRIGHT =\n \"browser_snapshot needs Playwright 1.59 or newer (npm install playwright@latest)\";\nconst CHANGED =\n \"the page changed since the last browser_snapshot: take a new one \" +\n \"(a page that never holds still can be driven with text= or CSS selectors)\";\nconst LINE_KEY = /^ *- ('(?:[^']|'')*'|.*?)(:(?: .*)?)?$/s;\nconst ATTRIBUTES = /(?: \\[[^[\\]]*\\])*$/;\nconst FOCUS = / \\[active\\]/g;\nconst STATES =\n / \\[(?:checked(?:=mixed)?|expanded|pressed(?:=mixed)?|selected)\\]/g;\nconst ROLE = /^[a-z]+/;\nconst REF = /\\[ref=((?:f[0-9]+)?e[0-9]+)\\]/g;\nconst REF_SELECTOR = /^ref=((?:f[0-9]+)?e[0-9]+)$/;\nconst EDITABLE_ROLES: ReadonlySet<string> = new Set([\n \"textbox\",\n \"searchbox\",\n \"combobox\",\n \"spinbutton\",\n \"slider\",\n]);\nconst VALUE_KEYS: ReadonlySet<string> = new Set([\"text\", \"/placeholder\"]);\nconst WITHHELD = \": [redacted]\";\n\nexport class PageStateError extends Error {\n override name = \"PageStateError\";\n}\n\n/** The ref a model's selector names, or null for a selector Playwright reads\n * itself. Only the toolkit may write `aria-ref`, so a selector that mentions\n * it is refused. */\nexport function selectorRef(selector: string): string | null {\n if (selector.includes(\"aria-ref\"))\n throw new PageStateError(\n \"aria-ref selectors are not taken: pass ref=… from browser_snapshot\",\n );\n return REF_SELECTOR.exec(selector.replace(/^ +| +$/g, \"\"))?.[1] ?? null;\n}\n\n/**\n * One snapshot line. Playwright writes a line's own attributes after its\n * name, so refs and `[disabled]` are read from the attribute run that ends\n * the key: a name cannot add one.\n */\nexport class AriaLine {\n constructor(\n readonly text: string,\n readonly indent: number,\n readonly key = \"\",\n readonly attributes = \"\",\n readonly rest = \"\",\n ) {}\n\n static parse(text: string): AriaLine {\n const indent = text.length - text.replace(/^ +/, \"\").length;\n const found = LINE_KEY.exec(text);\n if (!found) return new AriaLine(text, indent);\n const key = found[1].startsWith(\"'\")\n ? found[1].slice(1, -1).replaceAll(\"''\", \"'\")\n : found[1];\n return new AriaLine(\n text,\n indent,\n key,\n ATTRIBUTES.exec(key)?.[0] ?? \"\",\n found[2] ?? \"\",\n );\n }\n\n static parseAll(aria: string): AriaLine[] {\n return aria === \"\"\n ? []\n : aria.split(\"\\n\").map((text) => AriaLine.parse(text));\n }\n\n get refs(): string[] {\n return [...this.attributes.matchAll(REF)].map((ref) => ref[1]);\n }\n\n get disabled(): boolean {\n return this.attributes.includes(\"[disabled]\");\n }\n\n get editable(): boolean {\n const role = ROLE.exec(this.key)?.[0];\n return role !== undefined && EDITABLE_ROLES.has(role);\n }\n\n /** A value line: a field's text, or the placeholder it shows. */\n get value(): boolean {\n return VALUE_KEYS.has(this.key);\n }\n\n get states(): string[] {\n return this.attributes.match(STATES) ?? [];\n }\n\n get namedLikeCredential(): boolean {\n return SECRET_KEY.test(\n this.key.slice(0, this.key.length - this.attributes.length),\n );\n }\n\n /** Whether every value in and under this line is withheld. A field is,\n * when it is named like a credential or sits in something that is, has no\n * ref to probe, or `describe` reads it as a credential field. Any other\n * line is, when it is named like a credential and holds typed text (a\n * contenteditable), or has no ref to tell. */\n async credentialField(\n describe: (ref: string) => Promise<string>,\n withinCredential: boolean,\n ): Promise<boolean> {\n if (this.editable)\n return this.credentialFieldInput(describe, withinCredential);\n if (!this.namedLikeCredential) return false;\n if (this.refs.length === 0) return true;\n return isTextField(await describe(this.refs[0]));\n }\n\n private async credentialFieldInput(\n describe: (ref: string) => Promise<string>,\n withinCredential: boolean,\n ): Promise<boolean> {\n if (withinCredential || this.namedLikeCredential) return true;\n if (this.refs.length === 0) return true;\n return isCredentialField(await describe(this.refs[0]));\n }\n\n /** The line as shown: `withholding` applied to its text, while its refs and\n * states are still read from the attribute run Playwright wrote, so a\n * withheld name cannot join that run. */\n withheldBy(withhold: (text: string) => string): AriaLine {\n return new AriaLine(\n this.withholding(withhold),\n this.indent,\n this.key,\n this.attributes,\n this.rest,\n );\n }\n\n /** The line with `withhold` applied to its name and value, its attribute\n * run (refs, states, levels) as Playwright wrote it. */\n withholding(withhold: (text: string) => string): string {\n const at = this.attributes\n ? this.text.lastIndexOf(\n this.attributes,\n this.text.length - this.rest.length - this.attributes.length,\n )\n : -1;\n if (at < 0) return withhold(this.text);\n const end = at + this.attributes.length;\n return (\n withhold(this.text.slice(0, at)) +\n this.attributes +\n withhold(this.text.slice(end))\n );\n }\n\n /** The line with its own value replaced, keeping the key as Playwright\n * wrote it. */\n get withheld(): string {\n if (this.key === \"/placeholder\" || !this.rest.startsWith(\": \"))\n return this.text;\n return this.text.slice(0, this.text.length - this.rest.length) + WITHHELD;\n }\n}\n\n/**\n * What one toolkit's own actions by ref left since its last snapshot: the\n * toggled states a click left on its element (read right after it), and the\n * text it typed into a field. The page should read as the snapshot with those\n * states in place, those fields holding exactly that text (read from the field\n * itself, so a field whose value cannot be read counts as changed), and focus\n * anywhere. Anything else that changed, a later change to a touched element\n * or a value the page rewrote included, refuses the next ref. Twin of\n * `page_state.Touched`.\n */\nexport class Touched {\n constructor(\n readonly clicked: ReadonlyMap<string, readonly string[]> = new Map(),\n readonly typed: ReadonlyMap<string, string> = new Map(),\n ) {}\n\n afterClick(ref: string, states: readonly string[]): Touched {\n return new Touched(new Map([...this.clicked, [ref, states]]), this.typed);\n }\n\n afterTyping(ref: string, text: string): Touched {\n return new Touched(this.clicked, new Map([...this.typed, [ref, text]]));\n }\n\n /** The snapshot's lines as the page should now read them. */\n expected(lines: readonly AriaLine[]): string[] {\n return this.compared(lines, (line) => this.leftByClick(line));\n }\n\n /** A fresh read's lines, in the same form. */\n actual(lines: readonly AriaLine[]): string[] {\n return this.compared(lines, (line) => line.states);\n }\n\n private compared(\n lines: readonly AriaLine[],\n states: (line: AriaLine) => readonly string[],\n ): string[] {\n const out: string[] = [];\n let typedAt: number | null = null;\n for (const line of lines) {\n if (typedAt !== null && line.indent > typedAt && line.value) continue;\n typedAt = this.isTyped(line) ? line.indent : null;\n out.push(this.comparedLine(line, states(line)));\n }\n return out;\n }\n\n private isTyped(line: AriaLine): boolean {\n return line.refs.some((ref) => this.typed.has(ref));\n }\n\n private clickedRef(line: AriaLine): string | undefined {\n return line.refs.find((ref) => this.clicked.has(ref));\n }\n\n private leftByClick(line: AriaLine): readonly string[] {\n const ref = this.clickedRef(line);\n return ref === undefined ? line.states : this.clicked.get(ref)!;\n }\n\n private comparedLine(line: AriaLine, states: readonly string[]): string {\n if (this.isTyped(line))\n return (\" \".repeat(line.indent) + \"- \" + line.key).replace(FOCUS, \"\");\n if (this.clickedRef(line) !== undefined)\n return line.text.replace(FOCUS, \"\").replace(STATES, \"\") + states.join(\"\");\n return line.text.replace(FOCUS, \"\");\n }\n}\n\n/** A snapshot with its credential values withheld, and the refs of the lines\n * it withheld. */\nexport type Redaction = { snapshot: string; withheld: ReadonlySet<string> };\n\nexport type PageObservation = {\n url: string;\n title: string;\n snapshot: string;\n truncated: boolean;\n};\n\nconst sameLines = (a: readonly string[], b: readonly string[]): boolean =>\n a.length === b.length && a.every((line, at) => line === b[at]);\n\nconst deeper = (line: AriaLine, below: number | null): number | null =>\n below !== null && line.indent > below ? below : null;\n\n/**\n * A world's page as a model reads it: Playwright's AI snapshot\n * (`ariaSnapshot({ mode: \"ai\" })`, Playwright 1.59 or newer), one line per\n * element, each numbered `[ref=e3]` by Playwright itself (`[ref=f1e2]` inside\n * a frame). A `ref=e3` selector resolves to Playwright's `aria-ref=e3`.\n * Playwright keeps a ref on its DOM node, and a page may reuse that node for\n * another record, so a ref acts only while the page reads as it did in the\n * snapshot the model saw (same URL and lines, with focus aside and what the\n * toolkit's own clicks and typing by ref left in place), checked before and after the\n * element is ready, and its action must start within `REF_ACT_TIMEOUT_MS`. A credential\n * field's value never leaves in a snapshot. Twin of\n * `gatewaysdk/page_state.py`; `conformance/page-state.json` pins both.\n */\nexport class PageState {\n constructor(\n readonly url: string,\n readonly title: string,\n readonly snapshot: string,\n readonly refs: ReadonlySet<string>,\n readonly disabled: ReadonlySet<string>,\n readonly truncated: boolean,\n readonly credentials: ReadonlySet<string> = new Set(),\n ) {}\n\n static parse(\n aria: string,\n opts: {\n url: string;\n title: string;\n maxChars?: number;\n credentials?: ReadonlySet<string>;\n },\n ): PageState {\n return PageState.ofLines(AriaLine.parseAll(aria), opts);\n }\n\n static ofLines(\n lines: readonly AriaLine[],\n opts: {\n url: string;\n title: string;\n maxChars?: number;\n credentials?: ReadonlySet<string>;\n },\n ): PageState {\n const maxChars = opts.maxChars ?? DEFAULT_MAX_CHARS;\n const shown: AriaLine[] = [];\n let size = 0;\n for (const line of lines) {\n const width = [...line.text].length + 1;\n if (size + width > maxChars) break;\n size += width;\n shown.push(line);\n }\n return new PageState(\n opts.url,\n opts.title,\n shown.map((line) => line.text).join(\"\\n\"),\n new Set(shown.flatMap((line) => line.refs)),\n new Set(\n shown.filter((line) => line.disabled).flatMap((line) => line.refs),\n ),\n shown.length < lines.length,\n opts.credentials ?? new Set(),\n );\n }\n\n /** `aria` with credential values withheld: every value in and under a\n * credential field (see `AriaLine.credentialField`; `describe` is\n * `DESCRIBE_FIELD_JS` of a ref's element), the placeholder aside, and the\n * value of any line named like a credential. Names, roles and refs stay. */\n static async redacted(\n aria: string,\n describe: (ref: string) => Promise<string>,\n ): Promise<Redaction> {\n const out: string[] = [];\n const withheld: string[] = [];\n let withheldBelow: number | null = null;\n let credentialBelow: number | null = null;\n for (const line of AriaLine.parseAll(aria)) {\n withheldBelow = deeper(line, withheldBelow);\n credentialBelow = deeper(line, credentialBelow);\n if (\n withheldBelow === null &&\n (await line.credentialField(describe, credentialBelow !== null))\n )\n withheldBelow = line.indent;\n if (credentialBelow === null && line.namedLikeCredential)\n credentialBelow = line.indent;\n const hidden = withheldBelow !== null || line.namedLikeCredential;\n out.push(hidden ? line.withheld : line.text);\n if (hidden) withheld.push(...line.refs);\n }\n return { snapshot: out.join(\"\\n\"), withheld: new Set(withheld) };\n }\n\n target(ref: string): string {\n if (!this.refs.has(ref))\n throw new PageStateError(\n `ref=${ref} is not in the last browser_snapshot: take a new one`,\n );\n if (this.disabled.has(ref))\n throw new PageStateError(`ref=${ref} is disabled`);\n return `aria-ref=${ref}`;\n }\n\n observation(): PageObservation {\n return {\n url: this.url,\n title: this.title,\n snapshot: this.snapshot,\n truncated: this.truncated,\n };\n }\n}\n\n/**\n * One toolkit's snapshots of one browser, and its clicks and typing. A\n * `ref=…` acts against the latest snapshot, and only while the page still\n * reads as that snapshot did, before and after the element is ready.\n */\nexport class PageObserver {\n last: PageState | null = null;\n private seen: AriaLine[] = [];\n private seenUrl = \"\";\n private touched = new Touched();\n private turn: Promise<unknown> = Promise.resolve();\n\n constructor(\n readonly browser: WorldBrowser,\n readonly maxChars = DEFAULT_MAX_CHARS,\n ) {}\n\n async snapshot(): Promise<PageState> {\n return this.inTurn(() => this.takeSnapshot());\n }\n\n async click(selector: string): Promise<void> {\n return this.inTurn(() => this.clickOnce(selector));\n }\n\n async type(selector: string, text: string): Promise<void> {\n return this.inTurn(() => this.typeOnce(selector, text));\n }\n\n /** One call at a time, so a tool call a model made in parallel cannot act\n * between another's checks and its action. */\n private inTurn<T>(fn: () => Promise<T>): Promise<T> {\n const run = this.turn.then(fn, fn);\n this.turn = run.catch(() => undefined);\n return run;\n }\n\n private async takeSnapshot(): Promise<PageState> {\n const aria = this.browser.scrubSession(await this.steady());\n const shown = await PageState.redacted(aria, (ref) =>\n this.browser.describeField(`aria-ref=${ref}`),\n );\n const secrets = new CredentialText([\n ...(await this.withheldValues(shown)),\n ...(await this.browser.credentialTexts()),\n ...this.browser.typedCredentials,\n ]);\n const lines = AriaLine.parseAll(shown.snapshot).map((line) =>\n line.withheldBy((text) => secrets.withhold(text)),\n );\n this.last = PageState.ofLines(lines, {\n url: this.url(),\n title: this.browser.scrub(await this.browser.title()),\n maxChars: this.maxChars,\n credentials: shown.withheld,\n });\n this.seen = AriaLine.parseAll(aria);\n this.seenUrl = this.browser.scrubSession(this.browser.url);\n this.touched = new Touched();\n return this.last;\n }\n\n /** The values of the fields the redaction withheld: a page may repeat them\n * in another line's name (a row or cell named from its content, a label\n * that wraps the field). */\n private async withheldValues(shown: Redaction): Promise<string[]> {\n const refs = AriaLine.parseAll(shown.snapshot)\n .filter((line) => line.editable)\n .flatMap((line) => line.refs)\n .filter((ref) => shown.withheld.has(ref));\n const values: string[] = [];\n for (const ref of refs)\n values.push((await this.browser.fieldValue(`aria-ref=${ref}`)) ?? \"\");\n return values;\n }\n\n private async clickOnce(selector: string): Promise<void> {\n const ref = selectorRef(selector);\n if (ref === null) return this.browser.click(selector);\n const [, target] = this.target(ref);\n await this.ready(target);\n await this.browser.click(target, { timeoutMs: REF_ACT_TIMEOUT_MS });\n const left = (await this.now()).find((line) => line.refs.includes(ref));\n if (left) this.touched = this.touched.afterClick(ref, left.states);\n }\n\n private async typeOnce(selector: string, text: string): Promise<void> {\n const ref = selectorRef(selector);\n if (ref === null) return this.browser.type(selector, text);\n const [last, target] = this.target(ref);\n const credential =\n last.credentials.has(ref) || (await this.browser.credentialField(target));\n await this.ready(target);\n await this.browser.type(target, text, {\n timeoutMs: REF_ACT_TIMEOUT_MS,\n credential,\n });\n this.touched = this.touched.afterTyping(ref, text);\n }\n\n private target(ref: string): [PageState, string] {\n if (this.last === null)\n throw new PageStateError(\n \"ref=… selectors come from browser_snapshot: take one first\",\n );\n return [this.last, this.last.target(ref)];\n }\n\n private async ready(target: string): Promise<void> {\n await this.still();\n await this.browser.actionable(target);\n await this.still();\n }\n\n /** A page still rendering when it is read would refuse the model's next\n * ref, so the snapshot it is shown is one that read the same before and\n * after the page settled again. */\n private async steady(): Promise<string> {\n const untouched = new Touched();\n let aria = await this.read();\n for (let read = 1; read < STEADY_READS; read++) {\n await this.browser.settle();\n const again = await this.read();\n if (\n sameLines(\n untouched.actual(AriaLine.parseAll(again)),\n untouched.actual(AriaLine.parseAll(aria)),\n )\n )\n return again;\n aria = again;\n }\n return aria;\n }\n\n private async read(): Promise<string> {\n try {\n return await this.browser.ariaSnapshot();\n } catch (error) {\n if (error instanceof TypeError)\n throw new PageStateError(NEEDS_PLAYWRIGHT);\n throw error;\n }\n }\n\n private url(): string {\n return this.browser.scrub(this.browser.url);\n }\n\n private async now(): Promise<AriaLine[]> {\n return AriaLine.parseAll(this.browser.scrubSession(await this.read()));\n }\n\n private async still(): Promise<void> {\n if (\n this.browser.scrubSession(this.browser.url) !== this.seenUrl ||\n !sameLines(\n this.touched.actual(await this.now()),\n this.touched.expected(this.seen),\n )\n )\n throw new PageStateError(CHANGED);\n for (const [ref, text] of this.touched.typed)\n if ((await this.browser.fieldValue(`aria-ref=${ref}`)) !== text)\n throw new PageStateError(CHANGED);\n }\n}\n","import type { WorldBrowser } from \"./browser\";\nimport { DEFAULT_MAX_CHARS, PageObserver } from \"./pageState\";\nimport { schemaFromSignature, type WorldToolkit } from \"./session\";\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_snapshot\",\n signature: \"browser_snapshot()\",\n doc: \"The page as an accessibility tree, one line per element with its role, name and [ref=e3]. To act on an element, pass `ref=e3` as the selector of browser_click or browser_type. Returns {url, title, snapshot, truncated}.\",\n },\n {\n name: \"browser_click\",\n signature: \"browser_click(selector)\",\n doc: \"Click an element by `ref=e3` from the last browser_snapshot, or 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 `ref=e3` or 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\n/** `impl` with any error it throws scrubbed of the session's credentials,\n * which Playwright quotes in its call logs, before it reaches the model. */\nconst scrubbingErrors =\n (\n browser: WorldBrowser,\n impl: WorldToolkit[\"impls\"][string],\n ): WorldToolkit[\"impls\"][string] =>\n async (args) => {\n try {\n return await impl(args);\n } catch (error) {\n browser.scrubError(error);\n throw error;\n }\n };\n\nconst str = (v: unknown, fallback: string): string =>\n typeof v === \"string\" && v.length > 0 ? v : fallback;\n\n/**\n * A session's browser as model tools, in the `WorldToolkit` shape the world's\n * own tools come in, so an agent loop that dispatches `toolkit().impls`\n * merges these and gains a screen. Twin of `gatewaysdk/browser_tools.py`.\n */\nexport function computerUseToolkit(\n browser: WorldBrowser,\n opts: { maxText?: number } = {},\n): WorldToolkit {\n const maxText = opts.maxText ?? DEFAULT_MAX_CHARS;\n const pages = new PageObserver(browser, maxText);\n const observe = async (selector = \"body\") => {\n const text = browser.scrub(await browser.text(selector));\n return {\n url: browser.scrub(browser.url),\n title: browser.scrub(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_snapshot: async () => (await pages.snapshot()).observation(),\n browser_click: async (a) => {\n await pages.click(str(a.selector, \"\"));\n return observe();\n },\n browser_type: async (a) => {\n await pages.type(str(a.selector, \"\"), String(a.text ?? \"\"));\n return { ok: true, url: browser.scrub(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.scrub(browser.url) };\n },\n browser_screenshot: async (a) => ({\n image_base64: await browser.screenshotBase64(a.full_page === true),\n url: browser.scrub(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: Object.fromEntries(\n Object.entries(impls).map(([name, impl]) => [\n name,\n scrubbingErrors(browser, impl),\n ]),\n ),\n specs,\n };\n}\n","/**\n * The provider-neutral action vocabulary every native computer executes.\n * Coordinates are in the MODEL's pixel space; the screen maps them to the page.\n * Twin of `gatewaysdk/native_computer/actions.py`.\n */\n\nexport const ACTION_NAMES = [\n \"screenshot\",\n \"zoom\",\n \"click\",\n \"move\",\n \"mouse_down\",\n \"mouse_up\",\n \"drag\",\n \"scroll\",\n \"type\",\n \"key\",\n \"hold_key\",\n \"wait\",\n \"cursor_position\",\n \"history\",\n] as const;\n\nexport type ActionName = (typeof ACTION_NAMES)[number];\nexport type Point = [number, number];\nexport type MouseButton = \"left\" | \"right\" | \"middle\";\n\nexport const SECRET_TEXT = \"[redacted]\";\n\n/** A finite JSON number from model output; anything else (null, text, a\n * list, a boolean, NaN) is refused. The Python twin is `to_number`. */\nexport function toNumber(value: unknown): number {\n if (typeof value !== \"number\" || !Number.isFinite(value))\n throw new Error(`not a number: ${JSON.stringify(value) ?? String(value)}`);\n return value;\n}\n\n/** `toNumber`, truncated like Python's `int()`. */\nexport function toInt(value: unknown): number {\n return Math.trunc(toNumber(value));\n}\n\n/** Model-controlled numbers an action may carry, inclusive. */\nexport const BOUNDS: Readonly<Record<string, [number, number]>> = {\n seconds: [0, 300],\n repeat: [1, 100],\n count: [1, 3],\n dx: [-10_000, 10_000],\n dy: [-10_000, 10_000],\n};\n\n/** Arguments by action:\n * `click` x?, y?, button, count, modifiers · `move` x, y, modifiers? ·\n * `mouse_down`/`mouse_up` button · `drag` path, modifiers ·\n * `scroll` x?, y?, dx, dy, modifiers · `type` text · `key` keys, repeat ·\n * `hold_key` keys, seconds · `wait` seconds · `zoom` region ·\n * `history` direction · `screenshot`/`cursor_position` none. */\nexport type ActionArgs = {\n x?: number;\n y?: number;\n button?: MouseButton;\n count?: number;\n modifiers?: string[];\n path?: Point[];\n dx?: number;\n dy?: number;\n text?: string;\n keys?: string[];\n repeat?: number;\n seconds?: number;\n region?: [number, number, number, number];\n direction?: \"back\" | \"forward\";\n};\n\nexport class ComputerAction {\n constructor(\n readonly name: ActionName,\n readonly args: ActionArgs = {},\n ) {\n if (!(ACTION_NAMES as readonly string[]).includes(name))\n throw new Error(`unknown computer action: ${name}`);\n for (const [key, [low, high]] of Object.entries(BOUNDS)) {\n const value = (args as Record<string, unknown>)[key];\n if (\n value !== undefined &&\n !(Number(value) >= low && Number(value) <= high)\n )\n throw new Error(\n `${name} ${key} must be between ${low} and ${high}, got ${String(value)}`,\n );\n }\n }\n\n /** Flat arguments for the browser timeline and the trace: lists become\n * `\"x,y\"` strings, and typed text is withheld when it went into a\n * credential field. */\n recordArgs(secretText: boolean): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(this.args))\n out[key] = Array.isArray(value) ? value.flat().join(\",\") : value;\n if (secretText && \"text\" in out) out.text = SECRET_TEXT;\n return out;\n }\n}\n\n/** What an action gave back: a PNG (`screenshot`, `zoom`), a line of text\n * (`cursor_position`), or neither. */\nexport type ActionResult = { image?: Buffer; text?: string };\n","/**\n * The model's pixel space versus the page's. Unscaled by default; when a\n * provider's image limits (or the caller) ask for a smaller display,\n * screenshots are captured downscaled and coordinates mapped back.\n * Twin of `gatewaysdk/native_computer/display.py`.\n */\n\nexport type Fits = (width: number, height: number) => boolean;\n\nconst FIT_STEP = 0.98;\n\nexport class Display {\n constructor(\n readonly width: number,\n readonly height: number,\n readonly viewportWidth: number,\n readonly viewportHeight: number,\n ) {}\n\n /** `size` when the caller names one; otherwise the largest downscale of the\n * viewport (at most 1:1) that `fits` the provider's limits. */\n static forViewport(\n viewport: { width: number; height: number },\n size?: [number, number],\n fits: Fits = () => true,\n ): Display {\n const { width, height } = viewport;\n if (size) return Display.sized(size[0], size[1], width, height);\n let scale = 1;\n while (!fits(Math.round(width * scale), Math.round(height * scale)))\n scale *= FIT_STEP;\n return new Display(\n Math.round(width * scale),\n Math.round(height * scale),\n width,\n height,\n );\n }\n\n /** A caller's display keeps the viewport's shape: screenshots are scaled\n * uniformly, so another aspect ratio would map clicks off the image. */\n private static sized(\n width: number,\n height: number,\n viewportWidth: number,\n viewportHeight: number,\n ): Display {\n if (width <= 0 || height <= 0)\n throw new Error(`display ${width}x${height} must be positive`);\n const sameShape = (width * viewportHeight) / viewportWidth;\n if (Math.abs(sameShape - height) > 1)\n throw new Error(\n `display ${width}x${height} must keep the viewport's aspect ratio ` +\n `(${viewportWidth}x${viewportHeight}); try ${width}x${Math.round(sameShape)}`,\n );\n return new Display(width, height, viewportWidth, viewportHeight);\n }\n\n get scaled(): boolean {\n return (\n this.width !== this.viewportWidth || this.height !== this.viewportHeight\n );\n }\n\n get scale(): number {\n return Math.min(\n this.width / this.viewportWidth,\n this.height / this.viewportHeight,\n );\n }\n\n toPage(x: number, y: number): [number, number] {\n return [\n (x * this.viewportWidth) / this.width,\n (y * this.viewportHeight) / this.height,\n ];\n }\n}\n","/**\n * Pixels and keys on a `WorldBrowser` page. Every provider's actions land here\n * as `ComputerAction` values and run as Playwright mouse and keyboard calls.\n * The cursor is tracked in the model's pixel space so a click without\n * coordinates lands where the pointer is. Twin of `native_computer/screen.py`.\n */\nimport type { BrowserPage } from \"../browser\";\nimport { DESCRIBE_FIELD_JS, isCredentialField } from \"../credentialField\";\nimport type { ActionResult, ComputerAction, Point } from \"./actions\";\nimport type { Display } from \"./display\";\n\ntype CdpSession = {\n send(\n method: string,\n params: Record<string, unknown>,\n ): Promise<{ data: string }>;\n detach(): Promise<void>;\n};\n\n/** The Playwright page surface pixel-level control needs, beyond `BrowserPage`. */\nexport type NativePage = {\n mouse: {\n move(x: number, y: number, opts?: { steps?: number }): Promise<void>;\n click(\n x: number,\n y: number,\n opts?: { button?: string; clickCount?: number },\n ): Promise<void>;\n down(opts?: { button?: string }): Promise<void>;\n up(opts?: { button?: string }): Promise<void>;\n wheel(dx: number, dy: number): Promise<void>;\n };\n keyboard: {\n down(key: string): Promise<void>;\n up(key: string): Promise<void>;\n press(key: string): Promise<void>;\n type(text: string): Promise<void>;\n };\n screenshot(opts?: { type?: \"png\" }): Promise<Buffer>;\n waitForTimeout(ms: number): Promise<void>;\n goBack(): Promise<unknown>;\n goForward(): Promise<unknown>;\n evaluate(expression: string): Promise<unknown>;\n context(): { newCDPSession(page: unknown): Promise<CdpSession> };\n};\n\n/** The slice of `WorldBrowser` a native computer drives. */\nexport type ScreenBrowser = {\n readonly page: BrowserPage;\n readonly viewport: { width: number; height: number };\n act<T>(\n action: string,\n args: Record<string, unknown>,\n fn: () => Promise<T>,\n onLoss?: \"retry\" | \"report\",\n ): Promise<T>;\n settle(): Promise<void>;\n scrub(text: string): string;\n};\n\nconst FOCUSED_FIELD_JS =\n \"(() => { let e = document.activeElement;\" +\n \" const inner = (el) => (el.shadowRoot && el.shadowRoot.activeElement)\" +\n \" || (el.contentDocument && el.contentDocument.activeElement);\" +\n \" while (e && inner(e)) e = inner(e);\" +\n ` return (${DESCRIBE_FIELD_JS})(e); })()`;\nconst DRAG_STEPS = 5;\nconst PNG_SIGNATURE = Buffer.from([\n 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,\n]);\n\ntype Clip = { x: number; y: number; width: number; height: number };\n\n/** The width in a PNG's header, or null for bytes that are not a PNG. */\nexport function pngWidth(png: Buffer): number | null {\n if (png.length < 24 || !png.subarray(0, 8).equals(PNG_SIGNATURE)) return null;\n return png.readUInt32BE(16);\n}\nconst NATIVE_METHODS = [\"move\", \"click\", \"down\", \"up\", \"wheel\"] as const;\n\nfunction isNativePage(page: unknown): page is NativePage {\n const candidate = page as Partial<NativePage> | null;\n const mouse = candidate?.mouse as Record<string, unknown> | undefined;\n return (\n typeof candidate?.context === \"function\" &&\n NATIVE_METHODS.every((m) => typeof mouse?.[m] === \"function\")\n );\n}\n\ntype Handler = (action: ComputerAction) => Promise<ActionResult>;\n\nexport class Screen {\n cursor: Point = [0, 0];\n private pixelRatio = 1;\n private readonly handlers: Record<ComputerAction[\"name\"], Handler> = {\n screenshot: async () => ({ image: await this.screenshot() }),\n zoom: (a) => this.zoom(a),\n click: (a) => this.click(a),\n move: (a) =>\n this.held(a.args.modifiers ?? [], () => this.moveTo(this.point(a))),\n mouse_down: async (a) => {\n await this.page.mouse.down({ button: a.args.button ?? \"left\" });\n return {};\n },\n mouse_up: async (a) => {\n await this.page.mouse.up({ button: a.args.button ?? \"left\" });\n return {};\n },\n drag: (a) => this.drag(a),\n scroll: (a) => this.scroll(a),\n type: async (a) => {\n await this.page.keyboard.type(a.args.text ?? \"\");\n return {};\n },\n key: (a) => this.key(a),\n hold_key: (a) =>\n this.held(a.args.keys ?? [], () =>\n this.page.waitForTimeout((a.args.seconds ?? 0) * 1000),\n ),\n wait: async (a) => {\n await this.page.waitForTimeout((a.args.seconds ?? 0) * 1000);\n return {};\n },\n cursor_position: async () => ({\n text: `X=${this.cursor[0]}, Y=${this.cursor[1]}`,\n }),\n history: async (a) => {\n const navigate = {\n back: () => this.page.goBack(),\n forward: () => this.page.goForward(),\n };\n await navigate[a.args.direction ?? \"back\"]();\n return {};\n },\n };\n\n constructor(\n readonly browser: ScreenBrowser,\n readonly display: Display,\n ) {}\n\n /** The live page (a new object after a reconnect), as pixel-level Playwright. */\n get page(): NativePage {\n const page: unknown = this.browser.page;\n if (!isNativePage(page))\n throw new Error(\n \"native computer use needs a Playwright page (mouse.move/click/down/up/wheel, context())\",\n );\n return page;\n }\n\n run(action: ComputerAction): Promise<ActionResult> {\n return this.handlers[action.name](action);\n }\n\n /** A PNG of the viewport at the model's display size. */\n async screenshot(): Promise<Buffer> {\n if (!this.display.scaled) return this.page.screenshot({ type: \"png\" });\n const { viewportWidth: width, viewportHeight: height } = this.display;\n return this.capture({ x: 0, y: 0, width, height }, this.display.scale);\n }\n\n /** Whether keystrokes go to a credential field (a password input, or one\n * named like a token, key or PIN), looking through shadow roots and\n * same-origin frames. An unreadable page, a cross-origin frame or a focus\n * that is not a text field (a closed shadow root's host) counts as one. */\n async focusedFieldIsSecret(): Promise<boolean> {\n let described: string;\n try {\n described = String((await this.page.evaluate(FOCUSED_FIELD_JS)) ?? \"\");\n } catch {\n return true;\n }\n return isCredentialField(described);\n }\n\n /** CDP renders a clip at the page's device pixel ratio as well as its\n * `scale` (a Retina host doubles it), so a capture of the wrong width\n * measures that ratio and is taken once more, corrected. */\n private async capture(clip: Clip, scale: number): Promise<Buffer> {\n const wanted = Math.round(clip.width * scale);\n const png = await this.cdpCapture(clip, scale / this.pixelRatio);\n const width = pngWidth(png);\n if (width === null || Math.abs(width - wanted) <= 1) return png;\n this.pixelRatio *= width / wanted;\n return this.cdpCapture(clip, scale / this.pixelRatio);\n }\n\n private async cdpCapture(clip: Clip, scale: number): Promise<Buffer> {\n const page = this.page;\n const session = await page.context().newCDPSession(page);\n try {\n const shot = await session.send(\"Page.captureScreenshot\", {\n format: \"png\",\n clip: { ...clip, scale },\n });\n return Buffer.from(shot.data, \"base64\");\n } finally {\n await session.detach();\n }\n }\n\n private point(action: ComputerAction): Point {\n const { x, y } = action.args;\n return x === undefined || y === undefined ? this.cursor : [x, y];\n }\n\n private async moveTo(point: Point, steps = 1): Promise<void> {\n const [x, y] = this.display.toPage(point[0], point[1]);\n await this.page.mouse.move(x, y, { steps });\n this.cursor = point;\n }\n\n private async held(\n modifiers: readonly string[],\n fn: () => Promise<unknown>,\n ): Promise<ActionResult> {\n for (const key of modifiers) await this.page.keyboard.down(key);\n try {\n await fn();\n } finally {\n for (const key of [...modifiers].reverse())\n await this.page.keyboard.up(key);\n }\n return {};\n }\n\n private async zoom(action: ComputerAction): Promise<ActionResult> {\n const [x0, y0, x1, y1] = action.args.region ?? [0, 0, 0, 0];\n const [left, top] = this.display.toPage(x0, y0);\n const [right, bottom] = this.display.toPage(x1, y1);\n if (right <= left || bottom <= top)\n throw new Error(\"zoom region must have x1 > x0 and y1 > y0\");\n const width = right - left;\n const height = bottom - top;\n const scale = Math.min(\n this.display.width / width,\n this.display.height / height,\n );\n return {\n image: await this.capture({ x: left, y: top, width, height }, scale),\n };\n }\n\n private async click(action: ComputerAction): Promise<ActionResult> {\n const point = this.point(action);\n return this.held(action.args.modifiers ?? [], async () => {\n await this.moveTo(point);\n const [x, y] = this.display.toPage(point[0], point[1]);\n await this.page.mouse.click(x, y, {\n button: action.args.button ?? \"left\",\n clickCount: action.args.count ?? 1,\n });\n });\n }\n\n private async drag(action: ComputerAction): Promise<ActionResult> {\n const path = action.args.path ?? [];\n if (path.length < 2) throw new Error(\"a drag needs at least two points\");\n return this.held(action.args.modifiers ?? [], async () => {\n await this.moveTo(path[0]);\n await this.page.mouse.down({ button: \"left\" });\n try {\n for (const point of path.slice(1)) await this.moveTo(point, DRAG_STEPS);\n } finally {\n await this.page.mouse.up({ button: \"left\" });\n }\n });\n }\n\n private async scroll(action: ComputerAction): Promise<ActionResult> {\n await this.moveTo(this.point(action));\n const scale = this.display.scale;\n return this.held(action.args.modifiers ?? [], () =>\n this.page.mouse.wheel(\n (action.args.dx ?? 0) / scale,\n (action.args.dy ?? 0) / scale,\n ),\n );\n }\n\n private async key(action: ComputerAction): Promise<ActionResult> {\n const combo = (action.args.keys ?? []).join(\"+\");\n for (let i = 0; i < (action.args.repeat ?? 1); i += 1)\n await this.page.keyboard.press(combo);\n return {};\n }\n}\n","/**\n * Attach an image (or any media) to a span: upload the bytes to the\n * platform's media store and put the returned reference into the span's\n * input or output. The trace view renders the reference inline:\n *\n * @@@langfuseMedia:type=image/png|id=<mediaId>|source=bytes@@@\n *\n * Three steps against `/api/public/media`: ask for a presigned URL (the\n * platform links the media to the trace and observation), PUT the bytes, then\n * report the upload's status. The presigned URL is a credential and never\n * reaches a log or an error. Python twin: `gatewaysdk/tracing/media.py`.\n * No OpenTelemetry import here, so the worlds entry can use it.\n */\nimport { createHash } from \"node:crypto\";\n\nimport { PlatformTransport, type PlatformMethod } from \"../worlds/transport\";\n\nexport const MEDIA_PATH = \"/api/public/media\";\nexport const MAX_MEDIA_BYTES = 5 * 1024 * 1024;\nconst PUT_TIMEOUT_MS = 30_000;\nconst MAX_UPLOAD_ERROR = 500;\nconst NETWORK_FAILURE_STATUS = 599;\n\nexport type MediaField = \"input\" | \"output\" | \"metadata\";\n\nexport class MediaUploadError extends Error {\n constructor(\n message: string,\n readonly status?: number,\n ) {\n super(message);\n this.name = \"MediaUploadError\";\n }\n}\n\nexport class MediaReference {\n constructor(\n readonly mediaId: string,\n readonly contentType: string,\n ) {}\n\n toString(): string {\n return `@@@langfuseMedia:type=${this.contentType}|id=${this.mediaId}|source=bytes@@@`;\n }\n}\n\nexport type PutBytes = (\n url: string,\n data: Buffer,\n headers: Record<string, string>,\n) => Promise<{ status: number; error: string | null }>;\n\n/** PUT to a presigned URL; a network failure is status 599 with the error's\n * name only, so the URL never travels. */\nexport async function putBytes(\n url: string,\n data: Buffer,\n headers: Record<string, string>,\n): Promise<{ status: number; error: string | null }> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), PUT_TIMEOUT_MS);\n try {\n const res = await fetch(url, {\n method: \"PUT\",\n body: new Uint8Array(data),\n headers,\n signal: controller.signal,\n });\n return {\n status: res.status,\n error: res.ok ? null : (await res.text()).slice(0, MAX_UPLOAD_ERROR),\n };\n } catch (error) {\n return {\n status: NETWORK_FAILURE_STATUS,\n error: error instanceof Error ? error.name : \"Error\",\n };\n } finally {\n clearTimeout(timer);\n }\n}\n\n/** Uploads media for one project (the key pair's). */\nexport class MediaUploader {\n constructor(\n private readonly transport: PlatformTransport,\n private readonly put: PutBytes = putBytes,\n public maxBytes: number = MAX_MEDIA_BYTES,\n ) {}\n\n /** The uploader for `GATEWAY_HOST` / `GATEWAY_PUBLIC_KEY` /\n * `GATEWAY_SECRET_KEY` only; null when any is unset, so a run traced with a saved login uploads none. */\n static fromEnv(env: NodeJS.ProcessEnv = process.env): MediaUploader | null {\n const host = env.GATEWAY_HOST;\n const publicKey = env.GATEWAY_PUBLIC_KEY;\n const secretKey = env.GATEWAY_SECRET_KEY;\n if (!host || !publicKey || !secretKey) return null;\n return new MediaUploader(\n new PlatformTransport({\n host: host.replace(/\\/$/, \"\"),\n publicKey,\n secretKey,\n }),\n );\n }\n\n /** Store `data` linked to the trace (and observation) and return its reference. */\n async upload(\n data: Buffer,\n link: {\n contentType: string;\n traceId: string;\n observationId: string | null;\n field: MediaField;\n },\n ): Promise<MediaReference> {\n if (data.length > this.maxBytes)\n throw new MediaUploadError(\n `media is ${data.length} bytes, over the ${this.maxBytes}-byte cap`,\n );\n const sha256Hash = createHash(\"sha256\").update(data).digest(\"base64\");\n const answer = (await this.send(\"POST\", MEDIA_PATH, {\n traceId: link.traceId,\n observationId: link.observationId,\n contentType: link.contentType,\n contentLength: data.length,\n sha256Hash,\n field: link.field,\n })) as { mediaId: string; uploadUrl?: string | null };\n if (typeof answer.mediaId !== \"string\" || !answer.mediaId)\n throw new MediaUploadError(\n \"POST /api/public/media answered without a mediaId\",\n );\n const reference = new MediaReference(answer.mediaId, link.contentType);\n if (answer.uploadUrl)\n await this.store(reference, answer.uploadUrl, data, sha256Hash);\n return reference;\n }\n\n private async store(\n reference: MediaReference,\n url: string,\n data: Buffer,\n sha256Hash: string,\n ): Promise<void> {\n const started = Date.now();\n const { status, error } = await this.put(url, data, {\n \"Content-Type\": reference.contentType,\n \"x-amz-checksum-sha256\": sha256Hash,\n \"x-ms-blob-type\": \"BlockBlob\",\n });\n await this.send(\n \"PATCH\",\n `${MEDIA_PATH}/${encodeURIComponent(reference.mediaId)}`,\n {\n uploadedAt: new Date().toISOString(),\n uploadHttpStatus: status,\n uploadHttpError: error,\n uploadTimeMs: Date.now() - started,\n },\n );\n if (status < 200 || status >= 300)\n throw new MediaUploadError(\n `media storage refused the upload (HTTP ${status})`,\n status,\n );\n }\n\n private async send(\n method: PlatformMethod,\n route: string,\n body: unknown,\n ): Promise<unknown> {\n const reply = await this.transport.send(method, route, body);\n if (!reply.ok)\n throw new MediaUploadError(\n `${method} ${route} -> ${reply.status}`,\n reply.status,\n );\n return reply.text ? JSON.parse(reply.text) : {};\n }\n}\n","/**\n * One span per native-computer action, with the screen after it attached.\n * Each action runs inside a `computer.<action>` tool span whose input is the\n * action and whose output carries a media reference to the post-action\n * screenshot. With no tracer provider registered (tracing not initialized)\n * the span does not record and nothing is captured or uploaded; without\n * `@opentelemetry/api` installed the action runs with no span (CJS entries\n * and the bundled CLI; the ESM entries still import it through\n * `tracing/identity` and `scores`). A failed\n * upload never fails the action: it is warned about once.\n * Twin of `gatewaysdk/native_computer/trace.py`.\n */\nimport type { Span } from \"@opentelemetry/api\";\n\nimport { MediaUploader } from \"../../tracing/media\";\nimport type { ActionResult, ComputerAction } from \"./actions\";\n\nexport const SPAN_PREFIX = \"computer.\";\nconst MAX_UPLOAD_FAILURES = 3;\nconst TRACER_NAME = \"@withgateway/sdk\";\nconst MAX_ERROR = 1000;\n\ntype OtelApi = typeof import(\"@opentelemetry/api\");\n\nlet otelApi: OtelApi | null | undefined;\n\n/** `@opentelemetry/api` is an optional peer, and the bundled CLI reaches this\n * module at startup without it: load it on the first action, never at import. */\nfunction loadOtelApi(): OtelApi | null {\n if (otelApi !== undefined) return otelApi;\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n otelApi = require(\"@opentelemetry/api\") as OtelApi;\n } catch {\n otelApi = null;\n }\n return otelApi;\n}\n\nexport class ActionTracer {\n private failures = 0;\n private warned = false;\n\n constructor(\n readonly media: MediaUploader | null,\n private readonly warn: (message: string) => void = (m) => console.warn(m),\n ) {}\n\n static fromEnv(): ActionTracer {\n return new ActionTracer(MediaUploader.fromEnv());\n }\n\n /** `args` are already redacted. A failure's status goes through `scrub`:\n * browser errors quote the session's ws URL and UI token. */\n async span(\n action: ComputerAction,\n args: Record<string, unknown>,\n run: () => Promise<ActionResult>,\n capture: () => Promise<Buffer>,\n scrub: (text: string) => string,\n ): Promise<ActionResult> {\n const otel = loadOtelApi();\n if (!otel) return run();\n const { SpanStatusCode, trace } = otel;\n const attributes = {\n \"gateway.observation.type\": \"tool\",\n \"tool.name\": SPAN_PREFIX + action.name,\n \"gateway.observation.input\": JSON.stringify({\n action: action.name,\n ...args,\n }),\n };\n return trace\n .getTracer(TRACER_NAME)\n .startActiveSpan(\n SPAN_PREFIX + action.name,\n { attributes },\n async (span) => {\n try {\n const result = await run();\n await this.finish(span, result, capture);\n span.setStatus({ code: SpanStatusCode.OK });\n return result;\n } catch (error) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: scrub(errorText(error)).slice(0, MAX_ERROR),\n });\n throw error;\n } finally {\n span.end();\n }\n },\n );\n }\n\n private async finish(\n span: Span,\n result: ActionResult,\n capture: () => Promise<Buffer>,\n ): Promise<void> {\n if (!span.isRecording()) return;\n const output: Record<string, string> = {\n screenshot: await this.screenshot(span, result, capture),\n };\n if (result.text !== undefined) output.text = result.text;\n span.setAttribute(\"gateway.observation.output\", JSON.stringify(output));\n }\n\n private async screenshot(\n span: Span,\n result: ActionResult,\n capture: () => Promise<Buffer>,\n ): Promise<string> {\n let png: Buffer;\n try {\n png = result.image ?? (await capture());\n } catch (error) {\n return `[screenshot unavailable: ${errorName(error)}]`;\n }\n return this.reference(png, span);\n }\n\n private async reference(png: Buffer, span: Span): Promise<string> {\n if (!this.media)\n return \"[screenshot not uploaded: GATEWAY_HOST / GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY unset]\";\n if (this.failures >= MAX_UPLOAD_FAILURES)\n return \"[screenshot not uploaded: uploads disabled after repeated failures]\";\n const { traceId, spanId } = span.spanContext();\n try {\n const reference = await this.media.upload(png, {\n contentType: \"image/png\",\n traceId,\n observationId: spanId,\n field: \"output\",\n });\n this.failures = 0;\n return reference.toString();\n } catch (error) {\n return this.failed(error);\n }\n }\n\n private failed(error: unknown): string {\n this.failures += 1;\n if (!this.warned) {\n this.warned = true;\n this.warn(\n `native computer: screenshot upload failed (${errorName(error)}: ${error instanceof Error ? error.message : String(error)}); spans keep going without it`,\n );\n }\n return `[screenshot not uploaded: ${errorName(error)}]`;\n }\n}\n\nfunction errorText(error: unknown): string {\n return error instanceof Error\n ? `${error.name}: ${error.message}`\n : String(error);\n}\n\nfunction errorName(error: unknown): string {\n return error instanceof Error ? error.name : \"Error\";\n}\n","/**\n * A provider kind (a subclass) knows only its wire format;\n * `NativeComputer.forProvider` is the one place a kind is chosen.\n * Twin of `gatewaysdk/native_computer/base.py`.\n */\nimport { redactActionArgs } from \"../browser\";\nimport { ComputerAction, type ActionResult } from \"./actions\";\nimport { Display } from \"./display\";\nimport { Screen, type ScreenBrowser } from \"./screen\";\nimport { ActionTracer } from \"./trace\";\n\nconst REPLAYABLE = new Set([\"screenshot\", \"zoom\", \"cursor_position\", \"wait\"]);\nconst SETTLING = new Set([\"click\", \"mouse_up\", \"drag\", \"key\", \"history\"]);\nconst EVENT_PREFIX = \"computer_\";\n\nexport type NativeComputerOptions = {\n /** The pixel size the model sees; default the viewport, or the largest\n * downscale that fits the provider's image limits. */\n display?: [number, number];\n /** Records one span per action with the screen after it; default uploads\n * screenshots with the `GATEWAY_*` keys when tracing is initialized. */\n tracer?: ActionTracer;\n};\n\n/** The major version of the `ai` package the tools are handed to. */\nexport type AiSdkMajor = 6 | 7;\n\nexport type AiSdkOptions<V extends AiSdkMajor = 6> = {\n /** The Anthropic kinds' screenshot part. Default 6: `image-data`, which\n * AI SDK 7 still accepts with a deprecation warning. 7: the `file` part with\n * `{ type: \"data\", data }`, which AI SDK 6 does not accept. The OpenAI kinds\n * return the provider's own `computer_screenshot` output and ignore it. */\n version?: V;\n};\n\ntype Kind = new (\n browser: ScreenBrowser,\n options?: NativeComputerOptions,\n) => NativeComputer;\n\n/** `item[name]` for the first spelling that is set (`scroll_x`, `scrollX`). */\nexport function readField(item: unknown, ...names: string[]): unknown {\n const record = (item ?? {}) as Record<string, unknown>;\n return names\n .map((name) => record[name])\n .find((value) => value !== undefined && value !== null);\n}\n\nexport abstract class NativeComputer {\n private static readonly kinds = new Map<string, Kind>();\n\n readonly display: Display;\n readonly screen: Screen;\n readonly tracer: ActionTracer;\n private queue: Promise<unknown> = Promise.resolve();\n\n static register(provider: string, kind: Kind): void {\n NativeComputer.kinds.set(provider, kind);\n }\n\n static get providers(): string[] {\n return [...NativeComputer.kinds.keys()].sort();\n }\n\n static forProvider(\n provider: string,\n browser: ScreenBrowser,\n options: NativeComputerOptions = {},\n ): NativeComputer {\n const Kind = NativeComputer.kinds.get(provider);\n if (!Kind)\n throw new Error(\n `unknown computer-use provider '${provider}'; choose from ${NativeComputer.providers.join(\", \")}`,\n );\n return new Kind(browser, options);\n }\n\n constructor(\n readonly browser: ScreenBrowser,\n options: NativeComputerOptions = {},\n ) {\n const kind = this.constructor as typeof NativeComputer;\n this.display = Display.forViewport(\n browser.viewport,\n options.display,\n (w, h) => kind.fits(w, h),\n );\n this.screen = new Screen(browser, this.display);\n this.tracer = options.tracer ?? ActionTracer.fromEnv();\n }\n\n /** Whether a screenshot of this size is within the provider's limits. */\n static fits(_width: number, _height: number): boolean {\n return true;\n }\n\n /** The tool definition to send the model. */\n abstract tool(): Record<string, unknown>;\n\n /** One action in the provider's own shape, as a `ComputerAction`. */\n abstract parse(raw: unknown): ComputerAction;\n\n /** The options to spread into the Vercel AI SDK's provider-defined computer\n * tool (`execute` and its companions), backed by this computer. */\n abstract aiSdk(options?: AiSdkOptions<AiSdkMajor>): object;\n\n /** Run one provider-shaped action (an OpenAI action object, or an Anthropic\n * `{ action: \"left_click\", ... }` input) and return what it produced: the\n * door for any agent framework that hands actions over one at a time. */\n executeAction(raw: unknown): Promise<ActionResult> {\n return this.perform(this.parse(raw));\n }\n\n /** Run one action on the page: reported on the session's browser timeline\n * and, when tracing is on, as a span with the screen after. */\n async perform(action: ComputerAction): Promise<ActionResult> {\n const secret =\n action.name === \"type\" && (await this.screen.focusedFieldIsSecret());\n const event = EVENT_PREFIX + action.name;\n const args = redactActionArgs(event, action.recordArgs(secret));\n return this.tracer.span(\n action,\n args,\n () =>\n this.browser.act(\n event,\n args,\n () => this.runOnScreen(action),\n this.onLoss(action),\n ),\n () => this.screen.screenshot(),\n (text) => this.browser.scrub(text),\n );\n }\n\n async performAll(\n actions: readonly ComputerAction[],\n ): Promise<ActionResult[]> {\n const results: ActionResult[] = [];\n for (const action of actions) results.push(await this.perform(action));\n return results;\n }\n\n /** The screen as the model sees it, as a traced `screenshot` action. */\n async screenshot(): Promise<Buffer> {\n return (\n (await this.perform(new ComputerAction(\"screenshot\"))).image ??\n Buffer.alloc(0)\n );\n }\n\n /** Run `fn` after every earlier call made through here: the AI SDK starts a\n * step's tool calls concurrently, but one screen takes one action at a time. */\n protected serial<T>(fn: () => Promise<T>): Promise<T> {\n const next = this.queue.then(fn, fn);\n this.queue = next.catch(() => undefined);\n return next;\n }\n\n private async runOnScreen(action: ComputerAction): Promise<ActionResult> {\n const result = await this.screen.run(action);\n if (SETTLING.has(action.name)) await this.browser.settle();\n return result;\n }\n\n private onLoss(action: ComputerAction): \"retry\" | \"report\" {\n return REPLAYABLE.has(action.name) ? \"retry\" : \"report\";\n }\n}\n","/**\n * Key names from each provider's vocabulary, mapped once to Playwright's.\n * Anthropic sends xdotool-style chords (`ctrl+a`, `Return`); OpenAI sends\n * arrays of upper-case names (`[\"CTRL\", \"A\"]`). Twin of\n * `gatewaysdk/native_computer/keys.py`; `conformance/native-computer.json` pins both.\n */\n\nconst F_KEYS = Object.fromEntries(\n Array.from({ length: 12 }, (_, i) => [`f${i + 1}`, `F${i + 1}`]),\n);\n\nexport const KEY_NAMES: Readonly<Record<string, string>> = {\n return: \"Enter\",\n enter: \"Enter\",\n kp_enter: \"Enter\",\n esc: \"Escape\",\n escape: \"Escape\",\n tab: \"Tab\",\n space: \"Space\",\n backspace: \"Backspace\",\n delete: \"Delete\",\n del: \"Delete\",\n insert: \"Insert\",\n home: \"Home\",\n end: \"End\",\n pageup: \"PageUp\",\n page_up: \"PageUp\",\n prior: \"PageUp\",\n pagedown: \"PageDown\",\n page_down: \"PageDown\",\n next: \"PageDown\",\n up: \"ArrowUp\",\n arrowup: \"ArrowUp\",\n down: \"ArrowDown\",\n arrowdown: \"ArrowDown\",\n left: \"ArrowLeft\",\n arrowleft: \"ArrowLeft\",\n right: \"ArrowRight\",\n arrowright: \"ArrowRight\",\n ctrl: \"Control\",\n control: \"Control\",\n shift: \"Shift\",\n alt: \"Alt\",\n option: \"Alt\",\n super: \"Meta\",\n meta: \"Meta\",\n cmd: \"Meta\",\n command: \"Meta\",\n win: \"Meta\",\n capslock: \"CapsLock\",\n caps_lock: \"CapsLock\",\n plus: \"+\",\n minus: \"-\",\n ...F_KEYS,\n};\n\n/** One provider key name as Playwright names it; an unknown name passes through. */\nexport function playwrightKey(token: string): string {\n return KEY_NAMES[token.toLowerCase()] ?? token;\n}\n\nfunction letterOrName(key: string): string {\n return /^[a-zA-Z]$/.test(key) ? key.toLowerCase() : playwrightKey(key);\n}\n\n/** Keys pressed together, in Playwright's names (`[\"Control\", \"a\"]`). */\nexport class KeyChord {\n private constructor(readonly keys: readonly string[]) {\n if (keys.length === 0)\n throw new Error(\"a key action needs at least one key\");\n }\n\n /** `ctrl+shift+t` / `Return`: Anthropic's vocabulary, case kept. */\n static fromXdotool(text: string): KeyChord {\n return new KeyChord(\n text.trim().split(\"+\").filter(Boolean).map(playwrightKey),\n );\n }\n\n /** `[\"CTRL\", \"A\"]`: OpenAI's vocabulary. A lone letter is the unshifted key. */\n static fromKeys(keys: readonly string[]): KeyChord {\n return new KeyChord(keys.map(letterOrName));\n }\n\n /** What `page.keyboard.press` takes: `Control+a`. */\n get combo(): string {\n return this.keys.join(\"+\");\n }\n}\n\n/** The modifiers an Anthropic click/scroll holds (`text: \"ctrl+shift\"`). */\nexport function modifierChord(text: unknown): string[] {\n return typeof text === \"string\" && text\n ? [...KeyChord.fromXdotool(text).keys]\n : [];\n}\n\n/** The modifiers an OpenAI mouse action holds (`keys: [\"SHIFT\"]`). */\nexport function modifierKeys(keys: unknown): string[] {\n return Array.isArray(keys) && keys.length > 0\n ? [...KeyChord.fromKeys(keys.map(String)).keys]\n : [];\n}\n","/**\n * Docs: https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool\n * Twin of `gatewaysdk/native_computer/anthropic.py`.\n */\nimport {\n ComputerAction,\n toInt,\n toNumber,\n type ActionResult,\n type MouseButton,\n type Point,\n} from \"./actions\";\nimport {\n NativeComputer,\n readField,\n type AiSdkMajor,\n type AiSdkOptions,\n} from \"./base\";\nimport { KeyChord, modifierChord } from \"./keys\";\n\nconst SCROLL_STEP_PX = 100;\nexport const NOT_EXECUTED =\n \"Not executed: an earlier computer action in this turn failed.\";\nconst MAX_ERROR = 1000;\nconst SCROLL_DIRECTIONS: Record<string, Point> = {\n up: [0, -1],\n down: [0, 1],\n left: [-1, 0],\n right: [1, 0],\n};\n\ntype Raw = Record<string, unknown>;\n\nexport type AiSdkAnthropicOutput = { type: \"image\"; data: string } | string;\ntype ImageParts = {\n 6: { type: \"image-data\"; data: string; mediaType: \"image/png\" };\n 7: {\n type: \"file\";\n mediaType: \"image/png\";\n data: { type: \"data\"; data: string };\n };\n};\nexport type AiSdkImagePart<V extends AiSdkMajor = AiSdkMajor> = ImageParts[V];\nexport type AiSdkModelOutput<V extends AiSdkMajor = 6> =\n | { type: \"text\"; value: string }\n | { type: \"content\"; value: AiSdkImagePart<V>[] };\n\nconst IMAGE_PARTS: {\n [V in AiSdkMajor]: (data: string) => AiSdkImagePart<V>;\n} = {\n 6: (data) => ({ type: \"image-data\", data, mediaType: \"image/png\" }),\n 7: (data) => ({\n type: \"file\",\n mediaType: \"image/png\",\n data: { type: \"data\", data },\n }),\n};\n\nexport type AnthropicContent =\n | { type: \"text\"; text: string }\n | {\n type: \"image\";\n source: { type: \"base64\"; media_type: \"image/png\"; data: string };\n };\n\nexport type AnthropicToolResult = {\n type: \"tool_result\";\n tool_use_id: string;\n toolset_name?: string;\n content: AnthropicContent[] | string;\n is_error?: true;\n};\n\nfunction required(raw: Raw, key: string): unknown {\n const value = raw[key];\n if (value === undefined || value === null)\n throw new Error(`${String(raw.action)} needs ${key}`);\n return value;\n}\n\nfunction pair(raw: Raw, key: string): Point {\n const value = required(raw, key) as unknown[];\n return [toInt(value[0]), toInt(value[1])];\n}\n\nfunction point(raw: Raw): { x?: number; y?: number } {\n if (raw.coordinate === undefined || raw.coordinate === null) return {};\n const [x, y] = pair(raw, \"coordinate\");\n return { x, y };\n}\n\nfunction chord(raw: Raw): string[] {\n return [...KeyChord.fromXdotool(String(required(raw, \"text\"))).keys];\n}\n\nfunction click(button: MouseButton, count: number) {\n return (raw: Raw) =>\n new ComputerAction(\"click\", {\n ...point(raw),\n button,\n count,\n modifiers: modifierChord(raw.text),\n });\n}\n\nconst MEMBERS: Record<string, (raw: Raw) => ComputerAction> = {\n screenshot: () => new ComputerAction(\"screenshot\"),\n zoom: (raw) =>\n new ComputerAction(\"zoom\", {\n region: (required(raw, \"region\") as unknown[]).map(toInt) as [\n number,\n number,\n number,\n number,\n ],\n }),\n left_click: click(\"left\", 1),\n right_click: click(\"right\", 1),\n middle_click: click(\"middle\", 1),\n double_click: click(\"left\", 2),\n triple_click: click(\"left\", 3),\n left_click_drag: (raw) =>\n new ComputerAction(\"drag\", {\n path: [pair(raw, \"start_coordinate\"), pair(raw, \"coordinate\")],\n modifiers: modifierChord(raw.text),\n }),\n mouse_move: (raw) => {\n const [x, y] = pair(raw, \"coordinate\");\n return new ComputerAction(\"move\", { x, y });\n },\n left_mouse_down: () => new ComputerAction(\"mouse_down\", { button: \"left\" }),\n left_mouse_up: () => new ComputerAction(\"mouse_up\", { button: \"left\" }),\n cursor_position: () => new ComputerAction(\"cursor_position\"),\n scroll: (raw) => {\n const direction = String(raw.scroll_direction ?? \"down\");\n if (!Object.hasOwn(SCROLL_DIRECTIONS, direction))\n throw new Error(\n `scroll_direction must be one of ${Object.keys(SCROLL_DIRECTIONS).join(\", \")}`,\n );\n const [dx, dy] = SCROLL_DIRECTIONS[direction];\n const amount = toInt(raw.scroll_amount ?? 1) * SCROLL_STEP_PX;\n return new ComputerAction(\"scroll\", {\n ...point(raw),\n dx: dx * amount,\n dy: dy * amount,\n modifiers: modifierChord(raw.text),\n });\n },\n type: (raw) =>\n new ComputerAction(\"type\", { text: String(required(raw, \"text\")) }),\n key: (raw) =>\n new ComputerAction(\"key\", {\n keys: chord(raw),\n repeat: toInt(raw.repeat ?? 1),\n }),\n hold_key: (raw) =>\n new ComputerAction(\"hold_key\", {\n keys: chord(raw),\n seconds: toNumber(required(raw, \"duration\")),\n }),\n wait: (raw) =>\n new ComputerAction(\"wait\", { seconds: toNumber(raw.duration ?? 1) }),\n};\n\n/** `computer_toolset_20260801` for Claude 5-family models (claude-sonnet-5-5,\n * claude-opus-5-5, ...): send `tool()` in `tools`, pass each response's\n * `content` to `execute`, and send the returned blocks back as the next user\n * message. */\nexport class AnthropicComputer extends NativeComputer {\n static readonly TOOL_TYPE: string = \"computer_toolset_20260801\";\n static readonly TOOLSET = \"computer\";\n static readonly BETA: string | null = null;\n static readonly MAX_LONG_EDGE: number = 2576;\n static readonly MAX_VISUAL_TOKENS = 4784;\n static readonly PATCH_PX = 28;\n\n static fits(width: number, height: number): boolean {\n const tokens =\n Math.ceil(width / this.PATCH_PX) * Math.ceil(height / this.PATCH_PX);\n return (\n Math.max(width, height) <= this.MAX_LONG_EDGE &&\n tokens <= this.MAX_VISUAL_TOKENS\n );\n }\n\n tool(): Record<string, unknown> {\n return { type: AnthropicComputer.TOOL_TYPE };\n }\n\n /** Whether a content block is a call to this computer. */\n owns(block: unknown): boolean {\n return (\n readField(block, \"type\") === \"tool_use\" &&\n readField(block, \"toolset_name\") === AnthropicComputer.TOOLSET\n );\n }\n\n member(block: unknown): [string, Raw] {\n return [\n String(readField(block, \"name\")),\n { ...((readField(block, \"input\") as Raw) ?? {}) },\n ];\n }\n\n parse(raw: unknown): ComputerAction {\n const name = String(readField(raw, \"action\"));\n const parser = Object.hasOwn(MEMBERS, name) ? MEMBERS[name] : undefined;\n if (!parser) throw new Error(`unknown computer action: ${name}`);\n return parser(raw as Raw);\n }\n\n /** Run every computer `tool_use` in a response's content, in order, and\n * return one `tool_result` per block. Other blocks are skipped. */\n async execute(content: Iterable<unknown>): Promise<AnthropicToolResult[]> {\n const results: AnthropicToolResult[] = [];\n let failed = false;\n for (const block of content) {\n if (!this.owns(block)) continue;\n if (failed) {\n results.push(this.envelope(block, NOT_EXECUTED, true));\n continue;\n }\n const [result, blockFailed] = await this.runBlock(block);\n results.push(result);\n failed = blockFailed;\n }\n return results;\n }\n\n /** The content an `ActionResult` goes back to the model as. */\n static content(result: ActionResult): AnthropicContent[] {\n if (result.image)\n return [\n {\n type: \"image\",\n source: {\n type: \"base64\",\n media_type: \"image/png\",\n data: result.image.toString(\"base64\"),\n },\n },\n ];\n return [{ type: \"text\", text: result.text ?? \"OK\" }];\n }\n\n /** For `anthropic.tools.computerToolset_20260801(computer.aiSdk({ version: 7 }))`\n * (AI SDK 7 only), or `computer_20251124` with the legacy kind (AI SDK 6\n * and 7): `execute` runs one action and returns `{ type: \"image\", data }` or\n * text; `toModelOutput` turns that into the tool result in the part shape\n * of `options.version`. Calls run one at a time, and once a call fails the\n * rest of that step's calls answer as not executed. */\n aiSdk<V extends AiSdkMajor = 6>(\n options: AiSdkOptions<V> = {},\n ): {\n execute: (\n input: unknown,\n options?: { messages?: readonly unknown[] },\n ) => Promise<AiSdkAnthropicOutput>;\n toModelOutput: (options: {\n output: AiSdkAnthropicOutput;\n }) => AiSdkModelOutput<V>;\n } {\n const imagePart = AnthropicComputer.imagePart(options);\n let failedStep: number | undefined;\n const execute = (\n input: unknown,\n options?: { messages?: readonly unknown[] },\n ) =>\n this.serial(async () => {\n const step = options?.messages?.length;\n if (step !== undefined && step === failedStep)\n throw new Error(NOT_EXECUTED);\n try {\n return AnthropicComputer.aiSdkOutput(await this.executeAction(input));\n } catch (error) {\n failedStep = step;\n throw error instanceof Error\n ? new Error(this.browser.scrub(error.message))\n : error;\n }\n });\n return {\n execute,\n toModelOutput: ({ output }) =>\n AnthropicComputer.modelOutput(output, imagePart),\n };\n }\n\n static aiSdkOutput(result: ActionResult): AiSdkAnthropicOutput {\n if (result.image)\n return { type: \"image\", data: result.image.toString(\"base64\") };\n return result.text ?? \"OK\";\n }\n\n /** A screenshot as the image part of AI SDK `options.version`:\n * `image-data` for 6 (the default), `file` with `{ type: \"data\", data }`\n * for 7. */\n static aiSdkModelOutput<V extends AiSdkMajor = 6>(\n output: AiSdkAnthropicOutput,\n options: AiSdkOptions<V> = {},\n ): AiSdkModelOutput<V> {\n return AnthropicComputer.modelOutput(\n output,\n AnthropicComputer.imagePart(options),\n );\n }\n\n private static imagePart<V extends AiSdkMajor>({\n version = 6 as V,\n }: AiSdkOptions<V>): (data: string) => AiSdkImagePart<V> {\n if (Object.hasOwn(IMAGE_PARTS, version)) return IMAGE_PARTS[version];\n throw new Error(\n `unsupported AI SDK version ${version}; choose ${Object.keys(IMAGE_PARTS).join(\" or \")}`,\n );\n }\n\n private static modelOutput<V extends AiSdkMajor>(\n output: AiSdkAnthropicOutput,\n imagePart: (data: string) => AiSdkImagePart<V>,\n ): AiSdkModelOutput<V> {\n if (typeof output === \"string\") return { type: \"text\", value: output };\n return { type: \"content\", value: [imagePart(output.data)] };\n }\n\n protected envelope(\n block: unknown,\n content: AnthropicContent[] | string,\n isError = false,\n ): AnthropicToolResult {\n return {\n type: \"tool_result\",\n tool_use_id: String(readField(block, \"id\")),\n toolset_name: AnthropicComputer.TOOLSET,\n content,\n ...(isError ? { is_error: true as const } : {}),\n };\n }\n\n private async runBlock(\n block: unknown,\n ): Promise<[AnthropicToolResult, boolean]> {\n const [name, payload] = this.member(block);\n try {\n const result = await this.executeAction({ ...payload, action: name });\n return [this.envelope(block, AnthropicComputer.content(result)), false];\n } catch (error) {\n const detail =\n error instanceof Error\n ? `${error.name}: ${error.message}`\n : String(error);\n return [\n this.envelope(\n block,\n this.browser.scrub(`Error: ${detail}`).slice(0, MAX_ERROR),\n true,\n ),\n true,\n ];\n }\n }\n}\n\n/** The `computer_20251124` tool (beta header `computer-use-2025-11-24`) for\n * models before the toolset, and Claude 5.5 on Amazon Bedrock: one tool named\n * `computer` whose input carries `action`. */\nexport class AnthropicComputer20251124 extends AnthropicComputer {\n static readonly TOOL_TYPE = \"computer_20251124\";\n static readonly BETA = \"computer-use-2025-11-24\";\n static readonly MAX_LONG_EDGE = 1568;\n static readonly MAX_PIXELS = 1_150_000;\n\n static fits(width: number, height: number): boolean {\n return (\n Math.max(width, height) <= this.MAX_LONG_EDGE &&\n width * height <= this.MAX_PIXELS\n );\n }\n\n tool(): Record<string, unknown> {\n return {\n type: AnthropicComputer20251124.TOOL_TYPE,\n name: AnthropicComputer.TOOLSET,\n display_width_px: this.display.width,\n display_height_px: this.display.height,\n enable_zoom: true,\n };\n }\n\n owns(block: unknown): boolean {\n return (\n readField(block, \"type\") === \"tool_use\" &&\n readField(block, \"name\") === AnthropicComputer.TOOLSET\n );\n }\n\n member(block: unknown): [string, Raw] {\n const { action, ...payload } = (readField(block, \"input\") as Raw) ?? {};\n return [String(action ?? \"\"), payload];\n }\n\n protected envelope(\n block: unknown,\n content: AnthropicContent[] | string,\n isError = false,\n ): AnthropicToolResult {\n const { toolset_name: _dropped, ...rest } = super.envelope(\n block,\n content,\n isError,\n );\n return rest;\n }\n}\n\nNativeComputer.register(\"anthropic\", AnthropicComputer);\nNativeComputer.register(\n \"anthropic-computer-20251124\",\n AnthropicComputer20251124,\n);\n","/**\n * OpenAI's computer use: the Responses API `computer` tool (GA), and the\n * legacy `computer_use_preview` tool as a second kind. Each `computer_call`\n * carries an ordered batch of `actions` (the preview carried one `action`);\n * they run in order, then the screen goes back as a `computer_call_output`.\n * A call with `pending_safety_checks` is not executed until the caller passes\n * them back as `acknowledged`.\n * Docs: https://developers.openai.com/api/docs/guides/tools-computer-use\n * Twin of `gatewaysdk/native_computer/openai.py`.\n */\nimport { ComputerAction, toInt, type MouseButton, type Point } from \"./actions\";\nimport { NativeComputer, readField } from \"./base\";\nimport { KeyChord, modifierKeys } from \"./keys\";\n\nconst WAIT_SECONDS = 1;\nconst BUTTONS: Record<string, MouseButton> = {\n left: \"left\",\n right: \"right\",\n wheel: \"middle\",\n middle: \"middle\",\n};\nconst HISTORY_BUTTONS = new Set([\"back\", \"forward\"]);\n\nexport type SafetyCheck = { id: string; code?: string; message?: string };\n\nexport type ComputerCallOutput = {\n type: \"computer_call_output\";\n call_id: string;\n output: {\n type: \"computer_screenshot\";\n image_url: string;\n detail: \"original\";\n };\n acknowledged_safety_checks?: SafetyCheck[];\n};\n\nexport type AiSdkComputerCall = {\n actions?: unknown[];\n pendingSafetyChecks?: unknown[];\n};\nexport type AiSdkComputerOutput = {\n output: { type: \"computer_screenshot\"; imageUrl: string };\n acknowledgedSafetyChecks?: SafetyCheck[];\n};\n\n/** The model flagged this call; nothing ran. Show `checks` to a person, then\n * `execute(call, checks)` to run it anyway. */\nexport class PendingSafetyChecks extends Error {\n constructor(\n readonly callId: string,\n readonly checks: SafetyCheck[],\n ) {\n const listed = checks\n .map((c) => `${c.code ?? \"check\"}: ${c.message ?? \"\"}`.trim())\n .join(\"; \");\n super(\n `computer_call ${callId} needs ${checks.length} safety check(s) acknowledged: ${listed}`,\n );\n this.name = \"PendingSafetyChecks\";\n }\n}\n\nexport function safetyCheck(raw: unknown): SafetyCheck {\n const check: SafetyCheck = { id: String(readField(raw, \"id\") ?? \"\") };\n const code = readField(raw, \"code\");\n const message = readField(raw, \"message\");\n if (code !== undefined) check.code = String(code);\n if (message !== undefined) check.message = String(message);\n return check;\n}\n\nexport function dataUrl(png: Buffer): string {\n return `data:image/png;base64,${png.toString(\"base64\")}`;\n}\n\nfunction xy(raw: unknown): { x: number; y: number } {\n return {\n x: toInt(readField(raw, \"x\") ?? 0),\n y: toInt(readField(raw, \"y\") ?? 0),\n };\n}\n\nfunction held(raw: unknown): string[] {\n return modifierKeys(readField(raw, \"keys\"));\n}\n\nconst ACTIONS: Record<string, (raw: unknown) => ComputerAction> = {\n click: (raw) => {\n const button = String(readField(raw, \"button\") ?? \"left\");\n if (HISTORY_BUTTONS.has(button))\n return new ComputerAction(\"history\", {\n direction: button as \"back\" | \"forward\",\n });\n if (!Object.hasOwn(BUTTONS, button))\n throw new Error(`unknown mouse button: ${button}`);\n return new ComputerAction(\"click\", {\n ...xy(raw),\n button: BUTTONS[button],\n count: 1,\n modifiers: held(raw),\n });\n },\n double_click: (raw) =>\n new ComputerAction(\"click\", {\n ...xy(raw),\n button: \"left\",\n count: 2,\n modifiers: held(raw),\n }),\n drag: (raw) =>\n new ComputerAction(\"drag\", {\n path: ((readField(raw, \"path\") as unknown[]) ?? []).map(\n (p): Point => [toInt(readField(p, \"x\")), toInt(readField(p, \"y\"))],\n ),\n modifiers: held(raw),\n }),\n keypress: (raw) =>\n new ComputerAction(\"key\", {\n keys: [\n ...KeyChord.fromKeys((readField(raw, \"keys\") as string[]) ?? []).keys,\n ],\n repeat: 1,\n }),\n move: (raw) =>\n new ComputerAction(\"move\", { ...xy(raw), modifiers: held(raw) }),\n scroll: (raw) =>\n new ComputerAction(\"scroll\", {\n ...xy(raw),\n dx: toInt(readField(raw, \"scroll_x\", \"scrollX\") ?? 0),\n dy: toInt(readField(raw, \"scroll_y\", \"scrollY\") ?? 0),\n modifiers: held(raw),\n }),\n type: (raw) =>\n new ComputerAction(\"type\", { text: String(readField(raw, \"text\") ?? \"\") }),\n wait: () => new ComputerAction(\"wait\", { seconds: WAIT_SECONDS }),\n screenshot: () => new ComputerAction(\"screenshot\"),\n};\n\n/** The GA `computer` tool (gpt-5.5, gpt-5.6-sol and the other models whose\n * page lists computer use): send `tool()` in `tools`, pass each\n * `computer_call` item to `execute`, and send the returned\n * `computer_call_output` back with `previous_response_id`. */\nexport class OpenAIComputer extends NativeComputer {\n tool(): Record<string, unknown> {\n return { type: \"computer\" };\n }\n\n owns(item: unknown): boolean {\n return readField(item, \"type\") === \"computer_call\";\n }\n\n parse(raw: unknown): ComputerAction {\n const kind = String(readField(raw, \"type\"));\n const parser = Object.hasOwn(ACTIONS, kind) ? ACTIONS[kind] : undefined;\n if (!parser) throw new Error(`unknown computer action: ${kind}`);\n return parser(raw);\n }\n\n static actionsOf(call: unknown): unknown[] {\n const batch = readField(call, \"actions\");\n if (Array.isArray(batch)) return batch;\n const single = readField(call, \"action\");\n return single === undefined ? [] : [single];\n }\n\n /** Run a `computer_call`'s actions and return its `computer_call_output`.\n * Throws `PendingSafetyChecks` (before anything runs) while a check the\n * model raised is not in `acknowledged`. */\n async execute(\n call: unknown,\n acknowledged: readonly unknown[] = [],\n ): Promise<ComputerCallOutput> {\n const callId = String(readField(call, \"call_id\", \"callId\"));\n const checks = (\n (readField(\n call,\n \"pending_safety_checks\",\n \"pendingSafetyChecks\",\n ) as unknown[]) ?? []\n ).map(safetyCheck);\n const png = await this.runCall(\n callId,\n OpenAIComputer.actionsOf(call),\n checks,\n acknowledged,\n );\n return {\n type: \"computer_call_output\",\n call_id: callId,\n output: {\n type: \"computer_screenshot\",\n image_url: dataUrl(png),\n detail: \"original\",\n },\n ...(checks.length > 0 ? { acknowledged_safety_checks: checks } : {}),\n };\n }\n\n /** For `openai.tools.computer({ ...computer.aiSdk() })`: `execute` runs a\n * call's `actions` and returns the screenshot output. A call with pending\n * safety checks asks for approval first (`needsApproval`), so the AI SDK's\n * approval flow puts them in front of a person; once approved, `execute`\n * acknowledges them. */\n aiSdk(): {\n execute: (input: AiSdkComputerCall) => Promise<AiSdkComputerOutput>;\n needsApproval: (input: AiSdkComputerCall) => boolean;\n } {\n return {\n needsApproval: (input) => (input.pendingSafetyChecks ?? []).length > 0,\n execute: (input) =>\n this.serial(async () => {\n const checks = (input.pendingSafetyChecks ?? []).map(safetyCheck);\n const png = await this.runCall(\n \"ai-sdk\",\n input.actions ?? [],\n checks,\n checks,\n );\n return {\n output: { type: \"computer_screenshot\", imageUrl: dataUrl(png) },\n ...(checks.length > 0 ? { acknowledgedSafetyChecks: checks } : {}),\n };\n }),\n };\n }\n\n /** The batch's actions, run after the safety checks clear; the screen after them. */\n async runCall(\n callId: string,\n rawActions: readonly unknown[],\n checks: readonly SafetyCheck[],\n acknowledged: readonly unknown[],\n ): Promise<Buffer> {\n const cleared = new Set(acknowledged.map((c) => safetyCheck(c).id));\n const waiting = checks.filter((c) => !c.id || !cleared.has(c.id));\n if (waiting.length > 0) throw new PendingSafetyChecks(callId, waiting);\n const actions = rawActions.map((raw) => this.parse(raw));\n const results = await this.performAll(actions);\n const last = actions.at(-1);\n if (last?.name === \"screenshot\")\n return results.at(-1)?.image ?? Buffer.alloc(0);\n return this.screenshot();\n }\n}\n\n/** The legacy `computer_use_preview` tool for the `computer-use-preview`\n * model: it declares the display size and `environment: \"browser\"`. */\nexport class OpenAIPreviewComputer extends OpenAIComputer {\n tool(): Record<string, unknown> {\n return {\n type: \"computer_use_preview\",\n display_width: this.display.width,\n display_height: this.display.height,\n environment: \"browser\",\n };\n }\n}\n\nNativeComputer.register(\"openai\", OpenAIComputer);\nNativeComputer.register(\"openai-preview\", OpenAIPreviewComputer);\n","/** Python twin: `gatewaysdk/native_computer/`. */\nexport {\n ComputerAction,\n ACTION_NAMES,\n type ActionResult,\n type ActionArgs,\n} from \"./actions\";\nexport {\n NativeComputer,\n readField,\n type AiSdkMajor,\n type AiSdkOptions,\n type NativeComputerOptions,\n} from \"./base\";\nexport { Display } from \"./display\";\nexport { KEY_NAMES, KeyChord, playwrightKey } from \"./keys\";\nexport { Screen, type NativePage, type ScreenBrowser } from \"./screen\";\nexport { ActionTracer, SPAN_PREFIX } from \"./trace\";\nexport {\n AnthropicComputer,\n AnthropicComputer20251124,\n NOT_EXECUTED,\n type AiSdkAnthropicOutput,\n type AiSdkImagePart,\n type AiSdkModelOutput,\n type AnthropicToolResult,\n} from \"./anthropic\";\nimport type { AnthropicComputer, AnthropicComputer20251124 } from \"./anthropic\";\nimport type { OpenAIComputer, OpenAIPreviewComputer } from \"./openai\";\n\n/** The class each provider name builds, so a caller gets the kind's own\n * `execute` without a cast. */\nexport type NativeComputerKinds = {\n anthropic: AnthropicComputer;\n \"anthropic-computer-20251124\": AnthropicComputer20251124;\n openai: OpenAIComputer;\n \"openai-preview\": OpenAIPreviewComputer;\n};\nexport type NativeComputerProvider = keyof NativeComputerKinds;\n\nexport {\n OpenAIComputer,\n OpenAIPreviewComputer,\n PendingSafetyChecks,\n type AiSdkComputerCall,\n type AiSdkComputerOutput,\n type ComputerCallOutput,\n type SafetyCheck,\n} from \"./openai\";\n","/**\n * The platform declares these once in\n * `gateway/packages/shared/src/server/services/worldSessionContract.ts`; this\n * module and `gatewaysdk/environment/world_session_contract.py` repeat them, and each is\n * pinned to `conformance/world-sessions.json` by a test, so the route, the\n * World Host and the two CLIs cannot drift apart.\n */\n\n/** The largest body `POST world-sessions/{id}/calls` accepts. The SDK\n * measures the serialized body against the byte count and refuses before\n * sending; the label is what help and the refusal name. */\nexport const CALL_BODY_LIMIT_BYTES = 4 * 1024 * 1024;\nexport const CALL_BODY_LIMIT_LABEL = \"4mb\";\n\n/** `session status` warns once an unpinned session has less than this left. */\nexport const IDLE_WARNING_MINUTES = 5;\n\n/** The most entries one page of a world's request ledger holds. */\nexport const REQUEST_LOG_PAGE_MAX = 200;\n\n/** How much of each body the request ledger keeps: the first this many bytes of its text. */\nexport const REQUEST_BODY_CAPTURE_BYTES = 64 * 1024;\n\n/** The code a session the World Host did not serve answers its request ledger read with. */\nexport const REQUESTS_NOT_RECORDED = \"requests_not_recorded\";\n\n/** The task an exploratory session runs on when the caller names none, and\n * the `task.source` the platform reports for it. */\nexport const EXPLORATORY_TASK = Object.freeze({\n instruction: \"exploratory session\",\n});\nexport const EXPLORATORY_TASK_SOURCE = \"none\";\n\n/** What a session that has no grader answers `grade` with, beside\n * `reward: null`. */\nexport const NO_GRADER_REASON = \"no grader\";\n\n/** The call's body exceeds the platform's limit: nothing was sent. `limit`\n * is the label the route enforces (`4mb`), `size` the body's bytes. */\nexport class WorldCallTooLarge extends Error {\n readonly code = \"payload_too_large\";\n\n constructor(\n readonly size: number,\n readonly limitBytes: number = CALL_BODY_LIMIT_BYTES,\n readonly limit: string = CALL_BODY_LIMIT_LABEL,\n ) {\n super(\n `call body is ${size} bytes; the platform accepts at most ${limit} (${limitBytes} bytes)`,\n );\n this.name = \"WorldCallTooLarge\";\n }\n\n /** The structured refusal the CLIs print. */\n toJSON(): {\n status: \"error\";\n code: \"payload_too_large\";\n limit: string;\n size: number;\n } {\n return {\n status: \"error\",\n code: this.code,\n limit: this.limit,\n size: this.size,\n };\n }\n}\n\n/** Measure a call body the way the route will and refuse an oversized one\n * before it leaves the machine. Returns the serialized body. */\nexport function serializeCallBody(body: unknown): string {\n const text = JSON.stringify(body);\n const size = Buffer.byteLength(text, \"utf8\");\n if (size > CALL_BODY_LIMIT_BYTES) throw new WorldCallTooLarge(size);\n return text;\n}\n\n/** What `session open` adds when its wait ran out: the session keeps opening. */\nexport const stillStartingHint = (sessionId: string): string =>\n `It keeps opening: poll \\`gateway worlds session status ${sessionId}\\` until ready, ` +\n `or end it with \\`gateway worlds session close ${sessionId}\\`.`;\n\n/** The line `session status` prints when an unpinned session has under\n * `IDLE_WARNING_MINUTES` left, else null. `now` is for tests. */\nexport function idleWarning(\n idleExpiresAt: string | null | undefined,\n now: Date = new Date(),\n): string | null {\n if (!idleExpiresAt) return null;\n const leftMs = new Date(idleExpiresAt).getTime() - now.getTime();\n if (leftMs >= IDLE_WARNING_MINUTES * 60_000) return null;\n const minutes = Math.max(0, Math.floor(leftMs / 60_000));\n return (\n `warning: session expires in ${minutes}m (idle TTL); ` +\n \"call a tool to extend it or `gateway worlds session pin` to keep it\"\n );\n}\n","import type { WorldToolSpec } from \"./session\";\n\nexport const modelToolName = (name: string): string =>\n name.replace(/[^A-Za-z0-9_-]/g, \"_\").slice(0, 64) || \"tool\";\n\n/**\n * Turn a world's Python signature into a JSON schema the model can call.\n *\n * `crm_update_deal(id, stage=None, owner=None, amount=None)` becomes an\n * object with `id` required and the rest optional. Types are read from the\n * DEFAULTS the world declares — a numeric default means a number, a boolean\n * default a boolean — because that is the only type information a signature\n * actually carries. Everything else is a string, which is what a tool CLI\n * receives anyway.\n */\nexport function schemaFromSignature(spec: WorldToolSpec): {\n type: \"function\";\n function: {\n name: string;\n description: string;\n parameters: Record<string, unknown>;\n };\n} {\n if (spec.inputSchema)\n return {\n type: \"function\",\n function: {\n name: modelToolName(spec.name),\n description: spec.doc ?? spec.name,\n parameters: spec.inputSchema,\n },\n };\n const inside = /\\(([\\s\\S]*)\\)\\s*$/.exec(spec.signature.trim())?.[1] ?? \"\";\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n // Split on top-level commas only: a default like `{\"a\": 1}` has its own.\n const params: string[] = [];\n let depth = 0;\n let current = \"\";\n for (const ch of inside) {\n if (\"([{\".includes(ch)) depth++;\n if (\")]}\".includes(ch)) depth--;\n if (ch === \",\" && depth === 0) {\n params.push(current);\n current = \"\";\n } else current += ch;\n }\n if (current.trim()) params.push(current);\n\n for (const raw of params) {\n const param = raw.trim();\n if (!param || param.startsWith(\"*\") || param === \"self\") continue;\n const eq = param.indexOf(\"=\");\n const name = (eq === -1 ? param : param.slice(0, eq)).split(\":\")[0].trim();\n if (!name) continue;\n if (eq === -1) {\n properties[name] = { type: \"string\" };\n required.push(name);\n continue;\n }\n const value = param.slice(eq + 1).trim();\n if (/^-?\\d+(\\.\\d+)?$/.test(value)) properties[name] = { type: \"number\" };\n else if (value === \"True\" || value === \"False\")\n properties[name] = { type: \"boolean\" };\n else properties[name] = { type: \"string\" };\n }\n return {\n type: \"function\",\n function: {\n name: modelToolName(spec.name),\n description: spec.doc ?? spec.name,\n parameters: { type: \"object\", properties, required },\n },\n };\n}\n","import { ApiError, apiRequest, type WorldsClientOptions } from \"./index\";\nimport type { WorldRequest, WorldRequestPage } from \"./requestLog\";\nimport { REQUESTS_NOT_RECORDED } from \"./sessionContract\";\n\nexport const WORLD_REQUEST_VIAS = [\"api\", \"ui\", \"tool\", \"webhook\", \"page\"] as const;\n\n/** One request with its exchange: the request's headers (credentials `[redacted]`) and the first 64 KB of each body, `null` for a body that is not text. */\nexport type WorldRequestEntry = Omit<WorldRequest, \"request\" | \"response\"> & {\n request: WorldRequest[\"request\"] & { headers: Record<string, string>; body: string | null };\n response: WorldRequest[\"response\"] & { body: string | null };\n};\n\nexport type WorldRequestFilter = {\n session?: string;\n version?: string;\n via?: string;\n operation?: string;\n status?: string;\n since?: string;\n until?: string;\n cursor?: string;\n limit?: number;\n};\n\nexport class WorldRequestFilterError extends Error {}\n\nconst NOT_RECORDED = \"This session's engine records no requests; only hosted World Host sessions do.\";\n\n/** The platform's 409 `requests_not_recorded`: the session's engine keeps no request ledger, only World Host\n * sessions record requests. Its message is the platform's own sentence. */\nexport class WorldRequestsNotRecorded extends Error {\n static from(error: unknown): unknown {\n if (!(error instanceof ApiError) || error.code !== REQUESTS_NOT_RECORDED) return error;\n return new WorldRequestsNotRecorded(platformMessage(error.text) || NOT_RECORDED);\n }\n\n static async mapped<T>(read: Promise<T>): Promise<T> {\n try {\n return await read;\n } catch (error) {\n throw WorldRequestsNotRecorded.from(error);\n }\n }\n}\n\nfunction platformMessage(text: string): string | null {\n try {\n const { message } = JSON.parse(text) as { message?: unknown };\n return typeof message === \"string\" ? message : null;\n } catch {\n return null;\n }\n}\n\nconst STATUS = /^(?:[1-5]\\d\\d|[1-5]xx)$/;\nconst INSTANT = /^(\\d{4})-(\\d{2})-(\\d{2})(?:T(\\d{2}):(\\d{2})(?::(\\d{2})(?:\\.(\\d{1,3}))?)?(Z|[+-]\\d{2}:\\d{2})?)?$/;\nconst WORLDS = \"/api/public/worlds\";\nconst SESSIONS = \"/api/public/world-sessions\";\n\nclass Instant {\n static parse(flag: string, raw: string): number {\n const match = INSTANT.exec(raw);\n const millis = match ? Instant.fromParts(match) : null;\n if (millis === null)\n throw new WorldRequestFilterError(\n `--${flag} must be an ISO 8601 date or time (2026-10-05, 2026-10-05T14:30:00Z), not \\`${raw}\\`.`,\n );\n return millis;\n }\n\n private static fromParts(match: RegExpExecArray): number | null {\n const [year, month, day, hour, minute, second] = [1, 2, 3, 4, 5, 6].map((i) => Number(match[i] ?? 0));\n const offset = Instant.offsetMinutes(match[8]);\n if (offset === null || year < 1 || hour > 23 || minute > 59 || second > 59) return null;\n const date = new Date(0);\n date.setUTCFullYear(year, month - 1, day);\n if (date.getUTCFullYear() !== year || date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day) return null;\n date.setUTCHours(hour, minute, second, Number((match[7] ?? \"\").padEnd(3, \"0\")));\n const utc = date.getTime() - offset * 60_000;\n const utcYear = new Date(utc).getUTCFullYear();\n return utcYear < 1 || utcYear > 9999 ? null : utc;\n }\n\n private static offsetMinutes(zone: string | undefined): number | null {\n if (zone === undefined || zone === \"Z\") return 0;\n const hours = Number(zone.slice(1, 3));\n const minutes = Number(zone.slice(4, 6));\n if (hours > 23 || minutes > 59) return null;\n return (zone.startsWith(\"-\") ? -1 : 1) * (hours * 60 + minutes);\n }\n}\n\n/** The filters of a request-ledger read, checked and put in the platform's form: `via` and `status` lower-cased,\n * `since`/`until` as UTC instants (a date alone is its midnight, a time without a zone is UTC). Twin of\n * `gatewaysdk.world_requests.WorldRequestQuery`; both run `conformance/world-request-cli.json`. */\nexport class WorldRequestQuery {\n private constructor(private readonly entries: [string, string][]) {}\n\n static parse(filter: WorldRequestFilter = {}): WorldRequestQuery {\n const via = WorldRequestQuery.via(filter.via);\n const status = WorldRequestQuery.status(filter.status);\n const since = filter.since === undefined ? undefined : Instant.parse(\"since\", filter.since);\n const until = filter.until === undefined ? undefined : Instant.parse(\"until\", filter.until);\n if (since !== undefined && until !== undefined && since > until)\n throw new WorldRequestFilterError(\"--since must not be after --until.\");\n const values: [string, string | undefined][] = [\n [\"session\", filter.session],\n [\"version\", filter.version],\n [\"via\", via],\n [\"operation\", filter.operation],\n [\"status\", status],\n [\"since\", since === undefined ? undefined : new Date(since).toISOString()],\n [\"until\", until === undefined ? undefined : new Date(until).toISOString()],\n [\"limit\", filter.limit === undefined ? undefined : String(filter.limit)],\n [\"cursor\", filter.cursor],\n ];\n return new WorldRequestQuery(values.filter((entry): entry is [string, string] => entry[1] !== undefined));\n }\n\n private static via(value: string | undefined): string | undefined {\n if (value === undefined) return undefined;\n const lower = value.toLowerCase();\n if ((WORLD_REQUEST_VIAS as readonly string[]).includes(lower)) return lower;\n throw new WorldRequestFilterError(`--via must be one of ${WORLD_REQUEST_VIAS.join(\", \")}, not \\`${value}\\`.`);\n }\n\n private static status(value: string | undefined): string | undefined {\n if (value === undefined) return undefined;\n const lower = value.toLowerCase();\n if (STATUS.test(lower)) return lower;\n throw new WorldRequestFilterError(`--status must be a code (200) or a class (2xx), not \\`${value}\\`.`);\n }\n\n get filtered(): boolean {\n return this.entries.some(([key]) => key !== \"limit\");\n }\n\n params(): [string, string][] {\n return this.entries.map(([key, value]) => [key, value]);\n }\n\n search(): string {\n return this.entries.length ? `?${new URLSearchParams(this.entries).toString()}` : \"\";\n }\n}\n\n/** A world's request ledger: every request the world received, from every session and version, through every\n * door (`via`: api, ui, tool, webhook, page), kept for the world's life. Reading it records nothing. Twin of\n * `gatewaysdk.world_requests.WorldRequestLedger`. */\nexport class WorldRequestLedger {\n constructor(private readonly options: WorldsClientOptions = {}) {}\n\n /** A page of the world's requests, newest first; `nextCursor` reads the page after it. Narrowed to a session\n * whose engine records none: `WorldRequestsNotRecorded`. */\n list(slug: string, query: WorldRequestQuery = WorldRequestQuery.parse()): Promise<WorldRequestPage> {\n return WorldRequestsNotRecorded.mapped(\n apiRequest<WorldRequestPage>(\n this.options,\n \"GET\",\n `${WORLDS}/${encodeURIComponent(slug)}/requests${query.search()}`,\n ),\n );\n }\n\n /** One of the world's requests, with its headers and bodies. */\n get(slug: string, requestId: string): Promise<WorldRequestEntry> {\n return apiRequest(\n this.options,\n \"GET\",\n `${WORLDS}/${encodeURIComponent(slug)}/requests/${encodeURIComponent(requestId)}`,\n );\n }\n\n /** A page of one session's requests, newest first; `WorldRequestsNotRecorded` when its engine records none. */\n forSession(sessionId: string, query: WorldRequestQuery = WorldRequestQuery.parse()): Promise<WorldRequestPage> {\n return WorldRequestsNotRecorded.mapped(\n apiRequest<WorldRequestPage>(\n this.options,\n \"GET\",\n `${SESSIONS}/${encodeURIComponent(sessionId)}/requests${query.search()}`,\n ),\n );\n }\n}\n","export type SessionStatus = {\n state: string;\n ready: boolean;\n failure?: { code: string | null; message: string } | null;\n};\n\n/** How long `ready()` waits unless told otherwise, and how often it asks. */\nexport const READY_TIMEOUT_MS = 10 * 60_000;\nconst READY_POLL_MS = 2_000;\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\nexport class WorldSessionTimeout extends Error {}\nexport class WorldSessionCallError extends Error {}\n\n/** The session ended before it was ready: it FAILED to open, or was STOPPED.\n * `code` is the platform's when it named one; `browser_capacity` and\n * `host_unavailable` are worth opening again. */\nexport class WorldSessionOpenFailed extends WorldSessionCallError {\n constructor(\n readonly sessionId: string,\n readonly state: string,\n readonly code: string | null,\n reason: string | null,\n ) {\n super(\n reason === null\n ? `World session ${sessionId} ${state.toLowerCase()} before it was ready.`\n : `World session ${sessionId} failed to open: ${reason}${code ? ` (${code})` : \"\"}`,\n );\n this.name = \"WorldSessionOpenFailed\";\n }\n}\n\nconst ENDED = new Set([\"FAILED\", \"STOPPED\"]);\n\n/** Waits on a session's status until it answers calls, ends, or the wait runs\n * out; it never sleeps past its deadline. */\nexport class SessionReadiness<T extends SessionStatus> {\n constructor(\n private readonly sessionId: string,\n private readonly status: () => Promise<T>,\n ) {}\n\n async wait(timeoutMs: number = READY_TIMEOUT_MS): Promise<T> {\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n const state = await this.status();\n if (state.ready) return state;\n if (ENDED.has(state.state))\n throw new WorldSessionOpenFailed(\n this.sessionId,\n state.state,\n state.failure?.code ?? null,\n state.failure?.message ?? null,\n );\n const left = deadline - Date.now();\n if (left <= 0)\n throw new WorldSessionTimeout(\n `World session ${this.sessionId} still ${state.state} after ${Math.round(timeoutMs / 1000)}s.`,\n );\n await sleep(Math.min(READY_POLL_MS, left));\n }\n }\n}\n","import { AsyncLocalStorage } from \"async_hooks\";\nimport type { Context } from \"@opentelemetry/api\";\nimport type {\n ReadableSpan,\n Span,\n SpanProcessor,\n} from \"@opentelemetry/sdk-trace-base\";\n\nexport const SESSION_ID_ATTRIBUTE = \"gateway.session.id\";\nexport const WORLD_SESSION_ID_ATTRIBUTE =\n \"gateway.trace.metadata.world_session_id\";\n\n// AsyncLocalStorage so concurrent runs or requests never bleed into each other.\n// Held on globalThis: tsup inlines this module into every published entry\n// (splitting: false), and `worlds` must write the store `tracing` reads.\n// Every SDK copy in the process shares the key and the string value; never\n// rename or reshape them.\nconst processStorage = (name: string): AsyncLocalStorage<string> => {\n const key = Symbol.for(`@withgateway/sdk/${name}`);\n const slots = globalThis as Record<symbol, AsyncLocalStorage<string>>;\n slots[key] ??= new AsyncLocalStorage<string>();\n return slots[key];\n};\nconst currentSessionStorage = processStorage(\"session-storage\");\nconst currentWorldSessionStorage = processStorage(\"world-session-storage\");\n\n/** The session id set by the innermost enclosing `withSession()`, or `undefined`. */\nexport function getAmbientSessionId(): string | undefined {\n return currentSessionStorage.getStore();\n}\n\n/** The live world session the current code is working in, or `undefined`. */\nexport function getCurrentWorldSessionId(): string | undefined {\n return currentWorldSessionStorage.getStore();\n}\n\nfunction runIn<T>(\n storage: AsyncLocalStorage<string>,\n value: string,\n fn: () => T | Promise<T>,\n): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n storage.run(value, () => {\n Promise.resolve().then(fn).then(resolve, reject);\n });\n });\n}\n\n/**\n * Group every trace recorded inside `fn` under one session id — the twin of\n * the Python SDK's `with tracing.session(session_id): ...`. Auto-instrumented\n * spans are grouped too; the innermost session wins.\n *\n * ```typescript\n * await withSession(\"checkout-regression-001\", async () => {\n * await observe(\"turn-1\", async () => { ... });\n * });\n * ```\n */\nexport function withSession<T>(\n sessionId: string,\n fn: () => T | Promise<T>,\n): Promise<T> {\n return runIn(currentSessionStorage, sessionId, fn);\n}\n\n/**\n * Trace `fn` as work inside one live world session: spans take the world\n * session's id as their session id and carry `world_session_id` trace\n * metadata. A `withSession()` block inside still wins for the session id;\n * the metadata stays. Without `tracing.init()` nothing is recorded. Twin of\n * Python's `tracing.context.world_session`; callers use\n * `WorldSession.withTraceContext(fn)`.\n */\nexport function withWorldSession<T>(\n worldSessionId: string,\n fn: () => T | Promise<T>,\n): Promise<T> {\n return runIn(currentWorldSessionStorage, worldSessionId, () =>\n withSession(worldSessionId, fn),\n );\n}\n\n/**\n * Stamps the session id and world session id on every span at start.\n * Registered by `tracing.init()`/`initIsolated()`. A session id the span was\n * started with (or is given after it starts) wins over the innermost\n * `withSession()` / `withWorldSession()` block, as in the Python SDK.\n */\nexport class SessionSpanProcessor implements SpanProcessor {\n onStart(span: Span, _parentContext: Context): void {\n const worldSessionId = getCurrentWorldSessionId();\n if (worldSessionId)\n span.setAttribute(WORLD_SESSION_ID_ATTRIBUTE, worldSessionId);\n const sessionId = getAmbientSessionId();\n if (!sessionId || span.attributes?.[SESSION_ID_ATTRIBUTE] !== undefined)\n return;\n span.setAttribute(SESSION_ID_ATTRIBUTE, sessionId);\n }\n\n onEnd(_span: ReadableSpan): void {}\n\n async shutdown(): Promise<void> {}\n\n async forceFlush(): Promise<void> {}\n}\n","import type {\n WorldSessionTask,\n WorldTaskIdRef,\n WorldTaskRef,\n WorldTaskSpec,\n} from \"./taskSpec\";\n\n/**\n * The three shapes a task reaches `openSession` in — a bundled scenario's\n * name, a stored task's `{ id, version? }`, an inline spec — and how each is\n * told apart, labelled and checked. No task at all (`undefined`) is the\n * fourth case, an exploratory session, and is not a ref.\n */\n\nexport const isTaskIdRef = (task: WorldTaskRef): task is WorldTaskIdRef =>\n typeof task === \"object\" && task !== null && \"id\" in task;\n\nexport const isTaskSpec = (task: WorldTaskRef): task is WorldTaskSpec =>\n typeof task === \"object\" && task !== null && \"instruction\" in task;\n\n/** The label a task goes by in results: its name, `inline:<hash>` for an\n * unnamed inline task once the platform has hashed it, or the stored task's\n * name (its id until the platform has answered). */\nexport const taskLabel = (\n task: WorldTaskRef,\n info?: WorldSessionTask | null,\n): string => {\n if (typeof task === \"string\") return task;\n if (isTaskIdRef(task)) return info?.name ?? task.id;\n if (task.name) return task.name;\n return info?.hash ? `inline:${info.hash.slice(0, 12)}` : \"inline\";\n};\n\n/** A task given to `openSession` must be one of the three shapes. */\nexport const assertTaskRef = (task: WorldTaskRef): void => {\n const malformed =\n task === null ||\n (typeof task === \"string\" && !task) ||\n (isTaskIdRef(task) && !task.id) ||\n (isTaskSpec(task) && !task.instruction) ||\n (typeof task === \"object\" && !isTaskIdRef(task) && !isTaskSpec(task));\n if (malformed)\n throw new Error(\n \"openSession needs a task: a bundled task name, a stored task { id, version? } or { instruction, seed?, grader?, metadata? } — or none at all for an exploratory session\",\n );\n};\n","import type { WorldDeprecation } from \"./session\";\n\nexport const TOOL_CONTRACT_UNREAD = \"tool-contract-unread\";\n\ntype NoticeKind = { label: string; next: string; refusesRun: boolean };\n\nconst DEPRECATION: NoticeKind = { label: \"deprecated\", next: \"Instead\", refusesRun: false };\n\nconst NOTICE_KINDS = new Map<string, NoticeKind>([\n [TOOL_CONTRACT_UNREAD, { label: \"warning\", next: \"Then\", refusesRun: true }],\n]);\n\n/** One notice from a world answer's `deprecations`, as the CLI prints it (`fixtures/tasks/world-notice-vectors.json`). */\nexport class WorldNotice {\n private constructor(\n readonly notice: WorldDeprecation,\n private readonly kind: NoticeKind,\n ) {}\n\n static of(notice: WorldDeprecation): WorldNotice {\n return new WorldNotice(notice, NOTICE_KINDS.get(notice.code) ?? DEPRECATION);\n }\n\n get refusesRun(): boolean {\n return this.kind.refusesRun;\n }\n\n line(): string {\n const { code, message, replacement } = this.notice;\n return `${this.kind.label} (${code}): ${message} ${this.kind.next}: ${replacement}`;\n }\n}\n\n/** A run refused before its agent started: the platform could not read a world's tools. */\nexport class WorldToolsUnread extends Error {\n readonly code: string;\n\n constructor(\n readonly world: string,\n readonly notice: WorldNotice,\n ) {\n super(\n `refused before the agent ran, nothing filed: world ${world} has no readable tools: ` +\n `${notice.notice.message} Then: ${notice.notice.replacement}`,\n );\n this.name = \"WorldToolsUnread\";\n this.code = notice.notice.code;\n }\n\n static refuse(world: string, notices: WorldDeprecation[]): void {\n const refusing = notices.map((notice) => WorldNotice.of(notice)).find((notice) => notice.refusesRun);\n if (refusing) throw new WorldToolsUnread(world, refusing);\n }\n}\n","/**\n * A world's grade as the SDK reads it, by the one score rule every grader\n * answers by: a finite number from 0 to 1, a passed check 1, a failed one 0,\n * null ungraded. The World Host's twin is `gatewaysdk/environment/score.py`;\n * both are pinned by `gatewaysdk/fixtures/tasks/grade-vectors.json`.\n */\n\nexport const messageOf = (error: unknown): string =>\n (error instanceof Error ? error.message || error.name : String(error)) ||\n \"Error\";\n\nexport type GradeResult = {\n reward: number | null;\n rewards: Record<string, number>;\n /** Why there is no reward: `no grader` on an exploratory session. */\n reason?: string;\n /** Why this world could not grade; the task's grade is then that error. */\n error?: string;\n /** The task's cross-world verifiers anchored on this session, by name:\n * each its own reward and named rewards, or `error` when it could not\n * grade (evidence missing, verify.py failed) — null, never zero. */\n verifiers?: Record<string, VerifierGrade>;\n raw: unknown;\n};\n\nexport type VerifierGrade = {\n reward: number | null;\n rewards: Record<string, number>;\n error?: string;\n};\n\nexport class Score {\n static readonly RULE = \"a score is a number from 0 to 1\";\n\n static admits(value: number): boolean {\n return Number.isFinite(value) && value >= 0 && value <= 1;\n }\n\n /** Every number among `scores` that is not a score, as `'<key>' = <value>`\n * and the rule, or null when all of them are. Pairs, not a map, so that no\n * key hides another. */\n static problem(scores: Iterable<[string, unknown]>): string | null {\n const refused = [...scores].flatMap(([key, value]) =>\n typeof value === \"number\" && !Score.admits(value)\n ? [`'${key}' = ${String(value)}`]\n : [],\n );\n return refused.length ? `${refused.join(\", \")}; ${Score.RULE}` : null;\n }\n}\n\n/** A world's grade that is never filed: it is not an object, a number in it\n * is not a score (a World Host older than the rule), a check is named both\n * beside and inside its rewards, or its rewards or verifiers are not objects\n * by name. */\nexport class GradeRefused extends Error {\n readonly name = \"GradeRefused\";\n}\n\ntype Numbers = { reward: number | null; rewards: Record<string, number> };\n\nexport class GradePayload {\n /** A grade payload's numbers, checked: every number in it must be a score,\n * and its rewards and verifiers objects by name, or the grade is refused; a\n * cross-world verifier's grade that breaks either rule is that verifier's\n * error, the way the World Host answers one that could not grade. */\n static read(raw: unknown): Omit<GradeResult, \"raw\"> {\n if (!GradePayload.objectOrAbsent(raw))\n throw new GradeRefused(\"the grade is not an object\");\n const record = GradePayload.record(raw);\n const problem =\n GradePayload.problem(record) ??\n GradePayload.verifiersProblem(record.verifiers);\n if (problem) throw new GradeRefused(problem);\n const verifiers = GradePayload.verifiers(record.verifiers);\n return {\n ...GradePayload.numbers(record),\n ...(typeof record.reason === \"string\" ? { reason: record.reason } : {}),\n ...(typeof record.error === \"string\" ? { error: record.error } : {}),\n ...(verifiers ? { verifiers } : {}),\n };\n }\n\n /** A world whose grade call failed (the platform refused it, the host had\n * lost the session): that world's error, never a score. */\n static failedCall(error: unknown): GradeResult {\n return { ...GradePayload.failed(messageOf(error)), raw: null };\n }\n\n private static problem(record: Record<string, unknown>): string | null {\n if (!GradePayload.objectOrAbsent(record.rewards))\n return \"the grade's rewards are not an object\";\n const scores = Score.problem(GradePayload.scores(record));\n if (scores) return `the grade answered ${scores}`;\n const twice = GradePayload.twice(record);\n return twice.length\n ? `the grade answered ${twice.map((key) => `'${key}'`).join(\", \")} both beside and inside rewards`\n : null;\n }\n\n private static twice(record: Record<string, unknown>): string[] {\n return Object.entries(GradePayload.record(record.rewards))\n .filter(\n ([key, value]) =>\n key !== \"reward\" &&\n typeof value === \"number\" &&\n typeof record[key] === \"number\",\n )\n .map(([key]) => key);\n }\n\n private static verifiersProblem(value: unknown): string | null {\n return GradePayload.objectOrAbsent(value)\n ? null\n : \"the grade's verifiers are not an object\";\n }\n\n private static scores(record: Record<string, unknown>): [string, unknown][] {\n return [\n [\"reward\", record.reward],\n ...Object.entries(GradePayload.record(record.rewards)),\n ...Object.entries(record).filter(\n ([key]) => key !== \"reward\" && key !== \"rewards\",\n ),\n ];\n }\n\n private static isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n }\n\n private static objectOrAbsent(value: unknown): boolean {\n return value === undefined || value === null || GradePayload.isRecord(value);\n }\n\n private static record(value: unknown): Record<string, unknown> {\n return GradePayload.isRecord(value) ? value : {};\n }\n\n /** `reward`, and every numeric key under `rewards` (the host's shape) or at\n * the top level (a bundled verifier's). */\n private static numbers(record: Record<string, unknown>): Numbers {\n const rewards: Record<string, number> = {};\n for (const [key, value] of Object.entries(\n GradePayload.record(record.rewards),\n ))\n if (typeof value === \"number\") rewards[key] = value;\n for (const [key, value] of Object.entries(record))\n if (key !== \"reward\" && typeof value === \"number\") rewards[key] = value;\n return {\n reward: typeof record.reward === \"number\" ? record.reward : null,\n rewards,\n };\n }\n\n private static verifiers(\n value: unknown,\n ): Record<string, VerifierGrade> | undefined {\n if (!GradePayload.isRecord(value)) return undefined;\n return Object.fromEntries(\n Object.entries(value).map(([name, grade]) => [\n name,\n GradePayload.verifier(name, grade),\n ]),\n );\n }\n\n private static verifier(name: string, grade: unknown): VerifierGrade {\n if (!GradePayload.isRecord(grade))\n return GradePayload.failed(`the grade's verifier '${name}' is not an object`);\n const problem = GradePayload.problem(grade);\n if (problem) return GradePayload.failed(problem);\n return {\n ...GradePayload.numbers(grade),\n ...(typeof grade.error === \"string\" ? { error: grade.error } : {}),\n };\n }\n\n private static failed(error: string): VerifierGrade {\n return { reward: null, rewards: {}, error };\n }\n}\n","import { randomUUID } from \"node:crypto\";\n\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\nimport {\n BrowserActionRecorder,\n PLATFORM_SESSION_HEADER,\n SURFACE_KINDS,\n WorldSurfaceUnavailable,\n assertBrowserTier,\n assertSessionAuthMode,\n openBrowser,\n uiEntryUrl,\n type BrowserActionEvent,\n type BrowserMode,\n type BrowserTier,\n type SessionAuthMode,\n type PlaywrightLike,\n type SessionSurfaces,\n type WorldBrowser,\n type WorldSurfaceKind,\n} from \"./browser\";\nimport type { RepairAnswer } from \"./browserReconnect\";\nimport { computerUseToolkit } from \"./browserTools\";\nimport {\n NativeComputer,\n type NativeComputerKinds,\n type NativeComputerOptions,\n type NativeComputerProvider,\n} from \"./nativeComputer\";\nimport type { WorldTaskSummary } from \"./tasks\";\nimport { REQUEST_LOG_PAGE_MAX, serializeCallBody } from \"./sessionContract\";\nimport { modelToolName, schemaFromSignature } from \"./toolSchema\";\nimport type { WorldRequestPage } from \"./requestLog\";\nimport { WorldRequestLedger, WorldRequestQuery } from \"./requestLedger\";\nimport {\n SessionReadiness,\n WorldSessionCallError,\n WorldSessionTimeout,\n} from \"./sessionReadiness\";\nimport { withWorldSession } from \"../tracing/session\";\nimport { assertTaskRef, isTaskIdRef, isTaskSpec, taskLabel } from \"./taskRef\";\nimport { WorldToolsUnread } from \"./worldNotice\";\nimport { GradePayload, type GradeResult } from \"./grade\";\nimport type {\n WorldTaskSpec,\n WorldTaskRef,\n WorldSessionTask,\n} from \"./taskSpec\";\nimport type {\n SeedResult,\n WorldDeprecation,\n WorldSessionCall,\n WorldSessionRestart,\n WorldSessionState,\n WorldSessionWorldState,\n WorldToolSpec,\n WorldToolkit,\n} from \"./sessionTypes\";\n\nexport { isTaskIdRef, isTaskSpec, taskLabel } from \"./taskRef\";\n\n/**\n * LIVE WORLD SESSIONS from TypeScript: your agent, the platform's container.\n *\n * The other two ways of running a world each give up something. Pulling the\n * bundle and executing it locally tests your agent against a COPY — your\n * python, your sqlite, your machine's idea of the environment. Dispatching a\n * hosted run gives you the real container but runs the platform's agent\n * inside it, so your agent never touches the world.\n *\n * A session is both: the platform boots the task's container and holds it\n * warm, and every `call()` here executes inside THAT container. Your agent\n * stays where it is — this file is just the wire.\n *\n * const world = await openWorld(\"revenue-ops-sim@main\");\n * const session = await openSession(world.slug, { task: \"revops-mara-dedupe-contacts\" });\n * await session.ready(); // wait for the container\n * await session.call(\"crm_search\", { entity: \"deals\" });\n * await session.withTraceContext(() => myAgent(session)); // traced under session.sessionId\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 * from \"./sessionTypes\";\nexport type * from \"./taskSpec\";\n\nexport type { GradeResult, VerifierGrade } from \"./grade\";\nexport {\n WorldSessionCallError,\n WorldSessionOpenFailed,\n WorldSessionTimeout,\n} from \"./sessionReadiness\";\nexport { modelToolName, schemaFromSignature };\n\n/** How long one call may take end to end (container claim + execution). */\nconst CALL_TIMEOUT_MS = 3 * 60_000;\nconst CALL_POLL_MS = 400;\n/** How long a grade the platform's judge finalizes may take: the model's own\n * timeout and retries, plus the worker's queue backoff. Polled slowly. */\nconst JUDGED_GRADE_TIMEOUT_MS = 15 * 60_000;\nconst JUDGED_GRADE_POLL_MS = 2_000;\nconst EXPORT_PAGE = 500;\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\nexport class WorldSession {\n constructor(\n readonly sessionId: string,\n private current: WorldSessionState,\n private readonly options: WorldsClientOptions,\n ) {}\n\n /** The task's display name: a bundled scenario's, or the inline spec's\n * `name` (null when the spec was unnamed). `task` is the same. */\n get taskName(): string | null {\n return this.current.taskName;\n }\n get task(): string | null {\n return this.taskName;\n }\n\n /** `{idleExpiresAt, pinned}` as of the last state read: when the fleet\n * reaps the session (null once pinned), and whether it is pinned. */\n get idle(): { idleExpiresAt: string | null; pinned: boolean } {\n return {\n idleExpiresAt: this.current.idleExpiresAt ?? null,\n pinned: this.current.pinned ?? false,\n };\n }\n\n /** The platform's notices about the world this session runs on (empty\n * for a schema world). Printed by the CLI on stderr at open. */\n get deprecations(): WorldDeprecation[] {\n return this.current.deprecations ?? [];\n }\n\n /** The task this session runs: bundled scenario, stored task or inline\n * spec, its name, hash and the caller's metadata. */\n get taskInfo(): WorldSessionTask {\n return (\n this.current.task ?? {\n source: \"bundled\",\n name: this.current.taskName,\n hash: null,\n metadata: {},\n }\n );\n }\n\n /** What this task asks for — the bundle's instruction.md, or the inline\n * spec's `instruction`. */\n get instruction(): string | null {\n return this.current.instruction ?? null;\n }\n\n get versionId(): string {\n return this.current.versionId;\n }\n\n get worldState(): WorldSessionWorldState | null {\n return this.current.worldState ?? null;\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's token in the\n * platform's `X-World-Session` header, which every world takes; `{}` for a pod\n * or hosted twin, which answers with the world's own declared auth. */\n async apiHeaders(): Promise<Record<string, string>> {\n const { api } = await this.surfaces();\n return api?.token ? { [PLATFORM_SESSION_HEADER]: api.token } : {};\n }\n\n /** URL of the world's UI entry page for this session. */\n async ui(): Promise<string> {\n const { ui } = await this.surfaces();\n if (!ui)\n throw new WorldSurfaceUnavailable(\n \"ui\",\n \"open the session with surfaces: ['ui'] on a world that declares [ui]\",\n );\n return uiEntryUrl(ui);\n }\n\n /** A Playwright browser on this session's UI: `hosted` drives the one the\n * platform runs next to the world, `local` launches one here, `auto`\n * prefers hosted. Call `close()` when done.\n *\n * Every action is reported to the platform under `agentId` (default:\n * `GATEWAY_AGENT_ID` or a fresh `agent-<hex>`) so the session page shows\n * this agent's own timeline — several agents may share one session and\n * one hosted browser. `record: false` opts out. */\n async browser(\n opts: {\n mode?: BrowserMode;\n headless?: boolean;\n playwright?: PlaywrightLike;\n agentId?: string;\n record?: boolean;\n } = {},\n ): Promise<WorldBrowser> {\n const { agentId, record = true, ...rest } = opts;\n return openBrowser(await this.surfaces(), {\n ...rest,\n recorder: record ? this.browserRecorder(agentId) : null,\n repair: () => this.repairBrowser(),\n });\n }\n\n /** Ask the platform to make this session's hosted browser reachable again\n * after its connection dropped: `healthy` (reconnect now), `replaced` (a new,\n * blank browser behind the same wsUrl; reconnect and reopen your page) or\n * `starting` (ask again in `retryAfterMs`). `browser()` does this on its\n * own; call it when you drive your own Playwright against `wsUrl`. */\n async repairBrowser(): Promise<RepairAnswer> {\n return apiRequest<RepairAnswer>(\n this.options,\n \"POST\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/browser-repair`,\n {},\n );\n }\n\n /** The reporter `browser()` uses; exposed for a page you drive yourself. */\n browserRecorder(agentId?: string): BrowserActionRecorder {\n const path = `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/browser-events`;\n const id =\n agentId ??\n process.env.GATEWAY_AGENT_ID ??\n `agent-${randomUUID().replace(/-/g, \"\").slice(0, 8)}`;\n return new BrowserActionRecorder(\n async (events: BrowserActionEvent[]) => {\n await apiRequest(this.options, \"POST\", path, { events });\n },\n id,\n {\n // Continue this agent's timeline where the platform has it, so a reopened id 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 browser as a provider's own pixel-based computer-use tool: `anthropic`\n * (`computer_toolset_20260801`), `openai` (Responses `computer`),\n * `anthropic-computer-20251124` or `openai-preview`. See `nativeComputer/`. */\n nativeComputer<P extends NativeComputerProvider = \"anthropic\">(\n browser: WorldBrowser,\n provider: P = \"anthropic\" as P,\n options: NativeComputerOptions = {},\n ): NativeComputerKinds[P] {\n return NativeComputer.forProvider(provider, browser, options) as NativeComputerKinds[P];\n }\n\n /** The session's latest platform state (one request, no waiting). */\n async status(): Promise<WorldSessionState> {\n return this.refresh(\n await apiRequest<WorldSessionState>(\n this.options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}`,\n ),\n );\n }\n\n /** The world started over under the same id, URLs and token, on what its pin (or `version`, which becomes\n * its pin) resolves to now: base data plus the task's seed. A grade then reads only the new world's requests. */\n async restart(\n opts: { version?: string } = {},\n ): Promise<WorldSessionState & { restart: WorldSessionRestart }> {\n const fresh = await apiRequest<\n WorldSessionState & { restart: WorldSessionRestart }\n >(\n this.options,\n \"POST\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/restart`,\n opts.version ? { version: opts.version } : {},\n );\n this.refresh(fresh);\n return fresh;\n }\n\n // A status read carries neither the objective nor the open's notices; keep the ones we opened with.\n private refresh(fresh: WorldSessionState): WorldSessionState {\n this.current = {\n instruction: this.current.instruction,\n tools: this.current.tools,\n surfaces: this.current.surfaces,\n task: this.current.task,\n deprecations: this.current.deprecations,\n ...fresh,\n };\n return this.current;\n }\n\n /**\n * Wait until the session answers calls: a World Host holds it, or the\n * process inside a pod has asked the platform for work. Throws\n * `WorldSessionOpenFailed` (with the platform's reason) when it ended\n * first, and `WorldSessionTimeout` when `timeoutMs` (default ten minutes)\n * ran out while it was still starting.\n */\n async ready(opts: { timeoutMs?: number } = {}): Promise<WorldSessionState> {\n return new SessionReadiness(this.sessionId, () => this.status()).wait(\n opts.timeoutMs,\n );\n }\n\n /** Enqueue one interaction and wait for the container's answer. */\n private async exchange(\n body: {\n kind?: \"call\" | \"grade\" | \"reset\" | \"state\" | \"seed\" | \"close\";\n tool?: string;\n args?: unknown;\n /** Grade only: the agent's report, for a rubric judge. */\n report?: string;\n },\n timeoutMs?: number,\n ): Promise<unknown> {\n // Measured the way the route measures it; over the limit nothing is sent.\n serializeCallBody(body);\n const enqueued = await apiRequest<{\n callId: string;\n seq: number;\n /** The platform's worker finalizes this call (a rubric grade). */\n pending?: boolean;\n }>(\n this.options,\n \"POST\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/calls`,\n body,\n );\n const { callId } = enqueued;\n const judged = enqueued.pending === true;\n const budgetMs =\n timeoutMs ?? (judged ? JUDGED_GRADE_TIMEOUT_MS : CALL_TIMEOUT_MS);\n const pollMs = judged ? JUDGED_GRADE_POLL_MS : CALL_POLL_MS;\n const deadline = Date.now() + budgetMs;\n for (;;) {\n const call = await apiRequest<{\n done: boolean;\n state: string;\n result: unknown;\n error: string | null;\n }>(\n this.options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/calls/${encodeURIComponent(callId)}`,\n );\n if (call.done) {\n if (call.error) throw new WorldSessionCallError(call.error);\n return call.result;\n }\n if (Date.now() > deadline)\n throw new WorldSessionTimeout(\n judged\n ? `Grade ${callId} still ${call.state} after ${Math.round(budgetMs / 1000)}s — the judge has not answered; the platform finalizes the call on its own, read it back with export().`\n : `Call ${callId} still ${call.state} after ${Math.round(budgetMs / 1000)}s — the container may have died.`,\n );\n await sleep(pollMs);\n }\n }\n\n /**\n * Run one of the world's tools INSIDE the container. The arguments and the\n * result are the world's own contract — this layer neither validates nor\n * reshapes them, so a tool error reads exactly as it would in a hosted run.\n */\n async call(\n tool: string,\n args: Record<string, unknown> = {},\n opts: { timeoutMs?: number } = {},\n ): Promise<unknown> {\n return this.exchange({ kind: \"call\", tool, args }, opts.timeoutMs);\n }\n\n /**\n * THE WORLD'S TOOLS, READY TO HAND TO A MODEL. Schemas come from the\n * world's own signatures and implementations call into this session, so a\n * caller never writes — and never has to re-sync — a tool map of their own:\n *\n * const { schemas, impls } = await session.toolkit();\n * await runMyAgent(impls, schemas, session.instruction);\n *\n * A tool added to the world shows up here on the next run; a tool renamed\n * in the world renames here too, instead of failing at call time against a\n * hand-written map that still remembers the old name.\n */\n async toolkit(): Promise<WorldToolkit> {\n let specs = this.current.tools;\n if (!specs) specs = (await this.status()).tools ?? [];\n const impls: WorldToolkit[\"impls\"] = Object.create(null);\n for (const spec of specs) {\n const alias = modelToolName(spec.name);\n if (Object.hasOwn(impls, alias))\n throw new WorldSessionCallError(`Model tool name collision: ${alias}`);\n impls[alias] = (args: Record<string, unknown> = {}) =>\n this.call(spec.name, args);\n }\n return { schemas: specs.map(schemaFromSignature), impls, specs };\n }\n\n /** Run the task's grader against the container's END STATE. Graders answer\n * in one of two shapes: the scalar with named rewards beside it\n * (`{reward, check_a, check_b}`, a task's own `grade.py`), or the named\n * rewards nested under `rewards` (the api, mock-tools and World Host\n * runners). Both land in `rewards`.\n *\n * A rubric grade is finalized by the platform's judge, not the container:\n * the platform answers the enqueue with `pending: true`, and this waits on\n * the judge's budget (15 min) instead of a call's. `timeoutMs` overrides\n * either. `report` is the agent's own account of what it did and found,\n * handed to the judge as its claim beside the evidence (the state and the\n * calls); assertions and python graders ignore it. `worlds` names the\n * task's other sessions by alias (`{alias: sessionId}`): the platform\n * reads each one's evidence and hands it to the cross-world verifiers\n * anchored on this session, whose grades come back under `verifiers`. A\n * score that is not a number from 0 to 1 is refused by key and value\n * (`GradeRefused`); a verifier's is that verifier's `error`. */\n async grade(\n opts: {\n timeoutMs?: number;\n report?: string;\n worlds?: Record<string, string>;\n } = {},\n ): Promise<GradeResult> {\n const raw = (await this.exchange(\n {\n kind: \"grade\",\n ...(opts.report !== undefined ? { report: opts.report } : {}),\n ...(opts.worlds && Object.keys(opts.worlds).length > 0\n ? { worlds: opts.worlds }\n : {}),\n },\n opts.timeoutMs,\n )) as Record<string, unknown> | null;\n return { ...GradePayload.read(raw), raw };\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 /** One page of the session's entries in its world's request ledger, newest\n * first and without bodies: at most `limit` after `cursor` (the last page's\n * `nextCursor`). Reading it records nothing in the session. */\n async requests(\n opts: { cursor?: string; limit?: number } = {},\n ): Promise<WorldRequestPage> {\n return new WorldRequestLedger(this.options).forSession(\n this.sessionId,\n WorldRequestQuery.parse({ cursor: opts.cursor, limit: opts.limit ?? REQUEST_LOG_PAGE_MAX }),\n );\n }\n\n private page<T>(route: string, limit: number, cursor?: string): Promise<T> {\n const query = new URLSearchParams({ limit: String(limit) });\n if (cursor) query.set(\"cursor\", cursor);\n return apiRequest<T>(\n this.options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/${route}?${query.toString()}`,\n );\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 page = await this.page<{\n calls: Record<string, unknown>[];\n nextCursor?: string | null;\n }>(\"calls\", EXPORT_PAGE, cursor);\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 * Run `fn` as work inside this session: spans it records take `sessionId`\n * as their session id and carry `world_session_id` trace metadata, so the\n * agent's traces land in the same session as the platform's traces of this\n * session's tool calls. A `withSession()` block inside still wins for the\n * session id. No effect before `tracing.init()`. `runSessions` wraps each\n * agent call in it.\n *\n * ```typescript\n * await session.withTraceContext(() => myAgent(toolkit, session.instruction));\n * ```\n */\n withTraceContext<T>(fn: () => T | Promise<T>): Promise<T> {\n return withWorldSession(this.sessionId, fn);\n }\n}\n\n/**\n * Attach to a session that already exists — resuming after a crash, or\n * driving a session someone else opened (a container started by hand on a\n * self-hosted install, a session opened by CI and handed to a developer).\n */\nexport async function attachSession(\n sessionId: string,\n options: WorldsClientOptions = {},\n): Promise<WorldSession> {\n const state = await apiRequest<WorldSessionState>(\n options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(sessionId)}`,\n );\n return new WorldSession(sessionId, state, options);\n}\n\nexport type OpenSessionOptions = {\n versionId?: string;\n reuseWarm?: boolean;\n /** More than `tools`: `[\"api\"]`, `[\"ui\"]`, `[\"browser\"]`. The platform\n * refuses (HTTP 400) rather than quietly serving less than asked. */\n surfaces?: WorldSurfaceKind[];\n /** Capacity for a World Host session's browser: `standard` (spot, may be\n * reclaimed) or `premium` (on-demand). Unset, the organization's default. */\n browserTier?: BrowserTier;\n /** `open`: the session asks for no credential; its api and ui answer on a\n * capability hostname whose url is the secret. Unset, the world's\n * `[auth] mode`. World Host sessions only. */\n auth?: SessionAuthMode;\n /** A world state of this world: the session opens on its data and knobs. World Host sessions only. */\n worldState?: string;\n options?: WorldsClientOptions;\n};\n\nconst OPEN_SESSION_OPTION_KEYS: ReadonlySet<string> = new Set([\n \"task\",\n \"versionId\",\n \"reuseWarm\",\n \"surfaces\",\n \"browserTier\",\n \"auth\",\n \"worldState\",\n \"options\",\n]);\n\n/** The second argument is an options bag only when every key is one of\n * `OpenSessionOptions` (+ `task`); any other object is the positional task\n * and is validated as one, so a misspelt spec is refused, not opened bare. */\nconst isOpenSessionOptions = (\n value: unknown,\n): value is OpenSessionOptions & { task?: WorldTaskRef } =>\n typeof value === \"object\" &&\n value !== null &&\n Object.keys(value).every((key) => OPEN_SESSION_OPTION_KEYS.has(key));\n\n/**\n * Open a live session on a world. Returns as soon as the platform has\n * accepted it — call `ready()` to wait for the container.\n *\n * `task` is a bundled scenario's name, a stored task's `{ id, version? }`\n * or an inline `WorldTaskSpec` (the latter two need a host engine world — the\n * platform answers 400 for a pod world). Omitted, the session is EXPLORATORY:\n * the platform records an inline `{instruction: \"exploratory session\"}` with\n * no grader as `task.source: \"none\"`, and `grade()` answers\n * `{reward: null, reason: \"no grader\"}`. The older positional form\n * `openSession(slug, \"task-name\", opts)` still works.\n */\nexport async function openSession(\n slugOrRef: string,\n task?: OpenSessionOptions & { task?: WorldTaskRef },\n): Promise<WorldSession>;\nexport async function openSession(\n slugOrRef: string,\n task: WorldTaskRef,\n opts?: OpenSessionOptions,\n): Promise<WorldSession>;\nexport async function openSession(\n slugOrRef: string,\n taskOrOpts:\n WorldTaskRef | (OpenSessionOptions & { task?: WorldTaskRef }) = {},\n positionalOpts: OpenSessionOptions = {},\n): Promise<WorldSession> {\n const { task, ...opts } = isOpenSessionOptions(taskOrOpts)\n ? taskOrOpts\n : { task: taskOrOpts as WorldTaskRef, ...positionalOpts };\n if (task !== undefined) assertTaskRef(task);\n const options = opts.options ?? {};\n const unknown = (opts.surfaces ?? []).filter(\n (s) => !(SURFACE_KINDS as readonly string[]).includes(s),\n );\n if (unknown.length)\n throw new Error(\n `Unknown world surfaces: ${unknown.join(\", \")}; choose from ${SURFACE_KINDS.join(\", \")}`,\n );\n if (opts.browserTier !== undefined) assertBrowserTier(opts.browserTier);\n if (opts.auth !== undefined) assertSessionAuthMode(opts.auth);\n const at = slugOrRef.indexOf(\"@\");\n const slug = at === -1 ? slugOrRef : slugOrRef.slice(0, at);\n const ref = at === -1 ? \"\" : slugOrRef.slice(at + 1);\n const state = await apiRequest<WorldSessionState & { reusedWarm: boolean }>(\n options,\n \"POST\",\n \"/api/public/world-sessions\",\n {\n ...(opts.versionId\n ? { versionId: opts.versionId }\n : { slug, ...(ref && { ref }) }),\n ...(task === undefined ? {} : { task }),\n ...(opts.reuseWarm === undefined ? {} : { reuseWarm: opts.reuseWarm }),\n ...(opts.surfaces?.length ? { surfaces: opts.surfaces } : {}),\n ...(opts.browserTier === undefined\n ? {}\n : { browserTier: opts.browserTier }),\n ...(opts.auth === undefined ? {} : { auth: opts.auth }),\n ...(opts.worldState === undefined ? {} : { worldState: opts.worldState }),\n },\n );\n return new WorldSession(state.sessionId, state, options);\n}\n\nexport type SessionRunResult = {\n /** The task's name, or `inline:<hash>` for an unnamed inline task. */\n task: string;\n sessionId: string;\n reward: number | null;\n rewards: Record<string, number>;\n /** Set when the task threw instead of grading. */\n error?: string;\n};\n\nexport type SessionRunReport = {\n results: SessionRunResult[];\n /** Mean reward over every task, counting failures as 0. */\n mean: number;\n /** Tasks that never graded: the session did not open or become ready, the\n * agent threw, or grading failed. Any failure fails the run — a 0 an agent\n * earned and a session that never opened are not the same result. */\n failed: number;\n /** True when no task failed and `mean >= failUnder` (or no gate was set). */\n passed: boolean;\n};\n\n/**\n * RUN MANY TASKS IN PARALLEL, one warm container each.\n *\n * Parallelism against live worlds is the normal case — a suite is a dozen\n * tasks and each needs its own container, because two agents sharing one\n * world state would corrupt both episodes. Every caller was writing the same\n * pool, the same per-task open/ready/toolkit/grade/close, and the same\n * \"don't let one failure kill the run\" logic, so it belongs here:\n *\n * const report = await runSessions({\n * world: \"revenue-ops-sim@main\",\n * tasks, // default: every task in the world\n * concurrency: 4,\n * failUnder: 0.7,\n * agent: async ({ toolkit, instruction }) =>\n * myAgent(toolkit.impls, toolkit.schemas, instruction),\n * });\n *\n * The handler gets a ready session with its toolkit already bound, and runs\n * inside `session.withTraceContext`; grading, closing (warm) and aggregation\n * are handled. A task that throws scores 0 and records why — the tasks that\n * 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 (a pinned one's own task list, never\n // the tip's), so a push mid-suite cannot split the results across two worlds.\n const { openWorld, openWorldVersion } = await import(\"./index\");\n const world = versionId\n ? await openWorldVersion(opts.world.split(\"@\", 1)[0]!, versionId, options)\n : await openWorld(opts.world, options);\n tasks = tasks ?? world.tasks.map((t) => t.name);\n versionId = versionId ?? world.version.versionId;\n }\n\n const results: SessionRunResult[] = [];\n let next = 0;\n await Promise.all(\n Array.from({ length: Math.min(concurrency, tasks.length) }, async () => {\n while (next < tasks!.length) {\n const taskRef = tasks![next++];\n let task = taskLabel(taskRef);\n let session: WorldSession | null = null;\n let keepWarm = opts.keepWarm ?? true;\n try {\n session = await openSession(opts.world, {\n task: taskRef,\n versionId,\n options,\n });\n task = taskLabel(taskRef, session.taskInfo);\n WorldToolsUnread.refuse(opts.world.split(\"@\", 1)[0]!, session.deprecations);\n await session.ready();\n const toolkit = await session.toolkit();\n const live = session;\n await live.withTraceContext(() =>\n opts.agent({\n session: live,\n toolkit,\n instruction:\n live.instruction ??\n (isTaskSpec(taskRef) ? taskRef.instruction : task),\n task,\n taskRef,\n }),\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 if (error instanceof WorldToolsUnread) keepWarm = false;\n const result: SessionRunResult = {\n task,\n sessionId: session?.sessionId ?? \"\",\n reward: 0,\n rewards: {},\n // An empty message reads as \"no error\" to a truthiness check; 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 fleet's idle TTL reaps it.\n await session\n ?.close({ keepWarm })\n .catch(() => undefined);\n }\n }\n }),\n );\n\n const mean =\n results.reduce((sum, r) => sum + (r.reward ?? 0), 0) /\n (results.length || 1);\n const failed = results.filter((r) => r.error).length;\n return {\n results: results.sort((a, b) => a.task.localeCompare(b.task)),\n mean,\n failed,\n passed:\n failed === 0 && (opts.failUnder === undefined || mean >= opts.failUnder),\n };\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\n\n/** Mirrors `WorldSessionListItemSchema` (web/features/public-api/types/world-sessions.ts). */\nexport type WorldSessionListItem = {\n sessionId: string;\n slug: string;\n containerId: string;\n state: string;\n ready: boolean;\n versionId: string;\n contentHash: string;\n taskName: string | null;\n engine: string;\n pinned: boolean;\n surfaces: string[];\n createdAt: string;\n lastUsedAt: string;\n};\n\n/** A World Host session's states (`SessionState` in shared `worldSessions.ts`). */\nexport const SESSION_STATES = [\n \"PROVISIONING\",\n \"RUNNING\",\n \"IDLE\",\n \"STOPPING\",\n \"STOPPED\",\n \"FAILED\",\n \"LOST\",\n] as const;\n\nexport type ListSessionsFilter = {\n /** One of SESSION_STATES. */\n state?: string;\n slug?: string;\n limit?: number;\n};\n\n/** The project's sessions in every state, newest first; `state` narrows to one. */\nexport async function listSessions(\n filter: ListSessionsFilter = {},\n options: WorldsClientOptions = {},\n): Promise<WorldSessionListItem[]> {\n const params = new URLSearchParams();\n if (filter.state) params.set(\"state\", filter.state);\n if (filter.slug) params.set(\"slug\", filter.slug);\n if (filter.limit !== undefined) params.set(\"limit\", String(filter.limit));\n const qs = params.toString();\n const res = await apiRequest<{ sessions: WorldSessionListItem[] }>(\n options,\n \"GET\",\n `/api/public/world-sessions${qs ? `?${qs}` : \"\"}`,\n );\n return res.sessions;\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\nimport type { WorldTaskSpec } from \"./session\";\n\n/**\n * STORED WORLD TASKS: a task spec kept by the project, outside any bundle.\n *\n * An inline task (`openSession(world, { task: { instruction, … } })`) belongs\n * to one session. A stored task is the same spec as a named, versioned\n * project resource: create it once, open as many sessions on it as you like\n * with `{ task: { id } }`, and every grade attributes back to the task and\n * its version. Updating the spec never rewrites history — it appends a\n * version, and a session opened on `{ id, version: 2 }` keeps running v2\n * after v3 exists.\n *\n * const task = await createTask({\n * name: \"refund-late-invoice\",\n * world: \"acme-billing\",\n * spec: { instruction: \"…\", seed: {…}, grader: {…} },\n * });\n * const session = await openSession(\"acme-billing\", { task: { id: task.id } });\n *\n * Tasks are project-scoped: another project's task id is not found (404),\n * never forbidden. `world` pins a task to one world's slug (validated against\n * that world's contract); null leaves it usable with any world.\n */\n\nexport type WorldTaskSummary = {\n id: string;\n name: string;\n world: string | null;\n version: number;\n hash: string;\n spec: WorldTaskSpec;\n /** A multi-world task's aliases in spec order; empty for a single world. */\n aliases: string[];\n /** Listed by world: the aliases that world plays in this task; else empty. */\n aliasesHere: string[];\n /** What grades the task, one row per check or verifier: its reward key,\n * the aliases it judges, what it checks in plain words, its source. */\n verifiers: WorldTaskVerifierRow[];\n createdAt: string;\n updatedAt: string;\n createdBy: string;\n updatedBy: string;\n /** On create, when the task is pinned to a world of a deprecated shape (an\n * api bundle): what to run instead. A retired shape is refused. */\n deprecations?: { code: string; message: string; replacement: string }[];\n};\n\nexport type WorldTaskVersionSummary = {\n version: number;\n hash: string;\n createdAt: string;\n createdBy: string;\n message: string | null;\n};\n\nexport type WorldTaskVerifierRow = {\n key: string;\n aliases: string[];\n kind: \"assertions\" | \"python\" | \"rubric\";\n description: string | null;\n source: string | null;\n sourceLanguage: \"python\" | \"text\" | null;\n};\n\nexport type WorldTaskDetail = WorldTaskSummary & {\n versions: WorldTaskVersionSummary[];\n};\n\nexport type WorldTaskPage = {\n tasks: WorldTaskSummary[];\n meta: {\n page: number;\n limit: number;\n totalItems: number;\n totalPages: number;\n /** Listed by world: the scan for multi-world tasks naming it filled its\n * bound, so `totalItems` is a floor. */\n scanTruncated?: true;\n };\n};\n\nexport type WorldTaskWorldValidation = {\n slug: string;\n ref: string;\n versionId: string;\n ok: boolean;\n checked: \"entities\" | \"none\";\n problems: string[];\n entities: string[] | null;\n};\n\nexport type WorldTaskValidation = {\n taskId: string;\n version: number;\n /** The world version the task was checked against; null for a task with\n * `worlds`, whose versions are per alias under `worlds`. */\n versionId: string | null;\n ok: boolean;\n /** `entities` when the world's contract was read and every seed and check\n * entity was matched against it; `none` when the version has no contract\n * to check (a mock-tools world), in which case `ok` says only that the\n * version exists and is READY; `worlds` for a multi-world task, checked\n * alias by alias against the ref each names. */\n checked: \"entities\" | \"none\" | \"worlds\";\n /** For a multi-world task each problem is prefixed with its alias. */\n problems: string[];\n entities: string[] | null;\n worlds?: Record<string, WorldTaskWorldValidation>;\n};\n\nconst TASKS = \"/api/public/world-tasks\";\nconst taskRoute = (id: string) => `${TASKS}/${encodeURIComponent(id)}`;\n\nconst compact = (body: Record<string, unknown>) =>\n Object.fromEntries(Object.entries(body).filter(([, v]) => v !== undefined));\n\n/** Store a task. `name` defaults to `spec.name`; one of the two is needed. */\nexport async function createTask(\n input: {\n spec: WorldTaskSpec;\n name?: string;\n world?: string | null;\n message?: string;\n },\n options: WorldsClientOptions = {},\n): Promise<WorldTaskSummary> {\n return apiRequest<WorldTaskSummary>(\n options,\n \"POST\",\n TASKS,\n compact({\n spec: input.spec,\n name: input.name,\n world: input.world,\n message: input.message,\n }),\n );\n}\n\n/** Change a task. A new `spec` becomes the next version (the old ones stay\n * readable and openable); `name` and `world` change in place. */\nexport async function updateTask(\n taskId: string,\n input: {\n spec?: WorldTaskSpec;\n name?: string;\n world?: string | null;\n message?: string;\n },\n options: WorldsClientOptions = {},\n): Promise<WorldTaskSummary> {\n if (\n input.spec === undefined &&\n input.name === undefined &&\n input.world === undefined\n )\n throw new Error(\"updateTask: nothing to update — pass spec, name or world\");\n return apiRequest<WorldTaskSummary>(\n options,\n \"PATCH\",\n taskRoute(taskId),\n compact({\n spec: input.spec,\n name: input.name,\n world: input.world,\n message: input.message,\n }),\n );\n}\n\n/** The project's tasks, newest change first. `world` keeps only tasks\n * that run against that slug (pinned to it, or naming it under an alias); `metadata` keeps tasks whose spec metadata carries\n * every given key/value (`{ externalUserId: \"u_42\" }`). */\nexport async function listTasks(\n filter: {\n world?: string;\n metadata?: Record<string, string>;\n page?: number;\n limit?: number;\n } = {},\n options: WorldsClientOptions = {},\n): Promise<WorldTaskPage> {\n const params = new URLSearchParams();\n if (filter.world) params.set(\"world\", filter.world);\n if (filter.page !== undefined) params.set(\"page\", String(filter.page));\n if (filter.limit !== undefined) params.set(\"limit\", String(filter.limit));\n for (const [key, value] of Object.entries(filter.metadata ?? {}))\n params.set(`metadata.${key}`, value);\n const query = params.toString();\n return apiRequest<WorldTaskPage>(\n options,\n \"GET\",\n query ? `${TASKS}?${query}` : TASKS,\n );\n}\n\n/** One task with its version history; `version` reads that version's spec\n * instead of the current one. */\nexport async function getTask(\n taskId: string,\n opts: { version?: number } = {},\n options: WorldsClientOptions = {},\n): Promise<WorldTaskDetail> {\n const query =\n opts.version === undefined ? \"\" : `?version=${String(opts.version)}`;\n return apiRequest<WorldTaskDetail>(\n options,\n \"GET\",\n `${taskRoute(taskId)}${query}`,\n );\n}\n\n/** Remove a task and every version. Sessions already opened on it keep\n * their copy of the spec. */\nexport async function deleteTask(\n taskId: string,\n options: WorldsClientOptions = {},\n): Promise<{ id: string; name: string }> {\n return apiRequest(options, \"DELETE\", taskRoute(taskId));\n}\n\n/** Check a task against a world version without opening a session: every\n * seed entity and every check's entity must exist in the world's contract.\n * `slug` checks against that world's head, `versionId` against an exact\n * version, neither against the task's own `world` pin. */\nexport async function validateTask(\n taskId: string,\n target: { version?: number; slug?: string; versionId?: string } = {},\n options: WorldsClientOptions = {},\n): Promise<WorldTaskValidation> {\n return apiRequest<WorldTaskValidation>(\n options,\n \"POST\",\n `${taskRoute(taskId)}/validate`,\n compact({\n version: target.version,\n slug: target.slug,\n versionId: target.versionId,\n }),\n );\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\nimport { type WorldTaskSpec } from \"./session\";\n\nexport type TaskTrialRequest = {\n seq: number;\n at: string;\n via: string | null;\n operation: string | null;\n method: string | null;\n path: string | null;\n status: number;\n};\n\nexport type TaskTrialCheck = {\n passed: boolean;\n reason?: string;\n matched: TaskTrialRequest[];\n maybe: TaskTrialRequest[];\n};\n\nexport type GradedJournal = {\n complete: boolean;\n reason: string | null;\n requests: number;\n throughSeq: number | null;\n};\n\n/** A task's grader over one stored World Host session, filed nowhere. */\nexport type TaskTrial = {\n sessionId: string;\n taskId: string | null;\n version: number | null;\n graded: \"live\" | \"checkpoint\" | \"journal\";\n reward: number | null;\n rewards: Record<string, number | null>;\n reasons: Record<string, string>;\n reason: string | null;\n checks: Record<string, TaskTrialCheck>;\n journal: GradedJournal | null;\n summary: {\n via: string | null;\n operation: string | null;\n method: string | null;\n status: number;\n count: number;\n path: string | null;\n }[];\n};\n\nexport type RegradedRollout = {\n sampleId: string;\n sessionId: string | null;\n state: \"regraded\" | \"skipped\";\n reward: number | null;\n previous: { reward: number | null; verifierVersion: number | null };\n reason?: string;\n graded?: TaskTrial[\"graded\"];\n rewards?: Record<string, number | null>;\n reasons?: Record<string, string>;\n};\n\nexport type TaskRegrade = {\n taskId: string;\n version: number;\n runs: {\n evaluationId: string;\n verifierVersions: number[];\n verifiers: string | null;\n reward: number | null;\n rollouts: RegradedRollout[];\n }[];\n regraded: number;\n skipped: number;\n};\n\nexport type TaskTrialTarget =\n | { taskId: string; version?: number }\n | { spec: WorldTaskSpec };\n\nexport type TaskRegradeScope = {\n version?: number;\n runs?: string[];\n allRuns?: boolean;\n sessions?: string[];\n limit?: number;\n};\n\nconst TASKS = \"/api/public/world-tasks\";\n\nconst compact = (body: Record<string, unknown>) =>\n Object.fromEntries(Object.entries(body).filter(([, v]) => v !== undefined));\n\n/**\n * A stored task's grader over stored World Host sessions: `try` grades one\n * session and files nothing (each check with the journal requests it\n * matched), `regrade` grades a task's past runs again by one of its versions\n * and files the grades in place. Twin of the Python `TaskGrades`.\n */\nexport class TaskGrades {\n constructor(private readonly options: WorldsClientOptions = {}) {}\n\n try(sessionId: string, target: TaskTrialTarget): Promise<TaskTrial> {\n return apiRequest<TaskTrial>(\n this.options,\n \"POST\",\n `${TASKS}/try`,\n compact({ sessionId, ...target }),\n );\n }\n\n regrade(taskId: string, scope: TaskRegradeScope = {}): Promise<TaskRegrade> {\n return apiRequest<TaskRegrade>(\n this.options,\n \"POST\",\n `${TASKS}/${encodeURIComponent(taskId)}/regrade`,\n compact({ ...scope }),\n );\n }\n}\n","import {\n surfaceKinds,\n uiEntryUrl,\n type BrowserTier,\n type SessionSurfaces,\n type WorldSurfaceKind,\n} from \"./browser\";\n\n/** Where a session answers, in the shape `session open` prints and a\n * `task up` manifest keeps per world. */\nexport type SurfaceDescriptor = {\n surfaces: WorldSurfaceKind[];\n api?: { url: string; token?: string; auth?: \"open\" };\n ui?: { url: string; entry: string; apiPath: string | null };\n browser?: {\n wsUrl: string;\n viewport?: unknown;\n tier?: BrowserTier;\n };\n};\n\nexport function surfaceDescriptor(s: SessionSurfaces): SurfaceDescriptor {\n return {\n surfaces: surfaceKinds(s),\n ...(s.api\n ? {\n api: {\n url: s.api.url,\n ...(s.api.token ? { token: s.api.token } : {}),\n ...(s.api.auth ? { auth: s.api.auth } : {}),\n },\n }\n : {}),\n ...(s.ui\n ? { ui: { url: s.ui.url, entry: uiEntryUrl(s.ui), apiPath: s.ui.apiPath ?? null } }\n : {}),\n ...(s.browser\n ? {\n browser: {\n wsUrl: s.browser.wsUrl,\n viewport: s.browser.viewport,\n ...(s.browser.tier ? { tier: s.browser.tier } : {}),\n },\n }\n : {}),\n };\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\nimport {\n assertBrowserTier,\n type BrowserTier,\n type SessionSurfaces,\n type WorldSurfaceKind,\n} from \"./browser\";\nimport { GradePayload } from \"./grade\";\nimport { surfaceDescriptor, type SurfaceDescriptor } from \"./surfaceDescriptor\";\nimport {\n WorldSession,\n attachSession,\n isTaskIdRef,\n type GradeResult,\n type VerifierGrade,\n type WorldSessionCall,\n type WorldSessionState,\n type WorldTaskIdRef,\n type WorldTaskSpec,\n} from \"./session\";\n\nconst TASK_SESSIONS = \"/api/public/world-task-sessions\";\n\n/** The per-world entry of a `WorldTaskSpec.worlds` table. */\nexport type WorldTaskWorld = {\n slug: string;\n ref?: string;\n seed?: WorldTaskSpec[\"seed\"];\n grader?: WorldTaskSpec[\"grader\"];\n tools?: string[];\n};\n\n/** One world's session as the platform answered it at up. */\nexport type TaskWorldSessionState = WorldSessionState & {\n alias: string;\n slug: string;\n ref: string;\n reusedWarm: boolean;\n};\n\n/** Which world an alias is, as recorded at up or attach. */\nexport type TaskWorldRef = {\n slug: string;\n ref: string | null;\n};\n\n/** What `POST /world-task-sessions` answers. */\nexport type TaskSessionsResponse = {\n taskId: string | null;\n taskVersion: number | null;\n name: string | null;\n hash: string;\n instruction: string;\n sessions: Record<string, TaskWorldSessionState>;\n};\n\n/** One world in the manifest: where it answers, in the shape\n * `gateway worlds session open` prints for a single session. */\nexport type TaskManifestSession = {\n slug: string;\n ref: string | null;\n versionId: string;\n sessionId: string;\n ready: boolean;\n state: string;\n} & SurfaceDescriptor;\n\n/** The manifest: every session of the task, keyed by alias. The file\n * `task up --out` writes and `task down|status|grade|export` read. */\nexport type TaskManifest = {\n taskId: string | null;\n taskVersion: number | null;\n name: string | null;\n instruction: string | null;\n sessions: Record<string, TaskManifestSession>;\n};\n\n/** A stored task's live sessions, as `GET /world-task-sessions` lists them. */\nexport type LiveTaskSession = {\n alias: string | null;\n slug: string | null;\n sessionId: string;\n state: string;\n ready: boolean;\n versionId: string;\n taskVersion: number | null;\n createdAt: string;\n};\n\n/** The task's grade: every world's own `GradeResult` under its alias, the\n * task's cross-world verifiers by name (lifted from the world each is\n * anchored on), and the aggregate. `reward` is the mean of the worlds' and\n * verifiers' numeric rewards — null when none answered one (no grader\n * anywhere, or a judge still pending); a world or verifier with no reward\n * is listed under `ungraded` (a verifier as `x.<name>`), never counted as\n * 0. `rewards` flattens each world's named rewards as `<alias>.<key>`\n * beside `<alias>` for the world's own reward, and a verifier's as\n * `x.<name>` / `x.<name>.<key>`. `errors` names, by key, each world or\n * verifier that could not grade and each key two rewards claimed; any error\n * makes `reward` null, never the mean of the rest. */\nexport type TaskGrade = {\n reward: number | null;\n rewards: Record<string, number>;\n worlds: Record<string, GradeResult>;\n ungraded: string[];\n verifiers: Record<string, VerifierGrade>;\n errors: Record<string, string>;\n};\n\n/** A cross-world verifier's rewards flatten under `x.<name>`. The platform\n * refuses `x` and `x.<…>` as a world alias, and the fold refuses a key two\n * rewards claim, so a world's check never scores as a verifier. */\nexport const VERIFIER_REWARD_PREFIX = \"x.\";\n\n/** Every world's call log, keyed by alias. */\nexport type TaskExport = Record<string, WorldSessionCall[]>;\n\nconst manifestSession = (\n s: SessionSurfaces,\n state: {\n sessionId: string;\n ready: boolean;\n state: string;\n versionId: string;\n },\n world: TaskWorldRef,\n): TaskManifestSession => ({\n slug: world.slug,\n ref: world.ref,\n versionId: state.versionId,\n sessionId: state.sessionId,\n ready: state.ready,\n state: state.state,\n ...surfaceDescriptor(s),\n});\n\nclass TaskGradeFold {\n readonly rewards: Record<string, number> = {};\n readonly ungraded: string[] = [];\n readonly errors: Record<string, string> = {};\n private readonly sources = new Map<string, string>();\n private readonly graded: number[] = [];\n\n add(key: string, grade: VerifierGrade, source: string): void {\n if (grade.error) this.errors[key] = grade.error;\n if (typeof grade.reward === \"number\") {\n this.put(key, grade.reward, source);\n this.graded.push(grade.reward);\n } else this.ungraded.push(key);\n for (const [name, value] of Object.entries(grade.rewards))\n this.put(`${key}.${name}`, value, source);\n }\n\n reward(): number | null {\n if (Object.keys(this.errors).length > 0 || !this.graded.length)\n return null;\n return this.graded.reduce((a, b) => a + b, 0) / this.graded.length;\n }\n\n private put(key: string, value: number, source: string): void {\n const first = this.sources.get(key) ?? source;\n this.sources.set(key, first);\n if (first !== source) {\n this.errors[key] =\n `two rewards are named ${key} (${first} and ${source}); rename one of them`;\n return;\n }\n this.rewards[key] = value;\n }\n}\n\n/** Combine per-world grades into the task's. Pure, so the CLI and the tests\n * share it with `TaskSessions.grade()`. */\nexport function aggregateTaskGrade(\n worlds: Record<string, GradeResult>,\n): TaskGrade {\n const fold = new TaskGradeFold();\n const verifiers: Record<string, VerifierGrade> = {};\n for (const [alias, grade] of Object.entries(worlds)) {\n fold.add(alias, grade, `world ${alias}`);\n Object.assign(verifiers, grade.verifiers ?? {});\n }\n for (const [name, grade] of Object.entries(verifiers))\n fold.add(`${VERIFIER_REWARD_PREFIX}${name}`, grade, `verifier ${name}`);\n return {\n reward: fold.reward(),\n rewards: fold.rewards,\n worlds,\n ungraded: fold.ungraded,\n verifiers,\n errors: fold.errors,\n };\n}\n\n/** Every error of a task's grade on one line (`<key>: <why>; …`), or null. */\nexport function taskGradeError(grade: TaskGrade): string | null {\n const lines = Object.entries(grade.errors).map(\n ([key, why]) => `${key}: ${why}`,\n );\n return lines.length ? lines.join(\"; \") : null;\n}\n\nexport class TaskSessions {\n constructor(\n /** The stored task's id, or null for a task given as a spec. */\n readonly taskId: string | null,\n readonly taskVersion: number | null,\n readonly name: string | null,\n /** The instruction every world's session shares. */\n readonly instruction: string | null,\n /** One live session per alias, in the spec's order. */\n readonly sessions: Record<string, WorldSession>,\n private readonly worlds: Record<string, TaskWorldRef>,\n /** The spec's content hash — set only by `openTask` (the raw platform\n * response carries it); null for a `TaskSessions` rebuilt with\n * `attachManifest`/`attachTask`, which have no spec to hash. */\n readonly hash: string | null = null,\n ) {}\n\n /** This alias's world as recorded at open/attach — what a `TaskRun`\n * filing needs to name, without exposing the whole map. */\n worldRef(alias: string): TaskWorldRef {\n return this.worlds[alias] ?? { slug: \"\", ref: null };\n }\n\n /** The aliases, in the spec's order. */\n get aliases(): string[] {\n return Object.keys(this.sessions);\n }\n\n /** The alias's session, or a clear error naming the aliases there are. */\n session(alias: string): WorldSession {\n const session = this.sessions[alias];\n if (!session)\n throw new Error(\n `task has no world '${alias}'; its worlds are ${this.aliases.join(\", \")}`,\n );\n return session;\n }\n\n private async each<T>(\n fn: (session: WorldSession, alias: string) => Promise<T>,\n ): Promise<Record<string, T>> {\n const entries = await Promise.all(\n Object.entries(this.sessions).map(\n async ([alias, session]) => [alias, await fn(session, alias)] as const,\n ),\n );\n return Object.fromEntries(entries);\n }\n\n /** Wait until every world answers ready. A world that never does throws\n * `WorldSessionTimeout` naming it; the others are left up. */\n async ready(opts: { timeoutMs?: number } = {}): Promise<void> {\n await this.each((session) => session.ready(opts));\n }\n\n /** Every world's current state, keyed by alias. */\n async status(): Promise<Record<string, WorldSessionState>> {\n return this.each((session) => session.status());\n }\n\n /** The manifest: where every world answers, keyed by alias. */\n async manifest(): Promise<TaskManifest> {\n const sessions = await this.each(async (session, alias) =>\n manifestSession(\n await session.surfaces(),\n {\n sessionId: session.sessionId,\n ready: session.isReady,\n state: (await session.status()).state,\n versionId: session.versionId,\n },\n this.worlds[alias]!,\n ),\n );\n return {\n taskId: this.taskId,\n taskVersion: this.taskVersion,\n name: this.name,\n instruction: this.instruction,\n sessions,\n };\n }\n\n /** Grade every world and aggregate — see `TaskGrade`. One `report` (the\n * agent's own account of the whole investigation) goes to every world's\n * judge; a world graded by assertions or python ignores it. Each grade\n * names the task's other sessions by alias, so the cross-world verifiers\n * anchored on that world can read them. A world whose grade call fails is\n * that world's error: the task's grade names it and keeps every other\n * world's grade. */\n async grade(\n opts: { timeoutMs?: number; report?: string } = {},\n ): Promise<TaskGrade> {\n return aggregateTaskGrade(\n await this.each((session, alias) =>\n session\n .grade({ ...opts, worlds: this.otherSessions(alias) })\n .catch((error: unknown) => GradePayload.failedCall(error)),\n ),\n );\n }\n\n /** The task's other sessions by alias: what a grade names. */\n private otherSessions(alias: string): Record<string, string> {\n return Object.fromEntries(\n Object.entries(this.sessions)\n .filter(([other]) => other !== alias)\n .map(([other, session]) => [other, session.sessionId]),\n );\n }\n\n /** Every world's call log, keyed by alias. */\n async export(): Promise<TaskExport> {\n return this.each((session) => session.export());\n }\n\n /** Close every world. Closes are attempted for all of them even when one\n * fails; the error then names every world that did not close. */\n async close(\n opts: { keepWarm?: boolean } = {},\n ): Promise<Record<string, { state: string }>> {\n const settled = await Promise.allSettled(\n Object.entries(this.sessions).map(\n async ([alias, session]) => [alias, await session.close(opts)] as const,\n ),\n );\n const failed: string[] = [];\n const closed: Record<string, { state: string }> = {};\n settled.forEach((result, i) => {\n const alias = this.aliases[i]!;\n if (result.status === \"fulfilled\") closed[alias] = result.value[1];\n else\n failed.push(\n `${alias}: ${result.reason instanceof Error ? result.reason.message : String(result.reason)}`,\n );\n });\n if (failed.length > 0)\n throw new Error(\n `${failed.length} of ${this.aliases.length} worlds did not close — ${failed.join(\"; \")}`,\n );\n return closed;\n }\n}\n\nexport type OpenTaskOptions = {\n /** With a task id: open that version of the task instead of the current. */\n version?: number;\n /** Asked of every world; the platform refuses (400) rather than serving\n * fewer surfaces than asked, and then nothing is up. */\n surfaces?: WorldSurfaceKind[];\n reuseWarm?: boolean;\n /** Browser capacity for every world the task opens: `standard` (spot, may\n * be reclaimed) or `premium` (on-demand). Unset, the organization's default. */\n browserTier?: BrowserTier;\n /** A world state per alias: that world's session opens on it. */\n worldStates?: Record<string, string>;\n options?: WorldsClientOptions;\n};\n\nfunction fromResponse(\n answer: TaskSessionsResponse,\n options: WorldsClientOptions,\n): TaskSessions {\n const sessions: Record<string, WorldSession> = {};\n const worlds: Record<string, TaskWorldRef> = {};\n for (const [alias, state] of Object.entries(answer.sessions)) {\n sessions[alias] = new WorldSession(state.sessionId, state, options);\n worlds[alias] = {\n slug: state.slug,\n ref: state.ref,\n };\n }\n return new TaskSessions(\n answer.taskId,\n answer.taskVersion,\n answer.name,\n answer.instruction,\n sessions,\n worlds,\n answer.hash ?? null,\n );\n}\n\n/**\n * Bring every world of a task up. `ref` is a stored task's id, its\n * `{ id, version? }`, or the spec itself (one with `worlds`). Returns as\n * soon as the platform has opened every session — `ready()` waits for the\n * containers. All or nothing: a world that fails to open closes the rest\n * and the error names it.\n */\nexport async function openTask(\n ref: string | WorldTaskIdRef | WorldTaskSpec,\n opts: OpenTaskOptions = {},\n): Promise<TaskSessions> {\n const options = opts.options ?? {};\n const task: WorldTaskIdRef | WorldTaskSpec =\n typeof ref === \"string\"\n ? {\n id: ref,\n ...(opts.version !== undefined ? { version: opts.version } : {}),\n }\n : isTaskIdRef(ref) && opts.version !== undefined\n ? { ...ref, version: opts.version }\n : ref;\n if (isTaskIdRef(task) ? !task.id : !task.instruction)\n throw new Error(\n \"openTask needs a task: a stored task id, { id, version? } or a spec with worlds\",\n );\n if (!isTaskIdRef(task) && !task.worlds)\n throw new Error(\n \"openTask needs a spec that names its worlds; a single-world spec opens with openSession\",\n );\n if (opts.browserTier !== undefined) assertBrowserTier(opts.browserTier);\n const answer = await apiRequest<TaskSessionsResponse>(\n options,\n \"POST\",\n TASK_SESSIONS,\n {\n task,\n ...(opts.reuseWarm === undefined ? {} : { reuseWarm: opts.reuseWarm }),\n ...(opts.surfaces?.length ? { surfaces: opts.surfaces } : {}),\n ...(opts.browserTier === undefined\n ? {}\n : { browserTier: opts.browserTier }),\n ...(opts.worldStates === undefined\n ? {}\n : { worldStates: opts.worldStates }),\n },\n );\n return fromResponse(answer, options);\n}\n\n/** A stored task's live sessions, newest first — every session the project\n * has opened on it that is not stopped or failed. */\nexport async function listTaskSessions(\n taskId: string,\n options: WorldsClientOptions = {},\n): Promise<LiveTaskSession[]> {\n const answer = await apiRequest<{\n taskId: string;\n sessions: LiveTaskSession[];\n }>(options, \"GET\", `${TASK_SESSIONS}?taskId=${encodeURIComponent(taskId)}`);\n return answer.sessions;\n}\n\n/**\n * Attach to the sessions a stored task has up — after a crash, or from a\n * process other than the one that ran `up`. Refuses when an alias is live\n * more than once (two `up`s of the same task): which set is meant is not\n * knowable, so pass the manifest (`attachManifest`) or close the extras.\n */\nexport async function attachTask(\n taskId: string,\n options: WorldsClientOptions = {},\n): Promise<TaskSessions> {\n const live = await listTaskSessions(taskId, options);\n if (live.length === 0)\n throw new Error(\n `task ${taskId} has no live sessions; run \\`task up\\` first`,\n );\n const byAlias = new Map<string, LiveTaskSession[]>();\n for (const session of live) {\n const alias = session.alias ?? session.sessionId;\n byAlias.set(alias, [...(byAlias.get(alias) ?? []), session]);\n }\n const doubled = [...byAlias.entries()].filter(([, rows]) => rows.length > 1);\n if (doubled.length > 0)\n throw new Error(\n `task ${taskId} has more than one live session for ${doubled\n .map(\n ([alias, rows]) =>\n `'${alias}' (${rows.map((r) => r.sessionId).join(\", \")})`,\n )\n .join(\", \")}; pass the manifest from \\`task up\\`, or close the extras`,\n );\n return attachManifest(\n {\n taskId,\n taskVersion: live[0]!.taskVersion,\n name: null,\n instruction: null,\n sessions: Object.fromEntries(\n [...byAlias.entries()].map(([alias, [row]]) => [\n alias,\n {\n slug: row!.slug ?? \"\",\n ref: null,\n versionId: row!.versionId,\n sessionId: row!.sessionId,\n ready: row!.ready,\n state: row!.state,\n surfaces: [\"tools\"] as WorldSurfaceKind[],\n },\n ]),\n ),\n },\n options,\n );\n}\n\n/** Attach to the sessions a manifest names — the file `task up --out`\n * wrote. Each session is read back from the platform, so a closed one is a\n * clear error rather than a stale handle. */\nexport async function attachManifest(\n manifest: TaskManifest,\n options: WorldsClientOptions = {},\n): Promise<TaskSessions> {\n const entries = await Promise.all(\n Object.entries(manifest.sessions).map(\n async ([alias, entry]) =>\n [alias, await attachSession(entry.sessionId, options)] as const,\n ),\n );\n const sessions = Object.fromEntries(entries);\n const instruction =\n manifest.instruction ?? entries[0]?.[1].instruction ?? null;\n return new TaskSessions(\n manifest.taskId,\n manifest.taskVersion,\n manifest.name,\n instruction,\n sessions,\n Object.fromEntries(\n Object.entries(manifest.sessions).map(([alias, entry]) => [\n alias,\n { slug: entry.slug, ref: entry.ref },\n ]),\n ),\n );\n}\n\n/** Whether a parsed JSON value is a task manifest (what `task up` wrote)\n * rather than a task spec. */\nexport function isTaskManifest(value: unknown): value is TaskManifest {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n typeof (value as { sessions?: unknown }).sessions === \"object\" &&\n (value as { sessions?: unknown }).sessions !== null &&\n !(\"instruction\" in value && \"worlds\" in value)\n );\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\nimport { PersonalTokenRefused, TOKEN_FILING } from \"./personalToken\";\nimport { platformEndpoint } from \"./platformEndpoint\";\nimport { RetryPolicy } from \"./transport\";\n\n/** TS twin of the Python SDK's GatewayEvalsClient (gatewaysdk/benchmark_hub/evals.py). */\n\nconst EVALUATIONS = \"/api/public/benchmark-containers/evaluations\";\n\nexport type EvalSample = {\n exampleId: string;\n task?: string;\n rolloutIndex?: number;\n prompt?: unknown;\n completion?: unknown;\n reward?: number;\n score?: number;\n correct?: boolean;\n /** A number, or null for a check that answered nothing; the platform refuses anything else. */\n rewards?: Record<string, number | null>;\n info?: Record<string, unknown>;\n};\n\nexport type CreateEvaluationOptions = {\n model?: string;\n /** A set run to file under; the platform refuses a run that does not admit this result. */\n runId?: string;\n rolloutsPerExample?: number;\n metadata?: Record<string, unknown>;\n /** Keys the filing: a repeated create answers the first evaluation, and every step of it is retried on a gateway\n * 5xx or no answer, since the platform answers a repeated step with the first one. */\n idempotencyKey?: string;\n};\n\nexport type FinalizeEvaluationOptions = {\n status?: \"COMPLETED\" | \"FAILED\";\n metrics?: Record<string, unknown>;\n};\n\nexport class GatewayEvalsClient {\n private readonly keyed = new Set<string>();\n\n constructor(\n private readonly options: WorldsClientOptions = {},\n private readonly retry: RetryPolicy = RetryPolicy.FILING,\n ) {\n GatewayEvalsClient.refuseToken(options);\n }\n\n static refuseToken(options: WorldsClientOptions): void {\n if (platformEndpoint(options)?.token) throw new PersonalTokenRefused(TOKEN_FILING);\n }\n\n async createEvaluation(\n versionId: string,\n opts: CreateEvaluationOptions = {},\n ): Promise<string> {\n const body: Record<string, unknown> = { versionId };\n if (opts.model !== undefined) body.model = opts.model;\n if (opts.runId !== undefined) body.runId = opts.runId;\n if (opts.rolloutsPerExample !== undefined)\n body.rolloutsPerExample = opts.rolloutsPerExample;\n if (opts.metadata !== undefined) body.metadata = opts.metadata;\n if (opts.idempotencyKey !== undefined)\n body.idempotencyKey = opts.idempotencyKey;\n const answer = await apiRequest<{ evaluationId: string }>(\n this.options,\n \"POST\",\n EVALUATIONS,\n body,\n {\n retry:\n opts.idempotencyKey === undefined ? RetryPolicy.NONE : this.retry,\n },\n );\n if (opts.idempotencyKey !== undefined) this.keyed.add(answer.evaluationId);\n return answer.evaluationId;\n }\n\n async pushSamples(\n evaluationId: string,\n samples: EvalSample[],\n ): Promise<number> {\n const answer = await apiRequest<{ inserted?: number }>(\n this.options,\n \"POST\",\n `${EVALUATIONS}/${encodeURIComponent(evaluationId)}/samples`,\n { samples },\n { retry: this.retryFor(evaluationId) },\n );\n return answer.inserted ?? samples.length;\n }\n\n async finalizeEvaluation(\n evaluationId: string,\n opts: FinalizeEvaluationOptions = {},\n ): Promise<string> {\n const body: Record<string, unknown> = {\n status: opts.status ?? \"COMPLETED\",\n };\n if (opts.metrics !== undefined) body.metrics = opts.metrics;\n const answer = await apiRequest<{ status: string }>(\n this.options,\n \"POST\",\n `${EVALUATIONS}/${encodeURIComponent(evaluationId)}/finalize`,\n body,\n { retry: this.retryFor(evaluationId) },\n );\n return answer.status;\n }\n\n private retryFor(evaluationId: string): RetryPolicy {\n return this.keyed.has(evaluationId) ? this.retry : RetryPolicy.NONE;\n }\n}\n","import { constants } from \"node:os\";\n\nexport type RunSignal = \"SIGINT\" | \"SIGTERM\";\n\nexport interface SignalTarget {\n on(signal: RunSignal, listener: (signal: RunSignal) => void): unknown;\n off(signal: RunSignal, listener: (signal: RunSignal) => void): unknown;\n listeners(signal: RunSignal): unknown[];\n listenerCount(signal: RunSignal): number;\n exit(code: number): void;\n}\n\ntype Cleanup = (signal: RunSignal, urgent: boolean) => Promise<void>;\n\nconst OWNER = Symbol(\"RunSignals\");\n\n/** While a run holds platform sessions, SIGINT and SIGTERM run its cleanups,\n * innermost first and one at a time (a task closes its sessions, and lets a\n * filing in flight finish, before the set run around it closes), then the\n * process exits 128 + the signal's number, the code a shell reports for a\n * process the signal ended. A hold opened inside another joins it. When a\n * listener someone else added holds the same signal, the exit is theirs. A\n * second signal runs every cleanup again as urgent (close without waiting for\n * an open or a filing in flight), then exits; a third exits at once. Python\n * twin: `gatewaysdk.run_signals.RunSignals`. */\nexport class RunSignals {\n static readonly SIGNALS: readonly RunSignal[] = [\"SIGINT\", \"SIGTERM\"];\n\n private readonly cleanups: Cleanup[] = [];\n private heardSignal: RunSignal | null = null;\n private heardCount = 0;\n private listening = false;\n private left = false;\n private readonly listener = Object.assign(\n (signal: RunSignal): void => this.heard(signal),\n { [OWNER]: this },\n );\n\n constructor(private readonly target: SignalTarget = process) {}\n\n /** The signal that arrived, once one has: start nothing new. */\n get signal(): RunSignal | null {\n return this.owner().heardSignal;\n }\n\n async during<T>(cleanup: Cleanup, work: () => Promise<T>): Promise<T> {\n return this.owner().hold(cleanup, work);\n }\n\n private owner(): RunSignals {\n const owners = this.target\n .listeners(\"SIGINT\")\n .map((listener) => (listener as { [OWNER]?: RunSignals })[OWNER]);\n return owners.find((owner) => owner !== undefined) ?? this;\n }\n\n private async hold<T>(cleanup: Cleanup, work: () => Promise<T>): Promise<T> {\n this.listen();\n this.cleanups.push(cleanup);\n try {\n return await work();\n } finally {\n this.cleanups.splice(this.cleanups.indexOf(cleanup), 1);\n if (!this.cleanups.length && this.heardSignal === null) this.unlisten();\n }\n }\n\n private heard(signal: RunSignal): void {\n this.heardCount += 1;\n if (this.heardCount > 2) return this.leave(signal);\n this.heardSignal ??= signal;\n void this.cleanUp(signal, this.heardCount === 2).finally(() => this.leave(signal));\n }\n\n private async cleanUp(signal: RunSignal, urgent: boolean): Promise<void> {\n for (const cleanup of [...this.cleanups].reverse())\n await Promise.resolve()\n .then(() => cleanup(signal, urgent))\n .catch(() => undefined);\n }\n\n private leave(signal: RunSignal): void {\n if (this.left) return;\n this.left = true;\n this.unlisten();\n if (this.target.listenerCount(signal) === 0)\n this.target.exit(128 + constants.signals[signal]);\n }\n\n private listen(): void {\n if (this.listening) return;\n this.listening = true;\n for (const signal of RunSignals.SIGNALS)\n this.target.on(signal, this.listener);\n }\n\n private unlisten(): void {\n this.listening = false;\n for (const signal of RunSignals.SIGNALS)\n this.target.off(signal, this.listener);\n }\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport { withoutUiToken } from \"./browser\";\nimport type { TaskManifest, TaskManifestSession } from \"./taskSessions\";\n\ntype BrowserDescriptor = NonNullable<TaskManifestSession[\"browser\"]>;\n\n/** `<outDir>/<runId>/` of a task run. The folder is made by its first file, so a refused run leaves\n * nothing behind; the manifest keeps ids, token-free URLs and surfaces, never a session credential.\n * Python twin: `gatewaysdk.world_task_run_dir.TaskRunDir`. */\nexport class TaskRunDir {\n constructor(readonly path: string) {}\n\n writeManifest(manifest: TaskManifest): void {\n this.writeJson(\"manifest.json\", {\n ...manifest,\n sessions: Object.fromEntries(\n Object.entries(manifest.sessions).map(([alias, session]) => [\n alias,\n sessionRecord(session),\n ]),\n ),\n });\n }\n\n writeJson(name: string, value: unknown): void {\n this.write(name, JSON.stringify(value, null, 2));\n }\n\n write(name: string, text: string): void {\n fs.mkdirSync(this.path, { recursive: true });\n fs.writeFileSync(path.join(this.path, name), text);\n }\n}\n\nconst browserRecord = ({ viewport, tier }: BrowserDescriptor) => ({\n viewport,\n ...(tier ? { tier } : {}),\n});\n\nfunction sessionRecord({ api, ui, browser, ...session }: TaskManifestSession) {\n return {\n ...session,\n ...(api ? { api: { url: api.url } } : {}),\n ...(ui ? { ui: { ...ui, entry: withoutUiToken(ui.entry) } } : {}),\n ...(browser ? { browser: browserRecord(browser) } : {}),\n };\n}\n","import type { EvalSample, FinalizeEvaluationOptions, GatewayEvalsClient } from \"./evals\";\nimport { messageOf } from \"./grade\";\nimport { taskGradeError, type TaskGrade, type TaskSessions } from \"./taskSessions\";\n\nexport type RunTaskSummary = {\n runId: string;\n taskId: string | null;\n taskVersion: number | null;\n name: string | null;\n instruction: string;\n model: string;\n aliases: string[];\n reward: number | null;\n rewards: Record<string, number>;\n ungraded: string[];\n agentError: string | null;\n /** Why the run stopped short of a grade (a world that never came up, an interrupt); filed FAILED with it. */\n runError: string | null;\n /** The grade's errors on one line (a world or verifier that could not grade, two rewards under one key); filed FAILED with it. */\n gradeError: string | null;\n /** Why the evaluation could not be filed; `filed` is then false. */\n fileError: string | null;\n /** The status the platform settled the filed evaluation at; null when nothing was filed. */\n evaluationStatus: string | null;\n report: string | null;\n traced: boolean;\n runDir: string;\n durationSeconds: number;\n notes: Record<string, unknown>;\n filed: boolean;\n evaluationId?: string;\n [extra: string]: unknown;\n};\n\n/** A failure is filed FAILED with its reason and no reward it did not earn. Python twin: `gatewaysdk.world_task_outcome.TaskRunOutcome`. */\nexport class TaskRunOutcome {\n report: string | null = null;\n extra: Record<string, unknown> = {};\n notes: Record<string, unknown> = {};\n agentError: string | null = null;\n grade: TaskGrade | null = null;\n traced = false;\n private runError: string | null = null;\n private fileError: string | null = null;\n private evaluationId: string | undefined;\n private evaluationStatus: string | null = null;\n private readonly started = Date.now();\n\n constructor(\n readonly runId: string,\n private readonly live: TaskSessions,\n private readonly model: string,\n private readonly runDir: string,\n ) {}\n\n stopped(error: unknown): void {\n this.runError ??= messageOf(error).slice(0, 2000);\n }\n\n agentRaised(error: unknown): void {\n this.agentError = messageOf(error).slice(0, 2000);\n }\n\n failure(): string | null {\n const reasons = [\n this.agentError === null ? null : `agent raised: ${this.agentError}`,\n this.runError === null ? null : `the run stopped: ${this.runError}`,\n this.gradeError(),\n this.grade === null && this.runError === null ? \"the run stopped before it was graded\" : null,\n ].filter((reason): reason is string => reason !== null);\n return reasons.length ? reasons.join(\"; \") : null;\n }\n\n async file(evals: GatewayEvalsClient, setRunId?: string): Promise<void> {\n let created: string | undefined;\n try {\n created = await evals.createEvaluation(this.ref(this.live.aliases[0]!).versionId, {\n model: this.model,\n rolloutsPerExample: 1,\n idempotencyKey: this.runId,\n ...(setRunId ? { runId: setRunId } : {}),\n metadata: this.metadata(),\n });\n await evals.pushSamples(created, [this.sample()]);\n this.evaluationStatus = await evals.finalizeEvaluation(created, this.finalized());\n this.evaluationId = created;\n } catch (error) {\n this.fileError = created ? `evaluation ${created}: ${messageOf(error)}` : messageOf(error);\n if (created)\n await evals\n .finalizeEvaluation(created, { status: \"FAILED\", metrics: { error: this.fileError } })\n .catch(() => undefined);\n }\n }\n\n summary(): RunTaskSummary {\n const live = this.live;\n const { evaluationId: _agentEvaluationId, ...extra } = this.extra;\n return {\n ...extra,\n runId: this.runId,\n taskId: live.taskId,\n taskVersion: live.taskVersion,\n name: live.name,\n instruction: live.instruction ?? \"\",\n model: this.model,\n aliases: live.aliases,\n reward: this.grade?.reward ?? null,\n rewards: this.grade?.rewards ?? {},\n ungraded: this.grade?.ungraded ?? live.aliases,\n agentError: this.agentError,\n runError: this.runError,\n gradeError: this.gradeError(),\n fileError: this.fileError,\n evaluationStatus: this.evaluationStatus,\n report: this.report,\n traced: this.traced,\n runDir: this.runDir,\n durationSeconds: Math.round((Date.now() - this.started) / 10) / 100,\n notes: this.notes,\n filed: this.evaluationId !== undefined,\n ...(this.evaluationId ? { evaluationId: this.evaluationId } : {}),\n };\n }\n\n private gradeError(): string | null {\n return this.grade ? taskGradeError(this.grade) : null;\n }\n\n private ref(alias: string) {\n const { slug, ref } = this.live.worldRef(alias);\n const session = this.live.sessions[alias]!;\n return { slug, ref, versionId: session.versionId, sessionId: session.sessionId };\n }\n\n private metadata(): Record<string, unknown> {\n const live = this.live;\n return {\n source: \"worlds-task-run\",\n task: { id: live.taskId, version: live.taskVersion, name: live.name, hash: live.hash },\n anchor: live.aliases[0],\n worlds: Object.fromEntries(live.aliases.map((alias) => [alias, this.ref(alias)])),\n runId: this.runId,\n };\n }\n\n private sample(): EvalSample {\n const live = this.live;\n const reward = this.grade?.reward ?? null;\n const gradeError = this.gradeError();\n const sample: Record<string, unknown> = {\n exampleId: live.name ?? live.taskId ?? this.runId,\n task: live.name ?? live.taskId ?? this.runId,\n rolloutIndex: 0,\n prompt: live.instruction,\n ...(this.report === null ? {} : { completion: this.report }),\n rewards: this.grade?.rewards ?? {},\n info: {\n sessionId: this.runId,\n worlds: Object.fromEntries(\n live.aliases.map((alias) => [\n alias,\n { ...this.ref(alias), reward: this.grade?.worlds[alias]?.reward ?? null },\n ]),\n ),\n ungraded: this.grade?.ungraded ?? live.aliases,\n verifierVersion: live.taskVersion,\n traced: this.traced,\n runDir: this.runDir,\n ...(this.agentError ? { agentError: this.agentError } : {}),\n ...(this.runError ? { runError: this.runError } : {}),\n ...(gradeError ? { verifyError: gradeError } : {}),\n },\n };\n if (typeof reward === \"number\")\n Object.assign(sample, { reward, score: reward, correct: reward >= 1.0 });\n return sample as unknown as EvalSample;\n }\n\n private finalized(): FinalizeEvaluationOptions {\n const reward = this.grade?.reward ?? null;\n const failure = this.failure();\n return {\n status: failure ? \"FAILED\" : \"COMPLETED\",\n metrics: {\n ...(typeof reward === \"number\" ? { avg_reward: reward } : {}),\n reward,\n ...Object.fromEntries(\n Object.entries(this.grade?.rewards ?? {}).map(([key, value]) => [`rewards.${key}`, value]),\n ),\n ...(failure ? { error: failure } : {}),\n },\n };\n }\n}\n","export const GATEWAY_ENV = {\n HOST: \"GATEWAY_HOST\",\n PUBLIC_KEY: \"GATEWAY_PUBLIC_KEY\",\n SECRET_KEY: \"GATEWAY_SECRET_KEY\",\n API_KEY: \"GATEWAY_API_KEY\",\n ENDPOINT: \"GATEWAY_OTLP_ENDPOINT\",\n} as const;\n\nexport const OTLP_TRACES_PATH = \"/api/public/otel/v1/traces\";\n\nexport const OPENTELEMETRY_PEERS = {\n \"@opentelemetry/api\": \"1.9.0\",\n \"@opentelemetry/exporter-trace-otlp-http\": \"0.222.0\",\n \"@opentelemetry/resources\": \"2.11.0\",\n \"@opentelemetry/sdk-trace-base\": \"2.11.0\",\n \"@opentelemetry/sdk-trace-node\": \"2.11.0\",\n} as const;\n\nconst PINNED_PEERS = Object.entries(OPENTELEMETRY_PEERS)\n .map(([name, version]) => `${name}@${version}`)\n .join(\" \");\n\nconst MODULE_NOT_FOUND = new Set([\"MODULE_NOT_FOUND\", \"ERR_MODULE_NOT_FOUND\"]);\n\nexport function getEnv(key: string): string | undefined {\n const value = process.env[key];\n return value ? value : undefined;\n}\n\n/**\n * Check if Gateway is configured via environment variables.\n */\nexport function isGatewayConfigured(): boolean {\n return !!(\n getEnv(GATEWAY_ENV.HOST) &&\n getEnv(GATEWAY_ENV.PUBLIC_KEY) &&\n getEnv(GATEWAY_ENV.SECRET_KEY)\n );\n}\n\nexport class OpenTelemetryMissing extends Error {\n constructor() {\n super(\n \"OpenTelemetry packages not found. Install them next to @withgateway/sdk, at the versions it is tested with:\\n\" +\n ` npm install ${PINNED_PEERS}\\n` +\n ` npm install -g ${PINNED_PEERS} (the gateway CLI, when it was installed with npm install -g)`,\n );\n this.name = \"OpenTelemetryMissing\";\n }\n\n static explains(error: unknown): boolean {\n if (error instanceof OpenTelemetryMissing) return true;\n const { code, message } = (error ?? {}) as {\n code?: unknown;\n message?: unknown;\n };\n return (\n MODULE_NOT_FOUND.has(String(code)) &&\n String(message).includes(\"@opentelemetry/\")\n );\n }\n}\n","import {\n GATEWAY_ENV,\n getEnv,\n OpenTelemetryMissing,\n OTLP_TRACES_PATH,\n} from \"../tracing/prerequisites\";\nimport type { TracingConfig } from \"../tracing/types\";\nimport type { WorldsClientOptions } from \"./index\";\nimport { GATEWAY_KEYS_MISSING, platformEndpoint } from \"./platformEndpoint\";\nimport { TOKEN_KEYS_ONLY } from \"./personalToken\";\nimport type { PlatformEndpoint } from \"./transport\";\n\ntype TracingInit = Pick<typeof import(\"../tracing/init\"), \"init\" | \"isInitialized\">;\n\nconst HOST_WITH_AUTHORITY = /^[a-z][a-z0-9+.-]*:\\/\\/[^/\\\\?#@\\s]+(\\/|$)/i;\n\nexport const TRACING_HELD_ELSEWHERE =\n \"Tracing in this process already sends spans to another destination or with other keys (an earlier \" +\n \"run, or the agent's own tracing.init()), so this run's spans would not reach its own project.\";\n\nexport class TaskTracing {\n private static warned = false;\n private static target: string | null = null;\n\n constructor(\n private readonly load: () => Promise<TracingInit> = () =>\n import(\"../tracing/init\"),\n ) {}\n\n async start(requested: boolean, options: WorldsClientOptions): Promise<boolean> {\n if (!requested) return false;\n let endpoint: PlatformEndpoint | null = null;\n try {\n endpoint = platformEndpoint(options);\n await this.initOnce(TaskTracing.config(endpoint));\n return true;\n } catch (error) {\n TaskTracing.warnOnce(TaskTracing.reason(error, endpoint));\n return false;\n }\n }\n\n // init() keeps the first provider for the whole process and ignores later calls, so a later run is\n // traced only when it exports to the same place with the same keys.\n private async initOnce(config: TracingConfig): Promise<void> {\n const tracing = await this.load();\n const target = JSON.stringify([config.endpoint, config.publicKey, config.secretKey]);\n if (!tracing.isInitialized()) {\n tracing.init(config);\n TaskTracing.target = target;\n return;\n }\n if (TaskTracing.target !== target) throw new Error(TRACING_HELD_ELSEWHERE);\n }\n\n private static config(endpoint: PlatformEndpoint | null): TracingConfig {\n if (!endpoint) throw new Error(GATEWAY_KEYS_MISSING);\n if (endpoint.token) throw new Error(TOKEN_KEYS_ONLY);\n return { ...endpoint, endpoint: TaskTracing.destination(endpoint) };\n }\n\n // B1: a saved login's keys go to their own host only. The redirect is compared as text, never parsed:\n // a fixed \"<host>/\" prefix leaves no URL parser room to read another host into it.\n private static destination(endpoint: PlatformEndpoint): string {\n const redirect = getEnv(GATEWAY_ENV.ENDPOINT);\n if (!redirect) return `${endpoint.host}${OTLP_TRACES_PATH}`;\n if (TaskTracing.underHost(redirect, endpoint.host) || TaskTracing.environmentKeys(endpoint)) return redirect;\n throw new Error(\n `GATEWAY_OTLP_ENDPOINT is not under ${endpoint.host}, and this run's keys are not ` +\n `GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY: they are sent to ${endpoint.host} only. ` +\n \"Unset GATEWAY_OTLP_ENDPOINT, or set both keys in the environment.\",\n );\n }\n\n private static underHost(redirect: string, host: string): boolean {\n return HOST_WITH_AUTHORITY.test(host) && redirect.startsWith(`${host}/`);\n }\n\n private static environmentKeys(endpoint: PlatformEndpoint): boolean {\n const secretKey = getEnv(GATEWAY_ENV.SECRET_KEY) ?? getEnv(GATEWAY_ENV.API_KEY);\n return endpoint.publicKey === getEnv(GATEWAY_ENV.PUBLIC_KEY) && endpoint.secretKey === secretKey;\n }\n\n private static warnOnce(reason: string): void {\n if (TaskTracing.warned) return;\n TaskTracing.warned = true;\n console.warn(\n `[gatewaysdk.tracing] Task runs in this process are not traced. ${reason}\\n` +\n \"Pass --no-trace (trace: false) to run untraced without this warning.\",\n );\n }\n\n private static reason(error: unknown, endpoint: PlatformEndpoint | null): string {\n if (OpenTelemetryMissing.explains(error)) return new OpenTelemetryMissing().message;\n const message = error instanceof Error ? error.message : String(error);\n const keys = [endpoint?.publicKey, endpoint?.secretKey, endpoint?.token?.value].filter(\n (key): key is string => Boolean(key),\n );\n return keys.reduce((text, key) => text.split(key).join(\"[redacted]\"), message);\n }\n}\n","import { randomBytes } from \"node:crypto\";\nimport * as path from \"node:path\";\n\nimport type { BrowserTier, WorldSurfaceKind } from \"./browser\";\nimport { WorldSurfaceUnavailable } from \"./browser\";\nimport { GatewayEvalsClient } from \"./evals\";\nimport type { WorldsClientOptions } from \"./index\";\nimport { RunSignals, type RunSignal } from \"./runSignals\";\nimport {\n modelToolName,\n schemaFromSignature,\n WorldSession,\n type WorldTaskIdRef,\n type WorldTaskSpec,\n type WorldToolkit,\n type WorldToolSpec,\n} from \"./session\";\nimport { openTask, TaskSessions, type TaskManifest } from \"./taskSessions\";\nimport { TaskRunDir } from \"./taskRunDir\";\nimport { TaskRunOutcome, type RunTaskSummary } from \"./taskRunOutcome\";\nimport { TaskTracing } from \"./taskTracing\";\nimport { WorldToolsUnread } from \"./worldNotice\";\n\nexport type { RunTaskSummary } from \"./taskRunOutcome\";\n\nexport class TaskRun {\n readonly notes: Record<string, unknown> = {};\n\n constructor(\n readonly runId: string,\n readonly instruction: string,\n readonly model: string,\n readonly sessions: Record<string, WorldSession>,\n readonly manifest: TaskManifest,\n ) {}\n\n session(alias: string): WorldSession {\n const session = this.sessions[alias];\n if (!session)\n throw new Error(\n `task run has no world '${alias}'; its worlds are ${Object.keys(this.sessions).join(\", \")}`,\n );\n return session;\n }\n\n /** Raises when the session was not opened with `surfaces: [\"api\"]`. */\n async api(alias: string): Promise<{ url: string; token?: string }> {\n const surfaces = await this.session(alias).surfaces();\n if (!surfaces.api)\n throw new WorldSurfaceUnavailable(\n \"api\",\n `open '${alias}' with surfaces: ['api']`,\n );\n return { url: surfaces.api.url, token: surfaces.api.token };\n }\n\n /** Each tool is prefixed `<alias>.<tool>` so a model can tell which world a call goes to. */\n async toolkit(): Promise<WorldToolkit> {\n const schemas: WorldToolkit[\"schemas\"] = [];\n const impls: WorldToolkit[\"impls\"] = {};\n const specs: WorldToolSpec[] = [];\n for (const [alias, session] of Object.entries(this.sessions)) {\n const kit = await session.toolkit();\n if (!kit.specs.length) continue;\n for (const spec of kit.specs) {\n const name = `${alias}.${spec.name}`;\n const prefixed: WorldToolSpec = {\n name,\n signature: spec.signature,\n doc: spec.doc,\n inputSchema: spec.inputSchema,\n };\n specs.push(prefixed);\n const schema = schemaFromSignature(prefixed);\n schema.function.name = name;\n schemas.push(schema);\n impls[name] = kit.impls[modelToolName(spec.name)]!;\n }\n }\n return { schemas, impls, specs };\n }\n\n /** Merged into `run.json` under `notes`; a later call overrides an earlier key. */\n record(notes: Record<string, unknown>): void {\n Object.assign(this.notes, notes);\n }\n}\n\nexport type RunTaskOptions = {\n model: string;\n surfaces?: WorldSurfaceKind[];\n /** Directory the run's own `<runId>/` folder is created under. Default `\"runs\"`. */\n outDir?: string;\n /**\n * Trace the agent's own spans with the host and keys the run's requests use (`options`, then\n * `GATEWAY_*`). Default `true`. A `GATEWAY_OTLP_ENDPOINT` on another host is followed only with the\n * environment's own keys. When tracing cannot start (the optional `@opentelemetry/*` peers are\n * missing, or a redirect would carry other keys), the run goes on untraced and the process warns once.\n */\n trace?: boolean;\n /** File one rollout when the run ends. Default `true`. */\n file?: boolean;\n /** Leave every session up instead of closing it when the run ends. Default `false`. */\n keepUp?: boolean;\n reuseWarm?: boolean;\n browserTier?: BrowserTier;\n /** A world state per alias: that world's session opens on it. */\n worldStates?: Record<string, string>;\n /** File the rollout under this set run (`runSet` sets it). */\n setRunId?: string;\n options?: WorldsClientOptions;\n};\n\nconst FILING_UNFINISHED = \"the filing did not finish\";\n\n/** The line a CLI prints before exiting 1 on a task run: the agent raised,\n * the run stopped short of a grade, the task could not be graded, the run\n * could not be filed, or the platform settled it failed; null when none. */\nexport function taskRunFailure(summary: RunTaskSummary): string | null {\n if (summary.agentError !== null) return `agent raised: ${summary.agentError}`;\n if (summary.runError !== null) return `the run stopped: ${summary.runError}`;\n if (summary.gradeError !== null)\n return `the task could not be graded: ${summary.gradeError}`;\n if (summary.fileError !== null)\n return `the run could not be filed: ${summary.fileError}`;\n if (summary.filed && summary.evaluationStatus !== \"COMPLETED\")\n return `the platform settled evaluation ${summary.evaluationId} as ${summary.evaluationStatus}`;\n return null;\n}\n\nexport type TaskRunResult =\n | string\n | { report?: unknown; [key: string]: unknown }\n | null\n | undefined;\n\nconst describeValue = (value: unknown): string =>\n Array.isArray(value) ? \"array\" : value === null ? \"null\" : typeof value;\n\nconst RESULT_CONTRACT =\n \"return a string report, an object {report?: string, ...} or nothing\";\n\nfunction reportFromResult(result: TaskRunResult): {\n report: string | null;\n extra: Record<string, unknown>;\n} {\n if (result === undefined || result === null)\n return { report: null, extra: {} };\n if (typeof result === \"string\") return { report: result, extra: {} };\n if (typeof result !== \"object\" || Array.isArray(result))\n throw new Error(\n `agent returned ${describeValue(result)}; ${RESULT_CONTRACT}`,\n );\n const { report, ...extra } = result as Record<string, unknown>;\n if (report === undefined || report === null) return { report: null, extra };\n if (typeof report !== \"string\")\n throw new Error(\n `agent returned a report of type ${describeValue(report)}; ${RESULT_CONTRACT}`,\n );\n return { report, extra };\n}\n\nasync function refuseUnreadTools(live: TaskSessions): Promise<void> {\n try {\n for (const alias of live.aliases)\n WorldToolsUnread.refuse(`${live.worldRef(alias).slug} (alias ${alias})`, live.session(alias).deprecations);\n } catch (error) {\n await live.close({ keepWarm: false }).catch(() => undefined);\n throw error;\n }\n}\n\ntype TaskAgent = (run: TaskRun) => TaskRunResult | Promise<TaskRunResult>;\n\n/** One run of a task whose sessions are up: play it, file it, write its\n * record and close, whatever stage it stopped at. An interrupt before the\n * grade closes the sessions, writes the record and files nothing; one after\n * it lets the filing in flight finish first. */\nclass LiveTaskRun {\n private readonly files: TaskRunDir;\n private readonly outcome: TaskRunOutcome;\n private played = false;\n private interrupted = false;\n private filing: Promise<void> | null = null;\n private ending: Promise<void> | null = null;\n\n constructor(\n runId: string,\n private readonly live: TaskSessions,\n private readonly opts: RunTaskOptions,\n private readonly options: WorldsClientOptions,\n ) {\n this.files = new TaskRunDir(path.join(opts.outDir ?? \"runs\", runId));\n this.outcome = new TaskRunOutcome(runId, live, opts.model, this.files.path);\n }\n\n async complete(agent: TaskAgent): Promise<RunTaskSummary> {\n try {\n await this.play(agent).catch((error: unknown) => this.outcome.stopped(error));\n this.played = true;\n await this.file();\n return this.record();\n } finally {\n await this.end();\n }\n }\n\n async interrupt(signal: RunSignal, urgent = false): Promise<void> {\n const sessions = this.opts.keepUp ? \"leaving its sessions up\" : \"closing its sessions\";\n const how = urgent ? \" now, without waiting\" : \"\";\n process.stderr.write(`${this.outcome.runId} interrupted by ${signal}; ${sessions}${how}\\n`);\n if (!this.played) this.outcome.stopped(`interrupted by ${signal}`);\n this.interrupted = true;\n try {\n if (!urgent) await this.filing;\n this.record();\n } catch (error) {\n const why = error instanceof Error ? error.message : String(error);\n process.stderr.write(`${this.outcome.runId}: run.json not written: ${why}\\n`);\n } finally {\n await this.end();\n }\n }\n\n summary(): RunTaskSummary {\n return this.outcome.summary();\n }\n\n private async play(agent: TaskAgent): Promise<void> {\n await this.live.ready();\n this.outcome.traced = await new TaskTracing().start(this.opts.trace !== false, this.options);\n const run = new TaskRun(\n this.outcome.runId,\n this.live.instruction ?? \"\",\n this.opts.model,\n this.live.sessions,\n await this.live.manifest(),\n );\n this.outcome.notes = run.notes;\n this.files.writeManifest(run.manifest);\n await this.callAgent(agent, run);\n const report = this.outcome.report;\n this.outcome.grade = await this.live.grade(report !== null ? { report } : {});\n this.files.writeJson(\"grades.json\", this.outcome.grade);\n if (report) this.files.write(\"report.md\", report);\n }\n\n private async callAgent(agent: TaskAgent, run: TaskRun): Promise<void> {\n try {\n const invoke = () => agent(run);\n const result = this.outcome.traced\n ? await (await import(\"../tracing/session\")).withSession(run.runId, invoke)\n : await invoke();\n ({ report: this.outcome.report, extra: this.outcome.extra } = reportFromResult(result));\n } catch (error) {\n this.outcome.agentRaised(error);\n }\n if (this.outcome.traced)\n await import(\"../tracing/init\")\n .then((tracing) => tracing.flush())\n .catch(() => undefined);\n }\n\n private async file(): Promise<void> {\n if (this.opts.file === false || this.interrupted) return;\n this.files.writeJson(\"run.json\", { ...this.outcome.summary(), fileError: FILING_UNFINISHED });\n this.filing = this.outcome.file(new GatewayEvalsClient(this.options), this.opts.setRunId);\n await this.filing;\n }\n\n private record(): RunTaskSummary {\n const summary = this.outcome.summary();\n this.files.writeJson(\"run.json\", summary);\n return summary;\n }\n\n private end(): Promise<void> {\n this.ending ??= this.opts.keepUp\n ? Promise.resolve()\n : this.live.close({ keepWarm: false }).then(\n () => undefined,\n () => undefined,\n );\n return this.ending;\n }\n}\n\n/** A run whose sessions the platform is still opening. A signal before it\n * answers waits for the answer, then closes what it opened; the agent never\n * starts. An urgent signal closes only what has already opened. */\nclass TaskOpening {\n private interrupting: Promise<void> | null = null;\n private run: LiveTaskRun | null = null;\n private readonly opened: Promise<LiveTaskRun>;\n\n constructor(opening: Promise<LiveTaskRun>) {\n this.opened = opening.then((run) => (this.run = run));\n }\n\n async complete(agent: TaskAgent): Promise<RunTaskSummary> {\n const run = await this.opened;\n if (!this.interrupting) return run.complete(agent);\n await this.interrupting;\n return run.summary();\n }\n\n interrupt(signal: RunSignal, urgent = false): Promise<void> {\n if (urgent) return this.run?.interrupt(signal, true) ?? Promise.resolve();\n this.interrupting ??= this.opened.then(\n (run) => run.interrupt(signal),\n () => undefined,\n );\n return this.interrupting;\n }\n}\n\n/** Mirrors `gatewaysdk.world_tasks.run_task`. Every run whose sessions opened\n * writes `run.json` and, unless `file: false`, files one evaluation: FAILED\n * with the reason when the agent raised, a world never came up, or the task\n * could not be graded; a failure that stops filing is `fileError`. Sessions\n * close unless `keepUp: true`. SIGINT or SIGTERM, from the open on, closes\n * them first (a signal during the open waits for the platform's answer) and\n * exits 128 + the signal's number. A world whose tools the platform could not\n * read throws `WorldToolsUnread` before the agent runs, and nothing is filed. */\nexport async function runTask(\n ref: string | WorldTaskIdRef | WorldTaskSpec,\n agent: (run: TaskRun) => TaskRunResult | Promise<TaskRunResult>,\n opts: RunTaskOptions,\n): Promise<RunTaskSummary> {\n const options = opts.options ?? {};\n if (opts.file !== false) GatewayEvalsClient.refuseToken(options);\n const runId = `wtr-${randomBytes(6).toString(\"hex\")}`;\n const opening = new TaskOpening(\n openTask(ref, {\n surfaces: opts.surfaces,\n reuseWarm: opts.reuseWarm,\n browserTier: opts.browserTier,\n worldStates: opts.worldStates,\n options,\n }).then(async (live) => {\n await refuseUnreadTools(live);\n return new LiveTaskRun(runId, live, opts, options);\n }),\n );\n return new RunSignals().during(\n (signal, urgent) => opening.interrupt(signal, urgent),\n () => opening.complete(agent),\n );\n}\n","import { execFileSync } from \"node:child_process\";\n\nexport type Checkout = {\n branch?: string;\n commit?: string;\n repoUrl?: string;\n pr?: { number: number; url: string; title?: string };\n};\n\ntype Env = Record<string, string | undefined>;\n\n/** Labels for the reader, never used to authorize. The PR comes from `GATEWAY_PR_URL`\n * (+ `GATEWAY_PR_TITLE`), else GitHub Actions' `GITHUB_REF=refs/pull/<n>/merge`. */\nexport class CheckoutProvenance {\n constructor(\n private readonly cwd: string,\n private readonly env: Env,\n ) {}\n\n static read(cwd: string = process.cwd(), env: Env = process.env): Checkout {\n return new CheckoutProvenance(cwd, env).checkout();\n }\n\n checkout(): Checkout {\n const commit = this.git(\"rev-parse\", \"HEAD\");\n if (!commit) return this.withPr({});\n const branch =\n this.env.GITHUB_HEAD_REF || this.git(\"rev-parse\", \"--abbrev-ref\", \"HEAD\");\n const remote = this.git(\"config\", \"--get\", \"remote.origin.url\");\n return this.withPr({\n commit,\n ...(branch && branch !== \"HEAD\" ? { branch } : {}),\n ...(remote ? { repoUrl: CheckoutProvenance.withoutCredentials(remote) } : {}),\n });\n }\n\n /** Security: credentials are stripped; scp-style `git@host:org/repo` has none and is kept. */\n static withoutCredentials(url: string): string {\n return url.replace(/^([a-z][a-z0-9+.-]*:\\/\\/)[^@/]+@/i, \"$1\");\n }\n\n private withPr(checkout: Checkout): Checkout {\n const pr = this.pullRequest();\n return pr ? { ...checkout, pr } : checkout;\n }\n\n private pullRequest(): Checkout[\"pr\"] | undefined {\n const url = this.env.GATEWAY_PR_URL;\n const fromUrl = url ? /\\/pull\\/(\\d+)/.exec(url)?.[1] : undefined;\n if (url && fromUrl)\n return {\n number: Number(fromUrl),\n url,\n ...(this.env.GATEWAY_PR_TITLE ? { title: this.env.GATEWAY_PR_TITLE } : {}),\n };\n const number = /^refs\\/pull\\/(\\d+)\\//.exec(this.env.GITHUB_REF ?? \"\")?.[1];\n const server = this.env.GITHUB_SERVER_URL;\n const repo = this.env.GITHUB_REPOSITORY;\n if (!number || !server || !repo) return undefined;\n return { number: Number(number), url: `${server}/${repo}/pull/${number}` };\n }\n\n private git(...args: string[]): string | undefined {\n try {\n const out = execFileSync(\"git\", args, {\n cwd: this.cwd,\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n timeout: 5_000,\n })\n .toString()\n .trim();\n return out || undefined;\n } catch {\n return undefined;\n }\n }\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\nimport type { BrowserTier, WorldSurfaceKind } from \"./browser\";\nimport { CheckoutProvenance, type Checkout } from \"./checkoutProvenance\";\nimport { GatewayEvalsClient } from \"./evals\";\nimport { RunSignals, type RunSignal } from \"./runSignals\";\nimport type { ActingUser } from \"./editSessions\";\nimport {\n runTask,\n taskRunFailure,\n type RunTaskSummary,\n type TaskRun,\n type TaskRunResult,\n} from \"./taskRun\";\n\nconst SET_RUNS = \"/api/public/set-runs\";\n\nexport type SetRunDoc = {\n id: string;\n status: \"running\" | \"completed\" | \"failed\";\n model: string | null;\n source: string | null;\n taskSetDatasetId: string | null;\n actor: { kind: string; id: string; actingUser: ActingUser | null } | null;\n git: Checkout | null;\n progress: { done: number; planned: number };\n score: { mean: number | null; gradedTasks: number; ungradedTasks: number };\n tasks: Array<{\n worldTaskId: string;\n datasetItemId: string;\n name: string;\n evaluationId: string | null;\n sampleId: string | null;\n status: \"pending\" | \"completed\" | \"failed\";\n reward: number | null;\n /** Why a failed task failed: its filing's error, or the reason this run\n * gave when it closed for a task that filed nothing. */\n error: string | null;\n checks: Array<{\n key: string;\n outcome: \"passed\" | \"failed\" | \"ungraded\";\n value: number | null;\n }>;\n }>;\n};\n\nexport type RunSetOptions = {\n model: string;\n /** Default `\"sdk\"`; the CLI passes `\"cli\"`. */\n source?: \"cli\" | \"sdk\";\n /** Default: read from the working directory; `null` records none. */\n git?: Checkout | null;\n surfaces?: WorldSurfaceKind[];\n browserTier?: BrowserTier;\n outDir?: string;\n trace?: boolean;\n onTask?: (summary: RunTaskSummary) => void;\n options?: WorldsClientOptions;\n};\n\n/** `failed`: an agent raised, a task could not run or be graded, or the platform stored the run as anything but completed. */\nexport type RunSetResult = {\n setRun: SetRunDoc;\n tasks: RunTaskSummary[];\n failed: boolean;\n closedAsRequested: boolean;\n};\n\n/** A low or missing reward is a result, not a failure; every task runs even after one fails. */\nexport async function runSet(\n datasetId: string,\n agent: (run: TaskRun) => TaskRunResult | Promise<TaskRunResult>,\n opts: RunSetOptions,\n): Promise<RunSetResult> {\n const options = opts.options ?? {};\n GatewayEvalsClient.refuseToken(options);\n const git = opts.git === undefined ? CheckoutProvenance.read() : opts.git;\n const opened = await apiRequest<SetRunDoc>(options, \"POST\", SET_RUNS, {\n datasetId,\n model: opts.model,\n source: opts.source ?? \"sdk\",\n ...(git && Object.keys(git).length ? { git } : {}),\n });\n return new SetRunner(opened, agent, opts, options).run();\n}\n\n/** Why a planned task filed nothing, sent when the run closes; the platform\n * keeps one bounded reason per task. */\ntype TaskFailure = { worldTaskId: string; reason: string };\n\n/** One set run: its tasks in order, then its close. A task that fails never\n * stops the rest. SIGINT or SIGTERM starts no further task: the task in\n * flight closes its own sessions and the set run is closed failed, naming it.\n * Python twin: `gatewaysdk.world_set_runs.SetRunner`. */\nclass SetRunner {\n private readonly tasks: RunTaskSummary[] = [];\n private readonly failures: TaskFailure[] = [];\n private failed = false;\n private current: string | null = null;\n private interrupted: Promise<SetRunDoc> | null = null;\n private readonly signals = new RunSignals();\n\n constructor(\n private readonly opened: SetRunDoc,\n private readonly agent: (run: TaskRun) => TaskRunResult | Promise<TaskRunResult>,\n private readonly opts: RunSetOptions,\n private readonly options: WorldsClientOptions,\n ) {}\n\n async run(): Promise<RunSetResult> {\n await this.signals.during(\n (signal) => this.interrupt(signal).then(() => undefined),\n () => this.runTasks(),\n );\n const signal = this.signals.signal;\n if (signal !== null) return this.result(await this.interrupt(signal), \"failed\");\n const requested = this.failed ? \"failed\" : \"completed\";\n return this.result(await this.close(requested, this.failures), requested);\n }\n\n private interrupt(signal: RunSignal): Promise<SetRunDoc> {\n const stopped = this.current\n ? [{ worldTaskId: this.current, reason: `interrupted by ${signal}` }]\n : [];\n this.interrupted ??= this.close(\"failed\", [...this.failures, ...stopped]);\n return this.interrupted;\n }\n\n private async runTasks(): Promise<void> {\n for (const task of this.opened.tasks) {\n if (this.signals.signal !== null) return;\n this.current = task.worldTaskId;\n await this.runOne(task);\n }\n this.current = null;\n }\n\n private async runOne(task: SetRunDoc[\"tasks\"][number]): Promise<void> {\n try {\n const summary = await runTask(task.worldTaskId, this.agent, {\n model: this.opts.model,\n surfaces: this.opts.surfaces,\n browserTier: this.opts.browserTier,\n outDir: this.opts.outDir,\n trace: this.opts.trace,\n setRunId: this.opened.id,\n options: this.options,\n });\n this.tasks.push(summary);\n this.failed ||= taskRunFailure(summary) !== null;\n if (summary.fileError !== null)\n this.failures.push({ worldTaskId: task.worldTaskId, reason: summary.fileError });\n this.opts.onTask?.(summary);\n } catch (error) {\n this.failed = true;\n const message = error instanceof Error ? error.message : String(error);\n process.stderr.write(`task ${task.name} could not run: ${message}\\n`);\n this.failures.push({\n worldTaskId: task.worldTaskId,\n reason: message || (error instanceof Error ? error.name : \"Error\"),\n });\n }\n }\n\n private close(status: \"failed\" | \"completed\", failures: TaskFailure[] = []): Promise<SetRunDoc> {\n return apiRequest<SetRunDoc>(\n this.options,\n \"POST\",\n `${SET_RUNS}/${encodeURIComponent(this.opened.id)}/close`,\n { status, ...(failures.length ? { failures } : {}) },\n );\n }\n\n private result(setRun: SetRunDoc, requested: \"failed\" | \"completed\"): RunSetResult {\n return {\n setRun,\n tasks: this.tasks,\n failed: this.failed || setRun.status !== \"completed\",\n closedAsRequested: setRun.status === requested,\n };\n }\n}\n","import { WORLD_REQUEST_VIAS, WorldRequestsNotRecorded } from \"./requestLedger\";\nimport type { WorldSession, WorldSessionCall } from \"./session\";\n\n/** One entry of a world's request ledger as a list carries it: what was asked\n * and what came back, without its headers and bodies. */\nexport type WorldRequest = {\n id: string;\n seq: number;\n at: string;\n durationMs: number | null;\n worldSlug: string;\n sessionId: string;\n versionId: string;\n via: (typeof WORLD_REQUEST_VIAS)[number] | null;\n operation: string | null;\n method: string | null;\n path: string | null;\n query: Record<string, unknown>;\n request: { bodyBytes: number | null; truncated: boolean; contentType: string | null };\n response: {\n status: number;\n bodyBytes: number | null;\n truncated: boolean;\n contentType: string | null;\n };\n rows: number | null;\n found: boolean | null;\n};\n\n/** One page of a ledger list, newest first, with what its scope did not record: `shed` requests kept without\n * their headers and bodies, `lost` requests a host counted as never recorded or the platform refused, and\n * `hostsLost` hosts lost before they stored every request, whose unsent requests no count holds; none of them on\n * a page whose filters narrow past its world, session or version. */\nexport type WorldRequestPage = {\n requests: WorldRequest[];\n nextCursor: string | null;\n shed?: number;\n lost?: number;\n hostsLost?: number;\n};\n\nconst UNRECORDED = [\n [\"lost\", \"{n} request\", \"{n} requests\"],\n [\"shed\", \"{n} request's headers and bodies\", \"{n} requests' headers and bodies\"],\n [\"hostsLost\", \"the requests {n} lost host held\", \"the requests {n} lost hosts held\"],\n] as const;\n\n/** The one line every reader shows for a page's `shed`, `lost` and `hostsLost`, none when all are 0; twin of\n * `worldRequestsUnrecorded` in the platform and `unrecorded` in `gatewaysdk/world_requests.py`, all pinned to\n * `conformance/world-request-log.json` `unrecorded`. */\nexport function worldRequestsUnrecorded(counts: {\n shed?: unknown;\n lost?: unknown;\n hostsLost?: unknown;\n}): string | null {\n const parts = UNRECORDED.map(([field, one, many]) => [counted(counts[field]), one, many] as const)\n .filter(([count]) => count > 0)\n .map(([count, one, many]) => (count === 1 ? one : many).replace(\"{n}\", String(count)));\n return parts.length > 0 ? `Not recorded: ${parts.join(\", \")}` : null;\n}\n\nfunction counted(value: unknown): number {\n return typeof value === \"number\" && Number.isSafeInteger(value) && value > 0 ? value : 0;\n}\n\n/**\n * A session's entries in its world's request ledger: every request the world\n * received, through every door (`via`: api, ui, tool, webhook, page), kept for the life of\n * the world. Read page by page without recording anything in the session; the\n * platform's call ledger (`export()`) holds what it brokered — tool calls,\n * seeds, grades. One entry's headers and bodies are `GET\n * worlds/{slug}/requests/{requestId}`.\n */\nexport class WorldRequestLog {\n private constructor(\n readonly requests: WorldRequest[],\n readonly notRecorded: string | null = null,\n readonly unrecorded: string | null = null,\n ) {}\n\n /** Every entry the ledger holds for the session, oldest first, and the line for what it did not record;\n * for a session the World Host did not serve, none, and `notRecorded` says why. */\n static async load(session: WorldSession): Promise<WorldRequestLog> {\n try {\n return await WorldRequestLog.pages(session);\n } catch (error) {\n const refused = WorldRequestsNotRecorded.from(error);\n if (!(refused instanceof WorldRequestsNotRecorded)) throw error;\n return new WorldRequestLog([], refused.message);\n }\n }\n\n private static async pages(session: WorldSession): Promise<WorldRequestLog> {\n const requests: WorldRequest[] = [];\n let cursor: string | undefined;\n for (;;) {\n const page = await session.requests(cursor ? { cursor } : {});\n requests.push(...page.requests);\n if (!page.nextCursor || page.requests.length === 0)\n return new WorldRequestLog(requests.reverse(), null, worldRequestsUnrecorded(page));\n cursor = page.nextCursor;\n }\n }\n\n /** Each entry in the shape of a ledger line, `kind: \"request\"`, so one JSONL\n * file holds both: `args` what was asked, `result` what came back under the\n * entry's `requestId`. */\n asCalls(): WorldSessionCall[] {\n return this.requests.map((r) => ({\n seq: r.seq,\n kind: \"request\",\n tool: r.operation,\n args: {\n method: r.method,\n path: r.path,\n query: r.query,\n via: r.via,\n contentType: r.request.contentType,\n bodyBytes: r.request.bodyBytes,\n truncated: r.request.truncated,\n },\n result: {\n requestId: r.id,\n status: r.response.status,\n rows: r.rows,\n found: r.found,\n durationMs: r.durationMs,\n contentType: r.response.contentType,\n bodyBytes: r.response.bodyBytes,\n truncated: r.response.truncated,\n },\n error: null,\n completedAt: r.at,\n }));\n }\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\n\nexport const WORLD_WEBHOOK_PAGE_MAX = 100;\nconst FORWARD_TIMEOUT_MS = 10_000;\nconst ERROR_CHARS = 500;\n\nexport type WorldWebhookSubscription = {\n key: Record<string, unknown>;\n url: string | null;\n events: string[];\n scope: Record<string, string[]>;\n enabled: boolean;\n /** Deliveries this subscription was sent since the session's feed began. */\n sent: number;\n};\n\nexport type WorldWebhookDelivery = {\n seq: number;\n id: string;\n eventId: string;\n eventType: string;\n subscription: Record<string, unknown>;\n url: string;\n headers: Record<string, string>;\n payload: string;\n at: number;\n};\n\nexport type WorldWebhookPage = {\n declared: boolean;\n subscriptions: WorldWebhookSubscription[];\n truncated: boolean;\n epoch: string;\n reset: boolean;\n deliveries: WorldWebhookDelivery[];\n next: number;\n more: boolean;\n missed: number;\n answered: number;\n};\n\n/** A page as the read key sees it: which event went to which subscription and when. */\nexport type WorldWebhookListing = Omit<WorldWebhookPage, \"deliveries\"> & {\n deliveries: Pick<WorldWebhookDelivery, \"seq\" | \"id\" | \"eventType\" | \"subscription\" | \"at\">[];\n};\n\nexport type WorldWebhookAnswer = {\n id: string;\n status: number;\n durationMs: number;\n error: string | null;\n};\n\nexport type ForwardedDelivery = { delivery: WorldWebhookDelivery; answer: WorldWebhookAnswer };\n\nconst route = (sessionId: string) => `/api/public/world-sessions/${encodeURIComponent(sessionId)}/webhooks`;\n\n/** The webhooks a World Host session's world declares and has sent, without their signed headers. */\nexport async function listWebhooks(\n options: WorldsClientOptions,\n sessionId: string,\n page: { after?: number; limit?: number; epoch?: string; tail?: boolean } = {},\n): Promise<WorldWebhookListing> {\n const query = new URLSearchParams({\n after: String(page.after ?? 0),\n limit: String(page.limit ?? WORLD_WEBHOOK_PAGE_MAX),\n tail: String(page.tail ?? false),\n });\n if (page.epoch) query.set(\"epoch\", page.epoch);\n return apiRequest<WorldWebhookListing>(options, \"GET\", `${route(sessionId)}?${query.toString()}`);\n}\n\n/**\n * The forward lane: polls a session's deliveries (secret key), replays each to `forwardTo` exactly as signed,\n * so a receiver on this machine verifies it as it would the vendor's, and hands each receiver's answer back\n * on the next poll, where the world's request ledger keeps it beside the delivery.\n */\nexport class WorldWebhookForwarder {\n private after = 0;\n private epoch: string | null = null;\n private answers: WorldWebhookAnswer[] = [];\n private readonly send: typeof fetch;\n\n constructor(\n private readonly options: WorldsClientOptions,\n private readonly sessionId: string,\n private readonly forwardTo: string,\n opts: { fetch?: typeof fetch } = {},\n ) {\n this.send = opts.fetch ?? fetch;\n }\n\n get cursor(): number {\n return this.after;\n }\n\n /** Where forwarding begins: the deliveries the session still holds (`replay`), or only those it sends from now. */\n async start(replay: boolean): Promise<WorldWebhookPage | null> {\n if (replay) return null;\n const page = await this.poll([], { tail: true, limit: 1 });\n this.follow(page);\n return page;\n }\n\n /** One poll: the answers held so far sent, the next page forwarded. A poll that fails keeps its answers for the next. */\n async round(): Promise<{ page: WorldWebhookPage; forwarded: ForwardedDelivery[] }> {\n const page = await this.withAnswers((answers) => this.poll(answers));\n const forwarded: ForwardedDelivery[] = [];\n for (const delivery of page.deliveries) {\n const answer = await this.forward(delivery);\n this.answers.push(answer);\n forwarded.push({ delivery, answer });\n }\n this.follow(page);\n return { page, forwarded };\n }\n\n /** Sends the answers still held; the cursor stays, so a delivery this poll returns is forwarded by the next round. */\n async settle(): Promise<number> {\n if (this.answers.length === 0) return 0;\n const page = await this.withAnswers((answers) => this.poll(answers, { limit: 1 }));\n return page.answered;\n }\n\n private follow(page: WorldWebhookPage): void {\n this.after = page.next;\n this.epoch = page.epoch;\n }\n\n private async withAnswers(poll: (answers: WorldWebhookAnswer[]) => Promise<WorldWebhookPage>): Promise<WorldWebhookPage> {\n const answers = this.answers.splice(0, WORLD_WEBHOOK_PAGE_MAX);\n try {\n return await poll(answers);\n } catch (error) {\n this.answers.unshift(...answers);\n throw error;\n }\n }\n\n private poll(\n answers: WorldWebhookAnswer[],\n opts: { tail?: boolean; limit?: number } = {},\n ): Promise<WorldWebhookPage> {\n return apiRequest<WorldWebhookPage>(this.options, \"POST\", route(this.sessionId), {\n after: this.after,\n epoch: this.epoch,\n tail: opts.tail ?? false,\n limit: opts.limit ?? WORLD_WEBHOOK_PAGE_MAX,\n subscriptions: false,\n answers,\n });\n }\n\n private async forward(delivery: WorldWebhookDelivery): Promise<WorldWebhookAnswer> {\n const started = Date.now();\n try {\n const reply = await this.send(this.forwardTo, {\n method: \"POST\",\n headers: delivery.headers,\n body: delivery.payload,\n redirect: \"manual\",\n signal: AbortSignal.timeout(FORWARD_TIMEOUT_MS),\n });\n await reply.arrayBuffer().catch(() => undefined);\n if (reply.status < 100 || reply.status > 599) throw new Error(\"the receiver answered an invalid HTTP status\");\n return { id: delivery.id, status: reply.status, durationMs: Date.now() - started, error: null };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return { id: delivery.id, status: 0, durationMs: Date.now() - started, error: message.slice(0, ERROR_CHARS) };\n }\n }\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\n/** What `localTreeState(dir)` reports: the tracked meta and the edits since its base. */\nexport type TreeState = {\n meta: { slug?: string; baseFiles?: Record<string, string> } | null;\n dirty: string[];\n clean: boolean;\n};\n\nexport class CheckoutRefusedError extends Error {\n constructor(message: string) {\n super(`checkout refused: ${message}`);\n this.name = \"CheckoutRefusedError\";\n }\n}\n\nconst NAMED_EDITS = 3;\n\n/**\n * Where a pull lands, decided before a byte is downloaded (P-20).\n *\n * - No target: `./<slug>`, de-duplicated with `-1`/`-2`; an existing dir is\n * never entered.\n * - Explicit target: absent or empty → used as-is; a clean checkout of the\n * same world → replaced (its base files are cleared first so files the new\n * version dropped do not linger); local edits, another world's checkout or\n * an untracked non-empty dir → refused unless `force`, which discards the\n * checkout's base files *and* its local edits (added files included) so the\n * result is the pulled version, nothing else the archive would see.\n * - A relative target stays under the current directory; one that escapes it\n * (`../x`) is refused — an absolute path is the explicit way elsewhere (P-21).\n *\n * Python twin: `gatewaysdk.benchmark_hub.checkout.CheckoutTarget`.\n */\nexport class CheckoutTarget {\n private constructor(\n readonly dir: string,\n /** Files of the checkout being replaced (its base + its local edits); removed by `clear()`. */\n readonly replaces: string[],\n ) {}\n\n static resolve(\n slug: string,\n target: string | undefined,\n opts: { cwd: string; force: boolean; state: (dir: string) => TreeState },\n ): CheckoutTarget {\n if (target === undefined) return CheckoutTarget.fresh(slug, opts.cwd);\n return CheckoutTarget.explicit(\n CheckoutTarget.confined(target, opts.cwd),\n slug,\n opts,\n );\n }\n\n /** The absolute destination; a relative target may not resolve above `cwd`. */\n private static confined(target: string, cwd: string): string {\n const dir = path.resolve(cwd, target);\n if (path.isAbsolute(target)) return dir;\n const rel = path.relative(cwd, dir);\n if (rel === \"\" || (!rel.startsWith(\"..\") && !path.isAbsolute(rel)))\n return dir;\n throw new CheckoutRefusedError(\n `--target ${target} resolves outside the current directory (${cwd}) — run from that directory, or pass an absolute path`,\n );\n }\n\n private static fresh(slug: string, cwd: string): CheckoutTarget {\n const base = path.join(cwd, slug);\n let dir = base;\n let i = 1;\n while (fs.existsSync(dir)) dir = `${base}-${i++}`;\n return new CheckoutTarget(dir, []);\n }\n\n private static explicit(\n dir: string,\n slug: string,\n opts: { force: boolean; state: (dir: string) => TreeState },\n ): CheckoutTarget {\n if (!fs.existsSync(dir)) return new CheckoutTarget(dir, []);\n if (!fs.statSync(dir).isDirectory())\n throw new CheckoutRefusedError(`${dir} is a file`);\n if (fs.readdirSync(dir).length === 0) return new CheckoutTarget(dir, []);\n const state = opts.state(dir);\n const refusal = CheckoutTarget.refusal(dir, slug, state);\n if (refusal === null || opts.force)\n return new CheckoutTarget(dir, CheckoutTarget.tracked(state));\n throw new CheckoutRefusedError(refusal);\n }\n\n /** Base files plus local edits — everything the archive would see in the old\n * checkout. `.env-metadata.json` is local input: a key that would leave the\n * checkout (`../x`, `/etc/x`) is dropped, never removed. */\n private static tracked(state: TreeState): string[] {\n if (!state.meta?.baseFiles) return [];\n return [\n ...new Set([...Object.keys(state.meta.baseFiles), ...state.dirty]),\n ]\n .filter(CheckoutTarget.confinedRel)\n .sort();\n }\n\n private static confinedRel(rel: string): boolean {\n if (rel === \"\" || path.isAbsolute(rel)) return false;\n return !rel.split(/[\\\\/]/).includes(\"..\");\n }\n\n /** Why `dir` cannot be overwritten, or null when it is a clean checkout of `slug`. */\n private static refusal(\n dir: string,\n slug: string,\n state: TreeState,\n ): string | null {\n if (!state.meta?.baseFiles)\n return `${dir} is not empty and is not a checkout of \"${slug}\" — pick an empty --target, or pass --force to overwrite it`;\n if (state.meta.slug !== undefined && state.meta.slug !== slug)\n return `${dir} tracks \"${state.meta.slug}\", not \"${slug}\" — pick another --target, or pass --force to replace it`;\n if (state.clean) return null;\n const n = state.dirty.length;\n const named = state.dirty.slice(0, NAMED_EDITS).join(\", \");\n const more = n > NAMED_EDITS ? `, +${n - NAMED_EDITS} more` : \"\";\n return `${dir} has ${n} local edit${n === 1 ? \"\" : \"s\"} not pushed (${named}${more}) — push or propose them first, or pass --force to discard them`;\n }\n\n /** Remove the replaced checkout's files (and the dirs they leave empty). */\n clear(): void {\n for (const rel of this.replaces) {\n const abs = path.join(this.dir, rel);\n fs.rmSync(abs, { force: true });\n this.pruneEmptyParents(path.dirname(abs));\n }\n }\n\n private pruneEmptyParents(from: string): void {\n let cur = from;\n while (cur !== this.dir && cur.startsWith(this.dir)) {\n if (fs.existsSync(cur) && fs.readdirSync(cur).length > 0) return;\n fs.rmSync(cur, { recursive: true, force: true });\n cur = path.dirname(cur);\n }\n }\n}\n","import { createHash } from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nexport const WORLD_MANIFEST = \"gateway-env.toml\";\nexport const API_BUNDLE_MANIFEST = \"gateway-api-world.toml\";\nexport const BUNDLE_MANIFEST = \"gateway-bundle.toml\";\nexport const BUNDLED_WORLD_PREFIX = \"server/world/\";\nexport const CONNECTOR_SPEC = \"connector.toml\";\nexport const PYPROJECT = \"pyproject.toml\";\nexport const BENCHMARK_CONFIG = \"benchmark.json\";\nexport const WORLD_SCHEMA_MARKERS = [\"schema/world.json\", \"schema/runtime.json\", \"schema/lock.json\"];\nconst WORLD_ROOT_MARKERS = [CONNECTOR_SPEC, ...WORLD_SCHEMA_MARKERS];\n/** Widen the archive to every ordinary root file: a world's executable contract and a benchmark's config live there. */\nconst BROAD_ROOT_MARKERS = [WORLD_MANIFEST, API_BUNDLE_MANIFEST, BENCHMARK_CONFIG, BUNDLE_MANIFEST];\nconst SKIPPED_DIRS = new Set([\"dist\", \"build\", \"outputs\", \"__pycache__\", \"node_modules\"]);\n\nexport type Exclusion = { path: string; files: number };\n\nexport type EnvKind = \"api\" | \"bundle\" | \"mock-tools\" | \"harbor\" | \"verifiers-v1\" | \"verifiers\";\n\n// `verifiers.v1` first shipped in verifiers 0.2.0: a v1 package pins >=0.2 (or any major >= 1), imports the\n// namespace, or subclasses Taskset beside a v1-style `__all__`.\nconst V1_DEP = /[\"']verifiers\\s*(?:\\[[^\\]]*\\])?\\s*(?:>=|~=|==|>)\\s*(?:0\\.(?:[2-9]\\d*|[1-9]\\d+)|[1-9]\\d*)/;\nconst V1_IMPORT = /^\\s*(?:from\\s+verifiers\\.v1\\s+import\\b|from\\s+verifiers\\s+import\\s+v1\\b|import\\s+verifiers\\.v1\\b)/m;\nconst V1_TASKSET = /class\\s+\\w+\\s*\\(\\s*(?:(?:vf|v1|verifiers(?:\\.v1)?)\\.)?Taskset\\s*[,)]/;\nconst HARBOR_TASK = /^(?:tasks\\/)?([^/]+)\\/task\\.toml$/;\n\nconst skippedDir = (name: string): boolean =>\n name.startsWith(\".\") || SKIPPED_DIRS.has(name) || name.endsWith(\".egg-info\");\n\n/** Python's `sorted()` order for relpaths: code points, not UTF-16 units. */\nexport const byCodePoint = (a: string, b: string): number => Buffer.compare(Buffer.from(a, \"utf-8\"), Buffer.from(b, \"utf-8\"));\n\nexport class WorldDir {\n private pathsMemo: string[] | undefined;\n\n private constructor(\n readonly dir: string,\n readonly worldRoot: \"\" | typeof BUNDLED_WORLD_PREFIX,\n ) {}\n\n static open(dir: string): WorldDir {\n const present = (rel: string) => fs.existsSync(path.join(dir, rel));\n const bundled = present(API_BUNDLE_MANIFEST) && WORLD_ROOT_MARKERS.some((m) => present(BUNDLED_WORLD_PREFIX + m));\n return new WorldDir(dir, bundled ? BUNDLED_WORLD_PREFIX : \"\");\n }\n\n has(rel: string): boolean {\n return fs.existsSync(path.join(this.dir, rel));\n }\n\n text(rel: string): string | null {\n try {\n return fs.readFileSync(path.join(this.dir, rel), \"utf-8\");\n } catch {\n return null;\n }\n }\n\n worldPath(rel: string): string {\n return this.worldRoot + rel;\n }\n\n get archivePaths(): string[] {\n if (this.pathsMemo) return this.pathsMemo;\n const broad = BROAD_ROOT_MARKERS.some((m) => this.has(m));\n const out: string[] = [];\n const walk = (rel: string) => {\n for (const entry of fs.readdirSync(rel ? path.join(this.dir, rel) : this.dir, { withFileTypes: true })) {\n const child = rel ? `${rel}/${entry.name}` : entry.name;\n if (entry.isDirectory()) {\n if (!skippedDir(entry.name)) walk(child);\n } else if (entry.isFile() && !entry.name.startsWith(\".\")) {\n const rootKept =\n broad || [\"README.md\", PYPROJECT, ...BROAD_ROOT_MARKERS].includes(entry.name) || entry.name.endsWith(\".py\");\n if (rel || rootKept) out.push(child);\n }\n }\n };\n walk(\"\");\n return (this.pathsMemo = out.sort(byCodePoint));\n }\n\n get exclusions(): Exclusion[] {\n const kept = new Set(this.archivePaths);\n const out: Exclusion[] = [];\n const filesUnder = (rel: string): string[] =>\n fs.readdirSync(path.join(this.dir, rel), { withFileTypes: true }).flatMap((entry) => {\n const child = `${rel}/${entry.name}`;\n if (entry.isDirectory()) return filesUnder(child);\n return entry.isFile() ? [child] : [];\n });\n for (const entry of fs.readdirSync(this.dir, { withFileTypes: true }).sort((a, b) => byCodePoint(a.name, b.name))) {\n if (entry.name.startsWith(\".\")) continue;\n if (entry.isDirectory()) {\n const all = filesUnder(entry.name);\n const missing = all.filter((rel) => !kept.has(rel));\n if (missing.length === 0) continue;\n const whole = missing.length === all.length;\n out.push(...(whole ? [{ path: `${entry.name}/`, files: missing.length }] : missing.map((p) => ({ path: p, files: 1 }))));\n continue;\n }\n // A file, or a symlink to anything: the archive never follows a link.\n if (!kept.has(entry.name)) out.push({ path: entry.name, files: 1 });\n }\n return out;\n }\n\n /** The Python SDK honours a root `.gitignore` when collecting; this package does not reimplement gitignore. */\n get hasRootGitignore(): boolean {\n return this.has(\".gitignore\");\n }\n\n /** The version's identity, byte-compatible with the Python SDK's `compute_content_hash` and Prime Intellect's hub. */\n get contentHash(): string {\n const hasher = createHash(\"sha256\");\n for (const rel of this.archivePaths) {\n hasher.update(Buffer.from(`file:${rel}`, \"utf-8\"));\n hasher.update(fs.readFileSync(path.join(this.dir, rel)));\n }\n return hasher.digest(\"hex\");\n }\n\n get isApiBundle(): boolean {\n return this.has(API_BUNDLE_MANIFEST);\n }\n\n get isWorldBundle(): boolean {\n return this.has(BUNDLE_MANIFEST);\n }\n\n get hasManifest(): boolean {\n return this.has(this.worldPath(WORLD_MANIFEST));\n }\n\n get hasSchemaMarker(): boolean {\n return WORLD_SCHEMA_MARKERS.some((m) => this.has(this.worldPath(m)));\n }\n\n taskDirs(): string[] {\n const names = new Set<string>();\n for (const rel of this.archivePaths) {\n const m = HARBOR_TASK.exec(rel);\n if (m) names.add(rel.startsWith(\"tasks/\") ? `tasks/${m[1]}` : m[1]!);\n }\n const under = [...names].filter((n) => n.startsWith(\"tasks/\"));\n return (under.length ? under : [...names]).sort();\n }\n\n pythonPackage(): { name: string; init: string } | null {\n if (!this.has(PYPROJECT)) return null;\n for (const base of [\"\", \"src/\"]) {\n const init = this.archivePaths.find((rel) => {\n const m = /^([^/]+)\\/__init__\\.py$/.exec(rel.startsWith(base) ? rel.slice(base.length) : \"\");\n return m !== null && m[1] !== \"tests\";\n });\n if (init) return { name: init.slice(base.length).split(\"/\")[0]!, init };\n }\n return null;\n }\n\n get isVerifiersV1(): boolean {\n for (const rel of this.archivePaths) {\n if (rel !== PYPROJECT && !rel.endsWith(\".py\")) continue;\n const text = this.text(rel);\n if (text === null) continue;\n if (rel === PYPROJECT ? V1_DEP.test(text) : V1_IMPORT.test(text) || (text.includes(\"__all__\") && V1_TASKSET.test(text)))\n return true;\n }\n return false;\n }\n\n get kind(): EnvKind {\n if (this.isApiBundle) return \"api\";\n if (this.isWorldBundle) return \"bundle\";\n if (this.has(WORLD_MANIFEST)) return \"mock-tools\";\n if (this.taskDirs().length) return \"harbor\";\n return this.isVerifiersV1 ? \"verifiers-v1\" : \"verifiers\";\n }\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { gunzipSync } from \"node:zlib\";\n\n/**\n * The sdk-ts reader of a world's gzipped tar bundle — the twin of the\n * platform's `packages/shared/src/server/worlds/tar.ts` walker. A bundle\n * `pull`/`checkout` downloads may have been written by any of the three\n * writers on the platform, so the walk understands every way a name can\n * travel:\n * • the 100-byte ustar `name` field, UTF-8 (this SDK's own writer),\n * • a GNU `L` long-name member naming the member that follows,\n * • a PAX `x` header whose `path=` record overrides the next name — what\n * Python's `tarfile` (the Python SDK's writer) emits for every\n * non-ASCII or >100-byte name, leaving a `?`-replaced ASCII fallback in\n * the ustar field,\n * • the POSIX ustar `prefix` field (bytes 345–500) joined as `prefix/name`.\n * Reading only the ustar field silently corrupts the other three (cold-batch\n * P-05: `ünïcödé ✓.txt` pulled as `?n?c?d? ?.txt`).\n */\n\nexport const TAR_FILE_MODE = 0o644;\nexport const TAR_EXEC_MODE = 0o755;\n\n/** The only mode detail a world keeps: executable or not. */\nexport function archiveMode(mode: number): number {\n return (mode & 0o111) !== 0 ? TAR_EXEC_MODE : TAR_FILE_MODE;\n}\n\nexport type TarMember = {\n name: string;\n bytes: Buffer;\n typeflag: string;\n mode: number;\n};\n\nfunction field(header: Buffer, start: number, end: number): string {\n return header.subarray(start, end).toString(\"utf-8\").replace(/\\0.*$/, \"\");\n}\n\nfunction octalField(header: Buffer, start: number, end: number): number {\n return parseInt(field(header, start, end).trim(), 8);\n}\n\n/** `path=` from a PAX extended-header payload (`LEN key=value\\n` records). */\nfunction paxPath(body: Buffer): string | null {\n let off = 0;\n let found: string | null = null;\n while (off < body.length) {\n const sp = body.indexOf(0x20, off);\n if (sp === -1) break;\n const len = parseInt(body.subarray(off, sp).toString(\"ascii\"), 10);\n if (!Number.isFinite(len) || len <= 0) break;\n const record = body.subarray(sp + 1, off + len);\n const eq = record.indexOf(0x3d);\n const key = eq === -1 ? \"\" : record.subarray(0, eq).toString(\"utf-8\");\n if (key === \"path\")\n found = record\n .subarray(eq + 1)\n .toString(\"utf-8\")\n .replace(/\\n$/, \"\");\n off += len;\n }\n return found;\n}\n\nexport class TarArchive {\n private constructor(private readonly tar: Buffer) {}\n\n static fromGzip(bundle: Buffer): TarArchive {\n return new TarArchive(gunzipSync(bundle));\n }\n\n static fromTar(tar: Buffer): TarArchive {\n return new TarArchive(tar);\n }\n\n /** Every member, names fully resolved; metadata members are consumed. */\n *members(): Generator<TarMember> {\n const tar = this.tar;\n let offset = 0;\n let pendingName: string | null = null;\n while (offset + 512 <= tar.length) {\n const header = tar.subarray(offset, offset + 512);\n offset += 512;\n if (header.every((b) => b === 0)) break;\n const size = octalField(header, 124, 136) || 0;\n const mode = octalField(header, 100, 108) || TAR_FILE_MODE;\n const typeflag = String.fromCharCode(header[156] ?? 0);\n const bytes = tar.subarray(offset, offset + size);\n offset += Math.ceil(size / 512) * 512;\n if (typeflag === \"L\") {\n pendingName = bytes.toString(\"utf-8\").replace(/\\0.*$/, \"\");\n continue;\n }\n if (typeflag === \"x\") {\n pendingName = paxPath(bytes) ?? pendingName;\n continue;\n }\n if (typeflag === \"K\" || typeflag === \"g\") continue;\n const name = pendingName ?? TarArchive.ustarName(header);\n pendingName = null;\n yield { name: name.replace(/^\\.\\//, \"\"), bytes, typeflag, mode };\n }\n }\n\n private static ustarName(header: Buffer): string {\n const name = field(header, 0, 100);\n const magic = header.subarray(257, 262).toString(\"ascii\");\n const prefix = magic === \"ustar\" ? field(header, 345, 500) : \"\";\n return prefix ? `${prefix}/${name}` : name;\n }\n\n /** Regular files only, confined to `dir` (absolute or `..` names are\n * skipped, never written). Returns the number of files written. */\n extractTo(dir: string): number {\n let written = 0;\n for (const member of this.members()) {\n if (member.typeflag !== \"0\" && member.typeflag !== \"\\0\") continue;\n if (!TarArchive.isConfined(member.name)) continue;\n const target = path.join(dir, member.name);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n const mode = archiveMode(member.mode);\n fs.writeFileSync(target, member.bytes, { mode });\n fs.chmodSync(target, mode);\n written++;\n }\n return written;\n }\n\n private static isConfined(name: string): boolean {\n if (name === \"\" || name.startsWith(\"/\")) return false;\n return !name.split(\"/\").includes(\"..\");\n }\n}\n","import { createHash } from \"node:crypto\";\nimport { gzipSync } from \"node:zlib\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\nimport { CheckoutTarget } from \"./checkoutTarget\";\nimport { WorldDir, type Exclusion } from \"./worldDir\";\nimport { TarArchive, TAR_FILE_MODE, archiveMode } from \"./tar\";\n\n/**\n * The working-dir half of the TS CLI: push / pull / checkout / status /\n * branch / tag / propose — a faithful port of the Python client\n * (`gatewaysdk/benchmark_hub/client.py` + `_archive.py`).\n *\n * The content hash is the version's identity and is byte-compatible with\n * Prime Intellect: `WorldDir.contentHash` (./worldDir.ts) computes it here,\n * `WorldTree.contentHash` on the platform and `_archive.compute_content_hash`\n * in the Python SDK; the conformance corpus pins the three to the same bytes.\n *\n * One deliberate refusal, same policy as the web upload path: a bundle with\n * a ROOT `.gitignore` is refused rather than mis-hashed — the Python CLI\n * honors it via `gitignore_parser`, and an imperfect reimplementation here\n * would produce a wrong, Prime-incompatible hash silently.\n */\n\nexport const DEFAULT_BRANCH = \"main\";\nconst META_RELPATH = path.join(\".gateway\", \".env-metadata.json\");\n\n/** The archive-visible files of a working dir, as sorted relpaths\n * (`WorldDir.archivePaths`). Throws on a root .gitignore (see the header). */\nexport function collectArchiveRelPaths(dir: string): string[] {\n const world = WorldDir.open(dir);\n if (world.hasRootGitignore) {\n throw new Error(\n \"This bundle has a root .gitignore, which the Python CLI honors via \" +\n \"gitignore_parser. Reimplementing that imperfectly here would \" +\n \"silently produce a different content hash, so the TS CLI refuses. \" +\n \"Remove the .gitignore (or bake its effect into the tree) and retry.\",\n );\n }\n return world.archivePaths;\n}\n\nexport function computeContentHash(dir: string): string {\n collectArchiveRelPaths(dir);\n return WorldDir.open(dir).contentHash;\n}\n\nfunction octal(value: number, length: number): Buffer {\n return Buffer.from(\n value.toString(8).padStart(length - 1, \"0\") + \"\\0\",\n \"ascii\",\n );\n}\n\n/** The two modes a stored world file can have: the tar (and `pull`) keep\n * only whether a file is executable — `tests/test.sh` in a harbor tree must\n * still run after a round trip. Owner/mtime are cleared for determinism. */\nconst FILE_MODE = TAR_FILE_MODE;\nexport { archiveMode };\n\nfunction tarHeader(name: string, size: number, mode = FILE_MODE): Buffer {\n const header = Buffer.alloc(512);\n header.write(name, 0, 100, \"utf-8\");\n octal(mode, 8).copy(header, 100);\n octal(0, 8).copy(header, 108);\n octal(0, 8).copy(header, 116);\n octal(size, 12).copy(header, 124);\n octal(0, 12).copy(header, 136);\n header.write(\" \", 148, \"ascii\");\n header.write(\"0\", 156, \"ascii\");\n header.write(\"ustar\", 257, \"ascii\");\n header.write(\"00\", 263, \"ascii\");\n let sum = 0;\n for (const byte of header) sum += byte;\n header.write(sum.toString(8).padStart(6, \"0\") + \"\\0 \", 148, \"ascii\");\n return header;\n}\n\nfunction tarMember(name: string, payload: Buffer, mode: number): Buffer[] {\n const parts: Buffer[] = [];\n const nameBytes = Buffer.byteLength(name, \"utf-8\");\n if (nameBytes > 100) {\n // GNU long name: an 'L' member whose body is the real name.\n const body = Buffer.from(name + \"\\0\", \"utf-8\");\n const lHeader = tarHeader(\"././@LongLink\", body.length);\n lHeader.write(\"L\", 156, \"ascii\");\n let sum = 0;\n lHeader.write(\" \", 148, \"ascii\");\n for (const byte of lHeader) sum += byte;\n lHeader.write(sum.toString(8).padStart(6, \"0\") + \"\\0 \", 148, \"ascii\");\n parts.push(lHeader, body);\n const pad = body.length % 512 === 0 ? 0 : 512 - (body.length % 512);\n if (pad) parts.push(Buffer.alloc(pad));\n parts.push(tarHeader(name.slice(0, 100), payload.length, mode));\n } else {\n parts.push(tarHeader(name, payload.length, mode));\n }\n parts.push(payload);\n const pad = payload.length % 512 === 0 ? 0 : 512 - (payload.length % 512);\n if (pad) parts.push(Buffer.alloc(pad));\n return parts;\n}\n\n/** A deterministic .tar.gz of the source files (node's gzip stamps no mtime,\n * matching the Python's mtime=0 gzip). */\nexport function buildSourceTarball(dir: string): Buffer {\n const parts: Buffer[] = [];\n for (const relPath of collectArchiveRelPaths(dir)) {\n const abs = path.join(dir, relPath);\n parts.push(\n ...tarMember(\n relPath,\n fs.readFileSync(abs),\n archiveMode(fs.statSync(abs).mode),\n ),\n );\n }\n parts.push(Buffer.alloc(1024));\n return gzipSync(Buffer.concat(parts), { level: 9 });\n}\n\nexport type LocalMeta = Record<string, unknown> & {\n slug?: string;\n /** Branch the checkout tracks; absent on a tag (detached) checkout. */\n branch?: string;\n /** Tag the checkout was taken from: immutable, so `push` refuses to move it. */\n tag?: string;\n versionId?: string;\n contentHash?: string;\n baseFiles?: Record<string, string>;\n};\n\nexport function readLocalMeta(dir: string): LocalMeta | null {\n try {\n const raw = fs.readFileSync(path.join(dir, META_RELPATH), \"utf-8\");\n const parsed = JSON.parse(raw);\n return parsed && typeof parsed === \"object\" ? (parsed as LocalMeta) : null;\n } catch {\n return null;\n }\n}\n\n/** The slug a push of `dir` lands on: an explicit one, else the slug the dir\n * was pushed to or pulled from (its `.gateway` meta), else the pyproject\n * name, else the directory's name — so a tracked checkout never creates a\n * second world named after its folder. */\nexport function pushSlug(dir: string, explicit?: string): string {\n return resolvePushSlug(dir, { explicit }).slug;\n}\n\nexport type SlugDeclaration = { source: string; slug: string };\n\nexport type PushSlugResolution = {\n slug: string;\n /** Where the slug came from (`--slug`, `.gateway metadata`, `benchmark.json`, `pyproject.toml`, `directory name`). */\n source: string;\n /** The slug the dir's `.gateway/.env-metadata.json` tracks from an earlier push or pull, if any. */\n tracked: string | null;\n /** What the tree itself declares (a caller's benchmark.json, then pyproject.toml), in precedence order. */\n declared: SlugDeclaration[];\n /** A declaration the tracked slug does not match — set only when the tracked slug won without `--slug`. */\n conflict: SlugDeclaration | null;\n};\n\nconst MINTED_SUFFIX = /^-\\d+$/;\n\n/** `pushSlug` with its provenance. `declared` are the caller's own slug sources\n * (e.g. `{ \"benchmark.json\": \"x\" }`), consulted before pyproject. A tracked slug\n * that disagrees with what the tree declares is reported as `conflict` so a\n * front door can refuse: that is how a directory pushed once with `--slug X`\n * silently landed every later push on X while its benchmark.json said Y. The\n * platform's collision suffix (`acme-2` minted for a taken `acme`) is not a\n * conflict; any other difference is (`acme-e2e` for `acme` was the mix-up). */\nexport function resolvePushSlug(\n dir: string,\n opts: { explicit?: string; declared?: Record<string, string | null | undefined> } = {},\n): PushSlugResolution {\n const meta = readLocalMeta(dir);\n const tracked = typeof meta?.slug === \"string\" && meta.slug ? meta.slug : null;\n const declared = Object.entries({ ...(opts.declared ?? {}), \"pyproject.toml\": readPyproject(dir).name })\n .filter((entry): entry is [string, string] => typeof entry[1] === \"string\" && entry[1] !== \"\")\n .map(([source, slug]) => ({ source, slug }));\n const base = { tracked, declared, conflict: null };\n if (opts.explicit) return { ...base, slug: opts.explicit, source: \"--slug\" };\n if (tracked) {\n const minted = (d: SlugDeclaration) => tracked.startsWith(d.slug) && MINTED_SUFFIX.test(tracked.slice(d.slug.length));\n const conflict = declared.find((d) => d.slug !== tracked && !minted(d)) ?? null;\n return { ...base, slug: tracked, source: \".gateway metadata\", conflict };\n }\n const first = declared[0];\n if (first) return { ...base, slug: first.slug, source: first.source };\n return { ...base, slug: path.basename(path.resolve(dir)), source: \"directory name\" };\n}\n\n/** The refusal a front door raises on `PushSlugResolution.conflict`: both slugs, both sources, every way out. */\nexport class PushSlugConflict extends Error {\n constructor(\n public readonly dir: string,\n public readonly tracked: string,\n public readonly declared: SlugDeclaration,\n ) {\n super(\n `${dir} tracks slug \\`${tracked}\\` (${META_RELPATH}, from an earlier push) but its ${declared.source} says \\`${declared.slug}\\`. ` +\n `Nothing was pushed. Pass --slug ${declared.slug} to push there (and retrack the dir), --slug ${tracked} to keep pushing to \\`${tracked}\\`, ` +\n `or delete ${META_RELPATH} to forget the earlier push.`,\n );\n this.name = \"PushSlugConflict\";\n }\n}\n\nexport function writeLocalMeta(dir: string, meta: LocalMeta): void {\n fs.mkdirSync(path.join(dir, \".gateway\"), { recursive: true });\n fs.writeFileSync(path.join(dir, META_RELPATH), JSON.stringify(meta, null, 2));\n}\n\nexport function snapshotTreeHashes(dir: string): Record<string, string> {\n const out: Record<string, string> = {};\n for (const relPath of collectArchiveRelPaths(dir)) {\n out[relPath] = createHash(\"sha256\")\n .update(fs.readFileSync(path.join(dir, relPath)))\n .digest(\"hex\");\n }\n return out;\n}\n\nexport function localTreeState(dir: string): {\n meta: LocalMeta | null;\n dirty: string[];\n clean: boolean;\n} {\n const meta = readLocalMeta(dir);\n const base = meta?.baseFiles;\n if (!base || typeof base !== \"object\") {\n return { meta, dirty: [], clean: false };\n }\n const now = snapshotTreeHashes(dir);\n const dirty = new Set<string>();\n for (const [p, h] of Object.entries(now)) if (base[p] !== h) dirty.add(p);\n for (const p of Object.keys(base)) if (!(p in now)) dirty.add(p);\n return { meta, dirty: [...dirty].sort(), clean: dirty.size === 0 };\n}\n\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 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\nfunction readWorldContractVersion(dir: string): {\n name?: string;\n version?: string;\n} {\n const world = WorldDir.open(dir);\n try {\n const parsed = JSON.parse(\n world.text(world.worldPath(\"schema/world.json\")) ?? \"\",\n ) as {\n \"x-gateway\"?: { package?: { id?: string; version?: string } };\n };\n const pkg = parsed[\"x-gateway\"]?.package;\n if (pkg?.version) return { name: pkg.id, version: pkg.version };\n } catch {\n // Not a schema world: it has no package block to read.\n }\n return {};\n}\n\n/** The rows the platform previews for a pushed DRAFT: the archive set, one\n * entry per file the content hash covers, so hash, tarball, manifest and\n * `pull` agree on what the world is. Finalize replaces them with rows\n * derived from the stored bytes. */\nexport function buildFileManifest(\n dir: string,\n): { path: string; isDirectory: boolean; size: number; sha256: string }[] {\n return collectArchiveRelPaths(dir).map((relPath) => {\n const payload = fs.readFileSync(path.join(dir, relPath));\n return {\n path: relPath,\n isDirectory: false,\n size: payload.length,\n sha256: createHash(\"sha256\").update(payload).digest(\"hex\"),\n };\n });\n}\n\nasync function putObject(\n url: string,\n data: Buffer,\n shaB64: string,\n): Promise<void> {\n const resp = await fetch(url, {\n method: \"PUT\",\n headers: {\n \"Content-Type\": \"application/gzip\",\n \"x-amz-checksum-sha256\": shaB64,\n },\n body: new Uint8Array(data),\n });\n if (!resp.ok) {\n throw new Error(\n `object PUT -> ${resp.status}: ${(await resp.text()).slice(0, 300)}`,\n );\n }\n}\n\nexport class DetachedPushError extends Error {\n constructor(dir: string, tag: string) {\n super(\n `push refused: ${dir} is a checkout of tag \"${tag}\" (tags are immutable). ` +\n `Nothing was pushed. Pass --branch <name> to land these files on a branch, or checkout a branch first.`,\n );\n this.name = \"DetachedPushError\";\n }\n}\n\n/** The branch a push of `dir` moves: an explicit --branch, else the tracked\n * branch, else main — never a tag. */\nexport function pushBranch(dir: string, localMeta: LocalMeta, explicit: string | undefined): string {\n if (explicit) return explicit;\n if (typeof localMeta.tag === \"string\" && localMeta.tag) throw new DetachedPushError(dir, localMeta.tag);\n return (localMeta.branch as string | undefined) ?? DEFAULT_BRANCH;\n}\n\nexport async function push(\n dir: string,\n opts: {\n slug?: string;\n branch?: string;\n force?: boolean;\n message?: string;\n author?: string;\n /** Push on top of this version instead of the local meta's base — what a\n * CI checkout (which has no local meta) passes after resolving the\n * branch tip, so re-validating a PR replaces its own previous push\n * instead of 409ing against it. */\n baseVersionId?: string | null;\n /** Container metadata recorded on resolve — the Python CLI's --name,\n * --description and --tag. */\n name?: string;\n description?: string;\n tags?: string[];\n /** Pre-built OCI image ref for image/agentic envs (recorded on the version). */\n imageRef?: string;\n options?: WorldsClientOptions;\n } = {},\n): Promise<{\n containerId: string;\n slug: string;\n versionId: string;\n contentHash: string;\n branch: string;\n state: string | null;\n alreadyUploaded: boolean;\n /** The edit session the push joined (`gateway worlds edit close <slug>` moves main); null when the platform landed it on main directly. */\n editSessionId: string | null;\n /** Files the archive rules kept (what the hash, manifest and tarball cover). */\n filesKept: number;\n /** What the archive rules left out, so nothing disappears silently. */\n excluded: Exclusion[];\n}> {\n const options = opts.options ?? {};\n if (!fs.statSync(dir).isDirectory())\n throw new Error(`Not a directory: ${dir}`);\n const localMeta = readLocalMeta(dir) ?? {};\n const branch = pushBranch(dir, localMeta, opts.branch);\n const baseVersionId = opts.baseVersionId ?? localMeta.versionId ?? null;\n\n const world = WorldDir.open(dir);\n const fileManifest = buildFileManifest(dir);\n if (fileManifest.length === 0)\n throw new Error(\n `Nothing to push: ${dir} has no files the archive rules keep (a world root marker, README.md, pyproject.toml, *.py, or any file below a subdirectory).`,\n );\n const contentHash = world.contentHash;\n const pyproject = readPyproject(dir);\n const contractVersion = pyproject.version\n ? undefined\n : readWorldContractVersion(dir).version;\n if (contractVersion) pyproject.version = contractVersion;\n // A dir that tracks a world (created, pulled or pushed before) pushes back\n // to THAT world: its recorded slug wins over the package name, so a world\n // created as `acme-f7` is not re-published as pyproject's `acme` — which is\n // how `worlds ci` minted an unsuffixed twin of every suffixed world.\n const slug =\n opts.slug ??\n localMeta.slug ??\n pyproject.name ??\n path.basename(path.resolve(dir));\n\n // Sent twice on purpose: resolve records it on a container it CREATES,\n // finalize refreshes an existing one — only when the push actually lands.\n // An omitted field leaves the container's value alone; an explicit one\n // replaces it, so `\"\"` clears the description and `[]` clears the tags.\n const metadata = {\n ...(opts.name !== undefined ? { name: opts.name } : {}),\n ...(opts.description !== undefined\n ? { description: opts.description }\n : {}),\n ...(opts.tags !== undefined ? { tags: opts.tags } : {}),\n };\n const resolve = await apiRequest<{ containerId: string }>(\n options,\n \"POST\",\n \"/api/public/benchmark-containers/resolve\",\n { slug, ...metadata },\n );\n\n const tarball = buildSourceTarball(dir);\n const bundleSha256 = sha256b64(tarball);\n\n const version = await apiRequest<{\n versionId: string;\n uploadUrl?: string;\n alreadyUploaded?: boolean;\n }>(options, \"POST\", \"/api/public/benchmark-containers/versions\", {\n containerId: resolve.containerId,\n contentHash,\n bundleSha256,\n bundleSizeBytes: tarball.length,\n ...(pyproject.version ? { semanticVersion: pyproject.version } : {}),\n pyprojectMeta: pyproject,\n fileManifest,\n branch,\n baseVersionId,\n ...(opts.force ? { force: true } : {}),\n ...(opts.message ? { changeReason: opts.message } : {}),\n ...(opts.author ? { author: opts.author } : {}),\n ...(opts.imageRef ? { imageRef: opts.imageRef } : {}),\n });\n\n if (version.uploadUrl)\n await putObject(version.uploadUrl, tarball, bundleSha256);\n\n const final = await apiRequest<{ state?: string; branch?: string; editSessionId?: string }>(\n options,\n \"POST\",\n `/api/public/benchmark-containers/versions/${version.versionId}/finalize`,\n {\n branch,\n baseVersionId,\n ...(opts.force ? { force: true } : {}),\n ...metadata,\n },\n );\n\n writeLocalMeta(dir, {\n ...localMeta,\n slug,\n ref: branch,\n branch,\n versionId: version.versionId,\n contentHash,\n semanticVersion: pyproject.version,\n forkedFromVersionId: baseVersionId,\n baseFiles: snapshotTreeHashes(dir),\n });\n return {\n containerId: resolve.containerId,\n slug,\n versionId: version.versionId,\n contentHash,\n branch: final.branch ?? branch,\n state: final.state ?? null,\n alreadyUploaded: Boolean(version.alreadyUploaded),\n editSessionId: final.editSessionId ?? null,\n filesKept: fileManifest.length,\n excluded: world.exclusions,\n };\n}\n\n/** Extract a downloaded bundle into `dir` (paths confined, executable bit\n * kept; every name encoding the platform's writers emit — see ./tar.ts). */\nexport function extractBundle(bundle: Buffer, dir: string): number {\n return TarArchive.fromGzip(bundle).extractTo(dir);\n}\n\n/** What a checkout tracks after a pull: the branch that answered the ref, or\n * the tag it was taken from (detached). Older servers name neither: latest\n * and semver/hash pins land on main; any other ref was a branch. */\nexport function checkoutIdentity(\n ref: string,\n resolved: { branch?: string | null; tag?: string | null },\n): { branch?: string; tag?: string } {\n if (resolved.tag) return { tag: resolved.tag };\n if (resolved.branch) return { branch: resolved.branch };\n const pinned = ref === \"latest\" || /^\\d|^[0-9a-f]{8,}$/.test(ref);\n return { branch: pinned ? DEFAULT_BRANCH : ref };\n}\n\nexport async function pull(\n slugRef: string,\n target?: string,\n options: WorldsClientOptions = {},\n opts: { force?: boolean } = {},\n): Promise<{ slug: string; dir: string; versionId: string; files: number }> {\n const at = slugRef.indexOf(\"@\");\n const slug = at === -1 ? slugRef : slugRef.slice(0, at);\n const asked = at === -1 ? undefined : slugRef.slice(at + 1);\n const ref = asked ?? \"latest\";\n // Decided first: a refused target costs no request and touches no file.\n const landing = CheckoutTarget.resolve(slug, target, {\n cwd: process.cwd(),\n force: opts.force ?? false,\n state: localTreeState,\n });\n\n const details = await apiRequest<{\n versionId: string;\n contentHash: string;\n semanticVersion?: string | null;\n branch?: string | null;\n tag?: string | null;\n downloadUrl?: string;\n bundleSha256?: string;\n }>(options, \"POST\", \"/api/public/benchmark-containers/resolve-version\", {\n slug,\n ...(asked ? { ref: asked } : {}),\n });\n if (!details.downloadUrl) {\n throw new Error(`${slug}@${ref} resolved but has no uploaded bundle`);\n }\n\n const resp = await fetch(details.downloadUrl);\n if (!resp.ok) throw new Error(`bundle download -> ${resp.status}`);\n const bundle = Buffer.from(await resp.arrayBuffer());\n if (details.bundleSha256 && sha256b64(bundle) !== details.bundleSha256) {\n throw new Error(\n `bundle integrity check failed for ${slug}@${ref}: downloaded sha256 != recorded bundleSha256`,\n );\n }\n\n const dir = landing.dir;\n fs.mkdirSync(dir, { recursive: true });\n landing.clear();\n const files = extractBundle(bundle, dir);\n writeLocalMeta(dir, {\n slug,\n ref,\n ...checkoutIdentity(ref, details),\n versionId: details.versionId,\n contentHash: details.contentHash,\n semanticVersion: details.semanticVersion ?? undefined,\n baseFiles: snapshotTreeHashes(dir),\n });\n return { slug, dir, versionId: details.versionId, files };\n}\n\nexport async function propose(\n dir: string,\n opts: {\n title: string;\n reason: string;\n targetBranch?: string;\n options?: WorldsClientOptions;\n },\n): Promise<{ proposalId: string }> {\n const meta = readLocalMeta(dir);\n if (!meta?.slug || !meta.baseFiles) {\n throw new Error(\n \"This dir has no pull/push base — run pull first, then edit, then propose.\",\n );\n }\n const state = localTreeState(dir);\n if (state.clean)\n throw new Error(\"Nothing to propose — the tree matches its base.\");\n const changes = state.dirty.map((relPath) => {\n const abs = path.join(dir, relPath);\n if (!fs.existsSync(abs))\n return { path: relPath, action: \"delete\" as const };\n return {\n path: relPath,\n action: \"write\" as const,\n newContent: fs.readFileSync(abs, \"utf-8\"),\n };\n });\n const res = await apiRequest<{ proposalId: string }>(\n opts.options ?? {},\n \"POST\",\n \"/api/public/benchmark-containers/proposals\",\n {\n slug: meta.slug,\n title: opts.title,\n changeReason: opts.reason,\n baseVersionId: meta.versionId,\n ...(opts.targetBranch ? { targetBranch: opts.targetBranch } : {}),\n changes,\n },\n );\n return res;\n}\n\nexport async function createRef(\n slug: string,\n name: string,\n kind: \"branch\" | \"tag\",\n versionId?: string,\n options: WorldsClientOptions = {},\n): Promise<{ name: string; kind: string; versionId: string }> {\n return apiRequest(options, \"POST\", \"/api/public/benchmark-containers/refs\", {\n slug,\n name,\n kind,\n ...(versionId ? { versionId } : {}),\n });\n}\n","/**\n * PR validation: push the checkout's world source, run it, gate on the graded\n * result — one composed call, because CI should not have to re-derive the\n * choreography from primitives.\n *\n * The differentiating property, stated so it stays true: validation runs the\n * PULL REQUEST'S OWN world source. The push files the checkout as a version on\n * the PR's branch (content-hash dedup makes re-runs cheap), the dispatch pins\n * that version, and the platform resolves the branch back to its open PR — so\n * the run page names the PR and the PR comment names the run. Nothing here\n * validates a standing deployment while pretending to validate the change.\n */\n\nimport {\n apiRequest,\n detectProvenance,\n listRunConfigs,\n waitForRun,\n type RunReport,\n type WorldsClientOptions,\n} from \"./index\";\nimport { DEFAULT_BRANCH, push, pushSlug } from \"./hub\";\n\nexport type ValidatedRun = {\n model: string;\n runId: string;\n report: RunReport | null;\n /** Why this run fails the gate, or null when it passes. */\n failure: string | null;\n};\n\nexport type ValidateReport = {\n ok: boolean;\n slug: string;\n branch: string;\n versionId: string;\n contentHash: string;\n runConfig: { id: string; name: string };\n runs: ValidatedRun[];\n /** A PR-comment-ready summary of the whole validation. */\n markdown: string;\n};\n\nfunction fmtScore(score: number | null): string {\n return score === null ? \"no score\" : score.toFixed(3);\n}\n\nfunction buildMarkdown(\n report: Omit<ValidateReport, \"markdown\">,\n minScore: number | null,\n source?: { repoUrl?: string; commit?: string },\n): string {\n const lines: string[] = [];\n lines.push(\n `### World validation ${report.ok ? \"passed\" : \"failed\"} — \\`${report.slug}@${report.branch}\\``,\n );\n lines.push(\"\");\n 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 if (taskRows.length > 0) {\n const fold = taskRows.length > 12;\n lines.push(\"\");\n if (fold) {\n lines.push(\n `<details><summary>Per-scenario rewards (${taskRows.length})</summary>`,\n );\n lines.push(\"\");\n } else {\n lines.push(`**Scenarios (${taskRows.length})**`);\n lines.push(\"\");\n }\n lines.push(\"| Scenario | Model | Reward |\");\n lines.push(\"| --- | --- | ---: |\");\n for (const row of taskRows) {\n lines.push(\n `| ${row.task} | \\`${row.model}\\` | ${row.reward === null ? \"no score\" : row.reward.toFixed(2)} |`,\n );\n }\n if (fold) {\n lines.push(\"\");\n lines.push(\"</details>\");\n }\n }\n return lines.join(\"\\n\");\n}\n\n/**\n * Push `dir` on the current (or given) branch, dispatch the named run config\n * against the pushed version, wait for every run, and gate.\n *\n * The gate: every dispatch accepted, every run terminal COMPLETED, and — when\n * `minScore` is set — every run's score meets it. A run with NO score fails a\n * score gate rather than passing it: null is \"not scored\", never 0 and never\n * fine.\n */\nexport async function validateWorld(\n dir: string,\n opts: {\n slug?: string;\n runConfig: string;\n branch?: string;\n minScore?: number | null;\n timeoutMinutes?: number;\n onProgress?: (line: string) => void;\n options?: WorldsClientOptions;\n },\n): Promise<ValidateReport> {\n const options = opts.options ?? {};\n const progress = opts.onProgress ?? (() => {});\n const minScore = opts.minScore ?? null;\n\n const provenance = detectProvenance();\n const branch = opts.branch ?? provenance.branch;\n if (!branch)\n throw new Error(\n \"No branch to validate on: pass --branch or run inside a git checkout / GitHub Actions.\",\n );\n\n const slug = pushSlug(dir, opts.slug);\n progress(`pushing ${dir} as ${slug}@${branch}…`);\n // CI checkouts carry no local push meta, so a re-validation would 409\n // against the branch tip its own previous run created. Validation's\n // semantics are \"this branch's tip BECOMES the PR's source\": resolve the\n // current tip and push on top of it. A branch that does not exist yet\n // resolves to no base, which is a fresh branch — also correct.\n let tipVersionId: string | null = null;\n try {\n const tip = await apiRequest<{ versionId?: string }>(\n options,\n \"POST\",\n \"/api/public/benchmark-containers/resolve-version\",\n { slug, ...(branch === DEFAULT_BRANCH ? {} : { ref: branch }) },\n );\n tipVersionId = tip.versionId ?? null;\n } catch {\n tipVersionId = null;\n }\n const pushed = await push(dir, {\n slug,\n branch,\n baseVersionId: tipVersionId,\n message: `PR validation push (${provenance.commit?.slice(0, 12) ?? \"local\"})`,\n ...(provenance.actor?.name ? { author: provenance.actor.name } : {}),\n options,\n });\n progress(`pushed version ${pushed.versionId} (${pushed.contentHash.slice(0, 12)})`);\n\n const configs = await listRunConfigs(options);\n const runConfig =\n configs.find((c) => c.id === opts.runConfig) ??\n configs.find((c) => c.name === opts.runConfig);\n if (!runConfig) {\n const known = configs.map((c) => c.name).join(\", \") || \"(none)\";\n throw new Error(\n `Run config \"${opts.runConfig}\" not found in this project. Have: ${known}`,\n );\n }\n\n progress(`dispatching run config \"${runConfig.name}\" (${runConfig.models.join(\", \")})…`);\n const dispatched = await apiRequest<{\n versionLabel: string;\n runs: { model: string; runId: string; ok: boolean; error?: string }[];\n }>(options, \"POST\", \"/api/public/benchmark-containers/run-configs/dispatch\", {\n runConfigId: runConfig.id,\n versionId: pushed.versionId,\n ...provenance,\n });\n\n // The run's platform page. New deployments return it on the run report\n // (`url`); against an older deployment we build the same page from the\n // evaluation id, because a PR comment that cannot link the run defeats\n // the point of the comment.\n const host = (\n options.host ??\n process.env.GATEWAY_HOST ??\n \"https://withgateway.ai\"\n ).replace(/\\/+$/, \"\");\n let projectId: string | null = null;\n try {\n const projects = await apiRequest<{ data?: { id?: string }[] }>(\n options,\n \"GET\",\n \"/api/public/projects\",\n );\n projectId = projects.data?.[0]?.id ?? null;\n } catch {\n projectId = null;\n }\n const fallbackUrl = (report: RunReport): string | null => {\n if (report.url) return report.url;\n const evaluationId = report.evaluations[0]?.id;\n return projectId && evaluationId\n ? `${host}/project/${projectId}/environment/runs/${encodeURIComponent(evaluationId)}`\n : null;\n };\n\n const runs: ValidatedRun[] = [];\n for (const run of dispatched.runs) {\n if (!run.ok) {\n runs.push({\n model: run.model,\n runId: run.runId,\n report: null,\n failure: `dispatch failed: ${run.error ?? \"unknown error\"}`,\n });\n continue;\n }\n progress(`waiting on ${run.model} (run ${run.runId})…`);\n let report: RunReport | null = null;\n let failure: string | null = null;\n try {\n report = await waitForRun(run.runId, {\n timeoutMinutes: opts.timeoutMinutes ?? 45,\n options,\n onTick: (r) =>\n progress(\n `…${run.model}: ${r.status.toLowerCase()} (${r.shardsCompleted ?? 0}/${r.parallelism} shards)`,\n ),\n });\n report = { ...report, url: fallbackUrl(report) };\n if (report.status.toUpperCase() !== \"COMPLETED\") {\n failure = report.status;\n } else if (minScore !== null) {\n if (report.score === null) failure = \"completed without a score\";\n else if (report.score < minScore)\n failure = `score ${fmtScore(report.score)} < ${minScore}`;\n }\n } catch (error) {\n failure = error instanceof Error ? error.message : String(error);\n }\n runs.push({ model: run.model, runId: run.runId, report, failure });\n }\n\n const base = {\n ok: runs.length > 0 && runs.every((r) => r.failure === null),\n slug: pushed.slug,\n branch,\n versionId: pushed.versionId,\n contentHash: pushed.contentHash,\n runConfig: { id: runConfig.id, name: runConfig.name },\n runs,\n };\n return {\n ...base,\n markdown: buildMarkdown(base, minScore, {\n repoUrl: provenance.repoUrl,\n commit: provenance.commit,\n }),\n };\n}\n","import { createHash, randomUUID } from \"node:crypto\";\n\nimport { ApiError, apiRequest, type WorldsClientOptions } from \"./index\";\nimport type { PlatformMethod } from \"./transport\";\n\n/**\n * The CLI sandbox: a server-side workspace opened on a READY version of a\n * world (`/workspace/env` in the console agent's sandbox) — or, with\n * `{ new, from }`, on a world that does not exist yet, seeded from the\n * `schema init` scaffold or an official template and created by its first\n * commit — edited and run there, and committed straight into the version\n * service; the source never lands on the caller's disk. `importData` is the\n * data door beside `commit`: a rows file in the sandbox tree into the platform\n * world's data ledger, read out by the platform (no credential enters the\n * sandbox, nothing passes through this machine). One client under\n * both `gateway worlds sandbox …` and `gateway bench sandbox …`; the\n * Python twin is `gatewaysdk.benchmark_hub.sandbox.WorldSandboxClient`.\n */\n\n/** Mirrors `SandboxSummaryResponse` (web/features/public-api/types/world-sandboxes.ts). */\nexport type SandboxSummary = {\n sandboxId: string;\n slug: string;\n /** null while a new-world sandbox awaits its first commit. */\n containerId: string | null;\n /** The version the next commit is validated against; advances on commit. null before the first commit of a new world. */\n baseVersionId: string | null;\n /** Set on a new-world sandbox until its first commit creates the world. */\n pendingSlug: string | null;\n status: \"open\" | \"closed\";\n lastCommitVersionId: string | null;\n pendingBatchId?: string | null;\n createdAt: string;\n};\n\nexport type SandboxOpened = SandboxSummary & {\n /** null for a new-world sandbox (no base). */\n baseContentHash: string | null;\n branch: string;\n dataSnapshotId: string | null;\n fileCount: number;\n workdir: string;\n /** The `gateway` CLI `exec` finds on PATH (the platform's version, staged runtime digest); null when the image cannot host it — `warnings` says why. */\n cli: { version: string; digest: string } | null;\n warnings: string[];\n};\n\nexport type SandboxExecResult = {\n exitCode: number;\n stdout: string;\n stderr: string;\n timedOut: boolean;\n truncated: boolean;\n durationMs: number;\n /** Why `gateway`/`sqlite3` were not on PATH for this command; empty when the runtime is staged. */\n warnings: string[];\n};\n\n/** A command still running after the request's `waitMs` (202); wait on it with `execId`. */\nexport type SandboxExecRunning = { state: \"running\"; execId: string; warnings: string[] };\n\nexport type SandboxChanges = {\n added: string[];\n modified: string[];\n removed: string[];\n};\n\nexport type SandboxCheckResult = {\n ok: boolean;\n contentHash: string | null;\n noChange: boolean;\n fileCount: number;\n changes: SandboxChanges;\n /** Working-tree paths left out of the version: `.gatewayignore`, default scratch, credential-shaped files, links. */\n ignored: string[];\n /** Why a listed path was held back (credential-shaped, a link), a data migration the commit will run, or a rehash; paths only. */\n warnings: string[];\n error: string | null;\n baseMoved?: { baseVersionId: string; tipVersionId: string } | null;\n pendingBatch?: { batchId: string; kind: string; state: string } | null;\n};\n\nexport type SandboxCommitResult = {\n /** The world the commit landed on. */\n slug: string;\n versionId: string;\n contentHash: string;\n branch: string;\n deduped: boolean;\n noChange: boolean;\n changes: SandboxChanges;\n ignored: string[];\n /** The same warnings `check` gives, so a commit never hides what it left out. */\n warnings: string[];\n /** The API key's edit session the commit joined; `gateway worlds edit close <slug>` moves main. */\n editSessionId?: string;\n rebasedOnto?: string | null;\n batchId?: string;\n};\n\nexport type SandboxCommitPending = {\n slug: string;\n batchId: string;\n state: string;\n migration: { fromSnapshotId: string; adds: string[] };\n changes: SandboxChanges;\n ignored: string[];\n warnings: string[];\n rebasedOnto: string | null;\n hint: string;\n};\n\nexport const isSandboxCommitPending = (\n answer: SandboxCommitResult | SandboxCommitPending,\n): answer is SandboxCommitPending => !(\"versionId\" in answer);\n\n/** Mirrors `PostSandboxImportBody`. */\nexport type SandboxImportInput = {\n /** A .json/.jsonl/.ndjson/.csv/.tsv (optionally .gz) relative to the world root. */\n path: string;\n entity?: string;\n /** One character (a real tab for TSV); defaults by extension. */\n delimiter?: string;\n mode?: \"append\" | \"replace\";\n merge?: \"upsert\" | \"fill\";\n redact?: \"off\" | \"apply\" | \"refuse\";\n atomic?: boolean;\n dryRun?: boolean;\n message?: string;\n};\n\n/** Mirrors `PostSandboxImportResponse` (201). */\nexport type SandboxImportResult = {\n containerId: string;\n slug: string;\n batchId: string | null;\n state: string;\n versionId: string | null;\n baseVersionId: string;\n contentHash: string | null;\n deduped: boolean;\n entityCounts: Record<string, number>;\n kind: string | null;\n dryRun: boolean;\n refusalCount: number;\n rowCount: number;\n chunkCount: number;\n /** `sandbox:<id>/<path>`. */\n source: string;\n warnings?: string[];\n};\n\n/** Mirrors `PostSandboxImportPendingResponse` (202): poll `worlds data batches`. */\nexport type SandboxImportPending = {\n batchId: string;\n state: string;\n rowCount: number;\n chunkCount: number;\n source: string;\n warnings?: string[];\n};\n\nexport const isSandboxImportPending = (\n answer: SandboxImportResult | SandboxImportPending,\n): answer is SandboxImportPending => !(\"versionId\" in answer);\n\n/** Mirrors `PostSandboxOpenBody`: an existing world at a ref, or a new world seeded from a template. */\nexport type SandboxOpenExisting = { slug: string; ref?: string };\nexport type SandboxOpenNew = { new: string; from: string };\nexport type SandboxOpenTarget = SandboxOpenExisting | SandboxOpenNew;\n\n/** `slug` or `slug@ref` → the open body; a bare slug opens the latest READY version. */\nexport function parseSlugRef(slugRef: string): SandboxOpenExisting {\n const at = slugRef.indexOf(\"@\");\n if (at === -1) return { slug: slugRef };\n return { slug: slugRef.slice(0, at), ref: slugRef.slice(at + 1) };\n}\n\nconst sid = encodeURIComponent;\n\nconst SANDBOXES = \"/api/public/benchmark-containers/sandboxes\";\n\n/** How long one sandbox request waits for its answer: under the 300 s Node's fetch waits before it cuts a request, so\n * this budget, not fetch, ends a slow one. The Python twin and both MCP proxies wait the same\n * (`conformance/world-sandbox-limits.json`). */\nexport const SANDBOX_REQUEST_TIMEOUT_MS = 290_000;\n\n/** The most one write request carries (`WORLD_SANDBOX_WRITE_CHUNK_BYTES`); a larger file goes up in parts of this size. */\nexport const SANDBOX_WRITE_CHUNK_BYTES = 4 * 1024 * 1024;\n\n/** The largest file a sandbox write lands (`WORLD_SANDBOX_FILE_MAX_BYTES`). */\nexport const SANDBOX_FILE_MAX_BYTES = 256 * 1024 * 1024;\n\n/** What writing a directory never uploads: a checkout's metadata and the scratch the platform never versions\n * (`conformance/world-ignore-defaults.json`). A name with a trailing slash is a directory at any depth, any\n * other a file name glob. */\nexport const SANDBOX_WRITE_SKIPPED: readonly string[] = [\n \".git/\",\n \".gateway/\",\n \"scratch/\",\n \".scratch/\",\n \"__pycache__/\",\n \"*.pyc\",\n \".pytest_cache/\",\n \".mypy_cache/\",\n \".ruff_cache/\",\n \"node_modules/\",\n \".venv/\",\n \"venv/\",\n \".DS_Store\",\n \"*.swp\",\n];\n\n/** Which directory entries writing a directory leaves out, by `SANDBOX_WRITE_SKIPPED`. */\nexport class WriteTreeFilter {\n private readonly directories = new Set(\n SANDBOX_WRITE_SKIPPED.filter((pattern) => pattern.endsWith(\"/\")).map((pattern) => pattern.slice(0, -1)),\n );\n private readonly files = SANDBOX_WRITE_SKIPPED.filter((pattern) => !pattern.endsWith(\"/\")).map(nameGlob);\n\n skipsDirectory(name: string): boolean {\n return this.directories.has(name);\n }\n\n skipsFile(name: string): boolean {\n return this.files.some((glob) => glob.test(name));\n }\n}\n\nfunction nameGlob(pattern: string): RegExp {\n const literal = (part: string) => part.replace(/[.+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n return new RegExp(`^${pattern.split(\"*\").map(literal).join(\".*\")}$`);\n}\n\ntype WriteAnswer = { path: string; size: number } | { path: string; received: number };\n\n/** How long one exec request waits on its command before the platform answers `running`; a longer command is\n * waited on again by `execId`, so no request outlives the edge in front of the platform. */\nexport const SANDBOX_EXEC_WAIT_MS = 40_000;\n\n/** The longest timeout an exec may ask for (`WORLD_SANDBOX_EXEC_TIMEOUT_MAX_MS`); a longer one is refused, never clamped. */\nexport const SANDBOX_EXEC_TIMEOUT_MAX_S = 600;\n\n/** How long past its timeout a command may go without a result before the client stops waiting on it. */\nexport const SANDBOX_EXEC_REPORT_MARGIN_MS = 35_000;\n\n/** How many times a start the platform deferred (`sandbox_exec_deferred`: nothing ran) is sent. */\nexport const SANDBOX_EXEC_START_ATTEMPTS = 3;\n\n/** Mirrors `PostSandboxCommitBody`: `rebase` replays the sandbox's edits onto the branch head when the base moved. */\nexport type SandboxCommitInput = {\n message: string;\n branch?: string;\n rebase?: boolean;\n};\n\n/** One path a rebase refused, as the 409 body's `conflicts[]` names it. */\nexport type RebaseConflictPath = { path: string; reason: string };\n\n/** A 409 from `commit --rebase`: the paths both sides changed and why each was refused. Null for any other failure. */\nexport function rebaseConflicts(error: unknown): RebaseConflictPath[] | null {\n if (!(error instanceof ApiError) || error.status !== 409) return null;\n let body: unknown;\n try {\n body = JSON.parse(error.text);\n } catch {\n return null;\n }\n const conflicts = (body as { conflicts?: unknown } | null)?.conflicts;\n if (!Array.isArray(conflicts)) return null;\n return conflicts\n .filter(isConflictPath)\n .map(({ path, reason }) => ({ path, reason }));\n}\n\nfunction isConflictPath(value: unknown): value is RebaseConflictPath {\n const entry = value as Partial<RebaseConflictPath> | null;\n return typeof entry?.path === \"string\" && typeof entry.reason === \"string\";\n}\n\n/** A 409 `sandbox_uncommitted` from `close`: the paths a commit would keep. Null for any other failure. */\nexport function uncommittedPaths(error: unknown): string[] | null {\n if (\n !(error instanceof ApiError) ||\n error.status !== 409 ||\n error.code !== \"sandbox_uncommitted\"\n )\n return null;\n let body: unknown;\n try {\n body = JSON.parse(error.text);\n } catch {\n return null;\n }\n const uncommitted = (body as { uncommitted?: unknown } | null)?.uncommitted;\n if (!Array.isArray(uncommitted)) return null;\n return uncommitted.filter((p): p is string => typeof p === \"string\");\n}\n\nconst carried = new WeakMap<object, string[]>();\n\n/**\n * The warnings an exec had collected before it failed (a deferral's, a running answer's) and the failing answer's\n * own, which its message holds only up to the detail's cut: no later call reports them. Those the message already\n * shows whole are left out, so each is printed once.\n */\nexport function carriedWarnings(error: unknown): string[] {\n const kept = typeof error === \"object\" && error !== null ? (carried.get(error) ?? []) : [];\n const shown = error instanceof Error ? error.message : \"\";\n return unique([...kept, ...bodyWarnings(error)]).filter((warning) => !shown.includes(warning));\n}\n\nfunction carrying(error: unknown, warnings: string[]): unknown {\n if (warnings.length > 0 && typeof error === \"object\" && error !== null)\n carried.set(error, unique([...(carried.get(error) ?? []), ...warnings]));\n return error;\n}\n\nfunction unique(warnings: string[]): string[] {\n return [...new Set(warnings)];\n}\n\nfunction bodyWarnings(error: unknown): string[] {\n if (!(error instanceof ApiError)) return [];\n let body: unknown;\n try {\n body = JSON.parse(error.text);\n } catch {\n return [];\n }\n const warnings = (body as { warnings?: unknown } | null)?.warnings;\n if (!Array.isArray(warnings)) return [];\n return warnings.filter((w): w is string => typeof w === \"string\");\n}\n\nfunction deferredWarnings(error: unknown): string[] | null {\n if (!(error instanceof ApiError) || error.status !== 409 || error.code !== \"sandbox_exec_deferred\") return null;\n return bodyWarnings(error);\n}\n\n/** A 400 `rows_refused` from `import`: the summary, every refusal counted, the first records and the full report. */\nexport type RowsRefusal = {\n message: string;\n batchId: string;\n refusalCount: number;\n refusals: Record<string, unknown>[];\n reportUrl: string | null;\n};\n\n/** The refusal a sandbox import answered, or null for any other failure. */\nexport function rowsRefusal(error: unknown): RowsRefusal | null {\n if (!(error instanceof ApiError) || error.status !== 400 || error.code !== \"rows_refused\") return null;\n let body: Record<string, unknown>;\n try {\n body = JSON.parse(error.text) as Record<string, unknown>;\n } catch {\n return null;\n }\n const { message, batchId, refusalCount, refusals, reportUrl } = body;\n if (typeof batchId !== \"string\" || typeof refusalCount !== \"number\" || !Array.isArray(refusals)) return null;\n return {\n message: typeof message === \"string\" ? message : \"\",\n batchId,\n refusalCount,\n refusals: refusals.filter((r): r is Record<string, unknown> => typeof r === \"object\" && r !== null),\n reportUrl: typeof reportUrl === \"string\" ? reportUrl : null,\n };\n}\n\n/** `sandbox list` narrows: status, world, count (newest first). */\nexport type SandboxListFilter = {\n status?: \"open\" | \"closed\";\n slug?: string;\n limit?: number;\n};\n\nfunction listQuery(filter: SandboxListFilter): string {\n const params = new URLSearchParams();\n if (filter.status) params.set(\"status\", filter.status);\n if (filter.slug) params.set(\"slug\", filter.slug);\n if (filter.limit !== undefined) params.set(\"limit\", String(filter.limit));\n const qs = params.toString();\n return qs ? `?${qs}` : \"\";\n}\n\nexport class WorldSandboxClient {\n constructor(private readonly options: WorldsClientOptions = {}) {}\n\n private request<T>(\n method: PlatformMethod,\n path: string,\n body?: unknown,\n ): Promise<T> {\n return apiRequest<T>(this.options, method, path, body, {\n timeoutMs: SANDBOX_REQUEST_TIMEOUT_MS,\n });\n }\n\n /**\n * `{ slug, ref? }` opens a READY version; `{ new, from }` opens a sandbox on\n * a world that does not exist yet (409 `world_exists` if the slug is taken,\n * 400 naming the official templates if `from` is unknown). Its first commit\n * creates the world on `main`.\n */\n open(target: SandboxOpenTarget): Promise<SandboxOpened> {\n return this.request(\"POST\", `${SANDBOXES}`, target);\n }\n\n status(sandboxId: string): Promise<SandboxSummary> {\n return this.request(\"GET\", `${SANDBOXES}/${sid(sandboxId)}`);\n }\n\n /** The project's sandboxes, newest first — how an agent finds one it left open. */\n async list(filter: SandboxListFilter = {}): Promise<SandboxSummary[]> {\n const res = await this.request<{ sandboxes: SandboxSummary[] }>(\n \"GET\",\n `${SANDBOXES}${listQuery(filter)}`,\n );\n return res.sandboxes;\n }\n\n async read(\n sandboxId: string,\n filePath: string,\n ): Promise<{ path: string; size: number; bytes: Buffer }> {\n const res = await this.request<{\n path: string;\n size: number;\n contentBase64: string;\n }>(\n \"GET\",\n `${SANDBOXES}/${sid(sandboxId)}/file?path=${encodeURIComponent(filePath)}`,\n );\n return {\n path: res.path,\n size: res.size,\n bytes: Buffer.from(res.contentBase64, \"base64\"),\n };\n }\n\n /** A file past one chunk goes up in parts under one upload id; the platform lands it whole once the last part's\n * size and SHA-256 check out. */\n async write(sandboxId: string, filePath: string, bytes: Buffer): Promise<{ path: string; size: number }> {\n if (bytes.length <= SANDBOX_WRITE_CHUNK_BYTES)\n return this.putFile(sandboxId, { path: filePath, contentBase64: bytes.toString(\"base64\") }) as Promise<{\n path: string;\n size: number;\n }>;\n const whole = { upload: randomUUID(), size: bytes.length, sha256: createHash(\"sha256\").update(bytes).digest(\"hex\") };\n let answer: WriteAnswer = { path: filePath, received: 0 };\n for (let offset = 0; offset < bytes.length; offset += SANDBOX_WRITE_CHUNK_BYTES) {\n const part = bytes.subarray(offset, offset + SANDBOX_WRITE_CHUNK_BYTES);\n answer = await this.putFile(sandboxId, {\n path: filePath,\n contentBase64: part.toString(\"base64\"),\n ...whole,\n offset,\n last: offset + part.length === bytes.length,\n });\n }\n return answer as { path: string; size: number };\n }\n\n private putFile(sandboxId: string, body: object): Promise<WriteAnswer> {\n return this.request(\"PUT\", `${SANDBOXES}/${sid(sandboxId)}/file`, body);\n }\n\n /** Runs as a job on the platform: a command that outlasts one request is waited on again until its result. */\n async exec(\n sandboxId: string,\n input: { command: string; cwd?: string; timeoutMs?: number },\n ): Promise<SandboxExecResult> {\n const budgetMs = (input.timeoutMs ?? SANDBOX_EXEC_TIMEOUT_MAX_S * 1000) + SANDBOX_EXEC_REPORT_MARGIN_MS;\n let answer = await this.startExec(sandboxId, { ...input, waitMs: SANDBOX_EXEC_WAIT_MS });\n const deadline = Date.now() + budgetMs;\n const warnings = [...(answer.warnings ?? [])];\n try {\n while (\"state\" in answer) {\n if (Date.now() >= deadline)\n throw new Error(\n `exec ${answer.execId} in sandbox ${sandboxId} has not reported back within ${budgetMs / 1000} s, past its timeout: ` +\n \"the sandbox may have restarted. Check the sandbox's status, then run the command again.\",\n );\n answer = await this.execStep(sandboxId, { execId: answer.execId, waitMs: SANDBOX_EXEC_WAIT_MS });\n warnings.push(...(answer.warnings ?? []));\n }\n } catch (error) {\n throw carrying(error, warnings);\n }\n return { ...answer, warnings };\n }\n\n // A deferred start ran nothing (the platform was still getting the sandbox ready), so starting again is safe. What\n // getting ready found rides on the deferral alone (no later call reports it), so it is kept for the answer, or for\n // the error when a later attempt fails.\n private async startExec(sandboxId: string, body: object): Promise<SandboxExecResult | SandboxExecRunning> {\n const kept: string[] = [];\n for (let attempt = 1; ; attempt += 1) {\n try {\n const answer = await this.execStep(sandboxId, body);\n return { ...answer, warnings: unique([...kept, ...(answer.warnings ?? [])]) };\n } catch (error) {\n const warnings = deferredWarnings(error);\n if (warnings === null || attempt === SANDBOX_EXEC_START_ATTEMPTS) throw carrying(error, kept);\n kept.push(...warnings);\n }\n }\n }\n\n private execStep(sandboxId: string, body: object): Promise<SandboxExecResult | SandboxExecRunning> {\n return this.request(\"POST\", `${SANDBOXES}/${sid(sandboxId)}/exec`, body);\n }\n\n check(sandboxId: string): Promise<SandboxCheckResult> {\n return this.request(\"POST\", `${SANDBOXES}/${sid(sandboxId)}/check`, {});\n }\n\n /** With `rebase`, a moved base is replayed onto; a 409 then names the conflicting paths (`rebaseConflicts`). */\n commit(\n sandboxId: string,\n input: SandboxCommitInput,\n ): Promise<SandboxCommitResult | SandboxCommitPending> {\n const { rebase, ...rest } = input;\n return this.request(\n \"POST\",\n `${SANDBOXES}/${sid(sandboxId)}/commit`,\n rebase ? { ...rest, rebase: true } : rest,\n );\n }\n\n /**\n * A rows file already in the sandbox tree into the PLATFORM world the\n * sandbox was opened on (201 with the version, 202 with the batch to poll,\n * 400 naming a refused row). Not `commit`: a commit versions the source\n * tree and never carries data.\n */\n importData(\n sandboxId: string,\n input: SandboxImportInput,\n ): Promise<SandboxImportResult | SandboxImportPending> {\n return this.request(\"POST\", `${SANDBOXES}/${sid(sandboxId)}/import`, input);\n }\n\n /** Uncommitted work is a 409 (`uncommittedPaths`) unless `force` discards it. */\n close(\n sandboxId: string,\n opts: { force?: boolean } = {},\n ): Promise<SandboxSummary> {\n return this.request(\n \"DELETE\",\n `${SANDBOXES}/${sid(sandboxId)}`,\n opts.force ? { force: true } : undefined,\n );\n }\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\nimport type { RedactPolicy, Redaction } from \"./redaction\";\nimport { parseSlugRef } from \"./sandbox\";\n\nexport type WorldField = {\n name: string;\n type: string | null;\n required: boolean;\n /** How the store holds it; null means in the clear (queryable by plaintext as given). */\n redaction: Redaction | null;\n /** The values the schema allows; absent when it lists none. */\n enum?: unknown[];\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 WorldBundleMember = {\n alias: string;\n pin: string;\n slug: string | null;\n versionId: string;\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 members?: WorldBundleMember[];\n entities: WorldEntity[];\n redact: RedactPolicy | null;\n};\n\n/** The world at `slug@ref`, described — `ref` is the one grammar shared with\n * pull/checkout/sandbox (`latest` | branch | tag | semver | version id | hash\n * prefix); a bare slug describes the head of `main`. An unknown ref is the\n * route's 404, never the head. */\nexport async function describeWorld(\n slugRef: string,\n options: WorldsClientOptions = {},\n): Promise<WorldDescription> {\n const { slug, ref } = parseSlugRef(slugRef);\n const query = ref === undefined ? \"\" : `?ref=${encodeURIComponent(ref)}`;\n return apiRequest<WorldDescription>(\n options,\n \"GET\",\n `/api/public/worlds/${encodeURIComponent(slug)}${query}`,\n );\n}\n","/**\n * JSON as the Python CLI sees it, so both CLIs write the same bytes.\n *\n * `JSON.parse` + `JSON.stringify` are not enough for parity with\n * `json.loads` + `json.dumps(separators=(\",\", \":\"), ensure_ascii=False)`:\n * JavaScript loses `1.0` vs `1` (Python keeps the float), rounds integers past\n * 2^53, moves integer-like keys to the front of an object, and spells\n * exponents differently (`1e-7` vs `1e-07`). Here a number keeps its source\n * text and its Python type, an object is a Map (insertion order, always), and\n * `dumps` renders exactly what CPython renders.\n */\n\nexport class JsonNumber {\n /** The lexeme as it appeared, e.g. \"1.0\", \"-0\", \"1e21\". */\n constructor(readonly text: string) {}\n /** A float in Python's eyes: a fraction, an exponent, or a non-finite literal. */\n get isFloat(): boolean {\n return /[.eE]/.test(this.text) || /[nN]/.test(this.text);\n }\n get value(): number {\n return Number(this.text);\n }\n}\n\nexport type JsonObject = Map<string, JsonValue>;\nexport type JsonValue = null | boolean | string | JsonNumber | JsonValue[] | JsonObject;\n\nexport class JsonSyntaxError extends Error {}\n\nexport const isObject = (value: JsonValue | undefined): value is JsonObject => value instanceof Map;\n\n// ------------------------------------------------------------------ parsing\n\n/** Parse one JSON text (a line, a row, a document) into the model above.\n * Accepts what `json.loads` accepts, including NaN/Infinity literals. */\nexport function parseJson(text: string): JsonValue {\n const p = new Parser(text);\n p.skipWs();\n const value = p.value();\n p.skipWs();\n if (p.i < text.length) throw new JsonSyntaxError(`Extra data at ${p.i}`);\n return value;\n}\n\nclass Parser {\n i = 0;\n constructor(readonly s: string) {}\n\n skipWs(): void {\n const s = this.s;\n while (this.i < s.length) {\n const c = s.charCodeAt(this.i);\n if (c === 0x20 || c === 0x0a || c === 0x0d || c === 0x09) this.i++;\n else break;\n }\n }\n\n fail(what: string): never {\n throw new JsonSyntaxError(`${what} at ${this.i}`);\n }\n\n value(): JsonValue {\n const s = this.s;\n if (this.i >= s.length) this.fail(\"Expecting value\");\n const c = s[this.i]!;\n if (c === \"{\") return this.object();\n if (c === \"[\") return this.array();\n if (c === '\"') return this.string();\n if (c === \"t\") return this.literal(\"true\", true);\n if (c === \"f\") return this.literal(\"false\", false);\n if (c === \"n\") return this.literal(\"null\", null);\n if (c === \"N\") return this.literal(\"NaN\", new JsonNumber(\"NaN\"));\n if (c === \"I\") return this.literal(\"Infinity\", new JsonNumber(\"Infinity\"));\n return this.number();\n }\n\n literal<T extends JsonValue>(word: string, value: T): T {\n if (!this.s.startsWith(word, this.i)) this.fail(\"Expecting value\");\n this.i += word.length;\n return value;\n }\n\n number(): JsonNumber {\n const s = this.s;\n const start = this.i;\n if (s[this.i] === \"-\") {\n this.i++;\n if (s.startsWith(\"Infinity\", this.i)) {\n this.i += 8;\n return new JsonNumber(\"-Infinity\");\n }\n }\n const intStart = this.i;\n if (s[this.i] === \"0\") this.i++;\n else {\n while (this.i < s.length && isDigit(s.charCodeAt(this.i))) this.i++;\n if (this.i === intStart) this.fail(\"Expecting value\");\n }\n if (s[this.i] === \".\") {\n this.i++;\n const fracStart = this.i;\n while (this.i < s.length && isDigit(s.charCodeAt(this.i))) this.i++;\n if (this.i === fracStart) this.fail(\"Invalid number\");\n }\n if (s[this.i] === \"e\" || s[this.i] === \"E\") {\n this.i++;\n if (s[this.i] === \"+\" || s[this.i] === \"-\") this.i++;\n const expStart = this.i;\n while (this.i < s.length && isDigit(s.charCodeAt(this.i))) this.i++;\n if (this.i === expStart) this.fail(\"Invalid number\");\n }\n return new JsonNumber(s.slice(start, this.i));\n }\n\n string(): string {\n const s = this.s;\n this.i++; // opening quote\n let out = \"\";\n let runStart = this.i;\n for (;;) {\n if (this.i >= s.length) this.fail(\"Unterminated string\");\n const c = s.charCodeAt(this.i);\n if (c === 0x22) {\n out += s.slice(runStart, this.i);\n this.i++;\n return out;\n }\n if (c < 0x20) this.fail(\"Invalid control character\");\n if (c !== 0x5c) {\n this.i++;\n continue;\n }\n out += s.slice(runStart, this.i);\n this.i++;\n const e = s[this.i];\n switch (e) {\n case '\"':\n case \"\\\\\":\n case \"/\":\n out += e;\n break;\n case \"b\":\n out += \"\\b\";\n break;\n case \"f\":\n out += \"\\f\";\n break;\n case \"n\":\n out += \"\\n\";\n break;\n case \"r\":\n out += \"\\r\";\n break;\n case \"t\":\n out += \"\\t\";\n break;\n case \"u\": {\n const hex = s.slice(this.i + 1, this.i + 5);\n if (!/^[0-9a-fA-F]{4}$/.test(hex)) this.fail(\"Invalid \\\\u escape\");\n out += String.fromCharCode(parseInt(hex, 16));\n this.i += 4;\n break;\n }\n default:\n this.fail(\"Invalid escape\");\n }\n this.i++;\n runStart = this.i;\n }\n }\n\n array(): JsonValue[] {\n this.i++;\n const out: JsonValue[] = [];\n this.skipWs();\n if (this.s[this.i] === \"]\") {\n this.i++;\n return out;\n }\n for (;;) {\n this.skipWs();\n out.push(this.value());\n this.skipWs();\n const c = this.s[this.i];\n if (c === \",\") {\n this.i++;\n continue;\n }\n if (c === \"]\") {\n this.i++;\n return out;\n }\n this.fail(\"Expecting ',' delimiter\");\n }\n }\n\n object(): JsonObject {\n this.i++;\n const out: JsonObject = new Map();\n this.skipWs();\n if (this.s[this.i] === \"}\") {\n this.i++;\n return out;\n }\n for (;;) {\n this.skipWs();\n if (this.s[this.i] !== '\"') this.fail(\"Expecting property name enclosed in double quotes\");\n const key = this.string();\n this.skipWs();\n if (this.s[this.i] !== \":\") this.fail(\"Expecting ':' delimiter\");\n this.i++;\n this.skipWs();\n out.set(key, this.value());\n this.skipWs();\n const c = this.s[this.i];\n if (c === \",\") {\n this.i++;\n continue;\n }\n if (c === \"}\") {\n this.i++;\n return out;\n }\n this.fail(\"Expecting ',' delimiter\");\n }\n }\n}\n\nconst isDigit = (c: number): boolean => c >= 0x30 && c <= 0x39;\n\n// ------------------------------------------------------------ serialising\n\n/** `json.dumps(value, separators=(\",\", \":\"), ensure_ascii=False)`, byte for byte. */\nexport function dumps(value: JsonValue): string {\n if (value === null) return \"null\";\n if (value === true) return \"true\";\n if (value === false) return \"false\";\n if (typeof value === \"string\") return JSON.stringify(value);\n if (value instanceof JsonNumber) return numberText(value);\n if (Array.isArray(value)) return \"[\" + value.map(dumps).join(\",\") + \"]\";\n const parts: string[] = [];\n for (const [key, item] of value) parts.push(JSON.stringify(key) + \":\" + dumps(item));\n return \"{\" + parts.join(\",\") + \"}\";\n}\n\n/** How `json.dumps` spells a parsed number: ints verbatim (`-0` becomes `0`),\n * floats through `float.__repr__`, non-finite as NaN/Infinity. */\nexport function numberText(n: JsonNumber): string {\n if (!n.isFloat) return /^-0+$/.test(n.text) ? \"0\" : n.text;\n const value = n.value;\n if (Number.isNaN(value)) return \"NaN\";\n if (value === Infinity) return \"Infinity\";\n if (value === -Infinity) return \"-Infinity\";\n return pyFloatRepr(value);\n}\n\n/** `str(value)` for the values the redaction digest sees: str, int, float, bool. */\nexport function pyStr(value: string | boolean | JsonNumber): string {\n if (typeof value === \"string\") return value;\n if (typeof value === \"boolean\") return value ? \"True\" : \"False\";\n if (!value.isFloat) return numberText(value);\n const v = value.value;\n if (Number.isNaN(v)) return \"nan\";\n if (v === Infinity) return \"inf\";\n if (v === -Infinity) return \"-inf\";\n return pyFloatRepr(v);\n}\n\n/**\n * CPython's `repr(float)`: the shortest digits that round-trip (which\n * JavaScript's `String(x)` also produces), laid out Python's way — a\n * trailing `.0` on integral values, scientific notation only below 1e-4 or\n * from 1e16, and exponents of at least two digits with a sign.\n */\nexport function pyFloatRepr(x: number): string {\n if (x === 0) return Object.is(x, -0) ? \"-0.0\" : \"0.0\";\n const sign = x < 0 ? \"-\" : \"\";\n const js = String(Math.abs(x));\n const [mantissa, exponentPart] = js.split(\"e\");\n let exponent = exponentPart ? Number(exponentPart) : 0;\n const [intPart, fracPart = \"\"] = mantissa!.split(\".\");\n let digits = intPart! + fracPart;\n // decpt: how many digits sit before the decimal point (may be <= 0 or > length).\n let decpt = intPart!.length + exponent;\n const leading = digits.match(/^0*/)![0].length;\n digits = digits.slice(leading);\n decpt -= leading;\n digits = digits.replace(/0+$/, \"\");\n if (digits === \"\") return sign + \"0.0\";\n const sci = decpt - 1;\n if (sci >= -4 && sci < 16) {\n if (decpt <= 0) return sign + \"0.\" + \"0\".repeat(-decpt) + digits;\n if (decpt >= digits.length) return sign + digits + \"0\".repeat(decpt - digits.length) + \".0\";\n return sign + digits.slice(0, decpt) + \".\" + digits.slice(decpt);\n }\n exponent = sci;\n const mag = String(Math.abs(exponent)).padStart(2, \"0\");\n return sign + digits[0] + (digits.length > 1 ? \".\" + digits.slice(1) : \"\") + \"e\" + (exponent < 0 ? \"-\" : \"+\") + mag;\n}\n\n/**\n * Python's `round(x, ndigits)` for the redaction policy: an int is returned\n * unchanged, a float is correctly rounded on its exact binary value with ties\n * to even (`round(0.125, 2) == 0.12`), then re-read as the nearest double.\n */\nexport function pyRound(n: JsonNumber, ndigits: number): JsonNumber {\n if (!n.isFloat) return n;\n const x = n.value;\n if (!Number.isFinite(x)) return n;\n const sign = x < 0 ? -1 : 1;\n const magnitude = Math.abs(x);\n // Every double at or above 2^53 is an integer already.\n if (magnitude >= 9007199254740992) return new JsonNumber(pyFloatRepr(x));\n const { m, k } = exactFraction(magnitude); // magnitude = m / 2^k, m odd (or zero)\n let rounded: number;\n if (k <= ndigits) rounded = magnitude; // exact at this precision\n else if (k !== ndigits + 1) rounded = Number(magnitude.toFixed(ndigits)); // no tie possible: correctly rounded\n else {\n // Exactly k = ndigits + 1 fractional digits, the last one a 5: a tie. Half to even.\n const scaled = m * 5n ** BigInt(k); // magnitude * 10^k, an integer\n let kept = scaled / 10n; // magnitude * 10^ndigits, truncated\n if (kept % 2n === 1n) kept += 1n;\n const text = kept.toString().padStart(ndigits + 1, \"0\");\n rounded = ndigits === 0 ? Number(text) : Number(text.slice(0, -ndigits) + \".\" + text.slice(-ndigits));\n }\n return new JsonNumber(pyFloatRepr(sign * rounded));\n}\n\n/** A finite non-negative double as m / 2^k with m odd (m = 0, k = 0 for zero). */\nfunction exactFraction(x: number): { m: bigint; k: number } {\n if (x === 0) return { m: 0n, k: 0 };\n const view = new DataView(new ArrayBuffer(8));\n view.setFloat64(0, x);\n const bits = view.getBigUint64(0);\n const exponent = Number((bits >> 52n) & 0x7ffn);\n let mantissa = bits & ((1n << 52n) - 1n);\n let e: number;\n if (exponent === 0) e = -1074;\n else {\n mantissa |= 1n << 52n;\n e = exponent - 1075;\n }\n while (mantissa !== 0n && (mantissa & 1n) === 0n) {\n mantissa >>= 1n;\n e += 1;\n }\n if (e >= 0) return { m: mantissa << BigInt(e), k: 0 };\n return { m: mantissa, k: -e };\n}\n","/**\n * Named plaintext transforms for cross-world entity mappings.\n *\n * A mapping between two worlds' fields is rarely a raw equality: SpyCloud\n * keeps `phone` as bare digits where a Torchlight client sends\n * `+1 (559) 779-1433`; one world keys people by `email`, another by\n * `email_username`. A transform normalises the plaintext on BOTH sides of a\n * mapping before `storedForms` salts it under each world's slug, so a\n * cross-world query is answerable from the plaintext alone, with no stored\n * join.\n *\n * The set is closed and named — no expressions, no user code — because any\n * client must reproduce a transform from the manifest by itself. This is the\n * TypeScript twin of the Python runtime's `environment/schema/transforms.py`;\n * the golden vectors in `__tests__/transforms.test.ts` and the Python\n * `tests/environment/test_schema_transforms.py` pin the two to each other,\n * byte for byte.\n *\n * Whitespace, for `trim` and `collapse_ws`, is the ASCII set `\" \\t\\n\\r\\f\\v\"`\n * by definition (Python's `str.split()` and JavaScript's `\\s` disagree at the\n * edges of Unicode; `nfkc` first folds a no-break space into a plain one).\n */\n\nimport { createHash } from \"node:crypto\";\n\nimport { pyFloatRepr } from \"../cli/platform/worldData/json\";\n\nexport type Transform = (value: string) => string;\n\nexport const WHITESPACE = \" \\t\\n\\r\\f\\v\";\nconst WHITESPACE_EDGES = new RegExp(`^[${WHITESPACE}]+|[${WHITESPACE}]+$`, \"g\");\nconst WHITESPACE_RUN = new RegExp(`[${WHITESPACE}]+`, \"g\");\nconst NOT_DIGIT = /[^0-9]/g;\n\nexport const STRIP_PREFIX = \"strip_prefix\";\n\nconst trim = (value: string): string => value.replace(WHITESPACE_EDGES, \"\");\n\nconst emailLocalPart = (value: string): string => {\n const at = value.lastIndexOf(\"@\");\n return at === -1 ? value : value.slice(0, at);\n};\n\nconst emailDomain = (value: string): string => {\n const at = value.lastIndexOf(\"@\");\n return at === -1 ? \"\" : value.slice(at + 1).toLowerCase();\n};\n\nconst stripPrefix =\n (prefix: string): Transform =>\n (value) =>\n value.startsWith(prefix) ? value.slice(prefix.length) : value;\n\nconst hex = (algorithm: \"sha1\" | \"sha256\", value: string): string =>\n createHash(algorithm).update(value, \"utf8\").digest(\"hex\");\n\nconst SIMPLE: Record<string, Transform> = {\n lower: (value) => value.toLowerCase(),\n upper: (value) => value.toUpperCase(),\n trim,\n collapse_ws: (value) => trim(value).replace(WHITESPACE_RUN, \" \"),\n nfkc: (value) => value.normalize(\"NFKC\"),\n digits: (value) => value.replace(NOT_DIGIT, \"\"),\n email_local_part: emailLocalPart,\n email_domain: emailDomain,\n // Vendor-style digests: lowercase hex of the utf-8 bytes, unsalted. This is\n // how SpyCloud accepts a hashed selector (`_digests` in its api_handlers).\n sha1: (value) => hex(\"sha1\", value),\n sha256: (value) => hex(\"sha256\", value),\n};\n\n/** The closed set, as a manifest spells it. `strip_prefix` takes its parameter\n * after a colon; the parameter may hold any character but `,`. */\nexport const TRANSFORMS: readonly string[] = [...Object.keys(SIMPLE), `${STRIP_PREFIX}:<prefix>`];\n\n/** The function a transform name denotes; throws when the name is not in the set. */\nexport function parseTransform(name: string): Transform {\n const simple = Object.prototype.hasOwnProperty.call(SIMPLE, name) ? SIMPLE[name] : undefined;\n if (simple) return simple;\n const colon = name.indexOf(\":\");\n if (colon !== -1) {\n const head = name.slice(0, colon);\n const prefix = name.slice(colon + 1);\n if (head === STRIP_PREFIX && prefix && !prefix.includes(\",\")) return stripPrefix(prefix);\n }\n throw new Error(`Unknown transform '${name}'; choose one of ${TRANSFORMS.join(\", \")}`);\n}\n\n/** `str(value)` as the Python runtime spells a number: an integral number is an\n * int, any other its float repr. */\nconst text = (value: string | number): string => {\n if (typeof value === \"string\") return value;\n return Number.isInteger(value) ? String(value) : pyFloatRepr(value);\n};\n\n/**\n * Compose `chain` left to right over `value`.\n *\n * A number is written as Python's `str()` first, the way `_digest` salts one,\n * so a number keyed on one side and a string on the other transform alike. The\n * whole chain is parsed before any step runs: a bad name at the end refuses\n * the mapping outright rather than after a partial result. An empty chain is\n * the identity.\n */\nexport function applyTransforms(value: string | number, chain: readonly string[]): string {\n const steps = chain.map(parseTransform);\n let out = text(value);\n for (const step of steps) out = step(out);\n return out;\n}\n","/**\n * Stored forms: what a world's store holds for a field given its plaintext.\n *\n * A schema world's `[redact]` table (connector.toml) rewrites named fields\n * before they reach disk — `hash` to a slug-salted sha256, `preserve` to a\n * shape-preserving digest, `round` to fewer decimals, `drop` to nothing. A\n * lookup by plaintext therefore has to compute the same form the store did.\n * This module is the TypeScript twin of the Python runtime's `_digest`,\n * `_shaped`, `redaction_of` and `stored_forms` (environment/schema/connector.py):\n * the rule is `\"sha256:\" + sha256(\"<slug>:<plaintext>\")`, no lowercasing, no\n * trimming, no other salt, and the golden vectors in redaction.test.ts pin the\n * two implementations to each other.\n */\n\nimport { createHash } from \"node:crypto\";\n\nimport { JsonNumber, pyFloatRepr, pyRound } from \"../cli/platform/worldData/json\";\nimport { applyTransforms } from \"./transforms\";\n\n/** The `[redact]` table as `describe` reports it (`connection.redact`, and\n * `redact` on `GET /api/public/worlds/{slug}`). */\nexport type RedactPolicy = {\n /** The digest salt: the connector's slug from connector.toml. It can differ\n * from the platform world slug (`spycloud` vs `spycloud-world`); `storedForms`\n * prefers it and falls back to the world slug only when it is absent. */\n slug?: string;\n hash: string[];\n drop: string[];\n preserve: string[];\n round: Record<string, number>;\n};\n\n/** The policy one field is stored under; null when it is stored in the clear. */\nexport type Redaction = \"hash\" | \"drop\" | \"preserve\" | `round:${number}`;\n\n/**\n * A value as the Python runtime would see it. JavaScript has one number\n * type, so an integral number takes Python's `int` path and any other number\n * its `float` path (`100` is `100`, never `100.0`); integers stay exact within\n * the safe range only.\n */\nexport type Plaintext = string | number;\n\nconst isInt = (value: Plaintext): value is number => typeof value === \"number\" && Number.isInteger(value);\n\n/** `str(value)` for an int or str, `repr(value)` for a float — the text the\n * Python runtime salts and shapes. */\nexport function pyText(value: Plaintext): string {\n if (typeof value === \"string\") return value;\n if (Number.isInteger(value)) return String(value);\n if (Number.isNaN(value)) return \"nan\";\n if (!Number.isFinite(value)) return value > 0 ? \"inf\" : \"-inf\";\n return pyFloatRepr(value);\n}\n\n/** The `hash` form: `\"sha256:\" + sha256(\"<slug>:<plaintext>\")` as hex. */\nexport function hashForm(slug: string, plaintext: Plaintext): string {\n return \"sha256:\" + createHash(\"sha256\").update(`${slug}:${pyText(plaintext)}`, \"utf8\").digest(\"hex\");\n}\n\n/**\n * The `preserve` form, the Python `_shaped`: the same length, every ASCII\n * digit still a digit, every ASCII letter still a letter of the same case,\n * everything else (separators, punctuation, non-ASCII) left in place. The\n * bytes come from sha256 of the seed `\"<slug>:<text>\"`, re-keyed as\n * sha256(digest + seed) once the 32 bytes are spent. A number keeps its type:\n * an int keeps its digit count (a leading zero is replaced), a float is re-read.\n */\nexport function preserveForm(slug: string, plaintext: Plaintext): Plaintext {\n const kind = typeof plaintext === \"string\" ? \"str\" : isInt(plaintext) ? \"int\" : \"float\";\n const shaped = shapeText(slug, pyText(plaintext), kind);\n return kind === \"str\" ? shaped : Number(shaped);\n}\n\n/** The shaping itself, on text: `kind` says which of Python's rules apply\n * (letters are re-lettered for a str only; an int keeps its digit count). */\nexport function shapeText(slug: string, text: string, kind: \"str\" | \"int\" | \"float\"): string {\n const seed = Buffer.from(`${slug}:${text}`, \"utf8\");\n let digest = createHash(\"sha256\").update(seed).digest();\n let cursor = 0;\n const out: string[] = [];\n for (const char of text) {\n if (cursor === digest.length) {\n digest = createHash(\"sha256\").update(Buffer.concat([digest, seed])).digest();\n cursor = 0;\n }\n const byte = digest[cursor]!;\n cursor += 1;\n if (char >= \"0\" && char <= \"9\") out.push(String(byte % 10));\n else if (kind === \"str\" && char >= \"a\" && char <= \"z\") out.push(String.fromCharCode(97 + (byte % 26)));\n else if (kind === \"str\" && char >= \"A\" && char <= \"Z\") out.push(String.fromCharCode(65 + (byte % 26)));\n else out.push(char);\n }\n // An int keeps its digit count; int() would drop a leading zero.\n if (kind === \"int\" && out.length > 1 && out[0] === \"0\") out[0] = String(1 + (digest[0]! % 9));\n return out.join(\"\");\n}\n\n/** The `round` form: Python's `round(value, decimals)` — an int unchanged, a\n * float correctly rounded with ties to even; a string is not a number and\n * passes through as the runtime leaves it. */\nexport function roundForm(plaintext: Plaintext, decimals: number): Plaintext {\n if (typeof plaintext === \"string\" || isInt(plaintext) || !Number.isFinite(plaintext)) return plaintext;\n return pyRound(new JsonNumber(pyFloatRepr(plaintext)), decimals).value;\n}\n\n/**\n * The policy a field of this name falls under, ranked as the runtime applies\n * them (drop, hash, preserve, round). Read without a path: a bare name in the\n * table counts, and so does a dotted path whose last segment is the field.\n */\nexport function redactionOf(redact: RedactPolicy | null | undefined, field: string): Redaction | null {\n if (!redact) return null;\n const named = (names: string[] | undefined) =>\n (names ?? []).some((name) => name === field || name.slice(name.lastIndexOf(\".\") + 1) === field);\n if (named(redact.drop)) return \"drop\";\n if (named(redact.hash)) return \"hash\";\n if (named(redact.preserve)) return \"preserve\";\n const decimals = redact.round?.[field];\n if (typeof decimals === \"number\") return `round:${decimals}`;\n return null;\n}\n\n/**\n * Every value the store may hold for `field` given this plaintext:\n *\n * clear field -> [plaintext]\n * hash -> [\"sha256:<hex>\"]\n * preserve -> [the shape-preserving digest]\n * round -> [round(plaintext, decimals)] for a number, [plaintext] otherwise\n * drop -> [] (the field is not on disk: a documented miss, not an error)\n *\n * `world` is what `describeWorld` / the bridge's `describe` return: the slug\n * is the salt, `redact` the table.\n *\n * `transform` — a cross-world mapping's chain (`./transforms`) — runs over the\n * plaintext FIRST, so `hash` and `preserve` salt the normalised text; omitted\n * (or empty) is today's behaviour, byte for byte.\n */\nexport function storedForms(\n world: { slug: string; redact?: RedactPolicy | null },\n field: string,\n plaintext: Plaintext,\n transform?: readonly string[],\n): Plaintext[] {\n if (transform?.length) plaintext = applyTransforms(plaintext, transform);\n const policy = redactionOf(world.redact, field);\n const salt = world.redact?.slug ?? world.slug;\n if (policy === \"drop\") return [];\n if (policy === \"hash\") return [hashForm(salt, plaintext)];\n if (policy === \"preserve\") return [preserveForm(salt, plaintext)];\n if (policy !== null) return [roundForm(plaintext, world.redact!.round[field]!)];\n return [plaintext];\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\nimport type { Plaintext } from \"./redaction\";\n\nexport type WorldQueryWhere = Record<string, Plaintext | Plaintext[]>;\n\nexport type WorldQueryOptions = {\n where?: WorldQueryWhere;\n /** The `where` values are plaintext: resolve each to its stored form before matching. */\n resolve?: boolean;\n limit?: number;\n offset?: number;\n /** Query the linked worlds too; the answer becomes groups. */\n across?: boolean;\n /** With `across`: add the parity report. */\n compare?: boolean;\n};\n\n/** The options that make `queryRows` answer {@link WorldQueryAcrossResult}. */\nexport type WorldQueryAcrossOptions = WorldQueryOptions & { across: true };\n\nexport type WorldQueryResult = {\n slug: string;\n versionId: string;\n kind: string | null;\n entity: string;\n rows: Record<string, unknown>[];\n /** Rows in this page. */\n count: number;\n /** Rows matching in all; null when the store does not count them. */\n total: number | null;\n limit: number;\n offset: number;\n /** With `resolve`: the stored forms each `where` field was matched against\n * (`[]` for a dropped field, which is why such a query matches nothing). */\n resolved?: Record<string, Plaintext[]>;\n entityCounts: Record<string, number>;\n snapshot: WorldQuerySnapshot | null;\n};\n\nexport type WorldQuerySnapshot = {\n snapshotId: string;\n contractHash: string;\n batchDigest: string;\n bytes: number;\n};\n\n/** One world's page inside an across answer: the root (`alias: null`, no\n * `mapping`) or a linked world with the mappings that carried the root's\n * `where` fields into its own entity. */\nexport type WorldQueryGroup = {\n world: { slug: string; alias: string | null; versionId: string };\n entity: string;\n rows: Record<string, unknown>[];\n count: number;\n total: number | null;\n limit: number;\n offset: number;\n resolved?: Record<string, Plaintext[]>;\n mapping?: { field: string; depField: string; transform: string[] }[];\n};\n\nexport type WorldQueryCompareStatus = \"matched\" | \"no match\" | \"unmapped\";\n\n/** Per `where` field, per world: whether the field reached the world and\n * whether any row matched there; `present`/`absent` list the worlds by slug. */\nexport type WorldQueryCompare = {\n present: string[];\n absent: string[];\n perField: {\n field: string;\n worlds: {\n world: string;\n alias: string | null;\n status: WorldQueryCompareStatus;\n /** `<depEntity>.<depField>` and the transform applied (mapped worlds only). */\n depField?: string;\n transform?: string[];\n }[];\n }[];\n};\n\nexport type WorldQueryAcrossResult = {\n slug: string;\n versionId: string;\n kind: string | null;\n entity: string;\n /** The root world first, then one per linked world that was queried. */\n groups: WorldQueryGroup[];\n compare?: WorldQueryCompare;\n entityCounts: Record<string, number>;\n snapshot: WorldQuerySnapshot | null;\n};\n\n/** The query string the route reads; `where` travels as URL-encoded JSON and\n * `ref` (the `@ref` of `slug@ref`) picks the version. */\nexport function queryRowsSearch(entity: string, opts: WorldQueryOptions = {}, ref?: string): string {\n const search = new URLSearchParams();\n if (ref) search.set(\"ref\", ref);\n search.set(\"entity\", entity);\n if (opts.where && Object.keys(opts.where).length) search.set(\"where\", JSON.stringify(opts.where));\n if (opts.limit !== undefined) search.set(\"limit\", String(opts.limit));\n if (opts.offset !== undefined) search.set(\"offset\", String(opts.offset));\n if (opts.resolve) search.set(\"resolve\", \"true\");\n if (opts.across) search.set(\"across\", \"true\");\n if (opts.compare) search.set(\"compare\", \"true\");\n return `?${search.toString()}`;\n}\n\n/** One version of the world, queried: the main tip for a bare slug, or the\n * version `slug@ref` names (branch, tag, semver pin or hash prefix — the\n * `bench pull` grammar; a ref nothing answers to is the platform's 404, never\n * the head). With `across: true` the answer is the groups shape. */\nexport async function queryRows(\n slug: string,\n entity: string,\n opts: WorldQueryAcrossOptions,\n options?: WorldsClientOptions,\n): Promise<WorldQueryAcrossResult>;\nexport async function queryRows(\n slug: string,\n entity: string,\n opts?: WorldQueryOptions,\n options?: WorldsClientOptions,\n): Promise<WorldQueryResult>;\nexport async function queryRows(\n slugRef: string,\n entity: string,\n opts: WorldQueryOptions = {},\n options: WorldsClientOptions = {},\n): Promise<WorldQueryResult | WorldQueryAcrossResult> {\n const [slug, ref] = slugRef.split(\"@\", 2) as [string, string | undefined];\n if (!slug || ref === \"\") throw new Error(`queryRows needs a slug, optionally slug@ref (got ${slugRef})`);\n if (!entity) throw new Error(\"queryRows needs an entity\");\n if (opts.compare && !opts.across) throw new Error(\"queryRows: compare needs across\");\n return apiRequest<WorldQueryResult | WorldQueryAcrossResult>(\n options,\n \"GET\",\n `/api/public/worlds/${encodeURIComponent(slug)}/data${queryRowsSearch(entity, opts, ref)}`,\n );\n}\n\nexport type WorldSqlOptions = {\n limit?: number;\n scenario?: string;\n};\n\nexport type WorldSqlResult = {\n slug: string;\n versionId: string;\n kind: string | null;\n engine: string;\n columns: string[];\n rows: unknown[][];\n count: number;\n limit: number;\n truncated: boolean;\n};\n\nexport async function sqlRows(\n slugRef: string,\n sql: string,\n opts: WorldSqlOptions = {},\n options: WorldsClientOptions = {},\n): Promise<WorldSqlResult> {\n const [slug, ref] = slugRef.split(\"@\", 2) as [string, string | undefined];\n if (!slug || ref === \"\") throw new Error(`sqlRows needs a slug, optionally slug@ref (got ${slugRef})`);\n if (!sql.trim()) throw new Error(\"sqlRows needs one SQL statement\");\n return apiRequest<WorldSqlResult>(options, \"POST\", `/api/public/worlds/${encodeURIComponent(slug)}/data/sql`, {\n sql,\n ...(ref ? { ref } : {}),\n ...(opts.limit !== undefined ? { limit: opts.limit } : {}),\n ...(opts.scenario ? { scenario: opts.scenario } : {}),\n });\n}\n","/**\n * `migrateWorld(slug)` — convert a stored world into a schema world, from\n * `POST /api/public/worlds/{slug}/migrate`; `migrateProjectWorlds()` plans\n * (or migrates) every connector world in the project from\n * `POST /api/public/worlds/migrate`. Dry run by default: the report says\n * what the version is, what the conversion does, or why it cannot; `apply`\n * commits the migrated tree as the next version (\"Migrated to a schema\n * world\"). Targets are the platform's connector worlds; a hand-built world\n * needs `force`. The CLI twin is `gateway worlds migrate`.\n */\n\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\n\nexport type WorldMigrationRefusal = {\n code: string;\n message: string;\n /** Paths the conversion needed and did not find. */\n missing: string[];\n};\n\nexport type WorldMigrationReport = {\n slug: string;\n containerId: string;\n versionId: string;\n /** True when the container was created from a connector template. */\n connectorWorld: boolean;\n /** schema | api-bundle | legacy-tools | harbor | verifiers */\n shape: string;\n target: \"schema\";\n /** True when the world already is a schema world. */\n unchanged: boolean;\n /** The dry-run report, one sentence each. */\n actions: string[];\n /** Files the migrated tree holds; 0 on a refusal. */\n files: number;\n refusal: WorldMigrationRefusal | null;\n /** True when this call committed the migrated tree. */\n applied: boolean;\n version: { id: string; contentHash: string } | null;\n};\n\nexport type MigrateWorldOptions = {\n /** Commit the migrated tree as the next version. Default false: dry run. */\n apply?: boolean;\n /** Migrate a world that was not created from a connector template. */\n force?: boolean;\n};\n\nexport async function migrateWorld(\n slug: string,\n input: MigrateWorldOptions = {},\n options: WorldsClientOptions = {},\n): Promise<WorldMigrationReport> {\n if (slug.includes(\"@\"))\n throw new Error(\n `migrateWorld converts a world's head version: pass the slug without @ref (got ${slug})`,\n );\n return apiRequest<WorldMigrationReport>(\n options,\n \"POST\",\n `/api/public/worlds/${encodeURIComponent(slug)}/migrate`,\n {\n ...(input.apply === undefined ? {} : { apply: input.apply }),\n ...(input.force === undefined ? {} : { force: input.force }),\n },\n );\n}\n\n/** Every connector world in the project, one report each. */\nexport async function migrateProjectWorlds(\n input: { apply?: boolean } = {},\n options: WorldsClientOptions = {},\n): Promise<{ worlds: WorldMigrationReport[]; applied: boolean }> {\n return apiRequest<{ worlds: WorldMigrationReport[]; applied: boolean }>(\n options,\n \"POST\",\n \"/api/public/worlds/migrate\",\n input.apply === undefined ? {} : { apply: input.apply },\n );\n}\n","/**\n * Records into a world's rows — the record contract, an interceptor that\n * writes it, the conversion from TOOL observations, and the door in.\n *\n * A tool's response is not the entity's shape, and nothing here assumes it\n * is. The workflow with real data is: pull the raw tool calls, look at them,\n * then ingest them through the route you declare — {@link ingest} with a\n * `transform` (your own `transform(records) -> {entity: [rows]}`, a function\n * or a script), with a `map` (an `ingest.toml` mapping for shapes that need\n * no code), or with neither, when the world's own `ingest.toml` applies or\n * each record's tool is a connector operation whose result *is* the\n * operation's response body (its `[ingest]` projection in `connector.toml`).\n * Mappings and projections run in the schema runtime (Python, bundled with\n * the CLI or on the platform), never re-implemented here; a transform runs\n * where you are.\n *\n * The record, one JSON object per line:\n *\n * {\"tool\": \"list_users\", \"args\": {\"team\": \"t1\"}, \"result\": {\"users\": [...]},\n * \"at\": \"2026-09-15T10:00:00Z\", \"session\": \"optional\", \"source\": \"optional free text\"}\n *\n * A `gateway worlds session export` line (`{seq, kind, tool, args, result,\n * error, completedAt}`) is accepted as it is. Redaction is optional and OFF\n * by default everywhere here: rows land as the tools returned them unless\n * `redact: \"apply\"` (the world's `[redact]` policy) or `\"refuse\"` is asked for.\n *\n * - {@link captureToolCalls} wraps an agent's tool functions so every real\n * call is recorded — the agent changes nothing.\n * - {@link toolCallsFromObservations} turns a trace's TOOL observations into\n * records (the `--from traces` path of `gateway worlds data ingest`).\n * - {@link ingest} puts records into a world through a transform, a mapping\n * or the operations: a local directory through the bundled runtime, a\n * platform slug through the batch lane. {@link ingestToolCalls} is the same\n * door with neither transform nor mapping of your own.\n */\n\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\n\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\nimport { GATEWAY_KEYS_MISSING, platformEndpoint } from \"./platformEndpoint\";\nimport { PersonalTokenRefused } from \"./personalToken\";\nimport type { PlatformEndpoint } from \"./transport\";\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/** 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\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/**\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/** What a TOOL observation carries, as `GET /api/public/observations` and\n * `GET /api/public/sessions/{id}?includeIO=true` return it. Both routes decode\n * stored JSON text once on the way out (`parseIoAsJson` defaults to true on the\n * v1 route; the session route renders with the same default), so `input` and\n * `output` arrive as the values the tool saw — an object, or a string when the\n * tool really produced text. Nothing here parses them again. */\nexport type ObservationLike = {\n id?: string;\n traceId?: string | null;\n type?: string;\n name?: string | null;\n input?: unknown;\n output?: unknown;\n startTime?: string | Date;\n level?: string;\n statusMessage?: string | null;\n};\n\nexport type ObservationConversion = {\n records: ToolCallRecord[];\n /** TOOL observations whose name is not one of the world's operations, by name. */\n unknownTools: Record<string, number>;\n /** Observations that were not converted, by reason. */\n skipped: Record<string, number>;\n};\n\nconst isoOf = (value: string | Date | undefined): string | undefined =>\n value instanceof Date ? value.toISOString() : typeof value === \"string\" ? value : undefined;\n\n/**\n * TOOL observations → tool-call records: `name` is the tool, `input` the args,\n * `output` the result, `startTime` the time, `trace:<traceId>/<id>` the source.\n * `input`/`output` arrive from the public API already decoded (it parses the\n * stored text once), so they are taken as they are: a string `output` stays a\n * string even when it looks like JSON; an `input` that is not an object leaves\n * `args` empty rather than guessed.\n * Only `type: \"TOOL\"` converts. With `tools` (the world's operation names) an\n * observation for any other tool is counted in `unknownTools`, not converted.\n * An `ERROR`-level observation converts with `error` set, so ingest counts it\n * as a failed call instead of projecting its output.\n */\nexport function toolCallsFromObservations(\n observations: ObservationLike[],\n opts: { tools?: Iterable<string> | null; session?: string; since?: string } = {},\n): ObservationConversion {\n const known = opts.tools ? new Set(opts.tools) : null;\n const sinceMs = opts.since ? Date.parse(opts.since) : NaN;\n const out: ObservationConversion = { records: [], unknownTools: {}, skipped: {} };\n const skip = (reason: string) => {\n out.skipped[reason] = (out.skipped[reason] ?? 0) + 1;\n };\n for (const observation of observations) {\n if (observation.type !== \"TOOL\") {\n skip(`type ${observation.type ?? \"unknown\"}`);\n continue;\n }\n const tool = observation.name;\n if (typeof tool !== \"string\" || !tool) {\n skip(\"no name\");\n continue;\n }\n const at = isoOf(observation.startTime);\n if (!Number.isNaN(sinceMs) && at !== undefined && Date.parse(at) < sinceMs) {\n skip(\"before since\");\n continue;\n }\n if (known && !known.has(tool)) {\n out.unknownTools[tool] = (out.unknownTools[tool] ?? 0) + 1;\n continue;\n }\n const record: ToolCallRecord = { tool, args: isObject(observation.input) ? observation.input : {} };\n if (observation.level === \"ERROR\") record.error = observation.statusMessage || \"ERROR\";\n else record.result = observation.output;\n if (at !== undefined) record.at = at;\n if (opts.session) record.session = opts.session;\n record.source = `trace:${observation.traceId ?? \"?\"}/${observation.id ?? \"?\"}`;\n out.records.push(record);\n }\n return out;\n}\n\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\nasync function runtimeEndpoint(options: IngestOptions): Promise<PlatformEndpoint | null> {\n try {\n return platformEndpoint(options);\n } catch (error) {\n const { localRuntime } = await import(\"../cli/runtime/local\");\n if (error instanceof PersonalTokenRefused && localRuntime()) return null;\n throw error;\n }\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 local = fs.existsSync(world) && fs.statSync(world).isDirectory();\n const creds = local ? await runtimeEndpoint(options) : platformEndpoint(options);\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);\n const { pull } = await import(\"./hub\");\n const slug = world.split(\"@\", 1)[0]!;\n const scratch = fs.mkdtempSync(path.join(os.tmpdir(), \"gateway-ingest-\"));\n try {\n const pulled = await pull(world, path.join(scratch, slug), options);\n // Produced and proven against the pulled contract; the platform's batch\n // lane checks every row again and redacts there, so this pass runs with\n // redaction off and hands the rows on as they were produced.\n let report: IngestReport;\n let projected: Rows;\n if (rows === null) {\n const proven = await ingestLocalToolCalls(pulled.dir, records, { redact: \"off\", dryRun: true, mode, map }, creds);\n report = reportOf(world, proven, redact);\n projected = proven.projected ?? {};\n } else {\n const proven = await checkLocalWorldData(pulled.dir, rows, creds);\n report = transformReport(world, records.length, rows, stderr, { dryRun, redact, changed: false, kind: proven.kind, entityCounts: proven.entity_counts });\n projected = rows;\n }\n report.dryRun = dryRun;\n if (dryRun || report.refusals.length || !Object.keys(projected).length) return report;\n const { pushRows } = await import(\"../cli/platform/worldData/push\");\n const status = await pushRows(creds, slug, projected, { mode, redact, message: options.message });\n report.batch = status;\n report.changed = status.state === \"applied\" || status.state === \"published\";\n if (status.entityCounts) report.entityCounts = status.entityCounts;\n return report;\n } finally {\n fs.rmSync(scratch, { recursive: true, force: true });\n }\n}\n\n/**\n * Tool-call records into a world with neither a transform nor a mapping of\n * your own: the world's `ingest.toml` when it has one, else each record's\n * tool through its operation's `[ingest]` projection (an unknown tool is a\n * refusal naming it and nothing is written). {@link ingest} with the same\n * options.\n */\nexport async function ingestToolCalls(world: string, records: unknown[], options: IngestToolCallsOptions = {}): Promise<IngestToolCallsReport> {\n return ingest(world, records, options);\n}\n\nfunction transformReport(\n world: string,\n records: number,\n rows: Rows,\n stderr: string,\n outcome: { dryRun: boolean; redact: RedactMode; changed: boolean; kind?: string; entityCounts?: Record<string, number> },\n): IngestReport {\n return {\n world,\n via: \"transform\",\n ...(stderr ? { stderr } : {}),\n records,\n ingested: records,\n skipped: {},\n refusals: [],\n rows: Object.fromEntries(Object.entries(rows).map(([entity, listed]) => [entity, listed.length])),\n dryRun: outcome.dryRun,\n redact: outcome.redact,\n changed: outcome.changed,\n ...(outcome.kind ? { kind: outcome.kind } : {}),\n ...(outcome.entityCounts ? { entityCounts: outcome.entityCounts } : {}),\n };\n}\n\nfunction reportOf(\n world: string,\n local: {\n via?: IngestReport[\"via\"];\n sources?: { name: string; kind: string; select: string; entity: string; records: number; items: number; rows: Record<string, number>; unmapped_fields: Record<string, string>; unset_fields: Record<string, string[]> }[];\n unmatched?: Record<string, number>;\n note?: string;\n records: number;\n ingested: number;\n skipped: Record<string, number>;\n refusals: IngestRefusal[];\n rows: Record<string, number>;\n dry_run: boolean;\n changed: boolean;\n kind?: string;\n entity_counts?: Record<string, number>;\n },\n redact: RedactMode,\n): IngestToolCallsReport {\n return {\n world,\n ...(local.via ? { via: local.via } : {}),\n ...(local.sources ? { sources: local.sources.map(({ unmapped_fields, unset_fields, ...rest }) => ({ ...rest, unmappedFields: unmapped_fields, unsetFields: unset_fields })) } : {}),\n ...(local.unmatched ? { unmatched: local.unmatched } : {}),\n ...(local.note ? { note: local.note } : {}),\n records: local.records,\n ingested: local.ingested,\n skipped: local.skipped,\n refusals: local.refusals,\n rows: local.rows,\n dryRun: local.dry_run,\n redact,\n changed: local.changed,\n ...(local.kind ? { kind: local.kind } : {}),\n ...(local.entity_counts ? { entityCounts: local.entity_counts } : {}),\n };\n}\n\n/** The TOOL observations of one session, every trace's, from `GET /api/public/sessions/{id}?includeIO=true`. */\nexport async function sessionToolObservations(sessionId: string, options: WorldsClientOptions = {}): Promise<ObservationLike[]> {\n const session = await apiRequest<{ traces?: { id?: string; observations?: ObservationLike[] }[] }>(\n options,\n \"GET\",\n `/api/public/sessions/${encodeURIComponent(sessionId)}?includeIO=true`,\n );\n const out: ObservationLike[] = [];\n for (const trace of session.traces ?? [])\n for (const observation of trace.observations ?? []) out.push({ traceId: trace.id ?? null, ...observation });\n return out;\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\nimport type { WorldTaskIdRef, WorldTaskSpec } from \"./session\";\n\n/**\n * Edit sessions: the version control unit for a world. Every write this\n * credential makes to a world (push, sandbox commit, data import, MCP, the\n * console editor) joins ONE open session per world per credential and lands\n * on that session's private branch; `close` seals the session into a version\n * on `main`, and a session nobody touches for an hour seals itself. Sessions\n * replace product-level proposals/PRs: `rollback` undoes a sealed session\n * (source + data together) as a new, itself-reversible session.\n *\n * One client under both `gateway worlds edit …` and `gateway bench edit …`;\n * the Python twin is `gatewaysdk.benchmark_hub.edit_sessions.WorldEditClient`.\n */\n\n/** The person behind a credential: named while a member of the organization, otherwise a former member with no id. */\nexport type ActingUser =\n | { status: \"member\"; id: string; name: string | null }\n | { status: \"former\" };\n\n/** Mirrors `WorldEditSessionSchema` (web/features/public-api/types/world-edits.ts). */\nexport type EditSessionSummary = {\n id: string;\n containerId: string;\n /** `apikey:<id>` for CLI/sandbox/MCP, `user:<id>` for the console, `agent:<id>` for the platform agent. */\n actor: string;\n /** The person behind `actor`, for a secret key or a member; null for a public key or when unknown. */\n actingUser: ActingUser | null;\n door: string;\n status: \"open\" | \"sealing\" | \"sealed\" | \"conflict\" | \"expired\" | \"discarded\" | string;\n baseVersionId: string | null;\n tipVersionId: string | null;\n sealedVersionId: string | null;\n editCount: number;\n startedAt: string;\n lastEditAt: string;\n expiresAt: string;\n closedAt: string | null;\n closeReason: string | null;\n conflictPaths: string[] | null;\n rollbackOfId: string | null;\n message: string | null;\n /** Set when `task edit close` sealed this session together with a task's other worlds. */\n sealGroupId: string | null;\n};\n\nexport type EditSessionList = {\n slug: string;\n containerId: string;\n /** This credential's open session, or null. */\n current: EditSessionSummary | null;\n sessions: EditSessionSummary[];\n};\n\n/** What close/discard/rollback return. */\nexport type EditSessionResult = { slug: string; session: EditSessionSummary };\n\nexport type EditSessionListQuery = { status?: string; limit?: number };\nexport type EditSessionCloseInput = { sessionId?: string; force?: boolean; message?: string };\nexport type EditSessionRollbackInput = { sessionId: string; force?: boolean; message?: string };\n\nconst WORLDS = \"/api/public/worlds\";\nexport class WorldEditClient {\n constructor(private readonly options: WorldsClientOptions = {}) {}\n\n /** The credential's current session and the world's newest-first sessions. */\n list(slug: string, query: EditSessionListQuery = {}): Promise<EditSessionList> {\n const qs = new URLSearchParams();\n if (query.status) qs.set(\"status\", query.status);\n if (query.limit !== undefined) qs.set(\"limit\", String(query.limit));\n const suffix = qs.size ? `?${qs.toString()}` : \"\";\n return apiRequest(this.options, \"GET\", `${WORLDS}/${encodeURIComponent(slug)}/edits${suffix}`);\n }\n\n /** Seal a session into a version on main (the credential's current one when `sessionId` is omitted). */\n close(slug: string, input: EditSessionCloseInput = {}): Promise<EditSessionResult> {\n return apiRequest(this.options, \"POST\", `${WORLDS}/${encodeURIComponent(slug)}/edits/close`, input);\n }\n\n /** Drop the session's private branch without making a version. */\n discard(slug: string, input: { sessionId?: string } = {}): Promise<EditSessionResult> {\n return apiRequest(this.options, \"POST\", `${WORLDS}/${encodeURIComponent(slug)}/edits/discard`, input);\n }\n\n /** Undo a sealed session (source and data) as a new sealed session. */\n rollback(slug: string, input: EditSessionRollbackInput): Promise<EditSessionResult> {\n return apiRequest(this.options, \"POST\", `${WORLDS}/${encodeURIComponent(slug)}/edits/rollback`, input);\n }\n}\n\n/** A stored task (`{id, version?}`) or a spec with `worlds`, as `task up` takes it. */\nexport type TaskEditTarget = WorldTaskIdRef | WorldTaskSpec;\n\n/** The task the platform resolved: stored id and version, or the spec's hash. */\nexport type TaskEditTaskRef = {\n taskId: string | null;\n taskVersion: number | null;\n name: string | null;\n hash: string;\n};\n\n/** Mirrors `TaskEditStatusResponseSchema` (web/features/public-api/types/world-task-edits.ts). */\nexport type TaskEditStatus = {\n task: TaskEditTaskRef;\n worlds: Record<\n string,\n {\n slug: string;\n ref: string;\n problem: string | null;\n session: EditSessionSummary | null;\n /** This credential's sessions parked in `conflict` on the world: unsealed too. */\n parked: EditSessionSummary[];\n mainVersionId: string | null;\n sealNow: \"fast-forward\" | \"rebase\" | \"conflict\" | null;\n conflictPaths: string[];\n }\n >;\n /** Aliases whose world holds edits only this credential sees. */\n unsealed: string[];\n hint: string | null;\n};\n\nexport type TaskEditSealed = { slug: string; session: EditSessionSummary };\n\nexport type TaskEditCloseResult = {\n task: TaskEditTaskRef;\n groupId: string | null;\n worlds: Record<string, TaskEditSealed>;\n skipped: Record<string, { slug: string; reason: string }>;\n};\n\nexport type TaskEditRollbackResult = {\n task: TaskEditTaskRef;\n groupId: string;\n rollbackOf: string;\n worlds: Record<string, TaskEditSealed>;\n /** Members whose seal left `main` where it was: nothing to undo there. */\n skipped: Record<string, { slug: string; reason: string }>;\n};\n\nexport type TaskEditCloseInput = { requireAll?: boolean; force?: boolean; message?: string };\nexport type TaskEditRollbackInput = { groupId: string; force?: boolean; message?: string };\n\nconst TASK_EDITS = \"/api/public/world-task-edits\";\n\n/**\n * This credential's edit sessions on every world a task names, together:\n * `close` seals them onto their mains in ONE platform transaction (all or\n * none), `rollback` undoes the seal group as one. Python twin:\n * `gatewaysdk.benchmark_hub.edit_sessions.TaskEditClient`.\n */\nexport class TaskEditClient {\n constructor(private readonly options: WorldsClientOptions = {}) {}\n\n status(task: TaskEditTarget): Promise<TaskEditStatus> {\n return apiRequest(this.options, \"POST\", `${TASK_EDITS}/status`, { task });\n }\n\n close(task: TaskEditTarget, input: TaskEditCloseInput = {}): Promise<TaskEditCloseResult> {\n return apiRequest(this.options, \"POST\", `${TASK_EDITS}/close`, { task, ...input });\n }\n\n rollback(task: TaskEditTarget, input: TaskEditRollbackInput): Promise<TaskEditRollbackResult> {\n return apiRequest(this.options, \"POST\", `${TASK_EDITS}/rollback`, { task, ...input });\n }\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\n\nexport type WorldStateDoc = {\n id: string;\n name: string;\n kind: string;\n description: string | null;\n bindings: Record<string, string>;\n dataSnapshotId: string | null;\n createdBy: string | null;\n updatedBy: string | null;\n createdAt: string;\n updatedAt: string;\n};\n\nexport type WorldStateSnapshot = {\n id: string;\n sha256: string;\n digest: string;\n contractHash: string;\n bytes: number;\n rowCounts: Record<string, number>;\n};\n\nexport type WorldStateOpening = {\n versionId: string;\n source: \"version\" | \"state\" | \"carried\";\n snapshot: WorldStateSnapshot | null;\n bindings: Record<string, string>;\n fingerprint: string;\n};\n\nexport type WorldStateRefusal = { code: string; message: string };\n\nexport type WorldStateList = { slug: string; containerId: string; states: WorldStateDoc[] };\n\nexport type WorldStateAnswer = {\n slug: string;\n state: WorldStateDoc;\n versionId: string | null;\n opens: WorldStateOpening | null;\n refusal: WorldStateRefusal | null;\n};\n\nexport type WorldStateDeleted = { slug: string; state: WorldStateDoc; deleted: true; runCount: number };\n\nexport type WorldStatePull = {\n slug: string;\n state: WorldStateDoc;\n opens: WorldStateOpening;\n download: { url: string; expiresAt: string } | null;\n};\n\nexport type WorldStateCreateInput = {\n name: string;\n description?: string;\n bindings?: Record<string, string>;\n fromSnapshot?: string;\n fromState?: string;\n};\n\nconst WORLDS = \"/api/public/worlds\";\n\nconst refQuery = (ref?: string): string => (ref ? `?${new URLSearchParams({ ref })}` : \"\");\n\nexport class WorldStateClient {\n constructor(private readonly options: WorldsClientOptions = {}) {}\n\n list(slug: string): Promise<WorldStateList> {\n return apiRequest(this.options, \"GET\", `${WORLDS}/${encodeURIComponent(slug)}/states`);\n }\n\n show(slug: string, name: string, ref?: string): Promise<WorldStateAnswer> {\n return apiRequest(this.options, \"GET\", `${WORLDS}/${encodeURIComponent(slug)}/states/${encodeURIComponent(name)}` + refQuery(ref));\n }\n\n create(slug: string, input: WorldStateCreateInput): Promise<WorldStateAnswer> {\n return apiRequest(this.options, \"POST\", `${WORLDS}/${encodeURIComponent(slug)}/states`, input);\n }\n\n delete(slug: string, name: string): Promise<WorldStateDeleted> {\n return apiRequest(this.options, \"DELETE\", `${WORLDS}/${encodeURIComponent(slug)}/states/${encodeURIComponent(name)}`);\n }\n\n pull(slug: string, name: string, ref?: string): Promise<WorldStatePull> {\n return apiRequest(this.options, \"GET\", `${WORLDS}/${encodeURIComponent(slug)}/states/${encodeURIComponent(name)}/pull` + refQuery(ref));\n }\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\n\n/**\n * The hosted one-task dry run: `POST /api/public/environments/{id}/dry-run`\n * and the run-status read that settles it. The runner runs ONE named task of a\n * harbor tree through harbor's `oracle` (the task's own `solution/solve.sh`)\n * with the real image rule (`[environment] docker_image` → pull, never build;\n * else build the Dockerfile). No model, no model key. The run is marked\n * `kind: \"dry-run\"` and never counts as a benchmark result.\n *\n * The caps are the server's: one task, one example, one rollout, the oracle.\n * The body carries the task name and, optionally, a pinned versionId; a body\n * that tries to widen the run (models, task lists, rollouts) is a 400.\n */\n\nexport const DRY_RUN_KIND = \"dry-run\" as const;\nexport const DRY_RUN_AGENT = \"oracle\" as const;\n\nexport type HostedDryRunDispatch = {\n runId: string;\n versionId: string;\n versionLabel: string;\n containerSlug: string;\n task: string;\n kind: typeof DRY_RUN_KIND;\n agent: typeof DRY_RUN_AGENT;\n evidence: false;\n where: \"hosted\";\n};\n\n/** The image decision the runner took — the SAME rule a real run applies. */\nexport type DryRunImageDecision = {\n source: \"prebuilt\" | \"dockerfile\";\n ref: string | null;\n};\n\n/** What the runner reported about the one trial (the Python twin is `benchmark_hub.dry_run.DryRunSettlement`). */\nexport type DryRunSettlement = {\n task: string;\n agent: typeof DRY_RUN_AGENT;\n image: DryRunImageDecision | null;\n command: string | null;\n reward: number | null;\n rewardFile: { name: string; content: unknown } | null;\n exitCode: number | null;\n errorTail: string | null;\n};\n\nexport type HostedDryRunStatus = {\n kind: typeof DRY_RUN_KIND;\n evidence: false;\n where: \"hosted\";\n agent: typeof DRY_RUN_AGENT;\n task: string | null;\n evaluationId: string | null;\n url: string | null;\n settlement: DryRunSettlement | null;\n};\n\n/** The run-status answer (`GET …/environments/runs/{runId}`) as a dry run reads it. */\nexport type HostedDryRunVerdict = {\n status: string;\n settled: boolean;\n progress: {\n harvested: number;\n planned: number | null;\n startedAt: string | null;\n completedAt: string | null;\n elapsedSeconds: number | null;\n } | null;\n dryRun: HostedDryRunStatus | null;\n};\n\n/** The server blocks a status read for at most this long; longer waits poll. */\nexport const STATUS_WAIT_CAP_SECONDS = 50;\n\nexport type SettleOptions = {\n /** Give up (return the last verdict, unsettled) after this long. */\n timeoutSeconds: number;\n /** Called once per unsettled poll with the verdict so far. */\n onProgress?: (verdict: HostedDryRunVerdict) => void;\n /** Injected for tests: the clock and the pause between empty polls. */\n now?: () => number;\n sleep?: (ms: number) => Promise<void>;\n};\n\nconst cid = (id: string) =>\n `/api/public/environments/${encodeURIComponent(id)}`;\n\n/** The client a `gateway benchmarks dry-run --hosted` is built on. */\nexport class HostedDryRunClient {\n constructor(private readonly options: WorldsClientOptions = {}) {}\n\n /** Dispatch ONE oracle job for `task` on `containerId` (a container id, not a slug); pins `versionId` when given. */\n dispatch(target: {\n containerId: string;\n task: string;\n versionId?: string;\n }): Promise<HostedDryRunDispatch> {\n return apiRequest(\n this.options,\n \"POST\",\n `${cid(target.containerId)}/dry-run`,\n {\n task: target.task,\n ...(target.versionId ? { versionId: target.versionId } : {}),\n },\n );\n }\n\n /** One status read, blocking server-side for up to `waitSeconds` (capped). */\n status(runId: string, waitSeconds = 0): Promise<HostedDryRunVerdict> {\n const wait = Math.max(\n 0,\n Math.min(Math.floor(waitSeconds), STATUS_WAIT_CAP_SECONDS),\n );\n const suffix = wait ? `?waitSeconds=${wait}` : \"\";\n return apiRequest(\n this.options,\n \"GET\",\n `/api/public/environments/runs/${encodeURIComponent(runId)}${suffix}`,\n );\n }\n\n /** Poll until the run settles or `timeoutSeconds` pass; the last verdict either way. */\n async settle(\n runId: string,\n opts: SettleOptions,\n ): Promise<HostedDryRunVerdict> {\n const now = opts.now ?? Date.now;\n const sleep =\n opts.sleep ??\n ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));\n const deadline = now() + opts.timeoutSeconds * 1000;\n for (;;) {\n const budget = Math.floor(\n Math.min(45, Math.max(0, (deadline - now()) / 1000)),\n );\n const asked = now();\n const verdict = await this.status(runId, budget);\n if (verdict.settled || now() >= deadline) return verdict;\n opts.onProgress?.(verdict);\n // A server that answered at once (no long poll behind it) must not be hammered.\n if (now() - asked < 1000) await sleep(1000);\n }\n }\n}\n\n/** The one exit-code decision, shared by the CLI twins: 0 only when the oracle scored exactly 1.0. */\nexport class DryRunOutcome {\n constructor(readonly verdict: HostedDryRunVerdict) {}\n\n get settlement(): DryRunSettlement | null {\n return this.verdict.dryRun?.settlement ?? null;\n }\n\n /** Why the dry run did not pass, or null when it did. */\n reason(): string | null {\n if (!this.verdict.settled) return `still running after the wait`;\n const settlement = this.settlement;\n if (!settlement)\n return `the runner filed no settlement (${this.verdict.status})`;\n const lastErrorLine =\n settlement.errorTail?.trim().split(\"\\n\").at(-1) || null;\n // A non-zero harbor exit is a failure whatever the reward file says: a\n // 1.0 written before the harness died is not a pass.\n if (settlement.exitCode !== null && settlement.exitCode !== 0)\n return `the runner failed (exit ${settlement.exitCode}): ${lastErrorLine ?? \"harbor exited non-zero\"}`;\n if (settlement.reward === null && lastErrorLine)\n return `the runner failed (exit ?): ${lastErrorLine}`;\n if (settlement.reward === null)\n return \"ungraded: the grader ran but wrote no reward\";\n if (settlement.reward !== 1)\n return `the reference solution scored ${settlement.reward}, not 1.0`;\n return null;\n }\n\n passed(): boolean {\n return this.reason() === null;\n }\n}\n","import { requirePlatformEndpoint } from \"./platformEndpoint\";\nimport type { WorldTaskIdRef } from \"./session\";\nimport type { PersonalToken } from \"./personalToken\";\nimport { PlatformTransport, type PlatformMethod, type RetryPolicy } from \"./transport\";\n\nexport { ApiError, invalidFields, parseErrorBody } from \"./apiError\";\n\nexport type WorldsClientOptions = {\n host?: string;\n publicKey?: string;\n secretKey?: string;\n token?: PersonalToken;\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\n/** Authenticated JSON request to the platform API. `init.timeoutMs` replaces the `GATEWAY_TIMEOUT_MS` budget for a request that\n * legitimately outlasts it; `init.retry` is only for a request whose repeat is harmless. */\nexport async function apiRequest<T>(\n options: WorldsClientOptions,\n method: PlatformMethod,\n path: string,\n body?: unknown,\n init: { timeoutMs?: number; retry?: RetryPolicy } = {},\n): Promise<T> {\n return new PlatformTransport(requirePlatformEndpoint(options)).json<T>(method, path, body, init);\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/** The project's run configs; CI resolves one by name and dispatches it 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/** Either the bundle's own scenarios (`taskNames`, `taskSetDatasetId`) or stored tasks (`worldTasks`, schema worlds only), never both;\n * a stored task ref without `version` runs the task's current version at 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, as `bench run-configs create --world-tasks` takes them. */\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 per-task rewards. */\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/** A run as `bench runs list` prints it: no logs, samples or links (`getRun` has those). */\nexport type RunSummary = {\n id: string;\n status: string;\n terminal: boolean;\n score: number | null;\n summary: string | null;\n createdAt: string;\n completedAt: string | null;\n model: string | null;\n versionId: string | null;\n versionLabel: string | null;\n runConfigId: string | null;\n runConfigName: string | null;\n parallelism: number;\n exitCode: number | null;\n};\n\nexport type ListRunsFilter = {\n /** Only runs of this world/benchmark; a slug the project lacks lists nothing. */\n slug?: string;\n /** Case-insensitive run status (RUNNING, completed, …). */\n status?: string;\n limit?: number;\n};\n\n/** The project's runs, newest first. */\nexport async function listRuns(\n filter: ListRunsFilter = {},\n options: WorldsClientOptions = {},\n): Promise<RunSummary[]> {\n const params = new URLSearchParams();\n if (filter.slug) params.set(\"slug\", filter.slug);\n if (filter.status) params.set(\"status\", filter.status);\n if (filter.limit !== undefined) params.set(\"limit\", String(filter.limit));\n const qs = params.toString();\n const res = await apiRequest<{ runs: RunSummary[] }>(\n options,\n \"GET\",\n `/api/public/benchmark-containers/runs${qs ? `?${qs}` : \"\"}`,\n );\n return res.runs;\n}\n\n/** Poll a run to terminal every `intervalSeconds` (default 20) for up to `timeoutMinutes` (default 45). */\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/** A dispatch's branch, commit and actor: from GitHub Actions under CI, else the local git checkout; every dispatch carries it unless overridden. */\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 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/** A world pinned to one version, with its tasks and hosted runs, as `openWorld` and `openWorldVersion` return it. */\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 /** Open a live session on a bundled task's name or an inline `WorldTaskSpec`; the platform boots or reuses a warm container. */\n async open(\n task: import(\"./session\").WorldTaskRef,\n opts: {\n reuseWarm?: boolean;\n surfaces?: import(\"./browser\").WorldSurfaceKind[];\n browserTier?: import(\"./browser\").BrowserTier;\n } = {},\n ): Promise<import(\"./session\").WorldSession> {\n const { openSession } = await import(\"./session\");\n return openSession(this.slug, {\n task,\n versionId: this.version.versionId,\n reuseWarm: opts.reuseWarm,\n surfaces: opts.surfaces,\n browserTier: opts.browserTier,\n options: this.options,\n });\n }\n\n /** Start a hosted run of a run config on this version (or `opts.versionId`): one graded run per model, provenance detected unless given. */\n async dispatch(\n runConfigId: string,\n opts: {\n containerId?: string;\n versionId?: string;\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/** Resolve `slug` or `slug@branch|tag|semver|hash` to its pinned version and task list, without downloading the bundle. */\nexport async function openWorld(\n slugRef: string,\n options: WorldsClientOptions = {},\n): Promise<WorldSet> {\n const at = slugRef.indexOf(\"@\");\n const slug = at === -1 ? slugRef : slugRef.slice(0, at);\n const ref = at === -1 ? null : slugRef.slice(at + 1);\n return resolveWorld(slugRef, slug, ref, ref ? { ref } : {}, options);\n}\n\n/** Resolve `slug` at one READY `versionId`, with that version's task list; another world's version, a draft or an unknown id is a 404, never the head. */\nexport async function openWorldVersion(\n slug: string,\n versionId: string,\n options: WorldsClientOptions = {},\n): Promise<WorldSet> {\n return resolveWorld(\n `${slug}@${versionId}`,\n slug,\n null,\n { versionId },\n options,\n );\n}\n\nasync function resolveWorld(\n slugRef: string,\n slug: string,\n ref: string | null,\n pin: { ref?: string; versionId?: string },\n options: WorldsClientOptions,\n): Promise<WorldSet> {\n const version = await apiRequest<\n ResolvedWorldVersion & { taskNames?: string[] }\n >(options, \"POST\", \"/api/public/benchmark-containers/resolve-version\", {\n slug,\n ...pin,\n });\n\n const world = new WorldSet(\n slugRef,\n slug,\n ref,\n {\n versionId: version.versionId,\n semanticVersion: version.semanticVersion ?? null,\n contentHash: version.contentHash,\n state: version.state,\n },\n [],\n options,\n );\n for (const name of version.taskNames ?? []) {\n const variant = /^[a-z0-9]+-([a-z0-9]+)-/.exec(name)?.[1] ?? null;\n world.tasks.push(new WorldTask(world, name, variant));\n }\n return world;\n}\n\n// session.ts imports apiRequest from here; the cycle is function-level only.\nexport * from \"./transport\";\nexport * from \"./session\";\nexport * from \"./grade\";\nexport * from \"./sessionList\";\nexport * from \"./sessionContract\";\nexport * from \"./taskRef\";\nexport * from \"./tasks\";\nexport * from \"./taskGrades\";\nexport * from \"./taskSessions\";\nexport * from \"./taskRun\";\nexport * from \"./setRun\";\nexport * from \"./checkoutProvenance\";\nexport * from \"./evals\";\nexport * from \"./browser\";\nexport { COMPUTER_USE_SPECS, computerUseToolkit } from \"./browserTools\";\nexport {\n PageObserver,\n PageState,\n PageStateError,\n type PageObservation,\n} from \"./pageState\";\nexport * from \"./surfaceDescriptor\";\nexport * from \"./requestLog\";\nexport * from \"./requestLedger\";\nexport * from \"./webhooks\";\nexport * from \"./browserReconnect\";\nexport * from \"./nativeComputer\";\nexport * from \"./hub\";\nexport * from \"./validate\";\nexport * from \"./describe\";\nexport * from \"./redaction\";\nexport * from \"./transforms\";\nexport * from \"./query\";\nexport * from \"./migrate\";\nexport * from \"./ingest\";\nexport * from \"./sandbox\";\nexport * from \"./editSessions\";\nexport * from \"./states\";\nexport * from \"./dryRun\";\nexport * from \"./worldNotice\";\n","/**\n * Read the project's traces, observations and trace sessions — the public\n * API behind `gateway traces …` and the MCP tools get_trace / get_observations\n * / get_session. Everything here is read-only.\n *\n * GET /api/public/traces?… a page of traces (page 1-based, limit ≤ 100)\n * GET /api/public/traces/{traceId} one trace with its observations and scores\n * GET /api/public/observations?… a page of observations (type, traceId, time window)\n * GET /api/public/sessions?… a page of trace sessions\n * GET /api/public/sessions/{sessionId} one session; includeIO=true attaches every trace's observations\n */\n\nimport { apiRequest, type WorldsClientOptions } from \"../worlds/index\";\n\nexport type TraceFilters = {\n fromTimestamp?: string;\n toTimestamp?: string;\n sessionId?: string;\n userId?: string;\n name?: string;\n tags?: string[];\n environment?: string;\n version?: string;\n release?: string;\n /** `timestamp.asc`, `timestamp.desc` (the default), … */\n orderBy?: string;\n};\n\nexport type ObservationFilters = {\n traceId?: string;\n type?: string;\n name?: string;\n userId?: string;\n level?: string;\n parentObservationId?: string;\n environment?: string;\n version?: string;\n fromStartTime?: string;\n toStartTime?: string;\n};\n\nexport type SessionFilters = { fromTimestamp?: string; toTimestamp?: string; environment?: string };\n\nexport type PageMeta = { page: number; limit: number; totalItems: number; totalPages: number };\nexport type Page<T> = { data: T[]; meta: PageMeta };\n\nexport type Trace = {\n id: string;\n timestamp: string;\n name: string | null;\n sessionId: string | null;\n userId: string | null;\n tags: string[];\n environment?: string;\n [key: string]: unknown;\n};\n\nexport type Observation = {\n id: string;\n traceId: string | null;\n type: string;\n name: string | null;\n startTime: string;\n endTime?: string | null;\n level?: string;\n [key: string]: unknown;\n};\n\nexport type TraceDetail = Trace & { observations: Observation[]; scores: unknown[]; latency?: number; totalCost?: number };\n\nexport type TraceSession = { id: string; createdAt: string; projectId: string; environment: string };\nexport type TraceSessionDetail = TraceSession & { traces: (Trace & { observations?: Observation[] })[] };\n\n/** The platform caps a page at 100. */\nexport const PAGE_LIMIT = 100;\n\ntype Scalar = string | number | boolean | undefined | null;\n\nfunction qs(params: Record<string, Scalar | string[]>): string {\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined || value === null || value === \"\") continue;\n if (Array.isArray(value)) for (const item of value) search.append(key, item);\n else search.set(key, String(value));\n }\n const text = search.toString();\n return text ? `?${text}` : \"\";\n}\n\nexport async function listTraces(\n options: WorldsClientOptions = {},\n filters: TraceFilters = {},\n page: { page?: number; limit?: number; fields?: string } = {},\n): Promise<Page<Trace>> {\n const { tags, ...rest } = filters;\n return apiRequest<Page<Trace>>(options, \"GET\", `/api/public/traces${qs({ ...rest, tags, page: page.page ?? 1, limit: page.limit ?? 50, fields: page.fields })}`);\n}\n\n/** Page through matching traces, newest first unless `orderBy` says otherwise; `max` stops early. */\nexport async function* iterateTraces(\n options: WorldsClientOptions = {},\n filters: TraceFilters = {},\n limits: { max?: number; fields?: string } = {},\n): AsyncGenerator<Trace> {\n yield* paged((page) => listTraces(options, filters, { page, limit: PAGE_LIMIT, fields: limits.fields }), limits.max);\n}\n\n/** One trace with its observations (input/output included) and scores. */\nexport async function getTrace(options: WorldsClientOptions = {}, traceId: string): Promise<TraceDetail> {\n return apiRequest<TraceDetail>(options, \"GET\", `/api/public/traces/${encodeURIComponent(traceId)}`);\n}\n\nexport async function listObservations(\n options: WorldsClientOptions = {},\n filters: ObservationFilters = {},\n page: { page?: number; limit?: number } = {},\n): Promise<Page<Observation>> {\n return apiRequest<Page<Observation>>(options, \"GET\", `/api/public/observations${qs({ ...filters, page: page.page ?? 1, limit: page.limit ?? 50 })}`);\n}\n\nexport async function* iterateObservations(\n options: WorldsClientOptions = {},\n filters: ObservationFilters = {},\n limits: { max?: number } = {},\n): AsyncGenerator<Observation> {\n yield* paged((page) => listObservations(options, filters, { page, limit: PAGE_LIMIT }), limits.max);\n}\n\nexport async function listSessions(\n options: WorldsClientOptions = {},\n filters: SessionFilters = {},\n page: { page?: number; limit?: number } = {},\n): Promise<Page<TraceSession>> {\n return apiRequest<Page<TraceSession>>(options, \"GET\", `/api/public/sessions${qs({ ...filters, page: page.page ?? 1, limit: page.limit ?? 50 })}`);\n}\n\nexport async function* iterateSessions(\n options: WorldsClientOptions = {},\n filters: SessionFilters = {},\n limits: { max?: number } = {},\n): AsyncGenerator<TraceSession> {\n yield* paged((page) => listSessions(options, filters, { page, limit: PAGE_LIMIT }), limits.max);\n}\n\n/** One trace session and its traces; `includeIO` attaches every trace's full observations. */\nexport async function getSession(\n options: WorldsClientOptions = {},\n sessionId: string,\n detail: { includeIO?: boolean } = {},\n): Promise<TraceSessionDetail> {\n return apiRequest<TraceSessionDetail>(options, \"GET\", `/api/public/sessions/${encodeURIComponent(sessionId)}${qs({ includeIO: detail.includeIO ? \"true\" : undefined })}`);\n}\n\nexport type ExportOptions = {\n /** Attach each trace's observations (one GET /traces/{id} per trace). */\n observations?: boolean;\n /** With `observations`: keep only this observation type (TOOL, GENERATION, SPAN, …). */\n type?: string;\n /** Stop after this many traces. */\n max?: number;\n};\n\nexport type ExportSummary = { traces: number; observations: number };\n\n/**\n * Every matching trace as one JSON object handed to `write`, ids and\n * timestamps exactly as the API returns them. With `observations`, each object\n * carries its `observations` array (filtered by `type` when given) and the\n * trace's `scores`, from `GET /traces/{id}`.\n */\nexport async function exportTraces(\n options: WorldsClientOptions = {},\n filters: TraceFilters = {},\n exportOptions: ExportOptions = {},\n write: (record: Record<string, unknown>) => void,\n): Promise<ExportSummary> {\n const summary: ExportSummary = { traces: 0, observations: 0 };\n const wantedType = exportOptions.type?.toUpperCase();\n for await (const trace of iterateTraces(options, filters, { max: exportOptions.max })) {\n let record: Record<string, unknown> = trace;\n if (exportOptions.observations) {\n const detail = await getTrace(options, trace.id);\n const observations = wantedType ? detail.observations.filter((o) => o.type?.toUpperCase() === wantedType) : detail.observations;\n summary.observations += observations.length;\n record = { ...detail, observations };\n }\n summary.traces++;\n write(record);\n }\n return summary;\n}\n\nasync function* paged<T>(fetchPage: (page: number) => Promise<Page<T>>, max?: number): AsyncGenerator<T> {\n let yielded = 0;\n for (let page = 1; ; page++) {\n const answer = await fetchPage(page);\n for (const item of answer.data) {\n if (max !== undefined && yielded >= max) return;\n yielded++;\n yield item;\n }\n const totalPages = answer.meta?.totalPages ?? (answer.data.length < PAGE_LIMIT ? page : page + 1);\n if (!answer.data.length || page >= totalPages) return;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAa,oBAEA,qBAEA,kBACA,kBAEA,mBAOP,UACA,SACA,UAIO,sBAEP,MAEO;AAxBb;AAAA;AAAA;AAAO,IAAM,qBACX;AACK,IAAM,sBACX;AACK,IAAM,mBAAmB;AACzB,IAAM,mBACX;AACK,IAAM,oBACX;AAMF,IAAM,WAAW;AACjB,IAAM,UAAU;AAChB,IAAM,WAAW,CAAC,sBAAsB,sBAAsB,iBAAiB;AAIxE,IAAM,uBAAN,cAAmC,MAAM;AAAA,IAAC;AAEjD,IAAM,OAAO,CAAC,SAAiB,KAAK,QAAQ,QAAQ,EAAE;AAE/C,IAAM,gBAAN,MAAM,eAAc;AAAA,MACjB,YACG,OACA,SACA,MACT;AAHS;AACA;AACA;AAAA,MACR;AAAA,MAHQ;AAAA,MACA;AAAA,MACA;AAAA,MAGX,OAAO,QAAQ,KAAwB,UAAwB,CAAC,GAAyB;AACvF,cAAM,QAAQ,IAAI;AAClB,YAAI,CAAC,MAAO,QAAO;AACnB,YAAI,QAAQ,QAAQ,SAAS,KAAK,CAAC,SAAS,IAAI,IAAI,CAAC,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A+C,KAAiC;AACvG,MAAI,UAAU;AACd,WAAS,OAAO,KAAK,QAAQ;AAC3B,UAAM,SAAS,MAAM,UAAU,IAAI;AACnC,eAAW,QAAQ,OAAO,MAAM;AAC9B,UAAI,QAAQ,UAAa,WAAW,IAAK;AACzC;AACA,YAAM;AAAA,IACR;AACA,UAAM,aAAa,OAAO,MAAM,eAAe,OAAO,KAAK,SAAS,aAAa,OAAO,OAAO;AAC/F,QAAI,CAAC,OAAO,KAAK,UAAU,QAAQ,WAAY;AAAA,EACjD;AACF;","names":["path","resolve","init_session","point","path","MAX_ERROR","options","import_node_crypto","init_session","init_session","import_node_crypto","path","init_session","fs","path","import_node_crypto","fs","path","fs","path","import_node_crypto","import_node_zlib","fs","path","import_node_crypto","import_node_crypto","import_node_crypto","fs","path","path","init_session"]}
|