@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,447 @@
1
+ import { Context, Tracer } from '@opentelemetry/api';
2
+ import { SpanProcessor, Span, ReadableSpan } from '@opentelemetry/sdk-trace-base';
3
+
4
+ /**
5
+ * End-user identity for GatewaySDK tracing.
6
+ *
7
+ * Mirrors the Python SDK's `gatewaysdk.tracing.identity` user half:
8
+ *
9
+ * - The ambient user is set via `identify()` and stored in an
10
+ * AsyncLocalStorage (the TS analogue of Python's ContextVar), so
11
+ * concurrent requests serving different users never bleed into each other.
12
+ * - `IdentitySpanProcessor` (registered by `tracing.init()`) stamps the
13
+ * ambient user on every span at start, so everything traced after
14
+ * `identify()` is attributed automatically — the same seam as Python's
15
+ * `TracingContextSpanProcessor` and this SDK's `ExperimentSpanProcessor`.
16
+ * - `identify()` also stamps the currently open span directly, because
17
+ * ingestion treats `gateway.user.id` on ANY span as a trace-level update —
18
+ * the in-flight trace is attributed immediately.
19
+ */
20
+
21
+ declare const USER_ID_ATTRIBUTE = "gateway.user.id";
22
+ /**
23
+ * The active end-user id: identify() context > GATEWAY_USER_ID env.
24
+ *
25
+ * Per-request user attribution (e.g. from auth middleware) can also override
26
+ * per span by setting the `gateway.user.id` attribute directly — explicit
27
+ * set wins over the ambient default stamped at span start.
28
+ */
29
+ declare function resolveUserId(): string | undefined;
30
+ interface IdentifyOptions {
31
+ /** Profile attributes to merge into the user's stored profile. */
32
+ attributes?: Record<string, string | number | boolean>;
33
+ displayName?: string;
34
+ email?: string;
35
+ }
36
+ /**
37
+ * Attribute everything that follows (and the current trace) to a user.
38
+ *
39
+ * - Sets the user for all spans started in this async context, and stamps
40
+ * the currently open span so the in-flight trace is attributed immediately.
41
+ * - When `attributes`/`displayName`/`email` are given, the user's platform
42
+ * profile is updated in the background (attributes merge with what's
43
+ * stored — ideal for incremental ROI facts like plan or account_value).
44
+ * Requires GATEWAY_HOST/GATEWAY_PUBLIC_KEY/GATEWAY_SECRET_KEY for the
45
+ * profile update; tracing attribution works without them. Failures are
46
+ * swallowed (debug-logged) and never produce unhandled rejections.
47
+ *
48
+ * @example
49
+ * ```typescript
50
+ * import { identify } from "@withgateway/sdk";
51
+ *
52
+ * identify("user-123", {
53
+ * attributes: { plan: "enterprise", account_value: "48000" },
54
+ * });
55
+ * ```
56
+ */
57
+ declare function identify(userId: string, options?: IdentifyOptions): void;
58
+ /** Testing hook: clear the ambient user for the current async context. */
59
+ declare function resetAmbientUser(): void;
60
+ /**
61
+ * Stamps the ambient end-user identity (identify() context or
62
+ * GATEWAY_USER_ID env) on every span at start. Registered automatically by
63
+ * `tracing.init()`. Explicit `setAttribute` calls after span start win over
64
+ * this ambient default.
65
+ */
66
+ declare class IdentitySpanProcessor implements SpanProcessor {
67
+ onStart(span: Span, _parentContext: Context): void;
68
+ onEnd(_span: ReadableSpan): void;
69
+ shutdown(): Promise<void>;
70
+ forceFlush(): Promise<void>;
71
+ }
72
+
73
+ /**
74
+ * Types for the tracing module.
75
+ */
76
+ interface TracingConfig {
77
+ /**
78
+ * Gateway server URL (e.g., "https://app.gateway.dev").
79
+ * Falls back to GATEWAY_HOST or GATEWAY_HOST env var.
80
+ */
81
+ host?: string;
82
+ /**
83
+ * Public key for authentication (pk-lf-...).
84
+ * Falls back to GATEWAY_PUBLIC_KEY or GATEWAY_PUBLIC_KEY env var.
85
+ */
86
+ publicKey?: string;
87
+ /**
88
+ * Secret key for authentication (sk-lf-...).
89
+ * Falls back to GATEWAY_SECRET_KEY or GATEWAY_SECRET_KEY env var.
90
+ */
91
+ secretKey?: string;
92
+ /**
93
+ * Service name for resource attributes.
94
+ * Defaults to "gatewaysdk-tracing".
95
+ */
96
+ serviceName?: string;
97
+ /**
98
+ * Environment name (e.g., "production", "staging").
99
+ * Sets resource attribute for filtering traces in Gateway.
100
+ */
101
+ environment?: string;
102
+ /**
103
+ * Application version (e.g., "1.2.3", git SHA).
104
+ * Sets resource attribute for tracking regressions.
105
+ */
106
+ version?: string;
107
+ /**
108
+ * Whether to enable debug logging to console.
109
+ * Defaults to false.
110
+ */
111
+ debug?: boolean;
112
+ /**
113
+ * Whether to automatically add ExperimentSpanProcessor when imported
114
+ * from the main entry ("@withgateway/sdk"). Has no effect when imported
115
+ * from the subpath ("@withgateway/sdk/tracing") — use customSpanProcessors
116
+ * instead.
117
+ * Defaults to true.
118
+ */
119
+ enableExperiments?: boolean;
120
+ /**
121
+ * Additional span processors to register with the provider.
122
+ * These are added before the BatchSpanProcessor (which handles export).
123
+ *
124
+ * When using the main entry (`import { tracing } from "@withgateway/sdk"`),
125
+ * ExperimentSpanProcessor is automatically added unless enableExperiments
126
+ * is false. When using the subpath import, pass it here manually:
127
+ *
128
+ * @example
129
+ * ```typescript
130
+ * import * as tracing from "@withgateway/sdk/tracing";
131
+ * import { ExperimentSpanProcessor } from "@withgateway/sdk/experiments";
132
+ *
133
+ * tracing.init({ customSpanProcessors: [new ExperimentSpanProcessor()] });
134
+ * ```
135
+ */
136
+ customSpanProcessors?: unknown[];
137
+ /**
138
+ * Custom OTLP endpoint URL. If not provided, derived from host.
139
+ */
140
+ endpoint?: string;
141
+ /**
142
+ * Batch processor configuration.
143
+ */
144
+ batch?: {
145
+ /** Max spans buffered in memory. Default: 2048 */
146
+ maxQueueSize?: number;
147
+ /** How often to flush spans (ms). Default: 5000 */
148
+ scheduledDelayMillis?: number;
149
+ /** Max spans per export call. Default: 512 */
150
+ maxExportBatchSize?: number;
151
+ };
152
+ }
153
+ interface TracingState {
154
+ initialized: boolean;
155
+ provider: unknown | null;
156
+ }
157
+
158
+ /**
159
+ * Initialization and lifecycle management for GatewaySDK tracing.
160
+ *
161
+ * This module provides the core init(), shutdown(), and flush() functions
162
+ * for managing the OpenTelemetry TracerProvider lifecycle, plus
163
+ * initIsolated() for creating additional self-contained providers (e.g. one
164
+ * process exporting different agents to different Gateway projects).
165
+ *
166
+ * Mirrors the Python SDK's tracing.init() for a consistent developer experience.
167
+ */
168
+
169
+ /**
170
+ * Handle to an isolated tracing provider created by initIsolated().
171
+ * Spans started from `tracer` export to that provider's Gateway project;
172
+ * the global tracer (from init()) is untouched.
173
+ */
174
+ interface TracingHandle {
175
+ tracer: Tracer;
176
+ /** Force-flush pending spans for this provider only. */
177
+ flush(): Promise<void>;
178
+ /** Flush and shut down this provider only. */
179
+ shutdown(): Promise<void>;
180
+ }
181
+ /**
182
+ * Initialize GatewaySDK tracing with automatic OpenTelemetry configuration.
183
+ *
184
+ * This function configures OpenTelemetry with a connection to Gateway
185
+ * and sets up the ExperimentSpanProcessor for automatic experiment tagging.
186
+ *
187
+ * @example
188
+ * ```typescript
189
+ * import { tracing } from "@withgateway/sdk";
190
+ *
191
+ * // Using environment variables (GATEWAY_HOST, GATEWAY_PUBLIC_KEY, GATEWAY_SECRET_KEY)
192
+ * tracing.init();
193
+ *
194
+ * // Or with explicit configuration
195
+ * tracing.init({
196
+ * host: "https://app.gateway.dev",
197
+ * publicKey: "pk-lf-...",
198
+ * secretKey: "sk-lf-...",
199
+ * serviceName: "my-agent",
200
+ * environment: "production",
201
+ * });
202
+ * ```
203
+ */
204
+ declare function init(config?: TracingConfig): void;
205
+ /**
206
+ * Create an ISOLATED tracing provider that is NOT registered globally.
207
+ *
208
+ * Use this when one process must export different work to different Gateway
209
+ * projects (e.g. a server hosting several agents, each with its own project
210
+ * keys), or when the process already has its own global OpenTelemetry
211
+ * provider that must not be replaced.
212
+ *
213
+ * Spans only reach the isolated provider when started from its `tracer` —
214
+ * pass it explicitly to observe()/observeClaude() via their `tracer` option,
215
+ * or to a framework's telemetry hook (e.g. the Vercel AI SDK's
216
+ * `experimental_telemetry.tracer`). Context propagation still works across
217
+ * providers, so nesting behaves exactly as with init().
218
+ *
219
+ * Can be called any number of times; each handle has its own exporter,
220
+ * batch queue, and lifecycle.
221
+ *
222
+ * @example
223
+ * ```typescript
224
+ * import { tracing } from "@withgateway/sdk";
225
+ *
226
+ * const support = tracing.initIsolated({
227
+ * host: "https://app.gateway.dev",
228
+ * publicKey: "pk-lf-support...",
229
+ * secretKey: "sk-lf-support...",
230
+ * serviceName: "support-agent",
231
+ * });
232
+ *
233
+ * await tracing.observe("support.run", run, { tracer: support.tracer });
234
+ * await support.flush();
235
+ * ```
236
+ */
237
+ declare function initIsolated(config?: TracingConfig): TracingHandle;
238
+ /**
239
+ * Force flush all pending spans without shutting down.
240
+ *
241
+ * Useful for ensuring spans are exported at specific points
242
+ * (e.g., after completing a batch of work) without ending the tracing session.
243
+ *
244
+ * @returns Promise that resolves when flush completes
245
+ */
246
+ declare function flush(): Promise<void>;
247
+ /**
248
+ * Force flush all pending spans and shutdown the tracer provider.
249
+ *
250
+ * This function should be called before process exit to ensure all spans
251
+ * are exported. It is safe to call multiple times.
252
+ *
253
+ * @example
254
+ * ```typescript
255
+ * import { tracing } from "@withgateway/sdk";
256
+ *
257
+ * tracing.init();
258
+ *
259
+ * // On shutdown
260
+ * process.on("SIGTERM", async () => {
261
+ * await tracing.shutdown();
262
+ * process.exit(0);
263
+ * });
264
+ * ```
265
+ */
266
+ declare function shutdown(): Promise<void>;
267
+ /**
268
+ * Check if tracing has been initialized.
269
+ */
270
+ declare function isInitialized(): boolean;
271
+ /**
272
+ * Check if Gateway is configured via environment variables.
273
+ */
274
+ declare function isGatewayConfigured(): boolean;
275
+
276
+ type ObservationKind = "AGENT" | "CHAIN" | "TOOL" | "LLM" | "RETRIEVER";
277
+ interface ObserveOptions {
278
+ /** Recorded as input.value on the span (JSON-stringified if not a string). */
279
+ input?: unknown;
280
+ /** OpenInference span kind. Defaults to "AGENT" for the outer run. */
281
+ kind?: ObservationKind;
282
+ /**
283
+ * When true (default), the callback's return value is recorded as
284
+ * output.value. Set false if the return value is large/uninteresting.
285
+ */
286
+ captureOutput?: boolean;
287
+ /**
288
+ * Tracer to start the span from. Defaults to the GLOBAL tracer (set up by
289
+ * tracing.init()). Pass an initIsolated() handle's tracer to route this
290
+ * observation to that handle's Gateway project instead.
291
+ */
292
+ tracer?: Tracer;
293
+ /**
294
+ * Extra attributes for the span — e.g. gateway.session.id /
295
+ * gateway.user.id to group runs into a session and attribute them to a user.
296
+ */
297
+ attributes?: Record<string, string>;
298
+ }
299
+ /**
300
+ * Run `fn` inside a span named `name`. Anything traced inside (auto-instrumented
301
+ * client calls, nested observe() calls) nests under it, forming one trace.
302
+ *
303
+ * @example
304
+ * ```ts
305
+ * const result = await observe("my-agent.run", async () => {
306
+ * // client.chat.completions.create(...) here becomes a child GENERATION
307
+ * return finalText;
308
+ * }, { input: prompt });
309
+ * ```
310
+ */
311
+ declare function observe<T>(name: string, fn: () => Promise<T>, options?: ObserveOptions): Promise<T>;
312
+
313
+ /**
314
+ * Client wrappers that turn an SDK's calls into spans on the Gateway provider.
315
+ *
316
+ * Node ESM can't retroactively patch a module the app already imported, so — as
317
+ * Langfuse does with `observeOpenAI` — the app hands us the client and we
318
+ * instrument it explicitly. One SDK call, no OpenTelemetry in the app.
319
+ *
320
+ * The OpenInference instrumentations are bundled optional deps of this package;
321
+ * we load them with require() (the ESM build injects a real createRequire).
322
+ */
323
+ /**
324
+ * Instrument an OpenAI client so its requests become GENERATION spans on the
325
+ * Gateway provider. Returns the same client (its class prototype is patched, so
326
+ * this and every other instance of that client are traced).
327
+ *
328
+ * @example
329
+ * ```ts
330
+ * import OpenAI from "openai";
331
+ * import { init, observeOpenAI } from "@withgateway/sdk/tracing";
332
+ * init();
333
+ * const client = observeOpenAI(new OpenAI());
334
+ * ```
335
+ */
336
+ declare function observeOpenAI<T extends object>(client: T): T;
337
+ /**
338
+ * Instrument an Anthropic client so its requests become GENERATION spans.
339
+ *
340
+ * @example
341
+ * ```ts
342
+ * import Anthropic from "@anthropic-ai/sdk";
343
+ * import { init, observeAnthropic } from "@withgateway/sdk/tracing";
344
+ * init();
345
+ * const client = observeAnthropic(new Anthropic());
346
+ * ```
347
+ */
348
+ declare function observeAnthropic<T extends object>(client: T): T;
349
+
350
+ /**
351
+ * observeClaude() — trace a Claude Agent SDK run.
352
+ *
353
+ * The Claude Agent SDK runs the agent in a separate `claude` CLI subprocess, so
354
+ * there's nothing in-process to patch. What the app has is the message stream it
355
+ * iterates. Wrap that stream with observeClaude() and it yields the same
356
+ * messages unchanged while emitting spans on the Gateway provider:
357
+ *
358
+ * AGENT (root)
359
+ * ├─ GENERATION per assistant turn (with per-turn token usage)
360
+ * └─ TOOL per tool call (input from tool_use, output from the
361
+ * matching tool_result, matched by id)
362
+ *
363
+ * The TS equivalent of the Python SDK's claude-agent-sdk instrumentor.
364
+ *
365
+ * @example
366
+ * ```ts
367
+ * const stream = query({ prompt, options });
368
+ * for await (const message of observeClaude(stream, { name, input: prompt })) {
369
+ * // ...consume messages as usual
370
+ * }
371
+ * ```
372
+ */
373
+
374
+ interface ObserveClaudeOptions {
375
+ /** Root span name (becomes the trace name). */
376
+ name: string;
377
+ /** Recorded as input.value on the root span → trace-level input. */
378
+ input?: string;
379
+ /** Model label for the generation spans. */
380
+ model?: string;
381
+ /**
382
+ * Tracer to start spans from. Defaults to the GLOBAL tracer (set up by
383
+ * tracing.init()). Pass an initIsolated() handle's tracer to route this
384
+ * run to that handle's Gateway project instead.
385
+ */
386
+ tracer?: Tracer;
387
+ /**
388
+ * Extra attributes for the ROOT span — e.g. gateway.session.id /
389
+ * gateway.user.id to group runs into a session and attribute them to a user.
390
+ */
391
+ attributes?: Record<string, string>;
392
+ }
393
+ declare function observeClaude(stream: AsyncIterable<any>, options: ObserveClaudeOptions): AsyncGenerator<any>;
394
+
395
+ /**
396
+ * Tracing module for GatewaySDK TypeScript SDK.
397
+ *
398
+ * Provides a simple init() function that configures OpenTelemetry with
399
+ * Gateway, mirroring the Python SDK's tracing.init() experience.
400
+ *
401
+ * @example
402
+ * ```typescript
403
+ * import { tracing } from "@withgateway/sdk";
404
+ *
405
+ * // Initialize with environment variables
406
+ * tracing.init();
407
+ *
408
+ * // Or with explicit configuration
409
+ * tracing.init({
410
+ * host: "https://app.gateway.dev",
411
+ * publicKey: "pk-lf-...",
412
+ * secretKey: "sk-lf-...",
413
+ * });
414
+ *
415
+ * // Ensure cleanup on shutdown
416
+ * process.on("SIGTERM", () => tracing.shutdown());
417
+ * ```
418
+ */
419
+
420
+ type _tracingModule_IdentifyOptions = IdentifyOptions;
421
+ type _tracingModule_IdentitySpanProcessor = IdentitySpanProcessor;
422
+ declare const _tracingModule_IdentitySpanProcessor: typeof IdentitySpanProcessor;
423
+ type _tracingModule_ObservationKind = ObservationKind;
424
+ type _tracingModule_ObserveClaudeOptions = ObserveClaudeOptions;
425
+ type _tracingModule_ObserveOptions = ObserveOptions;
426
+ type _tracingModule_TracingConfig = TracingConfig;
427
+ type _tracingModule_TracingHandle = TracingHandle;
428
+ type _tracingModule_TracingState = TracingState;
429
+ declare const _tracingModule_USER_ID_ATTRIBUTE: typeof USER_ID_ATTRIBUTE;
430
+ declare const _tracingModule_flush: typeof flush;
431
+ declare const _tracingModule_identify: typeof identify;
432
+ declare const _tracingModule_init: typeof init;
433
+ declare const _tracingModule_initIsolated: typeof initIsolated;
434
+ declare const _tracingModule_isGatewayConfigured: typeof isGatewayConfigured;
435
+ declare const _tracingModule_isInitialized: typeof isInitialized;
436
+ declare const _tracingModule_observe: typeof observe;
437
+ declare const _tracingModule_observeAnthropic: typeof observeAnthropic;
438
+ declare const _tracingModule_observeClaude: typeof observeClaude;
439
+ declare const _tracingModule_observeOpenAI: typeof observeOpenAI;
440
+ declare const _tracingModule_resetAmbientUser: typeof resetAmbientUser;
441
+ declare const _tracingModule_resolveUserId: typeof resolveUserId;
442
+ declare const _tracingModule_shutdown: typeof shutdown;
443
+ declare namespace _tracingModule {
444
+ export { type _tracingModule_IdentifyOptions as IdentifyOptions, _tracingModule_IdentitySpanProcessor as IdentitySpanProcessor, type _tracingModule_ObservationKind as ObservationKind, type _tracingModule_ObserveClaudeOptions as ObserveClaudeOptions, type _tracingModule_ObserveOptions as ObserveOptions, type _tracingModule_TracingConfig as TracingConfig, type _tracingModule_TracingHandle as TracingHandle, type _tracingModule_TracingState as TracingState, _tracingModule_USER_ID_ATTRIBUTE as USER_ID_ATTRIBUTE, _tracingModule_flush as flush, _tracingModule_identify as identify, _tracingModule_init as init, _tracingModule_initIsolated as initIsolated, _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_resetAmbientUser as resetAmbientUser, _tracingModule_resolveUserId as resolveUserId, _tracingModule_shutdown as shutdown };
445
+ }
446
+
447
+ export { type IdentifyOptions as I, type ObservationKind as O, type TracingConfig as T, USER_ID_ATTRIBUTE as U, _tracingModule as _, IdentitySpanProcessor as a, type ObserveClaudeOptions as b, type ObserveOptions as c, type TracingHandle as d, type TracingState as e, flush as f, init as g, initIsolated as h, identify as i, isGatewayConfigured as j, isInitialized as k, observeAnthropic as l, observeClaude as m, observeOpenAI as n, observe as o, resetAmbientUser as p, resolveUserId as r, shutdown as s };