@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.
- package/dist/agents/index.d.mts +12 -4
- package/dist/agents/index.d.ts +12 -4
- package/dist/agents/index.js +30 -0
- package/dist/agents/index.js.map +1 -1
- package/dist/agents/index.mjs +30 -0
- package/dist/agents/index.mjs.map +1 -1
- package/dist/cli.js +2291 -945
- package/dist/cli.js.map +1 -1
- package/dist/cli.mjs +2290 -944
- package/dist/cli.mjs.map +1 -1
- package/dist/files/index.js.map +1 -1
- package/dist/files/index.mjs.map +1 -1
- package/dist/index.js +325 -184
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +324 -183
- package/dist/index.mjs.map +1 -1
- package/dist/traces/index.js.map +1 -1
- package/dist/traces/index.mjs.map +1 -1
- package/dist/tracing/index.js +1 -1
- package/dist/tracing/index.js.map +1 -1
- package/dist/tracing/index.mjs +1 -1
- package/dist/tracing/index.mjs.map +1 -1
- package/dist/worlds/index.d.mts +3 -1
- package/dist/worlds/index.d.ts +3 -1
- package/dist/worlds/index.js +178 -67
- package/dist/worlds/index.js.map +1 -1
- package/dist/worlds/index.mjs +177 -66
- package/dist/worlds/index.mjs.map +1 -1
- package/package.json +1 -1
- package/runtime/gatewaysdk/environment/bundle_manifest.py +297 -9
- package/runtime/gatewaysdk/environment/factory_documents.py +670 -0
- package/runtime/gatewaysdk/environment/factory_rules.py +973 -0
- package/runtime/gatewaysdk/environment/factory_shapes.py +253 -0
- package/runtime/gatewaysdk/environment/factory_spine.py +1155 -0
- package/runtime/gatewaysdk/environment/factory_spine_shapes.py +480 -0
- package/runtime/gatewaysdk/environment/schema/admission.py +61 -59
- package/runtime/gatewaysdk/environment/schema/cast.py +133 -67
- package/runtime/gatewaysdk/environment/schema/compiler.py +16 -17
- package/runtime/gatewaysdk/environment/schema/handler_errors.py +58 -4
- package/runtime/gatewaysdk/environment/schema/host.py +21 -2
- package/runtime/gatewaysdk/environment/schema/host_control.py +3 -1
- package/runtime/gatewaysdk/environment/schema/host_loops.py +27 -4
- package/runtime/gatewaysdk/environment/schema/host_metrics.py +69 -0
- package/runtime/gatewaysdk/environment/schema/host_requests.py +21 -0
- package/runtime/gatewaysdk/environment/schema/host_session.py +7 -0
- package/runtime/gatewaysdk/environment/schema/host_versions.py +4 -0
- package/runtime/gatewaysdk/environment/schema/host_workers.py +172 -50
- package/runtime/gatewaysdk/environment/schema/ingest.py +12 -3
- package/runtime/gatewaysdk/environment/schema/mapping.py +1 -1
- package/runtime/gatewaysdk/environment/schema/measured_tests.py +187 -0
- package/runtime/gatewaysdk/environment/schema/platform.py +57 -3
- package/runtime/gatewaysdk/environment/schema/platform_query.py +4 -3
- package/runtime/gatewaysdk/environment/schema/platform_templates.py +105 -17
- package/runtime/gatewaysdk/environment/schema/process_memory.py +76 -0
- package/runtime/gatewaysdk/environment/schema/redaction.py +13 -0
- package/runtime/gatewaysdk/environment/schema/runtime.py +14 -0
- package/runtime/gatewaysdk/environment/schema/scaffold.py +21 -4
- package/runtime/gatewaysdk/environment/schema/shape_catalog.py +493 -0
- package/runtime/gatewaysdk/environment/schema/shape_declarations.py +219 -0
- package/runtime/gatewaysdk/environment/schema/skill.py +1 -0
- package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/SKILL.md +1 -0
- package/runtime/gatewaysdk/environment/schema/skills/factory-orchestrator/SKILL.md +147 -0
- package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/ROWS.md +5 -1
- package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/SKILL.md +4 -4
- package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/SKILL.md +2 -2
- package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/cli-mcp-map.md +1 -0
- package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/shape-catalog.md +59 -0
- package/runtime/gatewaysdk/environment/schema/validation.py +14 -0
- package/runtime/gatewaysdk/environment/schema/worker.py +7 -4
- package/runtime/gatewaysdk/environment/schema/worker_key.py +38 -0
- package/runtime/gatewaysdk/environment/schema/worker_peaks.py +38 -0
- package/runtime/gatewaysdk/environment/schema/worker_watch.py +50 -0
- package/runtime/gatewaysdk/environment/schema/workers.py +237 -68
- package/runtime/gatewaysdk/environment/schema/world_host.py +56 -62
- package/runtime/gatewaysdk/environment/schema/world_tests.py +3 -1
- package/skills/connector-schema-authoring/SKILL.md +1 -0
- package/skills/connector-schema-authoring/connector-worlds.md +1 -0
- package/skills/connector-schema-authoring/world-schema.md +7 -0
- package/skills/factory-orchestrator/SKILL.md +147 -0
- package/skills/world-data-ingestion/ROWS.md +5 -1
- package/skills/world-data-ingestion/SKILL.md +4 -4
- package/skills/worlds-getting-started/SKILL.md +2 -2
- package/skills/worlds-getting-started/references/cli-mcp-map.md +1 -0
- package/skills/worlds-getting-started/references/shape-catalog.md +59 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../package.json","../../src/tracing/index.ts","../../src/tracing/identity.ts","../../src/users/index.ts","../../src/tracing/secrets.ts","../../src/tracing/session.ts","../../src/scores/index.ts","../../src/build/index.ts","../../src/tracing/prerequisites.ts","../../src/tracing/init.ts","../../src/tracing/observe.ts","../../src/tracing/instrument.ts","../../src/tracing/claude.ts","../../src/tracing/media.ts","../../src/worlds/apiError.ts","../../src/worlds/personalToken.ts","../../src/worlds/transport.ts"],"sourcesContent":["{\n \"name\": \"@withgateway/sdk\",\n \"version\": \"0.9.1\",\n \"description\": \"Gateway SDK for TypeScript - A/B experiments, tracing, and observability\",\n \"main\": \"./dist/index.js\",\n \"module\": \"./dist/index.mjs\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.mjs\",\n \"require\": \"./dist/index.js\"\n },\n \"./experiments\": {\n \"types\": \"./dist/experiments/index.d.ts\",\n \"import\": \"./dist/experiments/index.mjs\",\n \"require\": \"./dist/experiments/index.js\"\n },\n \"./context\": {\n \"types\": \"./dist/context/index.d.ts\",\n \"import\": \"./dist/context/index.mjs\",\n \"require\": \"./dist/context/index.js\"\n },\n \"./memory\": {\n \"types\": \"./dist/memory/index.d.ts\",\n \"import\": \"./dist/memory/index.mjs\",\n \"require\": \"./dist/memory/index.js\"\n },\n \"./personas\": {\n \"types\": \"./dist/personas/index.d.ts\",\n \"import\": \"./dist/personas/index.mjs\",\n \"require\": \"./dist/personas/index.js\"\n },\n \"./replay\": {\n \"types\": \"./dist/replay/index.d.ts\",\n \"import\": \"./dist/replay/index.mjs\",\n \"require\": \"./dist/replay/index.js\"\n },\n \"./sessions\": {\n \"types\": \"./dist/sessions/index.d.ts\",\n \"import\": \"./dist/sessions/index.mjs\",\n \"require\": \"./dist/sessions/index.js\"\n },\n \"./tracing\": {\n \"types\": \"./dist/tracing/index.d.ts\",\n \"import\": \"./dist/tracing/index.mjs\",\n \"require\": \"./dist/tracing/index.js\"\n },\n \"./security\": {\n \"types\": \"./dist/security/index.d.ts\",\n \"import\": \"./dist/security/index.mjs\",\n \"require\": \"./dist/security/index.js\"\n },\n \"./users\": {\n \"types\": \"./dist/users/index.d.ts\",\n \"import\": \"./dist/users/index.mjs\",\n \"require\": \"./dist/users/index.js\"\n },\n \"./scores\": {\n \"types\": \"./dist/scores/index.d.ts\",\n \"import\": \"./dist/scores/index.mjs\",\n \"require\": \"./dist/scores/index.js\"\n },\n \"./worlds\": {\n \"types\": \"./dist/worlds/index.d.ts\",\n \"import\": \"./dist/worlds/index.mjs\",\n \"require\": \"./dist/worlds/index.js\"\n },\n \"./files\": {\n \"types\": \"./dist/files/index.d.ts\",\n \"import\": \"./dist/files/index.mjs\",\n \"require\": \"./dist/files/index.js\"\n },\n \"./traces\": {\n \"types\": \"./dist/traces/index.d.ts\",\n \"import\": \"./dist/traces/index.mjs\",\n \"require\": \"./dist/traces/index.js\"\n },\n \"./hooks\": {\n \"types\": \"./dist/hooks/index.d.ts\",\n \"import\": \"./dist/hooks/index.mjs\",\n \"require\": \"./dist/hooks/index.js\"\n },\n \"./agents\": {\n \"types\": \"./dist/agents/index.d.ts\",\n \"import\": \"./dist/agents/index.mjs\",\n \"require\": \"./dist/agents/index.js\"\n },\n \"./cli\": {\n \"types\": \"./dist/cli.d.ts\",\n \"import\": \"./dist/cli.mjs\",\n \"require\": \"./dist/cli.js\"\n }\n },\n \"files\": [\n \"dist\",\n \"skills\",\n \"runtime\",\n \"README.md\"\n ],\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"scripts\": {\n \"prebuild\": \"node scripts/copy-skills.mjs && node scripts/copy-runtime.mjs\",\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"typecheck\": \"tsc --noEmit\",\n \"typecheck:examples\": \"tsc -p tsconfig.examples.json --noEmit\",\n \"test\": \"vitest\",\n \"test:run\": \"vitest run\",\n \"test:integration\": \"vitest run --config vitest.integration.config.ts\",\n \"lint\": \"eslint src --ext .ts\",\n \"clean\": \"rm -rf dist\",\n \"example\": \"tsx examples/test-ab-experiment.ts\",\n \"test:crm\": \"tsx examples/test-crm-ab-experiment.ts\",\n \"test:crm:balanced\": \"tsx examples/test-crm-ab-experiment.ts --balanced\",\n \"test:crm:full\": \"tsx examples/test-crm-ab-experiment.ts --users 12 --all-tasks --concurrency 3\"\n },\n \"keywords\": [\n \"gateway\",\n \"ab-testing\",\n \"experiments\",\n \"opentelemetry\",\n \"tracing\",\n \"observability\",\n \"llm\"\n ],\n \"author\": \"Gateway Team\",\n \"license\": \"MIT\",\n \"engines\": {\n \"node\": \">=18.0.0\"\n },\n \"peerDependencies\": {\n \"@opentelemetry/api\": \"^1.0.0\",\n \"@opentelemetry/exporter-trace-otlp-http\": \">=0.50.0\",\n \"@opentelemetry/resources\": \">=1.0.0\",\n \"@opentelemetry/sdk-trace-base\": \">=1.0.0\",\n \"@opentelemetry/sdk-trace-node\": \">=1.0.0\",\n \"playwright\": \">=1.40.0\"\n },\n \"peerDependenciesMeta\": {\n \"@opentelemetry/api\": {\n \"optional\": true\n },\n \"@opentelemetry/sdk-trace-base\": {\n \"optional\": true\n },\n \"@opentelemetry/sdk-trace-node\": {\n \"optional\": true\n },\n \"@opentelemetry/exporter-trace-otlp-http\": {\n \"optional\": true\n },\n \"@opentelemetry/resources\": {\n \"optional\": true\n },\n \"playwright\": {\n \"optional\": true\n }\n },\n \"optionalDependencies\": {\n \"@arizeai/openinference-instrumentation-anthropic\": \"^0.2.8\",\n \"@arizeai/openinference-instrumentation-openai\": \"^4.2.7\"\n },\n \"devDependencies\": {\n \"@anthropic-ai/sdk\": \"^0.91.1\",\n \"@opentelemetry/api\": \"^1.9.0\",\n \"@opentelemetry/exporter-trace-otlp-http\": \"^0.222.0\",\n \"@opentelemetry/resources\": \"^2.11.0\",\n \"@opentelemetry/sdk-trace-base\": \"^2.11.0\",\n \"@opentelemetry/sdk-trace-node\": \"^2.11.0\",\n \"@opentelemetry/semantic-conventions\": \"^1.40.0\",\n \"@types/node\": \"^20.0.0\",\n \"openai\": \"^4.70.0\",\n \"tsup\": \"^8.0.0\",\n \"tsx\": \"^4.0.0\",\n \"typescript\": \"^5.0.0\",\n \"vitest\": \"^3.2.6\"\n },\n \"overrides\": {\n \"protobufjs\": \"^8.4.1\",\n \"vite@6\": \"^6.4.3\",\n \"postcss\": \"^8.5.18\",\n \"picomatch@4\": \"^4.0.4\",\n \"nanoid\": \">=3.3.18\",\n \"esbuild\": \">=0.28.1\"\n },\n \"pnpm\": {\n \"overrides\": {\n \"protobufjs\": \"^8.4.1\",\n \"vitest\": \"^3.2.6\",\n \"vite@6\": \"^6.4.3\",\n \"postcss\": \"^8.5.18\",\n \"picomatch@4\": \"^4.0.4\",\n \"nanoid\": \">=3.3.18\",\n \"esbuild\": \">=0.28.1\"\n }\n },\n \"bin\": {\n \"gateway\": \"./dist/cli.js\"\n }\n}\n","/**\n * Tracing module for GatewaySDK TypeScript SDK.\n *\n * Provides a simple init() function that configures OpenTelemetry with\n * Gateway, mirroring the Python SDK's tracing.init() experience.\n *\n * @example\n * ```typescript\n * import { tracing } from \"@withgateway/sdk\";\n *\n * // Initialize with environment variables\n * tracing.init();\n *\n * // Or with explicit configuration\n * tracing.init({\n * host: \"https://app.gateway.dev\",\n * publicKey: \"pk-lf-...\",\n * secretKey: \"sk-lf-...\",\n * });\n *\n * // Ensure cleanup on shutdown\n * process.on(\"SIGTERM\", () => tracing.shutdown());\n * ```\n */\n\nexport type { TracingConfig, TracingState } from \"./types\";\n\nexport {\n init,\n initIsolated,\n shutdown,\n flush,\n isInitialized,\n isGatewayConfigured,\n} from \"./init\";\nexport type { TracingHandle } from \"./init\";\n\nexport {\n identify,\n resolveUserId,\n resetAmbientUser,\n IdentitySpanProcessor,\n USER_ID_ATTRIBUTE,\n} from \"./identity\";\nexport type { IdentifyOptions } from \"./identity\";\n\nexport {\n withSession,\n withWorldSession,\n getAmbientSessionId,\n getCurrentWorldSessionId,\n SessionSpanProcessor,\n SESSION_ID_ATTRIBUTE,\n WORLD_SESSION_ID_ATTRIBUTE,\n} from \"./session\";\n\nexport {\n SecretRedactingSpanProcessor,\n SpanSecrets,\n SECRET_KEYS,\n} from \"./secrets\";\n\nexport { observe } from \"./observe\";\nexport type { ObserveOptions, ObservationKind } from \"./observe\";\n\nexport { observeOpenAI, observeAnthropic } from \"./instrument\";\n\nexport { observeClaude } from \"./claude\";\nexport type { ObserveClaudeOptions } from \"./claude\";\n\nexport { MediaReference, MediaUploader, MediaUploadError, MAX_MEDIA_BYTES } from \"./media\";\nexport type { MediaField } from \"./media\";\n","/**\n * End-user identity for GatewaySDK tracing.\n *\n * Mirrors the Python SDK's `gatewaysdk.tracing.identity` user half:\n *\n * - The ambient user is set via `identify()` and stored in an\n * AsyncLocalStorage (the TS analogue of Python's ContextVar), so\n * concurrent requests serving different users never bleed into each other.\n * - `IdentitySpanProcessor` (registered by `tracing.init()`) stamps the\n * ambient user on every span at start, so everything traced after\n * `identify()` is attributed automatically — the same seam as Python's\n * `TracingContextSpanProcessor` and this SDK's `ExperimentSpanProcessor`.\n * - `identify()` also stamps the currently open span directly, because\n * ingestion treats `gateway.user.id` on ANY span as a trace-level update —\n * the in-flight trace is attributed immediately.\n */\n\nimport { AsyncLocalStorage } from \"async_hooks\";\nimport { isSpanContextValid, trace } from \"@opentelemetry/api\";\nimport type { Context } from \"@opentelemetry/api\";\nimport type {\n ReadableSpan,\n Span,\n SpanProcessor,\n} from \"@opentelemetry/sdk-trace-base\";\nimport { UsersClient } from \"../users/index\";\n\nexport const USER_ID_ATTRIBUTE = \"gateway.user.id\";\n\n// Per-async-context user identity set via identify() — AsyncLocalStorage so\n// concurrent requests serving different users never bleed into each other.\nconst currentUserStorage = new AsyncLocalStorage<string>();\n\n/**\n * The active end-user id: identify() context > GATEWAY_USER_ID env.\n *\n * Per-request user attribution (e.g. from auth middleware) can also override\n * per span by setting the `gateway.user.id` attribute directly — explicit\n * set wins over the ambient default stamped at span start.\n */\nexport function resolveUserId(): string | undefined {\n const contextual = currentUserStorage.getStore();\n if (contextual) return contextual;\n const envUser = process.env.GATEWAY_USER_ID?.trim();\n return envUser ? envUser : undefined;\n}\n\nexport interface IdentifyOptions {\n /** Profile attributes to merge into the user's stored profile. */\n attributes?: Record<string, string | number | boolean>;\n displayName?: string;\n email?: string;\n}\n\n/**\n * Attribute everything that follows (and the current trace) to a user.\n *\n * - Sets the user for all spans started in this async context, and stamps\n * the currently open span so the in-flight trace is attributed immediately.\n * - When `attributes`/`displayName`/`email` are given, the user's platform\n * profile is updated in the background (attributes merge with what's\n * stored — ideal for incremental ROI facts like plan or account_value).\n * Requires GATEWAY_HOST/GATEWAY_PUBLIC_KEY/GATEWAY_SECRET_KEY for the\n * profile update; tracing attribution works without them. Failures are\n * swallowed (debug-logged) and never produce unhandled rejections.\n *\n * @example\n * ```typescript\n * import { identify } from \"@withgateway/sdk\";\n *\n * identify(\"user-123\", {\n * attributes: { plan: \"enterprise\", account_value: \"48000\" },\n * });\n * ```\n */\nexport function identify(userId: string, options: IdentifyOptions = {}): void {\n const cleaned = userId.trim();\n if (!cleaned) return;\n\n currentUserStorage.enterWith(cleaned);\n\n // Stamp the open span so the in-flight trace is upserted with the user —\n // ingestion treats user.id on ANY span as a trace-level update.\n try {\n const span = trace.getActiveSpan();\n if (span && isSpanContextValid(span.spanContext())) {\n span.setAttribute(USER_ID_ATTRIBUTE, cleaned);\n }\n } catch (error) {\n debugLog(\"identify(): no active span to stamp\", error);\n }\n\n if (options.attributes || options.displayName || options.email) {\n void pushProfile(cleaned, options);\n }\n}\n\nasync function pushProfile(\n userId: string,\n options: IdentifyOptions,\n): Promise<void> {\n try {\n const attributes: Record<string, string> = {};\n for (const [key, value] of Object.entries(options.attributes ?? {})) {\n attributes[key] = String(value);\n }\n await UsersClient.fromEnv().update(userId, {\n ...(options.displayName !== undefined\n ? { displayName: options.displayName }\n : {}),\n ...(options.email !== undefined ? { email: options.email } : {}),\n attributes,\n });\n } catch (error) {\n debugLog(\"identify(): profile update failed\", error);\n }\n}\n\n/** Testing hook: clear the ambient user for the current async context. */\nexport function resetAmbientUser(): void {\n currentUserStorage.enterWith(undefined as unknown as string);\n}\n\n/**\n * Stamps the ambient end-user identity (identify() context or\n * GATEWAY_USER_ID env) on every span at start. Registered automatically by\n * `tracing.init()`. Explicit `setAttribute` calls after span start win over\n * this ambient default.\n */\nexport class IdentitySpanProcessor implements SpanProcessor {\n onStart(span: Span, _parentContext: Context): void {\n const userId = resolveUserId();\n if (userId) {\n span.setAttribute(USER_ID_ATTRIBUTE, userId);\n }\n }\n\n onEnd(_span: ReadableSpan): void {}\n\n async shutdown(): Promise<void> {}\n\n async forceFlush(): Promise<void> {}\n}\n\nfunction debugLog(message: string, ...args: unknown[]): void {\n if (process.env.GATEWAY_DEBUG) {\n console.debug(`[gatewaysdk.tracing] ${message}`, ...args);\n }\n}\n","/**\n * End-user profiles — attribute usage and ROI to the real people behind\n * your agent's traffic.\n *\n * Profiles pair with the platform's per-user usage metrics (traces, tokens,\n * lifetime cost) on the Users page. Attributes merge by default, so pushing\n * an incremental ROI fact is one call:\n *\n * ```typescript\n * import { UsersClient } from \"@withgateway/sdk/users\";\n *\n * const users = UsersClient.fromEnv();\n * await users.update(\"user-123\", {\n * displayName: \"Acme Corp — Jane D.\",\n * attributes: { plan: \"enterprise\", account_value: \"48000\" },\n * });\n * ```\n *\n * Tip: `identify(\"user-123\", { attributes: {...} })` does this in the\n * background AND attributes the current trace/session to the user.\n *\n * Mirrors the Python SDK's `gatewaysdk.users` module.\n */\n\ntype UserProfile = {\n userId: string;\n displayName: string | null;\n email: string | null;\n attributes: Record<string, string>;\n notes: string | null;\n};\n\ntype UserProfileUpdate = {\n displayName?: string;\n email?: string;\n attributes?: Record<string, string>;\n notes?: string;\n /**\n * Attributes merge with the stored set by default. Set `merge: false`\n * to replace the stored attributes wholesale.\n */\n merge?: boolean;\n};\n\ntype UserEvent = {\n id: string;\n userId: string;\n event: string;\n /** Emitter-defined value (e.g. minutes saved, revenue). Summed at rollup. */\n value: number | null;\n metadata: Record<string, unknown>;\n traceId: string | null;\n sessionId: string | null;\n createdAt: Date;\n};\n\ntype UserEventOptions = {\n /** Worth of the event in your terms (minutes saved, revenue…). */\n value?: number;\n metadata?: Record<string, unknown>;\n /** Link to the trace that produced the event. */\n traceId?: string;\n /** Link to the session that produced the event. */\n sessionId?: string;\n};\n\ntype UsersClientConfig = {\n host: string;\n publicKey: string;\n secretKey: string;\n timeoutSeconds?: number;\n debug?: boolean;\n};\n\ntype UsersClientFromEnvConfig = Partial<UsersClientConfig>;\n\n/** Raised when the Gateway user-profiles API cannot complete a request. */\nexport class UserProfileError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message);\n this.name = \"UserProfileError\";\n this.cause = options?.cause;\n }\n}\n\n/** Client for Gateway's end-user profile endpoints (Basic project keys). */\nexport class UsersClient {\n private readonly host: string;\n private readonly publicKey: string;\n private readonly secretKey: string;\n private readonly timeoutSeconds: number;\n private readonly debug: boolean;\n\n constructor(config: UsersClientConfig) {\n this.host = config.host.replace(/\\/$/, \"\");\n this.publicKey = config.publicKey;\n this.secretKey = config.secretKey;\n this.timeoutSeconds = config.timeoutSeconds ?? 15;\n this.debug = config.debug ?? false;\n }\n\n /** Create a client from GATEWAY_HOST / GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY. */\n static fromEnv(config: UsersClientFromEnvConfig = {}) {\n const host = config.host ?? process.env.GATEWAY_HOST;\n const publicKey = config.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;\n const secretKey = config.secretKey ?? process.env.GATEWAY_SECRET_KEY;\n\n const missing = [\n [\"host\", host],\n [\"publicKey\", publicKey],\n [\"secretKey\", secretKey],\n ]\n .filter(([, value]) => !value)\n .map(([name]) => name);\n\n if (missing.length > 0) {\n throw new UserProfileError(\n `Missing Gateway user-profile configuration: ${missing.join(\", \")}`,\n );\n }\n\n return new UsersClient({\n ...config,\n host: host!,\n publicKey: publicKey!,\n secretKey: secretKey!,\n });\n }\n\n /** Fetch a user's stored profile. */\n async get(userId: string): Promise<UserProfile> {\n return parseProfile(\n await this.requestJson(\n \"GET\",\n `/api/public/user-profiles/${encodeURIComponent(userId)}`,\n ),\n );\n }\n\n /**\n * Upsert a user's profile. `attributes` merge with the stored set unless\n * `merge: false` (which replaces it).\n */\n async update(\n userId: string,\n update: UserProfileUpdate = {},\n ): Promise<UserProfile> {\n const body: Record<string, unknown> = {\n userId,\n attributes: update.attributes ?? {},\n mergeAttributes: update.merge ?? true,\n ...(update.displayName !== undefined\n ? { displayName: update.displayName }\n : {}),\n ...(update.email !== undefined ? { email: update.email } : {}),\n ...(update.notes !== undefined ? { notes: update.notes } : {}),\n };\n return parseProfile(\n await this.requestJson(\"POST\", \"/api/public/user-profiles\", body),\n );\n }\n\n /**\n * Record a VALUE EVENT for a user — the per-user ROI stream. `value` is\n * whatever the event is worth in your terms (minutes saved, revenue…);\n * Gateway sums it in the hours-saved/ROI rollups, and evals and task-set\n * replays can assert against the events. Link `traceId`/`sessionId` to tie\n * the event to the run that produced it.\n *\n * @example\n * ```ts\n * await client.trackEvent(\"user-123\", \"checkout_completed\", {\n * value: 25,\n * metadata: { cartSize: 3 },\n * sessionId,\n * });\n * ```\n */\n async trackEvent(\n userId: string,\n event: string,\n options: UserEventOptions = {},\n ): Promise<UserEvent> {\n const body: Record<string, unknown> = {\n userId,\n event,\n metadata: options.metadata ?? {},\n ...(options.value !== undefined ? { value: options.value } : {}),\n ...(options.traceId !== undefined ? { traceId: options.traceId } : {}),\n ...(options.sessionId !== undefined\n ? { sessionId: options.sessionId }\n : {}),\n };\n return parseEvent(\n await this.requestJson(\"POST\", \"/api/public/user-events\", body),\n );\n }\n\n /** List a project's user events, optionally filtered by user/event/time. */\n async listEvents(\n filter: {\n userId?: string;\n event?: string;\n fromTimestamp?: Date;\n toTimestamp?: Date;\n page?: number;\n limit?: number;\n } = {},\n ): Promise<{ data: UserEvent[]; totalItems: number }> {\n const params = new URLSearchParams();\n if (filter.userId) params.set(\"userId\", filter.userId);\n if (filter.event) params.set(\"event\", filter.event);\n if (filter.fromTimestamp)\n params.set(\"fromTimestamp\", filter.fromTimestamp.toISOString());\n if (filter.toTimestamp)\n params.set(\"toTimestamp\", filter.toTimestamp.toISOString());\n if (filter.page) params.set(\"page\", String(filter.page));\n if (filter.limit) params.set(\"limit\", String(filter.limit));\n const qs = params.toString();\n const payload = await this.requestJson(\n \"GET\",\n `/api/public/user-events${qs ? `?${qs}` : \"\"}`,\n );\n const rows = Array.isArray(payload.data) ? payload.data : [];\n const meta =\n payload.meta && typeof payload.meta === \"object\"\n ? (payload.meta as Record<string, unknown>)\n : {};\n return {\n data: rows.map((row) => parseEvent(row as Record<string, unknown>)),\n totalItems: Number(meta.totalItems ?? rows.length),\n };\n }\n\n private async requestJson(\n method: \"GET\" | \"POST\",\n path: string,\n payload?: Record<string, unknown>,\n ): Promise<Record<string, unknown>> {\n let response: Response;\n try {\n response = await fetch(`${this.host}${path}`, {\n method,\n headers: {\n Authorization: this.authHeader(),\n \"Content-Type\": \"application/json\",\n },\n ...(payload ? { body: JSON.stringify(payload) } : {}),\n signal: AbortSignal.timeout(this.timeoutSeconds * 1000),\n });\n } catch (error) {\n throw new UserProfileError(\n `${method} ${path} failed: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n\n const text = await response.text();\n if (!response.ok) {\n throw new UserProfileError(\n `${method} ${path} failed (${response.status}): ${text.slice(0, 500)}`,\n );\n }\n\n this.log(\"%s %s -> %s\", method, path, response.status);\n return safeJson(text);\n }\n\n private authHeader() {\n return `Basic ${Buffer.from(`${this.publicKey}:${this.secretKey}`).toString(\n \"base64\",\n )}`;\n }\n\n private log(message: string, ...args: unknown[]) {\n if (this.debug) {\n console.log(`[gateway.users] ${message}`, ...args);\n }\n }\n}\n\nfunction parseEvent(payload: Record<string, unknown>): UserEvent {\n return {\n id: String(payload.id ?? \"\"),\n userId: String(payload.userId ?? \"\"),\n event: String(payload.event ?? \"\"),\n value: typeof payload.value === \"number\" ? payload.value : null,\n metadata:\n payload.metadata &&\n typeof payload.metadata === \"object\" &&\n !Array.isArray(payload.metadata)\n ? (payload.metadata as Record<string, unknown>)\n : {},\n traceId: typeof payload.traceId === \"string\" ? payload.traceId : null,\n sessionId:\n typeof payload.sessionId === \"string\" ? payload.sessionId : null,\n createdAt:\n typeof payload.createdAt === \"string\"\n ? new Date(payload.createdAt)\n : new Date(0),\n };\n}\n\nfunction parseProfile(payload: Record<string, unknown>): UserProfile {\n return {\n userId: String(payload.userId ?? \"\"),\n displayName:\n typeof payload.displayName === \"string\" ? payload.displayName : null,\n email: typeof payload.email === \"string\" ? payload.email : null,\n attributes: parseAttributes(payload.attributes),\n notes: typeof payload.notes === \"string\" ? payload.notes : null,\n };\n}\n\nfunction parseAttributes(value: unknown): Record<string, string> {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return {};\n const attributes: Record<string, string> = {};\n for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {\n attributes[key] = String(entry);\n }\n return attributes;\n}\n\nfunction safeJson(value: string): Record<string, unknown> {\n try {\n const parsed = JSON.parse(value);\n return parsed && typeof parsed === \"object\" && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : {};\n } catch {\n return {};\n }\n}\n\nexport const users = {\n fromEnv: UsersClient.fromEnv,\n};\n\nexport type {\n UserProfile,\n UserProfileUpdate,\n UserEvent,\n UserEventOptions,\n UsersClientConfig,\n UsersClientFromEnvConfig,\n};\n","/**\n * Credentials a caller hands a model SDK (an MCP server's `authorization_token`), kept out of every\n * exported span. Twin of `gatewaysdk/tracing/secrets.py`; both run\n * `fixtures/tracing/span-secret-vectors.json`.\n */\n\nimport type { Context, SpanStatus } from \"@opentelemetry/api\";\nimport type {\n ReadableSpan,\n Span,\n SpanProcessor,\n TimedEvent,\n} from \"@opentelemetry/sdk-trace-base\";\n\nexport const SECRET_KEYS: ReadonlySet<string> = new Set([\n \"authorization_token\",\n \"authorizationToken\",\n]);\n\nexport const REDACTED = \"[redacted: holds a credential]\";\nexport const MIN_SECRET_LENGTH = 8;\n\ntype Attributes = Record<string, unknown>;\n\n/**\n * Which keys are credentials, and how to keep them out of a span attribute. An attribute whose name\n * contains a key is dropped. An attribute whose value names a key is exported only when the key can\n * be removed as a JSON object key (at any depth, also inside a JSON string nested in JSON) and then\n * neither the name nor any value removed under it (`MIN_SECRET_LENGTH` or longer) appears anywhere\n * in it. Any other attribute that names a key (a cut or non-JSON string, a repr, a query string, a\n * pair list, a command line, prose) is replaced whole by `REDACTED`: no rule can know where every\n * rendering of the value sits beside its name. A removed value withholds the attribute in its\n * percent-encoded or JSON-escaped form too, and a value that cannot be scrubbed for any reason is\n * withheld whole. Attributes that name no key are exported untouched.\n */\nexport class SpanSecrets {\n constructor(readonly keys: ReadonlySet<string> = SECRET_KEYS) {}\n\n isSecret(key: string): boolean {\n return this.keys.has(key);\n }\n\n drops(attribute: string): boolean {\n return this.mentions(attribute);\n }\n\n strip(value: unknown): unknown {\n if (typeof value === \"string\") return this.stripNested(value);\n if (Array.isArray(value)) return value.map((item) => this.strip(item));\n if (value === null || typeof value !== \"object\") return value;\n return Object.fromEntries(\n Object.entries(value)\n .filter(([key]) => !this.isSecret(key))\n .map(([key, item]) => [key, this.strip(item)]),\n );\n }\n\n scrubAttribute(value: unknown): unknown {\n try {\n return this.scrubbedValue(value);\n } catch {\n return Array.isArray(value) ? [REDACTED] : REDACTED;\n }\n }\n\n private scrubbedValue(value: unknown): unknown {\n if (typeof value === \"string\") return this.scrubbedText(value);\n if (!Array.isArray(value)) return value;\n const results = value.map((item) =>\n typeof item === \"string\"\n ? this.cleaned(item)\n : { text: item, removed: new Set<string>() },\n );\n const removed = new Set(results.flatMap((r) => [...r.removed]));\n const scrubbed = results.map((r) => r.text);\n const withheld = scrubbed.some(\n (item) => typeof item === \"string\" && this.carries(item, removed),\n );\n return withheld ? [REDACTED] : scrubbed;\n }\n\n scrubAttributes(attributes: Attributes): Attributes {\n return Object.fromEntries(\n Object.entries(attributes)\n .filter(([key]) => !this.drops(key))\n .map(([key, value]) => [key, this.scrubAttribute(value)]),\n );\n }\n\n private mentions(text: string): boolean {\n return [...this.keys].some((key) => text.includes(key));\n }\n\n private scrubbedText(text: string): string {\n const { text: cleaned, removed } = this.cleaned(text);\n return this.carries(cleaned, removed) ? REDACTED : cleaned;\n }\n\n private cleaned(text: string): { text: string; removed: Set<string> } {\n if (!this.mentions(text)) return { text, removed: new Set() };\n const parsed = jsonOrUndefined(text);\n if (parsed === undefined) return { text: REDACTED, removed: new Set() };\n return {\n text: JSON.stringify(this.strip(parsed)),\n removed: this.removed(parsed),\n };\n }\n\n private carries(text: string, removed: Set<string>): boolean {\n if (text === REDACTED || this.mentions(text)) return true;\n return [...removed].some((value) =>\n encodings(value).some((form) => text.includes(form)),\n );\n }\n\n private removed(value: unknown): Set<string> {\n if (typeof value === \"string\") {\n const nested = this.mentions(value) ? jsonOrUndefined(value) : undefined;\n return nested === undefined ? new Set() : this.removed(nested);\n }\n if (Array.isArray(value)) return union(value.map((v) => this.removed(v)));\n if (value === null || typeof value !== \"object\") return new Set();\n return union(\n Object.entries(value).map(([key, item]) =>\n this.isSecret(key) ? leaves(item) : this.removed(item),\n ),\n );\n }\n\n private stripNested(text: string): string {\n if (!this.mentions(text)) return text;\n const parsed = jsonOrUndefined(text);\n if (parsed === undefined) return text;\n return JSON.stringify(this.strip(parsed));\n }\n}\n\nfunction jsonOrUndefined(text: string): unknown {\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return undefined;\n }\n if (typeof parsed === \"string\") return parsed;\n return parsed !== null && typeof parsed === \"object\" ? parsed : undefined;\n}\n\nfunction encodings(value: string): string[] {\n return [value, percentEncoded(value), JSON.stringify(value).slice(1, -1)];\n}\n\nfunction percentEncoded(value: string): string {\n try {\n return encodeURIComponent(value);\n } catch {\n return value;\n }\n}\n\nfunction union(sets: Set<string>[]): Set<string> {\n return new Set(sets.flatMap((set) => [...set]));\n}\n\nfunction leaves(value: unknown): Set<string> {\n if (typeof value === \"string\") {\n return [...value].length >= MIN_SECRET_LENGTH\n ? new Set([value])\n : new Set();\n }\n if (Array.isArray(value)) return union(value.map(leaves));\n if (value === null || typeof value !== \"object\") return new Set();\n return union(Object.values(value).map(leaves));\n}\n\nexport const SPAN_SECRETS = new SpanSecrets();\n\nfunction sameAttributes(before: Attributes, after: Attributes): boolean {\n const keys = Object.keys(before);\n if (keys.length !== Object.keys(after).length) return false;\n return keys.every(\n (key) => before[key] === after[key] || sameArray(before[key], after[key]),\n );\n}\n\nfunction sameArray(before: unknown, after: unknown): boolean {\n if (!Array.isArray(before) || !Array.isArray(after)) return false;\n return (\n before.length === after.length &&\n before.every((item, i) => item === after[i])\n );\n}\n\n/**\n * Wraps a span processor so every read it makes, at start or at end, is without the credentials\n * `SpanSecrets` names in the span's attributes, event attributes or status message, whichever\n * instrumentor recorded them. `tracing.init()` puts one in front of its exporter and every custom\n * processor. A span that cannot be scrubbed at end is dropped rather than exported as it was.\n */\nexport class SecretRedactingSpanProcessor implements SpanProcessor {\n constructor(\n private readonly inner: SpanProcessor,\n private readonly secrets: SpanSecrets = SPAN_SECRETS,\n ) {}\n\n private readonly views = new WeakMap<object, Span>();\n\n onStart(span: Span, parentContext: Context): void {\n this.inner.onStart(this.viewFor(span), parentContext);\n }\n\n onEnd(span: ReadableSpan): void {\n const view = this.viewFor(span as Span);\n try {\n void [view.attributes, view.events, view.status];\n } catch (error) {\n console.warn(\n `[gatewaysdk.tracing] Dropped span \"${span.name}\": could not redact it: ${(error as Error)?.name}`,\n );\n return;\n }\n this.inner.onEnd(view as unknown as ReadableSpan);\n }\n\n private viewFor(span: Span): Span {\n const known = this.views.get(span);\n if (known) return known;\n const view = viewOf(span, {\n attributes: () => this.scrubbedAttributes(span.attributes as Attributes),\n events: () => span.events.map((event) => this.scrubbedEvent(event)),\n status: () => this.scrubbedStatus(span.status),\n });\n this.views.set(span, view);\n return view;\n }\n\n forceFlush(): Promise<void> {\n return this.inner.forceFlush();\n }\n\n shutdown(): Promise<void> {\n return this.inner.shutdown();\n }\n\n private scrubbedAttributes(attributes: Attributes): Attributes {\n const clean = this.secrets.scrubAttributes(attributes);\n return sameAttributes(attributes, clean) ? attributes : clean;\n }\n\n private scrubbedStatus(status: SpanStatus): SpanStatus {\n if (!status.message) return status;\n const message = this.secrets.scrubAttribute(status.message) as string;\n return message === status.message ? status : { ...status, message };\n }\n\n private scrubbedEvent(event: TimedEvent): TimedEvent {\n if (!event.attributes) return event;\n const attributes = this.scrubbedAttributes(event.attributes as Attributes);\n if (attributes === event.attributes) return event;\n return { ...event, attributes: attributes as TimedEvent[\"attributes\"] };\n }\n}\n\ntype Reads = Record<\"attributes\" | \"events\" | \"status\", () => unknown>;\n\nfunction scrubbedRead(reads: Reads, property: string | symbol) {\n return typeof property === \"string\" && property in reads\n ? reads[property as keyof Reads]\n : undefined;\n}\n\nfunction viewOf<T extends object>(span: T, reads: Reads): T {\n const view: T = new Proxy(span, {\n get(target, property) {\n const read = scrubbedRead(reads, property);\n if (read) return read();\n const value = Reflect.get(target, property, target);\n if (typeof value !== \"function\") return value;\n return (...args: unknown[]) => {\n const result = value.apply(target, args);\n return result === target ? view : result;\n };\n },\n getOwnPropertyDescriptor(target, property) {\n const descriptor = Reflect.getOwnPropertyDescriptor(target, property);\n const read = scrubbedRead(reads, property);\n if (!read || !descriptor || !(\"value\" in descriptor)) return descriptor;\n return { ...descriptor, value: read() };\n },\n });\n return view;\n}\n","import { AsyncLocalStorage } from \"async_hooks\";\nimport type { Context } from \"@opentelemetry/api\";\nimport type {\n ReadableSpan,\n Span,\n SpanProcessor,\n} from \"@opentelemetry/sdk-trace-base\";\n\nexport const SESSION_ID_ATTRIBUTE = \"gateway.session.id\";\nexport const WORLD_SESSION_ID_ATTRIBUTE =\n \"gateway.trace.metadata.world_session_id\";\n\n// AsyncLocalStorage so concurrent runs or requests never bleed into each other.\n// Held on globalThis: tsup inlines this module into every published entry\n// (splitting: false), and `worlds` must write the store `tracing` reads.\n// Every SDK copy in the process shares the key and the string value; never\n// rename or reshape them.\nconst processStorage = (name: string): AsyncLocalStorage<string> => {\n const key = Symbol.for(`@withgateway/sdk/${name}`);\n const slots = globalThis as Record<symbol, AsyncLocalStorage<string>>;\n slots[key] ??= new AsyncLocalStorage<string>();\n return slots[key];\n};\nconst currentSessionStorage = processStorage(\"session-storage\");\nconst currentWorldSessionStorage = processStorage(\"world-session-storage\");\n\n/** The session id set by the innermost enclosing `withSession()`, or `undefined`. */\nexport function getAmbientSessionId(): string | undefined {\n return currentSessionStorage.getStore();\n}\n\n/** The live world session the current code is working in, or `undefined`. */\nexport function getCurrentWorldSessionId(): string | undefined {\n return currentWorldSessionStorage.getStore();\n}\n\nfunction runIn<T>(\n storage: AsyncLocalStorage<string>,\n value: string,\n fn: () => T | Promise<T>,\n): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n storage.run(value, () => {\n Promise.resolve().then(fn).then(resolve, reject);\n });\n });\n}\n\n/**\n * Group every trace recorded inside `fn` under one session id — the twin of\n * the Python SDK's `with tracing.session(session_id): ...`. Auto-instrumented\n * spans are grouped too; the innermost session wins.\n *\n * ```typescript\n * await withSession(\"checkout-regression-001\", async () => {\n * await observe(\"turn-1\", async () => { ... });\n * });\n * ```\n */\nexport function withSession<T>(\n sessionId: string,\n fn: () => T | Promise<T>,\n): Promise<T> {\n return runIn(currentSessionStorage, sessionId, fn);\n}\n\n/**\n * Trace `fn` as work inside one live world session: spans take the world\n * session's id as their session id and carry `world_session_id` trace\n * metadata. A `withSession()` block inside still wins for the session id;\n * the metadata stays. Without `tracing.init()` nothing is recorded. Twin of\n * Python's `tracing.context.world_session`; callers use\n * `WorldSession.withTraceContext(fn)`.\n */\nexport function withWorldSession<T>(\n worldSessionId: string,\n fn: () => T | Promise<T>,\n): Promise<T> {\n return runIn(currentWorldSessionStorage, worldSessionId, () =>\n withSession(worldSessionId, fn),\n );\n}\n\n/**\n * Stamps the session id and world session id on every span at start.\n * Registered by `tracing.init()`/`initIsolated()`. A session id the span was\n * started with (or is given after it starts) wins over the innermost\n * `withSession()` / `withWorldSession()` block, as in the Python SDK.\n */\nexport class SessionSpanProcessor implements SpanProcessor {\n onStart(span: Span, _parentContext: Context): void {\n const worldSessionId = getCurrentWorldSessionId();\n if (worldSessionId)\n span.setAttribute(WORLD_SESSION_ID_ATTRIBUTE, worldSessionId);\n const sessionId = getAmbientSessionId();\n if (!sessionId || span.attributes?.[SESSION_ID_ATTRIBUTE] !== undefined)\n return;\n span.setAttribute(SESSION_ID_ATTRIBUTE, sessionId);\n }\n\n onEnd(_span: ReadableSpan): void {}\n\n async shutdown(): Promise<void> {}\n\n async forceFlush(): Promise<void> {}\n}\n","/**\n * Scores & success signals — record evaluation results and ROI-shaped success\n * signals against a Gateway project.\n *\n * A **score** is any evaluation value attached to a trace or session (visible\n * on the Scores page and in trace/session detail). A **success signal** is a\n * score carrying `metadata[\"gateway.success.signal\"]`, which the platform's\n * Success Metrics feature aggregates into a metric's headline count/pass-rate\n * (the `HOOK` metric source). Emit one whenever a real unit of business value\n * happens (\"resolved a ticket\", \"ran an eval\", \"a human accepted an edit\").\n *\n * This mirrors the Python SDK's `Run.score()` / `Run.success()`\n * (`gatewaysdk/sdk/src/gatewaysdk/run.py`). The score shape — name, numeric\n * value, `gateway.success.signal` + `gateway.success.metricName` metadata, and\n * the trace/session target — is IDENTICAL so the platform aggregates signals\n * from either SDK unchanged.\n *\n * ```typescript\n * import { ScoresClient } from \"@withgateway/sdk/scores\";\n *\n * const scores = ScoresClient.fromEnv();\n * // A pass/fail signal that feeds the \"resolved_ticket\" Success Metric:\n * await scores.success(\"resolved_ticket\", true, {\n * agentId: \"support-triage\",\n * sessionId,\n * });\n * // A numeric signal:\n * await scores.success(\"handle_time_s\", 42, { agentId: \"support-triage\", sessionId });\n * ```\n *\n * Under `tracing.initIsolated(...)` the returned handle exposes a `scores`\n * client already bound to that project's keys — that is how the platform\n * self-traces its own agents into dedicated projects.\n */\n\nimport { isSpanContextValid, trace } from \"@opentelemetry/api\";\n\n/** Score value data type, matching Gateway's ingestion schema. */\nexport type ScoreDataType = \"NUMERIC\" | \"CATEGORICAL\" | \"BOOLEAN\";\n\n/** Reserved metadata keys that mark a score as an aggregatable success signal. */\nexport const SUCCESS_SIGNAL_KEY = \"gateway.success.signal\";\nexport const SUCCESS_METRIC_NAME_KEY = \"gateway.success.metricName\";\nexport const AGENT_ID_KEY = \"gateway.agent.id\";\n\nexport type ScoreOptions = {\n /**\n * Trace to link the score to. Auto-detected from the active OpenTelemetry\n * span when omitted and no `sessionId` is given (mirrors the Python SDK).\n */\n traceId?: string;\n /** Session to link the score to. Preferred target when present. */\n sessionId?: string;\n /** Dataset-run to link the score to (dataset-run scores). */\n datasetRunId?: string;\n /** Span-level score — requires `traceId`. */\n observationId?: string;\n /** \"NUMERIC\" | \"CATEGORICAL\" | \"BOOLEAN\"; inferred when omitted. */\n dataType?: ScoreDataType;\n /** Optional comment stored alongside the score. */\n comment?: string;\n /** Extra metadata merged into the score. */\n metadata?: Record<string, unknown>;\n /** Environment tag; defaults to the project's `default` environment. */\n environment?: string;\n};\n\nexport type SuccessOptions = Omit<ScoreOptions, \"dataType\"> & {\n /**\n * The agent this signal belongs to (`gateway.agent.id`). Lets the platform\n * roll the signal into that agent's Success Metric without a trace join.\n */\n agentId?: string;\n /** The Success Metric name; defaults to the signal `name`. */\n metricName?: string;\n /** Override the inferred \"BOOLEAN\"/\"NUMERIC\" data type. */\n dataType?: \"NUMERIC\" | \"BOOLEAN\";\n};\n\nexport type ScoresClientConfig = {\n host: string;\n publicKey: string;\n secretKey: string;\n timeoutSeconds?: number;\n debug?: boolean;\n};\n\nexport type ScoresClientFromEnvConfig = Partial<ScoresClientConfig>;\n\n/** Raised by the low-level {@link ScoresClient.postScore} on a failed request. */\nexport class ScoreError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message);\n this.name = \"ScoreError\";\n this.cause = options?.cause;\n }\n}\n\n/**\n * Read the current trace id (32-hex) from the active OpenTelemetry span, or\n * undefined when there is no valid active span. Mirrors the Python SDK's\n * `_get_current_trace_id`.\n */\nexport function currentTraceId(): string | undefined {\n try {\n const span = trace.getActiveSpan();\n if (!span) return undefined;\n const ctx = span.spanContext();\n if (!ctx || !isSpanContextValid(ctx)) return undefined;\n return ctx.traceId;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Client for Gateway's public scores ingestion endpoint (Basic project keys).\n * The `score`/`success` convenience methods are FAIL-SOFT — they never reject\n * into the caller, they warn and resolve — matching the Python SDK's\n * fire-and-forget scoring. The raw {@link postScore} throws on failure for\n * callers that want to handle it.\n */\nexport class ScoresClient {\n private readonly host: string;\n private readonly publicKey: string;\n private readonly secretKey: string;\n private readonly timeoutSeconds: number;\n private readonly debug: boolean;\n\n constructor(config: ScoresClientConfig) {\n this.host = config.host.replace(/\\/$/, \"\");\n this.publicKey = config.publicKey;\n this.secretKey = config.secretKey;\n this.timeoutSeconds = config.timeoutSeconds ?? 15;\n this.debug = config.debug ?? false;\n }\n\n /** Create a client from GATEWAY_HOST / GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY. */\n static fromEnv(config: ScoresClientFromEnvConfig = {}): ScoresClient {\n const host = config.host ?? process.env.GATEWAY_HOST;\n const publicKey = config.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;\n const secretKey = config.secretKey ?? process.env.GATEWAY_SECRET_KEY;\n\n const missing = [\n [\"host\", host],\n [\"publicKey\", publicKey],\n [\"secretKey\", secretKey],\n ]\n .filter(([, value]) => !value)\n .map(([name]) => name);\n\n if (missing.length > 0) {\n throw new ScoreError(\n `Missing Gateway scores configuration: ${missing.join(\", \")}`,\n );\n }\n\n return new ScoresClient({\n ...config,\n host: host!,\n publicKey: publicKey!,\n secretKey: secretKey!,\n });\n }\n\n /**\n * Post a score, throwing {@link ScoreError} on any failure. Builds the exact\n * `POST /api/public/scores` body the Python SDK sends: exactly one of\n * `sessionId` / `traceId` (+ optional `observationId`) / `datasetRunId`.\n * When no target is provided, the active OTel trace id is used; if none is\n * available the call is a no-op (returns without posting), matching Python.\n */\n async postScore(\n name: string,\n value: number | string,\n options: ScoreOptions = {},\n ): Promise<void> {\n const body = this.buildScoreBody(name, value, options);\n if (!body) {\n this.log(\n \"score '%s' dropped: no sessionId, traceId or datasetRunId available\",\n name,\n );\n return;\n }\n await this.request(\"POST\", \"/api/public/scores\", body);\n }\n\n /**\n * Build the score request body, or null when no target can be resolved.\n * Split out so it is unit-testable and shared by score()/success().\n */\n buildScoreBody(\n name: string,\n value: number | string,\n options: ScoreOptions = {},\n ): Record<string, unknown> | null {\n // Prefer sessionId (scores typically grade a whole session/rollout), then\n // datasetRunId, then an explicit traceId, then the ambient OTel trace.\n const traceId = options.traceId ?? currentTraceId();\n const target: Record<string, unknown> = {};\n if (options.sessionId) {\n target.sessionId = options.sessionId;\n } else if (options.datasetRunId) {\n target.datasetRunId = options.datasetRunId;\n } else if (traceId) {\n target.traceId = traceId;\n if (options.observationId) target.observationId = options.observationId;\n } else {\n return null;\n }\n\n // Base metadata mirrors the Python SDK (source tag), then the caller's\n // metadata is merged on top — identical to `score_metadata.update(...)`.\n const metadata: Record<string, unknown> = {\n source: \"gatewaysdk\",\n ...(options.metadata ?? {}),\n };\n\n return {\n name,\n value,\n dataType: options.dataType ?? \"NUMERIC\",\n environment: options.environment ?? \"default\",\n ...(options.comment ? { comment: options.comment } : {}),\n metadata,\n ...target,\n };\n }\n\n /**\n * Post a score, FAIL-SOFT: warns and resolves on any failure so a broken\n * transport never throws into (or rejects out of) the caller.\n */\n async score(\n name: string,\n value: number | string,\n options: ScoreOptions = {},\n ): Promise<void> {\n try {\n await this.postScore(name, value, options);\n } catch (error) {\n this.warn(`score '${name}' failed`, error);\n }\n }\n\n /**\n * Emit a SUCCESS SIGNAL that feeds a Gateway Success Metric — a score tagged\n * with `gateway.success.signal` + `gateway.success.metricName` (and the agent\n * identity when `agentId` is set). A boolean `value` records a 1/0 BOOLEAN\n * score (pass/fail); a number records a NUMERIC score. FAIL-SOFT.\n *\n * The metadata shape matches the Python SDK's `Run.success()` exactly, so the\n * platform's Success Metrics aggregation counts signals from either SDK\n * without change.\n *\n * @example\n * ```ts\n * await scores.success(\"resolved_ticket\", true, { agentId: \"support-triage\", sessionId });\n * await scores.success(\"handle_time_s\", 42, { agentId: \"support-triage\", sessionId });\n * ```\n */\n async success(\n name: string,\n value: boolean | number = true,\n options: SuccessOptions = {},\n ): Promise<void> {\n const { numericValue, inferredType } = coerceSignalValue(value);\n const { agentId, metricName, metadata, dataType, ...rest } = options;\n\n // Required signal keys are written LAST so a caller's `metadata` cannot\n // accidentally clobber them and silently drop the signal from aggregation.\n const signalMetadata: Record<string, unknown> = {\n ...(metadata ?? {}),\n [SUCCESS_SIGNAL_KEY]: true,\n [SUCCESS_METRIC_NAME_KEY]: metricName ?? name,\n ...(agentId ? { [AGENT_ID_KEY]: agentId } : {}),\n };\n\n await this.score(name, numericValue, {\n ...rest,\n dataType: dataType ?? inferredType,\n metadata: signalMetadata,\n });\n }\n\n private async request(\n method: \"POST\",\n path: string,\n payload: Record<string, unknown>,\n ): Promise<void> {\n let response: Response;\n try {\n response = await fetch(`${this.host}${path}`, {\n method,\n headers: {\n Authorization: this.authHeader(),\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(payload),\n signal: AbortSignal.timeout(this.timeoutSeconds * 1000),\n });\n } catch (error) {\n throw new ScoreError(\n `${method} ${path} failed: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n\n const text = await response.text();\n if (!response.ok) {\n throw new ScoreError(\n `${method} ${path} failed (${response.status}): ${text.slice(0, 500)}`,\n );\n }\n this.log(\"%s %s -> %s\", method, path, response.status);\n }\n\n private authHeader(): string {\n return `Basic ${Buffer.from(`${this.publicKey}:${this.secretKey}`).toString(\n \"base64\",\n )}`;\n }\n\n private log(message: string, ...args: unknown[]): void {\n if (this.debug) {\n console.log(`[gateway.scores] ${message}`, ...args);\n }\n }\n\n private warn(message: string, ...args: unknown[]): void {\n console.warn(`[gateway.scores] ${message}`, ...args);\n }\n}\n\n/** Map a success value to its numeric score + inferred data type. */\nfunction coerceSignalValue(value: boolean | number): {\n numericValue: number;\n inferredType: \"NUMERIC\" | \"BOOLEAN\";\n} {\n if (typeof value === \"boolean\") {\n return { numericValue: value ? 1 : 0, inferredType: \"BOOLEAN\" };\n }\n return { numericValue: value, inferredType: \"NUMERIC\" };\n}\n\n/**\n * Emit a success signal using credentials from the environment\n * (GATEWAY_HOST / GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY) — the ergonomic\n * top-level entry point for the default `tracing.init()` path, mirroring the\n * Python SDK's `run.success(...)`. FAIL-SOFT end to end: a missing/invalid\n * environment or a transport failure warns and resolves, never throwing into\n * the caller. For isolated providers use the handle's bound client\n * (`handle.scores.success(...)`) instead so the signal lands in that project.\n */\nexport async function success(\n name: string,\n value: boolean | number = true,\n options: SuccessOptions = {},\n): Promise<void> {\n let client: ScoresClient;\n try {\n client = ScoresClient.fromEnv();\n } catch (error) {\n console.warn(`[gateway.scores] success '${name}' skipped`, error);\n return;\n }\n await client.success(name, value, options);\n}\n\n/** Lowercase convenience namespace, matching the `users` export. */\nexport const scores = {\n fromEnv: ScoresClient.fromEnv,\n success,\n};\n","/**\n * Agent build identity — \"the agent IS the manifest.\"\n *\n * There is no build file and no lockfile. As the agent constructs itself,\n * the SDK observes everything that defines a build: tools registered through\n * defineTool() (name, declared version, schema hash, effects, source\n * location), prompts registered through registerPrompt(), the code ref from\n * CI/env, and the SDK's own version. tracing.init({ agent, version })\n * assembles the canonical manifest, computes the content-addressed\n * buildHash, stamps it on every span, and auto-registers the build with\n * Gateway (idempotent on hash — every replica of the same code is one\n * build). Releases are label moves on the platform, never mutations here.\n *\n * v1 versioning is developer-declared: you bump `version` on the agent and\n * on tools; Gateway records schema/impl hashes as evidence alongside.\n */\nimport { createHash } from \"node:crypto\";\n\nexport type ToolEffects = \"read\" | \"write\" | \"irreversible\";\n\nexport interface ToolIdentity {\n name: string;\n version?: string;\n effects?: ToolEffects;\n schemaHash: string;\n description?: string;\n /** Source location of the defineTool call (\"src/tools/checkout.ts:42\"). */\n source?: string;\n}\n\n/** Any versioned artifact an agent is built from — tools, prompts, skills,\n * datasets, guardrails, configs… `content` hashes locally (off-platform);\n * `ref` pins a platform-hosted artifact (\"prompt/system@label:production\"). */\nexport interface ArtifactIdentity {\n kind: string;\n name: string;\n version?: string;\n contentHash?: string;\n ref?: string;\n source?: string;\n metadata?: Record<string, string>;\n}\n\nexport interface AgentBuildManifest {\n agentId: string;\n codeRef?: string;\n sdk: string;\n tools: ToolIdentity[];\n prompts: Record<string, string>;\n skills: Record<string, string>;\n artifacts: ArtifactIdentity[];\n}\n\n/** Deterministic JSON: object keys sorted recursively, arrays kept in order. */\nexport function canonicalJson(value: unknown): string {\n if (value === null || typeof value !== \"object\") {\n return JSON.stringify(value);\n }\n if (Array.isArray(value)) {\n return `[${value.map(canonicalJson).join(\",\")}]`;\n }\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n return `{${entries\n .map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`)\n .join(\",\")}}`;\n}\n\nexport function sha256(text: string): string {\n return `sha256:${createHash(\"sha256\").update(text).digest(\"hex\")}`;\n}\n\n// ── Registry (module-level; one agent process = one registry) ──────────────\n\nconst registeredTools = new Map<string, ToolIdentity>();\nconst registeredPrompts = new Map<string, string>();\nconst registeredSkills = new Map<string, string>();\nconst registeredArtifacts = new Map<string, ArtifactIdentity>();\n\n/** First app-code frame of the current stack (\"src/tools/checkout.ts:42\"). */\nfunction captureSource(): string | undefined {\n const stack = new Error().stack?.split(\"\\n\") ?? [];\n for (const line of stack.slice(1)) {\n // Skip the SDK's own frames (this module, packaged dist) and node internals\n // — NOT the whole install dir, or apps developed inside a monorepo next to\n // the SDK would never resolve a source.\n if (\n line.includes(\"build/index.ts\") ||\n line.includes(\"build/index.js\") ||\n line.includes(\"build/index.mjs\") ||\n line.includes(\"node_modules/@withgateway/\")\n ) {\n continue;\n }\n if (line.includes(\"node:internal\") || line.includes(\"(node:\")) continue;\n const match = /\\(?([^()\\s]+):(\\d+):\\d+\\)?$/.exec(line.trim());\n if (match) {\n const file = match[1].replace(/^file:\\/\\//, \"\");\n // Trim to a repo-relative-ish path for readability.\n const short = file.includes(\"/\") ? file.split(\"/\").slice(-4).join(\"/\") : file;\n return `${short}:${match[2]}`;\n }\n }\n return undefined;\n}\n\nexport interface DefineToolInput {\n name: string;\n /** Developer-declared tool version, e.g. \"2.1\" (v1: bumped manually). */\n version?: string;\n /** Side-effect class — feeds approval policies and gate severity. */\n effects?: ToolEffects;\n description?: string;\n /** JSON schema (or zod-serializable shape) of the tool's parameters. */\n schema?: unknown;\n /** Alias accepted for frameworks that call it inputSchema. */\n inputSchema?: unknown;\n}\n\n/**\n * Register a tool's identity and pass the definition through unchanged, so\n * it wraps ANY framework's tool shape:\n *\n * ```ts\n * const checkout = defineTool({\n * name: \"checkout\", version: \"2.1\", effects: \"write\",\n * schema, description, execute,\n * });\n * ```\n */\nexport function defineTool<T extends DefineToolInput>(tool: T): T {\n const schemaBasis = tool.schema ?? tool.inputSchema ?? null;\n const source = captureSource();\n const identity: ToolIdentity = {\n name: tool.name,\n ...(tool.version !== undefined ? { version: tool.version } : {}),\n ...(tool.effects !== undefined ? { effects: tool.effects } : {}),\n ...(tool.description !== undefined\n ? { description: tool.description.slice(0, 500) }\n : {}),\n schemaHash: sha256(\n canonicalJson({ schema: schemaBasis, description: tool.description ?? \"\" }),\n ),\n ...(source ? { source } : {}),\n };\n registeredTools.set(tool.name, identity);\n notifyRegistryChanged();\n return tool;\n}\n\n/**\n * Register a code-shipped prompt so it joins the build identity:\n * `const SYSTEM = registerPrompt(\"system\", \"You are…\")`. Returns the content\n * unchanged. Platform-served prompts don't need this — pin them by label.\n */\nexport interface RegisterArtifactOptions {\n /** Developer-declared version, e.g. \"1.2\" (v1: bumped manually). */\n version?: string;\n /** Local content — hashed into the identity (off-platform artifacts). */\n content?: string;\n /** Platform reference (on-platform artifacts): \"prompt/system@label:production\". */\n ref?: string;\n metadata?: Record<string, string>;\n}\n\n/**\n * Version ANY artifact the agent is built from — the generic primitive\n * behind registerPrompt/registerSkill. Works on- and off-platform:\n *\n * ```ts\n * registerArtifact(\"guardrail\", \"pii-filter\", { version: \"2.0\", content: RULES });\n * registerArtifact(\"prompt\", \"planner\", { ref: \"planner@label:production\" });\n * ```\n */\nexport function registerArtifact(\n kind: string,\n name: string,\n options: RegisterArtifactOptions = {},\n): ArtifactIdentity {\n const source = captureSource();\n const identity: ArtifactIdentity = {\n kind,\n name,\n ...(options.version !== undefined ? { version: options.version } : {}),\n ...(options.content !== undefined\n ? { contentHash: sha256(options.content) }\n : {}),\n ...(options.ref !== undefined ? { ref: options.ref } : {}),\n ...(source ? { source } : {}),\n ...(options.metadata ? { metadata: options.metadata } : {}),\n };\n registeredArtifacts.set(`${kind}:${name}`, identity);\n notifyRegistryChanged();\n return identity;\n}\n\nexport function registerPrompt(\n name: string,\n content: string,\n options: { version?: string } = {},\n): string {\n registeredPrompts.set(name, sha256(content));\n registerArtifact(\"prompt\", name, { ...options, content });\n return content;\n}\n\nexport function getRegisteredTools(): ToolIdentity[] {\n return [...registeredTools.values()].sort((a, b) =>\n a.name < b.name ? -1 : a.name > b.name ? 1 : 0,\n );\n}\n\n/**\n * Register a skill's identity — `registerSkill(\"triage\", \"1.0\")` — so skills\n * are versioned in the build like tools and prompts. The version string is\n * whatever you bump (or a content hash for file-based skills).\n */\nexport function registerSkill(\n name: string,\n version: string,\n options: { content?: string; ref?: string } = {},\n): void {\n registeredSkills.set(name, version);\n registerArtifact(\"skill\", name, { version, ...options });\n}\n\nexport function getRegisteredArtifacts(): ArtifactIdentity[] {\n return [...registeredArtifacts.values()].sort((a, b) =>\n `${a.kind}:${a.name}` < `${b.kind}:${b.name}` ? -1 : 1,\n );\n}\n\nexport function getRegisteredSkills(): Record<string, string> {\n return Object.fromEntries(\n [...registeredSkills.entries()].sort(([a], [b]) =>\n a < b ? -1 : a > b ? 1 : 0,\n ),\n );\n}\n\nexport function getRegisteredPrompts(): Record<string, string> {\n return Object.fromEntries(\n [...registeredPrompts.entries()].sort(([a], [b]) =>\n a < b ? -1 : a > b ? 1 : 0,\n ),\n );\n}\n\n/** Test hook. */\nexport function resetBuildRegistry(): void {\n registeredTools.clear();\n registeredPrompts.clear();\n registeredSkills.clear();\n registeredArtifacts.clear();\n activeBuilds.length = 0;\n if (reRegisterTimer) clearTimeout(reRegisterTimer);\n reRegisterTimer = null;\n}\n\n// ── Manifest assembly + registration ───────────────────────────────────────\n\nfunction sdkVersion(): string {\n try {\n // dist/build/index.js -> ../../package.json ; src/build -> same shape.\n /* eslint-disable-next-line @typescript-eslint/no-require-imports */\n const pkg = require(\"../../package.json\") as { version?: string };\n return `@withgateway/sdk@${pkg.version ?? \"unknown\"}`;\n } catch {\n return \"@withgateway/sdk\";\n }\n}\n\n/**\n * Git context most PaaS runtimes inject automatically (Vercel, Render,\n * Railway, Netlify, Heroku). On those hosts attribution is fully\n * zero-config — no GATEWAY_* or GITHUB_* env plumbing needed. Explicit\n * env vars always win; this only fills gaps.\n */\nexport function paasGitContext(): {\n provider: string;\n sha?: string;\n repo?: string;\n branch?: string;\n login?: string;\n} | null {\n const env = process.env;\n if (env.VERCEL_GIT_COMMIT_SHA) {\n // Only surface the repo when it's GitHub-shaped — enrichment is\n // GitHub-only; a GitLab/Bitbucket repo would just 404 over there.\n const isGithub = (env.VERCEL_GIT_PROVIDER ?? \"github\") === \"github\";\n return {\n provider: \"vercel\",\n sha: env.VERCEL_GIT_COMMIT_SHA,\n repo:\n isGithub && env.VERCEL_GIT_REPO_OWNER && env.VERCEL_GIT_REPO_SLUG\n ? `${env.VERCEL_GIT_REPO_OWNER}/${env.VERCEL_GIT_REPO_SLUG}`\n : undefined,\n branch: env.VERCEL_GIT_COMMIT_REF,\n login: env.VERCEL_GIT_COMMIT_AUTHOR_LOGIN,\n };\n }\n if (env.RENDER_GIT_COMMIT) {\n return {\n provider: \"render\",\n sha: env.RENDER_GIT_COMMIT,\n repo: env.RENDER_GIT_REPO_SLUG, // already \"owner/repo\"\n branch: env.RENDER_GIT_BRANCH,\n };\n }\n if (env.RAILWAY_GIT_COMMIT_SHA) {\n return {\n provider: \"railway\",\n sha: env.RAILWAY_GIT_COMMIT_SHA,\n repo:\n env.RAILWAY_GIT_REPO_OWNER && env.RAILWAY_GIT_REPO_NAME\n ? `${env.RAILWAY_GIT_REPO_OWNER}/${env.RAILWAY_GIT_REPO_NAME}`\n : undefined,\n branch: env.RAILWAY_GIT_BRANCH,\n login: env.RAILWAY_GIT_AUTHOR,\n };\n }\n if (env.NETLIFY && env.COMMIT_REF) {\n const repoMatch = /github\\.com[/:]([^/]+\\/[^/.]+)/.exec(\n env.REPOSITORY_URL ?? \"\",\n );\n return {\n provider: \"netlify\",\n sha: env.COMMIT_REF,\n repo: repoMatch?.[1],\n branch: env.BRANCH,\n };\n }\n // Heroku (dyno metadata) and common bare conventions: sha only — the\n // platform resolves the repo server-side via the GitHub connection.\n const bareSha =\n env.HEROKU_SLUG_COMMIT ?? env.SOURCE_VERSION ?? env.GIT_COMMIT ?? env.COMMIT_SHA;\n if (bareSha) {\n return {\n provider: env.HEROKU_SLUG_COMMIT || env.SOURCE_VERSION ? \"heroku\" : \"generic\",\n sha: bareSha,\n };\n }\n return null;\n}\n\nfunction codeRef(): string | undefined {\n const paas = paasGitContext();\n const sha =\n process.env.GATEWAY_COMMIT ??\n process.env.GITHUB_SHA ??\n process.env.CI_COMMIT_SHA ?? // GitLab\n process.env.CIRCLE_SHA1 ??\n paas?.sha;\n if (!sha) return undefined;\n const repo =\n process.env.GITHUB_REPOSITORY ?? process.env.CI_PROJECT_PATH ?? paas?.repo;\n return repo ? `git:${repo}@${sha}` : `git:${sha}`;\n}\n\nexport function assembleManifest(agentId: string): AgentBuildManifest {\n return {\n agentId,\n ...(codeRef() ? { codeRef: codeRef() } : {}),\n sdk: sdkVersion(),\n tools: getRegisteredTools(),\n prompts: getRegisteredPrompts(),\n skills: getRegisteredSkills(),\n artifacts: getRegisteredArtifacts(),\n };\n}\n\nexport function computeBuildHash(manifest: AgentBuildManifest): string {\n // Source locations are display metadata, not identity — the same tool\n // declared on a different line (or after a refactor that moved it) is the\n // same tool. They stay in the manifest payload for the platform to show.\n const identity = {\n ...manifest,\n tools: manifest.tools.map(({ source: _source, ...tool }) => tool),\n artifacts: manifest.artifacts.map(\n ({ source: _source, ...artifact }) => artifact,\n ),\n };\n return sha256(canonicalJson(identity));\n}\n\nexport function attributionFromEnv(): Record<string, unknown> {\n const attribution: Record<string, unknown> = { source: \"runtime\" };\n if (process.env.GITHUB_ACTIONS) attribution.source = \"ci\";\n if (process.env.GITHUB_ACTOR) attribution.githubLogin = process.env.GITHUB_ACTOR;\n const sha = process.env.GATEWAY_COMMIT ?? process.env.GITHUB_SHA;\n if (sha) attribution.commitSha = sha;\n if (process.env.GITHUB_REPOSITORY) attribution.repo = process.env.GITHUB_REPOSITORY;\n const branch = process.env.GITHUB_HEAD_REF ?? process.env.GITHUB_REF_NAME;\n if (branch) attribution.branch = branch;\n // PaaS-injected git context (Vercel/Render/Railway/Netlify/Heroku) fills\n // any gaps — zero-config attribution on those hosts. Explicit env wins.\n const paas = paasGitContext();\n if (paas) {\n if (attribution.source === \"runtime\") attribution.source = `paas:${paas.provider}`;\n if (!attribution.commitSha && paas.sha) attribution.commitSha = paas.sha;\n if (!attribution.repo && paas.repo) attribution.repo = paas.repo;\n if (!attribution.branch && paas.branch) attribution.branch = paas.branch;\n if (!attribution.githubLogin && paas.login) attribution.githubLogin = paas.login;\n }\n const ref = process.env.GITHUB_REF ?? \"\";\n const prMatch = /refs\\/pull\\/(\\d+)\\//.exec(ref);\n if (prMatch) attribution.prNumber = Number(prMatch[1]);\n // PR title/body are NOT in the default Actions env — workflows pass them\n // through in two lines:\n // env:\n // GATEWAY_PR_TITLE: ${{ github.event.pull_request.title }}\n // GATEWAY_PR_BODY: ${{ github.event.pull_request.body }}\n if (process.env.GATEWAY_PR_TITLE) {\n attribution.prTitle = process.env.GATEWAY_PR_TITLE.slice(0, 300);\n }\n if (process.env.GATEWAY_PR_BODY) {\n attribution.prDescription = process.env.GATEWAY_PR_BODY.slice(0, 2000);\n }\n if (\n attribution.repo &&\n attribution.prNumber &&\n !(\"prUrl\" in attribution)\n ) {\n attribution.prUrl = `https://github.com/${String(attribution.repo)}/pull/${String(attribution.prNumber)}`;\n }\n return attribution;\n}\n\n// ── Late registration ──────────────────────────────────────────────────────\n// Many agents build their tool maps lazily (per request), AFTER init. Any\n// defineTool/registerPrompt/registerSkill call re-assembles the manifest for\n// every active agent build (debounced) and re-registers when the hash moved.\n// Content-addressed and idempotent: the registry simply gains the fullest\n// manifest; traces keep the hash stamped at init (documented behavior).\n\nexport interface ActiveBuildContext {\n host: string;\n publicKey: string;\n secretKey: string;\n agentId: string;\n version?: string;\n lastRegisteredHash?: string;\n}\n\nconst activeBuilds: ActiveBuildContext[] = [];\nlet reRegisterTimer: ReturnType<typeof setTimeout> | null = null;\nconst RE_REGISTER_DEBOUNCE_MS = 3000;\n\nexport function trackActiveBuild(context: ActiveBuildContext): void {\n activeBuilds.push(context);\n}\n\nfunction notifyRegistryChanged(): void {\n if (activeBuilds.length === 0) return;\n if (reRegisterTimer) clearTimeout(reRegisterTimer);\n reRegisterTimer = setTimeout(() => {\n reRegisterTimer = null;\n for (const context of activeBuilds) {\n const manifest = assembleManifest(context.agentId);\n const buildHash = computeBuildHash(manifest);\n if (buildHash === context.lastRegisteredHash) continue;\n context.lastRegisteredHash = buildHash;\n void registerBuild({ ...context, manifest, buildHash }).catch(() => {\n // fail-soft; a later change retries via the next notify\n context.lastRegisteredHash = undefined;\n });\n }\n }, RE_REGISTER_DEBOUNCE_MS);\n // Never hold the process open just to re-register.\n if (typeof reRegisterTimer === \"object\" && \"unref\" in reRegisterTimer) {\n (reRegisterTimer as { unref(): void }).unref();\n }\n}\n\n/**\n * Fire-and-forget build registration. Idempotent on buildHash server-side;\n * failures are logged once and never affect the agent.\n */\nexport async function registerBuild(params: {\n host: string;\n publicKey: string;\n secretKey: string;\n agentId: string;\n version?: string;\n manifest: AgentBuildManifest;\n buildHash: string;\n}): Promise<void> {\n const auth = Buffer.from(`${params.publicKey}:${params.secretKey}`).toString(\n \"base64\",\n );\n const response = await fetch(\n `${params.host.replace(/\\/$/, \"\")}/api/public/agent-builds`,\n {\n method: \"POST\",\n headers: {\n Authorization: `Basic ${auth}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n agentId: params.agentId,\n buildHash: params.buildHash,\n ...(params.version ? { semanticVer: params.version } : {}),\n manifest: params.manifest,\n attribution: attributionFromEnv(),\n }),\n signal: AbortSignal.timeout(15_000),\n },\n );\n if (!response.ok) {\n throw new Error(\n `build registration failed (${response.status}): ${(await response.text()).slice(0, 300)}`,\n );\n }\n}\n","export const GATEWAY_ENV = {\n HOST: \"GATEWAY_HOST\",\n PUBLIC_KEY: \"GATEWAY_PUBLIC_KEY\",\n SECRET_KEY: \"GATEWAY_SECRET_KEY\",\n API_KEY: \"GATEWAY_API_KEY\",\n ENDPOINT: \"GATEWAY_OTLP_ENDPOINT\",\n} as const;\n\nexport const OTLP_TRACES_PATH = \"/api/public/otel/v1/traces\";\n\nexport const OPENTELEMETRY_PEERS = {\n \"@opentelemetry/api\": \"1.9.0\",\n \"@opentelemetry/exporter-trace-otlp-http\": \"0.222.0\",\n \"@opentelemetry/resources\": \"2.11.0\",\n \"@opentelemetry/sdk-trace-base\": \"2.11.0\",\n \"@opentelemetry/sdk-trace-node\": \"2.11.0\",\n} as const;\n\nconst PINNED_PEERS = Object.entries(OPENTELEMETRY_PEERS)\n .map(([name, version]) => `${name}@${version}`)\n .join(\" \");\n\nconst MODULE_NOT_FOUND = new Set([\"MODULE_NOT_FOUND\", \"ERR_MODULE_NOT_FOUND\"]);\n\nexport function getEnv(key: string): string | undefined {\n const value = process.env[key];\n return value ? value : undefined;\n}\n\n/**\n * Check if Gateway is configured via environment variables.\n */\nexport function isGatewayConfigured(): boolean {\n return !!(\n getEnv(GATEWAY_ENV.HOST) &&\n getEnv(GATEWAY_ENV.PUBLIC_KEY) &&\n getEnv(GATEWAY_ENV.SECRET_KEY)\n );\n}\n\nexport class OpenTelemetryMissing extends Error {\n constructor() {\n super(\n \"OpenTelemetry packages not found. Install them next to @withgateway/sdk, at the versions it is tested with:\\n\" +\n ` npm install ${PINNED_PEERS}\\n` +\n ` npm install -g ${PINNED_PEERS} (the gateway CLI, when it was installed with npm install -g)`,\n );\n this.name = \"OpenTelemetryMissing\";\n }\n\n static explains(error: unknown): boolean {\n if (error instanceof OpenTelemetryMissing) return true;\n const { code, message } = (error ?? {}) as {\n code?: unknown;\n message?: unknown;\n };\n return (\n MODULE_NOT_FOUND.has(String(code)) &&\n String(message).includes(\"@opentelemetry/\")\n );\n }\n}\n","import type { Tracer } from \"@opentelemetry/api\";\nimport type { TracingConfig, TracingState } from \"./types\";\nimport { IdentitySpanProcessor } from \"./identity\";\nimport { SecretRedactingSpanProcessor } from \"./secrets\";\nimport { SessionSpanProcessor } from \"./session\";\nimport { ScoresClient } from \"../scores/index\";\nimport {\n assembleManifest,\n computeBuildHash,\n registerBuild,\n trackActiveBuild,\n type AgentBuildManifest,\n} from \"../build/index\";\nimport {\n GATEWAY_ENV,\n getEnv,\n OpenTelemetryMissing,\n OTLP_TRACES_PATH,\n} from \"./prerequisites\";\n\nexport { isGatewayConfigured } from \"./prerequisites\";\n\nconst state: TracingState & { debug?: boolean } = {\n initialized: false,\n provider: null,\n};\n\nfunction log(message: string, ...args: unknown[]): void {\n if (state.debug) {\n console.log(`[gatewaysdk.tracing] ${message}`, ...args);\n }\n}\n\nfunction warn(message: string, ...args: unknown[]): void {\n console.warn(`[gatewaysdk.tracing] ${message}`, ...args);\n}\n\ntype LogFn = (message: string, ...args: unknown[]) => void;\n\n/**\n * Handle to an isolated tracing provider created by initIsolated().\n * Spans started from `tracer` export to that provider's Gateway project;\n * the global tracer (from init()) is untouched.\n */\nexport interface TracingHandle {\n tracer: Tracer;\n /**\n * Scores/success-signal client bound to THIS provider's project keys. Emit\n * ROI success signals into the same project the handle's spans export to —\n * `handle.scores.success(\"resolved_ticket\", true, { agentId, sessionId })` —\n * without threading credentials through your own code. Fail-soft, like the\n * rest of the client.\n */\n scores: ScoresClient;\n /** Force-flush pending spans for this provider only. */\n flush(): Promise<void>;\n /** Flush and shut down this provider only. */\n shutdown(): Promise<void>;\n}\n\n/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-require-imports */\nfunction buildProvider(config: TracingConfig, logFn: LogFn): any {\n const host = config.host ?? getEnv(GATEWAY_ENV.HOST);\n const publicKey = config.publicKey ?? getEnv(GATEWAY_ENV.PUBLIC_KEY);\n const secretKey = config.secretKey ?? getEnv(GATEWAY_ENV.SECRET_KEY);\n const endpoint =\n config.endpoint ??\n getEnv(GATEWAY_ENV.ENDPOINT) ??\n (host ? `${host.replace(/\\/$/, \"\")}${OTLP_TRACES_PATH}` : undefined);\n\n const missing: string[] = [];\n if (!host) missing.push(\"host (or GATEWAY_HOST env var)\");\n if (!publicKey) missing.push(\"publicKey (or GATEWAY_PUBLIC_KEY env var)\");\n if (!secretKey) missing.push(\"secretKey (or GATEWAY_SECRET_KEY env var)\");\n\n if (missing.length > 0) {\n throw new Error(\n `Missing required Gateway configuration: ${missing.join(\", \")}. ` +\n \"Provide these values via init() parameters or environment variables.\",\n );\n }\n\n // Peer dependencies, required lazily; `any` avoids cross-version OTel type conflicts.\n let NodeTracerProvider: any;\n let BatchSpanProcessor: any;\n let OTLPTraceExporter: any;\n let createResource: (attrs: Record<string, string>) => any;\n let ATTR_SERVICE_NAME: string;\n\n try {\n const traceNode = require(\"@opentelemetry/sdk-trace-node\");\n const traceBase = require(\"@opentelemetry/sdk-trace-base\");\n const otlpHttp = require(\"@opentelemetry/exporter-trace-otlp-http\");\n const resources = require(\"@opentelemetry/resources\");\n\n NodeTracerProvider = traceNode.NodeTracerProvider;\n BatchSpanProcessor = traceBase.BatchSpanProcessor;\n OTLPTraceExporter = otlpHttp.OTLPTraceExporter;\n\n if (resources.Resource) {\n createResource = (attrs) => new resources.Resource(attrs);\n } else if (resources.resourceFromAttributes) {\n createResource = resources.resourceFromAttributes;\n } else {\n createResource = () => resources.defaultResource();\n }\n\n try {\n const semconv = require(\"@opentelemetry/semantic-conventions\");\n ATTR_SERVICE_NAME =\n semconv.ATTR_SERVICE_NAME ??\n semconv.SEMRESATTRS_SERVICE_NAME ??\n \"service.name\";\n } catch {\n ATTR_SERVICE_NAME = \"service.name\";\n }\n } catch {\n throw new OpenTelemetryMissing();\n }\n\n const resourceAttrs: Record<string, string> = {\n [ATTR_SERVICE_NAME]: config.serviceName ?? \"gatewaysdk-tracing\",\n };\n if (config.environment) {\n resourceAttrs[\"gateway.environment\"] = config.environment;\n }\n if (config.version) {\n resourceAttrs[\"gateway.version\"] = config.version;\n }\n\n // Tools defined after init do not join the build identity.\n let buildInfo: { manifest: AgentBuildManifest; buildHash: string } | null =\n null;\n if (config.agent) {\n const manifest = assembleManifest(config.agent);\n const buildHash = computeBuildHash(manifest);\n buildInfo = { manifest, buildHash };\n resourceAttrs[\"gateway.agent.id\"] = config.agent;\n resourceAttrs[\"gateway.build.hash\"] = buildHash;\n if (config.version) {\n resourceAttrs[\"gateway.agent.version\"] = config.version;\n }\n logFn(\n \"Agent build identity: %s @ %s (%d tools, %d prompts)\",\n config.agent,\n buildHash.slice(0, 15),\n manifest.tools.length,\n Object.keys(manifest.prompts).length,\n );\n }\n\n let isLocalhost = false;\n if (endpoint) {\n try {\n const parsed = new URL(endpoint);\n isLocalhost =\n parsed.hostname === \"localhost\" || parsed.hostname === \"127.0.0.1\";\n } catch {\n isLocalhost = false;\n }\n }\n if (endpoint && !endpoint.startsWith(\"https://\") && !isLocalhost) {\n throw new Error(\n `Refusing to send credentials over insecure HTTP to ${endpoint}. ` +\n \"Use HTTPS or localhost for development.\",\n );\n }\n\n const credentials = `${publicKey}:${secretKey}`;\n const encoded = Buffer.from(credentials).toString(\"base64\");\n const authHeader = `Basic ${encoded}`;\n\n const exporter = new OTLPTraceExporter({\n url: endpoint,\n headers: {\n Authorization: authHeader,\n },\n });\n\n logFn(\"Configured Gateway exporter: endpoint=%s\", endpoint);\n\n // Custom processors go before the exporting BatchSpanProcessor.\n const spanProcessors: any[] = [];\n\n if (config.customSpanProcessors) {\n for (const sp of config.customSpanProcessors) {\n spanProcessors.push(new SecretRedactingSpanProcessor(sp as any));\n logFn(\n \"Added custom span processor: %s\",\n (sp as { constructor?: { name?: string } }).constructor?.name ??\n \"unknown\",\n );\n }\n }\n\n spanProcessors.push(new IdentitySpanProcessor());\n\n spanProcessors.push(new SessionSpanProcessor());\n\n const batchConfig: Record<string, number> = {};\n if (config.batch?.maxQueueSize) {\n batchConfig.maxQueueSize = config.batch.maxQueueSize;\n }\n if (config.batch?.scheduledDelayMillis) {\n batchConfig.scheduledDelayMillis = config.batch.scheduledDelayMillis;\n }\n if (config.batch?.maxExportBatchSize) {\n batchConfig.maxExportBatchSize = config.batch.maxExportBatchSize;\n }\n\n spanProcessors.push(\n new SecretRedactingSpanProcessor(\n new BatchSpanProcessor(exporter, batchConfig),\n ),\n );\n\n // OTel v2 removed addSpanProcessor(); its processors go in the constructor.\n let provider: any = new NodeTracerProvider({\n resource: createResource(resourceAttrs),\n });\n\n if (typeof provider.addSpanProcessor === \"function\") {\n for (const sp of spanProcessors) {\n provider.addSpanProcessor(sp);\n }\n } else {\n provider = new NodeTracerProvider({\n resource: createResource(resourceAttrs),\n spanProcessors,\n });\n }\n\n return {\n provider,\n buildInfo,\n connection: { host: host!, publicKey: publicKey!, secretKey: secretKey! },\n };\n}\n/* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/no-require-imports */\n\nfunction scheduleBuildRegistration(\n config: TracingConfig,\n built: ReturnType<typeof buildProvider>,\n): void {\n if (!config.agent || !built.buildInfo || config.registerBuild === false) {\n return;\n }\n const { manifest, buildHash } = built.buildInfo;\n // Track so tools/prompts/skills registered AFTER init re-register the\n // fullest manifest (debounced, content-addressed, idempotent).\n trackActiveBuild({\n host: built.connection.host,\n publicKey: built.connection.publicKey,\n secretKey: built.connection.secretKey,\n agentId: config.agent,\n version: config.version,\n lastRegisteredHash: buildHash,\n });\n void registerBuild({\n host: built.connection.host,\n publicKey: built.connection.publicKey,\n secretKey: built.connection.secretKey,\n agentId: config.agent,\n version: config.version,\n manifest,\n buildHash,\n }).catch((err: unknown) => {\n warn(\"Build registration failed (agent keeps running):\", err);\n });\n}\n\n/**\n * Initialize GatewaySDK tracing with automatic OpenTelemetry configuration.\n *\n * This function configures OpenTelemetry with a connection to Gateway\n * and sets up the ExperimentSpanProcessor for automatic experiment tagging.\n *\n * The Vercel AI SDK 7 emits spans only through a telemetry integration:\n * call `registerTelemetry(new OpenTelemetry())` (`registerTelemetry` from\n * `ai`, `OpenTelemetry` from `@ai-sdk/otel`) once after init(), or pass\n * `telemetry: { integrations: [new OpenTelemetry()] }` per call. AI SDK 6\n * takes `experimental_telemetry: { isEnabled: true }` instead.\n *\n * @example\n * ```typescript\n * import { tracing } from \"@withgateway/sdk\";\n *\n * // Using environment variables (GATEWAY_HOST, GATEWAY_PUBLIC_KEY, GATEWAY_SECRET_KEY)\n * tracing.init();\n *\n * // Or with explicit configuration\n * tracing.init({\n * host: \"https://app.gateway.dev\",\n * publicKey: \"pk-lf-...\",\n * secretKey: \"sk-lf-...\",\n * serviceName: \"my-agent\",\n * environment: \"production\",\n * });\n * ```\n */\nexport function init(config: TracingConfig = {}): void {\n if (state.initialized) {\n log(\"Tracing already initialized. Call shutdown() first to reinitialize.\");\n return;\n }\n\n state.debug = config.debug ?? false;\n\n const built = buildProvider(config, log);\n const provider = built.provider;\n provider.register();\n scheduleBuildRegistration(config, built);\n\n state.provider = provider;\n state.initialized = true;\n\n log(\n \"GatewaySDK tracing initialized successfully (service=%s)\",\n config.serviceName ?? \"gatewaysdk-tracing\",\n );\n}\n\n/**\n * Create an ISOLATED tracing provider that is NOT registered globally.\n *\n * Use this when one process must export different work to different Gateway\n * projects (e.g. a server hosting several agents, each with its own project\n * keys), or when the process already has its own global OpenTelemetry\n * provider that must not be replaced.\n *\n * Spans only reach the isolated provider when started from its `tracer` —\n * pass it explicitly to observe()/observeClaude() via their `tracer` option,\n * or to a framework's telemetry hook. On the Vercel AI SDK 7 that is\n * `telemetry: { integrations: [new OpenTelemetry({ tracer })] }`, with\n * `OpenTelemetry` from `@ai-sdk/otel`; AI SDK 6 takes\n * `experimental_telemetry: { isEnabled: true, tracer }` instead. Context\n * propagation still works across providers, so nesting behaves exactly as\n * with init().\n *\n * Can be called any number of times; each handle has its own exporter,\n * batch queue, and lifecycle.\n *\n * @example\n * ```typescript\n * import { tracing } from \"@withgateway/sdk\";\n *\n * const support = tracing.initIsolated({\n * host: \"https://app.gateway.dev\",\n * publicKey: \"pk-lf-support...\",\n * secretKey: \"sk-lf-support...\",\n * serviceName: \"support-agent\",\n * });\n *\n * await tracing.observe(\"support.run\", run, { tracer: support.tracer });\n * await support.flush();\n * ```\n *\n * @example\n * ```typescript\n * import { OpenTelemetry } from \"@ai-sdk/otel\";\n * import { generateText } from \"ai\";\n *\n * await generateText({\n * model,\n * prompt,\n * telemetry: {\n * integrations: [new OpenTelemetry({ tracer: support.tracer })],\n * },\n * });\n * ```\n */\nexport function initIsolated(config: TracingConfig = {}): TracingHandle {\n const debugLog: LogFn = config.debug\n ? (message, ...args) =>\n console.log(`[gatewaysdk.tracing:isolated] ${message}`, ...args)\n : () => {};\n\n const built = buildProvider(config, debugLog);\n const provider = built.provider;\n scheduleBuildRegistration(config, built);\n const tracer = provider.getTracer(\"@withgateway/sdk\") as Tracer;\n\n const scores = new ScoresClient({\n host: built.connection.host,\n publicKey: built.connection.publicKey,\n secretKey: built.connection.secretKey,\n debug: config.debug ?? false,\n });\n\n debugLog(\n \"Isolated tracing provider created (service=%s)\",\n config.serviceName ?? \"gatewaysdk-tracing\",\n );\n\n return {\n tracer,\n scores,\n async flush() {\n try {\n await (provider as { forceFlush: () => Promise<void> }).forceFlush();\n } catch (e) {\n warn(\"Error during isolated flush:\", e);\n }\n },\n async shutdown() {\n try {\n await (provider as { shutdown: () => Promise<void> }).shutdown();\n } catch (e) {\n warn(\"Error during isolated shutdown:\", e);\n }\n },\n };\n}\n\n/**\n * Force flush all pending spans without shutting down.\n *\n * Useful for ensuring spans are exported at specific points\n * (e.g., after completing a batch of work) without ending the tracing session.\n *\n * @returns Promise that resolves when flush completes\n */\nexport async function flush(): Promise<void> {\n if (!state.provider) {\n log(\"No provider to flush\");\n return;\n }\n\n try {\n await (state.provider as { forceFlush: () => Promise<void> }).forceFlush();\n log(\"Flush completed successfully\");\n } catch (e) {\n warn(\"Error during flush:\", e);\n }\n}\n\n/**\n * Force flush all pending spans and shutdown the tracer provider.\n *\n * This function should be called before process exit to ensure all spans\n * are exported. It is safe to call multiple times.\n *\n * @example\n * ```typescript\n * import { tracing } from \"@withgateway/sdk\";\n *\n * tracing.init();\n *\n * // On shutdown\n * process.on(\"SIGTERM\", async () => {\n * await tracing.shutdown();\n * process.exit(0);\n * });\n * ```\n */\nexport async function shutdown(): Promise<void> {\n if (!state.initialized || !state.provider) {\n log(\"Tracing not initialized, nothing to shutdown\");\n return;\n }\n\n try {\n await (state.provider as { shutdown: () => Promise<void> }).shutdown();\n log(\"Shutdown complete\");\n } catch (e) {\n warn(\"Error during shutdown:\", e);\n }\n\n state.provider = null;\n state.initialized = false;\n}\n\n/**\n * Check if tracing has been initialized.\n */\nexport function isInitialized(): boolean {\n return state.initialized;\n}\n","/**\n * observe() — group a unit of work (an agent run, a tool call) into a single\n * span so nested LLM/tool spans attach to it and the whole thing is one trace.\n *\n * Mirrors Langfuse's `observe()` / `startActiveObservation()`. This is what an\n * app uses to define a trace boundary when it drives a raw client loop (which\n * has no framework root span of its own): the callback runs inside the span's\n * OpenTelemetry context, so any auto-instrumented calls (see observeOpenAI) and\n * any nested observe() calls become children of it.\n *\n * The span carries OpenInference attributes (openinference.span.kind, input.value,\n * output.value), and Gateway maps a root span's input.value/output.value to the\n * trace-level input/output — so the trace shows the user input and final output.\n */\nimport { trace, context, SpanStatusCode } from \"@opentelemetry/api\";\nimport type { Tracer } from \"@opentelemetry/api\";\n\nexport type ObservationKind = \"AGENT\" | \"CHAIN\" | \"TOOL\" | \"LLM\" | \"RETRIEVER\";\n\nexport interface ObserveOptions {\n /** Recorded as input.value on the span (JSON-stringified if not a string). */\n input?: unknown;\n /** OpenInference span kind. Defaults to \"AGENT\" for the outer run. */\n kind?: ObservationKind;\n /**\n * When true (default), the callback's return value is recorded as\n * output.value. Set false if the return value is large/uninteresting.\n */\n captureOutput?: boolean;\n /**\n * Tracer to start the span from. Defaults to the GLOBAL tracer (set up by\n * tracing.init()). Pass an initIsolated() handle's tracer to route this\n * observation to that handle's Gateway project instead.\n */\n tracer?: Tracer;\n /**\n * Extra attributes for the span — e.g. gateway.session.id /\n * gateway.user.id to group runs into a session and attribute them to a user.\n */\n attributes?: Record<string, string>;\n}\n\nfunction asAttr(value: unknown): string {\n return typeof value === \"string\" ? value : JSON.stringify(value);\n}\n\n/**\n * Run `fn` inside a span named `name`. Anything traced inside (auto-instrumented\n * client calls, nested observe() calls) nests under it, forming one trace.\n *\n * @example\n * ```ts\n * const result = await observe(\"my-agent.run\", async () => {\n * // client.chat.completions.create(...) here becomes a child GENERATION\n * return finalText;\n * }, { input: prompt });\n * ```\n */\nexport async function observe<T>(\n name: string,\n fn: () => Promise<T>,\n options: ObserveOptions = {},\n): Promise<T> {\n const tracer = options.tracer ?? trace.getTracer(\"@withgateway/sdk\");\n const span = tracer.startSpan(name, {\n attributes: {\n \"openinference.span.kind\": options.kind ?? \"AGENT\",\n ...(options.input !== undefined\n ? { \"input.value\": asAttr(options.input) }\n : {}),\n ...(options.attributes ?? {}),\n },\n });\n\n try {\n const result = await context.with(\n trace.setSpan(context.active(), span),\n fn,\n );\n if (options.captureOutput !== false && result !== undefined) {\n span.setAttribute(\"output.value\", asAttr(result));\n }\n span.setStatus({ code: SpanStatusCode.OK });\n return result;\n } catch (error) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: error instanceof Error ? error.message : String(error),\n });\n throw error;\n } finally {\n span.end();\n }\n}\n","/**\n * Client wrappers that turn an SDK's calls into spans on the Gateway provider.\n *\n * Node ESM can't retroactively patch a module the app already imported, so — as\n * Langfuse does with `observeOpenAI` — the app hands us the client and we\n * instrument it explicitly. One SDK call, no OpenTelemetry in the app.\n *\n * The OpenInference instrumentations are bundled optional deps of this package;\n * we load them with require() (the ESM build injects a real createRequire).\n */\n/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-require-imports */\n\nfunction warn(message: string, ...args: unknown[]): void {\n console.warn(`[gatewaysdk.tracing] ${message}`, ...args);\n}\n\n/**\n * Instrument an OpenAI client so its requests become GENERATION spans on the\n * Gateway provider. Returns the same client (its class prototype is patched, so\n * this and every other instance of that client are traced).\n *\n * @example\n * ```ts\n * import OpenAI from \"openai\";\n * import { init, observeOpenAI } from \"@withgateway/sdk/tracing\";\n * init();\n * const client = observeOpenAI(new OpenAI());\n * ```\n */\nexport function observeOpenAI<T extends object>(client: T): T {\n try {\n const {\n OpenAIInstrumentation,\n } = require(\"@arizeai/openinference-instrumentation-openai\");\n // OpenInference patches `module.OpenAI.Chat.Completions.prototype`, so it\n // needs an object shaped like the openai module. Reconstruct it from the\n // instance's class (client.constructor === the OpenAI class).\n const OpenAIClass = (client as { constructor: unknown }).constructor;\n new OpenAIInstrumentation().manuallyInstrument({ OpenAI: OpenAIClass });\n } catch (error) {\n warn(\n \"observeOpenAI: could not load @arizeai/openinference-instrumentation-openai — OpenAI calls will not be traced.\",\n error,\n );\n }\n return client;\n}\n\n/**\n * Instrument an Anthropic client so its requests become GENERATION spans.\n *\n * @example\n * ```ts\n * import Anthropic from \"@anthropic-ai/sdk\";\n * import { init, observeAnthropic } from \"@withgateway/sdk/tracing\";\n * init();\n * const client = observeAnthropic(new Anthropic());\n * ```\n */\nexport function observeAnthropic<T extends object>(client: T): T {\n try {\n const {\n AnthropicInstrumentation,\n } = require(\"@arizeai/openinference-instrumentation-anthropic\");\n // The instrumentor patches `module.Messages.prototype.create`, so it wants\n // an object whose `Messages` is the Anthropic client's Messages class (a\n // static on the class). `client.messages` resolves `create` through that\n // prototype, so patching it traces this client and every other instance.\n const AnthropicClass = (client as { constructor: { Messages?: unknown } })\n .constructor;\n new AnthropicInstrumentation().manuallyInstrument({\n Messages: AnthropicClass.Messages,\n });\n } catch (error) {\n warn(\n \"observeAnthropic: could not load @arizeai/openinference-instrumentation-anthropic — Anthropic calls will not be traced.\",\n error,\n );\n }\n return client;\n}\n","/**\n * observeClaude() — trace a Claude Agent SDK run.\n *\n * The Claude Agent SDK runs the agent in a separate `claude` CLI subprocess, so\n * there's nothing in-process to patch. What the app has is the message stream it\n * iterates. Wrap that stream with observeClaude() and it yields the same\n * messages unchanged while emitting spans on the Gateway provider.\n *\n * Default (one trace per run):\n *\n * AGENT (root)\n * ├─ GENERATION per assistant turn (with per-turn token usage)\n * └─ TOOL per tool call (input from tool_use, output from the\n * matching tool_result, matched by id)\n *\n * With `perTurn: true` (one trace PER ASSISTANT TURN — long agent runs read as\n * a session of turn traces, the way a chat thread does):\n *\n * AGENT \"<name> · turn N\" (detached root; session/user attributes on every turn)\n * ├─ GENERATION (that turn's usage + text)\n * └─ TOOL per tool call in the turn\n *\n * An \"assistant turn\" is one Anthropic API message. The SDK streams that\n * message as several `assistant` events — one per content block (text, then\n * each tool_use), all sharing `message.id` and all repeating the message-level\n * `usage`. Slices of the same message are folded into ONE generation (and one\n * turn in per-turn mode) so usage is counted once and the turn's text and tool\n * calls land on the same span.\n *\n * The TS equivalent of the Python SDK's claude-agent-sdk instrumentor.\n *\n * @example\n * ```ts\n * const stream = query({ prompt, options });\n * for await (const message of observeClaude(stream, { name, input: prompt })) {\n * // ...consume messages as usual\n * }\n * ```\n */\nimport {\n trace,\n context,\n SpanStatusCode,\n type Span,\n type Context,\n type Tracer,\n} from \"@opentelemetry/api\";\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nexport interface ObserveClaudeOptions {\n /** Root span name (becomes the trace name; per-turn mode appends `· turn N`). */\n name: string;\n /** Recorded as input.value on the root span → trace-level input. */\n input?: string;\n /**\n * Model label for the generation spans when the assistant message does not\n * carry one (`message.message.model` wins when present so cost attribution\n * matches the model that actually answered).\n */\n model?: string;\n /**\n * Tracer to start spans from. Defaults to the GLOBAL tracer (set up by\n * tracing.init()). Pass an initIsolated() handle's tracer to route this\n * run to that handle's Gateway project instead.\n */\n tracer?: Tracer;\n /**\n * Extra attributes for the root span(s) — e.g. gateway.session.id /\n * gateway.user.id to group runs into a session and attribute them to a user.\n * In per-turn mode these ride EVERY turn root, so each turn trace maps to\n * the session.\n */\n attributes?: Record<string, string>;\n /**\n * Emit one TRACE PER ASSISTANT TURN instead of a single trace for the whole\n * run. Each turn's trace carries that turn's generation and tool calls; the\n * turn's input is the run input (turn 1) or the tool results that fed it\n * (later turns). Turn roots are detached (`root: true`), so they never nest\n * under ambient spans. Combine with `attributes.gateway.session.id` to read\n * a whole run as a session of turns.\n */\n perTurn?: boolean;\n}\n\n/** Strip the `mcp__<server>__` prefix so tool names read cleanly. */\nfunction cleanToolName(name: string): string {\n return name.replace(/^mcp__[^_]+__/, \"\");\n}\n\nfunction toolResultText(content: unknown): string {\n if (typeof content === \"string\") return content;\n if (Array.isArray(content))\n return content\n .map((b) =>\n b && typeof b === \"object\" && \"text\" in b\n ? String((b as { text: unknown }).text)\n : JSON.stringify(b),\n )\n .join(\"\");\n return JSON.stringify(content ?? \"\");\n}\n\n/** `→ tool_a, → tool_b` — what a turn \"said\" when it only called tools. */\nfunction toolSummary(names: readonly string[]): string {\n return names.map((n) => `→ ${n}`).join(\", \");\n}\n\n/** Anthropic message usage → OpenInference token-count attributes. */\nconst USAGE_ATTRIBUTES: ReadonlyArray<readonly [string, string]> = [\n [\"input_tokens\", \"llm.token_count.prompt\"],\n [\"output_tokens\", \"llm.token_count.completion\"],\n [\"cache_read_input_tokens\", \"llm.token_count.prompt_details.cache_read\"],\n [\"cache_creation_input_tokens\", \"llm.token_count.prompt_details.cache_write\"],\n];\n\nfunction setUsageAttributes(span: Span, usage: unknown): void {\n if (!usage || typeof usage !== \"object\") return;\n const u = usage as Record<string, unknown>;\n for (const [field, attribute] of USAGE_ATTRIBUTES) {\n const value = u[field];\n if (typeof value === \"number\" && Number.isFinite(value))\n span.setAttribute(attribute, value);\n }\n}\n\nconst TURN_INPUT_MAX = 4000;\n\nexport async function* observeClaude(\n stream: AsyncIterable<any>,\n options: ObserveClaudeOptions,\n): AsyncGenerator<any> {\n const tracer = options.tracer ?? trace.getTracer(\"@withgateway/sdk\");\n const fallbackModel = options.model ?? \"claude\";\n const openTools = new Map<string, Span>();\n\n // Single-trace mode: one root for the whole run.\n let root: Span | null = null;\n let rootCtx: Context | null = null;\n if (!options.perTurn) {\n root = tracer.startSpan(options.name, {\n attributes: {\n \"openinference.span.kind\": \"AGENT\",\n ...(options.input !== undefined\n ? { \"input.value\": options.input }\n : {}),\n ...(options.attributes ?? {}),\n },\n });\n rootCtx = trace.setSpan(context.active(), root);\n }\n\n // Per-turn mode: the current turn's root, rotated on each assistant message.\n let turnRoot: Span | null = null;\n let turnCtx: Context | null = null;\n let turnIndex = 0;\n let turnText = \"\";\n let turnTools: string[] = [];\n // What fed the CURRENT turn: the run input for turn 1, then the tool results\n // produced since the previous assistant message.\n let pendingTurnInput = options.input ?? \"\";\n\n // The open generation for the assistant message currently streaming in.\n let gen: Span | null = null;\n let genMessageId: string | undefined;\n let genText = \"\";\n let genTools: string[] = [];\n let genUsage: unknown;\n\n let finalText = \"\";\n\n const endGeneration = () => {\n if (!gen) return;\n gen.setAttribute(\"output.value\", genText || toolSummary(genTools));\n setUsageAttributes(gen, genUsage);\n gen.setStatus({ code: SpanStatusCode.OK });\n gen.end();\n gen = null;\n genMessageId = undefined;\n genText = \"\";\n genTools = [];\n genUsage = undefined;\n };\n\n const endTurn = () => {\n if (!turnRoot) return;\n const output = turnText || toolSummary(turnTools);\n if (output) turnRoot.setAttribute(\"output.value\", output);\n turnRoot.setStatus({ code: SpanStatusCode.OK });\n turnRoot.end();\n turnRoot = null;\n turnCtx = null;\n };\n\n const startTurn = () => {\n // A new assistant message starts a new turn: any tools still open belong\n // to the previous turn — settle them, then rotate the root.\n for (const span of openTools.values()) span.end();\n openTools.clear();\n endTurn();\n turnIndex += 1;\n turnText = \"\";\n turnTools = [];\n turnRoot = tracer.startSpan(`${options.name} · turn ${turnIndex}`, {\n root: true,\n attributes: {\n \"openinference.span.kind\": \"AGENT\",\n ...(pendingTurnInput\n ? { \"input.value\": pendingTurnInput.slice(0, TURN_INPUT_MAX) }\n : {}),\n ...(options.attributes ?? {}),\n },\n });\n turnCtx = trace.setSpan(context.active(), turnRoot);\n pendingTurnInput = \"\";\n };\n\n const startGeneration = (message: any) => {\n endGeneration();\n if (options.perTurn) startTurn();\n const childCtx = (options.perTurn ? turnCtx : rootCtx)!;\n genMessageId = message.message?.id;\n gen = tracer.startSpan(\n \"assistant\",\n {\n attributes: {\n \"openinference.span.kind\": \"LLM\",\n \"llm.model_name\": message.message?.model ?? fallbackModel,\n \"llm.provider\": \"anthropic\",\n },\n },\n childCtx,\n );\n };\n\n try {\n for await (const message of stream) {\n if (message?.type === \"assistant\") {\n const messageId: string | undefined = message.message?.id;\n const continuesGeneration =\n gen !== null && messageId !== undefined && messageId === genMessageId;\n if (!continuesGeneration) startGeneration(message);\n const childCtx = (options.perTurn ? turnCtx : rootCtx)!;\n\n for (const block of message.message?.content ?? []) {\n if (block?.type === \"text\") {\n finalText += block.text;\n turnText += block.text;\n genText += block.text;\n }\n if (block?.type === \"tool_use\") {\n const name = cleanToolName(block.name);\n genTools.push(name);\n turnTools.push(name);\n const span = tracer.startSpan(\n `tool.${name}`,\n {\n attributes: {\n \"openinference.span.kind\": \"TOOL\",\n \"tool.name\": name,\n \"input.value\": JSON.stringify(block.input),\n },\n },\n childCtx,\n );\n openTools.set(block.id, span);\n }\n }\n // Every slice repeats the message-level usage; the last one is final.\n if (message.message?.usage) genUsage = message.message.usage;\n }\n\n // tool_result (in a `user` message) closes the matching TOOL span, and in\n // per-turn mode also becomes part of the NEXT turn's input.\n if (message?.type === \"user\") {\n const content = message.message?.content;\n if (Array.isArray(content)) {\n for (const block of content) {\n if (block?.type === \"tool_result\") {\n const resultText = toolResultText(block.content);\n const span = openTools.get(block.tool_use_id);\n if (span) {\n span.setAttribute(\"output.value\", resultText);\n span.setStatus({ code: SpanStatusCode.OK });\n span.end();\n openTools.delete(block.tool_use_id);\n }\n if (options.perTurn && pendingTurnInput.length < TURN_INPUT_MAX) {\n pendingTurnInput +=\n (pendingTurnInput ? \"\\n\" : \"\") +\n resultText.slice(0, TURN_INPUT_MAX - pendingTurnInput.length);\n }\n }\n }\n }\n }\n\n yield message;\n }\n } finally {\n endGeneration();\n for (const span of openTools.values()) span.end();\n openTools.clear();\n if (options.perTurn) {\n endTurn();\n } else if (root) {\n root.setAttribute(\"output.value\", finalText);\n root.setStatus({ code: SpanStatusCode.OK });\n root.end();\n }\n }\n}\n","/**\n * Attach an image (or any media) to a span: upload the bytes to the\n * platform's media store and put the returned reference into the span's\n * input or output. The trace view renders the reference inline:\n *\n * @@@langfuseMedia:type=image/png|id=<mediaId>|source=bytes@@@\n *\n * Three steps against `/api/public/media`: ask for a presigned URL (the\n * platform links the media to the trace and observation), PUT the bytes, then\n * report the upload's status. The presigned URL is a credential and never\n * reaches a log or an error. Python twin: `gatewaysdk/tracing/media.py`.\n * No OpenTelemetry import here, so the worlds entry can use it.\n */\nimport { createHash } from \"node:crypto\";\n\nimport { PlatformTransport, type PlatformMethod } from \"../worlds/transport\";\n\nexport const MEDIA_PATH = \"/api/public/media\";\nexport const MAX_MEDIA_BYTES = 5 * 1024 * 1024;\nconst PUT_TIMEOUT_MS = 30_000;\nconst MAX_UPLOAD_ERROR = 500;\nconst NETWORK_FAILURE_STATUS = 599;\n\nexport type MediaField = \"input\" | \"output\" | \"metadata\";\n\nexport class MediaUploadError extends Error {\n constructor(\n message: string,\n readonly status?: number,\n ) {\n super(message);\n this.name = \"MediaUploadError\";\n }\n}\n\nexport class MediaReference {\n constructor(\n readonly mediaId: string,\n readonly contentType: string,\n ) {}\n\n toString(): string {\n return `@@@langfuseMedia:type=${this.contentType}|id=${this.mediaId}|source=bytes@@@`;\n }\n}\n\nexport type PutBytes = (\n url: string,\n data: Buffer,\n headers: Record<string, string>,\n) => Promise<{ status: number; error: string | null }>;\n\n/** PUT to a presigned URL; a network failure is status 599 with the error's\n * name only, so the URL never travels. */\nexport async function putBytes(\n url: string,\n data: Buffer,\n headers: Record<string, string>,\n): Promise<{ status: number; error: string | null }> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), PUT_TIMEOUT_MS);\n try {\n const res = await fetch(url, {\n method: \"PUT\",\n body: new Uint8Array(data),\n headers,\n signal: controller.signal,\n });\n return {\n status: res.status,\n error: res.ok ? null : (await res.text()).slice(0, MAX_UPLOAD_ERROR),\n };\n } catch (error) {\n return {\n status: NETWORK_FAILURE_STATUS,\n error: error instanceof Error ? error.name : \"Error\",\n };\n } finally {\n clearTimeout(timer);\n }\n}\n\n/** Uploads media for one project (the key pair's). */\nexport class MediaUploader {\n constructor(\n private readonly transport: PlatformTransport,\n private readonly put: PutBytes = putBytes,\n public maxBytes: number = MAX_MEDIA_BYTES,\n ) {}\n\n /** The uploader for `GATEWAY_HOST` / `GATEWAY_PUBLIC_KEY` /\n * `GATEWAY_SECRET_KEY` only; null when any is unset, so a run traced with a saved login uploads none. */\n static fromEnv(env: NodeJS.ProcessEnv = process.env): MediaUploader | null {\n const host = env.GATEWAY_HOST;\n const publicKey = env.GATEWAY_PUBLIC_KEY;\n const secretKey = env.GATEWAY_SECRET_KEY;\n if (!host || !publicKey || !secretKey) return null;\n return new MediaUploader(\n new PlatformTransport({\n host: host.replace(/\\/$/, \"\"),\n publicKey,\n secretKey,\n }),\n );\n }\n\n /** Store `data` linked to the trace (and observation) and return its reference. */\n async upload(\n data: Buffer,\n link: {\n contentType: string;\n traceId: string;\n observationId: string | null;\n field: MediaField;\n },\n ): Promise<MediaReference> {\n if (data.length > this.maxBytes)\n throw new MediaUploadError(\n `media is ${data.length} bytes, over the ${this.maxBytes}-byte cap`,\n );\n const sha256Hash = createHash(\"sha256\").update(data).digest(\"base64\");\n const answer = (await this.send(\"POST\", MEDIA_PATH, {\n traceId: link.traceId,\n observationId: link.observationId,\n contentType: link.contentType,\n contentLength: data.length,\n sha256Hash,\n field: link.field,\n })) as { mediaId: string; uploadUrl?: string | null };\n if (typeof answer.mediaId !== \"string\" || !answer.mediaId)\n throw new MediaUploadError(\n \"POST /api/public/media answered without a mediaId\",\n );\n const reference = new MediaReference(answer.mediaId, link.contentType);\n if (answer.uploadUrl)\n await this.store(reference, answer.uploadUrl, data, sha256Hash);\n return reference;\n }\n\n private async store(\n reference: MediaReference,\n url: string,\n data: Buffer,\n sha256Hash: string,\n ): Promise<void> {\n const started = Date.now();\n const { status, error } = await this.put(url, data, {\n \"Content-Type\": reference.contentType,\n \"x-amz-checksum-sha256\": sha256Hash,\n \"x-ms-blob-type\": \"BlockBlob\",\n });\n await this.send(\n \"PATCH\",\n `${MEDIA_PATH}/${encodeURIComponent(reference.mediaId)}`,\n {\n uploadedAt: new Date().toISOString(),\n uploadHttpStatus: status,\n uploadHttpError: error,\n uploadTimeMs: Date.now() - started,\n },\n );\n if (status < 200 || status >= 300)\n throw new MediaUploadError(\n `media storage refused the upload (HTTP ${status})`,\n status,\n );\n }\n\n private async send(\n method: PlatformMethod,\n route: string,\n body: unknown,\n ): Promise<unknown> {\n const reply = await this.transport.send(method, route, body);\n if (!reply.ok)\n throw new MediaUploadError(\n `${method} ${route} -> ${reply.status}`,\n reply.status,\n );\n return reply.text ? JSON.parse(reply.text) : {};\n }\n}\n","/** 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","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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,iBAAAA,UAAAC,SAAA;AAAA,IAAAA,QAAA;AAAA,MACE,MAAQ;AAAA,MACR,SAAW;AAAA,MACX,aAAe;AAAA,MACf,MAAQ;AAAA,MACR,QAAU;AAAA,MACV,OAAS;AAAA,MACT,SAAW;AAAA,QACT,KAAK;AAAA,UACH,OAAS;AAAA,UACT,QAAU;AAAA,UACV,SAAW;AAAA,QACb;AAAA,QACA,iBAAiB;AAAA,UACf,OAAS;AAAA,UACT,QAAU;AAAA,UACV,SAAW;AAAA,QACb;AAAA,QACA,aAAa;AAAA,UACX,OAAS;AAAA,UACT,QAAU;AAAA,UACV,SAAW;AAAA,QACb;AAAA,QACA,YAAY;AAAA,UACV,OAAS;AAAA,UACT,QAAU;AAAA,UACV,SAAW;AAAA,QACb;AAAA,QACA,cAAc;AAAA,UACZ,OAAS;AAAA,UACT,QAAU;AAAA,UACV,SAAW;AAAA,QACb;AAAA,QACA,YAAY;AAAA,UACV,OAAS;AAAA,UACT,QAAU;AAAA,UACV,SAAW;AAAA,QACb;AAAA,QACA,cAAc;AAAA,UACZ,OAAS;AAAA,UACT,QAAU;AAAA,UACV,SAAW;AAAA,QACb;AAAA,QACA,aAAa;AAAA,UACX,OAAS;AAAA,UACT,QAAU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IAAI,mBAAmB,UAAU,OAAO,CAAC;AAAA,MACtD;AAAA,QACE,aAAY,oBAAI,KAAK,GAAE,YAAY;AAAA,QACnC,kBAAkB;AAAA,QAClB,iBAAiB;AAAA,QACjB,cAAc,KAAK,IAAI,IAAI;AAAA,MAC7B;AAAA,IACF;AACA,QAAI,SAAS,OAAO,UAAU;AAC5B,YAAM,IAAI;AAAA,QACR,0CAA0C,MAAM;AAAA,QAChD;AAAA,MACF;AAAA,EACJ;AAAA,EAEA,MAAc,KACZ,QACA,OACA,MACkB;AAClB,UAAM,QAAQ,MAAM,KAAK,UAAU,KAAK,QAAQ,OAAO,IAAI;AAC3D,QAAI,CAAC,MAAM;AACT,YAAM,IAAI;AAAA,QACR,GAAG,MAAM,IAAI,KAAK,OAAO,MAAM,MAAM;AAAA,QACrC,MAAM;AAAA,MACR;AACF,WAAO,MAAM,OAAO,KAAK,MAAM,MAAM,IAAI,IAAI,CAAC;AAAA,EAChD;AACF;","names":["exports","module","import_async_hooks","import_api","context","debugLog","scores","import_api","warn","import_api","import_node_crypto"]}
|
|
1
|
+
{"version":3,"sources":["../../package.json","../../src/tracing/index.ts","../../src/tracing/identity.ts","../../src/users/index.ts","../../src/tracing/secrets.ts","../../src/tracing/session.ts","../../src/scores/index.ts","../../src/build/index.ts","../../src/tracing/prerequisites.ts","../../src/tracing/init.ts","../../src/tracing/observe.ts","../../src/tracing/instrument.ts","../../src/tracing/claude.ts","../../src/tracing/media.ts","../../src/worlds/apiError.ts","../../src/worlds/personalToken.ts","../../src/worlds/transport.ts"],"sourcesContent":["{\n \"name\": \"@withgateway/sdk\",\n \"version\": \"0.9.3\",\n \"description\": \"Gateway SDK for TypeScript - A/B experiments, tracing, and observability\",\n \"main\": \"./dist/index.js\",\n \"module\": \"./dist/index.mjs\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.mjs\",\n \"require\": \"./dist/index.js\"\n },\n \"./experiments\": {\n \"types\": \"./dist/experiments/index.d.ts\",\n \"import\": \"./dist/experiments/index.mjs\",\n \"require\": \"./dist/experiments/index.js\"\n },\n \"./context\": {\n \"types\": \"./dist/context/index.d.ts\",\n \"import\": \"./dist/context/index.mjs\",\n \"require\": \"./dist/context/index.js\"\n },\n \"./memory\": {\n \"types\": \"./dist/memory/index.d.ts\",\n \"import\": \"./dist/memory/index.mjs\",\n \"require\": \"./dist/memory/index.js\"\n },\n \"./personas\": {\n \"types\": \"./dist/personas/index.d.ts\",\n \"import\": \"./dist/personas/index.mjs\",\n \"require\": \"./dist/personas/index.js\"\n },\n \"./replay\": {\n \"types\": \"./dist/replay/index.d.ts\",\n \"import\": \"./dist/replay/index.mjs\",\n \"require\": \"./dist/replay/index.js\"\n },\n \"./sessions\": {\n \"types\": \"./dist/sessions/index.d.ts\",\n \"import\": \"./dist/sessions/index.mjs\",\n \"require\": \"./dist/sessions/index.js\"\n },\n \"./tracing\": {\n \"types\": \"./dist/tracing/index.d.ts\",\n \"import\": \"./dist/tracing/index.mjs\",\n \"require\": \"./dist/tracing/index.js\"\n },\n \"./security\": {\n \"types\": \"./dist/security/index.d.ts\",\n \"import\": \"./dist/security/index.mjs\",\n \"require\": \"./dist/security/index.js\"\n },\n \"./users\": {\n \"types\": \"./dist/users/index.d.ts\",\n \"import\": \"./dist/users/index.mjs\",\n \"require\": \"./dist/users/index.js\"\n },\n \"./scores\": {\n \"types\": \"./dist/scores/index.d.ts\",\n \"import\": \"./dist/scores/index.mjs\",\n \"require\": \"./dist/scores/index.js\"\n },\n \"./worlds\": {\n \"types\": \"./dist/worlds/index.d.ts\",\n \"import\": \"./dist/worlds/index.mjs\",\n \"require\": \"./dist/worlds/index.js\"\n },\n \"./files\": {\n \"types\": \"./dist/files/index.d.ts\",\n \"import\": \"./dist/files/index.mjs\",\n \"require\": \"./dist/files/index.js\"\n },\n \"./traces\": {\n \"types\": \"./dist/traces/index.d.ts\",\n \"import\": \"./dist/traces/index.mjs\",\n \"require\": \"./dist/traces/index.js\"\n },\n \"./hooks\": {\n \"types\": \"./dist/hooks/index.d.ts\",\n \"import\": \"./dist/hooks/index.mjs\",\n \"require\": \"./dist/hooks/index.js\"\n },\n \"./agents\": {\n \"types\": \"./dist/agents/index.d.ts\",\n \"import\": \"./dist/agents/index.mjs\",\n \"require\": \"./dist/agents/index.js\"\n },\n \"./cli\": {\n \"types\": \"./dist/cli.d.ts\",\n \"import\": \"./dist/cli.mjs\",\n \"require\": \"./dist/cli.js\"\n }\n },\n \"files\": [\n \"dist\",\n \"skills\",\n \"runtime\",\n \"README.md\"\n ],\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"scripts\": {\n \"prebuild\": \"node scripts/copy-skills.mjs && node scripts/copy-runtime.mjs\",\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"typecheck\": \"tsc --noEmit\",\n \"typecheck:examples\": \"tsc -p tsconfig.examples.json --noEmit\",\n \"test\": \"vitest\",\n \"test:run\": \"vitest run\",\n \"test:integration\": \"vitest run --config vitest.integration.config.ts\",\n \"lint\": \"eslint src --ext .ts\",\n \"clean\": \"rm -rf dist\",\n \"example\": \"tsx examples/test-ab-experiment.ts\",\n \"test:crm\": \"tsx examples/test-crm-ab-experiment.ts\",\n \"test:crm:balanced\": \"tsx examples/test-crm-ab-experiment.ts --balanced\",\n \"test:crm:full\": \"tsx examples/test-crm-ab-experiment.ts --users 12 --all-tasks --concurrency 3\"\n },\n \"keywords\": [\n \"gateway\",\n \"ab-testing\",\n \"experiments\",\n \"opentelemetry\",\n \"tracing\",\n \"observability\",\n \"llm\"\n ],\n \"author\": \"Gateway Team\",\n \"license\": \"MIT\",\n \"engines\": {\n \"node\": \">=18.0.0\"\n },\n \"peerDependencies\": {\n \"@opentelemetry/api\": \"^1.0.0\",\n \"@opentelemetry/exporter-trace-otlp-http\": \">=0.50.0\",\n \"@opentelemetry/resources\": \">=1.0.0\",\n \"@opentelemetry/sdk-trace-base\": \">=1.0.0\",\n \"@opentelemetry/sdk-trace-node\": \">=1.0.0\",\n \"playwright\": \">=1.40.0\"\n },\n \"peerDependenciesMeta\": {\n \"@opentelemetry/api\": {\n \"optional\": true\n },\n \"@opentelemetry/sdk-trace-base\": {\n \"optional\": true\n },\n \"@opentelemetry/sdk-trace-node\": {\n \"optional\": true\n },\n \"@opentelemetry/exporter-trace-otlp-http\": {\n \"optional\": true\n },\n \"@opentelemetry/resources\": {\n \"optional\": true\n },\n \"playwright\": {\n \"optional\": true\n }\n },\n \"optionalDependencies\": {\n \"@arizeai/openinference-instrumentation-anthropic\": \"^0.2.8\",\n \"@arizeai/openinference-instrumentation-openai\": \"^4.2.7\"\n },\n \"devDependencies\": {\n \"@anthropic-ai/sdk\": \"^0.91.1\",\n \"@opentelemetry/api\": \"^1.9.0\",\n \"@opentelemetry/exporter-trace-otlp-http\": \"^0.222.0\",\n \"@opentelemetry/resources\": \"^2.11.0\",\n \"@opentelemetry/sdk-trace-base\": \"^2.11.0\",\n \"@opentelemetry/sdk-trace-node\": \"^2.11.0\",\n \"@opentelemetry/semantic-conventions\": \"^1.40.0\",\n \"@types/node\": \"^20.0.0\",\n \"openai\": \"^4.70.0\",\n \"tsup\": \"^8.0.0\",\n \"tsx\": \"^4.0.0\",\n \"typescript\": \"^5.0.0\",\n \"vitest\": \"^3.2.6\"\n },\n \"overrides\": {\n \"protobufjs\": \"^8.4.1\",\n \"vite@6\": \"^6.4.3\",\n \"postcss\": \"^8.5.18\",\n \"picomatch@4\": \"^4.0.4\",\n \"nanoid\": \">=3.3.18\",\n \"esbuild\": \">=0.28.1\"\n },\n \"pnpm\": {\n \"overrides\": {\n \"protobufjs\": \"^8.4.1\",\n \"vitest\": \"^3.2.6\",\n \"vite@6\": \"^6.4.3\",\n \"postcss\": \"^8.5.18\",\n \"picomatch@4\": \"^4.0.4\",\n \"nanoid\": \">=3.3.18\",\n \"esbuild\": \">=0.28.1\"\n }\n },\n \"bin\": {\n \"gateway\": \"./dist/cli.js\"\n }\n}\n","/**\n * Tracing module for GatewaySDK TypeScript SDK.\n *\n * Provides a simple init() function that configures OpenTelemetry with\n * Gateway, mirroring the Python SDK's tracing.init() experience.\n *\n * @example\n * ```typescript\n * import { tracing } from \"@withgateway/sdk\";\n *\n * // Initialize with environment variables\n * tracing.init();\n *\n * // Or with explicit configuration\n * tracing.init({\n * host: \"https://app.gateway.dev\",\n * publicKey: \"pk-lf-...\",\n * secretKey: \"sk-lf-...\",\n * });\n *\n * // Ensure cleanup on shutdown\n * process.on(\"SIGTERM\", () => tracing.shutdown());\n * ```\n */\n\nexport type { TracingConfig, TracingState } from \"./types\";\n\nexport {\n init,\n initIsolated,\n shutdown,\n flush,\n isInitialized,\n isGatewayConfigured,\n} from \"./init\";\nexport type { TracingHandle } from \"./init\";\n\nexport {\n identify,\n resolveUserId,\n resetAmbientUser,\n IdentitySpanProcessor,\n USER_ID_ATTRIBUTE,\n} from \"./identity\";\nexport type { IdentifyOptions } from \"./identity\";\n\nexport {\n withSession,\n withWorldSession,\n getAmbientSessionId,\n getCurrentWorldSessionId,\n SessionSpanProcessor,\n SESSION_ID_ATTRIBUTE,\n WORLD_SESSION_ID_ATTRIBUTE,\n} from \"./session\";\n\nexport {\n SecretRedactingSpanProcessor,\n SpanSecrets,\n SECRET_KEYS,\n} from \"./secrets\";\n\nexport { observe } from \"./observe\";\nexport type { ObserveOptions, ObservationKind } from \"./observe\";\n\nexport { observeOpenAI, observeAnthropic } from \"./instrument\";\n\nexport { observeClaude } from \"./claude\";\nexport type { ObserveClaudeOptions } from \"./claude\";\n\nexport { MediaReference, MediaUploader, MediaUploadError, MAX_MEDIA_BYTES } from \"./media\";\nexport type { MediaField } from \"./media\";\n","/**\n * End-user identity for GatewaySDK tracing.\n *\n * Mirrors the Python SDK's `gatewaysdk.tracing.identity` user half:\n *\n * - The ambient user is set via `identify()` and stored in an\n * AsyncLocalStorage (the TS analogue of Python's ContextVar), so\n * concurrent requests serving different users never bleed into each other.\n * - `IdentitySpanProcessor` (registered by `tracing.init()`) stamps the\n * ambient user on every span at start, so everything traced after\n * `identify()` is attributed automatically — the same seam as Python's\n * `TracingContextSpanProcessor` and this SDK's `ExperimentSpanProcessor`.\n * - `identify()` also stamps the currently open span directly, because\n * ingestion treats `gateway.user.id` on ANY span as a trace-level update —\n * the in-flight trace is attributed immediately.\n */\n\nimport { AsyncLocalStorage } from \"async_hooks\";\nimport { isSpanContextValid, trace } from \"@opentelemetry/api\";\nimport type { Context } from \"@opentelemetry/api\";\nimport type {\n ReadableSpan,\n Span,\n SpanProcessor,\n} from \"@opentelemetry/sdk-trace-base\";\nimport { UsersClient } from \"../users/index\";\n\nexport const USER_ID_ATTRIBUTE = \"gateway.user.id\";\n\n// Per-async-context user identity set via identify() — AsyncLocalStorage so\n// concurrent requests serving different users never bleed into each other.\nconst currentUserStorage = new AsyncLocalStorage<string>();\n\n/**\n * The active end-user id: identify() context > GATEWAY_USER_ID env.\n *\n * Per-request user attribution (e.g. from auth middleware) can also override\n * per span by setting the `gateway.user.id` attribute directly — explicit\n * set wins over the ambient default stamped at span start.\n */\nexport function resolveUserId(): string | undefined {\n const contextual = currentUserStorage.getStore();\n if (contextual) return contextual;\n const envUser = process.env.GATEWAY_USER_ID?.trim();\n return envUser ? envUser : undefined;\n}\n\nexport interface IdentifyOptions {\n /** Profile attributes to merge into the user's stored profile. */\n attributes?: Record<string, string | number | boolean>;\n displayName?: string;\n email?: string;\n}\n\n/**\n * Attribute everything that follows (and the current trace) to a user.\n *\n * - Sets the user for all spans started in this async context, and stamps\n * the currently open span so the in-flight trace is attributed immediately.\n * - When `attributes`/`displayName`/`email` are given, the user's platform\n * profile is updated in the background (attributes merge with what's\n * stored — ideal for incremental ROI facts like plan or account_value).\n * Requires GATEWAY_HOST/GATEWAY_PUBLIC_KEY/GATEWAY_SECRET_KEY for the\n * profile update; tracing attribution works without them. Failures are\n * swallowed (debug-logged) and never produce unhandled rejections.\n *\n * @example\n * ```typescript\n * import { identify } from \"@withgateway/sdk\";\n *\n * identify(\"user-123\", {\n * attributes: { plan: \"enterprise\", account_value: \"48000\" },\n * });\n * ```\n */\nexport function identify(userId: string, options: IdentifyOptions = {}): void {\n const cleaned = userId.trim();\n if (!cleaned) return;\n\n currentUserStorage.enterWith(cleaned);\n\n // Stamp the open span so the in-flight trace is upserted with the user —\n // ingestion treats user.id on ANY span as a trace-level update.\n try {\n const span = trace.getActiveSpan();\n if (span && isSpanContextValid(span.spanContext())) {\n span.setAttribute(USER_ID_ATTRIBUTE, cleaned);\n }\n } catch (error) {\n debugLog(\"identify(): no active span to stamp\", error);\n }\n\n if (options.attributes || options.displayName || options.email) {\n void pushProfile(cleaned, options);\n }\n}\n\nasync function pushProfile(\n userId: string,\n options: IdentifyOptions,\n): Promise<void> {\n try {\n const attributes: Record<string, string> = {};\n for (const [key, value] of Object.entries(options.attributes ?? {})) {\n attributes[key] = String(value);\n }\n await UsersClient.fromEnv().update(userId, {\n ...(options.displayName !== undefined\n ? { displayName: options.displayName }\n : {}),\n ...(options.email !== undefined ? { email: options.email } : {}),\n attributes,\n });\n } catch (error) {\n debugLog(\"identify(): profile update failed\", error);\n }\n}\n\n/** Testing hook: clear the ambient user for the current async context. */\nexport function resetAmbientUser(): void {\n currentUserStorage.enterWith(undefined as unknown as string);\n}\n\n/**\n * Stamps the ambient end-user identity (identify() context or\n * GATEWAY_USER_ID env) on every span at start. Registered automatically by\n * `tracing.init()`. Explicit `setAttribute` calls after span start win over\n * this ambient default.\n */\nexport class IdentitySpanProcessor implements SpanProcessor {\n onStart(span: Span, _parentContext: Context): void {\n const userId = resolveUserId();\n if (userId) {\n span.setAttribute(USER_ID_ATTRIBUTE, userId);\n }\n }\n\n onEnd(_span: ReadableSpan): void {}\n\n async shutdown(): Promise<void> {}\n\n async forceFlush(): Promise<void> {}\n}\n\nfunction debugLog(message: string, ...args: unknown[]): void {\n if (process.env.GATEWAY_DEBUG) {\n console.debug(`[gatewaysdk.tracing] ${message}`, ...args);\n }\n}\n","/**\n * End-user profiles — attribute usage and ROI to the real people behind\n * your agent's traffic.\n *\n * Profiles pair with the platform's per-user usage metrics (traces, tokens,\n * lifetime cost) on the Users page. Attributes merge by default, so pushing\n * an incremental ROI fact is one call:\n *\n * ```typescript\n * import { UsersClient } from \"@withgateway/sdk/users\";\n *\n * const users = UsersClient.fromEnv();\n * await users.update(\"user-123\", {\n * displayName: \"Acme Corp — Jane D.\",\n * attributes: { plan: \"enterprise\", account_value: \"48000\" },\n * });\n * ```\n *\n * Tip: `identify(\"user-123\", { attributes: {...} })` does this in the\n * background AND attributes the current trace/session to the user.\n *\n * Mirrors the Python SDK's `gatewaysdk.users` module.\n */\n\ntype UserProfile = {\n userId: string;\n displayName: string | null;\n email: string | null;\n attributes: Record<string, string>;\n notes: string | null;\n};\n\ntype UserProfileUpdate = {\n displayName?: string;\n email?: string;\n attributes?: Record<string, string>;\n notes?: string;\n /**\n * Attributes merge with the stored set by default. Set `merge: false`\n * to replace the stored attributes wholesale.\n */\n merge?: boolean;\n};\n\ntype UserEvent = {\n id: string;\n userId: string;\n event: string;\n /** Emitter-defined value (e.g. minutes saved, revenue). Summed at rollup. */\n value: number | null;\n metadata: Record<string, unknown>;\n traceId: string | null;\n sessionId: string | null;\n createdAt: Date;\n};\n\ntype UserEventOptions = {\n /** Worth of the event in your terms (minutes saved, revenue…). */\n value?: number;\n metadata?: Record<string, unknown>;\n /** Link to the trace that produced the event. */\n traceId?: string;\n /** Link to the session that produced the event. */\n sessionId?: string;\n};\n\ntype UsersClientConfig = {\n host: string;\n publicKey: string;\n secretKey: string;\n timeoutSeconds?: number;\n debug?: boolean;\n};\n\ntype UsersClientFromEnvConfig = Partial<UsersClientConfig>;\n\n/** Raised when the Gateway user-profiles API cannot complete a request. */\nexport class UserProfileError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message);\n this.name = \"UserProfileError\";\n this.cause = options?.cause;\n }\n}\n\n/** Client for Gateway's end-user profile endpoints (Basic project keys). */\nexport class UsersClient {\n private readonly host: string;\n private readonly publicKey: string;\n private readonly secretKey: string;\n private readonly timeoutSeconds: number;\n private readonly debug: boolean;\n\n constructor(config: UsersClientConfig) {\n this.host = config.host.replace(/\\/$/, \"\");\n this.publicKey = config.publicKey;\n this.secretKey = config.secretKey;\n this.timeoutSeconds = config.timeoutSeconds ?? 15;\n this.debug = config.debug ?? false;\n }\n\n /** Create a client from GATEWAY_HOST / GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY. */\n static fromEnv(config: UsersClientFromEnvConfig = {}) {\n const host = config.host ?? process.env.GATEWAY_HOST;\n const publicKey = config.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;\n const secretKey = config.secretKey ?? process.env.GATEWAY_SECRET_KEY;\n\n const missing = [\n [\"host\", host],\n [\"publicKey\", publicKey],\n [\"secretKey\", secretKey],\n ]\n .filter(([, value]) => !value)\n .map(([name]) => name);\n\n if (missing.length > 0) {\n throw new UserProfileError(\n `Missing Gateway user-profile configuration: ${missing.join(\", \")}`,\n );\n }\n\n return new UsersClient({\n ...config,\n host: host!,\n publicKey: publicKey!,\n secretKey: secretKey!,\n });\n }\n\n /** Fetch a user's stored profile. */\n async get(userId: string): Promise<UserProfile> {\n return parseProfile(\n await this.requestJson(\n \"GET\",\n `/api/public/user-profiles/${encodeURIComponent(userId)}`,\n ),\n );\n }\n\n /**\n * Upsert a user's profile. `attributes` merge with the stored set unless\n * `merge: false` (which replaces it).\n */\n async update(\n userId: string,\n update: UserProfileUpdate = {},\n ): Promise<UserProfile> {\n const body: Record<string, unknown> = {\n userId,\n attributes: update.attributes ?? {},\n mergeAttributes: update.merge ?? true,\n ...(update.displayName !== undefined\n ? { displayName: update.displayName }\n : {}),\n ...(update.email !== undefined ? { email: update.email } : {}),\n ...(update.notes !== undefined ? { notes: update.notes } : {}),\n };\n return parseProfile(\n await this.requestJson(\"POST\", \"/api/public/user-profiles\", body),\n );\n }\n\n /**\n * Record a VALUE EVENT for a user — the per-user ROI stream. `value` is\n * whatever the event is worth in your terms (minutes saved, revenue…);\n * Gateway sums it in the hours-saved/ROI rollups, and evals and task-set\n * replays can assert against the events. Link `traceId`/`sessionId` to tie\n * the event to the run that produced it.\n *\n * @example\n * ```ts\n * await client.trackEvent(\"user-123\", \"checkout_completed\", {\n * value: 25,\n * metadata: { cartSize: 3 },\n * sessionId,\n * });\n * ```\n */\n async trackEvent(\n userId: string,\n event: string,\n options: UserEventOptions = {},\n ): Promise<UserEvent> {\n const body: Record<string, unknown> = {\n userId,\n event,\n metadata: options.metadata ?? {},\n ...(options.value !== undefined ? { value: options.value } : {}),\n ...(options.traceId !== undefined ? { traceId: options.traceId } : {}),\n ...(options.sessionId !== undefined\n ? { sessionId: options.sessionId }\n : {}),\n };\n return parseEvent(\n await this.requestJson(\"POST\", \"/api/public/user-events\", body),\n );\n }\n\n /** List a project's user events, optionally filtered by user/event/time. */\n async listEvents(\n filter: {\n userId?: string;\n event?: string;\n fromTimestamp?: Date;\n toTimestamp?: Date;\n page?: number;\n limit?: number;\n } = {},\n ): Promise<{ data: UserEvent[]; totalItems: number }> {\n const params = new URLSearchParams();\n if (filter.userId) params.set(\"userId\", filter.userId);\n if (filter.event) params.set(\"event\", filter.event);\n if (filter.fromTimestamp)\n params.set(\"fromTimestamp\", filter.fromTimestamp.toISOString());\n if (filter.toTimestamp)\n params.set(\"toTimestamp\", filter.toTimestamp.toISOString());\n if (filter.page) params.set(\"page\", String(filter.page));\n if (filter.limit) params.set(\"limit\", String(filter.limit));\n const qs = params.toString();\n const payload = await this.requestJson(\n \"GET\",\n `/api/public/user-events${qs ? `?${qs}` : \"\"}`,\n );\n const rows = Array.isArray(payload.data) ? payload.data : [];\n const meta =\n payload.meta && typeof payload.meta === \"object\"\n ? (payload.meta as Record<string, unknown>)\n : {};\n return {\n data: rows.map((row) => parseEvent(row as Record<string, unknown>)),\n totalItems: Number(meta.totalItems ?? rows.length),\n };\n }\n\n private async requestJson(\n method: \"GET\" | \"POST\",\n path: string,\n payload?: Record<string, unknown>,\n ): Promise<Record<string, unknown>> {\n let response: Response;\n try {\n response = await fetch(`${this.host}${path}`, {\n method,\n headers: {\n Authorization: this.authHeader(),\n \"Content-Type\": \"application/json\",\n },\n ...(payload ? { body: JSON.stringify(payload) } : {}),\n signal: AbortSignal.timeout(this.timeoutSeconds * 1000),\n });\n } catch (error) {\n throw new UserProfileError(\n `${method} ${path} failed: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n\n const text = await response.text();\n if (!response.ok) {\n throw new UserProfileError(\n `${method} ${path} failed (${response.status}): ${text.slice(0, 500)}`,\n );\n }\n\n this.log(\"%s %s -> %s\", method, path, response.status);\n return safeJson(text);\n }\n\n private authHeader() {\n return `Basic ${Buffer.from(`${this.publicKey}:${this.secretKey}`).toString(\n \"base64\",\n )}`;\n }\n\n private log(message: string, ...args: unknown[]) {\n if (this.debug) {\n console.log(`[gateway.users] ${message}`, ...args);\n }\n }\n}\n\nfunction parseEvent(payload: Record<string, unknown>): UserEvent {\n return {\n id: String(payload.id ?? \"\"),\n userId: String(payload.userId ?? \"\"),\n event: String(payload.event ?? \"\"),\n value: typeof payload.value === \"number\" ? payload.value : null,\n metadata:\n payload.metadata &&\n typeof payload.metadata === \"object\" &&\n !Array.isArray(payload.metadata)\n ? (payload.metadata as Record<string, unknown>)\n : {},\n traceId: typeof payload.traceId === \"string\" ? payload.traceId : null,\n sessionId:\n typeof payload.sessionId === \"string\" ? payload.sessionId : null,\n createdAt:\n typeof payload.createdAt === \"string\"\n ? new Date(payload.createdAt)\n : new Date(0),\n };\n}\n\nfunction parseProfile(payload: Record<string, unknown>): UserProfile {\n return {\n userId: String(payload.userId ?? \"\"),\n displayName:\n typeof payload.displayName === \"string\" ? payload.displayName : null,\n email: typeof payload.email === \"string\" ? payload.email : null,\n attributes: parseAttributes(payload.attributes),\n notes: typeof payload.notes === \"string\" ? payload.notes : null,\n };\n}\n\nfunction parseAttributes(value: unknown): Record<string, string> {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return {};\n const attributes: Record<string, string> = {};\n for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {\n attributes[key] = String(entry);\n }\n return attributes;\n}\n\nfunction safeJson(value: string): Record<string, unknown> {\n try {\n const parsed = JSON.parse(value);\n return parsed && typeof parsed === \"object\" && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : {};\n } catch {\n return {};\n }\n}\n\nexport const users = {\n fromEnv: UsersClient.fromEnv,\n};\n\nexport type {\n UserProfile,\n UserProfileUpdate,\n UserEvent,\n UserEventOptions,\n UsersClientConfig,\n UsersClientFromEnvConfig,\n};\n","/**\n * Credentials a caller hands a model SDK (an MCP server's `authorization_token`), kept out of every\n * exported span. Twin of `gatewaysdk/tracing/secrets.py`; both run\n * `fixtures/tracing/span-secret-vectors.json`.\n */\n\nimport type { Context, SpanStatus } from \"@opentelemetry/api\";\nimport type {\n ReadableSpan,\n Span,\n SpanProcessor,\n TimedEvent,\n} from \"@opentelemetry/sdk-trace-base\";\n\nexport const SECRET_KEYS: ReadonlySet<string> = new Set([\n \"authorization_token\",\n \"authorizationToken\",\n]);\n\nexport const REDACTED = \"[redacted: holds a credential]\";\nexport const MIN_SECRET_LENGTH = 8;\n\ntype Attributes = Record<string, unknown>;\n\n/**\n * Which keys are credentials, and how to keep them out of a span attribute. An attribute whose name\n * contains a key is dropped. An attribute whose value names a key is exported only when the key can\n * be removed as a JSON object key (at any depth, also inside a JSON string nested in JSON) and then\n * neither the name nor any value removed under it (`MIN_SECRET_LENGTH` or longer) appears anywhere\n * in it. Any other attribute that names a key (a cut or non-JSON string, a repr, a query string, a\n * pair list, a command line, prose) is replaced whole by `REDACTED`: no rule can know where every\n * rendering of the value sits beside its name. A removed value withholds the attribute in its\n * percent-encoded or JSON-escaped form too, and a value that cannot be scrubbed for any reason is\n * withheld whole. Attributes that name no key are exported untouched.\n */\nexport class SpanSecrets {\n constructor(readonly keys: ReadonlySet<string> = SECRET_KEYS) {}\n\n isSecret(key: string): boolean {\n return this.keys.has(key);\n }\n\n drops(attribute: string): boolean {\n return this.mentions(attribute);\n }\n\n strip(value: unknown): unknown {\n if (typeof value === \"string\") return this.stripNested(value);\n if (Array.isArray(value)) return value.map((item) => this.strip(item));\n if (value === null || typeof value !== \"object\") return value;\n return Object.fromEntries(\n Object.entries(value)\n .filter(([key]) => !this.isSecret(key))\n .map(([key, item]) => [key, this.strip(item)]),\n );\n }\n\n scrubAttribute(value: unknown): unknown {\n try {\n return this.scrubbedValue(value);\n } catch {\n return Array.isArray(value) ? [REDACTED] : REDACTED;\n }\n }\n\n private scrubbedValue(value: unknown): unknown {\n if (typeof value === \"string\") return this.scrubbedText(value);\n if (!Array.isArray(value)) return value;\n const results = value.map((item) =>\n typeof item === \"string\"\n ? this.cleaned(item)\n : { text: item, removed: new Set<string>() },\n );\n const removed = new Set(results.flatMap((r) => [...r.removed]));\n const scrubbed = results.map((r) => r.text);\n const withheld = scrubbed.some(\n (item) => typeof item === \"string\" && this.carries(item, removed),\n );\n return withheld ? [REDACTED] : scrubbed;\n }\n\n scrubAttributes(attributes: Attributes): Attributes {\n return Object.fromEntries(\n Object.entries(attributes)\n .filter(([key]) => !this.drops(key))\n .map(([key, value]) => [key, this.scrubAttribute(value)]),\n );\n }\n\n private mentions(text: string): boolean {\n return [...this.keys].some((key) => text.includes(key));\n }\n\n private scrubbedText(text: string): string {\n const { text: cleaned, removed } = this.cleaned(text);\n return this.carries(cleaned, removed) ? REDACTED : cleaned;\n }\n\n private cleaned(text: string): { text: string; removed: Set<string> } {\n if (!this.mentions(text)) return { text, removed: new Set() };\n const parsed = jsonOrUndefined(text);\n if (parsed === undefined) return { text: REDACTED, removed: new Set() };\n return {\n text: JSON.stringify(this.strip(parsed)),\n removed: this.removed(parsed),\n };\n }\n\n private carries(text: string, removed: Set<string>): boolean {\n if (text === REDACTED || this.mentions(text)) return true;\n return [...removed].some((value) =>\n encodings(value).some((form) => text.includes(form)),\n );\n }\n\n private removed(value: unknown): Set<string> {\n if (typeof value === \"string\") {\n const nested = this.mentions(value) ? jsonOrUndefined(value) : undefined;\n return nested === undefined ? new Set() : this.removed(nested);\n }\n if (Array.isArray(value)) return union(value.map((v) => this.removed(v)));\n if (value === null || typeof value !== \"object\") return new Set();\n return union(\n Object.entries(value).map(([key, item]) =>\n this.isSecret(key) ? leaves(item) : this.removed(item),\n ),\n );\n }\n\n private stripNested(text: string): string {\n if (!this.mentions(text)) return text;\n const parsed = jsonOrUndefined(text);\n if (parsed === undefined) return text;\n return JSON.stringify(this.strip(parsed));\n }\n}\n\nfunction jsonOrUndefined(text: string): unknown {\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return undefined;\n }\n if (typeof parsed === \"string\") return parsed;\n return parsed !== null && typeof parsed === \"object\" ? parsed : undefined;\n}\n\nfunction encodings(value: string): string[] {\n return [value, percentEncoded(value), JSON.stringify(value).slice(1, -1)];\n}\n\nfunction percentEncoded(value: string): string {\n try {\n return encodeURIComponent(value);\n } catch {\n return value;\n }\n}\n\nfunction union(sets: Set<string>[]): Set<string> {\n return new Set(sets.flatMap((set) => [...set]));\n}\n\nfunction leaves(value: unknown): Set<string> {\n if (typeof value === \"string\") {\n return [...value].length >= MIN_SECRET_LENGTH\n ? new Set([value])\n : new Set();\n }\n if (Array.isArray(value)) return union(value.map(leaves));\n if (value === null || typeof value !== \"object\") return new Set();\n return union(Object.values(value).map(leaves));\n}\n\nexport const SPAN_SECRETS = new SpanSecrets();\n\nfunction sameAttributes(before: Attributes, after: Attributes): boolean {\n const keys = Object.keys(before);\n if (keys.length !== Object.keys(after).length) return false;\n return keys.every(\n (key) => before[key] === after[key] || sameArray(before[key], after[key]),\n );\n}\n\nfunction sameArray(before: unknown, after: unknown): boolean {\n if (!Array.isArray(before) || !Array.isArray(after)) return false;\n return (\n before.length === after.length &&\n before.every((item, i) => item === after[i])\n );\n}\n\n/**\n * Wraps a span processor so every read it makes, at start or at end, is without the credentials\n * `SpanSecrets` names in the span's attributes, event attributes or status message, whichever\n * instrumentor recorded them. `tracing.init()` puts one in front of its exporter and every custom\n * processor. A span that cannot be scrubbed at end is dropped rather than exported as it was.\n */\nexport class SecretRedactingSpanProcessor implements SpanProcessor {\n constructor(\n private readonly inner: SpanProcessor,\n private readonly secrets: SpanSecrets = SPAN_SECRETS,\n ) {}\n\n private readonly views = new WeakMap<object, Span>();\n\n onStart(span: Span, parentContext: Context): void {\n this.inner.onStart(this.viewFor(span), parentContext);\n }\n\n onEnd(span: ReadableSpan): void {\n const view = this.viewFor(span as Span);\n try {\n void [view.attributes, view.events, view.status];\n } catch (error) {\n console.warn(\n `[gatewaysdk.tracing] Dropped span \"${span.name}\": could not redact it: ${(error as Error)?.name}`,\n );\n return;\n }\n this.inner.onEnd(view as unknown as ReadableSpan);\n }\n\n private viewFor(span: Span): Span {\n const known = this.views.get(span);\n if (known) return known;\n const view = viewOf(span, {\n attributes: () => this.scrubbedAttributes(span.attributes as Attributes),\n events: () => span.events.map((event) => this.scrubbedEvent(event)),\n status: () => this.scrubbedStatus(span.status),\n });\n this.views.set(span, view);\n return view;\n }\n\n forceFlush(): Promise<void> {\n return this.inner.forceFlush();\n }\n\n shutdown(): Promise<void> {\n return this.inner.shutdown();\n }\n\n private scrubbedAttributes(attributes: Attributes): Attributes {\n const clean = this.secrets.scrubAttributes(attributes);\n return sameAttributes(attributes, clean) ? attributes : clean;\n }\n\n private scrubbedStatus(status: SpanStatus): SpanStatus {\n if (!status.message) return status;\n const message = this.secrets.scrubAttribute(status.message) as string;\n return message === status.message ? status : { ...status, message };\n }\n\n private scrubbedEvent(event: TimedEvent): TimedEvent {\n if (!event.attributes) return event;\n const attributes = this.scrubbedAttributes(event.attributes as Attributes);\n if (attributes === event.attributes) return event;\n return { ...event, attributes: attributes as TimedEvent[\"attributes\"] };\n }\n}\n\ntype Reads = Record<\"attributes\" | \"events\" | \"status\", () => unknown>;\n\nfunction scrubbedRead(reads: Reads, property: string | symbol) {\n return typeof property === \"string\" && property in reads\n ? reads[property as keyof Reads]\n : undefined;\n}\n\nfunction viewOf<T extends object>(span: T, reads: Reads): T {\n const view: T = new Proxy(span, {\n get(target, property) {\n const read = scrubbedRead(reads, property);\n if (read) return read();\n const value = Reflect.get(target, property, target);\n if (typeof value !== \"function\") return value;\n return (...args: unknown[]) => {\n const result = value.apply(target, args);\n return result === target ? view : result;\n };\n },\n getOwnPropertyDescriptor(target, property) {\n const descriptor = Reflect.getOwnPropertyDescriptor(target, property);\n const read = scrubbedRead(reads, property);\n if (!read || !descriptor || !(\"value\" in descriptor)) return descriptor;\n return { ...descriptor, value: read() };\n },\n });\n return view;\n}\n","import { AsyncLocalStorage } from \"async_hooks\";\nimport type { Context } from \"@opentelemetry/api\";\nimport type {\n ReadableSpan,\n Span,\n SpanProcessor,\n} from \"@opentelemetry/sdk-trace-base\";\n\nexport const SESSION_ID_ATTRIBUTE = \"gateway.session.id\";\nexport const WORLD_SESSION_ID_ATTRIBUTE =\n \"gateway.trace.metadata.world_session_id\";\n\n// AsyncLocalStorage so concurrent runs or requests never bleed into each other.\n// Held on globalThis: tsup inlines this module into every published entry\n// (splitting: false), and `worlds` must write the store `tracing` reads.\n// Every SDK copy in the process shares the key and the string value; never\n// rename or reshape them.\nconst processStorage = (name: string): AsyncLocalStorage<string> => {\n const key = Symbol.for(`@withgateway/sdk/${name}`);\n const slots = globalThis as Record<symbol, AsyncLocalStorage<string>>;\n slots[key] ??= new AsyncLocalStorage<string>();\n return slots[key];\n};\nconst currentSessionStorage = processStorage(\"session-storage\");\nconst currentWorldSessionStorage = processStorage(\"world-session-storage\");\n\n/** The session id set by the innermost enclosing `withSession()`, or `undefined`. */\nexport function getAmbientSessionId(): string | undefined {\n return currentSessionStorage.getStore();\n}\n\n/** The live world session the current code is working in, or `undefined`. */\nexport function getCurrentWorldSessionId(): string | undefined {\n return currentWorldSessionStorage.getStore();\n}\n\nfunction runIn<T>(\n storage: AsyncLocalStorage<string>,\n value: string,\n fn: () => T | Promise<T>,\n): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n storage.run(value, () => {\n Promise.resolve().then(fn).then(resolve, reject);\n });\n });\n}\n\n/**\n * Group every trace recorded inside `fn` under one session id — the twin of\n * the Python SDK's `with tracing.session(session_id): ...`. Auto-instrumented\n * spans are grouped too; the innermost session wins.\n *\n * ```typescript\n * await withSession(\"checkout-regression-001\", async () => {\n * await observe(\"turn-1\", async () => { ... });\n * });\n * ```\n */\nexport function withSession<T>(\n sessionId: string,\n fn: () => T | Promise<T>,\n): Promise<T> {\n return runIn(currentSessionStorage, sessionId, fn);\n}\n\n/**\n * Trace `fn` as work inside one live world session: spans take the world\n * session's id as their session id and carry `world_session_id` trace\n * metadata. A `withSession()` block inside still wins for the session id;\n * the metadata stays. Without `tracing.init()` nothing is recorded. Twin of\n * Python's `tracing.context.world_session`; callers use\n * `WorldSession.withTraceContext(fn)`.\n */\nexport function withWorldSession<T>(\n worldSessionId: string,\n fn: () => T | Promise<T>,\n): Promise<T> {\n return runIn(currentWorldSessionStorage, worldSessionId, () =>\n withSession(worldSessionId, fn),\n );\n}\n\n/**\n * Stamps the session id and world session id on every span at start.\n * Registered by `tracing.init()`/`initIsolated()`. A session id the span was\n * started with (or is given after it starts) wins over the innermost\n * `withSession()` / `withWorldSession()` block, as in the Python SDK.\n */\nexport class SessionSpanProcessor implements SpanProcessor {\n onStart(span: Span, _parentContext: Context): void {\n const worldSessionId = getCurrentWorldSessionId();\n if (worldSessionId)\n span.setAttribute(WORLD_SESSION_ID_ATTRIBUTE, worldSessionId);\n const sessionId = getAmbientSessionId();\n if (!sessionId || span.attributes?.[SESSION_ID_ATTRIBUTE] !== undefined)\n return;\n span.setAttribute(SESSION_ID_ATTRIBUTE, sessionId);\n }\n\n onEnd(_span: ReadableSpan): void {}\n\n async shutdown(): Promise<void> {}\n\n async forceFlush(): Promise<void> {}\n}\n","/**\n * Scores & success signals — record evaluation results and ROI-shaped success\n * signals against a Gateway project.\n *\n * A **score** is any evaluation value attached to a trace or session (visible\n * on the Scores page and in trace/session detail). A **success signal** is a\n * score carrying `metadata[\"gateway.success.signal\"]`, which the platform's\n * Success Metrics feature aggregates into a metric's headline count/pass-rate\n * (the `HOOK` metric source). Emit one whenever a real unit of business value\n * happens (\"resolved a ticket\", \"ran an eval\", \"a human accepted an edit\").\n *\n * This mirrors the Python SDK's `Run.score()` / `Run.success()`\n * (`gatewaysdk/sdk/src/gatewaysdk/run.py`). The score shape — name, numeric\n * value, `gateway.success.signal` + `gateway.success.metricName` metadata, and\n * the trace/session target — is IDENTICAL so the platform aggregates signals\n * from either SDK unchanged.\n *\n * ```typescript\n * import { ScoresClient } from \"@withgateway/sdk/scores\";\n *\n * const scores = ScoresClient.fromEnv();\n * // A pass/fail signal that feeds the \"resolved_ticket\" Success Metric:\n * await scores.success(\"resolved_ticket\", true, {\n * agentId: \"support-triage\",\n * sessionId,\n * });\n * // A numeric signal:\n * await scores.success(\"handle_time_s\", 42, { agentId: \"support-triage\", sessionId });\n * ```\n *\n * Under `tracing.initIsolated(...)` the returned handle exposes a `scores`\n * client already bound to that project's keys — that is how the platform\n * self-traces its own agents into dedicated projects.\n */\n\nimport { isSpanContextValid, trace } from \"@opentelemetry/api\";\n\n/** Score value data type, matching Gateway's ingestion schema. */\nexport type ScoreDataType = \"NUMERIC\" | \"CATEGORICAL\" | \"BOOLEAN\";\n\n/** Reserved metadata keys that mark a score as an aggregatable success signal. */\nexport const SUCCESS_SIGNAL_KEY = \"gateway.success.signal\";\nexport const SUCCESS_METRIC_NAME_KEY = \"gateway.success.metricName\";\nexport const AGENT_ID_KEY = \"gateway.agent.id\";\n\nexport type ScoreOptions = {\n /**\n * Trace to link the score to. Auto-detected from the active OpenTelemetry\n * span when omitted and no `sessionId` is given (mirrors the Python SDK).\n */\n traceId?: string;\n /** Session to link the score to. Preferred target when present. */\n sessionId?: string;\n /** Dataset-run to link the score to (dataset-run scores). */\n datasetRunId?: string;\n /** Span-level score — requires `traceId`. */\n observationId?: string;\n /** \"NUMERIC\" | \"CATEGORICAL\" | \"BOOLEAN\"; inferred when omitted. */\n dataType?: ScoreDataType;\n /** Optional comment stored alongside the score. */\n comment?: string;\n /** Extra metadata merged into the score. */\n metadata?: Record<string, unknown>;\n /** Environment tag; defaults to the project's `default` environment. */\n environment?: string;\n};\n\nexport type SuccessOptions = Omit<ScoreOptions, \"dataType\"> & {\n /**\n * The agent this signal belongs to (`gateway.agent.id`). Lets the platform\n * roll the signal into that agent's Success Metric without a trace join.\n */\n agentId?: string;\n /** The Success Metric name; defaults to the signal `name`. */\n metricName?: string;\n /** Override the inferred \"BOOLEAN\"/\"NUMERIC\" data type. */\n dataType?: \"NUMERIC\" | \"BOOLEAN\";\n};\n\nexport type ScoresClientConfig = {\n host: string;\n publicKey: string;\n secretKey: string;\n timeoutSeconds?: number;\n debug?: boolean;\n};\n\nexport type ScoresClientFromEnvConfig = Partial<ScoresClientConfig>;\n\n/** Raised by the low-level {@link ScoresClient.postScore} on a failed request. */\nexport class ScoreError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message);\n this.name = \"ScoreError\";\n this.cause = options?.cause;\n }\n}\n\n/**\n * Read the current trace id (32-hex) from the active OpenTelemetry span, or\n * undefined when there is no valid active span. Mirrors the Python SDK's\n * `_get_current_trace_id`.\n */\nexport function currentTraceId(): string | undefined {\n try {\n const span = trace.getActiveSpan();\n if (!span) return undefined;\n const ctx = span.spanContext();\n if (!ctx || !isSpanContextValid(ctx)) return undefined;\n return ctx.traceId;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Client for Gateway's public scores ingestion endpoint (Basic project keys).\n * The `score`/`success` convenience methods are FAIL-SOFT — they never reject\n * into the caller, they warn and resolve — matching the Python SDK's\n * fire-and-forget scoring. The raw {@link postScore} throws on failure for\n * callers that want to handle it.\n */\nexport class ScoresClient {\n private readonly host: string;\n private readonly publicKey: string;\n private readonly secretKey: string;\n private readonly timeoutSeconds: number;\n private readonly debug: boolean;\n\n constructor(config: ScoresClientConfig) {\n this.host = config.host.replace(/\\/$/, \"\");\n this.publicKey = config.publicKey;\n this.secretKey = config.secretKey;\n this.timeoutSeconds = config.timeoutSeconds ?? 15;\n this.debug = config.debug ?? false;\n }\n\n /** Create a client from GATEWAY_HOST / GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY. */\n static fromEnv(config: ScoresClientFromEnvConfig = {}): ScoresClient {\n const host = config.host ?? process.env.GATEWAY_HOST;\n const publicKey = config.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;\n const secretKey = config.secretKey ?? process.env.GATEWAY_SECRET_KEY;\n\n const missing = [\n [\"host\", host],\n [\"publicKey\", publicKey],\n [\"secretKey\", secretKey],\n ]\n .filter(([, value]) => !value)\n .map(([name]) => name);\n\n if (missing.length > 0) {\n throw new ScoreError(\n `Missing Gateway scores configuration: ${missing.join(\", \")}`,\n );\n }\n\n return new ScoresClient({\n ...config,\n host: host!,\n publicKey: publicKey!,\n secretKey: secretKey!,\n });\n }\n\n /**\n * Post a score, throwing {@link ScoreError} on any failure. Builds the exact\n * `POST /api/public/scores` body the Python SDK sends: exactly one of\n * `sessionId` / `traceId` (+ optional `observationId`) / `datasetRunId`.\n * When no target is provided, the active OTel trace id is used; if none is\n * available the call is a no-op (returns without posting), matching Python.\n */\n async postScore(\n name: string,\n value: number | string,\n options: ScoreOptions = {},\n ): Promise<void> {\n const body = this.buildScoreBody(name, value, options);\n if (!body) {\n this.log(\n \"score '%s' dropped: no sessionId, traceId or datasetRunId available\",\n name,\n );\n return;\n }\n await this.request(\"POST\", \"/api/public/scores\", body);\n }\n\n /**\n * Build the score request body, or null when no target can be resolved.\n * Split out so it is unit-testable and shared by score()/success().\n */\n buildScoreBody(\n name: string,\n value: number | string,\n options: ScoreOptions = {},\n ): Record<string, unknown> | null {\n // Prefer sessionId (scores typically grade a whole session/rollout), then\n // datasetRunId, then an explicit traceId, then the ambient OTel trace.\n const traceId = options.traceId ?? currentTraceId();\n const target: Record<string, unknown> = {};\n if (options.sessionId) {\n target.sessionId = options.sessionId;\n } else if (options.datasetRunId) {\n target.datasetRunId = options.datasetRunId;\n } else if (traceId) {\n target.traceId = traceId;\n if (options.observationId) target.observationId = options.observationId;\n } else {\n return null;\n }\n\n // Base metadata mirrors the Python SDK (source tag), then the caller's\n // metadata is merged on top — identical to `score_metadata.update(...)`.\n const metadata: Record<string, unknown> = {\n source: \"gatewaysdk\",\n ...(options.metadata ?? {}),\n };\n\n return {\n name,\n value,\n dataType: options.dataType ?? \"NUMERIC\",\n environment: options.environment ?? \"default\",\n ...(options.comment ? { comment: options.comment } : {}),\n metadata,\n ...target,\n };\n }\n\n /**\n * Post a score, FAIL-SOFT: warns and resolves on any failure so a broken\n * transport never throws into (or rejects out of) the caller.\n */\n async score(\n name: string,\n value: number | string,\n options: ScoreOptions = {},\n ): Promise<void> {\n try {\n await this.postScore(name, value, options);\n } catch (error) {\n this.warn(`score '${name}' failed`, error);\n }\n }\n\n /**\n * Emit a SUCCESS SIGNAL that feeds a Gateway Success Metric — a score tagged\n * with `gateway.success.signal` + `gateway.success.metricName` (and the agent\n * identity when `agentId` is set). A boolean `value` records a 1/0 BOOLEAN\n * score (pass/fail); a number records a NUMERIC score. FAIL-SOFT.\n *\n * The metadata shape matches the Python SDK's `Run.success()` exactly, so the\n * platform's Success Metrics aggregation counts signals from either SDK\n * without change.\n *\n * @example\n * ```ts\n * await scores.success(\"resolved_ticket\", true, { agentId: \"support-triage\", sessionId });\n * await scores.success(\"handle_time_s\", 42, { agentId: \"support-triage\", sessionId });\n * ```\n */\n async success(\n name: string,\n value: boolean | number = true,\n options: SuccessOptions = {},\n ): Promise<void> {\n const { numericValue, inferredType } = coerceSignalValue(value);\n const { agentId, metricName, metadata, dataType, ...rest } = options;\n\n // Required signal keys are written LAST so a caller's `metadata` cannot\n // accidentally clobber them and silently drop the signal from aggregation.\n const signalMetadata: Record<string, unknown> = {\n ...(metadata ?? {}),\n [SUCCESS_SIGNAL_KEY]: true,\n [SUCCESS_METRIC_NAME_KEY]: metricName ?? name,\n ...(agentId ? { [AGENT_ID_KEY]: agentId } : {}),\n };\n\n await this.score(name, numericValue, {\n ...rest,\n dataType: dataType ?? inferredType,\n metadata: signalMetadata,\n });\n }\n\n private async request(\n method: \"POST\",\n path: string,\n payload: Record<string, unknown>,\n ): Promise<void> {\n let response: Response;\n try {\n response = await fetch(`${this.host}${path}`, {\n method,\n headers: {\n Authorization: this.authHeader(),\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(payload),\n signal: AbortSignal.timeout(this.timeoutSeconds * 1000),\n });\n } catch (error) {\n throw new ScoreError(\n `${method} ${path} failed: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n\n const text = await response.text();\n if (!response.ok) {\n throw new ScoreError(\n `${method} ${path} failed (${response.status}): ${text.slice(0, 500)}`,\n );\n }\n this.log(\"%s %s -> %s\", method, path, response.status);\n }\n\n private authHeader(): string {\n return `Basic ${Buffer.from(`${this.publicKey}:${this.secretKey}`).toString(\n \"base64\",\n )}`;\n }\n\n private log(message: string, ...args: unknown[]): void {\n if (this.debug) {\n console.log(`[gateway.scores] ${message}`, ...args);\n }\n }\n\n private warn(message: string, ...args: unknown[]): void {\n console.warn(`[gateway.scores] ${message}`, ...args);\n }\n}\n\n/** Map a success value to its numeric score + inferred data type. */\nfunction coerceSignalValue(value: boolean | number): {\n numericValue: number;\n inferredType: \"NUMERIC\" | \"BOOLEAN\";\n} {\n if (typeof value === \"boolean\") {\n return { numericValue: value ? 1 : 0, inferredType: \"BOOLEAN\" };\n }\n return { numericValue: value, inferredType: \"NUMERIC\" };\n}\n\n/**\n * Emit a success signal using credentials from the environment\n * (GATEWAY_HOST / GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY) — the ergonomic\n * top-level entry point for the default `tracing.init()` path, mirroring the\n * Python SDK's `run.success(...)`. FAIL-SOFT end to end: a missing/invalid\n * environment or a transport failure warns and resolves, never throwing into\n * the caller. For isolated providers use the handle's bound client\n * (`handle.scores.success(...)`) instead so the signal lands in that project.\n */\nexport async function success(\n name: string,\n value: boolean | number = true,\n options: SuccessOptions = {},\n): Promise<void> {\n let client: ScoresClient;\n try {\n client = ScoresClient.fromEnv();\n } catch (error) {\n console.warn(`[gateway.scores] success '${name}' skipped`, error);\n return;\n }\n await client.success(name, value, options);\n}\n\n/** Lowercase convenience namespace, matching the `users` export. */\nexport const scores = {\n fromEnv: ScoresClient.fromEnv,\n success,\n};\n","/**\n * Agent build identity — \"the agent IS the manifest.\"\n *\n * There is no build file and no lockfile. As the agent constructs itself,\n * the SDK observes everything that defines a build: tools registered through\n * defineTool() (name, declared version, schema hash, effects, source\n * location), prompts registered through registerPrompt(), the code ref from\n * CI/env, and the SDK's own version. tracing.init({ agent, version })\n * assembles the canonical manifest, computes the content-addressed\n * buildHash, stamps it on every span, and auto-registers the build with\n * Gateway (idempotent on hash — every replica of the same code is one\n * build). Releases are label moves on the platform, never mutations here.\n *\n * v1 versioning is developer-declared: you bump `version` on the agent and\n * on tools; Gateway records schema/impl hashes as evidence alongside.\n */\nimport { createHash } from \"node:crypto\";\n\nexport type ToolEffects = \"read\" | \"write\" | \"irreversible\";\n\nexport interface ToolIdentity {\n name: string;\n version?: string;\n effects?: ToolEffects;\n schemaHash: string;\n description?: string;\n /** Source location of the defineTool call (\"src/tools/checkout.ts:42\"). */\n source?: string;\n}\n\n/** Any versioned artifact an agent is built from — tools, prompts, skills,\n * datasets, guardrails, configs… `content` hashes locally (off-platform);\n * `ref` pins a platform-hosted artifact (\"prompt/system@label:production\"). */\nexport interface ArtifactIdentity {\n kind: string;\n name: string;\n version?: string;\n contentHash?: string;\n ref?: string;\n source?: string;\n metadata?: Record<string, string>;\n}\n\nexport interface AgentBuildManifest {\n agentId: string;\n codeRef?: string;\n sdk: string;\n tools: ToolIdentity[];\n prompts: Record<string, string>;\n skills: Record<string, string>;\n artifacts: ArtifactIdentity[];\n}\n\n/** Deterministic JSON: object keys sorted recursively, arrays kept in order. */\nexport function canonicalJson(value: unknown): string {\n if (value === null || typeof value !== \"object\") {\n return JSON.stringify(value);\n }\n if (Array.isArray(value)) {\n return `[${value.map(canonicalJson).join(\",\")}]`;\n }\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n return `{${entries\n .map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`)\n .join(\",\")}}`;\n}\n\nexport function sha256(text: string): string {\n return `sha256:${createHash(\"sha256\").update(text).digest(\"hex\")}`;\n}\n\n// ── Registry (module-level; one agent process = one registry) ──────────────\n\nconst registeredTools = new Map<string, ToolIdentity>();\nconst registeredPrompts = new Map<string, string>();\nconst registeredSkills = new Map<string, string>();\nconst registeredArtifacts = new Map<string, ArtifactIdentity>();\n\n/** First app-code frame of the current stack (\"src/tools/checkout.ts:42\"). */\nfunction captureSource(): string | undefined {\n const stack = new Error().stack?.split(\"\\n\") ?? [];\n for (const line of stack.slice(1)) {\n // Skip the SDK's own frames (this module, packaged dist) and node internals\n // — NOT the whole install dir, or apps developed inside a monorepo next to\n // the SDK would never resolve a source.\n if (\n line.includes(\"build/index.ts\") ||\n line.includes(\"build/index.js\") ||\n line.includes(\"build/index.mjs\") ||\n line.includes(\"node_modules/@withgateway/\")\n ) {\n continue;\n }\n if (line.includes(\"node:internal\") || line.includes(\"(node:\")) continue;\n const match = /\\(?([^()\\s]+):(\\d+):\\d+\\)?$/.exec(line.trim());\n if (match) {\n const file = match[1].replace(/^file:\\/\\//, \"\");\n // Trim to a repo-relative-ish path for readability.\n const short = file.includes(\"/\") ? file.split(\"/\").slice(-4).join(\"/\") : file;\n return `${short}:${match[2]}`;\n }\n }\n return undefined;\n}\n\nexport interface DefineToolInput {\n name: string;\n /** Developer-declared tool version, e.g. \"2.1\" (v1: bumped manually). */\n version?: string;\n /** Side-effect class — feeds approval policies and gate severity. */\n effects?: ToolEffects;\n description?: string;\n /** JSON schema (or zod-serializable shape) of the tool's parameters. */\n schema?: unknown;\n /** Alias accepted for frameworks that call it inputSchema. */\n inputSchema?: unknown;\n}\n\n/**\n * Register a tool's identity and pass the definition through unchanged, so\n * it wraps ANY framework's tool shape:\n *\n * ```ts\n * const checkout = defineTool({\n * name: \"checkout\", version: \"2.1\", effects: \"write\",\n * schema, description, execute,\n * });\n * ```\n */\nexport function defineTool<T extends DefineToolInput>(tool: T): T {\n const schemaBasis = tool.schema ?? tool.inputSchema ?? null;\n const source = captureSource();\n const identity: ToolIdentity = {\n name: tool.name,\n ...(tool.version !== undefined ? { version: tool.version } : {}),\n ...(tool.effects !== undefined ? { effects: tool.effects } : {}),\n ...(tool.description !== undefined\n ? { description: tool.description.slice(0, 500) }\n : {}),\n schemaHash: sha256(\n canonicalJson({ schema: schemaBasis, description: tool.description ?? \"\" }),\n ),\n ...(source ? { source } : {}),\n };\n registeredTools.set(tool.name, identity);\n notifyRegistryChanged();\n return tool;\n}\n\n/**\n * Register a code-shipped prompt so it joins the build identity:\n * `const SYSTEM = registerPrompt(\"system\", \"You are…\")`. Returns the content\n * unchanged. Platform-served prompts don't need this — pin them by label.\n */\nexport interface RegisterArtifactOptions {\n /** Developer-declared version, e.g. \"1.2\" (v1: bumped manually). */\n version?: string;\n /** Local content — hashed into the identity (off-platform artifacts). */\n content?: string;\n /** Platform reference (on-platform artifacts): \"prompt/system@label:production\". */\n ref?: string;\n metadata?: Record<string, string>;\n}\n\n/**\n * Version ANY artifact the agent is built from — the generic primitive\n * behind registerPrompt/registerSkill. Works on- and off-platform:\n *\n * ```ts\n * registerArtifact(\"guardrail\", \"pii-filter\", { version: \"2.0\", content: RULES });\n * registerArtifact(\"prompt\", \"planner\", { ref: \"planner@label:production\" });\n * ```\n */\nexport function registerArtifact(\n kind: string,\n name: string,\n options: RegisterArtifactOptions = {},\n): ArtifactIdentity {\n const source = captureSource();\n const identity: ArtifactIdentity = {\n kind,\n name,\n ...(options.version !== undefined ? { version: options.version } : {}),\n ...(options.content !== undefined\n ? { contentHash: sha256(options.content) }\n : {}),\n ...(options.ref !== undefined ? { ref: options.ref } : {}),\n ...(source ? { source } : {}),\n ...(options.metadata ? { metadata: options.metadata } : {}),\n };\n registeredArtifacts.set(`${kind}:${name}`, identity);\n notifyRegistryChanged();\n return identity;\n}\n\nexport function registerPrompt(\n name: string,\n content: string,\n options: { version?: string } = {},\n): string {\n registeredPrompts.set(name, sha256(content));\n registerArtifact(\"prompt\", name, { ...options, content });\n return content;\n}\n\nexport function getRegisteredTools(): ToolIdentity[] {\n return [...registeredTools.values()].sort((a, b) =>\n a.name < b.name ? -1 : a.name > b.name ? 1 : 0,\n );\n}\n\n/**\n * Register a skill's identity — `registerSkill(\"triage\", \"1.0\")` — so skills\n * are versioned in the build like tools and prompts. The version string is\n * whatever you bump (or a content hash for file-based skills).\n */\nexport function registerSkill(\n name: string,\n version: string,\n options: { content?: string; ref?: string } = {},\n): void {\n registeredSkills.set(name, version);\n registerArtifact(\"skill\", name, { version, ...options });\n}\n\nexport function getRegisteredArtifacts(): ArtifactIdentity[] {\n return [...registeredArtifacts.values()].sort((a, b) =>\n `${a.kind}:${a.name}` < `${b.kind}:${b.name}` ? -1 : 1,\n );\n}\n\nexport function getRegisteredSkills(): Record<string, string> {\n return Object.fromEntries(\n [...registeredSkills.entries()].sort(([a], [b]) =>\n a < b ? -1 : a > b ? 1 : 0,\n ),\n );\n}\n\nexport function getRegisteredPrompts(): Record<string, string> {\n return Object.fromEntries(\n [...registeredPrompts.entries()].sort(([a], [b]) =>\n a < b ? -1 : a > b ? 1 : 0,\n ),\n );\n}\n\n/** Test hook. */\nexport function resetBuildRegistry(): void {\n registeredTools.clear();\n registeredPrompts.clear();\n registeredSkills.clear();\n registeredArtifacts.clear();\n activeBuilds.length = 0;\n if (reRegisterTimer) clearTimeout(reRegisterTimer);\n reRegisterTimer = null;\n}\n\n// ── Manifest assembly + registration ───────────────────────────────────────\n\nfunction sdkVersion(): string {\n try {\n // dist/build/index.js -> ../../package.json ; src/build -> same shape.\n /* eslint-disable-next-line @typescript-eslint/no-require-imports */\n const pkg = require(\"../../package.json\") as { version?: string };\n return `@withgateway/sdk@${pkg.version ?? \"unknown\"}`;\n } catch {\n return \"@withgateway/sdk\";\n }\n}\n\n/**\n * Git context most PaaS runtimes inject automatically (Vercel, Render,\n * Railway, Netlify, Heroku). On those hosts attribution is fully\n * zero-config — no GATEWAY_* or GITHUB_* env plumbing needed. Explicit\n * env vars always win; this only fills gaps.\n */\nexport function paasGitContext(): {\n provider: string;\n sha?: string;\n repo?: string;\n branch?: string;\n login?: string;\n} | null {\n const env = process.env;\n if (env.VERCEL_GIT_COMMIT_SHA) {\n // Only surface the repo when it's GitHub-shaped — enrichment is\n // GitHub-only; a GitLab/Bitbucket repo would just 404 over there.\n const isGithub = (env.VERCEL_GIT_PROVIDER ?? \"github\") === \"github\";\n return {\n provider: \"vercel\",\n sha: env.VERCEL_GIT_COMMIT_SHA,\n repo:\n isGithub && env.VERCEL_GIT_REPO_OWNER && env.VERCEL_GIT_REPO_SLUG\n ? `${env.VERCEL_GIT_REPO_OWNER}/${env.VERCEL_GIT_REPO_SLUG}`\n : undefined,\n branch: env.VERCEL_GIT_COMMIT_REF,\n login: env.VERCEL_GIT_COMMIT_AUTHOR_LOGIN,\n };\n }\n if (env.RENDER_GIT_COMMIT) {\n return {\n provider: \"render\",\n sha: env.RENDER_GIT_COMMIT,\n repo: env.RENDER_GIT_REPO_SLUG, // already \"owner/repo\"\n branch: env.RENDER_GIT_BRANCH,\n };\n }\n if (env.RAILWAY_GIT_COMMIT_SHA) {\n return {\n provider: \"railway\",\n sha: env.RAILWAY_GIT_COMMIT_SHA,\n repo:\n env.RAILWAY_GIT_REPO_OWNER && env.RAILWAY_GIT_REPO_NAME\n ? `${env.RAILWAY_GIT_REPO_OWNER}/${env.RAILWAY_GIT_REPO_NAME}`\n : undefined,\n branch: env.RAILWAY_GIT_BRANCH,\n login: env.RAILWAY_GIT_AUTHOR,\n };\n }\n if (env.NETLIFY && env.COMMIT_REF) {\n const repoMatch = /github\\.com[/:]([^/]+\\/[^/.]+)/.exec(\n env.REPOSITORY_URL ?? \"\",\n );\n return {\n provider: \"netlify\",\n sha: env.COMMIT_REF,\n repo: repoMatch?.[1],\n branch: env.BRANCH,\n };\n }\n // Heroku (dyno metadata) and common bare conventions: sha only — the\n // platform resolves the repo server-side via the GitHub connection.\n const bareSha =\n env.HEROKU_SLUG_COMMIT ?? env.SOURCE_VERSION ?? env.GIT_COMMIT ?? env.COMMIT_SHA;\n if (bareSha) {\n return {\n provider: env.HEROKU_SLUG_COMMIT || env.SOURCE_VERSION ? \"heroku\" : \"generic\",\n sha: bareSha,\n };\n }\n return null;\n}\n\nfunction codeRef(): string | undefined {\n const paas = paasGitContext();\n const sha =\n process.env.GATEWAY_COMMIT ??\n process.env.GITHUB_SHA ??\n process.env.CI_COMMIT_SHA ?? // GitLab\n process.env.CIRCLE_SHA1 ??\n paas?.sha;\n if (!sha) return undefined;\n const repo =\n process.env.GITHUB_REPOSITORY ?? process.env.CI_PROJECT_PATH ?? paas?.repo;\n return repo ? `git:${repo}@${sha}` : `git:${sha}`;\n}\n\nexport function assembleManifest(agentId: string): AgentBuildManifest {\n return {\n agentId,\n ...(codeRef() ? { codeRef: codeRef() } : {}),\n sdk: sdkVersion(),\n tools: getRegisteredTools(),\n prompts: getRegisteredPrompts(),\n skills: getRegisteredSkills(),\n artifacts: getRegisteredArtifacts(),\n };\n}\n\nexport function computeBuildHash(manifest: AgentBuildManifest): string {\n // Source locations are display metadata, not identity — the same tool\n // declared on a different line (or after a refactor that moved it) is the\n // same tool. They stay in the manifest payload for the platform to show.\n const identity = {\n ...manifest,\n tools: manifest.tools.map(({ source: _source, ...tool }) => tool),\n artifacts: manifest.artifacts.map(\n ({ source: _source, ...artifact }) => artifact,\n ),\n };\n return sha256(canonicalJson(identity));\n}\n\nexport function attributionFromEnv(): Record<string, unknown> {\n const attribution: Record<string, unknown> = { source: \"runtime\" };\n if (process.env.GITHUB_ACTIONS) attribution.source = \"ci\";\n if (process.env.GITHUB_ACTOR) attribution.githubLogin = process.env.GITHUB_ACTOR;\n const sha = process.env.GATEWAY_COMMIT ?? process.env.GITHUB_SHA;\n if (sha) attribution.commitSha = sha;\n if (process.env.GITHUB_REPOSITORY) attribution.repo = process.env.GITHUB_REPOSITORY;\n const branch = process.env.GITHUB_HEAD_REF ?? process.env.GITHUB_REF_NAME;\n if (branch) attribution.branch = branch;\n // PaaS-injected git context (Vercel/Render/Railway/Netlify/Heroku) fills\n // any gaps — zero-config attribution on those hosts. Explicit env wins.\n const paas = paasGitContext();\n if (paas) {\n if (attribution.source === \"runtime\") attribution.source = `paas:${paas.provider}`;\n if (!attribution.commitSha && paas.sha) attribution.commitSha = paas.sha;\n if (!attribution.repo && paas.repo) attribution.repo = paas.repo;\n if (!attribution.branch && paas.branch) attribution.branch = paas.branch;\n if (!attribution.githubLogin && paas.login) attribution.githubLogin = paas.login;\n }\n const ref = process.env.GITHUB_REF ?? \"\";\n const prMatch = /refs\\/pull\\/(\\d+)\\//.exec(ref);\n if (prMatch) attribution.prNumber = Number(prMatch[1]);\n // PR title/body are NOT in the default Actions env — workflows pass them\n // through in two lines:\n // env:\n // GATEWAY_PR_TITLE: ${{ github.event.pull_request.title }}\n // GATEWAY_PR_BODY: ${{ github.event.pull_request.body }}\n if (process.env.GATEWAY_PR_TITLE) {\n attribution.prTitle = process.env.GATEWAY_PR_TITLE.slice(0, 300);\n }\n if (process.env.GATEWAY_PR_BODY) {\n attribution.prDescription = process.env.GATEWAY_PR_BODY.slice(0, 2000);\n }\n if (\n attribution.repo &&\n attribution.prNumber &&\n !(\"prUrl\" in attribution)\n ) {\n attribution.prUrl = `https://github.com/${String(attribution.repo)}/pull/${String(attribution.prNumber)}`;\n }\n return attribution;\n}\n\n// ── Late registration ──────────────────────────────────────────────────────\n// Many agents build their tool maps lazily (per request), AFTER init. Any\n// defineTool/registerPrompt/registerSkill call re-assembles the manifest for\n// every active agent build (debounced) and re-registers when the hash moved.\n// Content-addressed and idempotent: the registry simply gains the fullest\n// manifest; traces keep the hash stamped at init (documented behavior).\n\nexport interface ActiveBuildContext {\n host: string;\n publicKey: string;\n secretKey: string;\n agentId: string;\n version?: string;\n lastRegisteredHash?: string;\n}\n\nconst activeBuilds: ActiveBuildContext[] = [];\nlet reRegisterTimer: ReturnType<typeof setTimeout> | null = null;\nconst RE_REGISTER_DEBOUNCE_MS = 3000;\n\nexport function trackActiveBuild(context: ActiveBuildContext): void {\n activeBuilds.push(context);\n}\n\nfunction notifyRegistryChanged(): void {\n if (activeBuilds.length === 0) return;\n if (reRegisterTimer) clearTimeout(reRegisterTimer);\n reRegisterTimer = setTimeout(() => {\n reRegisterTimer = null;\n for (const context of activeBuilds) {\n const manifest = assembleManifest(context.agentId);\n const buildHash = computeBuildHash(manifest);\n if (buildHash === context.lastRegisteredHash) continue;\n context.lastRegisteredHash = buildHash;\n void registerBuild({ ...context, manifest, buildHash }).catch(() => {\n // fail-soft; a later change retries via the next notify\n context.lastRegisteredHash = undefined;\n });\n }\n }, RE_REGISTER_DEBOUNCE_MS);\n // Never hold the process open just to re-register.\n if (typeof reRegisterTimer === \"object\" && \"unref\" in reRegisterTimer) {\n (reRegisterTimer as { unref(): void }).unref();\n }\n}\n\n/**\n * Fire-and-forget build registration. Idempotent on buildHash server-side;\n * failures are logged once and never affect the agent.\n */\nexport async function registerBuild(params: {\n host: string;\n publicKey: string;\n secretKey: string;\n agentId: string;\n version?: string;\n manifest: AgentBuildManifest;\n buildHash: string;\n}): Promise<void> {\n const auth = Buffer.from(`${params.publicKey}:${params.secretKey}`).toString(\n \"base64\",\n );\n const response = await fetch(\n `${params.host.replace(/\\/$/, \"\")}/api/public/agent-builds`,\n {\n method: \"POST\",\n headers: {\n Authorization: `Basic ${auth}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n agentId: params.agentId,\n buildHash: params.buildHash,\n ...(params.version ? { semanticVer: params.version } : {}),\n manifest: params.manifest,\n attribution: attributionFromEnv(),\n }),\n signal: AbortSignal.timeout(15_000),\n },\n );\n if (!response.ok) {\n throw new Error(\n `build registration failed (${response.status}): ${(await response.text()).slice(0, 300)}`,\n );\n }\n}\n","export const GATEWAY_ENV = {\n HOST: \"GATEWAY_HOST\",\n PUBLIC_KEY: \"GATEWAY_PUBLIC_KEY\",\n SECRET_KEY: \"GATEWAY_SECRET_KEY\",\n API_KEY: \"GATEWAY_API_KEY\",\n ENDPOINT: \"GATEWAY_OTLP_ENDPOINT\",\n} as const;\n\nexport const OTLP_TRACES_PATH = \"/api/public/otel/v1/traces\";\n\nexport const OPENTELEMETRY_PEERS = {\n \"@opentelemetry/api\": \"1.9.0\",\n \"@opentelemetry/exporter-trace-otlp-http\": \"0.222.0\",\n \"@opentelemetry/resources\": \"2.11.0\",\n \"@opentelemetry/sdk-trace-base\": \"2.11.0\",\n \"@opentelemetry/sdk-trace-node\": \"2.11.0\",\n} as const;\n\nconst PINNED_PEERS = Object.entries(OPENTELEMETRY_PEERS)\n .map(([name, version]) => `${name}@${version}`)\n .join(\" \");\n\nconst MODULE_NOT_FOUND = new Set([\"MODULE_NOT_FOUND\", \"ERR_MODULE_NOT_FOUND\"]);\n\nexport function getEnv(key: string): string | undefined {\n const value = process.env[key];\n return value ? value : undefined;\n}\n\n/**\n * Check if Gateway is configured via environment variables.\n */\nexport function isGatewayConfigured(): boolean {\n return !!(\n getEnv(GATEWAY_ENV.HOST) &&\n getEnv(GATEWAY_ENV.PUBLIC_KEY) &&\n getEnv(GATEWAY_ENV.SECRET_KEY)\n );\n}\n\nexport class OpenTelemetryMissing extends Error {\n constructor() {\n super(\n \"OpenTelemetry packages not found. Install them next to @withgateway/sdk, at the versions it is tested with:\\n\" +\n ` npm install ${PINNED_PEERS}\\n` +\n ` npm install -g ${PINNED_PEERS} (the gateway CLI, when it was installed with npm install -g)`,\n );\n this.name = \"OpenTelemetryMissing\";\n }\n\n static explains(error: unknown): boolean {\n if (error instanceof OpenTelemetryMissing) return true;\n const { code, message } = (error ?? {}) as {\n code?: unknown;\n message?: unknown;\n };\n return (\n MODULE_NOT_FOUND.has(String(code)) &&\n String(message).includes(\"@opentelemetry/\")\n );\n }\n}\n","import type { Tracer } from \"@opentelemetry/api\";\nimport type { TracingConfig, TracingState } from \"./types\";\nimport { IdentitySpanProcessor } from \"./identity\";\nimport { SecretRedactingSpanProcessor } from \"./secrets\";\nimport { SessionSpanProcessor } from \"./session\";\nimport { ScoresClient } from \"../scores/index\";\nimport {\n assembleManifest,\n computeBuildHash,\n registerBuild,\n trackActiveBuild,\n type AgentBuildManifest,\n} from \"../build/index\";\nimport {\n GATEWAY_ENV,\n getEnv,\n OpenTelemetryMissing,\n OTLP_TRACES_PATH,\n} from \"./prerequisites\";\n\nexport { isGatewayConfigured } from \"./prerequisites\";\n\nconst state: TracingState & { debug?: boolean } = {\n initialized: false,\n provider: null,\n};\n\nfunction log(message: string, ...args: unknown[]): void {\n if (state.debug) {\n console.log(`[gatewaysdk.tracing] ${message}`, ...args);\n }\n}\n\nfunction warn(message: string, ...args: unknown[]): void {\n console.warn(`[gatewaysdk.tracing] ${message}`, ...args);\n}\n\ntype LogFn = (message: string, ...args: unknown[]) => void;\n\n/**\n * Handle to an isolated tracing provider created by initIsolated().\n * Spans started from `tracer` export to that provider's Gateway project;\n * the global tracer (from init()) is untouched.\n */\nexport interface TracingHandle {\n tracer: Tracer;\n /**\n * Scores/success-signal client bound to THIS provider's project keys. Emit\n * ROI success signals into the same project the handle's spans export to —\n * `handle.scores.success(\"resolved_ticket\", true, { agentId, sessionId })` —\n * without threading credentials through your own code. Fail-soft, like the\n * rest of the client.\n */\n scores: ScoresClient;\n /** Force-flush pending spans for this provider only. */\n flush(): Promise<void>;\n /** Flush and shut down this provider only. */\n shutdown(): Promise<void>;\n}\n\n/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-require-imports */\nfunction buildProvider(config: TracingConfig, logFn: LogFn): any {\n const host = config.host ?? getEnv(GATEWAY_ENV.HOST);\n const publicKey = config.publicKey ?? getEnv(GATEWAY_ENV.PUBLIC_KEY);\n const secretKey = config.secretKey ?? getEnv(GATEWAY_ENV.SECRET_KEY);\n const endpoint =\n config.endpoint ??\n getEnv(GATEWAY_ENV.ENDPOINT) ??\n (host ? `${host.replace(/\\/$/, \"\")}${OTLP_TRACES_PATH}` : undefined);\n\n const missing: string[] = [];\n if (!host) missing.push(\"host (or GATEWAY_HOST env var)\");\n if (!publicKey) missing.push(\"publicKey (or GATEWAY_PUBLIC_KEY env var)\");\n if (!secretKey) missing.push(\"secretKey (or GATEWAY_SECRET_KEY env var)\");\n\n if (missing.length > 0) {\n throw new Error(\n `Missing required Gateway configuration: ${missing.join(\", \")}. ` +\n \"Provide these values via init() parameters or environment variables.\",\n );\n }\n\n // Peer dependencies, required lazily; `any` avoids cross-version OTel type conflicts.\n let NodeTracerProvider: any;\n let BatchSpanProcessor: any;\n let OTLPTraceExporter: any;\n let createResource: (attrs: Record<string, string>) => any;\n let ATTR_SERVICE_NAME: string;\n\n try {\n const traceNode = require(\"@opentelemetry/sdk-trace-node\");\n const traceBase = require(\"@opentelemetry/sdk-trace-base\");\n const otlpHttp = require(\"@opentelemetry/exporter-trace-otlp-http\");\n const resources = require(\"@opentelemetry/resources\");\n\n NodeTracerProvider = traceNode.NodeTracerProvider;\n BatchSpanProcessor = traceBase.BatchSpanProcessor;\n OTLPTraceExporter = otlpHttp.OTLPTraceExporter;\n\n if (resources.Resource) {\n createResource = (attrs) => new resources.Resource(attrs);\n } else if (resources.resourceFromAttributes) {\n createResource = resources.resourceFromAttributes;\n } else {\n createResource = () => resources.defaultResource();\n }\n\n try {\n const semconv = require(\"@opentelemetry/semantic-conventions\");\n ATTR_SERVICE_NAME =\n semconv.ATTR_SERVICE_NAME ??\n semconv.SEMRESATTRS_SERVICE_NAME ??\n \"service.name\";\n } catch {\n ATTR_SERVICE_NAME = \"service.name\";\n }\n } catch {\n throw new OpenTelemetryMissing();\n }\n\n const resourceAttrs: Record<string, string> = {\n [ATTR_SERVICE_NAME]: config.serviceName ?? \"gatewaysdk-tracing\",\n };\n if (config.environment) {\n resourceAttrs[\"gateway.environment\"] = config.environment;\n }\n if (config.version) {\n resourceAttrs[\"gateway.version\"] = config.version;\n }\n\n // Tools defined after init do not join the build identity.\n let buildInfo: { manifest: AgentBuildManifest; buildHash: string } | null =\n null;\n if (config.agent) {\n const manifest = assembleManifest(config.agent);\n const buildHash = computeBuildHash(manifest);\n buildInfo = { manifest, buildHash };\n resourceAttrs[\"gateway.agent.id\"] = config.agent;\n resourceAttrs[\"gateway.build.hash\"] = buildHash;\n if (config.version) {\n resourceAttrs[\"gateway.agent.version\"] = config.version;\n }\n logFn(\n \"Agent build identity: %s @ %s (%d tools, %d prompts)\",\n config.agent,\n buildHash.slice(0, 15),\n manifest.tools.length,\n Object.keys(manifest.prompts).length,\n );\n }\n\n let isLocalhost = false;\n if (endpoint) {\n try {\n const parsed = new URL(endpoint);\n isLocalhost =\n parsed.hostname === \"localhost\" || parsed.hostname === \"127.0.0.1\";\n } catch {\n isLocalhost = false;\n }\n }\n if (endpoint && !endpoint.startsWith(\"https://\") && !isLocalhost) {\n throw new Error(\n `Refusing to send credentials over insecure HTTP to ${endpoint}. ` +\n \"Use HTTPS or localhost for development.\",\n );\n }\n\n const credentials = `${publicKey}:${secretKey}`;\n const encoded = Buffer.from(credentials).toString(\"base64\");\n const authHeader = `Basic ${encoded}`;\n\n const exporter = new OTLPTraceExporter({\n url: endpoint,\n headers: {\n Authorization: authHeader,\n },\n });\n\n logFn(\"Configured Gateway exporter: endpoint=%s\", endpoint);\n\n // Custom processors go before the exporting BatchSpanProcessor.\n const spanProcessors: any[] = [];\n\n if (config.customSpanProcessors) {\n for (const sp of config.customSpanProcessors) {\n spanProcessors.push(new SecretRedactingSpanProcessor(sp as any));\n logFn(\n \"Added custom span processor: %s\",\n (sp as { constructor?: { name?: string } }).constructor?.name ??\n \"unknown\",\n );\n }\n }\n\n spanProcessors.push(new IdentitySpanProcessor());\n\n spanProcessors.push(new SessionSpanProcessor());\n\n const batchConfig: Record<string, number> = {};\n if (config.batch?.maxQueueSize) {\n batchConfig.maxQueueSize = config.batch.maxQueueSize;\n }\n if (config.batch?.scheduledDelayMillis) {\n batchConfig.scheduledDelayMillis = config.batch.scheduledDelayMillis;\n }\n if (config.batch?.maxExportBatchSize) {\n batchConfig.maxExportBatchSize = config.batch.maxExportBatchSize;\n }\n\n spanProcessors.push(\n new SecretRedactingSpanProcessor(\n new BatchSpanProcessor(exporter, batchConfig),\n ),\n );\n\n // OTel v2 removed addSpanProcessor(); its processors go in the constructor.\n let provider: any = new NodeTracerProvider({\n resource: createResource(resourceAttrs),\n });\n\n if (typeof provider.addSpanProcessor === \"function\") {\n for (const sp of spanProcessors) {\n provider.addSpanProcessor(sp);\n }\n } else {\n provider = new NodeTracerProvider({\n resource: createResource(resourceAttrs),\n spanProcessors,\n });\n }\n\n return {\n provider,\n buildInfo,\n connection: { host: host!, publicKey: publicKey!, secretKey: secretKey! },\n };\n}\n/* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/no-require-imports */\n\nfunction scheduleBuildRegistration(\n config: TracingConfig,\n built: ReturnType<typeof buildProvider>,\n): void {\n if (!config.agent || !built.buildInfo || config.registerBuild === false) {\n return;\n }\n const { manifest, buildHash } = built.buildInfo;\n // Track so tools/prompts/skills registered AFTER init re-register the\n // fullest manifest (debounced, content-addressed, idempotent).\n trackActiveBuild({\n host: built.connection.host,\n publicKey: built.connection.publicKey,\n secretKey: built.connection.secretKey,\n agentId: config.agent,\n version: config.version,\n lastRegisteredHash: buildHash,\n });\n void registerBuild({\n host: built.connection.host,\n publicKey: built.connection.publicKey,\n secretKey: built.connection.secretKey,\n agentId: config.agent,\n version: config.version,\n manifest,\n buildHash,\n }).catch((err: unknown) => {\n warn(\"Build registration failed (agent keeps running):\", err);\n });\n}\n\n/**\n * Initialize GatewaySDK tracing with automatic OpenTelemetry configuration.\n *\n * This function configures OpenTelemetry with a connection to Gateway\n * and sets up the ExperimentSpanProcessor for automatic experiment tagging.\n *\n * The Vercel AI SDK 7 emits spans only through a telemetry integration:\n * call `registerTelemetry(new OpenTelemetry())` (`registerTelemetry` from\n * `ai`, `OpenTelemetry` from `@ai-sdk/otel`) once after init(), or pass\n * `telemetry: { integrations: [new OpenTelemetry()] }` per call. AI SDK 6\n * takes `experimental_telemetry: { isEnabled: true }` instead.\n *\n * @example\n * ```typescript\n * import { tracing } from \"@withgateway/sdk\";\n *\n * // Using environment variables (GATEWAY_HOST, GATEWAY_PUBLIC_KEY, GATEWAY_SECRET_KEY)\n * tracing.init();\n *\n * // Or with explicit configuration\n * tracing.init({\n * host: \"https://app.gateway.dev\",\n * publicKey: \"pk-lf-...\",\n * secretKey: \"sk-lf-...\",\n * serviceName: \"my-agent\",\n * environment: \"production\",\n * });\n * ```\n */\nexport function init(config: TracingConfig = {}): void {\n if (state.initialized) {\n log(\"Tracing already initialized. Call shutdown() first to reinitialize.\");\n return;\n }\n\n state.debug = config.debug ?? false;\n\n const built = buildProvider(config, log);\n const provider = built.provider;\n provider.register();\n scheduleBuildRegistration(config, built);\n\n state.provider = provider;\n state.initialized = true;\n\n log(\n \"GatewaySDK tracing initialized successfully (service=%s)\",\n config.serviceName ?? \"gatewaysdk-tracing\",\n );\n}\n\n/**\n * Create an ISOLATED tracing provider that is NOT registered globally.\n *\n * Use this when one process must export different work to different Gateway\n * projects (e.g. a server hosting several agents, each with its own project\n * keys), or when the process already has its own global OpenTelemetry\n * provider that must not be replaced.\n *\n * Spans only reach the isolated provider when started from its `tracer` —\n * pass it explicitly to observe()/observeClaude() via their `tracer` option,\n * or to a framework's telemetry hook. On the Vercel AI SDK 7 that is\n * `telemetry: { integrations: [new OpenTelemetry({ tracer })] }`, with\n * `OpenTelemetry` from `@ai-sdk/otel`; AI SDK 6 takes\n * `experimental_telemetry: { isEnabled: true, tracer }` instead. Context\n * propagation still works across providers, so nesting behaves exactly as\n * with init().\n *\n * Can be called any number of times; each handle has its own exporter,\n * batch queue, and lifecycle.\n *\n * @example\n * ```typescript\n * import { tracing } from \"@withgateway/sdk\";\n *\n * const support = tracing.initIsolated({\n * host: \"https://app.gateway.dev\",\n * publicKey: \"pk-lf-support...\",\n * secretKey: \"sk-lf-support...\",\n * serviceName: \"support-agent\",\n * });\n *\n * await tracing.observe(\"support.run\", run, { tracer: support.tracer });\n * await support.flush();\n * ```\n *\n * @example\n * ```typescript\n * import { OpenTelemetry } from \"@ai-sdk/otel\";\n * import { generateText } from \"ai\";\n *\n * await generateText({\n * model,\n * prompt,\n * telemetry: {\n * integrations: [new OpenTelemetry({ tracer: support.tracer })],\n * },\n * });\n * ```\n */\nexport function initIsolated(config: TracingConfig = {}): TracingHandle {\n const debugLog: LogFn = config.debug\n ? (message, ...args) =>\n console.log(`[gatewaysdk.tracing:isolated] ${message}`, ...args)\n : () => {};\n\n const built = buildProvider(config, debugLog);\n const provider = built.provider;\n scheduleBuildRegistration(config, built);\n const tracer = provider.getTracer(\"@withgateway/sdk\") as Tracer;\n\n const scores = new ScoresClient({\n host: built.connection.host,\n publicKey: built.connection.publicKey,\n secretKey: built.connection.secretKey,\n debug: config.debug ?? false,\n });\n\n debugLog(\n \"Isolated tracing provider created (service=%s)\",\n config.serviceName ?? \"gatewaysdk-tracing\",\n );\n\n return {\n tracer,\n scores,\n async flush() {\n try {\n await (provider as { forceFlush: () => Promise<void> }).forceFlush();\n } catch (e) {\n warn(\"Error during isolated flush:\", e);\n }\n },\n async shutdown() {\n try {\n await (provider as { shutdown: () => Promise<void> }).shutdown();\n } catch (e) {\n warn(\"Error during isolated shutdown:\", e);\n }\n },\n };\n}\n\n/**\n * Force flush all pending spans without shutting down.\n *\n * Useful for ensuring spans are exported at specific points\n * (e.g., after completing a batch of work) without ending the tracing session.\n *\n * @returns Promise that resolves when flush completes\n */\nexport async function flush(): Promise<void> {\n if (!state.provider) {\n log(\"No provider to flush\");\n return;\n }\n\n try {\n await (state.provider as { forceFlush: () => Promise<void> }).forceFlush();\n log(\"Flush completed successfully\");\n } catch (e) {\n warn(\"Error during flush:\", e);\n }\n}\n\n/**\n * Force flush all pending spans and shutdown the tracer provider.\n *\n * This function should be called before process exit to ensure all spans\n * are exported. It is safe to call multiple times.\n *\n * @example\n * ```typescript\n * import { tracing } from \"@withgateway/sdk\";\n *\n * tracing.init();\n *\n * // On shutdown\n * process.on(\"SIGTERM\", async () => {\n * await tracing.shutdown();\n * process.exit(0);\n * });\n * ```\n */\nexport async function shutdown(): Promise<void> {\n if (!state.initialized || !state.provider) {\n log(\"Tracing not initialized, nothing to shutdown\");\n return;\n }\n\n try {\n await (state.provider as { shutdown: () => Promise<void> }).shutdown();\n log(\"Shutdown complete\");\n } catch (e) {\n warn(\"Error during shutdown:\", e);\n }\n\n state.provider = null;\n state.initialized = false;\n}\n\n/**\n * Check if tracing has been initialized.\n */\nexport function isInitialized(): boolean {\n return state.initialized;\n}\n","/**\n * observe() — group a unit of work (an agent run, a tool call) into a single\n * span so nested LLM/tool spans attach to it and the whole thing is one trace.\n *\n * Mirrors Langfuse's `observe()` / `startActiveObservation()`. This is what an\n * app uses to define a trace boundary when it drives a raw client loop (which\n * has no framework root span of its own): the callback runs inside the span's\n * OpenTelemetry context, so any auto-instrumented calls (see observeOpenAI) and\n * any nested observe() calls become children of it.\n *\n * The span carries OpenInference attributes (openinference.span.kind, input.value,\n * output.value), and Gateway maps a root span's input.value/output.value to the\n * trace-level input/output — so the trace shows the user input and final output.\n */\nimport { trace, context, SpanStatusCode } from \"@opentelemetry/api\";\nimport type { Tracer } from \"@opentelemetry/api\";\n\nexport type ObservationKind = \"AGENT\" | \"CHAIN\" | \"TOOL\" | \"LLM\" | \"RETRIEVER\";\n\nexport interface ObserveOptions {\n /** Recorded as input.value on the span (JSON-stringified if not a string). */\n input?: unknown;\n /** OpenInference span kind. Defaults to \"AGENT\" for the outer run. */\n kind?: ObservationKind;\n /**\n * When true (default), the callback's return value is recorded as\n * output.value. Set false if the return value is large/uninteresting.\n */\n captureOutput?: boolean;\n /**\n * Tracer to start the span from. Defaults to the GLOBAL tracer (set up by\n * tracing.init()). Pass an initIsolated() handle's tracer to route this\n * observation to that handle's Gateway project instead.\n */\n tracer?: Tracer;\n /**\n * Extra attributes for the span — e.g. gateway.session.id /\n * gateway.user.id to group runs into a session and attribute them to a user.\n */\n attributes?: Record<string, string>;\n}\n\nfunction asAttr(value: unknown): string {\n return typeof value === \"string\" ? value : JSON.stringify(value);\n}\n\n/**\n * Run `fn` inside a span named `name`. Anything traced inside (auto-instrumented\n * client calls, nested observe() calls) nests under it, forming one trace.\n *\n * @example\n * ```ts\n * const result = await observe(\"my-agent.run\", async () => {\n * // client.chat.completions.create(...) here becomes a child GENERATION\n * return finalText;\n * }, { input: prompt });\n * ```\n */\nexport async function observe<T>(\n name: string,\n fn: () => Promise<T>,\n options: ObserveOptions = {},\n): Promise<T> {\n const tracer = options.tracer ?? trace.getTracer(\"@withgateway/sdk\");\n const span = tracer.startSpan(name, {\n attributes: {\n \"openinference.span.kind\": options.kind ?? \"AGENT\",\n ...(options.input !== undefined\n ? { \"input.value\": asAttr(options.input) }\n : {}),\n ...(options.attributes ?? {}),\n },\n });\n\n try {\n const result = await context.with(\n trace.setSpan(context.active(), span),\n fn,\n );\n if (options.captureOutput !== false && result !== undefined) {\n span.setAttribute(\"output.value\", asAttr(result));\n }\n span.setStatus({ code: SpanStatusCode.OK });\n return result;\n } catch (error) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: error instanceof Error ? error.message : String(error),\n });\n throw error;\n } finally {\n span.end();\n }\n}\n","/**\n * Client wrappers that turn an SDK's calls into spans on the Gateway provider.\n *\n * Node ESM can't retroactively patch a module the app already imported, so — as\n * Langfuse does with `observeOpenAI` — the app hands us the client and we\n * instrument it explicitly. One SDK call, no OpenTelemetry in the app.\n *\n * The OpenInference instrumentations are bundled optional deps of this package;\n * we load them with require() (the ESM build injects a real createRequire).\n */\n/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-require-imports */\n\nfunction warn(message: string, ...args: unknown[]): void {\n console.warn(`[gatewaysdk.tracing] ${message}`, ...args);\n}\n\n/**\n * Instrument an OpenAI client so its requests become GENERATION spans on the\n * Gateway provider. Returns the same client (its class prototype is patched, so\n * this and every other instance of that client are traced).\n *\n * @example\n * ```ts\n * import OpenAI from \"openai\";\n * import { init, observeOpenAI } from \"@withgateway/sdk/tracing\";\n * init();\n * const client = observeOpenAI(new OpenAI());\n * ```\n */\nexport function observeOpenAI<T extends object>(client: T): T {\n try {\n const {\n OpenAIInstrumentation,\n } = require(\"@arizeai/openinference-instrumentation-openai\");\n // OpenInference patches `module.OpenAI.Chat.Completions.prototype`, so it\n // needs an object shaped like the openai module. Reconstruct it from the\n // instance's class (client.constructor === the OpenAI class).\n const OpenAIClass = (client as { constructor: unknown }).constructor;\n new OpenAIInstrumentation().manuallyInstrument({ OpenAI: OpenAIClass });\n } catch (error) {\n warn(\n \"observeOpenAI: could not load @arizeai/openinference-instrumentation-openai — OpenAI calls will not be traced.\",\n error,\n );\n }\n return client;\n}\n\n/**\n * Instrument an Anthropic client so its requests become GENERATION spans.\n *\n * @example\n * ```ts\n * import Anthropic from \"@anthropic-ai/sdk\";\n * import { init, observeAnthropic } from \"@withgateway/sdk/tracing\";\n * init();\n * const client = observeAnthropic(new Anthropic());\n * ```\n */\nexport function observeAnthropic<T extends object>(client: T): T {\n try {\n const {\n AnthropicInstrumentation,\n } = require(\"@arizeai/openinference-instrumentation-anthropic\");\n // The instrumentor patches `module.Messages.prototype.create`, so it wants\n // an object whose `Messages` is the Anthropic client's Messages class (a\n // static on the class). `client.messages` resolves `create` through that\n // prototype, so patching it traces this client and every other instance.\n const AnthropicClass = (client as { constructor: { Messages?: unknown } })\n .constructor;\n new AnthropicInstrumentation().manuallyInstrument({\n Messages: AnthropicClass.Messages,\n });\n } catch (error) {\n warn(\n \"observeAnthropic: could not load @arizeai/openinference-instrumentation-anthropic — Anthropic calls will not be traced.\",\n error,\n );\n }\n return client;\n}\n","/**\n * observeClaude() — trace a Claude Agent SDK run.\n *\n * The Claude Agent SDK runs the agent in a separate `claude` CLI subprocess, so\n * there's nothing in-process to patch. What the app has is the message stream it\n * iterates. Wrap that stream with observeClaude() and it yields the same\n * messages unchanged while emitting spans on the Gateway provider.\n *\n * Default (one trace per run):\n *\n * AGENT (root)\n * ├─ GENERATION per assistant turn (with per-turn token usage)\n * └─ TOOL per tool call (input from tool_use, output from the\n * matching tool_result, matched by id)\n *\n * With `perTurn: true` (one trace PER ASSISTANT TURN — long agent runs read as\n * a session of turn traces, the way a chat thread does):\n *\n * AGENT \"<name> · turn N\" (detached root; session/user attributes on every turn)\n * ├─ GENERATION (that turn's usage + text)\n * └─ TOOL per tool call in the turn\n *\n * An \"assistant turn\" is one Anthropic API message. The SDK streams that\n * message as several `assistant` events — one per content block (text, then\n * each tool_use), all sharing `message.id` and all repeating the message-level\n * `usage`. Slices of the same message are folded into ONE generation (and one\n * turn in per-turn mode) so usage is counted once and the turn's text and tool\n * calls land on the same span.\n *\n * The TS equivalent of the Python SDK's claude-agent-sdk instrumentor.\n *\n * @example\n * ```ts\n * const stream = query({ prompt, options });\n * for await (const message of observeClaude(stream, { name, input: prompt })) {\n * // ...consume messages as usual\n * }\n * ```\n */\nimport {\n trace,\n context,\n SpanStatusCode,\n type Span,\n type Context,\n type Tracer,\n} from \"@opentelemetry/api\";\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nexport interface ObserveClaudeOptions {\n /** Root span name (becomes the trace name; per-turn mode appends `· turn N`). */\n name: string;\n /** Recorded as input.value on the root span → trace-level input. */\n input?: string;\n /**\n * Model label for the generation spans when the assistant message does not\n * carry one (`message.message.model` wins when present so cost attribution\n * matches the model that actually answered).\n */\n model?: string;\n /**\n * Tracer to start spans from. Defaults to the GLOBAL tracer (set up by\n * tracing.init()). Pass an initIsolated() handle's tracer to route this\n * run to that handle's Gateway project instead.\n */\n tracer?: Tracer;\n /**\n * Extra attributes for the root span(s) — e.g. gateway.session.id /\n * gateway.user.id to group runs into a session and attribute them to a user.\n * In per-turn mode these ride EVERY turn root, so each turn trace maps to\n * the session.\n */\n attributes?: Record<string, string>;\n /**\n * Emit one TRACE PER ASSISTANT TURN instead of a single trace for the whole\n * run. Each turn's trace carries that turn's generation and tool calls; the\n * turn's input is the run input (turn 1) or the tool results that fed it\n * (later turns). Turn roots are detached (`root: true`), so they never nest\n * under ambient spans. Combine with `attributes.gateway.session.id` to read\n * a whole run as a session of turns.\n */\n perTurn?: boolean;\n}\n\n/** Strip the `mcp__<server>__` prefix so tool names read cleanly. */\nfunction cleanToolName(name: string): string {\n return name.replace(/^mcp__[^_]+__/, \"\");\n}\n\nfunction toolResultText(content: unknown): string {\n if (typeof content === \"string\") return content;\n if (Array.isArray(content))\n return content\n .map((b) =>\n b && typeof b === \"object\" && \"text\" in b\n ? String((b as { text: unknown }).text)\n : JSON.stringify(b),\n )\n .join(\"\");\n return JSON.stringify(content ?? \"\");\n}\n\n/** `→ tool_a, → tool_b` — what a turn \"said\" when it only called tools. */\nfunction toolSummary(names: readonly string[]): string {\n return names.map((n) => `→ ${n}`).join(\", \");\n}\n\n/** Anthropic message usage → OpenInference token-count attributes. */\nconst USAGE_ATTRIBUTES: ReadonlyArray<readonly [string, string]> = [\n [\"input_tokens\", \"llm.token_count.prompt\"],\n [\"output_tokens\", \"llm.token_count.completion\"],\n [\"cache_read_input_tokens\", \"llm.token_count.prompt_details.cache_read\"],\n [\"cache_creation_input_tokens\", \"llm.token_count.prompt_details.cache_write\"],\n];\n\nfunction setUsageAttributes(span: Span, usage: unknown): void {\n if (!usage || typeof usage !== \"object\") return;\n const u = usage as Record<string, unknown>;\n for (const [field, attribute] of USAGE_ATTRIBUTES) {\n const value = u[field];\n if (typeof value === \"number\" && Number.isFinite(value))\n span.setAttribute(attribute, value);\n }\n}\n\nconst TURN_INPUT_MAX = 4000;\n\nexport async function* observeClaude(\n stream: AsyncIterable<any>,\n options: ObserveClaudeOptions,\n): AsyncGenerator<any> {\n const tracer = options.tracer ?? trace.getTracer(\"@withgateway/sdk\");\n const fallbackModel = options.model ?? \"claude\";\n const openTools = new Map<string, Span>();\n\n // Single-trace mode: one root for the whole run.\n let root: Span | null = null;\n let rootCtx: Context | null = null;\n if (!options.perTurn) {\n root = tracer.startSpan(options.name, {\n attributes: {\n \"openinference.span.kind\": \"AGENT\",\n ...(options.input !== undefined\n ? { \"input.value\": options.input }\n : {}),\n ...(options.attributes ?? {}),\n },\n });\n rootCtx = trace.setSpan(context.active(), root);\n }\n\n // Per-turn mode: the current turn's root, rotated on each assistant message.\n let turnRoot: Span | null = null;\n let turnCtx: Context | null = null;\n let turnIndex = 0;\n let turnText = \"\";\n let turnTools: string[] = [];\n // What fed the CURRENT turn: the run input for turn 1, then the tool results\n // produced since the previous assistant message.\n let pendingTurnInput = options.input ?? \"\";\n\n // The open generation for the assistant message currently streaming in.\n let gen: Span | null = null;\n let genMessageId: string | undefined;\n let genText = \"\";\n let genTools: string[] = [];\n let genUsage: unknown;\n\n let finalText = \"\";\n\n const endGeneration = () => {\n if (!gen) return;\n gen.setAttribute(\"output.value\", genText || toolSummary(genTools));\n setUsageAttributes(gen, genUsage);\n gen.setStatus({ code: SpanStatusCode.OK });\n gen.end();\n gen = null;\n genMessageId = undefined;\n genText = \"\";\n genTools = [];\n genUsage = undefined;\n };\n\n const endTurn = () => {\n if (!turnRoot) return;\n const output = turnText || toolSummary(turnTools);\n if (output) turnRoot.setAttribute(\"output.value\", output);\n turnRoot.setStatus({ code: SpanStatusCode.OK });\n turnRoot.end();\n turnRoot = null;\n turnCtx = null;\n };\n\n const startTurn = () => {\n // A new assistant message starts a new turn: any tools still open belong\n // to the previous turn — settle them, then rotate the root.\n for (const span of openTools.values()) span.end();\n openTools.clear();\n endTurn();\n turnIndex += 1;\n turnText = \"\";\n turnTools = [];\n turnRoot = tracer.startSpan(`${options.name} · turn ${turnIndex}`, {\n root: true,\n attributes: {\n \"openinference.span.kind\": \"AGENT\",\n ...(pendingTurnInput\n ? { \"input.value\": pendingTurnInput.slice(0, TURN_INPUT_MAX) }\n : {}),\n ...(options.attributes ?? {}),\n },\n });\n turnCtx = trace.setSpan(context.active(), turnRoot);\n pendingTurnInput = \"\";\n };\n\n const startGeneration = (message: any) => {\n endGeneration();\n if (options.perTurn) startTurn();\n const childCtx = (options.perTurn ? turnCtx : rootCtx)!;\n genMessageId = message.message?.id;\n gen = tracer.startSpan(\n \"assistant\",\n {\n attributes: {\n \"openinference.span.kind\": \"LLM\",\n \"llm.model_name\": message.message?.model ?? fallbackModel,\n \"llm.provider\": \"anthropic\",\n },\n },\n childCtx,\n );\n };\n\n try {\n for await (const message of stream) {\n if (message?.type === \"assistant\") {\n const messageId: string | undefined = message.message?.id;\n const continuesGeneration =\n gen !== null && messageId !== undefined && messageId === genMessageId;\n if (!continuesGeneration) startGeneration(message);\n const childCtx = (options.perTurn ? turnCtx : rootCtx)!;\n\n for (const block of message.message?.content ?? []) {\n if (block?.type === \"text\") {\n finalText += block.text;\n turnText += block.text;\n genText += block.text;\n }\n if (block?.type === \"tool_use\") {\n const name = cleanToolName(block.name);\n genTools.push(name);\n turnTools.push(name);\n const span = tracer.startSpan(\n `tool.${name}`,\n {\n attributes: {\n \"openinference.span.kind\": \"TOOL\",\n \"tool.name\": name,\n \"input.value\": JSON.stringify(block.input),\n },\n },\n childCtx,\n );\n openTools.set(block.id, span);\n }\n }\n // Every slice repeats the message-level usage; the last one is final.\n if (message.message?.usage) genUsage = message.message.usage;\n }\n\n // tool_result (in a `user` message) closes the matching TOOL span, and in\n // per-turn mode also becomes part of the NEXT turn's input.\n if (message?.type === \"user\") {\n const content = message.message?.content;\n if (Array.isArray(content)) {\n for (const block of content) {\n if (block?.type === \"tool_result\") {\n const resultText = toolResultText(block.content);\n const span = openTools.get(block.tool_use_id);\n if (span) {\n span.setAttribute(\"output.value\", resultText);\n span.setStatus({ code: SpanStatusCode.OK });\n span.end();\n openTools.delete(block.tool_use_id);\n }\n if (options.perTurn && pendingTurnInput.length < TURN_INPUT_MAX) {\n pendingTurnInput +=\n (pendingTurnInput ? \"\\n\" : \"\") +\n resultText.slice(0, TURN_INPUT_MAX - pendingTurnInput.length);\n }\n }\n }\n }\n }\n\n yield message;\n }\n } finally {\n endGeneration();\n for (const span of openTools.values()) span.end();\n openTools.clear();\n if (options.perTurn) {\n endTurn();\n } else if (root) {\n root.setAttribute(\"output.value\", finalText);\n root.setStatus({ code: SpanStatusCode.OK });\n root.end();\n }\n }\n}\n","/**\n * Attach an image (or any media) to a span: upload the bytes to the\n * platform's media store and put the returned reference into the span's\n * input or output. The trace view renders the reference inline:\n *\n * @@@langfuseMedia:type=image/png|id=<mediaId>|source=bytes@@@\n *\n * Three steps against `/api/public/media`: ask for a presigned URL (the\n * platform links the media to the trace and observation), PUT the bytes, then\n * report the upload's status. The presigned URL is a credential and never\n * reaches a log or an error. Python twin: `gatewaysdk/tracing/media.py`.\n * No OpenTelemetry import here, so the worlds entry can use it.\n */\nimport { createHash } from \"node:crypto\";\n\nimport { PlatformTransport, type PlatformMethod } from \"../worlds/transport\";\n\nexport const MEDIA_PATH = \"/api/public/media\";\nexport const MAX_MEDIA_BYTES = 5 * 1024 * 1024;\nconst PUT_TIMEOUT_MS = 30_000;\nconst MAX_UPLOAD_ERROR = 500;\nconst NETWORK_FAILURE_STATUS = 599;\n\nexport type MediaField = \"input\" | \"output\" | \"metadata\";\n\nexport class MediaUploadError extends Error {\n constructor(\n message: string,\n readonly status?: number,\n ) {\n super(message);\n this.name = \"MediaUploadError\";\n }\n}\n\nexport class MediaReference {\n constructor(\n readonly mediaId: string,\n readonly contentType: string,\n ) {}\n\n toString(): string {\n return `@@@langfuseMedia:type=${this.contentType}|id=${this.mediaId}|source=bytes@@@`;\n }\n}\n\nexport type PutBytes = (\n url: string,\n data: Buffer,\n headers: Record<string, string>,\n) => Promise<{ status: number; error: string | null }>;\n\n/** PUT to a presigned URL; a network failure is status 599 with the error's\n * name only, so the URL never travels. */\nexport async function putBytes(\n url: string,\n data: Buffer,\n headers: Record<string, string>,\n): Promise<{ status: number; error: string | null }> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), PUT_TIMEOUT_MS);\n try {\n const res = await fetch(url, {\n method: \"PUT\",\n body: new Uint8Array(data),\n headers,\n signal: controller.signal,\n });\n return {\n status: res.status,\n error: res.ok ? null : (await res.text()).slice(0, MAX_UPLOAD_ERROR),\n };\n } catch (error) {\n return {\n status: NETWORK_FAILURE_STATUS,\n error: error instanceof Error ? error.name : \"Error\",\n };\n } finally {\n clearTimeout(timer);\n }\n}\n\n/** Uploads media for one project (the key pair's). */\nexport class MediaUploader {\n constructor(\n private readonly transport: PlatformTransport,\n private readonly put: PutBytes = putBytes,\n public maxBytes: number = MAX_MEDIA_BYTES,\n ) {}\n\n /** The uploader for `GATEWAY_HOST` / `GATEWAY_PUBLIC_KEY` /\n * `GATEWAY_SECRET_KEY` only; null when any is unset, so a run traced with a saved login uploads none. */\n static fromEnv(env: NodeJS.ProcessEnv = process.env): MediaUploader | null {\n const host = env.GATEWAY_HOST;\n const publicKey = env.GATEWAY_PUBLIC_KEY;\n const secretKey = env.GATEWAY_SECRET_KEY;\n if (!host || !publicKey || !secretKey) return null;\n return new MediaUploader(\n new PlatformTransport({\n host: host.replace(/\\/$/, \"\"),\n publicKey,\n secretKey,\n }),\n );\n }\n\n /** Store `data` linked to the trace (and observation) and return its reference. */\n async upload(\n data: Buffer,\n link: {\n contentType: string;\n traceId: string;\n observationId: string | null;\n field: MediaField;\n },\n ): Promise<MediaReference> {\n if (data.length > this.maxBytes)\n throw new MediaUploadError(\n `media is ${data.length} bytes, over the ${this.maxBytes}-byte cap`,\n );\n const sha256Hash = createHash(\"sha256\").update(data).digest(\"base64\");\n const answer = (await this.send(\"POST\", MEDIA_PATH, {\n traceId: link.traceId,\n observationId: link.observationId,\n contentType: link.contentType,\n contentLength: data.length,\n sha256Hash,\n field: link.field,\n })) as { mediaId: string; uploadUrl?: string | null };\n if (typeof answer.mediaId !== \"string\" || !answer.mediaId)\n throw new MediaUploadError(\n \"POST /api/public/media answered without a mediaId\",\n );\n const reference = new MediaReference(answer.mediaId, link.contentType);\n if (answer.uploadUrl)\n await this.store(reference, answer.uploadUrl, data, sha256Hash);\n return reference;\n }\n\n private async store(\n reference: MediaReference,\n url: string,\n data: Buffer,\n sha256Hash: string,\n ): Promise<void> {\n const started = Date.now();\n const { status, error } = await this.put(url, data, {\n \"Content-Type\": reference.contentType,\n \"x-amz-checksum-sha256\": sha256Hash,\n \"x-ms-blob-type\": \"BlockBlob\",\n });\n await this.send(\n \"PATCH\",\n `${MEDIA_PATH}/${encodeURIComponent(reference.mediaId)}`,\n {\n uploadedAt: new Date().toISOString(),\n uploadHttpStatus: status,\n uploadHttpError: error,\n uploadTimeMs: Date.now() - started,\n },\n );\n if (status < 200 || status >= 300)\n throw new MediaUploadError(\n `media storage refused the upload (HTTP ${status})`,\n status,\n );\n }\n\n private async send(\n method: PlatformMethod,\n route: string,\n body: unknown,\n ): Promise<unknown> {\n const reply = await this.transport.send(method, route, body);\n if (!reply.ok)\n throw new MediaUploadError(\n `${method} ${route} -> ${reply.status}`,\n reply.status,\n );\n return reply.text ? JSON.parse(reply.text) : {};\n }\n}\n","/** 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","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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,iBAAAA,UAAAC,SAAA;AAAA,IAAAA,QAAA;AAAA,MACE,MAAQ;AAAA,MACR,SAAW;AAAA,MACX,aAAe;AAAA,MACf,MAAQ;AAAA,MACR,QAAU;AAAA,MACV,OAAS;AAAA,MACT,SAAW;AAAA,QACT,KAAK;AAAA,UACH,OAAS;AAAA,UACT,QAAU;AAAA,UACV,SAAW;AAAA,QACb;AAAA,QACA,iBAAiB;AAAA,UACf,OAAS;AAAA,UACT,QAAU;AAAA,UACV,SAAW;AAAA,QACb;AAAA,QACA,aAAa;AAAA,UACX,OAAS;AAAA,UACT,QAAU;AAAA,UACV,SAAW;AAAA,QACb;AAAA,QACA,YAAY;AAAA,UACV,OAAS;AAAA,UACT,QAAU;AAAA,UACV,SAAW;AAAA,QACb;AAAA,QACA,cAAc;AAAA,UACZ,OAAS;AAAA,UACT,QAAU;AAAA,UACV,SAAW;AAAA,QACb;AAAA,QACA,YAAY;AAAA,UACV,OAAS;AAAA,UACT,QAAU;AAAA,UACV,SAAW;AAAA,QACb;AAAA,QACA,cAAc;AAAA,UACZ,OAAS;AAAA,UACT,QAA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B,kBAAkB;AAAA,IACpB,CAAC;AACD,UAAM,KAAK;AAAA,MACT;AAAA,MACA,GAAG,UAAU,IAAI,mBAAmB,UAAU,OAAO,CAAC;AAAA,MACtD;AAAA,QACE,aAAY,oBAAI,KAAK,GAAE,YAAY;AAAA,QACnC,kBAAkB;AAAA,QAClB,iBAAiB;AAAA,QACjB,cAAc,KAAK,IAAI,IAAI;AAAA,MAC7B;AAAA,IACF;AACA,QAAI,SAAS,OAAO,UAAU;AAC5B,YAAM,IAAI;AAAA,QACR,0CAA0C,MAAM;AAAA,QAChD;AAAA,MACF;AAAA,EACJ;AAAA,EAEA,MAAc,KACZ,QACA,OACA,MACkB;AAClB,UAAM,QAAQ,MAAM,KAAK,UAAU,KAAK,QAAQ,OAAO,IAAI;AAC3D,QAAI,CAAC,MAAM;AACT,YAAM,IAAI;AAAA,QACR,GAAG,MAAM,IAAI,KAAK,OAAO,MAAM,MAAM;AAAA,QACrC,MAAM;AAAA,MACR;AACF,WAAO,MAAM,OAAO,KAAK,MAAM,MAAM,IAAI,IAAI,CAAC;AAAA,EAChD;AACF;","names":["exports","module","import_async_hooks","import_api","context","debugLog","scores","import_api","warn","import_api","import_node_crypto"]}
|