@withgateway/sdk 0.1.20 → 0.2.0

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.
Files changed (130) hide show
  1. package/README.md +141 -2
  2. package/dist/cli.js +8683 -1343
  3. package/dist/cli.js.map +1 -1
  4. package/dist/cli.mjs +8683 -1344
  5. package/dist/cli.mjs.map +1 -1
  6. package/dist/index.d.mts +1 -1
  7. package/dist/index.d.ts +1 -1
  8. package/dist/index.js +979 -46
  9. package/dist/index.js.map +1 -1
  10. package/dist/index.mjs +943 -38
  11. package/dist/index.mjs.map +1 -1
  12. package/dist/tracing/index.js +9 -2
  13. package/dist/tracing/index.js.map +1 -1
  14. package/dist/tracing/index.mjs +9 -2
  15. package/dist/tracing/index.mjs.map +1 -1
  16. package/dist/worlds/index.d.mts +738 -28
  17. package/dist/worlds/index.d.ts +738 -28
  18. package/dist/worlds/index.js +940 -42
  19. package/dist/worlds/index.js.map +1 -1
  20. package/dist/worlds/index.mjs +934 -36
  21. package/dist/worlds/index.mjs.map +1 -1
  22. package/package.json +9 -2
  23. package/runtime/gatewaysdk/__init__.py +0 -0
  24. package/runtime/gatewaysdk/environment/__init__.py +108 -0
  25. package/runtime/gatewaysdk/environment/_bundle.py +281 -0
  26. package/runtime/gatewaysdk/environment/_harbor.py +276 -0
  27. package/runtime/gatewaysdk/environment/_materialize.py +97 -0
  28. package/runtime/gatewaysdk/environment/_tar.py +33 -0
  29. package/runtime/gatewaysdk/environment/_world.py +346 -0
  30. package/runtime/gatewaysdk/environment/core.py +527 -0
  31. package/runtime/gatewaysdk/environment/errors.py +58 -0
  32. package/runtime/gatewaysdk/environment/runtime.py +150 -0
  33. package/runtime/gatewaysdk/environment/schema/__init__.py +35 -0
  34. package/runtime/gatewaysdk/environment/schema/__main__.py +225 -0
  35. package/runtime/gatewaysdk/environment/schema/_slack_fidelity.py +116 -0
  36. package/runtime/gatewaysdk/environment/schema/_slack_scenario.py +183 -0
  37. package/runtime/gatewaysdk/environment/schema/api.py +1628 -0
  38. package/runtime/gatewaysdk/environment/schema/batch.py +755 -0
  39. package/runtime/gatewaysdk/environment/schema/compiler.py +615 -0
  40. package/runtime/gatewaysdk/environment/schema/conform.py +428 -0
  41. package/runtime/gatewaysdk/environment/schema/connector.py +777 -0
  42. package/runtime/gatewaysdk/environment/schema/connectors/apple-business-manager/handlers.py +17 -0
  43. package/runtime/gatewaysdk/environment/schema/connectors/apple-business-manager/parity.json +28 -0
  44. package/runtime/gatewaysdk/environment/schema/connectors/apple-business-manager/provenance.json +233 -0
  45. package/runtime/gatewaysdk/environment/schema/connectors/apple-business-manager/scope.toml +112 -0
  46. package/runtime/gatewaysdk/environment/schema/connectors/apple-business-manager/world.json +1380 -0
  47. package/runtime/gatewaysdk/environment/schema/connectors/base.json +28 -0
  48. package/runtime/gatewaysdk/environment/schema/connectors/custom/handlers.py +18 -0
  49. package/runtime/gatewaysdk/environment/schema/connectors/custom/world.json +123 -0
  50. package/runtime/gatewaysdk/environment/schema/connectors/github/handlers.py +81 -0
  51. package/runtime/gatewaysdk/environment/schema/connectors/github/parity.json +37 -0
  52. package/runtime/gatewaysdk/environment/schema/connectors/github/provenance.json +134 -0
  53. package/runtime/gatewaysdk/environment/schema/connectors/github/scope.toml +158 -0
  54. package/runtime/gatewaysdk/environment/schema/connectors/github/world.json +5869 -0
  55. package/runtime/gatewaysdk/environment/schema/connectors/google-calendar/handlers.py +23 -0
  56. package/runtime/gatewaysdk/environment/schema/connectors/google-calendar/world.json +209 -0
  57. package/runtime/gatewaysdk/environment/schema/connectors/google-drive/handlers.py +18 -0
  58. package/runtime/gatewaysdk/environment/schema/connectors/google-drive/world.json +286 -0
  59. package/runtime/gatewaysdk/environment/schema/connectors/jamf/handlers.py +34 -0
  60. package/runtime/gatewaysdk/environment/schema/connectors/jamf/parity.json +49 -0
  61. package/runtime/gatewaysdk/environment/schema/connectors/jamf/provenance.json +181 -0
  62. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scope.toml +128 -0
  63. package/runtime/gatewaysdk/environment/schema/connectors/jamf/world.json +2218 -0
  64. package/runtime/gatewaysdk/environment/schema/connectors/jira/handlers.py +28 -0
  65. package/runtime/gatewaysdk/environment/schema/connectors/jira/world.json +389 -0
  66. package/runtime/gatewaysdk/environment/schema/connectors/kandji/handlers.py +38 -0
  67. package/runtime/gatewaysdk/environment/schema/connectors/kandji/parity.json +29 -0
  68. package/runtime/gatewaysdk/environment/schema/connectors/kandji/provenance.json +152 -0
  69. package/runtime/gatewaysdk/environment/schema/connectors/kandji/scope.toml +120 -0
  70. package/runtime/gatewaysdk/environment/schema/connectors/kandji/world.json +765 -0
  71. package/runtime/gatewaysdk/environment/schema/connectors/linear/handlers.py +20 -0
  72. package/runtime/gatewaysdk/environment/schema/connectors/linear/world.json +363 -0
  73. package/runtime/gatewaysdk/environment/schema/connectors/microsoft-teams/fidelity.json +45 -0
  74. package/runtime/gatewaysdk/environment/schema/connectors/microsoft-teams/handlers.py +1 -0
  75. package/runtime/gatewaysdk/environment/schema/connectors/microsoft-teams/provenance.json +851 -0
  76. package/runtime/gatewaysdk/environment/schema/connectors/microsoft-teams/scope.md +231 -0
  77. package/runtime/gatewaysdk/environment/schema/connectors/microsoft-teams/teams-types.json +1710 -0
  78. package/runtime/gatewaysdk/environment/schema/connectors/microsoft-teams/world.json +858 -0
  79. package/runtime/gatewaysdk/environment/schema/connectors/netsuite/handlers.py +32 -0
  80. package/runtime/gatewaysdk/environment/schema/connectors/netsuite/parity.json +50 -0
  81. package/runtime/gatewaysdk/environment/schema/connectors/netsuite/provenance.json +137 -0
  82. package/runtime/gatewaysdk/environment/schema/connectors/netsuite/scope.toml +78 -0
  83. package/runtime/gatewaysdk/environment/schema/connectors/netsuite/world.json +16243 -0
  84. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/handlers.py +806 -0
  85. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/parity.json +46 -0
  86. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/provenance.json +143 -0
  87. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scope.toml +174 -0
  88. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/world.json +4695 -0
  89. package/runtime/gatewaysdk/environment/schema/connectors/slack/MODEL.md +236 -0
  90. package/runtime/gatewaysdk/environment/schema/connectors/slack/capabilities.json +1039 -0
  91. package/runtime/gatewaysdk/environment/schema/connectors/slack/handlers.py +762 -0
  92. package/runtime/gatewaysdk/environment/schema/connectors/slack/parity.json +65 -0
  93. package/runtime/gatewaysdk/environment/schema/connectors/slack/provenance.json +294 -0
  94. package/runtime/gatewaysdk/environment/schema/connectors/slack/scope.toml +44 -0
  95. package/runtime/gatewaysdk/environment/schema/connectors/slack/world.json +4993 -0
  96. package/runtime/gatewaysdk/environment/schema/connectors/workday/handlers.py +75 -0
  97. package/runtime/gatewaysdk/environment/schema/connectors/workday/parity.json +36 -0
  98. package/runtime/gatewaysdk/environment/schema/connectors/workday/provenance.json +179 -0
  99. package/runtime/gatewaysdk/environment/schema/connectors/workday/scope.toml +180 -0
  100. package/runtime/gatewaysdk/environment/schema/connectors/workday/world.json +806 -0
  101. package/runtime/gatewaysdk/environment/schema/data.py +593 -0
  102. package/runtime/gatewaysdk/environment/schema/extract.py +263 -0
  103. package/runtime/gatewaysdk/environment/schema/host.py +2407 -0
  104. package/runtime/gatewaysdk/environment/schema/host_surfaces.py +275 -0
  105. package/runtime/gatewaysdk/environment/schema/platform.py +1272 -0
  106. package/runtime/gatewaysdk/environment/schema/scaffold.py +250 -0
  107. package/runtime/gatewaysdk/environment/schema/skill.py +118 -0
  108. package/runtime/gatewaysdk/environment/schema/skills/agents/connector-template-author.md +202 -0
  109. package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/CONNECTORS.md +331 -0
  110. package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/CONVENTIONS.md +100 -0
  111. package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/SKILL.md +313 -0
  112. package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/ROWS.md +223 -0
  113. package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/SKILL.md +293 -0
  114. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/SKILL.md +390 -0
  115. package/runtime/gatewaysdk/environment/schema/slack.py +757 -0
  116. package/runtime/gatewaysdk/environment/schema/snapshot.py +479 -0
  117. package/runtime/gatewaysdk/environment/schema/store.py +904 -0
  118. package/runtime/gatewaysdk/environment/schema/tasks.py +525 -0
  119. package/runtime/gatewaysdk/environment/schema/tools_world.py +322 -0
  120. package/runtime/gatewaysdk/environment/schema/validation.py +577 -0
  121. package/runtime/gatewaysdk/environment/schema/worker.py +78 -0
  122. package/runtime/gatewaysdk/environment/schema/workers.py +500 -0
  123. package/runtime/gatewaysdk/environment/schema/world_tests.py +336 -0
  124. package/skills/agents/connector-template-author.md +202 -0
  125. package/skills/connector-schema-authoring/CONNECTORS.md +331 -0
  126. package/skills/connector-schema-authoring/CONVENTIONS.md +100 -0
  127. package/skills/connector-schema-authoring/SKILL.md +313 -0
  128. package/skills/world-data-ingestion/ROWS.md +223 -0
  129. package/skills/world-data-ingestion/SKILL.md +293 -0
  130. package/skills/worlds-getting-started/SKILL.md +390 -0
package/dist/cli.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/worlds/session.ts","../src/worlds/hub.ts","../src/worlds/validate.ts","../src/worlds/index.ts","../src/cli.ts"],"sourcesContent":["import { apiRequest, type WorldsClientOptions } from \"./index\";\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, \"revops-mara-dedupe-contacts\");\n * await session.ready(); // wait for the container\n * await session.call(\"crm_search\", { entity: \"deals\" });\n * const { reward, rewards } = await session.grade();\n * await session.close({ keepWarm: true }); // hand it back to the pool\n *\n * 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};\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 WorldSessionState = {\n sessionId: string;\n state: string;\n ready: boolean;\n versionId: string;\n contentHash: string;\n taskName: string | null;\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};\n\nexport type GradeResult = {\n reward: number | null;\n rewards: Record<string, number>;\n raw: unknown;\n};\n\n/** How long `ready()` waits, and how often it asks. */\nconst READY_TIMEOUT_MS = 10 * 60_000;\nconst READY_POLL_MS = 2_000;\n/** How long one call may take end to end (container claim + execution). */\nconst CALL_TIMEOUT_MS = 3 * 60_000;\nconst CALL_POLL_MS = 400;\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\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 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: spec.name,\n description: spec.doc ?? spec.name,\n parameters: { type: \"object\", properties, required },\n },\n };\n}\n\nexport class WorldSessionTimeout extends Error {}\nexport class WorldSessionCallError extends Error {}\n\nexport class WorldSession {\n constructor(\n readonly sessionId: string,\n private state: WorldSessionState,\n private readonly options: WorldsClientOptions,\n ) {}\n\n get task(): string | null {\n return this.state.taskName;\n }\n\n /** What this task asks for — the bundle's own instruction.md. */\n get instruction(): string | null {\n return this.state.instruction ?? null;\n }\n\n get versionId(): string {\n return this.state.versionId;\n }\n\n /** The session's latest platform state (one request, no waiting). */\n async status(): Promise<WorldSessionState> {\n const fresh = await apiRequest<WorldSessionState>(\n this.options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}`,\n );\n // A status read does not carry the objective; keep the one we opened with.\n this.state = {\n instruction: this.state.instruction,\n tools: this.state.tools,\n ...fresh,\n };\n return this.state;\n }\n\n /**\n * Wait until the container is warm — meaning the process inside it has\n * asked the platform for work, not merely that a job was accepted.\n */\n async ready(opts: { timeoutMs?: number } = {}): Promise<WorldSessionState> {\n const deadline = Date.now() + (opts.timeoutMs ?? READY_TIMEOUT_MS);\n for (;;) {\n const state = await this.status();\n if (state.ready) return state;\n if (state.state === \"FAILED\" || state.state === \"STOPPED\")\n throw new WorldSessionCallError(\n `World session ${state.state.toLowerCase()} before it was ready.`,\n );\n if (Date.now() > deadline)\n throw new WorldSessionTimeout(\n `World session still ${state.state} after ${Math.round((opts.timeoutMs ?? READY_TIMEOUT_MS) / 1000)}s.`,\n );\n await sleep(READY_POLL_MS);\n }\n }\n\n /** Enqueue one interaction and wait for the container's answer. */\n private async exchange(\n body: { kind?: \"call\" | \"grade\" | \"close\"; tool?: string; args?: unknown },\n timeoutMs = CALL_TIMEOUT_MS,\n ): Promise<unknown> {\n const { callId } = await apiRequest<{ callId: string; seq: number }>(\n this.options,\n \"POST\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/calls`,\n body,\n );\n const deadline = Date.now() + timeoutMs;\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 `Call ${callId} still ${call.state} after ${Math.round(timeoutMs / 1000)}s — the container may have died.`,\n );\n await sleep(CALL_POLL_MS);\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.state.tools;\n if (!specs) specs = (await this.status()).tools ?? [];\n const impls: WorldToolkit[\"impls\"] = {};\n for (const spec of specs) {\n impls[spec.name] = (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. */\n async grade(opts: { timeoutMs?: number } = {}): Promise<GradeResult> {\n const raw = (await this.exchange(\n { kind: \"grade\" },\n opts.timeoutMs,\n )) as Record<string, unknown> | null;\n const record = raw && typeof raw === \"object\" ? raw : {};\n const rewards: Record<string, number> = {};\n for (const [key, value] of Object.entries(record)) {\n if (key !== \"reward\" && typeof value === \"number\") rewards[key] = value;\n }\n return {\n reward: typeof record.reward === \"number\" ? record.reward : null,\n rewards,\n raw,\n };\n }\n\n /**\n * End the session. `keepWarm` hands the container back to the pool instead\n * of tearing it down, so the next session for the same task starts warm —\n * the pooled instance still obeys the fleet's idle TTL and pinning.\n */\n async close(opts: { keepWarm?: boolean } = {}): Promise<{ state: string }> {\n return apiRequest(\n this.options,\n \"DELETE\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}`,\n { keepWarm: opts.keepWarm ?? false },\n );\n }\n}\n\n/**\n * Attach to a session that already exists — resuming after a crash, or\n * driving a session someone else opened (a container started by hand on a\n * self-hosted install, a session opened by CI and handed to a developer).\n */\nexport async function attachSession(\n sessionId: string,\n options: WorldsClientOptions = {},\n): Promise<WorldSession> {\n const state = await apiRequest<WorldSessionState>(\n options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(sessionId)}`,\n );\n return new WorldSession(sessionId, state, options);\n}\n\n/**\n * Open a live session against one task of a world. Returns as soon as the\n * platform has accepted it — call `ready()` to wait for the container.\n */\nexport async function openSession(\n slugOrRef: string,\n task: string,\n opts: {\n versionId?: string;\n reuseWarm?: boolean;\n options?: WorldsClientOptions;\n } = {},\n): Promise<WorldSession> {\n const options = opts.options ?? {};\n const at = slugOrRef.indexOf(\"@\");\n const slug = at === -1 ? slugOrRef : slugOrRef.slice(0, at);\n const state = await apiRequest<WorldSessionState & { reusedWarm: boolean }>(\n options,\n \"POST\",\n \"/api/public/world-sessions\",\n {\n ...(opts.versionId ? { versionId: opts.versionId } : { slug }),\n task,\n ...(opts.reuseWarm === undefined ? {} : { reuseWarm: opts.reuseWarm }),\n },\n );\n return new WorldSession(state.sessionId, state, options);\n}\n\n// ── running many tasks at once ───────────────────────────────────────────────\n\nexport type SessionRunResult = {\n task: string;\n sessionId: string;\n reward: number | null;\n rewards: Record<string, number>;\n /** Set when the task threw instead of grading. */\n error?: string;\n};\n\nexport type SessionRunReport = {\n results: SessionRunResult[];\n /** Mean reward over every task, counting failures as 0. */\n mean: number;\n /** True when `mean >= failUnder` (or no gate was set). */\n passed: boolean;\n};\n\n/**\n * RUN MANY TASKS IN PARALLEL, one warm container each.\n *\n * Parallelism against live worlds is the normal case — a suite is a dozen\n * tasks and each needs its own container, because two agents sharing one\n * world state would corrupt both episodes. Every caller was writing the same\n * pool, the same per-task open/ready/toolkit/grade/close, and the same\n * \"don't let one failure kill the run\" logic, so it belongs here:\n *\n * const report = await runSessions({\n * world: \"revenue-ops-sim@main\",\n * tasks, // default: every task in the world\n * concurrency: 4,\n * failUnder: 0.7,\n * agent: async ({ toolkit, instruction }) =>\n * myAgent(toolkit.impls, toolkit.schemas, instruction),\n * });\n *\n * The handler gets a ready session with its toolkit already bound; grading,\n * closing (warm) and aggregation are handled. A task that throws scores 0\n * and records why — the tasks that passed keep their results.\n */\nexport async function runSessions(opts: {\n world: string;\n tasks?: string[];\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 task: string;\n }) => Promise<unknown>;\n onResult?: (result: SessionRunResult) => void;\n options?: WorldsClientOptions;\n}): Promise<SessionRunReport> {\n const options = opts.options ?? {};\n const concurrency = Math.max(1, opts.concurrency ?? 3);\n\n let tasks = opts.tasks;\n let versionId = opts.versionId;\n if (!tasks || !versionId) {\n // One resolve for the whole run: every session pins the SAME version, so\n // a push mid-suite cannot split the results across two worlds.\n const { openWorld } = await import(\"./index\");\n const world = await openWorld(opts.world, options);\n tasks = tasks ?? world.tasks.map((t) => t.name);\n versionId = versionId ?? world.version.versionId;\n }\n\n const results: SessionRunResult[] = [];\n let next = 0;\n await Promise.all(\n Array.from({ length: Math.min(concurrency, tasks.length) }, async () => {\n while (next < tasks!.length) {\n const task = tasks![next++];\n let session: WorldSession | null = null;\n try {\n session = await openSession(opts.world, task, {\n versionId,\n options,\n });\n await session.ready();\n const toolkit = await session.toolkit();\n await opts.agent({\n session,\n toolkit,\n instruction: session.instruction ?? task,\n task,\n });\n const graded = await session.grade();\n const result: SessionRunResult = {\n task,\n sessionId: session.sessionId,\n reward: graded.reward,\n rewards: graded.rewards,\n };\n results.push(result);\n opts.onResult?.(result);\n } catch (error) {\n const result: SessionRunResult = {\n task,\n sessionId: session?.sessionId ?? \"\",\n reward: 0,\n rewards: {},\n // An Error with an empty message would read as \"no error\" to any\n // caller checking truthiness; name the type instead.\n error:\n (error instanceof Error ? error.message : String(error)) ||\n (error instanceof Error ? error.name : \"Unknown error\"),\n };\n results.push(result);\n opts.onResult?.(result);\n } finally {\n // Always give the container back — a leaked session bills until the\n // fleet's idle TTL reaps it.\n await session\n ?.close({ keepWarm: opts.keepWarm ?? true })\n .catch(() => undefined);\n }\n }\n }),\n );\n\n const mean =\n results.reduce((sum, r) => sum + (r.reward ?? 0), 0) /\n (results.length || 1);\n return {\n results: results.sort((a, b) => a.task.localeCompare(b.task)),\n mean,\n passed: opts.failUnder === undefined ? true : mean >= opts.failUnder,\n };\n}\n","import { createHash } from \"node:crypto\";\nimport { gzipSync, gunzipSync } from \"node:zlib\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\n\n/**\n * The working-dir half of the TS CLI: push / pull / checkout / status /\n * branch / tag / propose — a faithful port of the Python client\n * (`gatewaysdk/benchmark_hub/client.py` + `_archive.py`).\n *\n * LOCKSTEP WARNING — the content hash is the version's identity and is\n * byte-compatible with Prime Intellect. It now has FOUR implementations that\n * must stay identical: worker `environmentAgent/tar.ts`, web\n * `benchmark-hub/server/benchmarkContentHash.ts`, Python `_archive.py`, and\n * this file. This one is a line-for-line port of the WEB TypeScript\n * implementation (same language, same crypto) — if the rule ever changes,\n * change all four or push identity splits by client.\n *\n * One deliberate refusal, same policy as the web upload path: a bundle with\n * a ROOT `.gitignore` is refused rather than mis-hashed — the Python CLI\n * honors it via `gitignore_parser`, and an imperfect reimplementation here\n * would produce a wrong, Prime-incompatible hash silently.\n */\n\nexport const DEFAULT_BRANCH = \"main\";\nconst META_RELPATH = path.join(\".gateway\", \".env-metadata.json\");\nconst SKIP_DIRS = new Set([\n \".git\",\n \"__pycache__\",\n \"node_modules\",\n \".venv\",\n \".mypy_cache\",\n \"dist\",\n \"build\",\n \"outputs\",\n]);\nconst ROOT_EXCLUDED_DIRS = new Set([\"dist\", \"build\", \"outputs\", \"__pycache__\"]);\n\n/** Gateway-only root markers that widen collection to every ordinary root\n * file. The FOURTH copy of this list (python SDK `_archive.py`, web\n * `benchmarkContentHash.ts`, worker `tar.ts`, and here) — all four MUST stay\n * identical or the same tree hashes differently per pusher. This copy\n * missing `gateway-api-world.toml` is exactly how an api world pushed from\n * TS landed on the hub with no OpenAPI contract and no marker: the root\n * files never entered the manifest, and nothing downstream could tell. */\nconst BROAD_ROOT_MARKERS = [\"gateway-env.toml\", \"gateway-api-world.toml\"];\n\n// ── content-hash rules (port of web benchmarkContentHash.ts) ───────────────\n\nfunction isExcludedDirComponent(component: string): boolean {\n return (\n component.startsWith(\".\") ||\n ROOT_EXCLUDED_DIRS.has(component) ||\n component.endsWith(\".egg-info\")\n );\n}\n\nexport function isIncludedInContentHash(\n relPath: string,\n includeAllRootFiles: boolean,\n): boolean {\n const parts = relPath.split(\"/\");\n const name = parts[parts.length - 1];\n const dirParts = parts.slice(0, -1);\n if (name.startsWith(\".\")) return false;\n if (parts.includes(\"__pycache__\")) return false;\n if (dirParts.length === 0) {\n return (\n includeAllRootFiles ||\n name === \"README.md\" ||\n name === \"pyproject.toml\" ||\n BROAD_ROOT_MARKERS.includes(name) ||\n name.endsWith(\".py\")\n );\n }\n return !dirParts.some(isExcludedDirComponent);\n}\n\n/** The archive-visible files of a working dir, as sorted relpaths. Throws on\n * a root .gitignore (see the header). */\nexport function collectArchiveRelPaths(dir: string): string[] {\n if (fs.existsSync(path.join(dir, \".gitignore\"))) {\n throw new Error(\n \"This bundle has a root .gitignore, which the Python CLI honors via \" +\n \"gitignore_parser. Reimplementing that imperfectly here would \" +\n \"silently produce a different content hash, so the TS CLI refuses. \" +\n \"Remove the .gitignore (or bake its effect into the tree) and retry.\",\n );\n }\n const out: string[] = [];\n const includeAllRootFiles = BROAD_ROOT_MARKERS.some((marker) =>\n fs.existsSync(path.join(dir, marker)),\n );\n const walk = (rel: string) => {\n const abs = rel ? path.join(dir, rel) : dir;\n for (const entry of fs.readdirSync(abs, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {\n const childRel = rel ? `${rel}/${entry.name}` : entry.name;\n if (entry.isDirectory()) {\n if (!isExcludedDirComponent(entry.name)) walk(childRel);\n } else if (entry.isFile()) {\n if (isIncludedInContentHash(childRel, includeAllRootFiles)) {\n out.push(childRel);\n }\n }\n }\n };\n walk(\"\");\n return out.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));\n}\n\nexport function computeContentHash(dir: string): string {\n const hasher = createHash(\"sha256\");\n for (const relPath of collectArchiveRelPaths(dir)) {\n hasher.update(Buffer.from(`file:${relPath}`, \"utf-8\"));\n hasher.update(fs.readFileSync(path.join(dir, relPath)));\n }\n return hasher.digest(\"hex\");\n}\n\n// ── deterministic tar.gz writer ─────────────────────────────────────────────\n\nfunction octal(value: number, length: number): Buffer {\n return Buffer.from(value.toString(8).padStart(length - 1, \"0\") + \"\\0\", \"ascii\");\n}\n\nfunction tarHeader(name: string, size: number): Buffer {\n const header = Buffer.alloc(512);\n header.write(name, 0, 100, \"utf-8\");\n octal(0o644, 8).copy(header, 100); // mode\n octal(0, 8).copy(header, 108); // uid\n octal(0, 8).copy(header, 116); // gid\n octal(size, 12).copy(header, 124);\n octal(0, 12).copy(header, 136); // mtime = 0 (deterministic)\n header.write(\" \", 148, \"ascii\"); // checksum placeholder = spaces\n header.write(\"0\", 156, \"ascii\"); // regular file\n header.write(\"ustar\", 257, \"ascii\");\n header.write(\"00\", 263, \"ascii\");\n let sum = 0;\n for (const byte of header) sum += byte;\n header.write(sum.toString(8).padStart(6, \"0\") + \"\\0 \", 148, \"ascii\");\n return header;\n}\n\nfunction tarMember(name: string, payload: Buffer): Buffer[] {\n const parts: Buffer[] = [];\n const nameBytes = Buffer.byteLength(name, \"utf-8\");\n if (nameBytes > 100) {\n // GNU long name: an 'L' member whose body is the real name.\n const body = Buffer.from(name + \"\\0\", \"utf-8\");\n const lHeader = tarHeader(\"././@LongLink\", body.length);\n lHeader.write(\"L\", 156, \"ascii\");\n let sum = 0;\n lHeader.write(\" \", 148, \"ascii\");\n for (const byte of lHeader) sum += byte;\n lHeader.write(sum.toString(8).padStart(6, \"0\") + \"\\0 \", 148, \"ascii\");\n parts.push(lHeader, body);\n const pad = body.length % 512 === 0 ? 0 : 512 - (body.length % 512);\n if (pad) parts.push(Buffer.alloc(pad));\n parts.push(tarHeader(name.slice(0, 100), payload.length));\n } else {\n parts.push(tarHeader(name, payload.length));\n }\n parts.push(payload);\n const pad = payload.length % 512 === 0 ? 0 : 512 - (payload.length % 512);\n if (pad) parts.push(Buffer.alloc(pad));\n return parts;\n}\n\n/** A deterministic .tar.gz of the source files (node's gzip stamps no mtime,\n * matching the Python's mtime=0 gzip). */\nexport function buildSourceTarball(dir: string): Buffer {\n const parts: Buffer[] = [];\n for (const relPath of collectArchiveRelPaths(dir)) {\n parts.push(...tarMember(relPath, fs.readFileSync(path.join(dir, relPath))));\n }\n parts.push(Buffer.alloc(1024)); // end-of-archive\n return gzipSync(Buffer.concat(parts), { level: 9 });\n}\n\n// ── local metadata (.gateway/.env-metadata.json) ────────────────────────────\n\nexport type LocalMeta = Record<string, unknown> & {\n slug?: string;\n branch?: string;\n versionId?: string;\n contentHash?: string;\n baseFiles?: Record<string, string>;\n};\n\nexport function readLocalMeta(dir: string): LocalMeta | null {\n try {\n const raw = fs.readFileSync(path.join(dir, META_RELPATH), \"utf-8\");\n const parsed = JSON.parse(raw);\n return parsed && typeof parsed === \"object\" ? (parsed as LocalMeta) : null;\n } catch {\n return null;\n }\n}\n\nexport function writeLocalMeta(dir: string, meta: LocalMeta): void {\n fs.mkdirSync(path.join(dir, \".gateway\"), { recursive: true });\n fs.writeFileSync(path.join(dir, META_RELPATH), JSON.stringify(meta, null, 2));\n}\n\nexport function snapshotTreeHashes(dir: string): Record<string, string> {\n const out: Record<string, string> = {};\n for (const relPath of collectArchiveRelPaths(dir)) {\n out[relPath] = createHash(\"sha256\")\n .update(fs.readFileSync(path.join(dir, relPath)))\n .digest(\"hex\");\n }\n return out;\n}\n\nexport function localTreeState(dir: string): {\n meta: LocalMeta | null;\n dirty: string[];\n clean: boolean;\n} {\n const meta = readLocalMeta(dir);\n const base = meta?.baseFiles;\n if (!base || typeof base !== \"object\") {\n return { meta, dirty: [], clean: false };\n }\n const now = snapshotTreeHashes(dir);\n const dirty = new Set<string>();\n for (const [p, h] of Object.entries(now)) if (base[p] !== h) dirty.add(p);\n for (const p of Object.keys(base)) if (!(p in now)) dirty.add(p);\n return { meta, dirty: [...dirty].sort(), clean: dirty.size === 0 };\n}\n\n// ── protocol helpers ─────────────────────────────────────────────────────────\n\nconst sha256b64 = (data: Buffer) =>\n createHash(\"sha256\").update(data).digest(\"base64\");\n\nfunction readPyproject(dir: string): { name?: string; version?: string } {\n try {\n const text = fs.readFileSync(path.join(dir, \"pyproject.toml\"), \"utf-8\");\n // Minimal [project] reads — name and version only, quoted single-line form.\n const section = /\\[project\\]([\\s\\S]*?)(\\n\\[|$)/.exec(text)?.[1] ?? \"\";\n const name = /\\bname\\s*=\\s*\"([^\"]+)\"/.exec(section)?.[1];\n const version = /\\bversion\\s*=\\s*\"([^\"]+)\"/.exec(section)?.[1];\n return { name, version };\n } catch {\n return {};\n }\n}\n\nfunction buildFileManifest(\n dir: string,\n): { path: string; isDirectory: boolean; size: number; sha256: string }[] {\n const entries: { path: string; isDirectory: boolean; size: number; sha256: string }[] = [];\n const walk = (rel: string) => {\n const abs = rel ? path.join(dir, rel) : dir;\n for (const entry of fs.readdirSync(abs, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {\n const childRel = rel ? `${rel}/${entry.name}` : entry.name;\n if (entry.isDirectory()) {\n if (!SKIP_DIRS.has(entry.name) && !entry.name.endsWith(\".egg-info\")) {\n walk(childRel);\n }\n } else if (entry.isFile()) {\n const payload = fs.readFileSync(path.join(dir, childRel));\n entries.push({\n path: childRel,\n isDirectory: false,\n size: payload.length,\n sha256: createHash(\"sha256\").update(payload).digest(\"hex\"),\n });\n }\n }\n };\n walk(\"\");\n return entries;\n}\n\nasync function putObject(url: string, data: Buffer, shaB64: string): Promise<void> {\n const resp = await fetch(url, {\n method: \"PUT\",\n headers: {\n \"Content-Type\": \"application/gzip\",\n \"x-amz-checksum-sha256\": shaB64,\n },\n body: new Uint8Array(data),\n });\n if (!resp.ok) {\n throw new Error(`object PUT -> ${resp.status}: ${(await resp.text()).slice(0, 300)}`);\n }\n}\n\n// ── the workflows ────────────────────────────────────────────────────────────\n\nexport async function push(\n dir: string,\n opts: {\n slug?: string;\n branch?: string;\n force?: boolean;\n message?: string;\n author?: string;\n /** Push on top of this version instead of the local meta's base — what a\n * CI checkout (which has no local meta) passes after resolving the\n * branch tip, so re-validating a PR replaces its own previous push\n * instead of 409ing against it. */\n baseVersionId?: string | null;\n options?: WorldsClientOptions;\n } = {},\n): Promise<{ slug: string; versionId: string; contentHash: string; branch: string }> {\n const options = opts.options ?? {};\n if (!fs.statSync(dir).isDirectory()) throw new Error(`Not a directory: ${dir}`);\n const localMeta = readLocalMeta(dir) ?? {};\n const branch = opts.branch ?? (localMeta.branch as string | undefined) ?? DEFAULT_BRANCH;\n const baseVersionId = opts.baseVersionId ?? localMeta.versionId ?? null;\n\n const contentHash = computeContentHash(dir);\n const pyproject = readPyproject(dir);\n const slug = opts.slug ?? pyproject.name ?? path.basename(path.resolve(dir));\n\n const resolve = await apiRequest<{ containerId: string }>(\n options,\n \"POST\",\n \"/api/public/benchmark-containers/resolve\",\n { slug, name: pyproject.name ?? slug },\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 }>(options, \"POST\", \"/api/public/benchmark-containers/versions\", {\n containerId: resolve.containerId,\n contentHash,\n bundleSha256,\n bundleSizeBytes: tarball.length,\n ...(pyproject.version ? { semanticVersion: pyproject.version } : {}),\n pyprojectMeta: pyproject,\n fileManifest: buildFileManifest(dir),\n branch,\n baseVersionId,\n ...(opts.force ? { force: true } : {}),\n ...(opts.message ? { changeReason: opts.message } : {}),\n ...(opts.author ? { author: opts.author } : {}),\n });\n\n if (version.uploadUrl) await putObject(version.uploadUrl, tarball, bundleSha256);\n\n await apiRequest(\n options,\n \"POST\",\n `/api/public/benchmark-containers/versions/${version.versionId}/finalize`,\n { branch, baseVersionId, ...(opts.force ? { force: true } : {}) },\n );\n\n writeLocalMeta(dir, {\n ...localMeta,\n slug,\n ref: branch,\n branch,\n versionId: version.versionId,\n contentHash,\n semanticVersion: pyproject.version,\n forkedFromVersionId: baseVersionId,\n baseFiles: snapshotTreeHashes(dir),\n });\n return { slug, versionId: version.versionId, contentHash, branch };\n}\n\n/** Extract a downloaded bundle into `dir` (paths sanitized). */\nfunction extractBundle(bundle: Buffer, dir: string): number {\n const tar = gunzipSync(bundle);\n let offset = 0;\n let longName: string | null = null;\n let written = 0;\n while (offset + 512 <= tar.length) {\n const header = tar.subarray(offset, offset + 512);\n offset += 512;\n if (header.every((b) => b === 0)) break;\n const rawName = header.subarray(0, 100).toString(\"utf-8\").replace(/\\0.*$/, \"\");\n const size = parseInt(header.subarray(124, 136).toString(\"ascii\").replace(/\\0.*$/, \"\").trim(), 8) || 0;\n const typeflag = header.subarray(156, 157).toString(\"ascii\");\n const body = tar.subarray(offset, offset + size);\n offset += size + (size % 512 === 0 ? 0 : 512 - (size % 512));\n if (typeflag === \"L\") {\n longName = body.toString(\"utf-8\").replace(/\\0.*$/, \"\");\n continue;\n }\n const name = (longName ?? rawName).replace(/^\\.\\//, \"\");\n longName = null;\n if (typeflag !== \"0\" && typeflag !== \"\") continue;\n // Safe extract: no absolute paths, no traversal.\n if (name.startsWith(\"/\") || name.split(\"/\").includes(\"..\")) continue;\n const target = path.join(dir, name);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n fs.writeFileSync(target, body);\n written++;\n }\n return written;\n}\n\nexport async function pull(\n slugRef: string,\n target?: string,\n options: WorldsClientOptions = {},\n): Promise<{ slug: string; dir: string; versionId: string; files: number }> {\n const at = slugRef.indexOf(\"@\");\n const slug = at === -1 ? slugRef : slugRef.slice(0, at);\n const ref = at === -1 ? \"latest\" : slugRef.slice(at + 1);\n\n const details = await apiRequest<{\n versionId: string;\n contentHash: string;\n semanticVersion?: string | null;\n downloadUrl?: string;\n bundleSha256?: string;\n }>(options, \"POST\", \"/api/public/benchmark-containers/resolve-version\", {\n slug,\n ref,\n });\n if (!details.downloadUrl) {\n throw new Error(`${slug}@${ref} resolved but has no uploaded bundle`);\n }\n\n let dir = target ?? path.join(process.cwd(), slug);\n if (!target) {\n let i = 1;\n const base = dir;\n while (fs.existsSync(dir)) dir = `${base}-${i++}`;\n }\n fs.mkdirSync(dir, { recursive: true });\n\n const resp = await fetch(details.downloadUrl);\n if (!resp.ok) throw new Error(`bundle download -> ${resp.status}`);\n const bundle = Buffer.from(await resp.arrayBuffer());\n if (details.bundleSha256 && sha256b64(bundle) !== details.bundleSha256) {\n throw new Error(\n `bundle integrity check failed for ${slug}@${ref}: downloaded sha256 != recorded bundleSha256`,\n );\n }\n\n const files = extractBundle(bundle, dir);\n const branch = ref === \"latest\" || /^\\d|^[0-9a-f]{8,}$/.test(ref) ? DEFAULT_BRANCH : ref;\n writeLocalMeta(dir, {\n slug,\n ref,\n branch,\n versionId: details.versionId,\n contentHash: details.contentHash,\n semanticVersion: details.semanticVersion ?? undefined,\n baseFiles: snapshotTreeHashes(dir),\n });\n return { slug, dir, versionId: details.versionId, files };\n}\n\nexport async function propose(\n dir: string,\n opts: { title: string; reason: string; targetBranch?: string; options?: WorldsClientOptions },\n): Promise<{ proposalId: string }> {\n const meta = readLocalMeta(dir);\n if (!meta?.slug || !meta.baseFiles) {\n throw new Error(\"This dir has no pull/push base — run pull first, then edit, then propose.\");\n }\n const state = localTreeState(dir);\n if (state.clean) throw new Error(\"Nothing to propose — the tree matches its base.\");\n const changes = state.dirty.map((relPath) => {\n const abs = path.join(dir, relPath);\n if (!fs.existsSync(abs)) return { path: relPath, action: \"delete\" as const };\n return {\n path: relPath,\n action: \"write\" as const,\n newContent: fs.readFileSync(abs, \"utf-8\"),\n };\n });\n const res = await apiRequest<{ proposalId: string }>(\n opts.options ?? {},\n \"POST\",\n \"/api/public/benchmark-containers/proposals\",\n {\n slug: meta.slug,\n title: opts.title,\n changeReason: opts.reason,\n baseVersionId: meta.versionId,\n ...(opts.targetBranch ? { targetBranch: opts.targetBranch } : {}),\n changes,\n },\n );\n return res;\n}\n\nexport async function createRef(\n slug: string,\n name: string,\n kind: \"branch\" | \"tag\",\n versionId?: string,\n options: WorldsClientOptions = {},\n): Promise<{ name: string; kind: string; versionId: string }> {\n return apiRequest(options, \"POST\", \"/api/public/benchmark-containers/refs\", {\n slug,\n name,\n kind,\n ...(versionId ? { versionId } : {}),\n });\n}\n","/**\n * PR validation: push the checkout's world source, run it, gate on the graded\n * result — one composed call, because CI should not have to re-derive the\n * choreography from primitives.\n *\n * The differentiating property, stated so it stays true: validation runs the\n * PULL REQUEST'S OWN world source. The push files the checkout as a version on\n * the PR's branch (content-hash dedup makes re-runs cheap), the dispatch pins\n * that version, and the platform resolves the branch back to its open PR — so\n * the run page names the PR and the PR comment names the run. Nothing here\n * validates a standing deployment while pretending to validate the change.\n */\n\nimport {\n apiRequest,\n detectProvenance,\n listRunConfigs,\n waitForRun,\n type RunReport,\n type WorldsClientOptions,\n} from \"./index\";\nimport { push } from \"./hub\";\n\nexport type ValidatedRun = {\n model: string;\n runId: string;\n report: RunReport | null;\n /** Why this run fails the gate, or null when it passes. */\n failure: string | null;\n};\n\nexport type ValidateReport = {\n ok: boolean;\n slug: string;\n branch: string;\n versionId: string;\n contentHash: string;\n runConfig: { id: string; name: string };\n runs: ValidatedRun[];\n /** A PR-comment-ready summary of the whole validation. */\n markdown: string;\n};\n\nfunction fmtScore(score: number | null): string {\n return score === null ? \"no score\" : score.toFixed(3);\n}\n\nfunction buildMarkdown(\n report: Omit<ValidateReport, \"markdown\">,\n minScore: number | null,\n source?: { repoUrl?: string; commit?: string },\n): string {\n const lines: string[] = [];\n lines.push(\n `### World validation ${report.ok ? \"passed\" : \"failed\"} — \\`${report.slug}@${report.branch}\\``,\n );\n lines.push(\"\");\n // Name the exact source that ran: the commit on GitHub when we know it,\n // always the content hash the platform pinned.\n const commitLink =\n source?.repoUrl && source?.commit\n ? `[\\`${source.commit.slice(0, 12)}\\`](${source.repoUrl}/commit/${source.commit})`\n : null;\n lines.push(\n `Ran the pull request's own world source` +\n (commitLink ? ` (${commitLink} on \\`${report.branch}\\`` : ` (`) +\n `${commitLink ? \", \" : \"\"}pinned as \\`${report.contentHash.slice(0, 12)}\\`) ` +\n `through run config **${report.runConfig.name}**` +\n (minScore !== null ? `, gating at score ≥ ${minScore}.` : \".\"),\n );\n lines.push(\"\");\n lines.push(\"| Model | Status | Score | Run |\");\n lines.push(\"| --- | --- | ---: | --- |\");\n for (const run of report.runs) {\n const r = run.report;\n const link = r?.url ? `[open](${r.url})` : \"—\";\n const status = run.failure\n ? `❌ ${run.failure}`\n : `✅ ${r?.status ?? \"COMPLETED\"}`;\n lines.push(\n `| \\`${run.model}\\` | ${status} | ${fmtScore(r?.score ?? null)} | ${link} |`,\n );\n }\n const taskRows = report.runs.flatMap((run) =>\n (run.report?.samples ?? []).map((sample) => ({\n model: run.model,\n task: sample.task ?? \"?\",\n reward: sample.reward,\n })),\n );\n // Every scenario, in the open: a validation whose per-scenario grades hide\n // behind a fold reads as one opaque number. Fold only when the table is\n // genuinely long.\n if (taskRows.length > 0) {\n const fold = taskRows.length > 12;\n lines.push(\"\");\n if (fold) {\n lines.push(\n `<details><summary>Per-scenario rewards (${taskRows.length})</summary>`,\n );\n lines.push(\"\");\n } else {\n lines.push(`**Scenarios (${taskRows.length})**`);\n lines.push(\"\");\n }\n lines.push(\"| Scenario | Model | Reward |\");\n lines.push(\"| --- | --- | ---: |\");\n for (const row of taskRows) {\n lines.push(\n `| ${row.task} | \\`${row.model}\\` | ${row.reward === null ? \"no score\" : row.reward.toFixed(2)} |`,\n );\n }\n if (fold) {\n lines.push(\"\");\n lines.push(\"</details>\");\n }\n }\n return lines.join(\"\\n\");\n}\n\n/**\n * Push `dir` on the current (or given) branch, dispatch the named run config\n * against the pushed version, wait for every run, and gate.\n *\n * The gate: every dispatch accepted, every run terminal COMPLETED, and — when\n * `minScore` is set — every run's score meets it. A run with NO score fails a\n * score gate rather than passing it: null is \"not scored\", never 0 and never\n * fine.\n */\nexport async function validateWorld(\n dir: string,\n opts: {\n slug?: string;\n runConfig: string;\n branch?: string;\n minScore?: number | null;\n timeoutMinutes?: number;\n onProgress?: (line: string) => void;\n options?: WorldsClientOptions;\n },\n): Promise<ValidateReport> {\n const options = opts.options ?? {};\n const progress = opts.onProgress ?? (() => {});\n const minScore = opts.minScore ?? null;\n\n const provenance = detectProvenance();\n const branch = opts.branch ?? provenance.branch;\n if (!branch)\n throw new Error(\n \"No branch to validate on: pass --branch or run inside a git checkout / GitHub Actions.\",\n );\n\n progress(`pushing ${dir} as ${opts.slug ?? \"(pyproject name)\"}@${branch}…`);\n // CI checkouts carry no local push meta, so a re-validation would 409\n // against the branch tip its own previous run created. Validation's\n // semantics are \"this branch's tip BECOMES the PR's source\": resolve the\n // current tip and push on top of it. A branch that does not exist yet\n // resolves to no base, which is a fresh branch — also correct.\n let tipVersionId: string | null = null;\n if (opts.slug) {\n try {\n const tip = await apiRequest<{ versionId?: string }>(\n options,\n \"POST\",\n \"/api/public/benchmark-containers/resolve-version\",\n { slug: opts.slug, ref: branch },\n );\n tipVersionId = tip.versionId ?? null;\n } catch {\n tipVersionId = null;\n }\n }\n const pushed = await push(dir, {\n slug: opts.slug,\n branch,\n baseVersionId: tipVersionId,\n message: `PR validation push (${provenance.commit?.slice(0, 12) ?? \"local\"})`,\n ...(provenance.actor?.name ? { author: provenance.actor.name } : {}),\n options,\n });\n progress(`pushed version ${pushed.versionId} (${pushed.contentHash.slice(0, 12)})`);\n\n // Resolve the run config by name (the stable handle CI configures) or id.\n const configs = await listRunConfigs(options);\n const runConfig =\n configs.find((c) => c.id === opts.runConfig) ??\n configs.find((c) => c.name === opts.runConfig);\n if (!runConfig) {\n const known = configs.map((c) => c.name).join(\", \") || \"(none)\";\n throw new Error(\n `Run config \"${opts.runConfig}\" not found in this project. Have: ${known}`,\n );\n }\n\n progress(`dispatching run config \"${runConfig.name}\" (${runConfig.models.join(\", \")})…`);\n const dispatched = await apiRequest<{\n versionLabel: string;\n runs: { model: string; runId: string; ok: boolean; error?: string }[];\n }>(options, \"POST\", \"/api/public/benchmark-containers/run-configs/dispatch\", {\n runConfigId: runConfig.id,\n versionId: pushed.versionId,\n ...provenance,\n });\n\n // The run's platform page. New deployments return it on the run report\n // (`url`); against an older deployment we build the same page from the\n // evaluation id, because a PR comment that cannot link the run defeats\n // the point of the comment.\n const host = (\n options.host ??\n process.env.GATEWAY_HOST ??\n \"https://withgateway.ai\"\n ).replace(/\\/+$/, \"\");\n let projectId: string | null = null;\n try {\n const projects = await apiRequest<{ data?: { id?: string }[] }>(\n options,\n \"GET\",\n \"/api/public/projects\",\n );\n projectId = projects.data?.[0]?.id ?? null;\n } catch {\n projectId = null;\n }\n const fallbackUrl = (report: RunReport): string | null => {\n if (report.url) return report.url;\n const evaluationId = report.evaluations[0]?.id;\n return projectId && evaluationId\n ? `${host}/project/${projectId}/environment/runs/${encodeURIComponent(evaluationId)}`\n : null;\n };\n\n const runs: ValidatedRun[] = [];\n for (const run of dispatched.runs) {\n if (!run.ok) {\n runs.push({\n model: run.model,\n runId: run.runId,\n report: null,\n failure: `dispatch failed: ${run.error ?? \"unknown error\"}`,\n });\n continue;\n }\n progress(`waiting on ${run.model} (run ${run.runId})…`);\n let report: RunReport | null = null;\n let failure: string | null = null;\n try {\n report = await waitForRun(run.runId, {\n timeoutMinutes: opts.timeoutMinutes ?? 45,\n options,\n onTick: (r) =>\n progress(\n `…${run.model}: ${r.status.toLowerCase()} (${r.shardsCompleted ?? 0}/${r.parallelism} shards)`,\n ),\n });\n report = { ...report, url: fallbackUrl(report) };\n if (report.status.toUpperCase() !== \"COMPLETED\") {\n failure = report.status;\n } else if (minScore !== null) {\n if (report.score === null) failure = \"completed without a score\";\n else if (report.score < minScore)\n failure = `score ${fmtScore(report.score)} < ${minScore}`;\n }\n } catch (error) {\n failure = error instanceof Error ? error.message : String(error);\n }\n runs.push({ model: run.model, runId: run.runId, report, failure });\n }\n\n const base = {\n ok: runs.length > 0 && runs.every((r) => r.failure === null),\n slug: pushed.slug,\n branch,\n versionId: pushed.versionId,\n contentHash: pushed.contentHash,\n runConfig: { id: runConfig.id, name: runConfig.name },\n runs,\n };\n return {\n ...base,\n markdown: buildMarkdown(base, minScore, {\n repoUrl: provenance.repoUrl,\n commit: provenance.commit,\n }),\n };\n}\n","/**\n * Worlds from TypeScript: identity, tasks, and HOSTED execution.\n *\n * The same three-level model as the Python SDK — WorldSet → Task — with one\n * deliberate difference: a world's tools are Python modules, so TypeScript\n * does not materialize task environments in-process. What a TS agent\n * codebase needs is exactly what this module provides: resolve a world ref\n * to its pinned version, read its task list, and dispatch HOSTED runs\n * (parallelism included) that execute the world server-side and file graded,\n * version-pinned rollouts. Local in-process execution stays a Python\n * capability by design, not by omission.\n */\n\nexport type WorldsClientOptions = {\n host?: string;\n publicKey?: string;\n secretKey?: string;\n};\n\nexport type ResolvedWorldVersion = {\n versionId: string;\n semanticVersion: string | null;\n contentHash: string;\n state?: string;\n};\n\nexport type WorldTaskInfo = {\n name: string;\n variant: string | null;\n};\n\nexport type DispatchedRun = {\n model: string;\n runId: string;\n ok: boolean;\n error?: string;\n};\n\nfunction resolveEnv(options: WorldsClientOptions) {\n const host =\n options.host ?? process.env.GATEWAY_HOST ?? \"https://withgateway.ai\";\n const publicKey = options.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;\n const secretKey = options.secretKey ?? process.env.GATEWAY_SECRET_KEY;\n if (!publicKey || !secretKey) {\n throw new Error(\n \"Gateway keys missing: set GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY \" +\n \"(or pass publicKey/secretKey).\",\n );\n }\n return { host: host.replace(/\\/+$/, \"\"), publicKey, secretKey };\n}\n\n/** Authenticated JSON request against the platform API — the primitive the\n * worlds helpers and the TS CLI share. */\nexport async function apiRequest<T>(\n options: WorldsClientOptions,\n method: \"GET\" | \"POST\" | \"PUT\" | \"DELETE\",\n path: string,\n body?: unknown,\n): Promise<T> {\n const { host, publicKey, secretKey } = resolveEnv(options);\n const res = await fetch(`${host}${path}`, {\n method,\n headers: {\n \"content-type\": \"application/json\",\n authorization:\n \"Basic \" + Buffer.from(`${publicKey}:${secretKey}`).toString(\"base64\"),\n },\n ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n });\n const text = await res.text();\n if (!res.ok) {\n throw new Error(\n `${method} ${path} -> ${res.status}: ${text.slice(0, 400)}`,\n );\n }\n return JSON.parse(text) as T;\n}\n\n/** Set (or rotate) one environment secret — write-only: no API returns it. */\nexport async function setEnvSecret(\n slug: string,\n key: string,\n value: string,\n options: WorldsClientOptions = {},\n): Promise<{ key: string; created: boolean }> {\n return apiRequest(\n options,\n \"PUT\",\n \"/api/public/benchmark-containers/secrets\",\n {\n slug,\n key,\n value,\n },\n );\n}\n\n/** Keys and rotation timestamps only — never values. */\nexport async function listEnvSecretKeys(\n slug: string,\n options: WorldsClientOptions = {},\n): Promise<{ key: string; updatedAt: string }[]> {\n const res = await apiRequest<{\n secrets: { key: string; updatedAt: string }[];\n }>(\n options,\n \"GET\",\n `/api/public/benchmark-containers/secrets?slug=${encodeURIComponent(slug)}`,\n );\n return res.secrets;\n}\n\nexport async function deleteEnvSecret(\n slug: string,\n key: string,\n options: WorldsClientOptions = {},\n): Promise<void> {\n await apiRequest(\n options,\n \"DELETE\",\n \"/api/public/benchmark-containers/secrets\",\n {\n slug,\n key,\n },\n );\n}\n\nexport type RunConfigSummary = {\n id: string;\n name: string;\n runType: string;\n createdAt: string;\n models: string[];\n parallelism: number;\n autoRunOnPush: boolean;\n agent: string | null;\n};\n\n/** Run configs in the project. CI resolves by NAME and dispatches by id. */\nexport async function listRunConfigs(\n options: WorldsClientOptions = {},\n): Promise<RunConfigSummary[]> {\n const res = await apiRequest<{ runConfigs: RunConfigSummary[] }>(\n options,\n \"GET\",\n \"/api/public/benchmark-containers/run-configs\",\n );\n return res.runConfigs;\n}\n\nexport type RunReport = {\n id: string;\n status: string;\n terminal: boolean;\n score: number | null;\n summary: string | null;\n model: string | null;\n versionLabel: string | null;\n parallelism: number;\n shardsCompleted: number | null;\n /** The run's page on the platform — what a PR comment should link. */\n url: string | null;\n evaluations: {\n id: string;\n status: string;\n avgReward: number | null;\n url: string | null;\n }[];\n samples: {\n task: string | null;\n reward: number | null;\n rewards: Record<string, unknown>;\n sessionId: string | null;\n }[];\n};\n\n/** The read half of dispatch: status, score, per-shard evaluations, and\n * per-task rewards — everything a CI gate needs. */\nexport async function getRun(\n runId: string,\n options: WorldsClientOptions = {},\n): Promise<RunReport> {\n return apiRequest(\n options,\n \"GET\",\n `/api/public/benchmark-containers/runs/${encodeURIComponent(runId)}`,\n );\n}\n\n/** Poll a run to terminal (default every 20s, up to `timeoutMinutes`). */\nexport async function waitForRun(\n runId: string,\n opts: {\n timeoutMinutes?: number;\n intervalSeconds?: number;\n onTick?: (run: RunReport) => void;\n options?: WorldsClientOptions;\n } = {},\n): Promise<RunReport> {\n const deadline = Date.now() + (opts.timeoutMinutes ?? 45) * 60_000;\n for (;;) {\n const run = await getRun(runId, opts.options ?? {});\n if (run.terminal) return run;\n if (Date.now() > deadline)\n throw new Error(\n `Run ${runId} still ${run.status} after the wait timeout.`,\n );\n opts.onTick?.(run);\n await new Promise((resolve) =>\n setTimeout(resolve, (opts.intervalSeconds ?? 20) * 1000),\n );\n }\n}\n\nexport type RunProvenance = {\n branch?: string;\n commit?: string;\n repoUrl?: string;\n actor?: { id?: string; name?: string; imageUrl?: string; kind?: string };\n};\n\n/**\n * Where a dispatch comes from, DETECTED rather than configured: the CI\n * checkout's branch/commit/actor under GitHub Actions, else the developer's\n * own git checkout. A run nobody can trace to a branch is a score with no\n * code attached, so every dispatch carries this unless overridden.\n */\nexport function detectProvenance(): RunProvenance {\n const env =\n (globalThis as { process?: { env?: Record<string, string | undefined> } })\n .process?.env ?? {};\n const out: RunProvenance = {};\n const ref = env.GITHUB_HEAD_REF || env.GITHUB_REF_NAME;\n if (ref) out.branch = ref;\n if (env.GITHUB_SHA) out.commit = env.GITHUB_SHA;\n const server = env.GITHUB_SERVER_URL ?? \"https://github.com\";\n if (env.GITHUB_REPOSITORY) out.repoUrl = `${server}/${env.GITHUB_REPOSITORY}`;\n if (env.GITHUB_ACTOR) {\n out.actor = {\n kind: \"ci\",\n id: env.GITHUB_ACTOR,\n name: env.GITHUB_ACTOR,\n // GitHub serves every account's avatar at /<login>.png.\n imageUrl: `${server}/${env.GITHUB_ACTOR}.png`,\n };\n }\n if (!out.branch || !out.commit) {\n try {\n const { execFileSync } =\n require(\"node:child_process\") as typeof import(\"node:child_process\");\n const git = (args: string[]) =>\n execFileSync(\"git\", args, {\n encoding: \"utf-8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n })\n .toString()\n .trim();\n out.branch = out.branch ?? git([\"rev-parse\", \"--abbrev-ref\", \"HEAD\"]);\n out.commit = out.commit ?? git([\"rev-parse\", \"HEAD\"]);\n if (!out.repoUrl) {\n const remote = git([\"config\", \"--get\", \"remote.origin.url\"]);\n if (remote) out.repoUrl = remote.replace(/\\.git$/, \"\");\n }\n if (!out.actor) {\n const name = git([\"config\", \"--get\", \"user.name\"]);\n if (name) out.actor = { kind: \"user\", name };\n }\n } catch {\n // No git here — dispatch without provenance rather than failing.\n }\n }\n return out;\n}\n\n/** One scenario of a world, as data. */\nexport class WorldTask {\n constructor(\n readonly world: WorldSet,\n readonly name: string,\n readonly variant: string | null,\n ) {}\n}\n\n/**\n * THE world, from a TS process: pinned identity + its tasks + hosted runs.\n *\n * const world = await openWorld(\"google-drive-sim@main\");\n * console.log(world.version.semanticVersion, world.tasks.length);\n * const runs = await world.dispatch(runConfigId);\n */\nexport class WorldSet {\n constructor(\n readonly slugRef: string,\n readonly slug: string,\n readonly ref: string | null,\n readonly version: ResolvedWorldVersion,\n public tasks: WorldTask[],\n private readonly options: WorldsClientOptions,\n ) {}\n\n task(variant: string): WorldTask {\n const hit = this.tasks.find(\n (t) => t.variant === variant || t.name.includes(variant),\n );\n if (!hit) {\n const known = this.tasks.map((t) => t.variant ?? t.name).join(\", \");\n throw new Error(`no task matches ${variant}; have: ${known}`);\n }\n return hit;\n }\n\n /**\n * Open a LIVE session against one of this world's tasks: the platform boots\n * (or reuses) a warm container, and your agent calls its tools through the\n * platform. See worlds/session.ts.\n */\n async open(\n task: string,\n opts: { reuseWarm?: boolean } = {},\n ): Promise<import(\"./session\").WorldSession> {\n const { openSession } = await import(\"./session\");\n return openSession(this.slug, task, {\n versionId: this.version.versionId,\n reuseWarm: opts.reuseWarm,\n options: this.options,\n });\n }\n\n /**\n * Start a HOSTED run of a run config against this world — the platform\n * executes the (Python) world in parallel containers per the config's\n * `parallelism` and files one graded run per model. Returns those runs.\n */\n async dispatch(\n runConfigId: string,\n opts: {\n containerId?: string;\n versionId?: string;\n /** Override the auto-detected branch/commit/actor. */\n provenance?: RunProvenance;\n } = {},\n ): Promise<{ versionLabel: string; runs: DispatchedRun[] }> {\n const provenance = opts.provenance ?? detectProvenance();\n return apiRequest(\n this.options,\n \"POST\",\n \"/api/public/benchmark-containers/run-configs/dispatch\",\n {\n runConfigId,\n ...(opts.containerId ? { containerId: opts.containerId } : {}),\n versionId: opts.versionId ?? this.version.versionId,\n ...provenance,\n },\n );\n }\n}\n\n/**\n * Resolve `slug` / `slug@branch|tag|semver|hash` to its pinned version and\n * task list. The task list comes from the version's file manifest\n * (`tasks/<name>/task.toml`), so it needs no bundle download.\n */\nexport async function openWorld(\n slugRef: string,\n options: WorldsClientOptions = {},\n): Promise<WorldSet> {\n const at = slugRef.indexOf(\"@\");\n const slug = at === -1 ? slugRef : slugRef.slice(0, at);\n const ref = at === -1 ? null : slugRef.slice(at + 1);\n\n const version = await apiRequest<\n ResolvedWorldVersion & { taskNames?: string[] }\n >(options, \"POST\", \"/api/public/benchmark-containers/resolve-version\", {\n slug,\n ...(ref ? { ref } : {}),\n });\n\n const world = new WorldSet(\n slugRef,\n slug,\n ref,\n {\n versionId: version.versionId,\n semanticVersion: version.semanticVersion ?? null,\n contentHash: version.contentHash,\n state: version.state,\n },\n [],\n options,\n );\n for (const name of version.taskNames ?? []) {\n const variant = /^[a-z0-9]+-([a-z0-9]+)-/.exec(name)?.[1] ?? null;\n world.tasks.push(new WorldTask(world, name, variant));\n }\n return world;\n}\n\n// The session surface completes the worlds module, so `@withgateway/sdk/worlds`\n// carries both halves: running a world locally, and driving one the platform\n// hosts. (session.ts imports apiRequest from here; the cycle is function-level\n// only, and the build below is what proves it resolves.)\nexport * from \"./session\";\n\n// The hub half: push, pull, propose and the content-hash primitives the CLI\n// runs on. These were reachable only from inside the package, so a consumer\n// could drive a world but never publish one.\nexport * from \"./hub\";\n\n// PR validation: push-dispatch-wait-gate as one composed call, for CI.\nexport * from \"./validate\";\n","#!/usr/bin/env node\n/**\n * The TypeScript `gateway` CLI — full command parity with the Python CLI's\n * `bench` family, including the working-dir workflows (push/pull/checkout/\n * status/branch/tag/propose — see worlds/hub.ts and its LOCKSTEP WARNING on\n * the content hash). The one Python-only command is `eval`: it runs the\n * world locally on the Python engines, which a JS process cannot host —\n * hosted runs via `dispatch` are the equivalent.\n *\n * Auth: GATEWAY_HOST + GATEWAY_PUBLIC_KEY + GATEWAY_SECRET_KEY, same env as\n * the library.\n */\nimport * as fs from \"node:fs\";\n\nimport {\n apiRequest,\n deleteEnvSecret,\n getRun,\n listEnvSecretKeys,\n listRunConfigs,\n openWorld,\n setEnvSecret,\n waitForRun,\n} from \"./worlds/index\";\nimport {\n computeContentHash,\n createRef,\n localTreeState,\n propose,\n pull,\n push,\n} from \"./worlds/hub\";\nimport { validateWorld } from \"./worlds/validate\";\n\ntype Flags = Record<string, string | boolean>;\n\nfunction parseArgv(argv: string[]): { positional: string[]; flags: Flags } {\n const positional: string[] = [];\n const flags: Flags = {};\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i];\n if (arg.startsWith(\"--\")) {\n const key = arg.slice(2);\n const next = argv[i + 1];\n if (next !== undefined && !next.startsWith(\"--\")) {\n flags[key] = next;\n i++;\n } else {\n flags[key] = true;\n }\n } else {\n positional.push(arg);\n }\n }\n return { positional, flags };\n}\n\nfunction str(flags: Flags, key: string): string | undefined {\n const value = flags[key];\n return typeof value === \"string\" ? value : undefined;\n}\n\nfunction fail(message: string): never {\n console.error(message);\n process.exit(2);\n}\n\nconst PYTHON_ONLY = new Set([\"eval\"]);\n\nconst HELP = `gateway bench <command> — worlds from TypeScript\n\n resolve <slug[@ref]> pinned version + task count\n tasks <slug[@ref]> the task list\n dispatch <runConfigId> [--container-id X] [--version-id Y]\n run <runId> [--wait] [--timeout-min N] status, score, per-task rewards\n run-configs list\n run-configs create --name N --models a,b [--parallelism K] [--tasks t1,t2] [--agent A] [--auto-run-on-push] [--id existing]\n run-configs delete --id X\n secrets set --env <slug> --key K [--value V] (omit --value to read stdin)\n secrets list --env <slug>\n secrets unset --env <slug> --key K\n refs <slug> branches and tags\n log <slug> [--branch B] [--limit N] version history\n proposals <slug> [--status open|applied|dismissed]\n\n pull <slug[@ref]> [--dir D] materialize a working dir\n push [dir] [--slug S] [--branch B] [--force] [--message M]\n validate [dir] --run-config NAME [--slug S] [--branch B] [--min-score X]\n [--summary-file F] [--timeout-min N]\n push this checkout, run it, gate — the PR-validation entry\n checkout <slug@ref> --dir D re-aim an existing working dir\n status [dir] clean/dirty vs base + hash check\n branch <slug> <name> [--version-id V] create a branch\n tag <slug> <name> [--version-id V] create a tag\n propose [dir] --title T --reason R [--target-branch B]\n\n eval (local engine runs) is Python-only — run hosted via 'dispatch'.\n\nAuth: GATEWAY_HOST, GATEWAY_PUBLIC_KEY, GATEWAY_SECRET_KEY.`;\n\nasync function readStdin(): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) chunks.push(chunk as Buffer);\n return Buffer.concat(chunks).toString(\"utf-8\").trim();\n}\n\nasync function main(): Promise<number> {\n const [group, command, ...rest] = process.argv.slice(2);\n if (!group || group === \"help\" || group === \"--help\") {\n console.log(HELP);\n return 0;\n }\n if (group !== \"bench\") {\n fail(\n `Unknown command group '${group}' — this CLI covers 'gateway bench'. Run 'gateway help'.`,\n );\n }\n if (!command) fail(HELP);\n if (PYTHON_ONLY.has(command)) {\n fail(\n `'gateway bench eval' runs the world locally on the PYTHON engines (verifiers/harbor) — it cannot exist in a JS process.\\n` +\n `Run hosted instead: gateway bench dispatch <runConfigId> — same worlds, graded on the platform.`,\n );\n }\n\n const { positional, flags } = parseArgv(rest);\n\n switch (command) {\n case \"resolve\": {\n const slugRef =\n positional[0] ?? fail(\"usage: gateway bench resolve <slug[@ref]>\");\n const world = await openWorld(slugRef);\n console.log(\n `${world.slug}@${world.ref ?? \"latest\"}: ${world.version.semanticVersion ?? \"-\"} ` +\n `(${world.version.contentHash.slice(0, 12)}) · ${world.version.state ?? \"?\"} · ${world.tasks.length} tasks`,\n );\n console.log(`versionId: ${world.version.versionId}`);\n return 0;\n }\n case \"tasks\": {\n const slugRef =\n positional[0] ?? fail(\"usage: gateway bench tasks <slug[@ref]>\");\n const world = await openWorld(slugRef);\n if (world.tasks.length === 0) {\n console.log(\"No task manifest served for this version.\");\n return 0;\n }\n for (const task of world.tasks) {\n console.log(`${task.name}${task.variant ? ` (${task.variant})` : \"\"}`);\n }\n return 0;\n }\n case \"dispatch\": {\n const runConfigId =\n positional[0] ?? fail(\"usage: gateway bench dispatch <runConfigId>\");\n const body: Record<string, string> = { runConfigId };\n const containerId = str(flags, \"container-id\");\n const versionId = str(flags, \"version-id\");\n if (containerId) body.containerId = containerId;\n if (versionId) body.versionId = versionId;\n const result = await apiRequest<{\n versionLabel: string;\n runs: { model: string; runId: string; ok: boolean; error?: string }[];\n }>(\n {},\n \"POST\",\n \"/api/public/benchmark-containers/run-configs/dispatch\",\n body,\n );\n for (const run of result.runs) {\n console.log(\n `${run.model}: ${run.ok ? \"dispatched\" : `FAILED: ${run.error}`} run=${run.runId}`,\n );\n }\n console.log(`-> ${result.versionLabel}`);\n return result.runs.every((r) => r.ok) ? 0 : 1;\n }\n case \"run\": {\n const runId =\n positional[0] ?? fail(\"usage: gateway bench run <runId> [--wait]\");\n const report = flags.wait\n ? await waitForRun(runId, {\n timeoutMinutes: Number(str(flags, \"timeout-min\") ?? 45),\n onTick: (r) =>\n console.error(\n `…${r.status.toLowerCase()} (${r.shardsCompleted ?? 0}/${r.parallelism} shards)`,\n ),\n })\n : await getRun(runId);\n console.log(\n `${report.id} ${report.status}${report.score !== null ? ` score=${report.score.toFixed(3)}` : \"\"}` +\n ` (${report.model ?? \"?\"} · ${report.versionLabel ?? \"?\"} · x${report.parallelism})`,\n );\n for (const sample of report.samples) {\n const subs = Object.entries(sample.rewards)\n .filter(([, v]) => typeof v === \"number\")\n .map(([k, v]) => `${k}=${(v as number).toFixed(2)}`)\n .join(\" \");\n console.log(\n ` ${(sample.reward ?? 0).toFixed(2)} ${sample.task ?? \"?\"}${subs ? ` [${subs}]` : \"\"}`,\n );\n }\n if (report.summary) console.log(` ${report.summary}`);\n return report.terminal && report.status.toUpperCase() === \"COMPLETED\"\n ? 0\n : 1;\n }\n case \"run-configs\": {\n const action = positional[0] ?? \"list\";\n if (action === \"list\") {\n const rows = await listRunConfigs();\n if (rows.length === 0) {\n console.log(\"No run configs in this project.\");\n return 0;\n }\n for (const row of rows) {\n const extras = [\n row.parallelism > 1 ? `x${row.parallelism} containers` : null,\n row.autoRunOnPush ? \"auto-on-push\" : null,\n ].filter(Boolean);\n console.log(\n `${row.id} ${row.name} (${row.models.join(\", \") || \"no models\"})${extras.length ? ` [${extras.join(\", \")}]` : \"\"}`,\n );\n }\n return 0;\n }\n if (action === \"delete\") {\n const id = str(flags, \"id\") ?? fail(\"--id is required for delete\");\n await apiRequest(\n {},\n \"DELETE\",\n \"/api/public/benchmark-containers/run-configs\",\n { id },\n );\n console.log(`Deleted ${id}.`);\n return 0;\n }\n if (action !== \"create\")\n fail(\"run-configs actions: list | create | delete\");\n const name = str(flags, \"name\") ?? fail(\"--name is required for create\");\n const models = (\n str(flags, \"models\") ?? fail(\"--models is required for create\")\n )\n .split(\",\")\n .map((m) => m.trim())\n .filter(Boolean);\n const body: Record<string, unknown> = { name, models };\n const parallelism = str(flags, \"parallelism\");\n if (parallelism) body.parallelism = Number(parallelism);\n const agent = str(flags, \"agent\");\n if (agent) body.agent = agent;\n const tasks = str(flags, \"tasks\");\n if (tasks)\n body.taskNames = tasks\n .split(\",\")\n .map((t) => t.trim())\n .filter(Boolean);\n if (flags[\"auto-run-on-push\"]) body.autoRunOnPush = true;\n const id = str(flags, \"id\");\n if (id) body.id = id;\n const row = await apiRequest<{\n id: string;\n name: string;\n models: string[];\n }>({}, \"POST\", \"/api/public/benchmark-containers/run-configs\", body);\n console.log(`${row.id} ${row.name} (${row.models.join(\", \")})`);\n return 0;\n }\n case \"secrets\": {\n const action =\n positional[0] ?? fail(\"secrets actions: set | list | unset\");\n const env = str(flags, \"env\") ?? fail(\"--env <world slug> is required\");\n if (action === \"list\") {\n const rows = await listEnvSecretKeys(env);\n if (rows.length === 0) {\n console.log(`No secrets on ${env}.`);\n return 0;\n }\n for (const row of rows)\n console.log(`${row.key} (rotated ${row.updatedAt})`);\n return 0;\n }\n const key = str(flags, \"key\") ?? fail(`--key is required for ${action}`);\n if (action === \"unset\") {\n await deleteEnvSecret(env, key);\n console.log(`Deleted ${key} from ${env}.`);\n return 0;\n }\n if (action !== \"set\") fail(\"secrets actions: set | list | unset\");\n const value = str(flags, \"value\") ?? (await readStdin());\n if (!value)\n fail(\"empty value — nothing stored (pass --value or pipe stdin)\");\n const res = await setEnvSecret(env, key, value);\n console.log(\n `${res.created ? \"Added\" : \"Rotated\"} ${key} on ${env} — next hosted run receives it.`,\n );\n return 0;\n }\n case \"refs\": {\n const slug = positional[0] ?? fail(\"usage: gateway bench refs <slug>\");\n const res = await apiRequest<{\n refs: {\n name: string;\n kind: string;\n semanticVersion: string | null;\n contentHash: string | null;\n state: string | null;\n }[];\n }>(\n {},\n \"GET\",\n `/api/public/benchmark-containers/refs?slug=${encodeURIComponent(slug)}`,\n );\n for (const ref of res.refs) {\n console.log(\n `${ref.kind === \"tag\" ? \"tag \" : \"branch\"} ${ref.name} ${ref.semanticVersion ?? \"-\"} (${ref.contentHash?.slice(0, 12) ?? \"?\"}) ${ref.state ?? \"\"}`,\n );\n }\n return 0;\n }\n case \"log\": {\n const slug = positional[0] ?? fail(\"usage: gateway bench log <slug>\");\n const params = new URLSearchParams({ slug });\n const branch = str(flags, \"branch\");\n if (branch) params.set(\"branch\", branch);\n const limit = str(flags, \"limit\");\n if (limit) params.set(\"limit\", limit);\n const res = await apiRequest<{\n branch: string;\n entries: {\n versionId: string;\n contentHash: string;\n semanticVersion: string | null;\n state: string;\n author: string | null;\n changeReason: string | null;\n }[];\n }>(\n {},\n \"GET\",\n `/api/public/benchmark-containers/log?${params.toString()}`,\n );\n console.log(`branch: ${res.branch}`);\n for (const entry of res.entries) {\n console.log(\n `${entry.contentHash.slice(0, 12)} ${entry.semanticVersion ?? \"-\"} ${entry.state}` +\n `${entry.author ? ` by ${entry.author}` : \"\"}${entry.changeReason ? ` — ${entry.changeReason}` : \"\"}`,\n );\n }\n return 0;\n }\n case \"proposals\": {\n const slug =\n positional[0] ?? fail(\"usage: gateway bench proposals <slug>\");\n const params = new URLSearchParams({ slug });\n const status = str(flags, \"status\");\n if (status) params.set(\"status\", status);\n const res = await apiRequest<{\n proposals: {\n id: string;\n title?: string | null;\n status: string;\n createdAt?: string;\n }[];\n }>(\n {},\n \"GET\",\n `/api/public/benchmark-containers/proposals?${params.toString()}`,\n );\n if (res.proposals.length === 0) {\n console.log(\"No proposals.\");\n return 0;\n }\n for (const proposal of res.proposals) {\n console.log(\n `${proposal.id} [${proposal.status}] ${proposal.title ?? \"\"}`,\n );\n }\n return 0;\n }\n case \"pull\": {\n const slugRef =\n positional[0] ??\n fail(\"usage: gateway bench pull <slug[@ref]> [--dir D]\");\n const res = await pull(slugRef, str(flags, \"dir\"));\n console.log(\n `Pulled ${res.slug} -> ${res.dir} (${res.files} files, version ${res.versionId})`,\n );\n return 0;\n }\n case \"checkout\": {\n const slugRef =\n positional[0] ??\n fail(\"usage: gateway bench checkout <slug@ref> --dir D\");\n const dir =\n str(flags, \"dir\") ??\n fail(\"--dir is required for checkout (the working dir to re-aim)\");\n const res = await pull(slugRef, dir);\n console.log(\n `Checked out ${slugRef} into ${res.dir} (${res.files} files)`,\n );\n return 0;\n }\n case \"push\": {\n const dir = positional[0] ?? \".\";\n const res = await push(dir, {\n slug: str(flags, \"slug\"),\n branch: str(flags, \"branch\"),\n force: Boolean(flags.force),\n message: str(flags, \"message\"),\n author: str(flags, \"author\"),\n });\n console.log(\n `Pushed ${res.slug}@${res.branch}: version ${res.versionId} (${res.contentHash.slice(0, 12)})`,\n );\n return 0;\n }\n case \"validate\": {\n // The CI entry: push THIS checkout's world source on the PR's branch,\n // run it, gate on the graded result. Exit code is the check.\n const dir = positional[0] ?? \".\";\n const runConfig =\n str(flags, \"run-config\") ??\n fail(\n \"usage: gateway bench validate [dir] --run-config NAME [--slug S] [--branch B] [--min-score X] [--summary-file F] [--timeout-min N]\",\n );\n const minScoreRaw = str(flags, \"min-score\");\n const report = await validateWorld(dir, {\n slug: str(flags, \"slug\"),\n runConfig,\n branch: str(flags, \"branch\"),\n minScore: minScoreRaw === undefined ? null : Number(minScoreRaw),\n timeoutMinutes: Number(str(flags, \"timeout-min\") ?? 45),\n onProgress: (line) => console.error(line),\n });\n for (const run of report.runs) {\n console.log(\n `${run.model}: ${run.failure ? `FAIL — ${run.failure}` : \"pass\"}` +\n `${run.report?.score != null ? ` score=${run.report.score.toFixed(3)}` : \"\"}` +\n `${run.report?.url ? ` ${run.report.url}` : \"\"}`,\n );\n }\n // The markdown lands wherever the caller wants to publish it: a file\n // for a PR comment, and the step summary when GitHub provides one.\n const summaryFile = str(flags, \"summary-file\");\n if (summaryFile) fs.writeFileSync(summaryFile, report.markdown + \"\\n\");\n const stepSummary = process.env.GITHUB_STEP_SUMMARY;\n if (stepSummary) fs.appendFileSync(stepSummary, report.markdown + \"\\n\");\n console.log(report.ok ? \"validation passed\" : \"validation FAILED\");\n return report.ok ? 0 : 1;\n }\n case \"status\": {\n const dir = positional[0] ?? \".\";\n const state = localTreeState(dir);\n if (!state.meta) {\n console.log(\n \"Ad-hoc dir: no pull/push base recorded (.gateway missing).\",\n );\n return 0;\n }\n console.log(\n `base: ${state.meta.slug}@${state.meta.branch ?? \"?\"} version ${state.meta.versionId ?? \"?\"}`,\n );\n const localHash = computeContentHash(dir);\n const baseHash = state.meta.contentHash;\n console.log(\n `content hash: ${localHash.slice(0, 12)} ${localHash === baseHash ? \"== base (hash-verified)\" : `!= base ${String(baseHash).slice(0, 12)}`}`,\n );\n if (state.clean) {\n console.log(\"clean — tree matches its base.\");\n return 0;\n }\n console.log(`dirty (${state.dirty.length}):`);\n for (const p of state.dirty.slice(0, 40)) console.log(` ${p}`);\n return 0;\n }\n case \"branch\":\n case \"tag\": {\n const slug =\n positional[0] ?? fail(`usage: gateway bench ${command} <slug> <name>`);\n const name =\n positional[1] ?? fail(`usage: gateway bench ${command} <slug> <name>`);\n const ref = await createRef(\n slug,\n name,\n command as \"branch\" | \"tag\",\n str(flags, \"version-id\"),\n );\n console.log(`${ref.kind} ${ref.name} -> ${ref.versionId}`);\n return 0;\n }\n case \"propose\": {\n const dir = positional[0] ?? \".\";\n const title = str(flags, \"title\") ?? fail(\"--title is required\");\n const reason = str(flags, \"reason\") ?? fail(\"--reason is required\");\n const res = await propose(dir, {\n title,\n reason,\n targetBranch: str(flags, \"target-branch\"),\n });\n console.log(`Proposal ${res.proposalId} opened.`);\n return 0;\n }\n default:\n fail(`Unknown command 'bench ${command}'.\\n\\n${HELP}`);\n }\n}\n\nmain().then(\n (code) => process.exit(code),\n (error) => {\n console.error(error instanceof Error ? error.message : String(error));\n process.exit(1);\n },\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,IAAI,YAAY,IAAI,UAAU,UAAU;AAChD,aAAO;AAAA,IACT;AAAA,IACA;AACE,WAAK,0BAA0B,OAAO;AAAA;AAAA,EAAS,IAAI,EAAE;AAAA,EACzD;AACF;AAEA,KAAK,EAAE;AAAA,EACL,CAAC,SAAS,QAAQ,KAAK,IAAI;AAAA,EAC3B,CAAC,UAAU;AACT,YAAQ,MAAM,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AACpE,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF;","names":["openWorld","pad","resolve","path","resolve","openSession","fs","row","id"]}
1
+ {"version":3,"sources":["../src/cli/router.ts","../src/cli/config.ts","../src/cli/runtime/local.ts","../src/cli/runtime/client.ts","../src/worlds/browser.ts","../src/worlds/session.ts","../src/worlds/tasks.ts","../src/worlds/hub.ts","../src/worlds/validate.ts","../src/worlds/index.ts","../src/cli/runtime/data.ts","../src/cli/main.ts","../src/cli/platform/agent.ts","../src/cli/platform/shared.ts","../src/cli/platform/auth.ts","../src/cli/platform/bench.ts","../src/cli/platform/connector.ts","../src/cli/platform/skill.ts","../src/cli/platform/data.ts","../src/cli/platform/rows.ts","../src/cli/platform/worldData/batches.ts","../src/cli/platform/worldData/chunker.ts","../src/cli/platform/worldData/json.ts","../src/cli/platform/worldData/extract.ts","../src/cli/platform/worldData/rowSource.ts","../src/cli/platform/worldData/scanner.ts","../src/cli/platform/worldData/manifest.ts","../src/cli/platform/worldData/worldConfig.ts","../src/cli/platform/worldData/toml.ts","../src/cli/platform/dataset.ts","../src/cli/platform/environment.ts","../src/cli/platform/pythonOnly.ts","../src/cli/platform/release.ts","../src/cli/platform/run.ts","../src/cli/platform/secret.ts","../src/cli/platform/session.ts","../src/cli/platform/task.ts","../src/cli/platform/traces.ts","../src/cli/platform/worlds.ts","../src/cli/platform/index.ts","../src/cli/runtime/schema.ts","../src/cli/runtime/connector.ts","../src/cli/runtime/run.ts","../src/cli/runtime/serve.ts","../src/cli/runtime/test.ts","../src/cli/runtime/scaffold.ts","../src/cli/runtime/index.ts","../src/cli.ts"],"sourcesContent":["/**\n * The `gateway` command tree, with no dependency: groups hold commands, a\n * command declares its positionals and flags, help is generated from the\n * declarations so `gateway <group> --help` always matches what runs.\n *\n * Flags: `--name value`, `--name=value`, `--flag` (boolean), repeatable flags\n * collect into arrays when declared `repeat: true`. Anything after `--` is\n * positional.\n */\n\nexport type FlagSpec = {\n name: string;\n help: string;\n /** Short alias, e.g. \"m\" for --message. */\n short?: string;\n /** Boolean flags take no value. */\n boolean?: boolean;\n repeat?: boolean;\n default?: string | boolean;\n /** Environment variable that fills the flag when it is not given. */\n env?: string;\n};\n\nexport type PositionalSpec = {\n name: string;\n help: string;\n optional?: boolean;\n /** Collects every remaining positional. */\n variadic?: boolean;\n};\n\nexport type Parsed = {\n positionals: string[];\n flags: Record<string, string | boolean | string[] | undefined>;\n};\n\nexport type CommandSpec = {\n name: string;\n help: string;\n positionals?: PositionalSpec[];\n flags?: FlagSpec[];\n /** Long-form notes printed under the usage line in `--help`. */\n notes?: string;\n run: (args: Parsed, ctx: CommandContext) => Promise<number | void>;\n};\n\nexport type CommandContext = {\n stdout: (line: string) => void;\n stderr: (line: string) => void;\n /** Read all of stdin (for --value-less secrets, piped rows). */\n stdin: () => Promise<string>;\n /** Stdin as a stream, for inputs too large to hold (`worlds data import … -`). */\n stdinStream?: () => NodeJS.ReadableStream;\n};\n\nexport class CommandGroup {\n readonly groups = new Map<string, CommandGroup>();\n readonly commands = new Map<string, CommandSpec>();\n constructor(\n readonly name: string,\n readonly help: string,\n ) {}\n group(name: string, help: string): CommandGroup {\n const existing = this.groups.get(name);\n if (existing) return existing;\n const created = new CommandGroup(name, help);\n this.groups.set(name, created);\n return created;\n }\n command(spec: CommandSpec): this {\n this.commands.set(spec.name, spec);\n return this;\n }\n}\n\nexport class CliError extends Error {\n constructor(\n message: string,\n readonly exitCode = 2,\n ) {\n super(message);\n }\n}\n\nexport function parseArgs(spec: CommandSpec, argv: string[]): Parsed {\n const flagSpecs = spec.flags ?? [];\n const byName = new Map<string, FlagSpec>();\n for (const f of flagSpecs) {\n byName.set(f.name, f);\n if (f.short) byName.set(f.short, f);\n }\n const positionals: string[] = [];\n const flags: Parsed[\"flags\"] = {};\n let onlyPositionals = false;\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i]!;\n if (onlyPositionals || !arg.startsWith(\"-\") || arg === \"-\") {\n positionals.push(arg);\n continue;\n }\n if (arg === \"--\") {\n onlyPositionals = true;\n continue;\n }\n const bare = arg.replace(/^--?/, \"\");\n const [rawName, inlineValue] = bare.includes(\"=\")\n ? [bare.slice(0, bare.indexOf(\"=\")), bare.slice(bare.indexOf(\"=\") + 1)]\n : [bare, undefined];\n const f = byName.get(rawName);\n if (!f) throw new CliError(`Unknown flag --${rawName} for ${spec.name}`);\n if (f.boolean) {\n flags[f.name] =\n inlineValue === undefined ? true : inlineValue !== \"false\";\n continue;\n }\n let value = inlineValue;\n if (value === undefined) {\n const next = argv[i + 1];\n if (next === undefined || (next.startsWith(\"--\") && next.length > 2))\n throw new CliError(`--${f.name} needs a value`);\n value = next;\n i++;\n }\n if (f.repeat) {\n const current = flags[f.name];\n flags[f.name] = Array.isArray(current) ? [...current, value] : [value];\n } else flags[f.name] = value;\n }\n for (const f of flagSpecs) {\n if (flags[f.name] !== undefined) continue;\n const fromEnv = f.env ? process.env[f.env] : undefined;\n if (fromEnv !== undefined && fromEnv !== \"\") flags[f.name] = fromEnv;\n else if (f.default !== undefined) flags[f.name] = f.default;\n }\n const specs = spec.positionals ?? [];\n const required = specs.filter((p) => !p.optional && !p.variadic).length;\n if (positionals.length < required)\n throw new CliError(\n `${spec.name} needs ${specs\n .slice(0, required)\n .map((p) => `<${p.name}>`)\n .join(\" \")}`,\n );\n const variadic = specs.some((p) => p.variadic);\n if (!variadic && positionals.length > specs.length)\n throw new CliError(\n `${spec.name} takes ${specs.length} argument${specs.length === 1 ? \"\" : \"s\"}, got ${positionals.length}`,\n );\n return { positionals, flags };\n}\n\n/** Typed accessors so commands never repeat the narrowing. */\nexport const arg = {\n str(p: Parsed, name: string): string | undefined {\n const v = p.flags[name];\n return typeof v === \"string\" ? v : undefined;\n },\n bool(p: Parsed, name: string): boolean {\n return p.flags[name] === true;\n },\n list(p: Parsed, name: string): string[] {\n const v = p.flags[name];\n if (Array.isArray(v)) return v;\n return typeof v === \"string\" ? [v] : [];\n },\n int(p: Parsed, name: string): number | undefined {\n const v = arg.str(p, name);\n if (v === undefined) return undefined;\n const n = Number(v);\n if (!Number.isInteger(n))\n throw new CliError(`--${name} must be an integer`);\n return n;\n },\n};\n\nfunction usageLine(path: string[], spec: CommandSpec): string {\n const pos = (spec.positionals ?? [])\n .map((p) =>\n p.variadic\n ? `<${p.name}...>`\n : p.optional\n ? `[${p.name}]`\n : `<${p.name}>`,\n )\n .join(\" \");\n return `${path.join(\" \")} ${pos}`.trim();\n}\n\nexport function helpFor(\n path: string[],\n node: CommandGroup | CommandSpec,\n): string {\n if (node instanceof CommandGroup) {\n const lines = [`${path.join(\" \")} — ${node.help}`, \"\"];\n for (const [name, g] of node.groups)\n lines.push(` ${name.padEnd(16)} ${g.help}`);\n for (const [name, c] of node.commands)\n lines.push(` ${name.padEnd(16)} ${c.help}`);\n lines.push(\"\", `Run '${path.join(\" \")} <command> --help' for details.`);\n return lines.join(\"\\n\");\n }\n const lines = [usageLine(path, node), \"\", ` ${node.help}`];\n const pos = node.positionals ?? [];\n if (pos.length) {\n lines.push(\"\", \"Arguments:\");\n for (const p of pos) lines.push(` ${p.name.padEnd(18)} ${p.help}`);\n }\n const flags = node.flags ?? [];\n if (flags.length) {\n lines.push(\"\", \"Options:\");\n for (const f of flags) {\n const label = `--${f.name}${f.short ? `, -${f.short}` : \"\"}${f.boolean ? \"\" : \" <value>\"}`;\n const extras = [\n f.default !== undefined ? `default ${String(f.default)}` : null,\n f.env ? `env ${f.env}` : null,\n ]\n .filter(Boolean)\n .join(\", \");\n lines.push(\n ` ${label.padEnd(28)} ${f.help}${extras ? ` (${extras})` : \"\"}`,\n );\n }\n }\n if (node.notes) lines.push(\"\", node.notes);\n return lines.join(\"\\n\");\n}\n\n/** Walk the tree and run: exit code 0 on success, 2 on usage error, 1 on failure. */\nexport async function dispatch(\n root: CommandGroup,\n argv: string[],\n ctx: CommandContext,\n): Promise<number> {\n let node: CommandGroup = root;\n const path = [root.name];\n let i = 0;\n while (i < argv.length) {\n const token = argv[i]!;\n if (token === \"--help\" || token === \"-h\") {\n ctx.stdout(helpFor(path, node));\n return 0;\n }\n const group = node.groups.get(token);\n if (group) {\n node = group;\n path.push(token);\n i++;\n continue;\n }\n const command = node.commands.get(token);\n if (command) {\n const rest = argv.slice(i + 1);\n if (rest.includes(\"--help\") || rest.includes(\"-h\")) {\n ctx.stdout(helpFor([...path, token], command));\n return 0;\n }\n try {\n const parsed = parseArgs(command, rest);\n const code = await command.run(parsed, ctx);\n return code ?? 0;\n } catch (error) {\n if (error instanceof CliError) {\n ctx.stderr(error.message);\n return error.exitCode;\n }\n ctx.stderr(error instanceof Error ? error.message : String(error));\n return 1;\n }\n }\n ctx.stderr(\n `Unknown command '${token}' under '${path.join(\" \")}'.\\n\\n${helpFor(path, node)}`,\n );\n return 2;\n }\n ctx.stdout(helpFor(path, node));\n return node === root ? 0 : 2;\n}\n","import * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\n\nimport { CliError } from \"./router\";\n\n/**\n * Where the CLI's credentials come from, in this order (the same as the\n * Python CLI): explicit --host, environment (GATEWAY_HOST, GATEWAY_PUBLIC_KEY,\n * GATEWAY_SECRET_KEY / GATEWAY_API_KEY), then ~/.gateway/config.json written\n * by `gateway auth login`.\n */\nexport type StoredConfig = {\n host?: string;\n public_key?: string;\n api_key?: string;\n};\n\nexport function configPath(): string {\n return path.join(\n process.env.GATEWAY_CONFIG_DIR ?? path.join(os.homedir(), \".gateway\"),\n \"config.json\",\n );\n}\n\nexport function readConfig(): StoredConfig {\n try {\n return JSON.parse(fs.readFileSync(configPath(), \"utf8\")) as StoredConfig;\n } catch {\n return {};\n }\n}\n\nexport function writeConfig(config: StoredConfig): void {\n const file = configPath();\n fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });\n fs.writeFileSync(file, JSON.stringify(config, null, 2) + \"\\n\", { mode: 0o600 });\n}\n\nexport function clearConfig(): boolean {\n try {\n fs.unlinkSync(configPath());\n return true;\n } catch {\n return false;\n }\n}\n\nexport type Credentials = { host: string; publicKey: string; secretKey: string };\n\nexport function resolveCredentials(hostFlag?: string): Credentials {\n const stored = readConfig();\n const host = (hostFlag ?? process.env.GATEWAY_HOST ?? stored.host ?? \"\").replace(/\\/+$/, \"\");\n const publicKey = process.env.GATEWAY_PUBLIC_KEY ?? stored.public_key ?? \"\";\n const secretKey =\n process.env.GATEWAY_SECRET_KEY ?? process.env.GATEWAY_API_KEY ?? stored.api_key ?? \"\";\n if (!host)\n throw new CliError(\n \"Host not configured. Pass --host, set GATEWAY_HOST, or run `gateway auth login`.\",\n );\n if (!publicKey || !secretKey)\n throw new CliError(\n \"API key not configured. Set GATEWAY_PUBLIC_KEY and GATEWAY_SECRET_KEY, or run `gateway auth login`.\",\n );\n return { host, publicKey, secretKey };\n}\n\n/** One JSON request against the platform, Basic-authenticated with the project key. */\nexport async function api<T = unknown>(\n creds: Credentials,\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\",\n route: string,\n body?: unknown,\n init: { timeoutMs?: number } = {},\n): Promise<T> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), init.timeoutMs ?? 120_000);\n try {\n const res = await fetch(`${creds.host}${route}`, {\n method,\n headers: {\n \"content-type\": \"application/json\",\n accept: \"application/json\",\n authorization:\n \"Basic \" + Buffer.from(`${creds.publicKey}:${creds.secretKey}`).toString(\"base64\"),\n },\n ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n signal: controller.signal,\n });\n const text = await res.text();\n if (!res.ok) throw new CliError(`${method} ${route} -> ${res.status}: ${text.slice(0, 600)}`, 1);\n return (text ? JSON.parse(text) : {}) as T;\n } finally {\n clearTimeout(timer);\n }\n}\n\nexport function printJson(ctx: { stdout: (line: string) => void }, value: unknown): void {\n ctx.stdout(JSON.stringify(value, null, 2));\n}\n","import { spawn, spawnSync } from \"node:child_process\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport { CliError } from \"../router\";\nimport { type Credentials, resolveCredentials } from \"../config\";\nimport type { RuntimeRequest } from \"./client\";\n\n/**\n * The schema runtime, run on THIS machine. The npm package carries the SDK's\n * `gatewaysdk/environment` directory (stdlib-only Python, the same files the\n * platform's bridge executes), so any python3 >= 3.11 on the path runs it\n * exactly as the platform does — the same bootstrap, JSON in, JSON out. No\n * pip, no PyPI. When there is no such Python, callers fall back to\n * `POST /api/public/worlds/runtime`.\n *\n * `GATEWAY_RUNTIME=local|platform|auto` (default auto) forces one side;\n * `GATEWAY_PYTHON` names the interpreter.\n */\n\nconst MIN_PYTHON: [number, number] = [3, 11];\nconst DIAGNOSTIC_TAIL = 600;\n\n/** The end of a failed run's output: a Python traceback names the exception last. */\nfunction tailOf(output: string): string {\n return output.length > DIAGNOSTIC_TAIL\n ? `…${output.slice(-DIAGNOSTIC_TAIL)}`\n : output;\n}\n\n/** The platform's own bootstrap: build the `gatewaysdk` package in memory from\n * the runtime root and run the bridge as __main__ (see worldSchemaRuntime.ts). */\nconst BRIDGE_BOOTSTRAP = `import sys,runpy,types,os\nroot=sys.argv[1]\npackage=types.ModuleType('gatewaysdk')\npackage.__path__=[os.path.join(root,'gatewaysdk')]\nsys.modules['gatewaysdk']=package\nrunpy.run_module('gatewaysdk.environment.schema.platform',run_name='__main__')`;\n\n/** The same, but running the schema module's own CLI (serve, connector-capture …)\n * with the arguments after the root. */\nconst MODULE_BOOTSTRAP = `import sys,runpy,types,os\nroot=sys.argv[1]\npackage=types.ModuleType('gatewaysdk')\npackage.__path__=[os.path.join(root,'gatewaysdk')]\nsys.modules['gatewaysdk']=package\nsys.argv=['gateway worlds']+sys.argv[2:]\nrunpy.run_module('gatewaysdk.environment.schema',run_name='__main__')`;\n\nexport type RuntimeMode = \"auto\" | \"local\" | \"platform\";\n\nexport function runtimeMode(): RuntimeMode {\n const raw = (process.env.GATEWAY_RUNTIME ?? \"auto\").toLowerCase();\n if (raw === \"local\" || raw === \"platform\" || raw === \"auto\") return raw;\n throw new CliError(\n `GATEWAY_RUNTIME must be local, platform or auto (got ${raw})`,\n );\n}\n\n/** Where the bundled runtime lives: `<package>/runtime` beside dist/, or the\n * monorepo's SDK source when running from the repository. */\nexport function runtimeRoot(): string | null {\n const candidates: string[] = [];\n if (process.env.GATEWAY_RUNTIME_PATH)\n candidates.push(process.env.GATEWAY_RUNTIME_PATH);\n const entry = process.argv[1]\n ? path.dirname(fs.realpathSync(process.argv[1]))\n : null;\n if (entry) {\n candidates.push(path.resolve(entry, \"..\", \"runtime\"));\n candidates.push(path.resolve(entry, \"..\", \"..\", \"runtime\"));\n candidates.push(path.resolve(entry, \"..\", \"..\", \"..\", \"sdk\", \"src\"));\n candidates.push(path.resolve(entry, \"..\", \"..\", \"..\", \"..\", \"sdk\", \"src\"));\n }\n candidates.push(path.resolve(process.cwd(), \"runtime\"));\n for (const root of candidates)\n if (\n fs.existsSync(\n path.join(root, \"gatewaysdk\", \"environment\", \"schema\", \"platform.py\"),\n )\n )\n return root;\n return null;\n}\n\nlet pythonCache: string | null | undefined;\n\n/** A python3 at or above 3.11, or null. Cached for the process. */\nexport function findPython(): string | null {\n if (pythonCache !== undefined) return pythonCache;\n const names = process.env.GATEWAY_PYTHON\n ? [process.env.GATEWAY_PYTHON]\n : [\"python3\", \"python\"];\n for (const name of names) {\n const probe = spawnSync(\n name,\n [\"-c\", \"import sys;print(sys.version_info[0],sys.version_info[1])\"],\n {\n encoding: \"utf8\",\n timeout: 10_000,\n },\n );\n if (probe.status !== 0) continue;\n const [major, minor] = probe.stdout.trim().split(/\\s+/).map(Number);\n if (\n major! > MIN_PYTHON[0] ||\n (major === MIN_PYTHON[0] && minor! >= MIN_PYTHON[1])\n ) {\n pythonCache = name;\n return name;\n }\n }\n pythonCache = null;\n return null;\n}\n\n/** Can this machine run the runtime itself? Both a Python and the bundled files. */\nexport function localRuntime(): { python: string; root: string } | null {\n if (runtimeMode() === \"platform\") return null;\n const python = findPython();\n const root = runtimeRoot();\n if (!python || !root) {\n if (runtimeMode() === \"local\")\n throw new CliError(\n !python\n ? `GATEWAY_RUNTIME=local but no python3 >= ${MIN_PYTHON.join(\".\")} was found (set GATEWAY_PYTHON)`\n : \"GATEWAY_RUNTIME=local but the bundled runtime is missing (set GATEWAY_RUNTIME_PATH)\",\n );\n return null;\n }\n return { python, root };\n}\n\n/** Does the local Python have PyYAML? `conform` needs it for .yaml specs. */\nexport function localPythonHasYaml(python: string): boolean {\n return (\n spawnSync(python, [\"-c\", \"import yaml\"], { timeout: 10_000 }).status === 0\n );\n}\n\n/** One bridge request through the local runtime: JSON in on stdin, JSON out. */\nexport async function localBridge<T = Record<string, unknown>>(\n request: RuntimeRequest,\n local: { python: string; root: string },\n opts: { timeoutMs?: number } = {},\n): Promise<T> {\n const input = JSON.stringify(request);\n return await new Promise<T>((resolve, reject) => {\n const child = spawn(\n local.python,\n [\"-I\", \"-B\", \"-c\", BRIDGE_BOOTSTRAP, local.root],\n {\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n env: {\n PATH: process.env.PATH ?? \"\",\n HOME: process.env.HOME ?? \"\",\n TMPDIR: process.env.TMPDIR ?? \"\",\n },\n },\n );\n const out: Buffer[] = [];\n const err: Buffer[] = [];\n const timer = setTimeout(\n () => child.kill(\"SIGKILL\"),\n opts.timeoutMs ?? 300_000,\n );\n child.stdout.on(\"data\", (chunk: Buffer) => out.push(chunk));\n child.stderr.on(\"data\", (chunk: Buffer) => err.push(chunk));\n child.on(\"error\", (error) => {\n clearTimeout(timer);\n reject(\n new CliError(\n `local runtime could not start (${local.python}): ${error.message}`,\n 1,\n ),\n );\n });\n child.on(\"close\", (code) => {\n clearTimeout(timer);\n const text = Buffer.concat(out).toString(\"utf8\");\n const stderr = Buffer.concat(err).toString(\"utf8\");\n let payload: unknown = null;\n try {\n payload = text ? JSON.parse(text) : null;\n } catch {\n payload = null;\n }\n if (payload && typeof payload === \"object\") {\n resolve(payload as T);\n return;\n }\n reject(\n new CliError(\n `local runtime (${request.command}) exited ${code}: ${tailOf((stderr || text).trim()) || \"no output\"}`,\n 1,\n ),\n );\n });\n child.stdin.end(input);\n });\n}\n\n/** Run the schema module's own CLI in the foreground (serve, connector-capture …). */\nexport async function localModule(\n argv: string[],\n local: { python: string; root: string },\n opts: { env?: Record<string, string>; cwd?: string } = {},\n): Promise<number> {\n return await new Promise<number>((resolve, reject) => {\n const child = spawn(\n local.python,\n [\"-B\", \"-c\", MODULE_BOOTSTRAP, local.root, ...argv],\n {\n stdio: \"inherit\",\n cwd: opts.cwd,\n env: { ...process.env, ...opts.env },\n },\n );\n child.on(\"error\", (error) =>\n reject(\n new CliError(\n `local runtime could not start (${local.python}): ${error.message}`,\n 1,\n ),\n ),\n );\n child.on(\"close\", (code) => resolve(code ?? 1));\n });\n}\n\n/** Credentials when the platform may be needed; null when a local runtime\n * will do and none are configured (a `schema check` needs no login). */\nexport function credentialsForRuntime(hostFlag?: string): Credentials | null {\n try {\n return resolveCredentials(hostFlag);\n } catch (error) {\n if (error instanceof CliError && localRuntime()) return null;\n throw error;\n }\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport { CliError } from \"../router\";\nimport { localBridge, localPythonHasYaml, localRuntime } from \"./local\";\nimport type { Credentials } from \"../config\";\n\n/**\n * The wire to the schema runtime, which is Python and runs on the platform:\n * a world directory goes up as `[{path, content b64}]`, one bridge request\n * comes back verbatim, and any files in the answer land back in the\n * directory. Nothing here interprets a contract — that is the bridge's job.\n */\n\nexport type WorldFile = { path: string; content: string };\n\n/** Directories that are never part of a world's files. */\nconst SKIP_DIRS = new Set([\"__pycache__\", \".git\", \"node_modules\", \".gateway\"]);\n\n/** Every file under `dir` as base64 entries with forward-slash relative paths,\n * sorted so the same tree always produces the same request. */\n/** Compiled snapshots (`db/state.*`, `scenarios/<name>/state.*`) are build outputs\n * of the tree's data, never inputs: the runtime rebuilds them from the journals\n * and strips them from what it returns, and a real world's snapshots alone can\n * exceed the bridge's 64 MiB request cap. */\nconst BUILD_OUTPUT = /(^|\\/)state\\.(sqlite|json)$/;\n\nexport function isBuildOutput(relPath: string): boolean {\n return BUILD_OUTPUT.test(relPath);\n}\n\nexport function readWorldFiles(dir: string, opts: { buildOutputs?: boolean } = {}): WorldFile[] {\n if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())\n throw new CliError(`Not a directory: ${dir}`);\n const out: WorldFile[] = [];\n const walk = (rel: string) => {\n const abs = rel ? path.join(dir, rel) : dir;\n const entries = fs.readdirSync(abs, { withFileTypes: true });\n entries.sort((a, b) => a.name.localeCompare(b.name));\n for (const entry of entries) {\n const childRel = rel ? `${rel}/${entry.name}` : entry.name;\n if (entry.isDirectory()) {\n if (!SKIP_DIRS.has(entry.name)) walk(childRel);\n } else if (entry.isFile()) {\n if (!opts.buildOutputs && isBuildOutput(childRel)) continue;\n out.push({\n path: childRel,\n content: fs.readFileSync(path.join(dir, childRel)).toString(\"base64\"),\n });\n }\n }\n };\n walk(\"\");\n return out.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));\n}\n\nfunction assertSafeRelPath(rel: string): void {\n const parts = rel.split(\"/\");\n if (\n !rel ||\n rel.startsWith(\"/\") ||\n rel.includes(\"\\\\\") ||\n /^[A-Za-z]:/.test(rel) ||\n parts.some((p) => p === \"\" || p === \".\" || p === \"..\")\n )\n throw new CliError(`The runtime returned an unsafe file path: ${rel}`, 1);\n}\n\n/** Write bridge files into `dir`. With `clean`, files the runtime did not\n * return are removed first (the skipped dirs are left alone), so the tree\n * becomes exactly what the runtime holds. Returns the written paths. */\nexport function writeWorldFiles(\n dir: string,\n files: WorldFile[],\n opts: { clean?: boolean } = {},\n): string[] {\n for (const file of files) assertSafeRelPath(file.path);\n if (opts.clean && fs.existsSync(dir)) {\n const keep = new Set(files.map((f) => f.path));\n for (const existing of readWorldFiles(dir)) {\n if (!keep.has(existing.path)) fs.rmSync(path.join(dir, existing.path));\n }\n pruneEmptyDirs(dir);\n }\n fs.mkdirSync(dir, { recursive: true });\n const written: string[] = [];\n for (const file of files) {\n const target = path.join(dir, file.path);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n fs.writeFileSync(target, Buffer.from(file.content, \"base64\"));\n written.push(file.path);\n }\n return written;\n}\n\nfunction pruneEmptyDirs(root: string): void {\n const walk = (abs: string): boolean => {\n let empty = true;\n for (const entry of fs.readdirSync(abs, { withFileTypes: true })) {\n const child = path.join(abs, entry.name);\n if (entry.isDirectory()) {\n if (SKIP_DIRS.has(entry.name)) {\n empty = false;\n continue;\n }\n if (walk(child)) fs.rmdirSync(child);\n else empty = false;\n } else empty = false;\n }\n return empty;\n };\n walk(root);\n}\n\n/** The bridge's structured diagnostic, exactly as the Python ContractError\n * carries it (`code`, `message`, `path`, `schema_path`, plus context). */\nexport type BridgeErrorDetail = {\n code: string;\n message: string;\n path?: string;\n schema_path?: string;\n [key: string]: unknown;\n};\n\n/** Rendered the way the Python CLI prints a ContractError:\n * `{code} at {schema_path or path or '/'}: {message}`. */\nexport function formatBridgeError(detail: BridgeErrorDetail): string {\n const where = detail.schema_path || detail.path || \"/\";\n return `${detail.code} at ${where}: ${detail.message}`;\n}\n\nexport class BridgeRejected extends CliError {\n constructor(readonly detail: BridgeErrorDetail) {\n super(formatBridgeError(detail), 1);\n }\n}\n\nexport function detailFrom(payload: unknown): BridgeErrorDetail | null {\n if (!payload || typeof payload !== \"object\") return null;\n const error = (payload as { error?: unknown }).error;\n if (!error || typeof error !== \"object\") return null;\n const detail = error as Record<string, unknown>;\n if (typeof detail.code !== \"string\" || typeof detail.message !== \"string\") return null;\n return detail as BridgeErrorDetail;\n}\n\nexport type RuntimeRequest = { command: string } & Record<string, unknown>;\n\n/**\n * `POST /api/public/worlds/runtime` with the bridge request verbatim. A\n * rejection — whether the platform relays it with a 4xx or as a 200 with\n * `status: \"rejected\"` — becomes a BridgeRejected; anything else non-OK is a\n * plain CliError with the status and body excerpt.\n */\nexport async function runtime<T extends Record<string, unknown> = Record<string, unknown>>(\n creds: Credentials | null,\n request: RuntimeRequest,\n opts: { timeoutMs?: number } = {},\n): Promise<T> {\n // This machine first, when it can: the bundled runtime with a local\n // python3 is what the platform runs anyway, minus the round trip. A .yaml\n // conform spec needs PyYAML, which the vendored runtime does not carry.\n const local = localRuntime();\n const yamlSpec =\n request.command === \"conform\" &&\n Array.isArray(request.openapi) &&\n (request.openapi as { path?: string }[]).some((doc) => /\\.ya?ml$/i.test(doc.path ?? \"\"));\n if (local && !(yamlSpec && !localPythonHasYaml(local.python))) {\n const payload = await localBridge<Record<string, unknown>>(request, local, opts);\n const detail = detailFrom(payload);\n if (detail) throw new BridgeRejected(detail);\n return payload as T;\n }\n if (!creds)\n throw new CliError(\n \"This needs the schema runtime: install python3 >= 3.11 (the CLI bundles the runtime) or \" +\n \"configure platform credentials (`gateway auth login`).\",\n );\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), opts.timeoutMs ?? 180_000);\n const route = \"/api/public/worlds/runtime\";\n try {\n const res = await fetch(`${creds.host}${route}`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n accept: \"application/json\",\n authorization:\n \"Basic \" + Buffer.from(`${creds.publicKey}:${creds.secretKey}`).toString(\"base64\"),\n },\n body: JSON.stringify(request),\n signal: controller.signal,\n });\n const text = await res.text();\n let payload: unknown = null;\n try {\n payload = text ? JSON.parse(text) : {};\n } catch {\n payload = null;\n }\n const detail = detailFrom(payload);\n if (detail) throw new BridgeRejected(detail);\n if (!res.ok)\n throw new CliError(`POST ${route} (${request.command}) -> ${res.status}: ${text.slice(0, 600)}`, 1);\n if (payload === null) throw new CliError(`POST ${route} (${request.command}) returned non-JSON`, 1);\n return payload as T;\n } finally {\n clearTimeout(timer);\n }\n}\n\n/** Basic-auth headers for the few non-runtime routes this track calls. */\nexport function authHeaders(creds: Credentials): Record<string, string> {\n return {\n accept: \"application/json\",\n authorization:\n \"Basic \" + Buffer.from(`${creds.publicKey}:${creds.secretKey}`).toString(\"base64\"),\n };\n}\n\n/** Strip the `files` echo from a bridge report before printing it. */\nexport function withoutFiles<T extends Record<string, unknown>>(report: T): Omit<T, \"files\"> {\n const { files: _files, ...rest } = report;\n return rest;\n}\n\n/** JSON with sorted keys, the way the Python CLI prints bridge reports. */\nexport function sortedJson(value: unknown, indent = 2): string {\n const sort = (v: unknown): unknown => {\n if (Array.isArray(v)) return v.map(sort);\n if (v && typeof v === \"object\") {\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(v as Record<string, unknown>).sort())\n out[key] = sort((v as Record<string, unknown>)[key]);\n return out;\n }\n return v;\n };\n return JSON.stringify(sort(value), null, indent);\n}\n","import { schemaFromSignature, type WorldToolkit } from \"./session\";\n\n/**\n * A BROWSER ON A WORLD'S UI — the computer-use half of a live session.\n *\n * A session answers on SURFACES. `tools` is always there (the world's own\n * operations over the rendezvous). An api-type world may also answer on\n * `api` (the service itself), `ui` (its dashboard, over the same state) and\n * `browser` — a headless Chromium the platform runs NEXT TO that UI, which\n * an agent drives through Playwright. This file is the TS client for the\n * last two, call for call with `gatewaysdk/world_browser.py`.\n *\n * const s = await openSession(\"payments-like\", \"refund-dispute\", {\n * surfaces: [\"ui\", \"browser\"],\n * });\n * await s.ready();\n * const b = await s.browser(); // hosted, next to the world\n * await b.goto(); // the UI's entry page\n * await b.click(\"text=Refund\");\n * const tools = computerUseToolkit(b); // the same actions as model tools\n * await b.close();\n *\n * Playwright is an OPTIONAL peer: nothing here imports it until a browser is\n * opened, so sessions that never touch a UI never load it.\n *\n * MODES. `hosted` connects to the session's own browser (a Playwright server\n * the pod exposes over an authenticated websocket). `local` launches Chromium\n * on this machine and points it at the UI — a laptop against a hosted twin,\n * or a test. `auto` prefers hosted. Asking for a mode the session cannot\n * serve throws `WorldSurfaceUnavailable`; there is no silent fallback to a\n * browser other than the one the episode is judged on.\n *\n * OBSERVABILITY. Every action a `WorldBrowser` takes (goto, click, type,\n * press, scroll, back) is reported to the platform as one event — what was\n * done, whether it worked, where the page ended up, and a JPEG of the screen\n * after — through a `BrowserActionRecorder`. Reporting is fire-and-forget\n * and never fails the action; the platform renders it as the session's\n * browser timeline. Text typed into secret-looking fields is redacted before\n * it leaves the process.\n */\n\nexport const SURFACE_KINDS = [\"tools\", \"api\", \"ui\", \"browser\"] as const;\nexport type WorldSurfaceKind = (typeof SURFACE_KINDS)[number];\n\nexport const DEFAULT_VIEWPORT = { width: 1280, height: 800 };\nconst SETTLE_TIMEOUT_MS = 5_000;\nconst SETTLE_QUIET_MS = 150;\nconst SETTLE_POLL_MS = 25;\n\nexport const EVENT_BATCH_SIZE = 10;\nexport const EVENT_FLUSH_INTERVAL_MS = 1_000;\nexport const EVENT_MAX_RETRIES = 3;\nconst EVENT_SCREENSHOT_QUALITY = 60;\nconst EVENT_MAX_STRING = 500;\n\nconst SECRET_KEY =\n /pass(word|wd)?|secret|token|api[-_]?key|authorization|cookie|(^|[-_ #.\\[\"'=])(otp|pin|cvv|ssn)([-_ \\]\"']|$)/i;\nconst SECRET_VALUE =\n /^((sk|pk|ghp|xox[abp])[-_][-_A-Za-z0-9]{8,}|AKIA[0-9A-Z]{12,}|Bearer [-_.A-Za-z0-9]{8,})/;\n\n/** The `surfaces` block of a session descriptor, as the platform sends it. */\nexport type SessionSurfaces = {\n tools: { kind: \"rendezvous\" };\n api?: {\n url: string;\n /** Per-session credential of a World Host session: send it as\n * `Authorization: Bearer <token>` (the header only; a token in the URL is\n * refused). Absent when the world\n * itself answers with its declared auth (a pod or a customer-hosted twin). */\n token?: string;\n };\n ui?: {\n url: string;\n entry: string;\n /** Same-origin prefix the UI proxies to the world API, e.g. `/__world-api`;\n * null when the UI only reaches the API server-side. */\n apiPath?: string | null;\n /** Per-session credential of a World Host UI. A browser navigation cannot\n * carry a header, so the first page load presents it once as `?token=`\n * and the host answers with an HttpOnly cookie. Absent for pod UIs. */\n token?: string;\n };\n browser?: {\n wsUrl: string;\n /** `cdp`: the platform's Chromium relay (any number of agents share one\n * browser, each in its own context). `playwright`: a `run-server` endpoint. */\n protocol: \"cdp\" | \"playwright\";\n viewport: { width: number; height: number };\n };\n};\n\nexport class WorldSurfaceUnavailable extends Error {\n constructor(\n readonly surface: WorldSurfaceKind,\n reason: string,\n ) {\n super(`World surface '${surface}' is unavailable: ${reason}`);\n }\n}\n\nexport function surfaceKinds(s: SessionSurfaces): WorldSurfaceKind[] {\n const kinds: WorldSurfaceKind[] = [\"tools\"];\n if (s.api) kinds.push(\"api\");\n if (s.ui) kinds.push(\"ui\");\n if (s.browser) kinds.push(\"browser\");\n return kinds;\n}\n\nconst UI_TOKEN_QUERY = \"token\";\n\n/** The URL of `path` on a UI surface, carrying the session token when the\n * surface has one. `path` may already have a query string; the token is\n * appended to it. */\nexport function uiUrl(\n ui: NonNullable<SessionSurfaces[\"ui\"]>,\n path: string,\n): string {\n const base = ui.url.replace(/\\/+$/, \"\");\n const rel = path.startsWith(\"/\") ? path : `/${path}`;\n if (!ui.token) return base + rel;\n const [beforeHash, hash] = splitHash(rel);\n const joiner = beforeHash.includes(\"?\") ? \"&\" : \"?\";\n const query = `${UI_TOKEN_QUERY}=${encodeURIComponent(ui.token)}`;\n return base + beforeHash + joiner + query + hash;\n}\n\nexport function uiEntryUrl(ui: NonNullable<SessionSurfaces[\"ui\"]>): string {\n return uiUrl(ui, ui.entry || \"/\");\n}\n\n/** `url` without its `token` query parameter: what may be logged or shown. */\nexport function withoutUiToken(url: string): string {\n const [beforeHash, hash] = splitHash(url);\n const q = beforeHash.indexOf(\"?\");\n if (q < 0) return url;\n const kept = beforeHash\n .slice(q + 1)\n .split(\"&\")\n .filter((pair) => pair !== \"\" && pair.split(\"=\")[0] !== UI_TOKEN_QUERY);\n return (\n beforeHash.slice(0, q) + (kept.length ? `?${kept.join(\"&\")}` : \"\") + hash\n );\n}\n\nfunction splitHash(url: string): [string, string] {\n const h = url.indexOf(\"#\");\n return h < 0 ? [url, \"\"] : [url.slice(0, h), url.slice(h)];\n}\n\n/** The slice of a Playwright `Page` this module drives. */\nexport type BrowserPage = {\n url(): string;\n goto(url: string, opts?: { waitUntil?: \"load\" }): Promise<unknown>;\n click(selector: string): Promise<void>;\n fill(selector: string, value: string): Promise<void>;\n screenshot(opts?: {\n type?: \"png\" | \"jpeg\";\n quality?: number;\n fullPage?: boolean;\n }): Promise<Buffer>;\n innerText(selector: string): Promise<string>;\n content(): Promise<string>;\n goBack(opts?: { waitUntil?: \"load\" }): Promise<unknown>;\n waitForLoadState(state?: \"load\"): Promise<void>;\n waitForTimeout(ms: number): Promise<void>;\n on(\n event: \"request\" | \"requestfinished\" | \"requestfailed\",\n handler: (request: unknown) => void,\n ): unknown;\n title(): Promise<string>;\n keyboard: { press(key: string): Promise<void> };\n mouse: { wheel(dx: number, dy: number): Promise<void> };\n};\n\nexport type BrowserMode = \"auto\" | \"hosted\" | \"local\";\n\n// ── action events ────────────────────────────────────────────────────────────\n\n/** One browser action as the platform ingests it\n * (`POST /world-sessions/{id}/browser-events`). */\nexport type BrowserActionEvent = {\n agentId: string;\n seq: number;\n ts: string;\n action: string;\n args: Record<string, unknown>;\n ok: boolean;\n error: string | null;\n durationMs: number;\n url: string | null;\n title: string | null;\n mode: Exclude<BrowserMode, \"auto\">;\n viewport: { width: number; height: number };\n /** base64 JPEG of the screen after the action; null if it could not be taken. */\n screenshot: string | null;\n};\n\n/** What of an action's arguments may leave the process. Selectors, paths\n * and keys are what a reviewer needs; anything keyed like a credential, or\n * typed into a field whose selector names one, or shaped like a known key,\n * is replaced. Strings are capped, nested values dropped. */\nexport function redactActionArgs(\n action: string,\n args: Record<string, unknown>,\n): Record<string, unknown> {\n const secretField =\n action === \"browser_type\" && SECRET_KEY.test(String(args.selector ?? \"\"));\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(args)) {\n if (value === null || value === undefined) out[key] = null;\n else if (typeof value === \"boolean\" || typeof value === \"number\")\n out[key] = value;\n else if (typeof value === \"string\") {\n if (\n SECRET_KEY.test(key) ||\n SECRET_VALUE.test(value) ||\n (secretField && key === \"text\")\n )\n out[key] = \"[redacted]\";\n else\n out[key] =\n value.length <= EVENT_MAX_STRING\n ? value\n : value.slice(0, EVENT_MAX_STRING) + \"…\";\n } else out[key] = \"[omitted]\";\n }\n return out;\n}\n\n/**\n * Ships browser action events to the platform, off the action's hot path.\n *\n * `post` receives a batch of events (the request body's `events`). Events\n * are numbered here, so ordering survives batching and retries — the\n * platform dedups on `(agentId, seq)`. A batch that keeps failing is dropped\n * with a warning: telemetry must never stall or fail the agent.\n *\n * Numbering is durable across recorders: `nextSeq()` hands out a position\n * within this recorder, and the first send adds the base `resumeFrom`\n * reports — the platform's next free seq for this agent — so an agent id\n * reopened in a later process appends to its timeline instead of colliding\n * with (and being deduplicated against) what it already recorded. The base\n * is fixed once resolved, which keeps retries idempotent.\n */\nexport class BrowserActionRecorder {\n private seq = 0;\n private base: Promise<number> | null = null;\n private queue: BrowserActionEvent[] = [];\n private timer: ReturnType<typeof setTimeout> | null = null;\n private inflight: Promise<void> = Promise.resolve();\n sent = 0;\n dropped = 0;\n\n constructor(\n private readonly post: (events: BrowserActionEvent[]) => Promise<void>,\n readonly agentId: string,\n private readonly opts: {\n /** The platform's next free seq for `agentId`; 0 when not given. */\n resumeFrom?: () => Promise<number>;\n batchSize?: number;\n flushIntervalMs?: number;\n maxRetries?: number;\n sleep?: (ms: number) => Promise<void>;\n warn?: (message: string) => void;\n } = {},\n ) {}\n\n /** This recorder's next position; the wire seq is `resumeFrom() + this`. */\n nextSeq(): number {\n return this.seq++;\n }\n\n private resolveBase(): Promise<number> {\n if (this.base === null) {\n const resolve = this.opts.resumeFrom ?? (async () => 0);\n this.base = resolve().then((n) => {\n if (!Number.isInteger(n) || n < 0)\n throw new Error(\n `browser event base seq must be a non-negative integer, got ${String(n)}`,\n );\n return n;\n });\n // A failed lookup is retried with the batch, not remembered.\n this.base.catch(() => {\n this.base = null;\n });\n }\n return this.base;\n }\n\n record(event: BrowserActionEvent): void {\n this.queue.push(event);\n if (this.queue.length >= (this.opts.batchSize ?? EVENT_BATCH_SIZE)) {\n this.drain();\n } else if (this.timer === null) {\n this.timer = setTimeout(\n () => this.drain(),\n this.opts.flushIntervalMs ?? EVENT_FLUSH_INTERVAL_MS,\n );\n if (typeof this.timer === \"object\" && \"unref\" in this.timer)\n this.timer.unref();\n }\n }\n\n /** Resolve once everything recorded so far has been posted (or dropped). */\n async flush(): Promise<void> {\n this.drain();\n await this.inflight;\n }\n\n async close(): Promise<void> {\n await this.flush();\n }\n\n private drain(): void {\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n if (this.queue.length === 0) return;\n const batch = this.queue;\n this.queue = [];\n this.inflight = this.inflight.then(() => this.send(batch));\n }\n\n private async send(batch: BrowserActionEvent[]): Promise<void> {\n const retries = this.opts.maxRetries ?? EVENT_MAX_RETRIES;\n const sleep =\n this.opts.sleep ??\n ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));\n for (let attempt = 0; attempt < retries; attempt++) {\n try {\n const base = await this.resolveBase();\n await this.post(\n base === 0 ? batch : batch.map((e) => ({ ...e, seq: base + e.seq })),\n );\n this.sent += batch.length;\n return;\n } catch (error) {\n if (attempt + 1 === retries) {\n this.dropped += batch.length;\n (this.opts.warn ?? console.warn)(\n `dropping ${batch.length} browser events after ${attempt + 1} attempts: ${String(error)}`,\n );\n return;\n }\n await sleep(500 * 2 ** attempt);\n }\n }\n }\n}\n\n/**\n * One Playwright page on the session's UI. Thin on purpose — `page` is the\n * real Playwright page for anything this wrapper does not cover.\n */\nexport class WorldBrowser {\n constructor(\n readonly page: BrowserPage,\n readonly ui: SessionSurfaces[\"ui\"] | undefined,\n readonly mode: Exclude<BrowserMode, \"auto\">,\n private readonly teardown: () => Promise<void>,\n readonly viewport: { width: number; height: number } = DEFAULT_VIEWPORT,\n readonly recorder: BrowserActionRecorder | null = null,\n ) {\n page.on(\"request\", () => {\n this.inflight += 1;\n this.lastNetwork = Date.now();\n });\n const done = () => {\n this.inflight = Math.max(0, this.inflight - 1);\n this.lastNetwork = Date.now();\n };\n page.on(\"requestfinished\", done);\n page.on(\"requestfailed\", done);\n }\n\n private inflight = 0;\n private lastNetwork = Date.now();\n\n get agentId(): string | null {\n return this.recorder?.agentId ?? null;\n }\n\n /** Run one action and report it: the event carries what was asked,\n * whether it worked, and the screen after — for failures too, so a\n * reviewer sees what the agent saw when the selector did not match. */\n private async act<T>(\n action: string,\n args: Record<string, unknown>,\n fn: () => Promise<T>,\n ): Promise<T> {\n const recorder = this.recorder;\n if (!recorder) return fn();\n const started = Date.now();\n let ok = true;\n let error: string | null = null;\n try {\n return await fn();\n } catch (err) {\n ok = false;\n error = (\n err instanceof Error ? `${err.name}: ${err.message}` : String(err)\n ).slice(0, 4000);\n throw err;\n } finally {\n recorder.record({\n agentId: recorder.agentId,\n seq: recorder.nextSeq(),\n ts: new Date().toISOString(),\n action,\n args: redactActionArgs(action, args),\n ok,\n error,\n durationMs: Date.now() - started,\n mode: this.mode,\n viewport: { ...this.viewport },\n ...(await this.observeForEvent()),\n });\n }\n }\n\n private async observeForEvent(): Promise<\n Pick<BrowserActionEvent, \"url\" | \"title\" | \"screenshot\">\n > {\n const out: Pick<BrowserActionEvent, \"url\" | \"title\" | \"screenshot\"> = {\n url: null,\n title: null,\n screenshot: null,\n };\n try {\n out.url = this.page.url();\n out.title = await this.page.title();\n const jpeg = await this.page.screenshot({\n type: \"jpeg\",\n quality: EVENT_SCREENSHOT_QUALITY,\n });\n out.screenshot = jpeg.toString(\"base64\");\n } catch {\n // a closed page still gets its event\n }\n return out;\n }\n\n /** Open a UI path (`/customers`), a full URL, or — with no argument — the\n * UI's declared entry page. */\n async goto(pathOrUrl?: string): Promise<string> {\n let target: string;\n if (pathOrUrl === undefined) {\n if (!this.ui)\n throw new WorldSurfaceUnavailable(\n \"ui\",\n \"this session has no UI to navigate to\",\n );\n target = uiEntryUrl(this.ui);\n } else if (/^https?:\\/\\//.test(pathOrUrl)) {\n target = pathOrUrl;\n } else {\n if (!this.ui)\n throw new WorldSurfaceUnavailable(\n \"ui\",\n \"relative paths need a UI surface\",\n );\n target = uiUrl(this.ui, pathOrUrl);\n }\n return this.act(\n \"browser_goto\",\n { path: pathOrUrl ?? null, url: withoutUiToken(target) },\n async () => {\n await this.page.goto(target, { waitUntil: \"load\" });\n await this.settle();\n return this.page.url();\n },\n );\n }\n\n async back(): Promise<string> {\n return this.act(\"browser_back\", {}, async () => {\n await this.page.goBack({ waitUntil: \"load\" });\n await this.settle();\n return this.page.url();\n });\n }\n\n /** Wait for the page to finish reacting to an action. `load` alone is not\n * enough for client-rendered UIs (React et al.): a click returns before the\n * fetch that re-renders the page, so an agent would read stale text.\n * Playwright's `networkidle` is per navigation and resolves at once after\n * the first one, so this tracks requests itself: done when nothing is in\n * flight and the network has been quiet for `SETTLE_QUIET_MS`, bounded so\n * long-polling UIs cannot hang us. */\n private async settle(): Promise<void> {\n await this.page.waitForLoadState(\"load\");\n const deadline = Date.now() + SETTLE_TIMEOUT_MS;\n while (Date.now() < deadline) {\n const quiet = Date.now() - this.lastNetwork >= SETTLE_QUIET_MS;\n if (this.inflight === 0 && quiet) return;\n await this.page.waitForTimeout(SETTLE_POLL_MS);\n }\n }\n\n async click(selector: string): Promise<void> {\n await this.act(\"browser_click\", { selector }, async () => {\n await this.page.click(selector);\n await this.settle();\n });\n }\n\n async type(selector: string, text: string): Promise<void> {\n await this.act(\"browser_type\", { selector, text }, () =>\n this.page.fill(selector, text),\n );\n }\n\n async press(key: string): Promise<void> {\n await this.act(\"browser_press\", { key }, async () => {\n await this.page.keyboard.press(key);\n await this.settle();\n });\n }\n\n async scroll(dy: number): Promise<void> {\n await this.act(\"browser_scroll\", { dy }, () =>\n this.page.mouse.wheel(0, dy),\n );\n }\n\n async screenshot(fullPage = false): Promise<Buffer> {\n return this.page.screenshot({ type: \"png\", fullPage });\n }\n\n async screenshotBase64(fullPage = false): Promise<string> {\n return (await this.screenshot(fullPage)).toString(\"base64\");\n }\n\n async text(selector = \"body\"): Promise<string> {\n return this.page.innerText(selector);\n }\n\n async html(): Promise<string> {\n return this.page.content();\n }\n\n get url(): string {\n return this.page.url();\n }\n\n async title(): Promise<string> {\n return this.page.title();\n }\n\n async close(): Promise<void> {\n try {\n await this.teardown();\n } finally {\n await this.recorder?.close();\n }\n }\n}\n\n/** The Playwright entry points this module needs, so tests can inject a fake. */\nexport type PlaywrightLike = {\n chromium: {\n connect(wsEndpoint: string): Promise<PlaywrightBrowserLike>;\n connectOverCDP(endpointURL: string): Promise<PlaywrightBrowserLike>;\n launch(opts?: { headless?: boolean }): Promise<PlaywrightBrowserLike>;\n };\n};\n\nexport type PlaywrightBrowserLike = {\n newContext(opts?: {\n viewport?: { width: number; height: number };\n }): Promise<{ newPage(): Promise<BrowserPage>; close(): Promise<void> }>;\n close(): Promise<void>;\n};\n\nasync function loadPlaywright(): Promise<PlaywrightLike> {\n try {\n // A string specifier keeps bundlers from resolving the optional peer.\n const name = \"playwright\";\n return (await import(name)) as PlaywrightLike;\n } catch (error) {\n throw new Error(\n \"Driving a world UI needs Playwright: npm install playwright \" +\n \"(and `npx playwright install chromium` for local mode).\",\n { cause: error },\n );\n }\n}\n\nexport function resolveBrowserMode(\n surfaces: SessionSurfaces,\n mode: BrowserMode,\n): Exclude<BrowserMode, \"auto\"> {\n if (!surfaces.ui && !surfaces.browser)\n throw new WorldSurfaceUnavailable(\n \"ui\",\n \"open the session with surfaces: ['ui'] on a world that declares [ui]\",\n );\n const resolved =\n mode === \"auto\" ? (surfaces.browser ? \"hosted\" : \"local\") : mode;\n if (resolved === \"hosted\" && !surfaces.browser)\n throw new WorldSurfaceUnavailable(\n \"browser\",\n \"open the session with surfaces: ['browser'] to get a hosted browser\",\n );\n return resolved;\n}\n\n/** Open a browser on the session's UI in `hosted`, `local` or `auto` mode. */\nexport async function openBrowser(\n surfaces: SessionSurfaces,\n opts: {\n mode?: BrowserMode;\n headless?: boolean;\n playwright?: PlaywrightLike;\n recorder?: BrowserActionRecorder | null;\n } = {},\n): Promise<WorldBrowser> {\n const mode = resolveBrowserMode(surfaces, opts.mode ?? \"auto\");\n const pw = opts.playwright ?? (await loadPlaywright());\n const viewport = surfaces.browser?.viewport ?? DEFAULT_VIEWPORT;\n const browser =\n mode === \"hosted\"\n ? surfaces.browser!.protocol === \"playwright\"\n ? await pw.chromium.connect(surfaces.browser!.wsUrl)\n : await pw.chromium.connectOverCDP(surfaces.browser!.wsUrl)\n : await pw.chromium.launch({ headless: opts.headless ?? true });\n const context = await browser.newContext({ viewport });\n const page = await context.newPage();\n return new WorldBrowser(\n page,\n surfaces.ui,\n mode,\n async () => {\n await context.close();\n await browser.close();\n },\n viewport,\n opts.recorder ?? null,\n );\n}\n\n// ── computer-use tools ───────────────────────────────────────────────────────\n\nexport const COMPUTER_USE_SPECS = [\n {\n name: \"browser_goto\",\n signature: \"browser_goto(path=None)\",\n doc: \"Open a page of the world's UI. `path` is a UI path like /customers, a full URL, or omitted for the entry page. Returns the URL and page text.\",\n },\n {\n name: \"browser_click\",\n signature: \"browser_click(selector)\",\n doc: \"Click an element by Playwright selector (CSS, `text=Refund`, `role=button[name=Save]`). Returns the page text after the click.\",\n },\n {\n name: \"browser_type\",\n signature: \"browser_type(selector, text)\",\n doc: \"Replace the value of an input/textarea found by selector with `text`.\",\n },\n {\n name: \"browser_press\",\n signature: \"browser_press(key)\",\n doc: \"Press a key (Enter, Tab, Escape, ArrowDown, ...). Returns the page text after.\",\n },\n {\n name: \"browser_scroll\",\n signature: \"browser_scroll(dy=600)\",\n doc: \"Scroll the page vertically by `dy` pixels (negative scrolls up).\",\n },\n {\n name: \"browser_screenshot\",\n signature: \"browser_screenshot(full_page=False)\",\n doc: \"Take a PNG screenshot; returns {image_base64, url}.\",\n },\n {\n name: \"browser_read\",\n signature: \"browser_read(selector='body')\",\n doc: \"Return the visible text of an element (default: whole page) plus the URL and title.\",\n },\n {\n name: \"browser_back\",\n signature: \"browser_back()\",\n doc: \"Go back one page in history.\",\n },\n] as const;\n\nconst str = (v: unknown, fallback: string): string =>\n typeof v === \"string\" && v.length > 0 ? v : fallback;\n\n/**\n * The browser as model tools, in the same `WorldToolkit` shape the world's\n * own tools come in — so an agent loop that already dispatches\n * `toolkit().impls` merges `computerUseToolkit(b).impls` and gains a screen\n * without a second dispatch path.\n */\nexport function computerUseToolkit(\n browser: WorldBrowser,\n opts: { maxText?: number } = {},\n): WorldToolkit {\n const maxText = opts.maxText ?? 20_000;\n const observe = async (selector = \"body\") => {\n const text = await browser.text(selector);\n return {\n url: browser.url,\n title: await browser.title(),\n text: text.slice(0, maxText),\n truncated: text.length > maxText,\n };\n };\n\n const impls: WorldToolkit[\"impls\"] = {\n browser_goto: async (a) => {\n await browser.goto(typeof a.path === \"string\" ? a.path : undefined);\n return observe();\n },\n browser_click: async (a) => {\n await browser.click(str(a.selector, \"\"));\n return observe();\n },\n browser_type: async (a) => {\n await browser.type(str(a.selector, \"\"), String(a.text ?? \"\"));\n return { ok: true, url: browser.url };\n },\n browser_press: async (a) => {\n await browser.press(str(a.key, \"Enter\"));\n return observe();\n },\n browser_scroll: async (a) => {\n await browser.scroll(typeof a.dy === \"number\" ? a.dy : 600);\n return { ok: true, url: browser.url };\n },\n browser_screenshot: async (a) => ({\n image_base64: await browser.screenshotBase64(a.full_page === true),\n url: browser.url,\n }),\n browser_read: async (a) => observe(str(a.selector, \"body\")),\n browser_back: async () => {\n await browser.back();\n return observe();\n },\n };\n\n const specs = COMPUTER_USE_SPECS.map((s) => ({ ...s }));\n return {\n schemas: specs.map((spec) => schemaFromSignature(spec)),\n impls,\n specs,\n };\n}\n","import { randomUUID } from \"node:crypto\";\n\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\nimport {\n BrowserActionRecorder,\n SURFACE_KINDS,\n WorldSurfaceUnavailable,\n computerUseToolkit,\n openBrowser,\n uiEntryUrl,\n type BrowserActionEvent,\n type BrowserMode,\n type PlaywrightLike,\n type SessionSurfaces,\n type WorldBrowser,\n type WorldSurfaceKind,\n} from \"./browser\";\nimport type { WorldTaskSummary } from \"./tasks\";\n\n/**\n * LIVE WORLD SESSIONS from TypeScript: your agent, the platform's container.\n *\n * The other two ways of running a world each give up something. Pulling the\n * bundle and executing it locally tests your agent against a COPY — your\n * python, your sqlite, your machine's idea of the environment. Dispatching a\n * hosted run gives you the real container but runs the platform's agent\n * inside it, so your agent never touches the world.\n *\n * A session is both: the platform boots the task's container and holds it\n * warm, and every `call()` here executes inside THAT container. Your agent\n * stays where it is — this file is just the wire.\n *\n * const world = await openWorld(\"revenue-ops-sim@main\");\n * const session = await openSession(world.slug, { task: \"revops-mara-dedupe-contacts\" });\n * await session.ready(); // wait for the container\n * await session.call(\"crm_search\", { entity: \"deals\" });\n * const { reward, rewards } = await session.grade();\n * await session.close({ keepWarm: true }); // hand it back to the pool\n *\n * The task can also be YOURS rather than the bundle's — an instruction, the\n * rows the session starts with and how it is graded, for one end user:\n *\n * const session = await openSession(\"acme-billing@main\", {\n * task: {\n * instruction: \"Mark invoice INV-7 as paid.\",\n * seed: { rows: { invoices: [{ id: \"INV-7\", status: \"open\" }] } },\n * grader: { kind: \"assertions\", checks: [\n * { entity: \"invoices\", where: { id: \"INV-7\", status: \"paid\" } },\n * ] },\n * metadata: { externalUserId: \"u_42\" },\n * },\n * surfaces: [\"api\"],\n * });\n *\n * Every call is a row on the platform before it is an effect in a container,\n * so the episode is on the record — and the platform traces the session\n * itself, which is why these sessions show up under Sessions without the\n * caller instrumenting anything.\n */\n\nexport type WorldToolSpec = {\n name: string;\n /** The world's own signature, e.g. `crm_search(q=None, entity=\"deals\")`. */\n signature: string;\n doc: string | null;\n inputSchema?: Record<string, unknown>;\n};\n\n/** What a model needs to call a world: the schemas to advertise, and the\n * implementations that run them in the container. */\nexport type WorldToolkit = {\n /** OpenAI-shaped tool definitions, derived from the world's signatures. */\n schemas: {\n type: \"function\";\n function: {\n name: string;\n description: string;\n parameters: Record<string, unknown>;\n };\n }[];\n /** name -> implementation, each one a call into THIS session. */\n impls: Record<string, (args: Record<string, unknown>) => Promise<unknown>>;\n specs: WorldToolSpec[];\n};\n\n// ── tasks ────────────────────────────────────────────────────────────────────\n\n/** A JSON scalar: what `where` filters and field predicates compare against. */\nexport type WorldTaskScalar = string | number | boolean | null;\n\n/** The rows a task starts the session with — the `seed()` contract, applied\n * by the host right after it clones the version's snapshot. `append`\n * (default) upserts by primary key onto the base data; `replace` makes the\n * named entities hold exactly these rows. */\nexport type WorldTaskSeed = {\n mode?: \"append\" | \"replace\";\n rows: Record<string, Record<string, unknown>[]>;\n};\n\nexport type WorldTaskFieldOp =\n \"eq\" | \"neq\" | \"in\" | \"gt\" | \"gte\" | \"lt\" | \"lte\" | \"contains\";\n\n/**\n * One declarative check over the session's final rows. `where` selects rows\n * of `entity` by equality (dotted paths reach into nested objects); the\n * assertion says what must hold of the selection:\n *\n * exists (default) / absent at least one row / none\n * count `count` bound on how many\n * all / any `field op value` on every / some selected row\n *\n * A check's `id` names its entry in `rewards`; the task's reward is the\n * weighted share of checks that passed.\n */\nexport type WorldTaskCheck = {\n id?: string;\n weight?: number;\n entity: string;\n where?: Record<string, WorldTaskScalar>;\n assert?: \"exists\" | \"absent\" | \"count\" | \"all\" | \"any\";\n count?: { eq?: number; gte?: number; lte?: number };\n field?: string;\n op?: WorldTaskFieldOp;\n value?: WorldTaskScalar | WorldTaskScalar[];\n};\n\n/** One thing a rubric judge scores in [0, 1]; `id` names its entry in\n * `rewards`, `weight` (default 1) its share of the task's reward. */\nexport type WorldTaskRubricCriterion = {\n id: string;\n description: string;\n weight?: number;\n};\n\n/** A rubric is prose: what a good outcome looks like. The platform (never the\n * host) has a model read the session's final state and its call log against\n * it; the project's default evaluation model judges unless `model` pins one.\n * `grade()` then resolves asynchronously — `pending: true` first, the reward\n * once the judge has answered. */\nexport type WorldTaskRubricGrader = {\n kind: \"rubric\";\n rubric: string;\n criteria?: WorldTaskRubricCriterion[];\n model?: { provider: string; model: string };\n};\n\n/** How a task is graded: checks the host evaluates in-process, a `verify.py`\n * body (state JSON on stdin, last stdout line `{reward, ...}`) run through the\n * host's confined verifier, or a rubric judged by a model on the platform. */\nexport type WorldTaskGrader =\n | { kind: \"assertions\"; checks: WorldTaskCheck[] }\n | { kind: \"python\"; source: string; timeoutSeconds?: number }\n | WorldTaskRubricGrader;\n\n/** A task supplied at open, for one session, instead of a bundled scenario.\n * `instruction` is what the agent is told; without `seed` the session starts\n * on the version's base data, without `grader` `grade()` answers\n * `reward: null`; `tools` is the allow-list of the version's tools the agent\n * may call in this session (unset: all of them; a call outside it is refused\n * and logged); `metadata` is yours (an end-user id, a ticket) and is echoed\n * on the session, never read. Limits: shared/domain/worldTasks.ts. */\nexport type WorldTaskSpec = {\n name?: string;\n instruction: string;\n seed?: WorldTaskSeed;\n grader?: WorldTaskGrader;\n tools?: string[];\n metadata?: Record<string, unknown>;\n};\n\n/** A stored task of the project (see worlds/tasks.ts), opened by id; the\n * session runs a copy of one version's spec — the current one by default. */\nexport type WorldTaskIdRef = { id: string; version?: number };\n\n/** What `openSession` takes as the task: a bundled scenario's name, a\n * stored task's `{ id, version? }`, or an inline spec. */\nexport type WorldTaskRef = string | WorldTaskIdRef | WorldTaskSpec;\n\n/** What a session's task is, on every session response. `hash` is the\n * content hash of the spec (inline or stored) — what warm reuse matches on;\n * `id`/`version` name the stored task the session was opened on. */\nexport type WorldSessionTask = {\n source: \"bundled\" | \"inline\" | \"stored\";\n name: string | null;\n hash: string | null;\n id?: string | null;\n version?: number | null;\n metadata: Record<string, unknown>;\n};\n\nexport const isTaskIdRef = (task: WorldTaskRef): task is WorldTaskIdRef =>\n typeof task === \"object\" && task !== null && \"id\" in task;\n\nexport const isTaskSpec = (task: WorldTaskRef): task is WorldTaskSpec =>\n typeof task === \"object\" && task !== null && \"instruction\" in task;\n\n/** The label a task goes by in results: its name, `inline:<hash>` for an\n * unnamed inline task once the platform has hashed it, or the stored task's\n * name (its id until the platform has answered). */\nexport const taskLabel = (\n task: WorldTaskRef,\n info?: WorldSessionTask | null,\n): string => {\n if (typeof task === \"string\") return task;\n if (isTaskIdRef(task)) return info?.name ?? task.id;\n if (task.name) return task.name;\n return info?.hash ? `inline:${info.hash.slice(0, 12)}` : \"inline\";\n};\n\nexport type SeedResult = {\n seeded: number;\n mode: \"append\" | \"replace\";\n entity_counts: Record<string, number>;\n};\n\n/** One row of the session's call log. */\nexport type WorldSessionCall = {\n seq: number;\n kind: string;\n tool: string | null;\n args: unknown;\n result: unknown;\n error: string | null;\n completedAt: string | null;\n};\n\nexport type WorldSessionState = {\n sessionId: string;\n state: string;\n ready: boolean;\n versionId: string;\n contentHash: string;\n taskName: string | null;\n /** Where the task came from and what it is; absent on platforms that\n * predate session tasks, in which case it is derived from `taskName`. */\n task?: WorldSessionTask;\n /** The task's objective — present when the session was opened (not on a\n * bare status read), so a client never needs the bundle on disk. */\n instruction?: string | null;\n /** The tools this task serves. */\n tools?: WorldToolSpec[];\n /** Where the session answers besides `tools` — see worlds/browser.ts. */\n surfaces?: SessionSurfaces;\n};\n\nexport type GradeResult = {\n reward: number | null;\n rewards: Record<string, number>;\n raw: unknown;\n};\n\n/** How long `ready()` waits, and how often it asks. */\nconst READY_TIMEOUT_MS = 10 * 60_000;\nconst READY_POLL_MS = 2_000;\n/** How long one call may take end to end (container claim + execution). */\nconst CALL_TIMEOUT_MS = 3 * 60_000;\nconst CALL_POLL_MS = 400;\n/** How long a grade the platform's judge finalizes may take: the model's own\n * timeout and retries, plus the worker's queue backoff. Polled slowly. */\nconst JUDGED_GRADE_TIMEOUT_MS = 15 * 60_000;\nconst JUDGED_GRADE_POLL_MS = 2_000;\nconst EXPORT_PAGE = 500;\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\nconst modelToolName = (name: string): string =>\n name.replace(/[^A-Za-z0-9_-]/g, \"_\").slice(0, 64) || \"tool\";\n\n/**\n * Turn a world's Python signature into a JSON schema the model can call.\n *\n * `crm_update_deal(id, stage=None, owner=None, amount=None)` becomes an\n * object with `id` required and the rest optional. Types are read from the\n * DEFAULTS the world declares — a numeric default means a number, a boolean\n * default a boolean — because that is the only type information a signature\n * actually carries. Everything else is a string, which is what a tool CLI\n * receives anyway.\n */\nexport function schemaFromSignature(spec: WorldToolSpec): {\n type: \"function\";\n function: {\n name: string;\n description: string;\n parameters: Record<string, unknown>;\n };\n} {\n if (spec.inputSchema)\n return {\n type: \"function\",\n function: {\n name: modelToolName(spec.name),\n description: spec.doc ?? spec.name,\n parameters: spec.inputSchema,\n },\n };\n const inside = /\\(([\\s\\S]*)\\)\\s*$/.exec(spec.signature.trim())?.[1] ?? \"\";\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n // Split on top-level commas only: a default like `{\"a\": 1}` has its own.\n const params: string[] = [];\n let depth = 0;\n let current = \"\";\n for (const ch of inside) {\n if (\"([{\".includes(ch)) depth++;\n if (\")]}\".includes(ch)) depth--;\n if (ch === \",\" && depth === 0) {\n params.push(current);\n current = \"\";\n } else current += ch;\n }\n if (current.trim()) params.push(current);\n\n for (const raw of params) {\n const param = raw.trim();\n if (!param || param.startsWith(\"*\") || param === \"self\") continue;\n const eq = param.indexOf(\"=\");\n const name = (eq === -1 ? param : param.slice(0, eq)).split(\":\")[0].trim();\n if (!name) continue;\n if (eq === -1) {\n properties[name] = { type: \"string\" };\n required.push(name);\n continue;\n }\n const value = param.slice(eq + 1).trim();\n if (/^-?\\d+(\\.\\d+)?$/.test(value)) properties[name] = { type: \"number\" };\n else if (value === \"True\" || value === \"False\")\n properties[name] = { type: \"boolean\" };\n else properties[name] = { type: \"string\" };\n }\n return {\n type: \"function\",\n function: {\n name: modelToolName(spec.name),\n description: spec.doc ?? spec.name,\n parameters: { type: \"object\", properties, required },\n },\n };\n}\n\nexport class WorldSessionTimeout extends Error {}\nexport class WorldSessionCallError extends Error {}\n\nexport class WorldSession {\n constructor(\n readonly sessionId: string,\n private current: WorldSessionState,\n private readonly options: WorldsClientOptions,\n ) {}\n\n /** The task's display name: a bundled scenario's, or the inline spec's\n * `name` (null when the spec was unnamed). Same as `taskName`. */\n get task(): string | null {\n return this.current.taskName;\n }\n\n /** The task's display name: a bundled scenario's, or the inline spec's\n * `name` (null when the spec was unnamed). */\n get taskName(): string | null {\n return this.current.taskName;\n }\n\n /** The task this session runs: bundled scenario, stored task or inline\n * spec, its name, hash and the caller's metadata. */\n get taskInfo(): WorldSessionTask {\n return (\n this.current.task ?? {\n source: \"bundled\",\n name: this.current.taskName,\n hash: null,\n metadata: {},\n }\n );\n }\n\n /** What this task asks for — the bundle's instruction.md, or the inline\n * spec's `instruction`. */\n get instruction(): string | null {\n return this.current.instruction ?? null;\n }\n\n get versionId(): string {\n return this.current.versionId;\n }\n\n /** Whether the session answered ready as of the last state read (the open,\n * a `status()`, or the poll inside `ready()`); no request is made. */\n get isReady(): boolean {\n return this.current.ready;\n }\n\n /** `api` / `ui` / `browser` are present exactly when the world declares\n * them AND the session was opened asking for them. */\n async surfaces(): Promise<SessionSurfaces> {\n if (!this.current.surfaces) await this.status();\n return this.current.surfaces ?? { tools: { kind: \"rendezvous\" } };\n }\n\n /** Base URL of the world's own HTTP API for this session. */\n async api(): Promise<string> {\n const { api } = await this.surfaces();\n if (!api)\n throw new WorldSurfaceUnavailable(\n \"api\",\n \"open the session with surfaces: ['api'] on an api-type world\",\n );\n return api.url;\n }\n\n /** Headers every request to `api()` needs. A World Host session gates its\n * api surface on a per-session token; a pod or hosted twin answers with the\n * world's own declared auth and this is `{}`. */\n async apiHeaders(): Promise<Record<string, string>> {\n const { api } = await this.surfaces();\n return api?.token ? { Authorization: `Bearer ${api.token}` } : {};\n }\n\n /** URL of the world's UI entry page for this session. */\n async ui(): Promise<string> {\n const { ui } = await this.surfaces();\n if (!ui)\n throw new WorldSurfaceUnavailable(\n \"ui\",\n \"open the session with surfaces: ['ui'] on a world that declares [ui]\",\n );\n return uiEntryUrl(ui);\n }\n\n /** A Playwright browser on this session's UI: `hosted` drives the one the\n * platform runs next to the world, `local` launches one here, `auto`\n * prefers hosted. Call `close()` when done.\n *\n * Every action is reported to the platform under `agentId` (default:\n * `GATEWAY_AGENT_ID` or a fresh `agent-<hex>`) so the session page shows\n * this agent's own timeline — several agents may share one session and\n * one hosted browser. `record: false` opts out. */\n async browser(\n opts: {\n mode?: BrowserMode;\n headless?: boolean;\n playwright?: PlaywrightLike;\n agentId?: string;\n record?: boolean;\n } = {},\n ): Promise<WorldBrowser> {\n const { agentId, record = true, ...rest } = opts;\n return openBrowser(await this.surfaces(), {\n ...rest,\n recorder: record ? this.browserRecorder(agentId) : null,\n });\n }\n\n /** The reporter `browser()` uses; exposed for a page you drive yourself. */\n browserRecorder(agentId?: string): BrowserActionRecorder {\n const path = `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/browser-events`;\n const id =\n agentId ??\n process.env.GATEWAY_AGENT_ID ??\n `agent-${randomUUID().replace(/-/g, \"\").slice(0, 8)}`;\n return new BrowserActionRecorder(\n async (events: BrowserActionEvent[]) => {\n await apiRequest(this.options, \"POST\", path, { events });\n },\n id,\n {\n // Continue this agent's timeline where the platform has it, so the\n // same id reopened later never re-numbers from zero.\n resumeFrom: async () => {\n const summary = await apiRequest<{\n agents: { agentId: string; nextSeq: number }[];\n }>(this.options, \"GET\", path);\n return summary.agents.find((a) => a.agentId === id)?.nextSeq ?? 0;\n },\n },\n );\n }\n\n /** Browser actions as model tools, in the same shape as `toolkit()`. */\n computerUseTools(browser: WorldBrowser): WorldToolkit {\n return computerUseToolkit(browser);\n }\n\n /** The session's latest platform state (one request, no waiting). */\n async status(): Promise<WorldSessionState> {\n const fresh = await apiRequest<WorldSessionState>(\n this.options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}`,\n );\n // A status read does not carry the objective; keep the one we opened with.\n this.current = {\n instruction: this.current.instruction,\n tools: this.current.tools,\n surfaces: this.current.surfaces,\n task: this.current.task,\n ...fresh,\n };\n return this.current;\n }\n\n /**\n * Wait until the container is warm — meaning the process inside it has\n * asked the platform for work, not merely that a job was accepted.\n */\n async ready(opts: { timeoutMs?: number } = {}): Promise<WorldSessionState> {\n const deadline = Date.now() + (opts.timeoutMs ?? READY_TIMEOUT_MS);\n for (;;) {\n const state = await this.status();\n if (state.ready) return state;\n if (state.state === \"FAILED\" || state.state === \"STOPPED\")\n throw new WorldSessionCallError(\n `World session ${state.state.toLowerCase()} before it was ready.`,\n );\n if (Date.now() > deadline)\n throw new WorldSessionTimeout(\n `World session still ${state.state} after ${Math.round((opts.timeoutMs ?? READY_TIMEOUT_MS) / 1000)}s.`,\n );\n await sleep(READY_POLL_MS);\n }\n }\n\n /** Enqueue one interaction and wait for the container's answer. */\n private async exchange(\n body: {\n kind?: \"call\" | \"grade\" | \"reset\" | \"state\" | \"seed\" | \"close\";\n tool?: string;\n args?: unknown;\n },\n timeoutMs?: number,\n ): Promise<unknown> {\n const enqueued = await apiRequest<{\n callId: string;\n seq: number;\n /** The platform's worker finalizes this call (a rubric grade). */\n pending?: boolean;\n }>(\n this.options,\n \"POST\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/calls`,\n body,\n );\n const { callId } = enqueued;\n const judged = enqueued.pending === true;\n const budgetMs =\n timeoutMs ?? (judged ? JUDGED_GRADE_TIMEOUT_MS : CALL_TIMEOUT_MS);\n const pollMs = judged ? JUDGED_GRADE_POLL_MS : CALL_POLL_MS;\n const deadline = Date.now() + budgetMs;\n for (;;) {\n const call = await apiRequest<{\n done: boolean;\n state: string;\n result: unknown;\n error: string | null;\n }>(\n this.options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/calls/${encodeURIComponent(callId)}`,\n );\n if (call.done) {\n if (call.error) throw new WorldSessionCallError(call.error);\n return call.result;\n }\n if (Date.now() > deadline)\n throw new WorldSessionTimeout(\n judged\n ? `Grade ${callId} still ${call.state} after ${Math.round(budgetMs / 1000)}s — the judge has not answered; the platform finalizes the call on its own, read it back with export().`\n : `Call ${callId} still ${call.state} after ${Math.round(budgetMs / 1000)}s — the container may have died.`,\n );\n await sleep(pollMs);\n }\n }\n\n /**\n * Run one of the world's tools INSIDE the container. The arguments and the\n * result are the world's own contract — this layer neither validates nor\n * reshapes them, so a tool error reads exactly as it would in a hosted run.\n */\n async call(\n tool: string,\n args: Record<string, unknown> = {},\n opts: { timeoutMs?: number } = {},\n ): Promise<unknown> {\n return this.exchange({ kind: \"call\", tool, args }, opts.timeoutMs);\n }\n\n /**\n * THE WORLD'S TOOLS, READY TO HAND TO A MODEL. Schemas come from the\n * world's own signatures and implementations call into this session, so a\n * caller never writes — and never has to re-sync — a tool map of their own:\n *\n * const { schemas, impls } = await session.toolkit();\n * await runMyAgent(impls, schemas, session.instruction);\n *\n * A tool added to the world shows up here on the next run; a tool renamed\n * in the world renames here too, instead of failing at call time against a\n * hand-written map that still remembers the old name.\n */\n async toolkit(): Promise<WorldToolkit> {\n let specs = this.current.tools;\n if (!specs) specs = (await this.status()).tools ?? [];\n const impls: WorldToolkit[\"impls\"] = Object.create(null);\n for (const spec of specs) {\n const alias = modelToolName(spec.name);\n if (Object.hasOwn(impls, alias))\n throw new WorldSessionCallError(`Model tool name collision: ${alias}`);\n impls[alias] = (args: Record<string, unknown> = {}) =>\n this.call(spec.name, args);\n }\n return { schemas: specs.map(schemaFromSignature), impls, specs };\n }\n\n /** Run the task's grader against the container's END STATE. Graders answer\n * in one of two shapes: the scalar with named rewards beside it\n * (`{reward, check_a, check_b}`, a task's own `grade.py`), or the named\n * rewards nested under `rewards` (the api, mock-tools and World Host\n * runners). Both land in `rewards`.\n *\n * A rubric grade is finalized by the platform's judge, not the container:\n * the platform answers the enqueue with `pending: true`, and this waits on\n * the judge's budget (15 min) instead of a call's. `timeoutMs` overrides\n * either. */\n async grade(opts: { timeoutMs?: number } = {}): Promise<GradeResult> {\n const raw = (await this.exchange(\n { kind: \"grade\" },\n opts.timeoutMs,\n )) as Record<string, unknown> | null;\n const record = raw && typeof raw === \"object\" ? raw : {};\n const rewards: Record<string, number> = {};\n const nested = record.rewards;\n if (nested && typeof nested === \"object\") {\n for (const [key, value] of Object.entries(nested)) {\n if (typeof value === \"number\") rewards[key] = value;\n }\n }\n for (const [key, value] of Object.entries(record)) {\n if (key !== \"reward\" && typeof value === \"number\") rewards[key] = value;\n }\n return {\n reward: typeof record.reward === \"number\" ? record.reward : null,\n rewards,\n raw,\n };\n }\n\n /**\n * Put rows into the LIVE world through its contract, in one batch:\n * `append` (default) upserts by primary key, `replace` makes the named\n * entities hold exactly these rows. Atomic — a refused row leaves the\n * session unchanged and the error names the entity, row and field.\n */\n async seed(\n rows: Record<string, Record<string, unknown>[]>,\n opts: { mode?: \"append\" | \"replace\"; timeoutMs?: number } = {},\n ): Promise<SeedResult> {\n const mode = opts.mode ?? \"append\";\n return (await this.exchange(\n { kind: \"seed\", args: { mode, rows } },\n opts.timeoutMs,\n )) as SeedResult;\n }\n\n /** Every entity's rows as the world holds them now — the same dump a\n * grader reads. The shape is the world runtime's: a schema world answers\n * `{<entity>: {<key>: row}, snapshot}`, a mock-tools world\n * `{entities: {<entity>: [row]}}`. */\n async state(opts: { timeoutMs?: number } = {}): Promise<unknown> {\n return this.exchange({ kind: \"state\" }, opts.timeoutMs);\n }\n\n /** Back to the opening state: the version's data plus the bundled\n * scenario's or the inline task's seed. Rows written since are gone; the\n * call log stays. */\n async reset(opts: { timeoutMs?: number } = {}): Promise<void> {\n await this.exchange({ kind: \"reset\" }, opts.timeoutMs);\n }\n\n /** The session's call log, oldest first: every tool call, seed, reset,\n * grade with its result — the record of the episode. */\n async export(): Promise<WorldSessionCall[]> {\n const calls: WorldSessionCall[] = [];\n let cursor: string | undefined;\n do {\n const params = new URLSearchParams({ limit: String(EXPORT_PAGE) });\n if (cursor) params.set(\"cursor\", cursor);\n const page = await apiRequest<{\n calls: Record<string, unknown>[];\n nextCursor?: string | null;\n }>(\n this.options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/calls?${params.toString()}`,\n );\n for (const call of page.calls) {\n calls.push({\n seq: Number(call.seq),\n kind: String(call.kind ?? \"call\"),\n tool: typeof call.tool === \"string\" ? call.tool : null,\n args: call.args ?? null,\n result: call.result ?? null,\n error: typeof call.error === \"string\" ? call.error : null,\n completedAt:\n typeof call.completedAt === \"string\" ? call.completedAt : null,\n });\n }\n cursor = page.nextCursor ?? undefined;\n } while (cursor);\n return calls;\n }\n\n /**\n * Promote this session's inline task into a stored task of the project\n * (version 1, pinned to the session's world unless `world` says otherwise),\n * so a task written for one end user can be reused and its grades\n * compared. The session then records the new task's id. A session on a\n * bundled task has nothing to save; one on a stored task is already saved.\n */\n async saveTask(\n opts: { name?: string; world?: string | null; message?: string } = {},\n ): Promise<WorldTaskSummary> {\n const task = await apiRequest<WorldTaskSummary>(\n this.options,\n \"POST\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/task`,\n {\n ...(opts.name !== undefined ? { name: opts.name } : {}),\n ...(opts.world !== undefined ? { world: opts.world } : {}),\n ...(opts.message !== undefined ? { message: opts.message } : {}),\n },\n );\n this.current = {\n ...this.current,\n taskName: task.name,\n task: {\n ...this.taskInfo,\n source: \"stored\",\n name: task.name,\n id: task.id,\n version: task.version,\n },\n };\n return task;\n }\n\n /**\n * End the session. `keepWarm` hands the container back to the pool instead\n * of tearing it down, so the next session for the same task starts warm —\n * the pooled instance still obeys the fleet's idle TTL and pinning.\n */\n async close(opts: { keepWarm?: boolean } = {}): Promise<{ state: string }> {\n return apiRequest(\n this.options,\n \"DELETE\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}`,\n { keepWarm: opts.keepWarm ?? false },\n );\n }\n}\n\n/**\n * Attach to a session that already exists — resuming after a crash, or\n * driving a session someone else opened (a container started by hand on a\n * self-hosted install, a session opened by CI and handed to a developer).\n */\nexport async function attachSession(\n sessionId: string,\n options: WorldsClientOptions = {},\n): Promise<WorldSession> {\n const state = await apiRequest<WorldSessionState>(\n options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(sessionId)}`,\n );\n return new WorldSession(sessionId, state, options);\n}\n\nexport type OpenSessionOptions = {\n versionId?: string;\n reuseWarm?: boolean;\n /** More than `tools`: `[\"api\"]`, `[\"ui\"]`, `[\"browser\"]`. The platform\n * refuses (HTTP 400) rather than quietly serving less than asked. */\n surfaces?: WorldSurfaceKind[];\n options?: WorldsClientOptions;\n};\n\n/**\n * Open a live session against one task of a world. Returns as soon as the\n * platform has accepted it — call `ready()` to wait for the container.\n *\n * `task` is a bundled scenario's name, a stored task's `{ id, version? }`\n * or an inline `WorldTaskSpec` (the latter two need a host engine world — the\n * platform answers 400 for a pod world). The older positional form\n * `openSession(slug, \"task-name\", opts)` still works.\n */\nexport async function openSession(\n slugOrRef: string,\n task: OpenSessionOptions & { task: WorldTaskRef },\n): Promise<WorldSession>;\nexport async function openSession(\n slugOrRef: string,\n task: WorldTaskRef,\n opts?: OpenSessionOptions,\n): Promise<WorldSession>;\nexport async function openSession(\n slugOrRef: string,\n taskOrOpts: WorldTaskRef | (OpenSessionOptions & { task: WorldTaskRef }),\n positionalOpts: OpenSessionOptions = {},\n): Promise<WorldSession> {\n const { task, ...opts } =\n typeof taskOrOpts === \"object\" && \"task\" in taskOrOpts\n ? taskOrOpts\n : { task: taskOrOpts as WorldTaskRef, ...positionalOpts };\n if (\n task === undefined ||\n task === null ||\n (typeof task === \"string\" && !task) ||\n (isTaskIdRef(task) && !task.id) ||\n (isTaskSpec(task) && !task.instruction) ||\n (typeof task === \"object\" && !isTaskIdRef(task) && !isTaskSpec(task))\n )\n throw new Error(\n \"openSession needs a task: a bundled task name, a stored task { id, version? } or { instruction, seed?, grader?, metadata? }\",\n );\n const options = opts.options ?? {};\n const unknown = (opts.surfaces ?? []).filter(\n (s) => !(SURFACE_KINDS as readonly string[]).includes(s),\n );\n if (unknown.length)\n throw new Error(\n `Unknown world surfaces: ${unknown.join(\", \")}; choose from ${SURFACE_KINDS.join(\", \")}`,\n );\n const at = slugOrRef.indexOf(\"@\");\n const slug = at === -1 ? slugOrRef : slugOrRef.slice(0, at);\n const state = await apiRequest<WorldSessionState & { reusedWarm: boolean }>(\n options,\n \"POST\",\n \"/api/public/world-sessions\",\n {\n ...(opts.versionId ? { versionId: opts.versionId } : { slug }),\n task,\n ...(opts.reuseWarm === undefined ? {} : { reuseWarm: opts.reuseWarm }),\n ...(opts.surfaces?.length ? { surfaces: opts.surfaces } : {}),\n },\n );\n return new WorldSession(state.sessionId, state, options);\n}\n\n// ── running many tasks at once ───────────────────────────────────────────────\n\nexport type SessionRunResult = {\n /** The task's name, or `inline:<hash>` for an unnamed inline task. */\n task: string;\n sessionId: string;\n reward: number | null;\n rewards: Record<string, number>;\n /** Set when the task threw instead of grading. */\n error?: string;\n};\n\nexport type SessionRunReport = {\n results: SessionRunResult[];\n /** Mean reward over every task, counting failures as 0. */\n mean: number;\n /** True when `mean >= failUnder` (or no gate was set). */\n passed: boolean;\n};\n\n/**\n * RUN MANY TASKS IN PARALLEL, one warm container each.\n *\n * Parallelism against live worlds is the normal case — a suite is a dozen\n * tasks and each needs its own container, because two agents sharing one\n * world state would corrupt both episodes. Every caller was writing the same\n * pool, the same per-task open/ready/toolkit/grade/close, and the same\n * \"don't let one failure kill the run\" logic, so it belongs here:\n *\n * const report = await runSessions({\n * world: \"revenue-ops-sim@main\",\n * tasks, // default: every task in the world\n * concurrency: 4,\n * failUnder: 0.7,\n * agent: async ({ toolkit, instruction }) =>\n * myAgent(toolkit.impls, toolkit.schemas, instruction),\n * });\n *\n * The handler gets a ready session with its toolkit already bound; grading,\n * closing (warm) and aggregation are handled. A task that throws scores 0\n * and records why — the tasks that passed keep their results.\n */\nexport async function runSessions(opts: {\n world: string;\n /** Bundled task names, stored task refs and/or inline task specs\n * (default: every bundled task in the world). */\n tasks?: WorldTaskRef[];\n concurrency?: number;\n failUnder?: number;\n /** Pin every session to one version (default: the world's head). */\n versionId?: string;\n /** Hand the containers back warm for the next run (default: true). */\n keepWarm?: boolean;\n agent: (ctx: {\n session: WorldSession;\n toolkit: WorldToolkit;\n instruction: string;\n /** The task's label — see `SessionRunResult.task`. */\n task: string;\n /** The task as it was given: a bundled name, a stored ref or the\n * inline spec. */\n taskRef: WorldTaskRef;\n }) => Promise<unknown>;\n onResult?: (result: SessionRunResult) => void;\n options?: WorldsClientOptions;\n}): Promise<SessionRunReport> {\n const options = opts.options ?? {};\n const concurrency = Math.max(1, opts.concurrency ?? 3);\n\n let tasks = opts.tasks;\n let versionId = opts.versionId;\n if (!tasks || !versionId) {\n // One resolve for the whole run: every session pins the SAME version, so\n // a push mid-suite cannot split the results across two worlds.\n const { openWorld } = await import(\"./index\");\n const world = await openWorld(opts.world, options);\n tasks = tasks ?? world.tasks.map((t) => t.name);\n versionId = versionId ?? world.version.versionId;\n }\n\n const results: SessionRunResult[] = [];\n let next = 0;\n await Promise.all(\n Array.from({ length: Math.min(concurrency, tasks.length) }, async () => {\n while (next < tasks!.length) {\n const taskRef = tasks![next++];\n let task = taskLabel(taskRef);\n let session: WorldSession | null = null;\n try {\n session = await openSession(opts.world, {\n task: taskRef,\n versionId,\n options,\n });\n task = taskLabel(taskRef, session.taskInfo);\n await session.ready();\n const toolkit = await session.toolkit();\n await opts.agent({\n session,\n toolkit,\n instruction:\n session.instruction ??\n (isTaskSpec(taskRef) ? taskRef.instruction : task),\n task,\n taskRef,\n });\n const graded = await session.grade();\n const result: SessionRunResult = {\n task,\n sessionId: session.sessionId,\n reward: graded.reward,\n rewards: graded.rewards,\n };\n results.push(result);\n opts.onResult?.(result);\n } catch (error) {\n const result: SessionRunResult = {\n task,\n sessionId: session?.sessionId ?? \"\",\n reward: 0,\n rewards: {},\n // An Error with an empty message would read as \"no error\" to any\n // caller checking truthiness; name the type instead.\n error:\n (error instanceof Error ? error.message : String(error)) ||\n (error instanceof Error ? error.name : \"Unknown error\"),\n };\n results.push(result);\n opts.onResult?.(result);\n } finally {\n // Always give the container back — a leaked session bills until the\n // fleet's idle TTL reaps it.\n await session\n ?.close({ keepWarm: opts.keepWarm ?? true })\n .catch(() => undefined);\n }\n }\n }),\n );\n\n const mean =\n results.reduce((sum, r) => sum + (r.reward ?? 0), 0) /\n (results.length || 1);\n return {\n results: results.sort((a, b) => a.task.localeCompare(b.task)),\n mean,\n passed: opts.failUnder === undefined ? true : mean >= opts.failUnder,\n };\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\nimport type { WorldTaskSpec } from \"./session\";\n\n/**\n * STORED WORLD TASKS: a task spec kept by the project, outside any bundle.\n *\n * An inline task (`openSession(world, { task: { instruction, … } })`) belongs\n * to one session. A stored task is the same spec as a named, versioned\n * project resource: create it once, open as many sessions on it as you like\n * with `{ task: { id } }`, and every grade attributes back to the task and\n * its version. Updating the spec never rewrites history — it appends a\n * version, and a session opened on `{ id, version: 2 }` keeps running v2\n * after v3 exists.\n *\n * const task = await createTask({\n * name: \"refund-late-invoice\",\n * world: \"acme-billing\",\n * spec: { instruction: \"…\", seed: {…}, grader: {…} },\n * });\n * const session = await openSession(\"acme-billing\", { task: { id: task.id } });\n *\n * Tasks are project-scoped: another project's task id is not found (404),\n * never forbidden. `world` pins a task to one world's slug (validated against\n * that world's contract); null leaves it usable with any world.\n */\n\nexport type WorldTaskSummary = {\n id: string;\n name: string;\n world: string | null;\n version: number;\n hash: string;\n spec: WorldTaskSpec;\n createdAt: string;\n updatedAt: string;\n createdBy: string;\n updatedBy: string;\n};\n\nexport type WorldTaskVersionSummary = {\n version: number;\n hash: string;\n createdAt: string;\n createdBy: string;\n message: string | null;\n};\n\nexport type WorldTaskDetail = WorldTaskSummary & {\n versions: WorldTaskVersionSummary[];\n};\n\nexport type WorldTaskPage = {\n tasks: WorldTaskSummary[];\n meta: { page: number; limit: number; totalItems: number; totalPages: number };\n};\n\nexport type WorldTaskValidation = {\n taskId: string;\n version: number;\n /** The world version the task was checked against. */\n versionId: string;\n ok: boolean;\n /** `entities` when the world's contract was read and every seed and check\n * entity was matched against it; `none` when the version has no contract\n * to check (a mock-tools world), in which case `ok` says only that the\n * version exists and is READY. */\n checked: \"entities\" | \"none\";\n problems: string[];\n entities: string[] | null;\n};\n\nconst TASKS = \"/api/public/world-tasks\";\nconst taskRoute = (id: string) => `${TASKS}/${encodeURIComponent(id)}`;\n\nconst compact = (body: Record<string, unknown>) =>\n Object.fromEntries(Object.entries(body).filter(([, v]) => v !== undefined));\n\n/** Store a task. `name` defaults to `spec.name`; one of the two is needed. */\nexport async function createTask(\n input: {\n spec: WorldTaskSpec;\n name?: string;\n world?: string | null;\n message?: string;\n },\n options: WorldsClientOptions = {},\n): Promise<WorldTaskSummary> {\n return apiRequest<WorldTaskSummary>(\n options,\n \"POST\",\n TASKS,\n compact({\n spec: input.spec,\n name: input.name,\n world: input.world,\n message: input.message,\n }),\n );\n}\n\n/** Change a task. A new `spec` becomes the next version (the old ones stay\n * readable and openable); `name` and `world` change in place. */\nexport async function updateTask(\n taskId: string,\n input: {\n spec?: WorldTaskSpec;\n name?: string;\n world?: string | null;\n message?: string;\n },\n options: WorldsClientOptions = {},\n): Promise<WorldTaskSummary> {\n if (\n input.spec === undefined &&\n input.name === undefined &&\n input.world === undefined\n )\n throw new Error(\"updateTask: nothing to update — pass spec, name or world\");\n return apiRequest<WorldTaskSummary>(\n options,\n \"PATCH\",\n taskRoute(taskId),\n compact({\n spec: input.spec,\n name: input.name,\n world: input.world,\n message: input.message,\n }),\n );\n}\n\n/** The project's tasks, newest change first. `world` keeps only tasks\n * pinned to that slug; `metadata` keeps tasks whose spec metadata carries\n * every given key/value (`{ externalUserId: \"u_42\" }`). */\nexport async function listTasks(\n filter: {\n world?: string;\n metadata?: Record<string, string>;\n page?: number;\n limit?: number;\n } = {},\n options: WorldsClientOptions = {},\n): Promise<WorldTaskPage> {\n const params = new URLSearchParams();\n if (filter.world) params.set(\"world\", filter.world);\n if (filter.page !== undefined) params.set(\"page\", String(filter.page));\n if (filter.limit !== undefined) params.set(\"limit\", String(filter.limit));\n for (const [key, value] of Object.entries(filter.metadata ?? {}))\n params.set(`metadata.${key}`, value);\n const query = params.toString();\n return apiRequest<WorldTaskPage>(\n options,\n \"GET\",\n query ? `${TASKS}?${query}` : TASKS,\n );\n}\n\n/** One task with its version history; `version` reads that version's spec\n * instead of the current one. */\nexport async function getTask(\n taskId: string,\n opts: { version?: number } = {},\n options: WorldsClientOptions = {},\n): Promise<WorldTaskDetail> {\n const query =\n opts.version === undefined ? \"\" : `?version=${String(opts.version)}`;\n return apiRequest<WorldTaskDetail>(\n options,\n \"GET\",\n `${taskRoute(taskId)}${query}`,\n );\n}\n\n/** Remove a task and every version. Sessions already opened on it keep\n * their copy of the spec. */\nexport async function deleteTask(\n taskId: string,\n options: WorldsClientOptions = {},\n): Promise<{ id: string; name: string }> {\n return apiRequest(options, \"DELETE\", taskRoute(taskId));\n}\n\n/** Check a task against a world version without opening a session: every\n * seed entity and every check's entity must exist in the world's contract.\n * `slug` checks against that world's head, `versionId` against an exact\n * version, neither against the task's own `world` pin. */\nexport async function validateTask(\n taskId: string,\n target: { version?: number; slug?: string; versionId?: string } = {},\n options: WorldsClientOptions = {},\n): Promise<WorldTaskValidation> {\n return apiRequest<WorldTaskValidation>(\n options,\n \"POST\",\n `${taskRoute(taskId)}/validate`,\n compact({\n version: target.version,\n slug: target.slug,\n versionId: target.versionId,\n }),\n );\n}\n","import { createHash } from \"node:crypto\";\nimport { gzipSync, gunzipSync } from \"node:zlib\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\n\n/**\n * The working-dir half of the TS CLI: push / pull / checkout / status /\n * branch / tag / propose — a faithful port of the Python client\n * (`gatewaysdk/benchmark_hub/client.py` + `_archive.py`).\n *\n * LOCKSTEP WARNING — the content hash is the version's identity and is\n * byte-compatible with Prime Intellect. It now has FOUR implementations that\n * must stay identical: worker `environmentAgent/tar.ts`, web\n * `benchmark-hub/server/benchmarkContentHash.ts`, Python `_archive.py`, and\n * this file. This one is a line-for-line port of the WEB TypeScript\n * implementation (same language, same crypto) — if the rule ever changes,\n * change all four or push identity splits by client.\n *\n * One deliberate refusal, same policy as the web upload path: a bundle with\n * a ROOT `.gitignore` is refused rather than mis-hashed — the Python CLI\n * honors it via `gitignore_parser`, and an imperfect reimplementation here\n * would produce a wrong, Prime-incompatible hash silently.\n */\n\nexport const DEFAULT_BRANCH = \"main\";\nconst META_RELPATH = path.join(\".gateway\", \".env-metadata.json\");\nconst SKIP_DIRS = new Set([\n \".git\",\n \"__pycache__\",\n \"node_modules\",\n \".venv\",\n \".mypy_cache\",\n \"dist\",\n \"build\",\n \"outputs\",\n]);\nconst ROOT_EXCLUDED_DIRS = new Set([\"dist\", \"build\", \"outputs\", \"__pycache__\"]);\n\n/** Gateway-only root markers that widen collection to every ordinary root\n * file. The FOURTH copy of this list (python SDK `_archive.py`, web\n * `benchmarkContentHash.ts`, worker `tar.ts`, and here) — all four MUST stay\n * identical or the same tree hashes differently per pusher. This copy\n * missing `gateway-api-world.toml` is exactly how an api world pushed from\n * TS landed on the hub with no OpenAPI contract and no marker: the root\n * files never entered the manifest, and nothing downstream could tell. */\nconst BROAD_ROOT_MARKERS = [\"gateway-env.toml\", \"gateway-api-world.toml\"];\n\n// ── content-hash rules (port of web benchmarkContentHash.ts) ───────────────\n\nfunction isExcludedDirComponent(component: string): boolean {\n return (\n component.startsWith(\".\") ||\n ROOT_EXCLUDED_DIRS.has(component) ||\n component.endsWith(\".egg-info\")\n );\n}\n\nexport function isIncludedInContentHash(\n relPath: string,\n includeAllRootFiles: boolean,\n): boolean {\n const parts = relPath.split(\"/\");\n const name = parts[parts.length - 1];\n const dirParts = parts.slice(0, -1);\n if (name.startsWith(\".\")) return false;\n if (parts.includes(\"__pycache__\")) return false;\n if (dirParts.length === 0) {\n return (\n includeAllRootFiles ||\n name === \"README.md\" ||\n name === \"pyproject.toml\" ||\n BROAD_ROOT_MARKERS.includes(name) ||\n name.endsWith(\".py\")\n );\n }\n return !dirParts.some(isExcludedDirComponent);\n}\n\n/** The archive-visible files of a working dir, as sorted relpaths. Throws on\n * a root .gitignore (see the header). */\nexport function collectArchiveRelPaths(dir: string): string[] {\n if (fs.existsSync(path.join(dir, \".gitignore\"))) {\n throw new Error(\n \"This bundle has a root .gitignore, which the Python CLI honors via \" +\n \"gitignore_parser. Reimplementing that imperfectly here would \" +\n \"silently produce a different content hash, so the TS CLI refuses. \" +\n \"Remove the .gitignore (or bake its effect into the tree) and retry.\",\n );\n }\n const out: string[] = [];\n const includeAllRootFiles = BROAD_ROOT_MARKERS.some((marker) =>\n fs.existsSync(path.join(dir, marker)),\n );\n const walk = (rel: string) => {\n const abs = rel ? path.join(dir, rel) : dir;\n for (const entry of fs.readdirSync(abs, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {\n const childRel = rel ? `${rel}/${entry.name}` : entry.name;\n if (entry.isDirectory()) {\n if (!isExcludedDirComponent(entry.name)) walk(childRel);\n } else if (entry.isFile()) {\n if (isIncludedInContentHash(childRel, includeAllRootFiles)) {\n out.push(childRel);\n }\n }\n }\n };\n walk(\"\");\n return out.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));\n}\n\nexport function computeContentHash(dir: string): string {\n const hasher = createHash(\"sha256\");\n for (const relPath of collectArchiveRelPaths(dir)) {\n hasher.update(Buffer.from(`file:${relPath}`, \"utf-8\"));\n hasher.update(fs.readFileSync(path.join(dir, relPath)));\n }\n return hasher.digest(\"hex\");\n}\n\n// ── deterministic tar.gz writer ─────────────────────────────────────────────\n\nfunction octal(value: number, length: number): Buffer {\n return Buffer.from(value.toString(8).padStart(length - 1, \"0\") + \"\\0\", \"ascii\");\n}\n\nfunction tarHeader(name: string, size: number): Buffer {\n const header = Buffer.alloc(512);\n header.write(name, 0, 100, \"utf-8\");\n octal(0o644, 8).copy(header, 100); // mode\n octal(0, 8).copy(header, 108); // uid\n octal(0, 8).copy(header, 116); // gid\n octal(size, 12).copy(header, 124);\n octal(0, 12).copy(header, 136); // mtime = 0 (deterministic)\n header.write(\" \", 148, \"ascii\"); // checksum placeholder = spaces\n header.write(\"0\", 156, \"ascii\"); // regular file\n header.write(\"ustar\", 257, \"ascii\");\n header.write(\"00\", 263, \"ascii\");\n let sum = 0;\n for (const byte of header) sum += byte;\n header.write(sum.toString(8).padStart(6, \"0\") + \"\\0 \", 148, \"ascii\");\n return header;\n}\n\nfunction tarMember(name: string, payload: Buffer): Buffer[] {\n const parts: Buffer[] = [];\n const nameBytes = Buffer.byteLength(name, \"utf-8\");\n if (nameBytes > 100) {\n // GNU long name: an 'L' member whose body is the real name.\n const body = Buffer.from(name + \"\\0\", \"utf-8\");\n const lHeader = tarHeader(\"././@LongLink\", body.length);\n lHeader.write(\"L\", 156, \"ascii\");\n let sum = 0;\n lHeader.write(\" \", 148, \"ascii\");\n for (const byte of lHeader) sum += byte;\n lHeader.write(sum.toString(8).padStart(6, \"0\") + \"\\0 \", 148, \"ascii\");\n parts.push(lHeader, body);\n const pad = body.length % 512 === 0 ? 0 : 512 - (body.length % 512);\n if (pad) parts.push(Buffer.alloc(pad));\n parts.push(tarHeader(name.slice(0, 100), payload.length));\n } else {\n parts.push(tarHeader(name, payload.length));\n }\n parts.push(payload);\n const pad = payload.length % 512 === 0 ? 0 : 512 - (payload.length % 512);\n if (pad) parts.push(Buffer.alloc(pad));\n return parts;\n}\n\n/** A deterministic .tar.gz of the source files (node's gzip stamps no mtime,\n * matching the Python's mtime=0 gzip). */\nexport function buildSourceTarball(dir: string): Buffer {\n const parts: Buffer[] = [];\n for (const relPath of collectArchiveRelPaths(dir)) {\n parts.push(...tarMember(relPath, fs.readFileSync(path.join(dir, relPath))));\n }\n parts.push(Buffer.alloc(1024)); // end-of-archive\n return gzipSync(Buffer.concat(parts), { level: 9 });\n}\n\n// ── local metadata (.gateway/.env-metadata.json) ────────────────────────────\n\nexport type LocalMeta = Record<string, unknown> & {\n slug?: string;\n branch?: string;\n versionId?: string;\n contentHash?: string;\n baseFiles?: Record<string, string>;\n};\n\nexport function readLocalMeta(dir: string): LocalMeta | null {\n try {\n const raw = fs.readFileSync(path.join(dir, META_RELPATH), \"utf-8\");\n const parsed = JSON.parse(raw);\n return parsed && typeof parsed === \"object\" ? (parsed as LocalMeta) : null;\n } catch {\n return null;\n }\n}\n\nexport function writeLocalMeta(dir: string, meta: LocalMeta): void {\n fs.mkdirSync(path.join(dir, \".gateway\"), { recursive: true });\n fs.writeFileSync(path.join(dir, META_RELPATH), JSON.stringify(meta, null, 2));\n}\n\nexport function snapshotTreeHashes(dir: string): Record<string, string> {\n const out: Record<string, string> = {};\n for (const relPath of collectArchiveRelPaths(dir)) {\n out[relPath] = createHash(\"sha256\")\n .update(fs.readFileSync(path.join(dir, relPath)))\n .digest(\"hex\");\n }\n return out;\n}\n\nexport function localTreeState(dir: string): {\n meta: LocalMeta | null;\n dirty: string[];\n clean: boolean;\n} {\n const meta = readLocalMeta(dir);\n const base = meta?.baseFiles;\n if (!base || typeof base !== \"object\") {\n return { meta, dirty: [], clean: false };\n }\n const now = snapshotTreeHashes(dir);\n const dirty = new Set<string>();\n for (const [p, h] of Object.entries(now)) if (base[p] !== h) dirty.add(p);\n for (const p of Object.keys(base)) if (!(p in now)) dirty.add(p);\n return { meta, dirty: [...dirty].sort(), clean: dirty.size === 0 };\n}\n\n// ── protocol helpers ─────────────────────────────────────────────────────────\n\nconst sha256b64 = (data: Buffer) =>\n createHash(\"sha256\").update(data).digest(\"base64\");\n\nfunction readPyproject(dir: string): { name?: string; version?: string } {\n try {\n const text = fs.readFileSync(path.join(dir, \"pyproject.toml\"), \"utf-8\");\n // Minimal [project] reads — name and version only, quoted single-line form.\n const section = /\\[project\\]([\\s\\S]*?)(\\n\\[|$)/.exec(text)?.[1] ?? \"\";\n const name = /\\bname\\s*=\\s*\"([^\"]+)\"/.exec(section)?.[1];\n const version = /\\bversion\\s*=\\s*\"([^\"]+)\"/.exec(section)?.[1];\n return { name, version };\n } catch {\n return {};\n }\n}\n\nfunction buildFileManifest(\n dir: string,\n): { path: string; isDirectory: boolean; size: number; sha256: string }[] {\n const entries: { path: string; isDirectory: boolean; size: number; sha256: string }[] = [];\n const walk = (rel: string) => {\n const abs = rel ? path.join(dir, rel) : dir;\n for (const entry of fs.readdirSync(abs, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {\n const childRel = rel ? `${rel}/${entry.name}` : entry.name;\n if (entry.isDirectory()) {\n if (!SKIP_DIRS.has(entry.name) && !entry.name.endsWith(\".egg-info\")) {\n walk(childRel);\n }\n } else if (entry.isFile()) {\n const payload = fs.readFileSync(path.join(dir, childRel));\n entries.push({\n path: childRel,\n isDirectory: false,\n size: payload.length,\n sha256: createHash(\"sha256\").update(payload).digest(\"hex\"),\n });\n }\n }\n };\n walk(\"\");\n return entries;\n}\n\nasync function putObject(url: string, data: Buffer, shaB64: string): Promise<void> {\n const resp = await fetch(url, {\n method: \"PUT\",\n headers: {\n \"Content-Type\": \"application/gzip\",\n \"x-amz-checksum-sha256\": shaB64,\n },\n body: new Uint8Array(data),\n });\n if (!resp.ok) {\n throw new Error(`object PUT -> ${resp.status}: ${(await resp.text()).slice(0, 300)}`);\n }\n}\n\n// ── the workflows ────────────────────────────────────────────────────────────\n\nexport async function push(\n dir: string,\n opts: {\n slug?: string;\n branch?: string;\n force?: boolean;\n message?: string;\n author?: string;\n /** Push on top of this version instead of the local meta's base — what a\n * CI checkout (which has no local meta) passes after resolving the\n * branch tip, so re-validating a PR replaces its own previous push\n * instead of 409ing against it. */\n baseVersionId?: string | null;\n /** Container metadata recorded on resolve — the Python CLI's --name,\n * --description, --tag and --visibility. */\n name?: string;\n description?: string;\n tags?: string[];\n visibility?: string;\n /** Pre-built OCI image ref for image/agentic envs (recorded on the version). */\n imageRef?: string;\n options?: WorldsClientOptions;\n } = {},\n): Promise<{\n containerId: string;\n slug: string;\n versionId: string;\n contentHash: string;\n branch: string;\n state: string | null;\n alreadyUploaded: boolean;\n}> {\n const options = opts.options ?? {};\n if (!fs.statSync(dir).isDirectory()) throw new Error(`Not a directory: ${dir}`);\n const localMeta = readLocalMeta(dir) ?? {};\n const branch = opts.branch ?? (localMeta.branch as string | undefined) ?? DEFAULT_BRANCH;\n const baseVersionId = opts.baseVersionId ?? localMeta.versionId ?? null;\n\n const contentHash = computeContentHash(dir);\n const pyproject = readPyproject(dir);\n const slug = opts.slug ?? pyproject.name ?? path.basename(path.resolve(dir));\n\n const resolve = await apiRequest<{ containerId: string }>(\n options,\n \"POST\",\n \"/api/public/benchmark-containers/resolve\",\n {\n slug,\n name: opts.name ?? pyproject.name ?? slug,\n ...(opts.description ? { description: opts.description } : {}),\n ...(opts.tags?.length ? { tags: opts.tags } : {}),\n ...(opts.visibility ? { visibility: opts.visibility } : {}),\n },\n );\n\n const tarball = buildSourceTarball(dir);\n const bundleSha256 = sha256b64(tarball);\n\n const version = await apiRequest<{\n versionId: string;\n uploadUrl?: string;\n alreadyUploaded?: boolean;\n }>(options, \"POST\", \"/api/public/benchmark-containers/versions\", {\n containerId: resolve.containerId,\n contentHash,\n bundleSha256,\n bundleSizeBytes: tarball.length,\n ...(pyproject.version ? { semanticVersion: pyproject.version } : {}),\n pyprojectMeta: pyproject,\n fileManifest: buildFileManifest(dir),\n branch,\n baseVersionId,\n ...(opts.force ? { force: true } : {}),\n ...(opts.message ? { changeReason: opts.message } : {}),\n ...(opts.author ? { author: opts.author } : {}),\n ...(opts.imageRef ? { imageRef: opts.imageRef } : {}),\n });\n\n if (version.uploadUrl) await putObject(version.uploadUrl, tarball, bundleSha256);\n\n const final = await apiRequest<{ state?: string; branch?: string }>(\n options,\n \"POST\",\n `/api/public/benchmark-containers/versions/${version.versionId}/finalize`,\n { branch, baseVersionId, ...(opts.force ? { force: true } : {}) },\n );\n\n writeLocalMeta(dir, {\n ...localMeta,\n slug,\n ref: branch,\n branch,\n versionId: version.versionId,\n contentHash,\n semanticVersion: pyproject.version,\n forkedFromVersionId: baseVersionId,\n baseFiles: snapshotTreeHashes(dir),\n });\n return {\n containerId: resolve.containerId,\n slug,\n versionId: version.versionId,\n contentHash,\n branch: final.branch ?? branch,\n state: final.state ?? null,\n alreadyUploaded: Boolean(version.alreadyUploaded),\n };\n}\n\n/** Extract a downloaded bundle into `dir` (paths sanitized). */\nfunction extractBundle(bundle: Buffer, dir: string): number {\n const tar = gunzipSync(bundle);\n let offset = 0;\n let longName: string | null = null;\n let written = 0;\n while (offset + 512 <= tar.length) {\n const header = tar.subarray(offset, offset + 512);\n offset += 512;\n if (header.every((b) => b === 0)) break;\n const rawName = header.subarray(0, 100).toString(\"utf-8\").replace(/\\0.*$/, \"\");\n const size = parseInt(header.subarray(124, 136).toString(\"ascii\").replace(/\\0.*$/, \"\").trim(), 8) || 0;\n const typeflag = header.subarray(156, 157).toString(\"ascii\");\n const body = tar.subarray(offset, offset + size);\n offset += size + (size % 512 === 0 ? 0 : 512 - (size % 512));\n if (typeflag === \"L\") {\n longName = body.toString(\"utf-8\").replace(/\\0.*$/, \"\");\n continue;\n }\n const name = (longName ?? rawName).replace(/^\\.\\//, \"\");\n longName = null;\n if (typeflag !== \"0\" && typeflag !== \"\") continue;\n // Safe extract: no absolute paths, no traversal.\n if (name.startsWith(\"/\") || name.split(\"/\").includes(\"..\")) continue;\n const target = path.join(dir, name);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n fs.writeFileSync(target, body);\n written++;\n }\n return written;\n}\n\nexport async function pull(\n slugRef: string,\n target?: string,\n options: WorldsClientOptions = {},\n): Promise<{ slug: string; dir: string; versionId: string; files: number }> {\n const at = slugRef.indexOf(\"@\");\n const slug = at === -1 ? slugRef : slugRef.slice(0, at);\n const ref = at === -1 ? \"latest\" : slugRef.slice(at + 1);\n\n const details = await apiRequest<{\n versionId: string;\n contentHash: string;\n semanticVersion?: string | null;\n downloadUrl?: string;\n bundleSha256?: string;\n }>(options, \"POST\", \"/api/public/benchmark-containers/resolve-version\", {\n slug,\n ref,\n });\n if (!details.downloadUrl) {\n throw new Error(`${slug}@${ref} resolved but has no uploaded bundle`);\n }\n\n let dir = target ?? path.join(process.cwd(), slug);\n if (!target) {\n let i = 1;\n const base = dir;\n while (fs.existsSync(dir)) dir = `${base}-${i++}`;\n }\n fs.mkdirSync(dir, { recursive: true });\n\n const resp = await fetch(details.downloadUrl);\n if (!resp.ok) throw new Error(`bundle download -> ${resp.status}`);\n const bundle = Buffer.from(await resp.arrayBuffer());\n if (details.bundleSha256 && sha256b64(bundle) !== details.bundleSha256) {\n throw new Error(\n `bundle integrity check failed for ${slug}@${ref}: downloaded sha256 != recorded bundleSha256`,\n );\n }\n\n const files = extractBundle(bundle, dir);\n const branch = ref === \"latest\" || /^\\d|^[0-9a-f]{8,}$/.test(ref) ? DEFAULT_BRANCH : ref;\n writeLocalMeta(dir, {\n slug,\n ref,\n branch,\n versionId: details.versionId,\n contentHash: details.contentHash,\n semanticVersion: details.semanticVersion ?? undefined,\n baseFiles: snapshotTreeHashes(dir),\n });\n return { slug, dir, versionId: details.versionId, files };\n}\n\nexport async function propose(\n dir: string,\n opts: { title: string; reason: string; targetBranch?: string; options?: WorldsClientOptions },\n): Promise<{ proposalId: string }> {\n const meta = readLocalMeta(dir);\n if (!meta?.slug || !meta.baseFiles) {\n throw new Error(\"This dir has no pull/push base — run pull first, then edit, then propose.\");\n }\n const state = localTreeState(dir);\n if (state.clean) throw new Error(\"Nothing to propose — the tree matches its base.\");\n const changes = state.dirty.map((relPath) => {\n const abs = path.join(dir, relPath);\n if (!fs.existsSync(abs)) return { path: relPath, action: \"delete\" as const };\n return {\n path: relPath,\n action: \"write\" as const,\n newContent: fs.readFileSync(abs, \"utf-8\"),\n };\n });\n const res = await apiRequest<{ proposalId: string }>(\n opts.options ?? {},\n \"POST\",\n \"/api/public/benchmark-containers/proposals\",\n {\n slug: meta.slug,\n title: opts.title,\n changeReason: opts.reason,\n baseVersionId: meta.versionId,\n ...(opts.targetBranch ? { targetBranch: opts.targetBranch } : {}),\n changes,\n },\n );\n return res;\n}\n\nexport async function createRef(\n slug: string,\n name: string,\n kind: \"branch\" | \"tag\",\n versionId?: string,\n options: WorldsClientOptions = {},\n): Promise<{ name: string; kind: string; versionId: string }> {\n return apiRequest(options, \"POST\", \"/api/public/benchmark-containers/refs\", {\n slug,\n name,\n kind,\n ...(versionId ? { versionId } : {}),\n });\n}\n","/**\n * PR validation: push the checkout's world source, run it, gate on the graded\n * result — one composed call, because CI should not have to re-derive the\n * choreography from primitives.\n *\n * The differentiating property, stated so it stays true: validation runs the\n * PULL REQUEST'S OWN world source. The push files the checkout as a version on\n * the PR's branch (content-hash dedup makes re-runs cheap), the dispatch pins\n * that version, and the platform resolves the branch back to its open PR — so\n * the run page names the PR and the PR comment names the run. Nothing here\n * validates a standing deployment while pretending to validate the change.\n */\n\nimport {\n apiRequest,\n detectProvenance,\n listRunConfigs,\n waitForRun,\n type RunReport,\n type WorldsClientOptions,\n} from \"./index\";\nimport { push } from \"./hub\";\n\nexport type ValidatedRun = {\n model: string;\n runId: string;\n report: RunReport | null;\n /** Why this run fails the gate, or null when it passes. */\n failure: string | null;\n};\n\nexport type ValidateReport = {\n ok: boolean;\n slug: string;\n branch: string;\n versionId: string;\n contentHash: string;\n runConfig: { id: string; name: string };\n runs: ValidatedRun[];\n /** A PR-comment-ready summary of the whole validation. */\n markdown: string;\n};\n\nfunction fmtScore(score: number | null): string {\n return score === null ? \"no score\" : score.toFixed(3);\n}\n\nfunction buildMarkdown(\n report: Omit<ValidateReport, \"markdown\">,\n minScore: number | null,\n source?: { repoUrl?: string; commit?: string },\n): string {\n const lines: string[] = [];\n lines.push(\n `### World validation ${report.ok ? \"passed\" : \"failed\"} — \\`${report.slug}@${report.branch}\\``,\n );\n lines.push(\"\");\n // Name the exact source that ran: the commit on GitHub when we know it,\n // always the content hash the platform pinned.\n const commitLink =\n source?.repoUrl && source?.commit\n ? `[\\`${source.commit.slice(0, 12)}\\`](${source.repoUrl}/commit/${source.commit})`\n : null;\n lines.push(\n `Ran the pull request's own world source` +\n (commitLink ? ` (${commitLink} on \\`${report.branch}\\`` : ` (`) +\n `${commitLink ? \", \" : \"\"}pinned as \\`${report.contentHash.slice(0, 12)}\\`) ` +\n `through run config **${report.runConfig.name}**` +\n (minScore !== null ? `, gating at score ≥ ${minScore}.` : \".\"),\n );\n lines.push(\"\");\n lines.push(\"| Model | Status | Score | Run |\");\n lines.push(\"| --- | --- | ---: | --- |\");\n for (const run of report.runs) {\n const r = run.report;\n const link = r?.url ? `[open](${r.url})` : \"—\";\n const status = run.failure\n ? `❌ ${run.failure}`\n : `✅ ${r?.status ?? \"COMPLETED\"}`;\n lines.push(\n `| \\`${run.model}\\` | ${status} | ${fmtScore(r?.score ?? null)} | ${link} |`,\n );\n }\n const taskRows = report.runs.flatMap((run) =>\n (run.report?.samples ?? []).map((sample) => ({\n model: run.model,\n task: sample.task ?? \"?\",\n reward: sample.reward,\n })),\n );\n // Every scenario, in the open: a validation whose per-scenario grades hide\n // behind a fold reads as one opaque number. Fold only when the table is\n // genuinely long.\n if (taskRows.length > 0) {\n const fold = taskRows.length > 12;\n lines.push(\"\");\n if (fold) {\n lines.push(\n `<details><summary>Per-scenario rewards (${taskRows.length})</summary>`,\n );\n lines.push(\"\");\n } else {\n lines.push(`**Scenarios (${taskRows.length})**`);\n lines.push(\"\");\n }\n lines.push(\"| Scenario | Model | Reward |\");\n lines.push(\"| --- | --- | ---: |\");\n for (const row of taskRows) {\n lines.push(\n `| ${row.task} | \\`${row.model}\\` | ${row.reward === null ? \"no score\" : row.reward.toFixed(2)} |`,\n );\n }\n if (fold) {\n lines.push(\"\");\n lines.push(\"</details>\");\n }\n }\n return lines.join(\"\\n\");\n}\n\n/**\n * Push `dir` on the current (or given) branch, dispatch the named run config\n * against the pushed version, wait for every run, and gate.\n *\n * The gate: every dispatch accepted, every run terminal COMPLETED, and — when\n * `minScore` is set — every run's score meets it. A run with NO score fails a\n * score gate rather than passing it: null is \"not scored\", never 0 and never\n * fine.\n */\nexport async function validateWorld(\n dir: string,\n opts: {\n slug?: string;\n runConfig: string;\n branch?: string;\n minScore?: number | null;\n timeoutMinutes?: number;\n onProgress?: (line: string) => void;\n options?: WorldsClientOptions;\n },\n): Promise<ValidateReport> {\n const options = opts.options ?? {};\n const progress = opts.onProgress ?? (() => {});\n const minScore = opts.minScore ?? null;\n\n const provenance = detectProvenance();\n const branch = opts.branch ?? provenance.branch;\n if (!branch)\n throw new Error(\n \"No branch to validate on: pass --branch or run inside a git checkout / GitHub Actions.\",\n );\n\n progress(`pushing ${dir} as ${opts.slug ?? \"(pyproject name)\"}@${branch}…`);\n // CI checkouts carry no local push meta, so a re-validation would 409\n // against the branch tip its own previous run created. Validation's\n // semantics are \"this branch's tip BECOMES the PR's source\": resolve the\n // current tip and push on top of it. A branch that does not exist yet\n // resolves to no base, which is a fresh branch — also correct.\n let tipVersionId: string | null = null;\n if (opts.slug) {\n try {\n const tip = await apiRequest<{ versionId?: string }>(\n options,\n \"POST\",\n \"/api/public/benchmark-containers/resolve-version\",\n { slug: opts.slug, ref: branch },\n );\n tipVersionId = tip.versionId ?? null;\n } catch {\n tipVersionId = null;\n }\n }\n const pushed = await push(dir, {\n slug: opts.slug,\n branch,\n baseVersionId: tipVersionId,\n message: `PR validation push (${provenance.commit?.slice(0, 12) ?? \"local\"})`,\n ...(provenance.actor?.name ? { author: provenance.actor.name } : {}),\n options,\n });\n progress(`pushed version ${pushed.versionId} (${pushed.contentHash.slice(0, 12)})`);\n\n // Resolve the run config by name (the stable handle CI configures) or id.\n const configs = await listRunConfigs(options);\n const runConfig =\n configs.find((c) => c.id === opts.runConfig) ??\n configs.find((c) => c.name === opts.runConfig);\n if (!runConfig) {\n const known = configs.map((c) => c.name).join(\", \") || \"(none)\";\n throw new Error(\n `Run config \"${opts.runConfig}\" not found in this project. Have: ${known}`,\n );\n }\n\n progress(`dispatching run config \"${runConfig.name}\" (${runConfig.models.join(\", \")})…`);\n const dispatched = await apiRequest<{\n versionLabel: string;\n runs: { model: string; runId: string; ok: boolean; error?: string }[];\n }>(options, \"POST\", \"/api/public/benchmark-containers/run-configs/dispatch\", {\n runConfigId: runConfig.id,\n versionId: pushed.versionId,\n ...provenance,\n });\n\n // The run's platform page. New deployments return it on the run report\n // (`url`); against an older deployment we build the same page from the\n // evaluation id, because a PR comment that cannot link the run defeats\n // the point of the comment.\n const host = (\n options.host ??\n process.env.GATEWAY_HOST ??\n \"https://withgateway.ai\"\n ).replace(/\\/+$/, \"\");\n let projectId: string | null = null;\n try {\n const projects = await apiRequest<{ data?: { id?: string }[] }>(\n options,\n \"GET\",\n \"/api/public/projects\",\n );\n projectId = projects.data?.[0]?.id ?? null;\n } catch {\n projectId = null;\n }\n const fallbackUrl = (report: RunReport): string | null => {\n if (report.url) return report.url;\n const evaluationId = report.evaluations[0]?.id;\n return projectId && evaluationId\n ? `${host}/project/${projectId}/environment/runs/${encodeURIComponent(evaluationId)}`\n : null;\n };\n\n const runs: ValidatedRun[] = [];\n for (const run of dispatched.runs) {\n if (!run.ok) {\n runs.push({\n model: run.model,\n runId: run.runId,\n report: null,\n failure: `dispatch failed: ${run.error ?? \"unknown error\"}`,\n });\n continue;\n }\n progress(`waiting on ${run.model} (run ${run.runId})…`);\n let report: RunReport | null = null;\n let failure: string | null = null;\n try {\n report = await waitForRun(run.runId, {\n timeoutMinutes: opts.timeoutMinutes ?? 45,\n options,\n onTick: (r) =>\n progress(\n `…${run.model}: ${r.status.toLowerCase()} (${r.shardsCompleted ?? 0}/${r.parallelism} shards)`,\n ),\n });\n report = { ...report, url: fallbackUrl(report) };\n if (report.status.toUpperCase() !== \"COMPLETED\") {\n failure = report.status;\n } else if (minScore !== null) {\n if (report.score === null) failure = \"completed without a score\";\n else if (report.score < minScore)\n failure = `score ${fmtScore(report.score)} < ${minScore}`;\n }\n } catch (error) {\n failure = error instanceof Error ? error.message : String(error);\n }\n runs.push({ model: run.model, runId: run.runId, report, failure });\n }\n\n const base = {\n ok: runs.length > 0 && runs.every((r) => r.failure === null),\n slug: pushed.slug,\n branch,\n versionId: pushed.versionId,\n contentHash: pushed.contentHash,\n runConfig: { id: runConfig.id, name: runConfig.name },\n runs,\n };\n return {\n ...base,\n markdown: buildMarkdown(base, minScore, {\n repoUrl: provenance.repoUrl,\n commit: provenance.commit,\n }),\n };\n}\n","/**\n * Worlds from TypeScript: identity, tasks, and HOSTED execution.\n *\n * The same three-level model as the Python SDK — WorldSet → Task — with one\n * deliberate difference: a world's tools are Python modules, so TypeScript\n * does not materialize task environments in-process. What a TS agent\n * codebase needs is exactly what this module provides: resolve a world ref\n * to its pinned version, read its task list, and dispatch HOSTED runs\n * (parallelism included) that execute the world server-side and file graded,\n * version-pinned rollouts. Local in-process execution stays a Python\n * capability by design, not by omission.\n */\n\nimport type { WorldTaskIdRef } from \"./session\";\n\nexport type WorldsClientOptions = {\n host?: string;\n publicKey?: string;\n secretKey?: string;\n};\n\nexport type ResolvedWorldVersion = {\n versionId: string;\n semanticVersion: string | null;\n contentHash: string;\n state?: string;\n};\n\nexport type WorldTaskInfo = {\n name: string;\n variant: string | null;\n};\n\nexport type DispatchedRun = {\n model: string;\n runId: string;\n ok: boolean;\n error?: string;\n};\n\nfunction resolveEnv(options: WorldsClientOptions) {\n const host =\n options.host ?? process.env.GATEWAY_HOST ?? \"https://withgateway.ai\";\n const publicKey = options.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;\n const secretKey = options.secretKey ?? process.env.GATEWAY_SECRET_KEY;\n if (!publicKey || !secretKey) {\n throw new Error(\n \"Gateway keys missing: set GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY \" +\n \"(or pass publicKey/secretKey).\",\n );\n }\n return { host: host.replace(/\\/+$/, \"\"), publicKey, secretKey };\n}\n\n/** Authenticated JSON request against the platform API — the primitive the\n * worlds helpers and the TS CLI share. */\nexport async function apiRequest<T>(\n options: WorldsClientOptions,\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\",\n path: string,\n body?: unknown,\n): Promise<T> {\n const { host, publicKey, secretKey } = resolveEnv(options);\n const res = await fetch(`${host}${path}`, {\n method,\n headers: {\n \"content-type\": \"application/json\",\n authorization:\n \"Basic \" + Buffer.from(`${publicKey}:${secretKey}`).toString(\"base64\"),\n },\n ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n });\n const text = await res.text();\n if (!res.ok) {\n throw new Error(\n `${method} ${path} -> ${res.status}: ${text.slice(0, 400)}`,\n );\n }\n return JSON.parse(text) as T;\n}\n\n/** Set (or rotate) one environment secret — write-only: no API returns it. */\nexport async function setEnvSecret(\n slug: string,\n key: string,\n value: string,\n options: WorldsClientOptions = {},\n): Promise<{ key: string; created: boolean }> {\n return apiRequest(\n options,\n \"PUT\",\n \"/api/public/benchmark-containers/secrets\",\n {\n slug,\n key,\n value,\n },\n );\n}\n\n/** Keys and rotation timestamps only — never values. */\nexport async function listEnvSecretKeys(\n slug: string,\n options: WorldsClientOptions = {},\n): Promise<{ key: string; updatedAt: string }[]> {\n const res = await apiRequest<{\n secrets: { key: string; updatedAt: string }[];\n }>(\n options,\n \"GET\",\n `/api/public/benchmark-containers/secrets?slug=${encodeURIComponent(slug)}`,\n );\n return res.secrets;\n}\n\nexport async function deleteEnvSecret(\n slug: string,\n key: string,\n options: WorldsClientOptions = {},\n): Promise<void> {\n await apiRequest(\n options,\n \"DELETE\",\n \"/api/public/benchmark-containers/secrets\",\n {\n slug,\n key,\n },\n );\n}\n\nexport type RunConfigSummary = {\n id: string;\n name: string;\n runType: string;\n createdAt: string;\n models: string[];\n parallelism: number;\n autoRunOnPush: boolean;\n agent: string | null;\n};\n\n/** Run configs in the project. CI resolves by NAME and dispatches by id. */\nexport async function listRunConfigs(\n options: WorldsClientOptions = {},\n): Promise<RunConfigSummary[]> {\n const res = await apiRequest<{ runConfigs: RunConfigSummary[] }>(\n options,\n \"GET\",\n \"/api/public/benchmark-containers/run-configs\",\n );\n return res.runConfigs;\n}\n\n/** What a run config selects for the runner to work through. A config runs\n * EITHER the bundle's own scenarios (`taskNames`, `taskSetDatasetId`) OR the\n * project's stored tasks (`worldTasks`, api worlds only) — never both. A\n * stored task ref without `version` runs the task's current version at\n * dispatch time; with it, that version forever. */\nexport type RunConfigInput = {\n id?: string;\n name: string;\n models: string[];\n parallelism?: number;\n numExamples?: number;\n rolloutsPerExample?: number;\n timeoutMinutes?: number;\n agent?: string;\n taskSetDatasetId?: string | null;\n taskNames?: string[];\n worldTasks?: WorldTaskIdRef[];\n autoRunOnPush?: boolean;\n};\n\n/** Create a run config, or update the one named by `id`. */\nexport async function upsertRunConfig(\n input: RunConfigInput,\n options: WorldsClientOptions = {},\n): Promise<RunConfigSummary> {\n return apiRequest<RunConfigSummary>(\n options,\n \"POST\",\n \"/api/public/benchmark-containers/run-configs\",\n input,\n );\n}\n\n/** `id[@version]` items (comma-separated or an array) → stored task refs;\n * the spelling `bench run-configs create --world-tasks` takes. */\nexport function parseWorldTaskRefs(spec: string | string[]): WorldTaskIdRef[] {\n const items = (Array.isArray(spec) ? spec : spec.split(\",\"))\n .map((s) => s.trim())\n .filter(Boolean);\n return items.map((item) => {\n const at = item.lastIndexOf(\"@\");\n if (at < 0) return { id: item };\n const id = item.slice(0, at);\n const version = Number(item.slice(at + 1));\n if (!id || !Number.isInteger(version) || version < 1)\n throw new Error(\n `stored task ref '${item}' is not <id> or <id>@<version> (version a positive integer)`,\n );\n return { id, version };\n });\n}\n\nexport type RunReport = {\n id: string;\n status: string;\n terminal: boolean;\n score: number | null;\n summary: string | null;\n model: string | null;\n versionLabel: string | null;\n parallelism: number;\n shardsCompleted: number | null;\n /** The run's page on the platform — what a PR comment should link. */\n url: string | null;\n evaluations: {\n id: string;\n status: string;\n avgReward: number | null;\n url: string | null;\n }[];\n samples: {\n task: string | null;\n reward: number | null;\n rewards: Record<string, unknown>;\n sessionId: string | null;\n }[];\n};\n\n/** The read half of dispatch: status, score, per-shard evaluations, and\n * per-task rewards — everything a CI gate needs. */\nexport async function getRun(\n runId: string,\n options: WorldsClientOptions = {},\n): Promise<RunReport> {\n return apiRequest(\n options,\n \"GET\",\n `/api/public/benchmark-containers/runs/${encodeURIComponent(runId)}`,\n );\n}\n\n/** Poll a run to terminal (default every 20s, up to `timeoutMinutes`). */\nexport async function waitForRun(\n runId: string,\n opts: {\n timeoutMinutes?: number;\n intervalSeconds?: number;\n onTick?: (run: RunReport) => void;\n options?: WorldsClientOptions;\n } = {},\n): Promise<RunReport> {\n const deadline = Date.now() + (opts.timeoutMinutes ?? 45) * 60_000;\n for (;;) {\n const run = await getRun(runId, opts.options ?? {});\n if (run.terminal) return run;\n if (Date.now() > deadline)\n throw new Error(\n `Run ${runId} still ${run.status} after the wait timeout.`,\n );\n opts.onTick?.(run);\n await new Promise((resolve) =>\n setTimeout(resolve, (opts.intervalSeconds ?? 20) * 1000),\n );\n }\n}\n\nexport type RunProvenance = {\n branch?: string;\n commit?: string;\n repoUrl?: string;\n actor?: { id?: string; name?: string; imageUrl?: string; kind?: string };\n};\n\n/**\n * Where a dispatch comes from, DETECTED rather than configured: the CI\n * checkout's branch/commit/actor under GitHub Actions, else the developer's\n * own git checkout. A run nobody can trace to a branch is a score with no\n * code attached, so every dispatch carries this unless overridden.\n */\nexport function detectProvenance(): RunProvenance {\n const env =\n (globalThis as { process?: { env?: Record<string, string | undefined> } })\n .process?.env ?? {};\n const out: RunProvenance = {};\n const ref = env.GITHUB_HEAD_REF || env.GITHUB_REF_NAME;\n if (ref) out.branch = ref;\n if (env.GITHUB_SHA) out.commit = env.GITHUB_SHA;\n const server = env.GITHUB_SERVER_URL ?? \"https://github.com\";\n if (env.GITHUB_REPOSITORY) out.repoUrl = `${server}/${env.GITHUB_REPOSITORY}`;\n if (env.GITHUB_ACTOR) {\n out.actor = {\n kind: \"ci\",\n id: env.GITHUB_ACTOR,\n name: env.GITHUB_ACTOR,\n // GitHub serves every account's avatar at /<login>.png.\n imageUrl: `${server}/${env.GITHUB_ACTOR}.png`,\n };\n }\n if (!out.branch || !out.commit) {\n try {\n const { execFileSync } =\n require(\"node:child_process\") as typeof import(\"node:child_process\");\n const git = (args: string[]) =>\n execFileSync(\"git\", args, {\n encoding: \"utf-8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n })\n .toString()\n .trim();\n out.branch = out.branch ?? git([\"rev-parse\", \"--abbrev-ref\", \"HEAD\"]);\n out.commit = out.commit ?? git([\"rev-parse\", \"HEAD\"]);\n if (!out.repoUrl) {\n const remote = git([\"config\", \"--get\", \"remote.origin.url\"]);\n if (remote) out.repoUrl = remote.replace(/\\.git$/, \"\");\n }\n if (!out.actor) {\n const name = git([\"config\", \"--get\", \"user.name\"]);\n if (name) out.actor = { kind: \"user\", name };\n }\n } catch {\n // No git here — dispatch without provenance rather than failing.\n }\n }\n return out;\n}\n\n/** One scenario of a world, as data. */\nexport class WorldTask {\n constructor(\n readonly world: WorldSet,\n readonly name: string,\n readonly variant: string | null,\n ) {}\n}\n\n/**\n * THE world, from a TS process: pinned identity + its tasks + hosted runs.\n *\n * const world = await openWorld(\"google-drive-sim@main\");\n * console.log(world.version.semanticVersion, world.tasks.length);\n * const runs = await world.dispatch(runConfigId);\n */\nexport class WorldSet {\n constructor(\n readonly slugRef: string,\n readonly slug: string,\n readonly ref: string | null,\n readonly version: ResolvedWorldVersion,\n public tasks: WorldTask[],\n private readonly options: WorldsClientOptions,\n ) {}\n\n task(variant: string): WorldTask {\n const hit = this.tasks.find(\n (t) => t.variant === variant || t.name.includes(variant),\n );\n if (!hit) {\n const known = this.tasks.map((t) => t.variant ?? t.name).join(\", \");\n throw new Error(`no task matches ${variant}; have: ${known}`);\n }\n return hit;\n }\n\n /**\n * Open a LIVE session against one of this world's tasks — a bundled task's\n * name or an inline `WorldTaskSpec`: the platform boots (or reuses) a warm\n * container, and your agent calls its tools through the platform. See\n * worlds/session.ts.\n */\n async open(\n task: import(\"./session\").WorldTaskRef,\n opts: {\n reuseWarm?: boolean;\n surfaces?: import(\"./browser\").WorldSurfaceKind[];\n } = {},\n ): Promise<import(\"./session\").WorldSession> {\n const { openSession } = await import(\"./session\");\n return openSession(this.slug, {\n task,\n versionId: this.version.versionId,\n reuseWarm: opts.reuseWarm,\n surfaces: opts.surfaces,\n options: this.options,\n });\n }\n\n /**\n * Start a HOSTED run of a run config against this world — the platform\n * executes the (Python) world in parallel containers per the config's\n * `parallelism` and files one graded run per model. Returns those runs.\n */\n async dispatch(\n runConfigId: string,\n opts: {\n containerId?: string;\n versionId?: string;\n /** Override the auto-detected branch/commit/actor. */\n provenance?: RunProvenance;\n } = {},\n ): Promise<{ versionLabel: string; runs: DispatchedRun[] }> {\n const provenance = opts.provenance ?? detectProvenance();\n return apiRequest(\n this.options,\n \"POST\",\n \"/api/public/benchmark-containers/run-configs/dispatch\",\n {\n runConfigId,\n ...(opts.containerId ? { containerId: opts.containerId } : {}),\n versionId: opts.versionId ?? this.version.versionId,\n ...provenance,\n },\n );\n }\n}\n\n/**\n * Resolve `slug` / `slug@branch|tag|semver|hash` to its pinned version and\n * task list. The task list comes from the version's file manifest\n * (`tasks/<name>/task.toml`), so it needs no bundle download.\n */\nexport async function openWorld(\n slugRef: string,\n options: WorldsClientOptions = {},\n): Promise<WorldSet> {\n const at = slugRef.indexOf(\"@\");\n const slug = at === -1 ? slugRef : slugRef.slice(0, at);\n const ref = at === -1 ? null : slugRef.slice(at + 1);\n\n const version = await apiRequest<\n ResolvedWorldVersion & { taskNames?: string[] }\n >(options, \"POST\", \"/api/public/benchmark-containers/resolve-version\", {\n slug,\n ...(ref ? { ref } : {}),\n });\n\n const world = new WorldSet(\n slugRef,\n slug,\n ref,\n {\n versionId: version.versionId,\n semanticVersion: version.semanticVersion ?? null,\n contentHash: version.contentHash,\n state: version.state,\n },\n [],\n options,\n );\n for (const name of version.taskNames ?? []) {\n const variant = /^[a-z0-9]+-([a-z0-9]+)-/.exec(name)?.[1] ?? null;\n world.tasks.push(new WorldTask(world, name, variant));\n }\n return world;\n}\n\n// The session surface completes the worlds module, so `@withgateway/sdk/worlds`\n// carries both halves: running a world locally, and driving one the platform\n// hosts. (session.ts imports apiRequest from here; the cycle is function-level\n// only, and the build below is what proves it resolves.)\nexport * from \"./session\";\n\n// Stored tasks: the task spec as a named, versioned project resource that\n// `openSession(world, { task: { id } })` opens on.\nexport * from \"./tasks\";\n\n// The computer-use half: surfaces, a Playwright browser on the world's UI,\n// and browser actions as model tools.\nexport * from \"./browser\";\n\n// The hub half: push, pull, propose and the content-hash primitives the CLI\n// runs on. These were reachable only from inside the package, so a consumer\n// could drive a world but never publish one.\nexport * from \"./hub\";\n\n// PR validation: push-dispatch-wait-gate as one composed call, for CI.\nexport * from \"./validate\";\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport type { Credentials } from \"../config\";\nimport {\n readWorldFiles,\n runtime,\n writeWorldFiles,\n type WorldFile,\n} from \"./client\";\n\n/**\n * Rows into, and counts out of, a world that lives in a LOCAL directory. The\n * `worlds data import|show` commands (registered by the platform track) call\n * these two for the directory case; a slug goes to the platform's world data\n * routes instead. The gate is the world's own contract, run by the platform\n * runtime: a bad row is refused with the field named and nothing is written.\n */\n\nexport type Rows = Record<string, Record<string, unknown>[]>;\nexport type ImportMode = \"append\" | \"replace\";\n\nexport type LocalImportResult = {\n kind: string;\n entity_counts: Record<string, number>;\n changed: boolean;\n};\n\nexport async function importLocalWorldData(\n dir: string,\n rows: Rows,\n opts: { mode?: ImportMode },\n creds: Credentials | null,\n): Promise<LocalImportResult> {\n const res = await runtime<{\n kind?: string;\n entity_counts?: Record<string, number>;\n changed?: boolean;\n files?: WorldFile[];\n }>(creds, {\n command: \"import-data\",\n files: readWorldFiles(dir),\n rows,\n mode: opts.mode ?? \"append\",\n });\n if (res.files?.length) writeWorldFiles(dir, res.files);\n // Snapshots are build outputs, not tree files: the runtime answers without\n // them, and the ones on disk were built from the journals BEFORE this import.\n // A served world ignores a stale snapshot and replays the journals, but the\n // files would still sit there claiming an older state — drop them, and let\n // `worlds schema compile` build them again from the data that is there now.\n if (res.changed) dropBuildOutputs(dir);\n return {\n kind: res.kind ?? \"unknown\",\n entity_counts: res.entity_counts ?? {},\n changed: Boolean(res.changed),\n };\n}\n\nconst BUILD_OUTPUT = /(^|\\/)state\\.(sqlite|json)$/;\n\n/** Remove the compiled snapshots (`db/state.*`, `scenarios/<name>/state.*`)\n * that no longer match the tree's journals. */\nexport function dropBuildOutputs(dir: string): string[] {\n const dropped: string[] = [];\n for (const file of readWorldFiles(dir, { buildOutputs: true })) {\n if (!BUILD_OUTPUT.test(file.path)) continue;\n fs.rmSync(path.join(dir, file.path), { force: true });\n dropped.push(file.path);\n }\n return dropped;\n}\n\n/**\n * The same bridge import over the tree, with the answered files discarded:\n * the rows are checked through the world's contract and nothing on disk\n * changes. A refused row surfaces as a BridgeRejected, as an import would.\n */\nexport async function checkLocalWorldData(\n dir: string,\n rows: Rows,\n creds: Credentials | null,\n): Promise<LocalImportResult> {\n const res = await runtime<{\n kind?: string;\n entity_counts?: Record<string, number>;\n changed?: boolean;\n }>(creds, {\n command: \"import-data\",\n files: readWorldFiles(dir),\n rows,\n mode: \"append\",\n });\n return {\n kind: res.kind ?? \"unknown\",\n entity_counts: res.entity_counts ?? {},\n changed: Boolean(res.changed),\n };\n}\n\nexport type LocalShowResult = {\n kind: string;\n entity_counts?: Record<string, number>;\n entity?: string;\n rows?: Record<string, unknown>[];\n};\n\nexport async function showLocalWorldData(\n dir: string,\n entity: string | undefined,\n creds: Credentials | null,\n): Promise<LocalShowResult> {\n const res = await runtime<{\n kind?: string;\n entity_counts?: Record<string, number>;\n rows?: Record<string, unknown>[];\n }>(creds, {\n command: \"counts\",\n files: readWorldFiles(dir),\n ...(entity ? { entity } : {}),\n });\n const out: LocalShowResult = { kind: res.kind ?? \"unknown\" };\n if (entity) {\n out.entity = entity;\n out.rows = res.rows ?? [];\n } else out.entity_counts = res.entity_counts ?? {};\n return out;\n}\n","import { CommandGroup, dispatch } from \"./router\";\nimport { registerPlatformCommands } from \"./platform/index\";\nimport { registerRuntimeCommands } from \"./runtime/index\";\n\n/** The whole tree, built once; `gateway --help` lists the groups. */\nexport function buildCli(): CommandGroup {\n const root = new CommandGroup(\n \"gateway\",\n \"Gateway: worlds, connectors, sessions, runs and releases from the terminal.\",\n );\n root.group(\"auth\", \"Save or inspect the platform credentials this CLI uses.\");\n root.group(\"secret\", \"Project secrets (write-only).\");\n root.group(\"agent\", \"Registered agents.\");\n root.group(\"run\", \"Platform optimization runs.\");\n root.group(\"dataset\", \"Datasets and task files.\");\n root.group(\n \"bench\",\n \"Worlds as versioned bundles: push, pull, fork, diff, propose, dispatch.\",\n );\n const worlds = root.group(\"worlds\", \"Build, seed, serve and run worlds.\");\n worlds.group(\n \"session\",\n \"Live hosted sessions with api, ui and browser surfaces.\",\n );\n worlds.group(\n \"schema\",\n \"Compile and check gateway-world/1 contracts (the runtime runs on the platform).\",\n );\n worlds.group(\n \"connector\",\n \"Vendor connections: validate, capture, conform, ingest, publish, clone.\",\n );\n worlds.group(\"data\", \"Put rows into a world, or see what it holds.\");\n root.group(\n \"environment\",\n \"Environments: runs, tasks, rollouts, performance, agent triggers.\",\n );\n root.group(\"release\", \"Release gates.\");\n registerPlatformCommands(root);\n registerRuntimeCommands(root);\n return root;\n}\n\nexport async function main(argv = process.argv.slice(2)): Promise<number> {\n const stdinOnce = async () => {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) chunks.push(chunk as Buffer);\n return Buffer.concat(chunks).toString(\"utf8\");\n };\n return dispatch(buildCli(), argv, {\n stdout: (line) => process.stdout.write(line + \"\\n\"),\n stderr: (line) => process.stderr.write(line + \"\\n\"),\n stdin: stdinOnce,\n stdinStream: () => process.stdin,\n });\n}\n","import { api } from \"../config\";\nimport type { CommandGroup } from \"../router\";\nimport { API_KEY_FLAG, credentials, HOST_FLAG } from \"./shared\";\n\nexport type AgentRow = {\n name?: string;\n image?: string;\n compatibleAlgorithms?: string[];\n taskInputSchema?: unknown;\n};\n\n/** `gateway agent list` over /api/public/agents. */\nexport function registerAgentCommands(root: CommandGroup): void {\n const agent = root.group(\"agent\", \"Manage registered agents.\");\n\n agent.command({\n name: \"list\",\n help: \"List registered agents.\",\n flags: [HOST_FLAG, API_KEY_FLAG],\n run: async (args, ctx) => {\n const res = await api<{ agents?: AgentRow[] }>(credentials(args), \"GET\", \"/api/public/agents\");\n const agents = res.agents ?? [];\n if (agents.length === 0) {\n ctx.stdout(\"No agents registered. Run `gateway deploy` to register an agent.\");\n return;\n }\n ctx.stdout(`${\"Name\".padEnd(20)} ${\"Image\".padEnd(30)} Compatible`);\n ctx.stdout(\"-\".repeat(70));\n for (const a of agents) {\n const compat = (a.compatibleAlgorithms ?? []).join(\", \");\n ctx.stdout(`${(a.name ?? \"\").padEnd(20)} ${(a.image ?? \"\").slice(0, 28).padEnd(30)} ${compat}`);\n }\n },\n });\n}\n","import * as fs from \"node:fs\";\n\nimport { resolveCredentials, type Credentials } from \"../config\";\nimport { arg, CliError, type CommandContext, type FlagSpec, type Parsed } from \"../router\";\nimport type { WorldsClientOptions } from \"../../worlds/index\";\n\n/** `--host` exactly as the Python CLI declares it (env GATEWAY_HOST). */\nexport const HOST_FLAG: FlagSpec = {\n name: \"host\",\n help: \"Gateway server URL (e.g. https://withgateway.ai).\",\n env: \"GATEWAY_HOST\",\n};\n\n/** `--api-key` where the Python command takes one (env GATEWAY_SECRET_KEY). */\nexport const API_KEY_FLAG: FlagSpec = {\n name: \"api-key\",\n help: \"Project secret key (sk-lf-...).\",\n env: \"GATEWAY_SECRET_KEY\",\n};\n\n/** Credentials for a command: --host / --api-key first, then env, then ~/.gateway/config.json. */\nexport function credentials(args: Parsed): Credentials {\n const creds = resolveCredentials(arg.str(args, \"host\"));\n const apiKey = arg.str(args, \"api-key\");\n return apiKey ? { ...creds, secretKey: apiKey } : creds;\n}\n\n/** The same credentials in the shape the `worlds/*` helpers take. */\nexport function worldsOptions(creds: Credentials): WorldsClientOptions {\n return { host: creds.host, publicKey: creds.publicKey, secretKey: creds.secretKey };\n}\n\nexport type RawResponse = {\n status: number;\n ok: boolean;\n text: string;\n json: () => unknown;\n};\n\n/**\n * One request whose status the command inspects itself (409 → update, 404 →\n * untested, …), where `api()`'s throw-on-non-2xx would hide the branch.\n */\nexport async function rawRequest(\n creds: Credentials,\n method: \"GET\" | \"POST\" | \"PUT\" | \"DELETE\",\n route: string,\n body?: unknown,\n): Promise<RawResponse> {\n const res = await fetch(`${creds.host}${route}`, {\n method,\n headers: {\n \"content-type\": \"application/json\",\n accept: \"application/json\",\n authorization:\n \"Basic \" + Buffer.from(`${creds.publicKey}:${creds.secretKey}`).toString(\"base64\"),\n },\n ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n });\n const text = await res.text();\n return {\n status: res.status,\n ok: res.ok,\n text,\n json: () => (text ? JSON.parse(text) : {}),\n };\n}\n\nexport function query(params: Record<string, string | number | boolean | undefined | null>): string {\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined || value === null || value === \"\") continue;\n search.set(key, String(value));\n }\n const encoded = search.toString();\n return encoded ? `?${encoded}` : \"\";\n}\n\nexport function failed(status: number, text: string): CliError {\n return new CliError(`Failed (HTTP ${status}): ${text}`, 1);\n}\n\nexport const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));\n\n/** Where the Python CLI needed its own runtime: say so, name the equivalent, exit 2. */\nexport function pythonOnly(ctx: CommandContext, command: string, reason: string, equivalent: string): number {\n ctx.stderr(`'gateway ${command}' is Python-only: ${reason}\\n${equivalent}`);\n return 2;\n}\n\n/** Append a markdown block to $GITHUB_STEP_SUMMARY when Actions provides one; never fatal. */\nexport function appendStepSummary(text: string): void {\n const path = process.env.GITHUB_STEP_SUMMARY;\n if (!path) return;\n try {\n fs.appendFileSync(path, text + \"\\n\\n\");\n } catch {\n // the summary is a nicety; the exit code is the contract\n }\n}\n","import { clearConfig, configPath, readConfig, writeConfig } from \"../config\";\nimport { arg, CliError, type CommandGroup } from \"../router\";\n\n/** `gateway auth login|logout|status` — the credentials file the other commands read. */\nexport function registerAuthCommands(root: CommandGroup): void {\n const auth = root.group(\"auth\", \"Manage authentication credentials.\");\n\n auth.command({\n name: \"login\",\n help: \"Store credentials for the gateway CLI.\",\n flags: [\n { name: \"host\", help: \"Gateway server URL\", env: \"GATEWAY_HOST\" },\n { name: \"public-key\", help: \"Project public key (pk-lf-...)\", env: \"GATEWAY_PUBLIC_KEY\" },\n { name: \"api-key\", help: \"Project secret key (sk-lf-...)\", env: \"GATEWAY_SECRET_KEY\" },\n ],\n notes: \"The Python CLI prompts for what is missing; here pass all three flags (or set the env vars).\",\n run: async (args, ctx) => {\n const host = arg.str(args, \"host\");\n const publicKey = arg.str(args, \"public-key\");\n const apiKey = arg.str(args, \"api-key\");\n if (!host || !publicKey || !apiKey)\n throw new CliError(\"auth login needs --host, --public-key and --api-key\");\n writeConfig({ host: host.replace(/\\/+$/, \"\"), public_key: publicKey, api_key: apiKey });\n ctx.stdout(`Credentials saved to ${configPath()}`);\n },\n });\n\n auth.command({\n name: \"logout\",\n help: \"Clear stored credentials.\",\n run: async (_args, ctx) => {\n ctx.stdout(clearConfig() ? \"Credentials cleared.\" : \"No credentials stored.\");\n },\n });\n\n auth.command({\n name: \"status\",\n help: \"Show current authentication status.\",\n run: async (_args, ctx) => {\n // The environment wins over the stored file, the same order every\n // command resolves credentials in; say which one is in effect.\n const envHost = process.env.GATEWAY_HOST;\n const envKey = process.env.GATEWAY_SECRET_KEY ?? process.env.GATEWAY_API_KEY;\n if (envHost || envKey) {\n ctx.stdout(`Host: ${envHost ?? \"(not set)\"} (from environment)`);\n ctx.stdout(`API key: ${envKey ? \"configured\" : \"not set\"} (from environment)`);\n return;\n }\n const config = readConfig();\n if (!config.host) {\n ctx.stdout(\"No credentials stored. Run `gateway auth login`.\");\n return;\n }\n ctx.stdout(`Host: ${config.host}`);\n ctx.stdout(`API key: ${config.api_key ? \"configured\" : \"not set\"}`);\n },\n });\n}\n","import * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\n\nimport { api, printJson } from \"../config\";\nimport { arg, CliError, type CommandContext, type CommandGroup, type FlagSpec, type Parsed } from \"../router\";\nimport { readWorldFiles, runtime, writeWorldFiles } from \"../runtime/client\";\nimport { credentialsForRuntime } from \"../runtime/local\";\nimport {\n deleteEnvSecret,\n getRun,\n listEnvSecretKeys,\n listRunConfigs,\n openWorld,\n parseWorldTaskRefs,\n setEnvSecret,\n waitForRun,\n} from \"../../worlds/index\";\nimport {\n computeContentHash,\n createRef,\n DEFAULT_BRANCH,\n localTreeState,\n propose,\n pull,\n push,\n readLocalMeta,\n writeLocalMeta,\n} from \"../../worlds/hub\";\nimport { validateWorld } from \"../../worlds/validate\";\nimport { credentials, HOST_FLAG, pythonOnly, query, worldsOptions } from \"./shared\";\n\n// ── semver bumps (port of benchmark_hub/versioning.py) ──────────────────────\n\n/** Patch bump: `1.2.3` -> `1.2.4`; strips a `-`/`+` suffix to find the patch. */\nexport function bumpVersion(version: string): string {\n const parts = version.split(\".\");\n if (parts.length >= 3) {\n const patchPart = parts[2]!;\n const patchNum = patchPart.includes(\"-\")\n ? patchPart.split(\"-\")[0]!\n : patchPart.includes(\"+\")\n ? patchPart.split(\"+\")[0]!\n : patchPart;\n if (/^\\d+$/.test(patchNum)) {\n parts[2] = String(Number(patchNum) + 1);\n return parts.join(\".\");\n }\n return `${version}.1`;\n }\n if (parts.length === 2) return `${version}.1`;\n return `${version}.0.1`;\n}\n\n/** `1.2.3` -> `1.2.3.rc0`, `1.2.3.rc0` -> `1.2.3.rc1`. */\nexport function bumpRcVersion(version: string): string {\n const m = /^(.*?)(?:\\.rc|rc)(\\d+)$/.exec(version);\n if (m) return `${m[1]}.rc${Number(m[2]) + 1}`;\n return `${version.replace(/([+-].*)$/, \"\")}.rc0`;\n}\n\n/** `1.2.3` -> `1.2.3.post0`, `1.2.3.post0` -> `1.2.3.post1`. */\nexport function bumpPostVersion(version: string): string {\n const m = /^(.*?)(?:\\.post|post)(\\d+)$/.exec(version);\n if (m) return `${m[1]}.post${Number(m[2]) + 1}`;\n return `${version.replace(/([+-].*)$/, \"\")}.post0`;\n}\n\nfunction readPyprojectVersion(dir: string): string | undefined {\n try {\n const text = fs.readFileSync(path.join(dir, \"pyproject.toml\"), \"utf8\");\n const section = /\\[project\\]([\\s\\S]*?)(\\n\\[|$)/.exec(text)?.[1] ?? \"\";\n return /\\bversion\\s*=\\s*\"([^\"]+)\"/.exec(section)?.[1];\n } catch {\n return undefined;\n }\n}\n\n/** Rewrite the `version = \"...\"` line in place (formatting and comments kept). */\nexport function updatePyprojectVersion(file: string, newVersion: string): void {\n const content = fs.readFileSync(file, \"utf8\");\n const updated = content.replace(/(\\s*)version\\s*=\\s*[\"'][^\"']*[\"']/, `$1version = \"${newVersion}\"`);\n if (updated === content) throw new CliError(\"version line not found or unchanged in pyproject.toml\", 1);\n fs.writeFileSync(file, updated);\n}\n\n/** Apply `--auto-bump` / `--rc` / `--post` to the working tree before hashing. */\nexport function applyVersionBump(dir: string, args: Parsed): string | null {\n const picked = [\"auto-bump\", \"rc\", \"post\"].filter((name) => arg.bool(args, name));\n if (picked.length === 0) return null;\n if (picked.length > 1) throw new CliError(\"--auto-bump, --rc and --post are mutually exclusive\");\n const current = readPyprojectVersion(dir);\n if (!current)\n throw new CliError(\n `--${picked[0]} needs a [project].version in ${path.join(dir, \"pyproject.toml\")} to bump; this dir has none.`,\n 1,\n );\n const next =\n picked[0] === \"auto-bump\" ? bumpVersion(current) : picked[0] === \"rc\" ? bumpRcVersion(current) : bumpPostVersion(current);\n updatePyprojectVersion(path.join(dir, \"pyproject.toml\"), next);\n return next;\n}\n\n// ── helpers ─────────────────────────────────────────────────────────────────\n\ntype RefRow = {\n name: string;\n kind: string;\n versionId?: string | null;\n semanticVersion?: string | null;\n contentHash?: string | null;\n state?: string | null;\n};\n\nconst VERSION_ID_FLAG: FlagSpec = { name: \"version-id\", help: \"Version id (default: the main tip).\" };\n\nfunction slugForDir(args: Parsed, dir: string): string {\n const slug = arg.str(args, \"slug\") ?? readLocalMeta(dir)?.slug;\n if (!slug) throw new CliError(\"Error: no --slug and this dir tracks no container (pull first).\", 1);\n return slug;\n}\n\n/**\n * `branch`/`tag` take EITHER the Python shape (`<name> --path D --slug S`) or\n * the earlier TypeScript shape (`<slug> <name>`); two positionals mean the latter.\n */\nfunction slugAndName(args: Parsed, kind: \"branch\" | \"tag\"): { slug: string; name: string | undefined } {\n const [first, second] = args.positionals;\n if (second !== undefined) return { slug: first!, name: second };\n const dir = arg.str(args, \"path\") ?? \".\";\n if (first === undefined && kind === \"tag\") throw new CliError(\"bench tag needs <name>\");\n return { slug: slugForDir(args, dir), name: first };\n}\n\n// ── the group ───────────────────────────────────────────────────────────────\n\n/** `gateway bench …` — worlds as versioned bundles. */\n/** A schema world that serves a vendor API: connector.toml beside schema/world.json,\n * and not already packaged (no gateway-api-world.toml at its root). */\nexport function isConnectorWorld(dir: string): boolean {\n return (\n fs.existsSync(path.join(dir, \"connector.toml\")) &&\n fs.existsSync(path.join(dir, \"schema\", \"world.json\")) &&\n !fs.existsSync(path.join(dir, \"gateway-api-world.toml\"))\n );\n}\n\n/** Package a connector world as its api bundle in a scratch directory, carrying\n * the world dir's .gateway base metadata so the push fast-forwards. */\nasync function packageApiBundle(dir: string, args: Parsed, ctx: CommandContext): Promise<string> {\n const creds = credentialsForRuntime(arg.str(args, \"host\"));\n const res = await runtime<{ files?: { path: string; content: string }[] }>(creds, {\n command: \"api-bundle\",\n files: readWorldFiles(dir),\n });\n const out = fs.mkdtempSync(path.join(os.tmpdir(), \"gateway-api-bundle-\"));\n writeWorldFiles(out, res.files ?? [], { clean: false });\n const meta = readLocalMeta(dir);\n if (meta) writeLocalMeta(out, meta);\n ctx.stderr(`packaged ${dir} as its api bundle (${(res.files ?? []).length} files)`);\n return out;\n}\n\nexport function registerBenchCommands(root: CommandGroup): void {\n const bench = root.group(\n \"bench\",\n \"Benchmark container hub — version and push benchmark environments to Gateway.\",\n );\n\n bench.command({\n name: \"push\",\n help: \"Push a benchmark container to Gateway as a content-hashed source bundle.\",\n positionals: [{ name: \"path\", help: \"Path to the environment directory (default: cwd).\", optional: true }],\n flags: [\n { name: \"slug\", help: \"Container slug (defaults to the directory name).\" },\n { name: \"name\", help: \"Human-readable container name.\" },\n { name: \"description\", help: \"Container description.\" },\n { name: \"tag\", help: \"Tag (repeatable).\", repeat: true },\n { name: \"visibility\", help: \"PRIVATE or PUBLIC.\" },\n { name: \"auto-bump\", help: \"Patch-bump pyproject version before pushing.\", boolean: true },\n { name: \"rc\", help: \"Bump/create an .rc pre-release before pushing.\", boolean: true },\n { name: \"post\", help: \"Bump/create a .post release before pushing.\", boolean: true },\n { name: \"image\", help: \"Pre-built OCI image ref for image/agentic envs (recorded on the version).\" },\n {\n name: \"build-wheel\",\n help: \"Build a wheel (uv build --wheel) + upload it — Python-only, refused here.\",\n boolean: true,\n },\n { name: \"branch\", short: \"b\", help: \"Branch to push to (default: the dir's tracked branch, else main).\" },\n { name: \"force\", help: \"Skip the fast-forward check (move the branch even if it diverged).\", boolean: true },\n { name: \"message\", short: \"m\", help: \"Change reason, shown in History.\" },\n { name: \"author\", help: \"Attribution shown in History (default: GATEWAY_AUTHOR env).\", env: \"GATEWAY_AUTHOR\" },\n HOST_FLAG,\n ],\n notes:\n \"The dir's .gateway/.env-metadata.json (written by pull/push) supplies the BASE version —\\n\" +\n \"pushing onto a branch whose tip moved refuses with a 409. --auto-bump/--rc/--post rewrite\\n\" +\n \"[project].version in pyproject.toml before hashing, so the bump lands in the bundle.\\n\" +\n \"A connector world (connector.toml + schema/world.json, no gateway-api-world.toml) is packaged\\n\" +\n \"as its api bundle first — the form the platform hosts — through the schema runtime, and the\\n\" +\n \"bundle is what lands; the directory's own .gateway base metadata is kept in step.\",\n run: async (args, ctx) => {\n if (arg.bool(args, \"build-wheel\"))\n return pythonOnly(\n ctx,\n \"bench push --build-wheel\",\n \"it runs `uv build --wheel` on a Python package.\",\n \"Push without --build-wheel, or build the wheel with the Python CLI.\",\n );\n const dir = args.positionals[0] ?? \".\";\n if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) throw new CliError(`Not a directory: ${dir}`, 1);\n const options = worldsOptions(credentials(args));\n applyVersionBump(dir, args);\n // A connector world is pushed as its api bundle: the schema runtime\n // packages it (server/world = the authored tree), the bundle is what the\n // platform stores and hosts, and the world dir keeps the base metadata.\n const packaged = isConnectorWorld(dir) ? await packageApiBundle(dir, args, ctx) : null;\n const result = await push(packaged ?? dir, {\n slug: arg.str(args, \"slug\") ?? (packaged ? path.basename(path.resolve(dir)) : undefined),\n name: arg.str(args, \"name\"),\n description: arg.str(args, \"description\"),\n tags: arg.list(args, \"tag\"),\n visibility: arg.str(args, \"visibility\"),\n imageRef: arg.str(args, \"image\"),\n branch: arg.str(args, \"branch\"),\n force: arg.bool(args, \"force\"),\n message: arg.str(args, \"message\"),\n author: arg.str(args, \"author\"),\n options,\n });\n if (packaged) {\n const meta = readLocalMeta(packaged);\n if (meta) writeLocalMeta(dir, meta);\n fs.rmSync(packaged, { recursive: true, force: true });\n }\n printJson(ctx, { ...result, wheelBuilt: false, ...(packaged ? { packaged: \"api-bundle\" } : {}) });\n },\n });\n\n bench.command({\n name: \"pull\",\n help: \"Reconstruct a container version's source directory, addressed by name.\",\n positionals: [{ name: \"slug\", help: \"Container slug, optionally slug@latest | @<semver> | @<hash-prefix>.\" }],\n flags: [\n { name: \"target\", short: \"t\", help: \"Target dir (defaults to ./<slug>).\" },\n { name: \"dir\", help: \"Alias of --target.\" },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const slugRef = args.positionals[0]!;\n const target = arg.str(args, \"target\") ?? arg.str(args, \"dir\");\n printJson(ctx, await pullJson(slugRef, target, args));\n },\n });\n\n bench.command({\n name: \"checkout\",\n help: \"Materialize a ref into a working dir and track it (pull + set base).\",\n positionals: [{ name: \"slug_ref\", help: \"slug@<branch|tag|semver|hash> (bare slug = main).\" }],\n flags: [\n { name: \"target\", short: \"t\", help: \"Target dir (defaults to ./<slug>).\" },\n { name: \"dir\", help: \"Alias of --target.\" },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const slugRef = args.positionals[0]!;\n const target = arg.str(args, \"target\") ?? arg.str(args, \"dir\");\n printJson(ctx, await pullJson(slugRef, target, args));\n },\n });\n\n bench.command({\n name: \"fork\",\n help: \"Fork a container into a new one (shares the bundle; records forkedFromVersionId).\",\n positionals: [{ name: \"slug\", help: \"Source container slug (forks the head; omit @version).\" }],\n flags: [{ name: \"into\", help: \"Target slug (defaults to <slug>-fork).\" }, HOST_FLAG],\n run: async (args, ctx) => {\n const slug = args.positionals[0]!;\n if (slug.includes(\"@\")) throw new CliError(\"fork a container head; omit the @version suffix\", 1);\n const into = arg.str(args, \"into\");\n const result = await api(credentials(args), \"POST\", \"/api/public/benchmark-containers/fork\", {\n slug,\n ...(into ? { targetSlug: into } : {}),\n });\n printJson(ctx, result);\n },\n });\n\n bench.command({\n name: \"status\",\n help: \"Where this dir stands: tracked branch, base version, local edits (dirty), remote tip moved (behind).\",\n positionals: [{ name: \"path\", help: \"Working dir (defaults to cwd).\", optional: true }],\n flags: [HOST_FLAG],\n run: async (args, ctx) => {\n const dir = args.positionals[0] ?? \".\";\n const meta = readLocalMeta(dir);\n if (!meta?.slug)\n throw new CliError(\n `${dir} has no .gateway/.env-metadata.json — pull or push it first so the dir knows which container/branch it tracks.`,\n 1,\n );\n const branch = meta.branch ?? DEFAULT_BRANCH;\n const localHash = computeContentHash(dir);\n const refs = await api<{ refs: RefRow[] }>(\n credentials(args),\n \"GET\",\n `/api/public/benchmark-containers/refs${query({ slug: meta.slug })}`,\n );\n const tip = refs.refs.find((r) => r.name === branch);\n const behind = Boolean(tip && tip.versionId !== meta.versionId);\n const dirty = localHash !== meta.contentHash;\n printJson(ctx, {\n slug: meta.slug,\n branch,\n baseVersionId: meta.versionId ?? null,\n baseContentHash: meta.contentHash ?? null,\n localContentHash: localHash,\n dirty,\n behind,\n remoteTipVersionId: tip?.versionId ?? null,\n remoteTipContentHash: tip?.contentHash ?? null,\n dirtyFiles: localTreeState(dir).dirty,\n });\n if (dirty) ctx.stderr(\"# local edits not pushed\");\n if (behind) ctx.stderr(\"# branch tip moved past your base — `gateway bench pull` before pushing\");\n },\n });\n\n bench.command({\n name: \"log\",\n help: \"A branch's version lineage, tip first — hash, semver, author, reason.\",\n positionals: [{ name: \"slug\", help: \"Container slug.\" }],\n flags: [\n { name: \"branch\", short: \"b\", help: \"Branch (default main).\" },\n { name: \"limit\", short: \"n\", help: \"Max entries.\", default: \"20\" },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const result = await api(\n credentials(args),\n \"GET\",\n `/api/public/benchmark-containers/log${query({\n slug: args.positionals[0],\n limit: arg.int(args, \"limit\") ?? 20,\n branch: arg.str(args, \"branch\"),\n })}`,\n );\n printJson(ctx, result);\n },\n });\n\n bench.command({\n name: \"branch\",\n help: \"List branches/tags (the dir's current branch marked with *), or create one.\",\n positionals: [\n { name: \"name\", help: \"Create a branch with this name (omit to list). `<slug> <name>` also works.\", optional: true },\n { name: \"name2\", help: \"The branch name when the first argument is a slug.\", optional: true },\n ],\n flags: [\n { name: \"path\", help: \"Working dir whose container/branch to use.\", default: \".\" },\n { name: \"slug\", help: \"Container slug (default: the dir's tracked slug).\" },\n { name: \"from\", help: \"Start version id (default: the main tip).\" },\n VERSION_ID_FLAG,\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const creds = credentials(args);\n const { slug, name } = slugAndName(args, \"branch\");\n if (name) {\n const ref = await createRef(slug, name, \"branch\", arg.str(args, \"from\") ?? arg.str(args, \"version-id\"), worldsOptions(creds));\n printJson(ctx, ref);\n return;\n }\n const dir = arg.str(args, \"path\") ?? \".\";\n const meta = readLocalMeta(dir);\n const current = meta?.slug === slug ? meta?.branch : undefined;\n const refs = await api<{ refs: RefRow[] }>(\n creds,\n \"GET\",\n `/api/public/benchmark-containers/refs${query({ slug })}`,\n );\n for (const ref of refs.refs) {\n const marker = ref.kind === \"branch\" && ref.name === current ? \"*\" : \" \";\n ctx.stdout(\n `${marker} ${ref.kind.padEnd(6)} ${ref.name.padEnd(24)} ${(ref.contentHash ?? \"\").slice(0, 12).padEnd(12)} ${ref.semanticVersion ?? \"\"}`.trimEnd(),\n );\n }\n },\n });\n\n bench.command({\n name: \"tag\",\n help: \"Create an immutable tag pointing at a version.\",\n positionals: [\n { name: \"name\", help: \"Tag name (immutable). `<slug> <name>` also works.\" },\n { name: \"name2\", help: \"The tag name when the first argument is a slug.\", optional: true },\n ],\n flags: [\n { name: \"path\", help: \"Working dir whose container to use.\", default: \".\" },\n { name: \"slug\", help: \"Container slug (default: the dir's tracked slug).\" },\n { name: \"version\", help: \"Version id to tag (default: main tip).\" },\n VERSION_ID_FLAG,\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const { slug, name } = slugAndName(args, \"tag\");\n const ref = await createRef(\n slug,\n name!,\n \"tag\",\n arg.str(args, \"version\") ?? arg.str(args, \"version-id\"),\n worldsOptions(credentials(args)),\n );\n printJson(ctx, ref);\n },\n });\n\n bench.command({\n name: \"propose\",\n help: \"File local edits as a change proposal (a PR to the env) instead of pushing to the branch.\",\n positionals: [{ name: \"path\", help: \"Working dir with local edits (default: cwd).\", optional: true }],\n flags: [\n { name: \"title\", help: \"Proposal title, shown to the reviewer.\" },\n { name: \"message\", short: \"m\", help: \"Why this changeset.\" },\n { name: \"reason\", help: \"Alias of --message.\" },\n { name: \"branch\", short: \"b\", help: \"Branch the proposal merges into (default main).\" },\n { name: \"target-branch\", help: \"Alias of --branch.\" },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const title = arg.str(args, \"title\");\n const reason = arg.str(args, \"message\") ?? arg.str(args, \"reason\");\n if (!title || !reason) throw new CliError(\"bench propose needs --title and --message\");\n const result = await propose(args.positionals[0] ?? \".\", {\n title,\n reason,\n targetBranch: arg.str(args, \"branch\") ?? arg.str(args, \"target-branch\"),\n options: worldsOptions(credentials(args)),\n });\n printJson(ctx, result);\n },\n });\n\n bench.command({\n name: \"diff\",\n help: \"Per-file diff (added/removed/modified/unchanged) between two version ids.\",\n positionals: [\n { name: \"base\", help: \"Base version id.\" },\n { name: \"head\", help: \"Head version id.\" },\n ],\n flags: [HOST_FLAG],\n run: async (args, ctx) => {\n const [base, head] = args.positionals;\n const result = await api(\n credentials(args),\n \"GET\",\n `/api/public/benchmark-containers/versions/diff${query({ base, head })}`,\n );\n printJson(ctx, result);\n },\n });\n\n bench.command({\n name: \"dispatch\",\n help: \"Start a hosted run of a run config — the same dispatch the Run button uses, parallelism included.\",\n positionals: [{ name: \"run_config_id\", help: \"Run config id (world page -> Runs -> Configs).\" }],\n flags: [\n { name: \"container-id\", help: \"Which environment, when the project hosts several.\" },\n { name: \"version-id\", help: \"Pin to a specific READY version (default: head).\" },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const containerId = arg.str(args, \"container-id\");\n const versionId = arg.str(args, \"version-id\");\n const result = await api<{ versionLabel: string; runs: { ok: boolean }[] }>(\n credentials(args),\n \"POST\",\n \"/api/public/benchmark-containers/run-configs/dispatch\",\n {\n runConfigId: args.positionals[0],\n ...(containerId ? { containerId } : {}),\n ...(versionId ? { versionId } : {}),\n },\n );\n printJson(ctx, result);\n return result.runs.every((r) => r.ok) ? 0 : 1;\n },\n });\n\n bench.command({\n name: \"run\",\n help: \"One hosted run: status, score, per-task rewards (--wait polls to terminal).\",\n positionals: [{ name: \"run_id\", help: \"Run id from `bench dispatch`.\" }],\n flags: [\n { name: \"wait\", help: \"Poll until the run is terminal.\", boolean: true },\n { name: \"timeout-min\", help: \"Minutes to wait (with --wait).\", default: \"45\" },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const runId = args.positionals[0]!;\n const options = worldsOptions(credentials(args));\n const report = arg.bool(args, \"wait\")\n ? await waitForRun(runId, {\n timeoutMinutes: arg.int(args, \"timeout-min\") ?? 45,\n options,\n onTick: (r) =>\n ctx.stderr(`…${r.status.toLowerCase()} (${r.shardsCompleted ?? 0}/${r.parallelism} shards)`),\n })\n : await getRun(runId, options);\n ctx.stdout(\n `${report.id} ${report.status}${report.score !== null ? ` score=${report.score.toFixed(3)}` : \"\"}` +\n ` (${report.model ?? \"?\"} · ${report.versionLabel ?? \"?\"} · x${report.parallelism})`,\n );\n for (const sample of report.samples) {\n const subs = Object.entries(sample.rewards)\n .filter(([, v]) => typeof v === \"number\")\n .map(([k, v]) => `${k}=${(v as number).toFixed(2)}`)\n .join(\" \");\n ctx.stdout(` ${(sample.reward ?? 0).toFixed(2)} ${sample.task ?? \"?\"}${subs ? ` [${subs}]` : \"\"}`);\n }\n if (report.summary) ctx.stdout(` ${report.summary}`);\n return report.terminal && report.status.toUpperCase() === \"COMPLETED\" ? 0 : 1;\n },\n });\n\n bench.command({\n name: \"run-configs\",\n help: \"Run configs from the CLI — list them, create one for CI, delete one.\",\n positionals: [{ name: \"action\", help: \"list | create | delete (default list).\", optional: true }],\n flags: [\n { name: \"name\", help: \"Config name (create).\" },\n { name: \"models\", help: \"Comma-separated model list (create).\" },\n { name: \"parallelism\", help: \"Containers per model, 1-16 (create).\", default: \"1\" },\n { name: \"tasks\", help: \"Comma-separated bundled task names (create).\" },\n {\n name: \"world-tasks\",\n help: \"Comma-separated stored task refs, <id> or <id>@<version> (create; api worlds, not with --tasks).\",\n },\n { name: \"agent\", help: \"harbor agent (create).\" },\n { name: \"auto-run-on-push\", help: \"Dispatch on every pushed READY version (create).\", boolean: true },\n { name: \"id\", help: \"Config id (delete/update).\" },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const action = args.positionals[0] ?? \"list\";\n const creds = credentials(args);\n const options = worldsOptions(creds);\n if (action === \"list\") {\n const rows = await listRunConfigs(options);\n if (rows.length === 0) {\n ctx.stdout(\"No run configs in this project.\");\n return;\n }\n for (const row of rows) {\n const extras = [\n row.parallelism > 1 ? `x${row.parallelism} containers` : null,\n row.autoRunOnPush ? \"auto-on-push\" : null,\n ].filter(Boolean);\n ctx.stdout(\n `${row.id} ${row.name} (${row.models.join(\", \") || \"no models\"})${extras.length ? ` [${extras.join(\", \")}]` : \"\"}`,\n );\n }\n return;\n }\n if (action === \"delete\") {\n const id = arg.str(args, \"id\");\n if (!id) throw new CliError(\"--id is required for delete\");\n await api(creds, \"DELETE\", \"/api/public/benchmark-containers/run-configs\", { id });\n ctx.stdout(`Deleted ${id}.`);\n return;\n }\n if (action !== \"create\") throw new CliError(\"action must be one of: list | create | delete\");\n const name = arg.str(args, \"name\");\n const models = arg.str(args, \"models\");\n if (!name || !models) throw new CliError(\"--name and --models are required for create\");\n const fields: Record<string, unknown> = {\n name,\n models: models.split(\",\").map((m) => m.trim()).filter(Boolean),\n parallelism: arg.int(args, \"parallelism\") ?? 1,\n };\n const agent = arg.str(args, \"agent\");\n if (agent) fields.agent = agent;\n const tasks = arg.str(args, \"tasks\");\n if (tasks) fields.taskNames = tasks.split(\",\").map((t) => t.trim()).filter(Boolean);\n const worldTasks = arg.str(args, \"world-tasks\");\n if (worldTasks) {\n if (tasks) throw new CliError(\"--tasks and --world-tasks are exclusive: a config runs bundled scenarios or stored tasks\");\n try {\n fields.worldTasks = parseWorldTaskRefs(worldTasks);\n } catch (e) {\n throw new CliError(e instanceof Error ? e.message : String(e));\n }\n }\n if (arg.bool(args, \"auto-run-on-push\")) fields.autoRunOnPush = true;\n const id = arg.str(args, \"id\");\n if (id) fields.id = id;\n const row = await api<{ id: string; name: string; models?: string[] }>(\n creds,\n \"POST\",\n \"/api/public/benchmark-containers/run-configs\",\n fields,\n );\n ctx.stdout(`${row.id} ${row.name} (${(row.models ?? []).join(\", \")})`);\n },\n });\n\n bench.command({\n name: \"secrets\",\n help: \"Environment secrets — env vars every HOSTED run of the world receives (write-only).\",\n positionals: [{ name: \"action\", help: \"set | list | unset\" }],\n flags: [\n { name: \"env\", help: \"World slug the secret belongs to.\" },\n { name: \"key\", help: \"Secret name (UPPER_SNAKE_CASE) — required for set/unset.\" },\n { name: \"value\", help: \"Secret value for `set`; omit to read from stdin (keeps it out of shell history).\" },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const action = args.positionals[0]!;\n const env = arg.str(args, \"env\");\n if (!env) throw new CliError(\"--env <world slug> is required\");\n const options = worldsOptions(credentials(args));\n if (action === \"list\") {\n const rows = await listEnvSecretKeys(env, options);\n if (rows.length === 0) {\n ctx.stdout(`No secrets on ${env}.`);\n return;\n }\n for (const row of rows) ctx.stdout(`${row.key} (rotated ${row.updatedAt})`);\n return;\n }\n if (action !== \"set\" && action !== \"unset\") throw new CliError(\"action must be one of: set | list | unset\");\n const key = arg.str(args, \"key\");\n if (!key) throw new CliError(`--key is required for \\`${action}\\``);\n if (action === \"unset\") {\n await deleteEnvSecret(env, key, options);\n ctx.stdout(`Deleted ${key} from ${env}.`);\n return;\n }\n const value = arg.str(args, \"value\") ?? (await ctx.stdin()).trim();\n if (!value) throw new CliError(\"empty value — nothing stored\");\n const res = await setEnvSecret(env, key, value, options);\n ctx.stdout(`${res.created ? \"Added\" : \"Rotated\"} ${key} on ${env} — next hosted run receives it.`);\n },\n });\n\n bench.command({\n name: \"validate\",\n help: \"Push this checkout, run the named run config against it, gate — the PR-validation entry.\",\n positionals: [{ name: \"path\", help: \"World directory (default: cwd).\", optional: true }],\n flags: [\n { name: \"run-config\", help: \"Run config NAME to dispatch.\" },\n { name: \"slug\", help: \"Container slug (default: pyproject name / dir name).\" },\n { name: \"branch\", help: \"Branch to push (default: the checkout's git branch).\" },\n { name: \"min-score\", help: \"Fail any run scoring below this.\" },\n { name: \"summary-file\", help: \"Write the markdown summary here (PR comment).\" },\n { name: \"timeout-min\", help: \"Minutes to wait for the runs.\", default: \"45\" },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const runConfig = arg.str(args, \"run-config\");\n if (!runConfig) throw new CliError(\"bench validate needs --run-config NAME\");\n const minScoreRaw = arg.str(args, \"min-score\");\n const report = await validateWorld(args.positionals[0] ?? \".\", {\n slug: arg.str(args, \"slug\"),\n runConfig,\n branch: arg.str(args, \"branch\"),\n minScore: minScoreRaw === undefined ? null : Number(minScoreRaw),\n timeoutMinutes: arg.int(args, \"timeout-min\") ?? 45,\n onProgress: (line) => ctx.stderr(line),\n options: worldsOptions(credentials(args)),\n });\n for (const run of report.runs) {\n ctx.stdout(\n `${run.model}: ${run.failure ? `FAIL — ${run.failure}` : \"pass\"}` +\n `${run.report?.score != null ? ` score=${run.report.score.toFixed(3)}` : \"\"}` +\n `${run.report?.url ? ` ${run.report.url}` : \"\"}`,\n );\n }\n const summaryFile = arg.str(args, \"summary-file\");\n if (summaryFile) fs.writeFileSync(summaryFile, report.markdown + \"\\n\");\n const stepSummary = process.env.GITHUB_STEP_SUMMARY;\n if (stepSummary) fs.appendFileSync(stepSummary, report.markdown + \"\\n\");\n ctx.stdout(report.ok ? \"validation passed\" : \"validation FAILED\");\n return report.ok ? 0 : 1;\n },\n });\n\n bench.command({\n name: \"resolve\",\n help: \"Pinned version + task count for slug[@ref].\",\n positionals: [{ name: \"slug_ref\", help: \"slug, or slug@branch|tag|semver|hash.\" }],\n flags: [HOST_FLAG],\n run: async (args, ctx) => {\n const world = await openWorld(args.positionals[0]!, worldsOptions(credentials(args)));\n ctx.stdout(\n `${world.slug}@${world.ref ?? \"latest\"}: ${world.version.semanticVersion ?? \"-\"} ` +\n `(${world.version.contentHash.slice(0, 12)}) · ${world.version.state ?? \"?\"} · ${world.tasks.length} tasks`,\n );\n ctx.stdout(`versionId: ${world.version.versionId}`);\n },\n });\n\n bench.command({\n name: \"tests\",\n help: \"The runs of the tests a world ships (on push, from the CLI, from the API), newest first; --run <id> prints one report.\",\n positionals: [{ name: \"slug\", help: \"World slug.\" }],\n flags: [\n { name: \"run\", help: \"Print this run's full report instead of the list.\" },\n { name: \"limit\", help: \"How many runs to list (default 20).\" },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const slug = args.positionals[0];\n if (!slug) throw new CliError(\"bench tests needs a world slug\", 1);\n const creds = credentials(args);\n const runId = arg.str(args, \"run\");\n if (runId) {\n const one = await api<{ run: Record<string, unknown> }>(creds, \"GET\", `/api/public/worlds/${encodeURIComponent(slug)}/tests/${encodeURIComponent(runId)}`);\n printJson(ctx, one.run);\n return 0;\n }\n const limit = arg.int(args, \"limit\");\n const listed = await api<{ runs: { id: string; state: string; trigger: string; versionId: string; createdAt: string; summary?: { passed?: number; failed?: number; skipped?: number } | null; error?: string | null }[] }>(\n creds,\n \"GET\",\n `/api/public/worlds/${encodeURIComponent(slug)}/tests${limit ? `?limit=${limit}` : \"\"}`,\n );\n if (!listed.runs.length) ctx.stdout(\"no test runs yet — ship tests/ with the world and push, or `gateway worlds test <slug>`\");\n for (const r of listed.runs) {\n const s = r.summary;\n ctx.stdout(\n `${r.createdAt} ${r.state.padEnd(7)} ${r.trigger.padEnd(6)} ${r.versionId} ${s ? `${s.passed ?? 0} passed, ${s.failed ?? 0} failed` : r.error ?? \"\"} ${r.id}`,\n );\n }\n return 0;\n },\n });\n\n bench.command({\n name: \"tasks\",\n help: \"The task list of slug[@ref].\",\n positionals: [{ name: \"slug_ref\", help: \"slug, or slug@branch|tag|semver|hash.\" }],\n flags: [HOST_FLAG],\n run: async (args, ctx) => {\n const world = await openWorld(args.positionals[0]!, worldsOptions(credentials(args)));\n if (world.tasks.length === 0) {\n ctx.stdout(\"No task manifest served for this version.\");\n return;\n }\n for (const task of world.tasks) ctx.stdout(`${task.name}${task.variant ? ` (${task.variant})` : \"\"}`);\n },\n });\n\n bench.command({\n name: \"refs\",\n help: \"Branches and tags of a container.\",\n positionals: [{ name: \"slug\", help: \"Container slug.\" }],\n flags: [HOST_FLAG],\n run: async (args, ctx) => {\n const res = await api<{ refs: RefRow[] }>(\n credentials(args),\n \"GET\",\n `/api/public/benchmark-containers/refs${query({ slug: args.positionals[0] })}`,\n );\n for (const ref of res.refs) {\n ctx.stdout(\n `${ref.kind === \"tag\" ? \"tag \" : \"branch\"} ${ref.name} ${ref.semanticVersion ?? \"-\"} (${ref.contentHash?.slice(0, 12) ?? \"?\"}) ${ref.state ?? \"\"}`.trimEnd(),\n );\n }\n },\n });\n\n bench.command({\n name: \"proposals\",\n help: \"Change proposals filed against a container.\",\n positionals: [{ name: \"slug\", help: \"Container slug.\" }],\n flags: [{ name: \"status\", help: \"open | applied | dismissed\" }, HOST_FLAG],\n run: async (args, ctx) => {\n const res = await api<{ proposals: { id: string; title?: string | null; status: string }[] }>(\n credentials(args),\n \"GET\",\n `/api/public/benchmark-containers/proposals${query({ slug: args.positionals[0], status: arg.str(args, \"status\") })}`,\n );\n if (res.proposals.length === 0) {\n ctx.stdout(\"No proposals.\");\n return;\n }\n for (const p of res.proposals) ctx.stdout(`${p.id} [${p.status}] ${p.title ?? \"\"}`.trimEnd());\n },\n });\n\n // ── Python-only: local engines and pip ────────────────────────────────────\n\n bench.command({\n name: \"eval\",\n help: \"Python-only (local verifiers/harbor engines) — run hosted with `bench dispatch` instead.\",\n flags: [HOST_FLAG],\n run: async (_args, ctx) =>\n pythonOnly(\n ctx,\n \"bench eval\",\n \"it runs the world locally on the Python engines (verifiers/harbor), which a JS process cannot host.\",\n \"Run hosted instead: gateway bench dispatch <runConfigId> — same worlds, graded on the platform.\",\n ),\n });\n\n bench.command({\n name: \"install\",\n help: \"Python-only (pip-installs a version's wheel) — n/a from TypeScript.\",\n flags: [HOST_FLAG],\n run: async (_args, ctx) =>\n pythonOnly(\n ctx,\n \"bench install\",\n \"it pip-installs a Python wheel into the current Python environment.\",\n \"Use `pip install gatewaysdk` and `gateway bench install <slug>` from the Python CLI.\",\n ),\n });\n\n bench.command({\n name: \"harvest-harbor\",\n help: \"Python-only (harvests a local harbor jobs dir) — n/a from TypeScript.\",\n flags: [HOST_FLAG],\n run: async (_args, ctx) =>\n pythonOnly(\n ctx,\n \"bench harvest-harbor\",\n \"it reads a harbor jobs directory produced by the Python runner.\",\n \"Hosted runs file themselves: gateway bench dispatch <runConfigId>.\",\n ),\n });\n}\n\nasync function pullJson(slugRef: string, target: string | undefined, args: Parsed) {\n const res = await pull(slugRef, target, worldsOptions(credentials(args)));\n const meta = readLocalMeta(res.dir);\n const at = slugRef.indexOf(\"@\");\n return {\n slug: res.slug,\n ref: at === -1 ? \"latest\" : slugRef.slice(at + 1),\n branch: meta?.branch ?? DEFAULT_BRANCH,\n versionId: res.versionId,\n contentHash: meta?.contentHash ?? null,\n target: res.dir,\n files: res.files,\n };\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport { api } from \"../config\";\nimport { arg, CliError, type CommandGroup } from \"../router\";\nimport { credentials, HOST_FLAG, query } from \"./shared\";\nimport { printOrInstallSkill, SKILL_NAME } from \"./skill\";\n\nexport const CONNECTORS = \"/api/public/context/connectors\";\nexport const HUB = \"/api/public/connectors/hub\";\nexport const CLONE = \"/api/public/connectors/clone\";\n\n// ── collect_template (port of connectors/template.py) ───────────────────────\n\nconst WORLD_SKIPPED_DIRS = new Set([\"data\", \"captures\", \"db\", \"verifiers\"]);\nconst WORLD_SKIPPED_FILES = new Set([\"gateway-env.toml\", \"tool-schemas.json\"]);\nconst WORLD_CARRIED_DIRS = new Set([\"api\", \"scenarios\", \"evidence\", \"reports\"]);\nconst SUPPORTING_SUFFIXES = new Set([\".json\", \".md\", \".toml\"]);\nconst GENERATED_NAMES = new Set([\"base.json\", \"runtime.json\", \"lock.json\", \"README.md\", \"tool-schemas.json\"]);\n\nexport type TemplateFiles = { source: \"template\" | \"world\"; files: Record<string, string>; skipped: string[] };\n\nexport function walk(root: string): string[] {\n const out: string[] = [];\n const visit = (rel: string) => {\n const abs = rel ? path.join(root, rel) : root;\n for (const entry of fs.readdirSync(abs, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {\n const childRel = rel ? `${rel}/${entry.name}` : entry.name;\n if (entry.isSymbolicLink()) continue;\n if (entry.isDirectory()) {\n if (entry.name === \"__pycache__\" || entry.name.startsWith(\".\")) continue;\n visit(childRel);\n } else if (entry.isFile()) {\n if (entry.name.startsWith(\".\") || entry.name.endsWith(\".pyc\")) continue;\n out.push(childRel);\n }\n }\n };\n visit(\"\");\n return out;\n}\n\nfunction readText(root: string, relative: string): string {\n const bytes = fs.readFileSync(path.join(root, relative));\n const text = bytes.toString(\"utf8\");\n if (Buffer.from(text, \"utf8\").length !== bytes.length || text.includes(\"�\"))\n throw new CliError(`${relative} is not UTF-8 text; a connector template holds text files only`, 1);\n return text;\n}\n\n/** The template path a world-directory file maps to, or null to leave it behind. */\nfunction templatePath(relative: string): string | null {\n const parts = relative.split(\"/\");\n if (WORLD_SKIPPED_DIRS.has(parts[0]!) || WORLD_SKIPPED_FILES.has(relative)) return null;\n if (parts.length === 1) return relative === \"connector.toml\" ? relative : null;\n if (parts[0] === \"schema\") {\n const name = parts[parts.length - 1]!;\n if (parts.length !== 2 || !SUPPORTING_SUFFIXES.has(path.extname(name)) || GENERATED_NAMES.has(name)) return null;\n return name;\n }\n if (relative === \"tools/handlers.py\") return \"handlers.py\";\n if (WORLD_CARRIED_DIRS.has(parts[0]!)) return relative;\n return null;\n}\n\n/** The files a workspace connector is made of, from a template dir or the world dir it was authored in. */\nexport function collectTemplate(directory: string): TemplateFiles {\n if (fs.existsSync(path.join(directory, \"world.json\"))) {\n const files: Record<string, string> = {};\n for (const relative of walk(directory)) files[relative] = readText(directory, relative);\n return { source: \"template\", files, skipped: [] };\n }\n if (!fs.existsSync(path.join(directory, \"schema\", \"world.json\")))\n throw new CliError(`${directory}: neither a connector template (world.json) nor a world (schema/world.json)`, 1);\n const files: Record<string, string> = {};\n const skipped: string[] = [];\n for (const relative of walk(directory)) {\n const target = templatePath(relative);\n if (target === null) skipped.push(relative);\n else files[target] = readText(directory, relative);\n }\n return { source: \"world\", files, skipped };\n}\n\n// ── the client shapes ───────────────────────────────────────────────────────\n\ntype HubRow = {\n id?: string;\n slug?: string;\n name?: string;\n orgName?: string;\n isOwn?: boolean;\n visibility?: string;\n metadata?: { vendor?: string; auth?: string; entityCount?: number; operationCount?: number };\n};\n\ntype Pulled = {\n repo?: Record<string, unknown>;\n commit?: { commitHash?: string; id?: string };\n files?: Record<string, { type?: string; content?: unknown }>;\n};\n\nfunction oneRoute(slug: string, params: Record<string, string | undefined> = {}): string {\n if (!slug || slug.includes(\"/\")) throw new CliError(\"a connector slug is a single path segment\");\n return `${CONNECTORS}/${encodeURIComponent(slug)}${query(params)}`;\n}\n\nfunction table(rows: string[][], header: string[]): string {\n const widths = header.map((h, i) => Math.max(h.length, ...rows.map((r) => (r[i] ?? \"\").length)));\n return [header, ...rows]\n .map((line) => line.map((cell, i) => cell.padEnd(widths[i]!)).join(\" \").trimEnd())\n .join(\"\\n\");\n}\n\n/** `gateway worlds connector list|pull|clone|publish|skill`. C2 registers validate|capture|conform|ingest. */\nexport function registerConnectorCommands(root: CommandGroup): void {\n const connector = root\n .group(\"worlds\", \"Build, seed, serve and run worlds.\")\n .group(\"connector\", \"Describe a vendor connection, capture what it returns, seed the world from it\");\n\n connector.command({\n name: \"publish\",\n help: \"Save the template as a workspace connector: created on first publish, a new commit after.\",\n positionals: [{ name: \"path\", help: \"A connector template directory, or the world directory it was authored in\" }],\n flags: [\n { name: \"slug\", help: \"Connector slug (default: the directory name)\" },\n { name: \"message\", short: \"m\", help: \"Commit message\" },\n { name: \"description\", help: \"One-line description shown in listings\" },\n { name: \"tag\", help: \"Tag (repeatable)\", repeat: true },\n { name: \"workspace-visible\", help: \"Visible to the whole workspace, not only this project's members\", boolean: true },\n { name: \"project-scope\", help: \"Own it in this project rather than the org\", boolean: true },\n HOST_FLAG,\n ],\n notes:\n \"A world directory is mapped back into the template layout (schema/world.json → world.json,\\n\" +\n \"tools/handlers.py → handlers.py, …); data/, captures/, db/ and generated files stay behind.\\n\" +\n \"The published connector equals the directory: paths no longer present are removed.\",\n run: async (args, ctx) => {\n const dir = args.positionals[0]!;\n const gathered = collectTemplate(dir);\n const slug = arg.str(args, \"slug\") ?? path.basename(path.resolve(dir));\n const creds = credentials(args);\n const files: Record<string, { content: string } | null> = Object.fromEntries(\n Object.entries(gathered.files).map(([p, content]) => [p, { content }]),\n );\n let parent: string | undefined;\n const exists = await api<{ exists?: boolean }>(creds, \"GET\", oneRoute(slug, { exists: \"true\" }));\n if (exists.exists) {\n const head = await api<Pulled>(creds, \"GET\", oneRoute(slug));\n for (const stale of Object.keys(head.files ?? {}).sort()) {\n if (stale in files) continue;\n files[stale] = null;\n ctx.stderr(`# removing ${stale}`);\n }\n const hash = head.commit?.commitHash;\n parent = typeof hash === \"string\" && hash.length >= 8 ? hash : undefined;\n }\n for (const left of gathered.skipped) ctx.stderr(`# left behind: ${left}`);\n const tags = arg.list(args, \"tag\");\n const description = arg.str(args, \"description\");\n const result = await api<Record<string, unknown>>(creds, \"POST\", oneRoute(slug), {\n files,\n message: arg.str(args, \"message\") ?? `publish ${slug}`,\n is_public: arg.bool(args, \"workspace-visible\"),\n scope: arg.bool(args, \"project-scope\") ? \"project\" : \"org\",\n source: \"sdk\",\n ...(parent ? { parent_commit: parent } : {}),\n ...(description ? { description } : {}),\n ...(tags.length ? { tags } : {}),\n });\n const commit = result.commitHash ?? result.commitId ?? \"\";\n ctx.stdout(`${result.status ?? \"committed\"} ${slug} ${commit} ${result.url ?? \"\"}`.trimEnd());\n },\n });\n\n connector.command({\n name: \"list\",\n help: \"List this organization's workspace connectors (--hub adds the ones other organizations published).\",\n flags: [\n { name: \"hub\", help: \"Every connector this organization can use, published ones included\", boolean: true },\n { name: \"query\", help: \"Filter by slug, name or description\" },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const hub = arg.bool(args, \"hub\");\n let rows = await hubRows(args);\n if (!hub) rows = rows.filter((row) => row.isOwn);\n if (rows.length === 0) {\n ctx.stderr(\"no connectors\" + (hub ? \" in the hub\" : \"; `gateway worlds connector publish` adds one\"));\n return;\n }\n const header = [\"slug\", \"name\", \"vendor\", \"auth\", \"entities\", \"operations\", \"visibility\", ...(hub ? [\"org\"] : [])];\n const lines = rows.map((row) => {\n const meta = row.metadata ?? {};\n const line = [\n row.slug ?? \"\",\n row.name ?? \"\",\n meta.vendor ?? \"-\",\n meta.auth ?? \"-\",\n String(meta.entityCount ?? \"-\"),\n String(meta.operationCount ?? \"-\"),\n row.visibility ?? \"\",\n ];\n if (hub) line.push(`${row.orgName ?? \"\"}${row.isOwn ? \" (own)\" : \"\"}`);\n return line;\n });\n ctx.stdout(table(lines, header));\n },\n });\n\n connector.command({\n name: \"pull\",\n help: \"Write the connector's template files to a directory.\",\n positionals: [{ name: \"slug\", help: \"Workspace connector slug\" }],\n flags: [\n { name: \"out\", help: \"New or empty directory (default: ./<slug>)\" },\n { name: \"version\", help: \"A label or commit hash; the head by default\" },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const slug = args.positionals[0]!;\n const out = arg.str(args, \"out\") ?? slug;\n if (fs.existsSync(out) && (!fs.statSync(out).isDirectory() || fs.readdirSync(out).length > 0))\n throw new CliError(`${out}: must be a new or empty directory`, 1);\n const pulled = await api<Pulled>(credentials(args), \"GET\", oneRoute(slug, { version: arg.str(args, \"version\") }));\n const files = flattenFiles(slug, pulled);\n for (const relative of Object.keys(files).sort()) {\n if (relative.startsWith(\"/\") || relative.split(\"/\").includes(\"..\"))\n throw new CliError(`Refusing a template path outside the directory: ${relative}`, 1);\n const target = path.join(out, relative);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n fs.writeFileSync(target, files[relative]!);\n ctx.stdout(relative);\n }\n ctx.stderr(`# ${slug} @ ${pulled.commit?.commitHash ?? pulled.commit?.id ?? \"\"} -> ${out}`);\n },\n });\n\n connector.command({\n name: \"clone\",\n help: \"Copy a connector another organization published into this organization, with provenance.\",\n positionals: [{ name: \"source\", help: \"A hub connector's slug or repo id\" }],\n flags: [\n { name: \"name\", help: \"Name for the clone (default: the source's)\" },\n { name: \"slug\", help: \"Slug for the clone (default: the source's)\" },\n { name: \"project-scope\", help: \"Own it in this project rather than the org\", boolean: true },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const source = args.positionals[0]!;\n const rows = await hubRows(args, undefined);\n let chosen = rows.find((row) => row.id === source);\n if (!chosen) {\n const matches = rows.filter((row) => row.slug === source);\n const candidates = matches.filter((row) => !row.isOwn);\n const pool = candidates.length ? candidates : matches;\n if (pool.length === 0)\n throw new CliError(`${source}: not in the hub; \\`gateway worlds connector list --hub\\` shows what is`, 1);\n if (pool.length > 1) {\n ctx.stderr(`${source} names ${pool.length} hub connectors; clone by repo id instead:`);\n for (const row of pool) ctx.stderr(` ${row.id} ${row.orgName}`);\n return 1;\n }\n chosen = pool[0]!;\n }\n const name = arg.str(args, \"name\");\n const slug = arg.str(args, \"slug\");\n const result = await api<Record<string, unknown>>(credentials(args), \"POST\", CLONE, {\n sourceRepoId: chosen.id,\n scope: arg.bool(args, \"project-scope\") ? \"project\" : \"org\",\n ...(name ? { name } : {}),\n ...(slug ? { slug } : {}),\n });\n ctx.stdout(\n `cloned ${chosen.slug} from ${chosen.orgName} -> ${result.slug} (${result.id}) commit ${result.commitId}`,\n );\n },\n });\n\n connector.command({\n name: \"skill\",\n help: \"The connector authoring skill for agents: print it, or --install it into a repository's .claude/.\",\n flags: [\n { name: \"install\", help: \"Repository to install the skill and agent into (under its .claude/)\" },\n { name: \"force\", help: \"Overwrite an existing file whose content differs\", boolean: true },\n ],\n notes: `An alias of \\`gateway worlds skill ${SKILL_NAME}\\`.`,\n run: async (args, ctx) => printOrInstallSkill(ctx, SKILL_NAME, arg.str(args, \"install\"), arg.bool(args, \"force\")),\n });\n}\n\nasync function hubRows(args: Parameters<typeof credentials>[0], q?: string): Promise<HubRow[]> {\n const search = q ?? arg.str(args, \"query\");\n const res = await api<{ connectors?: HubRow[] }>(credentials(args), \"GET\", `${HUB}${query({ query: search })}`);\n return res.connectors ?? [];\n}\n\n/** `pull` flattens each file entry to its text — the same mapping `push` takes. */\nexport function flattenFiles(slug: string, pulled: Pulled): Record<string, string> {\n const files: Record<string, string> = {};\n for (const [p, entry] of Object.entries(pulled.files ?? {})) {\n if (!entry || typeof entry !== \"object\" || entry.type !== \"file\" || typeof entry.content !== \"string\")\n throw new CliError(`${slug}: ${p} is not a file entry; a connector template holds files only`, 1);\n files[p] = entry.content;\n }\n return files;\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport { arg, CliError, type CommandContext, type CommandGroup } from \"../router\";\n\n/**\n * The skills shipped with the SDK, so any agent can pick them up.\n *\n * `gateway worlds skill NAME` prints one; `--install DIR` lands it in a\n * repository's `.claude/` (the skill's files, plus any agent it ships) — the\n * layout Claude Code, Cursor and Codex read. The files are copied from the\n * Python package (`gatewaysdk/environment/schema/skills/`) into `skills/` at\n * build time (scripts/copy-skills.mjs) and shipped with the npm package.\n */\n\nexport const SKILL_NAME = \"connector-schema-authoring\";\nconst AGENT_FILE = \"connector-template-author.md\";\n/** Agents a skill installs beside itself, under `.claude/agents/`. */\nconst SKILL_AGENTS: Record<string, string[]> = { [SKILL_NAME]: [AGENT_FILE] };\nconst NEXT_STEPS: Record<string, string> = {\n [SKILL_NAME]: \"gateway worlds schema init ./<vendor>-world --connector custom\",\n \"world-data-ingestion\": \"gateway worlds data import <world> rows.json\",\n \"worlds-getting-started\": \"gateway worlds schema init ./my-world --connector custom\",\n};\n\n/**\n * Where the packaged skills live: `GATEWAY_SKILLS_DIR` when set, else\n * `<package>/skills` next to the built cli.js, else (running from the repo)\n * the Python package's skills directory.\n */\nexport function skillsRoot(): string {\n const candidates: string[] = [];\n if (process.env.GATEWAY_SKILLS_DIR) candidates.push(process.env.GATEWAY_SKILLS_DIR);\n const entry = process.argv[1];\n if (entry) {\n let packageRoot: string;\n try {\n packageRoot = path.dirname(path.dirname(fs.realpathSync(entry)));\n } catch {\n packageRoot = path.dirname(path.dirname(path.resolve(entry)));\n }\n candidates.push(path.join(packageRoot, \"skills\"));\n candidates.push(path.join(packageRoot, \"..\", \"sdk\", \"src\", \"gatewaysdk\", \"environment\", \"schema\", \"skills\"));\n }\n candidates.push(path.join(process.cwd(), \"skills\"));\n for (const candidate of candidates) {\n if (fs.existsSync(path.join(candidate)) && fs.statSync(candidate).isDirectory()) return candidate;\n }\n throw new CliError(\n \"No packaged skills found: this build shipped without skills/ (run `npm run build`, which copies them) \" +\n \"or set GATEWAY_SKILLS_DIR.\",\n 1,\n );\n}\n\n/** Every skill the package ships: a directory under skills/ holding a SKILL.md. */\nexport function packagedSkills(): string[] {\n const root = skillsRoot();\n return fs\n .readdirSync(root, { withFileTypes: true })\n .filter((entry) => entry.isDirectory() && fs.existsSync(path.join(root, entry.name, \"SKILL.md\")))\n .map((entry) => entry.name)\n .sort();\n}\n\nfunction skillDir(name: string): string {\n const directory = path.join(skillsRoot(), name);\n if (name.includes(\"/\") || name.includes(\"\\\\\") || !fs.existsSync(path.join(directory, \"SKILL.md\")))\n throw new CliError(`No packaged skill '${name}'; the package ships: ${packagedSkills().join(\", \")}`, 1);\n return directory;\n}\n\nexport function skillText(name: string): string {\n return fs.readFileSync(path.join(skillDir(name), \"SKILL.md\"), \"utf8\");\n}\n\nfunction listFiles(dir: string, rel = \"\"): string[] {\n const out: string[] = [];\n for (const entry of fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {\n if (entry.name === \"__pycache__\") continue;\n const childRel = rel ? `${rel}/${entry.name}` : entry.name;\n if (entry.isDirectory()) out.push(...listFiles(path.join(dir, entry.name), childRel));\n else if (entry.isFile()) out.push(childRel);\n }\n return out;\n}\n\n/** Repository-relative destination → packaged source, for every file the skill installs. */\nexport function packagedFiles(name: string): Record<string, string> {\n const directory = skillDir(name);\n const files: Record<string, string> = {};\n for (const relative of listFiles(directory)) files[`.claude/skills/${name}/${relative}`] = path.join(directory, relative);\n for (const agent of SKILL_AGENTS[name] ?? []) files[`.claude/agents/${agent}`] = path.join(skillsRoot(), \"agents\", agent);\n return files;\n}\n\nexport type InstallReport = { written: string[]; unchanged: string[]; conflicts: string[] };\n\n/**\n * Write the skill (and its agents) under `destination/.claude/`. An existing\n * file with the same content is left alone; one with different content is a\n * conflict and nothing is written unless `force`.\n */\nexport function installSkill(destination: string, name: string, force = false): InstallReport {\n const report: InstallReport = { written: [], unchanged: [], conflicts: [] };\n const planned: [string, Buffer][] = [];\n for (const [relative, source] of Object.entries(packagedFiles(name))) {\n const content = fs.readFileSync(source);\n const target = path.join(destination, relative);\n if (fs.existsSync(target) && fs.readFileSync(target).equals(content)) report.unchanged.push(relative);\n else if (fs.existsSync(target) && !force) report.conflicts.push(relative);\n else {\n planned.push([target, content]);\n report.written.push(relative);\n }\n }\n if (report.conflicts.length) {\n report.written = [];\n return report;\n }\n for (const [target, content] of planned) {\n fs.mkdirSync(path.dirname(target), { recursive: true });\n fs.writeFileSync(target, content);\n }\n return report;\n}\n\nexport function printOrInstallSkill(\n ctx: CommandContext,\n name: string,\n install: string | undefined,\n force: boolean,\n): number | void {\n const text = skillText(name);\n if (install === undefined) {\n process.stdout.write(text);\n return;\n }\n const report = installSkill(install, name, force);\n if (report.conflicts.length) {\n ctx.stderr(\"Refusing to overwrite files that differ from the packaged skill:\");\n for (const relative of report.conflicts) ctx.stderr(` ${path.join(install, relative)}`);\n ctx.stderr(\"Pass --force to replace them.\");\n return 1;\n }\n for (const relative of report.written) ctx.stdout(`wrote ${path.join(install, relative)}`);\n for (const relative of report.unchanged) ctx.stdout(`unchanged ${path.join(install, relative)}`);\n const step = NEXT_STEPS[name];\n if (step) ctx.stdout(`next: ${step}`);\n}\n\n/** `gateway worlds skill [NAME] [--list] [--install DIR] [--force]`; no NAME with `--install` lands every skill. */\nexport function registerSkillCommands(root: CommandGroup): void {\n root.group(\"worlds\", \"Build, seed, serve and run worlds.\").command({\n name: \"skill\",\n help: \"Print a packaged skill for an agent, or --install it into a repository's .claude/.\",\n positionals: [\n {\n name: \"name\",\n help: \"Packaged skill: connector-schema-authoring, world-data-ingestion, worlds-getting-started\",\n optional: true,\n },\n ],\n flags: [\n { name: \"list\", help: \"List the skills this SDK ships and exit\", boolean: true },\n {\n name: \"install\",\n help: \"Repository to install the skill (and any agent it ships) into, under .claude/; every skill when no NAME\",\n },\n { name: \"force\", help: \"Overwrite an existing file whose content differs\", boolean: true },\n ],\n run: async (args, ctx) => {\n const name = args.positionals[0];\n const install = arg.str(args, \"install\");\n const force = arg.bool(args, \"force\");\n if (arg.bool(args, \"list\") || (name === undefined && install === undefined)) {\n for (const skill of packagedSkills()) ctx.stdout(skill);\n if (name === undefined && !arg.bool(args, \"list\"))\n ctx.stderr(\"Name one to print it, or --install DIR to land every skill in a repository.\");\n return;\n }\n if (name === undefined) {\n // `--install DIR` alone: every packaged skill, so an agent needs one command.\n let code: number | undefined;\n for (const skill of packagedSkills()) code = printOrInstallSkill(ctx, skill, install, force) ?? code;\n return code;\n }\n return printOrInstallSkill(ctx, name, install, force);\n },\n });\n}\n","import * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport { Readable } from \"node:stream\";\n\nimport { api, printJson, type Credentials } from \"../config\";\nimport { arg, CliError, type CommandContext, type CommandGroup, type FlagSpec, type Parsed } from \"../router\";\nimport { pull, readLocalMeta } from \"../../worlds/hub\";\nimport { parseRows, rowsMode, type Rows } from \"./rows\";\nimport { credentials, HOST_FLAG, query, worldsOptions } from \"./shared\";\nimport { forEachLimited, waitForBatch, WorldDataApi, writeRefusalReport, type BatchStatus } from \"./worldData/batches\";\nimport { buildChunks, DEFAULT_CHUNK_BYTES, parseSize } from \"./worldData/chunker\";\nimport { extractRows, pyDumpsPlain, SHAPES, type Merge, type Shape } from \"./worldData/extract\";\nimport { findResumable, manifestDir, MANIFEST_DIR, newManifest, readManifest, recordChunk, uploadedEntry, writeManifest, type Manifest, type ManifestFlags } from \"./worldData/manifest\";\nimport { fileInput, readRows, type RowInput } from \"./worldData/rowSource\";\nimport { loadWorldConfig } from \"./worldData/worldConfig\";\n\n// A local directory goes through the runtime track's bridge; the import is\n// lazy so a slug-only invocation never loads it.\nconst runtimeData = () => import(\"../runtime/data\");\n\nconst isDirectory = (p: string) => fs.existsSync(p) && fs.statSync(p).isDirectory();\nconst slugOf = (world: string) => world.split(\"@\", 1)[0]!;\nconst worldRoute = (world: string) => `/api/public/worlds/${encodeURIComponent(slugOf(world))}/data`;\n\n/** The inline gate for a local directory: the bridge takes the rows whole (the Python `INLINE_*`). */\nexport const INLINE_ROWS = 5000;\nexport const INLINE_BYTES = 4 * 1024 * 1024;\n\nconst WORLD_HELP = \"World directory, or a platform world slug (optionally slug@ref).\";\nconst ENTITY_FLAG: FlagSpec = { name: \"entity\", help: \"The entity bare-row files hold.\" };\nconst REPORT_FLAG: FlagSpec = { name: \"report\", help: \"Write the refusals as JSONL here.\" };\nconst MESSAGE_FLAG: FlagSpec = { name: \"message\", short: \"m\", help: \"Change reason for the version.\" };\n\n/**\n * `gateway worlds data …`, the same surface as the Python CLI (contract §11):\n * rows into a world and out of the shapes agents have. A platform slug\n * streams chunks into a data batch (§7, §10); a local directory keeps the\n * small inline import through the runtime bridge. `extract` runs here,\n * natively, on files of any size.\n */\nexport function registerDataCommands(root: CommandGroup): void {\n const data = root\n .group(\"worlds\", \"Build, seed, serve and run worlds.\")\n .group(\"data\", \"Put rows into a world, or see what it holds — local directory or platform slug\");\n\n data.command({\n name: \"import\",\n help: \"Put rows into a world through its own gate.\",\n positionals: [\n { name: \"world\", help: WORLD_HELP },\n { name: \"rows\", help: \"Rows files ({entity: [rows]} JSON, {entity,row} JSONL, bare rows), or - for stdin.\", variadic: true },\n ],\n flags: [\n ENTITY_FLAG,\n { name: \"mode\", help: \"append (upsert by primary key) | replace (named entities).\", default: \"append\" },\n { name: \"merge\", help: \"Inside the batch, by key: upsert (last wins) | fill (first wins, later add fields).\", default: \"upsert\" },\n { name: \"chunk-rows\", help: \"Rows per uploaded chunk (instead of --chunk-bytes).\" },\n { name: \"chunk-bytes\", help: \"JSONL bytes per uploaded chunk before gzip (default 64MiB).\" },\n { name: \"parallel\", help: \"Chunk uploads in flight.\", default: \"4\" },\n { name: \"resume\", help: \"Pick up the newest incomplete upload of this world and these files.\", boolean: true },\n { name: \"atomic\", help: \"One refusal refuses the batch (default).\", boolean: true },\n { name: \"per-chunk\", help: \"One refusal refuses only its chunk.\", boolean: true },\n { name: \"publish\", help: \"now: a version per batch | later: fold with `data publish`.\", default: \"now\" },\n { name: \"wait\", help: \"Wait for the batch to apply (default).\", boolean: true },\n { name: \"no-wait\", help: \"Print {batchId, state} once the batch is queued.\", boolean: true },\n REPORT_FLAG,\n { name: \"dry-run\", help: \"Validate against the contract; upload nothing to the world, write nothing.\", boolean: true },\n MESSAGE_FLAG,\n HOST_FLAG,\n ],\n notes:\n \"A directory: the rows go into the tree (data/initial.json for a schema world, db/seed.sql for\\n\" +\n \"mock-tools), small inputs only. A slug: the rows stream up as gzipped chunks into a data batch\\n\" +\n \"the platform validates, applies onto the world's snapshot and (with --publish now) turns into a\\n\" +\n \"data-only version. Exit 0 applied or published, 2 refused (report written), 1 error.\",\n run: async (args, ctx) => {\n const [world, ...files] = args.positionals;\n if (files.length === 0) throw new CliError(\"worlds data import needs at least one rows file\");\n const dryRun = arg.bool(args, \"dry-run\");\n if (isDirectory(world!)) return dryRun ? checkLocalDirectory(world!, files, args, ctx) : importLocalDirectory(world!, files, args, ctx);\n return importBatch(world!, files, args, ctx, dryRun ? \"check\" : \"import\");\n },\n });\n\n data.command({\n name: \"check\",\n help: \"Dry run: every row checked against the world's contract; nothing uploaded to the world, nothing written.\",\n positionals: [\n { name: \"world\", help: \"World directory, or a platform world slug (its contract is pulled).\" },\n { name: \"rows\", help: \"Rows files, or - for stdin.\", variadic: true },\n ],\n flags: [\n ENTITY_FLAG,\n { name: \"mode\", help: \"append | replace, as the import would run.\", default: \"append\" },\n { name: \"merge\", help: \"upsert | fill, as the import would run.\", default: \"upsert\" },\n REPORT_FLAG,\n HOST_FLAG,\n ],\n notes:\n \"A slug: a dry-run batch on the platform (every chunk validated, nothing applied). A directory: the\\n\" +\n \"runtime bridge's import over a scratch copy, nothing written back. Exit 2 when any row is refused.\",\n run: async (args, ctx) => {\n const [world, ...files] = args.positionals;\n if (files.length === 0) throw new CliError(\"worlds data check needs at least one rows file\");\n if (isDirectory(world!)) return checkLocalDirectory(world!, files, args, ctx);\n return importBatch(world!, files, args, ctx, \"check\");\n },\n });\n\n data.command({\n name: \"extract\",\n help: \"Rows out of a tool-results export, a vendor response or a session export, shaped for `data import`.\",\n positionals: [\n { name: \"world\", help: \"World directory, or a platform world slug (its contract is pulled).\" },\n { name: \"source\", help: \"Input file, or - for stdin.\" },\n ],\n flags: [\n { name: \"shape\", help: \"tool-results | vendor-envelope | session-export.\" },\n { name: \"entity\", help: \"The entity the rows belong to.\" },\n { name: \"out\", help: \"Write tagged JSONL here (default stdout, also -).\" },\n { name: \"merge\", help: \"Dedupe by primary key: fill (first wins) | upsert (last wins).\", default: \"fill\" },\n { name: \"no-redact\", help: \"Skip the world's [redact] policy.\", boolean: true },\n HOST_FLAG,\n ],\n notes:\n \"Null and empty fields dropped, undeclared fields stripped (and counted on stderr), deduped by\\n\" +\n \"primary key, the world's [redact] policy applied. Summary on stderr:\\n\" +\n '{\"read\": N, \"rows\": M, \"unknownFields\": {...}, \"redacted\": {\"dropped\": n, \"hashed\": n}}.',\n run: async (args, ctx) => {\n const [world, source] = args.positionals;\n const shape = arg.str(args, \"shape\");\n if (!shape || !SHAPES.includes(shape as Shape)) throw new CliError(`shape must be one of ${SHAPES.join(\", \")}`, 1);\n const entity = arg.str(args, \"entity\");\n if (!entity) throw new CliError(\"extract needs --entity\");\n const merge = arg.str(args, \"merge\") ?? \"fill\";\n if (merge !== \"fill\" && merge !== \"upsert\") throw new CliError(\"merge must be one of fill, upsert\", 1);\n const dir = isDirectory(world!) ? world! : await pullWorld(world!, credentials(args));\n const config = loadWorldConfig(dir);\n const input = source === \"-\" ? stdinInput(ctx) : fileInput(source!);\n const out = arg.str(args, \"out\");\n const sink = out && out !== \"-\" ? fs.createWriteStream(out) : null;\n const write = sink ? (line: string) => void sink.write(line + \"\\n\") : (line: string) => ctx.stdout(line);\n const summary = await extractRows(input, config, { shape: shape as Shape, entity, merge: merge as Merge, redact: !arg.bool(args, \"no-redact\") }, write);\n if (sink) await new Promise<void>((resolve, reject) => sink.end((error?: Error | null) => (error ? reject(error) : resolve())));\n ctx.stderr(pyDumpsPlain(summary));\n },\n });\n\n data.command({\n name: \"status\",\n help: \"One batch's state, progress, counts and first refusals.\",\n positionals: [{ name: \"batchId\", help: \"The batch id `data import` printed or recorded in .gateway/imports/.\" }],\n flags: [{ name: \"world\", help: \"The world slug, when no manifest names it.\" }, HOST_FLAG],\n run: async (args, ctx) => {\n const batchId = args.positionals[0]!;\n const slug = arg.str(args, \"world\") ?? readManifest(batchId)?.slug;\n if (!slug) throw new CliError(`no manifest for ${batchId} under ${MANIFEST_DIR}; pass --world SLUG`, 1);\n printJson(ctx, await new WorldDataApi(credentials(args), slugOf(slug)).get(batchId));\n },\n });\n\n data.command({\n name: \"batches\",\n help: \"The world's data batches, newest first.\",\n positionals: [{ name: \"world\", help: \"World slug.\" }],\n flags: [{ name: \"limit\", help: \"At most this many, newest first.\" }, HOST_FLAG],\n run: async (args, ctx) => {\n printJson(ctx, await new WorldDataApi(credentials(args), slugOf(args.positionals[0]!)).list(arg.int(args, \"limit\")));\n },\n });\n\n data.command({\n name: \"publish\",\n help: \"Fold every applied `--publish later` batch into one data-only version.\",\n positionals: [{ name: \"world\", help: \"World slug.\" }],\n flags: [MESSAGE_FLAG, HOST_FLAG],\n run: async (args, ctx) => {\n printJson(ctx, await new WorldDataApi(credentials(args), slugOf(args.positionals[0]!)).publish(arg.str(args, \"message\")));\n },\n });\n\n data.command({\n name: \"show\",\n help: \"What a world seeds with: every entity's row count, or one entity's rows.\",\n positionals: [{ name: \"world\", help: WORLD_HELP }],\n flags: [{ name: \"entity\", help: \"Print this entity's rows instead of counts.\" }, HOST_FLAG],\n run: async (args, ctx) => {\n const world = args.positionals[0]!;\n const entity = arg.str(args, \"entity\");\n if (isDirectory(world)) {\n const { showLocalWorldData } = await runtimeData();\n const { credentialsForRuntime } = await import(\"../runtime/local\");\n const creds = credentialsForRuntime(arg.str(args, \"host\"));\n printJson(ctx, { world, ...(await showLocalWorldData(world, entity, creds)) });\n return;\n }\n const creds = credentials(args);\n const result = await api<Record<string, unknown>>(creds, \"GET\", `${worldRoute(world)}${query({ entity })}`);\n printJson(ctx, { world, ...(entity ? { entity } : {}), ...result });\n },\n });\n}\n\n// ------------------------------------------------------------ the batch door\n\ntype ImportFlags = ManifestFlags & { parallel: number; wait: boolean; resume: boolean; message?: string; report?: string };\n\n/** `check` is a dry-run batch: atomic, waited for, never published. */\ntype Purpose = \"import\" | \"check\";\n\nfunction importFlags(args: Parsed, purpose: Purpose): ImportFlags {\n const mode = arg.str(args, \"mode\") ?? \"append\";\n const merge = arg.str(args, \"merge\") ?? \"upsert\";\n const publish = purpose === \"check\" ? \"now\" : (arg.str(args, \"publish\") ?? \"now\");\n if (![\"append\", \"replace\"].includes(mode) || ![\"upsert\", \"fill\"].includes(merge) || ![\"now\", \"later\"].includes(publish))\n throw new CliError(\"--mode is append|replace, --merge is upsert|fill, --publish is now|later\", 1);\n if (arg.bool(args, \"atomic\") && arg.bool(args, \"per-chunk\")) throw new CliError(\"--atomic and --per-chunk exclude each other\");\n if (arg.bool(args, \"wait\") && arg.bool(args, \"no-wait\")) throw new CliError(\"--wait and --no-wait exclude each other\");\n const chunkRows = arg.int(args, \"chunk-rows\") ?? null;\n if (chunkRows !== null && chunkRows < 1) throw new CliError(\"chunk bounds must be positive\", 1);\n const sizeText = arg.str(args, \"chunk-bytes\");\n let chunkBytes = DEFAULT_CHUNK_BYTES;\n if (sizeText !== undefined) {\n try {\n chunkBytes = parseSize(sizeText);\n } catch (error) {\n throw new CliError((error as Error).message, 1);\n }\n }\n return {\n mode: mode as ManifestFlags[\"mode\"],\n merge: merge as ManifestFlags[\"merge\"],\n atomic: purpose === \"check\" ? true : !arg.bool(args, \"per-chunk\"),\n publish: publish as ManifestFlags[\"publish\"],\n dryRun: purpose === \"check\",\n chunkBytes,\n chunkRows,\n entity: arg.str(args, \"entity\") ?? null,\n parallel: Math.max(1, arg.int(args, \"parallel\") ?? 4),\n wait: purpose === \"check\" ? true : !arg.bool(args, \"no-wait\"),\n resume: purpose === \"check\" ? false : arg.bool(args, \"resume\"),\n message: arg.str(args, \"message\"),\n report: arg.str(args, \"report\"),\n };\n}\n\nfunction rowInputs(files: string[], ctx: CommandContext): RowInput[] {\n if (files.filter((f) => f === \"-\").length > 1) throw new CliError(\"stdin (-) can be read once\");\n for (const file of files) {\n // Refuse before a batch is opened for nothing.\n if (file !== \"-\" && !(fs.existsSync(file) && fs.statSync(file).isFile())) throw new CliError(`Cannot read ${file}`, 1);\n }\n return files.map((f) => (f === \"-\" ? stdinInput(ctx) : fileInput(f)));\n}\n\nfunction stdinInput(ctx: CommandContext): RowInput {\n return {\n name: \"-\",\n open: () =>\n ctx.stdinStream\n ? (ctx.stdinStream() as Readable)\n : Readable.from(\n (async function* () {\n yield Buffer.from(await ctx.stdin(), \"utf8\");\n })(),\n ),\n };\n}\n\n/** Phase lines on stderr: on a TTY, or as GATEWAY_PROGRESS=1|0 says (the Python `tty_progress`). */\nfunction showProgress(): boolean {\n const forced = process.env.GATEWAY_PROGRESS;\n if (forced === \"1\") return true;\n if (forced === \"0\") return false;\n return Boolean(process.stderr.isTTY);\n}\n\n/** The first pause between status polls; CI and tests shorten it. */\nfunction pollMs(): number {\n const raw = Number(process.env.GATEWAY_WORLD_DATA_POLL_MS ?? 1000);\n return Number.isFinite(raw) && raw >= 0 ? raw : 1000;\n}\n\n/**\n * Stream, chunk, upload, complete, then follow the job — the Python\n * `world_data.import_rows` + `wait`, request for request. Shared by\n * `import` and `check` (a dry-run batch).\n */\nasync function importBatch(world: string, files: string[], args: Parsed, ctx: CommandContext, purpose: Purpose): Promise<number> {\n const slug = slugOf(world);\n const creds = credentials(args);\n const flags = importFlags(args, purpose);\n const client = new WorldDataApi(creds, slug);\n const progress = (line: string) => {\n if (showProgress()) ctx.stderr(line);\n };\n\n // An unfinished import is resumed with the flags it was started with: the\n // chunk boundaries (and so the digests the server holds) depend on them.\n const resumable = flags.resume ? findResumable(slug, files) : null;\n if (flags.resume && !resumable) throw new CliError(`nothing to resume: no incomplete manifest for ${slug} under ${manifestDir()}`, 1);\n const plan: ManifestFlags = resumable\n ? resumable.flags\n : { mode: flags.mode, merge: flags.merge, atomic: flags.atomic, publish: flags.publish, dryRun: flags.dryRun, chunkBytes: flags.chunkBytes, chunkRows: flags.chunkRows, entity: flags.entity };\n\n // Read the first row before anything is opened on the platform: a file\n // that fits no shape is refused with no request made.\n const source = readRows(rowInputs(files, ctx), plan.entity ?? undefined);\n const first = await source.next();\n if (first.done) throw new CliError(`no rows in ${files.join(\" \")}; nothing to import`, 1);\n const rows = (async function* () {\n yield first.value;\n yield* source;\n })();\n\n let manifest: Manifest;\n if (resumable) {\n const status = await client.get(resumable.batchId);\n if (status.state !== \"open\" && status.state !== \"uploading\") throw new CliError(`batch ${resumable.batchId} is ${status.state}; only an open or uploading batch resumes`, 1);\n manifest = resumable;\n progress(`resuming batch ${manifest.batchId} (${manifest.chunks.length} chunks recorded)`);\n } else {\n const opened = await client.open({\n mode: plan.mode,\n merge: plan.merge,\n atomic: plan.atomic,\n dryRun: plan.dryRun,\n publish: plan.publish,\n ...(flags.message ? { message: flags.message } : {}),\n });\n if (!opened.batchId) throw new CliError(\"the platform opened no batch (no batchId in the answer)\", 1);\n const limit = opened.limits?.chunkBytes;\n if (typeof limit === \"number\" && plan.chunkBytes > limit) throw new CliError(`--chunk-bytes ${plan.chunkBytes} exceeds the platform's chunk limit ${limit}`, 1);\n manifest = newManifest({ batchId: opened.batchId, slug, host: creds.host, flags: plan, inputs: files });\n writeManifest(manifest);\n progress(`batch ${manifest.batchId} open`);\n }\n const batchId = manifest.batchId;\n\n const chunks = buildChunks(rows, { chunkBytes: plan.chunkBytes, chunkRows: plan.chunkRows, entity: plan.entity });\n await forEachLimited(chunks, flags.parallel, async (chunk) => {\n if (uploadedEntry(manifest, chunk.ordinal, chunk.digest)) {\n progress(`chunk ${chunk.ordinal}: already uploaded (${chunk.rows} rows)`);\n return;\n }\n const entry = await client.upload(batchId, chunk);\n recordChunk(manifest, entry);\n writeManifest(manifest);\n progress(`chunk ${chunk.ordinal}: uploaded ${chunk.rows} rows, ${chunk.bytes} bytes (${entry.chunkId})`);\n });\n\n await client.complete(batchId);\n manifest.completed = true;\n writeManifest(manifest);\n progress(`batch ${batchId} complete: ${manifest.chunks.length} chunks`);\n\n if (!flags.wait) {\n ctx.stdout(JSON.stringify({ batchId, state: \"queued\" }));\n return 0;\n }\n const status = await waitForBatch(client, batchId, {\n onPhase: (line) => progress(line),\n initialDelayMs: pollMs(),\n });\n if (flags.report !== undefined) {\n const written = await writeRefusalReport(status, flags.report);\n progress(`${written} refusal${written === 1 ? \"\" : \"s\"} written to ${flags.report}`);\n }\n if (purpose === \"check\") {\n printJson(ctx, { world, dryRun: true, rows: status.rows ?? 0, refusalCount: status.refusalCount ?? 0, refusals: (status.refusals ?? []).slice(0, 200), entityCounts: status.entityCounts ?? {} });\n if (status.state === \"failed\") {\n ctx.stderr(`batch ${batchId} failed: ${status.error ?? \"unknown error\"}`);\n return 1;\n }\n return status.refusalCount ? 2 : 0;\n }\n printJson(ctx, { world, ...status });\n if (status.state === \"applied\" || status.state === \"published\") return 0;\n if (status.state === \"refused\") return 2;\n ctx.stderr(`batch ${batchId} ${status.state}: ${status.error ?? \"unknown error\"}`);\n return 1;\n}\n\n// ---------------------------------------------------------- local directories\n\n/** The platform slug a local world would import into: its pulled metadata, else its name. */\nfunction worldSlug(dir: string): string {\n const slug = readLocalMeta(dir)?.slug;\n return typeof slug === \"string\" && slug ? slug : path.basename(path.resolve(dir));\n}\n\n/** The rows for a directory, whole, within the inline cap — or a pointer to the platform world. */\nasync function inlineRows(dir: string, files: string[], args: Parsed, ctx: CommandContext): Promise<Rows> {\n const entity = arg.str(args, \"entity\");\n const tooLarge = () =>\n new CliError(\n `${files.length} file(s) exceed the inline cap (${INLINE_ROWS} rows / ${INLINE_BYTES} bytes) for a directory; ` +\n `import into the platform world \\`${worldSlug(dir)}\\``,\n 1,\n );\n const paths: string[] = [];\n let scratch: string | null = null;\n try {\n let size = 0;\n for (const file of files) {\n if (file === \"-\") {\n scratch ??= fs.mkdtempSync(path.join(os.tmpdir(), \"gateway-stdin-\"));\n const stdin = path.join(scratch, \"stdin.rows\");\n fs.writeFileSync(stdin, await ctx.stdin());\n paths.push(stdin);\n continue;\n }\n if (!fs.existsSync(file) || !fs.statSync(file).isFile()) throw new CliError(`Cannot read ${file}`, 1);\n size += fs.statSync(file).size;\n paths.push(file);\n }\n if (size > INLINE_BYTES) throw tooLarge();\n let count = 0;\n for await (const _ of readRows(paths.map(fileInput), entity)) if (++count > INLINE_ROWS) throw tooLarge();\n return parseRows(paths, entity);\n } finally {\n if (scratch) fs.rmSync(scratch, { recursive: true, force: true });\n }\n}\n\nasync function importLocalDirectory(dir: string, files: string[], args: Parsed, ctx: CommandContext): Promise<number> {\n const mode = rowsMode(arg.str(args, \"mode\"));\n const rows = await inlineRows(dir, files, args, ctx);\n const { importLocalWorldData } = await runtimeData();\n const { credentialsForRuntime } = await import(\"../runtime/local\");\n const creds = credentialsForRuntime(arg.str(args, \"host\"));\n printJson(ctx, { world: dir, ...(await importLocalWorldData(dir, rows, { mode }, creds)) });\n return 0;\n}\n\n/** The bridge's import over the tree, files not written back: a dry run by construction. */\nasync function checkLocalDirectory(dir: string, files: string[], args: Parsed, ctx: CommandContext): Promise<number> {\n const rows = await inlineRows(dir, files, args, ctx);\n const count = Object.values(rows).reduce((n, listed) => n + listed.length, 0);\n const { checkLocalWorldData } = await runtimeData();\n const { credentialsForRuntime } = await import(\"../runtime/local\");\n const { BridgeRejected } = await import(\"../runtime/client\");\n const creds = credentialsForRuntime(arg.str(args, \"host\"));\n const report = arg.str(args, \"report\");\n try {\n const checked = await checkLocalWorldData(dir, rows, creds);\n if (report !== undefined) fs.writeFileSync(report, \"\");\n printJson(ctx, { world: dir, dryRun: true, rows: count, refusalCount: 0, refusals: [], entityCounts: checked.entity_counts });\n return 0;\n } catch (error) {\n if (!(error instanceof BridgeRejected)) throw error;\n const refusal = refusalFromBridge(error.detail);\n if (report !== undefined) fs.writeFileSync(report, JSON.stringify(refusal) + \"\\n\");\n printJson(ctx, { world: dir, dryRun: true, rows: count, refusalCount: 1, refusals: [refusal], entityCounts: {} });\n return 2;\n }\n}\n\n/** One refusal record (contract §2) from the bridge's ContractError detail. */\nfunction refusalFromBridge(detail: { code: string; message: string; path?: string }): Record<string, unknown> {\n const pointer = detail.path ?? \"/\";\n const [, entity, index, field] = /^\\/([^/]+)(?:\\/(\\d+))?(?:\\/(.+))?$/.exec(pointer) ?? [];\n return {\n chunk: 0,\n index: index !== undefined ? Number(index) : 0,\n entity: entity ?? null,\n primaryKey: null,\n field: field ?? null,\n pointer,\n detail: detail.message,\n };\n}\n\n/** A slug's tree in a temp dir, for `extract` to read its contract and connector.toml. */\nasync function pullWorld(slugRef: string, creds: Credentials): Promise<string> {\n const target = path.join(fs.mkdtempSync(path.join(os.tmpdir(), \"gateway-world-data-\")), slugOf(slugRef));\n const pulled = await pull(slugRef, target, worldsOptions(creds));\n return pulled.dir;\n}\n\nexport type { BatchStatus };\n","import * as fs from \"node:fs\";\n\nimport { CliError } from \"../router\";\n\n/** `{entity: [row, …]}` — the shape every rows file resolves to. */\nexport type Rows = Record<string, Record<string, unknown>[]>;\n\n/**\n * Read rows from files into `{entity: [row, …]}` — a port of the Python\n * `gatewaysdk.environment.schema.data.parse_rows`, so both CLIs accept the\n * same files and refuse the same ones with the same words.\n *\n * Each file is one of: a JSON object `{\"<entity>\": [row, …]}`; JSONL where\n * every line is `{\"entity\": \"<name>\", \"row\": {…}}`; or — only with `entity` —\n * a JSON array or JSONL of bare rows. Several files merge in order. A file\n * that fits none of these is refused, naming the file.\n */\nexport function parseRows(paths: string[], entity?: string): Rows {\n const rows: Rows = {};\n for (const path of paths) {\n let text: string;\n try {\n text = fs.readFileSync(path, \"utf8\");\n } catch {\n throw refuse(`Cannot read ${path} as UTF-8 text`);\n }\n for (const [name, listed] of Object.entries(rowsIn(text, path, entity))) {\n (rows[name] ??= []).push(...listed);\n }\n }\n return rows;\n}\n\nfunction refuse(message: string): CliError {\n return new CliError(message, 1);\n}\n\nfunction rowsIn(text: string, path: string, entity: string | undefined): Rows {\n const stripped = text.trim();\n if (!stripped) return {};\n let document: unknown;\n try {\n document = JSON.parse(stripped);\n } catch {\n return jsonlRows(stripped, path, entity);\n }\n if (isObject(document)) {\n if (entity !== undefined) {\n const keys = Object.keys(document);\n if (keys.length === 1 && keys[0] === entity && Array.isArray(document[entity])) {\n return {\n [entity]: (document[entity] as unknown[]).map((row, i) =>\n rowObject(row, `${path}:${entity}[${i}]`),\n ),\n };\n }\n // One bare row on one line is a JSON object too; --entity says that is what it is.\n return jsonlRows(stripped, path, entity);\n }\n const out: Rows = {};\n for (const [name, listed] of Object.entries(document)) {\n if (!Array.isArray(listed))\n throw refuse(`${path}: ${name} must map to an array of rows (JSONL lines are {\"entity\", \"row\"})`);\n out[name] = listed.map((row, index) => rowObject(row, `${path}:${name}[${index}]`));\n }\n return out;\n }\n if (Array.isArray(document)) {\n if (entity === undefined)\n throw refuse(`${path} is a bare array; say which entity it holds with --entity`);\n return { [entity]: document.map((row, index) => rowObject(row, `${path}[${index}]`)) };\n }\n throw refuse(`${path} is neither a JSON object of entity -> rows nor an array of rows`);\n}\n\nfunction jsonlRows(text: string, path: string, entity: string | undefined): Rows {\n const out: Rows = {};\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 const number = index + 1;\n let item: unknown;\n try {\n item = JSON.parse(line);\n } catch {\n throw refuse(`${path}:${number} is not JSON`);\n }\n const where = `${path}:${number}`;\n if (entity !== undefined) {\n (out[entity] ??= []).push(rowObject(item, where));\n continue;\n }\n if (\n !isObject(item) ||\n Object.keys(item).length !== 2 ||\n !(\"entity\" in item) ||\n !(\"row\" in item) ||\n typeof item.entity !== \"string\"\n )\n throw refuse(`${where}: expected {\"entity\": name, \"row\": {…}} (or pass --entity for bare rows)`);\n (out[item.entity] ??= []).push(rowObject(item.row, where));\n }\n return out;\n}\n\nfunction rowObject(row: unknown, where: string): Record<string, unknown> {\n if (!isObject(row)) throw refuse(`${where}: a row must be a JSON object`);\n return row;\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** `append` (upsert by primary key) or `replace` (the named entities wholesale). */\nexport type RowsMode = \"append\" | \"replace\";\n\nexport function rowsMode(value: string | undefined): RowsMode {\n const mode = value ?? \"append\";\n if (mode !== \"append\" && mode !== \"replace\") throw new CliError(\"--mode must be append or replace\");\n return mode;\n}\n","import { createHash } from \"node:crypto\";\nimport * as fs from \"node:fs\";\n\nimport { api, type Credentials } from \"../../config\";\nimport { CliError } from \"../../router\";\nimport type { BuiltChunk } from \"./chunker\";\nimport type { ManifestChunk } from \"./manifest\";\n\n/**\n * The batch protocol of `/api/public/worlds/{slug}/data` (contract §7): open\n * a batch, register each chunk by digest (the server hands back a presigned\n * PUT, or says it already holds that content), confirm the upload, complete,\n * then poll. Thin on purpose: the server owns validation and the ledger.\n */\n\nexport type Refusal = {\n chunk: number;\n index: number;\n entity: string | null;\n primaryKey: Record<string, unknown> | null;\n field: string | null;\n pointer: string;\n detail: string;\n};\n\nexport type BatchStatus = {\n batchId: string;\n state: string;\n mode?: string;\n merge?: string;\n atomic?: boolean;\n dryRun?: boolean;\n publish?: string;\n chunks?: number;\n uploadedChunks?: number;\n rows?: number;\n refusalCount?: number;\n refusals?: Refusal[];\n reportUrl?: string;\n progress?: { phase?: string; validatedChunks?: number; appliedRows?: number };\n entityCounts?: Record<string, number>;\n snapshotId?: string | null;\n batchDigest?: string | null;\n versionId?: string | null;\n error?: string | null;\n createdAt?: string;\n updatedAt?: string;\n};\n\nexport type OpenBatchBody = {\n mode: \"append\" | \"replace\";\n merge: \"upsert\" | \"fill\";\n atomic: boolean;\n dryRun: boolean;\n publish: \"now\" | \"later\";\n message?: string;\n expectedChunks?: number;\n entities?: string[];\n};\n\nexport type OpenedBatch = { batchId: string; state: string; limits?: { chunkBytes?: number; batchBytes?: number; inlineBytes?: number } };\n\nexport type RegisteredChunk = {\n chunkId: string;\n uploaded: boolean;\n uploadUrl?: string;\n /** Headers the presigned PUT was signed for (content-type, content-length, x-amz-checksum-sha256); sent exactly. */\n uploadHeaders?: Record<string, string>;\n expiresAt?: string;\n};\n\nexport const TERMINAL_STATES = new Set([\"applied\", \"refused\", \"published\", \"failed\"]);\n\nexport const sleepMs = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));\n\nexport class WorldDataApi {\n readonly base: string;\n constructor(\n readonly creds: Credentials,\n readonly slug: string,\n /** Injectable for tests: the pause between retries and polls. */\n readonly sleep: (ms: number) => Promise<void> = sleepMs,\n ) {\n this.base = `/api/public/worlds/${encodeURIComponent(slug)}/data`;\n }\n\n open(body: OpenBatchBody): Promise<OpenedBatch> {\n return api<OpenedBatch>(this.creds, \"POST\", `${this.base}/batches`, body);\n }\n\n register(batchId: string, chunk: { ordinal: number; digest: string; bytes: number; rows: number; entity: string | null }): Promise<RegisteredChunk> {\n return api<RegisteredChunk>(this.creds, \"POST\", `${this.base}/batches/${batchId}/chunks`, {\n ordinal: chunk.ordinal,\n digest: chunk.digest,\n bytes: chunk.bytes,\n rows: chunk.rows,\n ...(chunk.entity ? { entity: chunk.entity } : {}),\n });\n }\n\n markUploaded(batchId: string, chunkId: string): Promise<{ chunkId: string; uploaded: boolean; bytes: number }> {\n return api(this.creds, \"POST\", `${this.base}/batches/${batchId}/chunks/${chunkId}/uploaded`);\n }\n\n complete(batchId: string): Promise<{ batchId: string; state: string }> {\n return api(this.creds, \"POST\", `${this.base}/batches/${batchId}/complete`);\n }\n\n get(batchId: string): Promise<BatchStatus> {\n return api<BatchStatus>(this.creds, \"GET\", `${this.base}/batches/${batchId}`);\n }\n\n list(limit?: number, cursor?: string): Promise<{ batches: BatchStatus[]; nextCursor?: string }> {\n const params = new URLSearchParams();\n if (limit !== undefined) params.set(\"limit\", String(limit));\n if (cursor) params.set(\"cursor\", cursor);\n const q = params.toString();\n return api(this.creds, \"GET\", `${this.base}/batches${q ? `?${q}` : \"\"}`);\n }\n\n publish(message?: string): Promise<{ versionId: string; snapshotId: string; batchIds: string[] }> {\n return api(this.creds, \"POST\", `${this.base}/publish`, message ? { message } : {});\n }\n\n /**\n * PUT the gzipped chunk to its presigned URL with exactly the headers the\n * URL was signed for (the platform's `uploadHeaders`; the same three when it\n * sends none), with backoff on a dropped connection or a 5xx.\n */\n async put(uploadUrl: string, gz: Buffer, signed?: Record<string, string>): Promise<void> {\n const headers = signed ?? uploadHeadersFor(gz);\n const delays = [500, 1500, 4000];\n for (let attempt = 0; ; attempt++) {\n try {\n const res = await fetch(uploadUrl, { method: \"PUT\", body: new Uint8Array(gz), headers });\n if (res.ok) return;\n if (res.status < 500 || attempt >= delays.length) throw new CliError(`chunk upload -> ${res.status}: ${(await res.text()).slice(0, 300)}`, 1);\n } catch (error) {\n if (error instanceof CliError || attempt >= delays.length) throw error instanceof CliError ? error : new CliError(`chunk upload failed: ${(error as Error).message}`, 1);\n }\n await this.sleep(delays[attempt]!);\n }\n }\n\n /** Register, upload unless the server already holds the content, confirm. */\n async upload(batchId: string, chunk: BuiltChunk): Promise<ManifestChunk> {\n const registered = await this.register(batchId, chunk);\n if (!registered.uploaded) {\n if (!registered.uploadUrl) throw new CliError(`the server registered chunk ${chunk.ordinal} without an upload URL`, 1);\n await this.put(registered.uploadUrl, chunk.gz, registered.uploadHeaders);\n await this.markUploaded(batchId, registered.chunkId);\n }\n return { ordinal: chunk.ordinal, digest: chunk.digest, bytes: chunk.bytes, rows: chunk.rows, entity: chunk.entity, chunkId: registered.chunkId, uploaded: true };\n }\n}\n\n/** What a chunk's presigned PUT is signed for: its type, size and sha256 (base64, S3's spelling). */\nexport function uploadHeadersFor(gz: Buffer): Record<string, string> {\n return {\n \"content-type\": \"application/gzip\",\n \"content-length\": String(gz.length),\n \"x-amz-checksum-sha256\": createHash(\"sha256\").update(gz).digest(\"base64\"),\n };\n}\n\n/** Run `fn` over an async stream with at most `limit` in flight; results in input order. */\nexport async function forEachLimited<T>(items: AsyncIterable<T>, limit: number, fn: (item: T) => Promise<void>): Promise<void> {\n const inFlight = new Set<Promise<void>>();\n let failure: unknown = null;\n const track = (p: Promise<void>) => {\n const wrapped: Promise<void> = p.then(\n () => {\n inFlight.delete(wrapped);\n },\n (error) => {\n failure ??= error;\n inFlight.delete(wrapped);\n },\n );\n inFlight.add(wrapped);\n };\n for await (const item of items) {\n if (failure) break;\n track(fn(item));\n if (inFlight.size >= limit) await Promise.race(inFlight);\n }\n await Promise.all(inFlight);\n if (failure) throw failure;\n}\n\nexport type WaitOptions = {\n /** Called once per phase change with a printable line. */\n onPhase?: (line: string) => void;\n sleep?: (ms: number) => Promise<void>;\n /** The first pause between polls (default 1 s; GATEWAY_WORLD_DATA_POLL_MS in the CLI). */\n initialDelayMs?: number;\n};\n\n/** Poll until the batch settles; 1 s growing to 10 s between polls. */\nexport async function waitForBatch(client: WorldDataApi, batchId: string, opts: WaitOptions = {}): Promise<BatchStatus> {\n const sleep = opts.sleep ?? client.sleep;\n let delay = opts.initialDelayMs ?? 1000;\n let last = \"\";\n for (;;) {\n const status = await client.get(batchId);\n const phase = phaseLine(status);\n if (phase !== last) {\n opts.onPhase?.(phase);\n last = phase;\n }\n if (TERMINAL_STATES.has(status.state)) return status;\n await sleep(delay);\n delay = Math.min(10_000, Math.round(delay * 1.5));\n }\n}\n\n/** The Python CLI's progress line: `state`, with the job's phase in parentheses when it has one. */\nexport function phaseLine(status: BatchStatus): string {\n const phase = status.progress?.phase;\n return phase ? `${status.state} (${phase})` : status.state;\n}\n\n/**\n * The refusal report as JSONL: the server's full report when it has one\n * (`reportUrl`), else the records the status carries inline. Returns the\n * number of lines written.\n */\nexport async function writeRefusalReport(status: BatchStatus, file: string): Promise<number> {\n let text: string;\n if (status.reportUrl) {\n const res = await fetch(status.reportUrl);\n if (!res.ok) throw new CliError(`refusal report -> ${res.status}`, 1);\n text = await res.text();\n if (text && !text.endsWith(\"\\n\")) text += \"\\n\";\n } else text = (status.refusals ?? []).map((r) => JSON.stringify(r) + \"\\n\").join(\"\");\n fs.writeFileSync(file, text);\n return text ? text.split(\"\\n\").filter(Boolean).length : 0;\n}\n","import { createHash } from \"node:crypto\";\nimport { deflateRawSync } from \"node:zlib\";\n\nimport { dumps, type JsonObject } from \"./json\";\nimport type { TaggedRow } from \"./rowSource\";\n\n/**\n * Rows into chunks: gzip over JSONL, cut on row boundaries at `--chunk-rows`\n * or `--chunk-bytes` (uncompressed), content-addressed by the sha256 of the\n * gzipped bytes. The same rows with the same flags give the same content\n * digests (over the JSONL) in both CLIs and on every platform, and the same\n * gzip digests wherever the two zlibs deflate alike: lines are the Python\n * serialisation (`dumps`), the deflate stream is zlib's at level 9, and the\n * gzip header is written here rather than by zlib, as CPython's\n * `gzip.compress(…, mtime=0)` writes it — zlib would stamp the platform's OS\n * byte instead. Node 20 and 24 bundle Chromium's zlib, which deflates\n * differently from CPython's stock zlib, so a chunk's gzip digest can differ\n * between CLIs while its content digest agrees; `--resume` keys on the digest\n * of what this CLI wrote, so it is unaffected. See `zlibDeflatesLikeCPython`.\n */\n\nexport const DEFAULT_CHUNK_BYTES = 64 * 1024 * 1024;\nexport const GZIP_LEVEL = 9;\n\nexport type ChunkPlan = {\n /** Always bound: the Python CLI keeps 64 MiB even with --chunk-rows. */\n chunkBytes: number;\n chunkRows: number | null;\n /** When set, chunks are declared with this entity and lines are bare rows. */\n entity: string | null;\n};\n\nexport type BuiltChunk = {\n ordinal: number;\n /** sha256 of the gzipped bytes, hex. */\n digest: string;\n /** Gzipped size. */\n bytes: number;\n rows: number;\n entity: string | null;\n /** Uncompressed JSONL size (`contentBytes` in the shared manifest). */\n rawBytes: number;\n /** sha256 of the uncompressed JSONL: the cross-zlib parity check. */\n contentSha256: string;\n /** Index of the chunk's first row in the input stream. */\n firstRow: number;\n gz: Buffer;\n};\n\n/** One row as the line a chunk carries: tagged, or bare when the chunk declares its entity. */\nexport function chunkLine(row: TaggedRow, declared: string | null): string {\n if (declared !== null) return dumps(row.row) + \"\\n\";\n const tagged: JsonObject = new Map();\n tagged.set(\"entity\", row.entity);\n tagged.set(\"row\", row.row);\n return dumps(tagged) + \"\\n\";\n}\n\nexport async function* buildChunks(rows: AsyncIterable<TaggedRow>, plan: ChunkPlan): AsyncGenerator<BuiltChunk> {\n let lines: Buffer[] = [];\n let rawBytes = 0;\n let ordinal = 0;\n let seen = 0;\n const flush = (): BuiltChunk => {\n const raw = Buffer.concat(lines);\n const built = finishChunk(ordinal++, raw, lines.length, plan.entity, seen - lines.length);\n lines = [];\n rawBytes = 0;\n return built;\n };\n for await (const row of rows) {\n const line = Buffer.from(chunkLine(row, plan.entity), \"utf8\");\n const full =\n lines.length > 0 &&\n ((plan.chunkRows !== null && lines.length >= plan.chunkRows) ||\n rawBytes + line.length > plan.chunkBytes);\n if (full) yield flush();\n lines.push(line);\n rawBytes += line.length;\n seen++;\n }\n if (lines.length) yield flush();\n}\n\nexport function finishChunk(ordinal: number, raw: Buffer, rows: number, entity: string | null, firstRow = 0): BuiltChunk {\n const gz = gzipDeterministic(raw, { name: chunkName(ordinal) });\n return {\n ordinal,\n digest: createHash(\"sha256\").update(gz).digest(\"hex\"),\n bytes: gz.length,\n rows,\n entity,\n rawBytes: raw.length,\n contentSha256: createHash(\"sha256\").update(raw).digest(\"hex\"),\n firstRow,\n gz,\n };\n}\n\n/**\n * Whether this Node's zlib deflates as the CPython that wrote the fixtures\n * did. Deflate output is a property of the zlib build, not of the format:\n * the same input inflates everywhere, but a zlib-ng or a future Chromium\n * zlib may pick different matches, and then gzip digests differ across\n * CLIs while content digests (over the JSONL) still agree. The manifest\n * parity check is on the content; the gzip digest is informative.\n */\nexport function zlibDeflatesLikeCPython(): boolean {\n return deflateRawSync(Buffer.from(CPYTHON_PROBE_TEXT), { level: GZIP_LEVEL }).toString(\"hex\") === CPYTHON_PROBE_DEFLATE;\n}\n/**\n * Two tagged rows, as the chunker writes them, and CPython's deflate of them (zlib\n * 1.2.12, which also wrote the fixtures). The probe has to be this long: \"hello\\n\"\n * deflates identically on every zlib, so it proved nothing, while on this text\n * Node 20 and 24 (Chromium's zlib 1.3.1) pick different matches and land two\n * bytes shorter than Node 25 and CPython (stock zlib).\n */\nconst CPYTHON_PROBE_TEXT = '{\"entity\":\"customers\",\"row\":{\"id\":0,\"name\":\"n0\",\"score\":0.0,\"tags\":[\"a\"]}}\\n{\"entity\":\"customers\",\"row\":{\"id\":1,\"name\":\"n1\",\"score\":1.0,\"tags\":[\"a\"]}}\\n';\nconst CPYTHON_PROBE_DEFLATE = \"ab564acd2bc92ca954b2524a2e2d2ec9cf4d2d2a56d2512aca2f57b2aa56ca4c51b232d051ca4bcc4d052ac83300ca1427e7170139067a40f192c4f46225ab68a544a5d8da5aae6a824619228c3244186588691400\";\n\n/** The file name the Python CLI gives chunk N (`chunk-00007.jsonl.gz`), which\n * its `GzipFile` records in the gzip header, so it is part of the digest. */\nexport const chunkName = (ordinal: number): string => `chunk-${String(ordinal).padStart(5, \"0\")}.jsonl`;\n\n/**\n * Gzip as CPython's `gzip.GzipFile(fileobj, \"wb\", mtime=0)` writes it: mtime\n * 0, XFL for the level, OS \"unknown\" (0xff), and — when a name is given — the\n * FNAME field, exactly as GzipFile records the basename of the file it writes.\n */\nexport function gzipDeterministic(raw: Buffer, opts: { level?: number; name?: string } = {}): Buffer {\n const level = opts.level ?? GZIP_LEVEL;\n const name = opts.name ? Buffer.concat([Buffer.from(opts.name, \"latin1\"), Buffer.from([0])]) : Buffer.alloc(0);\n const header = Buffer.from([0x1f, 0x8b, 0x08, opts.name ? 0x08 : 0x00, 0, 0, 0, 0, level === 9 ? 0x02 : level === 1 ? 0x04 : 0x00, 0xff]);\n const body = deflateRawSync(raw, { level });\n const trailer = Buffer.alloc(8);\n trailer.writeUInt32LE(crc32(raw), 0);\n trailer.writeUInt32LE(raw.length >>> 0, 4);\n return Buffer.concat([header, name, body, trailer]);\n}\n\nlet table: Uint32Array | null = null;\n\n/** CRC-32 (IEEE), the gzip trailer's checksum. A table here keeps the CLI on Node 18. */\nexport function crc32(data: Buffer): number {\n if (!table) {\n table = new Uint32Array(256);\n for (let n = 0; n < 256; n++) {\n let c = n;\n for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;\n table[n] = c >>> 0;\n }\n }\n let crc = 0xffffffff;\n for (let i = 0; i < data.length; i++) crc = table[(crc ^ data[i]!) & 0xff]! ^ (crc >>> 8);\n return (crc ^ 0xffffffff) >>> 0;\n}\n\n/** The Python CLI's `_parse_size`: an integer and a unit — none, b, k, kib, kb, m, mib, mb, g, gib, gb. */\nexport function parseSize(text: string): number {\n const units: Record<string, number> = { \"\": 1, b: 1, k: 1024, kib: 1024, kb: 1000, m: 1024 ** 2, mib: 1024 ** 2, mb: 1000 ** 2, g: 1024 ** 3, gib: 1024 ** 3, gb: 1000 ** 3 };\n const raw = text.trim().toLowerCase().replace(/ /g, \"\");\n const m = /^(\\d+)([a-z]*)$/.exec(raw);\n if (!m || !(m[2]! in units)) throw new Error(`--chunk-bytes takes a size like 64MiB or 1000000, not '${text}'`);\n return Number(m[1]) * units[m[2]!]!;\n}\n","/**\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","import { createHash } from \"node:crypto\";\n\nimport { CliError } from \"../../router\";\nimport { dumps, isObject, JsonNumber, parseJson, pyRound, pyStr, type JsonObject, type JsonValue } from \"./json\";\nimport { openInput, readLines, readWhole, refuse, rowObject, streamValues, type RowInput } from \"./rowSource\";\nimport type { RedactPolicy, WorldConfig } from \"./worldConfig\";\n\n/**\n * `gateway worlds data extract`: rows out of the shapes agents actually have\n * (contract §12), the same in both CLIs — this is a port of the Python\n * runtime's `extract.py`, decision for decision. An adapter finds candidate\n * rows; then every row loses its null and empty-string fields, loses the\n * fields the entity does not declare (counted, never silent), is skipped\n * when it lacks its primary key, is deduped by that key with `--merge`, and\n * passes through the world's `[redact]` policy. Rows are held for the\n * dedupe; the input is streamed.\n */\n\nexport type Shape = \"vendor-envelope\" | \"tool-results\" | \"session-export\";\nexport const SHAPES: Shape[] = [\"tool-results\", \"vendor-envelope\", \"session-export\"];\n\nexport type Merge = \"fill\" | \"upsert\";\n\nexport type ExtractOptions = {\n shape: Shape;\n entity: string;\n merge: Merge;\n redact: boolean;\n};\n\nexport type ExtractSummary = {\n read: number;\n rows: number;\n unknownFields: Record<string, number>;\n redacted: { dropped: number; hashed: number };\n};\n\nexport async function extractRows(input: RowInput, config: WorldConfig, opts: ExtractOptions, out: (line: string) => void): Promise<ExtractSummary> {\n const entity = config.entities[opts.entity];\n if (!entity) throw new CliError(`Unknown entity ${opts.entity}; the world has ${Object.keys(config.entities).sort().join(\", \")}`, 1);\n const keys = entity.primaryKey;\n const summary: ExtractSummary = { read: 0, rows: 0, unknownFields: {}, redacted: { dropped: 0, hashed: 0 } };\n const held = new Map<string, JsonObject>();\n\n const take = (raw: JsonObject): void => {\n summary.read++;\n const row = clean(raw, entity.fields, summary);\n if (!keys.every((name) => row.has(name))) return;\n const key = dumps(keys.map((name) => row.get(name)!));\n const existing = held.get(key);\n if (!existing) held.set(key, row);\n else if (opts.merge === \"upsert\") held.set(key, row);\n else for (const [name, value] of row) if (!existing.has(name)) existing.set(name, value);\n };\n\n await adapters[opts.shape](input, config, keys, take);\n\n const policy = opts.redact ? config.redact : null;\n for (const row of held.values()) {\n let final = row;\n if (policy) {\n final = redact(row, policy, config.slug ?? \"\") as JsonObject;\n countRedaction(row, final, policy, summary);\n }\n const tagged: JsonObject = new Map();\n tagged.set(\"entity\", opts.entity);\n tagged.set(\"row\", final);\n out(dumps(tagged));\n summary.rows++;\n }\n summary.unknownFields = Object.fromEntries(Object.entries(summary.unknownFields).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));\n return summary;\n}\n\n/** Drop null and \"\" values; strip (and count) fields the entity does not declare. */\nfunction clean(row: JsonObject, declared: Set<string> | null, summary: ExtractSummary): JsonObject {\n const out: JsonObject = new Map();\n for (const [name, value] of row) {\n if (value === null || value === \"\") continue;\n if (declared && !declared.has(name)) {\n summary.unknownFields[name] = (summary.unknownFields[name] ?? 0) + 1;\n continue;\n }\n out.set(name, value);\n }\n return out;\n}\n\n/** The Python `_count_redaction`: top-level fields gone, top-level hash fields hashed. */\nfunction countRedaction(before: JsonObject, after: JsonObject, policy: RedactPolicy, summary: ExtractSummary): void {\n for (const [name, value] of before) {\n if (!after.has(name)) summary.redacted.dropped++;\n else if (policy.hash.includes(name) && value !== null) summary.redacted.hashed++;\n }\n}\n\ntype Take = (candidate: JsonObject) => void;\ntype Adapter = (input: RowInput, config: WorldConfig, keys: string[], take: Take) => Promise<void>;\n\n/** `{..., \"raw_output\": {...}}` per line; rows are `raw_output.results[]` (or `items[]`) carrying the key. */\nconst toolResults: Adapter = async (input, _config, keys, take) => {\n for await (const record of records(input)) {\n if (!isObject(record)) continue;\n const raw = record.get(\"raw_output\");\n if (!isObject(raw)) continue;\n let listed = raw.get(\"results\");\n if (listed === undefined || listed === null) listed = raw.get(\"items\");\n for (const item of objects(listed)) if (keys.every((name) => item.has(name))) take(item);\n }\n};\n\n/** Each line, or the one document, is the vendor's response; rows sit under `[api].envelope`. */\nconst vendorEnvelope: Adapter = async (input, config, _keys, take) => {\n const where = input.name;\n const envelope = config.envelope;\n const opened = await openInput(input, () => true);\n if (!opened) return;\n if (opened.kind === \"array\") {\n if (envelope) throw refuse(`${where} is a bare array but the world's envelope is '${envelope}'`);\n for await (const item of streamValues(opened.bytes, where)) take(rowObject(item.value, item.where));\n return;\n }\n if (opened.kind === \"other\") throw refuse(`${where} is neither a JSON object nor an array`);\n if (!envelope) throw refuse(`${where} is an object but the world's envelope is empty: expected a bare array`);\n if (opened.kind === \"lines\") {\n for await (const response of records(input, opened.lines)) for (const row of objects(dig(response, envelope))) take(row);\n return;\n }\n // One pretty-printed response. A top-level envelope key streams; a dotted one\n // is read whole, as the Python side reads every document of this shape.\n const parts = envelope.split(\".\").filter(Boolean);\n if (parts.length === 1) {\n const top = parts[0]!;\n const values = streamValues(opened.bytes, where, {\n other: (key, value) => {\n if (key === top) for (const row of objects(value)) take(row);\n },\n });\n for await (const item of values) if (item.key === top && isObject(item.value)) take(item.value);\n return;\n }\n const text = await readWhole(opened.bytes);\n let document: JsonValue;\n try {\n document = parseJson(text);\n } catch {\n throw refuse(`${where}: not valid JSON`);\n }\n for (const row of objects(dig(document, envelope))) take(row);\n};\n\n/** `calls.jsonl`: rows are `result.<envelope>[]` of successful `call` records. */\nconst sessionExport: Adapter = async (input, config, _keys, take) => {\n for await (const record of records(input)) {\n if (!isObject(record) || record.get(\"kind\") !== \"call\") continue;\n const error = record.get(\"error\");\n if (error !== null && error !== undefined) continue;\n const result = record.get(\"result\") ?? null;\n for (const row of objects(config.envelope ? dig(result, config.envelope) : result)) take(row);\n }\n};\n\nconst adapters: Record<Shape, Adapter> = {\n \"tool-results\": toolResults,\n \"vendor-envelope\": vendorEnvelope,\n \"session-export\": sessionExport,\n};\n\n/** The Python `_lines`: every non-blank line parsed, numbered from 1. */\nasync function* records(input: RowInput, lines: AsyncIterable<string> = readLines(input)): AsyncGenerator<JsonValue> {\n let number = 0;\n for await (const raw of lines) {\n number++;\n const line = raw.endsWith(\"\\r\") ? raw.slice(0, -1) : raw;\n if (!line.trim()) continue;\n try {\n yield parseJson(line);\n } catch {\n throw refuse(`${input.name}:${number} is not JSON`);\n }\n }\n}\n\n/** The Python `_objects`: the objects of a list, or the one object. */\nfunction objects(value: JsonValue | undefined): JsonObject[] {\n if (Array.isArray(value)) return value.filter(isObject);\n if (isObject(value)) return [value];\n return [];\n}\n\n/** The Python `_dig`: walk a dotted path through objects; null when it is not there. */\nexport function dig(value: JsonValue | undefined, path: string): JsonValue {\n let at: JsonValue | undefined = value;\n for (const part of path.split(\".\").filter(Boolean)) {\n if (!isObject(at) || !at.has(part)) return null;\n at = at.get(part);\n }\n return at ?? null;\n}\n\n// ---------------------------------------------------------------- redaction\n\nconst named = (key: string, here: string, names: string[]): boolean => names.includes(key) || names.includes(here);\n\n/** `\"sha256:\" + sha256(\"<slug>:\" + str(value))`; lists element-wise; objects and null untouched. */\nexport function digest(slug: string, item: JsonValue): JsonValue {\n if (Array.isArray(item)) return item.map((element) => digest(slug, element));\n if (isObject(item) || item === null) return item;\n return \"sha256:\" + createHash(\"sha256\").update(`${slug}:${pyStr(item)}`, \"utf8\").digest(\"hex\");\n}\n\n/**\n * The Python runtime's `redact`: a bare name applies at any depth, a dotted\n * path at that place only (`*` for a list item). Hash, drop or round; the\n * rest recurses untouched.\n */\nexport function redact(value: JsonValue, policy: RedactPolicy, slug: string, path = \"\"): JsonValue {\n if (isObject(value)) {\n const out: JsonObject = new Map();\n for (const [key, item] of value) {\n const here = path ? `${path}.${key}` : key;\n if (named(key, here, policy.drop)) continue;\n if (named(key, here, policy.hash) && item !== null) out.set(key, digest(slug, item));\n else if (key in policy.round && item instanceof JsonNumber) out.set(key, pyRound(item, policy.round[key]!));\n else out.set(key, redact(item, policy, slug, here));\n }\n return out;\n }\n if (Array.isArray(value)) return value.map((item) => redact(item, policy, slug, path ? `${path}.*` : \"*\"));\n return value;\n}\n\n/** `json.dumps(summary)` with Python's default separators and ASCII escaping, for the stderr line. */\nexport function pyDumpsPlain(value: unknown): string {\n if (value === null || value === undefined) return \"null\";\n if (typeof value === \"boolean\") return value ? \"true\" : \"false\";\n if (typeof value === \"number\") return Number.isInteger(value) ? String(value) : String(value);\n if (typeof value === \"string\") return JSON.stringify(value).replace(/[-￿]/g, (c) => \"\\\\u\" + c.charCodeAt(0).toString(16).padStart(4, \"0\"));\n if (Array.isArray(value)) return \"[\" + value.map(pyDumpsPlain).join(\", \") + \"]\";\n return \"{\" + Object.entries(value as Record<string, unknown>).map(([k, v]) => `${pyDumpsPlain(k)}: ${pyDumpsPlain(v)}`).join(\", \") + \"}\";\n}\n","import * as fs from \"node:fs\";\nimport { Readable } from \"node:stream\";\nimport { createGunzip } from \"node:zlib\";\n\nimport { CliError } from \"../../router\";\nimport { isObject, parseJson, type JsonObject, type JsonValue } from \"./json\";\nimport { ScanError, TopLevelScanner } from \"./scanner\";\n\n/**\n * Rows files as a stream, the way the Python runtime's `iter_file_rows`\n * reads them: the three shapes (a JSON object of entity -> rows, tagged\n * JSONL, bare rows with --entity), refused with the same words, never held\n * whole. The first byte decides between an array and an object; for an\n * object the first line decides between JSONL (it parses as a row) and a\n * document (it does not, or it is longer than `LINE_CAP`), which then\n * streams through the top-level scanner one element at a time. `-` is\n * stdin; a `.gz` path is gunzipped.\n */\n\nexport type TaggedRow = { entity: string; row: JsonObject; where: string };\n\nexport type RowInput = { name: string; open: () => Readable };\n\n/** A first line longer than this is a one-line document, never a JSONL row. */\nexport const LINE_CAP = 1024 * 1024;\n\nexport const refuse = (message: string): CliError => new CliError(message, 1);\n\nexport function fileInput(path: string): RowInput {\n return {\n name: path,\n open: () => {\n const raw = fs.createReadStream(path);\n return path.endsWith(\".gz\") ? raw.pipe(createGunzip()) : raw;\n },\n };\n}\n\nexport async function* readRows(inputs: RowInput[], entity?: string): AsyncGenerator<TaggedRow> {\n for (const input of inputs) yield* readOne(input, entity);\n}\n\n/** How an input reads, decided from its first byte and first line. */\nexport type InputShape =\n | { kind: \"array\"; bytes: AsyncIterable<Buffer> }\n | { kind: \"document\"; bytes: AsyncIterable<Buffer> }\n | { kind: \"lines\"; lines: AsyncIterable<string> }\n | { kind: \"other\" };\n\n/**\n * Open an input and decide its shape; null when it holds only whitespace.\n * `looksLikeRow` says whether a first line that parsed as an object is a\n * JSONL row (then the file is lines) or the start of a document.\n */\nexport async function openInput(input: RowInput, looksLikeRow: (first: JsonObject) => boolean): Promise<InputShape | null> {\n const bytes = openBytes(input);\n const first = await bytes.firstNonWhitespace();\n if (first === null) return null;\n if (first === 0x5b) return { kind: \"array\", bytes: bytes.remaining() };\n if (first !== 0x7b) return { kind: \"other\" };\n const line = await bytes.firstLine(LINE_CAP);\n if (line !== null) {\n let parsed: JsonValue | undefined;\n try {\n parsed = parseJson(line);\n } catch {\n parsed = undefined;\n }\n if (parsed !== undefined && isObject(parsed) && looksLikeRow(parsed)) return { kind: \"lines\", lines: bytes.lines() };\n }\n return { kind: \"document\", bytes: bytes.remaining() };\n}\n\n/** Every line of an input, whatever its first byte (the Python `_lines`). */\nexport function readLines(input: RowInput): AsyncIterable<string> {\n return openBytes(input).lines();\n}\n\n/** The whole input as text — for the one shape the Python side reads whole too. */\nexport async function readWhole(bytes: AsyncIterable<Buffer>): Promise<string> {\n const parts: Buffer[] = [];\n for await (const chunk of bytes) parts.push(chunk);\n return Buffer.concat(parts).toString(\"utf8\");\n}\n\nfunction openBytes(input: RowInput): ByteReader {\n let stream: Readable;\n try {\n stream = input.open();\n } catch {\n throw refuse(`Cannot read ${input.name}`);\n }\n return new ByteReader(stream, input.name);\n}\n\nasync function* readOne(input: RowInput, entity: string | undefined): AsyncGenerator<TaggedRow> {\n const path = input.name;\n const isRow = (parsed: JsonObject) => {\n const keys = [...parsed.keys()];\n if (entity === undefined) return keys.length === 2 && parsed.has(\"entity\") && parsed.has(\"row\");\n return !(keys.length === 1 && keys[0] === entity && Array.isArray(parsed.get(entity)));\n };\n const opened = await openInput(input, isRow);\n if (!opened) return; // blank file: no rows\n if (opened.kind === \"other\") throw refuse(`${path} is neither a JSON object of entity -> rows nor an array of rows`);\n if (opened.kind === \"array\") {\n if (entity === undefined) throw refuse(`${path} is a bare array; say which entity it holds with --entity`);\n for await (const { value, where } of streamValues(opened.bytes, path)) yield { entity, row: rowObject(value, where), where };\n return;\n }\n if (opened.kind === \"lines\") {\n yield* jsonlRows(opened.lines, path, entity);\n return;\n }\n const values = streamValues(opened.bytes, path, {\n key: (key, isArray) => {\n if (!isArray) throw refuse(`${path}: ${key} must map to an array of rows (JSONL lines are {\"entity\", \"row\"})`);\n if (entity !== undefined && key !== entity) throw refuse(`${path} maps entities; drop --entity or make the file a bare array`);\n },\n });\n for await (const { key, value, where } of values) yield { entity: key!, row: rowObject(value, where), where };\n}\n\nexport type StreamedValue = { key: string | null; value: JsonValue; index: number; where: string };\n\n/**\n * The elements of a document as the scanner finds them, parsed: the items of\n * an array document (`key` null), or of each array value of an object\n * document. `hooks.key` sees every object key with whether its value is an\n * array; a non-array value goes whole to `hooks.other`. Content after the\n * document's closing bracket is ignored, as the Python reader ignores it.\n */\nexport async function* streamValues(\n bytes: AsyncIterable<Buffer>,\n path: string,\n hooks: { key?: (key: string, isArray: boolean) => void; other?: (key: string, value: JsonValue) => void } = {},\n): AsyncGenerator<StreamedValue> {\n const queue: StreamedValue[] = [];\n const whereOf = (key: string | null, index: number) => (key === null ? `${path}[${index}]` : `${path}:${key}[${index}]`);\n const scanner = new TopLevelScanner({\n key: (key, isArray) => hooks.key?.(key, isArray),\n element: (key, text, index) => {\n const where = whereOf(key, index);\n queue.push({ key, value: parseElement(text, where), index, where });\n },\n other: (key, text) => hooks.other?.(key, parseElement(text, `${path}:${key}`)),\n });\n try {\n for await (const chunk of bytes) {\n scanner.feed(chunk);\n if (queue.length) yield* queue.splice(0);\n }\n scanner.end();\n } catch (error) {\n if (error instanceof ScanError) throw refuse(`${error.open ? whereOf(error.open.key, error.open.index) : path}: not valid JSON`);\n throw error;\n }\n if (queue.length) yield* queue.splice(0);\n}\n\nfunction parseElement(text: string, where: string): JsonValue {\n try {\n return parseJson(text);\n } catch {\n throw refuse(`${where}: not valid JSON`);\n }\n}\n\n/** JSONL, numbered from the first line as the Python reader numbers them\n * (a blank line counts; the first line is never blank). */\nasync function* jsonlRows(lines: AsyncIterable<string>, path: string, entity: string | undefined): AsyncGenerator<TaggedRow> {\n let number = 0;\n for await (const raw of lines) {\n number++;\n const line = raw.endsWith(\"\\r\") ? raw.slice(0, -1) : raw;\n if (!line.trim()) continue;\n let item: JsonValue;\n try {\n item = parseJson(line);\n } catch {\n throw refuse(`${path}:${number} is not JSON`);\n }\n const where = `${path}:${number}`;\n if (entity !== undefined) {\n yield { entity, row: rowObject(item, where), where };\n continue;\n }\n if (!isObject(item) || item.size !== 2 || !item.has(\"entity\") || !item.has(\"row\") || typeof item.get(\"entity\") !== \"string\")\n throw refuse(`${where}: expected {\"entity\": name, \"row\": {…}} (or pass --entity for bare rows)`);\n yield { entity: item.get(\"entity\") as string, row: rowObject(item.get(\"row\")!, where), where };\n }\n}\n\nexport function rowObject(row: JsonValue, where: string): JsonObject {\n if (!isObject(row)) throw refuse(`${where}: a row must be a JSON object`);\n return row;\n}\n\n// ------------------------------------------------------------ byte reading\n\nconst isWs = (c: number): boolean => c === 0x20 || c === 0x0a || c === 0x0d || c === 0x09;\nconst BOM = Buffer.from([0xef, 0xbb, 0xbf]);\n\n/** A readable's bytes with a re-readable prefix: what the probe consumed is\n * handed back to whichever reader (document scanner, line splitter) follows. */\nclass ByteReader {\n private held: Buffer[] = [];\n private readonly iterator: AsyncIterator<Buffer>;\n private done = false;\n private start = 0; // bytes of leading whitespace (and a BOM) already skipped\n\n constructor(\n stream: Readable,\n private readonly path: string,\n ) {\n this.iterator = stream[Symbol.asyncIterator]() as AsyncIterator<Buffer>;\n }\n\n private async next(): Promise<Buffer | null> {\n if (this.done) return null;\n let result: IteratorResult<Buffer>;\n try {\n result = await this.iterator.next();\n } catch (error) {\n const code = (error as { code?: string }).code;\n throw refuse(code === \"Z_DATA_ERROR\" ? `Cannot read ${this.path} as UTF-8 text` : `Cannot read ${this.path}`);\n }\n if (result.done) {\n this.done = true;\n return null;\n }\n const chunk = result.value;\n return Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as unknown as string, \"utf8\");\n }\n\n private all(): Buffer {\n if (this.held.length > 1) this.held = [Buffer.concat(this.held)];\n return this.held[0] ?? Buffer.alloc(0);\n }\n\n /** The first non-whitespace byte (a leading BOM is whitespace), keeping everything read. */\n async firstNonWhitespace(): Promise<number | null> {\n for (;;) {\n const buf = this.all();\n let i = this.start;\n if (i === 0 && buf.length >= 3 && buf.subarray(0, 3).equals(BOM)) i = 3;\n while (i < buf.length && isWs(buf[i]!)) i++;\n if (i < buf.length) {\n this.start = i;\n return buf[i]!;\n }\n const chunk = await this.next();\n if (chunk === null) return null;\n this.held.push(chunk);\n }\n }\n\n /** The first line from the first non-whitespace byte, without its newline;\n * null when no newline shows up within `cap` bytes (a one-line document). */\n async firstLine(cap: number): Promise<string | null> {\n for (;;) {\n const buf = this.all();\n const at = buf.indexOf(0x0a, this.start);\n if (at !== -1) return buf.subarray(this.start, at).toString(\"utf8\");\n if (buf.length - this.start > cap) return null;\n const chunk = await this.next();\n if (chunk === null) return buf.length > this.start ? buf.subarray(this.start).toString(\"utf8\") : null;\n this.held.push(chunk);\n }\n }\n\n /** Everything from the first non-whitespace byte: the held prefix, then the rest of the stream. */\n async *remaining(): AsyncGenerator<Buffer> {\n const prefix = this.all().subarray(this.start);\n this.held = [];\n this.start = 0;\n if (prefix.length) yield prefix;\n for (;;) {\n const chunk = await this.next();\n if (chunk === null) return;\n yield chunk;\n }\n }\n\n /** Lines split on `\\n` (a trailing `\\r` is the caller's to strip). */\n async *lines(): AsyncGenerator<string> {\n let carry = \"\";\n const decoder = new TextDecoder(\"utf-8\", { fatal: true });\n const decode = (chunk: Buffer | undefined): string => {\n try {\n return chunk ? decoder.decode(chunk, { stream: true }) : decoder.decode();\n } catch {\n throw refuse(`Cannot read ${this.path} as UTF-8 text`);\n }\n };\n for await (const chunk of this.remaining()) {\n const text = carry + decode(chunk);\n const parts = text.split(\"\\n\");\n carry = parts.pop()!;\n yield* parts;\n }\n carry += decode(undefined);\n if (carry) yield carry;\n }\n}\n","/**\n * A byte-level scanner over one top-level JSON document, so a rows file of\n * any size streams: `{\"<key>\": [row, row, …], …}` hands out each element's\n * text as it closes (and each non-array value whole), `[row, row, …]` hands\n * out its elements. Only the current value is ever held. Elements are parsed\n * by the caller (`parseJson`), never here — this only finds their bounds.\n *\n * Structural bytes are ASCII, so slicing on them never splits a UTF-8\n * sequence; strings and escapes are tracked so a `]` inside a string is text.\n */\n\nexport class ScanError extends Error {\n constructor(\n message: string,\n /** The array element that was open when the document ended, if any. */\n readonly open: { key: string | null; index: number } | null = null,\n ) {\n super(message);\n }\n}\n\nexport type ScanEvents = {\n /** The document's first byte decided its shape. */\n shape?: (shape: \"object\" | \"array\") => void;\n /** An object key, as soon as its value's first byte says whether it is an array. */\n key?: (key: string, isArray: boolean) => void;\n /** An element of a depth-1 array (`key` null for an array document). */\n element: (key: string | null, text: string, index: number) => void;\n /** A depth-1 object value that is not an array, whole. */\n other?: (key: string, text: string) => void;\n /** The top-level value closed; anything but whitespace after it is `trailing`. */\n end?: (trailing: boolean) => void;\n};\n\ntype Mode =\n | \"start\"\n | \"objKey\"\n | \"objColon\"\n | \"objValue\"\n | \"objAfterValue\"\n | \"arrElem\"\n | \"arrAfterElem\"\n | \"done\"\n | \"trailing\"\n | \"notDocument\";\n\ntype Capture = { kind: \"string\" | \"container\" | \"scalar\"; depth: number; inString: boolean; escape: boolean };\n\nconst WS = new Set([0x20, 0x0a, 0x0d, 0x09]);\n\nexport class TopLevelScanner {\n private mode: Mode = \"start\";\n private pending: Buffer = Buffer.alloc(0);\n private cursor = 0; // scan position inside pending\n private captureStart = -1;\n private capture: Capture | null = null;\n private key: string | null = null;\n private index = 0;\n private afterKey: \"objColon\" | null = null;\n /** True when the first byte said this is not an object or array document. */\n notDocument = false;\n\n constructor(private readonly events: ScanEvents) {}\n\n feed(chunk: Buffer): void {\n if (this.mode === \"notDocument\" || this.mode === \"trailing\") return;\n this.pending = this.pending.length ? Buffer.concat([this.pending, chunk]) : chunk;\n this.scan();\n }\n\n end(): void {\n if (this.mode === \"notDocument\" || this.mode === \"trailing\") return;\n this.scan();\n if (this.mode === \"start\") return; // blank input: no document at all\n if (this.mode !== \"done\")\n throw new ScanError(\"Unexpected end of document\", this.capture && (this.mode === \"arrElem\" || this.mode === \"arrAfterElem\") ? { key: this.key, index: this.index } : null);\n this.events.end?.(false);\n }\n\n private scan(): void {\n const buf = this.pending;\n while (this.cursor < buf.length) {\n if (this.capture) {\n if (!this.advanceCapture(buf)) return;\n continue;\n }\n const c = buf[this.cursor]!;\n if (WS.has(c) && this.mode !== \"trailing\") {\n this.cursor++;\n continue;\n }\n switch (this.mode) {\n case \"start\":\n if (c === 0x7b) {\n this.mode = \"objKey\";\n this.events.shape?.(\"object\");\n } else if (c === 0x5b) {\n this.mode = \"arrElem\";\n this.events.shape?.(\"array\");\n } else {\n this.mode = \"notDocument\";\n this.notDocument = true;\n return;\n }\n this.cursor++;\n break;\n case \"objKey\":\n if (c === 0x7d) {\n this.cursor++;\n this.finish();\n break;\n }\n if (c !== 0x22) throw new ScanError(\"Expecting property name enclosed in double quotes\");\n this.beginCapture(\"string\");\n this.afterKey = \"objColon\";\n break;\n case \"objColon\":\n if (c !== 0x3a) throw new ScanError(\"Expecting ':' delimiter\");\n this.cursor++;\n this.mode = \"objValue\";\n break;\n case \"objValue\":\n this.events.key?.(this.key!, c === 0x5b);\n if (c === 0x5b) {\n this.cursor++;\n this.index = 0;\n this.mode = \"arrElem\";\n } else this.beginCapture(c === 0x22 ? \"string\" : c === 0x7b ? \"container\" : \"scalar\");\n break;\n case \"objAfterValue\":\n if (c === 0x2c) {\n this.cursor++;\n this.mode = \"objKey\";\n } else if (c === 0x7d) {\n this.cursor++;\n this.finish();\n } else throw new ScanError(\"Expecting ',' delimiter\");\n break;\n case \"arrElem\":\n if (c === 0x5d) {\n this.cursor++;\n this.closeArray();\n } else this.beginCapture(c === 0x22 ? \"string\" : c === 0x7b || c === 0x5b ? \"container\" : \"scalar\");\n break;\n case \"arrAfterElem\":\n if (c === 0x2c) {\n this.cursor++;\n this.mode = \"arrElem\";\n } else if (c === 0x5d) {\n this.cursor++;\n this.closeArray();\n } else throw new ScanError(\"Expecting ',' delimiter\");\n break;\n case \"done\":\n this.mode = \"trailing\";\n this.events.end?.(true);\n return;\n default:\n return;\n }\n }\n // Everything before the capture start is consumed; keep only the open capture.\n if (this.capture) {\n this.pending = buf.subarray(this.captureStart);\n this.cursor -= this.captureStart;\n this.captureStart = 0;\n } else {\n this.pending = Buffer.alloc(0);\n this.cursor = 0;\n }\n }\n\n private beginCapture(kind: Capture[\"kind\"]): void {\n this.captureStart = this.cursor;\n this.capture = { kind, depth: 0, inString: kind === \"string\", escape: false };\n if (kind === \"string\") this.cursor++;\n }\n\n /** Advance the open capture; true when it closed. */\n private advanceCapture(buf: Buffer): boolean {\n const cap = this.capture!;\n while (this.cursor < buf.length) {\n const c = buf[this.cursor]!;\n if (cap.inString) {\n if (cap.escape) cap.escape = false;\n else if (c === 0x5c) cap.escape = true;\n else if (c === 0x22) {\n cap.inString = false;\n if (cap.kind === \"string\") {\n this.cursor++;\n this.closeCapture(buf);\n return true;\n }\n }\n this.cursor++;\n continue;\n }\n if (cap.kind === \"scalar\") {\n if (c === 0x2c || c === 0x5d || c === 0x7d || WS.has(c)) {\n this.closeCapture(buf);\n return true;\n }\n this.cursor++;\n continue;\n }\n // container\n if (c === 0x22) cap.inString = true;\n else if (c === 0x7b || c === 0x5b) cap.depth++;\n else if (c === 0x7d || c === 0x5d) {\n cap.depth--;\n if (cap.depth === 0) {\n this.cursor++;\n this.closeCapture(buf);\n return true;\n }\n }\n this.cursor++;\n }\n return false;\n }\n\n private closeCapture(buf: Buffer): void {\n const text = buf.subarray(this.captureStart, this.cursor);\n this.capture = null;\n this.captureStart = -1;\n if (this.afterKey) {\n this.key = decodeKey(text);\n this.afterKey = null;\n this.mode = \"objColon\";\n return;\n }\n if (this.mode === \"objValue\") {\n this.events.other?.(this.key!, text.toString(\"utf8\"));\n this.mode = \"objAfterValue\";\n return;\n }\n // an array element\n this.events.element(this.key, text.toString(\"utf8\"), this.index++);\n this.mode = \"arrAfterElem\";\n }\n\n private closeArray(): void {\n if (this.key === null) this.finish();\n else this.mode = \"objAfterValue\";\n }\n\n private finish(): void {\n this.mode = \"done\";\n this.key = null;\n }\n}\n\nfunction decodeKey(text: Buffer): string {\n const raw = text.toString(\"utf8\");\n try {\n return JSON.parse(raw) as string;\n } catch {\n throw new ScanError(\"Invalid property name\");\n }\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport { CliError } from \"../../router\";\n\n/**\n * The client manifest of an import, `.gateway/imports/<batchId>.json` in the\n * working directory: what was sent, chunk by chunk, so `--resume` after a\n * dropped connection re-opens the same batch and skips what was already\n * uploaded. The schema is shared with the Python CLI (contract §10) and so is\n * the layout: `.gateway/` carries its own `.gitignore` (`*`) so the manifests\n * never enter a repository, whichever CLI created the directory.\n */\n\nexport type ManifestFlags = {\n mode: \"append\" | \"replace\";\n merge: \"upsert\" | \"fill\";\n atomic: boolean;\n publish: \"now\" | \"later\";\n dryRun: boolean;\n chunkBytes: number;\n chunkRows: number | null;\n entity: string | null;\n};\n\nexport type ManifestChunk = {\n ordinal: number;\n digest: string;\n bytes: number;\n rows: number;\n entity: string | null;\n chunkId: string | null;\n uploaded: boolean;\n};\n\nexport type Manifest = {\n version: 1;\n batchId: string;\n slug: string;\n host: string;\n flags: ManifestFlags;\n inputs: string[];\n chunks: ManifestChunk[];\n completed: boolean;\n createdAt: string;\n updatedAt: string;\n};\n\nexport const MANIFEST_DIR = path.join(\".gateway\", \"imports\");\n\nexport function manifestDir(cwd = process.cwd()): string {\n return path.join(cwd, MANIFEST_DIR);\n}\n\nexport function manifestPath(batchId: string, cwd = process.cwd()): string {\n if (!/^[A-Za-z0-9_-]+$/.test(batchId)) throw new CliError(`Not a batch id: ${batchId}`);\n return path.join(manifestDir(cwd), `${batchId}.json`);\n}\n\n/** `2026-09-11T23:00:00Z`: seconds, UTC, as the Python CLI stamps it. */\nexport const stamp = (): string => new Date().toISOString().replace(/\\.\\d{3}Z$/, \"Z\");\n\nexport function newManifest(fields: Omit<Manifest, \"version\" | \"chunks\" | \"completed\" | \"createdAt\" | \"updatedAt\">): Manifest {\n const now = stamp();\n return { version: 1, ...fields, chunks: [], completed: false, createdAt: now, updatedAt: now };\n}\n\n/** Write atomically (rename over), stamping `updatedAt`; creates the directory and its gitignore. */\nexport function writeManifest(manifest: Manifest, cwd = process.cwd()): string {\n const file = manifestPath(manifest.batchId, cwd);\n fs.mkdirSync(path.dirname(file), { recursive: true });\n const ignore = path.join(cwd, \".gateway\", \".gitignore\");\n if (!fs.existsSync(ignore)) fs.writeFileSync(ignore, \"*\\n\");\n manifest.updatedAt = stamp();\n const tmp = `${file}.tmp`;\n fs.writeFileSync(tmp, JSON.stringify(manifest, null, 1) + \"\\n\");\n fs.renameSync(tmp, file);\n return file;\n}\n\nexport function readManifest(batchId: string, cwd = process.cwd()): Manifest | null {\n try {\n const parsed = JSON.parse(fs.readFileSync(manifestPath(batchId, cwd), \"utf8\")) as Manifest;\n return parsed && parsed.version === 1 && parsed.batchId === batchId ? parsed : null;\n } catch {\n return null;\n }\n}\n\n/** Record a chunk's registration/upload state by ordinal (replacing an earlier entry). */\nexport function recordChunk(manifest: Manifest, chunk: ManifestChunk): void {\n manifest.chunks = [...manifest.chunks.filter((c) => c.ordinal !== chunk.ordinal), chunk].sort((a, b) => a.ordinal - b.ordinal);\n}\n\n/** The manifest's entry for this chunk when it was already uploaded (same ordinal and digest). */\nexport function uploadedEntry(manifest: Manifest, ordinal: number, digest: string): ManifestChunk | null {\n return manifest.chunks.find((c) => c.ordinal === ordinal && c.digest === digest && c.uploaded) ?? null;\n}\n\n/** Every manifest in the working directory, newest first. */\nexport function listManifests(cwd = process.cwd()): Manifest[] {\n const dir = manifestDir(cwd);\n if (!fs.existsSync(dir)) return [];\n const out: Manifest[] = [];\n for (const name of fs.readdirSync(dir)) {\n if (!name.endsWith(\".json\")) continue;\n const manifest = readManifest(name.slice(0, -5), cwd);\n if (manifest) out.push(manifest);\n }\n return out.sort((a, b) => (a.updatedAt < b.updatedAt ? 1 : a.updatedAt > b.updatedAt ? -1 : 0));\n}\n\n/** The newest unfinished import of these inputs into this world, if one was started here. */\nexport function findResumable(slug: string, inputs: string[], cwd = process.cwd()): Manifest | null {\n const same = (a: string[], b: string[]) => a.length === b.length && a.every((x, i) => x === b[i]);\n return listManifests(cwd).find((m) => !m.completed && m.slug === slug && same(m.inputs, inputs)) ?? null;\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport { CliError } from \"../../router\";\nimport { parseToml, TomlError, type TomlTable, type TomlValue } from \"./toml\";\n\n/**\n * What `data extract` needs to know about a world, read from its tree:\n * each entity's primary key and declared fields (`schema/world.json`,\n * `x-gateway.entities`), and from `connector.toml` the connector slug (the\n * digest salt), the `[redact]` policy and the `[api]` envelope.\n */\n\nexport type EntityInfo = {\n primaryKey: string[];\n /** The entity schema's declared properties; null when they cannot be resolved. */\n fields: Set<string> | null;\n};\n\nexport type RedactPolicy = {\n hash: string[];\n drop: string[];\n round: Record<string, number>;\n};\n\nexport type WorldConfig = {\n dir: string;\n slug: string | null;\n entities: Record<string, EntityInfo>;\n redact: RedactPolicy;\n envelope: string;\n hitsKey: string;\n};\n\nexport function loadWorldConfig(dir: string): WorldConfig {\n const worldFile = [\"schema/world.json\", \"world.json\"].map((p) => path.join(dir, p)).find((p) => fs.existsSync(p));\n if (!worldFile) throw new CliError(`${dir} has no schema/world.json; extract needs a schema world`, 1);\n let document: Record<string, unknown>;\n try {\n document = JSON.parse(fs.readFileSync(worldFile, \"utf8\")) as Record<string, unknown>;\n } catch {\n throw new CliError(`${worldFile} is not valid JSON`, 1);\n }\n const annotation = document[\"x-gateway\"] as { entities?: Record<string, Record<string, unknown>> } | undefined;\n if (!annotation || typeof annotation !== \"object\" || !annotation.entities || typeof annotation.entities !== \"object\")\n throw new CliError(`${worldFile} declares no x-gateway entities`, 1);\n const entities: Record<string, EntityInfo> = {};\n for (const [name, entity] of Object.entries(annotation.entities)) {\n const primaryKey = Array.isArray(entity.primary_key) ? (entity.primary_key as string[]) : [];\n entities[name] = { primaryKey, fields: declaredFields(document, entity.schema) };\n }\n const spec = readSpec(path.join(dir, \"connector.toml\"));\n return { dir, slug: spec.slug, entities, redact: spec.redact, envelope: spec.envelope, hitsKey: spec.hitsKey };\n}\n\n/** Follow `$ref` pointers inside world.json to the entity's closed object; its property names. */\nfunction declaredFields(document: Record<string, unknown>, schema: unknown): Set<string> | null {\n let node = schema;\n for (let hops = 0; hops < 16 && node && typeof node === \"object\"; hops++) {\n const ref = (node as { $ref?: unknown }).$ref;\n if (typeof ref !== \"string\") break;\n if (!ref.startsWith(\"#/\")) return null; // another document (base.json): types, not entity roots\n node = ref\n .slice(2)\n .split(\"/\")\n .map((part) => part.replace(/~1/g, \"/\").replace(/~0/g, \"~\"))\n .reduce<unknown>((at, part) => (at && typeof at === \"object\" ? (at as Record<string, unknown>)[part] : undefined), document);\n }\n const properties = node && typeof node === \"object\" ? (node as { properties?: unknown }).properties : undefined;\n if (!properties || typeof properties !== \"object\") return null;\n return new Set(Object.keys(properties as Record<string, unknown>));\n}\n\nfunction readSpec(file: string): { slug: string | null; redact: RedactPolicy; envelope: string; hitsKey: string } {\n const none = { slug: null, redact: { hash: [], drop: [], round: {} }, envelope: \"\", hitsKey: \"hits\" };\n if (!fs.existsSync(file)) return none;\n let raw: TomlTable;\n try {\n raw = parseToml(fs.readFileSync(file, \"utf8\"));\n } catch (error) {\n if (error instanceof TomlError) throw new CliError(`${file}: ${error.message}`, 1);\n throw error;\n }\n const connector = table(raw.connector);\n const redact = table(raw.redact);\n const apiTable = table(raw.api);\n return {\n slug: typeof connector.slug === \"string\" ? connector.slug : null,\n redact: { hash: strings(redact.hash), drop: strings(redact.drop), round: rounding(redact.round) },\n envelope: typeof apiTable.envelope === \"string\" ? apiTable.envelope : \"\",\n hitsKey: typeof apiTable.hits_key === \"string\" ? apiTable.hits_key : \"hits\",\n };\n}\n\nconst table = (value: TomlValue | undefined): TomlTable => (value && typeof value === \"object\" && !Array.isArray(value) ? value : {});\nconst strings = (value: TomlValue | undefined): string[] => (Array.isArray(value) ? value.filter((v): v is string => typeof v === \"string\") : []);\nfunction rounding(value: TomlValue | undefined): Record<string, number> {\n const out: Record<string, number> = {};\n for (const [key, digits] of Object.entries(table(value))) if (typeof digits === \"number\" && Number.isInteger(digits)) out[key] = digits;\n return out;\n}\n","/**\n * A minimal TOML reader for what `data extract` needs from a world's\n * `connector.toml`: `[connector] slug`, the `[redact]` lists (`hash`, `drop`)\n * and map (`round`, inline or as `[redact.round]`), and `[api] envelope` /\n * `hits_key`. The package carries no TOML dependency (the Python side reads\n * the file with `tomllib`), so this covers: tables and dotted tables,\n * arrays of tables (their keys are kept under the array), key = value with\n * basic and literal strings, integers, floats, booleans, arrays (multi-line\n * too) and inline tables, and `#` comments. It does not cover multi-line\n * strings, dotted keys, dates, or exotic escapes; a connector.toml that uses\n * them keeps those values out of reach here, nothing more.\n */\n\nexport type TomlValue = string | number | boolean | TomlValue[] | TomlTable;\nexport type TomlTable = { [key: string]: TomlValue };\n\nexport class TomlError extends Error {}\n\nexport function parseToml(text: string): TomlTable {\n const root: TomlTable = {};\n let current: TomlTable = root;\n const lines = joinContinuations(text);\n for (const [number, rawLine] of lines.entries()) {\n const line = stripComment(rawLine).trim();\n if (!line) continue;\n const arrayTable = /^\\[\\[\\s*([^\\]]+?)\\s*\\]\\]$/.exec(line);\n if (arrayTable) {\n const parent = tableAt(root, keyPath(arrayTable[1]!).slice(0, -1));\n const name = keyPath(arrayTable[1]!).at(-1)!;\n const list = (parent[name] ??= []) as TomlValue[];\n if (!Array.isArray(list)) throw new TomlError(`line ${number + 1}: ${name} is not an array of tables`);\n current = {};\n list.push(current);\n continue;\n }\n const table = /^\\[\\s*([^\\]]+?)\\s*\\]$/.exec(line);\n if (table) {\n current = tableAt(root, keyPath(table[1]!));\n continue;\n }\n const eq = line.indexOf(\"=\");\n if (eq === -1) throw new TomlError(`line ${number + 1}: expected key = value`);\n const key = unquoteKey(line.slice(0, eq).trim());\n const [value, rest] = readValue(line.slice(eq + 1).trim(), number + 1);\n if (rest.trim()) throw new TomlError(`line ${number + 1}: unexpected text after value`);\n current[key] = value;\n }\n return root;\n}\n\n/** `[a.b]` -> [\"a\", \"b\"], quoted segments allowed. */\nfunction keyPath(header: string): string[] {\n return header.split(\".\").map((part) => unquoteKey(part.trim()));\n}\n\nfunction unquoteKey(key: string): string {\n if ((key.startsWith('\"') && key.endsWith('\"')) || (key.startsWith(\"'\") && key.endsWith(\"'\"))) return key.slice(1, -1);\n return key;\n}\n\nfunction tableAt(root: TomlTable, parts: string[]): TomlTable {\n let node: TomlTable = root;\n for (const part of parts) {\n const next = (node[part] ??= {});\n if (Array.isArray(next)) {\n // [a.b] after [[a]] addresses the latest a\n const last = next[next.length - 1];\n if (!last || typeof last !== \"object\" || Array.isArray(last)) throw new TomlError(`${part} is not a table`);\n node = last;\n } else if (typeof next !== \"object\") throw new TomlError(`${part} is not a table`);\n else node = next;\n }\n return node;\n}\n\n/** Arrays and inline tables may span lines: join until brackets balance outside strings. */\nfunction joinContinuations(text: string): string[] {\n const out: string[] = [];\n let pending = \"\";\n let depth = 0;\n for (const physical of text.split(/\\r?\\n/)) {\n const raw = stripComment(physical);\n const line = pending ? pending + \"\\n\" + raw : raw;\n depth = bracketDepth(line);\n if (depth > 0) {\n pending = line;\n continue;\n }\n pending = \"\";\n out.push(line);\n }\n if (pending) out.push(pending);\n return out;\n}\n\nfunction bracketDepth(line: string): number {\n let depth = 0;\n let quote: string | null = null;\n for (let i = 0; i < line.length; i++) {\n const c = line[i]!;\n if (quote) {\n if (c === \"\\\\\" && quote === '\"') i++;\n else if (c === quote) quote = null;\n continue;\n }\n if (c === '\"' || c === \"'\") quote = c;\n else if (c === \"[\" || c === \"{\") depth++;\n else if (c === \"]\" || c === \"}\") depth--;\n }\n return depth;\n}\n\nfunction stripComment(line: string): string {\n let quote: string | null = null;\n for (let i = 0; i < line.length; i++) {\n const c = line[i]!;\n if (quote) {\n if (c === \"\\\\\" && quote === '\"') i++;\n else if (c === quote) quote = null;\n continue;\n }\n if (c === '\"' || c === \"'\") quote = c;\n else if (c === \"#\") return line.slice(0, i);\n }\n return line;\n}\n\n/** Read one value at the start of `text`; returns it and what follows. */\nfunction readValue(text: string, line: number): [TomlValue, string] {\n const s = text.trimStart();\n if (s.startsWith('\"')) {\n let out = \"\";\n for (let i = 1; i < s.length; i++) {\n const c = s[i]!;\n if (c === \"\\\\\") {\n const e = s[++i];\n const map: Record<string, string> = { n: \"\\n\", t: \"\\t\", r: \"\\r\", '\"': '\"', \"\\\\\": \"\\\\\", b: \"\\b\", f: \"\\f\" };\n if (e === \"u\" || e === \"U\") {\n const width = e === \"u\" ? 4 : 8;\n out += String.fromCodePoint(parseInt(s.slice(i + 1, i + 1 + width), 16));\n i += width;\n } else if (e !== undefined && e in map) out += map[e];\n else throw new TomlError(`line ${line}: unsupported escape \\\\${e ?? \"\"}`);\n continue;\n }\n if (c === '\"') return [out, s.slice(i + 1)];\n out += c;\n }\n throw new TomlError(`line ${line}: unterminated string`);\n }\n if (s.startsWith(\"'\")) {\n const end = s.indexOf(\"'\", 1);\n if (end === -1) throw new TomlError(`line ${line}: unterminated string`);\n return [s.slice(1, end), s.slice(end + 1)];\n }\n if (s.startsWith(\"[\")) {\n const items: TomlValue[] = [];\n let rest = s.slice(1);\n for (;;) {\n rest = rest.replace(/^[\\s\\n]+/, \"\");\n if (rest.startsWith(\"]\")) return [items, rest.slice(1)];\n const [item, after] = readValue(rest, line);\n items.push(item);\n rest = after.replace(/^[\\s\\n]+/, \"\");\n if (rest.startsWith(\",\")) rest = rest.slice(1);\n else if (!rest.startsWith(\"]\")) throw new TomlError(`line ${line}: expected , or ] in array`);\n }\n }\n if (s.startsWith(\"{\")) {\n const table: TomlTable = {};\n let rest = s.slice(1);\n for (;;) {\n rest = rest.replace(/^[\\s\\n]+/, \"\");\n if (rest.startsWith(\"}\")) return [table, rest.slice(1)];\n const eq = rest.indexOf(\"=\");\n if (eq === -1) throw new TomlError(`line ${line}: expected key = value in inline table`);\n const key = unquoteKey(rest.slice(0, eq).trim());\n const [value, after] = readValue(rest.slice(eq + 1), line);\n table[key] = value;\n rest = after.replace(/^[\\s\\n]+/, \"\");\n if (rest.startsWith(\",\")) rest = rest.slice(1);\n else if (!rest.startsWith(\"}\")) throw new TomlError(`line ${line}: expected , or } in inline table`);\n }\n }\n const scalar = /^([^,\\]}\\s]+)/.exec(s);\n if (!scalar) throw new TomlError(`line ${line}: expected a value`);\n const token = scalar[1]!;\n const rest = s.slice(token.length);\n if (token === \"true\") return [true, rest];\n if (token === \"false\") return [false, rest];\n if (/^[+-]?\\d[\\d_]*$/.test(token)) return [Number(token.replace(/_/g, \"\")), rest];\n if (/^[+-]?(\\d[\\d_]*)?\\.?\\d[\\d_]*([eE][+-]?\\d+)?$/.test(token)) return [Number(token.replace(/_/g, \"\")), rest];\n throw new TomlError(`line ${line}: unsupported value ${token}`);\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport { api } from \"../config\";\nimport { arg, CliError, type CommandGroup } from \"../router\";\nimport type { AgentRow } from \"./agent\";\nimport { API_KEY_FLAG, credentials, HOST_FLAG, rawRequest } from \"./shared\";\n\n/** Items from a JSON (`[...]`, `{tasks: [...]}`, `{items: [...]}`) or JSONL file. */\nexport function readDatasetItems(file: string): unknown[] {\n const raw = fs.readFileSync(file, \"utf8\").trim();\n const looksJson = path.extname(file) === \".json\" || raw.startsWith(\"{\") || raw.startsWith(\"[\");\n if (looksJson) {\n let data: unknown;\n try {\n data = JSON.parse(raw);\n } catch (error) {\n // A .jsonl whose first line starts with \"{\" is JSONL, not one document\n // (the Python CLI trips here; the documented JSONL shape wins).\n if (path.extname(file) === \".json\") throw error;\n data = undefined;\n }\n if (data !== undefined) {\n if (Array.isArray(data)) return data;\n if (data && typeof data === \"object\") {\n const record = data as Record<string, unknown>;\n const listed = record.tasks ?? record.items;\n return Array.isArray(listed) ? listed : [];\n }\n return [];\n }\n }\n return raw\n .split(/\\r?\\n/)\n .filter((line) => line.trim())\n .map((line) => JSON.parse(line) as unknown);\n}\n\n/** `gateway dataset upload FILE --name ...` over /api/public/datasets/import. */\nexport function registerDatasetCommands(root: CommandGroup): void {\n const dataset = root.group(\"dataset\", \"Manage datasets.\");\n\n dataset.command({\n name: \"upload\",\n help: \"Upload a JSON or JSONL file as a dataset.\",\n positionals: [{ name: \"path\", help: \"Path to JSON or JSONL file\" }],\n flags: [\n { name: \"name\", help: \"Dataset name\" },\n { name: \"agent\", help: \"Validate items against this agent's task schema\" },\n { name: \"description\", help: \"Description\" },\n HOST_FLAG,\n API_KEY_FLAG,\n ],\n notes: [\n \"Supports:\",\n ' - JSON with {\"tasks\": [...]} or {\"items\": [...]} wrapper',\n \" - JSON bare array [item1, item2, ...]\",\n \" - JSONL (one JSON object per line)\",\n ].join(\"\\n\"),\n run: async (args, ctx) => {\n const file = args.positionals[0]!;\n const name = arg.str(args, \"name\");\n if (!name) throw new CliError(\"dataset upload needs --name\");\n if (!fs.existsSync(file)) throw new CliError(`Error: File not found: ${file}`, 1);\n const items = readDatasetItems(file);\n if (items.length === 0) throw new CliError(\"Error: No items found in file.\", 1);\n ctx.stdout(`Found ${items.length} items in ${path.basename(file)}`);\n\n const creds = credentials(args);\n const agent = arg.str(args, \"agent\");\n if (agent) {\n const listed = await rawRequest(creds, \"GET\", \"/api/public/agents\");\n if (!listed.ok) {\n ctx.stderr(`Warning: Could not fetch agents for validation: HTTP ${listed.status}`);\n } else {\n const agents = ((listed.json() as { agents?: AgentRow[] }).agents ?? []).filter((a) => a.name === agent);\n if (agents.length === 0) ctx.stderr(`Warning: Agent '${agent}' not found, skipping validation`);\n else if (!agents[0]!.taskInputSchema)\n ctx.stdout(`Agent '${agent}' has no taskInputSchema, skipping validation`);\n else\n // The Python CLI validates with the optional `jsonschema` package and\n // skips with this warning when it is absent; a dependency-free CLI\n // takes the same branch rather than half-implementing JSON Schema.\n ctx.stderr(\n \"Warning: JSON Schema validation is not available in the TypeScript CLI, skipping validation. \" +\n \"The platform validates items against the agent's schema on import.\",\n );\n }\n }\n\n ctx.stdout(`Uploading ${items.length} items as dataset '${name}'...`);\n const payload: Record<string, unknown> = { name, items: items.map((item) => ({ input: item })) };\n const description = arg.str(args, \"description\");\n if (description) payload.description = description;\n const data = await api<Record<string, unknown>>(creds, \"POST\", \"/api/public/datasets/import\", payload);\n ctx.stdout(\"Dataset created!\");\n ctx.stdout(` Dataset ID: ${data.datasetId}`);\n ctx.stdout(` Name: ${data.datasetName}`);\n ctx.stdout(` Items: ${data.itemCount}`);\n },\n });\n}\n","import * as fs from \"node:fs\";\n\nimport { api, printJson, type Credentials } from \"../config\";\nimport { arg, CliError, type CommandGroup } from \"../router\";\nimport { credentials, HOST_FLAG, query, sleep } from \"./shared\";\n\nconst ENV = \"/api/public/environments\";\nconst cid = (id: string) => `${ENV}/${encodeURIComponent(id)}`;\n\ntype EnvRun = {\n status: string;\n avgReward?: number | null;\n settled: boolean;\n rollouts?: { task?: string; reward?: unknown; verifiers?: unknown }[];\n};\n\n/** Accept a container id OR a slug everywhere an environment is named. */\nexport async function resolveEnvironmentId(creds: Credentials, ref: string): Promise<string> {\n const listing = await api<{ environments?: { id: string; slug?: string }[] }>(\n creds,\n \"GET\",\n `${ENV}${query({ slug: ref, limit: 5 })}`,\n );\n return listing.environments?.find((env) => env.slug === ref)?.id ?? ref;\n}\n\nasync function getRun(creds: Credentials, runId: string, waitSeconds: number): Promise<EnvRun> {\n const wait = Math.max(0, Math.min(waitSeconds, 50));\n return api<EnvRun>(creds, \"GET\", `${ENV}/runs/${encodeURIComponent(runId)}${wait ? `?waitSeconds=${wait}` : \"\"}`);\n}\n\n/** `gateway environment …` — the environments public API. */\nexport function registerEnvironmentCommands(root: CommandGroup): void {\n const environment = root.group(\n \"environment\",\n \"Environment hub — inspect environments, task sets, rollouts, and the Environment Agent.\",\n );\n const containerId = { name: \"container_id\", help: \"Environment (container) id.\" };\n\n environment.command({\n name: \"list\",\n help: \"List the project's environments (id, slug, latest version, task-set link).\",\n flags: [\n { name: \"slug\", help: \"Filter to one environment slug.\" },\n { name: \"limit\", short: \"n\", help: \"Max environments to list.\", default: \"50\" },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n printJson(\n ctx,\n await api(credentials(args), \"GET\", `${ENV}${query({ limit: arg.int(args, \"limit\") ?? 50, slug: arg.str(args, \"slug\") })}`),\n );\n },\n });\n\n environment.command({\n name: \"get\",\n help: \"Show one environment with its version history and rollout count.\",\n positionals: [containerId],\n flags: [HOST_FLAG],\n run: async (args, ctx) => printJson(ctx, await api(credentials(args), \"GET\", cid(args.positionals[0]!))),\n });\n\n environment.command({\n name: \"tasks\",\n help: \"Show the environment's linked task set and its tasks.\",\n positionals: [containerId],\n flags: [HOST_FLAG],\n run: async (args, ctx) => printJson(ctx, await api(credentials(args), \"GET\", `${cid(args.positionals[0]!)}/task-set`)),\n });\n\n environment.command({\n name: \"run\",\n help: \"Dispatch hosted rollouts — one runner job per model — and (by default) wait for the verdicts.\",\n positionals: [{ name: \"environment\", help: \"Environment slug or container id.\" }],\n flags: [\n {\n name: \"model\",\n short: \"m\",\n help: \"Model to run, repeatable, provider-prefixed: anthropic/..., openrouter/vendor/model, gateway/vendor/model, bedrock/...\",\n repeat: true,\n },\n { name: \"version-id\", help: \"Pin a READY version (default: newest).\" },\n { name: \"num-examples\", short: \"n\", help: \"Cap scenarios (default: all).\" },\n { name: \"rollouts\", short: \"k\", help: \"Rollouts per scenario (default 1).\" },\n { name: \"no-wait\", help: \"Return after dispatch instead of blocking until every run settles.\", boolean: true },\n { name: \"wait\", help: \"Block until every run settles and print verdicts (the default).\", boolean: true },\n { name: \"wait-timeout\", help: \"Seconds to wait before giving up (with --wait).\", default: \"1200\" },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const models = arg.list(args, \"model\");\n if (models.length === 0) throw new CliError(\"environment run needs at least one --model\");\n const creds = credentials(args);\n const id = await resolveEnvironmentId(creds, args.positionals[0]!);\n const versionId = arg.str(args, \"version-id\");\n const numExamples = arg.int(args, \"num-examples\");\n const rollouts = arg.int(args, \"rollouts\");\n const dispatch = await api<{ runs: { model: string; runId?: string; ok: boolean; error?: string }[] }>(\n creds,\n \"POST\",\n `${cid(id)}/run`,\n {\n models,\n ...(versionId ? { versionId } : {}),\n ...(numExamples !== undefined ? { numExamples } : {}),\n ...(rollouts !== undefined ? { rolloutsPerExample: rollouts } : {}),\n },\n );\n printJson(ctx, dispatch);\n const dispatched = dispatch.runs.filter((r) => r.ok && r.runId);\n for (const r of dispatch.runs) if (!r.ok) ctx.stderr(`# ${r.model}: ${r.error}`);\n if (arg.bool(args, \"no-wait\") || dispatched.length === 0) return dispatched.length ? 0 : 1;\n\n const waitTimeout = arg.int(args, \"wait-timeout\") ?? 1200;\n const deadline = Date.now() + waitTimeout * 1000;\n let failed = false;\n for (const r of dispatched) {\n for (;;) {\n const budget = Math.floor(Math.min(45, Math.max(0, (deadline - Date.now()) / 1000)));\n const verdict = await getRun(creds, r.runId!, budget);\n if (verdict.settled) {\n ctx.stdout(`${r.model}: ${verdict.status} avgReward=${verdict.avgReward ?? null}`);\n for (const rollout of verdict.rollouts ?? [])\n ctx.stdout(` ${rollout.task}: ${rollout.reward} ${JSON.stringify(rollout.verifiers ?? {})}`);\n failed = failed || ![\"COMPLETED\", \"SUCCEEDED\"].includes(verdict.status.toUpperCase());\n break;\n }\n if (Date.now() >= deadline) {\n ctx.stderr(`${r.model}: still running after ${waitTimeout}s (runId=${r.runId})`);\n failed = true;\n break;\n }\n if (budget === 0) await sleep(1000);\n }\n }\n return failed ? 1 : 0;\n },\n });\n\n environment.command({\n name: \"run-status\",\n help: \"One run's verdict: status, avgReward, settled, per-task rollouts.\",\n positionals: [{ name: \"run_id\", help: \"Run id from `environment run` / dispatch.\" }],\n flags: [{ name: \"wait\", short: \"w\", help: \"Block server-side up to N seconds (max 50) for it to settle.\", default: \"0\" }, HOST_FLAG],\n notes: \"`settled: false` after a wait means keep polling — it is not failure.\",\n run: async (args, ctx) => printJson(ctx, await getRun(credentials(args), args.positionals[0]!, arg.int(args, \"wait\") ?? 0)),\n });\n\n environment.command({\n name: \"link-task-set\",\n help: \"Create/fill a scenario set and attach it — idempotent: reuses the linked set, skips existing names.\",\n positionals: [{ name: \"environment\", help: \"Environment slug or container id.\" }],\n flags: [\n { name: \"tasks\", help: \"tasks.jsonl to fill the set from (rows: id, prompt, metadata, worlds).\" },\n { name: \"name\", help: \"Task-set name (default: '<slug> scenarios').\" },\n { name: \"description\", help: \"Task-set description.\" },\n { name: \"fresh\", help: \"Always create a new set instead of reusing the linked one.\", boolean: true },\n { name: \"detach\", help: \"Unlink the environment's task set and exit.\", boolean: true },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const creds = credentials(args);\n const ref = args.positionals[0]!;\n const id = await resolveEnvironmentId(creds, ref);\n if (arg.bool(args, \"detach\")) {\n printJson(ctx, await api(creds, \"POST\", `${cid(id)}/task-set`, { taskSetDatasetId: null }));\n return;\n }\n let datasetId: string | undefined;\n const existing = new Set<string>();\n if (!arg.bool(args, \"fresh\")) {\n try {\n const current = await api<{ datasetId: string; tasks?: { name: string }[] }>(creds, \"GET\", `${cid(id)}/task-set`);\n datasetId = current.datasetId;\n for (const t of current.tasks ?? []) existing.add(t.name);\n ctx.stderr(`# reusing linked task set ${datasetId}`);\n } catch {\n datasetId = undefined;\n }\n }\n if (!datasetId) {\n const setName = arg.str(args, \"name\") ?? `${ref} scenarios`;\n const description = arg.str(args, \"description\");\n const created = await api<{ datasetId: string }>(creds, \"POST\", \"/api/public/task-sets\", {\n name: setName,\n ...(description ? { description } : {}),\n });\n datasetId = created.datasetId;\n ctx.stderr(`# created task set ${datasetId} (${setName})`);\n }\n const tasks = arg.str(args, \"tasks\");\n if (tasks) {\n for (const line of fs.readFileSync(tasks, \"utf8\").split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n const row = JSON.parse(line) as Record<string, unknown>;\n const taskName = String(row.id ?? row.task ?? \"\");\n if (!taskName || existing.has(taskName)) continue;\n const metadata: Record<string, unknown> = { ...((row.metadata as Record<string, unknown>) ?? {}) };\n if (row.worlds !== undefined) metadata.worlds = row.worlds;\n await api(creds, \"POST\", `/api/public/task-sets/${encodeURIComponent(datasetId)}/tasks`, {\n name: taskName,\n prompt: String(row.prompt ?? \"\"),\n ...(Object.keys(metadata).length ? { metadata } : {}),\n });\n ctx.stderr(`# task ${taskName} created`);\n }\n }\n printJson(ctx, await api(creds, \"POST\", `${cid(id)}/task-set`, { taskSetDatasetId: datasetId }));\n },\n });\n\n environment.command({\n name: \"performance\",\n help: \"Show per-task performance across rollouts (nulls kept as their own category).\",\n positionals: [containerId],\n flags: [HOST_FLAG],\n run: async (args, ctx) => printJson(ctx, await api(credentials(args), \"GET\", `${cid(args.positionals[0]!)}/performance`)),\n });\n\n environment.command({\n name: \"rollouts\",\n help: \"List the environment's rollouts (evaluations), newest first.\",\n positionals: [containerId],\n flags: [HOST_FLAG],\n run: async (args, ctx) => printJson(ctx, await api(credentials(args), \"GET\", `${cid(args.positionals[0]!)}/rollouts`)),\n });\n\n environment.command({\n name: \"samples\",\n help: \"Show the scored samples of one rollout (reward/score/correct + sub-rewards).\",\n positionals: [containerId, { name: \"evaluation_id\", help: \"Rollout (evaluation) id.\" }],\n flags: [{ name: \"limit\", short: \"n\", help: \"Max samples to return.\", default: \"200\" }, HOST_FLAG],\n run: async (args, ctx) => {\n const [container, evaluation] = args.positionals;\n printJson(\n ctx,\n await api(\n credentials(args),\n \"GET\",\n `${cid(container!)}/rollouts/${encodeURIComponent(evaluation!)}/samples${query({ limit: arg.int(args, \"limit\") ?? 200 })}`,\n ),\n );\n },\n });\n\n environment.command({\n name: \"create-task\",\n help: \"Create a task in a task set (a kind='tasks' dataset item). Requires a secret key.\",\n positionals: [{ name: \"dataset_id\", help: \"Task set dataset id (kind='tasks').\" }],\n flags: [\n { name: \"name\", help: \"Task name.\" },\n { name: \"prompt\", help: \"Task prompt.\" },\n { name: \"expected-output\", help: \"Optional expected output.\" },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const name = arg.str(args, \"name\");\n const prompt = arg.str(args, \"prompt\");\n if (!name || !prompt) throw new CliError(\"environment create-task needs --name and --prompt\");\n const expected = arg.str(args, \"expected-output\");\n printJson(\n ctx,\n await api(credentials(args), \"POST\", `/api/public/task-sets/${encodeURIComponent(args.positionals[0]!)}/tasks`, {\n name,\n prompt,\n ...(expected !== undefined ? { expectedOutput: expected } : {}),\n }),\n );\n },\n });\n\n environment.command({\n name: \"agent-status\",\n help: \"Show the project's Environment Agent config and recent runs.\",\n flags: [HOST_FLAG],\n run: async (args, ctx) => printJson(ctx, await api(credentials(args), \"GET\", \"/api/public/environment-agent\")),\n });\n\n environment.command({\n name: \"agent-trigger\",\n help: \"Enqueue a manual Environment Agent run. Requires a saved config and a secret key.\",\n flags: [HOST_FLAG],\n run: async (args, ctx) => printJson(ctx, await api(credentials(args), \"POST\", \"/api/public/environment-agent/trigger\", {})),\n });\n}\n","import type { CommandGroup } from \"../router\";\nimport { pythonOnly } from \"./shared\";\n\n/**\n * Root-level Python commands that build or scaffold PYTHON agent projects\n * (Docker images, gateway_manifest/, Algorithm subclasses). They exist here\n * so `gateway deploy` says what to do instead of \"unknown command\".\n */\nexport function registerPythonOnlyCommands(root: CommandGroup): void {\n root.command({\n name: \"deploy\",\n help: \"Python-only: build, push and register a Python agent image (gatewaysdk[platform]).\",\n run: async (_args, ctx) =>\n pythonOnly(\n ctx,\n \"deploy\",\n \"it builds a Docker image from a Python agent project and registers its manifest.\",\n \"pip install 'gatewaysdk[platform]' && gateway deploy --tag <agent>:<version>\",\n ),\n });\n\n root.command({\n name: \"init\",\n help: \"Python-only: scaffold a Python agent project (Dockerfile + gateway_manifest/).\",\n run: async (_args, ctx) =>\n pythonOnly(\n ctx,\n \"init\",\n \"it scaffolds a Python agent project around the gateway-agent runner.\",\n \"pip install 'gatewaysdk[platform]' && gateway init --agent module:attr\",\n ),\n });\n\n const algorithm = root.group(\"algorithm\", \"Python-only: list and scaffold Python SDK algorithms.\");\n algorithm.command({\n name: \"list\",\n help: \"Python-only: list Algorithm subclasses importable in the Python SDK.\",\n run: async (_args, ctx) =>\n pythonOnly(ctx, \"algorithm list\", \"algorithms are Python classes.\", \"pip install gatewaysdk && gateway algorithm list\"),\n });\n algorithm.command({\n name: \"new\",\n help: \"Python-only: scaffold an Algorithm subclass.\",\n run: async (_args, ctx) =>\n pythonOnly(ctx, \"algorithm new\", \"algorithms are Python classes.\", \"pip install gatewaysdk && gateway algorithm new <name>\"),\n });\n}\n","import type { Credentials } from \"../config\";\nimport { arg, CliError, type CommandGroup } from \"../router\";\nimport { API_KEY_FLAG, appendStepSummary, credentials, HOST_FLAG, query, rawRequest, sleep } from \"./shared\";\n\n/**\n * `gateway release gate` — ask the release gate about a build, from CI.\n *\n * The verdict is computed on the server with the same rule the Releases page\n * enforces; this command only turns it into an exit code:\n * 0 pass · 1 blocked · 2 untested (no run recorded, or still going).\n */\n\nexport const GATE_PATH = \"/api/public/agent-builds/gate\";\nexport const EXIT_CODES: Record<string, number> = { pass: 0, blocked: 1, untested: 2 };\nexport const TERMINAL_STATES = new Set([\"COMPLETED\", \"FAILED\", \"ERROR\", \"TIMEOUT\", \"CANCELLED\"]);\n\nexport type GateResult = {\n build?: Record<string, unknown>;\n gate?: {\n verdict?: string;\n passRate?: number | null;\n threshold?: number | null;\n gradedRollouts?: number;\n minGradedRollouts?: number;\n reasons?: string[];\n };\n comparedTo?: Record<string, unknown> | null;\n evaluatedRuns?: Record<string, unknown>[];\n};\n\n/** Exactly one way of naming the build, as the endpoint's query string. */\nexport function buildQuery(opts: { build?: string; agent?: string; version?: string; commit?: string }): Record<string, string> {\n const ways = [opts.build !== undefined, opts.agent !== undefined || opts.version !== undefined, opts.commit !== undefined];\n if (ways.filter(Boolean).length !== 1)\n throw new CliError(\"name the build one way: --build, --agent + --version, or --commit\");\n if (opts.build !== undefined) return { buildId: opts.build };\n if (opts.commit !== undefined) return { commitSha: opts.commit };\n if (!opts.agent || !opts.version) throw new CliError(\"--agent and --version go together; supply both\");\n return { agentId: opts.agent, version: opts.version };\n}\n\nexport async function fetchGate(creds: Credentials, q: Record<string, string>): Promise<GateResult> {\n const res = await rawRequest(creds, \"GET\", `${GATE_PATH}${query(q)}`);\n if (res.status === 404) {\n let detail: string | undefined;\n try {\n const body = res.json() as Record<string, unknown>;\n detail = [body.message, body.error].find((v): v is string => typeof v === \"string\");\n } catch {\n detail = undefined;\n }\n throw new CliError(`Error: ${detail ?? \"no build matches that lookup\"}`, 2);\n }\n if (!res.ok) throw new CliError(`Failed (HTTP ${res.status}): ${res.text}`, 2);\n return res.json() as GateResult;\n}\n\nexport function runsSettled(result: GateResult): boolean {\n const runs = result.evaluatedRuns ?? [];\n if (runs.length === 0) return false;\n return runs.every((run) => TERMINAL_STATES.has(String(run.state ?? \"\").toUpperCase()));\n}\n\nexport function exitCodeFor(result: GateResult): number {\n const verdict = String(result.gate?.verdict ?? \"\").toLowerCase();\n if (!(verdict in EXIT_CODES)) throw new CliError(`unknown gate verdict '${verdict}'`, 2);\n return EXIT_CODES[verdict]!;\n}\n\nconst fmtRate = (rate: number | null | undefined) => (rate === null || rate === undefined ? \"n/a\" : rate.toFixed(2));\n\nexport function renderTable(result: GateResult): string {\n const build = result.build ?? {};\n const gate = result.gate ?? {};\n const rows: [string, string][] = [\n [\"verdict\", String(gate.verdict ?? \"?\").toUpperCase()],\n [\"agent\", String(build.agentId ?? \"?\")],\n [\"version\", String(build.version ?? \"-\")],\n [\"build\", String(build.id ?? \"?\")],\n [\"commit\", String(build.commitSha ?? \"-\")],\n [\"pass rate\", fmtRate(gate.passRate)],\n [\"graded\", String(gate.gradedRollouts ?? 0)],\n [\"rule\", `needs ${fmtRate(gate.threshold)} pass rate and at least ${gate.minGradedRollouts ?? \"?\"} graded`],\n ];\n if (result.comparedTo) rows.push([\"production\", String(result.comparedTo.stableVersion ?? result.comparedTo.stableBuildId)]);\n const width = Math.max(...rows.map(([k]) => k.length));\n const lines = rows.map(([k, v]) => `${k.padEnd(width)} ${v}`);\n const reasons = gate.reasons ?? [];\n if (reasons.length) lines.push(\"\", ...reasons.map((r) => `- ${r}`));\n const runs = result.evaluatedRuns ?? [];\n if (runs.length) {\n lines.push(\"\", \"runs (newest first):\");\n for (const run of runs)\n lines.push(\n ` ${run.runId} ${run.state} world=${run.world ?? \"-\"} model=${run.model ?? \"-\"} ` +\n `pass=${fmtRate(run.passRate as number | null | undefined)} graded=${run.graded ?? 0}`,\n );\n }\n return lines.join(\"\\n\");\n}\n\nfunction sortedJson(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(sortedJson);\n if (value && typeof value === \"object\")\n return Object.fromEntries(\n Object.keys(value as Record<string, unknown>)\n .sort()\n .map((k) => [k, sortedJson((value as Record<string, unknown>)[k])]),\n );\n return value;\n}\n\nexport function stepSummary(result: GateResult): string {\n const build = result.build ?? {};\n const gate = result.gate ?? {};\n const lines = [\n `### Release gate: ${build.agentId ?? \"?\"} ${build.version ?? \"\"}`.trimEnd(),\n \"\",\n \"| | |\",\n \"|---|---|\",\n `| verdict | ${String(gate.verdict ?? \"?\").toUpperCase()} |`,\n `| pass rate | ${fmtRate(gate.passRate)} |`,\n `| graded | ${gate.gradedRollouts ?? 0} |`,\n `| rule | ${fmtRate(gate.threshold)} / ${gate.minGradedRollouts ?? \"?\"} graded |`,\n ];\n for (const reason of gate.reasons ?? []) lines.push(`| reason | ${reason} |`);\n return lines.join(\"\\n\");\n}\n\nexport function registerReleaseCommands(root: CommandGroup): void {\n const release = root.group(\"release\", \"Release gate for agent builds — ask the platform whether a build may ship.\");\n\n release.command({\n name: \"gate\",\n help: \"The release gate's verdict on a build, as an exit code CI can branch on.\",\n flags: [\n { name: \"build\", help: \"Agent build id.\" },\n { name: \"agent\", help: \"Agent id (with --version).\" },\n { name: \"version\", help: \"Declared build version (with --agent).\" },\n { name: \"commit\", help: \"Commit sha the build was registered from (full, or a 7+ char prefix).\" },\n { name: \"wait\", help: \"Poll until every run attributed to the build is terminal.\", boolean: true },\n { name: \"timeout\", help: \"Seconds to wait for runs to settle (with --wait).\", default: \"1800\" },\n { name: \"interval\", help: \"Seconds between polls (with --wait).\", default: \"15\" },\n { name: \"json\", help: \"Print the endpoint's JSON instead of a table.\", boolean: true },\n HOST_FLAG,\n API_KEY_FLAG,\n ],\n notes: \"Exit codes:\\n 0 pass the gate is open on the build's latest run\\n 1 blocked the latest run failed the project's rule (reasons printed)\\n 2 untested no run recorded this build, or its latest run is still going\",\n run: async (args, ctx) => {\n const q = buildQuery({\n build: arg.str(args, \"build\"),\n agent: arg.str(args, \"agent\"),\n version: arg.str(args, \"version\"),\n commit: arg.str(args, \"commit\"),\n });\n const creds = credentials(args);\n const asJson = arg.bool(args, \"json\");\n let result: GateResult;\n if (arg.bool(args, \"wait\")) {\n const timeout = Number(arg.str(args, \"timeout\") ?? 1800);\n const interval = Number(arg.str(args, \"interval\") ?? 15);\n if (!(timeout >= 1) || !(interval >= 1)) throw new CliError(\"--timeout and --interval must be at least 1\");\n const deadline = Date.now() + timeout * 1000;\n for (;;) {\n result = await fetchGate(creds, q);\n if (!asJson) {\n const runs = result.evaluatedRuns ?? [];\n const pending = runs.filter((r) => !TERMINAL_STATES.has(String(r.state ?? \"\").toUpperCase()));\n if (runs.length === 0) ctx.stderr(\"waiting: no run has recorded this build yet\");\n else if (pending.length) ctx.stderr(`waiting: ${pending.length} of ${runs.length} run(s) still going`);\n }\n if (runsSettled(result)) break;\n if (Date.now() >= deadline) {\n ctx.stderr(`timed out after ${timeout}s; reporting the latest verdict`);\n break;\n }\n await sleep(interval * 1000);\n }\n } else {\n result = await fetchGate(creds, q);\n }\n ctx.stdout(asJson ? JSON.stringify(sortedJson(result), null, 2) : renderTable(result));\n appendStepSummary(stepSummary(result));\n return exitCodeFor(result);\n },\n });\n}\n","import { api } from \"../config\";\nimport { arg, CliError, type CommandGroup } from \"../router\";\nimport { API_KEY_FLAG, credentials, HOST_FLAG, query } from \"./shared\";\n\n/** `gateway run start|verify|list` over /api/public/runs*. */\nexport function registerRunCommands(root: CommandGroup): void {\n const run = root.group(\"run\", \"Manage platform optimization runs.\");\n\n run.command({\n name: \"start\",\n help: \"Start a platform optimization run.\",\n positionals: [{ name: \"algorithm\", help: \"Algorithm name (e.g., gepa)\" }],\n flags: [\n { name: \"agent\", help: \"Registered agent ID\" },\n { name: \"dataset\", help: \"Dataset ID\" },\n { name: \"name\", help: \"Run name\" },\n { name: \"config\", help: \"JSON config string\" },\n HOST_FLAG,\n API_KEY_FLAG,\n ],\n run: async (args, ctx) => {\n const agentId = arg.str(args, \"agent\");\n const datasetId = arg.str(args, \"dataset\");\n if (!agentId || !datasetId) throw new CliError(\"run start needs --agent and --dataset\");\n const payload: Record<string, unknown> = {\n algorithmName: args.positionals[0],\n agentId,\n datasetId,\n };\n const name = arg.str(args, \"name\");\n if (name) payload.name = name;\n const config = arg.str(args, \"config\");\n if (config) {\n try {\n payload.config = JSON.parse(config);\n } catch {\n throw new CliError(\"--config must be a JSON string\");\n }\n }\n const data = await api<Record<string, unknown>>(\n credentials(args),\n \"POST\",\n \"/api/public/runs/start\",\n payload,\n );\n ctx.stdout(\"Run started!\");\n ctx.stdout(` Run ID: ${data.runId}`);\n ctx.stdout(` Run #: ${data.runNumber}`);\n ctx.stdout(` Job ID: ${data.jobId}`);\n ctx.stdout(` Status: ${data.status}`);\n },\n });\n\n run.command({\n name: \"verify\",\n help: \"Verify an algorithm configuration.\",\n positionals: [{ name: \"algorithm\", help: \"Algorithm name\" }],\n flags: [\n { name: \"agent\", help: \"Agent ID\" },\n { name: \"dataset\", help: \"Dataset ID\" },\n HOST_FLAG,\n API_KEY_FLAG,\n ],\n run: async (args, ctx) => {\n const agentId = arg.str(args, \"agent\");\n if (!agentId) throw new CliError(\"run verify needs --agent\");\n const payload: Record<string, unknown> = { algorithmName: args.positionals[0], agentId };\n const datasetId = arg.str(args, \"dataset\");\n if (datasetId) payload.datasetId = datasetId;\n const data = await api<{ jobId?: string }>(credentials(args), \"POST\", \"/api/public/runs/verify\", payload);\n ctx.stdout(`Verify job queued: ${data.jobId}`);\n },\n });\n\n run.command({\n name: \"list\",\n help: \"List runs.\",\n flags: [\n { name: \"source\", help: \"Filter by source (platform/sdk)\" },\n { name: \"limit\", help: \"Max results\", default: \"20\" },\n HOST_FLAG,\n API_KEY_FLAG,\n ],\n run: async (args, ctx) => {\n const data = await api<{ runs?: Record<string, unknown>[] }>(\n credentials(args),\n \"GET\",\n `/api/public/runs${query({ limit: arg.int(args, \"limit\") ?? 20, source: arg.str(args, \"source\") })}`,\n );\n const runs = data.runs ?? [];\n if (runs.length === 0) {\n ctx.stdout(\"No runs found.\");\n return;\n }\n ctx.stdout(`${\"#\".padEnd(6)} ${\"Name\".padEnd(30)} ${\"State\".padEnd(12)} ${\"Source\".padEnd(10)}`);\n ctx.stdout(\"-\".repeat(60));\n for (const r of runs) {\n ctx.stdout(\n `${String(r.runNumber ?? \"\").padEnd(6)} ` +\n `${String(r.name ?? \"\").slice(0, 28).padEnd(30)} ` +\n `${String(r.state ?? \"\").padEnd(12)} ` +\n `${String(r.source ?? \"\").padEnd(10)}`,\n );\n }\n },\n });\n}\n","import { api } from \"../config\";\nimport { arg, CliError, type CommandGroup } from \"../router\";\nimport { API_KEY_FLAG, credentials, failed, HOST_FLAG, rawRequest } from \"./shared\";\n\ntype SecretRow = { name?: string; scope?: string; description?: string; displayValue?: string };\n\n/** `gateway secret set|list|delete` over /api/public/secrets. */\nexport function registerSecretCommands(root: CommandGroup): void {\n const secret = root.group(\"secret\", \"Manage project secrets (encrypted env vars for agent containers).\");\n\n secret.command({\n name: \"set\",\n help: \"Create or update a project secret.\",\n positionals: [{ name: \"name\", help: \"Secret name (UPPER_SNAKE_CASE, e.g. TAVILY_API_KEY)\" }],\n flags: [\n { name: \"value\", short: \"v\", help: \"Secret value. If omitted, it is read from stdin.\" },\n { name: \"description\", short: \"d\", help: \"Human-readable description\" },\n { name: \"scope\", help: \"Scope: agent, worker, or both\", default: \"agent\" },\n HOST_FLAG,\n API_KEY_FLAG,\n ],\n run: async (args, ctx) => {\n const name = args.positionals[0]!;\n const value = arg.str(args, \"value\") ?? (await ctx.stdin()).trim();\n if (!value) throw new CliError(\"empty value — nothing stored (pass --value or pipe stdin)\");\n const creds = credentials(args);\n const payload: Record<string, string> = { name, value, scope: arg.str(args, \"scope\") ?? \"agent\" };\n const description = arg.str(args, \"description\");\n if (description) payload.description = description;\n\n const created = await rawRequest(creds, \"POST\", \"/api/public/secrets\", payload);\n if (created.ok) {\n const data = created.json() as SecretRow;\n ctx.stdout(`Secret '${data.name ?? name}' saved (${data.displayValue ?? \"****\"})`);\n return;\n }\n if (created.status !== 409) throw failed(created.status, created.text);\n const updated = await rawRequest(\n creds,\n \"PUT\",\n `/api/public/secrets/${encodeURIComponent(name)}`,\n payload,\n );\n if (!updated.ok) throw failed(updated.status, updated.text);\n ctx.stdout(`Secret '${name}' updated.`);\n },\n });\n\n secret.command({\n name: \"list\",\n help: \"List project secrets (names and descriptions only, not values).\",\n flags: [HOST_FLAG, API_KEY_FLAG],\n run: async (args, ctx) => {\n const res = await api<{ secrets?: SecretRow[] }>(credentials(args), \"GET\", \"/api/public/secrets\");\n const secrets = res.secrets ?? [];\n if (secrets.length === 0) {\n ctx.stdout(\"No secrets configured. Run `gateway secret set <name>` to add one.\");\n return;\n }\n ctx.stdout(`${\"Name\".padEnd(30)} ${\"Scope\".padEnd(10)} Description`);\n ctx.stdout(\"-\".repeat(70));\n for (const s of secrets) {\n const desc = (s.description ?? \"\").slice(0, 28);\n ctx.stdout(`${(s.name ?? \"\").padEnd(30)} ${(s.scope ?? \"\").padEnd(10)} ${desc}`);\n }\n },\n });\n\n secret.command({\n name: \"delete\",\n help: \"Delete a project secret.\",\n positionals: [{ name: \"name\", help: \"Secret name to delete\" }],\n flags: [HOST_FLAG, API_KEY_FLAG],\n run: async (args, ctx) => {\n const name = args.positionals[0]!;\n await api(credentials(args), \"DELETE\", `/api/public/secrets/${encodeURIComponent(name)}`);\n ctx.stdout(`Secret '${name}' deleted.`);\n },\n });\n}\n","import * as fs from \"node:fs\";\n\nimport { api, printJson } from \"../config\";\nimport { arg, CliError, type CommandGroup } from \"../router\";\nimport {\n attachSession,\n openSession,\n surfaceKinds,\n uiEntryUrl,\n WorldSessionTimeout,\n type BrowserMode,\n type WorldSession,\n type WorldSurfaceKind,\n type WorldTaskRef,\n} from \"../../worlds/index\";\nimport { parseRows, rowsMode } from \"./rows\";\nimport { credentials, HOST_FLAG, sleep, worldsOptions } from \"./shared\";\nimport { readTaskSpec } from \"./task\";\n\nconst SEED_TIMEOUT_MS = 60_000;\nconst SEED_POLL_MS = 1_000;\nconst EXPORT_PAGE = 500;\nconst EXPORT_KEYS = [\n \"args\",\n \"completedAt\",\n \"error\",\n \"kind\",\n \"result\",\n \"seq\",\n \"tool\",\n] as const;\n\nasync function surfacesJson(session: WorldSession) {\n const s = await session.surfaces();\n return {\n sessionId: session.sessionId,\n surfaces: surfaceKinds(s),\n ...(s.api\n ? {\n api: {\n url: s.api.url,\n ...(s.api.token ? { token: s.api.token } : {}),\n },\n }\n : {}),\n ...(s.ui\n ? {\n ui: {\n url: s.ui.url,\n entry: uiEntryUrl(s.ui),\n apiPath: s.ui.apiPath ?? null,\n },\n }\n : {}),\n ...(s.browser\n ? { browser: { wsUrl: s.browser.wsUrl, viewport: s.browser.viewport } }\n : {}),\n };\n}\n\nconst sessionRoute = (id: string) =>\n `/api/public/world-sessions/${encodeURIComponent(id)}`;\n\n/** Exactly one of `--task` (a bundled scenario), `--task-id` (a stored task,\n * optionally `--task-version`) and `--task-file` (a JSON task spec:\n * `{instruction, seed?, grader?, metadata?, name?}`). */\nfunction taskFromFlags(flags: {\n task?: string;\n taskId?: string;\n taskVersion?: number;\n taskFile?: string;\n}): WorldTaskRef {\n const given = [flags.task, flags.taskId, flags.taskFile].filter(Boolean);\n if (given.length > 1)\n throw new CliError(\n \"worlds session open takes one of --task, --task-id or --task-file\",\n );\n if (flags.taskVersion !== undefined && !flags.taskId)\n throw new CliError(\"--task-version needs --task-id\");\n if (flags.task) return flags.task;\n if (flags.taskId)\n return flags.taskVersion === undefined\n ? { id: flags.taskId }\n : { id: flags.taskId, version: flags.taskVersion };\n if (!flags.taskFile)\n throw new CliError(\n \"worlds session open needs --task, --task-id or --task-file\",\n );\n return readTaskSpec(flags.taskFile, \"--task-file\");\n}\n\n/** `gateway worlds session open|status|state|reset|browse|close|seed|export`. */\nexport function registerSessionCommands(root: CommandGroup): void {\n const session = root\n .group(\"worlds\", \"Build, seed, serve and run worlds.\")\n .group(\"session\", \"Live world sessions with api/ui/browser surfaces.\");\n\n session.command({\n name: \"open\",\n help: \"Open a live session and print where it answers.\",\n positionals: [{ name: \"slug\", help: \"World slug (optionally slug@ref).\" }],\n flags: [\n {\n name: \"task\",\n short: \"t\",\n help: \"Bundled task / scenario to open the session on.\",\n },\n {\n name: \"task-id\",\n help: \"Stored task (see `worlds task`) to open the session on instead of --task (host engine worlds).\",\n },\n {\n name: \"task-version\",\n help: \"With --task-id: open that version of the task instead of the current one.\",\n },\n {\n name: \"task-file\",\n help: \"JSON file with an inline task spec {instruction, seed?, grader?, metadata?, name?} instead of --task (host engine worlds).\",\n },\n {\n name: \"surface\",\n short: \"s\",\n help: \"Surface to ask for besides tools: api, ui, browser (repeatable or comma-separated).\",\n repeat: true,\n },\n { name: \"version-id\", help: \"Pin an exact world version.\" },\n {\n name: \"no-wait\",\n help: \"Return as soon as the platform accepts the session.\",\n boolean: true,\n },\n HOST_FLAG,\n ],\n notes:\n \"Prints {sessionId, ready, surfaces, api.url, ui.entry, browser.wsUrl} — the descriptor WorldSession.surfaces\\n\" +\n \"parses. A World Host session's api also carries `token`: send it as `Authorization: Bearer <token>`\\n\" +\n \"(header only, never in the URL) on every request to api.url. The platform refuses (HTTP 400) rather than serving\\n\" +\n \"fewer surfaces than asked.\\n\" +\n \"--task-file supplies the task with the open instead of naming a bundled one: `instruction` (what the agent is\\n\" +\n \"told), `seed` ({mode?, rows}) applied after the snapshot, `grader` ({kind: assertions, checks} or\\n\" +\n \"{kind: python, source}), `metadata` echoed on the session. --task-id opens a copy of a stored task's current\\n\" +\n \"(or --task-version) spec. The output's `task` block carries source (bundled|stored|inline)/name/hash/id/version.\",\n run: async (args, ctx) => {\n const task = taskFromFlags({\n task: arg.str(args, \"task\"),\n taskId: arg.str(args, \"task-id\"),\n taskVersion: arg.int(args, \"task-version\"),\n taskFile: arg.str(args, \"task-file\"),\n });\n const surfaces = arg\n .list(args, \"surface\")\n .flatMap((s) => s.split(\",\"))\n .map((s) => s.trim())\n .filter(Boolean) as WorldSurfaceKind[];\n const live = await openSession(args.positionals[0]!, {\n task,\n versionId: arg.str(args, \"version-id\"),\n surfaces,\n options: worldsOptions(credentials(args)),\n });\n const descriptor = async () => ({\n ...(await surfacesJson(live)),\n task: live.taskInfo,\n });\n if (!arg.bool(args, \"no-wait\")) {\n try {\n await live.ready();\n } catch (error) {\n if (!(error instanceof WorldSessionTimeout)) throw error;\n // Still coming (a cold pod takes longer): print where it will answer\n // so the caller polls instead of losing the id.\n printJson(ctx, { ...(await descriptor()), ready: false });\n ctx.stderr(\n `${error.message} Poll \\`gateway worlds session status ${live.sessionId}\\` until ready.`,\n );\n return 1;\n }\n }\n printJson(ctx, { ...(await descriptor()), ready: live.isReady });\n },\n });\n\n session.command({\n name: \"state\",\n help: \"Dump every entity's rows as the live world holds them now.\",\n positionals: [{ name: \"session_id\", help: \"Session id.\" }],\n flags: [HOST_FLAG],\n run: async (args, ctx) => {\n const live = await attachSession(\n args.positionals[0]!,\n worldsOptions(credentials(args)),\n );\n printJson(ctx, await live.state());\n },\n });\n\n session.command({\n name: \"reset\",\n help: \"Put the world back to its opening state (base data + the task's seed); the call log stays.\",\n positionals: [{ name: \"session_id\", help: \"Session id.\" }],\n flags: [HOST_FLAG],\n run: async (args, ctx) => {\n const live = await attachSession(\n args.positionals[0]!,\n worldsOptions(credentials(args)),\n );\n await live.reset();\n printJson(ctx, { sessionId: live.sessionId, reset: true });\n },\n });\n\n session.command({\n name: \"grade\",\n help: \"Run the session's task grader against the world's current state and print {reward, rewards, raw}.\",\n positionals: [{ name: \"session_id\", help: \"Session id.\" }],\n flags: [\n {\n name: \"timeout\",\n help: \"Seconds to wait for the grade; defaults to the grader's budget (a rubric judge gets 15 min).\",\n },\n HOST_FLAG,\n ],\n notes:\n \"Assertions and python graders answer from the engine in seconds. A rubric grader is judged\\n\" +\n \"by the platform's worker; the command waits for that verdict.\",\n run: async (args, ctx) => {\n const timeout = arg.int(args, \"timeout\");\n if (timeout !== undefined && timeout <= 0)\n throw new CliError(\"--timeout must be a positive number of seconds\");\n const timeoutMs = timeout === undefined ? undefined : timeout * 1000;\n const live = await attachSession(\n args.positionals[0]!,\n worldsOptions(credentials(args)),\n );\n const grade = await live.grade({ timeoutMs });\n printJson(ctx, { sessionId: live.sessionId, ...grade });\n },\n });\n\n session.command({\n name: \"status\",\n help: \"Print a session's state, tools and surfaces.\",\n positionals: [{ name: \"session_id\", help: \"Session id.\" }],\n flags: [HOST_FLAG],\n run: async (args, ctx) => {\n const live = await attachSession(\n args.positionals[0]!,\n worldsOptions(credentials(args)),\n );\n const state = await live.status();\n printJson(ctx, { ...state, ...(await surfacesJson(live)) });\n },\n });\n\n session.command({\n name: \"browse\",\n help: \"Open the session's UI in its browser surface and print what the agent would read.\",\n positionals: [{ name: \"session_id\", help: \"Session id.\" }],\n flags: [\n {\n name: \"mode\",\n help: \"hosted | local | auto (prefers hosted).\",\n default: \"auto\",\n },\n { name: \"path\", help: \"UI path to open instead of the declared entry.\" },\n { name: \"screenshot\", help: \"Write a PNG of the page here.\" },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const live = await attachSession(\n args.positionals[0]!,\n worldsOptions(credentials(args)),\n );\n const browser = await live.browser({\n mode: (arg.str(args, \"mode\") ?? \"auto\") as BrowserMode,\n });\n try {\n const url = await browser.goto(arg.str(args, \"path\"));\n const shot = arg.str(args, \"screenshot\");\n if (shot) fs.writeFileSync(shot, await browser.screenshot());\n printJson(ctx, {\n url,\n title: await browser.title(),\n text: await browser.text(),\n });\n } finally {\n await browser.close();\n }\n },\n });\n\n session.command({\n name: \"close\",\n help: \"End a session.\",\n positionals: [{ name: \"session_id\", help: \"Session id.\" }],\n flags: [\n {\n name: \"keep-warm\",\n help: \"Hand the container back to the warm pool.\",\n boolean: true,\n },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const live = await attachSession(\n args.positionals[0]!,\n worldsOptions(credentials(args)),\n );\n printJson(\n ctx,\n await live.close({ keepWarm: arg.bool(args, \"keep-warm\") }),\n );\n },\n });\n\n session.command({\n name: \"seed\",\n help: \"Put rows into a LIVE session's world and wait for the engine's answer.\",\n positionals: [\n { name: \"session_id\", help: \"Session id.\" },\n {\n name: \"rows\",\n help: \"Rows files: {entity: [rows]} JSON, {entity,row} JSONL, or bare rows.\",\n variadic: true,\n },\n ],\n flags: [\n { name: \"entity\", help: \"The entity bare-row files hold.\" },\n {\n name: \"mode\",\n help: \"append (upsert by primary key) | replace (named entities).\",\n default: \"append\",\n },\n HOST_FLAG,\n ],\n notes:\n 'Posts {kind: \"seed\", args: {mode, rows}}; the engine applies the rows through the world\\'s contract,\\n' +\n \"so a refused row leaves the session unchanged and the error names it.\",\n run: async (args, ctx) => {\n const [sessionId, ...files] = args.positionals;\n if (files.length === 0)\n throw new CliError(\"worlds session seed needs at least one rows file\");\n const mode = rowsMode(arg.str(args, \"mode\"));\n const rows = parseRows(files, arg.str(args, \"entity\"));\n const creds = credentials(args);\n const { callId } = await api<{ callId: string }>(\n creds,\n \"POST\",\n `${sessionRoute(sessionId!)}/calls`,\n {\n kind: \"seed\",\n args: { mode, rows },\n },\n );\n const deadline = Date.now() + SEED_TIMEOUT_MS;\n for (;;) {\n const call = await api<{\n done?: boolean;\n state: string;\n result: unknown;\n error: string | null;\n }>(\n creds,\n \"GET\",\n `${sessionRoute(sessionId!)}/calls/${encodeURIComponent(callId)}`,\n );\n const settled =\n call.done || call.state === \"completed\" || call.state === \"failed\";\n if (settled) {\n if (call.error || call.state === \"failed\")\n throw new CliError(call.error ?? \"seed failed\", 1);\n printJson(ctx, { sessionId, mode, result: call.result });\n return;\n }\n if (Date.now() > deadline)\n throw new CliError(\n `Seed call ${callId} still ${call.state} after ${SEED_TIMEOUT_MS / 1000}s.`,\n 1,\n );\n await sleep(SEED_POLL_MS);\n }\n },\n });\n\n session.command({\n name: \"export\",\n help: \"The session's call log as JSONL, one {seq, kind, tool, args, result, error, completedAt} per line, oldest first.\",\n positionals: [{ name: \"session_id\", help: \"Session id.\" }],\n flags: [\n { name: \"out\", help: \"Write the JSONL here instead of stdout.\" },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const sessionId = args.positionals[0]!;\n const creds = credentials(args);\n const calls: Record<string, unknown>[] = [];\n let cursor: string | undefined;\n do {\n const params = new URLSearchParams({ limit: String(EXPORT_PAGE) });\n if (cursor) params.set(\"cursor\", cursor);\n const page = await api<{\n calls: Record<string, unknown>[];\n nextCursor?: string | null;\n }>(\n creds,\n \"GET\",\n `${sessionRoute(sessionId)}/calls?${params.toString()}`,\n );\n calls.push(...page.calls);\n cursor = page.nextCursor ?? undefined;\n } while (cursor);\n const lines = calls.map((call) =>\n JSON.stringify(\n Object.fromEntries(\n EXPORT_KEYS.map((key) => [key, call[key] ?? null]),\n ),\n ),\n );\n const text = lines.join(\"\\n\") + (lines.length ? \"\\n\" : \"\");\n const out = arg.str(args, \"out\");\n if (!out) {\n if (text) process.stdout.write(text);\n return;\n }\n fs.writeFileSync(out, text);\n ctx.stdout(`wrote ${lines.length} calls to ${out}`);\n },\n });\n}\n","import * as fs from \"node:fs\";\n\nimport { printJson } from \"../config\";\nimport { arg, CliError, type CommandGroup, type FlagSpec } from \"../router\";\nimport {\n attachSession,\n createTask,\n deleteTask,\n getTask,\n listTasks,\n updateTask,\n validateTask,\n type WorldTaskSpec,\n} from \"../../worlds/index\";\nimport { credentials, HOST_FLAG, worldsOptions } from \"./shared\";\n\nconst WORLD_FLAG: FlagSpec = {\n name: \"world\",\n short: \"w\",\n help: \"Pin the task to this world (slug); validated against its contract.\",\n};\nconst NO_WORLD_FLAG: FlagSpec = {\n name: \"no-world\",\n help: \"Unpin the task so it can open on any world.\",\n boolean: true,\n};\nconst MESSAGE_FLAG: FlagSpec = {\n name: \"message\",\n short: \"m\",\n help: \"Note kept with this version.\",\n};\n\n/** A task spec from a JSON file: `{instruction, seed?, grader?, metadata?, name?}`. */\nexport function readTaskSpec(file: string, flag = \"--spec\"): WorldTaskSpec {\n let parsed: unknown;\n try {\n parsed = JSON.parse(fs.readFileSync(file, \"utf8\"));\n } catch (error) {\n throw new CliError(\n `${flag} ${file}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n if (\n !parsed ||\n typeof parsed !== \"object\" ||\n Array.isArray(parsed) ||\n typeof (parsed as { instruction?: unknown }).instruction !== \"string\"\n )\n throw new CliError(\n `${flag} ${file}: a task spec is a JSON object with an \"instruction\" string`,\n );\n return parsed as WorldTaskSpec;\n}\n\n/** `--world <slug>` / `--no-world` → the API's `world` (slug, null, or unset). */\nfunction worldFromFlags(\n world: string | undefined,\n noWorld: boolean,\n): string | null | undefined {\n if (world && noWorld)\n throw new CliError(\"--world and --no-world exclude each other\");\n if (noWorld) return null;\n return world;\n}\n\n/** `--metadata key=value` pairs → the list filter. */\nfunction metadataFromFlags(pairs: string[]): Record<string, string> {\n const out: Record<string, string> = {};\n for (const pair of pairs) {\n const eq = pair.indexOf(\"=\");\n if (eq <= 0)\n throw new CliError(\n `--metadata takes key=value, got ${JSON.stringify(pair)}`,\n );\n out[pair.slice(0, eq)] = pair.slice(eq + 1);\n }\n return out;\n}\n\n/** `gateway worlds task create|update|list|show|validate|delete` and\n * `gateway worlds session task save`. */\nexport function registerTaskCommands(root: CommandGroup): void {\n const worlds = root.group(\"worlds\", \"Build, seed, serve and run worlds.\");\n const task = worlds.group(\n \"task\",\n \"Stored tasks: instruction + seed + grader kept by the project, outside any bundle.\",\n );\n\n task.command({\n name: \"create\",\n help: \"Store a task from a JSON spec file; prints the task (version 1).\",\n positionals: [\n {\n name: \"spec\",\n help: \"JSON file: {instruction, seed?, grader?, metadata?, name?}.\",\n },\n ],\n flags: [\n {\n name: \"name\",\n short: \"n\",\n help: \"Task name (default: the spec's `name`).\",\n },\n WORLD_FLAG,\n MESSAGE_FLAG,\n HOST_FLAG,\n ],\n notes:\n \"The same spec `worlds session open --task-file` takes, kept as a project resource so sessions open on it by id\\n\" +\n \"(`session open --task-id <id>`) and grades attribute to the task and its version. --world pins it to one world\\n\" +\n \"and checks the seed and grader entities against that world's contract.\",\n run: async (args, ctx) => {\n const spec = readTaskSpec(args.positionals[0]!, \"spec\");\n const created = await createTask(\n {\n spec,\n name: arg.str(args, \"name\"),\n world: arg.str(args, \"world\"),\n message: arg.str(args, \"message\"),\n },\n worldsOptions(credentials(args)),\n );\n printJson(ctx, created);\n },\n });\n\n task.command({\n name: \"update\",\n help: \"Change a task: a new spec becomes the next version; --name/--world change in place.\",\n positionals: [{ name: \"task_id\", help: \"Task id.\" }],\n flags: [\n { name: \"spec\", help: \"JSON spec file that becomes the next version.\" },\n { name: \"name\", short: \"n\", help: \"Rename the task.\" },\n WORLD_FLAG,\n NO_WORLD_FLAG,\n MESSAGE_FLAG,\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const specFile = arg.str(args, \"spec\");\n const world = worldFromFlags(\n arg.str(args, \"world\"),\n arg.bool(args, \"no-world\"),\n );\n const name = arg.str(args, \"name\");\n if (specFile === undefined && world === undefined && name === undefined)\n throw new CliError(\n \"worlds task update needs --spec, --name, --world or --no-world\",\n );\n const updated = await updateTask(\n args.positionals[0]!,\n {\n spec: specFile ? readTaskSpec(specFile) : undefined,\n name,\n world,\n message: arg.str(args, \"message\"),\n },\n worldsOptions(credentials(args)),\n );\n printJson(ctx, updated);\n },\n });\n\n task.command({\n name: \"list\",\n help: \"The project's stored tasks, most recently changed first.\",\n flags: [\n {\n name: \"world\",\n short: \"w\",\n help: \"Only tasks pinned to this world (slug).\",\n },\n {\n name: \"metadata\",\n help: \"Only tasks whose spec metadata has key=value (repeatable).\",\n repeat: true,\n },\n { name: \"page\", help: \"Page number (1-based).\", default: \"1\" },\n { name: \"limit\", help: \"Tasks per page.\", default: \"50\" },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const page = await listTasks(\n {\n world: arg.str(args, \"world\"),\n metadata: metadataFromFlags(arg.list(args, \"metadata\")),\n page: arg.int(args, \"page\"),\n limit: arg.int(args, \"limit\"),\n },\n worldsOptions(credentials(args)),\n );\n printJson(ctx, page);\n },\n });\n\n task.command({\n name: \"show\",\n help: \"One task with its spec and version history.\",\n positionals: [{ name: \"task_id\", help: \"Task id.\" }],\n flags: [\n {\n name: \"version\",\n help: \"Show this version's spec instead of the current one.\",\n },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const detail = await getTask(\n args.positionals[0]!,\n { version: arg.int(args, \"version\") },\n worldsOptions(credentials(args)),\n );\n printJson(ctx, detail);\n },\n });\n\n task.command({\n name: \"validate\",\n help: \"Check a task's seed and grader entities against a world version without opening a session.\",\n positionals: [{ name: \"task_id\", help: \"Task id.\" }],\n flags: [\n { name: \"version\", help: \"Check this task version (default: current).\" },\n {\n name: \"world\",\n short: \"w\",\n help: \"World (slug) to check against; default the task's pin.\",\n },\n { name: \"version-id\", help: \"Exact world version to check against.\" },\n HOST_FLAG,\n ],\n notes:\n \"Exit 1 with the problems listed when a seed or check names an entity the world does not have.\",\n run: async (args, ctx) => {\n const result = await validateTask(\n args.positionals[0]!,\n {\n version: arg.int(args, \"version\"),\n slug: arg.str(args, \"world\"),\n versionId: arg.str(args, \"version-id\"),\n },\n worldsOptions(credentials(args)),\n );\n printJson(ctx, result);\n if (!result.ok) return 1;\n },\n });\n\n task.command({\n name: \"delete\",\n help: \"Remove a task and every version; open sessions keep their copy.\",\n positionals: [{ name: \"task_id\", help: \"Task id.\" }],\n flags: [HOST_FLAG],\n run: async (args, ctx) => {\n printJson(\n ctx,\n await deleteTask(\n args.positionals[0]!,\n worldsOptions(credentials(args)),\n ),\n );\n },\n });\n\n worlds\n .group(\"session\", \"Live world sessions with api/ui/browser surfaces.\")\n .group(\"task\", \"The task a live session runs.\")\n .command({\n name: \"save\",\n help: \"Promote a session's inline task into a stored task (version 1).\",\n positionals: [{ name: \"session_id\", help: \"Session id.\" }],\n flags: [\n {\n name: \"name\",\n short: \"n\",\n help: \"Task name (default: the spec's `name`).\",\n },\n WORLD_FLAG,\n NO_WORLD_FLAG,\n MESSAGE_FLAG,\n HOST_FLAG,\n ],\n notes:\n \"Default pin is the session's world. A session on a bundled task has nothing to save; one already on a stored\\n\" +\n \"task is refused (409).\",\n run: async (args, ctx) => {\n const live = await attachSession(\n args.positionals[0]!,\n worldsOptions(credentials(args)),\n );\n const saved = await live.saveTask({\n name: arg.str(args, \"name\"),\n world: worldFromFlags(\n arg.str(args, \"world\"),\n arg.bool(args, \"no-world\"),\n ),\n message: arg.str(args, \"message\"),\n });\n printJson(ctx, saved);\n },\n });\n}\n","import * as fs from \"node:fs\";\n\nimport { api } from \"../config\";\nimport { arg, CliError, type CommandGroup } from \"../router\";\nimport { API_KEY_FLAG, credentials, HOST_FLAG } from \"./shared\";\n\n/**\n * `gateway traces import <file>`: push OTLP/JSON traces exported by any tool\n * (an OpenTelemetry collector `file` exporter, Braintrust, Arize/Phoenix,\n * Galileo, LangSmith, a hand-written fixture) to the project's OTLP endpoint.\n * The platform normalizes vendor conventions on ingest; this command only\n * batches, optionally stamps resource attributes, and posts.\n */\n\nexport const OTLP_TRACES_ROUTE = \"/api/public/otel/v1/traces\";\n\ntype KeyValue = { key: string; value: Record<string, unknown> };\ntype ResourceSpans = { resource?: { attributes?: KeyValue[] } } & Record<string, unknown>;\nexport type ExportTraceServiceRequest = { resourceSpans: ResourceSpans[] };\n\nconst isObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === \"object\" && v !== null && !Array.isArray(v);\n\n/**\n * Accepts one OTLP request (`{resourceSpans: [...]}`), a bare `resourceSpans`\n * array, a JSON array of requests, or JSONL with one request per line.\n */\nexport function parseOtlpDocument(text: string, fileName = \"input\"): ExportTraceServiceRequest[] {\n const trimmed = text.trim();\n if (!trimmed) throw new CliError(`${fileName} is empty`);\n let values: unknown[];\n try {\n values = [JSON.parse(trimmed)];\n } catch {\n values = trimmed.split(\"\\n\").flatMap((line, i) => {\n if (!line.trim()) return [];\n try {\n return [JSON.parse(line)];\n } catch (err) {\n throw new CliError(`${fileName}:${i + 1} is neither JSON nor a JSONL line: ${(err as Error).message}`);\n }\n });\n }\n const out: ExportTraceServiceRequest[] = [];\n const push = (value: unknown, where: string) => {\n if (Array.isArray(value)) {\n if (value.every((item) => isObject(item) && Array.isArray(item.scopeSpans)))\n return void out.push({ resourceSpans: value as ResourceSpans[] });\n value.forEach((item, i) => push(item, `${where}[${i}]`));\n return;\n }\n if (!isObject(value) || !Array.isArray(value.resourceSpans))\n throw new CliError(`${where} is not an OTLP/JSON trace export: expected {\"resourceSpans\": [...]}`);\n out.push({ resourceSpans: value.resourceSpans as ResourceSpans[] });\n };\n values.forEach((value, i) => push(value, values.length === 1 ? fileName : `${fileName} line ${i + 1}`));\n return out.filter((req) => req.resourceSpans.length);\n}\n\n/** Set (or overwrite) string attributes on every resource of a request. */\nexport function stampResourceAttributes(\n request: ExportTraceServiceRequest,\n attributes: Record<string, string>,\n): ExportTraceServiceRequest {\n const entries = Object.entries(attributes);\n if (!entries.length) return request;\n return {\n resourceSpans: request.resourceSpans.map((rs) => {\n const existing = (rs.resource?.attributes ?? []).filter((kv) => !(kv.key in attributes));\n const added: KeyValue[] = entries.map(([key, value]) => ({ key, value: { stringValue: value } }));\n return { ...rs, resource: { ...(rs.resource ?? {}), attributes: [...existing, ...added] } };\n }),\n };\n}\n\nexport function countSpans(request: ExportTraceServiceRequest): number {\n let n = 0;\n for (const rs of request.resourceSpans) {\n const scopeSpans = Array.isArray(rs.scopeSpans) ? rs.scopeSpans : [];\n for (const ss of scopeSpans) if (isObject(ss) && Array.isArray(ss.spans)) n += ss.spans.length;\n }\n return n;\n}\n\nexport function registerTracesCommands(root: CommandGroup): void {\n const traces = root.group(\"traces\", \"Bring traces in from any OpenTelemetry-compatible source.\");\n\n traces.command({\n name: \"import\",\n help: \"POST OTLP/JSON trace exports (a file, several, or `-` for stdin) to this project's OTLP endpoint.\",\n positionals: [{ name: \"file\", help: \"OTLP/JSON or JSONL export; `-` reads stdin\", variadic: true }],\n flags: [\n { name: \"source\", help: \"Label the exporter (braintrust, galileo, arize, …); stored as gateway.otel.source.\" },\n { name: \"world\", help: \"Link every trace to a world slug (gateway.world).\" },\n { name: \"world-version\", help: \"World version label (gateway.world.version).\" },\n { name: \"task\", help: \"Task name (gateway.task).\" },\n { name: \"session\", help: \"Force one session id on every span (gateway.session.id).\" },\n { name: \"environment\", help: \"Tracing environment (gateway.environment).\" },\n { name: \"attr\", help: \"Extra resource attribute key=value; repeatable.\", repeat: true },\n { name: \"dry-run\", help: \"Parse and count; send nothing.\", boolean: true },\n HOST_FLAG,\n API_KEY_FLAG,\n ],\n notes:\n \"Spans keep their own session/user/model/input/output attributes: Braintrust, OpenInference (Arize,\\n\" +\n \"Phoenix, Galileo), OpenTelemetry GenAI, Langfuse and LangSmith conventions are normalized on ingest.\\n\" +\n \"Flags only add resource attributes, so a span's own value always wins.\",\n run: async (args, ctx) => {\n const files = args.positionals.length ? args.positionals : [\"-\"];\n const stamp: Record<string, string> = {};\n const put = (key: string, flag: string) => {\n const value = arg.str(args, flag);\n if (value !== undefined) stamp[key] = value;\n };\n put(\"gateway.otel.source\", \"source\");\n put(\"gateway.world\", \"world\");\n put(\"gateway.world.version\", \"world-version\");\n put(\"gateway.task\", \"task\");\n put(\"gateway.session.id\", \"session\");\n put(\"gateway.environment\", \"environment\");\n for (const item of arg.list(args, \"attr\")) {\n const eq = item.indexOf(\"=\");\n if (eq <= 0) throw new CliError(`--attr looks like key=value, got ${JSON.stringify(item)}`);\n stamp[item.slice(0, eq).trim()] = item.slice(eq + 1);\n }\n\n const requests: ExportTraceServiceRequest[] = [];\n for (const file of files) {\n const text = file === \"-\" ? await ctx.stdin() : readFile(file);\n for (const req of parseOtlpDocument(text, file === \"-\" ? \"stdin\" : file))\n requests.push(stampResourceAttributes(req, stamp));\n }\n const spans = requests.reduce((n, req) => n + countSpans(req), 0);\n if (!spans) throw new CliError(\"No spans found in the input\");\n\n const dryRun = arg.bool(args, \"dry-run\");\n if (!dryRun) {\n const creds = credentials(args);\n for (const req of requests) await api(creds, \"POST\", OTLP_TRACES_ROUTE, req);\n }\n ctx.stdout(\n JSON.stringify(\n {\n status: dryRun ? \"dry-run\" : \"accepted\",\n batches: requests.length,\n spans,\n resourceAttributes: stamp,\n endpoint: OTLP_TRACES_ROUTE,\n },\n null,\n 2,\n ),\n );\n },\n });\n}\n\nfunction readFile(file: string): string {\n if (!fs.existsSync(file)) throw new CliError(`${file} does not exist`, 1);\n return fs.readFileSync(file, \"utf8\");\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport { api, printJson, type Credentials } from \"../config\";\nimport { arg, CliError, type CommandContext, type CommandGroup, type Parsed } from \"../router\";\nimport { walk } from \"./connector\";\nimport { parseRows } from \"./rows\";\nimport { credentials, HOST_FLAG } from \"./shared\";\n\nexport const WORLDS = \"/api/public/worlds\";\n\ntype FileInput = { path: string; content: string; encoding?: \"base64\" };\n\n/** Every file under a directory, text as UTF-8 and anything else base64, in the route's shape. */\nexport function collectFiles(directory: string): FileInput[] {\n if (!fs.existsSync(directory) || !fs.statSync(directory).isDirectory())\n throw new CliError(`${directory}: not a directory`, 1);\n return walk(directory).map((relative) => {\n const bytes = fs.readFileSync(path.join(directory, relative));\n const text = bytes.toString(\"utf8\");\n return Buffer.from(text, \"utf8\").equals(bytes) && !text.includes(\"\\uFFFD\")\n ? { path: relative, content: text }\n : {\n path: relative,\n content: bytes.toString(\"base64\"),\n encoding: \"base64\" as const,\n };\n });\n}\n\n/** A world path names a template slug, `workspace:<slug>`, or a directory holding a tree. */\nfunction source(from: string): Record<string, unknown> {\n if (fs.existsSync(from) && fs.statSync(from).isDirectory()) return { files: collectFiles(from) };\n if (from.includes(\"/\") || from.includes(\".\"))\n throw new CliError(`${from}: neither a directory nor a template slug (a shipped template, or workspace:<slug>)`, 1);\n return { connector: from };\n}\n\nexport type CreateWorldRequest = {\n slug: string;\n name?: string;\n description?: string;\n from: Record<string, unknown>;\n overlay?: { files: FileInput[] };\n data?: { rows: Record<string, Record<string, unknown>[]> };\n message?: string;\n};\n\nexport type CreatedWorld = {\n slug: string;\n name: string;\n containerId: string;\n kind: string;\n version: { id: string; contentHash: string; semanticVersion: string | null };\n source: {\n connector: string;\n packageVersion: string;\n domainVersion: string;\n } | null;\n entityCounts: Record<string, number>;\n tools: string[];\n url: string;\n};\n\nfunction requestFrom(args: Parsed, slug: string): CreateWorldRequest {\n const from = arg.str(args, \"from\");\n if (!from) throw new CliError(\"worlds create needs --from <template|workspace:slug|directory>\");\n const overlay = arg.str(args, \"overlay\");\n const rows = arg.list(args, \"rows\");\n const body: CreateWorldRequest = { slug, from: source(from) };\n const name = arg.str(args, \"name\");\n if (name) body.name = name;\n const description = arg.str(args, \"description\");\n if (description) body.description = description;\n if (overlay) body.overlay = { files: collectFiles(overlay) };\n if (rows.length) body.data = { rows: parseRows(rows, arg.str(args, \"entity\")) };\n const message = arg.str(args, \"message\");\n if (message) body.message = message;\n return body;\n}\n\nfunction summary(world: CreatedWorld): string {\n const counts = Object.entries(world.entityCounts)\n .filter(([, n]) => n > 0)\n .map(([entity, n]) => `${entity}=${n}`)\n .join(\" \");\n const from = world.source ? ` from ${world.source.connector}@${world.source.packageVersion}` : \"\";\n return `created ${world.slug} (${world.kind})${from} ${world.version.contentHash.slice(0, 12)}${counts ? ` [${counts}]` : \"\"} ${world.url}`;\n}\n\n/** One line of `--batch`: the request body as the route takes it, or `{slug, from}` shorthand with a string `from`. */\nfunction batchLine(line: string, index: number): CreateWorldRequest {\n let parsed: unknown;\n try {\n parsed = JSON.parse(line);\n } catch {\n throw new CliError(`batch line ${index + 1}: not JSON`, 1);\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed))\n throw new CliError(`batch line ${index + 1}: expected an object`, 1);\n const record = parsed as Record<string, unknown>;\n if (typeof record.slug !== \"string\") throw new CliError(`batch line ${index + 1}: needs a \"slug\"`, 1);\n if (typeof record.from === \"string\") return { ...record, from: source(record.from) } as CreateWorldRequest;\n if (typeof record.from !== \"object\" || record.from === null)\n throw new CliError(`batch line ${index + 1}: needs \"from\" (a template slug, or {connector} / {files})`, 1);\n return record as CreateWorldRequest;\n}\n\nasync function createOne(creds: Credentials, body: CreateWorldRequest): Promise<CreatedWorld> {\n return api<CreatedWorld>(creds, \"POST\", WORLDS, body, { timeoutMs: 600_000 });\n}\n\nasync function runBatch(file: string, args: Parsed, ctx: CommandContext): Promise<number> {\n const text = file === \"-\" ? fs.readFileSync(0, \"utf8\") : fs.readFileSync(file, \"utf8\");\n const requests = text\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter(Boolean)\n .map(batchLine);\n if (requests.length === 0) throw new CliError(\"batch file holds no worlds\", 1);\n const creds = credentials(args);\n let failed = 0;\n for (const body of requests) {\n try {\n const world = await createOne(creds, body);\n ctx.stdout(\n JSON.stringify({\n slug: world.slug,\n status: \"created\",\n containerId: world.containerId,\n version: world.version,\n url: world.url,\n }),\n );\n } catch (error) {\n failed += 1;\n const message = error instanceof Error ? error.message : String(error);\n ctx.stdout(JSON.stringify({ slug: body.slug, status: \"failed\", error: message }));\n }\n }\n ctx.stderr(`# ${requests.length - failed}/${requests.length} created`);\n return failed === 0 ? 0 : 2;\n}\n\n/** `gateway worlds create`: a world on the platform from a template, a workspace connector or a tree (twin: MCP `create_world`). */\nexport function registerWorldCommands(root: CommandGroup): void {\n const worlds = root.group(\"worlds\", \"Build, seed, serve and run worlds.\");\n\n worlds.command({\n name: \"create\",\n help: \"Create a world in the project from a connector template, a workspace connector or a directory.\",\n positionals: [\n {\n name: \"slug\",\n help: \"URL-safe slug, unique in the project (omit with --batch).\",\n optional: true,\n },\n ],\n flags: [\n {\n name: \"from\",\n help: \"Shipped template (slack, github, …), workspace:<slug>, or a world directory.\",\n },\n {\n name: \"overlay\",\n help: \"Directory of files laid over the source before the tree is compiled.\",\n },\n {\n name: \"rows\",\n help: \"Rows file seeded into the first version ({entity: [rows]} JSON or JSONL); repeatable.\",\n repeat: true,\n },\n { name: \"entity\", help: \"The entity bare-row files hold.\" },\n { name: \"name\", help: \"Display name (default: the slug).\" },\n { name: \"description\", help: \"One-line description.\" },\n {\n name: \"message\",\n short: \"m\",\n help: \"Change reason recorded on the first version.\",\n },\n {\n name: \"batch\",\n help: \"JSONL file (or -) of {slug, from, overlay?, data?, name?} lines; one result line each.\",\n },\n { name: \"json\", help: \"Print the created world as JSON.\", boolean: true },\n HOST_FLAG,\n ],\n notes:\n \"The same request as POST /api/public/worlds and the MCP tool create_world. A shipped template or\\n\" +\n \"workspace connector is pinned on the world; an overlay or a directory is compiled by the schema\\n\" +\n \"runtime (lock/runtime/db regenerated) and refused, with the path, when the contract does not hold.\\n\" +\n \"The first version is READY and attributed to the key; the world is not owned by a person.\\n\" +\n \"Exit 0 created, 2 when any batch line failed, 1 on error.\",\n run: async (args, ctx) => {\n const batch = arg.str(args, \"batch\");\n if (batch) {\n if (args.positionals.length) throw new CliError(\"--batch takes the slugs from the file; drop the positional\");\n return runBatch(batch, args, ctx);\n }\n const slug = args.positionals[0];\n if (!slug) throw new CliError(\"worlds create needs a slug (or --batch)\");\n const body = requestFrom(args, slug);\n const world = await createOne(credentials(args), body);\n if (arg.bool(args, \"json\")) printJson(ctx, world);\n else ctx.stdout(summary(world));\n return 0;\n },\n });\n}\n","import type { CommandGroup } from \"../router\";\nimport { registerAgentCommands } from \"./agent\";\nimport { registerAuthCommands } from \"./auth\";\nimport { registerBenchCommands } from \"./bench\";\nimport { registerConnectorCommands } from \"./connector\";\nimport { registerDataCommands } from \"./data\";\nimport { registerDatasetCommands } from \"./dataset\";\nimport { registerEnvironmentCommands } from \"./environment\";\nimport { registerPythonOnlyCommands } from \"./pythonOnly\";\nimport { registerReleaseCommands } from \"./release\";\nimport { registerRunCommands } from \"./run\";\nimport { registerSecretCommands } from \"./secret\";\nimport { registerSessionCommands } from \"./session\";\nimport { registerSkillCommands } from \"./skill\";\nimport { registerTaskCommands } from \"./task\";\nimport { registerTracesCommands } from \"./traces\";\nimport { registerWorldCommands } from \"./worlds\";\n\n/** Platform-backed groups: auth, secret, agent, run, dataset, bench, worlds\n * session/task/connector/skill/data, environment, release — one file per group,\n * every command's name and flags mirroring the Python CLI. */\nexport function registerPlatformCommands(root: CommandGroup): void {\n registerAuthCommands(root);\n registerSecretCommands(root);\n registerAgentCommands(root);\n registerRunCommands(root);\n registerDatasetCommands(root);\n registerBenchCommands(root);\n registerWorldCommands(root);\n registerSessionCommands(root);\n registerTaskCommands(root);\n registerConnectorCommands(root);\n registerSkillCommands(root);\n registerDataCommands(root);\n registerEnvironmentCommands(root);\n registerReleaseCommands(root);\n registerTracesCommands(root);\n registerPythonOnlyCommands(root);\n}\n\nexport { parseRows, rowsMode, type Rows, type RowsMode } from \"./rows\";\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport { CliError, arg, type CommandGroup } from \"../router\";\nimport { api, resolveCredentials, type Credentials } from \"../config\";\nimport { credentialsForRuntime, localRuntime } from \"./local\";\nimport {\n readWorldFiles,\n runtime,\n sortedJson,\n withoutFiles,\n writeWorldFiles,\n type WorldFile,\n} from \"./client\";\n\n/**\n * `gateway worlds schema …` — the gateway-world/1 contract commands. Every one\n * of them used to run the Python compiler locally; they now send the\n * directory to the platform's runtime and print what the Python CLI printed.\n */\n\nconst HOST_FLAG = {\n name: \"host\",\n help: \"Platform host (default: GATEWAY_HOST or the saved login).\",\n env: \"GATEWAY_HOST\",\n};\n\ntype TemplateSummary = {\n slug: string;\n name?: string;\n description?: string;\n entities?: string[];\n tools?: string[];\n};\n\nasync function listTemplates(creds: Credentials | null): Promise<TemplateSummary[]> {\n // The local runtime answers directly; the platform's memoized route is\n // only for a machine that has no Python.\n if (!creds || localRuntime()) {\n const res = await runtime<{ templates?: TemplateSummary[] | string[] }>(creds, {\n command: \"templates\",\n });\n return normalizeTemplates(res.templates);\n }\n try {\n const res = await api<{ templates?: TemplateSummary[] } | TemplateSummary[]>(\n creds,\n \"GET\",\n \"/api/public/worlds/templates\",\n );\n const templates = Array.isArray(res) ? res : res.templates;\n if (Array.isArray(templates)) return templates;\n } catch {\n // Fall through to the runtime: older deployments have only the bridge.\n }\n return normalizeTemplates(\n (await runtime<{ templates?: TemplateSummary[] | string[] }>(creds, { command: \"templates\" })).templates,\n );\n}\n\nfunction normalizeTemplates(raw: TemplateSummary[] | string[] | undefined): TemplateSummary[] {\n const res = { templates: raw };\n return (res.templates ?? []).map((t) => (typeof t === \"string\" ? { slug: t } : t));\n}\n\nfunction assertEmptyTarget(dir: string): void {\n if (!fs.existsSync(dir)) return;\n if (!fs.statSync(dir).isDirectory()) throw new CliError(`${dir} exists and is not a directory`);\n if (fs.readdirSync(dir).length > 0) throw new CliError(`${dir} must be a new or empty directory`);\n}\n\n/** A workspace connector's template, from the platform's copy: the Python CLI\n * pulls `/api/public/context/connectors/<slug>` and hands the files to the\n * compiler; here the compiler is the bridge's `init-template-files`. */\nasync function pullWorkspaceTemplate(\n creds: Credentials | null,\n slug: string,\n): Promise<{ files: WorldFile[]; commit: string | null }> {\n if (!creds)\n throw new CliError(\"workspace:<slug> pulls the connector from the platform: run `gateway auth login` first\");\n const pulled = await api<{\n commit?: { commitHash?: string; id?: string };\n files?: Record<string, { type?: string; content?: unknown }>;\n }>(creds, \"GET\", `/api/public/context/connectors/${encodeURIComponent(slug)}`);\n const files: WorldFile[] = [];\n for (const [rel, entry] of Object.entries(pulled.files ?? {})) {\n if (!entry || entry.type !== \"file\" || typeof entry.content !== \"string\")\n throw new CliError(`${slug}: ${rel} is not a file entry; a connector template holds files only`, 1);\n files.push({ path: rel, content: Buffer.from(entry.content, \"utf8\").toString(\"base64\") });\n }\n if (!files.length) throw new CliError(`${slug}: the workspace connector has no files`, 1);\n return { files, commit: pulled.commit?.commitHash ?? pulled.commit?.id ?? null };\n}\n\ntype ContractReport = Record<string, unknown> & { files?: WorldFile[] };\n\n/** The `describe` summary as text, the way the Python `describe` renders a\n * bundle; `--json` prints the document itself. */\nexport function renderDescription(description: Record<string, unknown>): string {\n const lines: string[] = [];\n const domain = description.domainId ?? \"(no $id)\";\n const version = description.packageVersion ? ` v${description.packageVersion}` : \"\";\n lines.push(`${String(domain)}${version}`);\n const entities = Array.isArray(description.entities) ? description.entities : [];\n if (entities.length) {\n lines.push(\"\", \"Entities:\");\n for (const entity of entities as Record<string, unknown>[]) {\n const pk = Array.isArray(entity.primaryKey) ? entity.primaryKey.join(\", \") : \"\";\n lines.push(` ${String(entity.name)}${pk ? ` (pk: ${pk})` : \"\"}`);\n for (const field of (Array.isArray(entity.fields) ? entity.fields : []) as Record<string, unknown>[]) {\n lines.push(\n ` ${String(field.name)}: ${String(field.type ?? \"any\")}${field.required ? \"\" : \"?\"}`,\n );\n }\n }\n }\n const tools = Array.isArray(description.tools) ? description.tools : [];\n if (tools.length) {\n lines.push(\"\", \"Tools:\");\n for (const tool of tools) {\n if (typeof tool === \"string\") lines.push(` ${tool}`);\n else {\n const t = tool as Record<string, unknown>;\n lines.push(` ${String(t.name)}${t.description ? `: ${String(t.description)}` : \"\"}`);\n }\n }\n }\n const connection = description.connection as Record<string, unknown> | null | undefined;\n if (connection) {\n lines.push(\"\", `Connection: ${String(connection.slug)} ${String(connection.baseUrl)} auth=${String(connection.auth)}`);\n for (const op of (Array.isArray(connection.operations) ? connection.operations : []) as Record<string, unknown>[]) {\n const target = op.entity ? ` -> ${String(op.entity)}` : \"\";\n lines.push(` ${String(op.name)}: ${String(op.method)} ${String(op.path)}${target}`);\n }\n }\n return lines.join(\"\\n\");\n}\n\nexport function registerSchemaCommands(schema: CommandGroup): void {\n schema.command({\n name: \"templates\",\n help: \"List the installed connector templates; `custom` is always offered last.\",\n flags: [\n { name: \"json\", help: \"Print each template's name, description, entities and tools.\", boolean: true },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const creds = credentialsForRuntime(arg.str(args, \"host\"));\n const templates = await listTemplates(creds);\n if (arg.bool(args, \"json\")) {\n ctx.stdout(JSON.stringify(templates, null, 2));\n return;\n }\n const slugs = templates.map((t) => t.slug).filter((s) => s !== \"custom\");\n if (templates.some((t) => t.slug === \"custom\")) slugs.push(\"custom\");\n for (const slug of slugs) ctx.stdout(slug);\n },\n });\n\n schema.command({\n name: \"init\",\n help: \"Initialize a schema world from a connector template, then compile it.\",\n positionals: [{ name: \"path\", help: \"New or empty directory for the world\" }],\n flags: [\n {\n name: \"connector\",\n help:\n \"Connector template slug; `custom` is the blank contract, `workspace:<slug>` a workspace \" +\n \"connector pulled from the platform. `gateway worlds schema templates` lists what is installed.\",\n default: \"custom\",\n },\n { name: \"name\", help: \"Environment name and package id\" },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const dir = path.resolve(args.positionals[0]!);\n const connector = arg.str(args, \"connector\") ?? \"custom\";\n const name = arg.str(args, \"name\");\n assertEmptyTarget(dir);\n const creds = credentialsForRuntime(arg.str(args, \"host\"));\n let report: ContractReport;\n let commit: string | null = null;\n if (connector.startsWith(\"workspace:\")) {\n const slug = connector.slice(\"workspace:\".length);\n if (!slug) throw new CliError(\"workspace:<slug> needs the connector's slug\");\n const pulled = await pullWorkspaceTemplate(creds, slug);\n commit = pulled.commit;\n report = await runtime<ContractReport>(creds, {\n command: \"init-template-files\",\n connector: slug,\n files: pulled.files,\n ...(name ? { name } : {}),\n });\n } else {\n report = await runtime<ContractReport>(creds, {\n command: \"init-template\",\n connector,\n ...(name ? { name } : {}),\n });\n }\n const files = report.files ?? [];\n if (!files.length) throw new CliError(\"The runtime compiled the world but returned no files\", 1);\n writeWorldFiles(dir, files);\n const out: Record<string, unknown> = { status: \"ok\", domain: report.domain };\n if (connector.startsWith(\"workspace:\"))\n out.connector = { slug: connector.slice(\"workspace:\".length), commit };\n ctx.stdout(sortedJson(out, 0));\n },\n });\n\n for (const [command, help] of [\n [\"compile\", \"Compile the world's contract on the platform and write back what the compiler produced.\"],\n [\"check\", \"Check the world's contract on the platform; writes nothing.\"],\n ] as const) {\n schema.command({\n name: command,\n help,\n positionals: [{ name: \"path\", help: \"World directory\" }],\n flags: [HOST_FLAG],\n run: async (args, ctx) => {\n const dir = path.resolve(args.positionals[0]!);\n const creds = credentialsForRuntime(arg.str(args, \"host\"));\n const report = await runtime<ContractReport>(creds, {\n command: command === \"compile\" ? \"compile\" : \"validate\",\n files: readWorldFiles(dir),\n });\n if (command === \"compile\" && report.files?.length) writeWorldFiles(dir, report.files);\n ctx.stdout(sortedJson(withoutFiles(report), 0));\n },\n });\n }\n\n schema.command({\n name: \"describe\",\n help: \"Describe the world's contract: entities, tools and the vendor connection it answers to.\",\n positionals: [{ name: \"path\", help: \"World directory\" }],\n flags: [{ name: \"json\", help: \"Print the description document as JSON.\", boolean: true }, HOST_FLAG],\n run: async (args, ctx) => {\n const dir = path.resolve(args.positionals[0]!);\n const creds = credentialsForRuntime(arg.str(args, \"host\"));\n const res = await runtime<{ description?: Record<string, unknown> }>(creds, {\n command: \"describe\",\n files: readWorldFiles(dir),\n });\n const description = res.description ?? {};\n if (arg.bool(args, \"json\")) ctx.stdout(JSON.stringify(description, null, 2));\n else ctx.stdout(renderDescription(description));\n },\n });\n\n schema.command({\n name: \"api-bundle\",\n help: \"Write the api-kind bundle that hosts this world's API (built by the platform runtime).\",\n positionals: [\n { name: \"path\", help: \"World directory holding connector.toml\" },\n { name: \"out\", help: \"Empty (or absent) directory for the api-kind bundle\" },\n ],\n flags: [HOST_FLAG],\n run: async (args, ctx) => {\n const [dir, out] = args.positionals as [string, string];\n const creds = credentialsForRuntime(arg.str(args, \"host\"));\n const res = await runtime<{ files?: { path: string; content: string }[] }>(creds, {\n command: \"api-bundle\",\n files: readWorldFiles(dir),\n });\n writeWorldFiles(out, res.files ?? [], { clean: false });\n ctx.stdout(`api bundle: ${out}`);\n },\n });\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport { CliError, arg, type CommandContext, type CommandGroup } from \"../router\";\nimport { api, resolveCredentials, type Credentials } from \"../config\";\nimport { credentialsForRuntime, localModule, localRuntime } from \"./local\";\nimport { readWorldFiles, runtime, sortedJson, writeWorldFiles, type WorldFile } from \"./client\";\n\n/**\n * `gateway worlds connector validate|capture|conform|ingest` — the vendor\n * connection of a schema world. validate/conform/ingest go through the\n * platform runtime; capture is `--remote` only, because a local capture runs\n * the vendor call from this machine with the Python runtime.\n */\n\nconst HOST_FLAG = {\n name: \"host\",\n help: \"Platform host (default: GATEWAY_HOST or the saved login).\",\n env: \"GATEWAY_HOST\",\n};\n\nexport const CAPTURES = \"captures\";\nexport const MANIFEST = \"manifest.json\";\n\nfunction pairs(values: string[], what: string): Record<string, string> {\n const out: Record<string, string> = {};\n for (const item of values) {\n const eq = item.indexOf(\"=\");\n if (eq === -1) throw new CliError(`${what} must look like name=value, got ${JSON.stringify(item)}`);\n out[item.slice(0, eq).trim()] = item.slice(eq + 1);\n }\n return out;\n}\n\nfunction requireConnectorToml(dir: string): string {\n const file = path.join(dir, \"connector.toml\");\n if (!fs.existsSync(file)) throw new CliError(`${dir} holds no connector.toml`, 1);\n return fs.readFileSync(file, \"utf8\");\n}\n\ntype Connection = {\n slug: string;\n baseUrl: string;\n auth: string;\n operations: { name: string; method: string; path: string; entity?: string | null }[];\n};\n\nexport function renderConnection(spec: Connection): string[] {\n const lines = [`${spec.slug} ${spec.baseUrl} auth=${spec.auth}`];\n for (const op of spec.operations) {\n const target = op.entity ? ` -> ${op.entity}` : \"\";\n lines.push(` ${op.name}: ${op.method} ${op.path}${target}`);\n }\n return lines;\n}\n\n// ── remote capture (mirror of the Python `_remote_capture`) ─────────────────\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\nasync function resolveEnvironmentId(creds: Credentials, ref: string): Promise<string> {\n const listing = await api<{ environments?: { id: string; slug: string }[] }>(\n creds,\n \"GET\",\n `/api/public/environments?slug=${encodeURIComponent(ref)}&limit=5`,\n );\n for (const env of listing.environments ?? []) if (env.slug === ref) return env.id;\n return ref;\n}\n\ntype CaptureView = {\n stage: string;\n error?: string | null;\n worldSlug?: string;\n files?: { path: string }[];\n manifest?: unknown[];\n};\n\nexport async function remoteCapture(\n creds: Credentials,\n world: string,\n opts: {\n op: string;\n args: Record<string, string>;\n params: Record<string, string>;\n maxPages?: number;\n environment?: string;\n timeoutSeconds: number;\n pollMs?: number;\n },\n ctx: CommandContext,\n): Promise<string[]> {\n const specText = requireConnectorToml(world);\n const containerId = await resolveEnvironmentId(creds, opts.environment ?? path.basename(path.resolve(world)));\n const base = `/api/public/environments/${encodeURIComponent(containerId)}`;\n const started = await api<{ requestId: string }>(creds, \"POST\", `${base}/connector-captures`, {\n connectorToml: specText,\n op: opts.op,\n ...(Object.keys(opts.args).length ? { args: opts.args } : {}),\n ...(Object.keys(opts.params).length ? { params: opts.params } : {}),\n ...(opts.maxPages !== undefined ? { maxPages: opts.maxPages } : {}),\n });\n const requestId = String(started.requestId);\n ctx.stderr(`# remote capture ${requestId} on ${containerId}`);\n const deadline = Date.now() + opts.timeoutSeconds * 1000;\n let view: CaptureView;\n for (;;) {\n view = await api<CaptureView>(creds, \"GET\", `${base}/connector-captures/${encodeURIComponent(requestId)}`);\n if (view.stage === \"complete\") break;\n if (view.stage === \"failed\" || view.stage === \"cancelled\")\n throw new CliError(`Remote capture ${view.stage}: ${view.error || \"no detail\"}`, 1);\n if (Date.now() >= deadline)\n throw new CliError(\n `Remote capture still ${view.stage} after ${opts.timeoutSeconds}s; poll it with the request id ${requestId}`,\n 1,\n );\n await sleep(opts.pollMs ?? 5_000);\n }\n const slugPrefix = `worlds/${view.worldSlug}/`;\n const written: string[] = [];\n for (const file of view.files ?? []) {\n const drivePath = String(file.path);\n const relative = drivePath.startsWith(slugPrefix) ? drivePath.slice(slugPrefix.length) : drivePath;\n if (!relative.startsWith(`${CAPTURES}/`) || relative.split(\"/\").includes(\"..\"))\n throw new CliError(`Refusing a capture outside ${CAPTURES}/: ${drivePath}`, 1);\n const info = await api<{ url: string }>(\n creds,\n \"GET\",\n `${base}/files/download?path=${encodeURIComponent(drivePath)}`,\n );\n const res = await fetch(info.url);\n if (!res.ok) throw new CliError(`download ${drivePath} -> ${res.status}`, 1);\n const destination = path.join(world, relative);\n fs.mkdirSync(path.dirname(destination), { recursive: true });\n fs.writeFileSync(destination, Buffer.from(await res.arrayBuffer()));\n written.push(relative);\n }\n const manifestPath = path.join(world, CAPTURES, MANIFEST);\n const existing: unknown[] = fs.existsSync(manifestPath)\n ? (JSON.parse(fs.readFileSync(manifestPath, \"utf8\")) as unknown[])\n : [];\n const known = new Set(\n existing.map((e) => (e && typeof e === \"object\" ? (e as { file?: unknown }).file : undefined)),\n );\n for (const entry of view.manifest ?? []) {\n if (!entry || typeof entry !== \"object\") continue;\n const file = (entry as { file?: unknown }).file;\n if (known.has(file)) continue;\n existing.push(entry);\n known.add(file);\n }\n fs.mkdirSync(path.dirname(manifestPath), { recursive: true });\n fs.writeFileSync(manifestPath, sortedJson(existing, 1) + \"\\n\");\n return written;\n}\n\n// ── conform ──────────────────────────────────────────────────────────────────\n\ntype ConformOutcome = {\n operation: string;\n method: string;\n path: string;\n documented: boolean;\n ok?: boolean;\n status?: number | null;\n expected?: string[];\n problems?: string[];\n schema?: string;\n};\n\ntype ConformReport = {\n /** `Report.to_json()` names the list `operations`; older payloads said `outcomes`. */\n operations?: ConformOutcome[];\n outcomes?: ConformOutcome[];\n summary?: Record<string, unknown>;\n [key: string]: unknown;\n};\n\n/** Python's `Outcome.ok`: documented, answered a documented status, and no\n * schema violation. `ok` on the wire wins when a payload carries it. */\nexport function outcomeOk(outcome: ConformOutcome): boolean {\n if (typeof outcome.ok === \"boolean\") return outcome.ok;\n return (\n outcome.documented &&\n outcome.status != null &&\n (outcome.expected ?? []).includes(String(outcome.status)) &&\n (outcome.schema === \"ok\" || outcome.schema === \"no-schema\")\n );\n}\n\nexport function renderConformOutcome(outcome: ConformOutcome): string {\n const mark = !outcome.documented ? \" ? \" : outcomeOk(outcome) ? \" ok \" : \" FAIL\";\n let detail = outcome.documented ? \"\" : \"not in the document\";\n const expected = outcome.expected ?? [];\n const problems = outcome.problems ?? [];\n if (outcome.documented && outcome.status != null && !expected.includes(String(outcome.status)))\n detail = `status ${outcome.status}, vendor documents ${expected.join(\", \")}`;\n else if (problems.length)\n detail = problems[0]! + (problems.length > 1 ? ` (+${problems.length - 1})` : \"\");\n return `${mark} ${outcome.method.padEnd(6)} ${outcome.path.padEnd(60)} ${outcome.operation} ${detail}`;\n}\n\n// ── the commands ─────────────────────────────────────────────────────────────\n\nexport function registerConnectorCommands(connector: CommandGroup): void {\n connector.command({\n name: \"validate\",\n help: \"Parse connector.toml and list its operations.\",\n positionals: [{ name: \"path\", help: \"World directory holding connector.toml\" }],\n flags: [HOST_FLAG],\n run: async (args, ctx) => {\n const dir = path.resolve(args.positionals[0]!);\n requireConnectorToml(dir);\n const creds = credentialsForRuntime(arg.str(args, \"host\"));\n const res = await runtime<{ summary?: { connection?: Connection | null } }>(creds, {\n command: \"template-summary\",\n files: readWorldFiles(dir),\n });\n const connection = res.summary?.connection;\n if (!connection) throw new CliError(\"The runtime read no vendor connection from this world\", 1);\n for (const line of renderConnection(connection)) ctx.stdout(line);\n },\n });\n\n connector.command({\n name: \"capture\",\n help: \"Call the live connection once (following its cursor) and record every page under captures/.\",\n notes:\n \"The platform makes the calls (--remote) — from the pod whose IP the vendor allow-listed, with the\\n\" +\n \"credential held as the environment's secret (`gateway secret set`) — and the redacted pages land in\\n\" +\n \"captures/ here, ready for `connector ingest`. A local capture runs the vendor call from this machine\\n\" +\n \"and runs on this machine when a python3 >= 3.11 is installed (the CLI bundles the runtime).\",\n positionals: [{ name: \"path\", help: \"World directory holding connector.toml\" }],\n flags: [\n { name: \"op\", help: \"Operation name from connector.toml\" },\n { name: \"arg\", help: \"Path argument, name=value (repeatable)\", repeat: true },\n { name: \"param\", help: \"Query parameter, name=value (repeatable)\", repeat: true },\n { name: \"max-pages\", help: \"Override [capture].max_pages\" },\n { name: \"remote\", help: \"Run the capture on the platform and pull the pages into captures/ here.\", boolean: true },\n { name: \"environment\", help: \"Environment slug or id for --remote (default: the world's directory name)\" },\n { name: \"timeout\", help: \"Seconds to wait for a --remote capture\", default: \"900\" },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const dir = path.resolve(args.positionals[0]!);\n const op = arg.str(args, \"op\");\n if (!op) throw new CliError(\"capture needs --op\");\n if (!arg.bool(args, \"remote\")) {\n // A local capture calls the vendor from this machine with the\n // credential from the environment variable connector.toml names —\n // the bundled runtime does it when a python3 is here.\n const local = localRuntime();\n if (!local)\n throw new CliError(\n \"local capture runs the vendor call from this machine and needs python3 >= 3.11 \" +\n \"(the CLI bundles the runtime); install one, or use --remote to capture from the platform\",\n );\n const argv = [\"connector-capture\", dir, \"--op\", op];\n for (const pair of arg.list(args, \"arg\")) argv.push(\"--arg\", pair);\n for (const pair of arg.list(args, \"param\")) argv.push(\"--param\", pair);\n const maxPages = arg.int(args, \"max-pages\");\n if (maxPages !== undefined) argv.push(\"--max-pages\", String(maxPages));\n return localModule(argv, local);\n }\n const creds = resolveCredentials(arg.str(args, \"host\"));\n const written = await remoteCapture(\n creds,\n dir,\n {\n op,\n args: pairs(arg.list(args, \"arg\"), \"--arg\"),\n params: pairs(arg.list(args, \"param\"), \"--param\"),\n maxPages: arg.int(args, \"max-pages\"),\n environment: arg.str(args, \"environment\"),\n timeoutSeconds: arg.int(args, \"timeout\") ?? 900,\n },\n ctx,\n );\n for (const file of written) ctx.stdout(file);\n },\n });\n\n connector.command({\n name: \"conform\",\n help:\n \"Serve the world and check every operation's answer against the vendor's OpenAPI: the documented \" +\n \"status, and a body the vendor's response schema accepts.\",\n positionals: [{ name: \"path\", help: \"World directory holding connector.toml\" }],\n flags: [\n { name: \"openapi\", help: \"The vendor's OpenAPI document (JSON or YAML); repeatable\", repeat: true },\n { name: \"out\", help: \"Write the full report as JSON here\" },\n { name: \"limit\", help: \"Check only the first N operations\" },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const dir = path.resolve(args.positionals[0]!);\n const documents = arg.list(args, \"openapi\");\n if (!documents.length) throw new CliError(\"conform needs --openapi FILE (repeatable)\");\n requireConnectorToml(dir);\n const openapi: WorldFile[] = documents.map((file) => {\n if (!fs.existsSync(file)) throw new CliError(`--openapi ${file} does not exist`);\n return { path: path.basename(file), content: fs.readFileSync(file).toString(\"base64\") };\n });\n const limit = arg.int(args, \"limit\");\n const creds = credentialsForRuntime(arg.str(args, \"host\"));\n const res = await runtime<{ report?: ConformReport }>(creds, {\n command: \"conform\",\n files: readWorldFiles(dir),\n openapi,\n ...(limit !== undefined ? { max_operations: limit } : {}),\n });\n const report = res.report ?? {};\n for (const outcome of report.operations ?? report.outcomes ?? [])\n ctx.stdout(renderConformOutcome(outcome));\n const summary = report.summary ?? {};\n ctx.stdout(JSON.stringify(summary));\n const out = arg.str(args, \"out\");\n if (out) {\n fs.writeFileSync(out, JSON.stringify(report, null, 1) + \"\\n\");\n ctx.stdout(`report: ${out}`);\n }\n return Number(summary.status_mismatch) || Number(summary.schema_violations) ? 1 : 0;\n },\n });\n\n connector.command({\n name: \"ingest\",\n help: \"Seed data/initial.json from the successful captures, gated by the world's contract.\",\n positionals: [{ name: \"path\", help: \"World directory holding captures/\" }],\n flags: [\n { name: \"batch-id\", help: \"Batch id; defaults to the next initial version\" },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const dir = path.resolve(args.positionals[0]!);\n if (!fs.existsSync(path.join(dir, CAPTURES)))\n throw new CliError(`${dir} holds no ${CAPTURES}/ — run \\`connector capture --remote\\` first`, 1);\n const batchId = arg.str(args, \"batch-id\");\n const creds = credentialsForRuntime(arg.str(args, \"host\"));\n const res = await runtime<{\n result?: { batch?: string; mutations?: number; entity_counts?: Record<string, number> };\n files?: WorldFile[];\n }>(creds, {\n command: \"ingest\",\n files: readWorldFiles(dir),\n ...(batchId ? { batch_id: batchId } : {}),\n });\n if (res.files?.length) writeWorldFiles(dir, res.files);\n const result = res.result ?? {};\n ctx.stdout(`batch ${result.batch ?? \"?\"}: ${result.mutations ?? 0} mutations`);\n for (const [entity, count] of Object.entries(result.entity_counts ?? {}).sort())\n ctx.stdout(` ${entity}: ${count}`);\n },\n });\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\nimport { CliError, arg, type CommandContext, type CommandGroup, type Parsed } from \"../router\";\nimport { resolveCredentials, type Credentials } from \"../config\";\nimport { openWorld, type WorldsClientOptions } from \"../../worlds/index\";\nimport { openSession, type WorldSession } from \"../../worlds/session\";\nimport type { WorldSurfaceKind } from \"../../worlds/browser\";\nimport { push, readLocalMeta } from \"../../worlds/hub\";\nimport { validateWorld } from \"../../worlds/validate\";\n\n/**\n * `gateway worlds run` and `gateway worlds ci`: a TypeScript agent module\n * against HOSTED sessions of a world. The Python `worlds run` executes the\n * world in-process; TypeScript cannot (a world's tools are Python), so every\n * task here is a live session the platform hosts — your agent stays where it\n * is and calls into the container through `WorldSession`.\n */\n\nexport type AgentTask = { name: string; instruction: string };\nexport type AgentModule = (session: WorldSession, task: AgentTask) => Promise<void>;\n\nconst HOST_FLAG = {\n name: \"host\",\n help: \"Platform host (default: GATEWAY_HOST or the saved login).\",\n env: \"GATEWAY_HOST\",\n};\n\nconst toOptions = (creds: Credentials): WorldsClientOptions => ({\n host: creds.host,\n publicKey: creds.publicKey,\n secretKey: creds.secretKey,\n});\n\n/** Import the agent module. `.js/.mjs/.cjs` load directly; a `.ts` file loads\n * through `tsx` (or `ts-node`) when one is installed next to the agent,\n * otherwise the user builds to JavaScript first. */\nexport async function loadAgent(file: string): Promise<AgentModule> {\n const abs = path.resolve(file);\n if (!fs.existsSync(abs)) throw new CliError(`--agent ${file} does not exist`);\n const ext = path.extname(abs);\n if (ext === \".ts\" || ext === \".mts\" || ext === \".cts\") await registerTypeScriptLoader(abs);\n else if (![\".js\", \".mjs\", \".cjs\"].includes(ext))\n throw new CliError(`--agent must be a .js/.mjs/.cjs or .ts module, got ${ext || \"no extension\"}`);\n const mod = (await import(pathToFileURL(abs).href)) as Record<string, unknown>;\n let candidate: unknown = mod.default ?? mod.agent ?? mod;\n if (candidate && typeof candidate === \"object\" && \"default\" in (candidate as object))\n candidate = (candidate as { default: unknown }).default;\n if (typeof candidate !== \"function\")\n throw new CliError(\n `${file} must default-export an agent: async (session, task) => void (see @withgateway/sdk/worlds WorldSession)`,\n );\n return candidate as AgentModule;\n}\n\nasync function registerTypeScriptLoader(agentPath: string): Promise<void> {\n // Resolve relative to the AGENT, so the user's own devDependency is found\n // — this package deliberately has no runtime dependencies.\n const { createRequire } = await import(\"node:module\");\n const localRequire = createRequire(agentPath);\n const loaders: (() => Promise<void>)[] = [\n async () => {\n const tsx = localRequire.resolve(\"tsx/esm/api\");\n const mod = (await import(pathToFileURL(tsx).href)) as { register?: () => void };\n if (typeof mod.register !== \"function\") throw new Error(\"tsx has no register()\");\n mod.register();\n },\n async () => {\n localRequire(\"ts-node/register\");\n },\n ];\n for (const load of loaders) {\n try {\n await load();\n return;\n } catch {\n // try the next loader\n }\n }\n throw new CliError(\n `${agentPath} is TypeScript and neither tsx nor ts-node is installed next to it. ` +\n \"Add `tsx` as a devDependency, or build the agent to .js and pass that.\",\n );\n}\n\n// ── the world to run against ─────────────────────────────────────────────────\n\nexport type RunTarget = {\n slug: string;\n ref: string | null;\n /** Pinned version every session opens on; null = the ref's head. */\n versionId: string | null;\n /** A local directory, when the target was one. */\n dir: string | null;\n};\n\n/** `<dir>` reads `.gateway/.env-metadata.json` (written by push/pull) for the\n * slug and pinned version; `<slug[@ref]>` is the platform world. */\nexport function resolveTarget(target: string, versionFlag?: string): RunTarget {\n if (fs.existsSync(target) && fs.statSync(target).isDirectory()) {\n const dir = path.resolve(target);\n const meta = readLocalMeta(dir);\n return {\n slug: (meta?.slug as string | undefined) ?? path.basename(dir),\n ref: (meta?.branch as string | undefined) ?? null,\n versionId: versionFlag ?? meta?.versionId ?? null,\n dir,\n };\n }\n const at = target.indexOf(\"@\");\n return {\n slug: at === -1 ? target : target.slice(0, at),\n ref: at === -1 ? null : target.slice(at + 1),\n versionId: versionFlag ?? null,\n dir: null,\n };\n}\n\nasync function resolveTasks(\n target: RunTarget,\n args: Parsed,\n creds: Credentials,\n): Promise<{ tasks: string[]; versionId: string | null }> {\n const one = arg.str(args, \"task\");\n if (one && !arg.bool(args, \"all\")) return { tasks: [one], versionId: target.versionId };\n if (!arg.bool(args, \"all\")) throw new CliError(\"pass --task <name> or --all\");\n const world = await openWorld(target.ref ? `${target.slug}@${target.ref}` : target.slug, toOptions(creds));\n if (!world.tasks.length) throw new CliError(`${target.slug} declares no tasks`, 1);\n return {\n tasks: world.tasks.map((t) => t.name),\n versionId: target.versionId ?? world.version.versionId,\n };\n}\n\n// ── running ──────────────────────────────────────────────────────────────────\n\nexport type TaskResult = {\n task: string;\n sessionId: string;\n reward: number | null;\n rewards: Record<string, number>;\n error?: string;\n};\n\nexport type RunSummary = {\n world: { slug: string; versionId: string | null };\n agent: string;\n results: TaskResult[];\n /** Mean reward over every task, a failed task counting 0. */\n mean: number;\n};\n\nexport async function runTasks(opts: {\n target: RunTarget;\n versionId: string | null;\n tasks: string[];\n agent: AgentModule;\n agentName: string;\n surfaces: WorldSurfaceKind[];\n timeoutMs?: number;\n creds: Credentials;\n ctx: CommandContext;\n}): Promise<RunSummary> {\n const options = toOptions(opts.creds);\n const results: TaskResult[] = [];\n for (const task of opts.tasks) {\n let session: WorldSession | null = null;\n try {\n session = await openSession(opts.target.slug, task, {\n ...(opts.versionId ? { versionId: opts.versionId } : {}),\n ...(opts.surfaces.length ? { surfaces: opts.surfaces } : {}),\n options,\n });\n opts.ctx.stderr(`# ${task}: session ${session.sessionId}`);\n await session.ready({ timeoutMs: opts.timeoutMs });\n await opts.agent(session, { name: task, instruction: session.instruction ?? task });\n const graded = await session.grade({ timeoutMs: opts.timeoutMs });\n results.push({ task, sessionId: session.sessionId, reward: graded.reward, rewards: graded.rewards });\n } catch (error) {\n results.push({\n task,\n sessionId: session?.sessionId ?? \"\",\n reward: 0,\n rewards: {},\n error: (error instanceof Error ? error.message : String(error)) || \"Unknown error\",\n });\n } finally {\n await session?.close().catch(() => undefined);\n }\n }\n const mean = results.reduce((sum, r) => sum + (r.reward ?? 0), 0) / (results.length || 1);\n return {\n world: { slug: opts.target.slug, versionId: opts.versionId },\n agent: opts.agentName,\n results,\n mean,\n };\n}\n\nfunction parseSurfaces(value: string | undefined): WorldSurfaceKind[] {\n return (value ?? \"\")\n .split(\",\")\n .map((s) => s.trim())\n .filter((s) => s && s !== \"tools\") as WorldSurfaceKind[];\n}\n\nfunction timeoutMs(args: Parsed): number | undefined {\n const minutes = arg.int(args, \"timeout-min\");\n return minutes === undefined ? undefined : minutes * 60_000;\n}\n\nconst RUN_FLAGS = [\n { name: \"agent\", short: \"a\", help: \"Agent module (.js/.mjs/.cjs, or .ts with tsx installed) whose default export is async (session, task) => void.\" },\n { name: \"task\", short: \"t\", help: \"Run this one task.\" },\n { name: \"all\", help: \"Run every task in the world's task set.\", boolean: true },\n { name: \"version-id\", help: \"Pin every session to this version (default: the dir's recorded base, else the ref's head).\" },\n { name: \"surface\", short: \"s\", help: \"Surfaces to open besides tools, comma-separated: api,ui,browser.\", default: \"\" },\n { name: \"timeout-min\", help: \"Minutes to wait for a container to be ready, and for a grade.\" },\n HOST_FLAG,\n];\n\n/** The Python `_ci_finish`: a step-summary table under GitHub Actions. */\nexport function writeStepSummary(title: string, rows: [string, string][]): void {\n const summaryPath = process.env.GITHUB_STEP_SUMMARY;\n if (!summaryPath) return;\n const lines = [`### ${title}`, \"\", \"| | |\", \"|---|---|\", ...rows.map(([k, v]) => `| ${k} | ${v} |`)];\n try {\n fs.appendFileSync(summaryPath, lines.join(\"\\n\") + \"\\n\\n\");\n } catch {\n // the summary is a nicety; the gate is the contract\n }\n}\n\nexport function registerRunCommands(worlds: CommandGroup): void {\n worlds.command({\n name: \"run\",\n help: \"Run a TypeScript agent module against hosted sessions of a world and print the graded results.\",\n notes:\n \" gateway worlds run ./acme-world --agent ./agent.mjs --all\\n\" +\n \" gateway worlds run acme-world@main --agent ./agent.ts --task acme-alice-dedupe\\n\\n\" +\n \"Each task opens one live session; the agent gets (session, {name, instruction}) and uses\\n\" +\n \"session.call / session.toolkit(); the task's own grader scores the end state.\",\n positionals: [{ name: \"world\", help: \"World directory (pushed or pulled), or a platform slug[@ref].\" }],\n flags: RUN_FLAGS,\n run: async (args, ctx) => {\n const agentFile = arg.str(args, \"agent\");\n if (!agentFile) throw new CliError(\"run needs --agent <module>\");\n const creds = resolveCredentials(arg.str(args, \"host\"));\n const target = resolveTarget(args.positionals[0]!, arg.str(args, \"version-id\"));\n const agent = await loadAgent(agentFile);\n const { tasks, versionId } = await resolveTasks(target, args, creds);\n const summary = await runTasks({\n target,\n versionId,\n tasks,\n agent,\n agentName: agentFile,\n surfaces: parseSurfaces(arg.str(args, \"surface\")),\n timeoutMs: timeoutMs(args),\n creds,\n ctx,\n });\n ctx.stdout(JSON.stringify(summary, null, 2));\n return summary.results.some((r) => r.error) ? 1 : 0;\n },\n });\n\n worlds.command({\n name: \"ci\",\n help: \"Push the checked-out world, run every task, and exit 1 below --min-score — the PR gate in one command.\",\n notes:\n \" gateway worlds ci ./acme-world --agent ./agent.mjs --min-score 0.7\\n\" +\n \" gateway worlds ci ./acme-world --run-config nightly --min-score 0.7\\n\\n\" +\n \"The branch defaults to GITHUB_HEAD_REF (PRs), then GITHUB_REF_NAME, then the dir's recorded branch.\\n\" +\n \"--run-config dispatches a hosted run config against the pushed version instead of a local agent.\\n\" +\n \"Writes a $GITHUB_STEP_SUMMARY table under GitHub Actions.\",\n positionals: [{ name: \"path\", help: \"World directory inside the checked-out repo.\" }],\n flags: [\n ...RUN_FLAGS.filter((f) => ![\"task\", \"all\"].includes(f.name)),\n { name: \"run-config\", help: \"Dispatch this run config (name or id) on the platform instead of running --agent.\" },\n { name: \"min-score\", help: \"Reward gate: exit 1 when the mean reward lands below this bar.\" },\n { name: \"summary-file\", help: \"Write the JSON summary here as well as to stdout.\" },\n { name: \"branch\", short: \"b\", help: \"Hub branch to push and run.\" },\n { name: \"message\", short: \"M\", help: \"Push change reason (default: a CI commit line).\" },\n ],\n run: async (args, ctx) => {\n const dir = path.resolve(args.positionals[0]!);\n if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())\n throw new CliError(`path is not a directory: ${args.positionals[0]}`);\n const agentFile = arg.str(args, \"agent\");\n const runConfig = arg.str(args, \"run-config\");\n if (!agentFile && !runConfig) throw new CliError(\"ci needs --agent <module> or --run-config <name>\");\n const minScoreRaw = arg.str(args, \"min-score\");\n const minScore = minScoreRaw === undefined ? null : Number(minScoreRaw);\n if (minScore !== null && !(minScore >= 0 && minScore <= 1))\n throw new CliError(\"--min-score must be a number between 0 and 1\");\n const creds = resolveCredentials(arg.str(args, \"host\"));\n const options = toOptions(creds);\n const meta = readLocalMeta(dir) ?? {};\n const branch =\n arg.str(args, \"branch\") ||\n process.env.GITHUB_HEAD_REF ||\n process.env.GITHUB_REF_NAME ||\n (meta.branch as string | undefined) ||\n (meta.ref as string | undefined) ||\n \"main\";\n const sha = (process.env.GITHUB_SHA ?? \"\").slice(0, 12);\n const repo = process.env.GITHUB_REPOSITORY ?? \"\";\n const message = arg.str(args, \"message\") ?? (repo && sha ? `[ci] ${repo}@${sha}` : \"[ci] working tree\");\n const summaryFile = arg.str(args, \"summary-file\");\n\n if (runConfig) {\n const report = await validateWorld(dir, {\n runConfig,\n branch,\n minScore,\n timeoutMinutes: arg.int(args, \"timeout-min\") ?? undefined,\n onProgress: (line) => ctx.stderr(line),\n options,\n });\n const { markdown, ...summary } = report;\n ctx.stdout(JSON.stringify(summary, null, 2));\n if (summaryFile) fs.writeFileSync(summaryFile, JSON.stringify(summary, null, 2) + \"\\n\");\n const stepSummary = process.env.GITHUB_STEP_SUMMARY;\n if (stepSummary) {\n try {\n fs.appendFileSync(stepSummary, markdown + \"\\n\\n\");\n } catch {\n // nicety only\n }\n }\n return report.ok ? 0 : 1;\n }\n\n // The hub branch MIRRORS this checkout (the PR's code), so force.\n const pushed = await push(dir, { branch, force: true, message, options });\n ctx.stderr(`pushed ${pushed.slug}@${branch} (${pushed.contentHash.slice(0, 8)})`);\n const agent = await loadAgent(agentFile!);\n const world = await openWorld(`${pushed.slug}@${branch}`, options);\n const tasks = world.tasks.map((t) => t.name);\n if (!tasks.length) throw new CliError(`${pushed.slug} declares no tasks`, 1);\n const target: RunTarget = { slug: pushed.slug, ref: branch, versionId: pushed.versionId, dir };\n const summary = await runTasks({\n target,\n versionId: pushed.versionId,\n tasks,\n agent,\n agentName: agentFile!,\n surfaces: parseSurfaces(arg.str(args, \"surface\")),\n timeoutMs: timeoutMs(args),\n creds,\n ctx,\n });\n const out = { ...summary, branch, contentHash: pushed.contentHash };\n ctx.stdout(JSON.stringify(out, null, 2));\n if (summaryFile) fs.writeFileSync(summaryFile, JSON.stringify(out, null, 2) + \"\\n\");\n const rows: [string, string][] = [\n [\"avg reward\", summary.mean.toFixed(3)],\n [\"tasks\", String(summary.results.length)],\n [\"agent\", agentFile!],\n [\"version\", pushed.contentHash.slice(0, 8)],\n ];\n const passed = minScore === null || summary.mean >= minScore;\n if (minScore !== null) rows.push([\"gate\", `${passed ? \"PASS\" : \"FAIL\"} — bar ${minScore}`]);\n writeStepSummary(`World sim · ${pushed.slug}@${branch}`, rows);\n if (minScore !== null) {\n ctx.stderr(\n passed\n ? `gate: avg reward ${summary.mean.toFixed(3)} clears the ${minScore} bar.`\n : `gate: avg reward ${summary.mean.toFixed(3)} is below the ${minScore} bar.`,\n );\n }\n return passed ? 0 : 1;\n },\n });\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport { CliError, arg, type CommandGroup } from \"../router\";\nimport { resolveCredentials } from \"../config\";\nimport { openWorld } from \"../../worlds/index\";\nimport { openSession } from \"../../worlds/session\";\nimport { readLocalMeta } from \"../../worlds/hub\";\nimport { localModule, localRuntime } from \"./local\";\n\n/**\n * `gateway worlds serve`: the world's vendor API on this machine through the\n * bundled runtime when a python3 is installed (what the Python CLI did), or a\n * HOSTED api-surface session when none is — the same routes, from the\n * platform's container, no wait.\n */\n\nexport function registerServeCommand(worlds: CommandGroup): void {\n worlds.command({\n name: \"serve\",\n help: \"Serve the world's vendor API here (bundled runtime + python3), or open a hosted api session when no Python is installed.\",\n notes:\n \"With a python3 >= 3.11 on this machine the CLI serves the world here from its bundled runtime\\n\" +\n \"(the same files the platform runs), on --port, in the foreground. Without one it does what\\n\" +\n \"`gateway worlds session open <slug> --task <scenario> --surface api --no-wait` does: the platform\\n\" +\n \"serves the world's vendor API for one session, and the session id + api url are printed. Close it\\n\" +\n \"with `gateway worlds session close <id>`. GATEWAY_RUNTIME=platform forces the hosted path.\",\n positionals: [{ name: \"path\", help: \"World directory (pushed or pulled), or a platform slug[@ref].\" }],\n flags: [\n { name: \"scenario\", help: \"Start in one of the world's scenarios (default: the world's first task).\" },\n { name: \"port\", help: \"Port for the local server (a hosted session picks its own address).\", default: \"8080\" },\n { name: \"api-key\", help: \"Pin the credential the local server accepts (a hosted session carries its own).\" },\n { name: \"host\", help: \"Platform host (default: GATEWAY_HOST or the saved login).\", env: \"GATEWAY_HOST\" },\n ],\n run: async (args, ctx) => {\n const target = args.positionals[0]!;\n // With a python3 on this machine the bundled runtime serves the world\n // here, exactly as the Python CLI did; the hosted session is the\n // fallback for a machine without one.\n const local = localRuntime();\n if (local && fs.existsSync(target) && fs.statSync(target).isDirectory()) {\n const argv = [\"serve\", path.resolve(target), \"--port\", arg.str(args, \"port\") ?? \"8080\"];\n const apiKey = arg.str(args, \"api-key\");\n if (apiKey) argv.push(\"--api-key\", apiKey);\n const scenario = arg.str(args, \"scenario\");\n if (scenario) argv.push(\"--scenario\", scenario);\n ctx.stderr(`# serving ${path.resolve(target)} on http://127.0.0.1:${arg.str(args, \"port\") ?? \"8080\"} (local runtime: ${local.python})`);\n return localModule(argv, local);\n }\n const creds = resolveCredentials(arg.str(args, \"host\"));\n const options = { host: creds.host, publicKey: creds.publicKey, secretKey: creds.secretKey };\n let slugRef = target;\n let versionId: string | undefined;\n if (fs.existsSync(target) && fs.statSync(target).isDirectory()) {\n const dir = path.resolve(target);\n const meta = readLocalMeta(dir);\n const slug = (meta?.slug as string | undefined) ?? path.basename(dir);\n slugRef = meta?.branch ? `${slug}@${meta.branch}` : slug;\n versionId = meta?.versionId;\n }\n ctx.stderr(\n \"`worlds serve` runs a local server with the Python runtime; opening a hosted api-surface session instead.\",\n );\n let scenario = arg.str(args, \"scenario\");\n if (!scenario) {\n const world = await openWorld(slugRef, options);\n scenario = world.tasks[0]?.name;\n if (!scenario) throw new CliError(`${slugRef} declares no tasks; pass --scenario`, 1);\n ctx.stderr(`# no --scenario given; using the world's first task: ${scenario}`);\n }\n const session = await openSession(slugRef, scenario, {\n ...(versionId ? { versionId } : {}),\n surfaces: [\"api\"],\n options,\n });\n const surfaces = await session.surfaces();\n ctx.stdout(\n JSON.stringify(\n {\n sessionId: session.sessionId,\n task: scenario,\n versionId: session.versionId,\n api: surfaces.api?.url ?? null,\n note: \"hosted session; `gateway worlds session status <id>` for readiness, `session close <id>` when done\",\n },\n null,\n 2,\n ),\n );\n },\n });\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport { CliError, arg, type CommandGroup } from \"../router\";\nimport { HOST_FLAG } from \"../platform/shared\";\nimport { credentialsForRuntime } from \"./local\";\nimport { api, resolveCredentials } from \"../config\";\nimport { readWorldFiles, runtime } from \"./client\";\n\n/** The report `run-tests` returns: what `<world>/tests/` asserted and how the world answered. */\nexport type WorldTestReport = {\n world?: string;\n scenario?: string | null;\n summary?: { total?: number; passed?: number; failed?: number; skipped?: number; status?: string };\n cases?: {\n name: string;\n file: string;\n status: string;\n request?: { method?: string; path?: string };\n actual?: { status?: number; body?: string };\n problems?: string[];\n }[];\n python?: { status: string; files?: string[]; tests?: number; failures?: number; errors?: number; reason?: string | null; output?: string };\n};\n\nexport function renderWorldTestReport(report: WorldTestReport): string[] {\n const lines: string[] = [];\n for (const c of report.cases ?? []) {\n const mark = c.status === \"passed\" ? \" ok \" : \"FAIL\";\n const where = c.request ? `${c.request.method ?? \"GET\"} ${c.request.path ?? \"/\"}` : \"\";\n lines.push(`${mark} ${c.name} ${where}`.trimEnd());\n for (const p of c.problems ?? []) lines.push(` ${p}`);\n }\n const py = report.python;\n if (py && py.status !== \"none\") {\n const detail =\n py.status === \"skipped\"\n ? py.reason ?? \"skipped\"\n : `${py.tests ?? 0} tests, ${py.failures ?? 0} failures, ${py.errors ?? 0} errors`;\n lines.push(`${py.status === \"passed\" ? \" ok \" : py.status === \"skipped\" ? \"skip\" : \"FAIL\"} python tests (${(py.files ?? []).join(\", \")}) ${detail}`);\n if (py.status === \"failed\" && py.output) lines.push(...py.output.trimEnd().split(\"\\n\").slice(-30).map((l) => ` ${l}`));\n }\n return lines;\n}\n\n/**\n * `gateway worlds test <path>` — run the tests a world ships for itself\n * (`tests/*.json` HTTP cases, `tests/test_*.py`) against the world at that\n * path, served in the schema runtime. Tests are not evals: an eval grades an\n * agent on a task; a test asserts the world answers as its author says it\n * must, and runs on every push when the manifest asks for it.\n */\nexport function registerTestCommand(worlds: CommandGroup): void {\n worlds.command({\n name: \"test\",\n help: \"Run the tests a world ships for itself (tests/*.json HTTP cases, tests/test_*.py) against the served world.\",\n positionals: [{ name: \"path\", help: \"World directory (a schema world, or its api bundle), or a platform slug[@versionId] to run the suite on the platform.\" }],\n flags: [\n { name: \"scenario\", help: \"Start the world in one of its scenarios before testing (default: the base state).\" },\n { name: \"out\", help: \"Write the full report as JSON here\" },\n { name: \"json\", help: \"Print the report as JSON instead of lines.\", boolean: true },\n HOST_FLAG,\n ],\n notes:\n \"A world's tests live in <world>/tests/: *.json files of {name, request: {method, path, query?, headers?, body?, auth?},\\n\" +\n \"expect: {status?, json?, length?, contains?, headers?}} cases, and pytest files that get WORLD_URL + WORLD_API_KEY.\\n\" +\n \"With `[actions] on_push = [\\\"tests\\\"]` in gateway-env.toml the platform runs the same suite on every push;\\n\" +\n \"`gateway bench tests <slug>` reads those runs. Exit 1 when any test fails.\",\n run: async (args, ctx) => {\n const target = args.positionals[0] ?? \".\";\n const dir = path.resolve(target);\n if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) {\n // Not a directory here: a world on the platform. The platform runs the\n // suite the pushed version ships and answers with the run.\n if (/[\\/\\\\]/.test(target) || target.startsWith(\".\")) throw new CliError(`Not a directory: ${dir}`, 1);\n const creds = resolveCredentials(arg.str(args, \"host\"));\n const [slug, ref] = target.split(\"@\");\n const scenario = arg.str(args, \"scenario\");\n const answer = await api<{ run: { id: string; state: string; versionId: string; summary?: WorldTestReport[\"summary\"]; error?: string | null; report?: WorldTestReport | null } }>(\n creds,\n \"POST\",\n `/api/public/worlds/${encodeURIComponent(slug!)}/tests`,\n { ...(ref ? { versionId: ref } : {}), ...(scenario ? { scenario } : {}) },\n { timeoutMs: 15 * 60_000 },\n );\n const run = answer.run;\n const report = run.report ?? {};\n if (arg.bool(args, \"json\")) ctx.stdout(JSON.stringify({ runId: run.id, state: run.state, versionId: run.versionId, ...report }, null, 1));\n else {\n for (const line of renderWorldTestReport(report)) ctx.stdout(line);\n const s = run.summary ?? report.summary ?? {};\n ctx.stdout(`${run.state}: ${s.passed ?? 0} passed, ${s.failed ?? 0} failed, ${s.skipped ?? 0} skipped (run ${run.id} on ${run.versionId})`);\n if (run.error) ctx.stdout(`error: ${run.error}`);\n }\n const out = arg.str(args, \"out\");\n if (out) fs.writeFileSync(out, JSON.stringify({ runId: run.id, state: run.state, versionId: run.versionId, ...report }, null, 1) + \"\\n\");\n return run.state === \"passed\" ? 0 : 1;\n }\n const tests = fs.existsSync(path.join(dir, \"tests\")) || fs.existsSync(path.join(dir, \"server\", \"world\", \"tests\"));\n if (!tests) throw new CliError(`${dir} ships no tests/ directory — see \\`gateway worlds test --help\\` for the contract`, 1);\n const creds = credentialsForRuntime(arg.str(args, \"host\"));\n const scenario = arg.str(args, \"scenario\");\n const res = await runtime<{ report?: WorldTestReport }>(creds, {\n command: \"run-tests\",\n files: readWorldFiles(dir),\n ...(scenario ? { scenario } : {}),\n });\n const report = res.report ?? {};\n if (arg.bool(args, \"json\")) ctx.stdout(JSON.stringify(report, null, 1));\n else {\n for (const line of renderWorldTestReport(report)) ctx.stdout(line);\n const s = report.summary ?? {};\n ctx.stdout(`${s.status ?? \"?\"}: ${s.passed ?? 0} passed, ${s.failed ?? 0} failed, ${s.skipped ?? 0} skipped`);\n }\n const out = arg.str(args, \"out\");\n if (out) {\n fs.writeFileSync(out, JSON.stringify(report, null, 1) + \"\\n\");\n ctx.stdout(`report: ${out}`);\n }\n return report.summary?.status === \"passed\" ? 0 : 1;\n },\n });\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport { CliError, arg, type CommandGroup } from \"../router\";\n\n/**\n * `gateway worlds schema entity add` and `gateway worlds connector route add`:\n * local scaffolds that append one declaration to a hand-authored file so the\n * shape is right without the author remembering it. Neither talks to the\n * platform; `worlds schema check` / `worlds connector validate` still judge\n * the result.\n */\n\nconst ENTITY_NAME = /^[A-Za-z][A-Za-z0-9_]*$/;\nconst PROPERTY_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;\nconst HTTP_METHODS = new Set([\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"]);\nconst API_ACTIONS = new Set([\"read\", \"create\", \"update\", \"delete\", \"handler\"]);\nconst FIELD_TYPES = new Set([\"string\", \"integer\", \"number\", \"boolean\"]);\n\ntype JsonObject = Record<string, unknown>;\n\nconst isObject = (value: unknown): value is JsonObject =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nexport type Relationship = { fields: string[]; target: string; on_delete: \"restrict\" };\n\nexport type EntityDeclaration = {\n schema: JsonObject;\n primary_key: string[];\n unique?: string[][];\n relationships?: Relationship[];\n};\n\nexport type EntitySpec = {\n name: string;\n /** `--ref Name` → `{\"$ref\": \"#/$defs/Name\"}`. */\n ref?: string;\n /** Inline JSON Schema for the payload (mutually exclusive with `ref`). */\n schema?: JsonObject;\n /** `--fields id:string,name:string?`: an object def written under `$defs` and referenced. */\n fields?: string;\n primaryKey: string[];\n unique: string[][];\n relationships: Relationship[];\n};\n\nexport function parseFields(spec: string): JsonObject {\n const properties: JsonObject = {};\n const required: string[] = [];\n for (const raw of spec.split(\",\")) {\n const item = raw.trim();\n if (!item) continue;\n const colon = item.indexOf(\":\");\n if (colon === -1)\n throw new CliError(`--fields entries look like name:type[?], got ${JSON.stringify(item)}`);\n const name = item.slice(0, colon).trim();\n let type = item.slice(colon + 1).trim();\n const optional = type.endsWith(\"?\");\n if (optional) type = type.slice(0, -1);\n if (!PROPERTY_NAME.test(name)) throw new CliError(`Invalid property name ${JSON.stringify(name)}`);\n if (!FIELD_TYPES.has(type))\n throw new CliError(\n `Unknown field type ${JSON.stringify(type)} for ${name}; use ${[...FIELD_TYPES].join(\", \")}`,\n );\n if (name in properties) throw new CliError(`Duplicate field ${name}`);\n properties[name] = { type };\n if (!optional) required.push(name);\n }\n if (!Object.keys(properties).length) throw new CliError(\"--fields declares no properties\");\n return { type: \"object\", properties, required, additionalProperties: false };\n}\n\n/** `account_id->crm_accounts`, `workspace_id,user_id->slack_users`. */\nexport function parseRelationship(spec: string): Relationship {\n const arrow = spec.indexOf(\"->\");\n if (arrow === -1)\n throw new CliError(`--relationship looks like field[,field]->target_entity, got ${JSON.stringify(spec)}`);\n const fields = spec\n .slice(0, arrow)\n .split(\",\")\n .map((f) => f.trim())\n .filter(Boolean);\n const target = spec.slice(arrow + 2).trim();\n if (!fields.length || !target)\n throw new CliError(`--relationship looks like field[,field]->target_entity, got ${JSON.stringify(spec)}`);\n return { fields, target, on_delete: \"restrict\" };\n}\n\nfunction defName(entity: string): string {\n return entity\n .split(\"_\")\n .filter(Boolean)\n .map((part) => part[0]!.toUpperCase() + part.slice(1))\n .join(\"\");\n}\n\nfunction resolveObjectSchema(root: JsonObject, schema: JsonObject): JsonObject | undefined {\n const ref = schema.$ref;\n if (typeof ref === \"string\") {\n if (!ref.startsWith(\"#/$defs/\")) return undefined;\n const defs = root.$defs;\n const target = isObject(defs) ? defs[ref.slice(\"#/$defs/\".length)] : undefined;\n return isObject(target) ? target : undefined;\n }\n return schema;\n}\n\n/**\n * Pure: returns the document with the entity declared (and a `$defs` entry when\n * `--fields` built one). Throws a CliError naming exactly what is wrong.\n */\nexport function addEntity(root: JsonObject, spec: EntitySpec): { document: JsonObject; declaration: EntityDeclaration; def?: string } {\n if (!ENTITY_NAME.test(spec.name))\n throw new CliError(`Entity names match [A-Za-z][A-Za-z0-9_]*, got ${JSON.stringify(spec.name)}`);\n const gateway = root[\"x-gateway\"];\n if (!isObject(gateway) || !isObject(gateway.entities))\n throw new CliError(\"schema/world.json is not a gateway-world/1 root: it has no x-gateway.entities\");\n const entities = gateway.entities;\n const collision = Object.keys(entities).find((k) => k.toLowerCase() === spec.name.toLowerCase());\n if (collision) throw new CliError(`Entity ${collision} is already declared`);\n\n const chosen = [spec.ref, spec.schema, spec.fields].filter((v) => v !== undefined).length;\n if (chosen !== 1) throw new CliError(\"Give exactly one of --ref, --schema or --fields\");\n\n const defs: JsonObject = isObject(root.$defs) ? { ...root.$defs } : {};\n let schema: JsonObject;\n let def: string | undefined;\n if (spec.ref !== undefined) {\n if (!(spec.ref in defs))\n throw new CliError(\n `$defs has no ${spec.ref}; declare it first or use --fields to write one (have: ${Object.keys(defs).join(\", \") || \"none\"})`,\n );\n schema = { $ref: `#/$defs/${spec.ref}` };\n } else if (spec.fields !== undefined) {\n def = defName(spec.name);\n if (def in defs) throw new CliError(`$defs already has ${def}; use --ref ${def} to reuse it`);\n defs[def] = parseFields(spec.fields);\n schema = { $ref: `#/$defs/${def}` };\n } else {\n schema = spec.schema!;\n }\n\n if (!spec.primaryKey.length) throw new CliError(\"--key is required (repeat it for a composite key)\");\n if (new Set(spec.primaryKey).size !== spec.primaryKey.length)\n throw new CliError(\"--key fields must be distinct\");\n const payload = resolveObjectSchema({ ...root, $defs: defs }, schema);\n if (payload) {\n if (payload.type !== \"object\" || payload.additionalProperties !== false)\n throw new CliError(\"An entity payload must be a closed object: type \\\"object\\\" with additionalProperties false\");\n const properties = isObject(payload.properties) ? payload.properties : {};\n const required = Array.isArray(payload.required) ? payload.required : [];\n for (const key of spec.primaryKey) {\n const prop = properties[key];\n if (!isObject(prop)) throw new CliError(`Primary key field ${key} is not a property of the payload`);\n if (prop.type !== \"string\" && prop.type !== \"integer\")\n throw new CliError(`Primary key field ${key} must be a string or integer property`);\n if (!required.includes(key)) throw new CliError(`Primary key field ${key} must be required`);\n }\n for (const rel of spec.relationships)\n for (const field of rel.fields)\n if (!(field in properties) && !field.startsWith(\"/\"))\n throw new CliError(`Relationship field ${field} is not a property of the payload`);\n }\n\n for (const rel of spec.relationships) {\n const target = entities[rel.target];\n if (!isObject(target)) {\n if (rel.target === spec.name) continue;\n throw new CliError(`Relationship target ${rel.target} is not a declared entity`);\n }\n const targetKey = Array.isArray(target.primary_key) ? target.primary_key : [];\n if (targetKey.length !== rel.fields.length)\n throw new CliError(\n `Relationship to ${rel.target} needs ${targetKey.length} field(s) to match its primary key [${targetKey.join(\", \")}]`,\n );\n }\n\n const declaration: EntityDeclaration = { schema, primary_key: spec.primaryKey };\n if (spec.unique.length) declaration.unique = spec.unique;\n if (spec.relationships.length) declaration.relationships = spec.relationships;\n\n const document: JsonObject = { ...root };\n if (def !== undefined || root.$defs !== undefined) document.$defs = defs;\n document[\"x-gateway\"] = { ...gateway, entities: { ...entities, [spec.name]: declaration } };\n return { document, declaration, def };\n}\n\n// ── connector routes ────────────────────────────────────────────────────────\n\nexport type RouteSpec = {\n name: string;\n method: string;\n path: string;\n params: string[];\n entity?: string;\n results?: string;\n api: {\n action?: string;\n status?: number;\n single?: boolean;\n filter: Record<string, string>;\n body: Record<string, string>;\n handler?: string;\n };\n};\n\nconst tomlString = (value: string) => JSON.stringify(value);\n\nconst tomlInlineTable = (pairs: Record<string, string>) =>\n `{ ${Object.entries(pairs)\n .map(([k, v]) => `${PROPERTY_NAME.test(k) ? k : tomlString(k)} = ${tomlString(v)}`)\n .join(\", \")} }`;\n\n/** The `[[operations]]` block (and `[operations.api]` when any api key is set). */\nexport function renderRoute(spec: RouteSpec): string {\n const lines = [\"[[operations]]\", `name = ${tomlString(spec.name)}`, `method = ${tomlString(spec.method)}`, `path = ${tomlString(spec.path)}`];\n if (spec.params.length) lines.push(`params = [${spec.params.map(tomlString).join(\", \")}]`);\n if (spec.entity !== undefined) lines.push(`entity = ${tomlString(spec.entity)}`);\n if (spec.results !== undefined) lines.push(`results = ${tomlString(spec.results)}`);\n const api: string[] = [];\n if (spec.api.action !== undefined) api.push(`action = ${tomlString(spec.api.action)}`);\n if (spec.api.status !== undefined) api.push(`status = ${spec.api.status}`);\n if (spec.api.single) api.push(\"single = true\");\n if (Object.keys(spec.api.filter).length) api.push(`filter = ${tomlInlineTable(spec.api.filter)}`);\n if (Object.keys(spec.api.body).length) api.push(`body = ${tomlInlineTable(spec.api.body)}`);\n if (spec.api.handler !== undefined) api.push(`handler = ${tomlString(spec.api.handler)}`);\n if (api.length) lines.push(\"\", \"[operations.api]\", ...api);\n return lines.join(\"\\n\") + \"\\n\";\n}\n\nexport function declaredOperationNames(toml: string): string[] {\n const names: string[] = [];\n let inOperation = false;\n for (const raw of toml.split(\"\\n\")) {\n const line = raw.trim();\n if (line.startsWith(\"[\")) inOperation = line === \"[[operations]]\";\n else if (inOperation) {\n const m = /^name\\s*=\\s*\"([^\"]*)\"/.exec(line);\n if (m) names.push(m[1]!);\n }\n }\n return names;\n}\n\n/** Pure: the connector.toml text with one more `[[operations]]` appended. */\nexport function addRoute(toml: string, spec: RouteSpec, declaredEntities?: string[]): string {\n if (!/^\\s*\\[connector\\]\\s*$/m.test(toml))\n throw new CliError(\"connector.toml has no [connector] table; it is not a connector spec\");\n if (!PROPERTY_NAME.test(spec.name))\n throw new CliError(`Operation names match [A-Za-z_][A-Za-z0-9_]*, got ${JSON.stringify(spec.name)}`);\n if (declaredOperationNames(toml).includes(spec.name))\n throw new CliError(`Operation ${spec.name} is already declared`);\n if (!HTTP_METHODS.has(spec.method))\n throw new CliError(`--method must be one of ${[...HTTP_METHODS].join(\", \")}, got ${spec.method}`);\n if (!spec.path.startsWith(\"/\")) throw new CliError(`--path must start with /, got ${spec.path}`);\n if (spec.path.includes(\"?\")) throw new CliError(\"--path carries no query string; declare query parameters with --param\");\n if (spec.api.action !== undefined && !API_ACTIONS.has(spec.api.action))\n throw new CliError(`--action must be one of ${[...API_ACTIONS].join(\", \")}, got ${spec.api.action}`);\n if (spec.api.action === \"handler\" && spec.api.handler === undefined)\n throw new CliError(\"--action handler needs --handler <function> from api/handlers.py\");\n if (spec.api.handler !== undefined && spec.api.action !== \"handler\")\n throw new CliError(\"--handler only applies with --action handler\");\n if (spec.api.status !== undefined && (spec.api.status < 200 || spec.api.status > 299))\n throw new CliError(\"--status must be a 2xx\");\n if (spec.entity !== undefined && declaredEntities && !declaredEntities.includes(spec.entity))\n throw new CliError(\n `Entity ${spec.entity} is not declared in schema/world.json (have: ${declaredEntities.join(\", \") || \"none\"}); run \\`gateway worlds schema entity add\\` first`,\n );\n if (spec.entity === undefined && (spec.results !== undefined || spec.api.action !== undefined && spec.api.action !== \"handler\"))\n throw new CliError(\"--results and store actions need --entity: an operation without an entity never seeds\");\n const pathArgs = [...spec.path.matchAll(/\\{([^}]+)\\}/g)].map((m) => m[1]!);\n for (const [key] of Object.entries(spec.api.filter))\n if (!pathArgs.includes(key) && !spec.params.includes(key))\n throw new CliError(`--filter ${key} is neither a {${key}} path argument nor a declared --param`);\n\n const body = toml.endsWith(\"\\n\") ? toml : toml + \"\\n\";\n return body + \"\\n\" + renderRoute(spec);\n}\n\n// ── commands ────────────────────────────────────────────────────────────────\n\nfunction readJsonFile(file: string): JsonObject {\n if (!fs.existsSync(file)) throw new CliError(`${file} does not exist; run \\`gateway worlds schema init\\` first`, 1);\n let parsed: unknown;\n try {\n parsed = JSON.parse(fs.readFileSync(file, \"utf8\"));\n } catch (err) {\n throw new CliError(`${file} is not valid JSON: ${(err as Error).message}`, 1);\n }\n if (!isObject(parsed)) throw new CliError(`${file} must hold a JSON object`, 1);\n return parsed;\n}\n\nfunction declaredEntities(dir: string): string[] | undefined {\n const file = path.join(dir, \"schema\", \"world.json\");\n if (!fs.existsSync(file)) return undefined;\n const gateway = readJsonFile(file)[\"x-gateway\"];\n return isObject(gateway) && isObject(gateway.entities) ? Object.keys(gateway.entities) : [];\n}\n\nfunction parsePairs(values: string[], flag: string): Record<string, string> {\n const out: Record<string, string> = {};\n for (const item of values) {\n const eq = item.indexOf(\"=\");\n if (eq === -1) throw new CliError(`--${flag} looks like name=value, got ${JSON.stringify(item)}`);\n out[item.slice(0, eq).trim()] = item.slice(eq + 1).trim();\n }\n return out;\n}\n\nexport function registerScaffoldCommands(worlds: CommandGroup): void {\n const schema = worlds.group(\n \"schema\",\n \"Compile and check gateway-world/1 contracts (the runtime runs on the platform).\",\n );\n schema\n .group(\"entity\", \"Declare entities in schema/world.json without hand-editing the catalog.\")\n .command({\n name: \"add\",\n help: \"Declare one entity in schema/world.json: its payload, primary key, unique keys and relationships.\",\n positionals: [\n { name: \"path\", help: \"World directory holding schema/world.json\" },\n { name: \"entity\", help: \"Entity name, e.g. crm_accounts\" },\n ],\n flags: [\n { name: \"ref\", help: \"Payload is an existing $defs entry: --ref Account.\" },\n { name: \"fields\", help: \"Write a closed object def and reference it: --fields id:string,name:string,archived:boolean?\" },\n { name: \"schema\", help: \"Inline JSON Schema for the payload (a JSON string).\" },\n { name: \"key\", help: \"Primary-key field; repeat for a composite key.\", short: \"k\", repeat: true },\n { name: \"unique\", help: \"Unique key as field[,field]; repeatable.\", repeat: true },\n {\n name: \"relationship\",\n help: \"field[,field]->target_entity; repeatable. on_delete is always restrict.\",\n repeat: true,\n },\n ],\n notes:\n \"Exactly one of --ref, --fields or --schema. The file is rewritten with two-space indentation;\\n\" +\n \"run `gateway worlds schema check <path>` afterwards for the full contract check.\",\n run: async (args, ctx) => {\n const dir = path.resolve(args.positionals[0]!);\n const file = path.join(dir, \"schema\", \"world.json\");\n const root = readJsonFile(file);\n let inline: JsonObject | undefined;\n const schemaFlag = arg.str(args, \"schema\");\n if (schemaFlag !== undefined) {\n let parsed: unknown;\n try {\n parsed = JSON.parse(schemaFlag);\n } catch (err) {\n throw new CliError(`--schema is not valid JSON: ${(err as Error).message}`);\n }\n if (!isObject(parsed)) throw new CliError(\"--schema must be a JSON object\");\n inline = parsed;\n }\n const name = args.positionals[1]!;\n const { document, declaration, def } = addEntity(root, {\n name,\n ref: arg.str(args, \"ref\"),\n fields: arg.str(args, \"fields\"),\n schema: inline,\n primaryKey: arg.list(args, \"key\"),\n unique: arg.list(args, \"unique\").map((u) => u.split(\",\").map((f) => f.trim()).filter(Boolean)),\n relationships: arg.list(args, \"relationship\").map(parseRelationship),\n });\n fs.writeFileSync(file, JSON.stringify(document, null, 2) + \"\\n\");\n const out: JsonObject = { status: \"ok\", entity: name, declaration, file: path.relative(process.cwd(), file) || file };\n if (def) out.def = def;\n ctx.stdout(JSON.stringify(out, null, 2));\n },\n });\n\n const connector = worlds.group(\n \"connector\",\n \"Vendor connections: validate, capture, conform, ingest, publish, clone.\",\n );\n connector\n .group(\"route\", \"Declare operations in connector.toml without hand-editing the spec.\")\n .command({\n name: \"add\",\n help: \"Append one [[operations]] entry to connector.toml.\",\n positionals: [\n { name: \"path\", help: \"World directory holding connector.toml\" },\n { name: \"name\", help: \"Operation name, e.g. list_users\" },\n ],\n flags: [\n { name: \"method\", help: \"HTTP method.\", short: \"X\", default: \"GET\" },\n { name: \"path\", help: \"Vendor path under base_url; {arg} segments become path arguments.\", short: \"p\" },\n { name: \"param\", help: \"Declared query parameter; repeatable.\", repeat: true },\n { name: \"entity\", help: \"Entity the rows seed and the route answers from (from schema/world.json).\" },\n { name: \"results\", help: \"Dotted path to the row array in the vendor body; empty when the body is the row.\" },\n { name: \"action\", help: \"read (default), create, update, delete or handler.\" },\n { name: \"status\", help: \"2xx the vendor answers (201 for create, 204 for delete by default).\" },\n { name: \"single\", help: \"Answer the row itself instead of an envelope.\", boolean: true },\n { name: \"filter\", help: \"arg=row_field selecting rows by a path argument or --param; repeatable.\", repeat: true },\n { name: \"body\", help: \"row_field=request.body.path for create/update; repeatable.\", repeat: true },\n { name: \"handler\", help: \"Function in api/handlers.py (with --action handler).\" },\n ],\n notes:\n \"Existing text is untouched; the block is appended. --entity must already be declared in\\n\" +\n \"schema/world.json (`gateway worlds schema entity add`). Then `gateway worlds connector validate <path>`.\",\n run: async (args, ctx) => {\n const dir = path.resolve(args.positionals[0]!);\n const file = path.join(dir, \"connector.toml\");\n if (!fs.existsSync(file)) throw new CliError(`${dir} holds no connector.toml`, 1);\n const routePath = arg.str(args, \"path\");\n if (routePath === undefined) throw new CliError(\"--path is required, e.g. --path /users\");\n const spec: RouteSpec = {\n name: args.positionals[1]!,\n method: (arg.str(args, \"method\") ?? \"GET\").toUpperCase(),\n path: routePath,\n params: arg.list(args, \"param\"),\n entity: arg.str(args, \"entity\"),\n results: arg.str(args, \"results\"),\n api: {\n action: arg.str(args, \"action\"),\n status: arg.int(args, \"status\"),\n single: arg.bool(args, \"single\"),\n filter: parsePairs(arg.list(args, \"filter\"), \"filter\"),\n body: parsePairs(arg.list(args, \"body\"), \"body\"),\n handler: arg.str(args, \"handler\"),\n },\n };\n const updated = addRoute(fs.readFileSync(file, \"utf8\"), spec, declaredEntities(dir));\n fs.writeFileSync(file, updated);\n ctx.stdout(\n JSON.stringify(\n { status: \"ok\", operation: spec.name, method: spec.method, path: spec.path, entity: spec.entity ?? null, file: path.relative(process.cwd(), file) || file },\n null,\n 2,\n ),\n );\n },\n });\n}\n","import type { CommandGroup } from \"../router\";\nimport { registerSchemaCommands } from \"./schema\";\nimport { registerConnectorCommands } from \"./connector\";\nimport { registerRunCommands } from \"./run\";\nimport { registerServeCommand } from \"./serve\";\nimport { registerTestCommand } from \"./test\";\nimport { registerScaffoldCommands } from \"./scaffold\";\n\nexport {\n importLocalWorldData,\n checkLocalWorldData,\n showLocalWorldData,\n} from \"./data\";\nexport {\n readWorldFiles,\n writeWorldFiles,\n runtime,\n BridgeRejected,\n formatBridgeError,\n} from \"./client\";\n\n/**\n * Runtime-backed commands: the schema runtime (compiler, store, connector\n * capture/ingest/conform, describe, import-data) is Python and runs on the\n * platform behind `POST /api/public/worlds/runtime`. These commands send a\n * world directory up and write the answer back:\n *\n * worlds schema templates | init | compile | check | describe | api-bundle (Python-only note)\n * worlds schema entity add local: declare one entity in schema/world.json\n * worlds connector validate | capture (--remote) | conform | ingest\n * worlds connector route add local: append one [[operations]] to connector.toml\n * worlds run | ci a TypeScript agent against hosted sessions\n * worlds serve Python-only locally; opens a hosted api-surface session instead\n *\n * `worlds data import|show` are registered by the platform track and call\n * `importLocalWorldData` / `showLocalWorldData` for a local directory.\n */\nexport function registerRuntimeCommands(root: CommandGroup): void {\n const worlds = root.group(\"worlds\", \"Build, seed, serve and run worlds.\");\n registerSchemaCommands(\n worlds.group(\n \"schema\",\n \"Compile and check gateway-world/1 contracts (the runtime runs on the platform).\",\n ),\n );\n registerConnectorCommands(\n worlds.group(\n \"connector\",\n \"Vendor connections: validate, capture, conform, ingest, publish, clone.\",\n ),\n );\n registerScaffoldCommands(worlds);\n registerRunCommands(worlds);\n registerServeCommand(worlds);\n registerTestCommand(worlds);\n}\n","#!/usr/bin/env node\n/**\n * The `gateway` CLI — the TypeScript port of the Python CLI, group for group:\n * auth, secret, agent, run, dataset, bench, worlds (session, schema,\n * connector, data, skill, run, ci, serve), environment, release. The tree\n * lives in src/cli/main.ts; each group in src/cli/platform/* (platform API)\n * or src/cli/runtime/* (the schema runtime, which runs on the platform).\n */\nimport { main } from \"./cli/main\";\n\n// Set the exit code and let the event loop drain rather than calling\n// process.exit: a piped stdout is asynchronous, and exiting the moment the\n// command returns truncated anything past the first 64 KiB (`describe --json`\n// of a real world, a long `session export`) for whoever was reading the pipe.\nmain().then(\n (code) => {\n process.exitCode = code;\n },\n (error) => {\n process.stderr.write((error instanceof Error ? error.message : String(error)) + \"\\n\");\n process.exitCode = 1;\n },\n);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAoFO,SAAS,UAAU,MAAmB,MAAwB;AACnE,QAAM,YAAY,KAAK,SAAS,CAAC;AACjC,QAAM,SAAS,oBAAI,IAAsB;AACzC,aAAW,KAAK,WAAW;AACzB,WAAO,IAAI,EAAE,MAAM,CAAC;AACpB,QAAI,EAAE,MAAO,QAAO,IAAI,EAAE,OAAO,CAAC;AAAA,EACpC;AACA,QAAM,cAAwB,CAAC;AAC/B,QAAM,QAAyB,CAAC;AAChC,MAAI,kBAAkB;AACtB,WAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACpC,UAAMA,OAAM,KAAK,CAAC;AAClB,QAAI,mBAAmB,CAACA,KAAI,WAAW,GAAG,KAAKA,SAAQ,KAAK;AAC1D,kBAAY,KAAKA,IAAG;AACpB;AAAA,IACF;AACA,QAAIA,SAAQ,MAAM;AAChB,wBAAkB;AAClB;AAAA,IACF;AACA,UAAM,OAAOA,KAAI,QAAQ,QAAQ,EAAE;AACnC,UAAM,CAAC,SAAS,WAAW,IAAI,KAAK,SAAS,GAAG,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D,OAAK;AAAA,IACH;AAAA,IACA;AAAA,EACF;AACA,QAAM,SAAS,KAAK,MAAM,UAAU,oCAAoC;AACxE,SAAO;AAAA,IACL;AAAA,IACA;AAAA,EACF;AACA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,EACF;AACA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,EACF;AACA,SAAO,MAAM,QAAQ,8CAA8C;AACnE,OAAK;AAAA,IACH;AAAA,IACA;AAAA,EACF;AACA,OAAK,MAAM,WAAW,gBAAgB;AACtC,2BAAyB,IAAI;AAC7B,0BAAwB,IAAI;AAC5B,SAAO;AACT;AAEA,eAAsB,KAAK,OAAO,QAAQ,KAAK,MAAM,CAAC,GAAoB;AACxE,QAAM,YAAY,YAAY;AAC5B,UAAM,SAAmB,CAAC;AAC1B,qBAAiB,SAAS,QAAQ,MAAO,QAAO,KAAK,KAAe;AACpE,WAAO,OAAO,OAAO,MAAM,EAAE,SAAS,MAAM;AAAA,EAC9C;AACA,SAAO,SAAS,SAAS,GAAG,MAAM;AAAA,IAChC,QAAQ,CAAC,SAAS,QAAQ,OAAO,MAAM,OAAO,IAAI;AAAA,IAClD,QAAQ,CAAC,SAAS,QAAQ,OAAO,MAAM,OAAO,IAAI;AAAA,IAClD,OAAO;AAAA,IACP,aAAa,MAAM,QAAQ;AAAA,EAC7B,CAAC;AACH;;;AoCzCA,KAAK,EAAE;AAAA,EACL,CAAC,SAAS;AACR,YAAQ,WAAW;AAAA,EACrB;AAAA,EACA,CAAC,UAAU;AACT,YAAQ,OAAO,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,KAAK,IAAI;AACpF,YAAQ,WAAW;AAAA,EACrB;AACF;","names":["arg","path","lines","fs","path","resolve","fs","path","walk","path","query","resolve","sleep","openWorld","sleep","api","path","summary","timeoutMs","pollMs","query","fs","path","walk","pad","SKIP_DIRS","resolve","source","path","resolve","openSession","fs","path","BUILD_OUTPUT","fs","resolve","path","fs","os","path","row","id","stepSummary","fs","path","fs","path","relative","source","relative","files","source","fs","os","path","fs","path","createHash","fs","resolve","sleep","createHash","isObject","createHash","table","createHash","fs","refuse","path","isObject","rowObject","jsonlRows","summary","isObject","refuse","rowObject","path","createHash","fs","path","digest","fs","path","table","rest","table","redact","source","summary","resolve","showLocalWorldData","credentialsForRuntime","creds","status","importLocalWorldData","checkLocalWorldData","BridgeRejected","fs","path","fs","getRun","dispatch","failed","TERMINAL_STATES","sortedJson","fs","fs","MESSAGE_FLAG","pairs","EXPORT_PAGE","timeoutMs","fs","isObject","push","stamp","fs","path","relative","failed","fs","path","HOST_FLAG","fs","path","HOST_FLAG","sleep","resolveEnvironmentId","relative","manifestPath","registerConnectorCommands","summary","fs","path","HOST_FLAG","registerRunCommands","summary","stepSummary","fs","path","scenario","fs","path","creds","scenario","report","out","fs","path","isObject","pairs","api","declaredEntities","registerConnectorCommands","registerRunCommands"]}