@withgateway/sdk 0.1.8 → 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, {
@@ -305,6 +450,109 @@ function debugLog(message, ...args) {
305
450
  }
306
451
  }
307
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
+
308
556
  // src/tracing/init.ts
309
557
  var ENV_VARS = {
310
558
  HOST: "GATEWAY_HOST",
@@ -383,6 +631,24 @@ function buildProvider(config, logFn) {
383
631
  if (config.version) {
384
632
  resourceAttrs["gateway.version"] = config.version;
385
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
+ }
386
652
  let isLocalhost = false;
387
653
  if (endpoint) {
388
654
  try {
@@ -442,7 +708,28 @@ function buildProvider(config, logFn) {
442
708
  spanProcessors
443
709
  });
444
710
  }
445
- 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
+ });
446
733
  }
447
734
  function init(config = {}) {
448
735
  if (state.initialized) {
@@ -450,8 +737,10 @@ function init(config = {}) {
450
737
  return;
451
738
  }
452
739
  state.debug = config.debug ?? false;
453
- const provider = buildProvider(config, log);
740
+ const built = buildProvider(config, log);
741
+ const provider = built.provider;
454
742
  provider.register();
743
+ scheduleBuildRegistration(config, built);
455
744
  state.provider = provider;
456
745
  state.initialized = true;
457
746
  log(
@@ -462,7 +751,9 @@ function init(config = {}) {
462
751
  function initIsolated(config = {}) {
463
752
  const debugLog2 = config.debug ? (message, ...args) => console.log(`[gatewaysdk.tracing:isolated] ${message}`, ...args) : () => {
464
753
  };
465
- const provider = buildProvider(config, debugLog2);
754
+ const built = buildProvider(config, debugLog2);
755
+ const provider = built.provider;
756
+ scheduleBuildRegistration(config, built);
466
757
  const tracer = provider.getTracer("@withgateway/sdk");
467
758
  debugLog2(
468
759
  "Isolated tracing provider created (service=%s)",