@withgateway/sdk 0.1.8 → 0.1.10

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.10",
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,158 @@ 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
+ if (process.env.GATEWAY_PR_TITLE) {
2862
+ attribution.prTitle = process.env.GATEWAY_PR_TITLE.slice(0, 300);
2863
+ }
2864
+ if (process.env.GATEWAY_PR_BODY) {
2865
+ attribution.prDescription = process.env.GATEWAY_PR_BODY.slice(0, 2e3);
2866
+ }
2867
+ if (attribution.repo && attribution.prNumber && !("prUrl" in attribution)) {
2868
+ attribution.prUrl = `https://github.com/${String(attribution.repo)}/pull/${String(attribution.prNumber)}`;
2869
+ }
2870
+ return attribution;
2871
+ }
2872
+ async function registerBuild(params) {
2873
+ const auth = Buffer.from(`${params.publicKey}:${params.secretKey}`).toString(
2874
+ "base64"
2875
+ );
2876
+ const response = await fetch(
2877
+ `${params.host.replace(/\/$/, "")}/api/public/agent-builds`,
2878
+ {
2879
+ method: "POST",
2880
+ headers: {
2881
+ Authorization: `Basic ${auth}`,
2882
+ "Content-Type": "application/json"
2883
+ },
2884
+ body: JSON.stringify({
2885
+ agentId: params.agentId,
2886
+ buildHash: params.buildHash,
2887
+ ...params.version ? { semanticVer: params.version } : {},
2888
+ manifest: params.manifest,
2889
+ attribution: attributionFromEnv()
2890
+ }),
2891
+ signal: AbortSignal.timeout(15e3)
2892
+ }
2893
+ );
2894
+ if (!response.ok) {
2895
+ throw new Error(
2896
+ `build registration failed (${response.status}): ${(await response.text()).slice(0, 300)}`
2897
+ );
2898
+ }
2899
+ }
2900
+
2603
2901
  // src/tracing/identity.ts
2604
2902
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
2605
2903
  import { isSpanContextValid, trace } from "@opentelemetry/api";
@@ -2763,6 +3061,24 @@ function buildProvider(config, logFn) {
2763
3061
  if (config.version) {
2764
3062
  resourceAttrs["gateway.version"] = config.version;
2765
3063
  }
3064
+ let buildInfo = null;
3065
+ if (config.agent) {
3066
+ const manifest = assembleManifest(config.agent);
3067
+ const buildHash = computeBuildHash(manifest);
3068
+ buildInfo = { manifest, buildHash };
3069
+ resourceAttrs["gateway.agent.id"] = config.agent;
3070
+ resourceAttrs["gateway.build.hash"] = buildHash;
3071
+ if (config.version) {
3072
+ resourceAttrs["gateway.agent.version"] = config.version;
3073
+ }
3074
+ logFn(
3075
+ "Agent build identity: %s @ %s (%d tools, %d prompts)",
3076
+ config.agent,
3077
+ buildHash.slice(0, 15),
3078
+ manifest.tools.length,
3079
+ Object.keys(manifest.prompts).length
3080
+ );
3081
+ }
2766
3082
  let isLocalhost = false;
2767
3083
  if (endpoint) {
2768
3084
  try {
@@ -2822,7 +3138,28 @@ function buildProvider(config, logFn) {
2822
3138
  spanProcessors
2823
3139
  });
2824
3140
  }
2825
- return provider;
3141
+ return {
3142
+ provider,
3143
+ buildInfo,
3144
+ connection: { host, publicKey, secretKey }
3145
+ };
3146
+ }
3147
+ function scheduleBuildRegistration(config, built) {
3148
+ if (!config.agent || !built.buildInfo || config.registerBuild === false) {
3149
+ return;
3150
+ }
3151
+ const { manifest, buildHash } = built.buildInfo;
3152
+ void registerBuild({
3153
+ host: built.connection.host,
3154
+ publicKey: built.connection.publicKey,
3155
+ secretKey: built.connection.secretKey,
3156
+ agentId: config.agent,
3157
+ version: config.version,
3158
+ manifest,
3159
+ buildHash
3160
+ }).catch((err) => {
3161
+ warn("Build registration failed (agent keeps running):", err);
3162
+ });
2826
3163
  }
2827
3164
  function init2(config = {}) {
2828
3165
  if (state.initialized) {
@@ -2830,8 +3167,10 @@ function init2(config = {}) {
2830
3167
  return;
2831
3168
  }
2832
3169
  state.debug = config.debug ?? false;
2833
- const provider = buildProvider(config, log);
3170
+ const built = buildProvider(config, log);
3171
+ const provider = built.provider;
2834
3172
  provider.register();
3173
+ scheduleBuildRegistration(config, built);
2835
3174
  state.provider = provider;
2836
3175
  state.initialized = true;
2837
3176
  log(
@@ -2842,7 +3181,9 @@ function init2(config = {}) {
2842
3181
  function initIsolated(config = {}) {
2843
3182
  const debugLog2 = config.debug ? (message, ...args) => console.log(`[gatewaysdk.tracing:isolated] ${message}`, ...args) : () => {
2844
3183
  };
2845
- const provider = buildProvider(config, debugLog2);
3184
+ const built = buildProvider(config, debugLog2);
3185
+ const provider = built.provider;
3186
+ scheduleBuildRegistration(config, built);
2846
3187
  const tracer = provider.getTracer("@withgateway/sdk");
2847
3188
  debugLog2(
2848
3189
  "Isolated tracing provider created (service=%s)",
@@ -3183,21 +3524,29 @@ export {
3183
3524
  UserProfileError,
3184
3525
  UsersClient,
3185
3526
  addExperimentAttributes,
3527
+ assembleManifest,
3186
3528
  assignVariant,
3187
3529
  basicAuthHeader,
3530
+ canonicalJson,
3188
3531
  clearExperimentContext,
3532
+ computeBuildHash,
3189
3533
  computeHash,
3190
3534
  context,
3535
+ defineTool,
3191
3536
  experimentContextStorage,
3192
3537
  singleton_exports as experiments,
3193
3538
  gateway,
3194
3539
  getExperimentContext,
3540
+ getRegisteredPrompts,
3541
+ getRegisteredTools,
3195
3542
  identify,
3196
3543
  loadSession,
3197
3544
  memory,
3198
3545
  personas,
3546
+ registerPrompt,
3199
3547
  renderAgentSystem,
3200
3548
  replay,
3549
+ resetBuildRegistry,
3201
3550
  resolveUserId,
3202
3551
  runSuite,
3203
3552
  runWithExperimentContext,