@withgateway/sdk 0.1.7 → 0.1.9

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.
@@ -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-CubrUmOe.mjs';
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-CTc8iOrx.mjs';
2
2
  import '@opentelemetry/api';
3
3
  import '@opentelemetry/sdk-trace-base';
@@ -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-CubrUmOe.js';
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-CTc8iOrx.js';
2
2
  import '@opentelemetry/api';
3
3
  import '@opentelemetry/sdk-trace-base';
@@ -3,6 +3,9 @@ var __defProp = Object.defineProperty;
3
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __commonJS = (cb, mod) => function __require() {
7
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
8
+ };
6
9
  var __export = (target, all) => {
7
10
  for (var name in all)
8
11
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -17,6 +20,148 @@ var __copyProps = (to, from, except, desc) => {
17
20
  };
18
21
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
22
 
23
+ // package.json
24
+ var require_package = __commonJS({
25
+ "package.json"(exports2, module2) {
26
+ module2.exports = {
27
+ name: "@withgateway/sdk",
28
+ version: "0.1.9",
29
+ description: "Gateway SDK for TypeScript - A/B experiments, tracing, and observability",
30
+ main: "./dist/index.js",
31
+ module: "./dist/index.mjs",
32
+ types: "./dist/index.d.ts",
33
+ exports: {
34
+ ".": {
35
+ types: "./dist/index.d.ts",
36
+ import: "./dist/index.mjs",
37
+ require: "./dist/index.js"
38
+ },
39
+ "./experiments": {
40
+ types: "./dist/experiments/index.d.ts",
41
+ import: "./dist/experiments/index.mjs",
42
+ require: "./dist/experiments/index.js"
43
+ },
44
+ "./context": {
45
+ types: "./dist/context/index.d.ts",
46
+ import: "./dist/context/index.mjs",
47
+ require: "./dist/context/index.js"
48
+ },
49
+ "./memory": {
50
+ types: "./dist/memory/index.d.ts",
51
+ import: "./dist/memory/index.mjs",
52
+ require: "./dist/memory/index.js"
53
+ },
54
+ "./personas": {
55
+ types: "./dist/personas/index.d.ts",
56
+ import: "./dist/personas/index.mjs",
57
+ require: "./dist/personas/index.js"
58
+ },
59
+ "./replay": {
60
+ types: "./dist/replay/index.d.ts",
61
+ import: "./dist/replay/index.mjs",
62
+ require: "./dist/replay/index.js"
63
+ },
64
+ "./sessions": {
65
+ types: "./dist/sessions/index.d.ts",
66
+ import: "./dist/sessions/index.mjs",
67
+ require: "./dist/sessions/index.js"
68
+ },
69
+ "./tracing": {
70
+ types: "./dist/tracing/index.d.ts",
71
+ import: "./dist/tracing/index.mjs",
72
+ require: "./dist/tracing/index.js"
73
+ },
74
+ "./security": {
75
+ types: "./dist/security/index.d.ts",
76
+ import: "./dist/security/index.mjs",
77
+ require: "./dist/security/index.js"
78
+ },
79
+ "./users": {
80
+ types: "./dist/users/index.d.ts",
81
+ import: "./dist/users/index.mjs",
82
+ require: "./dist/users/index.js"
83
+ }
84
+ },
85
+ files: [
86
+ "dist",
87
+ "README.md"
88
+ ],
89
+ publishConfig: {
90
+ access: "public"
91
+ },
92
+ scripts: {
93
+ build: "tsup",
94
+ dev: "tsup --watch",
95
+ typecheck: "tsc --noEmit",
96
+ test: "vitest",
97
+ "test:run": "vitest run",
98
+ lint: "eslint src --ext .ts",
99
+ clean: "rm -rf dist",
100
+ example: "tsx examples/test-ab-experiment.ts",
101
+ "test:crm": "tsx examples/test-crm-ab-experiment.ts",
102
+ "test:crm:balanced": "tsx examples/test-crm-ab-experiment.ts --balanced",
103
+ "test:crm:full": "tsx examples/test-crm-ab-experiment.ts --users 12 --all-tasks --concurrency 3"
104
+ },
105
+ keywords: [
106
+ "gateway",
107
+ "ab-testing",
108
+ "experiments",
109
+ "opentelemetry",
110
+ "tracing",
111
+ "observability",
112
+ "llm"
113
+ ],
114
+ author: "Gateway Team",
115
+ license: "MIT",
116
+ engines: {
117
+ node: ">=18.0.0"
118
+ },
119
+ peerDependencies: {
120
+ "@opentelemetry/api": "^1.0.0",
121
+ "@opentelemetry/exporter-trace-otlp-http": ">=0.50.0",
122
+ "@opentelemetry/resources": ">=1.0.0",
123
+ "@opentelemetry/sdk-trace-base": ">=1.0.0",
124
+ "@opentelemetry/sdk-trace-node": ">=1.0.0"
125
+ },
126
+ peerDependenciesMeta: {
127
+ "@opentelemetry/api": {
128
+ optional: true
129
+ },
130
+ "@opentelemetry/sdk-trace-base": {
131
+ optional: true
132
+ },
133
+ "@opentelemetry/sdk-trace-node": {
134
+ optional: true
135
+ },
136
+ "@opentelemetry/exporter-trace-otlp-http": {
137
+ optional: true
138
+ },
139
+ "@opentelemetry/resources": {
140
+ optional: true
141
+ }
142
+ },
143
+ optionalDependencies: {
144
+ "@arizeai/openinference-instrumentation-anthropic": "^0.1.15",
145
+ "@arizeai/openinference-instrumentation-openai": "^4.1.5"
146
+ },
147
+ devDependencies: {
148
+ "@anthropic-ai/sdk": "^0.79.0",
149
+ "@opentelemetry/api": "^1.9.0",
150
+ "@opentelemetry/exporter-trace-otlp-http": "^0.212.0",
151
+ "@opentelemetry/resources": "^2.6.0",
152
+ "@opentelemetry/sdk-trace-base": "^1.30.1",
153
+ "@opentelemetry/sdk-trace-node": "^2.6.0",
154
+ "@opentelemetry/semantic-conventions": "^1.40.0",
155
+ "@types/node": "^20.0.0",
156
+ tsup: "^8.0.0",
157
+ tsx: "^4.0.0",
158
+ typescript: "^5.0.0",
159
+ vitest: "^2.0.0"
160
+ }
161
+ };
162
+ }
163
+ });
164
+
20
165
  // src/tracing/index.ts
21
166
  var tracing_exports = {};
22
167
  __export(tracing_exports, {
@@ -111,6 +256,58 @@ var UsersClient = class _UsersClient {
111
256
  await this.requestJson("POST", "/api/public/user-profiles", body)
112
257
  );
113
258
  }
259
+ /**
260
+ * Record a VALUE EVENT for a user — the per-user ROI stream. `value` is
261
+ * whatever the event is worth in your terms (minutes saved, revenue…);
262
+ * Gateway sums it in the hours-saved/ROI rollups, and evals and task-set
263
+ * replays can assert against the events. Link `traceId`/`sessionId` to tie
264
+ * the event to the run that produced it.
265
+ *
266
+ * @example
267
+ * ```ts
268
+ * await client.trackEvent("user-123", "checkout_completed", {
269
+ * value: 25,
270
+ * metadata: { cartSize: 3 },
271
+ * sessionId,
272
+ * });
273
+ * ```
274
+ */
275
+ async trackEvent(userId, event, options = {}) {
276
+ const body = {
277
+ userId,
278
+ event,
279
+ metadata: options.metadata ?? {},
280
+ ...options.value !== void 0 ? { value: options.value } : {},
281
+ ...options.traceId !== void 0 ? { traceId: options.traceId } : {},
282
+ ...options.sessionId !== void 0 ? { sessionId: options.sessionId } : {}
283
+ };
284
+ return parseEvent(
285
+ await this.requestJson("POST", "/api/public/user-events", body)
286
+ );
287
+ }
288
+ /** List a project's user events, optionally filtered by user/event/time. */
289
+ async listEvents(filter = {}) {
290
+ const params = new URLSearchParams();
291
+ if (filter.userId) params.set("userId", filter.userId);
292
+ if (filter.event) params.set("event", filter.event);
293
+ if (filter.fromTimestamp)
294
+ params.set("fromTimestamp", filter.fromTimestamp.toISOString());
295
+ if (filter.toTimestamp)
296
+ params.set("toTimestamp", filter.toTimestamp.toISOString());
297
+ if (filter.page) params.set("page", String(filter.page));
298
+ if (filter.limit) params.set("limit", String(filter.limit));
299
+ const qs = params.toString();
300
+ const payload = await this.requestJson(
301
+ "GET",
302
+ `/api/public/user-events${qs ? `?${qs}` : ""}`
303
+ );
304
+ const rows = Array.isArray(payload.data) ? payload.data : [];
305
+ const meta = payload.meta && typeof payload.meta === "object" ? payload.meta : {};
306
+ return {
307
+ data: rows.map((row) => parseEvent(row)),
308
+ totalItems: Number(meta.totalItems ?? rows.length)
309
+ };
310
+ }
114
311
  async requestJson(method, path, payload) {
115
312
  let response;
116
313
  try {
@@ -149,6 +346,18 @@ var UsersClient = class _UsersClient {
149
346
  }
150
347
  }
151
348
  };
349
+ function parseEvent(payload) {
350
+ return {
351
+ id: String(payload.id ?? ""),
352
+ userId: String(payload.userId ?? ""),
353
+ event: String(payload.event ?? ""),
354
+ value: typeof payload.value === "number" ? payload.value : null,
355
+ metadata: payload.metadata && typeof payload.metadata === "object" && !Array.isArray(payload.metadata) ? payload.metadata : {},
356
+ traceId: typeof payload.traceId === "string" ? payload.traceId : null,
357
+ sessionId: typeof payload.sessionId === "string" ? payload.sessionId : null,
358
+ createdAt: typeof payload.createdAt === "string" ? new Date(payload.createdAt) : /* @__PURE__ */ new Date(0)
359
+ };
360
+ }
152
361
  function parseProfile(payload) {
153
362
  return {
154
363
  userId: String(payload.userId ?? ""),
@@ -241,6 +450,109 @@ function debugLog(message, ...args) {
241
450
  }
242
451
  }
243
452
 
453
+ // src/build/index.ts
454
+ var import_node_crypto = require("crypto");
455
+ function canonicalJson(value) {
456
+ if (value === null || typeof value !== "object") {
457
+ return JSON.stringify(value);
458
+ }
459
+ if (Array.isArray(value)) {
460
+ return `[${value.map(canonicalJson).join(",")}]`;
461
+ }
462
+ const entries = Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
463
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(",")}}`;
464
+ }
465
+ function sha256(text) {
466
+ return `sha256:${(0, import_node_crypto.createHash)("sha256").update(text).digest("hex")}`;
467
+ }
468
+ var registeredTools = /* @__PURE__ */ new Map();
469
+ var registeredPrompts = /* @__PURE__ */ new Map();
470
+ function getRegisteredTools() {
471
+ return [...registeredTools.values()].sort(
472
+ (a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0
473
+ );
474
+ }
475
+ function getRegisteredPrompts() {
476
+ return Object.fromEntries(
477
+ [...registeredPrompts.entries()].sort(
478
+ ([a], [b]) => a < b ? -1 : a > b ? 1 : 0
479
+ )
480
+ );
481
+ }
482
+ function sdkVersion() {
483
+ try {
484
+ const pkg = require_package();
485
+ return `@withgateway/sdk@${pkg.version ?? "unknown"}`;
486
+ } catch {
487
+ return "@withgateway/sdk";
488
+ }
489
+ }
490
+ function codeRef() {
491
+ const sha = process.env.GATEWAY_COMMIT ?? process.env.GITHUB_SHA ?? process.env.CI_COMMIT_SHA ?? // GitLab
492
+ process.env.CIRCLE_SHA1;
493
+ if (!sha) return void 0;
494
+ const repo = process.env.GITHUB_REPOSITORY ?? process.env.CI_PROJECT_PATH;
495
+ return repo ? `git:${repo}@${sha}` : `git:${sha}`;
496
+ }
497
+ function assembleManifest(agentId) {
498
+ return {
499
+ agentId,
500
+ ...codeRef() ? { codeRef: codeRef() } : {},
501
+ sdk: sdkVersion(),
502
+ tools: getRegisteredTools(),
503
+ prompts: getRegisteredPrompts()
504
+ };
505
+ }
506
+ function computeBuildHash(manifest) {
507
+ const identity = {
508
+ ...manifest,
509
+ tools: manifest.tools.map(({ source: _source, ...tool }) => tool)
510
+ };
511
+ return sha256(canonicalJson(identity));
512
+ }
513
+ function attributionFromEnv() {
514
+ const attribution = { source: "runtime" };
515
+ if (process.env.GITHUB_ACTIONS) attribution.source = "ci";
516
+ if (process.env.GITHUB_ACTOR) attribution.githubLogin = process.env.GITHUB_ACTOR;
517
+ const sha = process.env.GATEWAY_COMMIT ?? process.env.GITHUB_SHA;
518
+ if (sha) attribution.commitSha = sha;
519
+ if (process.env.GITHUB_REPOSITORY) attribution.repo = process.env.GITHUB_REPOSITORY;
520
+ const branch = process.env.GITHUB_HEAD_REF ?? process.env.GITHUB_REF_NAME;
521
+ if (branch) attribution.branch = branch;
522
+ const ref = process.env.GITHUB_REF ?? "";
523
+ const prMatch = /refs\/pull\/(\d+)\//.exec(ref);
524
+ if (prMatch) attribution.prNumber = Number(prMatch[1]);
525
+ return attribution;
526
+ }
527
+ async function registerBuild(params) {
528
+ const auth = Buffer.from(`${params.publicKey}:${params.secretKey}`).toString(
529
+ "base64"
530
+ );
531
+ const response = await fetch(
532
+ `${params.host.replace(/\/$/, "")}/api/public/agent-builds`,
533
+ {
534
+ method: "POST",
535
+ headers: {
536
+ Authorization: `Basic ${auth}`,
537
+ "Content-Type": "application/json"
538
+ },
539
+ body: JSON.stringify({
540
+ agentId: params.agentId,
541
+ buildHash: params.buildHash,
542
+ ...params.version ? { semanticVer: params.version } : {},
543
+ manifest: params.manifest,
544
+ attribution: attributionFromEnv()
545
+ }),
546
+ signal: AbortSignal.timeout(15e3)
547
+ }
548
+ );
549
+ if (!response.ok) {
550
+ throw new Error(
551
+ `build registration failed (${response.status}): ${(await response.text()).slice(0, 300)}`
552
+ );
553
+ }
554
+ }
555
+
244
556
  // src/tracing/init.ts
245
557
  var ENV_VARS = {
246
558
  HOST: "GATEWAY_HOST",
@@ -319,6 +631,24 @@ function buildProvider(config, logFn) {
319
631
  if (config.version) {
320
632
  resourceAttrs["gateway.version"] = config.version;
321
633
  }
634
+ let buildInfo = null;
635
+ if (config.agent) {
636
+ const manifest = assembleManifest(config.agent);
637
+ const buildHash = computeBuildHash(manifest);
638
+ buildInfo = { manifest, buildHash };
639
+ resourceAttrs["gateway.agent.id"] = config.agent;
640
+ resourceAttrs["gateway.build.hash"] = buildHash;
641
+ if (config.version) {
642
+ resourceAttrs["gateway.agent.version"] = config.version;
643
+ }
644
+ logFn(
645
+ "Agent build identity: %s @ %s (%d tools, %d prompts)",
646
+ config.agent,
647
+ buildHash.slice(0, 15),
648
+ manifest.tools.length,
649
+ Object.keys(manifest.prompts).length
650
+ );
651
+ }
322
652
  let isLocalhost = false;
323
653
  if (endpoint) {
324
654
  try {
@@ -378,7 +708,28 @@ function buildProvider(config, logFn) {
378
708
  spanProcessors
379
709
  });
380
710
  }
381
- return provider;
711
+ return {
712
+ provider,
713
+ buildInfo,
714
+ connection: { host, publicKey, secretKey }
715
+ };
716
+ }
717
+ function scheduleBuildRegistration(config, built) {
718
+ if (!config.agent || !built.buildInfo || config.registerBuild === false) {
719
+ return;
720
+ }
721
+ const { manifest, buildHash } = built.buildInfo;
722
+ void registerBuild({
723
+ host: built.connection.host,
724
+ publicKey: built.connection.publicKey,
725
+ secretKey: built.connection.secretKey,
726
+ agentId: config.agent,
727
+ version: config.version,
728
+ manifest,
729
+ buildHash
730
+ }).catch((err) => {
731
+ warn("Build registration failed (agent keeps running):", err);
732
+ });
382
733
  }
383
734
  function init(config = {}) {
384
735
  if (state.initialized) {
@@ -386,8 +737,10 @@ function init(config = {}) {
386
737
  return;
387
738
  }
388
739
  state.debug = config.debug ?? false;
389
- const provider = buildProvider(config, log);
740
+ const built = buildProvider(config, log);
741
+ const provider = built.provider;
390
742
  provider.register();
743
+ scheduleBuildRegistration(config, built);
391
744
  state.provider = provider;
392
745
  state.initialized = true;
393
746
  log(
@@ -398,7 +751,9 @@ function init(config = {}) {
398
751
  function initIsolated(config = {}) {
399
752
  const debugLog2 = config.debug ? (message, ...args) => console.log(`[gatewaysdk.tracing:isolated] ${message}`, ...args) : () => {
400
753
  };
401
- const provider = buildProvider(config, debugLog2);
754
+ const built = buildProvider(config, debugLog2);
755
+ const provider = built.provider;
756
+ scheduleBuildRegistration(config, built);
402
757
  const tracer = provider.getTracer("@withgateway/sdk");
403
758
  debugLog2(
404
759
  "Isolated tracing provider created (service=%s)",