@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.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) {
@@ -2469,6 +2615,58 @@ var UsersClient = class _UsersClient {
2469
2615
  await this.requestJson("POST", "/api/public/user-profiles", body)
2470
2616
  );
2471
2617
  }
2618
+ /**
2619
+ * Record a VALUE EVENT for a user — the per-user ROI stream. `value` is
2620
+ * whatever the event is worth in your terms (minutes saved, revenue…);
2621
+ * Gateway sums it in the hours-saved/ROI rollups, and evals and task-set
2622
+ * replays can assert against the events. Link `traceId`/`sessionId` to tie
2623
+ * the event to the run that produced it.
2624
+ *
2625
+ * @example
2626
+ * ```ts
2627
+ * await client.trackEvent("user-123", "checkout_completed", {
2628
+ * value: 25,
2629
+ * metadata: { cartSize: 3 },
2630
+ * sessionId,
2631
+ * });
2632
+ * ```
2633
+ */
2634
+ async trackEvent(userId, event, options = {}) {
2635
+ const body = {
2636
+ userId,
2637
+ event,
2638
+ metadata: options.metadata ?? {},
2639
+ ...options.value !== void 0 ? { value: options.value } : {},
2640
+ ...options.traceId !== void 0 ? { traceId: options.traceId } : {},
2641
+ ...options.sessionId !== void 0 ? { sessionId: options.sessionId } : {}
2642
+ };
2643
+ return parseEvent(
2644
+ await this.requestJson("POST", "/api/public/user-events", body)
2645
+ );
2646
+ }
2647
+ /** List a project's user events, optionally filtered by user/event/time. */
2648
+ async listEvents(filter = {}) {
2649
+ const params = new URLSearchParams();
2650
+ if (filter.userId) params.set("userId", filter.userId);
2651
+ if (filter.event) params.set("event", filter.event);
2652
+ if (filter.fromTimestamp)
2653
+ params.set("fromTimestamp", filter.fromTimestamp.toISOString());
2654
+ if (filter.toTimestamp)
2655
+ params.set("toTimestamp", filter.toTimestamp.toISOString());
2656
+ if (filter.page) params.set("page", String(filter.page));
2657
+ if (filter.limit) params.set("limit", String(filter.limit));
2658
+ const qs = params.toString();
2659
+ const payload = await this.requestJson(
2660
+ "GET",
2661
+ `/api/public/user-events${qs ? `?${qs}` : ""}`
2662
+ );
2663
+ const rows = Array.isArray(payload.data) ? payload.data : [];
2664
+ const meta = payload.meta && typeof payload.meta === "object" ? payload.meta : {};
2665
+ return {
2666
+ data: rows.map((row) => parseEvent(row)),
2667
+ totalItems: Number(meta.totalItems ?? rows.length)
2668
+ };
2669
+ }
2472
2670
  async requestJson(method, path, payload) {
2473
2671
  let response;
2474
2672
  try {
@@ -2507,6 +2705,18 @@ var UsersClient = class _UsersClient {
2507
2705
  }
2508
2706
  }
2509
2707
  };
2708
+ function parseEvent(payload) {
2709
+ return {
2710
+ id: String(payload.id ?? ""),
2711
+ userId: String(payload.userId ?? ""),
2712
+ event: String(payload.event ?? ""),
2713
+ value: typeof payload.value === "number" ? payload.value : null,
2714
+ metadata: payload.metadata && typeof payload.metadata === "object" && !Array.isArray(payload.metadata) ? payload.metadata : {},
2715
+ traceId: typeof payload.traceId === "string" ? payload.traceId : null,
2716
+ sessionId: typeof payload.sessionId === "string" ? payload.sessionId : null,
2717
+ createdAt: typeof payload.createdAt === "string" ? new Date(payload.createdAt) : /* @__PURE__ */ new Date(0)
2718
+ };
2719
+ }
2510
2720
  function parseProfile(payload) {
2511
2721
  return {
2512
2722
  userId: String(payload.userId ?? ""),
@@ -2536,6 +2746,149 @@ var users = {
2536
2746
  fromEnv: UsersClient.fromEnv
2537
2747
  };
2538
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
+
2539
2892
  // src/tracing/identity.ts
2540
2893
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
2541
2894
  import { isSpanContextValid, trace } from "@opentelemetry/api";
@@ -2699,6 +3052,24 @@ function buildProvider(config, logFn) {
2699
3052
  if (config.version) {
2700
3053
  resourceAttrs["gateway.version"] = config.version;
2701
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
+ }
2702
3073
  let isLocalhost = false;
2703
3074
  if (endpoint) {
2704
3075
  try {
@@ -2758,7 +3129,28 @@ function buildProvider(config, logFn) {
2758
3129
  spanProcessors
2759
3130
  });
2760
3131
  }
2761
- 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
+ });
2762
3154
  }
2763
3155
  function init2(config = {}) {
2764
3156
  if (state.initialized) {
@@ -2766,8 +3158,10 @@ function init2(config = {}) {
2766
3158
  return;
2767
3159
  }
2768
3160
  state.debug = config.debug ?? false;
2769
- const provider = buildProvider(config, log);
3161
+ const built = buildProvider(config, log);
3162
+ const provider = built.provider;
2770
3163
  provider.register();
3164
+ scheduleBuildRegistration(config, built);
2771
3165
  state.provider = provider;
2772
3166
  state.initialized = true;
2773
3167
  log(
@@ -2778,7 +3172,9 @@ function init2(config = {}) {
2778
3172
  function initIsolated(config = {}) {
2779
3173
  const debugLog2 = config.debug ? (message, ...args) => console.log(`[gatewaysdk.tracing:isolated] ${message}`, ...args) : () => {
2780
3174
  };
2781
- const provider = buildProvider(config, debugLog2);
3175
+ const built = buildProvider(config, debugLog2);
3176
+ const provider = built.provider;
3177
+ scheduleBuildRegistration(config, built);
2782
3178
  const tracer = provider.getTracer("@withgateway/sdk");
2783
3179
  debugLog2(
2784
3180
  "Isolated tracing provider created (service=%s)",
@@ -3119,21 +3515,29 @@ export {
3119
3515
  UserProfileError,
3120
3516
  UsersClient,
3121
3517
  addExperimentAttributes,
3518
+ assembleManifest,
3122
3519
  assignVariant,
3123
3520
  basicAuthHeader,
3521
+ canonicalJson,
3124
3522
  clearExperimentContext,
3523
+ computeBuildHash,
3125
3524
  computeHash,
3126
3525
  context,
3526
+ defineTool,
3127
3527
  experimentContextStorage,
3128
3528
  singleton_exports as experiments,
3129
3529
  gateway,
3130
3530
  getExperimentContext,
3531
+ getRegisteredPrompts,
3532
+ getRegisteredTools,
3131
3533
  identify,
3132
3534
  loadSession,
3133
3535
  memory,
3134
3536
  personas,
3537
+ registerPrompt,
3135
3538
  renderAgentSystem,
3136
3539
  replay,
3540
+ resetBuildRegistry,
3137
3541
  resolveUserId,
3138
3542
  runSuite,
3139
3543
  runWithExperimentContext,