@midscene/core 0.1.0 → 0.1.1

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