@midscene/core 0.1.0 → 0.1.2

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/es/index.js CHANGED
@@ -1,9 +1,18 @@
1
+ var __create = Object.create;
1
2
  var __defProp = Object.defineProperty;
2
3
  var __defProps = Object.defineProperties;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
5
  var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
7
  var __getOwnPropSymbols = Object.getOwnPropertySymbols;
8
+ var __getProtoOf = Object.getPrototypeOf;
5
9
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
10
  var __propIsEnum = Object.prototype.propertyIsEnumerable;
11
+ var __knownSymbol = (name, symbol) => {
12
+ if (symbol = Symbol[name])
13
+ return symbol;
14
+ throw Error("Symbol." + name + " is not defined");
15
+ };
7
16
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
17
  var __spreadValues = (a, b) => {
9
18
  for (var prop in b || (b = {}))
@@ -17,6 +26,7 @@ var __spreadValues = (a, b) => {
17
26
  return a;
18
27
  };
19
28
  var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
29
+ var __restKey = (key) => typeof key === "symbol" ? key : key + "";
20
30
  var __objRest = (source, exclude) => {
21
31
  var target = {};
22
32
  for (var prop in source)
@@ -29,10 +39,974 @@ var __objRest = (source, exclude) => {
29
39
  }
30
40
  return target;
31
41
  };
42
+ var __commonJS = (cb, mod) => function __require() {
43
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
44
+ };
45
+ var __copyProps = (to, from, except, desc) => {
46
+ if (from && typeof from === "object" || typeof from === "function") {
47
+ for (let key of __getOwnPropNames(from))
48
+ if (!__hasOwnProp.call(to, key) && key !== except)
49
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
50
+ }
51
+ return to;
52
+ };
53
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
54
+ // If the importer is in node compatibility mode or this is not an ESM
55
+ // file that has been converted to a CommonJS file using a Babel-
56
+ // compatible transform (i.e. "__esModule" has not been set), then set
57
+ // "default" to the CommonJS "module.exports" for node compatibility.
58
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
59
+ mod
60
+ ));
32
61
  var __publicField = (obj, key, value) => {
33
62
  __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
34
63
  return value;
35
64
  };
65
+ var __await = function(promise, isYieldStar) {
66
+ this[0] = promise;
67
+ this[1] = isYieldStar;
68
+ };
69
+ var __asyncGenerator = (__this, __arguments, generator) => {
70
+ var resume = (k, v, yes, no) => {
71
+ try {
72
+ var x = generator[k](v), isAwait = (v = x.value) instanceof __await, done = x.done;
73
+ Promise.resolve(isAwait ? v[0] : v).then((y) => isAwait ? resume(k === "return" ? k : "next", v[1] ? { done: y.done, value: y.value } : y, yes, no) : yes({ value: y, done })).catch((e) => resume("throw", e, yes, no));
74
+ } catch (e) {
75
+ no(e);
76
+ }
77
+ };
78
+ var method = (k) => it[k] = (x) => new Promise((yes, no) => resume(k, x, yes, no));
79
+ var it = {};
80
+ return generator = generator.apply(__this, __arguments), it[Symbol.asyncIterator] = () => it, method("next"), method("throw"), method("return"), it;
81
+ };
82
+ var __yieldStar = (value) => {
83
+ var obj = value[__knownSymbol("asyncIterator")];
84
+ var isAwait = false;
85
+ var method;
86
+ var it = {};
87
+ if (obj == null) {
88
+ obj = value[__knownSymbol("iterator")]();
89
+ method = (k) => it[k] = (x) => obj[k](x);
90
+ } else {
91
+ obj = obj.call(value);
92
+ method = (k) => it[k] = (v) => {
93
+ if (isAwait) {
94
+ isAwait = false;
95
+ if (k === "throw")
96
+ throw v;
97
+ return v;
98
+ }
99
+ isAwait = true;
100
+ return {
101
+ done: false,
102
+ value: new __await(new Promise((resolve) => {
103
+ var x = obj[k](v);
104
+ if (!(x instanceof Object))
105
+ throw TypeError("Object expected");
106
+ resolve(x);
107
+ }), 1)
108
+ };
109
+ };
110
+ }
111
+ return it[__knownSymbol("iterator")] = () => it, method("next"), "throw" in obj ? method("throw") : it.throw = (x) => {
112
+ throw x;
113
+ }, "return" in obj && method("return"), it;
114
+ };
115
+ var __forAwait = (obj, it, method) => (it = obj[__knownSymbol("asyncIterator")]) ? it.call(obj) : (obj = obj[__knownSymbol("iterator")](), it = {}, method = (key, fn) => (fn = obj[key]) && (it[key] = (arg) => new Promise((yes, no, done) => (arg = fn.call(obj, arg), done = arg.done, Promise.resolve(arg.value).then((value) => yes({ value, done }), no)))), method("next"), method("return"), it);
116
+
117
+ // ../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry_operation.js
118
+ var require_retry_operation = __commonJS({
119
+ "../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry_operation.js"(exports, module) {
120
+ "use strict";
121
+ function RetryOperation(timeouts, options) {
122
+ if (typeof options === "boolean") {
123
+ options = { forever: options };
124
+ }
125
+ this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));
126
+ this._timeouts = timeouts;
127
+ this._options = options || {};
128
+ this._maxRetryTime = options && options.maxRetryTime || Infinity;
129
+ this._fn = null;
130
+ this._errors = [];
131
+ this._attempts = 1;
132
+ this._operationTimeout = null;
133
+ this._operationTimeoutCb = null;
134
+ this._timeout = null;
135
+ this._operationStart = null;
136
+ this._timer = null;
137
+ if (this._options.forever) {
138
+ this._cachedTimeouts = this._timeouts.slice(0);
139
+ }
140
+ }
141
+ module.exports = RetryOperation;
142
+ RetryOperation.prototype.reset = function() {
143
+ this._attempts = 1;
144
+ this._timeouts = this._originalTimeouts.slice(0);
145
+ };
146
+ RetryOperation.prototype.stop = function() {
147
+ if (this._timeout) {
148
+ clearTimeout(this._timeout);
149
+ }
150
+ if (this._timer) {
151
+ clearTimeout(this._timer);
152
+ }
153
+ this._timeouts = [];
154
+ this._cachedTimeouts = null;
155
+ };
156
+ RetryOperation.prototype.retry = function(err) {
157
+ if (this._timeout) {
158
+ clearTimeout(this._timeout);
159
+ }
160
+ if (!err) {
161
+ return false;
162
+ }
163
+ var currentTime = (/* @__PURE__ */ new Date()).getTime();
164
+ if (err && currentTime - this._operationStart >= this._maxRetryTime) {
165
+ this._errors.push(err);
166
+ this._errors.unshift(new Error("RetryOperation timeout occurred"));
167
+ return false;
168
+ }
169
+ this._errors.push(err);
170
+ var timeout = this._timeouts.shift();
171
+ if (timeout === void 0) {
172
+ if (this._cachedTimeouts) {
173
+ this._errors.splice(0, this._errors.length - 1);
174
+ timeout = this._cachedTimeouts.slice(-1);
175
+ } else {
176
+ return false;
177
+ }
178
+ }
179
+ var self = this;
180
+ this._timer = setTimeout(function() {
181
+ self._attempts++;
182
+ if (self._operationTimeoutCb) {
183
+ self._timeout = setTimeout(function() {
184
+ self._operationTimeoutCb(self._attempts);
185
+ }, self._operationTimeout);
186
+ if (self._options.unref) {
187
+ self._timeout.unref();
188
+ }
189
+ }
190
+ self._fn(self._attempts);
191
+ }, timeout);
192
+ if (this._options.unref) {
193
+ this._timer.unref();
194
+ }
195
+ return true;
196
+ };
197
+ RetryOperation.prototype.attempt = function(fn, timeoutOps) {
198
+ this._fn = fn;
199
+ if (timeoutOps) {
200
+ if (timeoutOps.timeout) {
201
+ this._operationTimeout = timeoutOps.timeout;
202
+ }
203
+ if (timeoutOps.cb) {
204
+ this._operationTimeoutCb = timeoutOps.cb;
205
+ }
206
+ }
207
+ var self = this;
208
+ if (this._operationTimeoutCb) {
209
+ this._timeout = setTimeout(function() {
210
+ self._operationTimeoutCb();
211
+ }, self._operationTimeout);
212
+ }
213
+ this._operationStart = (/* @__PURE__ */ new Date()).getTime();
214
+ this._fn(this._attempts);
215
+ };
216
+ RetryOperation.prototype.try = function(fn) {
217
+ console.log("Using RetryOperation.try() is deprecated");
218
+ this.attempt(fn);
219
+ };
220
+ RetryOperation.prototype.start = function(fn) {
221
+ console.log("Using RetryOperation.start() is deprecated");
222
+ this.attempt(fn);
223
+ };
224
+ RetryOperation.prototype.start = RetryOperation.prototype.try;
225
+ RetryOperation.prototype.errors = function() {
226
+ return this._errors;
227
+ };
228
+ RetryOperation.prototype.attempts = function() {
229
+ return this._attempts;
230
+ };
231
+ RetryOperation.prototype.mainError = function() {
232
+ if (this._errors.length === 0) {
233
+ return null;
234
+ }
235
+ var counts = {};
236
+ var mainError = null;
237
+ var mainErrorCount = 0;
238
+ for (var i = 0; i < this._errors.length; i++) {
239
+ var error = this._errors[i];
240
+ var message = error.message;
241
+ var count = (counts[message] || 0) + 1;
242
+ counts[message] = count;
243
+ if (count >= mainErrorCount) {
244
+ mainError = error;
245
+ mainErrorCount = count;
246
+ }
247
+ }
248
+ return mainError;
249
+ };
250
+ }
251
+ });
252
+
253
+ // ../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry.js
254
+ var require_retry = __commonJS({
255
+ "../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry.js"(exports) {
256
+ "use strict";
257
+ var RetryOperation = require_retry_operation();
258
+ exports.operation = function(options) {
259
+ var timeouts = exports.timeouts(options);
260
+ return new RetryOperation(timeouts, {
261
+ forever: options && (options.forever || options.retries === Infinity),
262
+ unref: options && options.unref,
263
+ maxRetryTime: options && options.maxRetryTime
264
+ });
265
+ };
266
+ exports.timeouts = function(options) {
267
+ if (options instanceof Array) {
268
+ return [].concat(options);
269
+ }
270
+ var opts = {
271
+ retries: 10,
272
+ factor: 2,
273
+ minTimeout: 1 * 1e3,
274
+ maxTimeout: Infinity,
275
+ randomize: false
276
+ };
277
+ for (var key in options) {
278
+ opts[key] = options[key];
279
+ }
280
+ if (opts.minTimeout > opts.maxTimeout) {
281
+ throw new Error("minTimeout is greater than maxTimeout");
282
+ }
283
+ var timeouts = [];
284
+ for (var i = 0; i < opts.retries; i++) {
285
+ timeouts.push(this.createTimeout(i, opts));
286
+ }
287
+ if (options && options.forever && !timeouts.length) {
288
+ timeouts.push(this.createTimeout(i, opts));
289
+ }
290
+ timeouts.sort(function(a, b) {
291
+ return a - b;
292
+ });
293
+ return timeouts;
294
+ };
295
+ exports.createTimeout = function(attempt, opts) {
296
+ var random = opts.randomize ? Math.random() + 1 : 1;
297
+ var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt));
298
+ timeout = Math.min(timeout, opts.maxTimeout);
299
+ return timeout;
300
+ };
301
+ exports.wrap = function(obj, options, methods) {
302
+ if (options instanceof Array) {
303
+ methods = options;
304
+ options = null;
305
+ }
306
+ if (!methods) {
307
+ methods = [];
308
+ for (var key in obj) {
309
+ if (typeof obj[key] === "function") {
310
+ methods.push(key);
311
+ }
312
+ }
313
+ }
314
+ for (var i = 0; i < methods.length; i++) {
315
+ var method = methods[i];
316
+ var original = obj[method];
317
+ obj[method] = function retryWrapper(original2) {
318
+ var op = exports.operation(options);
319
+ var args = Array.prototype.slice.call(arguments, 1);
320
+ var callback = args.pop();
321
+ args.push(function(err) {
322
+ if (op.retry(err)) {
323
+ return;
324
+ }
325
+ if (err) {
326
+ arguments[0] = op.mainError();
327
+ }
328
+ callback.apply(this, arguments);
329
+ });
330
+ op.attempt(function() {
331
+ original2.apply(obj, args);
332
+ });
333
+ }.bind(obj, original);
334
+ obj[method].options = options;
335
+ }
336
+ };
337
+ }
338
+ });
339
+
340
+ // ../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/index.js
341
+ var require_retry2 = __commonJS({
342
+ "../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/index.js"(exports, module) {
343
+ "use strict";
344
+ module.exports = require_retry();
345
+ }
346
+ });
347
+
348
+ // ../../node_modules/.pnpm/p-retry@4.6.2/node_modules/p-retry/index.js
349
+ var require_p_retry = __commonJS({
350
+ "../../node_modules/.pnpm/p-retry@4.6.2/node_modules/p-retry/index.js"(exports, module) {
351
+ "use strict";
352
+ var retry = require_retry2();
353
+ var networkErrorMsgs = [
354
+ "Failed to fetch",
355
+ // Chrome
356
+ "NetworkError when attempting to fetch resource.",
357
+ // Firefox
358
+ "The Internet connection appears to be offline.",
359
+ // Safari
360
+ "Network request failed"
361
+ // `cross-fetch`
362
+ ];
363
+ var AbortError = class extends Error {
364
+ constructor(message) {
365
+ super();
366
+ if (message instanceof Error) {
367
+ this.originalError = message;
368
+ ({ message } = message);
369
+ } else {
370
+ this.originalError = new Error(message);
371
+ this.originalError.stack = this.stack;
372
+ }
373
+ this.name = "AbortError";
374
+ this.message = message;
375
+ }
376
+ };
377
+ var decorateErrorWithCounts = (error, attemptNumber, options) => {
378
+ const retriesLeft = options.retries - (attemptNumber - 1);
379
+ error.attemptNumber = attemptNumber;
380
+ error.retriesLeft = retriesLeft;
381
+ return error;
382
+ };
383
+ var isNetworkError = (errorMessage) => networkErrorMsgs.includes(errorMessage);
384
+ var pRetry2 = (input, options) => new Promise((resolve, reject) => {
385
+ options = __spreadValues({
386
+ onFailedAttempt: () => {
387
+ },
388
+ retries: 10
389
+ }, options);
390
+ const operation = retry.operation(options);
391
+ operation.attempt(async (attemptNumber) => {
392
+ try {
393
+ resolve(await input(attemptNumber));
394
+ } catch (error) {
395
+ if (!(error instanceof Error)) {
396
+ reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`));
397
+ return;
398
+ }
399
+ if (error instanceof AbortError) {
400
+ operation.stop();
401
+ reject(error.originalError);
402
+ } else if (error instanceof TypeError && !isNetworkError(error.message)) {
403
+ operation.stop();
404
+ reject(error);
405
+ } else {
406
+ decorateErrorWithCounts(error, attemptNumber, options);
407
+ try {
408
+ await options.onFailedAttempt(error);
409
+ } catch (error2) {
410
+ reject(error2);
411
+ return;
412
+ }
413
+ if (!operation.retry(error)) {
414
+ reject(operation.mainError());
415
+ }
416
+ }
417
+ }
418
+ });
419
+ });
420
+ module.exports = pRetry2;
421
+ module.exports.default = pRetry2;
422
+ module.exports.AbortError = AbortError;
423
+ }
424
+ });
425
+
426
+ // ../../node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js
427
+ var require_eventemitter3 = __commonJS({
428
+ "../../node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js"(exports, module) {
429
+ "use strict";
430
+ var has = Object.prototype.hasOwnProperty;
431
+ var prefix = "~";
432
+ function Events() {
433
+ }
434
+ if (Object.create) {
435
+ Events.prototype = /* @__PURE__ */ Object.create(null);
436
+ if (!new Events().__proto__)
437
+ prefix = false;
438
+ }
439
+ function EE(fn, context, once) {
440
+ this.fn = fn;
441
+ this.context = context;
442
+ this.once = once || false;
443
+ }
444
+ function addListener(emitter, event, fn, context, once) {
445
+ if (typeof fn !== "function") {
446
+ throw new TypeError("The listener must be a function");
447
+ }
448
+ var listener = new EE(fn, context || emitter, once), evt = prefix ? prefix + event : event;
449
+ if (!emitter._events[evt])
450
+ emitter._events[evt] = listener, emitter._eventsCount++;
451
+ else if (!emitter._events[evt].fn)
452
+ emitter._events[evt].push(listener);
453
+ else
454
+ emitter._events[evt] = [emitter._events[evt], listener];
455
+ return emitter;
456
+ }
457
+ function clearEvent(emitter, evt) {
458
+ if (--emitter._eventsCount === 0)
459
+ emitter._events = new Events();
460
+ else
461
+ delete emitter._events[evt];
462
+ }
463
+ function EventEmitter() {
464
+ this._events = new Events();
465
+ this._eventsCount = 0;
466
+ }
467
+ EventEmitter.prototype.eventNames = function eventNames() {
468
+ var names = [], events, name;
469
+ if (this._eventsCount === 0)
470
+ return names;
471
+ for (name in events = this._events) {
472
+ if (has.call(events, name))
473
+ names.push(prefix ? name.slice(1) : name);
474
+ }
475
+ if (Object.getOwnPropertySymbols) {
476
+ return names.concat(Object.getOwnPropertySymbols(events));
477
+ }
478
+ return names;
479
+ };
480
+ EventEmitter.prototype.listeners = function listeners(event) {
481
+ var evt = prefix ? prefix + event : event, handlers = this._events[evt];
482
+ if (!handlers)
483
+ return [];
484
+ if (handlers.fn)
485
+ return [handlers.fn];
486
+ for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
487
+ ee[i] = handlers[i].fn;
488
+ }
489
+ return ee;
490
+ };
491
+ EventEmitter.prototype.listenerCount = function listenerCount(event) {
492
+ var evt = prefix ? prefix + event : event, listeners = this._events[evt];
493
+ if (!listeners)
494
+ return 0;
495
+ if (listeners.fn)
496
+ return 1;
497
+ return listeners.length;
498
+ };
499
+ EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
500
+ var evt = prefix ? prefix + event : event;
501
+ if (!this._events[evt])
502
+ return false;
503
+ var listeners = this._events[evt], len = arguments.length, args, i;
504
+ if (listeners.fn) {
505
+ if (listeners.once)
506
+ this.removeListener(event, listeners.fn, void 0, true);
507
+ switch (len) {
508
+ case 1:
509
+ return listeners.fn.call(listeners.context), true;
510
+ case 2:
511
+ return listeners.fn.call(listeners.context, a1), true;
512
+ case 3:
513
+ return listeners.fn.call(listeners.context, a1, a2), true;
514
+ case 4:
515
+ return listeners.fn.call(listeners.context, a1, a2, a3), true;
516
+ case 5:
517
+ return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
518
+ case 6:
519
+ return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
520
+ }
521
+ for (i = 1, args = new Array(len - 1); i < len; i++) {
522
+ args[i - 1] = arguments[i];
523
+ }
524
+ listeners.fn.apply(listeners.context, args);
525
+ } else {
526
+ var length = listeners.length, j;
527
+ for (i = 0; i < length; i++) {
528
+ if (listeners[i].once)
529
+ this.removeListener(event, listeners[i].fn, void 0, true);
530
+ switch (len) {
531
+ case 1:
532
+ listeners[i].fn.call(listeners[i].context);
533
+ break;
534
+ case 2:
535
+ listeners[i].fn.call(listeners[i].context, a1);
536
+ break;
537
+ case 3:
538
+ listeners[i].fn.call(listeners[i].context, a1, a2);
539
+ break;
540
+ case 4:
541
+ listeners[i].fn.call(listeners[i].context, a1, a2, a3);
542
+ break;
543
+ default:
544
+ if (!args)
545
+ for (j = 1, args = new Array(len - 1); j < len; j++) {
546
+ args[j - 1] = arguments[j];
547
+ }
548
+ listeners[i].fn.apply(listeners[i].context, args);
549
+ }
550
+ }
551
+ }
552
+ return true;
553
+ };
554
+ EventEmitter.prototype.on = function on(event, fn, context) {
555
+ return addListener(this, event, fn, context, false);
556
+ };
557
+ EventEmitter.prototype.once = function once(event, fn, context) {
558
+ return addListener(this, event, fn, context, true);
559
+ };
560
+ EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
561
+ var evt = prefix ? prefix + event : event;
562
+ if (!this._events[evt])
563
+ return this;
564
+ if (!fn) {
565
+ clearEvent(this, evt);
566
+ return this;
567
+ }
568
+ var listeners = this._events[evt];
569
+ if (listeners.fn) {
570
+ if (listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context)) {
571
+ clearEvent(this, evt);
572
+ }
573
+ } else {
574
+ for (var i = 0, events = [], length = listeners.length; i < length; i++) {
575
+ if (listeners[i].fn !== fn || once && !listeners[i].once || context && listeners[i].context !== context) {
576
+ events.push(listeners[i]);
577
+ }
578
+ }
579
+ if (events.length)
580
+ this._events[evt] = events.length === 1 ? events[0] : events;
581
+ else
582
+ clearEvent(this, evt);
583
+ }
584
+ return this;
585
+ };
586
+ EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
587
+ var evt;
588
+ if (event) {
589
+ evt = prefix ? prefix + event : event;
590
+ if (this._events[evt])
591
+ clearEvent(this, evt);
592
+ } else {
593
+ this._events = new Events();
594
+ this._eventsCount = 0;
595
+ }
596
+ return this;
597
+ };
598
+ EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
599
+ EventEmitter.prototype.addListener = EventEmitter.prototype.on;
600
+ EventEmitter.prefixed = prefix;
601
+ EventEmitter.EventEmitter = EventEmitter;
602
+ if ("undefined" !== typeof module) {
603
+ module.exports = EventEmitter;
604
+ }
605
+ }
606
+ });
607
+
608
+ // ../../node_modules/.pnpm/p-finally@1.0.0/node_modules/p-finally/index.js
609
+ var require_p_finally = __commonJS({
610
+ "../../node_modules/.pnpm/p-finally@1.0.0/node_modules/p-finally/index.js"(exports, module) {
611
+ "use strict";
612
+ module.exports = (promise, onFinally) => {
613
+ onFinally = onFinally || (() => {
614
+ });
615
+ return promise.then(
616
+ (val) => new Promise((resolve) => {
617
+ resolve(onFinally());
618
+ }).then(() => val),
619
+ (err) => new Promise((resolve) => {
620
+ resolve(onFinally());
621
+ }).then(() => {
622
+ throw err;
623
+ })
624
+ );
625
+ };
626
+ }
627
+ });
628
+
629
+ // ../../node_modules/.pnpm/p-timeout@3.2.0/node_modules/p-timeout/index.js
630
+ var require_p_timeout = __commonJS({
631
+ "../../node_modules/.pnpm/p-timeout@3.2.0/node_modules/p-timeout/index.js"(exports, module) {
632
+ "use strict";
633
+ var pFinally = require_p_finally();
634
+ var TimeoutError = class extends Error {
635
+ constructor(message) {
636
+ super(message);
637
+ this.name = "TimeoutError";
638
+ }
639
+ };
640
+ var pTimeout = (promise, milliseconds, fallback) => new Promise((resolve, reject) => {
641
+ if (typeof milliseconds !== "number" || milliseconds < 0) {
642
+ throw new TypeError("Expected `milliseconds` to be a positive number");
643
+ }
644
+ if (milliseconds === Infinity) {
645
+ resolve(promise);
646
+ return;
647
+ }
648
+ const timer = setTimeout(() => {
649
+ if (typeof fallback === "function") {
650
+ try {
651
+ resolve(fallback());
652
+ } catch (error) {
653
+ reject(error);
654
+ }
655
+ return;
656
+ }
657
+ const message = typeof fallback === "string" ? fallback : `Promise timed out after ${milliseconds} milliseconds`;
658
+ const timeoutError = fallback instanceof Error ? fallback : new TimeoutError(message);
659
+ if (typeof promise.cancel === "function") {
660
+ promise.cancel();
661
+ }
662
+ reject(timeoutError);
663
+ }, milliseconds);
664
+ pFinally(
665
+ // eslint-disable-next-line promise/prefer-await-to-then
666
+ promise.then(resolve, reject),
667
+ () => {
668
+ clearTimeout(timer);
669
+ }
670
+ );
671
+ });
672
+ module.exports = pTimeout;
673
+ module.exports.default = pTimeout;
674
+ module.exports.TimeoutError = TimeoutError;
675
+ }
676
+ });
677
+
678
+ // ../../node_modules/.pnpm/p-queue@6.6.2/node_modules/p-queue/dist/lower-bound.js
679
+ var require_lower_bound = __commonJS({
680
+ "../../node_modules/.pnpm/p-queue@6.6.2/node_modules/p-queue/dist/lower-bound.js"(exports) {
681
+ "use strict";
682
+ Object.defineProperty(exports, "__esModule", { value: true });
683
+ function lowerBound(array, value, comparator) {
684
+ let first = 0;
685
+ let count = array.length;
686
+ while (count > 0) {
687
+ const step = count / 2 | 0;
688
+ let it = first + step;
689
+ if (comparator(array[it], value) <= 0) {
690
+ first = ++it;
691
+ count -= step + 1;
692
+ } else {
693
+ count = step;
694
+ }
695
+ }
696
+ return first;
697
+ }
698
+ exports.default = lowerBound;
699
+ }
700
+ });
701
+
702
+ // ../../node_modules/.pnpm/p-queue@6.6.2/node_modules/p-queue/dist/priority-queue.js
703
+ var require_priority_queue = __commonJS({
704
+ "../../node_modules/.pnpm/p-queue@6.6.2/node_modules/p-queue/dist/priority-queue.js"(exports) {
705
+ "use strict";
706
+ Object.defineProperty(exports, "__esModule", { value: true });
707
+ var lower_bound_1 = require_lower_bound();
708
+ var PriorityQueue = class {
709
+ constructor() {
710
+ this._queue = [];
711
+ }
712
+ enqueue(run, options) {
713
+ options = Object.assign({ priority: 0 }, options);
714
+ const element = {
715
+ priority: options.priority,
716
+ run
717
+ };
718
+ if (this.size && this._queue[this.size - 1].priority >= options.priority) {
719
+ this._queue.push(element);
720
+ return;
721
+ }
722
+ const index = lower_bound_1.default(this._queue, element, (a, b) => b.priority - a.priority);
723
+ this._queue.splice(index, 0, element);
724
+ }
725
+ dequeue() {
726
+ const item = this._queue.shift();
727
+ return item === null || item === void 0 ? void 0 : item.run;
728
+ }
729
+ filter(options) {
730
+ return this._queue.filter((element) => element.priority === options.priority).map((element) => element.run);
731
+ }
732
+ get size() {
733
+ return this._queue.length;
734
+ }
735
+ };
736
+ exports.default = PriorityQueue;
737
+ }
738
+ });
739
+
740
+ // ../../node_modules/.pnpm/p-queue@6.6.2/node_modules/p-queue/dist/index.js
741
+ var require_dist = __commonJS({
742
+ "../../node_modules/.pnpm/p-queue@6.6.2/node_modules/p-queue/dist/index.js"(exports) {
743
+ "use strict";
744
+ Object.defineProperty(exports, "__esModule", { value: true });
745
+ var EventEmitter = require_eventemitter3();
746
+ var p_timeout_1 = require_p_timeout();
747
+ var priority_queue_1 = require_priority_queue();
748
+ var empty = () => {
749
+ };
750
+ var timeoutError = new p_timeout_1.TimeoutError();
751
+ var PQueue = class extends EventEmitter {
752
+ constructor(options) {
753
+ var _a, _b, _c, _d;
754
+ super();
755
+ this._intervalCount = 0;
756
+ this._intervalEnd = 0;
757
+ this._pendingCount = 0;
758
+ this._resolveEmpty = empty;
759
+ this._resolveIdle = empty;
760
+ options = Object.assign({ carryoverConcurrencyCount: false, intervalCap: Infinity, interval: 0, concurrency: Infinity, autoStart: true, queueClass: priority_queue_1.default }, options);
761
+ if (!(typeof options.intervalCap === "number" && options.intervalCap >= 1)) {
762
+ throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(_b = (_a = options.intervalCap) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : ""}\` (${typeof options.intervalCap})`);
763
+ }
764
+ if (options.interval === void 0 || !(Number.isFinite(options.interval) && options.interval >= 0)) {
765
+ throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(_d = (_c = options.interval) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : ""}\` (${typeof options.interval})`);
766
+ }
767
+ this._carryoverConcurrencyCount = options.carryoverConcurrencyCount;
768
+ this._isIntervalIgnored = options.intervalCap === Infinity || options.interval === 0;
769
+ this._intervalCap = options.intervalCap;
770
+ this._interval = options.interval;
771
+ this._queue = new options.queueClass();
772
+ this._queueClass = options.queueClass;
773
+ this.concurrency = options.concurrency;
774
+ this._timeout = options.timeout;
775
+ this._throwOnTimeout = options.throwOnTimeout === true;
776
+ this._isPaused = options.autoStart === false;
777
+ }
778
+ get _doesIntervalAllowAnother() {
779
+ return this._isIntervalIgnored || this._intervalCount < this._intervalCap;
780
+ }
781
+ get _doesConcurrentAllowAnother() {
782
+ return this._pendingCount < this._concurrency;
783
+ }
784
+ _next() {
785
+ this._pendingCount--;
786
+ this._tryToStartAnother();
787
+ this.emit("next");
788
+ }
789
+ _resolvePromises() {
790
+ this._resolveEmpty();
791
+ this._resolveEmpty = empty;
792
+ if (this._pendingCount === 0) {
793
+ this._resolveIdle();
794
+ this._resolveIdle = empty;
795
+ this.emit("idle");
796
+ }
797
+ }
798
+ _onResumeInterval() {
799
+ this._onInterval();
800
+ this._initializeIntervalIfNeeded();
801
+ this._timeoutId = void 0;
802
+ }
803
+ _isIntervalPaused() {
804
+ const now = Date.now();
805
+ if (this._intervalId === void 0) {
806
+ const delay = this._intervalEnd - now;
807
+ if (delay < 0) {
808
+ this._intervalCount = this._carryoverConcurrencyCount ? this._pendingCount : 0;
809
+ } else {
810
+ if (this._timeoutId === void 0) {
811
+ this._timeoutId = setTimeout(() => {
812
+ this._onResumeInterval();
813
+ }, delay);
814
+ }
815
+ return true;
816
+ }
817
+ }
818
+ return false;
819
+ }
820
+ _tryToStartAnother() {
821
+ if (this._queue.size === 0) {
822
+ if (this._intervalId) {
823
+ clearInterval(this._intervalId);
824
+ }
825
+ this._intervalId = void 0;
826
+ this._resolvePromises();
827
+ return false;
828
+ }
829
+ if (!this._isPaused) {
830
+ const canInitializeInterval = !this._isIntervalPaused();
831
+ if (this._doesIntervalAllowAnother && this._doesConcurrentAllowAnother) {
832
+ const job = this._queue.dequeue();
833
+ if (!job) {
834
+ return false;
835
+ }
836
+ this.emit("active");
837
+ job();
838
+ if (canInitializeInterval) {
839
+ this._initializeIntervalIfNeeded();
840
+ }
841
+ return true;
842
+ }
843
+ }
844
+ return false;
845
+ }
846
+ _initializeIntervalIfNeeded() {
847
+ if (this._isIntervalIgnored || this._intervalId !== void 0) {
848
+ return;
849
+ }
850
+ this._intervalId = setInterval(() => {
851
+ this._onInterval();
852
+ }, this._interval);
853
+ this._intervalEnd = Date.now() + this._interval;
854
+ }
855
+ _onInterval() {
856
+ if (this._intervalCount === 0 && this._pendingCount === 0 && this._intervalId) {
857
+ clearInterval(this._intervalId);
858
+ this._intervalId = void 0;
859
+ }
860
+ this._intervalCount = this._carryoverConcurrencyCount ? this._pendingCount : 0;
861
+ this._processQueue();
862
+ }
863
+ /**
864
+ Executes all queued functions until it reaches the limit.
865
+ */
866
+ _processQueue() {
867
+ while (this._tryToStartAnother()) {
868
+ }
869
+ }
870
+ get concurrency() {
871
+ return this._concurrency;
872
+ }
873
+ set concurrency(newConcurrency) {
874
+ if (!(typeof newConcurrency === "number" && newConcurrency >= 1)) {
875
+ throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${newConcurrency}\` (${typeof newConcurrency})`);
876
+ }
877
+ this._concurrency = newConcurrency;
878
+ this._processQueue();
879
+ }
880
+ /**
881
+ Adds a sync or async task to the queue. Always returns a promise.
882
+ */
883
+ async add(fn, options = {}) {
884
+ return new Promise((resolve, reject) => {
885
+ const run = async () => {
886
+ this._pendingCount++;
887
+ this._intervalCount++;
888
+ try {
889
+ const operation = this._timeout === void 0 && options.timeout === void 0 ? fn() : p_timeout_1.default(Promise.resolve(fn()), options.timeout === void 0 ? this._timeout : options.timeout, () => {
890
+ if (options.throwOnTimeout === void 0 ? this._throwOnTimeout : options.throwOnTimeout) {
891
+ reject(timeoutError);
892
+ }
893
+ return void 0;
894
+ });
895
+ resolve(await operation);
896
+ } catch (error) {
897
+ reject(error);
898
+ }
899
+ this._next();
900
+ };
901
+ this._queue.enqueue(run, options);
902
+ this._tryToStartAnother();
903
+ this.emit("add");
904
+ });
905
+ }
906
+ /**
907
+ Same as `.add()`, but accepts an array of sync or async functions.
908
+
909
+ @returns A promise that resolves when all functions are resolved.
910
+ */
911
+ async addAll(functions, options) {
912
+ return Promise.all(functions.map(async (function_) => this.add(function_, options)));
913
+ }
914
+ /**
915
+ Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.)
916
+ */
917
+ start() {
918
+ if (!this._isPaused) {
919
+ return this;
920
+ }
921
+ this._isPaused = false;
922
+ this._processQueue();
923
+ return this;
924
+ }
925
+ /**
926
+ Put queue execution on hold.
927
+ */
928
+ pause() {
929
+ this._isPaused = true;
930
+ }
931
+ /**
932
+ Clear the queue.
933
+ */
934
+ clear() {
935
+ this._queue = new this._queueClass();
936
+ }
937
+ /**
938
+ Can be called multiple times. Useful if you for example add additional items at a later time.
939
+
940
+ @returns A promise that settles when the queue becomes empty.
941
+ */
942
+ async onEmpty() {
943
+ if (this._queue.size === 0) {
944
+ return;
945
+ }
946
+ return new Promise((resolve) => {
947
+ const existingResolve = this._resolveEmpty;
948
+ this._resolveEmpty = () => {
949
+ existingResolve();
950
+ resolve();
951
+ };
952
+ });
953
+ }
954
+ /**
955
+ The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet.
956
+
957
+ @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`.
958
+ */
959
+ async onIdle() {
960
+ if (this._pendingCount === 0 && this._queue.size === 0) {
961
+ return;
962
+ }
963
+ return new Promise((resolve) => {
964
+ const existingResolve = this._resolveIdle;
965
+ this._resolveIdle = () => {
966
+ existingResolve();
967
+ resolve();
968
+ };
969
+ });
970
+ }
971
+ /**
972
+ Size of the queue.
973
+ */
974
+ get size() {
975
+ return this._queue.size;
976
+ }
977
+ /**
978
+ Size of the queue, filtered by the given options.
979
+
980
+ For example, this can be used to find the number of items remaining in the queue with a specific priority level.
981
+ */
982
+ sizeBy(options) {
983
+ return this._queue.filter(options).length;
984
+ }
985
+ /**
986
+ Number of pending promises.
987
+ */
988
+ get pending() {
989
+ return this._pendingCount;
990
+ }
991
+ /**
992
+ Whether the queue is currently paused.
993
+ */
994
+ get isPaused() {
995
+ return this._isPaused;
996
+ }
997
+ get timeout() {
998
+ return this._timeout;
999
+ }
1000
+ /**
1001
+ Set the timeout for future operations.
1002
+ */
1003
+ set timeout(milliseconds) {
1004
+ this._timeout = milliseconds;
1005
+ }
1006
+ };
1007
+ exports.default = PQueue;
1008
+ }
1009
+ });
36
1010
 
37
1011
  // src/insight/index.ts
38
1012
  import assert6 from "assert";
@@ -122,7 +1096,7 @@ function writeDumpFile(opts) {
122
1096
  gitIgnorePath,
123
1097
  `${gitIgnoreContent}
124
1098
  # MidScene.js dump files
125
- ${logDirName}/midscene-report
1099
+ ${logDirName}/report
126
1100
  ${logDirName}/dump-logger
127
1101
  `,
128
1102
  "utf-8"
@@ -418,7 +1392,3218 @@ function expandLiteSection(liteSection, elementById) {
418
1392
  // src/ai-model/openai.ts
419
1393
  import assert5 from "assert";
420
1394
  import OpenAI from "openai";
421
- import wrapper from "langsmith/wrappers";
1395
+
1396
+ // ../../node_modules/.pnpm/langsmith@0.1.36_openai@4.47.1/node_modules/langsmith/dist/traceable.js
1397
+ import { AsyncLocalStorage } from "async_hooks";
1398
+
1399
+ // ../../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/rng.js
1400
+ import crypto from "crypto";
1401
+ var rnds8Pool = new Uint8Array(256);
1402
+ var poolPtr = rnds8Pool.length;
1403
+ function rng() {
1404
+ if (poolPtr > rnds8Pool.length - 16) {
1405
+ crypto.randomFillSync(rnds8Pool);
1406
+ poolPtr = 0;
1407
+ }
1408
+ return rnds8Pool.slice(poolPtr, poolPtr += 16);
1409
+ }
1410
+
1411
+ // ../../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/regex.js
1412
+ var regex_default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
1413
+
1414
+ // ../../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/validate.js
1415
+ function validate(uuid) {
1416
+ return typeof uuid === "string" && regex_default.test(uuid);
1417
+ }
1418
+ var validate_default = validate;
1419
+
1420
+ // ../../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/stringify.js
1421
+ var byteToHex = [];
1422
+ for (let i = 0; i < 256; ++i) {
1423
+ byteToHex.push((i + 256).toString(16).slice(1));
1424
+ }
1425
+ function unsafeStringify(arr, offset = 0) {
1426
+ return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]];
1427
+ }
1428
+
1429
+ // ../../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/native.js
1430
+ import crypto2 from "crypto";
1431
+ var native_default = {
1432
+ randomUUID: crypto2.randomUUID
1433
+ };
1434
+
1435
+ // ../../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/v4.js
1436
+ function v4(options, buf, offset) {
1437
+ if (native_default.randomUUID && !buf && !options) {
1438
+ return native_default.randomUUID();
1439
+ }
1440
+ options = options || {};
1441
+ const rnds = options.random || (options.rng || rng)();
1442
+ rnds[6] = rnds[6] & 15 | 64;
1443
+ rnds[8] = rnds[8] & 63 | 128;
1444
+ if (buf) {
1445
+ offset = offset || 0;
1446
+ for (let i = 0; i < 16; ++i) {
1447
+ buf[offset + i] = rnds[i];
1448
+ }
1449
+ return buf;
1450
+ }
1451
+ return unsafeStringify(rnds);
1452
+ }
1453
+ var v4_default = v4;
1454
+
1455
+ // ../../node_modules/.pnpm/langsmith@0.1.36_openai@4.47.1/node_modules/langsmith/dist/utils/async_caller.js
1456
+ var import_p_retry = __toESM(require_p_retry());
1457
+ var import_p_queue = __toESM(require_dist());
1458
+ var STATUS_NO_RETRY = [
1459
+ 400,
1460
+ // Bad Request
1461
+ 401,
1462
+ // Unauthorized
1463
+ 403,
1464
+ // Forbidden
1465
+ 404,
1466
+ // Not Found
1467
+ 405,
1468
+ // Method Not Allowed
1469
+ 406,
1470
+ // Not Acceptable
1471
+ 407,
1472
+ // Proxy Authentication Required
1473
+ 408
1474
+ // Request Timeout
1475
+ ];
1476
+ var STATUS_IGNORE = [
1477
+ 409
1478
+ // Conflict
1479
+ ];
1480
+ var AsyncCaller = class {
1481
+ constructor(params) {
1482
+ var _a, _b;
1483
+ Object.defineProperty(this, "maxConcurrency", {
1484
+ enumerable: true,
1485
+ configurable: true,
1486
+ writable: true,
1487
+ value: void 0
1488
+ });
1489
+ Object.defineProperty(this, "maxRetries", {
1490
+ enumerable: true,
1491
+ configurable: true,
1492
+ writable: true,
1493
+ value: void 0
1494
+ });
1495
+ Object.defineProperty(this, "queue", {
1496
+ enumerable: true,
1497
+ configurable: true,
1498
+ writable: true,
1499
+ value: void 0
1500
+ });
1501
+ Object.defineProperty(this, "onFailedResponseHook", {
1502
+ enumerable: true,
1503
+ configurable: true,
1504
+ writable: true,
1505
+ value: void 0
1506
+ });
1507
+ this.maxConcurrency = (_a = params.maxConcurrency) != null ? _a : Infinity;
1508
+ this.maxRetries = (_b = params.maxRetries) != null ? _b : 6;
1509
+ if ("default" in import_p_queue.default) {
1510
+ this.queue = new import_p_queue.default.default({
1511
+ concurrency: this.maxConcurrency
1512
+ });
1513
+ } else {
1514
+ this.queue = new import_p_queue.default({ concurrency: this.maxConcurrency });
1515
+ }
1516
+ this.onFailedResponseHook = params == null ? void 0 : params.onFailedResponseHook;
1517
+ }
1518
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1519
+ call(callable, ...args) {
1520
+ const onFailedResponseHook = this.onFailedResponseHook;
1521
+ return this.queue.add(() => (0, import_p_retry.default)(() => callable(...args).catch((error) => {
1522
+ if (error instanceof Error) {
1523
+ throw error;
1524
+ } else {
1525
+ throw new Error(error);
1526
+ }
1527
+ }), {
1528
+ async onFailedAttempt(error) {
1529
+ if (error.message.startsWith("Cancel") || error.message.startsWith("TimeoutError") || error.message.startsWith("AbortError")) {
1530
+ throw error;
1531
+ }
1532
+ if ((error == null ? void 0 : error.code) === "ECONNABORTED") {
1533
+ throw error;
1534
+ }
1535
+ const response = error == null ? void 0 : error.response;
1536
+ const status = response == null ? void 0 : response.status;
1537
+ if (status) {
1538
+ if (STATUS_NO_RETRY.includes(+status)) {
1539
+ throw error;
1540
+ } else if (STATUS_IGNORE.includes(+status)) {
1541
+ return;
1542
+ }
1543
+ if (onFailedResponseHook) {
1544
+ await onFailedResponseHook(response);
1545
+ }
1546
+ }
1547
+ },
1548
+ // If needed we can change some of the defaults here,
1549
+ // but they're quite sensible.
1550
+ retries: this.maxRetries,
1551
+ randomize: true
1552
+ }), { throwOnTimeout: true });
1553
+ }
1554
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1555
+ callWithOptions(options, callable, ...args) {
1556
+ if (options.signal) {
1557
+ return Promise.race([
1558
+ this.call(callable, ...args),
1559
+ new Promise((_, reject) => {
1560
+ var _a;
1561
+ (_a = options.signal) == null ? void 0 : _a.addEventListener("abort", () => {
1562
+ reject(new Error("AbortError"));
1563
+ });
1564
+ })
1565
+ ]);
1566
+ }
1567
+ return this.call(callable, ...args);
1568
+ }
1569
+ fetch(...args) {
1570
+ return this.call(() => fetch(...args).then((res) => res.ok ? res : Promise.reject(res)));
1571
+ }
1572
+ };
1573
+
1574
+ // ../../node_modules/.pnpm/langsmith@0.1.36_openai@4.47.1/node_modules/langsmith/dist/utils/messages.js
1575
+ function isLangChainMessage(message) {
1576
+ return typeof (message == null ? void 0 : message._getType) === "function";
1577
+ }
1578
+ function convertLangChainMessageToExample(message) {
1579
+ const converted = {
1580
+ type: message._getType(),
1581
+ data: { content: message.content }
1582
+ };
1583
+ if ((message == null ? void 0 : message.additional_kwargs) && Object.keys(message.additional_kwargs).length > 0) {
1584
+ converted.data.additional_kwargs = __spreadValues({}, message.additional_kwargs);
1585
+ }
1586
+ return converted;
1587
+ }
1588
+
1589
+ // ../../node_modules/.pnpm/langsmith@0.1.36_openai@4.47.1/node_modules/langsmith/dist/utils/_uuid.js
1590
+ function assertUuid(str) {
1591
+ if (!validate_default(str)) {
1592
+ throw new Error(`Invalid UUID: ${str}`);
1593
+ }
1594
+ }
1595
+
1596
+ // ../../node_modules/.pnpm/langsmith@0.1.36_openai@4.47.1/node_modules/langsmith/dist/utils/warn.js
1597
+ var warnedMessages = {};
1598
+ function warnOnce(message) {
1599
+ if (!warnedMessages[message]) {
1600
+ console.warn(message);
1601
+ warnedMessages[message] = true;
1602
+ }
1603
+ }
1604
+
1605
+ // ../../node_modules/.pnpm/langsmith@0.1.36_openai@4.47.1/node_modules/langsmith/dist/client.js
1606
+ async function mergeRuntimeEnvIntoRunCreates(runs) {
1607
+ const runtimeEnv = await getRuntimeEnvironment();
1608
+ const envVars = getLangChainEnvVarsMetadata();
1609
+ return runs.map((run) => {
1610
+ var _a, _b;
1611
+ const extra = (_a = run.extra) != null ? _a : {};
1612
+ const metadata = extra.metadata;
1613
+ run.extra = __spreadProps(__spreadValues({}, extra), {
1614
+ runtime: __spreadValues(__spreadValues({}, runtimeEnv), extra == null ? void 0 : extra.runtime),
1615
+ metadata: __spreadValues(__spreadValues(__spreadValues({}, envVars), envVars.revision_id || run.revision_id ? { revision_id: (_b = run.revision_id) != null ? _b : envVars.revision_id } : {}), metadata)
1616
+ });
1617
+ return run;
1618
+ });
1619
+ }
1620
+ var getTracingSamplingRate = () => {
1621
+ const samplingRateStr = getEnvironmentVariable("LANGCHAIN_TRACING_SAMPLING_RATE");
1622
+ if (samplingRateStr === void 0) {
1623
+ return void 0;
1624
+ }
1625
+ const samplingRate = parseFloat(samplingRateStr);
1626
+ if (samplingRate < 0 || samplingRate > 1) {
1627
+ throw new Error(`LANGCHAIN_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${samplingRate}`);
1628
+ }
1629
+ return samplingRate;
1630
+ };
1631
+ var isLocalhost = (url) => {
1632
+ const strippedUrl = url.replace("http://", "").replace("https://", "");
1633
+ const hostname = strippedUrl.split("/")[0].split(":")[0];
1634
+ return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1";
1635
+ };
1636
+ var raiseForStatus = async (response, operation) => {
1637
+ const body = await response.text();
1638
+ if (!response.ok) {
1639
+ throw new Error(`Failed to ${operation}: ${response.status} ${response.statusText} ${body}`);
1640
+ }
1641
+ };
1642
+ async function toArray(iterable) {
1643
+ const result = [];
1644
+ try {
1645
+ for (var iter = __forAwait(iterable), more, temp, error; more = !(temp = await iter.next()).done; more = false) {
1646
+ const item = temp.value;
1647
+ result.push(item);
1648
+ }
1649
+ } catch (temp) {
1650
+ error = [temp];
1651
+ } finally {
1652
+ try {
1653
+ more && (temp = iter.return) && await temp.call(iter);
1654
+ } finally {
1655
+ if (error)
1656
+ throw error[0];
1657
+ }
1658
+ }
1659
+ return result;
1660
+ }
1661
+ function trimQuotes(str) {
1662
+ if (str === void 0) {
1663
+ return void 0;
1664
+ }
1665
+ return str.trim().replace(/^"(.*)"$/, "$1").replace(/^'(.*)'$/, "$1");
1666
+ }
1667
+ var handle429 = async (response) => {
1668
+ var _a;
1669
+ if ((response == null ? void 0 : response.status) === 429) {
1670
+ const retryAfter = parseInt((_a = response.headers.get("retry-after")) != null ? _a : "30", 10) * 1e3;
1671
+ if (retryAfter > 0) {
1672
+ await new Promise((resolve) => setTimeout(resolve, retryAfter));
1673
+ return true;
1674
+ }
1675
+ }
1676
+ return false;
1677
+ };
1678
+ var Queue = class {
1679
+ constructor() {
1680
+ Object.defineProperty(this, "items", {
1681
+ enumerable: true,
1682
+ configurable: true,
1683
+ writable: true,
1684
+ value: []
1685
+ });
1686
+ }
1687
+ get size() {
1688
+ return this.items.length;
1689
+ }
1690
+ push(item) {
1691
+ return new Promise((resolve) => {
1692
+ this.items.push([item, resolve]);
1693
+ });
1694
+ }
1695
+ pop(upToN) {
1696
+ if (upToN < 1) {
1697
+ throw new Error("Number of items to pop off may not be less than 1.");
1698
+ }
1699
+ const popped = [];
1700
+ while (popped.length < upToN && this.items.length) {
1701
+ const item = this.items.shift();
1702
+ if (item) {
1703
+ popped.push(item);
1704
+ } else {
1705
+ break;
1706
+ }
1707
+ }
1708
+ return [popped.map((it) => it[0]), () => popped.forEach((it) => it[1]())];
1709
+ }
1710
+ };
1711
+ var DEFAULT_BATCH_SIZE_LIMIT_BYTES = 20971520;
1712
+ var Client = class _Client {
1713
+ constructor(config = {}) {
1714
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
1715
+ Object.defineProperty(this, "apiKey", {
1716
+ enumerable: true,
1717
+ configurable: true,
1718
+ writable: true,
1719
+ value: void 0
1720
+ });
1721
+ Object.defineProperty(this, "apiUrl", {
1722
+ enumerable: true,
1723
+ configurable: true,
1724
+ writable: true,
1725
+ value: void 0
1726
+ });
1727
+ Object.defineProperty(this, "webUrl", {
1728
+ enumerable: true,
1729
+ configurable: true,
1730
+ writable: true,
1731
+ value: void 0
1732
+ });
1733
+ Object.defineProperty(this, "caller", {
1734
+ enumerable: true,
1735
+ configurable: true,
1736
+ writable: true,
1737
+ value: void 0
1738
+ });
1739
+ Object.defineProperty(this, "batchIngestCaller", {
1740
+ enumerable: true,
1741
+ configurable: true,
1742
+ writable: true,
1743
+ value: void 0
1744
+ });
1745
+ Object.defineProperty(this, "timeout_ms", {
1746
+ enumerable: true,
1747
+ configurable: true,
1748
+ writable: true,
1749
+ value: void 0
1750
+ });
1751
+ Object.defineProperty(this, "_tenantId", {
1752
+ enumerable: true,
1753
+ configurable: true,
1754
+ writable: true,
1755
+ value: null
1756
+ });
1757
+ Object.defineProperty(this, "hideInputs", {
1758
+ enumerable: true,
1759
+ configurable: true,
1760
+ writable: true,
1761
+ value: void 0
1762
+ });
1763
+ Object.defineProperty(this, "hideOutputs", {
1764
+ enumerable: true,
1765
+ configurable: true,
1766
+ writable: true,
1767
+ value: void 0
1768
+ });
1769
+ Object.defineProperty(this, "tracingSampleRate", {
1770
+ enumerable: true,
1771
+ configurable: true,
1772
+ writable: true,
1773
+ value: void 0
1774
+ });
1775
+ Object.defineProperty(this, "sampledPostUuids", {
1776
+ enumerable: true,
1777
+ configurable: true,
1778
+ writable: true,
1779
+ value: /* @__PURE__ */ new Set()
1780
+ });
1781
+ Object.defineProperty(this, "autoBatchTracing", {
1782
+ enumerable: true,
1783
+ configurable: true,
1784
+ writable: true,
1785
+ value: true
1786
+ });
1787
+ Object.defineProperty(this, "batchEndpointSupported", {
1788
+ enumerable: true,
1789
+ configurable: true,
1790
+ writable: true,
1791
+ value: void 0
1792
+ });
1793
+ Object.defineProperty(this, "autoBatchQueue", {
1794
+ enumerable: true,
1795
+ configurable: true,
1796
+ writable: true,
1797
+ value: new Queue()
1798
+ });
1799
+ Object.defineProperty(this, "pendingAutoBatchedRunLimit", {
1800
+ enumerable: true,
1801
+ configurable: true,
1802
+ writable: true,
1803
+ value: 100
1804
+ });
1805
+ Object.defineProperty(this, "autoBatchTimeout", {
1806
+ enumerable: true,
1807
+ configurable: true,
1808
+ writable: true,
1809
+ value: void 0
1810
+ });
1811
+ Object.defineProperty(this, "autoBatchInitialDelayMs", {
1812
+ enumerable: true,
1813
+ configurable: true,
1814
+ writable: true,
1815
+ value: 250
1816
+ });
1817
+ Object.defineProperty(this, "autoBatchAggregationDelayMs", {
1818
+ enumerable: true,
1819
+ configurable: true,
1820
+ writable: true,
1821
+ value: 50
1822
+ });
1823
+ Object.defineProperty(this, "serverInfo", {
1824
+ enumerable: true,
1825
+ configurable: true,
1826
+ writable: true,
1827
+ value: void 0
1828
+ });
1829
+ Object.defineProperty(this, "fetchOptions", {
1830
+ enumerable: true,
1831
+ configurable: true,
1832
+ writable: true,
1833
+ value: void 0
1834
+ });
1835
+ const defaultConfig = _Client.getDefaultClientConfig();
1836
+ this.tracingSampleRate = getTracingSamplingRate();
1837
+ this.apiUrl = (_b = trimQuotes((_a = config.apiUrl) != null ? _a : defaultConfig.apiUrl)) != null ? _b : "";
1838
+ this.apiKey = trimQuotes((_c = config.apiKey) != null ? _c : defaultConfig.apiKey);
1839
+ this.webUrl = trimQuotes((_d = config.webUrl) != null ? _d : defaultConfig.webUrl);
1840
+ this.timeout_ms = (_e = config.timeout_ms) != null ? _e : 12e3;
1841
+ this.caller = new AsyncCaller((_f = config.callerOptions) != null ? _f : {});
1842
+ this.batchIngestCaller = new AsyncCaller(__spreadProps(__spreadValues({}, (_g = config.callerOptions) != null ? _g : {}), {
1843
+ onFailedResponseHook: handle429
1844
+ }));
1845
+ this.hideInputs = (_i = (_h = config.hideInputs) != null ? _h : config.anonymizer) != null ? _i : defaultConfig.hideInputs;
1846
+ this.hideOutputs = (_k = (_j = config.hideOutputs) != null ? _j : config.anonymizer) != null ? _k : defaultConfig.hideOutputs;
1847
+ this.autoBatchTracing = (_l = config.autoBatchTracing) != null ? _l : this.autoBatchTracing;
1848
+ this.pendingAutoBatchedRunLimit = (_m = config.pendingAutoBatchedRunLimit) != null ? _m : this.pendingAutoBatchedRunLimit;
1849
+ this.fetchOptions = config.fetchOptions || {};
1850
+ }
1851
+ static getDefaultClientConfig() {
1852
+ var _a;
1853
+ const apiKey = getEnvironmentVariable("LANGCHAIN_API_KEY");
1854
+ const apiUrl = (_a = getEnvironmentVariable("LANGCHAIN_ENDPOINT")) != null ? _a : "https://api.smith.langchain.com";
1855
+ const hideInputs = getEnvironmentVariable("LANGCHAIN_HIDE_INPUTS") === "true";
1856
+ const hideOutputs = getEnvironmentVariable("LANGCHAIN_HIDE_OUTPUTS") === "true";
1857
+ return {
1858
+ apiUrl,
1859
+ apiKey,
1860
+ webUrl: void 0,
1861
+ hideInputs,
1862
+ hideOutputs
1863
+ };
1864
+ }
1865
+ getHostUrl() {
1866
+ if (this.webUrl) {
1867
+ return this.webUrl;
1868
+ } else if (isLocalhost(this.apiUrl)) {
1869
+ this.webUrl = "http://localhost:3000";
1870
+ return this.webUrl;
1871
+ } else if (this.apiUrl.includes("/api") && !this.apiUrl.split(".", 1)[0].endsWith("api")) {
1872
+ this.webUrl = this.apiUrl.replace("/api", "");
1873
+ return this.webUrl;
1874
+ } else if (this.apiUrl.split(".", 1)[0].includes("dev")) {
1875
+ this.webUrl = "https://dev.smith.langchain.com";
1876
+ return this.webUrl;
1877
+ } else {
1878
+ this.webUrl = "https://smith.langchain.com";
1879
+ return this.webUrl;
1880
+ }
1881
+ }
1882
+ get headers() {
1883
+ const headers = {
1884
+ "User-Agent": `langsmith-js/${__version__}`
1885
+ };
1886
+ if (this.apiKey) {
1887
+ headers["x-api-key"] = `${this.apiKey}`;
1888
+ }
1889
+ return headers;
1890
+ }
1891
+ processInputs(inputs) {
1892
+ if (this.hideInputs === false) {
1893
+ return inputs;
1894
+ }
1895
+ if (this.hideInputs === true) {
1896
+ return {};
1897
+ }
1898
+ if (typeof this.hideInputs === "function") {
1899
+ return this.hideInputs(inputs);
1900
+ }
1901
+ return inputs;
1902
+ }
1903
+ processOutputs(outputs) {
1904
+ if (this.hideOutputs === false) {
1905
+ return outputs;
1906
+ }
1907
+ if (this.hideOutputs === true) {
1908
+ return {};
1909
+ }
1910
+ if (typeof this.hideOutputs === "function") {
1911
+ return this.hideOutputs(outputs);
1912
+ }
1913
+ return outputs;
1914
+ }
1915
+ prepareRunCreateOrUpdateInputs(run) {
1916
+ const runParams = __spreadValues({}, run);
1917
+ if (runParams.inputs !== void 0) {
1918
+ runParams.inputs = this.processInputs(runParams.inputs);
1919
+ }
1920
+ if (runParams.outputs !== void 0) {
1921
+ runParams.outputs = this.processOutputs(runParams.outputs);
1922
+ }
1923
+ return runParams;
1924
+ }
1925
+ async _getResponse(path, queryParams) {
1926
+ var _a;
1927
+ const paramsString = (_a = queryParams == null ? void 0 : queryParams.toString()) != null ? _a : "";
1928
+ const url = `${this.apiUrl}${path}?${paramsString}`;
1929
+ const response = await this.caller.call(fetch, url, __spreadValues({
1930
+ method: "GET",
1931
+ headers: this.headers,
1932
+ signal: AbortSignal.timeout(this.timeout_ms)
1933
+ }, this.fetchOptions));
1934
+ if (!response.ok) {
1935
+ throw new Error(`Failed to fetch ${path}: ${response.status} ${response.statusText}`);
1936
+ }
1937
+ return response;
1938
+ }
1939
+ async _get(path, queryParams) {
1940
+ const response = await this._getResponse(path, queryParams);
1941
+ return response.json();
1942
+ }
1943
+ _getPaginated(_0) {
1944
+ return __asyncGenerator(this, arguments, function* (path, queryParams = new URLSearchParams()) {
1945
+ let offset = Number(queryParams.get("offset")) || 0;
1946
+ const limit = Number(queryParams.get("limit")) || 100;
1947
+ while (true) {
1948
+ queryParams.set("offset", String(offset));
1949
+ queryParams.set("limit", String(limit));
1950
+ const url = `${this.apiUrl}${path}?${queryParams}`;
1951
+ const response = yield new __await(this.caller.call(fetch, url, __spreadValues({
1952
+ method: "GET",
1953
+ headers: this.headers,
1954
+ signal: AbortSignal.timeout(this.timeout_ms)
1955
+ }, this.fetchOptions)));
1956
+ if (!response.ok) {
1957
+ throw new Error(`Failed to fetch ${path}: ${response.status} ${response.statusText}`);
1958
+ }
1959
+ const items = yield new __await(response.json());
1960
+ if (items.length === 0) {
1961
+ break;
1962
+ }
1963
+ yield items;
1964
+ if (items.length < limit) {
1965
+ break;
1966
+ }
1967
+ offset += items.length;
1968
+ }
1969
+ });
1970
+ }
1971
+ _getCursorPaginatedList(path, body = null, requestMethod = "POST", dataKey = "runs") {
1972
+ return __asyncGenerator(this, null, function* () {
1973
+ const bodyParams = body ? __spreadValues({}, body) : {};
1974
+ while (true) {
1975
+ const response = yield new __await(this.caller.call(fetch, `${this.apiUrl}${path}`, __spreadProps(__spreadValues({
1976
+ method: requestMethod,
1977
+ headers: __spreadProps(__spreadValues({}, this.headers), { "Content-Type": "application/json" }),
1978
+ signal: AbortSignal.timeout(this.timeout_ms)
1979
+ }, this.fetchOptions), {
1980
+ body: JSON.stringify(bodyParams)
1981
+ })));
1982
+ const responseBody = yield new __await(response.json());
1983
+ if (!responseBody) {
1984
+ break;
1985
+ }
1986
+ if (!responseBody[dataKey]) {
1987
+ break;
1988
+ }
1989
+ yield responseBody[dataKey];
1990
+ const cursors = responseBody.cursors;
1991
+ if (!cursors) {
1992
+ break;
1993
+ }
1994
+ if (!cursors.next) {
1995
+ break;
1996
+ }
1997
+ bodyParams.cursor = cursors.next;
1998
+ }
1999
+ });
2000
+ }
2001
+ _filterForSampling(runs, patch = false) {
2002
+ if (this.tracingSampleRate === void 0) {
2003
+ return runs;
2004
+ }
2005
+ if (patch) {
2006
+ const sampled = [];
2007
+ for (const run of runs) {
2008
+ if (this.sampledPostUuids.has(run.id)) {
2009
+ sampled.push(run);
2010
+ this.sampledPostUuids.delete(run.id);
2011
+ }
2012
+ }
2013
+ return sampled;
2014
+ } else {
2015
+ const sampled = [];
2016
+ for (const run of runs) {
2017
+ if (Math.random() < this.tracingSampleRate) {
2018
+ sampled.push(run);
2019
+ this.sampledPostUuids.add(run.id);
2020
+ }
2021
+ }
2022
+ return sampled;
2023
+ }
2024
+ }
2025
+ async drainAutoBatchQueue() {
2026
+ while (this.autoBatchQueue.size >= 0) {
2027
+ const [batch, done] = this.autoBatchQueue.pop(this.pendingAutoBatchedRunLimit);
2028
+ if (!batch.length) {
2029
+ done();
2030
+ return;
2031
+ }
2032
+ try {
2033
+ await this.batchIngestRuns({
2034
+ runCreates: batch.filter((item) => item.action === "create").map((item) => item.item),
2035
+ runUpdates: batch.filter((item) => item.action === "update").map((item) => item.item)
2036
+ });
2037
+ } finally {
2038
+ done();
2039
+ }
2040
+ }
2041
+ }
2042
+ async processRunOperation(item, immediatelyTriggerBatch) {
2043
+ const oldTimeout = this.autoBatchTimeout;
2044
+ clearTimeout(this.autoBatchTimeout);
2045
+ this.autoBatchTimeout = void 0;
2046
+ const itemPromise = this.autoBatchQueue.push(item);
2047
+ if (immediatelyTriggerBatch || this.autoBatchQueue.size > this.pendingAutoBatchedRunLimit) {
2048
+ await this.drainAutoBatchQueue();
2049
+ }
2050
+ if (this.autoBatchQueue.size > 0) {
2051
+ this.autoBatchTimeout = setTimeout(() => {
2052
+ this.autoBatchTimeout = void 0;
2053
+ void this.drainAutoBatchQueue().catch(console.error);
2054
+ }, oldTimeout ? this.autoBatchAggregationDelayMs : this.autoBatchInitialDelayMs);
2055
+ }
2056
+ return itemPromise;
2057
+ }
2058
+ async _getServerInfo() {
2059
+ const response = await fetch(`${this.apiUrl}/info`, __spreadValues({
2060
+ method: "GET",
2061
+ headers: { Accept: "application/json" },
2062
+ signal: AbortSignal.timeout(this.timeout_ms)
2063
+ }, this.fetchOptions));
2064
+ if (!response.ok) {
2065
+ await response.text();
2066
+ throw new Error("Failed to retrieve server info.");
2067
+ }
2068
+ return response.json();
2069
+ }
2070
+ async batchEndpointIsSupported() {
2071
+ try {
2072
+ this.serverInfo = await this._getServerInfo();
2073
+ } catch (e) {
2074
+ return false;
2075
+ }
2076
+ return true;
2077
+ }
2078
+ async createRun(run) {
2079
+ var _a;
2080
+ if (!this._filterForSampling([run]).length) {
2081
+ return;
2082
+ }
2083
+ const headers = __spreadProps(__spreadValues({}, this.headers), { "Content-Type": "application/json" });
2084
+ const session_name = run.project_name;
2085
+ delete run.project_name;
2086
+ const runCreate = this.prepareRunCreateOrUpdateInputs(__spreadProps(__spreadValues({
2087
+ session_name
2088
+ }, run), {
2089
+ start_time: (_a = run.start_time) != null ? _a : Date.now()
2090
+ }));
2091
+ if (this.autoBatchTracing && runCreate.trace_id !== void 0 && runCreate.dotted_order !== void 0) {
2092
+ void this.processRunOperation({
2093
+ action: "create",
2094
+ item: runCreate
2095
+ }).catch(console.error);
2096
+ return;
2097
+ }
2098
+ const mergedRunCreateParams = await mergeRuntimeEnvIntoRunCreates([
2099
+ runCreate
2100
+ ]);
2101
+ const response = await this.caller.call(fetch, `${this.apiUrl}/runs`, __spreadValues({
2102
+ method: "POST",
2103
+ headers,
2104
+ body: JSON.stringify(mergedRunCreateParams[0]),
2105
+ signal: AbortSignal.timeout(this.timeout_ms)
2106
+ }, this.fetchOptions));
2107
+ await raiseForStatus(response, "create run");
2108
+ }
2109
+ /**
2110
+ * Batch ingest/upsert multiple runs in the Langsmith system.
2111
+ * @param runs
2112
+ */
2113
+ async batchIngestRuns({ runCreates, runUpdates }) {
2114
+ var _a, _b, _c, _d, _e;
2115
+ if (runCreates === void 0 && runUpdates === void 0) {
2116
+ return;
2117
+ }
2118
+ let preparedCreateParams = (_a = runCreates == null ? void 0 : runCreates.map((create) => this.prepareRunCreateOrUpdateInputs(create))) != null ? _a : [];
2119
+ let preparedUpdateParams = (_b = runUpdates == null ? void 0 : runUpdates.map((update) => this.prepareRunCreateOrUpdateInputs(update))) != null ? _b : [];
2120
+ if (preparedCreateParams.length > 0 && preparedUpdateParams.length > 0) {
2121
+ const createById = preparedCreateParams.reduce((params, run) => {
2122
+ if (!run.id) {
2123
+ return params;
2124
+ }
2125
+ params[run.id] = run;
2126
+ return params;
2127
+ }, {});
2128
+ const standaloneUpdates = [];
2129
+ for (const updateParam of preparedUpdateParams) {
2130
+ if (updateParam.id !== void 0 && createById[updateParam.id]) {
2131
+ createById[updateParam.id] = __spreadValues(__spreadValues({}, createById[updateParam.id]), updateParam);
2132
+ } else {
2133
+ standaloneUpdates.push(updateParam);
2134
+ }
2135
+ }
2136
+ preparedCreateParams = Object.values(createById);
2137
+ preparedUpdateParams = standaloneUpdates;
2138
+ }
2139
+ const rawBatch = {
2140
+ post: this._filterForSampling(preparedCreateParams),
2141
+ patch: this._filterForSampling(preparedUpdateParams, true)
2142
+ };
2143
+ if (!rawBatch.post.length && !rawBatch.patch.length) {
2144
+ return;
2145
+ }
2146
+ preparedCreateParams = await mergeRuntimeEnvIntoRunCreates(preparedCreateParams);
2147
+ if (this.batchEndpointSupported === void 0) {
2148
+ this.batchEndpointSupported = await this.batchEndpointIsSupported();
2149
+ }
2150
+ if (!this.batchEndpointSupported) {
2151
+ this.autoBatchTracing = false;
2152
+ for (const preparedCreateParam of rawBatch.post) {
2153
+ await this.createRun(preparedCreateParam);
2154
+ }
2155
+ for (const preparedUpdateParam of rawBatch.patch) {
2156
+ if (preparedUpdateParam.id !== void 0) {
2157
+ await this.updateRun(preparedUpdateParam.id, preparedUpdateParam);
2158
+ }
2159
+ }
2160
+ return;
2161
+ }
2162
+ const sizeLimitBytes = (_e = (_d = (_c = this.serverInfo) == null ? void 0 : _c.batch_ingest_config) == null ? void 0 : _d.size_limit_bytes) != null ? _e : DEFAULT_BATCH_SIZE_LIMIT_BYTES;
2163
+ const batchChunks = {
2164
+ post: [],
2165
+ patch: []
2166
+ };
2167
+ let currentBatchSizeBytes = 0;
2168
+ for (const k of ["post", "patch"]) {
2169
+ const key = k;
2170
+ const batchItems = rawBatch[key].reverse();
2171
+ let batchItem = batchItems.pop();
2172
+ while (batchItem !== void 0) {
2173
+ const stringifiedBatchItem = JSON.stringify(batchItem);
2174
+ if (currentBatchSizeBytes > 0 && currentBatchSizeBytes + stringifiedBatchItem.length > sizeLimitBytes) {
2175
+ await this._postBatchIngestRuns(JSON.stringify(batchChunks));
2176
+ currentBatchSizeBytes = 0;
2177
+ batchChunks.post = [];
2178
+ batchChunks.patch = [];
2179
+ }
2180
+ currentBatchSizeBytes += stringifiedBatchItem.length;
2181
+ batchChunks[key].push(batchItem);
2182
+ batchItem = batchItems.pop();
2183
+ }
2184
+ }
2185
+ if (batchChunks.post.length > 0 || batchChunks.patch.length > 0) {
2186
+ await this._postBatchIngestRuns(JSON.stringify(batchChunks));
2187
+ }
2188
+ }
2189
+ async _postBatchIngestRuns(body) {
2190
+ const headers = __spreadProps(__spreadValues({}, this.headers), {
2191
+ "Content-Type": "application/json",
2192
+ Accept: "application/json"
2193
+ });
2194
+ const response = await this.batchIngestCaller.call(fetch, `${this.apiUrl}/runs/batch`, __spreadValues({
2195
+ method: "POST",
2196
+ headers,
2197
+ body,
2198
+ signal: AbortSignal.timeout(this.timeout_ms)
2199
+ }, this.fetchOptions));
2200
+ await raiseForStatus(response, "batch create run");
2201
+ }
2202
+ async updateRun(runId, run) {
2203
+ assertUuid(runId);
2204
+ if (run.inputs) {
2205
+ run.inputs = this.processInputs(run.inputs);
2206
+ }
2207
+ if (run.outputs) {
2208
+ run.outputs = this.processOutputs(run.outputs);
2209
+ }
2210
+ const data = __spreadProps(__spreadValues({}, run), { id: runId });
2211
+ if (!this._filterForSampling([data], true).length) {
2212
+ return;
2213
+ }
2214
+ if (this.autoBatchTracing && data.trace_id !== void 0 && data.dotted_order !== void 0) {
2215
+ if (run.end_time !== void 0 && data.parent_run_id === void 0) {
2216
+ await this.processRunOperation({ action: "update", item: data }, true);
2217
+ return;
2218
+ } else {
2219
+ void this.processRunOperation({ action: "update", item: data }).catch(console.error);
2220
+ }
2221
+ return;
2222
+ }
2223
+ const headers = __spreadProps(__spreadValues({}, this.headers), { "Content-Type": "application/json" });
2224
+ const response = await this.caller.call(fetch, `${this.apiUrl}/runs/${runId}`, __spreadValues({
2225
+ method: "PATCH",
2226
+ headers,
2227
+ body: JSON.stringify(run),
2228
+ signal: AbortSignal.timeout(this.timeout_ms)
2229
+ }, this.fetchOptions));
2230
+ await raiseForStatus(response, "update run");
2231
+ }
2232
+ async readRun(runId, { loadChildRuns } = { loadChildRuns: false }) {
2233
+ assertUuid(runId);
2234
+ let run = await this._get(`/runs/${runId}`);
2235
+ if (loadChildRuns && run.child_run_ids) {
2236
+ run = await this._loadChildRuns(run);
2237
+ }
2238
+ return run;
2239
+ }
2240
+ async getRunUrl({ runId, run, projectOpts }) {
2241
+ if (run !== void 0) {
2242
+ let sessionId;
2243
+ if (run.session_id) {
2244
+ sessionId = run.session_id;
2245
+ } else if (projectOpts == null ? void 0 : projectOpts.projectName) {
2246
+ sessionId = (await this.readProject({ projectName: projectOpts == null ? void 0 : projectOpts.projectName })).id;
2247
+ } else if (projectOpts == null ? void 0 : projectOpts.projectId) {
2248
+ sessionId = projectOpts == null ? void 0 : projectOpts.projectId;
2249
+ } else {
2250
+ const project = await this.readProject({
2251
+ projectName: getEnvironmentVariable("LANGCHAIN_PROJECT") || "default"
2252
+ });
2253
+ sessionId = project.id;
2254
+ }
2255
+ const tenantId = await this._getTenantId();
2256
+ return `${this.getHostUrl()}/o/${tenantId}/projects/p/${sessionId}/r/${run.id}?poll=true`;
2257
+ } else if (runId !== void 0) {
2258
+ const run_ = await this.readRun(runId);
2259
+ if (!run_.app_path) {
2260
+ throw new Error(`Run ${runId} has no app_path`);
2261
+ }
2262
+ const baseUrl = this.getHostUrl();
2263
+ return `${baseUrl}${run_.app_path}`;
2264
+ } else {
2265
+ throw new Error("Must provide either runId or run");
2266
+ }
2267
+ }
2268
+ async _loadChildRuns(run) {
2269
+ const childRuns = await toArray(this.listRuns({ id: run.child_run_ids }));
2270
+ const treemap = {};
2271
+ const runs = {};
2272
+ childRuns.sort((a, b) => {
2273
+ var _a, _b;
2274
+ return ((_a = a == null ? void 0 : a.dotted_order) != null ? _a : "").localeCompare((_b = b == null ? void 0 : b.dotted_order) != null ? _b : "");
2275
+ });
2276
+ for (const childRun of childRuns) {
2277
+ if (childRun.parent_run_id === null || childRun.parent_run_id === void 0) {
2278
+ throw new Error(`Child run ${childRun.id} has no parent`);
2279
+ }
2280
+ if (!(childRun.parent_run_id in treemap)) {
2281
+ treemap[childRun.parent_run_id] = [];
2282
+ }
2283
+ treemap[childRun.parent_run_id].push(childRun);
2284
+ runs[childRun.id] = childRun;
2285
+ }
2286
+ run.child_runs = treemap[run.id] || [];
2287
+ for (const runId in treemap) {
2288
+ if (runId !== run.id) {
2289
+ runs[runId].child_runs = treemap[runId];
2290
+ }
2291
+ }
2292
+ return run;
2293
+ }
2294
+ /**
2295
+ * List runs from the LangSmith server.
2296
+ * @param projectId - The ID of the project to filter by.
2297
+ * @param projectName - The name of the project to filter by.
2298
+ * @param parentRunId - The ID of the parent run to filter by.
2299
+ * @param traceId - The ID of the trace to filter by.
2300
+ * @param referenceExampleId - The ID of the reference example to filter by.
2301
+ * @param startTime - The start time to filter by.
2302
+ * @param isRoot - Indicates whether to only return root runs.
2303
+ * @param runType - The run type to filter by.
2304
+ * @param error - Indicates whether to filter by error runs.
2305
+ * @param id - The ID of the run to filter by.
2306
+ * @param query - The query string to filter by.
2307
+ * @param filter - The filter string to apply to the run spans.
2308
+ * @param traceFilter - The filter string to apply on the root run of the trace.
2309
+ * @param limit - The maximum number of runs to retrieve.
2310
+ * @returns {AsyncIterable<Run>} - The runs.
2311
+ *
2312
+ * @example
2313
+ * // List all runs in a project
2314
+ * const projectRuns = client.listRuns({ projectName: "<your_project>" });
2315
+ *
2316
+ * @example
2317
+ * // List LLM and Chat runs in the last 24 hours
2318
+ * const todaysLLMRuns = client.listRuns({
2319
+ * projectName: "<your_project>",
2320
+ * start_time: new Date(Date.now() - 24 * 60 * 60 * 1000),
2321
+ * run_type: "llm",
2322
+ * });
2323
+ *
2324
+ * @example
2325
+ * // List traces in a project
2326
+ * const rootRuns = client.listRuns({
2327
+ * projectName: "<your_project>",
2328
+ * execution_order: 1,
2329
+ * });
2330
+ *
2331
+ * @example
2332
+ * // List runs without errors
2333
+ * const correctRuns = client.listRuns({
2334
+ * projectName: "<your_project>",
2335
+ * error: false,
2336
+ * });
2337
+ *
2338
+ * @example
2339
+ * // List runs by run ID
2340
+ * const runIds = [
2341
+ * "a36092d2-4ad5-4fb4-9c0d-0dba9a2ed836",
2342
+ * "9398e6be-964f-4aa4-8ae9-ad78cd4b7074",
2343
+ * ];
2344
+ * const selectedRuns = client.listRuns({ run_ids: runIds });
2345
+ *
2346
+ * @example
2347
+ * // List all "chain" type runs that took more than 10 seconds and had `total_tokens` greater than 5000
2348
+ * const chainRuns = client.listRuns({
2349
+ * projectName: "<your_project>",
2350
+ * filter: 'and(eq(run_type, "chain"), gt(latency, 10), gt(total_tokens, 5000))',
2351
+ * });
2352
+ *
2353
+ * @example
2354
+ * // List all runs called "extractor" whose root of the trace was assigned feedback "user_score" score of 1
2355
+ * const goodExtractorRuns = client.listRuns({
2356
+ * projectName: "<your_project>",
2357
+ * filter: 'eq(name, "extractor")',
2358
+ * traceFilter: 'and(eq(feedback_key, "user_score"), eq(feedback_score, 1))',
2359
+ * });
2360
+ *
2361
+ * @example
2362
+ * // List all runs that started after a specific timestamp and either have "error" not equal to null or a "Correctness" feedback score equal to 0
2363
+ * const complexRuns = client.listRuns({
2364
+ * projectName: "<your_project>",
2365
+ * filter: 'and(gt(start_time, "2023-07-15T12:34:56Z"), or(neq(error, null), and(eq(feedback_key, "Correctness"), eq(feedback_score, 0.0))))',
2366
+ * });
2367
+ *
2368
+ * @example
2369
+ * // List all runs where `tags` include "experimental" or "beta" and `latency` is greater than 2 seconds
2370
+ * const taggedRuns = client.listRuns({
2371
+ * projectName: "<your_project>",
2372
+ * filter: 'and(or(has(tags, "experimental"), has(tags, "beta")), gt(latency, 2))',
2373
+ * });
2374
+ */
2375
+ listRuns(props) {
2376
+ return __asyncGenerator(this, null, function* () {
2377
+ const { projectId, projectName, parentRunId, traceId, referenceExampleId, startTime, executionOrder, isRoot, runType, error, id, query, filter, traceFilter, treeFilter, limit, select } = props;
2378
+ let projectIds = [];
2379
+ if (projectId) {
2380
+ projectIds = Array.isArray(projectId) ? projectId : [projectId];
2381
+ }
2382
+ if (projectName) {
2383
+ const projectNames = Array.isArray(projectName) ? projectName : [projectName];
2384
+ const projectIds_ = yield new __await(Promise.all(projectNames.map((name) => this.readProject({ projectName: name }).then((project) => project.id))));
2385
+ projectIds.push(...projectIds_);
2386
+ }
2387
+ const default_select = [
2388
+ "app_path",
2389
+ "child_run_ids",
2390
+ "completion_cost",
2391
+ "completion_tokens",
2392
+ "dotted_order",
2393
+ "end_time",
2394
+ "error",
2395
+ "events",
2396
+ "extra",
2397
+ "feedback_stats",
2398
+ "first_token_time",
2399
+ "id",
2400
+ "inputs",
2401
+ "name",
2402
+ "outputs",
2403
+ "parent_run_id",
2404
+ "parent_run_ids",
2405
+ "prompt_cost",
2406
+ "prompt_tokens",
2407
+ "reference_example_id",
2408
+ "run_type",
2409
+ "session_id",
2410
+ "start_time",
2411
+ "status",
2412
+ "tags",
2413
+ "total_cost",
2414
+ "total_tokens",
2415
+ "trace_id"
2416
+ ];
2417
+ const body = {
2418
+ session: projectIds.length ? projectIds : null,
2419
+ run_type: runType,
2420
+ reference_example: referenceExampleId,
2421
+ query,
2422
+ filter,
2423
+ trace_filter: traceFilter,
2424
+ tree_filter: treeFilter,
2425
+ execution_order: executionOrder,
2426
+ parent_run: parentRunId,
2427
+ start_time: startTime ? startTime.toISOString() : null,
2428
+ error,
2429
+ id,
2430
+ limit,
2431
+ trace: traceId,
2432
+ select: select ? select : default_select,
2433
+ is_root: isRoot
2434
+ };
2435
+ let runsYielded = 0;
2436
+ try {
2437
+ for (var iter = __forAwait(this._getCursorPaginatedList("/runs/query", body)), more, temp, error2; more = !(temp = yield new __await(iter.next())).done; more = false) {
2438
+ const runs = temp.value;
2439
+ if (limit) {
2440
+ if (runsYielded >= limit) {
2441
+ break;
2442
+ }
2443
+ if (runs.length + runsYielded > limit) {
2444
+ const newRuns = runs.slice(0, limit - runsYielded);
2445
+ yield* __yieldStar(newRuns);
2446
+ break;
2447
+ }
2448
+ runsYielded += runs.length;
2449
+ yield* __yieldStar(runs);
2450
+ } else {
2451
+ yield* __yieldStar(runs);
2452
+ }
2453
+ }
2454
+ } catch (temp) {
2455
+ error2 = [temp];
2456
+ } finally {
2457
+ try {
2458
+ more && (temp = iter.return) && (yield new __await(temp.call(iter)));
2459
+ } finally {
2460
+ if (error2)
2461
+ throw error2[0];
2462
+ }
2463
+ }
2464
+ });
2465
+ }
2466
+ async shareRun(runId, { shareId } = {}) {
2467
+ const data = {
2468
+ run_id: runId,
2469
+ share_token: shareId || v4_default()
2470
+ };
2471
+ assertUuid(runId);
2472
+ const response = await this.caller.call(fetch, `${this.apiUrl}/runs/${runId}/share`, __spreadValues({
2473
+ method: "PUT",
2474
+ headers: this.headers,
2475
+ body: JSON.stringify(data),
2476
+ signal: AbortSignal.timeout(this.timeout_ms)
2477
+ }, this.fetchOptions));
2478
+ const result = await response.json();
2479
+ if (result === null || !("share_token" in result)) {
2480
+ throw new Error("Invalid response from server");
2481
+ }
2482
+ return `${this.getHostUrl()}/public/${result["share_token"]}/r`;
2483
+ }
2484
+ async unshareRun(runId) {
2485
+ assertUuid(runId);
2486
+ const response = await this.caller.call(fetch, `${this.apiUrl}/runs/${runId}/share`, __spreadValues({
2487
+ method: "DELETE",
2488
+ headers: this.headers,
2489
+ signal: AbortSignal.timeout(this.timeout_ms)
2490
+ }, this.fetchOptions));
2491
+ await raiseForStatus(response, "unshare run");
2492
+ }
2493
+ async readRunSharedLink(runId) {
2494
+ assertUuid(runId);
2495
+ const response = await this.caller.call(fetch, `${this.apiUrl}/runs/${runId}/share`, __spreadValues({
2496
+ method: "GET",
2497
+ headers: this.headers,
2498
+ signal: AbortSignal.timeout(this.timeout_ms)
2499
+ }, this.fetchOptions));
2500
+ const result = await response.json();
2501
+ if (result === null || !("share_token" in result)) {
2502
+ return void 0;
2503
+ }
2504
+ return `${this.getHostUrl()}/public/${result["share_token"]}/r`;
2505
+ }
2506
+ async listSharedRuns(shareToken, { runIds } = {}) {
2507
+ const queryParams = new URLSearchParams({
2508
+ share_token: shareToken
2509
+ });
2510
+ if (runIds !== void 0) {
2511
+ for (const runId of runIds) {
2512
+ queryParams.append("id", runId);
2513
+ }
2514
+ }
2515
+ assertUuid(shareToken);
2516
+ const response = await this.caller.call(fetch, `${this.apiUrl}/public/${shareToken}/runs${queryParams}`, __spreadValues({
2517
+ method: "GET",
2518
+ headers: this.headers,
2519
+ signal: AbortSignal.timeout(this.timeout_ms)
2520
+ }, this.fetchOptions));
2521
+ const runs = await response.json();
2522
+ return runs;
2523
+ }
2524
+ async readDatasetSharedSchema(datasetId, datasetName) {
2525
+ if (!datasetId && !datasetName) {
2526
+ throw new Error("Either datasetId or datasetName must be given");
2527
+ }
2528
+ if (!datasetId) {
2529
+ const dataset = await this.readDataset({ datasetName });
2530
+ datasetId = dataset.id;
2531
+ }
2532
+ assertUuid(datasetId);
2533
+ const response = await this.caller.call(fetch, `${this.apiUrl}/datasets/${datasetId}/share`, __spreadValues({
2534
+ method: "GET",
2535
+ headers: this.headers,
2536
+ signal: AbortSignal.timeout(this.timeout_ms)
2537
+ }, this.fetchOptions));
2538
+ const shareSchema = await response.json();
2539
+ shareSchema.url = `${this.getHostUrl()}/public/${shareSchema.share_token}/d`;
2540
+ return shareSchema;
2541
+ }
2542
+ async shareDataset(datasetId, datasetName) {
2543
+ if (!datasetId && !datasetName) {
2544
+ throw new Error("Either datasetId or datasetName must be given");
2545
+ }
2546
+ if (!datasetId) {
2547
+ const dataset = await this.readDataset({ datasetName });
2548
+ datasetId = dataset.id;
2549
+ }
2550
+ const data = {
2551
+ dataset_id: datasetId
2552
+ };
2553
+ assertUuid(datasetId);
2554
+ const response = await this.caller.call(fetch, `${this.apiUrl}/datasets/${datasetId}/share`, __spreadValues({
2555
+ method: "PUT",
2556
+ headers: this.headers,
2557
+ body: JSON.stringify(data),
2558
+ signal: AbortSignal.timeout(this.timeout_ms)
2559
+ }, this.fetchOptions));
2560
+ const shareSchema = await response.json();
2561
+ shareSchema.url = `${this.getHostUrl()}/public/${shareSchema.share_token}/d`;
2562
+ return shareSchema;
2563
+ }
2564
+ async unshareDataset(datasetId) {
2565
+ assertUuid(datasetId);
2566
+ const response = await this.caller.call(fetch, `${this.apiUrl}/datasets/${datasetId}/share`, __spreadValues({
2567
+ method: "DELETE",
2568
+ headers: this.headers,
2569
+ signal: AbortSignal.timeout(this.timeout_ms)
2570
+ }, this.fetchOptions));
2571
+ await raiseForStatus(response, "unshare dataset");
2572
+ }
2573
+ async readSharedDataset(shareToken) {
2574
+ assertUuid(shareToken);
2575
+ const response = await this.caller.call(fetch, `${this.apiUrl}/public/${shareToken}/datasets`, __spreadValues({
2576
+ method: "GET",
2577
+ headers: this.headers,
2578
+ signal: AbortSignal.timeout(this.timeout_ms)
2579
+ }, this.fetchOptions));
2580
+ const dataset = await response.json();
2581
+ return dataset;
2582
+ }
2583
+ async createProject({ projectName, description = null, metadata = null, upsert = false, projectExtra = null, referenceDatasetId = null }) {
2584
+ const upsert_ = upsert ? `?upsert=true` : "";
2585
+ const endpoint = `${this.apiUrl}/sessions${upsert_}`;
2586
+ const extra = projectExtra || {};
2587
+ if (metadata) {
2588
+ extra["metadata"] = metadata;
2589
+ }
2590
+ const body = {
2591
+ name: projectName,
2592
+ extra,
2593
+ description
2594
+ };
2595
+ if (referenceDatasetId !== null) {
2596
+ body["reference_dataset_id"] = referenceDatasetId;
2597
+ }
2598
+ const response = await this.caller.call(fetch, endpoint, __spreadValues({
2599
+ method: "POST",
2600
+ headers: __spreadProps(__spreadValues({}, this.headers), { "Content-Type": "application/json" }),
2601
+ body: JSON.stringify(body),
2602
+ signal: AbortSignal.timeout(this.timeout_ms)
2603
+ }, this.fetchOptions));
2604
+ const result = await response.json();
2605
+ if (!response.ok) {
2606
+ throw new Error(`Failed to create session ${projectName}: ${response.status} ${response.statusText}`);
2607
+ }
2608
+ return result;
2609
+ }
2610
+ async updateProject(projectId, { name = null, description = null, metadata = null, projectExtra = null, endTime = null }) {
2611
+ const endpoint = `${this.apiUrl}/sessions/${projectId}`;
2612
+ let extra = projectExtra;
2613
+ if (metadata) {
2614
+ extra = __spreadProps(__spreadValues({}, extra || {}), { metadata });
2615
+ }
2616
+ const body = {
2617
+ name,
2618
+ extra,
2619
+ description,
2620
+ end_time: endTime ? new Date(endTime).toISOString() : null
2621
+ };
2622
+ const response = await this.caller.call(fetch, endpoint, __spreadValues({
2623
+ method: "PATCH",
2624
+ headers: __spreadProps(__spreadValues({}, this.headers), { "Content-Type": "application/json" }),
2625
+ body: JSON.stringify(body),
2626
+ signal: AbortSignal.timeout(this.timeout_ms)
2627
+ }, this.fetchOptions));
2628
+ const result = await response.json();
2629
+ if (!response.ok) {
2630
+ throw new Error(`Failed to update project ${projectId}: ${response.status} ${response.statusText}`);
2631
+ }
2632
+ return result;
2633
+ }
2634
+ async hasProject({ projectId, projectName }) {
2635
+ let path = "/sessions";
2636
+ const params = new URLSearchParams();
2637
+ if (projectId !== void 0 && projectName !== void 0) {
2638
+ throw new Error("Must provide either projectName or projectId, not both");
2639
+ } else if (projectId !== void 0) {
2640
+ assertUuid(projectId);
2641
+ path += `/${projectId}`;
2642
+ } else if (projectName !== void 0) {
2643
+ params.append("name", projectName);
2644
+ } else {
2645
+ throw new Error("Must provide projectName or projectId");
2646
+ }
2647
+ const response = await this.caller.call(fetch, `${this.apiUrl}${path}?${params}`, __spreadValues({
2648
+ method: "GET",
2649
+ headers: this.headers,
2650
+ signal: AbortSignal.timeout(this.timeout_ms)
2651
+ }, this.fetchOptions));
2652
+ try {
2653
+ const result = await response.json();
2654
+ if (!response.ok) {
2655
+ return false;
2656
+ }
2657
+ if (Array.isArray(result)) {
2658
+ return result.length > 0;
2659
+ }
2660
+ return true;
2661
+ } catch (e) {
2662
+ return false;
2663
+ }
2664
+ }
2665
+ async readProject({ projectId, projectName, includeStats }) {
2666
+ let path = "/sessions";
2667
+ const params = new URLSearchParams();
2668
+ if (projectId !== void 0 && projectName !== void 0) {
2669
+ throw new Error("Must provide either projectName or projectId, not both");
2670
+ } else if (projectId !== void 0) {
2671
+ assertUuid(projectId);
2672
+ path += `/${projectId}`;
2673
+ } else if (projectName !== void 0) {
2674
+ params.append("name", projectName);
2675
+ } else {
2676
+ throw new Error("Must provide projectName or projectId");
2677
+ }
2678
+ if (includeStats !== void 0) {
2679
+ params.append("include_stats", includeStats.toString());
2680
+ }
2681
+ const response = await this._get(path, params);
2682
+ let result;
2683
+ if (Array.isArray(response)) {
2684
+ if (response.length === 0) {
2685
+ throw new Error(`Project[id=${projectId}, name=${projectName}] not found`);
2686
+ }
2687
+ result = response[0];
2688
+ } else {
2689
+ result = response;
2690
+ }
2691
+ return result;
2692
+ }
2693
+ async getProjectUrl({ projectId, projectName }) {
2694
+ if (projectId === void 0 && projectName === void 0) {
2695
+ throw new Error("Must provide either projectName or projectId");
2696
+ }
2697
+ const project = await this.readProject({ projectId, projectName });
2698
+ const tenantId = await this._getTenantId();
2699
+ return `${this.getHostUrl()}/o/${tenantId}/projects/p/${project.id}`;
2700
+ }
2701
+ async getDatasetUrl({ datasetId, datasetName }) {
2702
+ if (datasetId === void 0 && datasetName === void 0) {
2703
+ throw new Error("Must provide either datasetName or datasetId");
2704
+ }
2705
+ const dataset = await this.readDataset({ datasetId, datasetName });
2706
+ const tenantId = await this._getTenantId();
2707
+ return `${this.getHostUrl()}/o/${tenantId}/datasets/${dataset.id}`;
2708
+ }
2709
+ async _getTenantId() {
2710
+ if (this._tenantId !== null) {
2711
+ return this._tenantId;
2712
+ }
2713
+ const queryParams = new URLSearchParams({ limit: "1" });
2714
+ try {
2715
+ for (var iter = __forAwait(this._getPaginated("/sessions", queryParams)), more, temp, error; more = !(temp = await iter.next()).done; more = false) {
2716
+ const projects = temp.value;
2717
+ this._tenantId = projects[0].tenant_id;
2718
+ return projects[0].tenant_id;
2719
+ }
2720
+ } catch (temp) {
2721
+ error = [temp];
2722
+ } finally {
2723
+ try {
2724
+ more && (temp = iter.return) && await temp.call(iter);
2725
+ } finally {
2726
+ if (error)
2727
+ throw error[0];
2728
+ }
2729
+ }
2730
+ throw new Error("No projects found to resolve tenant.");
2731
+ }
2732
+ listProjects() {
2733
+ return __asyncGenerator(this, arguments, function* ({ projectIds, name, nameContains, referenceDatasetId, referenceDatasetName, referenceFree } = {}) {
2734
+ const params = new URLSearchParams();
2735
+ if (projectIds !== void 0) {
2736
+ for (const projectId of projectIds) {
2737
+ params.append("id", projectId);
2738
+ }
2739
+ }
2740
+ if (name !== void 0) {
2741
+ params.append("name", name);
2742
+ }
2743
+ if (nameContains !== void 0) {
2744
+ params.append("name_contains", nameContains);
2745
+ }
2746
+ if (referenceDatasetId !== void 0) {
2747
+ params.append("reference_dataset", referenceDatasetId);
2748
+ } else if (referenceDatasetName !== void 0) {
2749
+ const dataset = yield new __await(this.readDataset({
2750
+ datasetName: referenceDatasetName
2751
+ }));
2752
+ params.append("reference_dataset", dataset.id);
2753
+ }
2754
+ if (referenceFree !== void 0) {
2755
+ params.append("reference_free", referenceFree.toString());
2756
+ }
2757
+ try {
2758
+ for (var iter = __forAwait(this._getPaginated("/sessions", params)), more, temp, error; more = !(temp = yield new __await(iter.next())).done; more = false) {
2759
+ const projects = temp.value;
2760
+ yield* __yieldStar(projects);
2761
+ }
2762
+ } catch (temp) {
2763
+ error = [temp];
2764
+ } finally {
2765
+ try {
2766
+ more && (temp = iter.return) && (yield new __await(temp.call(iter)));
2767
+ } finally {
2768
+ if (error)
2769
+ throw error[0];
2770
+ }
2771
+ }
2772
+ });
2773
+ }
2774
+ async deleteProject({ projectId, projectName }) {
2775
+ let projectId_;
2776
+ if (projectId === void 0 && projectName === void 0) {
2777
+ throw new Error("Must provide projectName or projectId");
2778
+ } else if (projectId !== void 0 && projectName !== void 0) {
2779
+ throw new Error("Must provide either projectName or projectId, not both");
2780
+ } else if (projectId === void 0) {
2781
+ projectId_ = (await this.readProject({ projectName })).id;
2782
+ } else {
2783
+ projectId_ = projectId;
2784
+ }
2785
+ assertUuid(projectId_);
2786
+ const response = await this.caller.call(fetch, `${this.apiUrl}/sessions/${projectId_}`, __spreadValues({
2787
+ method: "DELETE",
2788
+ headers: this.headers,
2789
+ signal: AbortSignal.timeout(this.timeout_ms)
2790
+ }, this.fetchOptions));
2791
+ await raiseForStatus(response, `delete session ${projectId_} (${projectName})`);
2792
+ }
2793
+ async uploadCsv({ csvFile, fileName, inputKeys, outputKeys, description, dataType, name }) {
2794
+ const url = `${this.apiUrl}/datasets/upload`;
2795
+ const formData = new FormData();
2796
+ formData.append("file", csvFile, fileName);
2797
+ inputKeys.forEach((key) => {
2798
+ formData.append("input_keys", key);
2799
+ });
2800
+ outputKeys.forEach((key) => {
2801
+ formData.append("output_keys", key);
2802
+ });
2803
+ if (description) {
2804
+ formData.append("description", description);
2805
+ }
2806
+ if (dataType) {
2807
+ formData.append("data_type", dataType);
2808
+ }
2809
+ if (name) {
2810
+ formData.append("name", name);
2811
+ }
2812
+ const response = await this.caller.call(fetch, url, __spreadValues({
2813
+ method: "POST",
2814
+ headers: this.headers,
2815
+ body: formData,
2816
+ signal: AbortSignal.timeout(this.timeout_ms)
2817
+ }, this.fetchOptions));
2818
+ if (!response.ok) {
2819
+ const result2 = await response.json();
2820
+ if (result2.detail && result2.detail.includes("already exists")) {
2821
+ throw new Error(`Dataset ${fileName} already exists`);
2822
+ }
2823
+ throw new Error(`Failed to upload CSV: ${response.status} ${response.statusText}`);
2824
+ }
2825
+ const result = await response.json();
2826
+ return result;
2827
+ }
2828
+ async createDataset(name, { description, dataType } = {}) {
2829
+ const body = {
2830
+ name,
2831
+ description
2832
+ };
2833
+ if (dataType) {
2834
+ body.data_type = dataType;
2835
+ }
2836
+ const response = await this.caller.call(fetch, `${this.apiUrl}/datasets`, __spreadValues({
2837
+ method: "POST",
2838
+ headers: __spreadProps(__spreadValues({}, this.headers), { "Content-Type": "application/json" }),
2839
+ body: JSON.stringify(body),
2840
+ signal: AbortSignal.timeout(this.timeout_ms)
2841
+ }, this.fetchOptions));
2842
+ if (!response.ok) {
2843
+ const result2 = await response.json();
2844
+ if (result2.detail && result2.detail.includes("already exists")) {
2845
+ throw new Error(`Dataset ${name} already exists`);
2846
+ }
2847
+ throw new Error(`Failed to create dataset ${response.status} ${response.statusText}`);
2848
+ }
2849
+ const result = await response.json();
2850
+ return result;
2851
+ }
2852
+ async readDataset({ datasetId, datasetName }) {
2853
+ let path = "/datasets";
2854
+ const params = new URLSearchParams({ limit: "1" });
2855
+ if (datasetId !== void 0 && datasetName !== void 0) {
2856
+ throw new Error("Must provide either datasetName or datasetId, not both");
2857
+ } else if (datasetId !== void 0) {
2858
+ assertUuid(datasetId);
2859
+ path += `/${datasetId}`;
2860
+ } else if (datasetName !== void 0) {
2861
+ params.append("name", datasetName);
2862
+ } else {
2863
+ throw new Error("Must provide datasetName or datasetId");
2864
+ }
2865
+ const response = await this._get(path, params);
2866
+ let result;
2867
+ if (Array.isArray(response)) {
2868
+ if (response.length === 0) {
2869
+ throw new Error(`Dataset[id=${datasetId}, name=${datasetName}] not found`);
2870
+ }
2871
+ result = response[0];
2872
+ } else {
2873
+ result = response;
2874
+ }
2875
+ return result;
2876
+ }
2877
+ async hasDataset({ datasetId, datasetName }) {
2878
+ try {
2879
+ await this.readDataset({ datasetId, datasetName });
2880
+ return true;
2881
+ } catch (e) {
2882
+ if (
2883
+ // eslint-disable-next-line no-instanceof/no-instanceof
2884
+ e instanceof Error && e.message.toLocaleLowerCase().includes("not found")
2885
+ ) {
2886
+ return false;
2887
+ }
2888
+ throw e;
2889
+ }
2890
+ }
2891
+ async diffDatasetVersions({ datasetId, datasetName, fromVersion, toVersion }) {
2892
+ let datasetId_ = datasetId;
2893
+ if (datasetId_ === void 0 && datasetName === void 0) {
2894
+ throw new Error("Must provide either datasetName or datasetId");
2895
+ } else if (datasetId_ !== void 0 && datasetName !== void 0) {
2896
+ throw new Error("Must provide either datasetName or datasetId, not both");
2897
+ } else if (datasetId_ === void 0) {
2898
+ const dataset = await this.readDataset({ datasetName });
2899
+ datasetId_ = dataset.id;
2900
+ }
2901
+ const urlParams = new URLSearchParams({
2902
+ from_version: typeof fromVersion === "string" ? fromVersion : fromVersion.toISOString(),
2903
+ to_version: typeof toVersion === "string" ? toVersion : toVersion.toISOString()
2904
+ });
2905
+ const response = await this._get(`/datasets/${datasetId_}/versions/diff`, urlParams);
2906
+ return response;
2907
+ }
2908
+ async readDatasetOpenaiFinetuning({ datasetId, datasetName }) {
2909
+ const path = "/datasets";
2910
+ if (datasetId !== void 0) {
2911
+ } else if (datasetName !== void 0) {
2912
+ datasetId = (await this.readDataset({ datasetName })).id;
2913
+ } else {
2914
+ throw new Error("Must provide datasetName or datasetId");
2915
+ }
2916
+ const response = await this._getResponse(`${path}/${datasetId}/openai_ft`);
2917
+ const datasetText = await response.text();
2918
+ const dataset = datasetText.trim().split("\n").map((line) => JSON.parse(line));
2919
+ return dataset;
2920
+ }
2921
+ listDatasets() {
2922
+ return __asyncGenerator(this, arguments, function* ({ limit = 100, offset = 0, datasetIds, datasetName, datasetNameContains } = {}) {
2923
+ const path = "/datasets";
2924
+ const params = new URLSearchParams({
2925
+ limit: limit.toString(),
2926
+ offset: offset.toString()
2927
+ });
2928
+ if (datasetIds !== void 0) {
2929
+ for (const id_ of datasetIds) {
2930
+ params.append("id", id_);
2931
+ }
2932
+ }
2933
+ if (datasetName !== void 0) {
2934
+ params.append("name", datasetName);
2935
+ }
2936
+ if (datasetNameContains !== void 0) {
2937
+ params.append("name_contains", datasetNameContains);
2938
+ }
2939
+ try {
2940
+ for (var iter = __forAwait(this._getPaginated(path, params)), more, temp, error; more = !(temp = yield new __await(iter.next())).done; more = false) {
2941
+ const datasets = temp.value;
2942
+ yield* __yieldStar(datasets);
2943
+ }
2944
+ } catch (temp) {
2945
+ error = [temp];
2946
+ } finally {
2947
+ try {
2948
+ more && (temp = iter.return) && (yield new __await(temp.call(iter)));
2949
+ } finally {
2950
+ if (error)
2951
+ throw error[0];
2952
+ }
2953
+ }
2954
+ });
2955
+ }
2956
+ /**
2957
+ * Update a dataset
2958
+ * @param props The dataset details to update
2959
+ * @returns The updated dataset
2960
+ */
2961
+ async updateDataset(props) {
2962
+ const _a = props, { datasetId, datasetName } = _a, update = __objRest(_a, ["datasetId", "datasetName"]);
2963
+ if (!datasetId && !datasetName) {
2964
+ throw new Error("Must provide either datasetName or datasetId");
2965
+ }
2966
+ const _datasetId = datasetId != null ? datasetId : (await this.readDataset({ datasetName })).id;
2967
+ assertUuid(_datasetId);
2968
+ const response = await this.caller.call(fetch, `${this.apiUrl}/datasets/${_datasetId}`, __spreadValues({
2969
+ method: "PATCH",
2970
+ headers: __spreadProps(__spreadValues({}, this.headers), { "Content-Type": "application/json" }),
2971
+ body: JSON.stringify(update),
2972
+ signal: AbortSignal.timeout(this.timeout_ms)
2973
+ }, this.fetchOptions));
2974
+ if (!response.ok) {
2975
+ throw new Error(`Failed to update dataset ${_datasetId}: ${response.status} ${response.statusText}`);
2976
+ }
2977
+ return await response.json();
2978
+ }
2979
+ async deleteDataset({ datasetId, datasetName }) {
2980
+ let path = "/datasets";
2981
+ let datasetId_ = datasetId;
2982
+ if (datasetId !== void 0 && datasetName !== void 0) {
2983
+ throw new Error("Must provide either datasetName or datasetId, not both");
2984
+ } else if (datasetName !== void 0) {
2985
+ const dataset = await this.readDataset({ datasetName });
2986
+ datasetId_ = dataset.id;
2987
+ }
2988
+ if (datasetId_ !== void 0) {
2989
+ assertUuid(datasetId_);
2990
+ path += `/${datasetId_}`;
2991
+ } else {
2992
+ throw new Error("Must provide datasetName or datasetId");
2993
+ }
2994
+ const response = await this.caller.call(fetch, this.apiUrl + path, __spreadValues({
2995
+ method: "DELETE",
2996
+ headers: this.headers,
2997
+ signal: AbortSignal.timeout(this.timeout_ms)
2998
+ }, this.fetchOptions));
2999
+ if (!response.ok) {
3000
+ throw new Error(`Failed to delete ${path}: ${response.status} ${response.statusText}`);
3001
+ }
3002
+ await response.json();
3003
+ }
3004
+ async createExample(inputs, outputs, { datasetId, datasetName, createdAt, exampleId, metadata, split }) {
3005
+ let datasetId_ = datasetId;
3006
+ if (datasetId_ === void 0 && datasetName === void 0) {
3007
+ throw new Error("Must provide either datasetName or datasetId");
3008
+ } else if (datasetId_ !== void 0 && datasetName !== void 0) {
3009
+ throw new Error("Must provide either datasetName or datasetId, not both");
3010
+ } else if (datasetId_ === void 0) {
3011
+ const dataset = await this.readDataset({ datasetName });
3012
+ datasetId_ = dataset.id;
3013
+ }
3014
+ const createdAt_ = createdAt || /* @__PURE__ */ new Date();
3015
+ const data = {
3016
+ dataset_id: datasetId_,
3017
+ inputs,
3018
+ outputs,
3019
+ created_at: createdAt_ == null ? void 0 : createdAt_.toISOString(),
3020
+ id: exampleId,
3021
+ metadata,
3022
+ split
3023
+ };
3024
+ const response = await this.caller.call(fetch, `${this.apiUrl}/examples`, __spreadValues({
3025
+ method: "POST",
3026
+ headers: __spreadProps(__spreadValues({}, this.headers), { "Content-Type": "application/json" }),
3027
+ body: JSON.stringify(data),
3028
+ signal: AbortSignal.timeout(this.timeout_ms)
3029
+ }, this.fetchOptions));
3030
+ if (!response.ok) {
3031
+ throw new Error(`Failed to create example: ${response.status} ${response.statusText}`);
3032
+ }
3033
+ const result = await response.json();
3034
+ return result;
3035
+ }
3036
+ async createExamples(props) {
3037
+ const { inputs, outputs, metadata, sourceRunIds, exampleIds, datasetId, datasetName } = props;
3038
+ let datasetId_ = datasetId;
3039
+ if (datasetId_ === void 0 && datasetName === void 0) {
3040
+ throw new Error("Must provide either datasetName or datasetId");
3041
+ } else if (datasetId_ !== void 0 && datasetName !== void 0) {
3042
+ throw new Error("Must provide either datasetName or datasetId, not both");
3043
+ } else if (datasetId_ === void 0) {
3044
+ const dataset = await this.readDataset({ datasetName });
3045
+ datasetId_ = dataset.id;
3046
+ }
3047
+ const formattedExamples = inputs.map((input, idx) => {
3048
+ return {
3049
+ dataset_id: datasetId_,
3050
+ inputs: input,
3051
+ outputs: outputs ? outputs[idx] : void 0,
3052
+ metadata: metadata ? metadata[idx] : void 0,
3053
+ split: props.splits ? props.splits[idx] : void 0,
3054
+ id: exampleIds ? exampleIds[idx] : void 0,
3055
+ source_run_id: sourceRunIds ? sourceRunIds[idx] : void 0
3056
+ };
3057
+ });
3058
+ const response = await this.caller.call(fetch, `${this.apiUrl}/examples/bulk`, __spreadValues({
3059
+ method: "POST",
3060
+ headers: __spreadProps(__spreadValues({}, this.headers), { "Content-Type": "application/json" }),
3061
+ body: JSON.stringify(formattedExamples),
3062
+ signal: AbortSignal.timeout(this.timeout_ms)
3063
+ }, this.fetchOptions));
3064
+ if (!response.ok) {
3065
+ throw new Error(`Failed to create examples: ${response.status} ${response.statusText}`);
3066
+ }
3067
+ const result = await response.json();
3068
+ return result;
3069
+ }
3070
+ async createLLMExample(input, generation, options) {
3071
+ return this.createExample({ input }, { output: generation }, options);
3072
+ }
3073
+ async createChatExample(input, generations, options) {
3074
+ const finalInput = input.map((message) => {
3075
+ if (isLangChainMessage(message)) {
3076
+ return convertLangChainMessageToExample(message);
3077
+ }
3078
+ return message;
3079
+ });
3080
+ const finalOutput = isLangChainMessage(generations) ? convertLangChainMessageToExample(generations) : generations;
3081
+ return this.createExample({ input: finalInput }, { output: finalOutput }, options);
3082
+ }
3083
+ async readExample(exampleId) {
3084
+ assertUuid(exampleId);
3085
+ const path = `/examples/${exampleId}`;
3086
+ return await this._get(path);
3087
+ }
3088
+ listExamples() {
3089
+ return __asyncGenerator(this, arguments, function* ({ datasetId, datasetName, exampleIds, asOf, splits, inlineS3Urls, metadata, limit, offset, filter } = {}) {
3090
+ let datasetId_;
3091
+ if (datasetId !== void 0 && datasetName !== void 0) {
3092
+ throw new Error("Must provide either datasetName or datasetId, not both");
3093
+ } else if (datasetId !== void 0) {
3094
+ datasetId_ = datasetId;
3095
+ } else if (datasetName !== void 0) {
3096
+ const dataset = yield new __await(this.readDataset({ datasetName }));
3097
+ datasetId_ = dataset.id;
3098
+ } else {
3099
+ throw new Error("Must provide a datasetName or datasetId");
3100
+ }
3101
+ const params = new URLSearchParams({ dataset: datasetId_ });
3102
+ const dataset_version = asOf ? typeof asOf === "string" ? asOf : asOf == null ? void 0 : asOf.toISOString() : void 0;
3103
+ if (dataset_version) {
3104
+ params.append("as_of", dataset_version);
3105
+ }
3106
+ const inlineS3Urls_ = inlineS3Urls != null ? inlineS3Urls : true;
3107
+ params.append("inline_s3_urls", inlineS3Urls_.toString());
3108
+ if (exampleIds !== void 0) {
3109
+ for (const id_ of exampleIds) {
3110
+ params.append("id", id_);
3111
+ }
3112
+ }
3113
+ if (splits !== void 0) {
3114
+ for (const split of splits) {
3115
+ params.append("splits", split);
3116
+ }
3117
+ }
3118
+ if (metadata !== void 0) {
3119
+ const serializedMetadata = JSON.stringify(metadata);
3120
+ params.append("metadata", serializedMetadata);
3121
+ }
3122
+ if (limit !== void 0) {
3123
+ params.append("limit", limit.toString());
3124
+ }
3125
+ if (offset !== void 0) {
3126
+ params.append("offset", offset.toString());
3127
+ }
3128
+ if (filter !== void 0) {
3129
+ params.append("filter", filter);
3130
+ }
3131
+ let i = 0;
3132
+ try {
3133
+ for (var iter = __forAwait(this._getPaginated("/examples", params)), more, temp, error; more = !(temp = yield new __await(iter.next())).done; more = false) {
3134
+ const examples = temp.value;
3135
+ for (const example of examples) {
3136
+ yield example;
3137
+ i++;
3138
+ }
3139
+ if (limit !== void 0 && i >= limit) {
3140
+ break;
3141
+ }
3142
+ }
3143
+ } catch (temp) {
3144
+ error = [temp];
3145
+ } finally {
3146
+ try {
3147
+ more && (temp = iter.return) && (yield new __await(temp.call(iter)));
3148
+ } finally {
3149
+ if (error)
3150
+ throw error[0];
3151
+ }
3152
+ }
3153
+ });
3154
+ }
3155
+ async deleteExample(exampleId) {
3156
+ assertUuid(exampleId);
3157
+ const path = `/examples/${exampleId}`;
3158
+ const response = await this.caller.call(fetch, this.apiUrl + path, __spreadValues({
3159
+ method: "DELETE",
3160
+ headers: this.headers,
3161
+ signal: AbortSignal.timeout(this.timeout_ms)
3162
+ }, this.fetchOptions));
3163
+ if (!response.ok) {
3164
+ throw new Error(`Failed to delete ${path}: ${response.status} ${response.statusText}`);
3165
+ }
3166
+ await response.json();
3167
+ }
3168
+ async updateExample(exampleId, update) {
3169
+ assertUuid(exampleId);
3170
+ const response = await this.caller.call(fetch, `${this.apiUrl}/examples/${exampleId}`, __spreadValues({
3171
+ method: "PATCH",
3172
+ headers: __spreadProps(__spreadValues({}, this.headers), { "Content-Type": "application/json" }),
3173
+ body: JSON.stringify(update),
3174
+ signal: AbortSignal.timeout(this.timeout_ms)
3175
+ }, this.fetchOptions));
3176
+ if (!response.ok) {
3177
+ throw new Error(`Failed to update example ${exampleId}: ${response.status} ${response.statusText}`);
3178
+ }
3179
+ const result = await response.json();
3180
+ return result;
3181
+ }
3182
+ /**
3183
+ * @deprecated This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead.
3184
+ */
3185
+ async evaluateRun(run, evaluator, { sourceInfo, loadChildRuns, referenceExample } = { loadChildRuns: false }) {
3186
+ warnOnce("This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead.");
3187
+ let run_;
3188
+ if (typeof run === "string") {
3189
+ run_ = await this.readRun(run, { loadChildRuns });
3190
+ } else if (typeof run === "object" && "id" in run) {
3191
+ run_ = run;
3192
+ } else {
3193
+ throw new Error(`Invalid run type: ${typeof run}`);
3194
+ }
3195
+ if (run_.reference_example_id !== null && run_.reference_example_id !== void 0) {
3196
+ referenceExample = await this.readExample(run_.reference_example_id);
3197
+ }
3198
+ const feedbackResult = await evaluator.evaluateRun(run_, referenceExample);
3199
+ const [_, feedbacks] = await this._logEvaluationFeedback(feedbackResult, run_, sourceInfo);
3200
+ return feedbacks[0];
3201
+ }
3202
+ async createFeedback(runId, key, { score, value, correction, comment, sourceInfo, feedbackSourceType = "api", sourceRunId, feedbackId, feedbackConfig, projectId, comparativeExperimentId }) {
3203
+ var _a;
3204
+ if (!runId && !projectId) {
3205
+ throw new Error("One of runId or projectId must be provided");
3206
+ }
3207
+ if (runId && projectId) {
3208
+ throw new Error("Only one of runId or projectId can be provided");
3209
+ }
3210
+ const feedback_source = {
3211
+ type: feedbackSourceType != null ? feedbackSourceType : "api",
3212
+ metadata: sourceInfo != null ? sourceInfo : {}
3213
+ };
3214
+ if (sourceRunId !== void 0 && (feedback_source == null ? void 0 : feedback_source.metadata) !== void 0 && !feedback_source.metadata["__run"]) {
3215
+ feedback_source.metadata["__run"] = { run_id: sourceRunId };
3216
+ }
3217
+ if ((feedback_source == null ? void 0 : feedback_source.metadata) !== void 0 && ((_a = feedback_source.metadata["__run"]) == null ? void 0 : _a.run_id) !== void 0) {
3218
+ assertUuid(feedback_source.metadata["__run"].run_id);
3219
+ }
3220
+ const feedback = {
3221
+ id: feedbackId != null ? feedbackId : v4_default(),
3222
+ run_id: runId,
3223
+ key,
3224
+ score,
3225
+ value,
3226
+ correction,
3227
+ comment,
3228
+ feedback_source,
3229
+ comparative_experiment_id: comparativeExperimentId,
3230
+ feedbackConfig,
3231
+ session_id: projectId
3232
+ };
3233
+ const url = `${this.apiUrl}/feedback`;
3234
+ const response = await this.caller.call(fetch, url, __spreadValues({
3235
+ method: "POST",
3236
+ headers: __spreadProps(__spreadValues({}, this.headers), { "Content-Type": "application/json" }),
3237
+ body: JSON.stringify(feedback),
3238
+ signal: AbortSignal.timeout(this.timeout_ms)
3239
+ }, this.fetchOptions));
3240
+ await raiseForStatus(response, "create feedback");
3241
+ return feedback;
3242
+ }
3243
+ async updateFeedback(feedbackId, { score, value, correction, comment }) {
3244
+ const feedbackUpdate = {};
3245
+ if (score !== void 0 && score !== null) {
3246
+ feedbackUpdate["score"] = score;
3247
+ }
3248
+ if (value !== void 0 && value !== null) {
3249
+ feedbackUpdate["value"] = value;
3250
+ }
3251
+ if (correction !== void 0 && correction !== null) {
3252
+ feedbackUpdate["correction"] = correction;
3253
+ }
3254
+ if (comment !== void 0 && comment !== null) {
3255
+ feedbackUpdate["comment"] = comment;
3256
+ }
3257
+ assertUuid(feedbackId);
3258
+ const response = await this.caller.call(fetch, `${this.apiUrl}/feedback/${feedbackId}`, __spreadValues({
3259
+ method: "PATCH",
3260
+ headers: __spreadProps(__spreadValues({}, this.headers), { "Content-Type": "application/json" }),
3261
+ body: JSON.stringify(feedbackUpdate),
3262
+ signal: AbortSignal.timeout(this.timeout_ms)
3263
+ }, this.fetchOptions));
3264
+ await raiseForStatus(response, "update feedback");
3265
+ }
3266
+ async readFeedback(feedbackId) {
3267
+ assertUuid(feedbackId);
3268
+ const path = `/feedback/${feedbackId}`;
3269
+ const response = await this._get(path);
3270
+ return response;
3271
+ }
3272
+ async deleteFeedback(feedbackId) {
3273
+ assertUuid(feedbackId);
3274
+ const path = `/feedback/${feedbackId}`;
3275
+ const response = await this.caller.call(fetch, this.apiUrl + path, __spreadValues({
3276
+ method: "DELETE",
3277
+ headers: this.headers,
3278
+ signal: AbortSignal.timeout(this.timeout_ms)
3279
+ }, this.fetchOptions));
3280
+ if (!response.ok) {
3281
+ throw new Error(`Failed to delete ${path}: ${response.status} ${response.statusText}`);
3282
+ }
3283
+ await response.json();
3284
+ }
3285
+ listFeedback() {
3286
+ return __asyncGenerator(this, arguments, function* ({ runIds, feedbackKeys, feedbackSourceTypes } = {}) {
3287
+ const queryParams = new URLSearchParams();
3288
+ if (runIds) {
3289
+ queryParams.append("run", runIds.join(","));
3290
+ }
3291
+ if (feedbackKeys) {
3292
+ for (const key of feedbackKeys) {
3293
+ queryParams.append("key", key);
3294
+ }
3295
+ }
3296
+ if (feedbackSourceTypes) {
3297
+ for (const type of feedbackSourceTypes) {
3298
+ queryParams.append("source", type);
3299
+ }
3300
+ }
3301
+ try {
3302
+ for (var iter = __forAwait(this._getPaginated("/feedback", queryParams)), more, temp, error; more = !(temp = yield new __await(iter.next())).done; more = false) {
3303
+ const feedbacks = temp.value;
3304
+ yield* __yieldStar(feedbacks);
3305
+ }
3306
+ } catch (temp) {
3307
+ error = [temp];
3308
+ } finally {
3309
+ try {
3310
+ more && (temp = iter.return) && (yield new __await(temp.call(iter)));
3311
+ } finally {
3312
+ if (error)
3313
+ throw error[0];
3314
+ }
3315
+ }
3316
+ });
3317
+ }
3318
+ /**
3319
+ * Creates a presigned feedback token and URL.
3320
+ *
3321
+ * The token can be used to authorize feedback metrics without
3322
+ * needing an API key. This is useful for giving browser-based
3323
+ * applications the ability to submit feedback without needing
3324
+ * to expose an API key.
3325
+ *
3326
+ * @param runId - The ID of the run.
3327
+ * @param feedbackKey - The feedback key.
3328
+ * @param options - Additional options for the token.
3329
+ * @param options.expiration - The expiration time for the token.
3330
+ *
3331
+ * @returns A promise that resolves to a FeedbackIngestToken.
3332
+ */
3333
+ async createPresignedFeedbackToken(runId, feedbackKey, { expiration, feedbackConfig } = {}) {
3334
+ const body = {
3335
+ run_id: runId,
3336
+ feedback_key: feedbackKey,
3337
+ feedback_config: feedbackConfig
3338
+ };
3339
+ if (expiration) {
3340
+ if (typeof expiration === "string") {
3341
+ body["expires_at"] = expiration;
3342
+ } else if ((expiration == null ? void 0 : expiration.hours) || (expiration == null ? void 0 : expiration.minutes) || (expiration == null ? void 0 : expiration.days)) {
3343
+ body["expires_in"] = expiration;
3344
+ }
3345
+ } else {
3346
+ body["expires_in"] = {
3347
+ hours: 3
3348
+ };
3349
+ }
3350
+ const response = await this.caller.call(fetch, `${this.apiUrl}/feedback/tokens`, __spreadValues({
3351
+ method: "POST",
3352
+ headers: __spreadProps(__spreadValues({}, this.headers), { "Content-Type": "application/json" }),
3353
+ body: JSON.stringify(body),
3354
+ signal: AbortSignal.timeout(this.timeout_ms)
3355
+ }, this.fetchOptions));
3356
+ const result = await response.json();
3357
+ return result;
3358
+ }
3359
+ async createComparativeExperiment({ name, experimentIds, referenceDatasetId, createdAt, description, metadata, id }) {
3360
+ var _a;
3361
+ if (experimentIds.length === 0) {
3362
+ throw new Error("At least one experiment is required");
3363
+ }
3364
+ if (!referenceDatasetId) {
3365
+ referenceDatasetId = (await this.readProject({
3366
+ projectId: experimentIds[0]
3367
+ })).reference_dataset_id;
3368
+ }
3369
+ if (!referenceDatasetId == null) {
3370
+ throw new Error("A reference dataset is required");
3371
+ }
3372
+ const body = {
3373
+ id,
3374
+ name,
3375
+ experiment_ids: experimentIds,
3376
+ reference_dataset_id: referenceDatasetId,
3377
+ description,
3378
+ created_at: (_a = createdAt != null ? createdAt : /* @__PURE__ */ new Date()) == null ? void 0 : _a.toISOString(),
3379
+ extra: {}
3380
+ };
3381
+ if (metadata)
3382
+ body.extra["metadata"] = metadata;
3383
+ const response = await this.caller.call(fetch, `${this.apiUrl}/datasets/comparative`, __spreadValues({
3384
+ method: "POST",
3385
+ headers: __spreadProps(__spreadValues({}, this.headers), { "Content-Type": "application/json" }),
3386
+ body: JSON.stringify(body),
3387
+ signal: AbortSignal.timeout(this.timeout_ms)
3388
+ }, this.fetchOptions));
3389
+ return await response.json();
3390
+ }
3391
+ /**
3392
+ * Retrieves a list of presigned feedback tokens for a given run ID.
3393
+ * @param runId The ID of the run.
3394
+ * @returns An async iterable of FeedbackIngestToken objects.
3395
+ */
3396
+ listPresignedFeedbackTokens(runId) {
3397
+ return __asyncGenerator(this, null, function* () {
3398
+ assertUuid(runId);
3399
+ const params = new URLSearchParams({ run_id: runId });
3400
+ try {
3401
+ for (var iter = __forAwait(this._getPaginated("/feedback/tokens", params)), more, temp, error; more = !(temp = yield new __await(iter.next())).done; more = false) {
3402
+ const tokens = temp.value;
3403
+ yield* __yieldStar(tokens);
3404
+ }
3405
+ } catch (temp) {
3406
+ error = [temp];
3407
+ } finally {
3408
+ try {
3409
+ more && (temp = iter.return) && (yield new __await(temp.call(iter)));
3410
+ } finally {
3411
+ if (error)
3412
+ throw error[0];
3413
+ }
3414
+ }
3415
+ });
3416
+ }
3417
+ _selectEvalResults(results) {
3418
+ let results_;
3419
+ if ("results" in results) {
3420
+ results_ = results.results;
3421
+ } else {
3422
+ results_ = [results];
3423
+ }
3424
+ return results_;
3425
+ }
3426
+ async _logEvaluationFeedback(evaluatorResponse, run, sourceInfo) {
3427
+ const evalResults = this._selectEvalResults(evaluatorResponse);
3428
+ const feedbacks = [];
3429
+ for (const res of evalResults) {
3430
+ let sourceInfo_ = sourceInfo || {};
3431
+ if (res.evaluatorInfo) {
3432
+ sourceInfo_ = __spreadValues(__spreadValues({}, res.evaluatorInfo), sourceInfo_);
3433
+ }
3434
+ let runId_ = null;
3435
+ if (res.targetRunId) {
3436
+ runId_ = res.targetRunId;
3437
+ } else if (run) {
3438
+ runId_ = run.id;
3439
+ }
3440
+ feedbacks.push(await this.createFeedback(runId_, res.key, {
3441
+ score: res.score,
3442
+ value: res.value,
3443
+ comment: res.comment,
3444
+ correction: res.correction,
3445
+ sourceInfo: sourceInfo_,
3446
+ sourceRunId: res.sourceRunId,
3447
+ feedbackConfig: res.feedbackConfig,
3448
+ feedbackSourceType: "model"
3449
+ }));
3450
+ }
3451
+ return [evalResults, feedbacks];
3452
+ }
3453
+ async logEvaluationFeedback(evaluatorResponse, run, sourceInfo) {
3454
+ const [results] = await this._logEvaluationFeedback(evaluatorResponse, run, sourceInfo);
3455
+ return results;
3456
+ }
3457
+ };
3458
+
3459
+ // ../../node_modules/.pnpm/langsmith@0.1.36_openai@4.47.1/node_modules/langsmith/dist/index.js
3460
+ var __version__ = "0.1.36";
3461
+
3462
+ // ../../node_modules/.pnpm/langsmith@0.1.36_openai@4.47.1/node_modules/langsmith/dist/utils/env.js
3463
+ var globalEnv;
3464
+ var isBrowser = () => typeof window !== "undefined" && typeof window.document !== "undefined";
3465
+ var isWebWorker = () => typeof globalThis === "object" && globalThis.constructor && globalThis.constructor.name === "DedicatedWorkerGlobalScope";
3466
+ var isJsDom = () => typeof window !== "undefined" && window.name === "nodejs" || typeof navigator !== "undefined" && (navigator.userAgent.includes("Node.js") || navigator.userAgent.includes("jsdom"));
3467
+ var isDeno = () => typeof Deno !== "undefined";
3468
+ var isNode = () => typeof process !== "undefined" && typeof process.versions !== "undefined" && typeof process.versions.node !== "undefined" && !isDeno();
3469
+ var getEnv = () => {
3470
+ if (globalEnv) {
3471
+ return globalEnv;
3472
+ }
3473
+ if (isBrowser()) {
3474
+ globalEnv = "browser";
3475
+ } else if (isNode()) {
3476
+ globalEnv = "node";
3477
+ } else if (isWebWorker()) {
3478
+ globalEnv = "webworker";
3479
+ } else if (isJsDom()) {
3480
+ globalEnv = "jsdom";
3481
+ } else if (isDeno()) {
3482
+ globalEnv = "deno";
3483
+ } else {
3484
+ globalEnv = "other";
3485
+ }
3486
+ return globalEnv;
3487
+ };
3488
+ var runtimeEnvironment;
3489
+ async function getRuntimeEnvironment() {
3490
+ if (runtimeEnvironment === void 0) {
3491
+ const env = getEnv();
3492
+ const releaseEnv = getShas();
3493
+ runtimeEnvironment = __spreadValues({
3494
+ library: "langsmith",
3495
+ runtime: env,
3496
+ sdk: "langsmith-js",
3497
+ sdk_version: __version__
3498
+ }, releaseEnv);
3499
+ }
3500
+ return runtimeEnvironment;
3501
+ }
3502
+ function getLangChainEnvVarsMetadata() {
3503
+ const allEnvVars = getEnvironmentVariables() || {};
3504
+ const envVars = {};
3505
+ const excluded = [
3506
+ "LANGCHAIN_API_KEY",
3507
+ "LANGCHAIN_ENDPOINT",
3508
+ "LANGCHAIN_TRACING_V2",
3509
+ "LANGCHAIN_PROJECT",
3510
+ "LANGCHAIN_SESSION"
3511
+ ];
3512
+ for (const [key, value] of Object.entries(allEnvVars)) {
3513
+ if (key.startsWith("LANGCHAIN_") && typeof value === "string" && !excluded.includes(key) && !key.toLowerCase().includes("key") && !key.toLowerCase().includes("secret") && !key.toLowerCase().includes("token")) {
3514
+ if (key === "LANGCHAIN_REVISION_ID") {
3515
+ envVars["revision_id"] = value;
3516
+ } else {
3517
+ envVars[key] = value;
3518
+ }
3519
+ }
3520
+ }
3521
+ return envVars;
3522
+ }
3523
+ function getEnvironmentVariables() {
3524
+ try {
3525
+ if (typeof process !== "undefined" && process.env) {
3526
+ return Object.entries(process.env).reduce((acc, [key, value]) => {
3527
+ acc[key] = String(value);
3528
+ return acc;
3529
+ }, {});
3530
+ }
3531
+ return void 0;
3532
+ } catch (e) {
3533
+ return void 0;
3534
+ }
3535
+ }
3536
+ function getEnvironmentVariable(name) {
3537
+ var _a;
3538
+ try {
3539
+ return typeof process !== "undefined" ? (
3540
+ // eslint-disable-next-line no-process-env
3541
+ (_a = process.env) == null ? void 0 : _a[name]
3542
+ ) : void 0;
3543
+ } catch (e) {
3544
+ return void 0;
3545
+ }
3546
+ }
3547
+ var cachedCommitSHAs;
3548
+ function getShas() {
3549
+ if (cachedCommitSHAs !== void 0) {
3550
+ return cachedCommitSHAs;
3551
+ }
3552
+ const common_release_envs = [
3553
+ "VERCEL_GIT_COMMIT_SHA",
3554
+ "NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA",
3555
+ "COMMIT_REF",
3556
+ "RENDER_GIT_COMMIT",
3557
+ "CI_COMMIT_SHA",
3558
+ "CIRCLE_SHA1",
3559
+ "CF_PAGES_COMMIT_SHA",
3560
+ "REACT_APP_GIT_SHA",
3561
+ "SOURCE_VERSION",
3562
+ "GITHUB_SHA",
3563
+ "TRAVIS_COMMIT",
3564
+ "GIT_COMMIT",
3565
+ "BUILD_VCS_NUMBER",
3566
+ "bamboo_planRepository_revision",
3567
+ "Build.SourceVersion",
3568
+ "BITBUCKET_COMMIT",
3569
+ "DRONE_COMMIT_SHA",
3570
+ "SEMAPHORE_GIT_SHA",
3571
+ "BUILDKITE_COMMIT"
3572
+ ];
3573
+ const shas = {};
3574
+ for (const env of common_release_envs) {
3575
+ const envVar = getEnvironmentVariable(env);
3576
+ if (envVar !== void 0) {
3577
+ shas[env] = envVar;
3578
+ }
3579
+ }
3580
+ cachedCommitSHAs = shas;
3581
+ return shas;
3582
+ }
3583
+
3584
+ // ../../node_modules/.pnpm/langsmith@0.1.36_openai@4.47.1/node_modules/langsmith/dist/env.js
3585
+ var isTracingEnabled = (tracingEnabled) => {
3586
+ if (tracingEnabled !== void 0) {
3587
+ return tracingEnabled;
3588
+ }
3589
+ const envVars = [
3590
+ "LANGSMITH_TRACING_V2",
3591
+ "LANGCHAIN_TRACING_V2",
3592
+ "LANGSMITH_TRACING",
3593
+ "LANGCHAIN_TRACING"
3594
+ ];
3595
+ return !!envVars.find((envVar) => getEnvironmentVariable(envVar) === "true");
3596
+ };
3597
+
3598
+ // ../../node_modules/.pnpm/langsmith@0.1.36_openai@4.47.1/node_modules/langsmith/dist/run_trees.js
3599
+ function stripNonAlphanumeric(input) {
3600
+ return input.replace(/[-:.]/g, "");
3601
+ }
3602
+ function convertToDottedOrderFormat(epoch, runId, executionOrder = 1) {
3603
+ const paddedOrder = executionOrder.toFixed(0).slice(0, 3).padStart(3, "0");
3604
+ return stripNonAlphanumeric(`${new Date(epoch).toISOString().slice(0, -1)}${paddedOrder}Z`) + runId;
3605
+ }
3606
+ var Baggage = class _Baggage {
3607
+ constructor(metadata, tags) {
3608
+ Object.defineProperty(this, "metadata", {
3609
+ enumerable: true,
3610
+ configurable: true,
3611
+ writable: true,
3612
+ value: void 0
3613
+ });
3614
+ Object.defineProperty(this, "tags", {
3615
+ enumerable: true,
3616
+ configurable: true,
3617
+ writable: true,
3618
+ value: void 0
3619
+ });
3620
+ this.metadata = metadata;
3621
+ this.tags = tags;
3622
+ }
3623
+ static fromHeader(value) {
3624
+ const items = value.split(",");
3625
+ let metadata = {};
3626
+ let tags = [];
3627
+ for (const item of items) {
3628
+ const [key, uriValue] = item.split("=");
3629
+ const value2 = decodeURIComponent(uriValue);
3630
+ if (key === "langsmith-metadata") {
3631
+ metadata = JSON.parse(value2);
3632
+ } else if (key === "langsmith-tags") {
3633
+ tags = value2.split(",");
3634
+ }
3635
+ }
3636
+ return new _Baggage(metadata, tags);
3637
+ }
3638
+ toHeader() {
3639
+ const items = [];
3640
+ if (this.metadata && Object.keys(this.metadata).length > 0) {
3641
+ items.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`);
3642
+ }
3643
+ if (this.tags && this.tags.length > 0) {
3644
+ items.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`);
3645
+ }
3646
+ return items.join(",");
3647
+ }
3648
+ };
3649
+ var RunTree = class _RunTree {
3650
+ constructor(originalConfig) {
3651
+ var _b, _c, _d, _e, _f;
3652
+ Object.defineProperty(this, "id", {
3653
+ enumerable: true,
3654
+ configurable: true,
3655
+ writable: true,
3656
+ value: void 0
3657
+ });
3658
+ Object.defineProperty(this, "name", {
3659
+ enumerable: true,
3660
+ configurable: true,
3661
+ writable: true,
3662
+ value: void 0
3663
+ });
3664
+ Object.defineProperty(this, "run_type", {
3665
+ enumerable: true,
3666
+ configurable: true,
3667
+ writable: true,
3668
+ value: void 0
3669
+ });
3670
+ Object.defineProperty(this, "project_name", {
3671
+ enumerable: true,
3672
+ configurable: true,
3673
+ writable: true,
3674
+ value: void 0
3675
+ });
3676
+ Object.defineProperty(this, "parent_run", {
3677
+ enumerable: true,
3678
+ configurable: true,
3679
+ writable: true,
3680
+ value: void 0
3681
+ });
3682
+ Object.defineProperty(this, "child_runs", {
3683
+ enumerable: true,
3684
+ configurable: true,
3685
+ writable: true,
3686
+ value: void 0
3687
+ });
3688
+ Object.defineProperty(this, "start_time", {
3689
+ enumerable: true,
3690
+ configurable: true,
3691
+ writable: true,
3692
+ value: void 0
3693
+ });
3694
+ Object.defineProperty(this, "end_time", {
3695
+ enumerable: true,
3696
+ configurable: true,
3697
+ writable: true,
3698
+ value: void 0
3699
+ });
3700
+ Object.defineProperty(this, "extra", {
3701
+ enumerable: true,
3702
+ configurable: true,
3703
+ writable: true,
3704
+ value: void 0
3705
+ });
3706
+ Object.defineProperty(this, "tags", {
3707
+ enumerable: true,
3708
+ configurable: true,
3709
+ writable: true,
3710
+ value: void 0
3711
+ });
3712
+ Object.defineProperty(this, "error", {
3713
+ enumerable: true,
3714
+ configurable: true,
3715
+ writable: true,
3716
+ value: void 0
3717
+ });
3718
+ Object.defineProperty(this, "serialized", {
3719
+ enumerable: true,
3720
+ configurable: true,
3721
+ writable: true,
3722
+ value: void 0
3723
+ });
3724
+ Object.defineProperty(this, "inputs", {
3725
+ enumerable: true,
3726
+ configurable: true,
3727
+ writable: true,
3728
+ value: void 0
3729
+ });
3730
+ Object.defineProperty(this, "outputs", {
3731
+ enumerable: true,
3732
+ configurable: true,
3733
+ writable: true,
3734
+ value: void 0
3735
+ });
3736
+ Object.defineProperty(this, "reference_example_id", {
3737
+ enumerable: true,
3738
+ configurable: true,
3739
+ writable: true,
3740
+ value: void 0
3741
+ });
3742
+ Object.defineProperty(this, "client", {
3743
+ enumerable: true,
3744
+ configurable: true,
3745
+ writable: true,
3746
+ value: void 0
3747
+ });
3748
+ Object.defineProperty(this, "events", {
3749
+ enumerable: true,
3750
+ configurable: true,
3751
+ writable: true,
3752
+ value: void 0
3753
+ });
3754
+ Object.defineProperty(this, "trace_id", {
3755
+ enumerable: true,
3756
+ configurable: true,
3757
+ writable: true,
3758
+ value: void 0
3759
+ });
3760
+ Object.defineProperty(this, "dotted_order", {
3761
+ enumerable: true,
3762
+ configurable: true,
3763
+ writable: true,
3764
+ value: void 0
3765
+ });
3766
+ Object.defineProperty(this, "tracingEnabled", {
3767
+ enumerable: true,
3768
+ configurable: true,
3769
+ writable: true,
3770
+ value: void 0
3771
+ });
3772
+ Object.defineProperty(this, "execution_order", {
3773
+ enumerable: true,
3774
+ configurable: true,
3775
+ writable: true,
3776
+ value: void 0
3777
+ });
3778
+ Object.defineProperty(this, "child_execution_order", {
3779
+ enumerable: true,
3780
+ configurable: true,
3781
+ writable: true,
3782
+ value: void 0
3783
+ });
3784
+ const defaultConfig = _RunTree.getDefaultConfig();
3785
+ const _a = originalConfig, { metadata } = _a, config = __objRest(_a, ["metadata"]);
3786
+ const client = (_b = config.client) != null ? _b : new Client();
3787
+ const dedupedMetadata = __spreadValues(__spreadValues({}, metadata), (_c = config == null ? void 0 : config.extra) == null ? void 0 : _c.metadata);
3788
+ config.extra = __spreadProps(__spreadValues({}, config.extra), { metadata: dedupedMetadata });
3789
+ Object.assign(this, __spreadProps(__spreadValues(__spreadValues({}, defaultConfig), config), { client }));
3790
+ if (!this.trace_id) {
3791
+ if (this.parent_run) {
3792
+ this.trace_id = (_d = this.parent_run.trace_id) != null ? _d : this.id;
3793
+ } else {
3794
+ this.trace_id = this.id;
3795
+ }
3796
+ }
3797
+ (_e = this.execution_order) != null ? _e : this.execution_order = 1;
3798
+ (_f = this.child_execution_order) != null ? _f : this.child_execution_order = 1;
3799
+ if (!this.dotted_order) {
3800
+ const currentDottedOrder = convertToDottedOrderFormat(this.start_time, this.id, this.execution_order);
3801
+ if (this.parent_run) {
3802
+ this.dotted_order = this.parent_run.dotted_order + "." + currentDottedOrder;
3803
+ } else {
3804
+ this.dotted_order = currentDottedOrder;
3805
+ }
3806
+ }
3807
+ }
3808
+ static getDefaultConfig() {
3809
+ var _a, _b, _c;
3810
+ return {
3811
+ id: v4_default(),
3812
+ run_type: "chain",
3813
+ project_name: (_b = (_a = getEnvironmentVariable("LANGCHAIN_PROJECT")) != null ? _a : getEnvironmentVariable("LANGCHAIN_SESSION")) != null ? _b : (
3814
+ // TODO: Deprecate
3815
+ "default"
3816
+ ),
3817
+ child_runs: [],
3818
+ api_url: (_c = getEnvironmentVariable("LANGCHAIN_ENDPOINT")) != null ? _c : "http://localhost:1984",
3819
+ api_key: getEnvironmentVariable("LANGCHAIN_API_KEY"),
3820
+ caller_options: {},
3821
+ start_time: Date.now(),
3822
+ serialized: {},
3823
+ inputs: {},
3824
+ extra: {}
3825
+ };
3826
+ }
3827
+ createChild(config) {
3828
+ const child_execution_order = this.child_execution_order + 1;
3829
+ const child = new _RunTree(__spreadProps(__spreadValues({}, config), {
3830
+ parent_run: this,
3831
+ project_name: this.project_name,
3832
+ client: this.client,
3833
+ tracingEnabled: this.tracingEnabled,
3834
+ execution_order: child_execution_order,
3835
+ child_execution_order
3836
+ }));
3837
+ const visited = /* @__PURE__ */ new Set();
3838
+ let current = this;
3839
+ while (current != null && !visited.has(current.id)) {
3840
+ visited.add(current.id);
3841
+ current.child_execution_order = Math.max(current.child_execution_order, child_execution_order);
3842
+ current = current.parent_run;
3843
+ }
3844
+ this.child_runs.push(child);
3845
+ return child;
3846
+ }
3847
+ async end(outputs, error, endTime = Date.now()) {
3848
+ var _a, _b, _c;
3849
+ this.outputs = (_a = this.outputs) != null ? _a : outputs;
3850
+ this.error = (_b = this.error) != null ? _b : error;
3851
+ this.end_time = (_c = this.end_time) != null ? _c : endTime;
3852
+ }
3853
+ _convertToCreate(run, runtimeEnv, excludeChildRuns = true) {
3854
+ var _a, _b;
3855
+ const runExtra = (_a = run.extra) != null ? _a : {};
3856
+ if (!runExtra.runtime) {
3857
+ runExtra.runtime = {};
3858
+ }
3859
+ if (runtimeEnv) {
3860
+ for (const [k, v] of Object.entries(runtimeEnv)) {
3861
+ if (!runExtra.runtime[k]) {
3862
+ runExtra.runtime[k] = v;
3863
+ }
3864
+ }
3865
+ }
3866
+ let child_runs;
3867
+ let parent_run_id;
3868
+ if (!excludeChildRuns) {
3869
+ child_runs = run.child_runs.map((child_run) => this._convertToCreate(child_run, runtimeEnv, excludeChildRuns));
3870
+ parent_run_id = void 0;
3871
+ } else {
3872
+ parent_run_id = (_b = run.parent_run) == null ? void 0 : _b.id;
3873
+ child_runs = [];
3874
+ }
3875
+ const persistedRun = {
3876
+ id: run.id,
3877
+ name: run.name,
3878
+ start_time: run.start_time,
3879
+ end_time: run.end_time,
3880
+ run_type: run.run_type,
3881
+ reference_example_id: run.reference_example_id,
3882
+ extra: runExtra,
3883
+ serialized: run.serialized,
3884
+ error: run.error,
3885
+ inputs: run.inputs,
3886
+ outputs: run.outputs,
3887
+ session_name: run.project_name,
3888
+ child_runs,
3889
+ parent_run_id,
3890
+ trace_id: run.trace_id,
3891
+ dotted_order: run.dotted_order,
3892
+ tags: run.tags
3893
+ };
3894
+ return persistedRun;
3895
+ }
3896
+ async postRun(excludeChildRuns = true) {
3897
+ const runtimeEnv = await getRuntimeEnvironment();
3898
+ const runCreate = await this._convertToCreate(this, runtimeEnv, true);
3899
+ await this.client.createRun(runCreate);
3900
+ if (!excludeChildRuns) {
3901
+ warnOnce("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");
3902
+ for (const childRun of this.child_runs) {
3903
+ await childRun.postRun(false);
3904
+ }
3905
+ }
3906
+ }
3907
+ async patchRun() {
3908
+ var _a;
3909
+ const runUpdate = {
3910
+ end_time: this.end_time,
3911
+ error: this.error,
3912
+ inputs: this.inputs,
3913
+ outputs: this.outputs,
3914
+ parent_run_id: (_a = this.parent_run) == null ? void 0 : _a.id,
3915
+ reference_example_id: this.reference_example_id,
3916
+ extra: this.extra,
3917
+ events: this.events,
3918
+ dotted_order: this.dotted_order,
3919
+ trace_id: this.trace_id,
3920
+ tags: this.tags
3921
+ };
3922
+ await this.client.updateRun(this.id, runUpdate);
3923
+ }
3924
+ toJSON() {
3925
+ return this._convertToCreate(this, void 0, false);
3926
+ }
3927
+ static fromRunnableConfig(parentConfig, props) {
3928
+ var _a, _b, _c, _d, _e, _f, _g;
3929
+ const callbackManager = parentConfig == null ? void 0 : parentConfig.callbacks;
3930
+ let parentRun;
3931
+ let projectName;
3932
+ let client;
3933
+ let tracingEnabled = isTracingEnabled();
3934
+ if (callbackManager) {
3935
+ const parentRunId = (_b = (_a = callbackManager == null ? void 0 : callbackManager.getParentRunId) == null ? void 0 : _a.call(callbackManager)) != null ? _b : "";
3936
+ const langChainTracer = (_c = callbackManager == null ? void 0 : callbackManager.handlers) == null ? void 0 : _c.find((handler) => (handler == null ? void 0 : handler.name) == "langchain_tracer");
3937
+ parentRun = (_d = langChainTracer == null ? void 0 : langChainTracer.getRun) == null ? void 0 : _d.call(langChainTracer, parentRunId);
3938
+ projectName = langChainTracer == null ? void 0 : langChainTracer.projectName;
3939
+ client = langChainTracer == null ? void 0 : langChainTracer.client;
3940
+ tracingEnabled = tracingEnabled || !!langChainTracer;
3941
+ }
3942
+ if (!parentRun) {
3943
+ return new _RunTree(__spreadProps(__spreadValues({}, props), {
3944
+ client,
3945
+ tracingEnabled,
3946
+ project_name: projectName
3947
+ }));
3948
+ }
3949
+ const parentRunTree = new _RunTree({
3950
+ name: parentRun.name,
3951
+ id: parentRun.id,
3952
+ client,
3953
+ tracingEnabled,
3954
+ project_name: projectName,
3955
+ tags: [
3956
+ ...new Set(((_e = parentRun == null ? void 0 : parentRun.tags) != null ? _e : []).concat((_f = parentConfig == null ? void 0 : parentConfig.tags) != null ? _f : []))
3957
+ ],
3958
+ extra: {
3959
+ metadata: __spreadValues(__spreadValues({}, (_g = parentRun == null ? void 0 : parentRun.extra) == null ? void 0 : _g.metadata), parentConfig == null ? void 0 : parentConfig.metadata)
3960
+ }
3961
+ });
3962
+ return parentRunTree.createChild(props);
3963
+ }
3964
+ static fromDottedOrder(dottedOrder) {
3965
+ return this.fromHeaders({ "langsmith-trace": dottedOrder });
3966
+ }
3967
+ static fromHeaders(headers, inheritArgs) {
3968
+ var _a, _b, _c, _d;
3969
+ const rawHeaders = "get" in headers && typeof headers.get === "function" ? {
3970
+ "langsmith-trace": headers.get("langsmith-trace"),
3971
+ baggage: headers.get("baggage")
3972
+ } : headers;
3973
+ const headerTrace = rawHeaders["langsmith-trace"];
3974
+ if (!headerTrace || typeof headerTrace !== "string")
3975
+ return void 0;
3976
+ const parentDottedOrder = headerTrace.trim();
3977
+ const parsedDottedOrder = parentDottedOrder.split(".").map((part) => {
3978
+ const [strTime, uuid] = part.split("Z");
3979
+ return { strTime, time: Date.parse(strTime + "Z"), uuid };
3980
+ });
3981
+ const traceId = parsedDottedOrder[0].uuid;
3982
+ const config = __spreadProps(__spreadValues({}, inheritArgs), {
3983
+ name: (_a = inheritArgs == null ? void 0 : inheritArgs["name"]) != null ? _a : "parent",
3984
+ run_type: (_b = inheritArgs == null ? void 0 : inheritArgs["run_type"]) != null ? _b : "chain",
3985
+ start_time: (_c = inheritArgs == null ? void 0 : inheritArgs["start_time"]) != null ? _c : Date.now(),
3986
+ id: (_d = parsedDottedOrder.at(-1)) == null ? void 0 : _d.uuid,
3987
+ trace_id: traceId,
3988
+ dotted_order: parentDottedOrder
3989
+ });
3990
+ if (rawHeaders["baggage"] && typeof rawHeaders["baggage"] === "string") {
3991
+ const baggage = Baggage.fromHeader(rawHeaders["baggage"]);
3992
+ config.metadata = baggage.metadata;
3993
+ config.tags = baggage.tags;
3994
+ }
3995
+ return new _RunTree(config);
3996
+ }
3997
+ toHeaders(headers) {
3998
+ var _a;
3999
+ const result = {
4000
+ "langsmith-trace": this.dotted_order,
4001
+ baggage: new Baggage((_a = this.extra) == null ? void 0 : _a.metadata, this.tags).toHeader()
4002
+ };
4003
+ if (headers) {
4004
+ for (const [key, value] of Object.entries(result)) {
4005
+ headers.set(key, value);
4006
+ }
4007
+ }
4008
+ return result;
4009
+ }
4010
+ };
4011
+ function isRunTree(x) {
4012
+ return x !== void 0 && typeof x.createChild === "function" && typeof x.postRun === "function";
4013
+ }
4014
+ function containsLangChainTracerLike(x) {
4015
+ return Array.isArray(x) && x.some((callback) => {
4016
+ return typeof callback.name === "string" && callback.name === "langchain_tracer";
4017
+ });
4018
+ }
4019
+ function isRunnableConfigLike(x) {
4020
+ var _a;
4021
+ return x !== void 0 && typeof x.callbacks === "object" && // Callback manager with a langchain tracer
4022
+ (containsLangChainTracerLike((_a = x.callbacks) == null ? void 0 : _a.handlers) || // Or it's an array with a LangChainTracerLike object within it
4023
+ containsLangChainTracerLike(x.callbacks));
4024
+ }
4025
+
4026
+ // ../../node_modules/.pnpm/langsmith@0.1.36_openai@4.47.1/node_modules/langsmith/dist/singletons/traceable.js
4027
+ var MockAsyncLocalStorage = class {
4028
+ getStore() {
4029
+ return void 0;
4030
+ }
4031
+ run(_, callback) {
4032
+ return callback();
4033
+ }
4034
+ };
4035
+ var AsyncLocalStorageProvider = class {
4036
+ constructor() {
4037
+ Object.defineProperty(this, "asyncLocalStorage", {
4038
+ enumerable: true,
4039
+ configurable: true,
4040
+ writable: true,
4041
+ value: new MockAsyncLocalStorage()
4042
+ });
4043
+ Object.defineProperty(this, "hasBeenInitialized", {
4044
+ enumerable: true,
4045
+ configurable: true,
4046
+ writable: true,
4047
+ value: false
4048
+ });
4049
+ }
4050
+ getInstance() {
4051
+ return this.asyncLocalStorage;
4052
+ }
4053
+ initializeGlobalInstance(instance) {
4054
+ if (!this.hasBeenInitialized) {
4055
+ this.hasBeenInitialized = true;
4056
+ this.asyncLocalStorage = instance;
4057
+ }
4058
+ }
4059
+ };
4060
+ var AsyncLocalStorageProviderSingleton = new AsyncLocalStorageProvider();
4061
+ var ROOT = Symbol.for("langsmith:traceable:root");
4062
+ function isTraceableFunction(x) {
4063
+ return typeof x === "function" && "langsmith:traceable" in x;
4064
+ }
4065
+
4066
+ // ../../node_modules/.pnpm/langsmith@0.1.36_openai@4.47.1/node_modules/langsmith/dist/utils/asserts.js
4067
+ function isPromiseMethod(x) {
4068
+ if (x === "then" || x === "catch" || x === "finally") {
4069
+ return true;
4070
+ }
4071
+ return false;
4072
+ }
4073
+ function isKVMap(x) {
4074
+ if (typeof x !== "object" || x == null) {
4075
+ return false;
4076
+ }
4077
+ const prototype = Object.getPrototypeOf(x);
4078
+ return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in x) && !(Symbol.iterator in x);
4079
+ }
4080
+ var isAsyncIterable = (x) => x != null && typeof x === "object" && // eslint-disable-next-line @typescript-eslint/no-explicit-any
4081
+ typeof x[Symbol.asyncIterator] === "function";
4082
+ var isIteratorLike = (x) => x != null && typeof x === "object" && "next" in x && typeof x.next === "function";
4083
+ var GeneratorFunction = function* () {
4084
+ }.constructor;
4085
+ var isGenerator = (x) => (
4086
+ // eslint-disable-next-line no-instanceof/no-instanceof
4087
+ x != null && typeof x === "function" && x instanceof GeneratorFunction
4088
+ );
4089
+ var isThenable = (x) => x != null && typeof x === "object" && "then" in x && typeof x.then === "function";
4090
+ var isReadableStream = (x) => x != null && typeof x === "object" && "getReader" in x && typeof x.getReader === "function";
4091
+
4092
+ // ../../node_modules/.pnpm/langsmith@0.1.36_openai@4.47.1/node_modules/langsmith/dist/traceable.js
4093
+ AsyncLocalStorageProviderSingleton.initializeGlobalInstance(new AsyncLocalStorage());
4094
+ var handleRunInputs = (rawInputs) => {
4095
+ const firstInput = rawInputs[0];
4096
+ if (firstInput == null) {
4097
+ return {};
4098
+ }
4099
+ if (rawInputs.length > 1) {
4100
+ return { args: rawInputs };
4101
+ }
4102
+ if (isKVMap(firstInput)) {
4103
+ return firstInput;
4104
+ }
4105
+ return { input: firstInput };
4106
+ };
4107
+ var handleRunOutputs = (rawOutputs) => {
4108
+ if (isKVMap(rawOutputs)) {
4109
+ return rawOutputs;
4110
+ }
4111
+ return { outputs: rawOutputs };
4112
+ };
4113
+ var getTracingRunTree = (runTree, inputs, getInvocationParams) => {
4114
+ var _a;
4115
+ if (!isTracingEnabled(runTree.tracingEnabled)) {
4116
+ return void 0;
4117
+ }
4118
+ runTree.inputs = handleRunInputs(inputs);
4119
+ const invocationParams = getInvocationParams == null ? void 0 : getInvocationParams(...inputs);
4120
+ if (invocationParams != null) {
4121
+ (_a = runTree.extra) != null ? _a : runTree.extra = {};
4122
+ runTree.extra.metadata = __spreadValues(__spreadValues({}, invocationParams), runTree.extra.metadata);
4123
+ }
4124
+ return runTree;
4125
+ };
4126
+ var getSerializablePromise = (arg) => {
4127
+ const proxyState = { current: void 0 };
4128
+ const promiseProxy = new Proxy(arg, {
4129
+ get(target, prop, receiver) {
4130
+ if (prop === "then") {
4131
+ const boundThen = arg[prop].bind(arg);
4132
+ return (resolve, reject = (x) => {
4133
+ throw x;
4134
+ }) => {
4135
+ return boundThen((value) => {
4136
+ proxyState.current = ["resolve", value];
4137
+ return resolve(value);
4138
+ }, (error) => {
4139
+ proxyState.current = ["reject", error];
4140
+ return reject(error);
4141
+ });
4142
+ };
4143
+ }
4144
+ if (prop === "catch") {
4145
+ const boundCatch = arg[prop].bind(arg);
4146
+ return (reject) => {
4147
+ return boundCatch((error) => {
4148
+ proxyState.current = ["reject", error];
4149
+ return reject(error);
4150
+ });
4151
+ };
4152
+ }
4153
+ if (prop === "toJSON") {
4154
+ return () => {
4155
+ var _a;
4156
+ if (!proxyState.current)
4157
+ return void 0;
4158
+ const [type, value] = (_a = proxyState.current) != null ? _a : [];
4159
+ if (type === "resolve")
4160
+ return value;
4161
+ return { error: value };
4162
+ };
4163
+ }
4164
+ return Reflect.get(target, prop, receiver);
4165
+ }
4166
+ });
4167
+ return promiseProxy;
4168
+ };
4169
+ var convertSerializableArg = (arg) => {
4170
+ if (isReadableStream(arg)) {
4171
+ const proxyState = [];
4172
+ const transform = new TransformStream({
4173
+ start: () => void 0,
4174
+ transform: (chunk, controller) => {
4175
+ proxyState.push(chunk);
4176
+ controller.enqueue(chunk);
4177
+ },
4178
+ flush: () => void 0
4179
+ });
4180
+ const pipeThrough = arg.pipeThrough(transform);
4181
+ Object.assign(pipeThrough, { toJSON: () => proxyState });
4182
+ return pipeThrough;
4183
+ }
4184
+ if (isAsyncIterable(arg)) {
4185
+ const proxyState = { current: [] };
4186
+ return new Proxy(arg, {
4187
+ get(target, prop, receiver) {
4188
+ if (prop === Symbol.asyncIterator) {
4189
+ return () => {
4190
+ const boundIterator = arg[Symbol.asyncIterator].bind(arg);
4191
+ const iterator = boundIterator();
4192
+ return new Proxy(iterator, {
4193
+ get(target2, prop2, receiver2) {
4194
+ if (prop2 === "next" || prop2 === "return" || prop2 === "throw") {
4195
+ const bound = iterator.next.bind(iterator);
4196
+ return (...args) => {
4197
+ const wrapped = getSerializablePromise(bound(...args));
4198
+ proxyState.current.push(wrapped);
4199
+ return wrapped;
4200
+ };
4201
+ }
4202
+ if (prop2 === "return" || prop2 === "throw") {
4203
+ return iterator.next.bind(iterator);
4204
+ }
4205
+ return Reflect.get(target2, prop2, receiver2);
4206
+ }
4207
+ });
4208
+ };
4209
+ }
4210
+ if (prop === "toJSON") {
4211
+ return () => {
4212
+ const onlyNexts = proxyState.current;
4213
+ const serialized = onlyNexts.map((next) => next.toJSON());
4214
+ const chunks = serialized.reduce((memo, next) => {
4215
+ if (next == null ? void 0 : next.value)
4216
+ memo.push(next.value);
4217
+ return memo;
4218
+ }, []);
4219
+ return chunks;
4220
+ };
4221
+ }
4222
+ return Reflect.get(target, prop, receiver);
4223
+ }
4224
+ });
4225
+ }
4226
+ if (!Array.isArray(arg) && isIteratorLike(arg)) {
4227
+ const proxyState = [];
4228
+ return new Proxy(arg, {
4229
+ get(target, prop, receiver) {
4230
+ var _a;
4231
+ if (prop === "next" || prop === "return" || prop === "throw") {
4232
+ const bound = (_a = arg[prop]) == null ? void 0 : _a.bind(arg);
4233
+ return (...args) => {
4234
+ const next = bound == null ? void 0 : bound(...args);
4235
+ if (next != null)
4236
+ proxyState.push(next);
4237
+ return next;
4238
+ };
4239
+ }
4240
+ if (prop === "toJSON") {
4241
+ return () => {
4242
+ const chunks = proxyState.reduce((memo, next) => {
4243
+ if (next.value)
4244
+ memo.push(next.value);
4245
+ return memo;
4246
+ }, []);
4247
+ return chunks;
4248
+ };
4249
+ }
4250
+ return Reflect.get(target, prop, receiver);
4251
+ }
4252
+ });
4253
+ }
4254
+ if (isThenable(arg)) {
4255
+ return getSerializablePromise(arg);
4256
+ }
4257
+ return arg;
4258
+ };
4259
+ function traceable(wrappedFunc, config) {
4260
+ const _a = config != null ? config : {}, { aggregator, argsConfigPath } = _a, runTreeConfig = __objRest(_a, ["aggregator", "argsConfigPath"]);
4261
+ const traceableFunc = (...args) => {
4262
+ var _b, _c, _d;
4263
+ let ensuredConfig;
4264
+ try {
4265
+ let runtimeConfig;
4266
+ if (argsConfigPath) {
4267
+ const [index, path] = argsConfigPath;
4268
+ if (index === args.length - 1 && !path) {
4269
+ runtimeConfig = args.pop();
4270
+ } else if (index <= args.length && typeof args[index] === "object" && args[index] !== null) {
4271
+ if (path) {
4272
+ const _a2 = args[index], { [path]: extracted } = _a2, rest = __objRest(_a2, [__restKey(path)]);
4273
+ runtimeConfig = extracted;
4274
+ args[index] = rest;
4275
+ } else {
4276
+ runtimeConfig = args[index];
4277
+ args.splice(index, 1);
4278
+ }
4279
+ }
4280
+ }
4281
+ ensuredConfig = __spreadProps(__spreadValues(__spreadValues({
4282
+ name: wrappedFunc.name || "<lambda>"
4283
+ }, runTreeConfig), runtimeConfig), {
4284
+ tags: [
4285
+ .../* @__PURE__ */ new Set([
4286
+ ...(_b = runTreeConfig == null ? void 0 : runTreeConfig.tags) != null ? _b : [],
4287
+ ...(_c = runtimeConfig == null ? void 0 : runtimeConfig.tags) != null ? _c : []
4288
+ ])
4289
+ ],
4290
+ metadata: __spreadValues(__spreadValues({}, runTreeConfig == null ? void 0 : runTreeConfig.metadata), runtimeConfig == null ? void 0 : runtimeConfig.metadata)
4291
+ });
4292
+ } catch (err) {
4293
+ console.warn(`Failed to extract runtime config from args for ${(_d = runTreeConfig == null ? void 0 : runTreeConfig.name) != null ? _d : wrappedFunc.name}`, err);
4294
+ ensuredConfig = __spreadValues({
4295
+ name: wrappedFunc.name || "<lambda>"
4296
+ }, runTreeConfig);
4297
+ }
4298
+ const asyncLocalStorage = AsyncLocalStorageProviderSingleton.getInstance();
4299
+ const processedArgs = args;
4300
+ for (let i = 0; i < processedArgs.length; i++) {
4301
+ processedArgs[i] = convertSerializableArg(processedArgs[i]);
4302
+ }
4303
+ const [currentRunTree, rawInputs] = (() => {
4304
+ const [firstArg, ...restArgs] = processedArgs;
4305
+ if (isRunnableConfigLike(firstArg)) {
4306
+ return [
4307
+ getTracingRunTree(RunTree.fromRunnableConfig(firstArg, ensuredConfig), restArgs, config == null ? void 0 : config.getInvocationParams),
4308
+ restArgs
4309
+ ];
4310
+ }
4311
+ if (isRunTree(firstArg) && "callbackManager" in firstArg && firstArg.callbackManager != null) {
4312
+ return [firstArg, restArgs];
4313
+ }
4314
+ if (firstArg === ROOT || isRunTree(firstArg)) {
4315
+ const currentRunTree3 = getTracingRunTree(firstArg === ROOT ? new RunTree(ensuredConfig) : firstArg.createChild(ensuredConfig), restArgs, config == null ? void 0 : config.getInvocationParams);
4316
+ return [currentRunTree3, [currentRunTree3, ...restArgs]];
4317
+ }
4318
+ const prevRunFromStore = asyncLocalStorage.getStore();
4319
+ if (prevRunFromStore) {
4320
+ return [
4321
+ getTracingRunTree(prevRunFromStore.createChild(ensuredConfig), processedArgs, config == null ? void 0 : config.getInvocationParams),
4322
+ processedArgs
4323
+ ];
4324
+ }
4325
+ const currentRunTree2 = getTracingRunTree(new RunTree(ensuredConfig), processedArgs, config == null ? void 0 : config.getInvocationParams);
4326
+ return [currentRunTree2, processedArgs];
4327
+ })();
4328
+ return asyncLocalStorage.run(currentRunTree, () => {
4329
+ const postRunPromise = currentRunTree == null ? void 0 : currentRunTree.postRun();
4330
+ async function handleChunks(chunks) {
4331
+ if (aggregator !== void 0) {
4332
+ try {
4333
+ return await aggregator(chunks);
4334
+ } catch (e) {
4335
+ console.error(`[ERROR]: LangSmith aggregation failed: `, e);
4336
+ }
4337
+ }
4338
+ return chunks;
4339
+ }
4340
+ function wrapAsyncGeneratorForTracing(iterable, snapshot) {
4341
+ return __asyncGenerator(this, null, function* () {
4342
+ let finished = false;
4343
+ const chunks = [];
4344
+ try {
4345
+ const iterator = iterable[Symbol.asyncIterator]();
4346
+ while (true) {
4347
+ const { value, done } = yield new __await(snapshot ? snapshot(() => iterator.next()) : iterator.next());
4348
+ if (done) {
4349
+ finished = true;
4350
+ break;
4351
+ }
4352
+ chunks.push(value);
4353
+ yield value;
4354
+ }
4355
+ } catch (e) {
4356
+ yield new __await(currentRunTree == null ? void 0 : currentRunTree.end(void 0, String(e)));
4357
+ throw e;
4358
+ } finally {
4359
+ if (!finished)
4360
+ yield new __await(currentRunTree == null ? void 0 : currentRunTree.end(void 0, "Cancelled"));
4361
+ yield new __await(currentRunTree == null ? void 0 : currentRunTree.end(handleRunOutputs(yield new __await(handleChunks(chunks)))));
4362
+ yield new __await(handleEnd());
4363
+ }
4364
+ });
4365
+ }
4366
+ async function handleEnd() {
4367
+ const onEnd = config == null ? void 0 : config.on_end;
4368
+ if (onEnd) {
4369
+ if (!currentRunTree) {
4370
+ console.warn("Can not call 'on_end' if currentRunTree is undefined");
4371
+ } else {
4372
+ onEnd(currentRunTree);
4373
+ }
4374
+ }
4375
+ await postRunPromise;
4376
+ await (currentRunTree == null ? void 0 : currentRunTree.patchRun());
4377
+ }
4378
+ function gatherAll(iterator) {
4379
+ const chunks = [];
4380
+ while (true) {
4381
+ const next = iterator.next();
4382
+ chunks.push(next);
4383
+ if (next.done)
4384
+ break;
4385
+ }
4386
+ return chunks;
4387
+ }
4388
+ let returnValue;
4389
+ try {
4390
+ returnValue = wrappedFunc(...rawInputs);
4391
+ } catch (err) {
4392
+ returnValue = Promise.reject(err);
4393
+ }
4394
+ if (isAsyncIterable(returnValue)) {
4395
+ const snapshot = AsyncLocalStorage.snapshot();
4396
+ return wrapAsyncGeneratorForTracing(returnValue, snapshot);
4397
+ }
4398
+ const tracedPromise = new Promise((resolve, reject) => {
4399
+ Promise.resolve(returnValue).then(async (rawOutput) => {
4400
+ if (isAsyncIterable(rawOutput)) {
4401
+ const snapshot = AsyncLocalStorage.snapshot();
4402
+ return resolve(wrapAsyncGeneratorForTracing(rawOutput, snapshot));
4403
+ }
4404
+ if (isGenerator(wrappedFunc) && isIteratorLike(rawOutput)) {
4405
+ const chunks = gatherAll(rawOutput);
4406
+ await (currentRunTree == null ? void 0 : currentRunTree.end(handleRunOutputs(await handleChunks(chunks.reduce((memo, { value, done }) => {
4407
+ if (!done || typeof value !== "undefined") {
4408
+ memo.push(value);
4409
+ }
4410
+ return memo;
4411
+ }, [])))));
4412
+ await handleEnd();
4413
+ return function* () {
4414
+ for (const ret of chunks) {
4415
+ if (ret.done)
4416
+ return ret.value;
4417
+ yield ret.value;
4418
+ }
4419
+ }();
4420
+ }
4421
+ try {
4422
+ await (currentRunTree == null ? void 0 : currentRunTree.end(handleRunOutputs(rawOutput)));
4423
+ await handleEnd();
4424
+ } finally {
4425
+ return rawOutput;
4426
+ }
4427
+ }, async (error) => {
4428
+ await (currentRunTree == null ? void 0 : currentRunTree.end(void 0, String(error)));
4429
+ await handleEnd();
4430
+ throw error;
4431
+ }).then(resolve, reject);
4432
+ });
4433
+ if (typeof returnValue !== "object" || returnValue === null) {
4434
+ return tracedPromise;
4435
+ }
4436
+ return new Proxy(returnValue, {
4437
+ get(target, prop, receiver) {
4438
+ if (isPromiseMethod(prop)) {
4439
+ return tracedPromise[prop].bind(tracedPromise);
4440
+ }
4441
+ return Reflect.get(target, prop, receiver);
4442
+ }
4443
+ });
4444
+ });
4445
+ };
4446
+ Object.defineProperty(traceableFunc, "langsmith:traceable", {
4447
+ value: runTreeConfig
4448
+ });
4449
+ return traceableFunc;
4450
+ }
4451
+
4452
+ // ../../node_modules/.pnpm/langsmith@0.1.36_openai@4.47.1/node_modules/langsmith/dist/wrappers/openai.js
4453
+ function _combineChatCompletionChoices(choices) {
4454
+ var _a, _b;
4455
+ const reversedChoices = choices.slice().reverse();
4456
+ const message = {
4457
+ role: "assistant",
4458
+ content: ""
4459
+ };
4460
+ for (const c of reversedChoices) {
4461
+ if (c.delta.role) {
4462
+ message["role"] = c.delta.role;
4463
+ break;
4464
+ }
4465
+ }
4466
+ const toolCalls = {};
4467
+ for (const c of choices) {
4468
+ if (c.delta.content) {
4469
+ message.content = message.content.concat(c.delta.content);
4470
+ }
4471
+ if (c.delta.function_call) {
4472
+ if (!message.function_call) {
4473
+ message.function_call = { name: "", arguments: "" };
4474
+ }
4475
+ if (c.delta.function_call.name) {
4476
+ message.function_call.name += c.delta.function_call.name;
4477
+ }
4478
+ if (c.delta.function_call.arguments) {
4479
+ message.function_call.arguments += c.delta.function_call.arguments;
4480
+ }
4481
+ }
4482
+ if (c.delta.tool_calls) {
4483
+ for (const tool_call of c.delta.tool_calls) {
4484
+ if (!toolCalls[c.index]) {
4485
+ toolCalls[c.index] = [];
4486
+ }
4487
+ toolCalls[c.index].push(tool_call);
4488
+ }
4489
+ }
4490
+ }
4491
+ if (Object.keys(toolCalls).length > 0) {
4492
+ message.tool_calls = [...Array(Object.keys(toolCalls).length)];
4493
+ for (const [index, toolCallChunks] of Object.entries(toolCalls)) {
4494
+ const idx = parseInt(index);
4495
+ message.tool_calls[idx] = {
4496
+ index: idx,
4497
+ id: ((_a = toolCallChunks.find((c) => c.id)) == null ? void 0 : _a.id) || null,
4498
+ type: ((_b = toolCallChunks.find((c) => c.type)) == null ? void 0 : _b.type) || null
4499
+ };
4500
+ for (const chunk of toolCallChunks) {
4501
+ if (chunk.function) {
4502
+ if (!message.tool_calls[idx].function) {
4503
+ message.tool_calls[idx].function = {
4504
+ name: "",
4505
+ arguments: ""
4506
+ };
4507
+ }
4508
+ if (chunk.function.name) {
4509
+ message.tool_calls[idx].function.name += chunk.function.name;
4510
+ }
4511
+ if (chunk.function.arguments) {
4512
+ message.tool_calls[idx].function.arguments += chunk.function.arguments;
4513
+ }
4514
+ }
4515
+ }
4516
+ }
4517
+ }
4518
+ return {
4519
+ index: choices[0].index,
4520
+ finish_reason: reversedChoices.find((c) => c.finish_reason) || null,
4521
+ message
4522
+ };
4523
+ }
4524
+ var chatAggregator = (chunks) => {
4525
+ if (!chunks || chunks.length === 0) {
4526
+ return { choices: [{ message: { role: "assistant", content: "" } }] };
4527
+ }
4528
+ const choicesByIndex = {};
4529
+ for (const chunk of chunks) {
4530
+ for (const choice of chunk.choices) {
4531
+ if (choicesByIndex[choice.index] === void 0) {
4532
+ choicesByIndex[choice.index] = [];
4533
+ }
4534
+ choicesByIndex[choice.index].push(choice);
4535
+ }
4536
+ }
4537
+ const aggregatedOutput = chunks[chunks.length - 1];
4538
+ aggregatedOutput.choices = Object.values(choicesByIndex).map((choices) => _combineChatCompletionChoices(choices));
4539
+ return aggregatedOutput;
4540
+ };
4541
+ var textAggregator = (allChunks) => {
4542
+ if (allChunks.length === 0) {
4543
+ return { choices: [{ text: "" }] };
4544
+ }
4545
+ const allContent = [];
4546
+ for (const chunk of allChunks) {
4547
+ const content2 = chunk.choices[0].text;
4548
+ if (content2 != null) {
4549
+ allContent.push(content2);
4550
+ }
4551
+ }
4552
+ const content = allContent.join("");
4553
+ const aggregatedOutput = allChunks[allChunks.length - 1];
4554
+ aggregatedOutput.choices = [
4555
+ __spreadProps(__spreadValues({}, aggregatedOutput.choices[0]), { text: content })
4556
+ ];
4557
+ return aggregatedOutput;
4558
+ };
4559
+ var wrapOpenAI = (openai, options) => {
4560
+ if (isTraceableFunction(openai.chat.completions.create) || isTraceableFunction(openai.completions.create)) {
4561
+ throw new Error("This instance of OpenAI client has been already wrapped once.");
4562
+ }
4563
+ openai.chat.completions.create = traceable(openai.chat.completions.create.bind(openai.chat.completions), __spreadValues({
4564
+ name: "ChatOpenAI",
4565
+ run_type: "llm",
4566
+ aggregator: chatAggregator,
4567
+ argsConfigPath: [1, "langsmithExtra"],
4568
+ getInvocationParams: (payload) => {
4569
+ var _a, _b, _c;
4570
+ if (typeof payload !== "object" || payload == null)
4571
+ return void 0;
4572
+ const params = payload;
4573
+ const ls_stop = (_a = typeof params.stop === "string" ? [params.stop] : params.stop) != null ? _a : void 0;
4574
+ return {
4575
+ ls_provider: "openai",
4576
+ ls_model_type: "chat",
4577
+ ls_model_name: params.model,
4578
+ ls_max_tokens: (_b = params.max_tokens) != null ? _b : void 0,
4579
+ ls_temperature: (_c = params.temperature) != null ? _c : void 0,
4580
+ ls_stop
4581
+ };
4582
+ }
4583
+ }, options));
4584
+ openai.completions.create = traceable(openai.completions.create.bind(openai.completions), __spreadValues({
4585
+ name: "OpenAI",
4586
+ run_type: "llm",
4587
+ aggregator: textAggregator,
4588
+ argsConfigPath: [1, "langsmithExtra"],
4589
+ getInvocationParams: (payload) => {
4590
+ var _a, _b, _c;
4591
+ if (typeof payload !== "object" || payload == null)
4592
+ return void 0;
4593
+ const params = payload;
4594
+ const ls_stop = (_a = typeof params.stop === "string" ? [params.stop] : params.stop) != null ? _a : void 0;
4595
+ return {
4596
+ ls_provider: "openai",
4597
+ ls_model_type: "text",
4598
+ ls_model_name: params.model,
4599
+ ls_max_tokens: (_b = params.max_tokens) != null ? _b : void 0,
4600
+ ls_temperature: (_c = params.temperature) != null ? _c : void 0,
4601
+ ls_stop
4602
+ };
4603
+ }
4604
+ }, options));
4605
+ return openai;
4606
+ };
422
4607
 
423
4608
  // src/types.ts
424
4609
  var BaseElement = class {
@@ -437,19 +4622,19 @@ var envModelKey = "MIDSCENE_MODEL_NAME";
437
4622
  var envSmithDebug = "MIDSCENE_LANGSMITH_DEBUG";
438
4623
  var extraConfig = {};
439
4624
  if (typeof process.env[envConfigKey] === "string") {
440
- console.log("will use env config for openai");
4625
+ console.log("config for openai loaded");
441
4626
  extraConfig = JSON.parse(process.env[envConfigKey]);
442
4627
  }
443
4628
  var model = "gpt-4o";
444
4629
  if (typeof process.env[envModelKey] === "string") {
445
- console.log(`will use model: ${process.env[envModelKey]}`);
4630
+ console.log(`model: ${process.env[envModelKey]}`);
446
4631
  model = process.env[envModelKey];
447
4632
  }
448
4633
  async function createOpenAI() {
449
4634
  const openai = new OpenAI(extraConfig);
450
4635
  if (process.env[envSmithDebug]) {
451
- console.log("DEBUGGING MODE: using langsmith wrapper");
452
- const openai2 = wrapper.wrapOpenAI(new OpenAI());
4636
+ console.log("DEBUGGING MODE: langsmith wrapper enabled");
4637
+ const openai2 = wrapOpenAI(new OpenAI());
453
4638
  return openai2;
454
4639
  }
455
4640
  return openai;