notte-sdk 0.0.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.
package/dist/index.js ADDED
@@ -0,0 +1,2866 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ Agent: () => Agent,
34
+ NotteClient: () => NotteClient,
35
+ NotteFunction: () => NotteFunction,
36
+ NottePersona: () => NottePersona,
37
+ NotteProxyAuthError: () => NotteProxyAuthError,
38
+ NotteVault: () => NotteVault,
39
+ Session: () => Session,
40
+ agentStart: () => agentStart,
41
+ agentStatus: () => agentStatus,
42
+ agentStop: () => agentStop,
43
+ anythingStart: () => anythingStart,
44
+ client: () => client,
45
+ createClient: () => createClient2,
46
+ default: () => NotteClient,
47
+ fileDownload: () => fileDownload,
48
+ fileListDownloads: () => fileListDownloads,
49
+ fileListUploads: () => fileListUploads,
50
+ fileUpload: () => fileUpload,
51
+ fileUploadDownloadedFile: () => fileUploadDownloadedFile,
52
+ functionCreate: () => functionCreate,
53
+ functionDelete: () => functionDelete,
54
+ functionDownloadUrl: () => functionDownloadUrl,
55
+ functionFork: () => functionFork,
56
+ functionRunGetMetadata: () => functionRunGetMetadata,
57
+ functionRunStart: () => functionRunStart,
58
+ functionRunStop: () => functionRunStop,
59
+ functionRunUpdateMetadata: () => functionRunUpdateMetadata,
60
+ functionScheduleDelete: () => functionScheduleDelete,
61
+ functionScheduleSet: () => functionScheduleSet,
62
+ functionUpdate: () => functionUpdate,
63
+ getScript: () => getScript,
64
+ getSessionScript: () => getSessionScript,
65
+ getUsage: () => getUsage,
66
+ getUsageLogs: () => getUsageLogs,
67
+ healthCheck: () => healthCheck,
68
+ improvePrompt: () => improvePrompt,
69
+ listAgents: () => listAgents,
70
+ listFunctionRunsByFunctionId: () => listFunctionRunsByFunctionId,
71
+ listFunctions: () => listFunctions,
72
+ listPersonas: () => listPersonas,
73
+ listSessions: () => listSessions,
74
+ listVaults: () => listVaults,
75
+ nudgePrompt: () => nudgePrompt,
76
+ pageExecute: () => pageExecute,
77
+ pageObserve: () => pageObserve,
78
+ pageScrape: () => pageScrape,
79
+ pageScreenshot: () => pageScreenshot,
80
+ personaCreate: () => personaCreate,
81
+ personaDelete: () => personaDelete,
82
+ personaEmailsList: () => personaEmailsList,
83
+ personaGet: () => personaGet,
84
+ personaSmsList: () => personaSmsList,
85
+ profileCreate: () => profileCreate,
86
+ profileDelete: () => profileDelete,
87
+ profileGet: () => profileGet,
88
+ profileList: () => profileList,
89
+ scrapeFromHtml: () => scrapeFromHtml,
90
+ scrapeWebpage: () => scrapeWebpage,
91
+ sessionCookiesGet: () => sessionCookiesGet,
92
+ sessionCookiesSet: () => sessionCookiesSet,
93
+ sessionDebugInfo: () => sessionDebugInfo,
94
+ sessionNetworkLogs: () => sessionNetworkLogs,
95
+ sessionOffset: () => sessionOffset,
96
+ sessionReplay: () => sessionReplay,
97
+ sessionStart: () => sessionStart,
98
+ sessionStatus: () => sessionStatus,
99
+ sessionStop: () => sessionStop,
100
+ vaultCreate: () => vaultCreate,
101
+ vaultCredentialsAdd: () => vaultCredentialsAdd,
102
+ vaultCredentialsDelete: () => vaultCredentialsDelete,
103
+ vaultCredentialsGet: () => vaultCredentialsGet,
104
+ vaultCredentialsList: () => vaultCredentialsList,
105
+ vaultCreditCardDelete: () => vaultCreditCardDelete,
106
+ vaultCreditCardGet: () => vaultCreditCardGet,
107
+ vaultCreditCardSet: () => vaultCreditCardSet,
108
+ vaultDelete: () => vaultDelete,
109
+ vaultUpdate: () => vaultUpdate
110
+ });
111
+ module.exports = __toCommonJS(index_exports);
112
+
113
+ // src/lib/client/core/bodySerializer.gen.ts
114
+ var serializeFormDataPair = (data, key, value) => {
115
+ if (typeof value === "string" || value instanceof Blob) {
116
+ data.append(key, value);
117
+ } else if (value instanceof Date) {
118
+ data.append(key, value.toISOString());
119
+ } else {
120
+ data.append(key, JSON.stringify(value));
121
+ }
122
+ };
123
+ var formDataBodySerializer = {
124
+ bodySerializer: (body) => {
125
+ const data = new FormData();
126
+ Object.entries(body).forEach(([key, value]) => {
127
+ if (value === void 0 || value === null) {
128
+ return;
129
+ }
130
+ if (Array.isArray(value)) {
131
+ value.forEach((v) => serializeFormDataPair(data, key, v));
132
+ } else {
133
+ serializeFormDataPair(data, key, value);
134
+ }
135
+ });
136
+ return data;
137
+ }
138
+ };
139
+ var jsonBodySerializer = {
140
+ bodySerializer: (body) => JSON.stringify(body, (_key, value) => typeof value === "bigint" ? value.toString() : value)
141
+ };
142
+
143
+ // src/lib/client/core/params.gen.ts
144
+ var extraPrefixesMap = {
145
+ $body_: "body",
146
+ $headers_: "headers",
147
+ $path_: "path",
148
+ $query_: "query"
149
+ };
150
+ var extraPrefixes = Object.entries(extraPrefixesMap);
151
+
152
+ // src/lib/client/core/serverSentEvents.gen.ts
153
+ var createSseClient = ({
154
+ onRequest,
155
+ onSseError,
156
+ onSseEvent,
157
+ responseTransformer,
158
+ responseValidator,
159
+ sseDefaultRetryDelay,
160
+ sseMaxRetryAttempts,
161
+ sseMaxRetryDelay,
162
+ sseSleepFn,
163
+ url,
164
+ ...options
165
+ }) => {
166
+ let lastEventId;
167
+ const sleep = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
168
+ const createStream = async function* () {
169
+ let retryDelay = sseDefaultRetryDelay ?? 3e3;
170
+ let attempt = 0;
171
+ const signal = options.signal ?? new AbortController().signal;
172
+ while (true) {
173
+ if (signal.aborted) break;
174
+ attempt++;
175
+ const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers);
176
+ if (lastEventId !== void 0) {
177
+ headers.set("Last-Event-ID", lastEventId);
178
+ }
179
+ try {
180
+ const requestInit = {
181
+ redirect: "follow",
182
+ ...options,
183
+ body: options.serializedBody,
184
+ headers,
185
+ signal
186
+ };
187
+ let request = new Request(url, requestInit);
188
+ if (onRequest) {
189
+ request = await onRequest(url, requestInit);
190
+ }
191
+ const _fetch = options.fetch ?? globalThis.fetch;
192
+ const response = await _fetch(request);
193
+ if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`);
194
+ if (!response.body) throw new Error("No body in SSE response");
195
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
196
+ let buffer = "";
197
+ const abortHandler = () => {
198
+ try {
199
+ reader.cancel();
200
+ } catch {
201
+ }
202
+ };
203
+ signal.addEventListener("abort", abortHandler);
204
+ try {
205
+ while (true) {
206
+ const { done, value } = await reader.read();
207
+ if (done) break;
208
+ buffer += value;
209
+ buffer = buffer.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
210
+ const chunks = buffer.split("\n\n");
211
+ buffer = chunks.pop() ?? "";
212
+ for (const chunk of chunks) {
213
+ const lines = chunk.split("\n");
214
+ const dataLines = [];
215
+ let eventName;
216
+ for (const line of lines) {
217
+ if (line.startsWith("data:")) {
218
+ dataLines.push(line.replace(/^data:\s*/, ""));
219
+ } else if (line.startsWith("event:")) {
220
+ eventName = line.replace(/^event:\s*/, "");
221
+ } else if (line.startsWith("id:")) {
222
+ lastEventId = line.replace(/^id:\s*/, "");
223
+ } else if (line.startsWith("retry:")) {
224
+ const parsed = Number.parseInt(line.replace(/^retry:\s*/, ""), 10);
225
+ if (!Number.isNaN(parsed)) {
226
+ retryDelay = parsed;
227
+ }
228
+ }
229
+ }
230
+ let data;
231
+ let parsedJson = false;
232
+ if (dataLines.length) {
233
+ const rawData = dataLines.join("\n");
234
+ try {
235
+ data = JSON.parse(rawData);
236
+ parsedJson = true;
237
+ } catch {
238
+ data = rawData;
239
+ }
240
+ }
241
+ if (parsedJson) {
242
+ if (responseValidator) {
243
+ await responseValidator(data);
244
+ }
245
+ if (responseTransformer) {
246
+ data = await responseTransformer(data);
247
+ }
248
+ }
249
+ onSseEvent?.({
250
+ data,
251
+ event: eventName,
252
+ id: lastEventId,
253
+ retry: retryDelay
254
+ });
255
+ if (dataLines.length) {
256
+ yield data;
257
+ }
258
+ }
259
+ }
260
+ } finally {
261
+ signal.removeEventListener("abort", abortHandler);
262
+ reader.releaseLock();
263
+ }
264
+ break;
265
+ } catch (error) {
266
+ onSseError?.(error);
267
+ if (sseMaxRetryAttempts !== void 0 && attempt >= sseMaxRetryAttempts) {
268
+ break;
269
+ }
270
+ const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 3e4);
271
+ await sleep(backoff);
272
+ }
273
+ }
274
+ };
275
+ const stream = createStream();
276
+ return { stream };
277
+ };
278
+
279
+ // src/lib/client/core/pathSerializer.gen.ts
280
+ var separatorArrayExplode = (style) => {
281
+ switch (style) {
282
+ case "label":
283
+ return ".";
284
+ case "matrix":
285
+ return ";";
286
+ case "simple":
287
+ return ",";
288
+ default:
289
+ return "&";
290
+ }
291
+ };
292
+ var separatorArrayNoExplode = (style) => {
293
+ switch (style) {
294
+ case "form":
295
+ return ",";
296
+ case "pipeDelimited":
297
+ return "|";
298
+ case "spaceDelimited":
299
+ return "%20";
300
+ default:
301
+ return ",";
302
+ }
303
+ };
304
+ var separatorObjectExplode = (style) => {
305
+ switch (style) {
306
+ case "label":
307
+ return ".";
308
+ case "matrix":
309
+ return ";";
310
+ case "simple":
311
+ return ",";
312
+ default:
313
+ return "&";
314
+ }
315
+ };
316
+ var serializeArrayParam = ({
317
+ allowReserved,
318
+ explode,
319
+ name,
320
+ style,
321
+ value
322
+ }) => {
323
+ if (!explode) {
324
+ const joinedValues2 = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
325
+ switch (style) {
326
+ case "label":
327
+ return `.${joinedValues2}`;
328
+ case "matrix":
329
+ return `;${name}=${joinedValues2}`;
330
+ case "simple":
331
+ return joinedValues2;
332
+ default:
333
+ return `${name}=${joinedValues2}`;
334
+ }
335
+ }
336
+ const separator = separatorArrayExplode(style);
337
+ const joinedValues = value.map((v) => {
338
+ if (style === "label" || style === "simple") {
339
+ return allowReserved ? v : encodeURIComponent(v);
340
+ }
341
+ return serializePrimitiveParam({
342
+ allowReserved,
343
+ name,
344
+ value: v
345
+ });
346
+ }).join(separator);
347
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
348
+ };
349
+ var serializePrimitiveParam = ({
350
+ allowReserved,
351
+ name,
352
+ value
353
+ }) => {
354
+ if (value === void 0 || value === null) {
355
+ return "";
356
+ }
357
+ if (typeof value === "object") {
358
+ throw new Error(
359
+ "Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these."
360
+ );
361
+ }
362
+ return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
363
+ };
364
+ var serializeObjectParam = ({
365
+ allowReserved,
366
+ explode,
367
+ name,
368
+ style,
369
+ value,
370
+ valueOnly
371
+ }) => {
372
+ if (value instanceof Date) {
373
+ return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
374
+ }
375
+ if (style !== "deepObject" && !explode) {
376
+ let values = [];
377
+ Object.entries(value).forEach(([key, v]) => {
378
+ values = [...values, key, allowReserved ? v : encodeURIComponent(v)];
379
+ });
380
+ const joinedValues2 = values.join(",");
381
+ switch (style) {
382
+ case "form":
383
+ return `${name}=${joinedValues2}`;
384
+ case "label":
385
+ return `.${joinedValues2}`;
386
+ case "matrix":
387
+ return `;${name}=${joinedValues2}`;
388
+ default:
389
+ return joinedValues2;
390
+ }
391
+ }
392
+ const separator = separatorObjectExplode(style);
393
+ const joinedValues = Object.entries(value).map(
394
+ ([key, v]) => serializePrimitiveParam({
395
+ allowReserved,
396
+ name: style === "deepObject" ? `${name}[${key}]` : key,
397
+ value: v
398
+ })
399
+ ).join(separator);
400
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
401
+ };
402
+
403
+ // src/lib/client/core/utils.gen.ts
404
+ var PATH_PARAM_RE = /\{[^{}]+\}/g;
405
+ var defaultPathSerializer = ({ path, url: _url }) => {
406
+ let url = _url;
407
+ const matches = _url.match(PATH_PARAM_RE);
408
+ if (matches) {
409
+ for (const match of matches) {
410
+ let explode = false;
411
+ let name = match.substring(1, match.length - 1);
412
+ let style = "simple";
413
+ if (name.endsWith("*")) {
414
+ explode = true;
415
+ name = name.substring(0, name.length - 1);
416
+ }
417
+ if (name.startsWith(".")) {
418
+ name = name.substring(1);
419
+ style = "label";
420
+ } else if (name.startsWith(";")) {
421
+ name = name.substring(1);
422
+ style = "matrix";
423
+ }
424
+ const value = path[name];
425
+ if (value === void 0 || value === null) {
426
+ continue;
427
+ }
428
+ if (Array.isArray(value)) {
429
+ url = url.replace(match, serializeArrayParam({ explode, name, style, value }));
430
+ continue;
431
+ }
432
+ if (typeof value === "object") {
433
+ url = url.replace(
434
+ match,
435
+ serializeObjectParam({
436
+ explode,
437
+ name,
438
+ style,
439
+ value,
440
+ valueOnly: true
441
+ })
442
+ );
443
+ continue;
444
+ }
445
+ if (style === "matrix") {
446
+ url = url.replace(
447
+ match,
448
+ `;${serializePrimitiveParam({
449
+ name,
450
+ value
451
+ })}`
452
+ );
453
+ continue;
454
+ }
455
+ const replaceValue = encodeURIComponent(
456
+ style === "label" ? `.${value}` : value
457
+ );
458
+ url = url.replace(match, replaceValue);
459
+ }
460
+ }
461
+ return url;
462
+ };
463
+ var getUrl = ({
464
+ baseUrl,
465
+ path,
466
+ query,
467
+ querySerializer,
468
+ url: _url
469
+ }) => {
470
+ const pathUrl = _url.startsWith("/") ? _url : `/${_url}`;
471
+ let url = (baseUrl ?? "") + pathUrl;
472
+ if (path) {
473
+ url = defaultPathSerializer({ path, url });
474
+ }
475
+ let search = query ? querySerializer(query) : "";
476
+ if (search.startsWith("?")) {
477
+ search = search.substring(1);
478
+ }
479
+ if (search) {
480
+ url += `?${search}`;
481
+ }
482
+ return url;
483
+ };
484
+ function getValidRequestBody(options) {
485
+ const hasBody = options.body !== void 0;
486
+ const isSerializedBody = hasBody && options.bodySerializer;
487
+ if (isSerializedBody) {
488
+ if ("serializedBody" in options) {
489
+ const hasSerializedBody = options.serializedBody !== void 0 && options.serializedBody !== "";
490
+ return hasSerializedBody ? options.serializedBody : null;
491
+ }
492
+ return options.body !== "" ? options.body : null;
493
+ }
494
+ if (hasBody) {
495
+ return options.body;
496
+ }
497
+ return void 0;
498
+ }
499
+
500
+ // src/lib/client/core/auth.gen.ts
501
+ var getAuthToken = async (auth, callback) => {
502
+ const token = typeof callback === "function" ? await callback(auth) : callback;
503
+ if (!token) {
504
+ return;
505
+ }
506
+ if (auth.scheme === "bearer") {
507
+ return `Bearer ${token}`;
508
+ }
509
+ if (auth.scheme === "basic") {
510
+ return `Basic ${btoa(token)}`;
511
+ }
512
+ return token;
513
+ };
514
+
515
+ // src/lib/client/client/utils.gen.ts
516
+ var createQuerySerializer = ({
517
+ parameters = {},
518
+ ...args
519
+ } = {}) => {
520
+ const querySerializer = (queryParams) => {
521
+ const search = [];
522
+ if (queryParams && typeof queryParams === "object") {
523
+ for (const name in queryParams) {
524
+ const value = queryParams[name];
525
+ if (value === void 0 || value === null) {
526
+ continue;
527
+ }
528
+ const options = parameters[name] || args;
529
+ if (Array.isArray(value)) {
530
+ const serializedArray = serializeArrayParam({
531
+ allowReserved: options.allowReserved,
532
+ explode: true,
533
+ name,
534
+ style: "form",
535
+ value,
536
+ ...options.array
537
+ });
538
+ if (serializedArray) search.push(serializedArray);
539
+ } else if (typeof value === "object") {
540
+ const serializedObject = serializeObjectParam({
541
+ allowReserved: options.allowReserved,
542
+ explode: true,
543
+ name,
544
+ style: "deepObject",
545
+ value,
546
+ ...options.object
547
+ });
548
+ if (serializedObject) search.push(serializedObject);
549
+ } else {
550
+ const serializedPrimitive = serializePrimitiveParam({
551
+ allowReserved: options.allowReserved,
552
+ name,
553
+ value
554
+ });
555
+ if (serializedPrimitive) search.push(serializedPrimitive);
556
+ }
557
+ }
558
+ }
559
+ return search.join("&");
560
+ };
561
+ return querySerializer;
562
+ };
563
+ var getParseAs = (contentType) => {
564
+ if (!contentType) {
565
+ return "stream";
566
+ }
567
+ const cleanContent = contentType.split(";")[0]?.trim();
568
+ if (!cleanContent) {
569
+ return;
570
+ }
571
+ if (cleanContent.startsWith("application/json") || cleanContent.endsWith("+json")) {
572
+ return "json";
573
+ }
574
+ if (cleanContent === "multipart/form-data") {
575
+ return "formData";
576
+ }
577
+ if (["application/", "audio/", "image/", "video/"].some((type) => cleanContent.startsWith(type))) {
578
+ return "blob";
579
+ }
580
+ if (cleanContent.startsWith("text/")) {
581
+ return "text";
582
+ }
583
+ return;
584
+ };
585
+ var checkForExistence = (options, name) => {
586
+ if (!name) {
587
+ return false;
588
+ }
589
+ if (options.headers.has(name) || options.query?.[name] || options.headers.get("Cookie")?.includes(`${name}=`)) {
590
+ return true;
591
+ }
592
+ return false;
593
+ };
594
+ var setAuthParams = async ({
595
+ security,
596
+ ...options
597
+ }) => {
598
+ for (const auth of security) {
599
+ if (checkForExistence(options, auth.name)) {
600
+ continue;
601
+ }
602
+ const token = await getAuthToken(auth, options.auth);
603
+ if (!token) {
604
+ continue;
605
+ }
606
+ const name = auth.name ?? "Authorization";
607
+ switch (auth.in) {
608
+ case "query":
609
+ if (!options.query) {
610
+ options.query = {};
611
+ }
612
+ options.query[name] = token;
613
+ break;
614
+ case "cookie":
615
+ options.headers.append("Cookie", `${name}=${token}`);
616
+ break;
617
+ case "header":
618
+ default:
619
+ options.headers.set(name, token);
620
+ break;
621
+ }
622
+ }
623
+ };
624
+ var buildUrl = (options) => getUrl({
625
+ baseUrl: options.baseUrl,
626
+ path: options.path,
627
+ query: options.query,
628
+ querySerializer: typeof options.querySerializer === "function" ? options.querySerializer : createQuerySerializer(options.querySerializer),
629
+ url: options.url
630
+ });
631
+ var mergeConfigs = (a, b) => {
632
+ const config = { ...a, ...b };
633
+ if (config.baseUrl?.endsWith("/")) {
634
+ config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
635
+ }
636
+ config.headers = mergeHeaders(a.headers, b.headers);
637
+ return config;
638
+ };
639
+ var headersEntries = (headers) => {
640
+ const entries = [];
641
+ headers.forEach((value, key) => {
642
+ entries.push([key, value]);
643
+ });
644
+ return entries;
645
+ };
646
+ var mergeHeaders = (...headers) => {
647
+ const mergedHeaders = new Headers();
648
+ for (const header of headers) {
649
+ if (!header) {
650
+ continue;
651
+ }
652
+ const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);
653
+ for (const [key, value] of iterator) {
654
+ if (value === null) {
655
+ mergedHeaders.delete(key);
656
+ } else if (Array.isArray(value)) {
657
+ for (const v of value) {
658
+ mergedHeaders.append(key, v);
659
+ }
660
+ } else if (value !== void 0) {
661
+ mergedHeaders.set(
662
+ key,
663
+ typeof value === "object" ? JSON.stringify(value) : value
664
+ );
665
+ }
666
+ }
667
+ }
668
+ return mergedHeaders;
669
+ };
670
+ var Interceptors = class {
671
+ constructor() {
672
+ this.fns = [];
673
+ }
674
+ clear() {
675
+ this.fns = [];
676
+ }
677
+ eject(id) {
678
+ const index = this.getInterceptorIndex(id);
679
+ if (this.fns[index]) {
680
+ this.fns[index] = null;
681
+ }
682
+ }
683
+ exists(id) {
684
+ const index = this.getInterceptorIndex(id);
685
+ return Boolean(this.fns[index]);
686
+ }
687
+ getInterceptorIndex(id) {
688
+ if (typeof id === "number") {
689
+ return this.fns[id] ? id : -1;
690
+ }
691
+ return this.fns.indexOf(id);
692
+ }
693
+ update(id, fn) {
694
+ const index = this.getInterceptorIndex(id);
695
+ if (this.fns[index]) {
696
+ this.fns[index] = fn;
697
+ return id;
698
+ }
699
+ return false;
700
+ }
701
+ use(fn) {
702
+ this.fns.push(fn);
703
+ return this.fns.length - 1;
704
+ }
705
+ };
706
+ var createInterceptors = () => ({
707
+ error: new Interceptors(),
708
+ request: new Interceptors(),
709
+ response: new Interceptors()
710
+ });
711
+ var defaultQuerySerializer = createQuerySerializer({
712
+ allowReserved: false,
713
+ array: {
714
+ explode: true,
715
+ style: "form"
716
+ },
717
+ object: {
718
+ explode: true,
719
+ style: "deepObject"
720
+ }
721
+ });
722
+ var defaultHeaders = {
723
+ "Content-Type": "application/json"
724
+ };
725
+ var createConfig = (override = {}) => ({
726
+ ...jsonBodySerializer,
727
+ headers: defaultHeaders,
728
+ parseAs: "auto",
729
+ querySerializer: defaultQuerySerializer,
730
+ ...override
731
+ });
732
+
733
+ // src/lib/client/client/client.gen.ts
734
+ var createClient = (config = {}) => {
735
+ let _config = mergeConfigs(createConfig(), config);
736
+ const getConfig = () => ({ ..._config });
737
+ const setConfig = (config2) => {
738
+ _config = mergeConfigs(_config, config2);
739
+ return getConfig();
740
+ };
741
+ const interceptors = createInterceptors();
742
+ const beforeRequest = async (options) => {
743
+ const opts = {
744
+ ..._config,
745
+ ...options,
746
+ fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
747
+ headers: mergeHeaders(_config.headers, options.headers),
748
+ serializedBody: void 0
749
+ };
750
+ if (opts.security) {
751
+ await setAuthParams({
752
+ ...opts,
753
+ security: opts.security
754
+ });
755
+ }
756
+ if (opts.requestValidator) {
757
+ await opts.requestValidator(opts);
758
+ }
759
+ if (opts.body !== void 0 && opts.bodySerializer) {
760
+ opts.serializedBody = opts.bodySerializer(opts.body);
761
+ }
762
+ if (opts.body === void 0 || opts.serializedBody === "") {
763
+ opts.headers.delete("Content-Type");
764
+ }
765
+ const resolvedOpts = opts;
766
+ const url = buildUrl(resolvedOpts);
767
+ return { opts: resolvedOpts, url };
768
+ };
769
+ const request = async (options) => {
770
+ const { opts, url } = await beforeRequest(options);
771
+ const requestInit = {
772
+ redirect: "follow",
773
+ ...opts,
774
+ body: getValidRequestBody(opts)
775
+ };
776
+ let request2 = new Request(url, requestInit);
777
+ for (const fn of interceptors.request.fns) {
778
+ if (fn) {
779
+ request2 = await fn(request2, opts);
780
+ }
781
+ }
782
+ const _fetch = opts.fetch;
783
+ let response;
784
+ try {
785
+ response = await _fetch(request2);
786
+ } catch (error2) {
787
+ let finalError2 = error2;
788
+ for (const fn of interceptors.error.fns) {
789
+ if (fn) {
790
+ finalError2 = await fn(error2, void 0, request2, opts);
791
+ }
792
+ }
793
+ finalError2 = finalError2 || {};
794
+ if (opts.throwOnError) {
795
+ throw finalError2;
796
+ }
797
+ return opts.responseStyle === "data" ? void 0 : {
798
+ error: finalError2,
799
+ request: request2,
800
+ response: void 0
801
+ };
802
+ }
803
+ for (const fn of interceptors.response.fns) {
804
+ if (fn) {
805
+ response = await fn(response, request2, opts);
806
+ }
807
+ }
808
+ const result = {
809
+ request: request2,
810
+ response
811
+ };
812
+ if (response.ok) {
813
+ const parseAs = (opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json";
814
+ if (response.status === 204 || response.headers.get("Content-Length") === "0") {
815
+ let emptyData;
816
+ switch (parseAs) {
817
+ case "arrayBuffer":
818
+ case "blob":
819
+ case "text":
820
+ emptyData = await response[parseAs]();
821
+ break;
822
+ case "formData":
823
+ emptyData = new FormData();
824
+ break;
825
+ case "stream":
826
+ emptyData = response.body;
827
+ break;
828
+ case "json":
829
+ default:
830
+ emptyData = {};
831
+ break;
832
+ }
833
+ return opts.responseStyle === "data" ? emptyData : {
834
+ data: emptyData,
835
+ ...result
836
+ };
837
+ }
838
+ let data;
839
+ switch (parseAs) {
840
+ case "arrayBuffer":
841
+ case "blob":
842
+ case "formData":
843
+ case "text":
844
+ data = await response[parseAs]();
845
+ break;
846
+ case "json": {
847
+ const text = await response.text();
848
+ data = text ? JSON.parse(text) : {};
849
+ break;
850
+ }
851
+ case "stream":
852
+ return opts.responseStyle === "data" ? response.body : {
853
+ data: response.body,
854
+ ...result
855
+ };
856
+ }
857
+ if (parseAs === "json") {
858
+ if (opts.responseValidator) {
859
+ await opts.responseValidator(data);
860
+ }
861
+ if (opts.responseTransformer) {
862
+ data = await opts.responseTransformer(data);
863
+ }
864
+ }
865
+ return opts.responseStyle === "data" ? data : {
866
+ data,
867
+ ...result
868
+ };
869
+ }
870
+ const textError = await response.text();
871
+ let jsonError;
872
+ try {
873
+ jsonError = JSON.parse(textError);
874
+ } catch {
875
+ }
876
+ const error = jsonError ?? textError;
877
+ let finalError = error;
878
+ for (const fn of interceptors.error.fns) {
879
+ if (fn) {
880
+ finalError = await fn(error, response, request2, opts);
881
+ }
882
+ }
883
+ finalError = finalError || {};
884
+ if (opts.throwOnError) {
885
+ throw finalError;
886
+ }
887
+ return opts.responseStyle === "data" ? void 0 : {
888
+ error: finalError,
889
+ ...result
890
+ };
891
+ };
892
+ const makeMethodFn = (method) => (options) => request({ ...options, method });
893
+ const makeSseFn = (method) => async (options) => {
894
+ const { opts, url } = await beforeRequest(options);
895
+ return createSseClient({
896
+ ...opts,
897
+ body: opts.body,
898
+ headers: opts.headers,
899
+ method,
900
+ onRequest: async (url2, init) => {
901
+ let request2 = new Request(url2, init);
902
+ for (const fn of interceptors.request.fns) {
903
+ if (fn) {
904
+ request2 = await fn(request2, opts);
905
+ }
906
+ }
907
+ return request2;
908
+ },
909
+ serializedBody: getValidRequestBody(opts),
910
+ url
911
+ });
912
+ };
913
+ const _buildUrl = (options) => buildUrl({ ..._config, ...options });
914
+ return {
915
+ buildUrl: _buildUrl,
916
+ connect: makeMethodFn("CONNECT"),
917
+ delete: makeMethodFn("DELETE"),
918
+ get: makeMethodFn("GET"),
919
+ getConfig,
920
+ head: makeMethodFn("HEAD"),
921
+ interceptors,
922
+ options: makeMethodFn("OPTIONS"),
923
+ patch: makeMethodFn("PATCH"),
924
+ post: makeMethodFn("POST"),
925
+ put: makeMethodFn("PUT"),
926
+ request,
927
+ setConfig,
928
+ sse: {
929
+ connect: makeSseFn("CONNECT"),
930
+ delete: makeSseFn("DELETE"),
931
+ get: makeSseFn("GET"),
932
+ head: makeSseFn("HEAD"),
933
+ options: makeSseFn("OPTIONS"),
934
+ patch: makeSseFn("PATCH"),
935
+ post: makeSseFn("POST"),
936
+ put: makeSseFn("PUT"),
937
+ trace: makeSseFn("TRACE")
938
+ },
939
+ trace: makeMethodFn("TRACE")
940
+ };
941
+ };
942
+
943
+ // src/lib/client/client.gen.ts
944
+ var client = createClient(createConfig({ baseUrl: "https://us-staging.notte.cc" }));
945
+
946
+ // src/lib/client/sdk.gen.ts
947
+ var listSessions = (options) => (options?.client ?? client).get({
948
+ security: [{ scheme: "bearer", type: "http" }],
949
+ url: "/sessions",
950
+ ...options
951
+ });
952
+ var sessionStart = (options) => (options.client ?? client).post({
953
+ security: [{ scheme: "bearer", type: "http" }],
954
+ url: "/sessions/start",
955
+ ...options,
956
+ headers: {
957
+ "Content-Type": "application/json",
958
+ ...options.headers
959
+ }
960
+ });
961
+ var sessionStatus = (options) => (options.client ?? client).get({
962
+ security: [{ scheme: "bearer", type: "http" }],
963
+ url: "/sessions/{session_id}",
964
+ ...options
965
+ });
966
+ var getSessionScript = (options) => (options.client ?? client).get({
967
+ security: [{ scheme: "bearer", type: "http" }],
968
+ url: "/sessions/{session_id}/workflow/code",
969
+ ...options
970
+ });
971
+ var sessionStop = (options) => (options.client ?? client).delete({
972
+ security: [{ scheme: "bearer", type: "http" }],
973
+ url: "/sessions/{session_id}/stop",
974
+ ...options
975
+ });
976
+ var sessionCookiesGet = (options) => (options.client ?? client).get({
977
+ security: [{ scheme: "bearer", type: "http" }],
978
+ url: "/sessions/{session_id}/cookies",
979
+ ...options
980
+ });
981
+ var sessionCookiesSet = (options) => (options.client ?? client).post({
982
+ security: [{ scheme: "bearer", type: "http" }],
983
+ url: "/sessions/{session_id}/cookies",
984
+ ...options,
985
+ headers: {
986
+ "Content-Type": "application/json",
987
+ ...options.headers
988
+ }
989
+ });
990
+ var sessionDebugInfo = (options) => (options.client ?? client).get({
991
+ security: [{ scheme: "bearer", type: "http" }],
992
+ url: "/sessions/{session_id}/debug",
993
+ ...options
994
+ });
995
+ var sessionOffset = (options) => (options.client ?? client).get({
996
+ security: [{ scheme: "bearer", type: "http" }],
997
+ url: "/sessions/{session_id}/offset",
998
+ ...options
999
+ });
1000
+ var pageObserve = (options) => (options.client ?? client).post({
1001
+ security: [{ scheme: "bearer", type: "http" }],
1002
+ url: "/sessions/{session_id}/page/observe",
1003
+ ...options,
1004
+ headers: {
1005
+ "Content-Type": "application/json",
1006
+ ...options.headers
1007
+ }
1008
+ });
1009
+ var pageScreenshot = (options) => (options.client ?? client).post({
1010
+ security: [{ scheme: "bearer", type: "http" }],
1011
+ url: "/sessions/{session_id}/page/screenshot",
1012
+ ...options
1013
+ });
1014
+ var pageExecute = (options) => (options.client ?? client).post({
1015
+ security: [{ scheme: "bearer", type: "http" }],
1016
+ url: "/sessions/{session_id}/page/execute",
1017
+ ...options,
1018
+ headers: {
1019
+ "Content-Type": "application/json",
1020
+ ...options.headers
1021
+ }
1022
+ });
1023
+ var pageScrape = (options) => (options.client ?? client).post({
1024
+ security: [{ scheme: "bearer", type: "http" }],
1025
+ url: "/sessions/{session_id}/page/scrape",
1026
+ ...options,
1027
+ headers: {
1028
+ "Content-Type": "application/json",
1029
+ ...options.headers
1030
+ }
1031
+ });
1032
+ var sessionNetworkLogs = (options) => (options.client ?? client).get({
1033
+ security: [{ scheme: "bearer", type: "http" }],
1034
+ url: "/sessions/{session_id}/network/logs",
1035
+ ...options
1036
+ });
1037
+ var sessionReplay = (options) => (options.client ?? client).get({
1038
+ security: [{ scheme: "bearer", type: "http" }],
1039
+ url: "/sessions/{session_id}/replay",
1040
+ ...options
1041
+ });
1042
+ var agentStart = (options) => (options.client ?? client).post({
1043
+ security: [{ scheme: "bearer", type: "http" }],
1044
+ url: "/agents/start",
1045
+ ...options,
1046
+ headers: {
1047
+ "Content-Type": "application/json",
1048
+ ...options.headers
1049
+ }
1050
+ });
1051
+ var agentStatus = (options) => (options.client ?? client).get({
1052
+ security: [{ scheme: "bearer", type: "http" }],
1053
+ url: "/agents/{agent_id}",
1054
+ ...options
1055
+ });
1056
+ var getScript = (options) => (options.client ?? client).get({
1057
+ security: [{ scheme: "bearer", type: "http" }],
1058
+ url: "/agents/{agent_id}/workflow/code",
1059
+ ...options
1060
+ });
1061
+ var agentStop = (options) => (options.client ?? client).delete({
1062
+ security: [{ scheme: "bearer", type: "http" }],
1063
+ url: "/agents/{agent_id}/stop",
1064
+ ...options
1065
+ });
1066
+ var listAgents = (options) => (options?.client ?? client).get({
1067
+ security: [{ scheme: "bearer", type: "http" }],
1068
+ url: "/agents",
1069
+ ...options
1070
+ });
1071
+ var listFunctions = (options) => (options?.client ?? client).get({
1072
+ security: [{ scheme: "bearer", type: "http" }],
1073
+ url: "/functions",
1074
+ ...options
1075
+ });
1076
+ var functionCreate = (options) => (options.client ?? client).post({
1077
+ ...formDataBodySerializer,
1078
+ security: [{ scheme: "bearer", type: "http" }],
1079
+ url: "/functions",
1080
+ ...options,
1081
+ headers: {
1082
+ "Content-Type": null,
1083
+ ...options.headers
1084
+ }
1085
+ });
1086
+ var functionDelete = (options) => (options.client ?? client).delete({
1087
+ security: [{ scheme: "bearer", type: "http" }],
1088
+ url: "/functions/{function_id}",
1089
+ ...options
1090
+ });
1091
+ var functionDownloadUrl = (options) => (options.client ?? client).get({
1092
+ security: [{ scheme: "bearer", type: "http" }],
1093
+ url: "/functions/{function_id}",
1094
+ ...options
1095
+ });
1096
+ var functionUpdate = (options) => (options.client ?? client).post({
1097
+ ...formDataBodySerializer,
1098
+ security: [{ scheme: "bearer", type: "http" }],
1099
+ url: "/functions/{function_id}",
1100
+ ...options,
1101
+ headers: {
1102
+ "Content-Type": null,
1103
+ ...options.headers
1104
+ }
1105
+ });
1106
+ var functionFork = (options) => (options.client ?? client).post({
1107
+ security: [{ scheme: "bearer", type: "http" }],
1108
+ url: "/functions/{function_id}/fork",
1109
+ ...options
1110
+ });
1111
+ var functionScheduleDelete = (options) => (options.client ?? client).delete({
1112
+ security: [{ scheme: "bearer", type: "http" }],
1113
+ url: "/functions/{function_id}/schedule",
1114
+ ...options
1115
+ });
1116
+ var functionScheduleSet = (options) => (options.client ?? client).post({
1117
+ security: [{ scheme: "bearer", type: "http" }],
1118
+ url: "/functions/{function_id}/schedule",
1119
+ ...options,
1120
+ headers: {
1121
+ "Content-Type": "application/json",
1122
+ ...options.headers
1123
+ }
1124
+ });
1125
+ var functionRunStart = (options) => (options.client ?? client).post({
1126
+ security: [{ scheme: "bearer", type: "http" }],
1127
+ url: "/functions/{function_id}/runs/start",
1128
+ ...options,
1129
+ headers: {
1130
+ "Content-Type": "application/json",
1131
+ ...options.headers
1132
+ }
1133
+ });
1134
+ var functionRunStop = (options) => (options.client ?? client).delete({
1135
+ security: [{ scheme: "bearer", type: "http" }],
1136
+ url: "/functions/{function_id}/runs/{run_id}",
1137
+ ...options
1138
+ });
1139
+ var functionRunGetMetadata = (options) => (options.client ?? client).get({
1140
+ security: [{ scheme: "bearer", type: "http" }],
1141
+ url: "/functions/{function_id}/runs/{run_id}",
1142
+ ...options
1143
+ });
1144
+ var functionRunUpdateMetadata = (options) => (options.client ?? client).patch({
1145
+ security: [{ scheme: "bearer", type: "http" }],
1146
+ url: "/functions/{function_id}/runs/{run_id}",
1147
+ ...options,
1148
+ headers: {
1149
+ "Content-Type": "application/json",
1150
+ ...options.headers
1151
+ }
1152
+ });
1153
+ var listFunctionRunsByFunctionId = (options) => (options.client ?? client).get({
1154
+ security: [{ scheme: "bearer", type: "http" }],
1155
+ url: "/functions/{function_id}/runs",
1156
+ ...options
1157
+ });
1158
+ var vaultCreate = (options) => (options.client ?? client).post({
1159
+ security: [{ scheme: "bearer", type: "http" }],
1160
+ url: "/vaults/create",
1161
+ ...options,
1162
+ headers: {
1163
+ "Content-Type": "application/json",
1164
+ ...options.headers
1165
+ }
1166
+ });
1167
+ var vaultCredentialsDelete = (options) => (options.client ?? client).delete({
1168
+ security: [{ scheme: "bearer", type: "http" }],
1169
+ url: "/vaults/{vault_id}/credentials",
1170
+ ...options
1171
+ });
1172
+ var vaultCredentialsGet = (options) => (options.client ?? client).get({
1173
+ security: [{ scheme: "bearer", type: "http" }],
1174
+ url: "/vaults/{vault_id}/credentials",
1175
+ ...options
1176
+ });
1177
+ var vaultCredentialsAdd = (options) => (options.client ?? client).post({
1178
+ security: [{ scheme: "bearer", type: "http" }],
1179
+ url: "/vaults/{vault_id}/credentials",
1180
+ ...options,
1181
+ headers: {
1182
+ "Content-Type": "application/json",
1183
+ ...options.headers
1184
+ }
1185
+ });
1186
+ var vaultDelete = (options) => (options.client ?? client).delete({
1187
+ security: [{ scheme: "bearer", type: "http" }],
1188
+ url: "/vaults/{vault_id}",
1189
+ ...options
1190
+ });
1191
+ var vaultCredentialsList = (options) => (options.client ?? client).get({
1192
+ security: [{ scheme: "bearer", type: "http" }],
1193
+ url: "/vaults/{vault_id}",
1194
+ ...options
1195
+ });
1196
+ var vaultUpdate = (options) => (options.client ?? client).patch({
1197
+ security: [{ scheme: "bearer", type: "http" }],
1198
+ url: "/vaults/{vault_id}",
1199
+ ...options,
1200
+ headers: {
1201
+ "Content-Type": "application/json",
1202
+ ...options.headers
1203
+ }
1204
+ });
1205
+ var vaultCreditCardDelete = (options) => (options.client ?? client).delete({
1206
+ security: [{ scheme: "bearer", type: "http" }],
1207
+ url: "/vaults/{vault_id}/card",
1208
+ ...options
1209
+ });
1210
+ var vaultCreditCardGet = (options) => (options.client ?? client).get({
1211
+ security: [{ scheme: "bearer", type: "http" }],
1212
+ url: "/vaults/{vault_id}/card",
1213
+ ...options
1214
+ });
1215
+ var vaultCreditCardSet = (options) => (options.client ?? client).post({
1216
+ security: [{ scheme: "bearer", type: "http" }],
1217
+ url: "/vaults/{vault_id}/card",
1218
+ ...options,
1219
+ headers: {
1220
+ "Content-Type": "application/json",
1221
+ ...options.headers
1222
+ }
1223
+ });
1224
+ var listVaults = (options) => (options?.client ?? client).get({
1225
+ security: [{ scheme: "bearer", type: "http" }],
1226
+ url: "/vaults",
1227
+ ...options
1228
+ });
1229
+ var profileCreate = (options) => (options.client ?? client).post({
1230
+ security: [{ scheme: "bearer", type: "http" }],
1231
+ url: "/profiles/create",
1232
+ ...options,
1233
+ headers: {
1234
+ "Content-Type": "application/json",
1235
+ ...options.headers
1236
+ }
1237
+ });
1238
+ var profileDelete = (options) => (options.client ?? client).delete({
1239
+ security: [{ scheme: "bearer", type: "http" }],
1240
+ url: "/profiles/{profile_id}",
1241
+ ...options
1242
+ });
1243
+ var profileGet = (options) => (options.client ?? client).get({
1244
+ security: [{ scheme: "bearer", type: "http" }],
1245
+ url: "/profiles/{profile_id}",
1246
+ ...options
1247
+ });
1248
+ var profileList = (options) => (options?.client ?? client).get({
1249
+ security: [{ scheme: "bearer", type: "http" }],
1250
+ url: "/profiles",
1251
+ ...options
1252
+ });
1253
+ var personaCreate = (options) => (options.client ?? client).post({
1254
+ security: [{ scheme: "bearer", type: "http" }],
1255
+ url: "/personas/create",
1256
+ ...options,
1257
+ headers: {
1258
+ "Content-Type": "application/json",
1259
+ ...options.headers
1260
+ }
1261
+ });
1262
+ var personaDelete = (options) => (options.client ?? client).delete({
1263
+ security: [{ scheme: "bearer", type: "http" }],
1264
+ url: "/personas/{persona_id}",
1265
+ ...options
1266
+ });
1267
+ var personaGet = (options) => (options.client ?? client).get({
1268
+ security: [{ scheme: "bearer", type: "http" }],
1269
+ url: "/personas/{persona_id}",
1270
+ ...options
1271
+ });
1272
+ var personaEmailsList = (options) => (options.client ?? client).get({
1273
+ security: [{ scheme: "bearer", type: "http" }],
1274
+ url: "/personas/{persona_id}/emails",
1275
+ ...options
1276
+ });
1277
+ var listPersonas = (options) => (options?.client ?? client).get({
1278
+ security: [{ scheme: "bearer", type: "http" }],
1279
+ url: "/personas",
1280
+ ...options
1281
+ });
1282
+ var personaSmsList = (options) => (options.client ?? client).get({
1283
+ security: [{ scheme: "bearer", type: "http" }],
1284
+ url: "/personas/{persona_id}/sms",
1285
+ ...options
1286
+ });
1287
+ var improvePrompt = (options) => (options.client ?? client).post({
1288
+ url: "/prompts/improve",
1289
+ ...options,
1290
+ headers: {
1291
+ "Content-Type": "application/json",
1292
+ ...options.headers
1293
+ }
1294
+ });
1295
+ var nudgePrompt = (options) => (options.client ?? client).post({
1296
+ url: "/prompts/nudge",
1297
+ ...options,
1298
+ headers: {
1299
+ "Content-Type": "application/json",
1300
+ ...options.headers
1301
+ }
1302
+ });
1303
+ var getUsage = (options) => (options?.client ?? client).get({
1304
+ security: [{ scheme: "bearer", type: "http" }],
1305
+ url: "/usage",
1306
+ ...options
1307
+ });
1308
+ var getUsageLogs = (options) => (options?.client ?? client).get({
1309
+ security: [{ scheme: "bearer", type: "http" }],
1310
+ url: "/usage/logs",
1311
+ ...options
1312
+ });
1313
+ var fileDownload = (options) => (options.client ?? client).get({
1314
+ security: [{ scheme: "bearer", type: "http" }],
1315
+ url: "/storage/{session_id}/downloads/{filename}",
1316
+ ...options
1317
+ });
1318
+ var fileUploadDownloadedFile = (options) => (options.client ?? client).post({
1319
+ ...formDataBodySerializer,
1320
+ security: [{ scheme: "bearer", type: "http" }],
1321
+ url: "/storage/{session_id}/downloads/{filename}",
1322
+ ...options,
1323
+ headers: {
1324
+ "Content-Type": null,
1325
+ ...options.headers
1326
+ }
1327
+ });
1328
+ var fileListDownloads = (options) => (options.client ?? client).get({
1329
+ security: [{ scheme: "bearer", type: "http" }],
1330
+ url: "/storage/{session_id}/downloads",
1331
+ ...options
1332
+ });
1333
+ var fileUpload = (options) => (options.client ?? client).post({
1334
+ ...formDataBodySerializer,
1335
+ security: [{ scheme: "bearer", type: "http" }],
1336
+ url: "/storage/uploads/{filename}",
1337
+ ...options,
1338
+ headers: {
1339
+ "Content-Type": null,
1340
+ ...options.headers
1341
+ }
1342
+ });
1343
+ var fileListUploads = (options) => (options?.client ?? client).get({
1344
+ security: [{ scheme: "bearer", type: "http" }],
1345
+ url: "/storage/uploads",
1346
+ ...options
1347
+ });
1348
+ var anythingStart = (options) => (options.client ?? client).post({
1349
+ security: [{ scheme: "bearer", type: "http" }],
1350
+ url: "/anything/start",
1351
+ ...options,
1352
+ headers: {
1353
+ "Content-Type": "application/json",
1354
+ ...options.headers
1355
+ }
1356
+ });
1357
+ var healthCheck = (options) => (options?.client ?? client).get({ url: "/health", ...options });
1358
+ var scrapeWebpage = (options) => (options.client ?? client).post({
1359
+ security: [{ scheme: "bearer", type: "http" }],
1360
+ url: "/scrape",
1361
+ ...options,
1362
+ headers: {
1363
+ "Content-Type": "application/json",
1364
+ ...options.headers
1365
+ }
1366
+ });
1367
+ var scrapeFromHtml = (options) => (options.client ?? client).post({
1368
+ security: [{ scheme: "bearer", type: "http" }],
1369
+ url: "/scrape_from_html",
1370
+ ...options,
1371
+ headers: {
1372
+ "Content-Type": "application/json",
1373
+ ...options.headers
1374
+ }
1375
+ });
1376
+
1377
+ // src/utils.ts
1378
+ function formatError(error) {
1379
+ if (typeof error === "object" && error !== null) {
1380
+ if ("message" in error && typeof error.message === "string") {
1381
+ return error.message;
1382
+ }
1383
+ try {
1384
+ return JSON.stringify(error, null, 2);
1385
+ } catch {
1386
+ return String(error);
1387
+ }
1388
+ }
1389
+ if (error instanceof Error) {
1390
+ return error.message;
1391
+ }
1392
+ return String(error);
1393
+ }
1394
+
1395
+ // src/session.ts
1396
+ var import_zod = require("zod");
1397
+ function processScrapeResponse(scrapeResponse, options) {
1398
+ if (options.only_images && scrapeResponse.images) {
1399
+ return scrapeResponse.images;
1400
+ }
1401
+ if (requiresSchema(options)) {
1402
+ const structured = scrapeResponse.structured;
1403
+ if (!structured) {
1404
+ throw new Error("Failed to scrape structured data. This should not happen. Please report this issue.");
1405
+ }
1406
+ if (options.response_format && typeof options.response_format.parse === "function") {
1407
+ if (structured.data) {
1408
+ try {
1409
+ const validatedData = options.response_format.parse(structured.data);
1410
+ return validatedData;
1411
+ } catch (error) {
1412
+ throw new Error(`Schema validation failed: ${error instanceof Error ? error.message : String(error)}`);
1413
+ }
1414
+ }
1415
+ return structured;
1416
+ }
1417
+ return structured;
1418
+ }
1419
+ if (options.response_format && typeof options.response_format.parse === "function") {
1420
+ try {
1421
+ const validatedData = options.response_format.parse(scrapeResponse);
1422
+ return validatedData;
1423
+ } catch (error) {
1424
+ throw new Error(`Schema validation failed: ${error instanceof Error ? error.message : String(error)}`);
1425
+ }
1426
+ }
1427
+ return scrapeResponse.markdown;
1428
+ }
1429
+ function requiresSchema(options) {
1430
+ return !!(options.response_format || options.instructions);
1431
+ }
1432
+ var Session = class {
1433
+ constructor(client2, options = {}) {
1434
+ this.sessionId = null;
1435
+ this.isActive = false;
1436
+ this.response = null;
1437
+ this.client = client2;
1438
+ this.options = options;
1439
+ }
1440
+ /**
1441
+ * Start the session - creates a new session on the server
1442
+ */
1443
+ async start() {
1444
+ if (this.isActive) {
1445
+ throw new Error("Session is already active");
1446
+ }
1447
+ try {
1448
+ const response = await sessionStart({
1449
+ client: this.client.getClient(),
1450
+ body: this.options
1451
+ });
1452
+ if (response?.error) {
1453
+ throw new Error(`Failed to create session: ${formatError(response.error)}`);
1454
+ }
1455
+ const sessionData = response.data;
1456
+ this.sessionId = sessionData.session_id;
1457
+ this.isActive = true;
1458
+ this.response = sessionData;
1459
+ } catch (error) {
1460
+ throw new Error(`Failed to start session: ${error instanceof Error ? error.message : String(error)}`);
1461
+ }
1462
+ }
1463
+ /**
1464
+ * Stop the session - terminates the session on the server
1465
+ */
1466
+ async stop() {
1467
+ if (!this.isActive || !this.sessionId) {
1468
+ return;
1469
+ }
1470
+ const response = await sessionStop({
1471
+ client: this.client.getClient(),
1472
+ path: {
1473
+ session_id: this.sessionId
1474
+ }
1475
+ });
1476
+ if (response?.error) {
1477
+ throw new Error(`Failed to stop session: ${formatError(response.error)}`);
1478
+ }
1479
+ this.response = response.data;
1480
+ this.isActive = false;
1481
+ this.sessionId = null;
1482
+ }
1483
+ /**
1484
+ * Get session status
1485
+ */
1486
+ async status() {
1487
+ if (!this.sessionId) {
1488
+ throw new Error("Session not started");
1489
+ }
1490
+ const response = await sessionStatus({
1491
+ client: this.client.getClient(),
1492
+ path: {
1493
+ session_id: this.sessionId
1494
+ }
1495
+ });
1496
+ if (response?.error) {
1497
+ throw new Error(`Failed to get session status: ${formatError(response.error)}`);
1498
+ }
1499
+ return response.data;
1500
+ }
1501
+ /**
1502
+ * Get session ID
1503
+ */
1504
+ getId() {
1505
+ return this.sessionId;
1506
+ }
1507
+ /**
1508
+ * Check if session is active
1509
+ */
1510
+ isSessionActive() {
1511
+ return this.isActive;
1512
+ }
1513
+ /**
1514
+ * Get the last response from session operations
1515
+ */
1516
+ getResponse() {
1517
+ return this.response;
1518
+ }
1519
+ /**
1520
+ * Set cookies for the session
1521
+ */
1522
+ async setCookies(cookies) {
1523
+ if (!this.sessionId) {
1524
+ throw new Error("Session not started");
1525
+ }
1526
+ const response = await sessionCookiesSet({
1527
+ client: this.client.getClient(),
1528
+ path: {
1529
+ session_id: this.sessionId
1530
+ },
1531
+ body: {
1532
+ cookies
1533
+ }
1534
+ });
1535
+ if (response?.error) {
1536
+ throw new Error(`Failed to set cookies: ${formatError(response.error)}`);
1537
+ }
1538
+ return response.data;
1539
+ }
1540
+ /**
1541
+ * Set cookies from a file
1542
+ */
1543
+ async setCookiesFromFile(cookieFile) {
1544
+ const fs = await import("fs/promises");
1545
+ const cookieData = await fs.readFile(cookieFile, "utf-8");
1546
+ const cookies = JSON.parse(cookieData);
1547
+ return this.setCookies(cookies);
1548
+ }
1549
+ /**
1550
+ * Get cookies from the session
1551
+ */
1552
+ async getCookies() {
1553
+ if (!this.sessionId) {
1554
+ throw new Error("Session not started");
1555
+ }
1556
+ const response = await sessionCookiesGet({
1557
+ client: this.client.getClient(),
1558
+ path: {
1559
+ session_id: this.sessionId
1560
+ }
1561
+ });
1562
+ if (response?.error) {
1563
+ throw new Error(`Failed to get cookies: ${formatError(response.error)}`);
1564
+ }
1565
+ return response.data.cookies;
1566
+ }
1567
+ /**
1568
+ * Execute an action on the page
1569
+ */
1570
+ async execute(action, raiseOnFailure = true) {
1571
+ if (!this.sessionId) {
1572
+ throw new Error("Session not started");
1573
+ }
1574
+ const response = await pageExecute({
1575
+ client: this.client.getClient(),
1576
+ path: {
1577
+ session_id: this.sessionId
1578
+ },
1579
+ body: action
1580
+ });
1581
+ if (response?.error) {
1582
+ throw new Error(`Failed to execute action: ${formatError(response.error)}`);
1583
+ }
1584
+ const result = response.data;
1585
+ if (raiseOnFailure && !result.success) {
1586
+ throw new Error(`Action execution failed: ${result.message}`);
1587
+ }
1588
+ return result;
1589
+ }
1590
+ /**
1591
+ * Observe the current page state
1592
+ */
1593
+ async observe(perceptionType = "fast") {
1594
+ if (!this.sessionId) {
1595
+ throw new Error("Session not started");
1596
+ }
1597
+ const response = await pageObserve({
1598
+ client: this.client.getClient(),
1599
+ path: {
1600
+ session_id: this.sessionId
1601
+ },
1602
+ body: {
1603
+ perception_type: perceptionType
1604
+ }
1605
+ });
1606
+ if (response?.error) {
1607
+ throw new Error(`Failed to observe page: ${formatError(response.error)}`);
1608
+ }
1609
+ return response.data;
1610
+ }
1611
+ /**
1612
+ * Get session replay data
1613
+ */
1614
+ async replay() {
1615
+ if (!this.sessionId) {
1616
+ throw new Error("Session not started");
1617
+ }
1618
+ const response = await sessionReplay({
1619
+ client: this.client.getClient(),
1620
+ path: {
1621
+ session_id: this.sessionId
1622
+ }
1623
+ });
1624
+ if (response?.error) {
1625
+ throw new Error(`Failed to get session replay: ${formatError(response.error)}`);
1626
+ }
1627
+ return response.data;
1628
+ }
1629
+ async scrape(options = {}) {
1630
+ if (!this.sessionId) {
1631
+ throw new Error("Session not started");
1632
+ }
1633
+ const apiOptions = { ...options };
1634
+ if (options.response_format && typeof options.response_format.parse === "function") {
1635
+ if (options.json_schema) {
1636
+ apiOptions.response_format = options.json_schema;
1637
+ } else {
1638
+ apiOptions.response_format = import_zod.z.toJSONSchema(options.response_format);
1639
+ }
1640
+ if (!apiOptions.instructions) {
1641
+ const schemaStr = JSON.stringify(apiOptions.response_format);
1642
+ if (schemaStr.includes("plans") || schemaStr.includes("plan")) {
1643
+ apiOptions.instructions = "Extract pricing plans from the page";
1644
+ } else if (schemaStr.includes("products") || schemaStr.includes("product")) {
1645
+ apiOptions.instructions = "Extract product information from the page";
1646
+ } else if (schemaStr.includes("articles") || schemaStr.includes("article")) {
1647
+ apiOptions.instructions = "Extract article information from the page";
1648
+ } else {
1649
+ apiOptions.instructions = "Extract structured data from the page based on the provided schema";
1650
+ }
1651
+ }
1652
+ }
1653
+ const response = await pageScrape({
1654
+ client: this.client.getClient(),
1655
+ path: {
1656
+ session_id: this.sessionId
1657
+ },
1658
+ body: apiOptions
1659
+ });
1660
+ if (response?.error) {
1661
+ throw new Error(`Failed to scrape page: ${JSON.stringify(response.error)}`);
1662
+ }
1663
+ return processScrapeResponse(response.data, options);
1664
+ }
1665
+ /**
1666
+ * Context manager pattern - automatically start and stop session
1667
+ * Usage: await session.use(async (session) => { ... })
1668
+ */
1669
+ async use(callback) {
1670
+ await this.start();
1671
+ try {
1672
+ return await callback(this);
1673
+ } finally {
1674
+ await this.stop();
1675
+ }
1676
+ }
1677
+ /**
1678
+ * Async iterator pattern for session lifecycle management
1679
+ * Usage: for await (const session of sessionInstance) { ... }
1680
+ */
1681
+ async *[Symbol.asyncIterator]() {
1682
+ await this.start();
1683
+ try {
1684
+ yield this;
1685
+ } finally {
1686
+ await this.stop();
1687
+ }
1688
+ }
1689
+ };
1690
+
1691
+ // src/agent.ts
1692
+ var import_ws = __toESM(require("ws"));
1693
+ function validatePersonaOption(persona, persona_id) {
1694
+ if (persona) {
1695
+ try {
1696
+ const personaId = persona.personaId;
1697
+ if (!personaId || personaId.length === 0) {
1698
+ throw new Error("Persona ID cannot be empty");
1699
+ }
1700
+ return personaId;
1701
+ } catch (error) {
1702
+ throw new Error(`Invalid persona object: ${error instanceof Error ? error.message : String(error)}`);
1703
+ }
1704
+ } else if (persona_id) {
1705
+ if (persona_id.length === 0) {
1706
+ throw new Error("Persona ID cannot be empty");
1707
+ }
1708
+ return persona_id;
1709
+ }
1710
+ return void 0;
1711
+ }
1712
+ function validateVaultOption(vault, vault_id) {
1713
+ if (vault) {
1714
+ try {
1715
+ const vaultId = vault.vaultId;
1716
+ if (!vaultId || vaultId.length === 0) {
1717
+ throw new Error("Vault ID cannot be empty");
1718
+ }
1719
+ return vaultId;
1720
+ } catch (error) {
1721
+ throw new Error(`Invalid vault object: ${error instanceof Error ? error.message : String(error)}`);
1722
+ }
1723
+ } else if (vault_id) {
1724
+ if (vault_id.length === 0) {
1725
+ throw new Error("Vault ID cannot be empty");
1726
+ }
1727
+ return vault_id;
1728
+ }
1729
+ return void 0;
1730
+ }
1731
+ function validateSessionOption(session) {
1732
+ const sessionId = session.getId();
1733
+ if (!sessionId || sessionId.length === 0) {
1734
+ throw new Error("Session ID cannot be empty");
1735
+ }
1736
+ return sessionId;
1737
+ }
1738
+ function validateAgentIdOption(agent_id) {
1739
+ if (agent_id.length === 0) {
1740
+ throw new Error("Agent ID cannot be empty");
1741
+ }
1742
+ }
1743
+ var defaultStepLogger = (stepData, stepCounter, agentId) => {
1744
+ console.log(`\u2728 Step ${stepCounter} (agent: ${agentId})`);
1745
+ if (stepData && typeof stepData === "object") {
1746
+ if (stepData.state) {
1747
+ const state = stepData.state;
1748
+ if (state.page_summary) {
1749
+ console.log(`\u{1F4DD} Current page: ${state.page_summary}`);
1750
+ }
1751
+ if (state.previous_goal_eval) {
1752
+ const statusEmoji = state.previous_goal_status === "success" ? "\u2705" : state.previous_goal_status === "failure" ? "\u274C" : "\u2753";
1753
+ console.log(`\u{1F52C} Previous goal: ${statusEmoji} ${state.previous_goal_eval}`);
1754
+ }
1755
+ if (state.memory) {
1756
+ console.log(`\u{1F9E0} Memory: ${state.memory}`);
1757
+ }
1758
+ if (state.next_goal) {
1759
+ console.log(`\u{1F3AF} Next goal: ${state.next_goal}`);
1760
+ }
1761
+ if (state.relevant_interactions && state.relevant_interactions.length > 0) {
1762
+ console.log(`\u{1F194} Relevant ids:`);
1763
+ state.relevant_interactions.forEach((interaction) => {
1764
+ console.log(` \u25B6 ${interaction.id}: ${interaction.reason}`);
1765
+ });
1766
+ }
1767
+ }
1768
+ if (stepData.action) {
1769
+ const action = stepData.action;
1770
+ let actionStr = `\u26A1 Taking action:
1771
+ \u25B6 ${action.name || action.type || "Unknown action"}`;
1772
+ if (action.id) {
1773
+ actionStr += ` with id ${action.id}`;
1774
+ } else if (action.param && action.param.name && action[action.param.name]) {
1775
+ actionStr += ` with ${action.param.name}=${action[action.param.name]}`;
1776
+ }
1777
+ console.log(actionStr);
1778
+ }
1779
+ } else {
1780
+ console.log(stepData);
1781
+ }
1782
+ console.log("");
1783
+ };
1784
+ var Agent = class {
1785
+ constructor(client2, options) {
1786
+ this.response = null;
1787
+ this.websocket = null;
1788
+ this.client = client2;
1789
+ if ("agent_id" in options && options.agent_id) {
1790
+ if (options.session) {
1791
+ throw new Error("Either session (for running a new agent) or agent_id (for accessing an existing agent) have to be provided, not both");
1792
+ }
1793
+ validateAgentIdOption(options.agent_id);
1794
+ this.existingAgent = true;
1795
+ this.response = { agent_id: options.agent_id };
1796
+ } else if ("session" in options && options.session) {
1797
+ if (options.agent_id) {
1798
+ throw new Error("Either session (for running a new agent) or agent_id (for accessing an existing agent) have to be provided, not both");
1799
+ }
1800
+ this.existingAgent = false;
1801
+ const { session, vault, persona, ...requestData } = options;
1802
+ const sessionId = validateSessionOption(session);
1803
+ const vaultId = validateVaultOption(vault, options.vault_id);
1804
+ const personaId = validatePersonaOption(persona, options.persona_id);
1805
+ this.request = {
1806
+ session_id: sessionId,
1807
+ vault_id: vaultId,
1808
+ persona_id: personaId,
1809
+ ...requestData
1810
+ };
1811
+ } else {
1812
+ throw new Error("Either session (for running a new agent) or agent_id (for accessing an existing agent) have to be provided");
1813
+ }
1814
+ }
1815
+ /**
1816
+ * Start an agent task (non-blocking) - mirrors Python start method
1817
+ */
1818
+ async start(data) {
1819
+ if (this.existingAgent) {
1820
+ throw new Error("You cannot call start() on an agent instantiated from agent id");
1821
+ }
1822
+ if (!this.request) {
1823
+ throw new Error("Agent not properly initialized with session");
1824
+ }
1825
+ try {
1826
+ const requestBody = {
1827
+ ...this.request,
1828
+ ...data
1829
+ };
1830
+ const response = await agentStart({
1831
+ client: this.client.getClient(),
1832
+ body: requestBody
1833
+ });
1834
+ if (response?.error) {
1835
+ throw new Error(`Failed to start agent: ${formatError(response.error)}`);
1836
+ }
1837
+ this.response = response.data;
1838
+ return this.response;
1839
+ } catch (error) {
1840
+ throw new Error(`Failed to start agent: ${error instanceof Error ? error.message : String(error)}`);
1841
+ }
1842
+ }
1843
+ /**
1844
+ * Run agent task (blocking) - mirrors Python run method behavior
1845
+ * This is the main method that mirrors the Python SDK's run method
1846
+ */
1847
+ async run(data) {
1848
+ if (this.existingAgent) {
1849
+ throw new Error("You cannot call run() on an agent instantiated from agent id");
1850
+ }
1851
+ this.response = await this.start(data);
1852
+ console.log(`[Agent] ${this.agentId} started`);
1853
+ return await this.watchLogsAndWait(true, data.updateHandler || null);
1854
+ }
1855
+ /**
1856
+ * Watch logs and wait for completion - mirrors Python watch_logs_and_wait
1857
+ */
1858
+ async watchLogsAndWait(log = true, updateHandler = null) {
1859
+ if (this.existingAgent) {
1860
+ throw new Error("You cannot call watchLogsAndWait() on an agent instantiated from agent id");
1861
+ }
1862
+ if (!this.response) {
1863
+ throw new Error("Agent not started");
1864
+ }
1865
+ try {
1866
+ const result = await this.watchLogs(log, updateHandler);
1867
+ if (result) {
1868
+ return result;
1869
+ }
1870
+ await new Promise((resolve) => setTimeout(resolve, 3e3));
1871
+ return await this.status();
1872
+ } catch (error) {
1873
+ console.error(`[Agent] ${this.agentId} failed to complete in time. Try running agent.status() after a few seconds.`);
1874
+ return await this.status();
1875
+ }
1876
+ }
1877
+ /**
1878
+ * Watch logs via WebSocket - mirrors Python watch_logs method
1879
+ */
1880
+ async watchLogs(log = true, updateHandler = null) {
1881
+ if (this.existingAgent) {
1882
+ throw new Error("You cannot call watchLogs() on an agent instantiated from agent id");
1883
+ }
1884
+ if (!this.response) {
1885
+ throw new Error("Agent not started");
1886
+ }
1887
+ const config = this.client.getConfig();
1888
+ const token = config.apiKey;
1889
+ const agentId = this.response.agent_id;
1890
+ const sessionId = this.response.session_id;
1891
+ const wsUrl = config.baseUrl?.replace("https://", "wss://").replace("http://", "ws://") + `/agents/${agentId}/debug/logs?token=${token}&session_id=${sessionId}`;
1892
+ return new Promise((resolve, reject) => {
1893
+ this.websocket = new import_ws.default(wsUrl);
1894
+ let counter = 0;
1895
+ this.websocket.on("open", () => {
1896
+ });
1897
+ this.websocket.on("error", (error) => {
1898
+ console.error(`Connection error: ${agentId} ${error.message}`);
1899
+ resolve(null);
1900
+ });
1901
+ this.websocket.on("message", (data) => {
1902
+ try {
1903
+ const message = data.toString();
1904
+ let parsed;
1905
+ try {
1906
+ parsed = JSON.parse(message);
1907
+ } catch {
1908
+ return;
1909
+ }
1910
+ if (parsed.agent_id === agentId && parsed.task !== void 0 && parsed.status !== void 0) {
1911
+ const response = parsed;
1912
+ if (updateHandler) {
1913
+ updateHandler({
1914
+ type: "completion",
1915
+ data: response,
1916
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1917
+ });
1918
+ } else if (!response.success) {
1919
+ console.error(response.answer);
1920
+ }
1921
+ this.disconnectWebSocket();
1922
+ resolve(response);
1923
+ return;
1924
+ }
1925
+ if (log) {
1926
+ counter++;
1927
+ if (updateHandler) {
1928
+ updateHandler({
1929
+ type: "step",
1930
+ data: parsed,
1931
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1932
+ });
1933
+ } else {
1934
+ defaultStepLogger(parsed, counter, agentId);
1935
+ }
1936
+ }
1937
+ } catch (error) {
1938
+ console.error(`Error processing WebSocket message: ${error}`);
1939
+ }
1940
+ });
1941
+ this.websocket.on("close", () => {
1942
+ this.websocket = null;
1943
+ resolve(null);
1944
+ });
1945
+ setTimeout(() => {
1946
+ if (this.websocket && this.websocket.readyState === import_ws.default.OPEN) {
1947
+ this.disconnectWebSocket();
1948
+ resolve(null);
1949
+ }
1950
+ }, 3e5);
1951
+ });
1952
+ }
1953
+ /**
1954
+ * Get agent status - mirrors Python status method
1955
+ */
1956
+ async status() {
1957
+ if (!this.response) {
1958
+ throw new Error("Agent not started or not accessible");
1959
+ }
1960
+ const response = await agentStatus({
1961
+ client: this.client.getClient(),
1962
+ path: {
1963
+ agent_id: this.response.agent_id
1964
+ }
1965
+ });
1966
+ if (response?.error) {
1967
+ throw new Error(`Failed to get agent status: ${formatError(response.error)}`);
1968
+ }
1969
+ return response.data;
1970
+ }
1971
+ /**
1972
+ * Stop the agent - mirrors Python stop method
1973
+ */
1974
+ async stop() {
1975
+ if (this.existingAgent) {
1976
+ throw new Error("You cannot call stop() on an agent instantiated from agent id");
1977
+ }
1978
+ if (!this.response) {
1979
+ throw new Error("Agent not started");
1980
+ }
1981
+ try {
1982
+ console.log(`[Agent] ${this.response.agent_id} is stopping`);
1983
+ const response = await agentStop({
1984
+ client: this.client.getClient(),
1985
+ path: {
1986
+ agent_id: this.response.agent_id
1987
+ },
1988
+ query: { session_id: this.response.session_id }
1989
+ });
1990
+ if (response?.error) {
1991
+ throw new Error(`Failed to stop agent: ${formatError(response.error)}`);
1992
+ }
1993
+ console.log(`[Agent] ${this.response.agent_id} stopped`);
1994
+ return response.data;
1995
+ } catch (error) {
1996
+ console.warn(`Failed to stop agent: ${error instanceof Error ? error.message : String(error)}`);
1997
+ throw error;
1998
+ } finally {
1999
+ this.disconnectWebSocket();
2000
+ }
2001
+ }
2002
+ /**
2003
+ * Disconnect WebSocket
2004
+ */
2005
+ disconnectWebSocket() {
2006
+ if (this.websocket) {
2007
+ this.websocket.close();
2008
+ this.websocket = null;
2009
+ }
2010
+ }
2011
+ /**
2012
+ * Get agent ID - mirrors Python agent_id property
2013
+ */
2014
+ get agentId() {
2015
+ if (!this.response) {
2016
+ throw new Error("You need to run the agent first to get the agent id");
2017
+ }
2018
+ return this.response.agent_id;
2019
+ }
2020
+ /**
2021
+ * Get session ID - mirrors Python session_id property
2022
+ */
2023
+ get sessionId() {
2024
+ if (!this.response) {
2025
+ throw new Error("You need to run the agent first to get the session id");
2026
+ }
2027
+ return this.response.session_id;
2028
+ }
2029
+ /**
2030
+ * Check if agent is running - convenience method
2031
+ */
2032
+ isRunning() {
2033
+ return this.response !== null;
2034
+ }
2035
+ };
2036
+
2037
+ // src/vaults.ts
2038
+ var NotteVault = class {
2039
+ constructor(client2, options = {}) {
2040
+ this._vaultId = null;
2041
+ this.initPromise = null;
2042
+ this.client = client2;
2043
+ if (options && "vault_id" in options && options.vault_id) {
2044
+ this.initPromise = this.initExistingVault(options.vault_id);
2045
+ } else {
2046
+ this.initPromise = this.initNewVault(options || {});
2047
+ }
2048
+ }
2049
+ async initExistingVault(vaultId) {
2050
+ await this.verifyVaultExists(vaultId);
2051
+ this._vaultId = vaultId;
2052
+ return this._vaultId;
2053
+ }
2054
+ async initNewVault(createData) {
2055
+ const response = await vaultCreate({
2056
+ client: this.client.getClient(),
2057
+ body: createData
2058
+ });
2059
+ if (response?.error) {
2060
+ throw new Error(`Failed to create vault: ${formatError(response.error)}`);
2061
+ }
2062
+ const vault = response.data;
2063
+ console.warn(`[Vault] ${vault.vault_id} created since no vault id was provided. Please store this to retrieve it later.`);
2064
+ this._vaultId = vault.vault_id;
2065
+ return this._vaultId;
2066
+ }
2067
+ async verifyVaultExists(vaultId) {
2068
+ if (vaultId.length === 0) {
2069
+ throw new Error("Vault ID cannot be empty");
2070
+ }
2071
+ const response = await vaultCredentialsList({
2072
+ client: this.client.getClient(),
2073
+ path: {
2074
+ vault_id: vaultId
2075
+ }
2076
+ });
2077
+ if (response?.error) {
2078
+ throw new Error(`Failed to verify vault exists: ${formatError(response.error)}`);
2079
+ }
2080
+ }
2081
+ async ensureInitialized() {
2082
+ if (this._vaultId) {
2083
+ return this._vaultId;
2084
+ }
2085
+ if (this.initPromise) {
2086
+ return await this.initPromise;
2087
+ }
2088
+ throw new Error("Vault not initialized");
2089
+ }
2090
+ get vaultId() {
2091
+ if (!this._vaultId) {
2092
+ throw new Error("Vault not initialized. Use await on vault operations first.");
2093
+ }
2094
+ return this._vaultId;
2095
+ }
2096
+ /**
2097
+ * Start the vault - no-op for compatibility with Python interface
2098
+ */
2099
+ start() {
2100
+ }
2101
+ /**
2102
+ * Stop the vault - deletes it and all credentials
2103
+ */
2104
+ async stop() {
2105
+ const vaultId = await this.ensureInitialized();
2106
+ console.log(`[Vault] ${vaultId} deleted. All credentials have been deleted.`);
2107
+ await this.delete();
2108
+ }
2109
+ /**
2110
+ * Add or update credentials for a URL
2111
+ */
2112
+ async addCredentials(url, credentials) {
2113
+ if (credentials.mfa_secret) {
2114
+ this.validateMfaSecret(credentials.mfa_secret);
2115
+ }
2116
+ const vaultId = await this.ensureInitialized();
2117
+ const response = await vaultCredentialsAdd({
2118
+ client: this.client.getClient(),
2119
+ path: {
2120
+ vault_id: vaultId
2121
+ },
2122
+ body: { url, credentials }
2123
+ });
2124
+ if (response?.error) {
2125
+ throw new Error(`Failed to add credentials: ${formatError(response.error)}`);
2126
+ }
2127
+ }
2128
+ /**
2129
+ * Get credentials for a URL
2130
+ */
2131
+ async getCredentials(url) {
2132
+ try {
2133
+ const vaultId = await this.ensureInitialized();
2134
+ const response = await vaultCredentialsGet({
2135
+ client: this.client.getClient(),
2136
+ path: {
2137
+ vault_id: vaultId
2138
+ },
2139
+ query: { url }
2140
+ });
2141
+ if (response?.error) {
2142
+ return null;
2143
+ }
2144
+ const credentialsResponse = response.data;
2145
+ return credentialsResponse.credentials;
2146
+ } catch (error) {
2147
+ return null;
2148
+ }
2149
+ }
2150
+ /**
2151
+ * Delete credentials for a URL
2152
+ */
2153
+ async deleteCredentials(url) {
2154
+ const vaultId = await this.ensureInitialized();
2155
+ const response = await vaultCredentialsDelete({
2156
+ client: this.client.getClient(),
2157
+ path: {
2158
+ vault_id: vaultId
2159
+ },
2160
+ query: { url }
2161
+ });
2162
+ if (response?.error) {
2163
+ throw new Error(`Failed to delete credentials: ${formatError(response.error)}`);
2164
+ }
2165
+ }
2166
+ /**
2167
+ * Set credit card information
2168
+ */
2169
+ async setCreditCard(creditCard) {
2170
+ const vaultId = await this.ensureInitialized();
2171
+ const response = await vaultCreditCardSet({
2172
+ client: this.client.getClient(),
2173
+ path: {
2174
+ vault_id: vaultId
2175
+ },
2176
+ body: { credit_card: creditCard }
2177
+ });
2178
+ if (response?.error) {
2179
+ throw new Error(`Failed to set credit card: ${formatError(response.error)}`);
2180
+ }
2181
+ }
2182
+ /**
2183
+ * Get credit card information
2184
+ */
2185
+ async getCreditCard() {
2186
+ const vaultId = await this.ensureInitialized();
2187
+ const response = await vaultCreditCardGet({
2188
+ client: this.client.getClient(),
2189
+ path: {
2190
+ vault_id: vaultId
2191
+ }
2192
+ });
2193
+ if (response?.error) {
2194
+ throw new Error(`Failed to get credit card: ${formatError(response.error)}`);
2195
+ }
2196
+ const creditCardResponse = response.data;
2197
+ return creditCardResponse.credit_card;
2198
+ }
2199
+ /**
2200
+ * List all credentials in the vault
2201
+ */
2202
+ async listCredentials() {
2203
+ const vaultId = await this.ensureInitialized();
2204
+ const response = await vaultCredentialsList({
2205
+ client: this.client.getClient(),
2206
+ path: {
2207
+ vault_id: vaultId
2208
+ }
2209
+ });
2210
+ if (response?.error) {
2211
+ throw new Error(`Failed to list credentials: ${formatError(response.error)}`);
2212
+ }
2213
+ const credentialsResponse = response.data;
2214
+ return credentialsResponse.credentials;
2215
+ }
2216
+ /**
2217
+ * Delete credit card information
2218
+ */
2219
+ async deleteCreditCard() {
2220
+ const vaultId = await this.ensureInitialized();
2221
+ const response = await vaultCreditCardDelete({
2222
+ client: this.client.getClient(),
2223
+ path: {
2224
+ vault_id: vaultId
2225
+ }
2226
+ });
2227
+ if (response?.error) {
2228
+ throw new Error(`Failed to delete credit card: ${formatError(response.error)}`);
2229
+ }
2230
+ }
2231
+ /**
2232
+ * Delete the entire vault
2233
+ */
2234
+ async delete() {
2235
+ const vaultId = await this.ensureInitialized();
2236
+ const response = await vaultDelete({
2237
+ client: this.client.getClient(),
2238
+ path: {
2239
+ vault_id: vaultId
2240
+ }
2241
+ });
2242
+ if (response?.error) {
2243
+ throw new Error(`Failed to delete vault: ${formatError(response.error)}`);
2244
+ }
2245
+ }
2246
+ /**
2247
+ * Add credentials from environment variables
2248
+ * Mirrors Python's add_credentials_from_env method
2249
+ */
2250
+ async addCredentialsFromEnv(url) {
2251
+ const domain = this.extractDomainFromUrl(url);
2252
+ const envPrefix = domain.replace(/[^a-zA-Z0-9]/g, "_").toUpperCase();
2253
+ const email = process.env[`${envPrefix}_EMAIL`] || process.env[`${envPrefix}_USERNAME`];
2254
+ const password = process.env[`${envPrefix}_PASSWORD`];
2255
+ if (!email || !password) {
2256
+ throw new Error(`Environment variables ${envPrefix}_EMAIL/USERNAME and ${envPrefix}_PASSWORD are required`);
2257
+ }
2258
+ const credentials = { email, password };
2259
+ const mfaSecret = process.env[`${envPrefix}_MFA_SECRET`];
2260
+ if (mfaSecret) {
2261
+ this.validateMfaSecret(mfaSecret);
2262
+ credentials.mfa_secret = mfaSecret;
2263
+ }
2264
+ await this.addCredentials(url, credentials);
2265
+ }
2266
+ /**
2267
+ * Extract domain from URL for environment variable naming
2268
+ */
2269
+ extractDomainFromUrl(url) {
2270
+ try {
2271
+ const urlObj = new URL(url);
2272
+ return urlObj.hostname.replace(/^www\./, "");
2273
+ } catch {
2274
+ const match = url.match(/(?:https?:\/\/)?(?:www\.)?([^\/]+)/);
2275
+ return match ? match[1] : url;
2276
+ }
2277
+ }
2278
+ /**
2279
+ * Validate MFA secret format
2280
+ * Mirrors Python's MFA secret validation
2281
+ */
2282
+ validateMfaSecret(mfaSecret) {
2283
+ if (/^\d+$/.test(mfaSecret)) {
2284
+ throw new Error("MFA secret cannot be all numbers. Please provide a valid base32 secret.");
2285
+ }
2286
+ if (mfaSecret.length < 16) {
2287
+ throw new Error("MFA secret must be at least 16 characters long");
2288
+ }
2289
+ }
2290
+ /**
2291
+ * Generate a secure random password
2292
+ * Mirrors Python's generate_password method
2293
+ */
2294
+ generatePassword(length = 20, includeSpecialChars = true) {
2295
+ const minRequiredLength = includeSpecialChars ? 4 : 3;
2296
+ if (length < minRequiredLength) {
2297
+ throw new Error(`Password length must be at least ${minRequiredLength} characters`);
2298
+ }
2299
+ const lowercase = "abcdefghijklmnopqrstuvwxyz";
2300
+ const uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
2301
+ const digits = "0123456789";
2302
+ const specialChars = "!@#$%^&*()_+-=[]|;:,.<>?";
2303
+ const crypto = globalThis.crypto || require("crypto");
2304
+ const array = new Uint8Array(length);
2305
+ crypto.getRandomValues(array);
2306
+ const allowedChars = includeSpecialChars ? "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
2307
+ let password = Array.from(array, (byte) => allowedChars[byte % allowedChars.length]).join("").slice(0, length);
2308
+ const passwordArray = password.split("");
2309
+ if (!includeSpecialChars) {
2310
+ for (let i = 0; i < passwordArray.length; i++) {
2311
+ if (specialChars.includes(passwordArray[i])) {
2312
+ const alphanumeric = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
2313
+ passwordArray[i] = alphanumeric[Math.floor(Math.random() * alphanumeric.length)];
2314
+ }
2315
+ }
2316
+ }
2317
+ let maxIterations = 10;
2318
+ while (maxIterations-- > 0) {
2319
+ let allRequirementsMet = true;
2320
+ if (!passwordArray.some((c) => lowercase.includes(c))) {
2321
+ const index = Math.floor(Math.random() * passwordArray.length);
2322
+ passwordArray[index] = lowercase[Math.floor(Math.random() * lowercase.length)];
2323
+ allRequirementsMet = false;
2324
+ }
2325
+ if (!passwordArray.some((c) => uppercase.includes(c))) {
2326
+ const index = Math.floor(Math.random() * passwordArray.length);
2327
+ passwordArray[index] = uppercase[Math.floor(Math.random() * uppercase.length)];
2328
+ allRequirementsMet = false;
2329
+ }
2330
+ if (!passwordArray.some((c) => digits.includes(c))) {
2331
+ const index = Math.floor(Math.random() * passwordArray.length);
2332
+ passwordArray[index] = digits[Math.floor(Math.random() * digits.length)];
2333
+ allRequirementsMet = false;
2334
+ }
2335
+ if (includeSpecialChars && !passwordArray.some((c) => specialChars.includes(c))) {
2336
+ const index = Math.floor(Math.random() * passwordArray.length);
2337
+ passwordArray[index] = specialChars[Math.floor(Math.random() * specialChars.length)];
2338
+ allRequirementsMet = false;
2339
+ }
2340
+ if (allRequirementsMet) {
2341
+ break;
2342
+ }
2343
+ }
2344
+ return passwordArray.join("");
2345
+ }
2346
+ };
2347
+
2348
+ // src/personas.ts
2349
+ var NottePersona = class {
2350
+ constructor(client2, options = {}) {
2351
+ this.response = null;
2352
+ this.initPromise = null;
2353
+ this.client = client2;
2354
+ if (options && "persona_id" in options && options.persona_id) {
2355
+ this.initPromise = this.initExistingPersona(options.persona_id);
2356
+ this._initRequest = {};
2357
+ } else {
2358
+ const createData = options || {};
2359
+ this._initRequest = createData;
2360
+ this.initPromise = this.initNewPersona(createData);
2361
+ }
2362
+ }
2363
+ /**
2364
+ * Get persona info
2365
+ */
2366
+ get info() {
2367
+ if (this.response === null) {
2368
+ throw new Error("Persona not initialized");
2369
+ }
2370
+ return this.response;
2371
+ }
2372
+ /**
2373
+ * Get vault (cached property equivalent)
2374
+ */
2375
+ get vault() {
2376
+ if (this._vault === void 0) {
2377
+ const vault = this._getVault();
2378
+ if (vault === null) {
2379
+ throw new Error(
2380
+ "Persona has no vault. Please create a new persona using `create_vault=true` to use this feature."
2381
+ );
2382
+ }
2383
+ this._vault = vault;
2384
+ }
2385
+ return this._vault;
2386
+ }
2387
+ /**
2388
+ * Check if persona has a vault
2389
+ */
2390
+ get hasVault() {
2391
+ return this.info.vault_id !== null;
2392
+ }
2393
+ async initExistingPersona(personaId) {
2394
+ const response = await personaGet({
2395
+ client: this.client.getClient(),
2396
+ path: {
2397
+ persona_id: personaId
2398
+ }
2399
+ });
2400
+ if (response?.error) {
2401
+ throw new Error(`Failed to get persona: ${formatError(response.error)}`);
2402
+ }
2403
+ this.response = response.data;
2404
+ return this.response;
2405
+ }
2406
+ async initNewPersona(createData) {
2407
+ const response = await personaCreate({
2408
+ client: this.client.getClient(),
2409
+ body: createData
2410
+ });
2411
+ if (response?.error) {
2412
+ throw new Error(`Failed to create persona: ${formatError(response.error)}`);
2413
+ }
2414
+ this.response = response.data;
2415
+ console.warn(
2416
+ `[Persona] ${this.response.persona_id} created since no persona id was provided. Please store this to retrieve it later.`
2417
+ );
2418
+ return this.response;
2419
+ }
2420
+ async ensureInitialized() {
2421
+ if (this.response) {
2422
+ return this.response;
2423
+ }
2424
+ if (this.initPromise) {
2425
+ return await this.initPromise;
2426
+ }
2427
+ throw new Error("Persona not initialized");
2428
+ }
2429
+ /**
2430
+ * Get persona ID
2431
+ */
2432
+ get personaId() {
2433
+ if (!this.response) {
2434
+ throw new Error("Persona not initialized. Use await on persona operations first.");
2435
+ }
2436
+ return this.response.persona_id;
2437
+ }
2438
+ /**
2439
+ * Start the persona - ensures initialization
2440
+ */
2441
+ async start() {
2442
+ if (this.response === null) {
2443
+ await this.create();
2444
+ }
2445
+ }
2446
+ /**
2447
+ * Stop the persona - deletes it
2448
+ */
2449
+ async stop() {
2450
+ await this.ensureInitialized();
2451
+ console.log(`[Persona] ${this.personaId} deleted.`);
2452
+ await this.delete();
2453
+ }
2454
+ /**
2455
+ * Get vault - private helper method
2456
+ */
2457
+ _getVault() {
2458
+ if (this.info.vault_id === null) {
2459
+ return null;
2460
+ }
2461
+ return new NotteVault(this.client, { vault_id: this.info.vault_id });
2462
+ }
2463
+ /**
2464
+ * Create the persona
2465
+ */
2466
+ async create() {
2467
+ if (this.response !== null) {
2468
+ throw new Error(`Persona ${this.personaId} already initialized`);
2469
+ }
2470
+ const response = await personaCreate({
2471
+ client: this.client.getClient(),
2472
+ body: this._initRequest
2473
+ });
2474
+ if (response?.error) {
2475
+ throw new Error(`Failed to create persona: ${formatError(response.error)}`);
2476
+ }
2477
+ this.response = response.data;
2478
+ }
2479
+ /**
2480
+ * Delete the persona from the notte console
2481
+ */
2482
+ async delete() {
2483
+ await this.ensureInitialized();
2484
+ const response = await personaDelete({
2485
+ client: this.client.getClient(),
2486
+ path: {
2487
+ persona_id: this.personaId
2488
+ }
2489
+ });
2490
+ if (response?.error) {
2491
+ throw new Error(`Failed to delete persona: ${formatError(response.error)}`);
2492
+ }
2493
+ return response.data;
2494
+ }
2495
+ /**
2496
+ * Add credentials to the persona (generates a password and stores it in the vault)
2497
+ */
2498
+ async addCredentials(url) {
2499
+ const vault = this._getVault();
2500
+ if (vault === null) {
2501
+ throw new Error(
2502
+ "Cannot add credentials to a persona without a vault. Please create a new persona using `create_vault=true` to use this feature."
2503
+ );
2504
+ }
2505
+ const password = vault.generatePassword();
2506
+ await vault.addCredentials(url, {
2507
+ email: this.info.email,
2508
+ password
2509
+ });
2510
+ }
2511
+ /**
2512
+ * Read recent emails sent to the persona
2513
+ */
2514
+ async emails(options) {
2515
+ await this.ensureInitialized();
2516
+ const response = await personaEmailsList({
2517
+ client: this.client.getClient(),
2518
+ path: {
2519
+ persona_id: this.personaId
2520
+ },
2521
+ query: options || {}
2522
+ });
2523
+ if (response?.error) {
2524
+ throw new Error(`Failed to list emails: ${formatError(response.error)}`);
2525
+ }
2526
+ return response.data;
2527
+ }
2528
+ /**
2529
+ * Read recent SMS messages sent to the persona
2530
+ */
2531
+ async sms(options) {
2532
+ await this.ensureInitialized();
2533
+ const response = await personaSmsList({
2534
+ client: this.client.getClient(),
2535
+ path: {
2536
+ persona_id: this.personaId
2537
+ },
2538
+ query: options || {}
2539
+ });
2540
+ if (response?.error) {
2541
+ throw new Error(`Failed to list SMS messages: ${formatError(response.error)}`);
2542
+ }
2543
+ return response.data;
2544
+ }
2545
+ /**
2546
+ * Get persona information (alias for ensureInitialized)
2547
+ */
2548
+ async get() {
2549
+ await this.ensureInitialized();
2550
+ return this.response;
2551
+ }
2552
+ /**
2553
+ * Context manager for automatic cleanup
2554
+ */
2555
+ async use(callback) {
2556
+ try {
2557
+ return await callback(this);
2558
+ } finally {
2559
+ if (this._initRequest && !("persona_id" in this._initRequest)) {
2560
+ try {
2561
+ await this.delete();
2562
+ } catch (error) {
2563
+ console.warn(`Failed to delete persona during cleanup: ${error}`);
2564
+ }
2565
+ }
2566
+ }
2567
+ }
2568
+ };
2569
+
2570
+ // src/version.ts
2571
+ var SDK_VERSION = true ? "0.0.1" : "dev";
2572
+
2573
+ // src/functions.ts
2574
+ var NotteFunction = class {
2575
+ constructor(client2, options) {
2576
+ this.client = client2;
2577
+ this.functionId = options.function_id;
2578
+ this.decryptionKey = options.decryption_key;
2579
+ }
2580
+ /**
2581
+ * Get metadata for a specific function run
2582
+ */
2583
+ async retrieve(functionRunId) {
2584
+ try {
2585
+ const response = await functionRunGetMetadata({
2586
+ client: this.client.getClient(),
2587
+ path: {
2588
+ function_id: this.functionId,
2589
+ run_id: functionRunId
2590
+ }
2591
+ });
2592
+ if (response?.error) {
2593
+ throw new Error(`Failed to get function run metadata: ${formatError(response.error)}`);
2594
+ }
2595
+ return response.data;
2596
+ } catch (error) {
2597
+ if (error instanceof Error && error.message.startsWith("Failed to get function run metadata:")) {
2598
+ throw error;
2599
+ }
2600
+ throw new Error(`Failed to get function run metadata: ${error instanceof Error ? error.message : String(error)}`);
2601
+ }
2602
+ }
2603
+ /**
2604
+ * Start a function run
2605
+ */
2606
+ async run(variables = {}) {
2607
+ const apiKey = this.client.getConfig().apiKey || "";
2608
+ if (!apiKey) {
2609
+ throw new Error("API key is required. Provide it via config.apiKey or set the NOTTE_API_KEY environment variable.");
2610
+ }
2611
+ try {
2612
+ const response = await functionRunStart({
2613
+ client: this.client.getClient(),
2614
+ path: {
2615
+ function_id: this.functionId
2616
+ },
2617
+ headers: {
2618
+ "x-notte-api-key": apiKey,
2619
+ "x-notte-request-origin": "sdk-node",
2620
+ "x-notte-sdk-version": SDK_VERSION
2621
+ },
2622
+ body: {
2623
+ workflow_id: this.functionId,
2624
+ variables,
2625
+ stream: false
2626
+ }
2627
+ });
2628
+ if (response?.error) {
2629
+ throw new Error(`Failed to start function run: ${formatError(response.error)}`);
2630
+ }
2631
+ return response.data;
2632
+ } catch (error) {
2633
+ if (error instanceof Error && error.message.startsWith("Failed to start function run:")) {
2634
+ throw error;
2635
+ }
2636
+ throw new Error(`Failed to run function: ${error instanceof Error ? error.message : String(error)}`);
2637
+ }
2638
+ }
2639
+ /**
2640
+ * Get the function ID
2641
+ */
2642
+ getFunctionId() {
2643
+ return this.functionId;
2644
+ }
2645
+ };
2646
+
2647
+ // src/client.ts
2648
+ var import_zod2 = require("zod");
2649
+ var NotteClient = class {
2650
+ constructor(config = {}) {
2651
+ const apiKey = config.apiKey || process.env.NOTTE_API_KEY;
2652
+ const isProxyMode = config.baseUrl && !config.baseUrl.startsWith("https://");
2653
+ if (!apiKey && !isProxyMode) {
2654
+ throw new Error("API key is required. Provide it via config.apiKey or set the NOTTE_API_KEY environment variable.");
2655
+ }
2656
+ this.config = {
2657
+ baseUrl: config.baseUrl || "https://api.notte.cc",
2658
+ apiKey,
2659
+ ...config
2660
+ };
2661
+ client.setConfig({
2662
+ baseUrl: this.config.baseUrl
2663
+ });
2664
+ client.interceptors.request.use((request) => {
2665
+ request.headers.set("Authorization", `Bearer ${this.config.apiKey}`);
2666
+ request.headers.set("x-notte-request-origin", "sdk-node");
2667
+ request.headers.set("x-notte-sdk-version", SDK_VERSION);
2668
+ return request;
2669
+ });
2670
+ }
2671
+ /**
2672
+ * Create a new session
2673
+ */
2674
+ Session(options = {}) {
2675
+ return new Session(this, options);
2676
+ }
2677
+ /**
2678
+ * Create a new agent
2679
+ */
2680
+ Agent(options) {
2681
+ return new Agent(this, options);
2682
+ }
2683
+ /**
2684
+ * Create or access a vault
2685
+ */
2686
+ Vault(options) {
2687
+ return new NotteVault(this, options);
2688
+ }
2689
+ /**
2690
+ * Create or access a persona
2691
+ */
2692
+ Persona(options) {
2693
+ return new NottePersona(this, options);
2694
+ }
2695
+ /**
2696
+ * Create or access a function
2697
+ */
2698
+ NotteFunction(options) {
2699
+ return new NotteFunction(this, options);
2700
+ }
2701
+ /**
2702
+ * Personas client for listing and managing personas
2703
+ */
2704
+ get personas() {
2705
+ return {
2706
+ list: async (options) => {
2707
+ const response = await listPersonas({
2708
+ client: this.getClient(),
2709
+ query: options || {}
2710
+ });
2711
+ if (response?.error) {
2712
+ throw new Error(`Failed to list personas: ${JSON.stringify(response.error)}`);
2713
+ }
2714
+ return response.data?.items || [];
2715
+ }
2716
+ };
2717
+ }
2718
+ /**
2719
+ * Get the configured client instance
2720
+ */
2721
+ getClient() {
2722
+ return client;
2723
+ }
2724
+ async scrape(url, options = {}) {
2725
+ const apiOptions = { ...options };
2726
+ if (options.response_format && typeof options.response_format.parse === "function") {
2727
+ if (options.json_schema) {
2728
+ apiOptions.response_format = options.json_schema;
2729
+ } else {
2730
+ apiOptions.response_format = import_zod2.z.toJSONSchema(options.response_format);
2731
+ }
2732
+ if (!apiOptions.instructions) {
2733
+ const schemaStr = JSON.stringify(apiOptions.response_format);
2734
+ if (schemaStr.includes("plans") || schemaStr.includes("plan")) {
2735
+ apiOptions.instructions = "Extract pricing plans from the page";
2736
+ } else if (schemaStr.includes("products") || schemaStr.includes("product")) {
2737
+ apiOptions.instructions = "Extract product information from the page";
2738
+ } else if (schemaStr.includes("articles") || schemaStr.includes("article")) {
2739
+ apiOptions.instructions = "Extract article information from the page";
2740
+ } else {
2741
+ apiOptions.instructions = "Extract structured data from the page based on the provided schema";
2742
+ }
2743
+ }
2744
+ }
2745
+ const response = await scrapeWebpage({
2746
+ client: this.getClient(),
2747
+ body: {
2748
+ url,
2749
+ ...apiOptions
2750
+ }
2751
+ });
2752
+ if (response?.error) {
2753
+ throw new Error(`Failed to scrape webpage: ${JSON.stringify(response.error)}`);
2754
+ }
2755
+ const scrapeResponse = response.data;
2756
+ return processScrapeResponse(scrapeResponse, options);
2757
+ }
2758
+ /**
2759
+ * Get the client configuration
2760
+ */
2761
+ getConfig() {
2762
+ return this.config;
2763
+ }
2764
+ };
2765
+
2766
+ // src/proxy/types.ts
2767
+ var NotteProxyAuthError = class extends Error {
2768
+ constructor(message = "Unauthorized") {
2769
+ super(message);
2770
+ this.name = "NotteProxyAuthError";
2771
+ }
2772
+ };
2773
+
2774
+ // src/index.ts
2775
+ var createClient2 = (config) => {
2776
+ if (config?.baseUrl) {
2777
+ client.setConfig({ baseUrl: config.baseUrl });
2778
+ }
2779
+ if (config?.token) {
2780
+ client.interceptors.request.use((request) => {
2781
+ request.headers.set("Authorization", `Bearer ${config.token}`);
2782
+ return request;
2783
+ });
2784
+ }
2785
+ return client;
2786
+ };
2787
+ // Annotate the CommonJS export names for ESM import in node:
2788
+ 0 && (module.exports = {
2789
+ Agent,
2790
+ NotteClient,
2791
+ NotteFunction,
2792
+ NottePersona,
2793
+ NotteProxyAuthError,
2794
+ NotteVault,
2795
+ Session,
2796
+ agentStart,
2797
+ agentStatus,
2798
+ agentStop,
2799
+ anythingStart,
2800
+ client,
2801
+ createClient,
2802
+ fileDownload,
2803
+ fileListDownloads,
2804
+ fileListUploads,
2805
+ fileUpload,
2806
+ fileUploadDownloadedFile,
2807
+ functionCreate,
2808
+ functionDelete,
2809
+ functionDownloadUrl,
2810
+ functionFork,
2811
+ functionRunGetMetadata,
2812
+ functionRunStart,
2813
+ functionRunStop,
2814
+ functionRunUpdateMetadata,
2815
+ functionScheduleDelete,
2816
+ functionScheduleSet,
2817
+ functionUpdate,
2818
+ getScript,
2819
+ getSessionScript,
2820
+ getUsage,
2821
+ getUsageLogs,
2822
+ healthCheck,
2823
+ improvePrompt,
2824
+ listAgents,
2825
+ listFunctionRunsByFunctionId,
2826
+ listFunctions,
2827
+ listPersonas,
2828
+ listSessions,
2829
+ listVaults,
2830
+ nudgePrompt,
2831
+ pageExecute,
2832
+ pageObserve,
2833
+ pageScrape,
2834
+ pageScreenshot,
2835
+ personaCreate,
2836
+ personaDelete,
2837
+ personaEmailsList,
2838
+ personaGet,
2839
+ personaSmsList,
2840
+ profileCreate,
2841
+ profileDelete,
2842
+ profileGet,
2843
+ profileList,
2844
+ scrapeFromHtml,
2845
+ scrapeWebpage,
2846
+ sessionCookiesGet,
2847
+ sessionCookiesSet,
2848
+ sessionDebugInfo,
2849
+ sessionNetworkLogs,
2850
+ sessionOffset,
2851
+ sessionReplay,
2852
+ sessionStart,
2853
+ sessionStatus,
2854
+ sessionStop,
2855
+ vaultCreate,
2856
+ vaultCredentialsAdd,
2857
+ vaultCredentialsDelete,
2858
+ vaultCredentialsGet,
2859
+ vaultCredentialsList,
2860
+ vaultCreditCardDelete,
2861
+ vaultCreditCardGet,
2862
+ vaultCreditCardSet,
2863
+ vaultDelete,
2864
+ vaultUpdate
2865
+ });
2866
+ //# sourceMappingURL=index.js.map