@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.
package/dist/index.mjs CHANGED
@@ -1,17 +1,163 @@
1
1
  import { createRequire as __gatewayCreateRequire } from "module";
2
2
  const require = __gatewayCreateRequire(import.meta.url);
3
3
  var __defProp = Object.defineProperty;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
5
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
5
6
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
6
7
  }) : x)(function(x) {
7
8
  if (typeof require !== "undefined") return require.apply(this, arguments);
8
9
  throw Error('Dynamic require of "' + x + '" is not supported');
9
10
  });
11
+ var __commonJS = (cb, mod) => function __require2() {
12
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
13
+ };
10
14
  var __export = (target, all) => {
11
15
  for (var name in all)
12
16
  __defProp(target, name, { get: all[name], enumerable: true });
13
17
  };
14
18
 
19
+ // package.json
20
+ var require_package = __commonJS({
21
+ "package.json"(exports, module) {
22
+ module.exports = {
23
+ name: "@withgateway/sdk",
24
+ version: "0.1.9",
25
+ description: "Gateway SDK for TypeScript - A/B experiments, tracing, and observability",
26
+ main: "./dist/index.js",
27
+ module: "./dist/index.mjs",
28
+ types: "./dist/index.d.ts",
29
+ exports: {
30
+ ".": {
31
+ types: "./dist/index.d.ts",
32
+ import: "./dist/index.mjs",
33
+ require: "./dist/index.js"
34
+ },
35
+ "./experiments": {
36
+ types: "./dist/experiments/index.d.ts",
37
+ import: "./dist/experiments/index.mjs",
38
+ require: "./dist/experiments/index.js"
39
+ },
40
+ "./context": {
41
+ types: "./dist/context/index.d.ts",
42
+ import: "./dist/context/index.mjs",
43
+ require: "./dist/context/index.js"
44
+ },
45
+ "./memory": {
46
+ types: "./dist/memory/index.d.ts",
47
+ import: "./dist/memory/index.mjs",
48
+ require: "./dist/memory/index.js"
49
+ },
50
+ "./personas": {
51
+ types: "./dist/personas/index.d.ts",
52
+ import: "./dist/personas/index.mjs",
53
+ require: "./dist/personas/index.js"
54
+ },
55
+ "./replay": {
56
+ types: "./dist/replay/index.d.ts",
57
+ import: "./dist/replay/index.mjs",
58
+ require: "./dist/replay/index.js"
59
+ },
60
+ "./sessions": {
61
+ types: "./dist/sessions/index.d.ts",
62
+ import: "./dist/sessions/index.mjs",
63
+ require: "./dist/sessions/index.js"
64
+ },
65
+ "./tracing": {
66
+ types: "./dist/tracing/index.d.ts",
67
+ import: "./dist/tracing/index.mjs",
68
+ require: "./dist/tracing/index.js"
69
+ },
70
+ "./security": {
71
+ types: "./dist/security/index.d.ts",
72
+ import: "./dist/security/index.mjs",
73
+ require: "./dist/security/index.js"
74
+ },
75
+ "./users": {
76
+ types: "./dist/users/index.d.ts",
77
+ import: "./dist/users/index.mjs",
78
+ require: "./dist/users/index.js"
79
+ }
80
+ },
81
+ files: [
82
+ "dist",
83
+ "README.md"
84
+ ],
85
+ publishConfig: {
86
+ access: "public"
87
+ },
88
+ scripts: {
89
+ build: "tsup",
90
+ dev: "tsup --watch",
91
+ typecheck: "tsc --noEmit",
92
+ test: "vitest",
93
+ "test:run": "vitest run",
94
+ lint: "eslint src --ext .ts",
95
+ clean: "rm -rf dist",
96
+ example: "tsx examples/test-ab-experiment.ts",
97
+ "test:crm": "tsx examples/test-crm-ab-experiment.ts",
98
+ "test:crm:balanced": "tsx examples/test-crm-ab-experiment.ts --balanced",
99
+ "test:crm:full": "tsx examples/test-crm-ab-experiment.ts --users 12 --all-tasks --concurrency 3"
100
+ },
101
+ keywords: [
102
+ "gateway",
103
+ "ab-testing",
104
+ "experiments",
105
+ "opentelemetry",
106
+ "tracing",
107
+ "observability",
108
+ "llm"
109
+ ],
110
+ author: "Gateway Team",
111
+ license: "MIT",
112
+ engines: {
113
+ node: ">=18.0.0"
114
+ },
115
+ peerDependencies: {
116
+ "@opentelemetry/api": "^1.0.0",
117
+ "@opentelemetry/exporter-trace-otlp-http": ">=0.50.0",
118
+ "@opentelemetry/resources": ">=1.0.0",
119
+ "@opentelemetry/sdk-trace-base": ">=1.0.0",
120
+ "@opentelemetry/sdk-trace-node": ">=1.0.0"
121
+ },
122
+ peerDependenciesMeta: {
123
+ "@opentelemetry/api": {
124
+ optional: true
125
+ },
126
+ "@opentelemetry/sdk-trace-base": {
127
+ optional: true
128
+ },
129
+ "@opentelemetry/sdk-trace-node": {
130
+ optional: true
131
+ },
132
+ "@opentelemetry/exporter-trace-otlp-http": {
133
+ optional: true
134
+ },
135
+ "@opentelemetry/resources": {
136
+ optional: true
137
+ }
138
+ },
139
+ optionalDependencies: {
140
+ "@arizeai/openinference-instrumentation-anthropic": "^0.1.15",
141
+ "@arizeai/openinference-instrumentation-openai": "^4.1.5"
142
+ },
143
+ devDependencies: {
144
+ "@anthropic-ai/sdk": "^0.79.0",
145
+ "@opentelemetry/api": "^1.9.0",
146
+ "@opentelemetry/exporter-trace-otlp-http": "^0.212.0",
147
+ "@opentelemetry/resources": "^2.6.0",
148
+ "@opentelemetry/sdk-trace-base": "^1.30.1",
149
+ "@opentelemetry/sdk-trace-node": "^2.6.0",
150
+ "@opentelemetry/semantic-conventions": "^1.40.0",
151
+ "@types/node": "^20.0.0",
152
+ tsup: "^8.0.0",
153
+ tsx: "^4.0.0",
154
+ typescript: "^5.0.0",
155
+ vitest: "^2.0.0"
156
+ }
157
+ };
158
+ }
159
+ });
160
+
15
161
  // src/experiments/assignment.ts
16
162
  import { createHash } from "crypto";
17
163
  function computeHash(experimentKey, userId) {
@@ -2600,6 +2746,149 @@ var users = {
2600
2746
  fromEnv: UsersClient.fromEnv
2601
2747
  };
2602
2748
 
2749
+ // src/build/index.ts
2750
+ import { createHash as createHash2 } from "crypto";
2751
+ function canonicalJson(value) {
2752
+ if (value === null || typeof value !== "object") {
2753
+ return JSON.stringify(value);
2754
+ }
2755
+ if (Array.isArray(value)) {
2756
+ return `[${value.map(canonicalJson).join(",")}]`;
2757
+ }
2758
+ const entries = Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
2759
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(",")}}`;
2760
+ }
2761
+ function sha256(text) {
2762
+ return `sha256:${createHash2("sha256").update(text).digest("hex")}`;
2763
+ }
2764
+ var registeredTools = /* @__PURE__ */ new Map();
2765
+ var registeredPrompts = /* @__PURE__ */ new Map();
2766
+ function captureSource() {
2767
+ const stack = new Error().stack?.split("\n") ?? [];
2768
+ for (const line of stack.slice(1)) {
2769
+ if (line.includes("build/index.ts") || line.includes("build/index.js") || line.includes("build/index.mjs") || line.includes("node_modules/@withgateway/")) {
2770
+ continue;
2771
+ }
2772
+ if (line.includes("node:internal") || line.includes("(node:")) continue;
2773
+ const match = /\(?([^()\s]+):(\d+):\d+\)?$/.exec(line.trim());
2774
+ if (match) {
2775
+ const file = match[1].replace(/^file:\/\//, "");
2776
+ const short = file.includes("/") ? file.split("/").slice(-4).join("/") : file;
2777
+ return `${short}:${match[2]}`;
2778
+ }
2779
+ }
2780
+ return void 0;
2781
+ }
2782
+ function defineTool(tool) {
2783
+ const schemaBasis = tool.schema ?? tool.inputSchema ?? null;
2784
+ const source = captureSource();
2785
+ const identity = {
2786
+ name: tool.name,
2787
+ ...tool.version !== void 0 ? { version: tool.version } : {},
2788
+ ...tool.effects !== void 0 ? { effects: tool.effects } : {},
2789
+ ...tool.description !== void 0 ? { description: tool.description.slice(0, 500) } : {},
2790
+ schemaHash: sha256(
2791
+ canonicalJson({ schema: schemaBasis, description: tool.description ?? "" })
2792
+ ),
2793
+ ...source ? { source } : {}
2794
+ };
2795
+ registeredTools.set(tool.name, identity);
2796
+ return tool;
2797
+ }
2798
+ function registerPrompt(name, content) {
2799
+ registeredPrompts.set(name, sha256(content));
2800
+ return content;
2801
+ }
2802
+ function getRegisteredTools() {
2803
+ return [...registeredTools.values()].sort(
2804
+ (a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0
2805
+ );
2806
+ }
2807
+ function getRegisteredPrompts() {
2808
+ return Object.fromEntries(
2809
+ [...registeredPrompts.entries()].sort(
2810
+ ([a], [b]) => a < b ? -1 : a > b ? 1 : 0
2811
+ )
2812
+ );
2813
+ }
2814
+ function resetBuildRegistry() {
2815
+ registeredTools.clear();
2816
+ registeredPrompts.clear();
2817
+ }
2818
+ function sdkVersion() {
2819
+ try {
2820
+ const pkg = require_package();
2821
+ return `@withgateway/sdk@${pkg.version ?? "unknown"}`;
2822
+ } catch {
2823
+ return "@withgateway/sdk";
2824
+ }
2825
+ }
2826
+ function codeRef() {
2827
+ const sha = process.env.GATEWAY_COMMIT ?? process.env.GITHUB_SHA ?? process.env.CI_COMMIT_SHA ?? // GitLab
2828
+ process.env.CIRCLE_SHA1;
2829
+ if (!sha) return void 0;
2830
+ const repo = process.env.GITHUB_REPOSITORY ?? process.env.CI_PROJECT_PATH;
2831
+ return repo ? `git:${repo}@${sha}` : `git:${sha}`;
2832
+ }
2833
+ function assembleManifest(agentId) {
2834
+ return {
2835
+ agentId,
2836
+ ...codeRef() ? { codeRef: codeRef() } : {},
2837
+ sdk: sdkVersion(),
2838
+ tools: getRegisteredTools(),
2839
+ prompts: getRegisteredPrompts()
2840
+ };
2841
+ }
2842
+ function computeBuildHash(manifest) {
2843
+ const identity = {
2844
+ ...manifest,
2845
+ tools: manifest.tools.map(({ source: _source, ...tool }) => tool)
2846
+ };
2847
+ return sha256(canonicalJson(identity));
2848
+ }
2849
+ function attributionFromEnv() {
2850
+ const attribution = { source: "runtime" };
2851
+ if (process.env.GITHUB_ACTIONS) attribution.source = "ci";
2852
+ if (process.env.GITHUB_ACTOR) attribution.githubLogin = process.env.GITHUB_ACTOR;
2853
+ const sha = process.env.GATEWAY_COMMIT ?? process.env.GITHUB_SHA;
2854
+ if (sha) attribution.commitSha = sha;
2855
+ if (process.env.GITHUB_REPOSITORY) attribution.repo = process.env.GITHUB_REPOSITORY;
2856
+ const branch = process.env.GITHUB_HEAD_REF ?? process.env.GITHUB_REF_NAME;
2857
+ if (branch) attribution.branch = branch;
2858
+ const ref = process.env.GITHUB_REF ?? "";
2859
+ const prMatch = /refs\/pull\/(\d+)\//.exec(ref);
2860
+ if (prMatch) attribution.prNumber = Number(prMatch[1]);
2861
+ return attribution;
2862
+ }
2863
+ async function registerBuild(params) {
2864
+ const auth = Buffer.from(`${params.publicKey}:${params.secretKey}`).toString(
2865
+ "base64"
2866
+ );
2867
+ const response = await fetch(
2868
+ `${params.host.replace(/\/$/, "")}/api/public/agent-builds`,
2869
+ {
2870
+ method: "POST",
2871
+ headers: {
2872
+ Authorization: `Basic ${auth}`,
2873
+ "Content-Type": "application/json"
2874
+ },
2875
+ body: JSON.stringify({
2876
+ agentId: params.agentId,
2877
+ buildHash: params.buildHash,
2878
+ ...params.version ? { semanticVer: params.version } : {},
2879
+ manifest: params.manifest,
2880
+ attribution: attributionFromEnv()
2881
+ }),
2882
+ signal: AbortSignal.timeout(15e3)
2883
+ }
2884
+ );
2885
+ if (!response.ok) {
2886
+ throw new Error(
2887
+ `build registration failed (${response.status}): ${(await response.text()).slice(0, 300)}`
2888
+ );
2889
+ }
2890
+ }
2891
+
2603
2892
  // src/tracing/identity.ts
2604
2893
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
2605
2894
  import { isSpanContextValid, trace } from "@opentelemetry/api";
@@ -2763,6 +3052,24 @@ function buildProvider(config, logFn) {
2763
3052
  if (config.version) {
2764
3053
  resourceAttrs["gateway.version"] = config.version;
2765
3054
  }
3055
+ let buildInfo = null;
3056
+ if (config.agent) {
3057
+ const manifest = assembleManifest(config.agent);
3058
+ const buildHash = computeBuildHash(manifest);
3059
+ buildInfo = { manifest, buildHash };
3060
+ resourceAttrs["gateway.agent.id"] = config.agent;
3061
+ resourceAttrs["gateway.build.hash"] = buildHash;
3062
+ if (config.version) {
3063
+ resourceAttrs["gateway.agent.version"] = config.version;
3064
+ }
3065
+ logFn(
3066
+ "Agent build identity: %s @ %s (%d tools, %d prompts)",
3067
+ config.agent,
3068
+ buildHash.slice(0, 15),
3069
+ manifest.tools.length,
3070
+ Object.keys(manifest.prompts).length
3071
+ );
3072
+ }
2766
3073
  let isLocalhost = false;
2767
3074
  if (endpoint) {
2768
3075
  try {
@@ -2822,7 +3129,28 @@ function buildProvider(config, logFn) {
2822
3129
  spanProcessors
2823
3130
  });
2824
3131
  }
2825
- return provider;
3132
+ return {
3133
+ provider,
3134
+ buildInfo,
3135
+ connection: { host, publicKey, secretKey }
3136
+ };
3137
+ }
3138
+ function scheduleBuildRegistration(config, built) {
3139
+ if (!config.agent || !built.buildInfo || config.registerBuild === false) {
3140
+ return;
3141
+ }
3142
+ const { manifest, buildHash } = built.buildInfo;
3143
+ void registerBuild({
3144
+ host: built.connection.host,
3145
+ publicKey: built.connection.publicKey,
3146
+ secretKey: built.connection.secretKey,
3147
+ agentId: config.agent,
3148
+ version: config.version,
3149
+ manifest,
3150
+ buildHash
3151
+ }).catch((err) => {
3152
+ warn("Build registration failed (agent keeps running):", err);
3153
+ });
2826
3154
  }
2827
3155
  function init2(config = {}) {
2828
3156
  if (state.initialized) {
@@ -2830,8 +3158,10 @@ function init2(config = {}) {
2830
3158
  return;
2831
3159
  }
2832
3160
  state.debug = config.debug ?? false;
2833
- const provider = buildProvider(config, log);
3161
+ const built = buildProvider(config, log);
3162
+ const provider = built.provider;
2834
3163
  provider.register();
3164
+ scheduleBuildRegistration(config, built);
2835
3165
  state.provider = provider;
2836
3166
  state.initialized = true;
2837
3167
  log(
@@ -2842,7 +3172,9 @@ function init2(config = {}) {
2842
3172
  function initIsolated(config = {}) {
2843
3173
  const debugLog2 = config.debug ? (message, ...args) => console.log(`[gatewaysdk.tracing:isolated] ${message}`, ...args) : () => {
2844
3174
  };
2845
- const provider = buildProvider(config, debugLog2);
3175
+ const built = buildProvider(config, debugLog2);
3176
+ const provider = built.provider;
3177
+ scheduleBuildRegistration(config, built);
2846
3178
  const tracer = provider.getTracer("@withgateway/sdk");
2847
3179
  debugLog2(
2848
3180
  "Isolated tracing provider created (service=%s)",
@@ -3183,21 +3515,29 @@ export {
3183
3515
  UserProfileError,
3184
3516
  UsersClient,
3185
3517
  addExperimentAttributes,
3518
+ assembleManifest,
3186
3519
  assignVariant,
3187
3520
  basicAuthHeader,
3521
+ canonicalJson,
3188
3522
  clearExperimentContext,
3523
+ computeBuildHash,
3189
3524
  computeHash,
3190
3525
  context,
3526
+ defineTool,
3191
3527
  experimentContextStorage,
3192
3528
  singleton_exports as experiments,
3193
3529
  gateway,
3194
3530
  getExperimentContext,
3531
+ getRegisteredPrompts,
3532
+ getRegisteredTools,
3195
3533
  identify,
3196
3534
  loadSession,
3197
3535
  memory,
3198
3536
  personas,
3537
+ registerPrompt,
3199
3538
  renderAgentSystem,
3200
3539
  replay,
3540
+ resetBuildRegistry,
3201
3541
  resolveUserId,
3202
3542
  runSuite,
3203
3543
  runWithExperimentContext,