@withgateway/sdk 0.1.4 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/index-DnowA8MG.d.mts +447 -0
  2. package/dist/index-DnowA8MG.d.ts +447 -0
  3. package/dist/index.d.mts +6 -1
  4. package/dist/index.d.ts +6 -1
  5. package/dist/index.js +1551 -33
  6. package/dist/index.js.map +1 -1
  7. package/dist/index.mjs +1511 -27
  8. package/dist/index.mjs.map +1 -1
  9. package/dist/personas/index.d.mts +102 -0
  10. package/dist/personas/index.d.ts +102 -0
  11. package/dist/personas/index.js +205 -0
  12. package/dist/personas/index.js.map +1 -0
  13. package/dist/personas/index.mjs +180 -0
  14. package/dist/personas/index.mjs.map +1 -0
  15. package/dist/replay/index.d.mts +351 -0
  16. package/dist/replay/index.d.ts +351 -0
  17. package/dist/replay/index.js +1094 -0
  18. package/dist/replay/index.js.map +1 -0
  19. package/dist/replay/index.mjs +1057 -0
  20. package/dist/replay/index.mjs.map +1 -0
  21. package/dist/sessions/index.d.mts +143 -0
  22. package/dist/sessions/index.d.ts +143 -0
  23. package/dist/sessions/index.js +320 -0
  24. package/dist/sessions/index.js.map +1 -0
  25. package/dist/sessions/index.mjs +288 -0
  26. package/dist/sessions/index.mjs.map +1 -0
  27. package/dist/tracing/index.d.mts +3 -1
  28. package/dist/tracing/index.d.ts +3 -1
  29. package/dist/tracing/index.js +277 -31
  30. package/dist/tracing/index.js.map +1 -1
  31. package/dist/tracing/index.mjs +266 -26
  32. package/dist/tracing/index.mjs.map +1 -1
  33. package/dist/users/index.d.mts +81 -0
  34. package/dist/users/index.d.ts +81 -0
  35. package/dist/users/index.js +168 -0
  36. package/dist/users/index.js.map +1 -0
  37. package/dist/users/index.mjs +144 -0
  38. package/dist/users/index.mjs.map +1 -0
  39. package/package.json +21 -1
  40. package/dist/index-yJgb8wh6.d.mts +0 -273
  41. package/dist/index-yJgb8wh6.d.ts +0 -273
@@ -0,0 +1,144 @@
1
+ import { createRequire as __gatewayCreateRequire } from "module";
2
+ const require = __gatewayCreateRequire(import.meta.url);
3
+
4
+ // src/users/index.ts
5
+ var UserProfileError = class extends Error {
6
+ constructor(message, options) {
7
+ super(message);
8
+ this.name = "UserProfileError";
9
+ this.cause = options?.cause;
10
+ }
11
+ };
12
+ var UsersClient = class _UsersClient {
13
+ host;
14
+ publicKey;
15
+ secretKey;
16
+ timeoutSeconds;
17
+ debug;
18
+ constructor(config) {
19
+ this.host = config.host.replace(/\/$/, "");
20
+ this.publicKey = config.publicKey;
21
+ this.secretKey = config.secretKey;
22
+ this.timeoutSeconds = config.timeoutSeconds ?? 15;
23
+ this.debug = config.debug ?? false;
24
+ }
25
+ /** Create a client from GATEWAY_HOST / GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY. */
26
+ static fromEnv(config = {}) {
27
+ const host = config.host ?? process.env.GATEWAY_HOST;
28
+ const publicKey = config.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;
29
+ const secretKey = config.secretKey ?? process.env.GATEWAY_SECRET_KEY;
30
+ const missing = [
31
+ ["host", host],
32
+ ["publicKey", publicKey],
33
+ ["secretKey", secretKey]
34
+ ].filter(([, value]) => !value).map(([name]) => name);
35
+ if (missing.length > 0) {
36
+ throw new UserProfileError(
37
+ `Missing Gateway user-profile configuration: ${missing.join(", ")}`
38
+ );
39
+ }
40
+ return new _UsersClient({
41
+ ...config,
42
+ host,
43
+ publicKey,
44
+ secretKey
45
+ });
46
+ }
47
+ /** Fetch a user's stored profile. */
48
+ async get(userId) {
49
+ return parseProfile(
50
+ await this.requestJson(
51
+ "GET",
52
+ `/api/public/user-profiles/${encodeURIComponent(userId)}`
53
+ )
54
+ );
55
+ }
56
+ /**
57
+ * Upsert a user's profile. `attributes` merge with the stored set unless
58
+ * `merge: false` (which replaces it).
59
+ */
60
+ async update(userId, update = {}) {
61
+ const body = {
62
+ userId,
63
+ attributes: update.attributes ?? {},
64
+ mergeAttributes: update.merge ?? true,
65
+ ...update.displayName !== void 0 ? { displayName: update.displayName } : {},
66
+ ...update.email !== void 0 ? { email: update.email } : {},
67
+ ...update.notes !== void 0 ? { notes: update.notes } : {}
68
+ };
69
+ return parseProfile(
70
+ await this.requestJson("POST", "/api/public/user-profiles", body)
71
+ );
72
+ }
73
+ async requestJson(method, path, payload) {
74
+ let response;
75
+ try {
76
+ response = await fetch(`${this.host}${path}`, {
77
+ method,
78
+ headers: {
79
+ Authorization: this.authHeader(),
80
+ "Content-Type": "application/json"
81
+ },
82
+ ...payload ? { body: JSON.stringify(payload) } : {},
83
+ signal: AbortSignal.timeout(this.timeoutSeconds * 1e3)
84
+ });
85
+ } catch (error) {
86
+ throw new UserProfileError(
87
+ `${method} ${path} failed: ${error instanceof Error ? error.message : String(error)}`,
88
+ { cause: error }
89
+ );
90
+ }
91
+ const text = await response.text();
92
+ if (!response.ok) {
93
+ throw new UserProfileError(
94
+ `${method} ${path} failed (${response.status}): ${text.slice(0, 500)}`
95
+ );
96
+ }
97
+ this.log("%s %s -> %s", method, path, response.status);
98
+ return safeJson(text);
99
+ }
100
+ authHeader() {
101
+ return `Basic ${Buffer.from(`${this.publicKey}:${this.secretKey}`).toString(
102
+ "base64"
103
+ )}`;
104
+ }
105
+ log(message, ...args) {
106
+ if (this.debug) {
107
+ console.log(`[gateway.users] ${message}`, ...args);
108
+ }
109
+ }
110
+ };
111
+ function parseProfile(payload) {
112
+ return {
113
+ userId: String(payload.userId ?? ""),
114
+ displayName: typeof payload.displayName === "string" ? payload.displayName : null,
115
+ email: typeof payload.email === "string" ? payload.email : null,
116
+ attributes: parseAttributes(payload.attributes),
117
+ notes: typeof payload.notes === "string" ? payload.notes : null
118
+ };
119
+ }
120
+ function parseAttributes(value) {
121
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
122
+ const attributes = {};
123
+ for (const [key, entry] of Object.entries(value)) {
124
+ attributes[key] = String(entry);
125
+ }
126
+ return attributes;
127
+ }
128
+ function safeJson(value) {
129
+ try {
130
+ const parsed = JSON.parse(value);
131
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
132
+ } catch {
133
+ return {};
134
+ }
135
+ }
136
+ var users = {
137
+ fromEnv: UsersClient.fromEnv
138
+ };
139
+ export {
140
+ UserProfileError,
141
+ UsersClient,
142
+ users
143
+ };
144
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/users/index.ts"],"sourcesContent":["/**\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"],"mappings":";;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- "version": "0.1.4",
3
+ "version": "0.1.6",
4
4
  "description": "Gateway SDK for TypeScript - A/B experiments, tracing, and observability",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",
@@ -26,6 +26,21 @@
26
26
  "import": "./dist/memory/index.mjs",
27
27
  "require": "./dist/memory/index.js"
28
28
  },
29
+ "./personas": {
30
+ "types": "./dist/personas/index.d.ts",
31
+ "import": "./dist/personas/index.mjs",
32
+ "require": "./dist/personas/index.js"
33
+ },
34
+ "./replay": {
35
+ "types": "./dist/replay/index.d.ts",
36
+ "import": "./dist/replay/index.mjs",
37
+ "require": "./dist/replay/index.js"
38
+ },
39
+ "./sessions": {
40
+ "types": "./dist/sessions/index.d.ts",
41
+ "import": "./dist/sessions/index.mjs",
42
+ "require": "./dist/sessions/index.js"
43
+ },
29
44
  "./tracing": {
30
45
  "types": "./dist/tracing/index.d.ts",
31
46
  "import": "./dist/tracing/index.mjs",
@@ -35,6 +50,11 @@
35
50
  "types": "./dist/security/index.d.ts",
36
51
  "import": "./dist/security/index.mjs",
37
52
  "require": "./dist/security/index.js"
53
+ },
54
+ "./users": {
55
+ "types": "./dist/users/index.d.ts",
56
+ "import": "./dist/users/index.mjs",
57
+ "require": "./dist/users/index.js"
38
58
  }
39
59
  },
40
60
  "files": [
@@ -1,273 +0,0 @@
1
- /**
2
- * Types for the tracing module.
3
- */
4
- interface TracingConfig {
5
- /**
6
- * Gateway server URL (e.g., "https://app.gateway.dev").
7
- * Falls back to GATEWAY_HOST or GATEWAY_HOST env var.
8
- */
9
- host?: string;
10
- /**
11
- * Public key for authentication (pk-lf-...).
12
- * Falls back to GATEWAY_PUBLIC_KEY or GATEWAY_PUBLIC_KEY env var.
13
- */
14
- publicKey?: string;
15
- /**
16
- * Secret key for authentication (sk-lf-...).
17
- * Falls back to GATEWAY_SECRET_KEY or GATEWAY_SECRET_KEY env var.
18
- */
19
- secretKey?: string;
20
- /**
21
- * Service name for resource attributes.
22
- * Defaults to "gatewaysdk-tracing".
23
- */
24
- serviceName?: string;
25
- /**
26
- * Environment name (e.g., "production", "staging").
27
- * Sets resource attribute for filtering traces in Gateway.
28
- */
29
- environment?: string;
30
- /**
31
- * Application version (e.g., "1.2.3", git SHA).
32
- * Sets resource attribute for tracking regressions.
33
- */
34
- version?: string;
35
- /**
36
- * Whether to enable debug logging to console.
37
- * Defaults to false.
38
- */
39
- debug?: boolean;
40
- /**
41
- * Whether to automatically add ExperimentSpanProcessor when imported
42
- * from the main entry ("@withgateway/sdk"). Has no effect when imported
43
- * from the subpath ("@withgateway/sdk/tracing") — use customSpanProcessors
44
- * instead.
45
- * Defaults to true.
46
- */
47
- enableExperiments?: boolean;
48
- /**
49
- * Additional span processors to register with the provider.
50
- * These are added before the BatchSpanProcessor (which handles export).
51
- *
52
- * When using the main entry (`import { tracing } from "@withgateway/sdk"`),
53
- * ExperimentSpanProcessor is automatically added unless enableExperiments
54
- * is false. When using the subpath import, pass it here manually:
55
- *
56
- * @example
57
- * ```typescript
58
- * import * as tracing from "@withgateway/sdk/tracing";
59
- * import { ExperimentSpanProcessor } from "@withgateway/sdk/experiments";
60
- *
61
- * tracing.init({ customSpanProcessors: [new ExperimentSpanProcessor()] });
62
- * ```
63
- */
64
- customSpanProcessors?: unknown[];
65
- /**
66
- * Custom OTLP endpoint URL. If not provided, derived from host.
67
- */
68
- endpoint?: string;
69
- /**
70
- * Batch processor configuration.
71
- */
72
- batch?: {
73
- /** Max spans buffered in memory. Default: 2048 */
74
- maxQueueSize?: number;
75
- /** How often to flush spans (ms). Default: 5000 */
76
- scheduledDelayMillis?: number;
77
- /** Max spans per export call. Default: 512 */
78
- maxExportBatchSize?: number;
79
- };
80
- }
81
- interface TracingState {
82
- initialized: boolean;
83
- provider: unknown | null;
84
- }
85
-
86
- /**
87
- * Initialization and lifecycle management for GatewaySDK tracing.
88
- *
89
- * This module provides the core init(), shutdown(), and flush() functions
90
- * for managing the OpenTelemetry TracerProvider lifecycle.
91
- *
92
- * Mirrors the Python SDK's tracing.init() for a consistent developer experience.
93
- */
94
-
95
- /**
96
- * Initialize GatewaySDK tracing with automatic OpenTelemetry configuration.
97
- *
98
- * This function configures OpenTelemetry with a connection to Gateway
99
- * and sets up the ExperimentSpanProcessor for automatic experiment tagging.
100
- *
101
- * @example
102
- * ```typescript
103
- * import { tracing } from "@withgateway/sdk";
104
- *
105
- * // Using environment variables (GATEWAY_HOST, GATEWAY_PUBLIC_KEY, GATEWAY_SECRET_KEY)
106
- * tracing.init();
107
- *
108
- * // Or with explicit configuration
109
- * tracing.init({
110
- * host: "https://app.gateway.dev",
111
- * publicKey: "pk-lf-...",
112
- * secretKey: "sk-lf-...",
113
- * serviceName: "my-agent",
114
- * environment: "production",
115
- * });
116
- * ```
117
- */
118
- declare function init(config?: TracingConfig): void;
119
- /**
120
- * Force flush all pending spans without shutting down.
121
- *
122
- * Useful for ensuring spans are exported at specific points
123
- * (e.g., after completing a batch of work) without ending the tracing session.
124
- *
125
- * @returns Promise that resolves when flush completes
126
- */
127
- declare function flush(): Promise<void>;
128
- /**
129
- * Force flush all pending spans and shutdown the tracer provider.
130
- *
131
- * This function should be called before process exit to ensure all spans
132
- * are exported. It is safe to call multiple times.
133
- *
134
- * @example
135
- * ```typescript
136
- * import { tracing } from "@withgateway/sdk";
137
- *
138
- * tracing.init();
139
- *
140
- * // On shutdown
141
- * process.on("SIGTERM", async () => {
142
- * await tracing.shutdown();
143
- * process.exit(0);
144
- * });
145
- * ```
146
- */
147
- declare function shutdown(): Promise<void>;
148
- /**
149
- * Check if tracing has been initialized.
150
- */
151
- declare function isInitialized(): boolean;
152
- /**
153
- * Check if Gateway is configured via environment variables.
154
- */
155
- declare function isGatewayConfigured(): boolean;
156
-
157
- type ObservationKind = "AGENT" | "CHAIN" | "TOOL" | "LLM" | "RETRIEVER";
158
- interface ObserveOptions {
159
- /** Recorded as input.value on the span (JSON-stringified if not a string). */
160
- input?: unknown;
161
- /** OpenInference span kind. Defaults to "AGENT" for the outer run. */
162
- kind?: ObservationKind;
163
- /**
164
- * When true (default), the callback's return value is recorded as
165
- * output.value. Set false if the return value is large/uninteresting.
166
- */
167
- captureOutput?: boolean;
168
- }
169
- /**
170
- * Run `fn` inside a span named `name`. Anything traced inside (auto-instrumented
171
- * client calls, nested observe() calls) nests under it, forming one trace.
172
- *
173
- * @example
174
- * ```ts
175
- * const result = await observe("my-agent.run", async () => {
176
- * // client.chat.completions.create(...) here becomes a child GENERATION
177
- * return finalText;
178
- * }, { input: prompt });
179
- * ```
180
- */
181
- declare function observe<T>(name: string, fn: () => Promise<T>, options?: ObserveOptions): Promise<T>;
182
-
183
- /**
184
- * Client wrappers that turn an SDK's calls into spans on the Gateway provider.
185
- *
186
- * Node ESM can't retroactively patch a module the app already imported, so — as
187
- * Langfuse does with `observeOpenAI` — the app hands us the client and we
188
- * instrument it explicitly. One SDK call, no OpenTelemetry in the app.
189
- *
190
- * The OpenInference instrumentations are bundled optional deps of this package;
191
- * we load them with require() (the ESM build injects a real createRequire).
192
- */
193
- /**
194
- * Instrument an OpenAI client so its requests become GENERATION spans on the
195
- * Gateway provider. Returns the same client (its class prototype is patched, so
196
- * this and every other instance of that client are traced).
197
- *
198
- * @example
199
- * ```ts
200
- * import OpenAI from "openai";
201
- * import { init, observeOpenAI } from "@withgateway/sdk/tracing";
202
- * init();
203
- * const client = observeOpenAI(new OpenAI());
204
- * ```
205
- */
206
- declare function observeOpenAI<T extends object>(client: T): T;
207
- /**
208
- * Instrument an Anthropic client so its requests become GENERATION spans.
209
- *
210
- * @example
211
- * ```ts
212
- * import Anthropic from "@anthropic-ai/sdk";
213
- * import { init, observeAnthropic } from "@withgateway/sdk/tracing";
214
- * init();
215
- * const client = observeAnthropic(new Anthropic());
216
- * ```
217
- */
218
- declare function observeAnthropic<T extends object>(client: T): T;
219
-
220
- interface ObserveClaudeOptions {
221
- /** Root span name (becomes the trace name). */
222
- name: string;
223
- /** Recorded as input.value on the root span → trace-level input. */
224
- input?: string;
225
- /** Model label for the generation spans. */
226
- model?: string;
227
- }
228
- declare function observeClaude(stream: AsyncIterable<any>, options: ObserveClaudeOptions): AsyncGenerator<any>;
229
-
230
- /**
231
- * Tracing module for GatewaySDK TypeScript SDK.
232
- *
233
- * Provides a simple init() function that configures OpenTelemetry with
234
- * Gateway, mirroring the Python SDK's tracing.init() experience.
235
- *
236
- * @example
237
- * ```typescript
238
- * import { tracing } from "@withgateway/sdk";
239
- *
240
- * // Initialize with environment variables
241
- * tracing.init();
242
- *
243
- * // Or with explicit configuration
244
- * tracing.init({
245
- * host: "https://app.gateway.dev",
246
- * publicKey: "pk-lf-...",
247
- * secretKey: "sk-lf-...",
248
- * });
249
- *
250
- * // Ensure cleanup on shutdown
251
- * process.on("SIGTERM", () => tracing.shutdown());
252
- * ```
253
- */
254
-
255
- type _tracingModule_ObservationKind = ObservationKind;
256
- type _tracingModule_ObserveClaudeOptions = ObserveClaudeOptions;
257
- type _tracingModule_ObserveOptions = ObserveOptions;
258
- type _tracingModule_TracingConfig = TracingConfig;
259
- type _tracingModule_TracingState = TracingState;
260
- declare const _tracingModule_flush: typeof flush;
261
- declare const _tracingModule_init: typeof init;
262
- declare const _tracingModule_isGatewayConfigured: typeof isGatewayConfigured;
263
- declare const _tracingModule_isInitialized: typeof isInitialized;
264
- declare const _tracingModule_observe: typeof observe;
265
- declare const _tracingModule_observeAnthropic: typeof observeAnthropic;
266
- declare const _tracingModule_observeClaude: typeof observeClaude;
267
- declare const _tracingModule_observeOpenAI: typeof observeOpenAI;
268
- declare const _tracingModule_shutdown: typeof shutdown;
269
- declare namespace _tracingModule {
270
- export { type _tracingModule_ObservationKind as ObservationKind, type _tracingModule_ObserveClaudeOptions as ObserveClaudeOptions, type _tracingModule_ObserveOptions as ObserveOptions, type _tracingModule_TracingConfig as TracingConfig, type _tracingModule_TracingState as TracingState, _tracingModule_flush as flush, _tracingModule_init as init, _tracingModule_isGatewayConfigured as isGatewayConfigured, _tracingModule_isInitialized as isInitialized, _tracingModule_observe as observe, _tracingModule_observeAnthropic as observeAnthropic, _tracingModule_observeClaude as observeClaude, _tracingModule_observeOpenAI as observeOpenAI, _tracingModule_shutdown as shutdown };
271
- }
272
-
273
- export { type ObservationKind as O, type TracingConfig as T, _tracingModule as _, type ObserveClaudeOptions as a, type ObserveOptions as b, type TracingState as c, isGatewayConfigured as d, isInitialized as e, flush as f, observeAnthropic as g, observeClaude as h, init as i, observeOpenAI as j, observe as o, shutdown as s };