@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.
@@ -353,13 +353,22 @@ declare function observeAnthropic<T extends object>(client: T): T;
353
353
  * The Claude Agent SDK runs the agent in a separate `claude` CLI subprocess, so
354
354
  * there's nothing in-process to patch. What the app has is the message stream it
355
355
  * iterates. Wrap that stream with observeClaude() and it yields the same
356
- * messages unchanged while emitting spans on the Gateway provider:
356
+ * messages unchanged while emitting spans on the Gateway provider.
357
+ *
358
+ * Default (one trace per run):
357
359
  *
358
360
  * AGENT (root)
359
361
  * ├─ GENERATION per assistant turn (with per-turn token usage)
360
362
  * └─ TOOL per tool call (input from tool_use, output from the
361
363
  * matching tool_result, matched by id)
362
364
  *
365
+ * With `perTurn: true` (one trace PER ASSISTANT TURN — long agent runs read as
366
+ * a session of turn traces, the way a chat thread does):
367
+ *
368
+ * AGENT "<name> · turn N" (detached root; session/user attributes on every turn)
369
+ * ├─ GENERATION (that turn's usage + text)
370
+ * └─ TOOL per tool call in the turn
371
+ *
363
372
  * The TS equivalent of the Python SDK's claude-agent-sdk instrumentor.
364
373
  *
365
374
  * @example
@@ -372,7 +381,7 @@ declare function observeAnthropic<T extends object>(client: T): T;
372
381
  */
373
382
 
374
383
  interface ObserveClaudeOptions {
375
- /** Root span name (becomes the trace name). */
384
+ /** Root span name (becomes the trace name; per-turn mode appends `· turn N`). */
376
385
  name: string;
377
386
  /** Recorded as input.value on the root span → trace-level input. */
378
387
  input?: string;
@@ -385,10 +394,21 @@ interface ObserveClaudeOptions {
385
394
  */
386
395
  tracer?: Tracer;
387
396
  /**
388
- * Extra attributes for the ROOT span — e.g. gateway.session.id /
397
+ * Extra attributes for the root span(s) — e.g. gateway.session.id /
389
398
  * gateway.user.id to group runs into a session and attribute them to a user.
399
+ * In per-turn mode these ride EVERY turn root, so each turn trace maps to
400
+ * the session.
390
401
  */
391
402
  attributes?: Record<string, string>;
403
+ /**
404
+ * Emit one TRACE PER ASSISTANT TURN instead of a single trace for the whole
405
+ * run. Each turn's trace carries that turn's generation and tool calls; the
406
+ * turn's input is the run input (turn 1) or the tool results that fed it
407
+ * (later turns). Turn roots are detached (`root: true`), so they never nest
408
+ * under ambient spans. Combine with `attributes.gateway.session.id` to read
409
+ * a whole run as a session of turns.
410
+ */
411
+ perTurn?: boolean;
392
412
  }
393
413
  declare function observeClaude(stream: AsyncIterable<any>, options: ObserveClaudeOptions): AsyncGenerator<any>;
394
414
 
@@ -353,13 +353,22 @@ declare function observeAnthropic<T extends object>(client: T): T;
353
353
  * The Claude Agent SDK runs the agent in a separate `claude` CLI subprocess, so
354
354
  * there's nothing in-process to patch. What the app has is the message stream it
355
355
  * iterates. Wrap that stream with observeClaude() and it yields the same
356
- * messages unchanged while emitting spans on the Gateway provider:
356
+ * messages unchanged while emitting spans on the Gateway provider.
357
+ *
358
+ * Default (one trace per run):
357
359
  *
358
360
  * AGENT (root)
359
361
  * ├─ GENERATION per assistant turn (with per-turn token usage)
360
362
  * └─ TOOL per tool call (input from tool_use, output from the
361
363
  * matching tool_result, matched by id)
362
364
  *
365
+ * With `perTurn: true` (one trace PER ASSISTANT TURN — long agent runs read as
366
+ * a session of turn traces, the way a chat thread does):
367
+ *
368
+ * AGENT "<name> · turn N" (detached root; session/user attributes on every turn)
369
+ * ├─ GENERATION (that turn's usage + text)
370
+ * └─ TOOL per tool call in the turn
371
+ *
363
372
  * The TS equivalent of the Python SDK's claude-agent-sdk instrumentor.
364
373
  *
365
374
  * @example
@@ -372,7 +381,7 @@ declare function observeAnthropic<T extends object>(client: T): T;
372
381
  */
373
382
 
374
383
  interface ObserveClaudeOptions {
375
- /** Root span name (becomes the trace name). */
384
+ /** Root span name (becomes the trace name; per-turn mode appends `· turn N`). */
376
385
  name: string;
377
386
  /** Recorded as input.value on the root span → trace-level input. */
378
387
  input?: string;
@@ -385,10 +394,21 @@ interface ObserveClaudeOptions {
385
394
  */
386
395
  tracer?: Tracer;
387
396
  /**
388
- * Extra attributes for the ROOT span — e.g. gateway.session.id /
397
+ * Extra attributes for the root span(s) — e.g. gateway.session.id /
389
398
  * gateway.user.id to group runs into a session and attribute them to a user.
399
+ * In per-turn mode these ride EVERY turn root, so each turn trace maps to
400
+ * the session.
390
401
  */
391
402
  attributes?: Record<string, string>;
403
+ /**
404
+ * Emit one TRACE PER ASSISTANT TURN instead of a single trace for the whole
405
+ * run. Each turn's trace carries that turn's generation and tool calls; the
406
+ * turn's input is the run input (turn 1) or the tool results that fed it
407
+ * (later turns). Turn roots are detached (`root: true`), so they never nest
408
+ * under ambient spans. Combine with `attributes.gateway.session.id` to read
409
+ * a whole run as a session of turns.
410
+ */
411
+ perTurn?: boolean;
392
412
  }
393
413
  declare function observeClaude(stream: AsyncIterable<any>, options: ObserveClaudeOptions): AsyncGenerator<any>;
394
414
 
package/dist/index.d.mts CHANGED
@@ -5,9 +5,9 @@ export { Persona, PersonaError, PersonaMessage, PersonaReply, PersonasClient, Pe
5
5
  export { DriftError, LocalTool, MissPolicy, REPLAY_ENVIRONMENT, RecordedToolCall, ReplayAgent, ReplayCase, ReplayCheck, ReplayCredentials, ReplayError, ReplayMode, ReplayReport, ReplayStatus, ReplaySuite, ReplaySuiteLoadOptions, ReplayTask, RunSuiteOptions, SessionLoader, StubCallLogEntry, StubFallback, StubMatch, StubMissError, StubRegistryMapping, ToolStub, ToolStubRegistry, TraceDiff, replay, runSuite, suite } from './replay/index.mjs';
6
6
  export { GatewayAgentDescriptor, GatewaySecurity, GatewaySecurityConfig, GatewaySecurityContext, GatewaySecurityError, GatewayToolApprovalRequiredError, GatewayToolBlockedError, GatewayToolCallAuthorizeResponse, GatewayToolDescriptor, GatewayToolsetResolveResponse, SecureToolsOptions, gateway } from './security/index.mjs';
7
7
  export { DEFAULT_TIMEOUT_SECONDS, ENV_GATEWAY_HOST, ENV_GATEWAY_PUBLIC_KEY, ENV_GATEWAY_SECRET_KEY, LoadSessionOptions, SessionLoadError, SessionObservation, SessionRecording, SessionTrace, basicAuthHeader, loadSession, sessionObservationFromApi, sessions } from './sessions/index.mjs';
8
- export { UserProfile, UserProfileError, UserProfileUpdate, UsersClient, UsersClientConfig, UsersClientFromEnvConfig, users } from './users/index.mjs';
9
- import { _ as _tracingModule } from './index-DnowA8MG.mjs';
10
- export { I as IdentifyOptions, i as identify, r as resolveUserId } from './index-DnowA8MG.mjs';
8
+ export { UserEvent, UserEventOptions, UserProfile, UserProfileError, UserProfileUpdate, UsersClient, UsersClientConfig, UsersClientFromEnvConfig, users } from './users/index.mjs';
9
+ import { _ as _tracingModule } from './index-CubrUmOe.mjs';
10
+ export { I as IdentifyOptions, i as identify, r as resolveUserId } from './index-CubrUmOe.mjs';
11
11
  import 'async_hooks';
12
12
  import '@opentelemetry/api';
13
13
  import '@opentelemetry/sdk-trace-base';
package/dist/index.d.ts CHANGED
@@ -5,9 +5,9 @@ export { Persona, PersonaError, PersonaMessage, PersonaReply, PersonasClient, Pe
5
5
  export { DriftError, LocalTool, MissPolicy, REPLAY_ENVIRONMENT, RecordedToolCall, ReplayAgent, ReplayCase, ReplayCheck, ReplayCredentials, ReplayError, ReplayMode, ReplayReport, ReplayStatus, ReplaySuite, ReplaySuiteLoadOptions, ReplayTask, RunSuiteOptions, SessionLoader, StubCallLogEntry, StubFallback, StubMatch, StubMissError, StubRegistryMapping, ToolStub, ToolStubRegistry, TraceDiff, replay, runSuite, suite } from './replay/index.js';
6
6
  export { GatewayAgentDescriptor, GatewaySecurity, GatewaySecurityConfig, GatewaySecurityContext, GatewaySecurityError, GatewayToolApprovalRequiredError, GatewayToolBlockedError, GatewayToolCallAuthorizeResponse, GatewayToolDescriptor, GatewayToolsetResolveResponse, SecureToolsOptions, gateway } from './security/index.js';
7
7
  export { DEFAULT_TIMEOUT_SECONDS, ENV_GATEWAY_HOST, ENV_GATEWAY_PUBLIC_KEY, ENV_GATEWAY_SECRET_KEY, LoadSessionOptions, SessionLoadError, SessionObservation, SessionRecording, SessionTrace, basicAuthHeader, loadSession, sessionObservationFromApi, sessions } from './sessions/index.js';
8
- export { UserProfile, UserProfileError, UserProfileUpdate, UsersClient, UsersClientConfig, UsersClientFromEnvConfig, users } from './users/index.js';
9
- import { _ as _tracingModule } from './index-DnowA8MG.js';
10
- export { I as IdentifyOptions, i as identify, r as resolveUserId } from './index-DnowA8MG.js';
8
+ export { UserEvent, UserEventOptions, UserProfile, UserProfileError, UserProfileUpdate, UsersClient, UsersClientConfig, UsersClientFromEnvConfig, users } from './users/index.js';
9
+ import { _ as _tracingModule } from './index-CubrUmOe.js';
10
+ export { I as IdentifyOptions, i as identify, r as resolveUserId } from './index-CubrUmOe.js';
11
11
  import 'async_hooks';
12
12
  import '@opentelemetry/api';
13
13
  import '@opentelemetry/sdk-trace-base';
package/dist/index.js CHANGED
@@ -2542,6 +2542,58 @@ var UsersClient = class _UsersClient {
2542
2542
  await this.requestJson("POST", "/api/public/user-profiles", body)
2543
2543
  );
2544
2544
  }
2545
+ /**
2546
+ * Record a VALUE EVENT for a user — the per-user ROI stream. `value` is
2547
+ * whatever the event is worth in your terms (minutes saved, revenue…);
2548
+ * Gateway sums it in the hours-saved/ROI rollups, and evals and task-set
2549
+ * replays can assert against the events. Link `traceId`/`sessionId` to tie
2550
+ * the event to the run that produced it.
2551
+ *
2552
+ * @example
2553
+ * ```ts
2554
+ * await client.trackEvent("user-123", "checkout_completed", {
2555
+ * value: 25,
2556
+ * metadata: { cartSize: 3 },
2557
+ * sessionId,
2558
+ * });
2559
+ * ```
2560
+ */
2561
+ async trackEvent(userId, event, options = {}) {
2562
+ const body = {
2563
+ userId,
2564
+ event,
2565
+ metadata: options.metadata ?? {},
2566
+ ...options.value !== void 0 ? { value: options.value } : {},
2567
+ ...options.traceId !== void 0 ? { traceId: options.traceId } : {},
2568
+ ...options.sessionId !== void 0 ? { sessionId: options.sessionId } : {}
2569
+ };
2570
+ return parseEvent(
2571
+ await this.requestJson("POST", "/api/public/user-events", body)
2572
+ );
2573
+ }
2574
+ /** List a project's user events, optionally filtered by user/event/time. */
2575
+ async listEvents(filter = {}) {
2576
+ const params = new URLSearchParams();
2577
+ if (filter.userId) params.set("userId", filter.userId);
2578
+ if (filter.event) params.set("event", filter.event);
2579
+ if (filter.fromTimestamp)
2580
+ params.set("fromTimestamp", filter.fromTimestamp.toISOString());
2581
+ if (filter.toTimestamp)
2582
+ params.set("toTimestamp", filter.toTimestamp.toISOString());
2583
+ if (filter.page) params.set("page", String(filter.page));
2584
+ if (filter.limit) params.set("limit", String(filter.limit));
2585
+ const qs = params.toString();
2586
+ const payload = await this.requestJson(
2587
+ "GET",
2588
+ `/api/public/user-events${qs ? `?${qs}` : ""}`
2589
+ );
2590
+ const rows = Array.isArray(payload.data) ? payload.data : [];
2591
+ const meta = payload.meta && typeof payload.meta === "object" ? payload.meta : {};
2592
+ return {
2593
+ data: rows.map((row) => parseEvent(row)),
2594
+ totalItems: Number(meta.totalItems ?? rows.length)
2595
+ };
2596
+ }
2545
2597
  async requestJson(method, path, payload) {
2546
2598
  let response;
2547
2599
  try {
@@ -2580,6 +2632,18 @@ var UsersClient = class _UsersClient {
2580
2632
  }
2581
2633
  }
2582
2634
  };
2635
+ function parseEvent(payload) {
2636
+ return {
2637
+ id: String(payload.id ?? ""),
2638
+ userId: String(payload.userId ?? ""),
2639
+ event: String(payload.event ?? ""),
2640
+ value: typeof payload.value === "number" ? payload.value : null,
2641
+ metadata: payload.metadata && typeof payload.metadata === "object" && !Array.isArray(payload.metadata) ? payload.metadata : {},
2642
+ traceId: typeof payload.traceId === "string" ? payload.traceId : null,
2643
+ sessionId: typeof payload.sessionId === "string" ? payload.sessionId : null,
2644
+ createdAt: typeof payload.createdAt === "string" ? new Date(payload.createdAt) : /* @__PURE__ */ new Date(0)
2645
+ };
2646
+ }
2583
2647
  function parseProfile(payload) {
2584
2648
  return {
2585
2649
  userId: String(payload.userId ?? ""),
@@ -2996,33 +3060,74 @@ function toolResultText(content) {
2996
3060
  ).join("");
2997
3061
  return JSON.stringify(content ?? "");
2998
3062
  }
3063
+ var TURN_INPUT_MAX = 4e3;
2999
3064
  async function* observeClaude(stream, options) {
3000
3065
  const tracer = options.tracer ?? import_api3.trace.getTracer("@withgateway/sdk");
3001
- const root = tracer.startSpan(options.name, {
3002
- attributes: {
3003
- "openinference.span.kind": "AGENT",
3004
- ...options.input !== void 0 ? { "input.value": options.input } : {},
3005
- ...options.attributes ?? {}
3006
- }
3007
- });
3008
- const rootCtx = import_api3.trace.setSpan(import_api3.context.active(), root);
3009
- const openTools = /* @__PURE__ */ new Map();
3010
3066
  const model = options.model ?? "claude";
3067
+ const openTools = /* @__PURE__ */ new Map();
3068
+ let root = null;
3069
+ let rootCtx = null;
3070
+ if (!options.perTurn) {
3071
+ root = tracer.startSpan(options.name, {
3072
+ attributes: {
3073
+ "openinference.span.kind": "AGENT",
3074
+ ...options.input !== void 0 ? { "input.value": options.input } : {},
3075
+ ...options.attributes ?? {}
3076
+ }
3077
+ });
3078
+ rootCtx = import_api3.trace.setSpan(import_api3.context.active(), root);
3079
+ }
3080
+ let turnRoot = null;
3081
+ let turnCtx = null;
3082
+ let turnIndex = 0;
3083
+ let turnText = "";
3084
+ let pendingTurnInput = options.input ?? "";
3011
3085
  let finalText = "";
3086
+ const endTurn = () => {
3087
+ if (!turnRoot) return;
3088
+ if (turnText) turnRoot.setAttribute("output.value", turnText);
3089
+ turnRoot.setStatus({ code: import_api3.SpanStatusCode.OK });
3090
+ turnRoot.end();
3091
+ turnRoot = null;
3092
+ turnCtx = null;
3093
+ };
3012
3094
  try {
3013
3095
  for await (const message of stream) {
3014
3096
  if (message?.type === "assistant") {
3015
- let turnText = "";
3097
+ if (options.perTurn) {
3098
+ for (const span of openTools.values()) span.end();
3099
+ openTools.clear();
3100
+ endTurn();
3101
+ turnIndex += 1;
3102
+ turnText = "";
3103
+ turnRoot = tracer.startSpan(`${options.name} \xB7 turn ${turnIndex}`, {
3104
+ root: true,
3105
+ attributes: {
3106
+ "openinference.span.kind": "AGENT",
3107
+ ...pendingTurnInput ? { "input.value": pendingTurnInput.slice(0, TURN_INPUT_MAX) } : {},
3108
+ ...options.attributes ?? {}
3109
+ }
3110
+ });
3111
+ turnCtx = import_api3.trace.setSpan(import_api3.context.active(), turnRoot);
3112
+ pendingTurnInput = "";
3113
+ }
3114
+ const childCtx = options.perTurn ? turnCtx : rootCtx;
3115
+ let text = "";
3016
3116
  const toolUses = [];
3017
3117
  for (const block of message.message?.content ?? []) {
3018
3118
  if (block?.type === "text") {
3019
3119
  finalText += block.text;
3020
- turnText += block.text;
3120
+ text += block.text;
3021
3121
  }
3022
3122
  if (block?.type === "tool_use") {
3023
- toolUses.push({ id: block.id, name: block.name, input: block.input });
3123
+ toolUses.push({
3124
+ id: block.id,
3125
+ name: block.name,
3126
+ input: block.input
3127
+ });
3024
3128
  }
3025
3129
  }
3130
+ turnText += text;
3026
3131
  const gen = tracer.startSpan(
3027
3132
  "assistant",
3028
3133
  {
@@ -3030,10 +3135,10 @@ async function* observeClaude(stream, options) {
3030
3135
  "openinference.span.kind": "LLM",
3031
3136
  "llm.model_name": model,
3032
3137
  "llm.provider": "anthropic",
3033
- "output.value": turnText || toolUses.map((t) => `\u2192 ${cleanToolName(t.name)}`).join(", ")
3138
+ "output.value": text || toolUses.map((t) => `\u2192 ${cleanToolName(t.name)}`).join(", ")
3034
3139
  }
3035
3140
  },
3036
- rootCtx
3141
+ childCtx
3037
3142
  );
3038
3143
  const usage = message.message?.usage;
3039
3144
  if (usage?.input_tokens != null)
@@ -3051,7 +3156,7 @@ async function* observeClaude(stream, options) {
3051
3156
  "input.value": JSON.stringify(t.input)
3052
3157
  }
3053
3158
  },
3054
- rootCtx
3159
+ childCtx
3055
3160
  );
3056
3161
  openTools.set(t.id, span);
3057
3162
  }
@@ -3061,13 +3166,17 @@ async function* observeClaude(stream, options) {
3061
3166
  if (Array.isArray(content)) {
3062
3167
  for (const block of content) {
3063
3168
  if (block?.type === "tool_result") {
3169
+ const resultText = toolResultText(block.content);
3064
3170
  const span = openTools.get(block.tool_use_id);
3065
3171
  if (span) {
3066
- span.setAttribute("output.value", toolResultText(block.content));
3172
+ span.setAttribute("output.value", resultText);
3067
3173
  span.setStatus({ code: import_api3.SpanStatusCode.OK });
3068
3174
  span.end();
3069
3175
  openTools.delete(block.tool_use_id);
3070
3176
  }
3177
+ if (options.perTurn && pendingTurnInput.length < TURN_INPUT_MAX) {
3178
+ pendingTurnInput += (pendingTurnInput ? "\n" : "") + resultText.slice(0, TURN_INPUT_MAX - pendingTurnInput.length);
3179
+ }
3071
3180
  }
3072
3181
  }
3073
3182
  }
@@ -3077,9 +3186,13 @@ async function* observeClaude(stream, options) {
3077
3186
  } finally {
3078
3187
  for (const span of openTools.values()) span.end();
3079
3188
  openTools.clear();
3080
- root.setAttribute("output.value", finalText);
3081
- root.setStatus({ code: import_api3.SpanStatusCode.OK });
3082
- root.end();
3189
+ if (options.perTurn) {
3190
+ endTurn();
3191
+ } else if (root) {
3192
+ root.setAttribute("output.value", finalText);
3193
+ root.setStatus({ code: import_api3.SpanStatusCode.OK });
3194
+ root.end();
3195
+ }
3083
3196
  }
3084
3197
  }
3085
3198