@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.
package/dist/index.js CHANGED
@@ -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/index.ts
21
166
  var src_exports = {};
22
167
  __export(src_exports, {
@@ -58,21 +203,29 @@ __export(src_exports, {
58
203
  UserProfileError: () => UserProfileError,
59
204
  UsersClient: () => UsersClient,
60
205
  addExperimentAttributes: () => addExperimentAttributes,
206
+ assembleManifest: () => assembleManifest,
61
207
  assignVariant: () => assignVariant,
62
208
  basicAuthHeader: () => basicAuthHeader,
209
+ canonicalJson: () => canonicalJson,
63
210
  clearExperimentContext: () => clearExperimentContext,
211
+ computeBuildHash: () => computeBuildHash,
64
212
  computeHash: () => computeHash,
65
213
  context: () => context,
214
+ defineTool: () => defineTool,
66
215
  experimentContextStorage: () => experimentContextStorage,
67
216
  experiments: () => singleton_exports,
68
217
  gateway: () => gateway,
69
218
  getExperimentContext: () => getExperimentContext,
219
+ getRegisteredPrompts: () => getRegisteredPrompts,
220
+ getRegisteredTools: () => getRegisteredTools,
70
221
  identify: () => identify,
71
222
  loadSession: () => loadSession,
72
223
  memory: () => memory,
73
224
  personas: () => personas,
225
+ registerPrompt: () => registerPrompt,
74
226
  renderAgentSystem: () => renderAgentSystem,
75
227
  replay: () => replay,
228
+ resetBuildRegistry: () => resetBuildRegistry,
76
229
  resolveUserId: () => resolveUserId,
77
230
  runSuite: () => runSuite,
78
231
  runWithExperimentContext: () => runWithExperimentContext,
@@ -2542,6 +2695,58 @@ var UsersClient = class _UsersClient {
2542
2695
  await this.requestJson("POST", "/api/public/user-profiles", body)
2543
2696
  );
2544
2697
  }
2698
+ /**
2699
+ * Record a VALUE EVENT for a user — the per-user ROI stream. `value` is
2700
+ * whatever the event is worth in your terms (minutes saved, revenue…);
2701
+ * Gateway sums it in the hours-saved/ROI rollups, and evals and task-set
2702
+ * replays can assert against the events. Link `traceId`/`sessionId` to tie
2703
+ * the event to the run that produced it.
2704
+ *
2705
+ * @example
2706
+ * ```ts
2707
+ * await client.trackEvent("user-123", "checkout_completed", {
2708
+ * value: 25,
2709
+ * metadata: { cartSize: 3 },
2710
+ * sessionId,
2711
+ * });
2712
+ * ```
2713
+ */
2714
+ async trackEvent(userId, event, options = {}) {
2715
+ const body = {
2716
+ userId,
2717
+ event,
2718
+ metadata: options.metadata ?? {},
2719
+ ...options.value !== void 0 ? { value: options.value } : {},
2720
+ ...options.traceId !== void 0 ? { traceId: options.traceId } : {},
2721
+ ...options.sessionId !== void 0 ? { sessionId: options.sessionId } : {}
2722
+ };
2723
+ return parseEvent(
2724
+ await this.requestJson("POST", "/api/public/user-events", body)
2725
+ );
2726
+ }
2727
+ /** List a project's user events, optionally filtered by user/event/time. */
2728
+ async listEvents(filter = {}) {
2729
+ const params = new URLSearchParams();
2730
+ if (filter.userId) params.set("userId", filter.userId);
2731
+ if (filter.event) params.set("event", filter.event);
2732
+ if (filter.fromTimestamp)
2733
+ params.set("fromTimestamp", filter.fromTimestamp.toISOString());
2734
+ if (filter.toTimestamp)
2735
+ params.set("toTimestamp", filter.toTimestamp.toISOString());
2736
+ if (filter.page) params.set("page", String(filter.page));
2737
+ if (filter.limit) params.set("limit", String(filter.limit));
2738
+ const qs = params.toString();
2739
+ const payload = await this.requestJson(
2740
+ "GET",
2741
+ `/api/public/user-events${qs ? `?${qs}` : ""}`
2742
+ );
2743
+ const rows = Array.isArray(payload.data) ? payload.data : [];
2744
+ const meta = payload.meta && typeof payload.meta === "object" ? payload.meta : {};
2745
+ return {
2746
+ data: rows.map((row) => parseEvent(row)),
2747
+ totalItems: Number(meta.totalItems ?? rows.length)
2748
+ };
2749
+ }
2545
2750
  async requestJson(method, path, payload) {
2546
2751
  let response;
2547
2752
  try {
@@ -2580,6 +2785,18 @@ var UsersClient = class _UsersClient {
2580
2785
  }
2581
2786
  }
2582
2787
  };
2788
+ function parseEvent(payload) {
2789
+ return {
2790
+ id: String(payload.id ?? ""),
2791
+ userId: String(payload.userId ?? ""),
2792
+ event: String(payload.event ?? ""),
2793
+ value: typeof payload.value === "number" ? payload.value : null,
2794
+ metadata: payload.metadata && typeof payload.metadata === "object" && !Array.isArray(payload.metadata) ? payload.metadata : {},
2795
+ traceId: typeof payload.traceId === "string" ? payload.traceId : null,
2796
+ sessionId: typeof payload.sessionId === "string" ? payload.sessionId : null,
2797
+ createdAt: typeof payload.createdAt === "string" ? new Date(payload.createdAt) : /* @__PURE__ */ new Date(0)
2798
+ };
2799
+ }
2583
2800
  function parseProfile(payload) {
2584
2801
  return {
2585
2802
  userId: String(payload.userId ?? ""),
@@ -2609,6 +2826,149 @@ var users = {
2609
2826
  fromEnv: UsersClient.fromEnv
2610
2827
  };
2611
2828
 
2829
+ // src/build/index.ts
2830
+ var import_node_crypto = require("crypto");
2831
+ function canonicalJson(value) {
2832
+ if (value === null || typeof value !== "object") {
2833
+ return JSON.stringify(value);
2834
+ }
2835
+ if (Array.isArray(value)) {
2836
+ return `[${value.map(canonicalJson).join(",")}]`;
2837
+ }
2838
+ const entries = Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
2839
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(",")}}`;
2840
+ }
2841
+ function sha256(text) {
2842
+ return `sha256:${(0, import_node_crypto.createHash)("sha256").update(text).digest("hex")}`;
2843
+ }
2844
+ var registeredTools = /* @__PURE__ */ new Map();
2845
+ var registeredPrompts = /* @__PURE__ */ new Map();
2846
+ function captureSource() {
2847
+ const stack = new Error().stack?.split("\n") ?? [];
2848
+ for (const line of stack.slice(1)) {
2849
+ if (line.includes("build/index.ts") || line.includes("build/index.js") || line.includes("build/index.mjs") || line.includes("node_modules/@withgateway/")) {
2850
+ continue;
2851
+ }
2852
+ if (line.includes("node:internal") || line.includes("(node:")) continue;
2853
+ const match = /\(?([^()\s]+):(\d+):\d+\)?$/.exec(line.trim());
2854
+ if (match) {
2855
+ const file = match[1].replace(/^file:\/\//, "");
2856
+ const short = file.includes("/") ? file.split("/").slice(-4).join("/") : file;
2857
+ return `${short}:${match[2]}`;
2858
+ }
2859
+ }
2860
+ return void 0;
2861
+ }
2862
+ function defineTool(tool) {
2863
+ const schemaBasis = tool.schema ?? tool.inputSchema ?? null;
2864
+ const source = captureSource();
2865
+ const identity = {
2866
+ name: tool.name,
2867
+ ...tool.version !== void 0 ? { version: tool.version } : {},
2868
+ ...tool.effects !== void 0 ? { effects: tool.effects } : {},
2869
+ ...tool.description !== void 0 ? { description: tool.description.slice(0, 500) } : {},
2870
+ schemaHash: sha256(
2871
+ canonicalJson({ schema: schemaBasis, description: tool.description ?? "" })
2872
+ ),
2873
+ ...source ? { source } : {}
2874
+ };
2875
+ registeredTools.set(tool.name, identity);
2876
+ return tool;
2877
+ }
2878
+ function registerPrompt(name, content) {
2879
+ registeredPrompts.set(name, sha256(content));
2880
+ return content;
2881
+ }
2882
+ function getRegisteredTools() {
2883
+ return [...registeredTools.values()].sort(
2884
+ (a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0
2885
+ );
2886
+ }
2887
+ function getRegisteredPrompts() {
2888
+ return Object.fromEntries(
2889
+ [...registeredPrompts.entries()].sort(
2890
+ ([a], [b]) => a < b ? -1 : a > b ? 1 : 0
2891
+ )
2892
+ );
2893
+ }
2894
+ function resetBuildRegistry() {
2895
+ registeredTools.clear();
2896
+ registeredPrompts.clear();
2897
+ }
2898
+ function sdkVersion() {
2899
+ try {
2900
+ const pkg = require_package();
2901
+ return `@withgateway/sdk@${pkg.version ?? "unknown"}`;
2902
+ } catch {
2903
+ return "@withgateway/sdk";
2904
+ }
2905
+ }
2906
+ function codeRef() {
2907
+ const sha = process.env.GATEWAY_COMMIT ?? process.env.GITHUB_SHA ?? process.env.CI_COMMIT_SHA ?? // GitLab
2908
+ process.env.CIRCLE_SHA1;
2909
+ if (!sha) return void 0;
2910
+ const repo = process.env.GITHUB_REPOSITORY ?? process.env.CI_PROJECT_PATH;
2911
+ return repo ? `git:${repo}@${sha}` : `git:${sha}`;
2912
+ }
2913
+ function assembleManifest(agentId) {
2914
+ return {
2915
+ agentId,
2916
+ ...codeRef() ? { codeRef: codeRef() } : {},
2917
+ sdk: sdkVersion(),
2918
+ tools: getRegisteredTools(),
2919
+ prompts: getRegisteredPrompts()
2920
+ };
2921
+ }
2922
+ function computeBuildHash(manifest) {
2923
+ const identity = {
2924
+ ...manifest,
2925
+ tools: manifest.tools.map(({ source: _source, ...tool }) => tool)
2926
+ };
2927
+ return sha256(canonicalJson(identity));
2928
+ }
2929
+ function attributionFromEnv() {
2930
+ const attribution = { source: "runtime" };
2931
+ if (process.env.GITHUB_ACTIONS) attribution.source = "ci";
2932
+ if (process.env.GITHUB_ACTOR) attribution.githubLogin = process.env.GITHUB_ACTOR;
2933
+ const sha = process.env.GATEWAY_COMMIT ?? process.env.GITHUB_SHA;
2934
+ if (sha) attribution.commitSha = sha;
2935
+ if (process.env.GITHUB_REPOSITORY) attribution.repo = process.env.GITHUB_REPOSITORY;
2936
+ const branch = process.env.GITHUB_HEAD_REF ?? process.env.GITHUB_REF_NAME;
2937
+ if (branch) attribution.branch = branch;
2938
+ const ref = process.env.GITHUB_REF ?? "";
2939
+ const prMatch = /refs\/pull\/(\d+)\//.exec(ref);
2940
+ if (prMatch) attribution.prNumber = Number(prMatch[1]);
2941
+ return attribution;
2942
+ }
2943
+ async function registerBuild(params) {
2944
+ const auth = Buffer.from(`${params.publicKey}:${params.secretKey}`).toString(
2945
+ "base64"
2946
+ );
2947
+ const response = await fetch(
2948
+ `${params.host.replace(/\/$/, "")}/api/public/agent-builds`,
2949
+ {
2950
+ method: "POST",
2951
+ headers: {
2952
+ Authorization: `Basic ${auth}`,
2953
+ "Content-Type": "application/json"
2954
+ },
2955
+ body: JSON.stringify({
2956
+ agentId: params.agentId,
2957
+ buildHash: params.buildHash,
2958
+ ...params.version ? { semanticVer: params.version } : {},
2959
+ manifest: params.manifest,
2960
+ attribution: attributionFromEnv()
2961
+ }),
2962
+ signal: AbortSignal.timeout(15e3)
2963
+ }
2964
+ );
2965
+ if (!response.ok) {
2966
+ throw new Error(
2967
+ `build registration failed (${response.status}): ${(await response.text()).slice(0, 300)}`
2968
+ );
2969
+ }
2970
+ }
2971
+
2612
2972
  // src/tracing/identity.ts
2613
2973
  var import_async_hooks2 = require("async_hooks");
2614
2974
  var import_api = require("@opentelemetry/api");
@@ -2772,6 +3132,24 @@ function buildProvider(config, logFn) {
2772
3132
  if (config.version) {
2773
3133
  resourceAttrs["gateway.version"] = config.version;
2774
3134
  }
3135
+ let buildInfo = null;
3136
+ if (config.agent) {
3137
+ const manifest = assembleManifest(config.agent);
3138
+ const buildHash = computeBuildHash(manifest);
3139
+ buildInfo = { manifest, buildHash };
3140
+ resourceAttrs["gateway.agent.id"] = config.agent;
3141
+ resourceAttrs["gateway.build.hash"] = buildHash;
3142
+ if (config.version) {
3143
+ resourceAttrs["gateway.agent.version"] = config.version;
3144
+ }
3145
+ logFn(
3146
+ "Agent build identity: %s @ %s (%d tools, %d prompts)",
3147
+ config.agent,
3148
+ buildHash.slice(0, 15),
3149
+ manifest.tools.length,
3150
+ Object.keys(manifest.prompts).length
3151
+ );
3152
+ }
2775
3153
  let isLocalhost = false;
2776
3154
  if (endpoint) {
2777
3155
  try {
@@ -2831,7 +3209,28 @@ function buildProvider(config, logFn) {
2831
3209
  spanProcessors
2832
3210
  });
2833
3211
  }
2834
- return provider;
3212
+ return {
3213
+ provider,
3214
+ buildInfo,
3215
+ connection: { host, publicKey, secretKey }
3216
+ };
3217
+ }
3218
+ function scheduleBuildRegistration(config, built) {
3219
+ if (!config.agent || !built.buildInfo || config.registerBuild === false) {
3220
+ return;
3221
+ }
3222
+ const { manifest, buildHash } = built.buildInfo;
3223
+ void registerBuild({
3224
+ host: built.connection.host,
3225
+ publicKey: built.connection.publicKey,
3226
+ secretKey: built.connection.secretKey,
3227
+ agentId: config.agent,
3228
+ version: config.version,
3229
+ manifest,
3230
+ buildHash
3231
+ }).catch((err) => {
3232
+ warn("Build registration failed (agent keeps running):", err);
3233
+ });
2835
3234
  }
2836
3235
  function init2(config = {}) {
2837
3236
  if (state.initialized) {
@@ -2839,8 +3238,10 @@ function init2(config = {}) {
2839
3238
  return;
2840
3239
  }
2841
3240
  state.debug = config.debug ?? false;
2842
- const provider = buildProvider(config, log);
3241
+ const built = buildProvider(config, log);
3242
+ const provider = built.provider;
2843
3243
  provider.register();
3244
+ scheduleBuildRegistration(config, built);
2844
3245
  state.provider = provider;
2845
3246
  state.initialized = true;
2846
3247
  log(
@@ -2851,7 +3252,9 @@ function init2(config = {}) {
2851
3252
  function initIsolated(config = {}) {
2852
3253
  const debugLog2 = config.debug ? (message, ...args) => console.log(`[gatewaysdk.tracing:isolated] ${message}`, ...args) : () => {
2853
3254
  };
2854
- const provider = buildProvider(config, debugLog2);
3255
+ const built = buildProvider(config, debugLog2);
3256
+ const provider = built.provider;
3257
+ scheduleBuildRegistration(config, built);
2855
3258
  const tracer = provider.getTracer("@withgateway/sdk");
2856
3259
  debugLog2(
2857
3260
  "Isolated tracing provider created (service=%s)",
@@ -3189,21 +3592,29 @@ var tracing = {
3189
3592
  UserProfileError,
3190
3593
  UsersClient,
3191
3594
  addExperimentAttributes,
3595
+ assembleManifest,
3192
3596
  assignVariant,
3193
3597
  basicAuthHeader,
3598
+ canonicalJson,
3194
3599
  clearExperimentContext,
3600
+ computeBuildHash,
3195
3601
  computeHash,
3196
3602
  context,
3603
+ defineTool,
3197
3604
  experimentContextStorage,
3198
3605
  experiments,
3199
3606
  gateway,
3200
3607
  getExperimentContext,
3608
+ getRegisteredPrompts,
3609
+ getRegisteredTools,
3201
3610
  identify,
3202
3611
  loadSession,
3203
3612
  memory,
3204
3613
  personas,
3614
+ registerPrompt,
3205
3615
  renderAgentSystem,
3206
3616
  replay,
3617
+ resetBuildRegistry,
3207
3618
  resolveUserId,
3208
3619
  runSuite,
3209
3620
  runWithExperimentContext,