@withgateway/sdk 0.1.6 → 0.1.8

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
@@ -2469,6 +2469,58 @@ var UsersClient = class _UsersClient {
2469
2469
  await this.requestJson("POST", "/api/public/user-profiles", body)
2470
2470
  );
2471
2471
  }
2472
+ /**
2473
+ * Record a VALUE EVENT for a user — the per-user ROI stream. `value` is
2474
+ * whatever the event is worth in your terms (minutes saved, revenue…);
2475
+ * Gateway sums it in the hours-saved/ROI rollups, and evals and task-set
2476
+ * replays can assert against the events. Link `traceId`/`sessionId` to tie
2477
+ * the event to the run that produced it.
2478
+ *
2479
+ * @example
2480
+ * ```ts
2481
+ * await client.trackEvent("user-123", "checkout_completed", {
2482
+ * value: 25,
2483
+ * metadata: { cartSize: 3 },
2484
+ * sessionId,
2485
+ * });
2486
+ * ```
2487
+ */
2488
+ async trackEvent(userId, event, options = {}) {
2489
+ const body = {
2490
+ userId,
2491
+ event,
2492
+ metadata: options.metadata ?? {},
2493
+ ...options.value !== void 0 ? { value: options.value } : {},
2494
+ ...options.traceId !== void 0 ? { traceId: options.traceId } : {},
2495
+ ...options.sessionId !== void 0 ? { sessionId: options.sessionId } : {}
2496
+ };
2497
+ return parseEvent(
2498
+ await this.requestJson("POST", "/api/public/user-events", body)
2499
+ );
2500
+ }
2501
+ /** List a project's user events, optionally filtered by user/event/time. */
2502
+ async listEvents(filter = {}) {
2503
+ const params = new URLSearchParams();
2504
+ if (filter.userId) params.set("userId", filter.userId);
2505
+ if (filter.event) params.set("event", filter.event);
2506
+ if (filter.fromTimestamp)
2507
+ params.set("fromTimestamp", filter.fromTimestamp.toISOString());
2508
+ if (filter.toTimestamp)
2509
+ params.set("toTimestamp", filter.toTimestamp.toISOString());
2510
+ if (filter.page) params.set("page", String(filter.page));
2511
+ if (filter.limit) params.set("limit", String(filter.limit));
2512
+ const qs = params.toString();
2513
+ const payload = await this.requestJson(
2514
+ "GET",
2515
+ `/api/public/user-events${qs ? `?${qs}` : ""}`
2516
+ );
2517
+ const rows = Array.isArray(payload.data) ? payload.data : [];
2518
+ const meta = payload.meta && typeof payload.meta === "object" ? payload.meta : {};
2519
+ return {
2520
+ data: rows.map((row) => parseEvent(row)),
2521
+ totalItems: Number(meta.totalItems ?? rows.length)
2522
+ };
2523
+ }
2472
2524
  async requestJson(method, path, payload) {
2473
2525
  let response;
2474
2526
  try {
@@ -2507,6 +2559,18 @@ var UsersClient = class _UsersClient {
2507
2559
  }
2508
2560
  }
2509
2561
  };
2562
+ function parseEvent(payload) {
2563
+ return {
2564
+ id: String(payload.id ?? ""),
2565
+ userId: String(payload.userId ?? ""),
2566
+ event: String(payload.event ?? ""),
2567
+ value: typeof payload.value === "number" ? payload.value : null,
2568
+ metadata: payload.metadata && typeof payload.metadata === "object" && !Array.isArray(payload.metadata) ? payload.metadata : {},
2569
+ traceId: typeof payload.traceId === "string" ? payload.traceId : null,
2570
+ sessionId: typeof payload.sessionId === "string" ? payload.sessionId : null,
2571
+ createdAt: typeof payload.createdAt === "string" ? new Date(payload.createdAt) : /* @__PURE__ */ new Date(0)
2572
+ };
2573
+ }
2510
2574
  function parseProfile(payload) {
2511
2575
  return {
2512
2576
  userId: String(payload.userId ?? ""),
@@ -2927,33 +2991,74 @@ function toolResultText(content) {
2927
2991
  ).join("");
2928
2992
  return JSON.stringify(content ?? "");
2929
2993
  }
2994
+ var TURN_INPUT_MAX = 4e3;
2930
2995
  async function* observeClaude(stream, options) {
2931
2996
  const tracer = options.tracer ?? trace3.getTracer("@withgateway/sdk");
2932
- const root = tracer.startSpan(options.name, {
2933
- attributes: {
2934
- "openinference.span.kind": "AGENT",
2935
- ...options.input !== void 0 ? { "input.value": options.input } : {},
2936
- ...options.attributes ?? {}
2937
- }
2938
- });
2939
- const rootCtx = trace3.setSpan(context3.active(), root);
2940
- const openTools = /* @__PURE__ */ new Map();
2941
2997
  const model = options.model ?? "claude";
2998
+ const openTools = /* @__PURE__ */ new Map();
2999
+ let root = null;
3000
+ let rootCtx = null;
3001
+ if (!options.perTurn) {
3002
+ root = tracer.startSpan(options.name, {
3003
+ attributes: {
3004
+ "openinference.span.kind": "AGENT",
3005
+ ...options.input !== void 0 ? { "input.value": options.input } : {},
3006
+ ...options.attributes ?? {}
3007
+ }
3008
+ });
3009
+ rootCtx = trace3.setSpan(context3.active(), root);
3010
+ }
3011
+ let turnRoot = null;
3012
+ let turnCtx = null;
3013
+ let turnIndex = 0;
3014
+ let turnText = "";
3015
+ let pendingTurnInput = options.input ?? "";
2942
3016
  let finalText = "";
3017
+ const endTurn = () => {
3018
+ if (!turnRoot) return;
3019
+ if (turnText) turnRoot.setAttribute("output.value", turnText);
3020
+ turnRoot.setStatus({ code: SpanStatusCode2.OK });
3021
+ turnRoot.end();
3022
+ turnRoot = null;
3023
+ turnCtx = null;
3024
+ };
2943
3025
  try {
2944
3026
  for await (const message of stream) {
2945
3027
  if (message?.type === "assistant") {
2946
- let turnText = "";
3028
+ if (options.perTurn) {
3029
+ for (const span of openTools.values()) span.end();
3030
+ openTools.clear();
3031
+ endTurn();
3032
+ turnIndex += 1;
3033
+ turnText = "";
3034
+ turnRoot = tracer.startSpan(`${options.name} \xB7 turn ${turnIndex}`, {
3035
+ root: true,
3036
+ attributes: {
3037
+ "openinference.span.kind": "AGENT",
3038
+ ...pendingTurnInput ? { "input.value": pendingTurnInput.slice(0, TURN_INPUT_MAX) } : {},
3039
+ ...options.attributes ?? {}
3040
+ }
3041
+ });
3042
+ turnCtx = trace3.setSpan(context3.active(), turnRoot);
3043
+ pendingTurnInput = "";
3044
+ }
3045
+ const childCtx = options.perTurn ? turnCtx : rootCtx;
3046
+ let text = "";
2947
3047
  const toolUses = [];
2948
3048
  for (const block of message.message?.content ?? []) {
2949
3049
  if (block?.type === "text") {
2950
3050
  finalText += block.text;
2951
- turnText += block.text;
3051
+ text += block.text;
2952
3052
  }
2953
3053
  if (block?.type === "tool_use") {
2954
- toolUses.push({ id: block.id, name: block.name, input: block.input });
3054
+ toolUses.push({
3055
+ id: block.id,
3056
+ name: block.name,
3057
+ input: block.input
3058
+ });
2955
3059
  }
2956
3060
  }
3061
+ turnText += text;
2957
3062
  const gen = tracer.startSpan(
2958
3063
  "assistant",
2959
3064
  {
@@ -2961,10 +3066,10 @@ async function* observeClaude(stream, options) {
2961
3066
  "openinference.span.kind": "LLM",
2962
3067
  "llm.model_name": model,
2963
3068
  "llm.provider": "anthropic",
2964
- "output.value": turnText || toolUses.map((t) => `\u2192 ${cleanToolName(t.name)}`).join(", ")
3069
+ "output.value": text || toolUses.map((t) => `\u2192 ${cleanToolName(t.name)}`).join(", ")
2965
3070
  }
2966
3071
  },
2967
- rootCtx
3072
+ childCtx
2968
3073
  );
2969
3074
  const usage = message.message?.usage;
2970
3075
  if (usage?.input_tokens != null)
@@ -2982,7 +3087,7 @@ async function* observeClaude(stream, options) {
2982
3087
  "input.value": JSON.stringify(t.input)
2983
3088
  }
2984
3089
  },
2985
- rootCtx
3090
+ childCtx
2986
3091
  );
2987
3092
  openTools.set(t.id, span);
2988
3093
  }
@@ -2992,13 +3097,17 @@ async function* observeClaude(stream, options) {
2992
3097
  if (Array.isArray(content)) {
2993
3098
  for (const block of content) {
2994
3099
  if (block?.type === "tool_result") {
3100
+ const resultText = toolResultText(block.content);
2995
3101
  const span = openTools.get(block.tool_use_id);
2996
3102
  if (span) {
2997
- span.setAttribute("output.value", toolResultText(block.content));
3103
+ span.setAttribute("output.value", resultText);
2998
3104
  span.setStatus({ code: SpanStatusCode2.OK });
2999
3105
  span.end();
3000
3106
  openTools.delete(block.tool_use_id);
3001
3107
  }
3108
+ if (options.perTurn && pendingTurnInput.length < TURN_INPUT_MAX) {
3109
+ pendingTurnInput += (pendingTurnInput ? "\n" : "") + resultText.slice(0, TURN_INPUT_MAX - pendingTurnInput.length);
3110
+ }
3002
3111
  }
3003
3112
  }
3004
3113
  }
@@ -3008,9 +3117,13 @@ async function* observeClaude(stream, options) {
3008
3117
  } finally {
3009
3118
  for (const span of openTools.values()) span.end();
3010
3119
  openTools.clear();
3011
- root.setAttribute("output.value", finalText);
3012
- root.setStatus({ code: SpanStatusCode2.OK });
3013
- root.end();
3120
+ if (options.perTurn) {
3121
+ endTurn();
3122
+ } else if (root) {
3123
+ root.setAttribute("output.value", finalText);
3124
+ root.setStatus({ code: SpanStatusCode2.OK });
3125
+ root.end();
3126
+ }
3014
3127
  }
3015
3128
  }
3016
3129