@withgateway/sdk 0.9.1 → 0.9.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/dist/agents/index.d.mts +12 -4
  2. package/dist/agents/index.d.ts +12 -4
  3. package/dist/agents/index.js +30 -0
  4. package/dist/agents/index.js.map +1 -1
  5. package/dist/agents/index.mjs +30 -0
  6. package/dist/agents/index.mjs.map +1 -1
  7. package/dist/cli.js +2291 -945
  8. package/dist/cli.js.map +1 -1
  9. package/dist/cli.mjs +2290 -944
  10. package/dist/cli.mjs.map +1 -1
  11. package/dist/files/index.js.map +1 -1
  12. package/dist/files/index.mjs.map +1 -1
  13. package/dist/index.js +325 -184
  14. package/dist/index.js.map +1 -1
  15. package/dist/index.mjs +324 -183
  16. package/dist/index.mjs.map +1 -1
  17. package/dist/traces/index.js.map +1 -1
  18. package/dist/traces/index.mjs.map +1 -1
  19. package/dist/tracing/index.js +1 -1
  20. package/dist/tracing/index.js.map +1 -1
  21. package/dist/tracing/index.mjs +1 -1
  22. package/dist/tracing/index.mjs.map +1 -1
  23. package/dist/worlds/index.d.mts +3 -1
  24. package/dist/worlds/index.d.ts +3 -1
  25. package/dist/worlds/index.js +178 -67
  26. package/dist/worlds/index.js.map +1 -1
  27. package/dist/worlds/index.mjs +177 -66
  28. package/dist/worlds/index.mjs.map +1 -1
  29. package/package.json +1 -1
  30. package/runtime/gatewaysdk/environment/bundle_manifest.py +297 -9
  31. package/runtime/gatewaysdk/environment/factory_documents.py +670 -0
  32. package/runtime/gatewaysdk/environment/factory_rules.py +973 -0
  33. package/runtime/gatewaysdk/environment/factory_shapes.py +253 -0
  34. package/runtime/gatewaysdk/environment/factory_spine.py +1155 -0
  35. package/runtime/gatewaysdk/environment/factory_spine_shapes.py +480 -0
  36. package/runtime/gatewaysdk/environment/schema/admission.py +61 -59
  37. package/runtime/gatewaysdk/environment/schema/cast.py +133 -67
  38. package/runtime/gatewaysdk/environment/schema/compiler.py +16 -17
  39. package/runtime/gatewaysdk/environment/schema/handler_errors.py +58 -4
  40. package/runtime/gatewaysdk/environment/schema/host.py +21 -2
  41. package/runtime/gatewaysdk/environment/schema/host_control.py +3 -1
  42. package/runtime/gatewaysdk/environment/schema/host_loops.py +27 -4
  43. package/runtime/gatewaysdk/environment/schema/host_metrics.py +69 -0
  44. package/runtime/gatewaysdk/environment/schema/host_requests.py +21 -0
  45. package/runtime/gatewaysdk/environment/schema/host_session.py +7 -0
  46. package/runtime/gatewaysdk/environment/schema/host_versions.py +4 -0
  47. package/runtime/gatewaysdk/environment/schema/host_workers.py +172 -50
  48. package/runtime/gatewaysdk/environment/schema/ingest.py +12 -3
  49. package/runtime/gatewaysdk/environment/schema/mapping.py +1 -1
  50. package/runtime/gatewaysdk/environment/schema/measured_tests.py +187 -0
  51. package/runtime/gatewaysdk/environment/schema/platform.py +57 -3
  52. package/runtime/gatewaysdk/environment/schema/platform_query.py +4 -3
  53. package/runtime/gatewaysdk/environment/schema/platform_templates.py +105 -17
  54. package/runtime/gatewaysdk/environment/schema/process_memory.py +76 -0
  55. package/runtime/gatewaysdk/environment/schema/redaction.py +13 -0
  56. package/runtime/gatewaysdk/environment/schema/runtime.py +14 -0
  57. package/runtime/gatewaysdk/environment/schema/scaffold.py +21 -4
  58. package/runtime/gatewaysdk/environment/schema/shape_catalog.py +493 -0
  59. package/runtime/gatewaysdk/environment/schema/shape_declarations.py +219 -0
  60. package/runtime/gatewaysdk/environment/schema/skill.py +1 -0
  61. package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/SKILL.md +1 -0
  62. package/runtime/gatewaysdk/environment/schema/skills/factory-orchestrator/SKILL.md +147 -0
  63. package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/ROWS.md +5 -1
  64. package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/SKILL.md +4 -4
  65. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/SKILL.md +2 -2
  66. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/cli-mcp-map.md +1 -0
  67. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/shape-catalog.md +59 -0
  68. package/runtime/gatewaysdk/environment/schema/validation.py +14 -0
  69. package/runtime/gatewaysdk/environment/schema/worker.py +7 -4
  70. package/runtime/gatewaysdk/environment/schema/worker_key.py +38 -0
  71. package/runtime/gatewaysdk/environment/schema/worker_peaks.py +38 -0
  72. package/runtime/gatewaysdk/environment/schema/worker_watch.py +50 -0
  73. package/runtime/gatewaysdk/environment/schema/workers.py +237 -68
  74. package/runtime/gatewaysdk/environment/schema/world_host.py +56 -62
  75. package/runtime/gatewaysdk/environment/schema/world_tests.py +3 -1
  76. package/skills/connector-schema-authoring/SKILL.md +1 -0
  77. package/skills/connector-schema-authoring/connector-worlds.md +1 -0
  78. package/skills/connector-schema-authoring/world-schema.md +7 -0
  79. package/skills/factory-orchestrator/SKILL.md +147 -0
  80. package/skills/world-data-ingestion/ROWS.md +5 -1
  81. package/skills/world-data-ingestion/SKILL.md +4 -4
  82. package/skills/worlds-getting-started/SKILL.md +2 -2
  83. package/skills/worlds-getting-started/references/cli-mcp-map.md +1 -0
  84. package/skills/worlds-getting-started/references/shape-catalog.md +59 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/agents/index.ts","../../src/worlds/apiError.ts","../../src/agents/patch.ts","../../src/agents/agent.ts","../../src/agents/definition.ts","../../src/worlds/personalToken.ts","../../src/worlds/transport.ts","../../src/agents/segment.ts","../../src/agents/agents.ts","../../src/worlds/platformEndpoint.ts","../../src/agents/sse.ts","../../src/agents/run.ts","../../src/agents/threads.ts","../../src/agents/gateway.ts","../../src/agents/tools.ts"],"sourcesContent":["export { Agent, AgentThreads, AgentTools, AgentVersionConflictError } from \"./agent\";\nexport type { AgentRunInput, EditOptions } from \"./agent\";\nexport { AgentDefinition, AgentDefinitionError, defineAgent } from \"./definition\";\nexport { ApiError } from \"../worlds/apiError\";\nexport { PlatformTransport, UnreachableError } from \"../worlds/transport\";\nexport type { AgentDefinitionInput, AgentDefinitionIssue, AgentDefinitionIssueCode } from \"./definition\";\nexport { Agents, AgentVersionNotFoundError } from \"./agents\";\nexport type { PushOptions } from \"./agents\";\nexport { Gateway } from \"./gateway\";\nexport type { GatewayOptions } from \"./gateway\";\nexport { AgentRun, ReconnectPolicy, SYSTEM_CLOCK } from \"./run\";\nexport type { AgentRunOptions, RequestOptions, RunClock, RunEventsOptions } from \"./run\";\nexport { EventStreamError, SseLimits, SseParser } from \"./sse\";\nexport type { EventStreamErrorCode, SseMessage } from \"./sse\";\nexport { AgentPatch } from \"./patch\";\nexport type { AgentPatchJSON, AgentUpdate } from \"./patch\";\nexport { Thread, Threads } from \"./threads\";\nexport { AGENT_EFFORTS, AGENT_MODELS, TOOL_SERVERS, tools } from \"./tools\";\nexport type { AgentEffort, AgentModel, AgentToolInput, ToolName, ToolServer, TypedGrant } from \"./tools\";\nexport type { CreateThreadOptions, SendOptions } from \"./threads\";\nexport type {\n AgentAttribution,\n AgentBuildRecord,\n AgentDefinitionSpec,\n AgentDeployment,\n AgentEditResult,\n AgentVersion,\n AgentVersionEntry,\n LiveAgentRecord,\n Run,\n RunAction,\n RunError,\n RunErrorCode,\n RunEvent,\n RunEventType,\n RunStatus,\n ThreadAutonomy,\n ThreadRecord,\n ThreadWarning,\n ToolGrant,\n} from \"./types\";\n","/** A non-2xx platform answer: act on `status` or the stable public `code` (never the server's error class) rather than parsing the message. */\nexport class ApiError extends Error {\n public readonly code: string | null;\n\n constructor(\n public readonly status: number,\n method: string,\n path: string,\n public readonly text: string,\n ) {\n const parsed = parseErrorBody(text, status);\n super(`${method} ${path} -> ${status}: ${parsed.detail}`);\n this.name = \"ApiError\";\n this.code = parsed.code;\n }\n}\n\nconst DETAIL_LIMIT = 600;\n\nconst EDGE_ANSWERS: Readonly<Record<number, string>> = {\n 502: \"Bad Gateway from the load balancer in front of the platform, not the platform's answer: the web server dropped the connection or restarted mid-request. Retry; if it repeats, the platform is restarting or overloaded.\",\n 503: \"Service Unavailable from the load balancer in front of the platform, not the platform's answer: no web server was ready to take the request (a deploy or a restart). Retry in a minute.\",\n 504: \"Gateway Time-out from the load balancer in front of the platform, not the platform's answer: the request sent nothing back within the load balancer's idle timeout (60 s unless the deployment raises it: Helm ingress.idleTimeoutSeconds) and was cut there, though the platform may still be running it. Check what it changed before you retry.\",\n};\nconst EDGE_FAILURE =\n \"The platform failed without its JSON error body: a proxy in front of it answered, or the server stopped before its error handler ran. Retry; if it repeats, report the request and the time.\";\nconst EDGE_PAGE =\n \"An HTML page answered instead of the platform's JSON: a proxy in front of the platform, or the configured host is not the platform.\";\n\nfunction edgeAnswer(text: string, status: number | undefined): string | null {\n if (status !== undefined && status >= 500) return EDGE_ANSWERS[status] ?? EDGE_FAILURE;\n return /^\\s*</.test(text) ? EDGE_PAGE : null;\n}\n\n/** The detail and stable code of a non-2xx body; an HTML page or a bare 5xx is named, never printed.\n * Python twin: `gatewaysdk.api_errors.error_detail`; both run `conformance/platform-error-bodies.json`. */\nexport function parseErrorBody(text: string, status?: number): { detail: string; code: string | null } {\n const raw = { detail: text.slice(0, DETAIL_LIMIT), code: null };\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return { detail: (edgeAnswer(text, status) ?? text).slice(0, DETAIL_LIMIT), code: null };\n }\n if (parsed === null || typeof parsed !== \"object\") return raw;\n const { message, code, error } = parsed as { message?: unknown; code?: unknown; error?: unknown };\n const stableCode = typeof code === \"string\" ? code : null;\n if (typeof message !== \"string\") return { ...raw, code: stableCode };\n const fields = invalidFields(error);\n const said = fields ? `${message}: ${fields}` : message;\n if (stableCode === null) return { detail: said.slice(0, DETAIL_LIMIT), code: null };\n return {\n detail: `${said} (${stableCode})`.slice(0, DETAIL_LIMIT),\n code: stableCode,\n };\n}\n\n/** `<path>: <message>` per issue of a validation error; empty when it carries none. Python twin: `gatewaysdk.api_errors.invalid_fields`. */\nexport function invalidFields(error: unknown): string {\n const issues = Array.isArray(error) ? error : [];\n return issues\n .filter((issue): issue is { path?: unknown; message: string } =>\n issue !== null && typeof issue === \"object\" && typeof (issue as { message?: unknown }).message === \"string\",\n )\n .map((issue) => {\n const path = Array.isArray(issue.path) ? issue.path.map(String).join(\".\") : \"\";\n return path ? `${path}: ${issue.message}` : issue.message;\n })\n .join(\"; \");\n}\n","import type { AgentEffort, AgentModel, AgentToolInput } from \"./tools\";\nimport type { ToolGrant } from \"./types\";\n\n/** The fields `agent.update` changes; `effort: null` removes the effort. The name is the agent's identity and never changes. */\nexport type AgentUpdate = {\n instructions?: string;\n model?: AgentModel;\n effort?: AgentEffort | null;\n maxTurns?: number;\n};\n\nexport type AgentPatchJSON = {\n set?: Record<string, unknown>;\n attach?: ToolGrant[];\n detach?: string[];\n};\n\nconst list = <T>(value: T | readonly T[]): readonly T[] =>\n Array.isArray(value) ? (value as readonly T[]) : [value as T];\n\nfunction grantOf(input: AgentToolInput | ToolGrant): ToolGrant {\n if (typeof input === \"string\") return { server: input };\n return input.only ? { server: input.server, only: [...input.only].sort() } : { server: input.server };\n}\n\n/**\n * One edit of a live agent as the platform takes it (`patch` of `POST …/definitions/{name}/versions`). The platform\n * applies it to the version `production` runs and validates the result; the SDK only shapes it. Pinned to\n * `gatewaysdk/fixtures/agents/patch-vectors.json`.\n */\nexport class AgentPatch {\n private constructor(private readonly json: AgentPatchJSON) {}\n\n static update(fields: AgentUpdate): AgentPatch {\n const set = Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== undefined));\n return new AgentPatch({ set });\n }\n\n static attach(grants: AgentToolInput | readonly AgentToolInput[]): AgentPatch {\n return new AgentPatch({ attach: list(grants).map(grantOf) });\n }\n\n static detach(servers: string | readonly string[]): AgentPatch {\n return new AgentPatch({ detach: [...list(servers)] });\n }\n\n toJSON(): AgentPatchJSON {\n return structuredClone(this.json);\n }\n}\n","import { ApiError } from \"../worlds/apiError\";\nimport type { PlatformMethod } from \"../worlds/transport\";\nimport type { Agents } from \"./agents\";\nimport { AgentPatch, type AgentUpdate } from \"./patch\";\nimport type { AgentRun } from \"./run\";\nimport type { CreateThreadOptions, Thread, Threads } from \"./threads\";\nimport type { AgentToolInput } from \"./tools\";\nimport type { AgentDefinitionSpec, AgentEditResult, AgentVersionEntry, LiveAgentRecord } from \"./types\";\n\n/** An edit or rollback made from a version that is no longer the live one: nothing was written. `refresh()` the agent, then edit again. */\nexport class AgentVersionConflictError extends ApiError {\n readonly currentVersionId: string | null;\n\n constructor(status: number, method: PlatformMethod, path: string, text: string) {\n super(status, method, path, text);\n this.name = \"AgentVersionConflictError\";\n this.currentVersionId = currentVersionOf(text);\n }\n}\n\nfunction currentVersionOf(text: string): string | null {\n try {\n const id = (JSON.parse(text) as { currentVersionId?: unknown }).currentVersionId;\n return typeof id === \"string\" ? id : null;\n } catch {\n return null;\n }\n}\n\n/** `deploy` (default true) moves `production` to the version the edit writes; `false` stages it. */\nexport type EditOptions = { deploy?: boolean };\n\nexport type AgentRunInput = Omit<CreateThreadOptions, \"agent\"> & { version?: string };\n\n/** The agent's tools: each attach or detach is a new version, live unless `deploy: false`. */\nexport class AgentTools {\n constructor(private readonly agent: Agent) {}\n\n /** Grant servers: one already attached keeps its place and takes the new grant. */\n attach(grants: AgentToolInput | readonly AgentToolInput[], options: EditOptions = {}): Promise<AgentEditResult> {\n return this.agent.edit(AgentPatch.attach(grants), options);\n }\n\n /** Remove servers; one that is not attached changes nothing. */\n detach(servers: string | readonly string[], options: EditOptions = {}): Promise<AgentEditResult> {\n return this.agent.edit(AgentPatch.detach(servers), options);\n }\n}\n\n/** Threads with this agent. */\nexport class AgentThreads {\n constructor(\n private readonly threads: Threads,\n private readonly name: string,\n ) {}\n\n create(options: Omit<CreateThreadOptions, \"agent\"> = {}): Promise<Thread> {\n return this.threads.create({ ...options, agent: this.name });\n }\n}\n\n/**\n * A live agent: every change is a call on it, and each one is an immutable version the platform keeps. An edit carries\n * the version this handle holds, so a change someone else made in between is refused (`AgentVersionConflictError`)\n * rather than overwritten. A run keeps the version it was sent on.\n */\nexport class Agent {\n readonly #agents: Agents;\n #record: LiveAgentRecord;\n readonly tools: AgentTools;\n readonly threads: AgentThreads;\n\n constructor(agents: Agents, record: LiveAgentRecord, threads: Threads) {\n this.#agents = agents;\n this.#record = liveOf(record);\n this.tools = new AgentTools(this);\n this.threads = new AgentThreads(threads, record.name);\n }\n\n get name(): string {\n return this.#record.name;\n }\n\n /** The version edits apply to: the one `production` runs (else, never deployed, the newest). */\n get versionId(): string {\n return this.#record.versionId;\n }\n\n get version(): number {\n return this.#record.version;\n }\n\n get buildHash(): string {\n return this.#record.buildHash;\n }\n\n get deployed(): boolean {\n return this.#record.deployed;\n }\n\n get definition(): Readonly<AgentDefinitionSpec> {\n return structuredClone(this.#record.definition);\n }\n\n /** Change fields: a new version, live unless `deploy: false`; a change to the values it already has writes nothing. */\n update(fields: AgentUpdate, options: EditOptions = {}): Promise<AgentEditResult> {\n return this.edit(AgentPatch.update(fields), options);\n }\n\n /** Apply one patch made of `AgentPatch.update`, `.attach` or `.detach`. */\n async edit(patch: AgentPatch, options: EditOptions = {}): Promise<AgentEditResult> {\n const result = await this.#agents.edit(this.name, patch, { ...options, from: this.versionId });\n if (result.deployed || !this.deployed) this.#record = liveOf(result);\n return result;\n }\n\n /** Move `production` to one of this agent's versions (an earlier one, or one staged with `deploy: false`); `force` crosses a breaking tool change. */\n async rollback(versionId: string, options: { force?: boolean } = {}): Promise<LiveAgentRecord> {\n this.#record = liveOf(await this.#agents.rollback(this.name, versionId, { ...options, from: this.versionId }));\n return this.toJSON();\n }\n\n /** Every version, newest first, with whether it is live and its changes against the version before it. */\n versions(): Promise<AgentVersionEntry[]> {\n return this.#agents.history(this.name);\n }\n\n /** Read the live version again, after a conflict or someone else's change. */\n async refresh(): Promise<this> {\n this.#record = liveOf(await this.#agents.live(this.name));\n return this;\n }\n\n /** Start a thread with this agent and send it `input`: the run uses the version `production` runs now (or `version`). */\n async run(input: string, options: AgentRunInput = {}): Promise<AgentRun> {\n const { version, ...thread } = options;\n return (await this.threads.create(thread)).send(input, { version });\n }\n\n toJSON(): LiveAgentRecord {\n return { ...this.#record, definition: this.definition };\n }\n}\n\nfunction liveOf(record: LiveAgentRecord): LiveAgentRecord {\n const { name, versionId, version, buildHash, deployed, definition } = record;\n return { name, versionId, version, buildHash, deployed, definition };\n}\n","import type { AgentEffort, AgentModel, AgentToolInput } from \"./tools\";\nimport type { AgentDefinitionSpec, ToolGrant } from \"./types\";\n\nconst NAME_PATTERN = /^[a-z0-9][a-z0-9-]{0,62}$/;\nconst DEFAULT_MODEL = \"claude-opus-5\";\nconst DEFAULT_MAX_TURNS = 50;\nconst INSTRUCTIONS = { min: 1, max: 65_536 };\nconst MAX_TURNS = { min: 1, max: 200 };\nconst DEFINITION_FIELDS: ReadonlySet<string> = new Set([\n \"name\",\n \"instructions\",\n \"model\",\n \"effort\",\n \"maxTurns\",\n \"tools\",\n]);\nconst GRANT_FIELDS: ReadonlySet<string> = new Set([\"server\", \"only\"]);\n\ntype Path = (string | number)[];\ntype Bounds = { min: number; max: number };\n\nexport type AgentDefinitionIssueCode =\n | \"invalid_type\"\n | \"invalid_name\"\n | \"too_small\"\n | \"too_large\"\n | \"unknown_field\"\n | \"duplicate_tool_server\"\n | \"duplicate_tool\";\n\n/** One broken rule of a definition: where (`path` into the normalized definition), which rule (`code`), and why. */\nexport type AgentDefinitionIssue = { path: Path; code: AgentDefinitionIssueCode; message: string };\n\n/** What `defineAgent` and `agents.create` take. A tool is a server name (`\"sandbox\"`: all of its tools) or a grant from `tools` (`tools.web({ only: [\"fetch_url\"] })`). */\nexport type AgentDefinitionInput = {\n name: string;\n instructions: string;\n model?: AgentModel;\n effort?: AgentEffort;\n maxTurns?: number;\n tools?: readonly AgentToolInput[];\n};\n\n/** A definition `defineAgent` refused before anything was sent: every broken rule, each with its path and code. The platform checks the rest (model, effort, tool servers and names). */\nexport class AgentDefinitionError extends Error {\n constructor(readonly issues: readonly AgentDefinitionIssue[]) {\n super(`Invalid agent definition: ${issues.map((issue) => `${pathText(issue.path)}: ${issue.message}`).join(\"; \")}`);\n this.name = \"AgentDefinitionError\";\n }\n}\n\ntype FrozenGrant = { readonly server: string; readonly only?: readonly string[] };\n\n/** An agent as code: frozen and normalized, so the JSON it sends is the JSON the platform hashes into the version's `buildHash`. */\nexport class AgentDefinition {\n readonly name: string;\n readonly instructions: string;\n readonly model: string;\n readonly effort: AgentEffort | undefined;\n readonly maxTurns: number;\n readonly tools: readonly FrozenGrant[];\n\n private constructor(spec: AgentDefinitionSpec) {\n this.name = spec.name;\n this.instructions = spec.instructions;\n this.model = spec.model;\n this.effort = spec.effort;\n this.maxTurns = spec.maxTurns;\n this.tools = Object.freeze(spec.tools.map(freezeGrant));\n Object.freeze(this);\n }\n\n /** Validate and normalize any value (a parsed JSON file included); throws `AgentDefinitionError` listing every broken rule. */\n static from(input: unknown): AgentDefinition {\n return new AgentDefinition(DefinitionReader.read(input));\n }\n\n /** The normalized definition: defaults filled, tool shorthands expanded, `only` sorted, `effort` present only when set. */\n toJSON(): AgentDefinitionSpec {\n return {\n name: this.name,\n instructions: this.instructions,\n model: this.model,\n ...(this.effort === undefined ? {} : { effort: this.effort }),\n maxTurns: this.maxTurns,\n tools: this.tools.map((grant) =>\n grant.only ? { server: grant.server, only: [...grant.only] } : { server: grant.server },\n ),\n };\n }\n}\n\n/** Define an agent: `model` defaults to `claude-opus-5`, `maxTurns` to 50 (1–200), `tools` to none. */\nexport function defineAgent(input: AgentDefinitionInput): AgentDefinition {\n return AgentDefinition.from(input);\n}\n\nfunction freezeGrant(grant: ToolGrant): FrozenGrant {\n const only = grant.only ? { only: Object.freeze([...grant.only]) } : {};\n return Object.freeze({ server: grant.server, ...only });\n}\n\nfunction pathText(path: Path): string {\n return path.length === 0 ? \"definition\" : path.join(\".\");\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isString(value: string | null): value is string {\n return value !== null;\n}\n\nclass DefinitionReader {\n readonly #issues: AgentDefinitionIssue[] = [];\n\n static read(input: unknown): AgentDefinitionSpec {\n const reader = new DefinitionReader();\n const spec = reader.spec(input);\n if (!spec || reader.#issues.length > 0) throw new AgentDefinitionError(reader.#issues);\n return spec;\n }\n\n private spec(input: unknown): AgentDefinitionSpec | null {\n if (!isRecord(input)) return this.refuse([], \"invalid_type\", \"a definition is an object\", null);\n this.unknownFields(input, DEFINITION_FIELDS, []);\n const effort = this.optionalString(input.effort, [\"effort\"]);\n return {\n name: this.name(input.name),\n instructions: this.instructions(input.instructions),\n model: this.optionalString(input.model, [\"model\"]) ?? DEFAULT_MODEL,\n ...(effort === undefined ? {} : { effort: effort as AgentEffort }),\n maxTurns: this.maxTurns(input.maxTurns),\n tools: this.tools(input.tools),\n };\n }\n\n private name(value: unknown): string {\n const name = this.string(value, [\"name\"]);\n if (name !== null && !NAME_PATTERN.test(name))\n this.issue([\"name\"], \"invalid_name\", \"lowercase letters, digits and dashes, 1-63 long, not starting with a dash\");\n return name ?? \"\";\n }\n\n private instructions(value: unknown): string {\n const instructions = this.string(value, [\"instructions\"]);\n if (instructions !== null) this.bounded(instructions.length, INSTRUCTIONS, [\"instructions\"], \"characters\");\n return instructions ?? \"\";\n }\n\n private maxTurns(value: unknown): number {\n if (value === undefined) return DEFAULT_MAX_TURNS;\n if (typeof value !== \"number\" || !Number.isInteger(value))\n return this.refuse([\"maxTurns\"], \"invalid_type\", \"a whole number\", DEFAULT_MAX_TURNS);\n this.bounded(value, MAX_TURNS, [\"maxTurns\"], \"turns\");\n return value;\n }\n\n private tools(value: unknown): ToolGrant[] {\n if (value === undefined) return [];\n if (!Array.isArray(value)) return this.refuse([\"tools\"], \"invalid_type\", \"a list of tools\", []);\n const grants = value.map((entry, index) => this.grant(entry, [\"tools\", index]));\n this.noRepeats(\n grants.map((grant) => grant?.server ?? null),\n (index) => [\"tools\", index, \"server\"],\n \"duplicate_tool_server\",\n \"this server is already granted\",\n );\n return grants.filter((grant): grant is ToolGrant => grant !== null);\n }\n\n private grant(entry: unknown, path: Path): ToolGrant | null {\n if (typeof entry === \"string\") return { server: entry };\n if (!isRecord(entry)) return this.refuse(path, \"invalid_type\", \"a server name or { server, only }\", null);\n this.unknownFields(entry, GRANT_FIELDS, path);\n const server = this.string(entry.server, [...path, \"server\"]);\n if (server === null) return null;\n return entry.only === undefined ? { server } : { server, only: this.only(entry.only, [...path, \"only\"]) };\n }\n\n private only(value: unknown, path: Path): string[] {\n if (!Array.isArray(value)) return this.refuse(path, \"invalid_type\", \"a list of tool names\", []);\n if (value.length === 0)\n this.issue(path, \"too_small\", \"names at least one tool; leave `only` out to grant the whole server\");\n const names = value.map((name, index) => this.string(name, [...path, index]));\n this.noRepeats(names, (index) => [...path, index], \"duplicate_tool\", \"this tool is already named\");\n return names.filter(isString).sort();\n }\n\n private string(value: unknown, path: Path): string | null {\n if (typeof value === \"string\") return value;\n return this.refuse(path, \"invalid_type\", \"a string\", null);\n }\n\n private optionalString(value: unknown, path: Path): string | undefined {\n if (value === undefined) return undefined;\n return this.string(value, path) ?? undefined;\n }\n\n private bounded(value: number, bounds: Bounds, path: Path, unit: string): void {\n if (value < bounds.min) this.issue(path, \"too_small\", `at least ${bounds.min} ${unit}`);\n if (value > bounds.max) this.issue(path, \"too_large\", `at most ${bounds.max} ${unit}`);\n }\n\n private unknownFields(record: Record<string, unknown>, known: ReadonlySet<string>, path: Path): void {\n for (const [key, value] of Object.entries(record)) {\n if (value !== undefined && !known.has(key))\n this.issue([...path, key], \"unknown_field\", \"not a field of an agent definition\");\n }\n }\n\n private noRepeats(\n values: (string | null)[],\n pathOf: (index: number) => Path,\n code: AgentDefinitionIssueCode,\n message: string,\n ): void {\n const seen = new Set<string>();\n values.forEach((value, index) => {\n if (value === null) return;\n if (seen.has(value)) this.issue(pathOf(index), code, message);\n seen.add(value);\n });\n }\n\n private issue(path: Path, code: AgentDefinitionIssueCode, message: string): void {\n this.#issues.push({ path, code, message });\n }\n\n private refuse<T>(path: Path, code: AgentDefinitionIssueCode, message: string, fallback: T): T {\n this.issue(path, code, message);\n return fallback;\n }\n}\n","export const TOKEN_NOT_PERSONAL =\n \"GATEWAY_TOKEN takes a personal access token: pat_ followed by letters and digits only.\";\nexport const TOKEN_NEEDS_PROJECT =\n \"GATEWAY_TOKEN acts in the project GATEWAY_PROJECT_ID names: set it to the official project's id (letters, digits, - and _).\";\nexport const TOKEN_NEEDS_HOST = \"GATEWAY_TOKEN goes only to the host GATEWAY_HOST names: set GATEWAY_HOST.\";\nexport const TOKEN_OTHER_HOST =\n \"GATEWAY_TOKEN goes only to the host GATEWAY_HOST names, and this call names another host: point the call at GATEWAY_HOST or unset GATEWAY_TOKEN.\";\nexport const TOKEN_BESIDE_KEYS =\n \"GATEWAY_TOKEN is set beside a project key (GATEWAY_PUBLIC_KEY, GATEWAY_SECRET_KEY, GATEWAY_API_KEY or a key passed in): unset one of them. Neither replaces the other.\";\nexport const TOKEN_FILING =\n \"Filing an evaluation takes your project's key pair, not GATEWAY_TOKEN: unset it (an official world runs once copied into your own project).\";\nexport const TOKEN_KEYS_ONLY =\n \"Task-run tracing exports with a project key pair (GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY), not GATEWAY_TOKEN.\";\n\nconst PERSONAL = /^pat_[A-Za-z0-9]+$/;\nconst PROJECT = /^[A-Za-z0-9_-]+$/;\nconst ENV_KEYS = [\"GATEWAY_PUBLIC_KEY\", \"GATEWAY_SECRET_KEY\", \"GATEWAY_API_KEY\"];\n\nexport type TokenRequest = { host?: string; keys?: boolean };\n\nexport class PersonalTokenRefused extends Error {}\n\nconst bare = (host: string) => host.replace(/\\/+$/, \"\");\n\nexport class PersonalToken {\n private constructor(\n readonly value: string,\n readonly project: string,\n readonly host: string,\n ) {}\n\n static fromEnv(env: NodeJS.ProcessEnv, request: TokenRequest = {}): PersonalToken | null {\n const value = env.GATEWAY_TOKEN;\n if (!value) return null;\n if (request.keys || ENV_KEYS.some((name) => env[name])) throw new PersonalTokenRefused(TOKEN_BESIDE_KEYS);\n const host = bare(env.GATEWAY_HOST ?? \"\");\n if (!host) throw new PersonalTokenRefused(TOKEN_NEEDS_HOST);\n if (request.host && bare(request.host) !== host) throw new PersonalTokenRefused(TOKEN_OTHER_HOST);\n if (!PERSONAL.test(value)) throw new PersonalTokenRefused(TOKEN_NOT_PERSONAL);\n const project = env.GATEWAY_PROJECT_ID ?? \"\";\n if (!PROJECT.test(project)) throw new PersonalTokenRefused(TOKEN_NEEDS_PROJECT);\n return new PersonalToken(value, project, host);\n }\n\n toJSON(): { project: string; host: string } {\n return { project: this.project, host: this.host };\n }\n\n [Symbol.for(\"nodejs.util.inspect.custom\")](): string {\n return `PersonalToken { project: ${this.project}, host: ${this.host} }`;\n }\n\n static scrubbed(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n return Object.fromEntries(Object.entries(env).filter(([key]) => key !== \"GATEWAY_TOKEN\"));\n }\n}\n","import { ApiError } from \"./apiError\";\nimport { type PersonalToken, PersonalTokenRefused, TOKEN_BESIDE_KEYS, TOKEN_OTHER_HOST } from \"./personalToken\";\n\nexport const PLATFORM_TIMEOUT_ENV = \"GATEWAY_TIMEOUT_MS\";\n\nexport const PLATFORM_TIMEOUT_DEFAULT_MS = 120_000;\n\nexport type PlatformEndpoint = { host: string; publicKey: string; secretKey: string; token?: PersonalToken };\n\nexport type PlatformMethod = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n\nexport type PlatformReply = { status: number; ok: boolean; text: string };\n\nexport type PlatformSendOptions = { timeoutMs?: number; retry?: RetryPolicy; signal?: AbortSignal };\n\n/** The request budget in force: `GATEWAY_TIMEOUT_MS` when set, else the default. */\nexport function platformTimeoutMs(env: NodeJS.ProcessEnv = process.env): number {\n const raw = env[PLATFORM_TIMEOUT_ENV];\n if (raw === undefined || raw === \"\") return PLATFORM_TIMEOUT_DEFAULT_MS;\n const value = Number(raw);\n if (Number.isInteger(value) && value > 0) return value;\n throw new Error(`${PLATFORM_TIMEOUT_ENV} must be a positive whole number of milliseconds, not \\`${raw}\\`.`);\n}\n\nconst CHECK_HOST = \"Check GATEWAY_HOST (or --host) points at a running platform, then retry.\";\nconst RETRY = \"Retry; if it repeats, check the network between here and the platform.\";\nconst FETCH_LIMIT = {\n reason: \"Node's fetch stopped waiting after 300 s\",\n next: \"The platform may still be running it: check what it changed before you retry.\",\n};\n\nconst CAUSES: Record<string, { reason: string; next: string }> = {\n UND_ERR_HEADERS_TIMEOUT: FETCH_LIMIT,\n UND_ERR_BODY_TIMEOUT: FETCH_LIMIT,\n ECONNREFUSED: { reason: \"connection refused\", next: CHECK_HOST },\n ENOTFOUND: { reason: \"DNS lookup failed\", next: CHECK_HOST },\n EAI_AGAIN: { reason: \"DNS lookup failed\", next: CHECK_HOST },\n ETIMEDOUT: { reason: \"connect timed out\", next: CHECK_HOST },\n UND_ERR_CONNECT_TIMEOUT: { reason: \"connect timed out\", next: CHECK_HOST },\n EHOSTUNREACH: { reason: \"host unreachable\", next: CHECK_HOST },\n ENETUNREACH: { reason: \"network unreachable\", next: RETRY },\n ECONNRESET: { reason: \"connection dropped\", next: RETRY },\n UND_ERR_SOCKET: { reason: \"connection dropped\", next: RETRY },\n EPIPE: { reason: \"connection dropped\", next: RETRY },\n};\n\nconst UNKNOWN_CAUSE = { reason: \"network error\", next: CHECK_HOST };\n\n/** Why a request got no answer, from the socket-level error undici hides under `fetch failed`. */\nexport class TransportCause {\n private constructor(\n readonly reason: string,\n readonly detail: string | null,\n readonly next: string,\n ) {}\n\n static timeout(timeoutMs: number): TransportCause {\n return new TransportCause(\n `timed out after ${timeoutMs / 1000}s`,\n null,\n `Retry; if the platform is slow, raise ${PLATFORM_TIMEOUT_ENV} (milliseconds per request).`,\n );\n }\n\n static idle(idleMs: number): TransportCause {\n return new TransportCause(\n `no data for ${idleMs / 1000}s`,\n null,\n \"The stream resumes from its last event; if it repeats, check the network between here and the platform.\",\n );\n }\n\n static of(error: unknown): TransportCause {\n const cause = error instanceof Error && error.cause instanceof Error ? error.cause : undefined;\n const code = cause && \"code\" in cause && typeof cause.code === \"string\" ? cause.code : null;\n const message = cause?.message ?? (error instanceof Error ? error.message : String(error));\n const known = (code && CAUSES[code]) || UNKNOWN_CAUSE;\n return new TransportCause(known.reason, code ? `${code}: ${message}` : message, known.next);\n }\n\n describe(): string {\n return this.detail === null ? this.reason : `${this.reason} (${this.detail})`;\n }\n}\n\nexport class UnreachableError extends Error {\n constructor(\n readonly host: string,\n readonly method: string,\n readonly route: string,\n readonly failure: TransportCause,\n ) {\n super(`${method} ${route}: no answer from ${host}: ${failure.describe()}. ${failure.next}`);\n this.name = \"UnreachableError\";\n }\n}\n\nconst sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));\n\n/**\n * Another attempt after a gateway 5xx (502, 503, 504) or no answer at all, for a request whose repeat is harmless: a\n * keyed filing step, which the platform answers with the first filing. Every other request gets one attempt (`NONE`).\n */\nexport class RetryPolicy {\n static readonly NONE = new RetryPolicy([]);\n /** A platform restart or a short edge outage: no wait starts that would end past five minutes, so a step ends\n * within the budget plus one request timeout. */\n static readonly FILING = new RetryPolicy([250, 500, 1_000, 2_000, 4_000, 8_000, 16_000, 30_000], sleep, 300_000);\n static readonly TRANSIENT_STATUSES: ReadonlySet<number> = new Set([502, 503, 504]);\n\n constructor(\n readonly delaysMs: readonly number[],\n private readonly wait: (ms: number) => Promise<void> = sleep,\n readonly budgetMs: number = Number.POSITIVE_INFINITY,\n private readonly now: () => number = Date.now,\n ) {}\n\n async run(attempt: () => Promise<PlatformReply>): Promise<PlatformReply> {\n const started = this.now();\n for (let tries = 0; ; tries += 1) {\n const outcome = await Attempt.of(attempt);\n const delayMs = this.delaysMs[tries];\n const spent = delayMs === undefined || this.now() - started + delayMs >= this.budgetMs;\n if (!outcome.transient || spent) return outcome.settle();\n await this.wait(delayMs);\n }\n }\n}\n\nclass Attempt {\n private constructor(\n private readonly reply: PlatformReply | null,\n private readonly error: unknown,\n readonly transient: boolean,\n ) {}\n\n static async of(attempt: () => Promise<PlatformReply>): Promise<Attempt> {\n try {\n const reply = await attempt();\n return new Attempt(reply, null, RetryPolicy.TRANSIENT_STATUSES.has(reply.status));\n } catch (error) {\n return new Attempt(null, error, error instanceof UnreachableError);\n }\n }\n\n settle(): PlatformReply {\n if (this.reply) return this.reply;\n throw this.error;\n }\n}\n\n/** How long an open event stream may stay silent (no event and no keepalive) before it counts as dropped. */\nexport const PLATFORM_STREAM_IDLE_MS = 60_000;\n\nexport type PlatformStreamOptions = { after?: string | null; signal?: AbortSignal; idleMs?: number };\n\nconst REFUSAL_TEXT_LIMIT = 64 * 1024;\n\n// No route the SDK calls redirects: a 3xx is answered as the refusal it is, so the key never rides a hop to any host, whatever the runtime's fetch does with Authorization.\nconst KEYED_REDIRECTS: RequestRedirect = \"manual\";\n\nexport function platformAuthorization(endpoint: PlatformEndpoint, url: string): Record<string, string> {\n const { token } = endpoint;\n if (!token)\n return { authorization: \"Basic \" + Buffer.from(`${endpoint.publicKey}:${endpoint.secretKey}`).toString(\"base64\") };\n if (endpoint.publicKey || endpoint.secretKey) throw new PersonalTokenRefused(TOKEN_BESIDE_KEYS);\n if (!url.startsWith(`${token.host}/`)) throw new PersonalTokenRefused(TOKEN_OTHER_HOST);\n return { authorization: `Bearer ${token.value}`, \"x-gateway-project\": token.project };\n}\n\n/** The one door every CLI and SDK request to the platform goes through: Basic auth with the project key, a per-request timeout, and a transport failure turned into an `UnreachableError`. */\nexport class PlatformTransport {\n readonly #endpoint: PlatformEndpoint;\n readonly #timeoutMs: number;\n\n constructor(endpoint: PlatformEndpoint, timeoutMs: number = platformTimeoutMs()) {\n this.#endpoint = endpoint;\n this.#timeoutMs = timeoutMs;\n }\n\n /** A request that legitimately takes longer (a sandbox exec, a world create) waits its own budget; every other one waits the default. */\n budget(ownMs?: number): number {\n return Math.max(ownMs ?? 0, this.#timeoutMs);\n }\n\n /** One request; the caller's `signal` aborts it in flight and throws the signal's reason, never an `UnreachableError`. */\n async send(\n method: PlatformMethod,\n route: string,\n body?: unknown,\n opts: PlatformSendOptions = {},\n ): Promise<PlatformReply> {\n const timeoutMs = this.budget(opts.timeoutMs);\n return (opts.retry ?? RetryPolicy.NONE).run(() => this.once(method, route, body, timeoutMs, opts.signal));\n }\n\n /** `send`, then the 2xx body as JSON; any other answer throws `ApiError` with its status and stable `code`. */\n async json<T>(method: PlatformMethod, route: string, body?: unknown, opts: PlatformSendOptions = {}): Promise<T> {\n const reply = await this.send(method, route, body, opts);\n if (!reply.ok) throw new ApiError(reply.status, method, route, reply.text);\n return JSON.parse(reply.text) as T;\n }\n\n /** The streaming twin of `send` for a `GET` event stream: nothing is buffered, `after` travels as `Last-Event-ID`, and each wait for the platform (the headers, every chunk) may last `idleMs` (default 60 s) instead of the request budget. */\n async stream(route: string, opts: PlatformStreamOptions = {}): Promise<PlatformStream> {\n const watch = new StreamWatch(opts.signal, opts.idleMs ?? PLATFORM_STREAM_IDLE_MS, this.#endpoint.host, route);\n const headers = this.headers(route, \"text/event-stream\", opts.after ? { \"last-event-id\": opts.after } : {});\n try {\n const response = await watch.within(() =>\n fetch(this.url(route), { method: \"GET\", headers, signal: watch.signal, redirect: KEYED_REDIRECTS }),\n );\n return new PlatformStream(response, watch);\n } catch (error) {\n watch.close();\n throw error;\n }\n }\n\n private url(route: string): string {\n return `${this.#endpoint.host}${route}`;\n }\n\n private headers(route: string, accept: string, extra: Record<string, string> = {}): Record<string, string> {\n return {\n \"content-type\": \"application/json\",\n accept,\n ...platformAuthorization(this.#endpoint, this.url(route)),\n ...extra,\n };\n }\n\n private async once(\n method: PlatformMethod,\n route: string,\n body: unknown,\n timeoutMs: number,\n caller?: AbortSignal,\n ): Promise<PlatformReply> {\n if (caller?.aborted) throw caller.reason;\n const payload = body === undefined ? {} : { body: JSON.stringify(body) };\n const headers = this.headers(route, \"application/json\");\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n const relay = (): void => controller.abort(caller?.reason);\n caller?.addEventListener(\"abort\", relay, { once: true });\n try {\n const res = await fetch(this.url(route), {\n method,\n headers,\n ...payload,\n signal: controller.signal,\n redirect: KEYED_REDIRECTS,\n });\n return { status: res.status, ok: res.ok, text: await res.text() };\n } catch (error) {\n if (caller?.aborted) throw caller.reason;\n const cause = controller.signal.aborted ? TransportCause.timeout(timeoutMs) : TransportCause.of(error);\n throw new UnreachableError(this.#endpoint.host, method, route, cause);\n } finally {\n clearTimeout(timer);\n caller?.removeEventListener(\"abort\", relay);\n }\n }\n}\n\nclass StreamWatch {\n readonly #controller = new AbortController();\n readonly #caller: AbortSignal | undefined;\n readonly #relay = (): void => this.#controller.abort(this.#caller?.reason);\n #idled = false;\n\n constructor(\n caller: AbortSignal | undefined,\n readonly idleMs: number,\n private readonly host: string,\n private readonly route: string,\n ) {\n this.#caller = caller;\n caller?.addEventListener(\"abort\", this.#relay, { once: true });\n if (caller?.aborted) this.#relay();\n }\n\n get signal(): AbortSignal {\n return this.#controller.signal;\n }\n\n async within<T>(wait: () => Promise<T>): Promise<T> {\n const timer = setTimeout(() => this.idle(), this.idleMs);\n try {\n return await wait();\n } catch (error) {\n throw this.failure(error);\n } finally {\n clearTimeout(timer);\n }\n }\n\n close(): void {\n this.#caller?.removeEventListener(\"abort\", this.#relay);\n this.#controller.abort();\n }\n\n private idle(): void {\n this.#idled = true;\n this.#controller.abort();\n }\n\n private failure(error: unknown): unknown {\n if (this.#caller?.aborted) return this.#caller.reason;\n const cause = this.#idled ? TransportCause.idle(this.idleMs) : TransportCause.of(error);\n return new UnreachableError(this.host, \"GET\", this.route, cause);\n }\n}\n\n/** An open event stream: its status, then its body as it arrives. A silence past the idle budget or a dropped connection throws `UnreachableError`; the caller's abort throws its reason. */\nexport class PlatformStream {\n readonly #response: Response;\n readonly #watch: StreamWatch;\n\n constructor(response: Response, watch: StreamWatch) {\n this.#response = response;\n this.#watch = watch;\n }\n\n get status(): number {\n return this.#response.status;\n }\n\n get ok(): boolean {\n return this.#response.ok;\n }\n\n /** The body as text, for a refusal: at most the first 64 KiB of characters; closes the stream. */\n async text(): Promise<string> {\n const decoder = new TextDecoder();\n let text = \"\";\n for await (const chunk of this.chunks()) {\n text += decoder.decode(chunk, { stream: true });\n if (text.length >= REFUSAL_TEXT_LIMIT) return text.slice(0, REFUSAL_TEXT_LIMIT);\n }\n return text + decoder.decode();\n }\n\n /** The body's bytes as they arrive; the idle budget runs only while waiting for the platform, never while the caller holds a chunk. */\n async *chunks(): AsyncGenerator<Uint8Array, void, undefined> {\n const reader = this.#response.body?.getReader();\n try {\n for (;;) {\n const next = reader ? await this.#watch.within(() => reader.read()) : { done: true as const };\n if (next.done) return;\n yield next.value;\n }\n } finally {\n this.close();\n }\n }\n\n close(): void {\n this.#watch.close();\n }\n}\n","/** One path segment from an id. An empty, `.` or `..` id is refused: a URL parser would resolve it into another route. */\nexport function segment(id: string): string {\n if (id === \"\" || id === \".\" || id === \"..\") throw new TypeError(`not an id: \"${id}\"`);\n return encodeURIComponent(id);\n}\n","import type { PlatformTransport } from \"../worlds/transport\";\nimport { ApiError } from \"../worlds/apiError\";\nimport type { PlatformMethod } from \"../worlds/transport\";\nimport { Agent, AgentVersionConflictError, type EditOptions } from \"./agent\";\nimport { AgentDefinition, type AgentDefinitionInput } from \"./definition\";\nimport type { AgentPatch } from \"./patch\";\nimport { segment } from \"./segment\";\nimport type { Threads } from \"./threads\";\nimport type {\n AgentAttribution,\n AgentBuildRecord,\n AgentDeployment,\n AgentEditResult,\n AgentVersion,\n AgentVersionEntry,\n LiveAgentRecord,\n} from \"./types\";\n\nconst PRODUCTION = \"production\";\nconst PAGE_SIZE = 100;\n\nconst buildRoute = (buildId: string) => `/api/public/agent-builds/${segment(buildId)}`;\n\ntype BuildPage = { data: AgentBuildRecord[]; meta: { totalPages: number } };\n\ntype HistoryPage = { data: AgentVersionEntry[]; meta: { totalPages: number } };\n\ntype LabelMove = { agentId: string; label: string; fromBuild: string | null; toBuild: string };\n\nexport type PushOptions = { attribution?: AgentAttribution; deploy?: boolean };\n\n/** `deploy` named a version that is not one of that agent's; no label moved. */\nexport class AgentVersionNotFoundError extends Error {\n readonly code = \"version_not_found\";\n\n constructor(\n readonly agent: string,\n readonly versionId: string,\n ) {\n super(`${versionId} is not a version of ${agent}; nothing was deployed.`);\n this.name = \"AgentVersionNotFoundError\";\n }\n}\n\n/** The project's defined agents: create one live and edit it in place, or push a definition from code and deploy a version of it. */\nexport class Agents {\n readonly #transport: PlatformTransport;\n readonly #threads: Threads;\n\n constructor(transport: PlatformTransport, threads: Threads) {\n this.#transport = transport;\n this.#threads = threads;\n }\n\n /** Create an agent, live in one call: version 1, deployed. A definition `defineAgent` would refuse throws `AgentDefinitionError` before anything is sent; a name the project already holds is 409 `agent_exists`. */\n async create(input: AgentDefinitionInput): Promise<Agent> {\n const { name, ...definition } = AgentDefinition.from(input).toJSON();\n const record = await this.#transport.json<LiveAgentRecord>(\n \"POST\",\n `/api/public/agent-builds/definitions/${segment(name)}`,\n definition,\n );\n return new Agent(this, record, this.#threads);\n }\n\n /** The live agent named `name`, to edit or run; 404 `agent_not_found` when the project has none. */\n async get(name: string): Promise<Agent> {\n return new Agent(this, await this.live(name), this.#threads);\n }\n\n /** The version of `name` that edits apply to: the one `production` runs, else the newest. */\n live(name: string): Promise<LiveAgentRecord> {\n return this.#transport.json<LiveAgentRecord>(\"GET\", `/api/public/agent-builds/definitions/${segment(name)}`);\n }\n\n /** Apply one patch to `name` as a new version, live unless `deploy: false`. With `from`, a version that is no longer the live one is refused (`AgentVersionConflictError`) and nothing is written. */\n edit(name: string, patch: AgentPatch, options: EditOptions & { from?: string } = {}): Promise<AgentEditResult> {\n const body = { patch: patch.toJSON(), from: options.from, deploy: options.deploy ?? true };\n return this.conflictAware(\"POST\", `/api/public/agent-builds/definitions/${segment(name)}/versions`, body);\n }\n\n /** Move `production` of `name` to one of its versions, with the audit row; `force` crosses a breaking tool change. */\n rollback(\n name: string,\n versionId: string,\n options: { from?: string; force?: boolean } = {},\n ): Promise<LiveAgentRecord> {\n const body = { versionId, from: options.from, force: options.force ?? false };\n return this.conflictAware(\"POST\", `/api/public/agent-builds/definitions/${segment(name)}/rollback`, body);\n }\n\n /** Every version of the live agent `name`, newest first, each with `isDeployed` and its changes against the one before; a version written while the pages are read never repeats one. */\n async history(name: string): Promise<AgentVersionEntry[]> {\n const versions = new Map<string, AgentVersionEntry>();\n for (let page = 1, pages = 1; page <= pages; page += 1) {\n const query = new URLSearchParams({ page: String(page), limit: String(PAGE_SIZE) });\n const reply = await this.#transport.json<HistoryPage>(\n \"GET\",\n `/api/public/agent-builds/definitions/${segment(name)}/versions?${query}`,\n );\n for (const version of reply.data) if (!versions.has(version.id)) versions.set(version.id, version);\n pages = reply.meta.totalPages;\n }\n return [...versions.values()];\n }\n\n /** Push a definition: a new version, or the identical one already pushed (`created: false`); the platform derives its `buildHash`. With `deploy`, `production` moves to it; when that move is refused the version still exists, and pushing again returns it. */\n async push(definition: AgentDefinition, options: PushOptions = {}): Promise<AgentVersion> {\n const body = { definition: definition.toJSON(), attribution: options.attribution };\n const version = await this.#transport.json<AgentVersion>(\"POST\", \"/api/public/agent-builds/definitions\", body);\n if (!options.deploy) return version;\n await this.move(version.id, false);\n return { ...version, deployed: true, labels: [...new Set([...version.labels, PRODUCTION])] };\n }\n\n /** Move `production` to `versionId`, after checking it is a defined version of `name` (an observed build of that name is not one). Rolling back is deploying an older version; `force` crosses a breaking tool change. */\n async deploy(name: string, versionId: string, options: { force?: boolean } = {}): Promise<AgentDeployment> {\n const versions = await this.versions(name);\n if (!versions.some((version) => version.id === versionId && version.kind === \"defined\"))\n throw new AgentVersionNotFoundError(name, versionId);\n return this.move(versionId, options.force ?? false);\n }\n\n /** Every version of `name`, newest first. */\n async versions(name: string): Promise<AgentBuildRecord[]> {\n const builds: AgentBuildRecord[] = [];\n for (let page = 1, pages = 1; page <= pages; page += 1) {\n const query = new URLSearchParams({ agentId: name, page: String(page), limit: String(PAGE_SIZE) });\n const reply = await this.#transport.json<BuildPage>(\"GET\", `/api/public/agent-builds?${query}`);\n builds.push(...reply.data);\n pages = reply.meta.totalPages;\n }\n return builds;\n }\n\n private async conflictAware<T>(method: PlatformMethod, path: string, body: unknown): Promise<T> {\n try {\n return await this.#transport.json<T>(method, path, body);\n } catch (error) {\n if (error instanceof ApiError && error.code === \"agent_version_conflict\")\n throw new AgentVersionConflictError(error.status, method, path, error.text);\n throw error;\n }\n }\n\n private async move(versionId: string, force: boolean): Promise<AgentDeployment> {\n const body = { label: PRODUCTION, source: \"api\", force };\n const moved = await this.#transport.json<LabelMove>(\"POST\", `${buildRoute(versionId)}/labels`, body);\n return {\n agentId: moved.agentId,\n label: moved.label,\n versionId,\n fromBuildHash: moved.fromBuild,\n toBuildHash: moved.toBuild,\n };\n }\n}\n","import { PersonalToken } from \"./personalToken\";\nimport type { PlatformEndpoint } from \"./transport\";\n\nconst DEFAULT_HOST = \"https://withgateway.ai\";\n\nexport const GATEWAY_KEYS_MISSING =\n \"Gateway keys missing: set GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY (or pass publicKey/secretKey).\";\n\nexport function platformEndpoint(options: Partial<PlatformEndpoint>): PlatformEndpoint | null {\n if (options.token)\n return {\n host: (options.host ?? options.token.host).replace(/\\/+$/, \"\"),\n publicKey: options.publicKey ?? \"\",\n secretKey: options.secretKey ?? \"\",\n token: options.token,\n };\n const token = PersonalToken.fromEnv(process.env, {\n host: options.host,\n keys: Boolean(options.publicKey || options.secretKey),\n });\n if (token) return { host: token.host, publicKey: \"\", secretKey: \"\", token };\n const host = (options.host ?? process.env.GATEWAY_HOST ?? DEFAULT_HOST).replace(/\\/+$/, \"\");\n const publicKey = options.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;\n const secretKey = options.secretKey ?? process.env.GATEWAY_SECRET_KEY;\n if (!publicKey || !secretKey) return null;\n return { host, publicKey, secretKey };\n}\n\nexport function requirePlatformEndpoint(options: Partial<PlatformEndpoint>): PlatformEndpoint {\n const endpoint = platformEndpoint(options);\n if (!endpoint) throw new Error(GATEWAY_KEYS_MISSING);\n return endpoint;\n}\n","/** A dispatched server-sent event: its name (`message` when the server named none), its data lines joined by `\\n`, and the stream's last event id at that point. */\nexport type SseMessage = { event: string; data: string; lastEventId: string | null };\n\nexport type EventStreamErrorCode =\n | \"line_too_large\"\n | \"event_too_large\"\n | \"malformed_event\"\n | \"reconnects_exhausted\"\n | \"run_not_finished\";\n\n/** A run's event stream that cannot be read on: a line or an event past the parser's caps, an event that is not the run's JSON, too many reconnects in a row, or a run the stream ended that the platform still reads as active. Never retried. */\nexport class EventStreamError extends Error {\n constructor(\n readonly code: EventStreamErrorCode,\n message: string,\n ) {\n super(message);\n this.name = \"EventStreamError\";\n }\n}\n\n/** The parser's memory bound, in characters: one line, and one event's data lines together. */\nexport class SseLimits {\n static readonly DEFAULT = new SseLimits(4 * 1024 * 1024, 4 * 1024 * 1024);\n\n constructor(\n readonly maxLineLength: number,\n readonly maxEventLength: number,\n ) {}\n}\n\nclass EventBlock {\n readonly #data: string[] = [];\n #length = 0;\n #type = \"\";\n\n constructor(\n public id: string,\n private readonly limits: SseLimits,\n ) {}\n\n addData(value: string): void {\n this.#length += value.length + 1;\n if (this.#length > this.limits.maxEventLength)\n throw new EventStreamError(\"event_too_large\", `an event passed ${this.limits.maxEventLength} characters`);\n this.#data.push(value);\n }\n\n setType(value: string): void {\n this.#type = value;\n }\n\n setId(value: string): void {\n if (!value.includes(\"\\0\")) this.id = value;\n }\n\n message(): SseMessage | null {\n if (this.#data.length === 0) return null;\n return { event: this.#type || \"message\", data: this.#data.join(\"\\n\"), lastEventId: this.id || null };\n }\n}\n\nconst FIELDS: ReadonlyMap<string, (block: EventBlock, value: string) => void> = new Map([\n [\"data\", (block: EventBlock, value: string) => block.addData(value)],\n [\"event\", (block: EventBlock, value: string) => block.setType(value)],\n [\"id\", (block: EventBlock, value: string) => block.setId(value)],\n]);\n\n/**\n * Server-sent events from bytes, as the WHATWG EventSource reads them: CRLF, LF or CR line ends (also split across\n * chunks), comments ignored, `data` lines joined, `retry` ignored, the last event id kept across events. Lines and events\n * past `SseLimits` throw `EventStreamError`, so a hostile stream cannot grow the buffer without bound.\n */\nexport class SseParser {\n readonly #decoder = new TextDecoder();\n readonly #lineEnd = /[\\r\\n]/g;\n readonly #limits: SseLimits;\n #pending = \"\";\n #afterCarriageReturn = false;\n #lastEventId: string;\n #block: EventBlock;\n\n constructor(lastEventId: string | null = null, limits: SseLimits = SseLimits.DEFAULT) {\n this.#limits = limits;\n this.#lastEventId = lastEventId ?? \"\";\n this.#block = new EventBlock(this.#lastEventId, limits);\n }\n\n /** The id a reconnect sends as `Last-Event-ID`: the last one set before a dispatched event, or null. */\n get lastEventId(): string | null {\n return this.#lastEventId || null;\n }\n\n /** Feed the next bytes; returns the events they completed, in order. */\n push(chunk: Uint8Array): SseMessage[] {\n const messages: SseMessage[] = [];\n for (const line of this.lines(this.#decoder.decode(chunk, { stream: true }))) {\n const message = this.line(line);\n if (message) messages.push(message);\n }\n return messages;\n }\n\n private lines(text: string): string[] {\n const scanFrom = this.#pending.length;\n this.#pending += this.skipLineFeed(text);\n const lines: string[] = [];\n let start = 0;\n this.#lineEnd.lastIndex = scanFrom;\n for (let end = this.#lineEnd.exec(this.#pending); end; end = this.#lineEnd.exec(this.#pending)) {\n lines.push(this.capped(this.#pending.slice(start, end.index)));\n start = this.lineEnd(end.index);\n this.#lineEnd.lastIndex = start;\n }\n this.#pending = this.capped(this.#pending.slice(start));\n return lines;\n }\n\n private lineEnd(index: number): number {\n const crlf = this.#pending.startsWith(\"\\r\\n\", index);\n this.#afterCarriageReturn = this.#pending[index] === \"\\r\" && index + 1 === this.#pending.length;\n return index + (crlf ? 2 : 1);\n }\n\n private skipLineFeed(text: string): string {\n if (!this.#afterCarriageReturn || text === \"\") return text;\n this.#afterCarriageReturn = false;\n return text.startsWith(\"\\n\") ? text.slice(1) : text;\n }\n\n private capped(line: string): string {\n if (line.length > this.#limits.maxLineLength)\n throw new EventStreamError(\"line_too_large\", `a line passed ${this.#limits.maxLineLength} characters`);\n return line;\n }\n\n private line(line: string): SseMessage | null {\n if (line === \"\") return this.dispatch();\n if (line.startsWith(\":\")) return null;\n const colon = line.indexOf(\":\");\n const field = colon === -1 ? line : line.slice(0, colon);\n const value = colon === -1 ? \"\" : line.slice(colon + 1).replace(/^ /, \"\");\n FIELDS.get(field)?.(this.#block, value);\n return null;\n }\n\n private dispatch(): SseMessage | null {\n const message = this.#block.message();\n this.#lastEventId = this.#block.id;\n this.#block = new EventBlock(this.#lastEventId, this.#limits);\n return message;\n }\n}\n","import { ApiError } from \"../worlds/apiError\";\nimport {\n PLATFORM_STREAM_IDLE_MS,\n RetryPolicy,\n UnreachableError,\n type PlatformStream,\n type PlatformTransport,\n} from \"../worlds/transport\";\nimport { segment } from \"./segment\";\nimport { EventStreamError, SseParser, type SseMessage } from \"./sse\";\nimport type { Run, RunEvent, RunEventType, RunStatus } from \"./types\";\n\n/** The time an `AgentRun` reads and waits on; tests pass a fake. */\nexport interface RunClock {\n now(): number;\n sleep(ms: number, signal?: AbortSignal): Promise<void>;\n}\n\nexport const SYSTEM_CLOCK: RunClock = Object.freeze({\n now: () => Date.now(),\n sleep: (ms: number, signal?: AbortSignal) =>\n new Promise<void>((resolve, reject) => {\n if (signal?.aborted) return reject(signal.reason);\n const abort = () => {\n clearTimeout(timer);\n reject(signal?.reason);\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", abort);\n resolve();\n }, ms);\n signal?.addEventListener(\"abort\", abort, { once: true });\n }),\n});\n\n/** How `events()` gets back onto a run's stream: one wait per reconnect in a row (so their count is the limit), and how long a connection may stay silent. */\nexport class ReconnectPolicy {\n static readonly DEFAULT = new ReconnectPolicy([250, 500, 1_000, 2_000, 4_000], PLATFORM_STREAM_IDLE_MS);\n\n constructor(\n readonly delaysMs: readonly number[],\n readonly idleMs: number,\n ) {}\n}\n\nexport type AgentRunOptions = { clock?: RunClock; reconnect?: ReconnectPolicy };\n\nexport type RunEventsOptions = { after?: string | null; signal?: AbortSignal };\n\nexport type RequestOptions = { signal?: AbortSignal };\n\ntype Stop = \"continues\" | \"waits\" | \"ends\";\n\nconst STOPS: Readonly<Record<RunEventType, Stop>> = {\n \"run.started\": \"continues\",\n \"step.attempt\": \"continues\",\n \"message.delta\": \"continues\",\n \"step.completed\": \"continues\",\n \"tool.started\": \"continues\",\n \"tool.completed\": \"continues\",\n \"run.error\": \"continues\",\n \"action.required\": \"waits\",\n \"run.completed\": \"ends\",\n \"run.failed\": \"ends\",\n \"run.cancelled\": \"ends\",\n};\n\nconst FINISHED: ReadonlySet<RunStatus> = new Set([\"completed\", \"failed\", \"cancelled\"]);\n\nconst REFRESH_RETRIES = 3;\n\nconst STREAM_REFUSALS_RETRIED: ReadonlySet<string> = new Set([\"too_many_streams\"]);\n\nconst runRoute = (threadId: string, runId: string) => `/api/public/threads/${segment(threadId)}/runs/${segment(runId)}`;\n\nfunction readEvent(message: SseMessage): RunEvent | null {\n if (!Object.hasOwn(STOPS, message.event)) return null;\n const data = parseJson(message.data);\n if (typeof data !== \"object\" || data === null || (data as { type?: unknown }).type !== message.event)\n throw new EventStreamError(\"malformed_event\", `a ${message.event} event whose data is not that event's JSON`);\n return data as RunEvent;\n}\n\nfunction retried(refusal: ApiError): boolean {\n return RetryPolicy.TRANSIENT_STATUSES.has(refusal.status) || STREAM_REFUSALS_RETRIED.has(refusal.code ?? \"\");\n}\n\nfunction parseJson(text: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n return undefined;\n }\n}\n\ntype Position = { cursor: string | null };\n\nclass Connection {\n #delivered = false;\n #closedCleanly = false;\n #stop: Stop = \"continues\";\n #why = \"the stream closed before the run ended\";\n\n constructor(readonly openedAt: number) {}\n\n get ended(): boolean {\n return this.#stop === \"ends\";\n }\n\n // The door closes after action.required only while the run waits; when more events follow, that wait was answered.\n get stopped(): boolean {\n return this.#stop !== \"continues\";\n }\n\n get why(): string {\n return this.#why;\n }\n\n delivered(): void {\n this.#delivered = true;\n }\n\n at(stop: Stop): void {\n this.#stop = stop;\n }\n\n closedCleanly(): void {\n this.#closedCleanly = true;\n }\n\n refused(status: number): void {\n this.#why = `the platform answered ${status}`;\n }\n\n dropped(error: unknown): void {\n if (!(error instanceof UnreachableError)) throw error;\n this.#why = error.message;\n }\n\n // A silence cut, a drop or a refused status never counts as working, however long it took: only an event, or the\n // platform's own clean close of a stream that lived the idle budget (its lifetime close), starts the count again.\n working(now: number, idleMs: number): boolean {\n return this.#delivered || (this.#closedCleanly && now - this.openedAt >= idleMs);\n }\n}\n\nclass Reconnects {\n #inARow = 0;\n\n constructor(\n private readonly policy: ReconnectPolicy,\n private readonly clock: RunClock,\n private readonly route: string,\n ) {}\n\n async after(connection: Connection, signal?: AbortSignal): Promise<void> {\n this.#inARow = connection.working(this.clock.now(), this.policy.idleMs) ? 1 : this.#inARow + 1;\n const delayMs = this.policy.delaysMs[this.#inARow - 1];\n if (delayMs === undefined)\n throw new EventStreamError(\n \"reconnects_exhausted\",\n `GET ${this.route}: no working stream after ${this.policy.delaysMs.length} reconnects in a row; last: ${connection.why}`,\n );\n await this.clock.sleep(delayMs, signal);\n }\n}\n\n/** One run of a thread: its events as they happen, resumed across dropped connections from the last event delivered, and the run's state. */\nexport class AgentRun {\n readonly #transport: PlatformTransport;\n readonly #clock: RunClock;\n readonly #reconnect: ReconnectPolicy;\n #snapshot: Run;\n #cursor: string | null = null;\n #ending: RunEventType | null = null;\n\n constructor(transport: PlatformTransport, run: Run, options: AgentRunOptions = {}) {\n this.#transport = transport;\n this.#snapshot = run;\n this.#clock = options.clock ?? SYSTEM_CLOCK;\n this.#reconnect = options.reconnect ?? ReconnectPolicy.DEFAULT;\n }\n\n get id(): string {\n return this.#snapshot.id;\n }\n\n get threadId(): string {\n return this.#snapshot.threadId;\n }\n\n /** The run as last read from the platform. */\n get snapshot(): Run {\n return this.#snapshot;\n }\n\n /** The id of the last event delivered by any reader; pass it as `after` to resume this run's events elsewhere. */\n get cursor(): string | null {\n return this.#cursor;\n }\n\n /**\n * The run's events from `after` (default: where the last `events()` stopped, else the start). A dropped connection, a\n * silence past the idle budget (60 s), a 502/503/504, a 429 `too_many_streams` or the platform closing the stream\n * reconnects with `Last-Event-ID`,\n * so each event arrives once; after 5 reconnects in a row with no event delivered (a clean close after at least the idle\n * budget also counts as working) it throws `EventStreamError`. Ends after `run.completed`, `run.failed` (`not_found` when\n * the run no longer exists) or `run.cancelled`, and at an `action.required` the platform ends the stream on (the run waits\n * for a person); an `action.required` followed by more events was a wait already answered, and the events go on. A key\n * holds at most 64 open streams: past that the platform answers 429 `too_many_streams`, which counts against the same\n * five reconnects.\n */\n async *events(options: RunEventsOptions = {}): AsyncGenerator<RunEvent, void, undefined> {\n const position: Position = { cursor: options.after === undefined ? this.#cursor : options.after };\n this.#ending = null;\n const reconnects = new Reconnects(this.#reconnect, this.#clock, `${runRoute(this.threadId, this.id)}/events`);\n for (;;) {\n const connection = new Connection(this.#clock.now());\n yield* this.connect(position, connection, options.signal);\n if (connection.stopped) return;\n await reconnects.after(connection, options.signal);\n }\n }\n\n /** The run once it has finished, or once it waits for a person (`status: \"requires_action\"` with its `action`). Throws `EventStreamError` `run_not_finished` when the stream ended the run and the platform still reads it as active after the reconnect delays, and the platform's 404 `ApiError` (`not_found`) for a run that no longer exists. */\n async wait(options: RequestOptions = {}): Promise<Run> {\n const polls = this.#reconnect.delaysMs[Symbol.iterator]();\n let run = this.#ending === null ? this.#snapshot : await this.refresh(options);\n while (!this.settled(run)) {\n await this.advance(polls, options.signal);\n run = await this.refresh(options);\n }\n return run;\n }\n\n /** The run as the platform reads it now; a gateway 5xx or a dropped connection is retried with the first reconnect delays. `signal` aborts the request and its retry waits. */\n async refresh(options: RequestOptions = {}): Promise<Run> {\n const { signal } = options;\n const retry = new RetryPolicy(this.#reconnect.delaysMs.slice(0, REFRESH_RETRIES), (ms) =>\n this.#clock.sleep(ms, signal),\n );\n return this.take(\n await this.#transport.json<Run>(\"GET\", `${runRoute(this.threadId, this.id)}`, undefined, { retry, signal }),\n );\n }\n\n /** Stop the run; a run already finished answers with its status. */\n async cancel(options: RequestOptions = {}): Promise<Run> {\n const { signal } = options;\n return this.take(\n await this.#transport.json<Run>(\"POST\", `${runRoute(this.threadId, this.id)}/cancel`, {}, { signal }),\n );\n }\n\n /** Answer the question the run waits on; the run is queued again and `events()` continues from where it stopped. */\n async resolve(answer: { actionId: string; answer: string }, options: RequestOptions = {}): Promise<Run> {\n const body = { actionId: answer.actionId, answer: answer.answer };\n const { signal } = options;\n const run = await this.#transport.json<Run>(\"POST\", `${runRoute(this.threadId, this.id)}/resolve`, body, {\n signal,\n });\n this.#ending = null;\n return this.take(run);\n }\n\n private settled(run: Run): boolean {\n return FINISHED.has(run.status) || (this.#ending === \"action.required\" && run.status === \"requires_action\");\n }\n\n private async advance(polls: Iterator<number>, signal?: AbortSignal): Promise<void> {\n if (this.#ending !== null && this.#ending !== \"action.required\") return this.pause(polls, signal);\n const before = this.#cursor;\n for await (const event of this.events({ signal })) void event;\n if (this.#ending === \"action.required\" && this.#cursor === before) await this.pause(polls, signal);\n }\n\n private async pause(polls: Iterator<number>, signal?: AbortSignal): Promise<void> {\n const delay = polls.next();\n if (delay.done)\n throw new EventStreamError(\n \"run_not_finished\",\n `${runRoute(this.threadId, this.id)}: the stream ended the run with ${this.#ending}, and the platform still reads it as ${this.#snapshot.status}`,\n );\n await this.#clock.sleep(delay.value, signal);\n }\n\n private take(run: Run): Run {\n this.#snapshot = run;\n return run;\n }\n\n private async *connect(\n position: Position,\n connection: Connection,\n signal?: AbortSignal,\n ): AsyncGenerator<RunEvent, void, undefined> {\n const stream = await this.open(position, connection, signal);\n if (!stream) return;\n try {\n yield* this.read(stream, position, connection);\n connection.closedCleanly();\n } catch (error) {\n connection.dropped(error);\n } finally {\n stream.close();\n }\n }\n\n private async open(position: Position, connection: Connection, signal?: AbortSignal): Promise<PlatformStream | null> {\n const route = `${runRoute(this.threadId, this.id)}/events`;\n try {\n const stream = await this.#transport.stream(route, {\n after: position.cursor,\n signal,\n idleMs: this.#reconnect.idleMs,\n });\n return await this.accepted(stream, route, connection);\n } catch (error) {\n connection.dropped(error);\n return null;\n }\n }\n\n private async accepted(\n stream: PlatformStream,\n route: string,\n connection: Connection,\n ): Promise<PlatformStream | null> {\n if (stream.ok) return stream;\n const refusal = new ApiError(stream.status, \"GET\", route, await stream.text());\n if (!retried(refusal)) throw refusal;\n connection.refused(stream.status);\n return null;\n }\n\n private async *read(\n stream: PlatformStream,\n position: Position,\n connection: Connection,\n ): AsyncGenerator<RunEvent, void, undefined> {\n const parser = new SseParser(position.cursor);\n for await (const chunk of stream.chunks()) {\n for (const message of parser.push(chunk)) {\n const event = readEvent(message);\n this.moveTo(position, message.lastEventId);\n if (!event) continue;\n connection.delivered();\n this.note(event, connection);\n yield event;\n if (connection.ended) return;\n }\n this.moveTo(position, parser.lastEventId);\n }\n }\n\n // Each events() call resumes from its own position, so two readers of one run never skip or repeat each other's events.\n private moveTo(position: Position, cursor: string | null): void {\n position.cursor = cursor;\n this.#cursor = cursor;\n }\n\n private note(event: RunEvent, connection: Connection): void {\n const stop = STOPS[event.type];\n this.#ending = stop === \"continues\" ? null : event.type;\n connection.at(stop);\n }\n}\n","import type { PlatformTransport } from \"../worlds/transport\";\nimport { AgentRun, type AgentRunOptions } from \"./run\";\nimport { segment } from \"./segment\";\nimport type { Run, RunStatus, ThreadAutonomy, ThreadRecord, ThreadWarning } from \"./types\";\n\nconst threadRoute = (threadId: string) => `/api/public/threads/${segment(threadId)}`;\n\n/** `agent` is an agent's name, or the `Agent` that `agents.create` / `agents.get` returned. */\nexport type CreateThreadOptions = { agent: string | { readonly name: string }; title?: string; autonomy?: ThreadAutonomy };\n\nexport type SendOptions = { version?: string; multitask?: \"reject\" };\n\n/** A conversation with a deployed agent, owned by the project of the key that created it. */\nexport class Thread {\n readonly #transport: PlatformTransport;\n readonly #runs: AgentRunOptions;\n readonly id: string;\n readonly agent: string;\n readonly title: string | null;\n readonly autonomy: Readonly<Required<ThreadAutonomy>>;\n readonly activeRun: Readonly<{ id: string; status: RunStatus }> | null;\n readonly createdAt: string;\n /** Granted tools this key cannot activate; only on the thread `create` returns. */\n readonly warnings: readonly ThreadWarning[];\n\n constructor(transport: PlatformTransport, record: ThreadRecord, runs: AgentRunOptions = {}) {\n this.#transport = transport;\n this.#runs = runs;\n this.id = record.id;\n this.agent = record.agent;\n this.title = record.title;\n this.autonomy = Object.freeze({ ...record.autonomy });\n this.activeRun = record.activeRun ? Object.freeze({ ...record.activeRun }) : null;\n this.createdAt = record.createdAt;\n this.warnings = Object.freeze([...(record.warnings ?? [])]);\n }\n\n /** Start a run on the agent's deployed version (or `version`); refused with 409 `thread_busy` while another run is active. */\n async send(input: string, options: SendOptions = {}): Promise<AgentRun> {\n const body = { input, version: options.version, multitask: options.multitask };\n const run = await this.#transport.json<Run>(\"POST\", `${threadRoute(this.id)}/runs`, body);\n return new AgentRun(this.#transport, run, this.#runs);\n }\n\n /** A run of this thread by id, as it is now. */\n async run(runId: string): Promise<AgentRun> {\n const run = await this.#transport.json<Run>(\"GET\", `${threadRoute(this.id)}/runs/${segment(runId)}`);\n return new AgentRun(this.#transport, run, this.#runs);\n }\n}\n\n/** The project's threads: create one per conversation with a deployed agent, or open one by id. */\nexport class Threads {\n readonly #transport: PlatformTransport;\n readonly #runs: AgentRunOptions;\n\n constructor(transport: PlatformTransport, runs: AgentRunOptions = {}) {\n this.#transport = transport;\n this.#runs = runs;\n }\n\n /** A thread for a deployed agent; `allowSelfSchedule` or `allowSubagents` set to `true` is refused (400 `autonomy_unsupported`). */\n async create(options: CreateThreadOptions): Promise<Thread> {\n const agent = typeof options.agent === \"string\" ? options.agent : options.agent.name;\n const body = { agent, title: options.title, autonomy: options.autonomy };\n const record = await this.#transport.json<ThreadRecord>(\"POST\", \"/api/public/threads\", body);\n return new Thread(this.#transport, record, this.#runs);\n }\n\n async get(threadId: string): Promise<Thread> {\n const record = await this.#transport.json<ThreadRecord>(\"GET\", `${threadRoute(threadId)}`);\n return new Thread(this.#transport, record, this.#runs);\n }\n}\n","import { requirePlatformEndpoint } from \"../worlds/platformEndpoint\";\nimport { PlatformTransport } from \"../worlds/transport\";\nimport { Agents } from \"./agents\";\nimport type { AgentRunOptions } from \"./run\";\nimport { Threads } from \"./threads\";\n\nexport type GatewayOptions = {\n host?: string;\n publicKey?: string;\n secretKey?: string;\n transport?: PlatformTransport;\n} & AgentRunOptions;\n\n/**\n * One project's agent primitives, authenticated by its secret key: `agents` (create and edit live agents, or push and deploy definitions) and `threads`\n * (talk to a deployed agent). Keys come from the options, else `GATEWAY_HOST` / `GATEWAY_PUBLIC_KEY` /\n * `GATEWAY_SECRET_KEY`; they are never printed, logged or serialized.\n */\nexport class Gateway {\n readonly agents: Agents;\n readonly threads: Threads;\n\n constructor(options: GatewayOptions = {}) {\n const transport = options.transport ?? new PlatformTransport(requirePlatformEndpoint(options));\n this.threads = new Threads(transport, { clock: options.clock, reconnect: options.reconnect });\n this.agents = new Agents(transport, this.threads);\n Object.freeze(this);\n }\n}\n","/** The models an agent may run on; the platform's default is `claude-opus-5`. Pinned to `gatewaysdk/fixtures/agents/definition-catalogue.json`. */\nexport const AGENT_MODELS = [\"claude-opus-5\", \"claude-sonnet-5\"] as const;\n\nexport type AgentModel = (typeof AGENT_MODELS)[number];\n\nexport const AGENT_EFFORTS = [\"low\", \"medium\", \"high\", \"xhigh\"] as const;\n\nexport type AgentEffort = (typeof AGENT_EFFORTS)[number];\n\n/** The tool servers a definition may grant, each with the tool names `only` may name. Pinned to `definition-catalogue.json`. */\nexport const TOOL_SERVERS = {\n docs: [\"search_docs\"],\n drive: [\"get_drive_file\", \"list_drive_files\", \"save_drive_file\"],\n sandbox: [\n \"copy_file\",\n \"execute_python\",\n \"grep_files\",\n \"ingest_sessions_to_sandbox\",\n \"list_files\",\n \"query_json\",\n \"read_file\",\n \"run_bash\",\n \"run_gateway_cli\",\n \"write_file\",\n ],\n web: [\"download_url_to_drive\", \"fetch_url\"],\n} as const;\n\nexport type ToolServer = keyof typeof TOOL_SERVERS;\n\nexport type ToolName<S extends ToolServer> = (typeof TOOL_SERVERS)[S][number];\n\n/** One server granted to an agent: all of its tools, or `only` the ones named. */\nexport type TypedGrant<S extends ToolServer = ToolServer> = {\n readonly server: S;\n readonly only?: readonly ToolName<S>[];\n};\n\n/** A tool as a definition or `agent.tools.attach` takes it: a server name, or a typed grant from `tools`. */\nexport type AgentToolInput = ToolServer | TypedGrant;\n\nconst grant =\n <S extends ToolServer>(server: S) =>\n (options: { only?: readonly ToolName<S>[] } = {}): TypedGrant<S> =>\n options.only ? { server, only: [...options.only] } : { server };\n\n/** Typed tool grants: `tools.web()` is the whole server, `tools.sandbox({ only: [\"run_gateway_cli\"] })` one tool of it. */\nexport const tools = Object.freeze({\n sandbox: grant(\"sandbox\"),\n drive: grant(\"drive\"),\n web: grant(\"web\"),\n docs: grant(\"docs\"),\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCO,IAAM,WAAN,cAAuB,MAAM;AAAA,EAGlC,YACkB,QAChB,QACA,MACgB,MAChB;AACA,UAAM,SAAS,eAAe,MAAM,MAAM;AAC1C,UAAM,GAAG,MAAM,IAAI,IAAI,OAAO,MAAM,KAAK,OAAO,MAAM,EAAE;AANxC;AAGA;AAIhB,SAAK,OAAO;AACZ,SAAK,OAAO,OAAO;AAAA,EACrB;AAAA,EATkB;AAAA,EAGA;AAAA,EANF;AAalB;AAEA,IAAM,eAAe;AAErB,IAAM,eAAiD;AAAA,EACrD,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AACP;AACA,IAAM,eACJ;AACF,IAAM,Y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AAO;AAAA,EACjC,SAAS,MAAM,SAAS;AAAA,EACxB,OAAO,MAAM,OAAO;AAAA,EACpB,KAAK,MAAM,KAAK;AAAA,EAChB,MAAM,MAAM,MAAM;AACpB,CAAC;","names":["grant"]}
1
+ {"version":3,"sources":["../../src/agents/index.ts","../../src/worlds/apiError.ts","../../src/agents/patch.ts","../../src/agents/agent.ts","../../src/agents/definition.ts","../../src/worlds/personalToken.ts","../../src/worlds/transport.ts","../../src/agents/segment.ts","../../src/agents/agents.ts","../../src/worlds/platformEndpoint.ts","../../src/agents/sse.ts","../../src/agents/run.ts","../../src/agents/threads.ts","../../src/agents/gateway.ts","../../src/agents/tools.ts"],"sourcesContent":["export { Agent, AgentThreads, AgentTools, AgentVersionConflictError } from \"./agent\";\nexport type { AgentRunInput, EditOptions } from \"./agent\";\nexport { AgentDefinition, AgentDefinitionError, defineAgent } from \"./definition\";\nexport { ApiError } from \"../worlds/apiError\";\nexport { PlatformTransport, UnreachableError } from \"../worlds/transport\";\nexport type { AgentDefinitionInput, AgentDefinitionIssue, AgentDefinitionIssueCode } from \"./definition\";\nexport { Agents, AgentVersionNotFoundError } from \"./agents\";\nexport type { PushOptions } from \"./agents\";\nexport { Gateway } from \"./gateway\";\nexport type { GatewayOptions } from \"./gateway\";\nexport { AgentRun, ReconnectPolicy, SYSTEM_CLOCK } from \"./run\";\nexport type { AgentRunOptions, RequestOptions, RunClock, RunEventsOptions } from \"./run\";\nexport { EventStreamError, SseLimits, SseParser } from \"./sse\";\nexport type { EventStreamErrorCode, SseMessage } from \"./sse\";\nexport { AgentPatch } from \"./patch\";\nexport type { AgentPatchJSON, AgentUpdate } from \"./patch\";\nexport { Thread, Threads } from \"./threads\";\nexport { AGENT_EFFORTS, AGENT_MODELS, TOOL_SERVERS, tools } from \"./tools\";\nexport type { AgentEffort, AgentModel, AgentToolInput, ToolName, ToolServer, TypedGrant } from \"./tools\";\nexport type { CreateThreadOptions, SendOptions } from \"./threads\";\nexport type {\n AgentAttribution,\n AgentBuildRecord,\n AgentDefinitionSpec,\n AgentDeployment,\n AgentEditResult,\n AgentVersion,\n AgentVersionEntry,\n LiveAgentRecord,\n Run,\n RunAction,\n RunError,\n RunErrorCode,\n RunEvent,\n RunEventType,\n RunStatus,\n ThreadAutonomy,\n ThreadRecord,\n ThreadWarning,\n ToolGrant,\n} from \"./types\";\n","/** A non-2xx platform answer: act on `status` or the stable public `code` (never the server's error class) rather than parsing the message. */\nexport class ApiError extends Error {\n public readonly code: string | null;\n\n constructor(\n public readonly status: number,\n method: string,\n path: string,\n public readonly text: string,\n ) {\n const parsed = parseErrorBody(text, status);\n super(`${method} ${path} -> ${status}: ${parsed.detail}`);\n this.name = \"ApiError\";\n this.code = parsed.code;\n }\n}\n\nconst DETAIL_LIMIT = 600;\n\nconst EDGE_ANSWERS: Readonly<Record<number, string>> = {\n 502: \"Bad Gateway from the load balancer in front of the platform, not the platform's answer: the web server dropped the connection or restarted mid-request. Retry; if it repeats, the platform is restarting or overloaded.\",\n 503: \"Service Unavailable from the load balancer in front of the platform, not the platform's answer: no web server was ready to take the request (a deploy or a restart). Retry in a minute.\",\n 504: \"Gateway Time-out from the load balancer in front of the platform, not the platform's answer: the request sent nothing back within the load balancer's idle timeout (60 s unless the deployment raises it: Helm ingress.idleTimeoutSeconds) and was cut there, though the platform may still be running it. Check what it changed before you retry.\",\n};\nconst EDGE_FAILURE =\n \"The platform failed without its JSON error body: a proxy in front of it answered, or the server stopped before its error handler ran. Retry; if it repeats, report the request and the time.\";\nconst EDGE_PAGE =\n \"An HTML page answered instead of the platform's JSON: a proxy in front of the platform, or the configured host is not the platform.\";\n\nfunction edgeAnswer(text: string, status: number | undefined): string | null {\n if (status !== undefined && status >= 500) return EDGE_ANSWERS[status] ?? EDGE_FAILURE;\n return /^\\s*</.test(text) ? EDGE_PAGE : null;\n}\n\n/** The detail and stable code of a non-2xx body; an HTML page or a bare 5xx is named, never printed.\n * Python twin: `gatewaysdk.api_errors.error_detail`; both run `conformance/platform-error-bodies.json`. */\nexport function parseErrorBody(text: string, status?: number): { detail: string; code: string | null } {\n const raw = { detail: text.slice(0, DETAIL_LIMIT), code: null };\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return { detail: (edgeAnswer(text, status) ?? text).slice(0, DETAIL_LIMIT), code: null };\n }\n if (parsed === null || typeof parsed !== \"object\") return raw;\n const { message, code, error } = parsed as { message?: unknown; code?: unknown; error?: unknown };\n const stableCode = typeof code === \"string\" ? code : null;\n if (typeof message !== \"string\") return { ...raw, code: stableCode };\n const fields = invalidFields(error);\n const said = fields ? `${message}: ${fields}` : message;\n if (stableCode === null) return { detail: said.slice(0, DETAIL_LIMIT), code: null };\n return {\n detail: `${said} (${stableCode})`.slice(0, DETAIL_LIMIT),\n code: stableCode,\n };\n}\n\n/** `<path>: <message>` per issue of a validation error; empty when it carries none. Python twin: `gatewaysdk.api_errors.invalid_fields`. */\nexport function invalidFields(error: unknown): string {\n const issues = Array.isArray(error) ? error : [];\n return issues\n .filter((issue): issue is { path?: unknown; message: string } =>\n issue !== null && typeof issue === \"object\" && typeof (issue as { message?: unknown }).message === \"string\",\n )\n .map((issue) => {\n const path = Array.isArray(issue.path) ? issue.path.map(String).join(\".\") : \"\";\n return path ? `${path}: ${issue.message}` : issue.message;\n })\n .join(\"; \");\n}\n","import type { AgentEffort, AgentModel, AgentToolInput } from \"./tools\";\nimport type { ToolGrant } from \"./types\";\n\n/** The fields `agent.update` changes; `effort: null` removes the effort. The name is the agent's identity and never changes. */\nexport type AgentUpdate = {\n instructions?: string;\n model?: AgentModel;\n effort?: AgentEffort | null;\n maxTurns?: number;\n};\n\nexport type AgentPatchJSON = {\n set?: Record<string, unknown>;\n attach?: ToolGrant[];\n detach?: string[];\n};\n\nconst list = <T>(value: T | readonly T[]): readonly T[] =>\n Array.isArray(value) ? (value as readonly T[]) : [value as T];\n\nfunction grantOf(input: AgentToolInput | ToolGrant): ToolGrant {\n if (typeof input === \"string\") return { server: input };\n return input.only ? { server: input.server, only: [...input.only].sort() } : { server: input.server };\n}\n\n/**\n * One edit of a live agent as the platform takes it (`patch` of `POST …/definitions/{name}/versions`). The platform\n * applies it to the version `production` runs and validates the result; the SDK only shapes it. Pinned to\n * `gatewaysdk/fixtures/agents/patch-vectors.json`.\n */\nexport class AgentPatch {\n private constructor(private readonly json: AgentPatchJSON) {}\n\n static update(fields: AgentUpdate): AgentPatch {\n const set = Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== undefined));\n return new AgentPatch({ set });\n }\n\n static attach(grants: AgentToolInput | readonly AgentToolInput[]): AgentPatch {\n return new AgentPatch({ attach: list(grants).map(grantOf) });\n }\n\n static detach(servers: string | readonly string[]): AgentPatch {\n return new AgentPatch({ detach: [...list(servers)] });\n }\n\n toJSON(): AgentPatchJSON {\n return structuredClone(this.json);\n }\n}\n","import { ApiError } from \"../worlds/apiError\";\nimport type { PlatformMethod } from \"../worlds/transport\";\nimport type { Agents } from \"./agents\";\nimport { AgentPatch, type AgentUpdate } from \"./patch\";\nimport type { AgentRun } from \"./run\";\nimport type { CreateThreadOptions, Thread, Threads } from \"./threads\";\nimport type { AgentToolInput } from \"./tools\";\nimport type { AgentEditResult, AgentVersionEntry, LiveAgentRecord, StoredAgentDefinition } from \"./types\";\n\n/** An edit or rollback made from a version that is no longer the live one: nothing was written. `refresh()` the agent, then edit again. */\nexport class AgentVersionConflictError extends ApiError {\n readonly currentVersionId: string | null;\n\n constructor(status: number, method: PlatformMethod, path: string, text: string) {\n super(status, method, path, text);\n this.name = \"AgentVersionConflictError\";\n this.currentVersionId = currentVersionOf(text);\n }\n}\n\nfunction currentVersionOf(text: string): string | null {\n try {\n const id = (JSON.parse(text) as { currentVersionId?: unknown }).currentVersionId;\n return typeof id === \"string\" ? id : null;\n } catch {\n return null;\n }\n}\n\n/** `deploy` (default true) moves `production` to the version the edit writes; `false` stages it. */\nexport type EditOptions = { deploy?: boolean };\n\nexport type AgentRunInput = Omit<CreateThreadOptions, \"agent\"> & { version?: string };\n\n/** The agent's tools: each attach or detach is a new version, live unless `deploy: false`. */\nexport class AgentTools {\n constructor(private readonly agent: Agent) {}\n\n /** Grant servers: one already attached keeps its place and takes the new grant. */\n attach(grants: AgentToolInput | readonly AgentToolInput[], options: EditOptions = {}): Promise<AgentEditResult> {\n return this.agent.edit(AgentPatch.attach(grants), options);\n }\n\n /** Remove servers; one that is not attached changes nothing. */\n detach(servers: string | readonly string[], options: EditOptions = {}): Promise<AgentEditResult> {\n return this.agent.edit(AgentPatch.detach(servers), options);\n }\n}\n\n/** Threads with this agent. */\nexport class AgentThreads {\n constructor(\n private readonly threads: Threads,\n private readonly name: string,\n ) {}\n\n create(options: Omit<CreateThreadOptions, \"agent\"> = {}): Promise<Thread> {\n return this.threads.create({ ...options, agent: this.name });\n }\n}\n\n/**\n * A live agent: every change is a call on it, and each one is an immutable version the platform keeps. An edit carries\n * the version this handle holds, so a change someone else made in between is refused (`AgentVersionConflictError`)\n * rather than overwritten. A run keeps the version it was sent on.\n */\nexport class Agent {\n readonly #agents: Agents;\n #record: LiveAgentRecord;\n readonly tools: AgentTools;\n readonly threads: AgentThreads;\n\n constructor(agents: Agents, record: LiveAgentRecord, threads: Threads) {\n this.#agents = agents;\n this.#record = liveOf(record);\n this.tools = new AgentTools(this);\n this.threads = new AgentThreads(threads, record.name);\n }\n\n get name(): string {\n return this.#record.name;\n }\n\n /** The version edits apply to: the one `production` runs (else, never deployed, the newest). */\n get versionId(): string {\n return this.#record.versionId;\n }\n\n get version(): number {\n return this.#record.version;\n }\n\n get buildHash(): string {\n return this.#record.buildHash;\n }\n\n get deployed(): boolean {\n return this.#record.deployed;\n }\n\n get definition(): Readonly<StoredAgentDefinition> {\n return structuredClone(this.#record.definition);\n }\n\n /** Change fields: a new version, live unless `deploy: false`; a change to the values it already has writes nothing. */\n update(fields: AgentUpdate, options: EditOptions = {}): Promise<AgentEditResult> {\n return this.edit(AgentPatch.update(fields), options);\n }\n\n /** Apply one patch made of `AgentPatch.update`, `.attach` or `.detach`. */\n async edit(patch: AgentPatch, options: EditOptions = {}): Promise<AgentEditResult> {\n const result = await this.#agents.edit(this.name, patch, { ...options, from: this.versionId });\n if (result.deployed || !this.deployed) this.#record = liveOf(result);\n return result;\n }\n\n /** Move `production` to one of this agent's versions (an earlier one, or one staged with `deploy: false`); `force` crosses a breaking tool change. */\n async rollback(versionId: string, options: { force?: boolean } = {}): Promise<LiveAgentRecord> {\n this.#record = liveOf(await this.#agents.rollback(this.name, versionId, { ...options, from: this.versionId }));\n return this.toJSON();\n }\n\n /** Every version, newest first, with whether it is live and its changes against the version before it. */\n versions(): Promise<AgentVersionEntry[]> {\n return this.#agents.history(this.name);\n }\n\n /** Read the live version again, after a conflict or someone else's change. */\n async refresh(): Promise<this> {\n this.#record = liveOf(await this.#agents.live(this.name));\n return this;\n }\n\n /** Start a thread with this agent and send it `input`: the run uses the version `production` runs now (or `version`). */\n async run(input: string, options: AgentRunInput = {}): Promise<AgentRun> {\n const { version, ...thread } = options;\n return (await this.threads.create(thread)).send(input, { version });\n }\n\n toJSON(): LiveAgentRecord {\n return { ...this.#record, definition: this.definition };\n }\n}\n\nfunction liveOf(record: LiveAgentRecord): LiveAgentRecord {\n const { name, versionId, version, buildHash, deployed, definition } = record;\n return { name, versionId, version, buildHash, deployed, definition };\n}\n","import type { AgentEffort, AgentModel, AgentToolInput } from \"./tools\";\nimport type { AgentDefinitionSpec, ToolGrant } from \"./types\";\n\nconst NAME_PATTERN = /^[a-z0-9][a-z0-9-]{0,62}$/;\nconst DEFAULT_MODEL = \"claude-opus-5\";\nconst DEFAULT_MAX_TURNS = 50;\nconst INSTRUCTIONS = { min: 1, max: 65_536 };\nconst MAX_TURNS = { min: 1, max: 200 };\nconst DEFINITION_FIELDS: ReadonlySet<string> = new Set([\n \"name\",\n \"instructions\",\n \"model\",\n \"effort\",\n \"maxTurns\",\n \"tools\",\n]);\nconst GRANT_FIELDS: ReadonlySet<string> = new Set([\"server\", \"only\"]);\n\ntype Path = (string | number)[];\ntype Bounds = { min: number; max: number };\n\nexport type AgentDefinitionIssueCode =\n | \"invalid_type\"\n | \"invalid_name\"\n | \"too_small\"\n | \"too_large\"\n | \"unknown_field\"\n | \"duplicate_tool_server\"\n | \"duplicate_tool\";\n\n/** One broken rule of a definition: where (`path` into the normalized definition), which rule (`code`), and why. */\nexport type AgentDefinitionIssue = { path: Path; code: AgentDefinitionIssueCode; message: string };\n\n/** What `defineAgent` and `agents.create` take. A tool is a server name (`\"sandbox\"`: all of its tools) or a grant from `tools` (`tools.web({ only: [\"fetch_url\"] })`). */\nexport type AgentDefinitionInput = {\n name: string;\n instructions: string;\n model?: AgentModel;\n effort?: AgentEffort;\n maxTurns?: number;\n tools?: readonly AgentToolInput[];\n};\n\n/** A definition `defineAgent` refused before anything was sent: every broken rule, each with its path and code. The platform checks the rest (model, effort, tool servers and names). */\nexport class AgentDefinitionError extends Error {\n constructor(readonly issues: readonly AgentDefinitionIssue[]) {\n super(`Invalid agent definition: ${issues.map((issue) => `${pathText(issue.path)}: ${issue.message}`).join(\"; \")}`);\n this.name = \"AgentDefinitionError\";\n }\n}\n\ntype FrozenGrant = { readonly server: string; readonly only?: readonly string[] };\n\n/** An agent as code: frozen and normalized, so the JSON it sends is the JSON the platform hashes into the version's `buildHash`. */\nexport class AgentDefinition {\n readonly name: string;\n readonly instructions: string;\n readonly model: string;\n readonly effort: AgentEffort | undefined;\n readonly maxTurns: number;\n readonly tools: readonly FrozenGrant[];\n\n private constructor(spec: AgentDefinitionSpec) {\n this.name = spec.name;\n this.instructions = spec.instructions;\n this.model = spec.model;\n this.effort = spec.effort;\n this.maxTurns = spec.maxTurns;\n this.tools = Object.freeze(spec.tools.map(freezeGrant));\n Object.freeze(this);\n }\n\n /** Validate and normalize any value (a parsed JSON file included); throws `AgentDefinitionError` listing every broken rule. */\n static from(input: unknown): AgentDefinition {\n return new AgentDefinition(DefinitionReader.read(input));\n }\n\n /** The normalized definition: defaults filled, tool shorthands expanded, `only` sorted, `effort` present only when set. */\n toJSON(): AgentDefinitionSpec {\n return {\n name: this.name,\n instructions: this.instructions,\n model: this.model,\n ...(this.effort === undefined ? {} : { effort: this.effort }),\n maxTurns: this.maxTurns,\n tools: this.tools.map((grant) =>\n grant.only ? { server: grant.server, only: [...grant.only] } : { server: grant.server },\n ),\n };\n }\n}\n\n/** Define an agent: `model` defaults to `claude-opus-5`, `maxTurns` to 50 (1–200), `tools` to none. */\nexport function defineAgent(input: AgentDefinitionInput): AgentDefinition {\n return AgentDefinition.from(input);\n}\n\nfunction freezeGrant(grant: ToolGrant): FrozenGrant {\n const only = grant.only ? { only: Object.freeze([...grant.only]) } : {};\n return Object.freeze({ server: grant.server, ...only });\n}\n\nfunction pathText(path: Path): string {\n return path.length === 0 ? \"definition\" : path.join(\".\");\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isString(value: string | null): value is string {\n return value !== null;\n}\n\nclass DefinitionReader {\n readonly #issues: AgentDefinitionIssue[] = [];\n\n static read(input: unknown): AgentDefinitionSpec {\n const reader = new DefinitionReader();\n const spec = reader.spec(input);\n if (!spec || reader.#issues.length > 0) throw new AgentDefinitionError(reader.#issues);\n return spec;\n }\n\n private spec(input: unknown): AgentDefinitionSpec | null {\n if (!isRecord(input)) return this.refuse([], \"invalid_type\", \"a definition is an object\", null);\n this.unknownFields(input, DEFINITION_FIELDS, []);\n const effort = this.optionalString(input.effort, [\"effort\"]);\n return {\n name: this.name(input.name),\n instructions: this.instructions(input.instructions),\n model: this.optionalString(input.model, [\"model\"]) ?? DEFAULT_MODEL,\n ...(effort === undefined ? {} : { effort: effort as AgentEffort }),\n maxTurns: this.maxTurns(input.maxTurns),\n tools: this.tools(input.tools),\n };\n }\n\n private name(value: unknown): string {\n const name = this.string(value, [\"name\"]);\n if (name !== null && !NAME_PATTERN.test(name))\n this.issue([\"name\"], \"invalid_name\", \"lowercase letters, digits and dashes, 1-63 long, not starting with a dash\");\n return name ?? \"\";\n }\n\n private instructions(value: unknown): string {\n const instructions = this.string(value, [\"instructions\"]);\n if (instructions !== null) this.bounded(instructions.length, INSTRUCTIONS, [\"instructions\"], \"characters\");\n return instructions ?? \"\";\n }\n\n private maxTurns(value: unknown): number {\n if (value === undefined) return DEFAULT_MAX_TURNS;\n if (typeof value !== \"number\" || !Number.isInteger(value))\n return this.refuse([\"maxTurns\"], \"invalid_type\", \"a whole number\", DEFAULT_MAX_TURNS);\n this.bounded(value, MAX_TURNS, [\"maxTurns\"], \"turns\");\n return value;\n }\n\n private tools(value: unknown): ToolGrant[] {\n if (value === undefined) return [];\n if (!Array.isArray(value)) return this.refuse([\"tools\"], \"invalid_type\", \"a list of tools\", []);\n const grants = value.map((entry, index) => this.grant(entry, [\"tools\", index]));\n this.noRepeats(\n grants.map((grant) => grant?.server ?? null),\n (index) => [\"tools\", index, \"server\"],\n \"duplicate_tool_server\",\n \"this server is already granted\",\n );\n return grants.filter((grant): grant is ToolGrant => grant !== null);\n }\n\n private grant(entry: unknown, path: Path): ToolGrant | null {\n if (typeof entry === \"string\") return { server: entry };\n if (!isRecord(entry)) return this.refuse(path, \"invalid_type\", \"a server name or { server, only }\", null);\n this.unknownFields(entry, GRANT_FIELDS, path);\n const server = this.string(entry.server, [...path, \"server\"]);\n if (server === null) return null;\n return entry.only === undefined ? { server } : { server, only: this.only(entry.only, [...path, \"only\"]) };\n }\n\n private only(value: unknown, path: Path): string[] {\n if (!Array.isArray(value)) return this.refuse(path, \"invalid_type\", \"a list of tool names\", []);\n if (value.length === 0)\n this.issue(path, \"too_small\", \"names at least one tool; leave `only` out to grant the whole server\");\n const names = value.map((name, index) => this.string(name, [...path, index]));\n this.noRepeats(names, (index) => [...path, index], \"duplicate_tool\", \"this tool is already named\");\n return names.filter(isString).sort();\n }\n\n private string(value: unknown, path: Path): string | null {\n if (typeof value === \"string\") return value;\n return this.refuse(path, \"invalid_type\", \"a string\", null);\n }\n\n private optionalString(value: unknown, path: Path): string | undefined {\n if (value === undefined) return undefined;\n return this.string(value, path) ?? undefined;\n }\n\n private bounded(value: number, bounds: Bounds, path: Path, unit: string): void {\n if (value < bounds.min) this.issue(path, \"too_small\", `at least ${bounds.min} ${unit}`);\n if (value > bounds.max) this.issue(path, \"too_large\", `at most ${bounds.max} ${unit}`);\n }\n\n private unknownFields(record: Record<string, unknown>, known: ReadonlySet<string>, path: Path): void {\n for (const [key, value] of Object.entries(record)) {\n if (value !== undefined && !known.has(key))\n this.issue([...path, key], \"unknown_field\", \"not a field of an agent definition\");\n }\n }\n\n private noRepeats(\n values: (string | null)[],\n pathOf: (index: number) => Path,\n code: AgentDefinitionIssueCode,\n message: string,\n ): void {\n const seen = new Set<string>();\n values.forEach((value, index) => {\n if (value === null) return;\n if (seen.has(value)) this.issue(pathOf(index), code, message);\n seen.add(value);\n });\n }\n\n private issue(path: Path, code: AgentDefinitionIssueCode, message: string): void {\n this.#issues.push({ path, code, message });\n }\n\n private refuse<T>(path: Path, code: AgentDefinitionIssueCode, message: string, fallback: T): T {\n this.issue(path, code, message);\n return fallback;\n }\n}\n","export const TOKEN_NOT_PERSONAL =\n \"GATEWAY_TOKEN takes a personal access token: pat_ followed by letters and digits only.\";\nexport const TOKEN_NEEDS_PROJECT =\n \"GATEWAY_TOKEN acts in the project GATEWAY_PROJECT_ID names: set it to the official project's id (letters, digits, - and _).\";\nexport const TOKEN_NEEDS_HOST = \"GATEWAY_TOKEN goes only to the host GATEWAY_HOST names: set GATEWAY_HOST.\";\nexport const TOKEN_OTHER_HOST =\n \"GATEWAY_TOKEN goes only to the host GATEWAY_HOST names, and this call names another host: point the call at GATEWAY_HOST or unset GATEWAY_TOKEN.\";\nexport const TOKEN_BESIDE_KEYS =\n \"GATEWAY_TOKEN is set beside a project key (GATEWAY_PUBLIC_KEY, GATEWAY_SECRET_KEY, GATEWAY_API_KEY or a key passed in): unset one of them. Neither replaces the other.\";\nexport const TOKEN_FILING =\n \"Filing an evaluation takes your project's key pair, not GATEWAY_TOKEN: unset it (an official world runs once copied into your own project).\";\nexport const TOKEN_KEYS_ONLY =\n \"Task-run tracing exports with a project key pair (GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY), not GATEWAY_TOKEN.\";\n\nconst PERSONAL = /^pat_[A-Za-z0-9]+$/;\nconst PROJECT = /^[A-Za-z0-9_-]+$/;\nconst ENV_KEYS = [\"GATEWAY_PUBLIC_KEY\", \"GATEWAY_SECRET_KEY\", \"GATEWAY_API_KEY\"];\n\nexport type TokenRequest = { host?: string; keys?: boolean };\n\nexport class PersonalTokenRefused extends Error {}\n\nconst bare = (host: string) => host.replace(/\\/+$/, \"\");\n\nexport class PersonalToken {\n private constructor(\n readonly value: string,\n readonly project: string,\n readonly host: string,\n ) {}\n\n static fromEnv(env: NodeJS.ProcessEnv, request: TokenRequest = {}): PersonalToken | null {\n const value = env.GATEWAY_TOKEN;\n if (!value) return null;\n if (request.keys || ENV_KEYS.some((name) => env[name])) throw new PersonalTokenRefused(TOKEN_BESIDE_KEYS);\n const host = bare(env.GATEWAY_HOST ?? \"\");\n if (!host) throw new PersonalTokenRefused(TOKEN_NEEDS_HOST);\n if (request.host && bare(request.host) !== host) throw new PersonalTokenRefused(TOKEN_OTHER_HOST);\n if (!PERSONAL.test(value)) throw new PersonalTokenRefused(TOKEN_NOT_PERSONAL);\n const project = env.GATEWAY_PROJECT_ID ?? \"\";\n if (!PROJECT.test(project)) throw new PersonalTokenRefused(TOKEN_NEEDS_PROJECT);\n return new PersonalToken(value, project, host);\n }\n\n toJSON(): { project: string; host: string } {\n return { project: this.project, host: this.host };\n }\n\n [Symbol.for(\"nodejs.util.inspect.custom\")](): string {\n return `PersonalToken { project: ${this.project}, host: ${this.host} }`;\n }\n\n static scrubbed(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n return Object.fromEntries(Object.entries(env).filter(([key]) => key !== \"GATEWAY_TOKEN\"));\n }\n}\n","import { ApiError } from \"./apiError\";\nimport { type PersonalToken, PersonalTokenRefused, TOKEN_BESIDE_KEYS, TOKEN_OTHER_HOST } from \"./personalToken\";\n\nexport const PLATFORM_TIMEOUT_ENV = \"GATEWAY_TIMEOUT_MS\";\n\nexport const PLATFORM_TIMEOUT_DEFAULT_MS = 120_000;\n\nexport type PlatformEndpoint = { host: string; publicKey: string; secretKey: string; token?: PersonalToken };\n\nexport type PlatformMethod = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n\nexport type PlatformReply = { status: number; ok: boolean; text: string };\n\nexport type PlatformSendOptions = { timeoutMs?: number; retry?: RetryPolicy; signal?: AbortSignal };\n\n/** The request budget in force: `GATEWAY_TIMEOUT_MS` when set, else the default. */\nexport function platformTimeoutMs(env: NodeJS.ProcessEnv = process.env): number {\n const raw = env[PLATFORM_TIMEOUT_ENV];\n if (raw === undefined || raw === \"\") return PLATFORM_TIMEOUT_DEFAULT_MS;\n const value = Number(raw);\n if (Number.isInteger(value) && value > 0) return value;\n throw new Error(`${PLATFORM_TIMEOUT_ENV} must be a positive whole number of milliseconds, not \\`${raw}\\`.`);\n}\n\nconst CHECK_HOST = \"Check GATEWAY_HOST (or --host) points at a running platform, then retry.\";\nconst RETRY = \"Retry; if it repeats, check the network between here and the platform.\";\nconst FETCH_LIMIT = {\n reason: \"Node's fetch stopped waiting after 300 s\",\n next: \"The platform may still be running it: check what it changed before you retry.\",\n};\n\nconst CAUSES: Record<string, { reason: string; next: string }> = {\n UND_ERR_HEADERS_TIMEOUT: FETCH_LIMIT,\n UND_ERR_BODY_TIMEOUT: FETCH_LIMIT,\n ECONNREFUSED: { reason: \"connection refused\", next: CHECK_HOST },\n ENOTFOUND: { reason: \"DNS lookup failed\", next: CHECK_HOST },\n EAI_AGAIN: { reason: \"DNS lookup failed\", next: CHECK_HOST },\n ETIMEDOUT: { reason: \"connect timed out\", next: CHECK_HOST },\n UND_ERR_CONNECT_TIMEOUT: { reason: \"connect timed out\", next: CHECK_HOST },\n EHOSTUNREACH: { reason: \"host unreachable\", next: CHECK_HOST },\n ENETUNREACH: { reason: \"network unreachable\", next: RETRY },\n ECONNRESET: { reason: \"connection dropped\", next: RETRY },\n UND_ERR_SOCKET: { reason: \"connection dropped\", next: RETRY },\n EPIPE: { reason: \"connection dropped\", next: RETRY },\n};\n\nconst UNKNOWN_CAUSE = { reason: \"network error\", next: CHECK_HOST };\n\n/** Why a request got no answer, from the socket-level error undici hides under `fetch failed`. */\nexport class TransportCause {\n private constructor(\n readonly reason: string,\n readonly detail: string | null,\n readonly next: string,\n ) {}\n\n static timeout(timeoutMs: number): TransportCause {\n return new TransportCause(\n `timed out after ${timeoutMs / 1000}s`,\n null,\n `Retry; if the platform is slow, raise ${PLATFORM_TIMEOUT_ENV} (milliseconds per request).`,\n );\n }\n\n static idle(idleMs: number): TransportCause {\n return new TransportCause(\n `no data for ${idleMs / 1000}s`,\n null,\n \"The stream resumes from its last event; if it repeats, check the network between here and the platform.\",\n );\n }\n\n static of(error: unknown): TransportCause {\n const cause = error instanceof Error && error.cause instanceof Error ? error.cause : undefined;\n const code = cause && \"code\" in cause && typeof cause.code === \"string\" ? cause.code : null;\n const message = cause?.message ?? (error instanceof Error ? error.message : String(error));\n const known = (code && CAUSES[code]) || UNKNOWN_CAUSE;\n return new TransportCause(known.reason, code ? `${code}: ${message}` : message, known.next);\n }\n\n describe(): string {\n return this.detail === null ? this.reason : `${this.reason} (${this.detail})`;\n }\n}\n\nexport class UnreachableError extends Error {\n constructor(\n readonly host: string,\n readonly method: string,\n readonly route: string,\n readonly failure: TransportCause,\n ) {\n super(`${method} ${route}: no answer from ${host}: ${failure.describe()}. ${failure.next}`);\n this.name = \"UnreachableError\";\n }\n}\n\nconst sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));\n\n/**\n * Another attempt after a gateway 5xx (502, 503, 504) or no answer at all, for a request whose repeat is harmless: a\n * keyed filing step, which the platform answers with the first filing. Every other request gets one attempt (`NONE`).\n */\nexport class RetryPolicy {\n static readonly NONE = new RetryPolicy([]);\n /** A platform restart or a short edge outage: no wait starts that would end past five minutes, so a step ends\n * within the budget plus one request timeout. */\n static readonly FILING = new RetryPolicy([250, 500, 1_000, 2_000, 4_000, 8_000, 16_000, 30_000], sleep, 300_000);\n static readonly TRANSIENT_STATUSES: ReadonlySet<number> = new Set([502, 503, 504]);\n\n constructor(\n readonly delaysMs: readonly number[],\n private readonly wait: (ms: number) => Promise<void> = sleep,\n readonly budgetMs: number = Number.POSITIVE_INFINITY,\n private readonly now: () => number = Date.now,\n ) {}\n\n async run(attempt: () => Promise<PlatformReply>): Promise<PlatformReply> {\n const started = this.now();\n for (let tries = 0; ; tries += 1) {\n const outcome = await Attempt.of(attempt);\n const delayMs = this.delaysMs[tries];\n const spent = delayMs === undefined || this.now() - started + delayMs >= this.budgetMs;\n if (!outcome.transient || spent) return outcome.settle();\n await this.wait(delayMs);\n }\n }\n}\n\nclass Attempt {\n private constructor(\n private readonly reply: PlatformReply | null,\n private readonly error: unknown,\n readonly transient: boolean,\n ) {}\n\n static async of(attempt: () => Promise<PlatformReply>): Promise<Attempt> {\n try {\n const reply = await attempt();\n return new Attempt(reply, null, RetryPolicy.TRANSIENT_STATUSES.has(reply.status));\n } catch (error) {\n return new Attempt(null, error, error instanceof UnreachableError);\n }\n }\n\n settle(): PlatformReply {\n if (this.reply) return this.reply;\n throw this.error;\n }\n}\n\n/** How long an open event stream may stay silent (no event and no keepalive) before it counts as dropped. */\nexport const PLATFORM_STREAM_IDLE_MS = 60_000;\n\nexport type PlatformStreamOptions = { after?: string | null; signal?: AbortSignal; idleMs?: number };\n\nconst REFUSAL_TEXT_LIMIT = 64 * 1024;\n\n// No route the SDK calls redirects: a 3xx is answered as the refusal it is, so the key never rides a hop to any host, whatever the runtime's fetch does with Authorization.\nconst KEYED_REDIRECTS: RequestRedirect = \"manual\";\n\nexport function platformAuthorization(endpoint: PlatformEndpoint, url: string): Record<string, string> {\n const { token } = endpoint;\n if (!token)\n return { authorization: \"Basic \" + Buffer.from(`${endpoint.publicKey}:${endpoint.secretKey}`).toString(\"base64\") };\n if (endpoint.publicKey || endpoint.secretKey) throw new PersonalTokenRefused(TOKEN_BESIDE_KEYS);\n if (!url.startsWith(`${token.host}/`)) throw new PersonalTokenRefused(TOKEN_OTHER_HOST);\n return { authorization: `Bearer ${token.value}`, \"x-gateway-project\": token.project };\n}\n\n/** The one door every CLI and SDK request to the platform goes through: Basic auth with the project key, a per-request timeout, and a transport failure turned into an `UnreachableError`. */\nexport class PlatformTransport {\n readonly #endpoint: PlatformEndpoint;\n readonly #timeoutMs: number;\n\n constructor(endpoint: PlatformEndpoint, timeoutMs: number = platformTimeoutMs()) {\n this.#endpoint = endpoint;\n this.#timeoutMs = timeoutMs;\n }\n\n /** A request that legitimately takes longer (a sandbox exec, a world create) waits its own budget; every other one waits the default. */\n budget(ownMs?: number): number {\n return Math.max(ownMs ?? 0, this.#timeoutMs);\n }\n\n /** One request; the caller's `signal` aborts it in flight and throws the signal's reason, never an `UnreachableError`. */\n async send(\n method: PlatformMethod,\n route: string,\n body?: unknown,\n opts: PlatformSendOptions = {},\n ): Promise<PlatformReply> {\n const timeoutMs = this.budget(opts.timeoutMs);\n return (opts.retry ?? RetryPolicy.NONE).run(() => this.once(method, route, body, timeoutMs, opts.signal));\n }\n\n /** `send`, then the 2xx body as JSON; any other answer throws `ApiError` with its status and stable `code`. */\n async json<T>(method: PlatformMethod, route: string, body?: unknown, opts: PlatformSendOptions = {}): Promise<T> {\n const reply = await this.send(method, route, body, opts);\n if (!reply.ok) throw new ApiError(reply.status, method, route, reply.text);\n return JSON.parse(reply.text) as T;\n }\n\n /** The streaming twin of `send` for a `GET` event stream: nothing is buffered, `after` travels as `Last-Event-ID`, and each wait for the platform (the headers, every chunk) may last `idleMs` (default 60 s) instead of the request budget. */\n async stream(route: string, opts: PlatformStreamOptions = {}): Promise<PlatformStream> {\n const watch = new StreamWatch(opts.signal, opts.idleMs ?? PLATFORM_STREAM_IDLE_MS, this.#endpoint.host, route);\n const headers = this.headers(route, \"text/event-stream\", opts.after ? { \"last-event-id\": opts.after } : {});\n try {\n const response = await watch.within(() =>\n fetch(this.url(route), { method: \"GET\", headers, signal: watch.signal, redirect: KEYED_REDIRECTS }),\n );\n return new PlatformStream(response, watch);\n } catch (error) {\n watch.close();\n throw error;\n }\n }\n\n private url(route: string): string {\n return `${this.#endpoint.host}${route}`;\n }\n\n private headers(route: string, accept: string, extra: Record<string, string> = {}): Record<string, string> {\n return {\n \"content-type\": \"application/json\",\n accept,\n ...platformAuthorization(this.#endpoint, this.url(route)),\n ...extra,\n };\n }\n\n private async once(\n method: PlatformMethod,\n route: string,\n body: unknown,\n timeoutMs: number,\n caller?: AbortSignal,\n ): Promise<PlatformReply> {\n if (caller?.aborted) throw caller.reason;\n const payload = body === undefined ? {} : { body: JSON.stringify(body) };\n const headers = this.headers(route, \"application/json\");\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n const relay = (): void => controller.abort(caller?.reason);\n caller?.addEventListener(\"abort\", relay, { once: true });\n try {\n const res = await fetch(this.url(route), {\n method,\n headers,\n ...payload,\n signal: controller.signal,\n redirect: KEYED_REDIRECTS,\n });\n return { status: res.status, ok: res.ok, text: await res.text() };\n } catch (error) {\n if (caller?.aborted) throw caller.reason;\n const cause = controller.signal.aborted ? TransportCause.timeout(timeoutMs) : TransportCause.of(error);\n throw new UnreachableError(this.#endpoint.host, method, route, cause);\n } finally {\n clearTimeout(timer);\n caller?.removeEventListener(\"abort\", relay);\n }\n }\n}\n\nclass StreamWatch {\n readonly #controller = new AbortController();\n readonly #caller: AbortSignal | undefined;\n readonly #relay = (): void => this.#controller.abort(this.#caller?.reason);\n #idled = false;\n\n constructor(\n caller: AbortSignal | undefined,\n readonly idleMs: number,\n private readonly host: string,\n private readonly route: string,\n ) {\n this.#caller = caller;\n caller?.addEventListener(\"abort\", this.#relay, { once: true });\n if (caller?.aborted) this.#relay();\n }\n\n get signal(): AbortSignal {\n return this.#controller.signal;\n }\n\n async within<T>(wait: () => Promise<T>): Promise<T> {\n const timer = setTimeout(() => this.idle(), this.idleMs);\n try {\n return await wait();\n } catch (error) {\n throw this.failure(error);\n } finally {\n clearTimeout(timer);\n }\n }\n\n close(): void {\n this.#caller?.removeEventListener(\"abort\", this.#relay);\n this.#controller.abort();\n }\n\n private idle(): void {\n this.#idled = true;\n this.#controller.abort();\n }\n\n private failure(error: unknown): unknown {\n if (this.#caller?.aborted) return this.#caller.reason;\n const cause = this.#idled ? TransportCause.idle(this.idleMs) : TransportCause.of(error);\n return new UnreachableError(this.host, \"GET\", this.route, cause);\n }\n}\n\n/** An open event stream: its status, then its body as it arrives. A silence past the idle budget or a dropped connection throws `UnreachableError`; the caller's abort throws its reason. */\nexport class PlatformStream {\n readonly #response: Response;\n readonly #watch: StreamWatch;\n\n constructor(response: Response, watch: StreamWatch) {\n this.#response = response;\n this.#watch = watch;\n }\n\n get status(): number {\n return this.#response.status;\n }\n\n get ok(): boolean {\n return this.#response.ok;\n }\n\n /** The body as text, for a refusal: at most the first 64 KiB of characters; closes the stream. */\n async text(): Promise<string> {\n const decoder = new TextDecoder();\n let text = \"\";\n for await (const chunk of this.chunks()) {\n text += decoder.decode(chunk, { stream: true });\n if (text.length >= REFUSAL_TEXT_LIMIT) return text.slice(0, REFUSAL_TEXT_LIMIT);\n }\n return text + decoder.decode();\n }\n\n /** The body's bytes as they arrive; the idle budget runs only while waiting for the platform, never while the caller holds a chunk. */\n async *chunks(): AsyncGenerator<Uint8Array, void, undefined> {\n const reader = this.#response.body?.getReader();\n try {\n for (;;) {\n const next = reader ? await this.#watch.within(() => reader.read()) : { done: true as const };\n if (next.done) return;\n yield next.value;\n }\n } finally {\n this.close();\n }\n }\n\n close(): void {\n this.#watch.close();\n }\n}\n","/** One path segment from an id. An empty, `.` or `..` id is refused: a URL parser would resolve it into another route. */\nexport function segment(id: string): string {\n if (id === \"\" || id === \".\" || id === \"..\") throw new TypeError(`not an id: \"${id}\"`);\n return encodeURIComponent(id);\n}\n","import type { PlatformTransport } from \"../worlds/transport\";\nimport { ApiError } from \"../worlds/apiError\";\nimport type { PlatformMethod } from \"../worlds/transport\";\nimport { Agent, AgentVersionConflictError, type EditOptions } from \"./agent\";\nimport { AgentDefinition, type AgentDefinitionInput } from \"./definition\";\nimport type { AgentPatch } from \"./patch\";\nimport { segment } from \"./segment\";\nimport type { Threads } from \"./threads\";\nimport type {\n AgentAttribution,\n AgentBuildRecord,\n AgentDeployment,\n AgentEditResult,\n AgentVersion,\n AgentVersionEntry,\n LiveAgentRecord,\n} from \"./types\";\n\nconst PRODUCTION = \"production\";\nconst PAGE_SIZE = 100;\n\nconst buildRoute = (buildId: string) => `/api/public/agent-builds/${segment(buildId)}`;\n\ntype BuildPage = { data: AgentBuildRecord[]; meta: { totalPages: number } };\n\ntype HistoryPage = { data: AgentVersionEntry[]; meta: { totalPages: number } };\n\ntype LabelMove = { agentId: string; label: string; fromBuild: string | null; toBuild: string };\n\nexport type PushOptions = { attribution?: AgentAttribution; deploy?: boolean };\n\n/** `deploy` named a version that is not one of that agent's; no label moved. */\nexport class AgentVersionNotFoundError extends Error {\n readonly code = \"version_not_found\";\n\n constructor(\n readonly agent: string,\n readonly versionId: string,\n ) {\n super(`${versionId} is not a version of ${agent}; nothing was deployed.`);\n this.name = \"AgentVersionNotFoundError\";\n }\n}\n\n/** The project's defined agents: create one live and edit it in place, or push a definition from code and deploy a version of it. */\nexport class Agents {\n readonly #transport: PlatformTransport;\n readonly #threads: Threads;\n\n constructor(transport: PlatformTransport, threads: Threads) {\n this.#transport = transport;\n this.#threads = threads;\n }\n\n /** Create an agent, live in one call: version 1, deployed. A definition `defineAgent` would refuse throws `AgentDefinitionError` before anything is sent; a name the project already holds is 409 `agent_exists`. */\n async create(input: AgentDefinitionInput): Promise<Agent> {\n const { name, ...definition } = AgentDefinition.from(input).toJSON();\n const record = await this.#transport.json<LiveAgentRecord>(\n \"POST\",\n `/api/public/agent-builds/definitions/${segment(name)}`,\n definition,\n );\n return new Agent(this, record, this.#threads);\n }\n\n /** The live agent named `name`, to edit or run; 404 `agent_not_found` when the project has none. */\n async get(name: string): Promise<Agent> {\n return new Agent(this, await this.live(name), this.#threads);\n }\n\n /** The version of `name` that edits apply to: the one `production` runs, else the newest. */\n live(name: string): Promise<LiveAgentRecord> {\n return this.#transport.json<LiveAgentRecord>(\"GET\", `/api/public/agent-builds/definitions/${segment(name)}`);\n }\n\n /** Apply one patch to `name` as a new version, live unless `deploy: false`. With `from`, a version that is no longer the live one is refused (`AgentVersionConflictError`) and nothing is written. */\n edit(name: string, patch: AgentPatch, options: EditOptions & { from?: string } = {}): Promise<AgentEditResult> {\n const body = { patch: patch.toJSON(), from: options.from, deploy: options.deploy ?? true };\n return this.conflictAware(\"POST\", `/api/public/agent-builds/definitions/${segment(name)}/versions`, body);\n }\n\n /** Move `production` of `name` to one of its versions, with the audit row; `force` crosses a breaking tool change. */\n rollback(\n name: string,\n versionId: string,\n options: { from?: string; force?: boolean } = {},\n ): Promise<LiveAgentRecord> {\n const body = { versionId, from: options.from, force: options.force ?? false };\n return this.conflictAware(\"POST\", `/api/public/agent-builds/definitions/${segment(name)}/rollback`, body);\n }\n\n /** Every version of the live agent `name`, newest first, each with `isDeployed` and its changes against the one before; a version written while the pages are read never repeats one. */\n async history(name: string): Promise<AgentVersionEntry[]> {\n const versions = new Map<string, AgentVersionEntry>();\n for (let page = 1, pages = 1; page <= pages; page += 1) {\n const query = new URLSearchParams({ page: String(page), limit: String(PAGE_SIZE) });\n const reply = await this.#transport.json<HistoryPage>(\n \"GET\",\n `/api/public/agent-builds/definitions/${segment(name)}/versions?${query}`,\n );\n for (const version of reply.data) if (!versions.has(version.id)) versions.set(version.id, version);\n pages = reply.meta.totalPages;\n }\n return [...versions.values()];\n }\n\n /** Push a definition: a new version, or the identical one already pushed (`created: false`); the platform derives its `buildHash`. With `deploy`, `production` moves to it; when that move is refused the version still exists, and pushing again returns it. */\n async push(definition: AgentDefinition, options: PushOptions = {}): Promise<AgentVersion> {\n const body = { definition: definition.toJSON(), attribution: options.attribution };\n const version = await this.#transport.json<AgentVersion>(\"POST\", \"/api/public/agent-builds/definitions\", body);\n if (!options.deploy) return version;\n await this.move(version.id, false);\n return { ...version, deployed: true, labels: [...new Set([...version.labels, PRODUCTION])] };\n }\n\n /** Move `production` to `versionId`, after checking it is a defined version of `name` (an observed build of that name is not one). Rolling back is deploying an older version; `force` crosses a breaking tool change. */\n async deploy(name: string, versionId: string, options: { force?: boolean } = {}): Promise<AgentDeployment> {\n const versions = await this.versions(name);\n if (!versions.some((version) => version.id === versionId && version.kind === \"defined\"))\n throw new AgentVersionNotFoundError(name, versionId);\n return this.move(versionId, options.force ?? false);\n }\n\n /** Every version of `name`, newest first. */\n async versions(name: string): Promise<AgentBuildRecord[]> {\n const builds: AgentBuildRecord[] = [];\n for (let page = 1, pages = 1; page <= pages; page += 1) {\n const query = new URLSearchParams({ agentId: name, page: String(page), limit: String(PAGE_SIZE) });\n const reply = await this.#transport.json<BuildPage>(\"GET\", `/api/public/agent-builds?${query}`);\n builds.push(...reply.data);\n pages = reply.meta.totalPages;\n }\n return builds;\n }\n\n private async conflictAware<T>(method: PlatformMethod, path: string, body: unknown): Promise<T> {\n try {\n return await this.#transport.json<T>(method, path, body);\n } catch (error) {\n if (error instanceof ApiError && error.code === \"agent_version_conflict\")\n throw new AgentVersionConflictError(error.status, method, path, error.text);\n throw error;\n }\n }\n\n private async move(versionId: string, force: boolean): Promise<AgentDeployment> {\n const body = { label: PRODUCTION, source: \"api\", force };\n const moved = await this.#transport.json<LabelMove>(\"POST\", `${buildRoute(versionId)}/labels`, body);\n return {\n agentId: moved.agentId,\n label: moved.label,\n versionId,\n fromBuildHash: moved.fromBuild,\n toBuildHash: moved.toBuild,\n };\n }\n}\n","import { PersonalToken } from \"./personalToken\";\nimport type { PlatformEndpoint } from \"./transport\";\n\nconst DEFAULT_HOST = \"https://withgateway.ai\";\n\nexport const GATEWAY_KEYS_MISSING =\n \"Gateway keys missing: set GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY (or pass publicKey/secretKey).\";\n\nexport function platformEndpoint(options: Partial<PlatformEndpoint>): PlatformEndpoint | null {\n if (options.token)\n return {\n host: (options.host ?? options.token.host).replace(/\\/+$/, \"\"),\n publicKey: options.publicKey ?? \"\",\n secretKey: options.secretKey ?? \"\",\n token: options.token,\n };\n const token = PersonalToken.fromEnv(process.env, {\n host: options.host,\n keys: Boolean(options.publicKey || options.secretKey),\n });\n if (token) return { host: token.host, publicKey: \"\", secretKey: \"\", token };\n const host = (options.host ?? process.env.GATEWAY_HOST ?? DEFAULT_HOST).replace(/\\/+$/, \"\");\n const publicKey = options.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;\n const secretKey = options.secretKey ?? process.env.GATEWAY_SECRET_KEY;\n if (!publicKey || !secretKey) return null;\n return { host, publicKey, secretKey };\n}\n\nexport function requirePlatformEndpoint(options: Partial<PlatformEndpoint>): PlatformEndpoint {\n const endpoint = platformEndpoint(options);\n if (!endpoint) throw new Error(GATEWAY_KEYS_MISSING);\n return endpoint;\n}\n","/** A dispatched server-sent event: its name (`message` when the server named none), its data lines joined by `\\n`, and the stream's last event id at that point. */\nexport type SseMessage = { event: string; data: string; lastEventId: string | null };\n\nexport type EventStreamErrorCode =\n | \"line_too_large\"\n | \"event_too_large\"\n | \"malformed_event\"\n | \"reconnects_exhausted\"\n | \"run_not_finished\";\n\n/** A run's event stream that cannot be read on: a line or an event past the parser's caps, an event that is not the run's JSON, too many reconnects in a row, or a run the stream ended that the platform still reads as active. Never retried. */\nexport class EventStreamError extends Error {\n constructor(\n readonly code: EventStreamErrorCode,\n message: string,\n ) {\n super(message);\n this.name = \"EventStreamError\";\n }\n}\n\n/** The parser's memory bound, in characters: one line, and one event's data lines together. */\nexport class SseLimits {\n static readonly DEFAULT = new SseLimits(4 * 1024 * 1024, 4 * 1024 * 1024);\n\n constructor(\n readonly maxLineLength: number,\n readonly maxEventLength: number,\n ) {}\n}\n\nclass EventBlock {\n readonly #data: string[] = [];\n #length = 0;\n #type = \"\";\n\n constructor(\n public id: string,\n private readonly limits: SseLimits,\n ) {}\n\n addData(value: string): void {\n this.#length += value.length + 1;\n if (this.#length > this.limits.maxEventLength)\n throw new EventStreamError(\"event_too_large\", `an event passed ${this.limits.maxEventLength} characters`);\n this.#data.push(value);\n }\n\n setType(value: string): void {\n this.#type = value;\n }\n\n setId(value: string): void {\n if (!value.includes(\"\\0\")) this.id = value;\n }\n\n message(): SseMessage | null {\n if (this.#data.length === 0) return null;\n return { event: this.#type || \"message\", data: this.#data.join(\"\\n\"), lastEventId: this.id || null };\n }\n}\n\nconst FIELDS: ReadonlyMap<string, (block: EventBlock, value: string) => void> = new Map([\n [\"data\", (block: EventBlock, value: string) => block.addData(value)],\n [\"event\", (block: EventBlock, value: string) => block.setType(value)],\n [\"id\", (block: EventBlock, value: string) => block.setId(value)],\n]);\n\n/**\n * Server-sent events from bytes, as the WHATWG EventSource reads them: CRLF, LF or CR line ends (also split across\n * chunks), comments ignored, `data` lines joined, `retry` ignored, the last event id kept across events. Lines and events\n * past `SseLimits` throw `EventStreamError`, so a hostile stream cannot grow the buffer without bound.\n */\nexport class SseParser {\n readonly #decoder = new TextDecoder();\n readonly #lineEnd = /[\\r\\n]/g;\n readonly #limits: SseLimits;\n #pending = \"\";\n #afterCarriageReturn = false;\n #lastEventId: string;\n #block: EventBlock;\n\n constructor(lastEventId: string | null = null, limits: SseLimits = SseLimits.DEFAULT) {\n this.#limits = limits;\n this.#lastEventId = lastEventId ?? \"\";\n this.#block = new EventBlock(this.#lastEventId, limits);\n }\n\n /** The id a reconnect sends as `Last-Event-ID`: the last one set before a dispatched event, or null. */\n get lastEventId(): string | null {\n return this.#lastEventId || null;\n }\n\n /** Feed the next bytes; returns the events they completed, in order. */\n push(chunk: Uint8Array): SseMessage[] {\n const messages: SseMessage[] = [];\n for (const line of this.lines(this.#decoder.decode(chunk, { stream: true }))) {\n const message = this.line(line);\n if (message) messages.push(message);\n }\n return messages;\n }\n\n private lines(text: string): string[] {\n const scanFrom = this.#pending.length;\n this.#pending += this.skipLineFeed(text);\n const lines: string[] = [];\n let start = 0;\n this.#lineEnd.lastIndex = scanFrom;\n for (let end = this.#lineEnd.exec(this.#pending); end; end = this.#lineEnd.exec(this.#pending)) {\n lines.push(this.capped(this.#pending.slice(start, end.index)));\n start = this.lineEnd(end.index);\n this.#lineEnd.lastIndex = start;\n }\n this.#pending = this.capped(this.#pending.slice(start));\n return lines;\n }\n\n private lineEnd(index: number): number {\n const crlf = this.#pending.startsWith(\"\\r\\n\", index);\n this.#afterCarriageReturn = this.#pending[index] === \"\\r\" && index + 1 === this.#pending.length;\n return index + (crlf ? 2 : 1);\n }\n\n private skipLineFeed(text: string): string {\n if (!this.#afterCarriageReturn || text === \"\") return text;\n this.#afterCarriageReturn = false;\n return text.startsWith(\"\\n\") ? text.slice(1) : text;\n }\n\n private capped(line: string): string {\n if (line.length > this.#limits.maxLineLength)\n throw new EventStreamError(\"line_too_large\", `a line passed ${this.#limits.maxLineLength} characters`);\n return line;\n }\n\n private line(line: string): SseMessage | null {\n if (line === \"\") return this.dispatch();\n if (line.startsWith(\":\")) return null;\n const colon = line.indexOf(\":\");\n const field = colon === -1 ? line : line.slice(0, colon);\n const value = colon === -1 ? \"\" : line.slice(colon + 1).replace(/^ /, \"\");\n FIELDS.get(field)?.(this.#block, value);\n return null;\n }\n\n private dispatch(): SseMessage | null {\n const message = this.#block.message();\n this.#lastEventId = this.#block.id;\n this.#block = new EventBlock(this.#lastEventId, this.#limits);\n return message;\n }\n}\n","import { ApiError } from \"../worlds/apiError\";\nimport {\n PLATFORM_STREAM_IDLE_MS,\n RetryPolicy,\n UnreachableError,\n type PlatformStream,\n type PlatformTransport,\n} from \"../worlds/transport\";\nimport { segment } from \"./segment\";\nimport { EventStreamError, SseParser, type SseMessage } from \"./sse\";\nimport type { Run, RunEvent, RunEventType, RunStatus } from \"./types\";\n\n/** The time an `AgentRun` reads and waits on; tests pass a fake. */\nexport interface RunClock {\n now(): number;\n sleep(ms: number, signal?: AbortSignal): Promise<void>;\n}\n\nexport const SYSTEM_CLOCK: RunClock = Object.freeze({\n now: () => Date.now(),\n sleep: (ms: number, signal?: AbortSignal) =>\n new Promise<void>((resolve, reject) => {\n if (signal?.aborted) return reject(signal.reason);\n const abort = () => {\n clearTimeout(timer);\n reject(signal?.reason);\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", abort);\n resolve();\n }, ms);\n signal?.addEventListener(\"abort\", abort, { once: true });\n }),\n});\n\n/** How `events()` gets back onto a run's stream: one wait per reconnect in a row (so their count is the limit), and how long a connection may stay silent. */\nexport class ReconnectPolicy {\n static readonly DEFAULT = new ReconnectPolicy([250, 500, 1_000, 2_000, 4_000], PLATFORM_STREAM_IDLE_MS);\n\n constructor(\n readonly delaysMs: readonly number[],\n readonly idleMs: number,\n ) {}\n}\n\nexport type AgentRunOptions = { clock?: RunClock; reconnect?: ReconnectPolicy };\n\nexport type RunEventsOptions = { after?: string | null; signal?: AbortSignal };\n\nexport type RequestOptions = { signal?: AbortSignal };\n\ntype Stop = \"continues\" | \"waits\" | \"ends\";\n\nconst STOPS: Readonly<Record<RunEventType, Stop>> = {\n \"run.started\": \"continues\",\n \"step.attempt\": \"continues\",\n \"message.delta\": \"continues\",\n \"step.completed\": \"continues\",\n \"tool.started\": \"continues\",\n \"tool.completed\": \"continues\",\n \"run.error\": \"continues\",\n \"action.required\": \"waits\",\n \"run.completed\": \"ends\",\n \"run.failed\": \"ends\",\n \"run.cancelled\": \"ends\",\n};\n\nconst FINISHED: ReadonlySet<RunStatus> = new Set([\"completed\", \"failed\", \"cancelled\"]);\n\nconst REFRESH_RETRIES = 3;\n\nconst STREAM_REFUSALS_RETRIED: ReadonlySet<string> = new Set([\"too_many_streams\"]);\n\nconst runRoute = (threadId: string, runId: string) => `/api/public/threads/${segment(threadId)}/runs/${segment(runId)}`;\n\nfunction readEvent(message: SseMessage): RunEvent | null {\n if (!Object.hasOwn(STOPS, message.event)) return null;\n const data = parseJson(message.data);\n if (typeof data !== \"object\" || data === null || (data as { type?: unknown }).type !== message.event)\n throw new EventStreamError(\"malformed_event\", `a ${message.event} event whose data is not that event's JSON`);\n return data as RunEvent;\n}\n\nfunction retried(refusal: ApiError): boolean {\n return RetryPolicy.TRANSIENT_STATUSES.has(refusal.status) || STREAM_REFUSALS_RETRIED.has(refusal.code ?? \"\");\n}\n\nfunction parseJson(text: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n return undefined;\n }\n}\n\ntype Position = { cursor: string | null };\n\nclass Connection {\n #delivered = false;\n #closedCleanly = false;\n #stop: Stop = \"continues\";\n #why = \"the stream closed before the run ended\";\n\n constructor(readonly openedAt: number) {}\n\n get ended(): boolean {\n return this.#stop === \"ends\";\n }\n\n // The door closes after action.required only while the run waits; when more events follow, that wait was answered.\n get stopped(): boolean {\n return this.#stop !== \"continues\";\n }\n\n get why(): string {\n return this.#why;\n }\n\n delivered(): void {\n this.#delivered = true;\n }\n\n at(stop: Stop): void {\n this.#stop = stop;\n }\n\n closedCleanly(): void {\n this.#closedCleanly = true;\n }\n\n refused(status: number): void {\n this.#why = `the platform answered ${status}`;\n }\n\n dropped(error: unknown): void {\n if (!(error instanceof UnreachableError)) throw error;\n this.#why = error.message;\n }\n\n // A silence cut, a drop or a refused status never counts as working, however long it took: only an event, or the\n // platform's own clean close of a stream that lived the idle budget (its lifetime close), starts the count again.\n working(now: number, idleMs: number): boolean {\n return this.#delivered || (this.#closedCleanly && now - this.openedAt >= idleMs);\n }\n}\n\nclass Reconnects {\n #inARow = 0;\n\n constructor(\n private readonly policy: ReconnectPolicy,\n private readonly clock: RunClock,\n private readonly route: string,\n ) {}\n\n async after(connection: Connection, signal?: AbortSignal): Promise<void> {\n this.#inARow = connection.working(this.clock.now(), this.policy.idleMs) ? 1 : this.#inARow + 1;\n const delayMs = this.policy.delaysMs[this.#inARow - 1];\n if (delayMs === undefined)\n throw new EventStreamError(\n \"reconnects_exhausted\",\n `GET ${this.route}: no working stream after ${this.policy.delaysMs.length} reconnects in a row; last: ${connection.why}`,\n );\n await this.clock.sleep(delayMs, signal);\n }\n}\n\n/** One run of a thread: its events as they happen, resumed across dropped connections from the last event delivered, and the run's state. */\nexport class AgentRun {\n readonly #transport: PlatformTransport;\n readonly #clock: RunClock;\n readonly #reconnect: ReconnectPolicy;\n #snapshot: Run;\n #cursor: string | null = null;\n #ending: RunEventType | null = null;\n\n constructor(transport: PlatformTransport, run: Run, options: AgentRunOptions = {}) {\n this.#transport = transport;\n this.#snapshot = run;\n this.#clock = options.clock ?? SYSTEM_CLOCK;\n this.#reconnect = options.reconnect ?? ReconnectPolicy.DEFAULT;\n }\n\n get id(): string {\n return this.#snapshot.id;\n }\n\n get threadId(): string {\n return this.#snapshot.threadId;\n }\n\n /** The run as last read from the platform. */\n get snapshot(): Run {\n return this.#snapshot;\n }\n\n /** The id of the last event delivered by any reader; pass it as `after` to resume this run's events elsewhere. */\n get cursor(): string | null {\n return this.#cursor;\n }\n\n /**\n * The run's events from `after` (default: where the last `events()` stopped, else the start). A dropped connection, a\n * silence past the idle budget (60 s), a 502/503/504, a 429 `too_many_streams` or the platform closing the stream\n * reconnects with `Last-Event-ID`,\n * so each event arrives once; after 5 reconnects in a row with no event delivered (a clean close after at least the idle\n * budget also counts as working) it throws `EventStreamError`. Ends after `run.completed`, `run.failed` (`not_found` when\n * the run no longer exists) or `run.cancelled`, and at an `action.required` the platform ends the stream on (the run waits\n * for a person); an `action.required` followed by more events was a wait already answered, and the events go on. A key\n * holds at most 64 open streams: past that the platform answers 429 `too_many_streams`, which counts against the same\n * five reconnects.\n */\n async *events(options: RunEventsOptions = {}): AsyncGenerator<RunEvent, void, undefined> {\n const position: Position = { cursor: options.after === undefined ? this.#cursor : options.after };\n this.#ending = null;\n const reconnects = new Reconnects(this.#reconnect, this.#clock, `${runRoute(this.threadId, this.id)}/events`);\n for (;;) {\n const connection = new Connection(this.#clock.now());\n yield* this.connect(position, connection, options.signal);\n if (connection.stopped) return;\n await reconnects.after(connection, options.signal);\n }\n }\n\n /** The run once it has finished, or once it waits for a person (`status: \"requires_action\"` with its `action`). Throws `EventStreamError` `run_not_finished` when the stream ended the run and the platform still reads it as active after the reconnect delays, and the platform's 404 `ApiError` (`not_found`) for a run that no longer exists. */\n async wait(options: RequestOptions = {}): Promise<Run> {\n const polls = this.#reconnect.delaysMs[Symbol.iterator]();\n let run = this.#ending === null ? this.#snapshot : await this.refresh(options);\n while (!this.settled(run)) {\n await this.advance(polls, options.signal);\n run = await this.refresh(options);\n }\n return run;\n }\n\n /** The run as the platform reads it now; a gateway 5xx or a dropped connection is retried with the first reconnect delays. `signal` aborts the request and its retry waits. */\n async refresh(options: RequestOptions = {}): Promise<Run> {\n const { signal } = options;\n const retry = new RetryPolicy(this.#reconnect.delaysMs.slice(0, REFRESH_RETRIES), (ms) =>\n this.#clock.sleep(ms, signal),\n );\n return this.take(\n await this.#transport.json<Run>(\"GET\", `${runRoute(this.threadId, this.id)}`, undefined, { retry, signal }),\n );\n }\n\n /** Stop the run; a run already finished answers with its status. */\n async cancel(options: RequestOptions = {}): Promise<Run> {\n const { signal } = options;\n return this.take(\n await this.#transport.json<Run>(\"POST\", `${runRoute(this.threadId, this.id)}/cancel`, {}, { signal }),\n );\n }\n\n /** Answer the question the run waits on; the run is queued again and `events()` continues from where it stopped. */\n async resolve(answer: { actionId: string; answer: string }, options: RequestOptions = {}): Promise<Run> {\n const body = { actionId: answer.actionId, answer: answer.answer };\n const { signal } = options;\n const run = await this.#transport.json<Run>(\"POST\", `${runRoute(this.threadId, this.id)}/resolve`, body, {\n signal,\n });\n this.#ending = null;\n return this.take(run);\n }\n\n private settled(run: Run): boolean {\n return FINISHED.has(run.status) || (this.#ending === \"action.required\" && run.status === \"requires_action\");\n }\n\n private async advance(polls: Iterator<number>, signal?: AbortSignal): Promise<void> {\n if (this.#ending !== null && this.#ending !== \"action.required\") return this.pause(polls, signal);\n const before = this.#cursor;\n for await (const event of this.events({ signal })) void event;\n if (this.#ending === \"action.required\" && this.#cursor === before) await this.pause(polls, signal);\n }\n\n private async pause(polls: Iterator<number>, signal?: AbortSignal): Promise<void> {\n const delay = polls.next();\n if (delay.done)\n throw new EventStreamError(\n \"run_not_finished\",\n `${runRoute(this.threadId, this.id)}: the stream ended the run with ${this.#ending}, and the platform still reads it as ${this.#snapshot.status}`,\n );\n await this.#clock.sleep(delay.value, signal);\n }\n\n private take(run: Run): Run {\n this.#snapshot = run;\n return run;\n }\n\n private async *connect(\n position: Position,\n connection: Connection,\n signal?: AbortSignal,\n ): AsyncGenerator<RunEvent, void, undefined> {\n const stream = await this.open(position, connection, signal);\n if (!stream) return;\n try {\n yield* this.read(stream, position, connection);\n connection.closedCleanly();\n } catch (error) {\n connection.dropped(error);\n } finally {\n stream.close();\n }\n }\n\n private async open(position: Position, connection: Connection, signal?: AbortSignal): Promise<PlatformStream | null> {\n const route = `${runRoute(this.threadId, this.id)}/events`;\n try {\n const stream = await this.#transport.stream(route, {\n after: position.cursor,\n signal,\n idleMs: this.#reconnect.idleMs,\n });\n return await this.accepted(stream, route, connection);\n } catch (error) {\n connection.dropped(error);\n return null;\n }\n }\n\n private async accepted(\n stream: PlatformStream,\n route: string,\n connection: Connection,\n ): Promise<PlatformStream | null> {\n if (stream.ok) return stream;\n const refusal = new ApiError(stream.status, \"GET\", route, await stream.text());\n if (!retried(refusal)) throw refusal;\n connection.refused(stream.status);\n return null;\n }\n\n private async *read(\n stream: PlatformStream,\n position: Position,\n connection: Connection,\n ): AsyncGenerator<RunEvent, void, undefined> {\n const parser = new SseParser(position.cursor);\n for await (const chunk of stream.chunks()) {\n for (const message of parser.push(chunk)) {\n const event = readEvent(message);\n this.moveTo(position, message.lastEventId);\n if (!event) continue;\n connection.delivered();\n this.note(event, connection);\n yield event;\n if (connection.ended) return;\n }\n this.moveTo(position, parser.lastEventId);\n }\n }\n\n // Each events() call resumes from its own position, so two readers of one run never skip or repeat each other's events.\n private moveTo(position: Position, cursor: string | null): void {\n position.cursor = cursor;\n this.#cursor = cursor;\n }\n\n private note(event: RunEvent, connection: Connection): void {\n const stop = STOPS[event.type];\n this.#ending = stop === \"continues\" ? null : event.type;\n connection.at(stop);\n }\n}\n","import type { PlatformTransport } from \"../worlds/transport\";\nimport { AgentRun, type AgentRunOptions } from \"./run\";\nimport { segment } from \"./segment\";\nimport type { Run, RunStatus, ThreadAutonomy, ThreadRecord, ThreadWarning } from \"./types\";\n\nconst threadRoute = (threadId: string) => `/api/public/threads/${segment(threadId)}`;\n\n/** `agent` is an agent's name, or the `Agent` that `agents.create` / `agents.get` returned. */\nexport type CreateThreadOptions = { agent: string | { readonly name: string }; title?: string; autonomy?: ThreadAutonomy };\n\nexport type SendOptions = { version?: string; multitask?: \"reject\" };\n\n/** A conversation with a deployed agent, owned by the project of the key that created it. */\nexport class Thread {\n readonly #transport: PlatformTransport;\n readonly #runs: AgentRunOptions;\n readonly id: string;\n readonly agent: string;\n readonly title: string | null;\n readonly autonomy: Readonly<Required<ThreadAutonomy>>;\n readonly activeRun: Readonly<{ id: string; status: RunStatus }> | null;\n readonly createdAt: string;\n /** Granted tools this key cannot activate; only on the thread `create` returns. */\n readonly warnings: readonly ThreadWarning[];\n\n constructor(transport: PlatformTransport, record: ThreadRecord, runs: AgentRunOptions = {}) {\n this.#transport = transport;\n this.#runs = runs;\n this.id = record.id;\n this.agent = record.agent;\n this.title = record.title;\n this.autonomy = Object.freeze({ ...record.autonomy });\n this.activeRun = record.activeRun ? Object.freeze({ ...record.activeRun }) : null;\n this.createdAt = record.createdAt;\n this.warnings = Object.freeze([...(record.warnings ?? [])]);\n }\n\n /** Start a run on the agent's deployed version (or `version`); refused with 409 `thread_busy` while another run is active. */\n async send(input: string, options: SendOptions = {}): Promise<AgentRun> {\n const body = { input, version: options.version, multitask: options.multitask };\n const run = await this.#transport.json<Run>(\"POST\", `${threadRoute(this.id)}/runs`, body);\n return new AgentRun(this.#transport, run, this.#runs);\n }\n\n /** A run of this thread by id, as it is now. */\n async run(runId: string): Promise<AgentRun> {\n const run = await this.#transport.json<Run>(\"GET\", `${threadRoute(this.id)}/runs/${segment(runId)}`);\n return new AgentRun(this.#transport, run, this.#runs);\n }\n}\n\n/** The project's threads: create one per conversation with a deployed agent, or open one by id. */\nexport class Threads {\n readonly #transport: PlatformTransport;\n readonly #runs: AgentRunOptions;\n\n constructor(transport: PlatformTransport, runs: AgentRunOptions = {}) {\n this.#transport = transport;\n this.#runs = runs;\n }\n\n /** A thread for a deployed agent; `allowSelfSchedule` or `allowSubagents` set to `true` is refused (400 `autonomy_unsupported`). */\n async create(options: CreateThreadOptions): Promise<Thread> {\n const agent = typeof options.agent === \"string\" ? options.agent : options.agent.name;\n const body = { agent, title: options.title, autonomy: options.autonomy };\n const record = await this.#transport.json<ThreadRecord>(\"POST\", \"/api/public/threads\", body);\n return new Thread(this.#transport, record, this.#runs);\n }\n\n async get(threadId: string): Promise<Thread> {\n const record = await this.#transport.json<ThreadRecord>(\"GET\", `${threadRoute(threadId)}`);\n return new Thread(this.#transport, record, this.#runs);\n }\n}\n","import { requirePlatformEndpoint } from \"../worlds/platformEndpoint\";\nimport { PlatformTransport } from \"../worlds/transport\";\nimport { Agents } from \"./agents\";\nimport type { AgentRunOptions } from \"./run\";\nimport { Threads } from \"./threads\";\n\nexport type GatewayOptions = {\n host?: string;\n publicKey?: string;\n secretKey?: string;\n transport?: PlatformTransport;\n} & AgentRunOptions;\n\n/**\n * One project's agent primitives, authenticated by its secret key: `agents` (create and edit live agents, or push and deploy definitions) and `threads`\n * (talk to a deployed agent). Keys come from the options, else `GATEWAY_HOST` / `GATEWAY_PUBLIC_KEY` /\n * `GATEWAY_SECRET_KEY`; they are never printed, logged or serialized.\n */\nexport class Gateway {\n readonly agents: Agents;\n readonly threads: Threads;\n\n constructor(options: GatewayOptions = {}) {\n const transport = options.transport ?? new PlatformTransport(requirePlatformEndpoint(options));\n this.threads = new Threads(transport, { clock: options.clock, reconnect: options.reconnect });\n this.agents = new Agents(transport, this.threads);\n Object.freeze(this);\n }\n}\n","/** The models an agent may run on; the platform's default is `claude-opus-5`. Pinned to `gatewaysdk/fixtures/agents/definition-catalogue.json`. */\nexport const AGENT_MODELS = [\"claude-opus-5\", \"claude-sonnet-5\"] as const;\n\nexport type AgentModel = (typeof AGENT_MODELS)[number];\n\nexport const AGENT_EFFORTS = [\"low\", \"medium\", \"high\", \"xhigh\"] as const;\n\nexport type AgentEffort = (typeof AGENT_EFFORTS)[number];\n\n/** The tool servers a definition may grant, each with the tool names `only` may name. Pinned to `definition-catalogue.json`. */\nexport const TOOL_SERVERS = {\n docs: [\"search_docs\"],\n drive: [\"get_drive_file\", \"list_drive_files\", \"save_drive_file\"],\n factory: [\n \"accept_factory_unit\",\n \"check_world_sandbox\",\n \"close_world_sandbox\",\n \"commit_world_sandbox\",\n \"describe_member\",\n \"diff_factory_revisions\",\n \"exec_in_world_sandbox\",\n \"generate_spine\",\n \"get_factory\",\n \"get_factory_data\",\n \"get_factory_revision\",\n \"get_spine\",\n \"get_spine_rows\",\n \"get_world_sandbox\",\n \"import_world_sandbox_data\",\n \"list_factory_revisions\",\n \"open_world_sandbox\",\n \"query_factory_data\",\n \"read_world_sandbox_file\",\n \"release_factory_data\",\n \"update_entity_graph\",\n \"update_ontology\",\n \"update_rules\",\n \"update_spine\",\n \"update_tests\",\n \"write_records\",\n \"write_world_sandbox_file\",\n ],\n sandbox: [\n \"copy_file\",\n \"execute_python\",\n \"grep_files\",\n \"ingest_sessions_to_sandbox\",\n \"list_files\",\n \"query_json\",\n \"read_file\",\n \"run_bash\",\n \"run_gateway_cli\",\n \"write_file\",\n ],\n web: [\"download_url_to_drive\", \"fetch_url\"],\n} as const;\n\nexport type ToolServer = keyof typeof TOOL_SERVERS;\n\nexport type ToolName<S extends ToolServer> = (typeof TOOL_SERVERS)[S][number];\n\n/** One server granted to an agent: all of its tools, or `only` the ones named. */\nexport type TypedGrant<S extends ToolServer = ToolServer> = {\n readonly server: S;\n readonly only?: readonly ToolName<S>[];\n};\n\n/** A tool as a definition or `agent.tools.attach` takes it: a server name, or a typed grant from `tools`. */\nexport type AgentToolInput = ToolServer | TypedGrant;\n\nconst grant =\n <S extends ToolServer>(server: S) =>\n (options: { only?: readonly ToolName<S>[] } = {}): TypedGrant<S> =>\n options.only ? { server, only: [...options.only] } : { server };\n\n/** Typed tool grants: `tools.web()` is the whole server, `tools.sandbox({ only: [\"run_gateway_cli\"] })` one tool of it. */\nexport const tools = Object.freeze({\n sandbox: grant(\"sandbox\"),\n drive: grant(\"drive\"),\n factory: grant(\"factory\"),\n web: grant(\"web\"),\n docs: grant(\"docs\"),\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCO,IAAM,WAAN,cAAuB,MAAM;AAAA,EAGlC,YACkB,QAChB,QACA,MACgB,MAChB;AACA,UAAM,SAAS,eAAe,MAAM,MAAM;AAC1C,UAAM,GAAG,MAAM,IAAI,IAAI,OAAO,MAAM,KAAK,OAAO,MAAM,EAAE;AANxC;AAGA;AAIhB,SAAK,OAAO;AACZ,SAAK,OAAO,OAAO;AAAA,EACrB;AAAA,EATkB;AAAA,EAGA;AAAA,EANF;AAalB;AAEA,IAAM,eAAe;AAErB,IAAM,eAAiD;AAAA,EACrD,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AACP;AACA,IAAM,eACJ;AACF,IAAM,YACJ;AAEF,SAAS,WAAW,MAAc,QAA2C;AAC3E,MAAI,WAAW,UAAa,UAAU,IAAK,QAAO,aAAa,MAAM,KAAK;AAC1E,SAAO,QAAQ,KAAK,IAAI,IAAI,YAAY;AAC1C;AAIO,SAAS,eAAe,MAAc,QAA0D;AACrG,QAAM,MAAM,E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C,MAC7C,QAAQ,OAAO,EAAE,QAAQ,MAAM,CAAC,GAAG,QAAQ,IAAI,EAAE,IAAI,EAAE,OAAO;AAG3D,IAAM,QAAQ,OAAO,OAAO;AAAA,EACjC,SAAS,MAAM,SAAS;AAAA,EACxB,OAAO,MAAM,OAAO;AAAA,EACpB,SAAS,MAAM,SAAS;AAAA,EACxB,KAAK,MAAM,KAAK;AAAA,EAChB,MAAM,MAAM,MAAM;AACpB,CAAC;","names":["grant"]}
@@ -1342,6 +1342,35 @@ var AGENT_EFFORTS = ["low", "medium", "high", "xhigh"];
1342
1342
  var TOOL_SERVERS = {
1343
1343
  docs: ["search_docs"],
1344
1344
  drive: ["get_drive_file", "list_drive_files", "save_drive_file"],
1345
+ factory: [
1346
+ "accept_factory_unit",
1347
+ "check_world_sandbox",
1348
+ "close_world_sandbox",
1349
+ "commit_world_sandbox",
1350
+ "describe_member",
1351
+ "diff_factory_revisions",
1352
+ "exec_in_world_sandbox",
1353
+ "generate_spine",
1354
+ "get_factory",
1355
+ "get_factory_data",
1356
+ "get_factory_revision",
1357
+ "get_spine",
1358
+ "get_spine_rows",
1359
+ "get_world_sandbox",
1360
+ "import_world_sandbox_data",
1361
+ "list_factory_revisions",
1362
+ "open_world_sandbox",
1363
+ "query_factory_data",
1364
+ "read_world_sandbox_file",
1365
+ "release_factory_data",
1366
+ "update_entity_graph",
1367
+ "update_ontology",
1368
+ "update_rules",
1369
+ "update_spine",
1370
+ "update_tests",
1371
+ "write_records",
1372
+ "write_world_sandbox_file"
1373
+ ],
1345
1374
  sandbox: [
1346
1375
  "copy_file",
1347
1376
  "execute_python",
@@ -1360,6 +1389,7 @@ var grant = (server) => (options = {}) => options.only ? { server, only: [...opt
1360
1389
  var tools = Object.freeze({
1361
1390
  sandbox: grant("sandbox"),
1362
1391
  drive: grant("drive"),
1392
+ factory: grant("factory"),
1363
1393
  web: grant("web"),
1364
1394
  docs: grant("docs")
1365
1395
  });