@withgateway/sdk 0.1.13 → 0.1.16
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/README.md +82 -4
- package/dist/cli.d.mts +1 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +1489 -0
- package/dist/cli.js.map +1 -0
- package/dist/cli.mjs +1476 -0
- package/dist/cli.mjs.map +1 -0
- package/dist/index.d.mts +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1213 -55
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1170 -54
- package/dist/index.mjs.map +1 -1
- package/dist/tracing/index.js +27 -2
- package/dist/tracing/index.js.map +1 -1
- package/dist/tracing/index.mjs +27 -2
- package/dist/tracing/index.mjs.map +1 -1
- package/dist/worlds/index.d.mts +508 -0
- package/dist/worlds/index.d.ts +508 -0
- package/dist/worlds/index.js +1120 -0
- package/dist/worlds/index.js.map +1 -0
- package/dist/worlds/index.mjs +1104 -0
- package/dist/worlds/index.mjs.map +1 -0
- package/package.json +27 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../package.json","../../src/tracing/identity.ts","../../src/users/index.ts","../../src/scores/index.ts","../../src/build/index.ts","../../src/tracing/init.ts","../../src/tracing/observe.ts","../../src/tracing/instrument.ts","../../src/tracing/claude.ts"],"sourcesContent":["{\n \"name\": \"@withgateway/sdk\",\n \"version\": \"0.1.13\",\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 },\n \"files\": [\n \"dist\",\n \"README.md\"\n ],\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"typecheck\": \"tsc --noEmit\",\n \"test\": \"vitest\",\n \"test:run\": \"vitest run\",\n \"lint\": \"eslint src --ext .ts\",\n \"clean\": \"rm -rf dist\",\n \"example\": \"tsx examples/test-ab-experiment.ts\",\n \"test:crm\": \"tsx examples/test-crm-ab-experiment.ts\",\n \"test:crm:balanced\": \"tsx examples/test-crm-ab-experiment.ts --balanced\",\n \"test:crm:full\": \"tsx examples/test-crm-ab-experiment.ts --users 12 --all-tasks --concurrency 3\"\n },\n \"keywords\": [\n \"gateway\",\n \"ab-testing\",\n \"experiments\",\n \"opentelemetry\",\n \"tracing\",\n \"observability\",\n \"llm\"\n ],\n \"author\": \"Gateway Team\",\n \"license\": \"MIT\",\n \"engines\": {\n \"node\": \">=18.0.0\"\n },\n \"peerDependencies\": {\n \"@opentelemetry/api\": \"^1.0.0\",\n \"@opentelemetry/exporter-trace-otlp-http\": \">=0.50.0\",\n \"@opentelemetry/resources\": \">=1.0.0\",\n \"@opentelemetry/sdk-trace-base\": \">=1.0.0\",\n \"@opentelemetry/sdk-trace-node\": \">=1.0.0\"\n },\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 },\n \"optionalDependencies\": {\n \"@arizeai/openinference-instrumentation-anthropic\": \"^0.1.15\",\n \"@arizeai/openinference-instrumentation-openai\": \"^4.1.5\"\n },\n \"devDependencies\": {\n \"@anthropic-ai/sdk\": \"^0.79.0\",\n \"@opentelemetry/api\": \"^1.9.0\",\n \"@opentelemetry/exporter-trace-otlp-http\": \"^0.212.0\",\n \"@opentelemetry/resources\": \"^2.6.0\",\n \"@opentelemetry/sdk-trace-base\": \"^1.30.1\",\n \"@opentelemetry/sdk-trace-node\": \"^2.6.0\",\n \"@opentelemetry/semantic-conventions\": \"^1.40.0\",\n \"@types/node\": \"^20.0.0\",\n \"tsup\": \"^8.0.0\",\n \"tsx\": \"^4.0.0\",\n \"typescript\": \"^5.0.0\",\n \"vitest\": \"^2.0.0\"\n }\n}\n","/**\n * End-user identity for GatewaySDK tracing.\n *\n * Mirrors the Python SDK's `gatewaysdk.tracing.identity` user half:\n *\n * - The ambient user is set via `identify()` and stored in an\n * AsyncLocalStorage (the TS analogue of Python's ContextVar), so\n * concurrent requests serving different users never bleed into each other.\n * - `IdentitySpanProcessor` (registered by `tracing.init()`) stamps the\n * ambient user on every span at start, so everything traced after\n * `identify()` is attributed automatically — the same seam as Python's\n * `TracingContextSpanProcessor` and this SDK's `ExperimentSpanProcessor`.\n * - `identify()` also stamps the currently open span directly, because\n * ingestion treats `gateway.user.id` on ANY span as a trace-level update —\n * the in-flight trace is attributed immediately.\n */\n\nimport { AsyncLocalStorage } from \"async_hooks\";\nimport { isSpanContextValid, trace } from \"@opentelemetry/api\";\nimport type { Context } from \"@opentelemetry/api\";\nimport type {\n ReadableSpan,\n Span,\n SpanProcessor,\n} from \"@opentelemetry/sdk-trace-base\";\nimport { UsersClient } from \"../users/index\";\n\nexport const USER_ID_ATTRIBUTE = \"gateway.user.id\";\n\n// Per-async-context user identity set via identify() — AsyncLocalStorage so\n// concurrent requests serving different users never bleed into each other.\nconst currentUserStorage = new AsyncLocalStorage<string>();\n\n/**\n * The active end-user id: identify() context > GATEWAY_USER_ID env.\n *\n * Per-request user attribution (e.g. from auth middleware) can also override\n * per span by setting the `gateway.user.id` attribute directly — explicit\n * set wins over the ambient default stamped at span start.\n */\nexport function resolveUserId(): string | undefined {\n const contextual = currentUserStorage.getStore();\n if (contextual) return contextual;\n const envUser = process.env.GATEWAY_USER_ID?.trim();\n return envUser ? envUser : undefined;\n}\n\nexport interface IdentifyOptions {\n /** Profile attributes to merge into the user's stored profile. */\n attributes?: Record<string, string | number | boolean>;\n displayName?: string;\n email?: string;\n}\n\n/**\n * Attribute everything that follows (and the current trace) to a user.\n *\n * - Sets the user for all spans started in this async context, and stamps\n * the currently open span so the in-flight trace is attributed immediately.\n * - When `attributes`/`displayName`/`email` are given, the user's platform\n * profile is updated in the background (attributes merge with what's\n * stored — ideal for incremental ROI facts like plan or account_value).\n * Requires GATEWAY_HOST/GATEWAY_PUBLIC_KEY/GATEWAY_SECRET_KEY for the\n * profile update; tracing attribution works without them. Failures are\n * swallowed (debug-logged) and never produce unhandled rejections.\n *\n * @example\n * ```typescript\n * import { identify } from \"@withgateway/sdk\";\n *\n * identify(\"user-123\", {\n * attributes: { plan: \"enterprise\", account_value: \"48000\" },\n * });\n * ```\n */\nexport function identify(userId: string, options: IdentifyOptions = {}): void {\n const cleaned = userId.trim();\n if (!cleaned) return;\n\n currentUserStorage.enterWith(cleaned);\n\n // Stamp the open span so the in-flight trace is upserted with the user —\n // ingestion treats user.id on ANY span as a trace-level update.\n try {\n const span = trace.getActiveSpan();\n if (span && isSpanContextValid(span.spanContext())) {\n span.setAttribute(USER_ID_ATTRIBUTE, cleaned);\n }\n } catch (error) {\n debugLog(\"identify(): no active span to stamp\", error);\n }\n\n if (options.attributes || options.displayName || options.email) {\n void pushProfile(cleaned, options);\n }\n}\n\nasync function pushProfile(\n userId: string,\n options: IdentifyOptions,\n): Promise<void> {\n try {\n const attributes: Record<string, string> = {};\n for (const [key, value] of Object.entries(options.attributes ?? {})) {\n attributes[key] = String(value);\n }\n await UsersClient.fromEnv().update(userId, {\n ...(options.displayName !== undefined\n ? { displayName: options.displayName }\n : {}),\n ...(options.email !== undefined ? { email: options.email } : {}),\n attributes,\n });\n } catch (error) {\n debugLog(\"identify(): profile update failed\", error);\n }\n}\n\n/** Testing hook: clear the ambient user for the current async context. */\nexport function resetAmbientUser(): void {\n currentUserStorage.enterWith(undefined as unknown as string);\n}\n\n/**\n * Stamps the ambient end-user identity (identify() context or\n * GATEWAY_USER_ID env) on every span at start. Registered automatically by\n * `tracing.init()`. Explicit `setAttribute` calls after span start win over\n * this ambient default.\n */\nexport class IdentitySpanProcessor implements SpanProcessor {\n onStart(span: Span, _parentContext: Context): void {\n const userId = resolveUserId();\n if (userId) {\n span.setAttribute(USER_ID_ATTRIBUTE, userId);\n }\n }\n\n onEnd(_span: ReadableSpan): void {}\n\n async shutdown(): Promise<void> {}\n\n async forceFlush(): Promise<void> {}\n}\n\nfunction debugLog(message: string, ...args: unknown[]): void {\n if (process.env.GATEWAY_DEBUG) {\n console.debug(`[gatewaysdk.tracing] ${message}`, ...args);\n }\n}\n","/**\n * End-user profiles — attribute usage and ROI to the real people behind\n * your agent's traffic.\n *\n * Profiles pair with the platform's per-user usage metrics (traces, tokens,\n * lifetime cost) on the Users page. Attributes merge by default, so pushing\n * an incremental ROI fact is one call:\n *\n * ```typescript\n * import { UsersClient } from \"@withgateway/sdk/users\";\n *\n * const users = UsersClient.fromEnv();\n * await users.update(\"user-123\", {\n * displayName: \"Acme Corp — Jane D.\",\n * attributes: { plan: \"enterprise\", account_value: \"48000\" },\n * });\n * ```\n *\n * Tip: `identify(\"user-123\", { attributes: {...} })` does this in the\n * background AND attributes the current trace/session to the user.\n *\n * Mirrors the Python SDK's `gatewaysdk.users` module.\n */\n\ntype UserProfile = {\n userId: string;\n displayName: string | null;\n email: string | null;\n attributes: Record<string, string>;\n notes: string | null;\n};\n\ntype UserProfileUpdate = {\n displayName?: string;\n email?: string;\n attributes?: Record<string, string>;\n notes?: string;\n /**\n * Attributes merge with the stored set by default. Set `merge: false`\n * to replace the stored attributes wholesale.\n */\n merge?: boolean;\n};\n\ntype UserEvent = {\n id: string;\n userId: string;\n event: string;\n /** Emitter-defined value (e.g. minutes saved, revenue). Summed at rollup. */\n value: number | null;\n metadata: Record<string, unknown>;\n traceId: string | null;\n sessionId: string | null;\n createdAt: Date;\n};\n\ntype UserEventOptions = {\n /** Worth of the event in your terms (minutes saved, revenue…). */\n value?: number;\n metadata?: Record<string, unknown>;\n /** Link to the trace that produced the event. */\n traceId?: string;\n /** Link to the session that produced the event. */\n sessionId?: string;\n};\n\ntype UsersClientConfig = {\n host: string;\n publicKey: string;\n secretKey: string;\n timeoutSeconds?: number;\n debug?: boolean;\n};\n\ntype UsersClientFromEnvConfig = Partial<UsersClientConfig>;\n\n/** Raised when the Gateway user-profiles API cannot complete a request. */\nexport class UserProfileError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message);\n this.name = \"UserProfileError\";\n this.cause = options?.cause;\n }\n}\n\n/** Client for Gateway's end-user profile endpoints (Basic project keys). */\nexport class UsersClient {\n private readonly host: string;\n private readonly publicKey: string;\n private readonly secretKey: string;\n private readonly timeoutSeconds: number;\n private readonly debug: boolean;\n\n constructor(config: UsersClientConfig) {\n this.host = config.host.replace(/\\/$/, \"\");\n this.publicKey = config.publicKey;\n this.secretKey = config.secretKey;\n this.timeoutSeconds = config.timeoutSeconds ?? 15;\n this.debug = config.debug ?? false;\n }\n\n /** Create a client from GATEWAY_HOST / GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY. */\n static fromEnv(config: UsersClientFromEnvConfig = {}) {\n const host = config.host ?? process.env.GATEWAY_HOST;\n const publicKey = config.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;\n const secretKey = config.secretKey ?? process.env.GATEWAY_SECRET_KEY;\n\n const missing = [\n [\"host\", host],\n [\"publicKey\", publicKey],\n [\"secretKey\", secretKey],\n ]\n .filter(([, value]) => !value)\n .map(([name]) => name);\n\n if (missing.length > 0) {\n throw new UserProfileError(\n `Missing Gateway user-profile configuration: ${missing.join(\", \")}`,\n );\n }\n\n return new UsersClient({\n ...config,\n host: host!,\n publicKey: publicKey!,\n secretKey: secretKey!,\n });\n }\n\n /** Fetch a user's stored profile. */\n async get(userId: string): Promise<UserProfile> {\n return parseProfile(\n await this.requestJson(\n \"GET\",\n `/api/public/user-profiles/${encodeURIComponent(userId)}`,\n ),\n );\n }\n\n /**\n * Upsert a user's profile. `attributes` merge with the stored set unless\n * `merge: false` (which replaces it).\n */\n async update(\n userId: string,\n update: UserProfileUpdate = {},\n ): Promise<UserProfile> {\n const body: Record<string, unknown> = {\n userId,\n attributes: update.attributes ?? {},\n mergeAttributes: update.merge ?? true,\n ...(update.displayName !== undefined\n ? { displayName: update.displayName }\n : {}),\n ...(update.email !== undefined ? { email: update.email } : {}),\n ...(update.notes !== undefined ? { notes: update.notes } : {}),\n };\n return parseProfile(\n await this.requestJson(\"POST\", \"/api/public/user-profiles\", body),\n );\n }\n\n /**\n * Record a VALUE EVENT for a user — the per-user ROI stream. `value` is\n * whatever the event is worth in your terms (minutes saved, revenue…);\n * Gateway sums it in the hours-saved/ROI rollups, and evals and task-set\n * replays can assert against the events. Link `traceId`/`sessionId` to tie\n * the event to the run that produced it.\n *\n * @example\n * ```ts\n * await client.trackEvent(\"user-123\", \"checkout_completed\", {\n * value: 25,\n * metadata: { cartSize: 3 },\n * sessionId,\n * });\n * ```\n */\n async trackEvent(\n userId: string,\n event: string,\n options: UserEventOptions = {},\n ): Promise<UserEvent> {\n const body: Record<string, unknown> = {\n userId,\n event,\n metadata: options.metadata ?? {},\n ...(options.value !== undefined ? { value: options.value } : {}),\n ...(options.traceId !== undefined ? { traceId: options.traceId } : {}),\n ...(options.sessionId !== undefined\n ? { sessionId: options.sessionId }\n : {}),\n };\n return parseEvent(\n await this.requestJson(\"POST\", \"/api/public/user-events\", body),\n );\n }\n\n /** List a project's user events, optionally filtered by user/event/time. */\n async listEvents(\n filter: {\n userId?: string;\n event?: string;\n fromTimestamp?: Date;\n toTimestamp?: Date;\n page?: number;\n limit?: number;\n } = {},\n ): Promise<{ data: UserEvent[]; totalItems: number }> {\n const params = new URLSearchParams();\n if (filter.userId) params.set(\"userId\", filter.userId);\n if (filter.event) params.set(\"event\", filter.event);\n if (filter.fromTimestamp)\n params.set(\"fromTimestamp\", filter.fromTimestamp.toISOString());\n if (filter.toTimestamp)\n params.set(\"toTimestamp\", filter.toTimestamp.toISOString());\n if (filter.page) params.set(\"page\", String(filter.page));\n if (filter.limit) params.set(\"limit\", String(filter.limit));\n const qs = params.toString();\n const payload = await this.requestJson(\n \"GET\",\n `/api/public/user-events${qs ? `?${qs}` : \"\"}`,\n );\n const rows = Array.isArray(payload.data) ? payload.data : [];\n const meta =\n payload.meta && typeof payload.meta === \"object\"\n ? (payload.meta as Record<string, unknown>)\n : {};\n return {\n data: rows.map((row) => parseEvent(row as Record<string, unknown>)),\n totalItems: Number(meta.totalItems ?? rows.length),\n };\n }\n\n private async requestJson(\n method: \"GET\" | \"POST\",\n path: string,\n payload?: Record<string, unknown>,\n ): Promise<Record<string, unknown>> {\n let response: Response;\n try {\n response = await fetch(`${this.host}${path}`, {\n method,\n headers: {\n Authorization: this.authHeader(),\n \"Content-Type\": \"application/json\",\n },\n ...(payload ? { body: JSON.stringify(payload) } : {}),\n signal: AbortSignal.timeout(this.timeoutSeconds * 1000),\n });\n } catch (error) {\n throw new UserProfileError(\n `${method} ${path} failed: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n\n const text = await response.text();\n if (!response.ok) {\n throw new UserProfileError(\n `${method} ${path} failed (${response.status}): ${text.slice(0, 500)}`,\n );\n }\n\n this.log(\"%s %s -> %s\", method, path, response.status);\n return safeJson(text);\n }\n\n private authHeader() {\n return `Basic ${Buffer.from(`${this.publicKey}:${this.secretKey}`).toString(\n \"base64\",\n )}`;\n }\n\n private log(message: string, ...args: unknown[]) {\n if (this.debug) {\n console.log(`[gateway.users] ${message}`, ...args);\n }\n }\n}\n\nfunction parseEvent(payload: Record<string, unknown>): UserEvent {\n return {\n id: String(payload.id ?? \"\"),\n userId: String(payload.userId ?? \"\"),\n event: String(payload.event ?? \"\"),\n value: typeof payload.value === \"number\" ? payload.value : null,\n metadata:\n payload.metadata &&\n typeof payload.metadata === \"object\" &&\n !Array.isArray(payload.metadata)\n ? (payload.metadata as Record<string, unknown>)\n : {},\n traceId: typeof payload.traceId === \"string\" ? payload.traceId : null,\n sessionId:\n typeof payload.sessionId === \"string\" ? payload.sessionId : null,\n createdAt:\n typeof payload.createdAt === \"string\"\n ? new Date(payload.createdAt)\n : new Date(0),\n };\n}\n\nfunction parseProfile(payload: Record<string, unknown>): UserProfile {\n return {\n userId: String(payload.userId ?? \"\"),\n displayName:\n typeof payload.displayName === \"string\" ? payload.displayName : null,\n email: typeof payload.email === \"string\" ? payload.email : null,\n attributes: parseAttributes(payload.attributes),\n notes: typeof payload.notes === \"string\" ? payload.notes : null,\n };\n}\n\nfunction parseAttributes(value: unknown): Record<string, string> {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return {};\n const attributes: Record<string, string> = {};\n for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {\n attributes[key] = String(entry);\n }\n return attributes;\n}\n\nfunction safeJson(value: string): Record<string, unknown> {\n try {\n const parsed = JSON.parse(value);\n return parsed && typeof parsed === \"object\" && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : {};\n } catch {\n return {};\n }\n}\n\nexport const users = {\n fromEnv: UsersClient.fromEnv,\n};\n\nexport type {\n UserProfile,\n UserProfileUpdate,\n UserEvent,\n UserEventOptions,\n UsersClientConfig,\n UsersClientFromEnvConfig,\n};\n","/**\n * Scores & success signals — record evaluation results and ROI-shaped success\n * signals against a Gateway project.\n *\n * A **score** is any evaluation value attached to a trace or session (visible\n * on the Scores page and in trace/session detail). A **success signal** is a\n * score carrying `metadata[\"gateway.success.signal\"]`, which the platform's\n * Success Metrics feature aggregates into a metric's headline count/pass-rate\n * (the `HOOK` metric source). Emit one whenever a real unit of business value\n * happens (\"resolved a ticket\", \"ran an eval\", \"a human accepted an edit\").\n *\n * This mirrors the Python SDK's `Run.score()` / `Run.success()`\n * (`gatewaysdk/sdk/src/gatewaysdk/run.py`). The score shape — name, numeric\n * value, `gateway.success.signal` + `gateway.success.metricName` metadata, and\n * the trace/session target — is IDENTICAL so the platform aggregates signals\n * from either SDK unchanged.\n *\n * ```typescript\n * import { ScoresClient } from \"@withgateway/sdk/scores\";\n *\n * const scores = ScoresClient.fromEnv();\n * // A pass/fail signal that feeds the \"resolved_ticket\" Success Metric:\n * await scores.success(\"resolved_ticket\", true, {\n * agentId: \"support-triage\",\n * sessionId,\n * });\n * // A numeric signal:\n * await scores.success(\"handle_time_s\", 42, { agentId: \"support-triage\", sessionId });\n * ```\n *\n * Under `tracing.initIsolated(...)` the returned handle exposes a `scores`\n * client already bound to that project's keys — that is how the platform\n * self-traces its own agents into dedicated projects.\n */\n\nimport { isSpanContextValid, trace } from \"@opentelemetry/api\";\n\n/** Score value data type, matching Gateway's ingestion schema. */\nexport type ScoreDataType = \"NUMERIC\" | \"CATEGORICAL\" | \"BOOLEAN\";\n\n/** Reserved metadata keys that mark a score as an aggregatable success signal. */\nexport const SUCCESS_SIGNAL_KEY = \"gateway.success.signal\";\nexport const SUCCESS_METRIC_NAME_KEY = \"gateway.success.metricName\";\nexport const AGENT_ID_KEY = \"gateway.agent.id\";\n\nexport type ScoreOptions = {\n /**\n * Trace to link the score to. Auto-detected from the active OpenTelemetry\n * span when omitted and no `sessionId` is given (mirrors the Python SDK).\n */\n traceId?: string;\n /** Session to link the score to. Preferred target when present. */\n sessionId?: string;\n /** Dataset-run to link the score to (dataset-run scores). */\n datasetRunId?: string;\n /** Span-level score — requires `traceId`. */\n observationId?: string;\n /** \"NUMERIC\" | \"CATEGORICAL\" | \"BOOLEAN\"; inferred when omitted. */\n dataType?: ScoreDataType;\n /** Optional comment stored alongside the score. */\n comment?: string;\n /** Extra metadata merged into the score. */\n metadata?: Record<string, unknown>;\n /** Environment tag; defaults to the project's `default` environment. */\n environment?: string;\n};\n\nexport type SuccessOptions = Omit<ScoreOptions, \"dataType\"> & {\n /**\n * The agent this signal belongs to (`gateway.agent.id`). Lets the platform\n * roll the signal into that agent's Success Metric without a trace join.\n */\n agentId?: string;\n /** The Success Metric name; defaults to the signal `name`. */\n metricName?: string;\n /** Override the inferred \"BOOLEAN\"/\"NUMERIC\" data type. */\n dataType?: \"NUMERIC\" | \"BOOLEAN\";\n};\n\nexport type ScoresClientConfig = {\n host: string;\n publicKey: string;\n secretKey: string;\n timeoutSeconds?: number;\n debug?: boolean;\n};\n\nexport type ScoresClientFromEnvConfig = Partial<ScoresClientConfig>;\n\n/** Raised by the low-level {@link ScoresClient.postScore} on a failed request. */\nexport class ScoreError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message);\n this.name = \"ScoreError\";\n this.cause = options?.cause;\n }\n}\n\n/**\n * Read the current trace id (32-hex) from the active OpenTelemetry span, or\n * undefined when there is no valid active span. Mirrors the Python SDK's\n * `_get_current_trace_id`.\n */\nexport function currentTraceId(): string | undefined {\n try {\n const span = trace.getActiveSpan();\n if (!span) return undefined;\n const ctx = span.spanContext();\n if (!ctx || !isSpanContextValid(ctx)) return undefined;\n return ctx.traceId;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Client for Gateway's public scores ingestion endpoint (Basic project keys).\n * The `score`/`success` convenience methods are FAIL-SOFT — they never reject\n * into the caller, they warn and resolve — matching the Python SDK's\n * fire-and-forget scoring. The raw {@link postScore} throws on failure for\n * callers that want to handle it.\n */\nexport class ScoresClient {\n private readonly host: string;\n private readonly publicKey: string;\n private readonly secretKey: string;\n private readonly timeoutSeconds: number;\n private readonly debug: boolean;\n\n constructor(config: ScoresClientConfig) {\n this.host = config.host.replace(/\\/$/, \"\");\n this.publicKey = config.publicKey;\n this.secretKey = config.secretKey;\n this.timeoutSeconds = config.timeoutSeconds ?? 15;\n this.debug = config.debug ?? false;\n }\n\n /** Create a client from GATEWAY_HOST / GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY. */\n static fromEnv(config: ScoresClientFromEnvConfig = {}): ScoresClient {\n const host = config.host ?? process.env.GATEWAY_HOST;\n const publicKey = config.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;\n const secretKey = config.secretKey ?? process.env.GATEWAY_SECRET_KEY;\n\n const missing = [\n [\"host\", host],\n [\"publicKey\", publicKey],\n [\"secretKey\", secretKey],\n ]\n .filter(([, value]) => !value)\n .map(([name]) => name);\n\n if (missing.length > 0) {\n throw new ScoreError(\n `Missing Gateway scores configuration: ${missing.join(\", \")}`,\n );\n }\n\n return new ScoresClient({\n ...config,\n host: host!,\n publicKey: publicKey!,\n secretKey: secretKey!,\n });\n }\n\n /**\n * Post a score, throwing {@link ScoreError} on any failure. Builds the exact\n * `POST /api/public/scores` body the Python SDK sends: exactly one of\n * `sessionId` / `traceId` (+ optional `observationId`) / `datasetRunId`.\n * When no target is provided, the active OTel trace id is used; if none is\n * available the call is a no-op (returns without posting), matching Python.\n */\n async postScore(\n name: string,\n value: number | string,\n options: ScoreOptions = {},\n ): Promise<void> {\n const body = this.buildScoreBody(name, value, options);\n if (!body) {\n this.log(\n \"score '%s' dropped: no sessionId, traceId or datasetRunId available\",\n name,\n );\n return;\n }\n await this.request(\"POST\", \"/api/public/scores\", body);\n }\n\n /**\n * Build the score request body, or null when no target can be resolved.\n * Split out so it is unit-testable and shared by score()/success().\n */\n buildScoreBody(\n name: string,\n value: number | string,\n options: ScoreOptions = {},\n ): Record<string, unknown> | null {\n // Prefer sessionId (scores typically grade a whole session/rollout), then\n // datasetRunId, then an explicit traceId, then the ambient OTel trace.\n const traceId = options.traceId ?? currentTraceId();\n const target: Record<string, unknown> = {};\n if (options.sessionId) {\n target.sessionId = options.sessionId;\n } else if (options.datasetRunId) {\n target.datasetRunId = options.datasetRunId;\n } else if (traceId) {\n target.traceId = traceId;\n if (options.observationId) target.observationId = options.observationId;\n } else {\n return null;\n }\n\n // Base metadata mirrors the Python SDK (source tag), then the caller's\n // metadata is merged on top — identical to `score_metadata.update(...)`.\n const metadata: Record<string, unknown> = {\n source: \"gatewaysdk\",\n ...(options.metadata ?? {}),\n };\n\n return {\n name,\n value,\n dataType: options.dataType ?? \"NUMERIC\",\n environment: options.environment ?? \"default\",\n ...(options.comment ? { comment: options.comment } : {}),\n metadata,\n ...target,\n };\n }\n\n /**\n * Post a score, FAIL-SOFT: warns and resolves on any failure so a broken\n * transport never throws into (or rejects out of) the caller.\n */\n async score(\n name: string,\n value: number | string,\n options: ScoreOptions = {},\n ): Promise<void> {\n try {\n await this.postScore(name, value, options);\n } catch (error) {\n this.warn(`score '${name}' failed`, error);\n }\n }\n\n /**\n * Emit a SUCCESS SIGNAL that feeds a Gateway Success Metric — a score tagged\n * with `gateway.success.signal` + `gateway.success.metricName` (and the agent\n * identity when `agentId` is set). A boolean `value` records a 1/0 BOOLEAN\n * score (pass/fail); a number records a NUMERIC score. FAIL-SOFT.\n *\n * The metadata shape matches the Python SDK's `Run.success()` exactly, so the\n * platform's Success Metrics aggregation counts signals from either SDK\n * without change.\n *\n * @example\n * ```ts\n * await scores.success(\"resolved_ticket\", true, { agentId: \"support-triage\", sessionId });\n * await scores.success(\"handle_time_s\", 42, { agentId: \"support-triage\", sessionId });\n * ```\n */\n async success(\n name: string,\n value: boolean | number = true,\n options: SuccessOptions = {},\n ): Promise<void> {\n const { numericValue, inferredType } = coerceSignalValue(value);\n const { agentId, metricName, metadata, dataType, ...rest } = options;\n\n // Required signal keys are written LAST so a caller's `metadata` cannot\n // accidentally clobber them and silently drop the signal from aggregation.\n const signalMetadata: Record<string, unknown> = {\n ...(metadata ?? {}),\n [SUCCESS_SIGNAL_KEY]: true,\n [SUCCESS_METRIC_NAME_KEY]: metricName ?? name,\n ...(agentId ? { [AGENT_ID_KEY]: agentId } : {}),\n };\n\n await this.score(name, numericValue, {\n ...rest,\n dataType: dataType ?? inferredType,\n metadata: signalMetadata,\n });\n }\n\n private async request(\n method: \"POST\",\n path: string,\n payload: Record<string, unknown>,\n ): Promise<void> {\n let response: Response;\n try {\n response = await fetch(`${this.host}${path}`, {\n method,\n headers: {\n Authorization: this.authHeader(),\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(payload),\n signal: AbortSignal.timeout(this.timeoutSeconds * 1000),\n });\n } catch (error) {\n throw new ScoreError(\n `${method} ${path} failed: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n\n const text = await response.text();\n if (!response.ok) {\n throw new ScoreError(\n `${method} ${path} failed (${response.status}): ${text.slice(0, 500)}`,\n );\n }\n this.log(\"%s %s -> %s\", method, path, response.status);\n }\n\n private authHeader(): string {\n return `Basic ${Buffer.from(`${this.publicKey}:${this.secretKey}`).toString(\n \"base64\",\n )}`;\n }\n\n private log(message: string, ...args: unknown[]): void {\n if (this.debug) {\n console.log(`[gateway.scores] ${message}`, ...args);\n }\n }\n\n private warn(message: string, ...args: unknown[]): void {\n console.warn(`[gateway.scores] ${message}`, ...args);\n }\n}\n\n/** Map a success value to its numeric score + inferred data type. */\nfunction coerceSignalValue(value: boolean | number): {\n numericValue: number;\n inferredType: \"NUMERIC\" | \"BOOLEAN\";\n} {\n if (typeof value === \"boolean\") {\n return { numericValue: value ? 1 : 0, inferredType: \"BOOLEAN\" };\n }\n return { numericValue: value, inferredType: \"NUMERIC\" };\n}\n\n/**\n * Emit a success signal using credentials from the environment\n * (GATEWAY_HOST / GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY) — the ergonomic\n * top-level entry point for the default `tracing.init()` path, mirroring the\n * Python SDK's `run.success(...)`. FAIL-SOFT end to end: a missing/invalid\n * environment or a transport failure warns and resolves, never throwing into\n * the caller. For isolated providers use the handle's bound client\n * (`handle.scores.success(...)`) instead so the signal lands in that project.\n */\nexport async function success(\n name: string,\n value: boolean | number = true,\n options: SuccessOptions = {},\n): Promise<void> {\n let client: ScoresClient;\n try {\n client = ScoresClient.fromEnv();\n } catch (error) {\n console.warn(`[gateway.scores] success '${name}' skipped`, error);\n return;\n }\n await client.success(name, value, options);\n}\n\n/** Lowercase convenience namespace, matching the `users` export. */\nexport const scores = {\n fromEnv: ScoresClient.fromEnv,\n success,\n};\n","/**\n * Agent build identity — \"the agent IS the manifest.\"\n *\n * There is no build file and no lockfile. As the agent constructs itself,\n * the SDK observes everything that defines a build: tools registered through\n * defineTool() (name, declared version, schema hash, effects, source\n * location), prompts registered through registerPrompt(), the code ref from\n * CI/env, and the SDK's own version. tracing.init({ agent, version })\n * assembles the canonical manifest, computes the content-addressed\n * buildHash, stamps it on every span, and auto-registers the build with\n * Gateway (idempotent on hash — every replica of the same code is one\n * build). Releases are label moves on the platform, never mutations here.\n *\n * v1 versioning is developer-declared: you bump `version` on the agent and\n * on tools; Gateway records schema/impl hashes as evidence alongside.\n */\nimport { createHash } from \"node:crypto\";\n\nexport type ToolEffects = \"read\" | \"write\" | \"irreversible\";\n\nexport interface ToolIdentity {\n name: string;\n version?: string;\n effects?: ToolEffects;\n schemaHash: string;\n description?: string;\n /** Source location of the defineTool call (\"src/tools/checkout.ts:42\"). */\n source?: string;\n}\n\n/** Any versioned artifact an agent is built from — tools, prompts, skills,\n * datasets, guardrails, configs… `content` hashes locally (off-platform);\n * `ref` pins a platform-hosted artifact (\"prompt/system@label:production\"). */\nexport interface ArtifactIdentity {\n kind: string;\n name: string;\n version?: string;\n contentHash?: string;\n ref?: string;\n source?: string;\n metadata?: Record<string, string>;\n}\n\nexport interface AgentBuildManifest {\n agentId: string;\n codeRef?: string;\n sdk: string;\n tools: ToolIdentity[];\n prompts: Record<string, string>;\n skills: Record<string, string>;\n artifacts: ArtifactIdentity[];\n}\n\n/** Deterministic JSON: object keys sorted recursively, arrays kept in order. */\nexport function canonicalJson(value: unknown): string {\n if (value === null || typeof value !== \"object\") {\n return JSON.stringify(value);\n }\n if (Array.isArray(value)) {\n return `[${value.map(canonicalJson).join(\",\")}]`;\n }\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n return `{${entries\n .map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`)\n .join(\",\")}}`;\n}\n\nexport function sha256(text: string): string {\n return `sha256:${createHash(\"sha256\").update(text).digest(\"hex\")}`;\n}\n\n// ── Registry (module-level; one agent process = one registry) ──────────────\n\nconst registeredTools = new Map<string, ToolIdentity>();\nconst registeredPrompts = new Map<string, string>();\nconst registeredSkills = new Map<string, string>();\nconst registeredArtifacts = new Map<string, ArtifactIdentity>();\n\n/** First app-code frame of the current stack (\"src/tools/checkout.ts:42\"). */\nfunction captureSource(): string | undefined {\n const stack = new Error().stack?.split(\"\\n\") ?? [];\n for (const line of stack.slice(1)) {\n // Skip the SDK's own frames (this module, packaged dist) and node internals\n // — NOT the whole install dir, or apps developed inside a monorepo next to\n // the SDK would never resolve a source.\n if (\n line.includes(\"build/index.ts\") ||\n line.includes(\"build/index.js\") ||\n line.includes(\"build/index.mjs\") ||\n line.includes(\"node_modules/@withgateway/\")\n ) {\n continue;\n }\n if (line.includes(\"node:internal\") || line.includes(\"(node:\")) continue;\n const match = /\\(?([^()\\s]+):(\\d+):\\d+\\)?$/.exec(line.trim());\n if (match) {\n const file = match[1].replace(/^file:\\/\\//, \"\");\n // Trim to a repo-relative-ish path for readability.\n const short = file.includes(\"/\") ? file.split(\"/\").slice(-4).join(\"/\") : file;\n return `${short}:${match[2]}`;\n }\n }\n return undefined;\n}\n\nexport interface DefineToolInput {\n name: string;\n /** Developer-declared tool version, e.g. \"2.1\" (v1: bumped manually). */\n version?: string;\n /** Side-effect class — feeds approval policies and gate severity. */\n effects?: ToolEffects;\n description?: string;\n /** JSON schema (or zod-serializable shape) of the tool's parameters. */\n schema?: unknown;\n /** Alias accepted for frameworks that call it inputSchema. */\n inputSchema?: unknown;\n}\n\n/**\n * Register a tool's identity and pass the definition through unchanged, so\n * it wraps ANY framework's tool shape:\n *\n * ```ts\n * const checkout = defineTool({\n * name: \"checkout\", version: \"2.1\", effects: \"write\",\n * schema, description, execute,\n * });\n * ```\n */\nexport function defineTool<T extends DefineToolInput>(tool: T): T {\n const schemaBasis = tool.schema ?? tool.inputSchema ?? null;\n const source = captureSource();\n const identity: ToolIdentity = {\n name: tool.name,\n ...(tool.version !== undefined ? { version: tool.version } : {}),\n ...(tool.effects !== undefined ? { effects: tool.effects } : {}),\n ...(tool.description !== undefined\n ? { description: tool.description.slice(0, 500) }\n : {}),\n schemaHash: sha256(\n canonicalJson({ schema: schemaBasis, description: tool.description ?? \"\" }),\n ),\n ...(source ? { source } : {}),\n };\n registeredTools.set(tool.name, identity);\n notifyRegistryChanged();\n return tool;\n}\n\n/**\n * Register a code-shipped prompt so it joins the build identity:\n * `const SYSTEM = registerPrompt(\"system\", \"You are…\")`. Returns the content\n * unchanged. Platform-served prompts don't need this — pin them by label.\n */\nexport interface RegisterArtifactOptions {\n /** Developer-declared version, e.g. \"1.2\" (v1: bumped manually). */\n version?: string;\n /** Local content — hashed into the identity (off-platform artifacts). */\n content?: string;\n /** Platform reference (on-platform artifacts): \"prompt/system@label:production\". */\n ref?: string;\n metadata?: Record<string, string>;\n}\n\n/**\n * Version ANY artifact the agent is built from — the generic primitive\n * behind registerPrompt/registerSkill. Works on- and off-platform:\n *\n * ```ts\n * registerArtifact(\"guardrail\", \"pii-filter\", { version: \"2.0\", content: RULES });\n * registerArtifact(\"prompt\", \"planner\", { ref: \"planner@label:production\" });\n * ```\n */\nexport function registerArtifact(\n kind: string,\n name: string,\n options: RegisterArtifactOptions = {},\n): ArtifactIdentity {\n const source = captureSource();\n const identity: ArtifactIdentity = {\n kind,\n name,\n ...(options.version !== undefined ? { version: options.version } : {}),\n ...(options.content !== undefined\n ? { contentHash: sha256(options.content) }\n : {}),\n ...(options.ref !== undefined ? { ref: options.ref } : {}),\n ...(source ? { source } : {}),\n ...(options.metadata ? { metadata: options.metadata } : {}),\n };\n registeredArtifacts.set(`${kind}:${name}`, identity);\n notifyRegistryChanged();\n return identity;\n}\n\nexport function registerPrompt(\n name: string,\n content: string,\n options: { version?: string } = {},\n): string {\n registeredPrompts.set(name, sha256(content));\n registerArtifact(\"prompt\", name, { ...options, content });\n return content;\n}\n\nexport function getRegisteredTools(): ToolIdentity[] {\n return [...registeredTools.values()].sort((a, b) =>\n a.name < b.name ? -1 : a.name > b.name ? 1 : 0,\n );\n}\n\n/**\n * Register a skill's identity — `registerSkill(\"triage\", \"1.0\")` — so skills\n * are versioned in the build like tools and prompts. The version string is\n * whatever you bump (or a content hash for file-based skills).\n */\nexport function registerSkill(\n name: string,\n version: string,\n options: { content?: string; ref?: string } = {},\n): void {\n registeredSkills.set(name, version);\n registerArtifact(\"skill\", name, { version, ...options });\n}\n\nexport function getRegisteredArtifacts(): ArtifactIdentity[] {\n return [...registeredArtifacts.values()].sort((a, b) =>\n `${a.kind}:${a.name}` < `${b.kind}:${b.name}` ? -1 : 1,\n );\n}\n\nexport function getRegisteredSkills(): Record<string, string> {\n return Object.fromEntries(\n [...registeredSkills.entries()].sort(([a], [b]) =>\n a < b ? -1 : a > b ? 1 : 0,\n ),\n );\n}\n\nexport function getRegisteredPrompts(): Record<string, string> {\n return Object.fromEntries(\n [...registeredPrompts.entries()].sort(([a], [b]) =>\n a < b ? -1 : a > b ? 1 : 0,\n ),\n );\n}\n\n/** Test hook. */\nexport function resetBuildRegistry(): void {\n registeredTools.clear();\n registeredPrompts.clear();\n registeredSkills.clear();\n registeredArtifacts.clear();\n activeBuilds.length = 0;\n if (reRegisterTimer) clearTimeout(reRegisterTimer);\n reRegisterTimer = null;\n}\n\n// ── Manifest assembly + registration ───────────────────────────────────────\n\nfunction sdkVersion(): string {\n try {\n // dist/build/index.js -> ../../package.json ; src/build -> same shape.\n /* eslint-disable-next-line @typescript-eslint/no-require-imports */\n const pkg = require(\"../../package.json\") as { version?: string };\n return `@withgateway/sdk@${pkg.version ?? \"unknown\"}`;\n } catch {\n return \"@withgateway/sdk\";\n }\n}\n\n/**\n * Git context most PaaS runtimes inject automatically (Vercel, Render,\n * Railway, Netlify, Heroku). On those hosts attribution is fully\n * zero-config — no GATEWAY_* or GITHUB_* env plumbing needed. Explicit\n * env vars always win; this only fills gaps.\n */\nexport function paasGitContext(): {\n provider: string;\n sha?: string;\n repo?: string;\n branch?: string;\n login?: string;\n} | null {\n const env = process.env;\n if (env.VERCEL_GIT_COMMIT_SHA) {\n // Only surface the repo when it's GitHub-shaped — enrichment is\n // GitHub-only; a GitLab/Bitbucket repo would just 404 over there.\n const isGithub = (env.VERCEL_GIT_PROVIDER ?? \"github\") === \"github\";\n return {\n provider: \"vercel\",\n sha: env.VERCEL_GIT_COMMIT_SHA,\n repo:\n isGithub && env.VERCEL_GIT_REPO_OWNER && env.VERCEL_GIT_REPO_SLUG\n ? `${env.VERCEL_GIT_REPO_OWNER}/${env.VERCEL_GIT_REPO_SLUG}`\n : undefined,\n branch: env.VERCEL_GIT_COMMIT_REF,\n login: env.VERCEL_GIT_COMMIT_AUTHOR_LOGIN,\n };\n }\n if (env.RENDER_GIT_COMMIT) {\n return {\n provider: \"render\",\n sha: env.RENDER_GIT_COMMIT,\n repo: env.RENDER_GIT_REPO_SLUG, // already \"owner/repo\"\n branch: env.RENDER_GIT_BRANCH,\n };\n }\n if (env.RAILWAY_GIT_COMMIT_SHA) {\n return {\n provider: \"railway\",\n sha: env.RAILWAY_GIT_COMMIT_SHA,\n repo:\n env.RAILWAY_GIT_REPO_OWNER && env.RAILWAY_GIT_REPO_NAME\n ? `${env.RAILWAY_GIT_REPO_OWNER}/${env.RAILWAY_GIT_REPO_NAME}`\n : undefined,\n branch: env.RAILWAY_GIT_BRANCH,\n login: env.RAILWAY_GIT_AUTHOR,\n };\n }\n if (env.NETLIFY && env.COMMIT_REF) {\n const repoMatch = /github\\.com[/:]([^/]+\\/[^/.]+)/.exec(\n env.REPOSITORY_URL ?? \"\",\n );\n return {\n provider: \"netlify\",\n sha: env.COMMIT_REF,\n repo: repoMatch?.[1],\n branch: env.BRANCH,\n };\n }\n // Heroku (dyno metadata) and common bare conventions: sha only — the\n // platform resolves the repo server-side via the GitHub connection.\n const bareSha =\n env.HEROKU_SLUG_COMMIT ?? env.SOURCE_VERSION ?? env.GIT_COMMIT ?? env.COMMIT_SHA;\n if (bareSha) {\n return {\n provider: env.HEROKU_SLUG_COMMIT || env.SOURCE_VERSION ? \"heroku\" : \"generic\",\n sha: bareSha,\n };\n }\n return null;\n}\n\nfunction codeRef(): string | undefined {\n const paas = paasGitContext();\n const sha =\n process.env.GATEWAY_COMMIT ??\n process.env.GITHUB_SHA ??\n process.env.CI_COMMIT_SHA ?? // GitLab\n process.env.CIRCLE_SHA1 ??\n paas?.sha;\n if (!sha) return undefined;\n const repo =\n process.env.GITHUB_REPOSITORY ?? process.env.CI_PROJECT_PATH ?? paas?.repo;\n return repo ? `git:${repo}@${sha}` : `git:${sha}`;\n}\n\nexport function assembleManifest(agentId: string): AgentBuildManifest {\n return {\n agentId,\n ...(codeRef() ? { codeRef: codeRef() } : {}),\n sdk: sdkVersion(),\n tools: getRegisteredTools(),\n prompts: getRegisteredPrompts(),\n skills: getRegisteredSkills(),\n artifacts: getRegisteredArtifacts(),\n };\n}\n\nexport function computeBuildHash(manifest: AgentBuildManifest): string {\n // Source locations are display metadata, not identity — the same tool\n // declared on a different line (or after a refactor that moved it) is the\n // same tool. They stay in the manifest payload for the platform to show.\n const identity = {\n ...manifest,\n tools: manifest.tools.map(({ source: _source, ...tool }) => tool),\n artifacts: manifest.artifacts.map(\n ({ source: _source, ...artifact }) => artifact,\n ),\n };\n return sha256(canonicalJson(identity));\n}\n\nexport function attributionFromEnv(): Record<string, unknown> {\n const attribution: Record<string, unknown> = { source: \"runtime\" };\n if (process.env.GITHUB_ACTIONS) attribution.source = \"ci\";\n if (process.env.GITHUB_ACTOR) attribution.githubLogin = process.env.GITHUB_ACTOR;\n const sha = process.env.GATEWAY_COMMIT ?? process.env.GITHUB_SHA;\n if (sha) attribution.commitSha = sha;\n if (process.env.GITHUB_REPOSITORY) attribution.repo = process.env.GITHUB_REPOSITORY;\n const branch = process.env.GITHUB_HEAD_REF ?? process.env.GITHUB_REF_NAME;\n if (branch) attribution.branch = branch;\n // PaaS-injected git context (Vercel/Render/Railway/Netlify/Heroku) fills\n // any gaps — zero-config attribution on those hosts. Explicit env wins.\n const paas = paasGitContext();\n if (paas) {\n if (attribution.source === \"runtime\") attribution.source = `paas:${paas.provider}`;\n if (!attribution.commitSha && paas.sha) attribution.commitSha = paas.sha;\n if (!attribution.repo && paas.repo) attribution.repo = paas.repo;\n if (!attribution.branch && paas.branch) attribution.branch = paas.branch;\n if (!attribution.githubLogin && paas.login) attribution.githubLogin = paas.login;\n }\n const ref = process.env.GITHUB_REF ?? \"\";\n const prMatch = /refs\\/pull\\/(\\d+)\\//.exec(ref);\n if (prMatch) attribution.prNumber = Number(prMatch[1]);\n // PR title/body are NOT in the default Actions env — workflows pass them\n // through in two lines:\n // env:\n // GATEWAY_PR_TITLE: ${{ github.event.pull_request.title }}\n // GATEWAY_PR_BODY: ${{ github.event.pull_request.body }}\n if (process.env.GATEWAY_PR_TITLE) {\n attribution.prTitle = process.env.GATEWAY_PR_TITLE.slice(0, 300);\n }\n if (process.env.GATEWAY_PR_BODY) {\n attribution.prDescription = process.env.GATEWAY_PR_BODY.slice(0, 2000);\n }\n if (\n attribution.repo &&\n attribution.prNumber &&\n !(\"prUrl\" in attribution)\n ) {\n attribution.prUrl = `https://github.com/${String(attribution.repo)}/pull/${String(attribution.prNumber)}`;\n }\n return attribution;\n}\n\n// ── Late registration ──────────────────────────────────────────────────────\n// Many agents build their tool maps lazily (per request), AFTER init. Any\n// defineTool/registerPrompt/registerSkill call re-assembles the manifest for\n// every active agent build (debounced) and re-registers when the hash moved.\n// Content-addressed and idempotent: the registry simply gains the fullest\n// manifest; traces keep the hash stamped at init (documented behavior).\n\nexport interface ActiveBuildContext {\n host: string;\n publicKey: string;\n secretKey: string;\n agentId: string;\n version?: string;\n lastRegisteredHash?: string;\n}\n\nconst activeBuilds: ActiveBuildContext[] = [];\nlet reRegisterTimer: ReturnType<typeof setTimeout> | null = null;\nconst RE_REGISTER_DEBOUNCE_MS = 3000;\n\nexport function trackActiveBuild(context: ActiveBuildContext): void {\n activeBuilds.push(context);\n}\n\nfunction notifyRegistryChanged(): void {\n if (activeBuilds.length === 0) return;\n if (reRegisterTimer) clearTimeout(reRegisterTimer);\n reRegisterTimer = setTimeout(() => {\n reRegisterTimer = null;\n for (const context of activeBuilds) {\n const manifest = assembleManifest(context.agentId);\n const buildHash = computeBuildHash(manifest);\n if (buildHash === context.lastRegisteredHash) continue;\n context.lastRegisteredHash = buildHash;\n void registerBuild({ ...context, manifest, buildHash }).catch(() => {\n // fail-soft; a later change retries via the next notify\n context.lastRegisteredHash = undefined;\n });\n }\n }, RE_REGISTER_DEBOUNCE_MS);\n // Never hold the process open just to re-register.\n if (typeof reRegisterTimer === \"object\" && \"unref\" in reRegisterTimer) {\n (reRegisterTimer as { unref(): void }).unref();\n }\n}\n\n/**\n * Fire-and-forget build registration. Idempotent on buildHash server-side;\n * failures are logged once and never affect the agent.\n */\nexport async function registerBuild(params: {\n host: string;\n publicKey: string;\n secretKey: string;\n agentId: string;\n version?: string;\n manifest: AgentBuildManifest;\n buildHash: string;\n}): Promise<void> {\n const auth = Buffer.from(`${params.publicKey}:${params.secretKey}`).toString(\n \"base64\",\n );\n const response = await fetch(\n `${params.host.replace(/\\/$/, \"\")}/api/public/agent-builds`,\n {\n method: \"POST\",\n headers: {\n Authorization: `Basic ${auth}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n agentId: params.agentId,\n buildHash: params.buildHash,\n ...(params.version ? { semanticVer: params.version } : {}),\n manifest: params.manifest,\n attribution: attributionFromEnv(),\n }),\n signal: AbortSignal.timeout(15_000),\n },\n );\n if (!response.ok) {\n throw new Error(\n `build registration failed (${response.status}): ${(await response.text()).slice(0, 300)}`,\n );\n }\n}\n","/**\n * Initialization and lifecycle management for GatewaySDK tracing.\n *\n * This module provides the core init(), shutdown(), and flush() functions\n * for managing the OpenTelemetry TracerProvider lifecycle, plus\n * initIsolated() for creating additional self-contained providers (e.g. one\n * process exporting different agents to different Gateway projects).\n *\n * Mirrors the Python SDK's tracing.init() for a consistent developer experience.\n */\n\nimport type { Tracer } from \"@opentelemetry/api\";\nimport type { TracingConfig, TracingState } from \"./types\";\nimport { IdentitySpanProcessor } from \"./identity\";\nimport { ScoresClient } from \"../scores/index\";\nimport {\n assembleManifest,\n computeBuildHash,\n registerBuild,\n trackActiveBuild,\n type AgentBuildManifest,\n} from \"../build/index\";\n\n// Environment variable names. (A legacy BRIDGELAYER_* prefix predated the\n// rebrand but was never in any published release, so only GATEWAY_* exists.)\nconst ENV_VARS = {\n HOST: \"GATEWAY_HOST\",\n PUBLIC_KEY: \"GATEWAY_PUBLIC_KEY\",\n SECRET_KEY: \"GATEWAY_SECRET_KEY\",\n ENDPOINT: \"GATEWAY_OTLP_ENDPOINT\",\n} as const;\n\nconst DEFAULT_OTLP_PATH = \"/api/public/otel/v1/traces\";\n\n// Module-level state\nconst state: TracingState & { debug?: boolean } = {\n initialized: false,\n provider: null,\n};\n\nfunction getEnv(key: string): string | undefined {\n const value = process.env[key];\n return value ? value : undefined;\n}\n\nfunction log(message: string, ...args: unknown[]): void {\n if (state.debug) {\n console.log(`[gatewaysdk.tracing] ${message}`, ...args);\n }\n}\n\nfunction warn(message: string, ...args: unknown[]): void {\n console.warn(`[gatewaysdk.tracing] ${message}`, ...args);\n}\n\ntype LogFn = (message: string, ...args: unknown[]) => void;\n\n/**\n * Handle to an isolated tracing provider created by initIsolated().\n * Spans started from `tracer` export to that provider's Gateway project;\n * the global tracer (from init()) is untouched.\n */\nexport interface TracingHandle {\n tracer: Tracer;\n /**\n * Scores/success-signal client bound to THIS provider's project keys. Emit\n * ROI success signals into the same project the handle's spans export to —\n * `handle.scores.success(\"resolved_ticket\", true, { agentId, sessionId })` —\n * without threading credentials through your own code. Fail-soft, like the\n * rest of the client.\n */\n scores: ScoresClient;\n /** Force-flush pending spans for this provider only. */\n flush(): Promise<void>;\n /** Flush and shut down this provider only. */\n shutdown(): Promise<void>;\n}\n\n/**\n * Build a fully-configured NodeTracerProvider from config + env. Shared by\n * init() (which registers it globally) and initIsolated() (which does not).\n */\n/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-require-imports */\nfunction buildProvider(config: TracingConfig, logFn: LogFn): any {\n // Resolve configuration from params or environment\n const host = config.host ?? getEnv(ENV_VARS.HOST);\n const publicKey = config.publicKey ?? getEnv(ENV_VARS.PUBLIC_KEY);\n const secretKey = config.secretKey ?? getEnv(ENV_VARS.SECRET_KEY);\n const endpoint =\n config.endpoint ??\n getEnv(ENV_VARS.ENDPOINT) ??\n (host ? `${host.replace(/\\/$/, \"\")}${DEFAULT_OTLP_PATH}` : undefined);\n\n // Validate required configuration\n const missing: string[] = [];\n if (!host) missing.push(\"host (or GATEWAY_HOST env var)\");\n if (!publicKey) missing.push(\"publicKey (or GATEWAY_PUBLIC_KEY env var)\");\n if (!secretKey) missing.push(\"secretKey (or GATEWAY_SECRET_KEY env var)\");\n\n if (missing.length > 0) {\n throw new Error(\n `Missing required Gateway configuration: ${missing.join(\", \")}. ` +\n \"Provide these values via init() parameters or environment variables.\",\n );\n }\n\n // Dynamically import OpenTelemetry modules (they're peer dependencies)\n // Using 'any' to avoid version conflicts between OTel packages\n let NodeTracerProvider: any;\n let BatchSpanProcessor: any;\n let OTLPTraceExporter: any;\n let createResource: (attrs: Record<string, string>) => any;\n let ATTR_SERVICE_NAME: string;\n\n try {\n const traceNode = require(\"@opentelemetry/sdk-trace-node\");\n const traceBase = require(\"@opentelemetry/sdk-trace-base\");\n const otlpHttp = require(\"@opentelemetry/exporter-trace-otlp-http\");\n const resources = require(\"@opentelemetry/resources\");\n\n NodeTracerProvider = traceNode.NodeTracerProvider;\n BatchSpanProcessor = traceBase.BatchSpanProcessor;\n OTLPTraceExporter = otlpHttp.OTLPTraceExporter;\n\n // Handle both old (Resource class) and new (resourceFromAttributes function) APIs\n if (resources.Resource) {\n createResource = (attrs) => new resources.Resource(attrs);\n } else if (resources.resourceFromAttributes) {\n createResource = resources.resourceFromAttributes;\n } else {\n createResource = () => resources.defaultResource();\n }\n\n // Try semantic conventions, fall back to string literal\n try {\n const semconv = require(\"@opentelemetry/semantic-conventions\");\n ATTR_SERVICE_NAME =\n semconv.ATTR_SERVICE_NAME ?? semconv.SEMRESATTRS_SERVICE_NAME ?? \"service.name\";\n } catch {\n ATTR_SERVICE_NAME = \"service.name\";\n }\n } catch {\n throw new Error(\n \"OpenTelemetry packages not found. Install them with:\\n\" +\n \"npm install @opentelemetry/sdk-trace-node @opentelemetry/sdk-trace-base \" +\n \"@opentelemetry/exporter-trace-otlp-http @opentelemetry/resources\",\n );\n }\n\n // Build resource attributes\n const resourceAttrs: Record<string, string> = {\n [ATTR_SERVICE_NAME]: config.serviceName ?? \"gatewaysdk-tracing\",\n };\n if (config.environment) {\n resourceAttrs[\"gateway.environment\"] = config.environment;\n }\n if (config.version) {\n resourceAttrs[\"gateway.version\"] = config.version;\n }\n\n // Agent build identity — \"the agent IS the manifest\": assemble from\n // everything registered before init, stamp the content-addressed hash on\n // every span. (Tools defined AFTER init don't join the identity — define\n // them first.)\n let buildInfo: { manifest: AgentBuildManifest; buildHash: string } | null =\n null;\n if (config.agent) {\n const manifest = assembleManifest(config.agent);\n const buildHash = computeBuildHash(manifest);\n buildInfo = { manifest, buildHash };\n resourceAttrs[\"gateway.agent.id\"] = config.agent;\n resourceAttrs[\"gateway.build.hash\"] = buildHash;\n if (config.version) {\n resourceAttrs[\"gateway.agent.version\"] = config.version;\n }\n logFn(\n \"Agent build identity: %s @ %s (%d tools, %d prompts)\",\n config.agent,\n buildHash.slice(0, 15),\n manifest.tools.length,\n Object.keys(manifest.prompts).length,\n );\n }\n\n // Security check: block insecure HTTP (except localhost/127.0.0.1)\n let isLocalhost = false;\n if (endpoint) {\n try {\n const parsed = new URL(endpoint);\n isLocalhost =\n parsed.hostname === \"localhost\" || parsed.hostname === \"127.0.0.1\";\n } catch {\n isLocalhost = false;\n }\n }\n if (endpoint && !endpoint.startsWith(\"https://\") && !isLocalhost) {\n throw new Error(\n `Refusing to send credentials over insecure HTTP to ${endpoint}. ` +\n \"Use HTTPS or localhost for development.\",\n );\n }\n\n // Construct Basic Auth header\n const credentials = `${publicKey}:${secretKey}`;\n const encoded = Buffer.from(credentials).toString(\"base64\");\n const authHeader = `Basic ${encoded}`;\n\n // Create OTLP exporter\n const exporter = new OTLPTraceExporter({\n url: endpoint,\n headers: {\n Authorization: authHeader,\n },\n });\n\n logFn(\"Configured Gateway exporter: endpoint=%s\", endpoint);\n\n // Build span processors — custom processors go first (before the BatchSpanProcessor)\n const spanProcessors: any[] = [];\n\n if (config.customSpanProcessors) {\n for (const sp of config.customSpanProcessors) {\n spanProcessors.push(sp);\n logFn(\n \"Added custom span processor: %s\",\n (sp as { constructor?: { name?: string } }).constructor?.name ??\n \"unknown\",\n );\n }\n }\n\n // Stamp the ambient end-user identity (identify() / GATEWAY_USER_ID) on\n // every span at start — mirrors the Python SDK's TracingContextSpanProcessor.\n spanProcessors.push(new IdentitySpanProcessor());\n\n // Add BatchSpanProcessor with exporter\n const batchConfig: Record<string, number> = {};\n if (config.batch?.maxQueueSize) {\n batchConfig.maxQueueSize = config.batch.maxQueueSize;\n }\n if (config.batch?.scheduledDelayMillis) {\n batchConfig.scheduledDelayMillis = config.batch.scheduledDelayMillis;\n }\n if (config.batch?.maxExportBatchSize) {\n batchConfig.maxExportBatchSize = config.batch.maxExportBatchSize;\n }\n\n spanProcessors.push(new BatchSpanProcessor(exporter, batchConfig));\n\n // Create provider — detect v1 vs v2 API via runtime feature check.\n // v1 has addSpanProcessor(); v2 removed it and requires spanProcessors in constructor.\n let provider: any = new NodeTracerProvider({\n resource: createResource(resourceAttrs),\n });\n\n if (typeof provider.addSpanProcessor === \"function\") {\n // v1 API: register each processor individually\n for (const sp of spanProcessors) {\n provider.addSpanProcessor(sp);\n }\n } else {\n // v2 API: must pass spanProcessors in constructor — recreate\n provider = new NodeTracerProvider({\n resource: createResource(resourceAttrs),\n spanProcessors,\n });\n }\n\n return {\n provider,\n buildInfo,\n connection: { host: host!, publicKey: publicKey!, secretKey: secretKey! },\n };\n}\n/* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/no-require-imports */\n\n/** Fire-and-forget build registration for a provider built with `agent`. */\nfunction scheduleBuildRegistration(\n config: TracingConfig,\n built: ReturnType<typeof buildProvider>,\n): void {\n if (!config.agent || !built.buildInfo || config.registerBuild === false) {\n return;\n }\n const { manifest, buildHash } = built.buildInfo;\n // Track so tools/prompts/skills registered AFTER init re-register the\n // fullest manifest (debounced, content-addressed, idempotent).\n trackActiveBuild({\n host: built.connection.host,\n publicKey: built.connection.publicKey,\n secretKey: built.connection.secretKey,\n agentId: config.agent,\n version: config.version,\n lastRegisteredHash: buildHash,\n });\n void registerBuild({\n host: built.connection.host,\n publicKey: built.connection.publicKey,\n secretKey: built.connection.secretKey,\n agentId: config.agent,\n version: config.version,\n manifest,\n buildHash,\n }).catch((err: unknown) => {\n warn(\"Build registration failed (agent keeps running):\", err);\n });\n}\n\n/**\n * Initialize GatewaySDK tracing with automatic OpenTelemetry configuration.\n *\n * This function configures OpenTelemetry with a connection to Gateway\n * and sets up the ExperimentSpanProcessor for automatic experiment tagging.\n *\n * @example\n * ```typescript\n * import { tracing } from \"@withgateway/sdk\";\n *\n * // Using environment variables (GATEWAY_HOST, GATEWAY_PUBLIC_KEY, GATEWAY_SECRET_KEY)\n * tracing.init();\n *\n * // Or with explicit configuration\n * tracing.init({\n * host: \"https://app.gateway.dev\",\n * publicKey: \"pk-lf-...\",\n * secretKey: \"sk-lf-...\",\n * serviceName: \"my-agent\",\n * environment: \"production\",\n * });\n * ```\n */\nexport function init(config: TracingConfig = {}): void {\n if (state.initialized) {\n log(\"Tracing already initialized. Call shutdown() first to reinitialize.\");\n return;\n }\n\n // Store debug flag in state for log() function\n state.debug = config.debug ?? false;\n\n const built = buildProvider(config, log);\n const provider = built.provider;\n provider.register();\n scheduleBuildRegistration(config, built);\n\n state.provider = provider;\n state.initialized = true;\n\n log(\n \"GatewaySDK tracing initialized successfully (service=%s)\",\n config.serviceName ?? \"gatewaysdk-tracing\",\n );\n}\n\n/**\n * Create an ISOLATED tracing provider that is NOT registered globally.\n *\n * Use this when one process must export different work to different Gateway\n * projects (e.g. a server hosting several agents, each with its own project\n * keys), or when the process already has its own global OpenTelemetry\n * provider that must not be replaced.\n *\n * Spans only reach the isolated provider when started from its `tracer` —\n * pass it explicitly to observe()/observeClaude() via their `tracer` option,\n * or to a framework's telemetry hook (e.g. the Vercel AI SDK's\n * `experimental_telemetry.tracer`). Context propagation still works across\n * providers, so nesting behaves exactly as with init().\n *\n * Can be called any number of times; each handle has its own exporter,\n * batch queue, and lifecycle.\n *\n * @example\n * ```typescript\n * import { tracing } from \"@withgateway/sdk\";\n *\n * const support = tracing.initIsolated({\n * host: \"https://app.gateway.dev\",\n * publicKey: \"pk-lf-support...\",\n * secretKey: \"sk-lf-support...\",\n * serviceName: \"support-agent\",\n * });\n *\n * await tracing.observe(\"support.run\", run, { tracer: support.tracer });\n * await support.flush();\n * ```\n */\nexport function initIsolated(config: TracingConfig = {}): TracingHandle {\n const debugLog: LogFn = config.debug\n ? (message, ...args) =>\n console.log(`[gatewaysdk.tracing:isolated] ${message}`, ...args)\n : () => {};\n\n const built = buildProvider(config, debugLog);\n const provider = built.provider;\n scheduleBuildRegistration(config, built);\n const tracer = provider.getTracer(\"@withgateway/sdk\") as Tracer;\n\n // Scores client bound to the SAME project keys the exporter uses, so a\n // handle can emit success signals into its own project with no extra wiring.\n const scores = new ScoresClient({\n host: built.connection.host,\n publicKey: built.connection.publicKey,\n secretKey: built.connection.secretKey,\n debug: config.debug ?? false,\n });\n\n debugLog(\n \"Isolated tracing provider created (service=%s)\",\n config.serviceName ?? \"gatewaysdk-tracing\",\n );\n\n return {\n tracer,\n scores,\n async flush() {\n try {\n await (provider as { forceFlush: () => Promise<void> }).forceFlush();\n } catch (e) {\n warn(\"Error during isolated flush:\", e);\n }\n },\n async shutdown() {\n try {\n await (provider as { shutdown: () => Promise<void> }).shutdown();\n } catch (e) {\n warn(\"Error during isolated shutdown:\", e);\n }\n },\n };\n}\n\n/**\n * Force flush all pending spans without shutting down.\n *\n * Useful for ensuring spans are exported at specific points\n * (e.g., after completing a batch of work) without ending the tracing session.\n *\n * @returns Promise that resolves when flush completes\n */\nexport async function flush(): Promise<void> {\n if (!state.provider) {\n log(\"No provider to flush\");\n return;\n }\n\n try {\n await (state.provider as { forceFlush: () => Promise<void> }).forceFlush();\n log(\"Flush completed successfully\");\n } catch (e) {\n warn(\"Error during flush:\", e);\n }\n}\n\n/**\n * Force flush all pending spans and shutdown the tracer provider.\n *\n * This function should be called before process exit to ensure all spans\n * are exported. It is safe to call multiple times.\n *\n * @example\n * ```typescript\n * import { tracing } from \"@withgateway/sdk\";\n *\n * tracing.init();\n *\n * // On shutdown\n * process.on(\"SIGTERM\", async () => {\n * await tracing.shutdown();\n * process.exit(0);\n * });\n * ```\n */\nexport async function shutdown(): Promise<void> {\n if (!state.initialized || !state.provider) {\n log(\"Tracing not initialized, nothing to shutdown\");\n return;\n }\n\n try {\n await (state.provider as { shutdown: () => Promise<void> }).shutdown();\n log(\"Shutdown complete\");\n } catch (e) {\n warn(\"Error during shutdown:\", e);\n }\n\n state.provider = null;\n state.initialized = false;\n}\n\n/**\n * Check if tracing has been initialized.\n */\nexport function isInitialized(): boolean {\n return state.initialized;\n}\n\n/**\n * Check if Gateway is configured via environment variables.\n */\nexport function isGatewayConfigured(): boolean {\n const host = getEnv(ENV_VARS.HOST);\n const publicKey = getEnv(ENV_VARS.PUBLIC_KEY);\n const secretKey = getEnv(ENV_VARS.SECRET_KEY);\n return !!(host && publicKey && secretKey);\n}\n","/**\n * observe() — group a unit of work (an agent run, a tool call) into a single\n * span so nested LLM/tool spans attach to it and the whole thing is one trace.\n *\n * Mirrors Langfuse's `observe()` / `startActiveObservation()`. This is what an\n * app uses to define a trace boundary when it drives a raw client loop (which\n * has no framework root span of its own): the callback runs inside the span's\n * OpenTelemetry context, so any auto-instrumented calls (see observeOpenAI) and\n * any nested observe() calls become children of it.\n *\n * The span carries OpenInference attributes (openinference.span.kind, input.value,\n * output.value), and Gateway maps a root span's input.value/output.value to the\n * trace-level input/output — so the trace shows the user input and final output.\n */\nimport { trace, context, SpanStatusCode } from \"@opentelemetry/api\";\nimport type { Tracer } from \"@opentelemetry/api\";\n\nexport type ObservationKind = \"AGENT\" | \"CHAIN\" | \"TOOL\" | \"LLM\" | \"RETRIEVER\";\n\nexport interface ObserveOptions {\n /** Recorded as input.value on the span (JSON-stringified if not a string). */\n input?: unknown;\n /** OpenInference span kind. Defaults to \"AGENT\" for the outer run. */\n kind?: ObservationKind;\n /**\n * When true (default), the callback's return value is recorded as\n * output.value. Set false if the return value is large/uninteresting.\n */\n captureOutput?: boolean;\n /**\n * Tracer to start the span from. Defaults to the GLOBAL tracer (set up by\n * tracing.init()). Pass an initIsolated() handle's tracer to route this\n * observation to that handle's Gateway project instead.\n */\n tracer?: Tracer;\n /**\n * Extra attributes for the span — e.g. gateway.session.id /\n * gateway.user.id to group runs into a session and attribute them to a user.\n */\n attributes?: Record<string, string>;\n}\n\nfunction asAttr(value: unknown): string {\n return typeof value === \"string\" ? value : JSON.stringify(value);\n}\n\n/**\n * Run `fn` inside a span named `name`. Anything traced inside (auto-instrumented\n * client calls, nested observe() calls) nests under it, forming one trace.\n *\n * @example\n * ```ts\n * const result = await observe(\"my-agent.run\", async () => {\n * // client.chat.completions.create(...) here becomes a child GENERATION\n * return finalText;\n * }, { input: prompt });\n * ```\n */\nexport async function observe<T>(\n name: string,\n fn: () => Promise<T>,\n options: ObserveOptions = {},\n): Promise<T> {\n const tracer = options.tracer ?? trace.getTracer(\"@withgateway/sdk\");\n const span = tracer.startSpan(name, {\n attributes: {\n \"openinference.span.kind\": options.kind ?? \"AGENT\",\n ...(options.input !== undefined\n ? { \"input.value\": asAttr(options.input) }\n : {}),\n ...(options.attributes ?? {}),\n },\n });\n\n try {\n const result = await context.with(\n trace.setSpan(context.active(), span),\n fn,\n );\n if (options.captureOutput !== false && result !== undefined) {\n span.setAttribute(\"output.value\", asAttr(result));\n }\n span.setStatus({ code: SpanStatusCode.OK });\n return result;\n } catch (error) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: error instanceof Error ? error.message : String(error),\n });\n throw error;\n } finally {\n span.end();\n }\n}\n","/**\n * Client wrappers that turn an SDK's calls into spans on the Gateway provider.\n *\n * Node ESM can't retroactively patch a module the app already imported, so — as\n * Langfuse does with `observeOpenAI` — the app hands us the client and we\n * instrument it explicitly. One SDK call, no OpenTelemetry in the app.\n *\n * The OpenInference instrumentations are bundled optional deps of this package;\n * we load them with require() (the ESM build injects a real createRequire).\n */\n/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-require-imports */\n\nfunction warn(message: string, ...args: unknown[]): void {\n console.warn(`[gatewaysdk.tracing] ${message}`, ...args);\n}\n\n/**\n * Instrument an OpenAI client so its requests become GENERATION spans on the\n * Gateway provider. Returns the same client (its class prototype is patched, so\n * this and every other instance of that client are traced).\n *\n * @example\n * ```ts\n * import OpenAI from \"openai\";\n * import { init, observeOpenAI } from \"@withgateway/sdk/tracing\";\n * init();\n * const client = observeOpenAI(new OpenAI());\n * ```\n */\nexport function observeOpenAI<T extends object>(client: T): T {\n try {\n const {\n OpenAIInstrumentation,\n } = require(\"@arizeai/openinference-instrumentation-openai\");\n // OpenInference patches `module.OpenAI.Chat.Completions.prototype`, so it\n // needs an object shaped like the openai module. Reconstruct it from the\n // instance's class (client.constructor === the OpenAI class).\n const OpenAIClass = (client as { constructor: unknown }).constructor;\n new OpenAIInstrumentation().manuallyInstrument({ OpenAI: OpenAIClass });\n } catch (error) {\n warn(\n \"observeOpenAI: could not load @arizeai/openinference-instrumentation-openai — OpenAI calls will not be traced.\",\n error,\n );\n }\n return client;\n}\n\n/**\n * Instrument an Anthropic client so its requests become GENERATION spans.\n *\n * @example\n * ```ts\n * import Anthropic from \"@anthropic-ai/sdk\";\n * import { init, observeAnthropic } from \"@withgateway/sdk/tracing\";\n * init();\n * const client = observeAnthropic(new Anthropic());\n * ```\n */\nexport function observeAnthropic<T extends object>(client: T): T {\n try {\n const {\n AnthropicInstrumentation,\n } = require(\"@arizeai/openinference-instrumentation-anthropic\");\n // The instrumentor patches `module.Messages.prototype.create`, so it wants\n // an object whose `Messages` is the Anthropic client's Messages class (a\n // static on the class). `client.messages` resolves `create` through that\n // prototype, so patching it traces this client and every other instance.\n const AnthropicClass = (client as { constructor: { Messages?: unknown } })\n .constructor;\n new AnthropicInstrumentation().manuallyInstrument({\n Messages: AnthropicClass.Messages,\n });\n } catch (error) {\n warn(\n \"observeAnthropic: could not load @arizeai/openinference-instrumentation-anthropic — Anthropic calls will not be traced.\",\n error,\n );\n }\n return client;\n}\n","/**\n * observeClaude() — trace a Claude Agent SDK run.\n *\n * The Claude Agent SDK runs the agent in a separate `claude` CLI subprocess, so\n * there's nothing in-process to patch. What the app has is the message stream it\n * iterates. Wrap that stream with observeClaude() and it yields the same\n * messages unchanged while emitting spans on the Gateway provider.\n *\n * Default (one trace per run):\n *\n * AGENT (root)\n * ├─ GENERATION per assistant turn (with per-turn token usage)\n * └─ TOOL per tool call (input from tool_use, output from the\n * matching tool_result, matched by id)\n *\n * With `perTurn: true` (one trace PER ASSISTANT TURN — long agent runs read as\n * a session of turn traces, the way a chat thread does):\n *\n * AGENT \"<name> · turn N\" (detached root; session/user attributes on every turn)\n * ├─ GENERATION (that turn's usage + text)\n * └─ TOOL per tool call in the turn\n *\n * The TS equivalent of the Python SDK's claude-agent-sdk instrumentor.\n *\n * @example\n * ```ts\n * const stream = query({ prompt, options });\n * for await (const message of observeClaude(stream, { name, input: prompt })) {\n * // ...consume messages as usual\n * }\n * ```\n */\nimport {\n trace,\n context,\n SpanStatusCode,\n type Span,\n type Context,\n type Tracer,\n} from \"@opentelemetry/api\";\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nexport interface ObserveClaudeOptions {\n /** Root span name (becomes the trace name; per-turn mode appends `· turn N`). */\n name: string;\n /** Recorded as input.value on the root span → trace-level input. */\n input?: string;\n /** Model label for the generation spans. */\n model?: string;\n /**\n * Tracer to start spans from. Defaults to the GLOBAL tracer (set up by\n * tracing.init()). Pass an initIsolated() handle's tracer to route this\n * run to that handle's Gateway project instead.\n */\n tracer?: Tracer;\n /**\n * Extra attributes for the root span(s) — e.g. gateway.session.id /\n * gateway.user.id to group runs into a session and attribute them to a user.\n * In per-turn mode these ride EVERY turn root, so each turn trace maps to\n * the session.\n */\n attributes?: Record<string, string>;\n /**\n * Emit one TRACE PER ASSISTANT TURN instead of a single trace for the whole\n * run. Each turn's trace carries that turn's generation and tool calls; the\n * turn's input is the run input (turn 1) or the tool results that fed it\n * (later turns). Turn roots are detached (`root: true`), so they never nest\n * under ambient spans. Combine with `attributes.gateway.session.id` to read\n * a whole run as a session of turns.\n */\n perTurn?: boolean;\n}\n\n/** Strip the `mcp__<server>__` prefix so tool names read cleanly. */\nfunction cleanToolName(name: string): string {\n return name.replace(/^mcp__[^_]+__/, \"\");\n}\n\nfunction toolResultText(content: unknown): string {\n if (typeof content === \"string\") return content;\n if (Array.isArray(content))\n return content\n .map((b) =>\n b && typeof b === \"object\" && \"text\" in b\n ? String((b as { text: unknown }).text)\n : JSON.stringify(b),\n )\n .join(\"\");\n return JSON.stringify(content ?? \"\");\n}\n\nconst TURN_INPUT_MAX = 4000;\n\nexport async function* observeClaude(\n stream: AsyncIterable<any>,\n options: ObserveClaudeOptions,\n): AsyncGenerator<any> {\n const tracer = options.tracer ?? trace.getTracer(\"@withgateway/sdk\");\n const model = options.model ?? \"claude\";\n const openTools = new Map<string, Span>();\n\n // Single-trace mode: one root for the whole run.\n let root: Span | null = null;\n let rootCtx: Context | null = null;\n if (!options.perTurn) {\n root = tracer.startSpan(options.name, {\n attributes: {\n \"openinference.span.kind\": \"AGENT\",\n ...(options.input !== undefined\n ? { \"input.value\": options.input }\n : {}),\n ...(options.attributes ?? {}),\n },\n });\n rootCtx = trace.setSpan(context.active(), root);\n }\n\n // Per-turn mode: the current turn's root, rotated on each assistant message.\n let turnRoot: Span | null = null;\n let turnCtx: Context | null = null;\n let turnIndex = 0;\n let turnText = \"\";\n // What fed the CURRENT turn: the run input for turn 1, then the tool results\n // produced since the previous assistant message.\n let pendingTurnInput = options.input ?? \"\";\n\n let finalText = \"\";\n\n const endTurn = () => {\n if (!turnRoot) return;\n if (turnText) turnRoot.setAttribute(\"output.value\", turnText);\n turnRoot.setStatus({ code: SpanStatusCode.OK });\n turnRoot.end();\n turnRoot = null;\n turnCtx = null;\n };\n\n try {\n for await (const message of stream) {\n if (message?.type === \"assistant\") {\n if (options.perTurn) {\n // A new assistant message starts a new turn: any tools still open\n // belong to the previous turn — settle them, then rotate the root.\n for (const span of openTools.values()) span.end();\n openTools.clear();\n endTurn();\n turnIndex += 1;\n turnText = \"\";\n turnRoot = tracer.startSpan(`${options.name} · turn ${turnIndex}`, {\n root: true,\n attributes: {\n \"openinference.span.kind\": \"AGENT\",\n ...(pendingTurnInput\n ? { \"input.value\": pendingTurnInput.slice(0, TURN_INPUT_MAX) }\n : {}),\n ...(options.attributes ?? {}),\n },\n });\n turnCtx = trace.setSpan(context.active(), turnRoot);\n pendingTurnInput = \"\";\n }\n const childCtx = (options.perTurn ? turnCtx : rootCtx)!;\n\n let text = \"\";\n const toolUses: Array<{ id: string; name: string; input: unknown }> =\n [];\n for (const block of message.message?.content ?? []) {\n if (block?.type === \"text\") {\n finalText += block.text;\n text += block.text;\n }\n if (block?.type === \"tool_use\") {\n toolUses.push({\n id: block.id,\n name: block.name,\n input: block.input,\n });\n }\n }\n turnText += text;\n\n const gen = tracer.startSpan(\n \"assistant\",\n {\n attributes: {\n \"openinference.span.kind\": \"LLM\",\n \"llm.model_name\": model,\n \"llm.provider\": \"anthropic\",\n \"output.value\":\n text ||\n toolUses.map((t) => `→ ${cleanToolName(t.name)}`).join(\", \"),\n },\n },\n childCtx,\n );\n const usage = message.message?.usage;\n if (usage?.input_tokens != null)\n gen.setAttribute(\"llm.token_count.prompt\", usage.input_tokens);\n if (usage?.output_tokens != null)\n gen.setAttribute(\"llm.token_count.completion\", usage.output_tokens);\n gen.end();\n\n for (const t of toolUses) {\n const span = tracer.startSpan(\n `tool.${cleanToolName(t.name)}`,\n {\n attributes: {\n \"openinference.span.kind\": \"TOOL\",\n \"tool.name\": cleanToolName(t.name),\n \"input.value\": JSON.stringify(t.input),\n },\n },\n childCtx,\n );\n openTools.set(t.id, span);\n }\n }\n\n // tool_result (in a `user` message) closes the matching TOOL span, and in\n // per-turn mode also becomes part of the NEXT turn's input.\n if (message?.type === \"user\") {\n const content = message.message?.content;\n if (Array.isArray(content)) {\n for (const block of content) {\n if (block?.type === \"tool_result\") {\n const resultText = toolResultText(block.content);\n const span = openTools.get(block.tool_use_id);\n if (span) {\n span.setAttribute(\"output.value\", resultText);\n span.setStatus({ code: SpanStatusCode.OK });\n span.end();\n openTools.delete(block.tool_use_id);\n }\n if (\n options.perTurn &&\n pendingTurnInput.length < TURN_INPUT_MAX\n ) {\n pendingTurnInput +=\n (pendingTurnInput ? \"\\n\" : \"\") +\n resultText.slice(0, TURN_INPUT_MAX - pendingTurnInput.length);\n }\n }\n }\n }\n }\n\n yield message;\n }\n } finally {\n for (const span of openTools.values()) span.end();\n openTools.clear();\n if (options.perTurn) {\n endTurn();\n } else if (root) {\n root.setAttribute(\"output.value\", finalText);\n root.setStatus({ code: SpanStatusCode.OK });\n root.end();\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA;AAAA;AAAA;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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O,UAAU,IAAI,MAAM,WAAW;AAC5C,kBAAI,MAAM;AACR,qBAAK,aAAa,gBAAgB,UAAU;AAC5C,qBAAK,UAAU,EAAE,MAAMC,gBAAe,GAAG,CAAC;AAC1C,qBAAK,IAAI;AACT,0BAAU,OAAO,MAAM,WAAW;AAAA,cACpC;AACA,kBACE,QAAQ,WACR,iBAAiB,SAAS,gBAC1B;AACA,qCACG,mBAAmB,OAAO,MAC3B,WAAW,MAAM,GAAG,iBAAiB,iBAAiB,MAAM;AAAA,cAChE;AAAA,YACF;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAEA,YAAM;AAAA,IACR;AAAA,EACF,UAAE;AACA,eAAW,QAAQ,UAAU,OAAO,EAAG,MAAK,IAAI;AAChD,cAAU,MAAM;AAChB,QAAI,QAAQ,SAAS;AACnB,cAAQ;AAAA,IACV,WAAW,MAAM;AACf,WAAK,aAAa,gBAAgB,SAAS;AAC3C,WAAK,UAAU,EAAE,MAAMA,gBAAe,GAAG,CAAC;AAC1C,WAAK,IAAI;AAAA,IACX;AAAA,EACF;AACF;","names":["isSpanContextValid","trace","context","debugLog","scores","trace","warn","trace","context","SpanStatusCode"]}
|
|
1
|
+
{"version":3,"sources":["../../package.json","../../src/tracing/identity.ts","../../src/users/index.ts","../../src/scores/index.ts","../../src/build/index.ts","../../src/tracing/init.ts","../../src/tracing/observe.ts","../../src/tracing/instrument.ts","../../src/tracing/claude.ts"],"sourcesContent":["{\n \"name\": \"@withgateway/sdk\",\n \"version\": \"0.1.16\",\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 },\n \"files\": [\n \"dist\",\n \"README.md\"\n ],\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"typecheck\": \"tsc --noEmit\",\n \"typecheck:examples\": \"tsc -p tsconfig.examples.json --noEmit\",\n \"test\": \"vitest\",\n \"test:run\": \"vitest run\",\n \"lint\": \"eslint src --ext .ts\",\n \"clean\": \"rm -rf dist\",\n \"example\": \"tsx examples/test-ab-experiment.ts\",\n \"test:crm\": \"tsx examples/test-crm-ab-experiment.ts\",\n \"test:crm:balanced\": \"tsx examples/test-crm-ab-experiment.ts --balanced\",\n \"test:crm:full\": \"tsx examples/test-crm-ab-experiment.ts --users 12 --all-tasks --concurrency 3\"\n },\n \"keywords\": [\n \"gateway\",\n \"ab-testing\",\n \"experiments\",\n \"opentelemetry\",\n \"tracing\",\n \"observability\",\n \"llm\"\n ],\n \"author\": \"Gateway Team\",\n \"license\": \"MIT\",\n \"engines\": {\n \"node\": \">=18.0.0\"\n },\n \"peerDependencies\": {\n \"@opentelemetry/api\": \"^1.0.0\",\n \"@opentelemetry/exporter-trace-otlp-http\": \">=0.50.0\",\n \"@opentelemetry/resources\": \">=1.0.0\",\n \"@opentelemetry/sdk-trace-base\": \">=1.0.0\",\n \"@opentelemetry/sdk-trace-node\": \">=1.0.0\"\n },\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 },\n \"optionalDependencies\": {\n \"@arizeai/openinference-instrumentation-anthropic\": \"^0.1.15\",\n \"@arizeai/openinference-instrumentation-openai\": \"^4.1.5\"\n },\n \"devDependencies\": {\n \"@anthropic-ai/sdk\": \"^0.79.0\",\n \"@opentelemetry/api\": \"^1.9.0\",\n \"@opentelemetry/exporter-trace-otlp-http\": \"^0.212.0\",\n \"@opentelemetry/resources\": \"^2.6.0\",\n \"@opentelemetry/sdk-trace-base\": \"^1.30.1\",\n \"@opentelemetry/sdk-trace-node\": \"^2.6.0\",\n \"@opentelemetry/semantic-conventions\": \"^1.40.0\",\n \"@types/node\": \"^20.0.0\",\n \"openai\": \"^4.70.0\",\n \"tsup\": \"^8.0.0\",\n \"tsx\": \"^4.0.0\",\n \"typescript\": \"^5.0.0\",\n \"vitest\": \"^3.2.6\"\n },\n \"overrides\": {\n \"protobufjs\": \"^8.4.1\",\n \"vite@6\": \"^6.4.3\",\n \"postcss\": \"^8.5.18\",\n \"picomatch@4\": \"^4.0.4\"\n },\n \"pnpm\": {\n \"overrides\": {\n \"protobufjs\": \"^8.4.1\",\n \"vitest\": \"^3.2.6\",\n \"vite@6\": \"^6.4.3\",\n \"postcss\": \"^8.5.18\",\n \"picomatch@4\": \"^4.0.4\"\n }\n },\n \"bin\": {\n \"gateway\": \"./dist/cli.js\"\n }\n}\n","/**\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 * 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","/**\n * Initialization and lifecycle management for GatewaySDK tracing.\n *\n * This module provides the core init(), shutdown(), and flush() functions\n * for managing the OpenTelemetry TracerProvider lifecycle, plus\n * initIsolated() for creating additional self-contained providers (e.g. one\n * process exporting different agents to different Gateway projects).\n *\n * Mirrors the Python SDK's tracing.init() for a consistent developer experience.\n */\n\nimport type { Tracer } from \"@opentelemetry/api\";\nimport type { TracingConfig, TracingState } from \"./types\";\nimport { IdentitySpanProcessor } from \"./identity\";\nimport { ScoresClient } from \"../scores/index\";\nimport {\n assembleManifest,\n computeBuildHash,\n registerBuild,\n trackActiveBuild,\n type AgentBuildManifest,\n} from \"../build/index\";\n\n// Environment variable names. (A legacy BRIDGELAYER_* prefix predated the\n// rebrand but was never in any published release, so only GATEWAY_* exists.)\nconst ENV_VARS = {\n HOST: \"GATEWAY_HOST\",\n PUBLIC_KEY: \"GATEWAY_PUBLIC_KEY\",\n SECRET_KEY: \"GATEWAY_SECRET_KEY\",\n ENDPOINT: \"GATEWAY_OTLP_ENDPOINT\",\n} as const;\n\nconst DEFAULT_OTLP_PATH = \"/api/public/otel/v1/traces\";\n\n// Module-level state\nconst state: TracingState & { debug?: boolean } = {\n initialized: false,\n provider: null,\n};\n\nfunction getEnv(key: string): string | undefined {\n const value = process.env[key];\n return value ? value : undefined;\n}\n\nfunction log(message: string, ...args: unknown[]): void {\n if (state.debug) {\n console.log(`[gatewaysdk.tracing] ${message}`, ...args);\n }\n}\n\nfunction warn(message: string, ...args: unknown[]): void {\n console.warn(`[gatewaysdk.tracing] ${message}`, ...args);\n}\n\ntype LogFn = (message: string, ...args: unknown[]) => void;\n\n/**\n * Handle to an isolated tracing provider created by initIsolated().\n * Spans started from `tracer` export to that provider's Gateway project;\n * the global tracer (from init()) is untouched.\n */\nexport interface TracingHandle {\n tracer: Tracer;\n /**\n * Scores/success-signal client bound to THIS provider's project keys. Emit\n * ROI success signals into the same project the handle's spans export to —\n * `handle.scores.success(\"resolved_ticket\", true, { agentId, sessionId })` —\n * without threading credentials through your own code. Fail-soft, like the\n * rest of the client.\n */\n scores: ScoresClient;\n /** Force-flush pending spans for this provider only. */\n flush(): Promise<void>;\n /** Flush and shut down this provider only. */\n shutdown(): Promise<void>;\n}\n\n/**\n * Build a fully-configured NodeTracerProvider from config + env. Shared by\n * init() (which registers it globally) and initIsolated() (which does not).\n */\n/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-require-imports */\nfunction buildProvider(config: TracingConfig, logFn: LogFn): any {\n // Resolve configuration from params or environment\n const host = config.host ?? getEnv(ENV_VARS.HOST);\n const publicKey = config.publicKey ?? getEnv(ENV_VARS.PUBLIC_KEY);\n const secretKey = config.secretKey ?? getEnv(ENV_VARS.SECRET_KEY);\n const endpoint =\n config.endpoint ??\n getEnv(ENV_VARS.ENDPOINT) ??\n (host ? `${host.replace(/\\/$/, \"\")}${DEFAULT_OTLP_PATH}` : undefined);\n\n // Validate required configuration\n const missing: string[] = [];\n if (!host) missing.push(\"host (or GATEWAY_HOST env var)\");\n if (!publicKey) missing.push(\"publicKey (or GATEWAY_PUBLIC_KEY env var)\");\n if (!secretKey) missing.push(\"secretKey (or GATEWAY_SECRET_KEY env var)\");\n\n if (missing.length > 0) {\n throw new Error(\n `Missing required Gateway configuration: ${missing.join(\", \")}. ` +\n \"Provide these values via init() parameters or environment variables.\",\n );\n }\n\n // Dynamically import OpenTelemetry modules (they're peer dependencies)\n // Using 'any' to avoid version conflicts between OTel packages\n let NodeTracerProvider: any;\n let BatchSpanProcessor: any;\n let OTLPTraceExporter: any;\n let createResource: (attrs: Record<string, string>) => any;\n let ATTR_SERVICE_NAME: string;\n\n try {\n const traceNode = require(\"@opentelemetry/sdk-trace-node\");\n const traceBase = require(\"@opentelemetry/sdk-trace-base\");\n const otlpHttp = require(\"@opentelemetry/exporter-trace-otlp-http\");\n const resources = require(\"@opentelemetry/resources\");\n\n NodeTracerProvider = traceNode.NodeTracerProvider;\n BatchSpanProcessor = traceBase.BatchSpanProcessor;\n OTLPTraceExporter = otlpHttp.OTLPTraceExporter;\n\n // Handle both old (Resource class) and new (resourceFromAttributes function) APIs\n if (resources.Resource) {\n createResource = (attrs) => new resources.Resource(attrs);\n } else if (resources.resourceFromAttributes) {\n createResource = resources.resourceFromAttributes;\n } else {\n createResource = () => resources.defaultResource();\n }\n\n // Try semantic conventions, fall back to string literal\n try {\n const semconv = require(\"@opentelemetry/semantic-conventions\");\n ATTR_SERVICE_NAME =\n semconv.ATTR_SERVICE_NAME ?? semconv.SEMRESATTRS_SERVICE_NAME ?? \"service.name\";\n } catch {\n ATTR_SERVICE_NAME = \"service.name\";\n }\n } catch {\n throw new Error(\n \"OpenTelemetry packages not found. Install them with:\\n\" +\n \"npm install @opentelemetry/sdk-trace-node @opentelemetry/sdk-trace-base \" +\n \"@opentelemetry/exporter-trace-otlp-http @opentelemetry/resources\",\n );\n }\n\n // Build resource attributes\n const resourceAttrs: Record<string, string> = {\n [ATTR_SERVICE_NAME]: config.serviceName ?? \"gatewaysdk-tracing\",\n };\n if (config.environment) {\n resourceAttrs[\"gateway.environment\"] = config.environment;\n }\n if (config.version) {\n resourceAttrs[\"gateway.version\"] = config.version;\n }\n\n // Agent build identity — \"the agent IS the manifest\": assemble from\n // everything registered before init, stamp the content-addressed hash on\n // every span. (Tools defined AFTER init don't join the identity — define\n // them first.)\n let buildInfo: { manifest: AgentBuildManifest; buildHash: string } | null =\n null;\n if (config.agent) {\n const manifest = assembleManifest(config.agent);\n const buildHash = computeBuildHash(manifest);\n buildInfo = { manifest, buildHash };\n resourceAttrs[\"gateway.agent.id\"] = config.agent;\n resourceAttrs[\"gateway.build.hash\"] = buildHash;\n if (config.version) {\n resourceAttrs[\"gateway.agent.version\"] = config.version;\n }\n logFn(\n \"Agent build identity: %s @ %s (%d tools, %d prompts)\",\n config.agent,\n buildHash.slice(0, 15),\n manifest.tools.length,\n Object.keys(manifest.prompts).length,\n );\n }\n\n // Security check: block insecure HTTP (except localhost/127.0.0.1)\n let isLocalhost = false;\n if (endpoint) {\n try {\n const parsed = new URL(endpoint);\n isLocalhost =\n parsed.hostname === \"localhost\" || parsed.hostname === \"127.0.0.1\";\n } catch {\n isLocalhost = false;\n }\n }\n if (endpoint && !endpoint.startsWith(\"https://\") && !isLocalhost) {\n throw new Error(\n `Refusing to send credentials over insecure HTTP to ${endpoint}. ` +\n \"Use HTTPS or localhost for development.\",\n );\n }\n\n // Construct Basic Auth header\n const credentials = `${publicKey}:${secretKey}`;\n const encoded = Buffer.from(credentials).toString(\"base64\");\n const authHeader = `Basic ${encoded}`;\n\n // Create OTLP exporter\n const exporter = new OTLPTraceExporter({\n url: endpoint,\n headers: {\n Authorization: authHeader,\n },\n });\n\n logFn(\"Configured Gateway exporter: endpoint=%s\", endpoint);\n\n // Build span processors — custom processors go first (before the BatchSpanProcessor)\n const spanProcessors: any[] = [];\n\n if (config.customSpanProcessors) {\n for (const sp of config.customSpanProcessors) {\n spanProcessors.push(sp);\n logFn(\n \"Added custom span processor: %s\",\n (sp as { constructor?: { name?: string } }).constructor?.name ??\n \"unknown\",\n );\n }\n }\n\n // Stamp the ambient end-user identity (identify() / GATEWAY_USER_ID) on\n // every span at start — mirrors the Python SDK's TracingContextSpanProcessor.\n spanProcessors.push(new IdentitySpanProcessor());\n\n // Add BatchSpanProcessor with exporter\n const batchConfig: Record<string, number> = {};\n if (config.batch?.maxQueueSize) {\n batchConfig.maxQueueSize = config.batch.maxQueueSize;\n }\n if (config.batch?.scheduledDelayMillis) {\n batchConfig.scheduledDelayMillis = config.batch.scheduledDelayMillis;\n }\n if (config.batch?.maxExportBatchSize) {\n batchConfig.maxExportBatchSize = config.batch.maxExportBatchSize;\n }\n\n spanProcessors.push(new BatchSpanProcessor(exporter, batchConfig));\n\n // Create provider — detect v1 vs v2 API via runtime feature check.\n // v1 has addSpanProcessor(); v2 removed it and requires spanProcessors in constructor.\n let provider: any = new NodeTracerProvider({\n resource: createResource(resourceAttrs),\n });\n\n if (typeof provider.addSpanProcessor === \"function\") {\n // v1 API: register each processor individually\n for (const sp of spanProcessors) {\n provider.addSpanProcessor(sp);\n }\n } else {\n // v2 API: must pass spanProcessors in constructor — recreate\n provider = new NodeTracerProvider({\n resource: createResource(resourceAttrs),\n spanProcessors,\n });\n }\n\n return {\n provider,\n buildInfo,\n connection: { host: host!, publicKey: publicKey!, secretKey: secretKey! },\n };\n}\n/* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/no-require-imports */\n\n/** Fire-and-forget build registration for a provider built with `agent`. */\nfunction scheduleBuildRegistration(\n config: TracingConfig,\n built: ReturnType<typeof buildProvider>,\n): void {\n if (!config.agent || !built.buildInfo || config.registerBuild === false) {\n return;\n }\n const { manifest, buildHash } = built.buildInfo;\n // Track so tools/prompts/skills registered AFTER init re-register the\n // fullest manifest (debounced, content-addressed, idempotent).\n trackActiveBuild({\n host: built.connection.host,\n publicKey: built.connection.publicKey,\n secretKey: built.connection.secretKey,\n agentId: config.agent,\n version: config.version,\n lastRegisteredHash: buildHash,\n });\n void registerBuild({\n host: built.connection.host,\n publicKey: built.connection.publicKey,\n secretKey: built.connection.secretKey,\n agentId: config.agent,\n version: config.version,\n manifest,\n buildHash,\n }).catch((err: unknown) => {\n warn(\"Build registration failed (agent keeps running):\", err);\n });\n}\n\n/**\n * Initialize GatewaySDK tracing with automatic OpenTelemetry configuration.\n *\n * This function configures OpenTelemetry with a connection to Gateway\n * and sets up the ExperimentSpanProcessor for automatic experiment tagging.\n *\n * @example\n * ```typescript\n * import { tracing } from \"@withgateway/sdk\";\n *\n * // Using environment variables (GATEWAY_HOST, GATEWAY_PUBLIC_KEY, GATEWAY_SECRET_KEY)\n * tracing.init();\n *\n * // Or with explicit configuration\n * tracing.init({\n * host: \"https://app.gateway.dev\",\n * publicKey: \"pk-lf-...\",\n * secretKey: \"sk-lf-...\",\n * serviceName: \"my-agent\",\n * environment: \"production\",\n * });\n * ```\n */\nexport function init(config: TracingConfig = {}): void {\n if (state.initialized) {\n log(\"Tracing already initialized. Call shutdown() first to reinitialize.\");\n return;\n }\n\n // Store debug flag in state for log() function\n state.debug = config.debug ?? false;\n\n const built = buildProvider(config, log);\n const provider = built.provider;\n provider.register();\n scheduleBuildRegistration(config, built);\n\n state.provider = provider;\n state.initialized = true;\n\n log(\n \"GatewaySDK tracing initialized successfully (service=%s)\",\n config.serviceName ?? \"gatewaysdk-tracing\",\n );\n}\n\n/**\n * Create an ISOLATED tracing provider that is NOT registered globally.\n *\n * Use this when one process must export different work to different Gateway\n * projects (e.g. a server hosting several agents, each with its own project\n * keys), or when the process already has its own global OpenTelemetry\n * provider that must not be replaced.\n *\n * Spans only reach the isolated provider when started from its `tracer` —\n * pass it explicitly to observe()/observeClaude() via their `tracer` option,\n * or to a framework's telemetry hook (e.g. the Vercel AI SDK's\n * `experimental_telemetry.tracer`). Context propagation still works across\n * providers, so nesting behaves exactly as with init().\n *\n * Can be called any number of times; each handle has its own exporter,\n * batch queue, and lifecycle.\n *\n * @example\n * ```typescript\n * import { tracing } from \"@withgateway/sdk\";\n *\n * const support = tracing.initIsolated({\n * host: \"https://app.gateway.dev\",\n * publicKey: \"pk-lf-support...\",\n * secretKey: \"sk-lf-support...\",\n * serviceName: \"support-agent\",\n * });\n *\n * await tracing.observe(\"support.run\", run, { tracer: support.tracer });\n * await support.flush();\n * ```\n */\nexport function initIsolated(config: TracingConfig = {}): TracingHandle {\n const debugLog: LogFn = config.debug\n ? (message, ...args) =>\n console.log(`[gatewaysdk.tracing:isolated] ${message}`, ...args)\n : () => {};\n\n const built = buildProvider(config, debugLog);\n const provider = built.provider;\n scheduleBuildRegistration(config, built);\n const tracer = provider.getTracer(\"@withgateway/sdk\") as Tracer;\n\n // Scores client bound to the SAME project keys the exporter uses, so a\n // handle can emit success signals into its own project with no extra wiring.\n const scores = new ScoresClient({\n host: built.connection.host,\n publicKey: built.connection.publicKey,\n secretKey: built.connection.secretKey,\n debug: config.debug ?? false,\n });\n\n debugLog(\n \"Isolated tracing provider created (service=%s)\",\n config.serviceName ?? \"gatewaysdk-tracing\",\n );\n\n return {\n tracer,\n scores,\n async flush() {\n try {\n await (provider as { forceFlush: () => Promise<void> }).forceFlush();\n } catch (e) {\n warn(\"Error during isolated flush:\", e);\n }\n },\n async shutdown() {\n try {\n await (provider as { shutdown: () => Promise<void> }).shutdown();\n } catch (e) {\n warn(\"Error during isolated shutdown:\", e);\n }\n },\n };\n}\n\n/**\n * Force flush all pending spans without shutting down.\n *\n * Useful for ensuring spans are exported at specific points\n * (e.g., after completing a batch of work) without ending the tracing session.\n *\n * @returns Promise that resolves when flush completes\n */\nexport async function flush(): Promise<void> {\n if (!state.provider) {\n log(\"No provider to flush\");\n return;\n }\n\n try {\n await (state.provider as { forceFlush: () => Promise<void> }).forceFlush();\n log(\"Flush completed successfully\");\n } catch (e) {\n warn(\"Error during flush:\", e);\n }\n}\n\n/**\n * Force flush all pending spans and shutdown the tracer provider.\n *\n * This function should be called before process exit to ensure all spans\n * are exported. It is safe to call multiple times.\n *\n * @example\n * ```typescript\n * import { tracing } from \"@withgateway/sdk\";\n *\n * tracing.init();\n *\n * // On shutdown\n * process.on(\"SIGTERM\", async () => {\n * await tracing.shutdown();\n * process.exit(0);\n * });\n * ```\n */\nexport async function shutdown(): Promise<void> {\n if (!state.initialized || !state.provider) {\n log(\"Tracing not initialized, nothing to shutdown\");\n return;\n }\n\n try {\n await (state.provider as { shutdown: () => Promise<void> }).shutdown();\n log(\"Shutdown complete\");\n } catch (e) {\n warn(\"Error during shutdown:\", e);\n }\n\n state.provider = null;\n state.initialized = false;\n}\n\n/**\n * Check if tracing has been initialized.\n */\nexport function isInitialized(): boolean {\n return state.initialized;\n}\n\n/**\n * Check if Gateway is configured via environment variables.\n */\nexport function isGatewayConfigured(): boolean {\n const host = getEnv(ENV_VARS.HOST);\n const publicKey = getEnv(ENV_VARS.PUBLIC_KEY);\n const secretKey = getEnv(ENV_VARS.SECRET_KEY);\n return !!(host && publicKey && secretKey);\n}\n","/**\n * observe() — group a unit of work (an agent run, a tool call) into a single\n * span so nested LLM/tool spans attach to it and the whole thing is one trace.\n *\n * Mirrors Langfuse's `observe()` / `startActiveObservation()`. This is what an\n * app uses to define a trace boundary when it drives a raw client loop (which\n * has no framework root span of its own): the callback runs inside the span's\n * OpenTelemetry context, so any auto-instrumented calls (see observeOpenAI) and\n * any nested observe() calls become children of it.\n *\n * The span carries OpenInference attributes (openinference.span.kind, input.value,\n * output.value), and Gateway maps a root span's input.value/output.value to the\n * trace-level input/output — so the trace shows the user input and final output.\n */\nimport { trace, context, SpanStatusCode } from \"@opentelemetry/api\";\nimport type { Tracer } from \"@opentelemetry/api\";\n\nexport type ObservationKind = \"AGENT\" | \"CHAIN\" | \"TOOL\" | \"LLM\" | \"RETRIEVER\";\n\nexport interface ObserveOptions {\n /** Recorded as input.value on the span (JSON-stringified if not a string). */\n input?: unknown;\n /** OpenInference span kind. Defaults to \"AGENT\" for the outer run. */\n kind?: ObservationKind;\n /**\n * When true (default), the callback's return value is recorded as\n * output.value. Set false if the return value is large/uninteresting.\n */\n captureOutput?: boolean;\n /**\n * Tracer to start the span from. Defaults to the GLOBAL tracer (set up by\n * tracing.init()). Pass an initIsolated() handle's tracer to route this\n * observation to that handle's Gateway project instead.\n */\n tracer?: Tracer;\n /**\n * Extra attributes for the span — e.g. gateway.session.id /\n * gateway.user.id to group runs into a session and attribute them to a user.\n */\n attributes?: Record<string, string>;\n}\n\nfunction asAttr(value: unknown): string {\n return typeof value === \"string\" ? value : JSON.stringify(value);\n}\n\n/**\n * Run `fn` inside a span named `name`. Anything traced inside (auto-instrumented\n * client calls, nested observe() calls) nests under it, forming one trace.\n *\n * @example\n * ```ts\n * const result = await observe(\"my-agent.run\", async () => {\n * // client.chat.completions.create(...) here becomes a child GENERATION\n * return finalText;\n * }, { input: prompt });\n * ```\n */\nexport async function observe<T>(\n name: string,\n fn: () => Promise<T>,\n options: ObserveOptions = {},\n): Promise<T> {\n const tracer = options.tracer ?? trace.getTracer(\"@withgateway/sdk\");\n const span = tracer.startSpan(name, {\n attributes: {\n \"openinference.span.kind\": options.kind ?? \"AGENT\",\n ...(options.input !== undefined\n ? { \"input.value\": asAttr(options.input) }\n : {}),\n ...(options.attributes ?? {}),\n },\n });\n\n try {\n const result = await context.with(\n trace.setSpan(context.active(), span),\n fn,\n );\n if (options.captureOutput !== false && result !== undefined) {\n span.setAttribute(\"output.value\", asAttr(result));\n }\n span.setStatus({ code: SpanStatusCode.OK });\n return result;\n } catch (error) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: error instanceof Error ? error.message : String(error),\n });\n throw error;\n } finally {\n span.end();\n }\n}\n","/**\n * Client wrappers that turn an SDK's calls into spans on the Gateway provider.\n *\n * Node ESM can't retroactively patch a module the app already imported, so — as\n * Langfuse does with `observeOpenAI` — the app hands us the client and we\n * instrument it explicitly. One SDK call, no OpenTelemetry in the app.\n *\n * The OpenInference instrumentations are bundled optional deps of this package;\n * we load them with require() (the ESM build injects a real createRequire).\n */\n/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-require-imports */\n\nfunction warn(message: string, ...args: unknown[]): void {\n console.warn(`[gatewaysdk.tracing] ${message}`, ...args);\n}\n\n/**\n * Instrument an OpenAI client so its requests become GENERATION spans on the\n * Gateway provider. Returns the same client (its class prototype is patched, so\n * this and every other instance of that client are traced).\n *\n * @example\n * ```ts\n * import OpenAI from \"openai\";\n * import { init, observeOpenAI } from \"@withgateway/sdk/tracing\";\n * init();\n * const client = observeOpenAI(new OpenAI());\n * ```\n */\nexport function observeOpenAI<T extends object>(client: T): T {\n try {\n const {\n OpenAIInstrumentation,\n } = require(\"@arizeai/openinference-instrumentation-openai\");\n // OpenInference patches `module.OpenAI.Chat.Completions.prototype`, so it\n // needs an object shaped like the openai module. Reconstruct it from the\n // instance's class (client.constructor === the OpenAI class).\n const OpenAIClass = (client as { constructor: unknown }).constructor;\n new OpenAIInstrumentation().manuallyInstrument({ OpenAI: OpenAIClass });\n } catch (error) {\n warn(\n \"observeOpenAI: could not load @arizeai/openinference-instrumentation-openai — OpenAI calls will not be traced.\",\n error,\n );\n }\n return client;\n}\n\n/**\n * Instrument an Anthropic client so its requests become GENERATION spans.\n *\n * @example\n * ```ts\n * import Anthropic from \"@anthropic-ai/sdk\";\n * import { init, observeAnthropic } from \"@withgateway/sdk/tracing\";\n * init();\n * const client = observeAnthropic(new Anthropic());\n * ```\n */\nexport function observeAnthropic<T extends object>(client: T): T {\n try {\n const {\n AnthropicInstrumentation,\n } = require(\"@arizeai/openinference-instrumentation-anthropic\");\n // The instrumentor patches `module.Messages.prototype.create`, so it wants\n // an object whose `Messages` is the Anthropic client's Messages class (a\n // static on the class). `client.messages` resolves `create` through that\n // prototype, so patching it traces this client and every other instance.\n const AnthropicClass = (client as { constructor: { Messages?: unknown } })\n .constructor;\n new AnthropicInstrumentation().manuallyInstrument({\n Messages: AnthropicClass.Messages,\n });\n } catch (error) {\n warn(\n \"observeAnthropic: could not load @arizeai/openinference-instrumentation-anthropic — Anthropic calls will not be traced.\",\n error,\n );\n }\n return client;\n}\n","/**\n * observeClaude() — trace a Claude Agent SDK run.\n *\n * The Claude Agent SDK runs the agent in a separate `claude` CLI subprocess, so\n * there's nothing in-process to patch. What the app has is the message stream it\n * iterates. Wrap that stream with observeClaude() and it yields the same\n * messages unchanged while emitting spans on the Gateway provider.\n *\n * Default (one trace per run):\n *\n * AGENT (root)\n * ├─ GENERATION per assistant turn (with per-turn token usage)\n * └─ TOOL per tool call (input from tool_use, output from the\n * matching tool_result, matched by id)\n *\n * With `perTurn: true` (one trace PER ASSISTANT TURN — long agent runs read as\n * a session of turn traces, the way a chat thread does):\n *\n * AGENT \"<name> · turn N\" (detached root; session/user attributes on every turn)\n * ├─ GENERATION (that turn's usage + text)\n * └─ TOOL per tool call in the turn\n *\n * The TS equivalent of the Python SDK's claude-agent-sdk instrumentor.\n *\n * @example\n * ```ts\n * const stream = query({ prompt, options });\n * for await (const message of observeClaude(stream, { name, input: prompt })) {\n * // ...consume messages as usual\n * }\n * ```\n */\nimport {\n trace,\n context,\n SpanStatusCode,\n type Span,\n type Context,\n type Tracer,\n} from \"@opentelemetry/api\";\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nexport interface ObserveClaudeOptions {\n /** Root span name (becomes the trace name; per-turn mode appends `· turn N`). */\n name: string;\n /** Recorded as input.value on the root span → trace-level input. */\n input?: string;\n /** Model label for the generation spans. */\n model?: string;\n /**\n * Tracer to start spans from. Defaults to the GLOBAL tracer (set up by\n * tracing.init()). Pass an initIsolated() handle's tracer to route this\n * run to that handle's Gateway project instead.\n */\n tracer?: Tracer;\n /**\n * Extra attributes for the root span(s) — e.g. gateway.session.id /\n * gateway.user.id to group runs into a session and attribute them to a user.\n * In per-turn mode these ride EVERY turn root, so each turn trace maps to\n * the session.\n */\n attributes?: Record<string, string>;\n /**\n * Emit one TRACE PER ASSISTANT TURN instead of a single trace for the whole\n * run. Each turn's trace carries that turn's generation and tool calls; the\n * turn's input is the run input (turn 1) or the tool results that fed it\n * (later turns). Turn roots are detached (`root: true`), so they never nest\n * under ambient spans. Combine with `attributes.gateway.session.id` to read\n * a whole run as a session of turns.\n */\n perTurn?: boolean;\n}\n\n/** Strip the `mcp__<server>__` prefix so tool names read cleanly. */\nfunction cleanToolName(name: string): string {\n return name.replace(/^mcp__[^_]+__/, \"\");\n}\n\nfunction toolResultText(content: unknown): string {\n if (typeof content === \"string\") return content;\n if (Array.isArray(content))\n return content\n .map((b) =>\n b && typeof b === \"object\" && \"text\" in b\n ? String((b as { text: unknown }).text)\n : JSON.stringify(b),\n )\n .join(\"\");\n return JSON.stringify(content ?? \"\");\n}\n\nconst TURN_INPUT_MAX = 4000;\n\nexport async function* observeClaude(\n stream: AsyncIterable<any>,\n options: ObserveClaudeOptions,\n): AsyncGenerator<any> {\n const tracer = options.tracer ?? trace.getTracer(\"@withgateway/sdk\");\n const model = options.model ?? \"claude\";\n const openTools = new Map<string, Span>();\n\n // Single-trace mode: one root for the whole run.\n let root: Span | null = null;\n let rootCtx: Context | null = null;\n if (!options.perTurn) {\n root = tracer.startSpan(options.name, {\n attributes: {\n \"openinference.span.kind\": \"AGENT\",\n ...(options.input !== undefined\n ? { \"input.value\": options.input }\n : {}),\n ...(options.attributes ?? {}),\n },\n });\n rootCtx = trace.setSpan(context.active(), root);\n }\n\n // Per-turn mode: the current turn's root, rotated on each assistant message.\n let turnRoot: Span | null = null;\n let turnCtx: Context | null = null;\n let turnIndex = 0;\n let turnText = \"\";\n // What fed the CURRENT turn: the run input for turn 1, then the tool results\n // produced since the previous assistant message.\n let pendingTurnInput = options.input ?? \"\";\n\n let finalText = \"\";\n\n const endTurn = () => {\n if (!turnRoot) return;\n if (turnText) turnRoot.setAttribute(\"output.value\", turnText);\n turnRoot.setStatus({ code: SpanStatusCode.OK });\n turnRoot.end();\n turnRoot = null;\n turnCtx = null;\n };\n\n try {\n for await (const message of stream) {\n if (message?.type === \"assistant\") {\n if (options.perTurn) {\n // A new assistant message starts a new turn: any tools still open\n // belong to the previous turn — settle them, then rotate the root.\n for (const span of openTools.values()) span.end();\n openTools.clear();\n endTurn();\n turnIndex += 1;\n turnText = \"\";\n turnRoot = tracer.startSpan(`${options.name} · turn ${turnIndex}`, {\n root: true,\n attributes: {\n \"openinference.span.kind\": \"AGENT\",\n ...(pendingTurnInput\n ? { \"input.value\": pendingTurnInput.slice(0, TURN_INPUT_MAX) }\n : {}),\n ...(options.attributes ?? {}),\n },\n });\n turnCtx = trace.setSpan(context.active(), turnRoot);\n pendingTurnInput = \"\";\n }\n const childCtx = (options.perTurn ? turnCtx : rootCtx)!;\n\n let text = \"\";\n const toolUses: Array<{ id: string; name: string; input: unknown }> =\n [];\n for (const block of message.message?.content ?? []) {\n if (block?.type === \"text\") {\n finalText += block.text;\n text += block.text;\n }\n if (block?.type === \"tool_use\") {\n toolUses.push({\n id: block.id,\n name: block.name,\n input: block.input,\n });\n }\n }\n turnText += text;\n\n const gen = tracer.startSpan(\n \"assistant\",\n {\n attributes: {\n \"openinference.span.kind\": \"LLM\",\n \"llm.model_name\": model,\n \"llm.provider\": \"anthropic\",\n \"output.value\":\n text ||\n toolUses.map((t) => `→ ${cleanToolName(t.name)}`).join(\", \"),\n },\n },\n childCtx,\n );\n const usage = message.message?.usage;\n if (usage?.input_tokens != null)\n gen.setAttribute(\"llm.token_count.prompt\", usage.input_tokens);\n if (usage?.output_tokens != null)\n gen.setAttribute(\"llm.token_count.completion\", usage.output_tokens);\n gen.end();\n\n for (const t of toolUses) {\n const span = tracer.startSpan(\n `tool.${cleanToolName(t.name)}`,\n {\n attributes: {\n \"openinference.span.kind\": \"TOOL\",\n \"tool.name\": cleanToolName(t.name),\n \"input.value\": JSON.stringify(t.input),\n },\n },\n childCtx,\n );\n openTools.set(t.id, span);\n }\n }\n\n // tool_result (in a `user` message) closes the matching TOOL span, and in\n // per-turn mode also becomes part of the NEXT turn's input.\n if (message?.type === \"user\") {\n const content = message.message?.content;\n if (Array.isArray(content)) {\n for (const block of content) {\n if (block?.type === \"tool_result\") {\n const resultText = toolResultText(block.content);\n const span = openTools.get(block.tool_use_id);\n if (span) {\n span.setAttribute(\"output.value\", resultText);\n span.setStatus({ code: SpanStatusCode.OK });\n span.end();\n openTools.delete(block.tool_use_id);\n }\n if (\n options.perTurn &&\n pendingTurnInput.length < TURN_INPUT_MAX\n ) {\n pendingTurnInput +=\n (pendingTurnInput ? \"\\n\" : \"\") +\n resultText.slice(0, TURN_INPUT_MAX - pendingTurnInput.length);\n }\n }\n }\n }\n }\n\n yield message;\n }\n } finally {\n for (const span of openTools.values()) span.end();\n openTools.clear();\n if (options.perTurn) {\n endTurn();\n } else if (root) {\n root.setAttribute(\"output.value\", finalText);\n root.setStatus({ code: SpanStatusCode.OK });\n root.end();\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA;AAAA;AAAA;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;AA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