@sentrial/sdk 0.1.0 → 0.2.0

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
@@ -147,6 +147,12 @@ var EventType = /* @__PURE__ */ ((EventType2) => {
147
147
 
148
148
  // src/client.ts
149
149
  var DEFAULT_API_URL = "https://api.sentrial.com";
150
+ var MAX_RETRIES = 3;
151
+ var INITIAL_BACKOFF_MS = 500;
152
+ var MAX_BACKOFF_MS = 8e3;
153
+ var BACKOFF_MULTIPLIER = 2;
154
+ var RETRYABLE_STATUS_CODES = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
155
+ var REQUEST_TIMEOUT_MS = 1e4;
150
156
  var SentrialClient = class {
151
157
  apiUrl;
152
158
  apiKey;
@@ -158,54 +164,83 @@ var SentrialClient = class {
158
164
  this.failSilently = config.failSilently ?? true;
159
165
  }
160
166
  /**
161
- * Make an HTTP request with graceful error handling
167
+ * Make an HTTP request with retry logic and exponential backoff.
168
+ *
169
+ * Retries on transient failures (network errors, timeouts, 429/5xx).
170
+ * Up to MAX_RETRIES attempts with exponential backoff.
162
171
  */
163
172
  async safeRequest(method, url, body) {
164
- try {
165
- const headers = {
166
- "Content-Type": "application/json"
167
- };
168
- if (this.apiKey) {
169
- headers["Authorization"] = `Bearer ${this.apiKey}`;
170
- }
171
- const response = await fetch(url, {
172
- method,
173
- headers,
174
- body: body ? JSON.stringify(body) : void 0
175
- });
176
- if (!response.ok) {
177
- const errorBody = await response.text();
178
- let errorData = {};
173
+ let lastError;
174
+ let backoff = INITIAL_BACKOFF_MS;
175
+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
176
+ try {
177
+ const headers = {
178
+ "Content-Type": "application/json"
179
+ };
180
+ if (this.apiKey) {
181
+ headers["Authorization"] = `Bearer ${this.apiKey}`;
182
+ }
183
+ const controller = new AbortController();
184
+ const timeoutId = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
185
+ let response;
179
186
  try {
180
- errorData = JSON.parse(errorBody);
181
- } catch {
187
+ response = await fetch(url, {
188
+ method,
189
+ headers,
190
+ body: body ? JSON.stringify(body) : void 0,
191
+ signal: controller.signal
192
+ });
193
+ } finally {
194
+ clearTimeout(timeoutId);
182
195
  }
183
- const error = new ApiError(
184
- errorData.error?.message || `HTTP ${response.status}: ${response.statusText}`,
185
- response.status,
186
- errorData.error?.code
187
- );
188
- if (this.failSilently) {
189
- console.warn(`Sentrial: Request failed (${method} ${url}):`, error.message);
190
- return null;
196
+ if (RETRYABLE_STATUS_CODES.has(response.status) && attempt < MAX_RETRIES) {
197
+ await this.sleep(backoff);
198
+ backoff = Math.min(backoff * BACKOFF_MULTIPLIER, MAX_BACKOFF_MS);
199
+ continue;
200
+ }
201
+ if (!response.ok) {
202
+ const errorBody = await response.text();
203
+ let errorData = {};
204
+ try {
205
+ errorData = JSON.parse(errorBody);
206
+ } catch {
207
+ }
208
+ const error = new ApiError(
209
+ errorData.error?.message || `HTTP ${response.status}: ${response.statusText}`,
210
+ response.status,
211
+ errorData.error?.code
212
+ );
213
+ if (this.failSilently) {
214
+ console.warn(`Sentrial: Request failed (${method} ${url}):`, error.message);
215
+ return null;
216
+ }
217
+ throw error;
218
+ }
219
+ return await response.json();
220
+ } catch (error) {
221
+ if (error instanceof ApiError) {
222
+ throw error;
223
+ }
224
+ lastError = error instanceof Error ? error : new Error(String(error));
225
+ if (attempt < MAX_RETRIES) {
226
+ await this.sleep(backoff);
227
+ backoff = Math.min(backoff * BACKOFF_MULTIPLIER, MAX_BACKOFF_MS);
228
+ continue;
191
229
  }
192
- throw error;
193
- }
194
- return await response.json();
195
- } catch (error) {
196
- if (error instanceof SentrialError) {
197
- throw error;
198
- }
199
- const networkError = new NetworkError(
200
- error instanceof Error ? error.message : "Unknown network error",
201
- error instanceof Error ? error : void 0
202
- );
203
- if (this.failSilently) {
204
- console.warn(`Sentrial: Request failed (${method} ${url}):`, networkError.message);
205
- return null;
206
230
  }
207
- throw networkError;
208
231
  }
232
+ const networkError = new NetworkError(
233
+ lastError?.message ?? "Unknown network error",
234
+ lastError
235
+ );
236
+ if (this.failSilently) {
237
+ console.warn(`Sentrial: Request failed after ${MAX_RETRIES + 1} attempts (${method} ${url}):`, networkError.message);
238
+ return null;
239
+ }
240
+ throw networkError;
241
+ }
242
+ sleep(ms) {
243
+ return new Promise((resolve) => setTimeout(resolve, ms));
209
244
  }
210
245
  /**
211
246
  * Create a new session
@@ -221,6 +256,9 @@ var SentrialClient = class {
221
256
  userId: params.userId,
222
257
  metadata: params.metadata
223
258
  };
259
+ if (params.parentSessionId) {
260
+ payload.parentSessionId = params.parentSessionId;
261
+ }
224
262
  const response = await this.safeRequest(
225
263
  "POST",
226
264
  `${this.apiUrl}/api/sdk/sessions`,
@@ -314,6 +352,42 @@ var SentrialClient = class {
314
352
  updateState(key, value) {
315
353
  this.currentState[key] = value;
316
354
  }
355
+ /**
356
+ * Set the user input for a session
357
+ *
358
+ * @param sessionId - Session ID
359
+ * @param input - User input text
360
+ * @returns Updated session or null on error
361
+ */
362
+ async setInput(sessionId, input) {
363
+ return this.safeRequest(
364
+ "PATCH",
365
+ `${this.apiUrl}/api/sdk/sessions/${sessionId}`,
366
+ { userInput: input }
367
+ );
368
+ }
369
+ /**
370
+ * Track a generic event
371
+ *
372
+ * @param params - Event parameters
373
+ * @returns Event data or null on error
374
+ */
375
+ async trackEvent(params) {
376
+ const stateBefore = { ...this.currentState };
377
+ const payload = {
378
+ sessionId: params.sessionId,
379
+ eventType: params.eventType,
380
+ stateBefore,
381
+ stateAfter: { ...this.currentState }
382
+ };
383
+ if (params.eventData) {
384
+ Object.assign(payload, params.eventData);
385
+ }
386
+ if (params.metadata) {
387
+ payload.metadata = params.metadata;
388
+ }
389
+ return this.safeRequest("POST", `${this.apiUrl}/api/sdk/events`, payload);
390
+ }
317
391
  /**
318
392
  * Complete a session with performance metrics
319
393
  *
@@ -353,7 +427,8 @@ var SentrialClient = class {
353
427
  if (params.completionTokens !== void 0) payload.completionTokens = params.completionTokens;
354
428
  if (params.totalTokens !== void 0) payload.totalTokens = params.totalTokens;
355
429
  if (params.userInput !== void 0) payload.userInput = params.userInput;
356
- if (params.assistantOutput !== void 0) payload.assistantOutput = params.assistantOutput;
430
+ const output = params.assistantOutput ?? params.output;
431
+ if (output !== void 0) payload.assistantOutput = output;
357
432
  return this.safeRequest(
358
433
  "PATCH",
359
434
  `${this.apiUrl}/api/sdk/sessions/${params.sessionId}`,
@@ -400,7 +475,8 @@ var SentrialClient = class {
400
475
  sessionId,
401
476
  eventId,
402
477
  userId: params.userId,
403
- event: params.event
478
+ event: params.event,
479
+ userInput: params.input
404
480
  });
405
481
  }
406
482
  // Cost calculation static methods for convenience
@@ -421,6 +497,7 @@ var Interaction = class {
421
497
  success = true;
422
498
  failureReason;
423
499
  output;
500
+ userInput;
424
501
  degraded;
425
502
  constructor(config) {
426
503
  this.client = config.client;
@@ -428,6 +505,7 @@ var Interaction = class {
428
505
  this.eventId = config.eventId;
429
506
  this.userId = config.userId;
430
507
  this.event = config.event;
508
+ this.userInput = config.userInput;
431
509
  this.degraded = config.sessionId === null;
432
510
  }
433
511
  /**
@@ -473,6 +551,7 @@ var Interaction = class {
473
551
  promptTokens: params.promptTokens,
474
552
  completionTokens: params.completionTokens,
475
553
  totalTokens: params.totalTokens,
554
+ userInput: this.userInput,
476
555
  assistantOutput: finalOutput
477
556
  });
478
557
  }
@@ -538,19 +617,1473 @@ var sentrial = {
538
617
  configure,
539
618
  begin
540
619
  };
620
+
621
+ // src/vercel.ts
622
+ var _defaultClient = null;
623
+ var _globalConfig = {};
624
+ function configureVercel(config) {
625
+ _defaultClient = new SentrialClient({
626
+ apiKey: config.apiKey,
627
+ apiUrl: config.apiUrl,
628
+ failSilently: config.failSilently ?? true
629
+ });
630
+ _globalConfig = {
631
+ defaultAgent: config.defaultAgent,
632
+ userId: config.userId
633
+ };
634
+ }
635
+ function getClient2() {
636
+ if (!_defaultClient) {
637
+ _defaultClient = new SentrialClient();
638
+ }
639
+ return _defaultClient;
640
+ }
641
+ function extractModelInfo(model) {
642
+ const modelId = model.modelId || model.id || "unknown";
643
+ const provider = model.provider || guessProvider(modelId);
644
+ return { modelId, provider };
645
+ }
646
+ function guessProvider(modelId) {
647
+ if (modelId.includes("gpt") || modelId.includes("o1") || modelId.includes("o3")) return "openai";
648
+ if (modelId.includes("claude")) return "anthropic";
649
+ if (modelId.includes("gemini")) return "google";
650
+ if (modelId.includes("mistral")) return "mistral";
651
+ if (modelId.includes("llama")) return "meta";
652
+ return "unknown";
653
+ }
654
+ function calculateCostForCall(provider, modelId, promptTokens, completionTokens) {
655
+ const params = { model: modelId, inputTokens: promptTokens, outputTokens: completionTokens };
656
+ switch (provider.toLowerCase()) {
657
+ case "openai":
658
+ return calculateOpenAICost(params);
659
+ case "anthropic":
660
+ return calculateAnthropicCost(params);
661
+ case "google":
662
+ return calculateGoogleCost(params);
663
+ default:
664
+ return promptTokens * 3e-6 + completionTokens * 6e-6;
665
+ }
666
+ }
667
+ function extractInput(params) {
668
+ if (params.prompt) return params.prompt;
669
+ if (params.messages && params.messages.length > 0) {
670
+ const lastUserMessage = [...params.messages].reverse().find((m) => m.role === "user");
671
+ return lastUserMessage?.content || JSON.stringify(params.messages);
672
+ }
673
+ return "";
674
+ }
675
+ function wrapTools(tools, sessionId, client) {
676
+ if (!tools) return void 0;
677
+ const wrappedTools = {};
678
+ for (const [toolName, tool] of Object.entries(tools)) {
679
+ if (typeof tool.execute === "function") {
680
+ const originalExecute = tool.execute;
681
+ wrappedTools[toolName] = {
682
+ ...tool,
683
+ execute: async (...args) => {
684
+ const startTime = Date.now();
685
+ try {
686
+ const result = await originalExecute(...args);
687
+ const durationMs = Date.now() - startTime;
688
+ await client.trackToolCall({
689
+ sessionId,
690
+ toolName,
691
+ toolInput: args[0],
692
+ toolOutput: result,
693
+ reasoning: `Tool executed in ${durationMs}ms`
694
+ });
695
+ return result;
696
+ } catch (error) {
697
+ const durationMs = Date.now() - startTime;
698
+ await client.trackToolCall({
699
+ sessionId,
700
+ toolName,
701
+ toolInput: args[0],
702
+ toolOutput: {},
703
+ toolError: { message: error instanceof Error ? error.message : "Unknown error" },
704
+ reasoning: `Tool failed after ${durationMs}ms`
705
+ });
706
+ throw error;
707
+ }
708
+ }
709
+ };
710
+ } else {
711
+ wrappedTools[toolName] = tool;
712
+ }
713
+ }
714
+ return wrappedTools;
715
+ }
716
+ function wrapGenerateText(originalFn, client) {
717
+ return async (params) => {
718
+ const startTime = Date.now();
719
+ const { modelId, provider } = extractModelInfo(params.model);
720
+ const input = extractInput(params);
721
+ const sessionId = await client.createSession({
722
+ name: `generateText: ${input.slice(0, 50)}${input.length > 50 ? "..." : ""}`,
723
+ agentName: _globalConfig.defaultAgent ?? "vercel-ai-sdk",
724
+ userId: _globalConfig.userId ?? "anonymous",
725
+ metadata: {
726
+ model: modelId,
727
+ provider,
728
+ function: "generateText"
729
+ }
730
+ });
731
+ if (!sessionId) {
732
+ return originalFn(params);
733
+ }
734
+ await client.setInput(sessionId, input);
735
+ const wrappedParams = {
736
+ ...params,
737
+ tools: wrapTools(params.tools, sessionId, client)
738
+ };
739
+ try {
740
+ const result = await originalFn(wrappedParams);
741
+ const durationMs = Date.now() - startTime;
742
+ const promptTokens = result.usage?.promptTokens || 0;
743
+ const completionTokens = result.usage?.completionTokens || 0;
744
+ const totalTokens = result.usage?.totalTokens || promptTokens + completionTokens;
745
+ const cost = calculateCostForCall(provider, modelId, promptTokens, completionTokens);
746
+ await client.trackEvent({
747
+ sessionId,
748
+ eventType: "llm_call",
749
+ eventData: {
750
+ model: modelId,
751
+ provider,
752
+ prompt_tokens: promptTokens,
753
+ completion_tokens: completionTokens,
754
+ total_tokens: totalTokens,
755
+ finish_reason: result.finishReason,
756
+ tool_calls: result.toolCalls?.map((tc) => tc.toolName)
757
+ }
758
+ });
759
+ await client.completeSession({
760
+ sessionId,
761
+ success: true,
762
+ output: result.text,
763
+ durationMs,
764
+ estimatedCost: cost,
765
+ promptTokens,
766
+ completionTokens,
767
+ totalTokens
768
+ });
769
+ return result;
770
+ } catch (error) {
771
+ const durationMs = Date.now() - startTime;
772
+ await client.trackError({
773
+ sessionId,
774
+ errorType: error instanceof Error ? error.name : "Error",
775
+ errorMessage: error instanceof Error ? error.message : "Unknown error"
776
+ });
777
+ await client.completeSession({
778
+ sessionId,
779
+ success: false,
780
+ failureReason: error instanceof Error ? error.message : "Unknown error",
781
+ durationMs
782
+ });
783
+ throw error;
784
+ }
785
+ };
786
+ }
787
+ function wrapStreamText(originalFn, client) {
788
+ return (params) => {
789
+ const startTime = Date.now();
790
+ const { modelId, provider } = extractModelInfo(params.model);
791
+ const input = extractInput(params);
792
+ let sessionId = null;
793
+ const sessionPromise = client.createSession({
794
+ name: `streamText: ${input.slice(0, 50)}${input.length > 50 ? "..." : ""}`,
795
+ agentName: _globalConfig.defaultAgent ?? "vercel-ai-sdk",
796
+ userId: _globalConfig.userId ?? "anonymous",
797
+ metadata: {
798
+ model: modelId,
799
+ provider,
800
+ function: "streamText"
801
+ }
802
+ }).then((id) => {
803
+ sessionId = id;
804
+ if (id) client.setInput(id, input);
805
+ return id;
806
+ });
807
+ const wrappedParams = {
808
+ ...params,
809
+ tools: params.tools ? wrapToolsAsync(params.tools, sessionPromise, client) : void 0
810
+ };
811
+ const result = originalFn(wrappedParams);
812
+ const originalTextStream = result.textStream;
813
+ let fullText = "";
814
+ result.textStream = (async function* () {
815
+ try {
816
+ for await (const chunk of originalTextStream) {
817
+ fullText += chunk;
818
+ yield chunk;
819
+ }
820
+ const durationMs = Date.now() - startTime;
821
+ const sid = sessionId || await sessionPromise;
822
+ if (sid) {
823
+ const usage = result.usage ? await result.usage : void 0;
824
+ const promptTokens = usage?.promptTokens || 0;
825
+ const completionTokens = usage?.completionTokens || 0;
826
+ const totalTokens = usage?.totalTokens || promptTokens + completionTokens;
827
+ const cost = calculateCostForCall(provider, modelId, promptTokens, completionTokens);
828
+ await client.completeSession({
829
+ sessionId: sid,
830
+ success: true,
831
+ output: fullText,
832
+ durationMs,
833
+ estimatedCost: cost,
834
+ promptTokens,
835
+ completionTokens,
836
+ totalTokens
837
+ });
838
+ }
839
+ } catch (error) {
840
+ const durationMs = Date.now() - startTime;
841
+ const sid = sessionId || await sessionPromise;
842
+ if (sid) {
843
+ await client.trackError({
844
+ sessionId: sid,
845
+ errorType: error instanceof Error ? error.name : "Error",
846
+ errorMessage: error instanceof Error ? error.message : "Unknown error"
847
+ });
848
+ await client.completeSession({
849
+ sessionId: sid,
850
+ success: false,
851
+ failureReason: error instanceof Error ? error.message : "Unknown error",
852
+ durationMs
853
+ });
854
+ }
855
+ throw error;
856
+ }
857
+ })();
858
+ return result;
859
+ };
860
+ }
861
+ function wrapToolsAsync(tools, sessionPromise, client) {
862
+ const wrappedTools = {};
863
+ for (const [toolName, tool] of Object.entries(tools)) {
864
+ if (typeof tool.execute === "function") {
865
+ const originalExecute = tool.execute;
866
+ wrappedTools[toolName] = {
867
+ ...tool,
868
+ execute: async (...args) => {
869
+ const startTime = Date.now();
870
+ const sessionId = await sessionPromise;
871
+ try {
872
+ const result = await originalExecute(...args);
873
+ const durationMs = Date.now() - startTime;
874
+ if (sessionId) {
875
+ await client.trackToolCall({
876
+ sessionId,
877
+ toolName,
878
+ toolInput: args[0],
879
+ toolOutput: result,
880
+ reasoning: `Tool executed in ${durationMs}ms`
881
+ });
882
+ }
883
+ return result;
884
+ } catch (error) {
885
+ const durationMs = Date.now() - startTime;
886
+ if (sessionId) {
887
+ await client.trackToolCall({
888
+ sessionId,
889
+ toolName,
890
+ toolInput: args[0],
891
+ toolOutput: {},
892
+ toolError: { message: error instanceof Error ? error.message : "Unknown error" },
893
+ reasoning: `Tool failed after ${durationMs}ms`
894
+ });
895
+ }
896
+ throw error;
897
+ }
898
+ }
899
+ };
900
+ } else {
901
+ wrappedTools[toolName] = tool;
902
+ }
903
+ }
904
+ return wrappedTools;
905
+ }
906
+ function wrapGenerateObject(originalFn, client) {
907
+ return async (params) => {
908
+ const startTime = Date.now();
909
+ const { modelId, provider } = extractModelInfo(params.model);
910
+ const input = extractInput(params);
911
+ const sessionId = await client.createSession({
912
+ name: `generateObject: ${input.slice(0, 50)}${input.length > 50 ? "..." : ""}`,
913
+ agentName: _globalConfig.defaultAgent ?? "vercel-ai-sdk",
914
+ userId: _globalConfig.userId ?? "anonymous",
915
+ metadata: {
916
+ model: modelId,
917
+ provider,
918
+ function: "generateObject"
919
+ }
920
+ });
921
+ if (!sessionId) {
922
+ return originalFn(params);
923
+ }
924
+ await client.setInput(sessionId, input);
925
+ try {
926
+ const result = await originalFn(params);
927
+ const durationMs = Date.now() - startTime;
928
+ const promptTokens = result.usage?.promptTokens || 0;
929
+ const completionTokens = result.usage?.completionTokens || 0;
930
+ const totalTokens = result.usage?.totalTokens || promptTokens + completionTokens;
931
+ const cost = calculateCostForCall(provider, modelId, promptTokens, completionTokens);
932
+ await client.completeSession({
933
+ sessionId,
934
+ success: true,
935
+ output: JSON.stringify(result.object),
936
+ durationMs,
937
+ estimatedCost: cost,
938
+ promptTokens,
939
+ completionTokens,
940
+ totalTokens
941
+ });
942
+ return result;
943
+ } catch (error) {
944
+ const durationMs = Date.now() - startTime;
945
+ await client.trackError({
946
+ sessionId,
947
+ errorType: error instanceof Error ? error.name : "Error",
948
+ errorMessage: error instanceof Error ? error.message : "Unknown error"
949
+ });
950
+ await client.completeSession({
951
+ sessionId,
952
+ success: false,
953
+ failureReason: error instanceof Error ? error.message : "Unknown error",
954
+ durationMs
955
+ });
956
+ throw error;
957
+ }
958
+ };
959
+ }
960
+ function wrapStreamObject(originalFn, client) {
961
+ return (params) => {
962
+ const startTime = Date.now();
963
+ const { modelId, provider } = extractModelInfo(params.model);
964
+ const input = extractInput(params);
965
+ const sessionPromise = client.createSession({
966
+ name: `streamObject: ${input.slice(0, 50)}${input.length > 50 ? "..." : ""}`,
967
+ agentName: _globalConfig.defaultAgent ?? "vercel-ai-sdk",
968
+ userId: _globalConfig.userId ?? "anonymous",
969
+ metadata: {
970
+ model: modelId,
971
+ provider,
972
+ function: "streamObject"
973
+ }
974
+ }).then((id) => {
975
+ if (id) client.setInput(id, input);
976
+ return id;
977
+ });
978
+ const result = originalFn(params);
979
+ if (result.object) {
980
+ const originalObjectPromise = result.object;
981
+ result.object = originalObjectPromise.then(async (obj) => {
982
+ const durationMs = Date.now() - startTime;
983
+ const sessionId = await sessionPromise;
984
+ if (sessionId) {
985
+ const usage = result.usage ? await result.usage : void 0;
986
+ const promptTokens = usage?.promptTokens || 0;
987
+ const completionTokens = usage?.completionTokens || 0;
988
+ const totalTokens = usage?.totalTokens || promptTokens + completionTokens;
989
+ const cost = calculateCostForCall(provider, modelId, promptTokens, completionTokens);
990
+ await client.completeSession({
991
+ sessionId,
992
+ success: true,
993
+ output: JSON.stringify(obj),
994
+ durationMs,
995
+ estimatedCost: cost,
996
+ promptTokens,
997
+ completionTokens,
998
+ totalTokens
999
+ });
1000
+ }
1001
+ return obj;
1002
+ }).catch(async (error) => {
1003
+ const durationMs = Date.now() - startTime;
1004
+ const sessionId = await sessionPromise;
1005
+ if (sessionId) {
1006
+ await client.trackError({
1007
+ sessionId,
1008
+ errorType: error instanceof Error ? error.name : "Error",
1009
+ errorMessage: error instanceof Error ? error.message : "Unknown error"
1010
+ });
1011
+ await client.completeSession({
1012
+ sessionId,
1013
+ success: false,
1014
+ failureReason: error instanceof Error ? error.message : "Unknown error",
1015
+ durationMs
1016
+ });
1017
+ }
1018
+ throw error;
1019
+ });
1020
+ }
1021
+ return result;
1022
+ };
1023
+ }
1024
+ function wrapAISDK(ai) {
1025
+ const client = getClient2();
1026
+ return {
1027
+ generateText: ai.generateText ? wrapGenerateText(ai.generateText, client) : wrapGenerateText(() => Promise.reject(new Error("generateText not available")), client),
1028
+ streamText: ai.streamText ? wrapStreamText(ai.streamText, client) : wrapStreamText(() => ({ textStream: (async function* () {
1029
+ })() }), client),
1030
+ generateObject: ai.generateObject ? wrapGenerateObject(ai.generateObject, client) : wrapGenerateObject(() => Promise.reject(new Error("generateObject not available")), client),
1031
+ streamObject: ai.streamObject ? wrapStreamObject(ai.streamObject, client) : wrapStreamObject(() => ({}), client)
1032
+ };
1033
+ }
1034
+
1035
+ // src/wrappers.ts
1036
+ var _currentSessionId = null;
1037
+ var _currentClient = null;
1038
+ var _defaultClient2 = null;
1039
+ function setSessionContext(sessionId, client) {
1040
+ _currentSessionId = sessionId;
1041
+ if (client) {
1042
+ _currentClient = client;
1043
+ }
1044
+ }
1045
+ function clearSessionContext() {
1046
+ _currentSessionId = null;
1047
+ _currentClient = null;
1048
+ }
1049
+ function getSessionContext() {
1050
+ return _currentSessionId;
1051
+ }
1052
+ function setDefaultClient(client) {
1053
+ _defaultClient2 = client;
1054
+ }
1055
+ function getTrackingClient() {
1056
+ return _currentClient ?? _defaultClient2;
1057
+ }
1058
+ function wrapOpenAI(client, options = {}) {
1059
+ const { trackWithoutSession = false } = options;
1060
+ const chat = client.chat;
1061
+ if (!chat?.completions?.create) {
1062
+ console.warn("Sentrial: OpenAI client does not have chat.completions.create");
1063
+ return client;
1064
+ }
1065
+ const originalCreate = chat.completions.create.bind(chat.completions);
1066
+ chat.completions.create = async function(...args) {
1067
+ const startTime = Date.now();
1068
+ const params = args[0] ?? {};
1069
+ const messages = params.messages ?? [];
1070
+ const model = params.model ?? "unknown";
1071
+ try {
1072
+ const response = await originalCreate(...args);
1073
+ const durationMs = Date.now() - startTime;
1074
+ const promptTokens = response.usage?.prompt_tokens ?? 0;
1075
+ const completionTokens = response.usage?.completion_tokens ?? 0;
1076
+ const totalTokens = response.usage?.total_tokens ?? 0;
1077
+ let outputContent = "";
1078
+ if (response.choices?.[0]?.message?.content) {
1079
+ outputContent = response.choices[0].message.content;
1080
+ }
1081
+ const cost = calculateOpenAICost({ model, inputTokens: promptTokens, outputTokens: completionTokens });
1082
+ trackLLMCall({
1083
+ provider: "openai",
1084
+ model,
1085
+ messages,
1086
+ output: outputContent,
1087
+ promptTokens,
1088
+ completionTokens,
1089
+ totalTokens,
1090
+ cost,
1091
+ durationMs,
1092
+ trackWithoutSession
1093
+ });
1094
+ return response;
1095
+ } catch (error) {
1096
+ const durationMs = Date.now() - startTime;
1097
+ trackLLMError({
1098
+ provider: "openai",
1099
+ model,
1100
+ messages,
1101
+ error,
1102
+ durationMs,
1103
+ trackWithoutSession
1104
+ });
1105
+ throw error;
1106
+ }
1107
+ };
1108
+ return client;
1109
+ }
1110
+ function wrapAnthropic(client, options = {}) {
1111
+ const { trackWithoutSession = false } = options;
1112
+ const messages = client.messages;
1113
+ if (!messages?.create) {
1114
+ console.warn("Sentrial: Anthropic client does not have messages.create");
1115
+ return client;
1116
+ }
1117
+ const originalCreate = messages.create.bind(messages);
1118
+ messages.create = async function(...args) {
1119
+ const startTime = Date.now();
1120
+ const params = args[0] ?? {};
1121
+ const inputMessages = params.messages ?? [];
1122
+ const model = params.model ?? "unknown";
1123
+ const system = params.system ?? "";
1124
+ try {
1125
+ const response = await originalCreate(...args);
1126
+ const durationMs = Date.now() - startTime;
1127
+ const promptTokens = response.usage?.input_tokens ?? 0;
1128
+ const completionTokens = response.usage?.output_tokens ?? 0;
1129
+ const totalTokens = promptTokens + completionTokens;
1130
+ let outputContent = "";
1131
+ if (response.content) {
1132
+ for (const block of response.content) {
1133
+ if (block.type === "text") {
1134
+ outputContent += block.text;
1135
+ }
1136
+ }
1137
+ }
1138
+ const cost = calculateAnthropicCost({ model, inputTokens: promptTokens, outputTokens: completionTokens });
1139
+ const fullMessages = system ? [{ role: "system", content: system }, ...inputMessages] : inputMessages;
1140
+ trackLLMCall({
1141
+ provider: "anthropic",
1142
+ model,
1143
+ messages: fullMessages,
1144
+ output: outputContent,
1145
+ promptTokens,
1146
+ completionTokens,
1147
+ totalTokens,
1148
+ cost,
1149
+ durationMs,
1150
+ trackWithoutSession
1151
+ });
1152
+ return response;
1153
+ } catch (error) {
1154
+ const durationMs = Date.now() - startTime;
1155
+ trackLLMError({
1156
+ provider: "anthropic",
1157
+ model,
1158
+ messages: inputMessages,
1159
+ error,
1160
+ durationMs,
1161
+ trackWithoutSession
1162
+ });
1163
+ throw error;
1164
+ }
1165
+ };
1166
+ return client;
1167
+ }
1168
+ function wrapGoogle(model, options = {}) {
1169
+ const { trackWithoutSession = false } = options;
1170
+ const originalGenerate = model.generateContent;
1171
+ if (!originalGenerate) {
1172
+ console.warn("Sentrial: Google model does not have generateContent");
1173
+ return model;
1174
+ }
1175
+ model.generateContent = async function(...args) {
1176
+ const startTime = Date.now();
1177
+ const contents = args[0];
1178
+ const modelName = model.model ?? "gemini-unknown";
1179
+ const messages = googleContentsToMessages(contents);
1180
+ try {
1181
+ const response = await originalGenerate.apply(model, args);
1182
+ const durationMs = Date.now() - startTime;
1183
+ let promptTokens = 0;
1184
+ let completionTokens = 0;
1185
+ if (response.usageMetadata) {
1186
+ promptTokens = response.usageMetadata.promptTokenCount ?? 0;
1187
+ completionTokens = response.usageMetadata.candidatesTokenCount ?? 0;
1188
+ }
1189
+ const totalTokens = promptTokens + completionTokens;
1190
+ let outputContent = "";
1191
+ try {
1192
+ outputContent = response.response?.text() ?? "";
1193
+ } catch {
1194
+ }
1195
+ const cost = calculateGoogleCost({ model: modelName, inputTokens: promptTokens, outputTokens: completionTokens });
1196
+ trackLLMCall({
1197
+ provider: "google",
1198
+ model: modelName,
1199
+ messages,
1200
+ output: outputContent,
1201
+ promptTokens,
1202
+ completionTokens,
1203
+ totalTokens,
1204
+ cost,
1205
+ durationMs,
1206
+ trackWithoutSession
1207
+ });
1208
+ return response;
1209
+ } catch (error) {
1210
+ const durationMs = Date.now() - startTime;
1211
+ trackLLMError({
1212
+ provider: "google",
1213
+ model: modelName,
1214
+ messages,
1215
+ error,
1216
+ durationMs,
1217
+ trackWithoutSession
1218
+ });
1219
+ throw error;
1220
+ }
1221
+ };
1222
+ return model;
1223
+ }
1224
+ function googleContentsToMessages(contents) {
1225
+ if (typeof contents === "string") {
1226
+ return [{ role: "user", content: contents }];
1227
+ }
1228
+ if (Array.isArray(contents)) {
1229
+ return contents.map((item) => {
1230
+ if (typeof item === "string") {
1231
+ return { role: "user", content: item };
1232
+ }
1233
+ if (item && typeof item === "object") {
1234
+ return { role: item.role ?? "user", content: String(item.content ?? item) };
1235
+ }
1236
+ return { role: "user", content: String(item) };
1237
+ });
1238
+ }
1239
+ return [{ role: "user", content: String(contents) }];
1240
+ }
1241
+ function wrapLLM(client, provider) {
1242
+ if (provider === "openai" || client.chat?.completions?.create) {
1243
+ return wrapOpenAI(client);
1244
+ }
1245
+ if (provider === "anthropic" || client.messages?.create) {
1246
+ return wrapAnthropic(client);
1247
+ }
1248
+ if (provider === "google" || client.generateContent) {
1249
+ return wrapGoogle(client);
1250
+ }
1251
+ console.warn("Sentrial: Unknown LLM client type. No auto-tracking applied.");
1252
+ return client;
1253
+ }
1254
+ function trackLLMCall(params) {
1255
+ const client = getTrackingClient();
1256
+ if (!client) return;
1257
+ const sessionId = _currentSessionId;
1258
+ if (!sessionId && !params.trackWithoutSession) {
1259
+ return;
1260
+ }
1261
+ if (sessionId) {
1262
+ client.trackToolCall({
1263
+ sessionId,
1264
+ toolName: `llm:${params.provider}:${params.model}`,
1265
+ toolInput: {
1266
+ messages: params.messages,
1267
+ model: params.model,
1268
+ provider: params.provider
1269
+ },
1270
+ toolOutput: {
1271
+ content: params.output,
1272
+ tokens: {
1273
+ prompt: params.promptTokens,
1274
+ completion: params.completionTokens,
1275
+ total: params.totalTokens
1276
+ },
1277
+ cost_usd: params.cost
1278
+ },
1279
+ reasoning: `LLM call to ${params.provider} ${params.model}`,
1280
+ estimatedCost: params.cost,
1281
+ tokenCount: params.totalTokens,
1282
+ metadata: {
1283
+ provider: params.provider,
1284
+ model: params.model,
1285
+ duration_ms: params.durationMs,
1286
+ prompt_tokens: params.promptTokens,
1287
+ completion_tokens: params.completionTokens
1288
+ }
1289
+ }).catch((err) => {
1290
+ console.warn("Sentrial: Failed to track LLM call:", err.message);
1291
+ });
1292
+ }
1293
+ }
1294
+ function trackLLMError(params) {
1295
+ const client = getTrackingClient();
1296
+ if (!client) return;
1297
+ const sessionId = _currentSessionId;
1298
+ if (!sessionId && !params.trackWithoutSession) {
1299
+ return;
1300
+ }
1301
+ if (sessionId) {
1302
+ client.trackError({
1303
+ sessionId,
1304
+ errorMessage: params.error.message,
1305
+ errorType: params.error.name,
1306
+ toolName: `llm:${params.provider}:${params.model}`,
1307
+ metadata: {
1308
+ provider: params.provider,
1309
+ model: params.model,
1310
+ duration_ms: params.durationMs
1311
+ }
1312
+ }).catch((err) => {
1313
+ console.warn("Sentrial: Failed to track LLM error:", err.message);
1314
+ });
1315
+ }
1316
+ }
1317
+
1318
+ // src/decorators.ts
1319
+ var _defaultClient3 = null;
1320
+ var _currentInteraction = null;
1321
+ function getClient3() {
1322
+ if (!_defaultClient3) {
1323
+ try {
1324
+ _defaultClient3 = new SentrialClient();
1325
+ setDefaultClient(_defaultClient3);
1326
+ } catch {
1327
+ return null;
1328
+ }
1329
+ }
1330
+ return _defaultClient3;
1331
+ }
1332
+ function setClient(client) {
1333
+ _defaultClient3 = client;
1334
+ setDefaultClient(client);
1335
+ }
1336
+ function getCurrentSessionId() {
1337
+ return getSessionContext();
1338
+ }
1339
+ function getCurrentInteraction() {
1340
+ return _currentInteraction;
1341
+ }
1342
+ function withTool(name, fn) {
1343
+ const isAsync = fn.constructor.name === "AsyncFunction";
1344
+ if (isAsync) {
1345
+ return async function(...args) {
1346
+ return trackToolAsync(name, fn, args);
1347
+ };
1348
+ } else {
1349
+ return function(...args) {
1350
+ return trackToolSync(name, fn, args);
1351
+ };
1352
+ }
1353
+ }
1354
+ async function trackToolAsync(toolName, fn, args) {
1355
+ const startTime = Date.now();
1356
+ const toolInput = buildToolInput(args);
1357
+ const client = getClient3();
1358
+ const sessionId = getSessionContext();
1359
+ try {
1360
+ const result = await fn(...args);
1361
+ const durationMs = Date.now() - startTime;
1362
+ if (client && sessionId) {
1363
+ const toolOutput = serializeOutput(result);
1364
+ client.trackToolCall({
1365
+ sessionId,
1366
+ toolName,
1367
+ toolInput,
1368
+ toolOutput,
1369
+ metadata: { duration_ms: durationMs }
1370
+ }).catch((err) => {
1371
+ console.warn(`Sentrial: Failed to track tool ${toolName}:`, err.message);
1372
+ });
1373
+ }
1374
+ return result;
1375
+ } catch (error) {
1376
+ const durationMs = Date.now() - startTime;
1377
+ if (client && sessionId) {
1378
+ client.trackError({
1379
+ sessionId,
1380
+ errorMessage: error.message,
1381
+ errorType: error.name,
1382
+ toolName,
1383
+ stackTrace: error.stack,
1384
+ metadata: { duration_ms: durationMs }
1385
+ }).catch(() => {
1386
+ });
1387
+ }
1388
+ throw error;
1389
+ }
1390
+ }
1391
+ function trackToolSync(toolName, fn, args) {
1392
+ const startTime = Date.now();
1393
+ const toolInput = buildToolInput(args);
1394
+ const client = getClient3();
1395
+ const sessionId = getSessionContext();
1396
+ try {
1397
+ const result = fn(...args);
1398
+ const durationMs = Date.now() - startTime;
1399
+ if (client && sessionId) {
1400
+ const toolOutput = serializeOutput(result);
1401
+ client.trackToolCall({
1402
+ sessionId,
1403
+ toolName,
1404
+ toolInput,
1405
+ toolOutput,
1406
+ metadata: { duration_ms: durationMs }
1407
+ }).catch((err) => {
1408
+ console.warn(`Sentrial: Failed to track tool ${toolName}:`, err.message);
1409
+ });
1410
+ }
1411
+ return result;
1412
+ } catch (error) {
1413
+ const durationMs = Date.now() - startTime;
1414
+ if (client && sessionId) {
1415
+ client.trackError({
1416
+ sessionId,
1417
+ errorMessage: error.message,
1418
+ errorType: error.name,
1419
+ toolName,
1420
+ stackTrace: error.stack,
1421
+ metadata: { duration_ms: durationMs }
1422
+ }).catch(() => {
1423
+ });
1424
+ }
1425
+ throw error;
1426
+ }
1427
+ }
1428
+ function withSession(agentName, fn, options = {}) {
1429
+ return async function(...args) {
1430
+ const client = getClient3();
1431
+ if (!client) {
1432
+ return fn(...args);
1433
+ }
1434
+ const { userId, userInput } = extractParams(args, options);
1435
+ const interaction = await client.begin({
1436
+ userId,
1437
+ event: agentName,
1438
+ input: userInput
1439
+ });
1440
+ const sessionId = interaction.getSessionId();
1441
+ if (sessionId) {
1442
+ setSessionContext(sessionId, client);
1443
+ }
1444
+ _currentInteraction = interaction;
1445
+ try {
1446
+ const result = await fn(...args);
1447
+ let output;
1448
+ if (typeof result === "string") {
1449
+ output = result;
1450
+ } else if (result && typeof result === "object") {
1451
+ if ("response" in result) {
1452
+ output = String(result.response);
1453
+ } else if ("output" in result) {
1454
+ output = String(result.output);
1455
+ }
1456
+ }
1457
+ if (output === void 0 && result !== null && result !== void 0) {
1458
+ output = String(result).slice(0, 1e3);
1459
+ }
1460
+ await interaction.finish({ output, success: true });
1461
+ return result;
1462
+ } catch (error) {
1463
+ await interaction.finish({
1464
+ success: false,
1465
+ failureReason: `${error.name}: ${error.message}`
1466
+ });
1467
+ throw error;
1468
+ } finally {
1469
+ clearSessionContext();
1470
+ _currentInteraction = null;
1471
+ }
1472
+ };
1473
+ }
1474
+ function extractParams(args, options) {
1475
+ let userId = "anonymous";
1476
+ let userInput;
1477
+ if (typeof options.userIdParam === "number") {
1478
+ userId = String(args[options.userIdParam] ?? "anonymous");
1479
+ } else if (typeof options.userIdParam === "string") {
1480
+ userId = String(args[0] ?? "anonymous");
1481
+ } else {
1482
+ userId = String(args[0] ?? "anonymous");
1483
+ }
1484
+ if (typeof options.inputParam === "number") {
1485
+ userInput = String(args[options.inputParam] ?? "");
1486
+ } else {
1487
+ const input = args[1];
1488
+ if (typeof input === "string") {
1489
+ userInput = input;
1490
+ } else if (Array.isArray(input)) {
1491
+ userInput = JSON.stringify(input).slice(0, 500);
1492
+ }
1493
+ }
1494
+ return { userId, userInput };
1495
+ }
1496
+ function Tool(name) {
1497
+ return function(_target, propertyKey, descriptor) {
1498
+ const originalMethod = descriptor.value;
1499
+ const toolName = name ?? String(propertyKey);
1500
+ descriptor.value = async function(...args) {
1501
+ const startTime = Date.now();
1502
+ const toolInput = buildToolInput(args);
1503
+ const client = getClient3();
1504
+ const sessionId = getSessionContext();
1505
+ try {
1506
+ const result = await originalMethod.apply(this, args);
1507
+ const durationMs = Date.now() - startTime;
1508
+ if (client && sessionId) {
1509
+ const toolOutput = serializeOutput(result);
1510
+ client.trackToolCall({
1511
+ sessionId,
1512
+ toolName,
1513
+ toolInput,
1514
+ toolOutput,
1515
+ metadata: { duration_ms: durationMs }
1516
+ }).catch((err) => {
1517
+ console.warn(`Sentrial: Failed to track tool ${toolName}:`, err.message);
1518
+ });
1519
+ }
1520
+ return result;
1521
+ } catch (error) {
1522
+ const durationMs = Date.now() - startTime;
1523
+ if (client && sessionId) {
1524
+ client.trackError({
1525
+ sessionId,
1526
+ errorMessage: error.message,
1527
+ errorType: error.name,
1528
+ toolName,
1529
+ stackTrace: error.stack,
1530
+ metadata: { duration_ms: durationMs }
1531
+ }).catch(() => {
1532
+ });
1533
+ }
1534
+ throw error;
1535
+ }
1536
+ };
1537
+ return descriptor;
1538
+ };
1539
+ }
1540
+ function TrackSession(agentName, options) {
1541
+ return function(target, _propertyKey, descriptor) {
1542
+ const originalMethod = descriptor.value;
1543
+ const agent = agentName ?? target.constructor.name;
1544
+ descriptor.value = async function(...args) {
1545
+ const client = getClient3();
1546
+ if (!client) {
1547
+ return originalMethod.apply(this, args);
1548
+ }
1549
+ const { userId, userInput } = extractParams(args, options ?? {});
1550
+ const interaction = await client.begin({
1551
+ userId,
1552
+ event: agent,
1553
+ input: userInput
1554
+ });
1555
+ const sessionId = interaction.getSessionId();
1556
+ if (sessionId) {
1557
+ setSessionContext(sessionId, client);
1558
+ }
1559
+ _currentInteraction = interaction;
1560
+ try {
1561
+ const result = await originalMethod.apply(this, args);
1562
+ let output;
1563
+ if (typeof result === "string") {
1564
+ output = result;
1565
+ } else if (result && typeof result === "object") {
1566
+ if ("response" in result) {
1567
+ output = String(result.response);
1568
+ } else if ("output" in result) {
1569
+ output = String(result.output);
1570
+ }
1571
+ }
1572
+ if (output === void 0 && result !== null && result !== void 0) {
1573
+ output = String(result).slice(0, 1e3);
1574
+ }
1575
+ await interaction.finish({ output, success: true });
1576
+ return result;
1577
+ } catch (error) {
1578
+ await interaction.finish({
1579
+ success: false,
1580
+ failureReason: `${error.name}: ${error.message}`
1581
+ });
1582
+ throw error;
1583
+ } finally {
1584
+ clearSessionContext();
1585
+ _currentInteraction = null;
1586
+ }
1587
+ };
1588
+ return descriptor;
1589
+ };
1590
+ }
1591
+ var SessionContext = class {
1592
+ userId;
1593
+ agent;
1594
+ input;
1595
+ client;
1596
+ interaction = null;
1597
+ output;
1598
+ constructor(options) {
1599
+ this.userId = options.userId;
1600
+ this.agent = options.agent;
1601
+ this.input = options.input;
1602
+ this.client = options.client ?? getClient3();
1603
+ }
1604
+ /**
1605
+ * Start the session
1606
+ */
1607
+ async start() {
1608
+ if (!this.client) return this;
1609
+ this.interaction = await this.client.begin({
1610
+ userId: this.userId,
1611
+ event: this.agent,
1612
+ input: this.input
1613
+ });
1614
+ const sessionId = this.interaction.getSessionId();
1615
+ if (sessionId) {
1616
+ setSessionContext(sessionId, this.client);
1617
+ }
1618
+ _currentInteraction = this.interaction;
1619
+ return this;
1620
+ }
1621
+ /**
1622
+ * Set the output for this session
1623
+ */
1624
+ setOutput(output) {
1625
+ this.output = output;
1626
+ }
1627
+ /**
1628
+ * Finish the session
1629
+ */
1630
+ async finish(options) {
1631
+ if (this.interaction) {
1632
+ await this.interaction.finish({
1633
+ output: this.output,
1634
+ success: options?.success ?? true,
1635
+ failureReason: options?.error
1636
+ });
1637
+ }
1638
+ clearSessionContext();
1639
+ _currentInteraction = null;
1640
+ }
1641
+ /**
1642
+ * Get the session ID
1643
+ */
1644
+ get sessionId() {
1645
+ return this.interaction?.getSessionId() ?? null;
1646
+ }
1647
+ };
1648
+ function buildToolInput(args) {
1649
+ if (args.length === 0) {
1650
+ return {};
1651
+ }
1652
+ if (args.length === 1 && typeof args[0] === "object" && args[0] !== null) {
1653
+ return serializeValue(args[0]);
1654
+ }
1655
+ return {
1656
+ args: args.map(serializeValue)
1657
+ };
1658
+ }
1659
+ function serializeValue(value) {
1660
+ if (value === null || value === void 0) {
1661
+ return value;
1662
+ }
1663
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
1664
+ return value;
1665
+ }
1666
+ if (Array.isArray(value)) {
1667
+ return value.map(serializeValue);
1668
+ }
1669
+ if (typeof value === "object") {
1670
+ const result = {};
1671
+ for (const [k, v] of Object.entries(value)) {
1672
+ result[k] = serializeValue(v);
1673
+ }
1674
+ return result;
1675
+ }
1676
+ try {
1677
+ return String(value).slice(0, 1e3);
1678
+ } catch {
1679
+ return `<${typeof value}>`;
1680
+ }
1681
+ }
1682
+ function serializeOutput(value) {
1683
+ if (value === null || value === void 0) {
1684
+ return { result: null };
1685
+ }
1686
+ if (typeof value === "object" && !Array.isArray(value)) {
1687
+ return serializeValue(value);
1688
+ }
1689
+ return { result: serializeValue(value) };
1690
+ }
1691
+
1692
+ // src/context.ts
1693
+ var _experimentContext = null;
1694
+ function getSystemPrompt(defaultPrompt) {
1695
+ if (_experimentContext?.systemPrompt) {
1696
+ return _experimentContext.systemPrompt;
1697
+ }
1698
+ return defaultPrompt ?? "";
1699
+ }
1700
+ function getExperimentContext() {
1701
+ return _experimentContext;
1702
+ }
1703
+ function isExperimentMode() {
1704
+ return _experimentContext !== null;
1705
+ }
1706
+ function getVariantName() {
1707
+ return _experimentContext?.variantName ?? null;
1708
+ }
1709
+ function getExperimentId() {
1710
+ return _experimentContext?.experimentId ?? null;
1711
+ }
1712
+ function setExperimentContext(context) {
1713
+ _experimentContext = context;
1714
+ }
1715
+ function clearExperimentContext() {
1716
+ _experimentContext = null;
1717
+ }
1718
+
1719
+ // src/experiment.ts
1720
+ var ExperimentRunTracker = class {
1721
+ experiment;
1722
+ variantName;
1723
+ baseSessionId;
1724
+ runId;
1725
+ resultSessionId;
1726
+ _success = true;
1727
+ _errorMessage;
1728
+ /** @internal */
1729
+ constructor(experiment, variantName, baseSessionId) {
1730
+ this.experiment = experiment;
1731
+ this.variantName = variantName;
1732
+ this.baseSessionId = baseSessionId;
1733
+ }
1734
+ /**
1735
+ * Start the run - creates a run record via API.
1736
+ */
1737
+ async start() {
1738
+ try {
1739
+ const response = await this.experiment.request(
1740
+ "POST",
1741
+ `/api/experiments/${this.experiment.experimentId}/runs`,
1742
+ {
1743
+ variantName: this.variantName,
1744
+ baseSessionId: this.baseSessionId
1745
+ }
1746
+ );
1747
+ this.runId = response?.run?.id;
1748
+ } catch {
1749
+ }
1750
+ return this;
1751
+ }
1752
+ /**
1753
+ * Set the session ID of the result session.
1754
+ */
1755
+ setResultSessionId(sessionId) {
1756
+ this.resultSessionId = sessionId;
1757
+ }
1758
+ /**
1759
+ * Mark the run as complete.
1760
+ */
1761
+ async complete() {
1762
+ if (!this.runId) return;
1763
+ try {
1764
+ await this.experiment.request(
1765
+ "PATCH",
1766
+ `/api/experiments/${this.experiment.experimentId}/runs/${this.runId}`,
1767
+ {
1768
+ status: "completed",
1769
+ resultSessionId: this.resultSessionId
1770
+ }
1771
+ );
1772
+ } catch {
1773
+ }
1774
+ }
1775
+ /**
1776
+ * Mark the run as failed.
1777
+ */
1778
+ async fail(errorMessage) {
1779
+ this._success = false;
1780
+ this._errorMessage = errorMessage;
1781
+ if (!this.runId) return;
1782
+ try {
1783
+ await this.experiment.request(
1784
+ "PATCH",
1785
+ `/api/experiments/${this.experiment.experimentId}/runs/${this.runId}`,
1786
+ {
1787
+ status: "failed",
1788
+ resultSessionId: this.resultSessionId,
1789
+ errorMessage
1790
+ }
1791
+ );
1792
+ } catch {
1793
+ }
1794
+ }
1795
+ /**
1796
+ * Get the result of this run.
1797
+ */
1798
+ getResult() {
1799
+ return {
1800
+ variantName: this.variantName,
1801
+ testCaseSessionId: this.baseSessionId,
1802
+ resultSessionId: this.resultSessionId,
1803
+ success: this._success,
1804
+ errorMessage: this._errorMessage
1805
+ };
1806
+ }
1807
+ };
1808
+ var Experiment = class {
1809
+ /** The experiment ID */
1810
+ experimentId;
1811
+ /** @internal */
1812
+ client;
1813
+ /** @internal */
1814
+ apiUrl;
1815
+ /** @internal */
1816
+ apiKey;
1817
+ config;
1818
+ _variants;
1819
+ _testCases;
1820
+ /**
1821
+ * Create an experiment instance.
1822
+ *
1823
+ * @param experimentId - The experiment ID from Sentrial dashboard
1824
+ * @param options - Configuration options
1825
+ */
1826
+ constructor(experimentId, options = {}) {
1827
+ this.experimentId = experimentId;
1828
+ this.apiUrl = (options.apiUrl ?? (typeof process !== "undefined" ? process.env?.SENTRIAL_API_URL : void 0) ?? "https://api.sentrial.com").replace(/\/$/, "");
1829
+ this.apiKey = options.apiKey ?? (typeof process !== "undefined" ? process.env?.SENTRIAL_API_KEY : void 0);
1830
+ this.client = new SentrialClient({
1831
+ apiKey: this.apiKey,
1832
+ apiUrl: this.apiUrl,
1833
+ failSilently: false
1834
+ // We want errors for experiments
1835
+ });
1836
+ }
1837
+ /**
1838
+ * Make an HTTP request to the API
1839
+ * @internal
1840
+ */
1841
+ async request(method, path, body) {
1842
+ const headers = {
1843
+ "Content-Type": "application/json"
1844
+ };
1845
+ if (this.apiKey) {
1846
+ headers["Authorization"] = `Bearer ${this.apiKey}`;
1847
+ }
1848
+ const response = await fetch(`${this.apiUrl}${path}`, {
1849
+ method,
1850
+ headers,
1851
+ body: body ? JSON.stringify(body) : void 0
1852
+ });
1853
+ if (!response.ok) {
1854
+ return null;
1855
+ }
1856
+ return response.json();
1857
+ }
1858
+ /**
1859
+ * Load the experiment configuration from the API.
1860
+ */
1861
+ async load() {
1862
+ const response = await this.request(
1863
+ "GET",
1864
+ `/api/experiments/${this.experimentId}/runs`
1865
+ );
1866
+ if (!response?.experiment) {
1867
+ throw new Error(`Failed to load experiment config for ${this.experimentId}`);
1868
+ }
1869
+ this.config = response.experiment;
1870
+ const variants = this.config.variants;
1871
+ this._variants = variants?.map((v) => ({
1872
+ name: v.name ?? "",
1873
+ systemPrompt: v.systemPrompt ?? "",
1874
+ description: v.description
1875
+ })) ?? [];
1876
+ const testCases = this.config.testCases;
1877
+ this._testCases = testCases?.filter((tc) => tc.userInput)?.map((tc) => ({
1878
+ sessionId: tc.sessionId ?? "",
1879
+ userInput: tc.userInput ?? ""
1880
+ })) ?? [];
1881
+ return this;
1882
+ }
1883
+ /**
1884
+ * Get experiment name.
1885
+ */
1886
+ get name() {
1887
+ return this.config?.name ?? "";
1888
+ }
1889
+ /**
1890
+ * Get experiment status.
1891
+ */
1892
+ get status() {
1893
+ return this.config?.status ?? "";
1894
+ }
1895
+ /**
1896
+ * Get list of variants to test.
1897
+ */
1898
+ get variants() {
1899
+ if (!this._variants) {
1900
+ throw new Error("Experiment not loaded. Call load() first.");
1901
+ }
1902
+ return this._variants;
1903
+ }
1904
+ /**
1905
+ * Get list of test cases.
1906
+ */
1907
+ get testCases() {
1908
+ if (!this._testCases) {
1909
+ throw new Error("Experiment not loaded. Call load() first.");
1910
+ }
1911
+ return this._testCases;
1912
+ }
1913
+ /**
1914
+ * Get a specific variant by name.
1915
+ */
1916
+ getVariant(name) {
1917
+ return this.variants.find((v) => v.name === name);
1918
+ }
1919
+ /**
1920
+ * Create a run tracker for manual experiment runs.
1921
+ */
1922
+ async trackRun(variantName, baseSessionId) {
1923
+ const tracker = new ExperimentRunTracker(this, variantName, baseSessionId);
1924
+ await tracker.start();
1925
+ return tracker;
1926
+ }
1927
+ /**
1928
+ * Run the experiment with all variants and test cases.
1929
+ *
1930
+ * @param agentFn - Function that runs your agent with a test case and variant
1931
+ * @param options - Run options
1932
+ * @returns List of run results
1933
+ */
1934
+ async run(agentFn, options = {}) {
1935
+ const { parallel = false, maxWorkers = 4 } = options;
1936
+ if (!this._variants || !this._testCases) {
1937
+ await this.load();
1938
+ }
1939
+ const results = [];
1940
+ const totalRuns = this.variants.length * this.testCases.length;
1941
+ let completed = 0;
1942
+ console.log(`Running experiment: ${this.name || this.experimentId}`);
1943
+ console.log(` Variants: ${this.variants.length}`);
1944
+ console.log(` Test cases: ${this.testCases.length}`);
1945
+ console.log(` Total runs: ${totalRuns}`);
1946
+ console.log();
1947
+ const runSingle = async (variant, testCase) => {
1948
+ const tracker = await this.trackRun(variant.name, testCase.sessionId);
1949
+ setExperimentContext({
1950
+ systemPrompt: variant.systemPrompt,
1951
+ variantName: variant.name,
1952
+ experimentId: this.experimentId,
1953
+ testCaseId: testCase.sessionId
1954
+ });
1955
+ try {
1956
+ await agentFn(testCase, variant, tracker);
1957
+ await tracker.complete();
1958
+ return tracker.getResult();
1959
+ } catch (error) {
1960
+ const errorMessage = error instanceof Error ? error.message : String(error);
1961
+ await tracker.fail(errorMessage);
1962
+ return tracker.getResult();
1963
+ } finally {
1964
+ clearExperimentContext();
1965
+ }
1966
+ };
1967
+ if (parallel) {
1968
+ const queue = [];
1969
+ for (const variant of this.variants) {
1970
+ for (const testCase of this.testCases) {
1971
+ queue.push(async () => {
1972
+ const result = await runSingle(variant, testCase);
1973
+ results.push(result);
1974
+ completed++;
1975
+ const status = result.success ? "\u2713" : "\u2717";
1976
+ console.log(
1977
+ ` [${completed}/${totalRuns}] ${status} ${variant.name} x ${testCase.sessionId.slice(0, 8)}...`
1978
+ );
1979
+ });
1980
+ }
1981
+ }
1982
+ const executing = [];
1983
+ for (const task of queue) {
1984
+ const promise = task().then(() => {
1985
+ executing.splice(executing.indexOf(promise), 1);
1986
+ });
1987
+ executing.push(promise);
1988
+ if (executing.length >= maxWorkers) {
1989
+ await Promise.race(executing);
1990
+ }
1991
+ }
1992
+ await Promise.all(executing);
1993
+ } else {
1994
+ for (const variant of this.variants) {
1995
+ for (const testCase of this.testCases) {
1996
+ const result = await runSingle(variant, testCase);
1997
+ results.push(result);
1998
+ completed++;
1999
+ const status = result.success ? "\u2713" : "\u2717";
2000
+ console.log(
2001
+ ` [${completed}/${totalRuns}] ${status} ${variant.name} x ${testCase.sessionId.slice(0, 8)}...`
2002
+ );
2003
+ }
2004
+ }
2005
+ }
2006
+ console.log();
2007
+ console.log("Experiment complete!");
2008
+ console.log(` Successful: ${results.filter((r) => r.success).length}/${totalRuns}`);
2009
+ console.log(` Failed: ${results.filter((r) => !r.success).length}/${totalRuns}`);
2010
+ return results;
2011
+ }
2012
+ /**
2013
+ * Reset all runs for this experiment (for re-running).
2014
+ */
2015
+ async reset() {
2016
+ try {
2017
+ const response = await this.request(
2018
+ "DELETE",
2019
+ `/api/experiments/${this.experimentId}/runs`
2020
+ );
2021
+ if (response !== null) {
2022
+ this.config = void 0;
2023
+ this._variants = void 0;
2024
+ this._testCases = void 0;
2025
+ return true;
2026
+ }
2027
+ return false;
2028
+ } catch {
2029
+ return false;
2030
+ }
2031
+ }
2032
+ /**
2033
+ * Fetch aggregated results from the API.
2034
+ */
2035
+ async getResults() {
2036
+ try {
2037
+ const response = await this.request(
2038
+ "GET",
2039
+ `/api/experiments/${this.experimentId}/results`
2040
+ );
2041
+ return response;
2042
+ } catch {
2043
+ return null;
2044
+ }
2045
+ }
2046
+ };
541
2047
  export {
542
2048
  ApiError,
543
2049
  EventType,
2050
+ Experiment,
2051
+ ExperimentRunTracker,
544
2052
  Interaction,
545
2053
  NetworkError,
546
2054
  SentrialClient,
547
2055
  SentrialError,
2056
+ SessionContext,
2057
+ Tool,
2058
+ TrackSession,
548
2059
  ValidationError,
549
2060
  begin,
550
2061
  calculateAnthropicCost,
551
2062
  calculateGoogleCost,
552
2063
  calculateOpenAICost,
2064
+ clearExperimentContext,
2065
+ clearSessionContext,
553
2066
  configure,
554
- sentrial
2067
+ configureVercel,
2068
+ getCurrentInteraction,
2069
+ getCurrentSessionId,
2070
+ getExperimentContext,
2071
+ getExperimentId,
2072
+ getSessionContext,
2073
+ getSystemPrompt,
2074
+ getVariantName,
2075
+ isExperimentMode,
2076
+ sentrial,
2077
+ setClient,
2078
+ setDefaultClient,
2079
+ setExperimentContext,
2080
+ setSessionContext,
2081
+ withSession,
2082
+ withTool,
2083
+ wrapAISDK,
2084
+ wrapAnthropic,
2085
+ wrapGoogle,
2086
+ wrapLLM,
2087
+ wrapOpenAI
555
2088
  };
556
2089
  //# sourceMappingURL=index.js.map