@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,11 +1,157 @@
1
1
  import { createRequire as __gatewayCreateRequire } from "module";
2
2
  const require = __gatewayCreateRequire(import.meta.url);
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
4
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
4
5
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
5
6
  }) : x)(function(x) {
6
7
  if (typeof require !== "undefined") return require.apply(this, arguments);
7
8
  throw Error('Dynamic require of "' + x + '" is not supported');
8
9
  });
10
+ var __commonJS = (cb, mod) => function __require2() {
11
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
12
+ };
13
+
14
+ // package.json
15
+ var require_package = __commonJS({
16
+ "package.json"(exports, module) {
17
+ module.exports = {
18
+ name: "@withgateway/sdk",
19
+ version: "0.1.9",
20
+ description: "Gateway SDK for TypeScript - A/B experiments, tracing, and observability",
21
+ main: "./dist/index.js",
22
+ module: "./dist/index.mjs",
23
+ types: "./dist/index.d.ts",
24
+ exports: {
25
+ ".": {
26
+ types: "./dist/index.d.ts",
27
+ import: "./dist/index.mjs",
28
+ require: "./dist/index.js"
29
+ },
30
+ "./experiments": {
31
+ types: "./dist/experiments/index.d.ts",
32
+ import: "./dist/experiments/index.mjs",
33
+ require: "./dist/experiments/index.js"
34
+ },
35
+ "./context": {
36
+ types: "./dist/context/index.d.ts",
37
+ import: "./dist/context/index.mjs",
38
+ require: "./dist/context/index.js"
39
+ },
40
+ "./memory": {
41
+ types: "./dist/memory/index.d.ts",
42
+ import: "./dist/memory/index.mjs",
43
+ require: "./dist/memory/index.js"
44
+ },
45
+ "./personas": {
46
+ types: "./dist/personas/index.d.ts",
47
+ import: "./dist/personas/index.mjs",
48
+ require: "./dist/personas/index.js"
49
+ },
50
+ "./replay": {
51
+ types: "./dist/replay/index.d.ts",
52
+ import: "./dist/replay/index.mjs",
53
+ require: "./dist/replay/index.js"
54
+ },
55
+ "./sessions": {
56
+ types: "./dist/sessions/index.d.ts",
57
+ import: "./dist/sessions/index.mjs",
58
+ require: "./dist/sessions/index.js"
59
+ },
60
+ "./tracing": {
61
+ types: "./dist/tracing/index.d.ts",
62
+ import: "./dist/tracing/index.mjs",
63
+ require: "./dist/tracing/index.js"
64
+ },
65
+ "./security": {
66
+ types: "./dist/security/index.d.ts",
67
+ import: "./dist/security/index.mjs",
68
+ require: "./dist/security/index.js"
69
+ },
70
+ "./users": {
71
+ types: "./dist/users/index.d.ts",
72
+ import: "./dist/users/index.mjs",
73
+ require: "./dist/users/index.js"
74
+ }
75
+ },
76
+ files: [
77
+ "dist",
78
+ "README.md"
79
+ ],
80
+ publishConfig: {
81
+ access: "public"
82
+ },
83
+ scripts: {
84
+ build: "tsup",
85
+ dev: "tsup --watch",
86
+ typecheck: "tsc --noEmit",
87
+ test: "vitest",
88
+ "test:run": "vitest run",
89
+ lint: "eslint src --ext .ts",
90
+ clean: "rm -rf dist",
91
+ example: "tsx examples/test-ab-experiment.ts",
92
+ "test:crm": "tsx examples/test-crm-ab-experiment.ts",
93
+ "test:crm:balanced": "tsx examples/test-crm-ab-experiment.ts --balanced",
94
+ "test:crm:full": "tsx examples/test-crm-ab-experiment.ts --users 12 --all-tasks --concurrency 3"
95
+ },
96
+ keywords: [
97
+ "gateway",
98
+ "ab-testing",
99
+ "experiments",
100
+ "opentelemetry",
101
+ "tracing",
102
+ "observability",
103
+ "llm"
104
+ ],
105
+ author: "Gateway Team",
106
+ license: "MIT",
107
+ engines: {
108
+ node: ">=18.0.0"
109
+ },
110
+ peerDependencies: {
111
+ "@opentelemetry/api": "^1.0.0",
112
+ "@opentelemetry/exporter-trace-otlp-http": ">=0.50.0",
113
+ "@opentelemetry/resources": ">=1.0.0",
114
+ "@opentelemetry/sdk-trace-base": ">=1.0.0",
115
+ "@opentelemetry/sdk-trace-node": ">=1.0.0"
116
+ },
117
+ peerDependenciesMeta: {
118
+ "@opentelemetry/api": {
119
+ optional: true
120
+ },
121
+ "@opentelemetry/sdk-trace-base": {
122
+ optional: true
123
+ },
124
+ "@opentelemetry/sdk-trace-node": {
125
+ optional: true
126
+ },
127
+ "@opentelemetry/exporter-trace-otlp-http": {
128
+ optional: true
129
+ },
130
+ "@opentelemetry/resources": {
131
+ optional: true
132
+ }
133
+ },
134
+ optionalDependencies: {
135
+ "@arizeai/openinference-instrumentation-anthropic": "^0.1.15",
136
+ "@arizeai/openinference-instrumentation-openai": "^4.1.5"
137
+ },
138
+ devDependencies: {
139
+ "@anthropic-ai/sdk": "^0.79.0",
140
+ "@opentelemetry/api": "^1.9.0",
141
+ "@opentelemetry/exporter-trace-otlp-http": "^0.212.0",
142
+ "@opentelemetry/resources": "^2.6.0",
143
+ "@opentelemetry/sdk-trace-base": "^1.30.1",
144
+ "@opentelemetry/sdk-trace-node": "^2.6.0",
145
+ "@opentelemetry/semantic-conventions": "^1.40.0",
146
+ "@types/node": "^20.0.0",
147
+ tsup: "^8.0.0",
148
+ tsx: "^4.0.0",
149
+ typescript: "^5.0.0",
150
+ vitest: "^2.0.0"
151
+ }
152
+ };
153
+ }
154
+ });
9
155
 
10
156
  // src/tracing/identity.ts
11
157
  import { AsyncLocalStorage } from "async_hooks";
@@ -80,6 +226,58 @@ var UsersClient = class _UsersClient {
80
226
  await this.requestJson("POST", "/api/public/user-profiles", body)
81
227
  );
82
228
  }
229
+ /**
230
+ * Record a VALUE EVENT for a user — the per-user ROI stream. `value` is
231
+ * whatever the event is worth in your terms (minutes saved, revenue…);
232
+ * Gateway sums it in the hours-saved/ROI rollups, and evals and task-set
233
+ * replays can assert against the events. Link `traceId`/`sessionId` to tie
234
+ * the event to the run that produced it.
235
+ *
236
+ * @example
237
+ * ```ts
238
+ * await client.trackEvent("user-123", "checkout_completed", {
239
+ * value: 25,
240
+ * metadata: { cartSize: 3 },
241
+ * sessionId,
242
+ * });
243
+ * ```
244
+ */
245
+ async trackEvent(userId, event, options = {}) {
246
+ const body = {
247
+ userId,
248
+ event,
249
+ metadata: options.metadata ?? {},
250
+ ...options.value !== void 0 ? { value: options.value } : {},
251
+ ...options.traceId !== void 0 ? { traceId: options.traceId } : {},
252
+ ...options.sessionId !== void 0 ? { sessionId: options.sessionId } : {}
253
+ };
254
+ return parseEvent(
255
+ await this.requestJson("POST", "/api/public/user-events", body)
256
+ );
257
+ }
258
+ /** List a project's user events, optionally filtered by user/event/time. */
259
+ async listEvents(filter = {}) {
260
+ const params = new URLSearchParams();
261
+ if (filter.userId) params.set("userId", filter.userId);
262
+ if (filter.event) params.set("event", filter.event);
263
+ if (filter.fromTimestamp)
264
+ params.set("fromTimestamp", filter.fromTimestamp.toISOString());
265
+ if (filter.toTimestamp)
266
+ params.set("toTimestamp", filter.toTimestamp.toISOString());
267
+ if (filter.page) params.set("page", String(filter.page));
268
+ if (filter.limit) params.set("limit", String(filter.limit));
269
+ const qs = params.toString();
270
+ const payload = await this.requestJson(
271
+ "GET",
272
+ `/api/public/user-events${qs ? `?${qs}` : ""}`
273
+ );
274
+ const rows = Array.isArray(payload.data) ? payload.data : [];
275
+ const meta = payload.meta && typeof payload.meta === "object" ? payload.meta : {};
276
+ return {
277
+ data: rows.map((row) => parseEvent(row)),
278
+ totalItems: Number(meta.totalItems ?? rows.length)
279
+ };
280
+ }
83
281
  async requestJson(method, path, payload) {
84
282
  let response;
85
283
  try {
@@ -118,6 +316,18 @@ var UsersClient = class _UsersClient {
118
316
  }
119
317
  }
120
318
  };
319
+ function parseEvent(payload) {
320
+ return {
321
+ id: String(payload.id ?? ""),
322
+ userId: String(payload.userId ?? ""),
323
+ event: String(payload.event ?? ""),
324
+ value: typeof payload.value === "number" ? payload.value : null,
325
+ metadata: payload.metadata && typeof payload.metadata === "object" && !Array.isArray(payload.metadata) ? payload.metadata : {},
326
+ traceId: typeof payload.traceId === "string" ? payload.traceId : null,
327
+ sessionId: typeof payload.sessionId === "string" ? payload.sessionId : null,
328
+ createdAt: typeof payload.createdAt === "string" ? new Date(payload.createdAt) : /* @__PURE__ */ new Date(0)
329
+ };
330
+ }
121
331
  function parseProfile(payload) {
122
332
  return {
123
333
  userId: String(payload.userId ?? ""),
@@ -210,6 +420,109 @@ function debugLog(message, ...args) {
210
420
  }
211
421
  }
212
422
 
423
+ // src/build/index.ts
424
+ import { createHash } from "crypto";
425
+ function canonicalJson(value) {
426
+ if (value === null || typeof value !== "object") {
427
+ return JSON.stringify(value);
428
+ }
429
+ if (Array.isArray(value)) {
430
+ return `[${value.map(canonicalJson).join(",")}]`;
431
+ }
432
+ const entries = Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
433
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(",")}}`;
434
+ }
435
+ function sha256(text) {
436
+ return `sha256:${createHash("sha256").update(text).digest("hex")}`;
437
+ }
438
+ var registeredTools = /* @__PURE__ */ new Map();
439
+ var registeredPrompts = /* @__PURE__ */ new Map();
440
+ function getRegisteredTools() {
441
+ return [...registeredTools.values()].sort(
442
+ (a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0
443
+ );
444
+ }
445
+ function getRegisteredPrompts() {
446
+ return Object.fromEntries(
447
+ [...registeredPrompts.entries()].sort(
448
+ ([a], [b]) => a < b ? -1 : a > b ? 1 : 0
449
+ )
450
+ );
451
+ }
452
+ function sdkVersion() {
453
+ try {
454
+ const pkg = require_package();
455
+ return `@withgateway/sdk@${pkg.version ?? "unknown"}`;
456
+ } catch {
457
+ return "@withgateway/sdk";
458
+ }
459
+ }
460
+ function codeRef() {
461
+ const sha = process.env.GATEWAY_COMMIT ?? process.env.GITHUB_SHA ?? process.env.CI_COMMIT_SHA ?? // GitLab
462
+ process.env.CIRCLE_SHA1;
463
+ if (!sha) return void 0;
464
+ const repo = process.env.GITHUB_REPOSITORY ?? process.env.CI_PROJECT_PATH;
465
+ return repo ? `git:${repo}@${sha}` : `git:${sha}`;
466
+ }
467
+ function assembleManifest(agentId) {
468
+ return {
469
+ agentId,
470
+ ...codeRef() ? { codeRef: codeRef() } : {},
471
+ sdk: sdkVersion(),
472
+ tools: getRegisteredTools(),
473
+ prompts: getRegisteredPrompts()
474
+ };
475
+ }
476
+ function computeBuildHash(manifest) {
477
+ const identity = {
478
+ ...manifest,
479
+ tools: manifest.tools.map(({ source: _source, ...tool }) => tool)
480
+ };
481
+ return sha256(canonicalJson(identity));
482
+ }
483
+ function attributionFromEnv() {
484
+ const attribution = { source: "runtime" };
485
+ if (process.env.GITHUB_ACTIONS) attribution.source = "ci";
486
+ if (process.env.GITHUB_ACTOR) attribution.githubLogin = process.env.GITHUB_ACTOR;
487
+ const sha = process.env.GATEWAY_COMMIT ?? process.env.GITHUB_SHA;
488
+ if (sha) attribution.commitSha = sha;
489
+ if (process.env.GITHUB_REPOSITORY) attribution.repo = process.env.GITHUB_REPOSITORY;
490
+ const branch = process.env.GITHUB_HEAD_REF ?? process.env.GITHUB_REF_NAME;
491
+ if (branch) attribution.branch = branch;
492
+ const ref = process.env.GITHUB_REF ?? "";
493
+ const prMatch = /refs\/pull\/(\d+)\//.exec(ref);
494
+ if (prMatch) attribution.prNumber = Number(prMatch[1]);
495
+ return attribution;
496
+ }
497
+ async function registerBuild(params) {
498
+ const auth = Buffer.from(`${params.publicKey}:${params.secretKey}`).toString(
499
+ "base64"
500
+ );
501
+ const response = await fetch(
502
+ `${params.host.replace(/\/$/, "")}/api/public/agent-builds`,
503
+ {
504
+ method: "POST",
505
+ headers: {
506
+ Authorization: `Basic ${auth}`,
507
+ "Content-Type": "application/json"
508
+ },
509
+ body: JSON.stringify({
510
+ agentId: params.agentId,
511
+ buildHash: params.buildHash,
512
+ ...params.version ? { semanticVer: params.version } : {},
513
+ manifest: params.manifest,
514
+ attribution: attributionFromEnv()
515
+ }),
516
+ signal: AbortSignal.timeout(15e3)
517
+ }
518
+ );
519
+ if (!response.ok) {
520
+ throw new Error(
521
+ `build registration failed (${response.status}): ${(await response.text()).slice(0, 300)}`
522
+ );
523
+ }
524
+ }
525
+
213
526
  // src/tracing/init.ts
214
527
  var ENV_VARS = {
215
528
  HOST: "GATEWAY_HOST",
@@ -288,6 +601,24 @@ function buildProvider(config, logFn) {
288
601
  if (config.version) {
289
602
  resourceAttrs["gateway.version"] = config.version;
290
603
  }
604
+ let buildInfo = null;
605
+ if (config.agent) {
606
+ const manifest = assembleManifest(config.agent);
607
+ const buildHash = computeBuildHash(manifest);
608
+ buildInfo = { manifest, buildHash };
609
+ resourceAttrs["gateway.agent.id"] = config.agent;
610
+ resourceAttrs["gateway.build.hash"] = buildHash;
611
+ if (config.version) {
612
+ resourceAttrs["gateway.agent.version"] = config.version;
613
+ }
614
+ logFn(
615
+ "Agent build identity: %s @ %s (%d tools, %d prompts)",
616
+ config.agent,
617
+ buildHash.slice(0, 15),
618
+ manifest.tools.length,
619
+ Object.keys(manifest.prompts).length
620
+ );
621
+ }
291
622
  let isLocalhost = false;
292
623
  if (endpoint) {
293
624
  try {
@@ -347,7 +678,28 @@ function buildProvider(config, logFn) {
347
678
  spanProcessors
348
679
  });
349
680
  }
350
- return provider;
681
+ return {
682
+ provider,
683
+ buildInfo,
684
+ connection: { host, publicKey, secretKey }
685
+ };
686
+ }
687
+ function scheduleBuildRegistration(config, built) {
688
+ if (!config.agent || !built.buildInfo || config.registerBuild === false) {
689
+ return;
690
+ }
691
+ const { manifest, buildHash } = built.buildInfo;
692
+ void registerBuild({
693
+ host: built.connection.host,
694
+ publicKey: built.connection.publicKey,
695
+ secretKey: built.connection.secretKey,
696
+ agentId: config.agent,
697
+ version: config.version,
698
+ manifest,
699
+ buildHash
700
+ }).catch((err) => {
701
+ warn("Build registration failed (agent keeps running):", err);
702
+ });
351
703
  }
352
704
  function init(config = {}) {
353
705
  if (state.initialized) {
@@ -355,8 +707,10 @@ function init(config = {}) {
355
707
  return;
356
708
  }
357
709
  state.debug = config.debug ?? false;
358
- const provider = buildProvider(config, log);
710
+ const built = buildProvider(config, log);
711
+ const provider = built.provider;
359
712
  provider.register();
713
+ scheduleBuildRegistration(config, built);
360
714
  state.provider = provider;
361
715
  state.initialized = true;
362
716
  log(
@@ -367,7 +721,9 @@ function init(config = {}) {
367
721
  function initIsolated(config = {}) {
368
722
  const debugLog2 = config.debug ? (message, ...args) => console.log(`[gatewaysdk.tracing:isolated] ${message}`, ...args) : () => {
369
723
  };
370
- const provider = buildProvider(config, debugLog2);
724
+ const built = buildProvider(config, debugLog2);
725
+ const provider = built.provider;
726
+ scheduleBuildRegistration(config, built);
371
727
  const tracer = provider.getTracer("@withgateway/sdk");
372
728
  debugLog2(
373
729
  "Isolated tracing provider created (service=%s)",