@withgateway/sdk 0.1.5 → 0.1.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{index-DnowA8MG.d.mts → index-CubrUmOe.d.mts} +23 -3
- package/dist/{index-DnowA8MG.d.ts → index-CubrUmOe.d.ts} +23 -3
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +75 -29
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +75 -29
- package/dist/index.mjs.map +1 -1
- package/dist/tracing/index.d.mts +1 -1
- package/dist/tracing/index.d.ts +1 -1
- package/dist/tracing/index.js +75 -29
- package/dist/tracing/index.js.map +1 -1
- package/dist/tracing/index.mjs +75 -29
- package/dist/tracing/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/tracing/index.d.mts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { I as IdentifyOptions, a as IdentitySpanProcessor, O as ObservationKind, b as ObserveClaudeOptions, c as ObserveOptions, T as TracingConfig, d as TracingHandle, e as TracingState, U as USER_ID_ATTRIBUTE, f as flush, i as identify, g as init, h as initIsolated, j as isGatewayConfigured, k as isInitialized, o as observe, l as observeAnthropic, m as observeClaude, n as observeOpenAI, p as resetAmbientUser, r as resolveUserId, s as shutdown } from '../index-
|
|
1
|
+
export { I as IdentifyOptions, a as IdentitySpanProcessor, O as ObservationKind, b as ObserveClaudeOptions, c as ObserveOptions, T as TracingConfig, d as TracingHandle, e as TracingState, U as USER_ID_ATTRIBUTE, f as flush, i as identify, g as init, h as initIsolated, j as isGatewayConfigured, k as isInitialized, o as observe, l as observeAnthropic, m as observeClaude, n as observeOpenAI, p as resetAmbientUser, r as resolveUserId, s as shutdown } from '../index-CubrUmOe.mjs';
|
|
2
2
|
import '@opentelemetry/api';
|
|
3
3
|
import '@opentelemetry/sdk-trace-base';
|
package/dist/tracing/index.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { I as IdentifyOptions, a as IdentitySpanProcessor, O as ObservationKind, b as ObserveClaudeOptions, c as ObserveOptions, T as TracingConfig, d as TracingHandle, e as TracingState, U as USER_ID_ATTRIBUTE, f as flush, i as identify, g as init, h as initIsolated, j as isGatewayConfigured, k as isInitialized, o as observe, l as observeAnthropic, m as observeClaude, n as observeOpenAI, p as resetAmbientUser, r as resolveUserId, s as shutdown } from '../index-
|
|
1
|
+
export { I as IdentifyOptions, a as IdentitySpanProcessor, O as ObservationKind, b as ObserveClaudeOptions, c as ObserveOptions, T as TracingConfig, d as TracingHandle, e as TracingState, U as USER_ID_ATTRIBUTE, f as flush, i as identify, g as init, h as initIsolated, j as isGatewayConfigured, k as isInitialized, o as observe, l as observeAnthropic, m as observeClaude, n as observeOpenAI, p as resetAmbientUser, r as resolveUserId, s as shutdown } from '../index-CubrUmOe.js';
|
|
2
2
|
import '@opentelemetry/api';
|
|
3
3
|
import '@opentelemetry/sdk-trace-base';
|
package/dist/tracing/index.js
CHANGED
|
@@ -243,22 +243,19 @@ function debugLog(message, ...args) {
|
|
|
243
243
|
|
|
244
244
|
// src/tracing/init.ts
|
|
245
245
|
var ENV_VARS = {
|
|
246
|
-
HOST:
|
|
247
|
-
PUBLIC_KEY:
|
|
248
|
-
SECRET_KEY:
|
|
249
|
-
ENDPOINT:
|
|
246
|
+
HOST: "GATEWAY_HOST",
|
|
247
|
+
PUBLIC_KEY: "GATEWAY_PUBLIC_KEY",
|
|
248
|
+
SECRET_KEY: "GATEWAY_SECRET_KEY",
|
|
249
|
+
ENDPOINT: "GATEWAY_OTLP_ENDPOINT"
|
|
250
250
|
};
|
|
251
251
|
var DEFAULT_OTLP_PATH = "/api/public/otel/v1/traces";
|
|
252
252
|
var state = {
|
|
253
253
|
initialized: false,
|
|
254
254
|
provider: null
|
|
255
255
|
};
|
|
256
|
-
function getEnv(
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
if (value) return value;
|
|
260
|
-
}
|
|
261
|
-
return void 0;
|
|
256
|
+
function getEnv(key) {
|
|
257
|
+
const value = process.env[key];
|
|
258
|
+
return value ? value : void 0;
|
|
262
259
|
}
|
|
263
260
|
function log(message, ...args) {
|
|
264
261
|
if (state.debug) {
|
|
@@ -546,33 +543,74 @@ function toolResultText(content) {
|
|
|
546
543
|
).join("");
|
|
547
544
|
return JSON.stringify(content ?? "");
|
|
548
545
|
}
|
|
546
|
+
var TURN_INPUT_MAX = 4e3;
|
|
549
547
|
async function* observeClaude(stream, options) {
|
|
550
548
|
const tracer = options.tracer ?? import_api3.trace.getTracer("@withgateway/sdk");
|
|
551
|
-
const root = tracer.startSpan(options.name, {
|
|
552
|
-
attributes: {
|
|
553
|
-
"openinference.span.kind": "AGENT",
|
|
554
|
-
...options.input !== void 0 ? { "input.value": options.input } : {},
|
|
555
|
-
...options.attributes ?? {}
|
|
556
|
-
}
|
|
557
|
-
});
|
|
558
|
-
const rootCtx = import_api3.trace.setSpan(import_api3.context.active(), root);
|
|
559
|
-
const openTools = /* @__PURE__ */ new Map();
|
|
560
549
|
const model = options.model ?? "claude";
|
|
550
|
+
const openTools = /* @__PURE__ */ new Map();
|
|
551
|
+
let root = null;
|
|
552
|
+
let rootCtx = null;
|
|
553
|
+
if (!options.perTurn) {
|
|
554
|
+
root = tracer.startSpan(options.name, {
|
|
555
|
+
attributes: {
|
|
556
|
+
"openinference.span.kind": "AGENT",
|
|
557
|
+
...options.input !== void 0 ? { "input.value": options.input } : {},
|
|
558
|
+
...options.attributes ?? {}
|
|
559
|
+
}
|
|
560
|
+
});
|
|
561
|
+
rootCtx = import_api3.trace.setSpan(import_api3.context.active(), root);
|
|
562
|
+
}
|
|
563
|
+
let turnRoot = null;
|
|
564
|
+
let turnCtx = null;
|
|
565
|
+
let turnIndex = 0;
|
|
566
|
+
let turnText = "";
|
|
567
|
+
let pendingTurnInput = options.input ?? "";
|
|
561
568
|
let finalText = "";
|
|
569
|
+
const endTurn = () => {
|
|
570
|
+
if (!turnRoot) return;
|
|
571
|
+
if (turnText) turnRoot.setAttribute("output.value", turnText);
|
|
572
|
+
turnRoot.setStatus({ code: import_api3.SpanStatusCode.OK });
|
|
573
|
+
turnRoot.end();
|
|
574
|
+
turnRoot = null;
|
|
575
|
+
turnCtx = null;
|
|
576
|
+
};
|
|
562
577
|
try {
|
|
563
578
|
for await (const message of stream) {
|
|
564
579
|
if (message?.type === "assistant") {
|
|
565
|
-
|
|
580
|
+
if (options.perTurn) {
|
|
581
|
+
for (const span of openTools.values()) span.end();
|
|
582
|
+
openTools.clear();
|
|
583
|
+
endTurn();
|
|
584
|
+
turnIndex += 1;
|
|
585
|
+
turnText = "";
|
|
586
|
+
turnRoot = tracer.startSpan(`${options.name} \xB7 turn ${turnIndex}`, {
|
|
587
|
+
root: true,
|
|
588
|
+
attributes: {
|
|
589
|
+
"openinference.span.kind": "AGENT",
|
|
590
|
+
...pendingTurnInput ? { "input.value": pendingTurnInput.slice(0, TURN_INPUT_MAX) } : {},
|
|
591
|
+
...options.attributes ?? {}
|
|
592
|
+
}
|
|
593
|
+
});
|
|
594
|
+
turnCtx = import_api3.trace.setSpan(import_api3.context.active(), turnRoot);
|
|
595
|
+
pendingTurnInput = "";
|
|
596
|
+
}
|
|
597
|
+
const childCtx = options.perTurn ? turnCtx : rootCtx;
|
|
598
|
+
let text = "";
|
|
566
599
|
const toolUses = [];
|
|
567
600
|
for (const block of message.message?.content ?? []) {
|
|
568
601
|
if (block?.type === "text") {
|
|
569
602
|
finalText += block.text;
|
|
570
|
-
|
|
603
|
+
text += block.text;
|
|
571
604
|
}
|
|
572
605
|
if (block?.type === "tool_use") {
|
|
573
|
-
toolUses.push({
|
|
606
|
+
toolUses.push({
|
|
607
|
+
id: block.id,
|
|
608
|
+
name: block.name,
|
|
609
|
+
input: block.input
|
|
610
|
+
});
|
|
574
611
|
}
|
|
575
612
|
}
|
|
613
|
+
turnText += text;
|
|
576
614
|
const gen = tracer.startSpan(
|
|
577
615
|
"assistant",
|
|
578
616
|
{
|
|
@@ -580,10 +618,10 @@ async function* observeClaude(stream, options) {
|
|
|
580
618
|
"openinference.span.kind": "LLM",
|
|
581
619
|
"llm.model_name": model,
|
|
582
620
|
"llm.provider": "anthropic",
|
|
583
|
-
"output.value":
|
|
621
|
+
"output.value": text || toolUses.map((t) => `\u2192 ${cleanToolName(t.name)}`).join(", ")
|
|
584
622
|
}
|
|
585
623
|
},
|
|
586
|
-
|
|
624
|
+
childCtx
|
|
587
625
|
);
|
|
588
626
|
const usage = message.message?.usage;
|
|
589
627
|
if (usage?.input_tokens != null)
|
|
@@ -601,7 +639,7 @@ async function* observeClaude(stream, options) {
|
|
|
601
639
|
"input.value": JSON.stringify(t.input)
|
|
602
640
|
}
|
|
603
641
|
},
|
|
604
|
-
|
|
642
|
+
childCtx
|
|
605
643
|
);
|
|
606
644
|
openTools.set(t.id, span);
|
|
607
645
|
}
|
|
@@ -611,13 +649,17 @@ async function* observeClaude(stream, options) {
|
|
|
611
649
|
if (Array.isArray(content)) {
|
|
612
650
|
for (const block of content) {
|
|
613
651
|
if (block?.type === "tool_result") {
|
|
652
|
+
const resultText = toolResultText(block.content);
|
|
614
653
|
const span = openTools.get(block.tool_use_id);
|
|
615
654
|
if (span) {
|
|
616
|
-
span.setAttribute("output.value",
|
|
655
|
+
span.setAttribute("output.value", resultText);
|
|
617
656
|
span.setStatus({ code: import_api3.SpanStatusCode.OK });
|
|
618
657
|
span.end();
|
|
619
658
|
openTools.delete(block.tool_use_id);
|
|
620
659
|
}
|
|
660
|
+
if (options.perTurn && pendingTurnInput.length < TURN_INPUT_MAX) {
|
|
661
|
+
pendingTurnInput += (pendingTurnInput ? "\n" : "") + resultText.slice(0, TURN_INPUT_MAX - pendingTurnInput.length);
|
|
662
|
+
}
|
|
621
663
|
}
|
|
622
664
|
}
|
|
623
665
|
}
|
|
@@ -627,9 +669,13 @@ async function* observeClaude(stream, options) {
|
|
|
627
669
|
} finally {
|
|
628
670
|
for (const span of openTools.values()) span.end();
|
|
629
671
|
openTools.clear();
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
root
|
|
672
|
+
if (options.perTurn) {
|
|
673
|
+
endTurn();
|
|
674
|
+
} else if (root) {
|
|
675
|
+
root.setAttribute("output.value", finalText);
|
|
676
|
+
root.setStatus({ code: import_api3.SpanStatusCode.OK });
|
|
677
|
+
root.end();
|
|
678
|
+
}
|
|
633
679
|
}
|
|
634
680
|
}
|
|
635
681
|
// Annotate the CommonJS export names for ESM import in node:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/tracing/index.ts","../../src/tracing/identity.ts","../../src/users/index.ts","../../src/tracing/init.ts","../../src/tracing/observe.ts","../../src/tracing/instrument.ts","../../src/tracing/claude.ts"],"sourcesContent":["/**\n * Tracing module for GatewaySDK TypeScript SDK.\n *\n * Provides a simple init() function that configures OpenTelemetry with\n * Gateway, mirroring the Python SDK's tracing.init() experience.\n *\n * @example\n * ```typescript\n * import { tracing } from \"@withgateway/sdk\";\n *\n * // Initialize with environment variables\n * tracing.init();\n *\n * // Or with explicit configuration\n * tracing.init({\n * host: \"https://app.gateway.dev\",\n * publicKey: \"pk-lf-...\",\n * secretKey: \"sk-lf-...\",\n * });\n *\n * // Ensure cleanup on shutdown\n * process.on(\"SIGTERM\", () => tracing.shutdown());\n * ```\n */\n\nexport type { TracingConfig, TracingState } from \"./types\";\n\nexport {\n init,\n initIsolated,\n shutdown,\n flush,\n isInitialized,\n isGatewayConfigured,\n} from \"./init\";\nexport type { TracingHandle } from \"./init\";\n\nexport {\n identify,\n resolveUserId,\n resetAmbientUser,\n IdentitySpanProcessor,\n USER_ID_ATTRIBUTE,\n} from \"./identity\";\nexport type { IdentifyOptions } from \"./identity\";\n\nexport { observe } from \"./observe\";\nexport type { ObserveOptions, ObservationKind } from \"./observe\";\n\nexport { observeOpenAI, observeAnthropic } from \"./instrument\";\n\nexport { observeClaude } from \"./claude\";\nexport type { ObserveClaudeOptions } from \"./claude\";\n","/**\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 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 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 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 UsersClientConfig,\n UsersClientFromEnvConfig,\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\";\n\n// Environment variable names (support both GATEWAY_* and GATEWAY_* prefixes)\nconst ENV_VARS = {\n HOST: [\"GATEWAY_HOST\", \"GATEWAY_HOST\"],\n PUBLIC_KEY: [\"GATEWAY_PUBLIC_KEY\", \"GATEWAY_PUBLIC_KEY\"],\n SECRET_KEY: [\"GATEWAY_SECRET_KEY\", \"GATEWAY_SECRET_KEY\"],\n ENDPOINT: [\"GATEWAY_OTLP_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(keys: readonly string[]): string | undefined {\n for (const key of keys) {\n const value = process.env[key];\n if (value) return value;\n }\n return 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 /** 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 // 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 provider;\n}\n/* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/no-require-imports */\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 provider = buildProvider(config, log);\n provider.register();\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 provider = buildProvider(config, debugLog);\n const tracer = provider.getTracer(\"@withgateway/sdk\") as Tracer;\n\n debugLog(\n \"Isolated tracing provider created (service=%s)\",\n config.serviceName ?? \"gatewaysdk-tracing\",\n );\n\n return {\n tracer,\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 * 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 * 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). */\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 — 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\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\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 root: Span = tracer.startSpan(options.name, {\n attributes: {\n \"openinference.span.kind\": \"AGENT\",\n ...(options.input !== undefined ? { \"input.value\": options.input } : {}),\n ...(options.attributes ?? {}),\n },\n });\n const rootCtx: Context = trace.setSpan(context.active(), root);\n const openTools = new Map<string, Span>();\n const model = options.model ?? \"claude\";\n let finalText = \"\";\n\n try {\n for await (const message of stream) {\n if (message?.type === \"assistant\") {\n let turnText = \"\";\n const toolUses: Array<{ id: string; name: string; input: unknown }> = [];\n for (const block of message.message?.content ?? []) {\n if (block?.type === \"text\") {\n finalText += block.text;\n turnText += block.text;\n }\n if (block?.type === \"tool_use\") {\n toolUses.push({ id: block.id, name: block.name, input: block.input });\n }\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 turnText ||\n toolUses.map((t) => `→ ${cleanToolName(t.name)}`).join(\", \"),\n },\n },\n rootCtx,\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 rootCtx,\n );\n openTools.set(t.id, span);\n }\n }\n\n // tool_result (in a `user` message) closes the matching TOOL span.\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 span = openTools.get(block.tool_use_id);\n if (span) {\n span.setAttribute(\"output.value\", toolResultText(block.content));\n span.setStatus({ code: SpanStatusCode.OK });\n span.end();\n openTools.delete(block.tool_use_id);\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 root.setAttribute(\"output.value\", finalText);\n root.setStatus({ code: SpanStatusCode.OK });\n root.end();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACiBA,yBAAkC;AAClC,iBAA0C;;;ACqCnC,IAAM,mBAAN,cAA+B,MAAM;AAAA,EAC1C,YAAY,SAAiB,SAA+B;AAC1D,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,QAAQ,SAAS;AAAA,EACxB;AACF;AAGO,IAAM,cAAN,MAAM,aAAY;AAAA,EACN;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEjB,YAAY,QAA2B;AACrC,SAAK,OAAO,OAAO,KAAK,QAAQ,OAAO,EAAE;AACzC,SAAK,YAAY,OAAO;AACxB,SAAK,YAAY,OAAO;AACxB,SAAK,iBAAiB,OAAO,kBAAkB;AAC/C,SAAK,QAAQ,OAAO,SAAS;AAAA,EAC/B;AAAA;AAAA,EAGA,OAAO,QAAQ,SAAmC,CAAC,GAAG;AACpD,UAAM,OAAO,OAAO,QAAQ,QAAQ,IAAI;AACxC,UAAM,YAAY,OAAO,aAAa,QAAQ,IAAI;AAClD,UAAM,YAAY,OAAO,aAAa,QAAQ,IAAI;AAElD,UAAM,UAAU;AAAA,MAC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,gBAAgB,eAAe,MAAM,OAAO,CAAC;AAC/D,qBAAK,UAAU,EAAE,MAAM,2BAAe,GAAG,CAAC;AAC1C,qBAAK,IAAI;AACT,0BAAU,OAAO,MAAM,WAAW;AAAA,cACpC;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,SAAK,aAAa,gBAAgB,SAAS;AAC3C,SAAK,UAAU,EAAE,MAAM,2BAAe,GAAG,CAAC;AAC1C,SAAK,IAAI;AAAA,EACX;AACF;","names":["debugLog","import_api","warn","import_api"]}
|
|
1
|
+
{"version":3,"sources":["../../src/tracing/index.ts","../../src/tracing/identity.ts","../../src/users/index.ts","../../src/tracing/init.ts","../../src/tracing/observe.ts","../../src/tracing/instrument.ts","../../src/tracing/claude.ts"],"sourcesContent":["/**\n * Tracing module for GatewaySDK TypeScript SDK.\n *\n * Provides a simple init() function that configures OpenTelemetry with\n * Gateway, mirroring the Python SDK's tracing.init() experience.\n *\n * @example\n * ```typescript\n * import { tracing } from \"@withgateway/sdk\";\n *\n * // Initialize with environment variables\n * tracing.init();\n *\n * // Or with explicit configuration\n * tracing.init({\n * host: \"https://app.gateway.dev\",\n * publicKey: \"pk-lf-...\",\n * secretKey: \"sk-lf-...\",\n * });\n *\n * // Ensure cleanup on shutdown\n * process.on(\"SIGTERM\", () => tracing.shutdown());\n * ```\n */\n\nexport type { TracingConfig, TracingState } from \"./types\";\n\nexport {\n init,\n initIsolated,\n shutdown,\n flush,\n isInitialized,\n isGatewayConfigured,\n} from \"./init\";\nexport type { TracingHandle } from \"./init\";\n\nexport {\n identify,\n resolveUserId,\n resetAmbientUser,\n IdentitySpanProcessor,\n USER_ID_ATTRIBUTE,\n} from \"./identity\";\nexport type { IdentifyOptions } from \"./identity\";\n\nexport { observe } from \"./observe\";\nexport type { ObserveOptions, ObservationKind } from \"./observe\";\n\nexport { observeOpenAI, observeAnthropic } from \"./instrument\";\n\nexport { observeClaude } from \"./claude\";\nexport type { ObserveClaudeOptions } from \"./claude\";\n","/**\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 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 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 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 UsersClientConfig,\n UsersClientFromEnvConfig,\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\";\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 /** 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 // 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 provider;\n}\n/* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/no-require-imports */\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 provider = buildProvider(config, log);\n provider.register();\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 provider = buildProvider(config, debugLog);\n const tracer = provider.getTracer(\"@withgateway/sdk\") as Tracer;\n\n debugLog(\n \"Isolated tracing provider created (service=%s)\",\n config.serviceName ?? \"gatewaysdk-tracing\",\n );\n\n return {\n tracer,\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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACiBA,yBAAkC;AAClC,iBAA0C;;;ACqCnC,IAAM,mBAAN,cAA+B,MAAM;AAAA,EAC1C,YAAY,SAAiB,SAA+B;AAC1D,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,QAAQ,SAAS;AAAA,EACxB;AACF;AAGO,IAAM,cAAN,MAAM,aAAY;AAAA,EACN;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEjB,YAAY,QAA2B;AACrC,SAAK,OAAO,OAAO,KAAK,QAAQ,OAAO,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AAE,MAAM,2BAAe,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,MAAM,2BAAe,GAAG,CAAC;AAC1C,WAAK,IAAI;AAAA,IACX;AAAA,EACF;AACF;","names":["debugLog","import_api","warn","import_api"]}
|
package/dist/tracing/index.mjs
CHANGED
|
@@ -212,22 +212,19 @@ function debugLog(message, ...args) {
|
|
|
212
212
|
|
|
213
213
|
// src/tracing/init.ts
|
|
214
214
|
var ENV_VARS = {
|
|
215
|
-
HOST:
|
|
216
|
-
PUBLIC_KEY:
|
|
217
|
-
SECRET_KEY:
|
|
218
|
-
ENDPOINT:
|
|
215
|
+
HOST: "GATEWAY_HOST",
|
|
216
|
+
PUBLIC_KEY: "GATEWAY_PUBLIC_KEY",
|
|
217
|
+
SECRET_KEY: "GATEWAY_SECRET_KEY",
|
|
218
|
+
ENDPOINT: "GATEWAY_OTLP_ENDPOINT"
|
|
219
219
|
};
|
|
220
220
|
var DEFAULT_OTLP_PATH = "/api/public/otel/v1/traces";
|
|
221
221
|
var state = {
|
|
222
222
|
initialized: false,
|
|
223
223
|
provider: null
|
|
224
224
|
};
|
|
225
|
-
function getEnv(
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
if (value) return value;
|
|
229
|
-
}
|
|
230
|
-
return void 0;
|
|
225
|
+
function getEnv(key) {
|
|
226
|
+
const value = process.env[key];
|
|
227
|
+
return value ? value : void 0;
|
|
231
228
|
}
|
|
232
229
|
function log(message, ...args) {
|
|
233
230
|
if (state.debug) {
|
|
@@ -519,33 +516,74 @@ function toolResultText(content) {
|
|
|
519
516
|
).join("");
|
|
520
517
|
return JSON.stringify(content ?? "");
|
|
521
518
|
}
|
|
519
|
+
var TURN_INPUT_MAX = 4e3;
|
|
522
520
|
async function* observeClaude(stream, options) {
|
|
523
521
|
const tracer = options.tracer ?? trace3.getTracer("@withgateway/sdk");
|
|
524
|
-
const root = tracer.startSpan(options.name, {
|
|
525
|
-
attributes: {
|
|
526
|
-
"openinference.span.kind": "AGENT",
|
|
527
|
-
...options.input !== void 0 ? { "input.value": options.input } : {},
|
|
528
|
-
...options.attributes ?? {}
|
|
529
|
-
}
|
|
530
|
-
});
|
|
531
|
-
const rootCtx = trace3.setSpan(context2.active(), root);
|
|
532
|
-
const openTools = /* @__PURE__ */ new Map();
|
|
533
522
|
const model = options.model ?? "claude";
|
|
523
|
+
const openTools = /* @__PURE__ */ new Map();
|
|
524
|
+
let root = null;
|
|
525
|
+
let rootCtx = null;
|
|
526
|
+
if (!options.perTurn) {
|
|
527
|
+
root = tracer.startSpan(options.name, {
|
|
528
|
+
attributes: {
|
|
529
|
+
"openinference.span.kind": "AGENT",
|
|
530
|
+
...options.input !== void 0 ? { "input.value": options.input } : {},
|
|
531
|
+
...options.attributes ?? {}
|
|
532
|
+
}
|
|
533
|
+
});
|
|
534
|
+
rootCtx = trace3.setSpan(context2.active(), root);
|
|
535
|
+
}
|
|
536
|
+
let turnRoot = null;
|
|
537
|
+
let turnCtx = null;
|
|
538
|
+
let turnIndex = 0;
|
|
539
|
+
let turnText = "";
|
|
540
|
+
let pendingTurnInput = options.input ?? "";
|
|
534
541
|
let finalText = "";
|
|
542
|
+
const endTurn = () => {
|
|
543
|
+
if (!turnRoot) return;
|
|
544
|
+
if (turnText) turnRoot.setAttribute("output.value", turnText);
|
|
545
|
+
turnRoot.setStatus({ code: SpanStatusCode2.OK });
|
|
546
|
+
turnRoot.end();
|
|
547
|
+
turnRoot = null;
|
|
548
|
+
turnCtx = null;
|
|
549
|
+
};
|
|
535
550
|
try {
|
|
536
551
|
for await (const message of stream) {
|
|
537
552
|
if (message?.type === "assistant") {
|
|
538
|
-
|
|
553
|
+
if (options.perTurn) {
|
|
554
|
+
for (const span of openTools.values()) span.end();
|
|
555
|
+
openTools.clear();
|
|
556
|
+
endTurn();
|
|
557
|
+
turnIndex += 1;
|
|
558
|
+
turnText = "";
|
|
559
|
+
turnRoot = tracer.startSpan(`${options.name} \xB7 turn ${turnIndex}`, {
|
|
560
|
+
root: true,
|
|
561
|
+
attributes: {
|
|
562
|
+
"openinference.span.kind": "AGENT",
|
|
563
|
+
...pendingTurnInput ? { "input.value": pendingTurnInput.slice(0, TURN_INPUT_MAX) } : {},
|
|
564
|
+
...options.attributes ?? {}
|
|
565
|
+
}
|
|
566
|
+
});
|
|
567
|
+
turnCtx = trace3.setSpan(context2.active(), turnRoot);
|
|
568
|
+
pendingTurnInput = "";
|
|
569
|
+
}
|
|
570
|
+
const childCtx = options.perTurn ? turnCtx : rootCtx;
|
|
571
|
+
let text = "";
|
|
539
572
|
const toolUses = [];
|
|
540
573
|
for (const block of message.message?.content ?? []) {
|
|
541
574
|
if (block?.type === "text") {
|
|
542
575
|
finalText += block.text;
|
|
543
|
-
|
|
576
|
+
text += block.text;
|
|
544
577
|
}
|
|
545
578
|
if (block?.type === "tool_use") {
|
|
546
|
-
toolUses.push({
|
|
579
|
+
toolUses.push({
|
|
580
|
+
id: block.id,
|
|
581
|
+
name: block.name,
|
|
582
|
+
input: block.input
|
|
583
|
+
});
|
|
547
584
|
}
|
|
548
585
|
}
|
|
586
|
+
turnText += text;
|
|
549
587
|
const gen = tracer.startSpan(
|
|
550
588
|
"assistant",
|
|
551
589
|
{
|
|
@@ -553,10 +591,10 @@ async function* observeClaude(stream, options) {
|
|
|
553
591
|
"openinference.span.kind": "LLM",
|
|
554
592
|
"llm.model_name": model,
|
|
555
593
|
"llm.provider": "anthropic",
|
|
556
|
-
"output.value":
|
|
594
|
+
"output.value": text || toolUses.map((t) => `\u2192 ${cleanToolName(t.name)}`).join(", ")
|
|
557
595
|
}
|
|
558
596
|
},
|
|
559
|
-
|
|
597
|
+
childCtx
|
|
560
598
|
);
|
|
561
599
|
const usage = message.message?.usage;
|
|
562
600
|
if (usage?.input_tokens != null)
|
|
@@ -574,7 +612,7 @@ async function* observeClaude(stream, options) {
|
|
|
574
612
|
"input.value": JSON.stringify(t.input)
|
|
575
613
|
}
|
|
576
614
|
},
|
|
577
|
-
|
|
615
|
+
childCtx
|
|
578
616
|
);
|
|
579
617
|
openTools.set(t.id, span);
|
|
580
618
|
}
|
|
@@ -584,13 +622,17 @@ async function* observeClaude(stream, options) {
|
|
|
584
622
|
if (Array.isArray(content)) {
|
|
585
623
|
for (const block of content) {
|
|
586
624
|
if (block?.type === "tool_result") {
|
|
625
|
+
const resultText = toolResultText(block.content);
|
|
587
626
|
const span = openTools.get(block.tool_use_id);
|
|
588
627
|
if (span) {
|
|
589
|
-
span.setAttribute("output.value",
|
|
628
|
+
span.setAttribute("output.value", resultText);
|
|
590
629
|
span.setStatus({ code: SpanStatusCode2.OK });
|
|
591
630
|
span.end();
|
|
592
631
|
openTools.delete(block.tool_use_id);
|
|
593
632
|
}
|
|
633
|
+
if (options.perTurn && pendingTurnInput.length < TURN_INPUT_MAX) {
|
|
634
|
+
pendingTurnInput += (pendingTurnInput ? "\n" : "") + resultText.slice(0, TURN_INPUT_MAX - pendingTurnInput.length);
|
|
635
|
+
}
|
|
594
636
|
}
|
|
595
637
|
}
|
|
596
638
|
}
|
|
@@ -600,9 +642,13 @@ async function* observeClaude(stream, options) {
|
|
|
600
642
|
} finally {
|
|
601
643
|
for (const span of openTools.values()) span.end();
|
|
602
644
|
openTools.clear();
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
root
|
|
645
|
+
if (options.perTurn) {
|
|
646
|
+
endTurn();
|
|
647
|
+
} else if (root) {
|
|
648
|
+
root.setAttribute("output.value", finalText);
|
|
649
|
+
root.setStatus({ code: SpanStatusCode2.OK });
|
|
650
|
+
root.end();
|
|
651
|
+
}
|
|
606
652
|
}
|
|
607
653
|
}
|
|
608
654
|
export {
|