agi 0.2.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,946 @@
1
+ import { createParser } from 'eventsource-parser';
2
+
3
+ // src/http.ts
4
+
5
+ // src/errors.ts
6
+ var AGIError = class _AGIError extends Error {
7
+ constructor(message, statusCode, response) {
8
+ super(message);
9
+ this.statusCode = statusCode;
10
+ this.response = response;
11
+ this.name = "AGIError";
12
+ Object.setPrototypeOf(this, _AGIError.prototype);
13
+ }
14
+ };
15
+ var AuthenticationError = class _AuthenticationError extends AGIError {
16
+ constructor(message, response) {
17
+ super(message, 401, response);
18
+ this.name = "AuthenticationError";
19
+ Object.setPrototypeOf(this, _AuthenticationError.prototype);
20
+ }
21
+ };
22
+ var NotFoundError = class _NotFoundError extends AGIError {
23
+ constructor(message, response) {
24
+ super(message, 404, response);
25
+ this.name = "NotFoundError";
26
+ Object.setPrototypeOf(this, _NotFoundError.prototype);
27
+ }
28
+ };
29
+ var RateLimitError = class _RateLimitError extends AGIError {
30
+ constructor(message, response) {
31
+ super(message, 429, response);
32
+ this.name = "RateLimitError";
33
+ Object.setPrototypeOf(this, _RateLimitError.prototype);
34
+ }
35
+ };
36
+ var AgentExecutionError = class _AgentExecutionError extends AGIError {
37
+ constructor(message, response) {
38
+ super(message, void 0, response);
39
+ this.name = "AgentExecutionError";
40
+ Object.setPrototypeOf(this, _AgentExecutionError.prototype);
41
+ }
42
+ };
43
+ var ValidationError = class _ValidationError extends AGIError {
44
+ constructor(message, response) {
45
+ super(message, 422, response);
46
+ this.name = "ValidationError";
47
+ Object.setPrototypeOf(this, _ValidationError.prototype);
48
+ }
49
+ };
50
+ var PermissionError = class _PermissionError extends AGIError {
51
+ constructor(message, response) {
52
+ super(message, 403, response);
53
+ this.name = "PermissionError";
54
+ Object.setPrototypeOf(this, _PermissionError.prototype);
55
+ }
56
+ };
57
+ var APIError = class _APIError extends AGIError {
58
+ constructor(message, statusCode, response) {
59
+ super(message, statusCode, response);
60
+ this.name = "APIError";
61
+ Object.setPrototypeOf(this, _APIError.prototype);
62
+ }
63
+ };
64
+
65
+ // src/http.ts
66
+ var HTTPClient = class {
67
+ apiKey;
68
+ baseUrl;
69
+ timeout;
70
+ maxRetries;
71
+ constructor(options) {
72
+ this.apiKey = options.apiKey;
73
+ this.baseUrl = options.baseUrl ?? "https://api.agi.tech";
74
+ this.timeout = options.timeout ?? 6e4;
75
+ this.maxRetries = options.maxRetries ?? 3;
76
+ }
77
+ /**
78
+ * Make an HTTP request with retries and error handling
79
+ */
80
+ async request(method, path, options) {
81
+ const url = this.buildUrl(path, options?.query);
82
+ const headers = this.buildHeaders(options?.headers);
83
+ let lastError;
84
+ for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
85
+ try {
86
+ const controller = new AbortController();
87
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
88
+ const response = await fetch(url, {
89
+ method,
90
+ headers,
91
+ body: options?.json ? JSON.stringify(options.json) : void 0,
92
+ signal: controller.signal
93
+ });
94
+ clearTimeout(timeoutId);
95
+ if (!response.ok) {
96
+ await this.handleErrorResponse(response);
97
+ }
98
+ const data = await response.json();
99
+ return data;
100
+ } catch (error) {
101
+ lastError = error;
102
+ if (error instanceof AGIError && error.statusCode && error.statusCode < 500) {
103
+ if (error.statusCode !== 429) {
104
+ throw error;
105
+ }
106
+ }
107
+ if (attempt === this.maxRetries) {
108
+ break;
109
+ }
110
+ await this.sleep(Math.pow(2, attempt) * 1e3);
111
+ }
112
+ }
113
+ throw lastError || new AGIError("Request failed after retries");
114
+ }
115
+ /**
116
+ * Stream Server-Sent Events from an endpoint
117
+ */
118
+ async *streamEvents(path, query) {
119
+ const url = this.buildUrl(path, query);
120
+ const headers = this.buildHeaders();
121
+ const controller = new AbortController();
122
+ const response = await fetch(url, {
123
+ method: "GET",
124
+ headers: {
125
+ ...headers,
126
+ Accept: "text/event-stream"
127
+ },
128
+ signal: controller.signal
129
+ });
130
+ if (!response.ok) {
131
+ await this.handleErrorResponse(response);
132
+ }
133
+ if (!response.body) {
134
+ throw new AGIError("Response body is null");
135
+ }
136
+ const reader = response.body.getReader();
137
+ const decoder = new TextDecoder();
138
+ let buffer = "";
139
+ const parser = createParser((event) => {
140
+ if (event.type === "event") {
141
+ try {
142
+ const data = JSON.parse(event.data);
143
+ this.pendingEvents.push({
144
+ id: event.id,
145
+ event: event.event,
146
+ data
147
+ });
148
+ } catch {
149
+ }
150
+ }
151
+ });
152
+ const pendingEvents = [];
153
+ this.pendingEvents = pendingEvents;
154
+ try {
155
+ while (true) {
156
+ const { done, value } = await reader.read();
157
+ if (done) {
158
+ break;
159
+ }
160
+ buffer += decoder.decode(value, { stream: true });
161
+ parser.feed(buffer);
162
+ buffer = "";
163
+ while (pendingEvents.length > 0) {
164
+ const event = pendingEvents.shift();
165
+ if (event) {
166
+ yield event;
167
+ }
168
+ }
169
+ }
170
+ } finally {
171
+ controller.abort();
172
+ reader.releaseLock();
173
+ }
174
+ }
175
+ pendingEvents = [];
176
+ buildUrl(path, query) {
177
+ const url = new URL(path, this.baseUrl);
178
+ if (query) {
179
+ Object.entries(query).forEach(([key, value]) => {
180
+ url.searchParams.append(key, value);
181
+ });
182
+ }
183
+ return url.toString();
184
+ }
185
+ buildHeaders(additional) {
186
+ return {
187
+ "Content-Type": "application/json",
188
+ Authorization: `Bearer ${this.apiKey}`,
189
+ "User-Agent": "agi-sdk-node/1.0.0",
190
+ ...additional
191
+ };
192
+ }
193
+ async handleErrorResponse(response) {
194
+ let errorData;
195
+ try {
196
+ errorData = await response.json();
197
+ } catch {
198
+ errorData = await response.text();
199
+ }
200
+ const errorMessage = typeof errorData === "object" && errorData.message ? errorData.message : typeof errorData === "string" ? errorData : `HTTP ${response.status}: ${response.statusText}`;
201
+ switch (response.status) {
202
+ case 401:
203
+ throw new AuthenticationError(`Authentication failed: ${errorMessage}`, errorData);
204
+ case 403:
205
+ throw new PermissionError(`Permission denied: ${errorMessage}`, errorData);
206
+ case 404:
207
+ throw new NotFoundError(`Resource not found: ${errorMessage}`, errorData);
208
+ case 422:
209
+ throw new ValidationError(`Validation error: ${errorMessage}`, errorData);
210
+ case 429:
211
+ throw new RateLimitError(`Rate limit exceeded: ${errorMessage}`, errorData);
212
+ default:
213
+ if (response.status >= 500) {
214
+ throw new APIError(
215
+ `Server error (${response.status}): ${errorMessage}`,
216
+ response.status,
217
+ errorData
218
+ );
219
+ }
220
+ throw new AGIError(
221
+ `API error (${response.status}): ${errorMessage}`,
222
+ response.status,
223
+ errorData
224
+ );
225
+ }
226
+ }
227
+ sleep(ms) {
228
+ return new Promise((resolve) => setTimeout(resolve, ms));
229
+ }
230
+ };
231
+
232
+ // src/types/screenshot.ts
233
+ var Screenshot = class _Screenshot {
234
+ constructor(data, format, timestamp, width, height, url, title) {
235
+ this.data = data;
236
+ this.format = format;
237
+ this.timestamp = timestamp;
238
+ this.width = width;
239
+ this.height = height;
240
+ this.url = url;
241
+ this.title = title;
242
+ }
243
+ /**
244
+ * Save screenshot to file
245
+ *
246
+ * @param path - File path to save to (e.g., "screenshot.png")
247
+ *
248
+ * @example
249
+ * ```typescript
250
+ * const screenshot = await session.screenshot();
251
+ * await screenshot.save("amazon.png");
252
+ * ```
253
+ */
254
+ async save(path) {
255
+ const fs = await import('fs/promises');
256
+ await fs.writeFile(path, this.data);
257
+ }
258
+ /**
259
+ * Create Screenshot from base64 data URL
260
+ *
261
+ * @param base64Data - Base64-encoded data URL (e.g., "data:image/jpeg;base64,...")
262
+ * @param url - Current page URL
263
+ * @param title - Current page title
264
+ * @param timestamp - Screenshot timestamp (defaults to now)
265
+ * @returns Screenshot instance with decoded image data
266
+ */
267
+ static fromBase64(base64Data, url, title, timestamp) {
268
+ let header;
269
+ let encoded;
270
+ if (base64Data.includes(",")) {
271
+ [header, encoded] = base64Data.split(",", 2);
272
+ } else {
273
+ encoded = base64Data;
274
+ header = "data:image/png;base64";
275
+ }
276
+ const imageData = Buffer.from(encoded, "base64");
277
+ const format = header.toLowerCase().includes("jpeg") || header.toLowerCase().includes("jpg") ? "jpg" : "png";
278
+ const { width, height } = _Screenshot.getImageDimensions(imageData, format);
279
+ return new _Screenshot(imageData, format, timestamp || /* @__PURE__ */ new Date(), width, height, url, title);
280
+ }
281
+ /**
282
+ * Extract width and height from image data
283
+ *
284
+ * @param data - Raw image bytes
285
+ * @param format - Image format (png, jpg)
286
+ * @returns Tuple of (width, height)
287
+ */
288
+ static getImageDimensions(data, format) {
289
+ try {
290
+ if (format === "png" && data.length >= 24) {
291
+ const width = data.readUInt32BE(16);
292
+ const height = data.readUInt32BE(20);
293
+ return { width, height };
294
+ } else if (format === "jpg") {
295
+ for (let i = 0; i < data.length - 9; i++) {
296
+ if (data[i] === 255 && data[i + 1] === 192) {
297
+ const height = data.readUInt16BE(i + 5);
298
+ const width = data.readUInt16BE(i + 7);
299
+ return { width, height };
300
+ }
301
+ }
302
+ }
303
+ } catch (error) {
304
+ }
305
+ return { width: 0, height: 0 };
306
+ }
307
+ };
308
+
309
+ // src/context/session-context.ts
310
+ var SessionContext = class {
311
+ constructor(client, agentName = "agi-0", createOptions) {
312
+ this.client = client;
313
+ this.agentName = agentName;
314
+ this.createOptions = createOptions;
315
+ }
316
+ sessionId;
317
+ vncUrl;
318
+ agentUrl;
319
+ /**
320
+ * Automatic cleanup via explicit resource management
321
+ */
322
+ async [Symbol.asyncDispose]() {
323
+ if (this.sessionId) {
324
+ try {
325
+ await this.client.sessions.delete(this.sessionId);
326
+ } catch (error) {
327
+ }
328
+ }
329
+ }
330
+ /**
331
+ * Ensure session is created
332
+ */
333
+ async ensureSession() {
334
+ if (this.sessionId) return;
335
+ const response = await this.client.sessions.create(this.agentName, this.createOptions);
336
+ this.sessionId = response.sessionId;
337
+ this.vncUrl = response.vncUrl;
338
+ this.agentUrl = response.agentUrl;
339
+ }
340
+ /**
341
+ * Run a task and wait for completion using HTTP polling
342
+ *
343
+ * This method uses HTTP polling instead of SSE streaming for better reliability
344
+ * with long-running tasks and network instability.
345
+ *
346
+ * @param task - Natural language task description
347
+ * @param options - Task execution options
348
+ * @returns TaskResult with data and execution metadata
349
+ *
350
+ * @example
351
+ * ```typescript
352
+ * const result = await session.runTask(
353
+ * 'Find cheapest iPhone 15 Pro',
354
+ * { timeout: 300000, pollInterval: 2000 } // 5 min timeout, 2s polling
355
+ * );
356
+ * console.log(result.data);
357
+ * console.log(`Took ${result.metadata.duration}s, ${result.metadata.steps} steps`);
358
+ * ```
359
+ */
360
+ async runTask(task, options) {
361
+ await this.ensureSession();
362
+ if (!this.sessionId) throw new Error("Session not created");
363
+ const timeout = options?.timeout ?? 6e5;
364
+ const pollInterval = options?.pollInterval ?? 3e3;
365
+ await this.client.sessions.sendMessage(this.sessionId, task, {
366
+ startUrl: options?.startUrl
367
+ });
368
+ const startTime = Date.now();
369
+ while (true) {
370
+ const elapsed = Date.now() - startTime;
371
+ if (elapsed > timeout) {
372
+ throw new AgentExecutionError(
373
+ `Task exceeded timeout of ${timeout}ms (elapsed: ${elapsed}ms)`
374
+ );
375
+ }
376
+ const statusResponse = await this.client.sessions.getStatus(this.sessionId);
377
+ if (statusResponse.status === "finished" || statusResponse.status === "waiting_for_input") {
378
+ const messagesResponse = await this.client.sessions.getMessages(this.sessionId);
379
+ const messages = messagesResponse.messages;
380
+ const doneMsg = messages.find((msg) => msg.type === "DONE" || msg.type === "QUESTION");
381
+ if (!doneMsg) {
382
+ throw new AgentExecutionError(
383
+ `Task status '${statusResponse.status}' but no DONE/QUESTION message found`
384
+ );
385
+ }
386
+ const content = doneMsg.content;
387
+ const data = typeof content === "object" && content !== null ? content : { content: content ?? {} };
388
+ const duration = (Date.now() - startTime) / 1e3;
389
+ const steps = messages.filter(
390
+ (msg) => ["THOUGHT", "QUESTION", "DONE"].includes(msg.type)
391
+ ).length;
392
+ const metadata = {
393
+ taskId: doneMsg.id,
394
+ sessionId: this.sessionId,
395
+ duration,
396
+ cost: 0,
397
+ timestamp: /* @__PURE__ */ new Date(),
398
+ steps,
399
+ success: true
400
+ };
401
+ return { data, metadata };
402
+ }
403
+ if (statusResponse.status === "error") {
404
+ const messagesResponse = await this.client.sessions.getMessages(this.sessionId);
405
+ const errorMsg = messagesResponse.messages.find((msg) => msg.type === "ERROR");
406
+ const errorDetails = errorMsg ? typeof errorMsg.content === "string" ? errorMsg.content : JSON.stringify(errorMsg.content) : "Unknown error";
407
+ throw new AgentExecutionError(`Task failed: ${errorDetails}`);
408
+ }
409
+ await new Promise((resolve) => setTimeout(resolve, pollInterval));
410
+ }
411
+ }
412
+ /**
413
+ * Send a message to the agent
414
+ *
415
+ * @param message - Message content
416
+ * @param options - Message options
417
+ * @returns SuccessResponse confirming message was sent
418
+ *
419
+ * @example
420
+ * ```typescript
421
+ * await session.sendMessage('Find flights from SFO to JFK under $450');
422
+ * ```
423
+ */
424
+ async sendMessage(message, options) {
425
+ await this.ensureSession();
426
+ if (!this.sessionId) throw new Error("Session not created");
427
+ return this.client.sessions.sendMessage(this.sessionId, message, options);
428
+ }
429
+ /**
430
+ * Get current execution status
431
+ *
432
+ * @returns ExecuteStatusResponse with status
433
+ *
434
+ * @example
435
+ * ```typescript
436
+ * const status = await session.getStatus();
437
+ * console.log(status.status);
438
+ * ```
439
+ */
440
+ async getStatus() {
441
+ await this.ensureSession();
442
+ if (!this.sessionId) throw new Error("Session not created");
443
+ return this.client.sessions.getStatus(this.sessionId);
444
+ }
445
+ /**
446
+ * Get messages from the session
447
+ *
448
+ * @param afterId - Return messages with ID > afterId (for polling)
449
+ * @param sanitize - Filter out system messages, prompts, and images
450
+ * @returns MessagesResponse with messages list and status
451
+ *
452
+ * @example
453
+ * ```typescript
454
+ * const messages = await session.getMessages(0);
455
+ * for (const msg of messages.messages) {
456
+ * console.log(`[${msg.type}] ${msg.content}`);
457
+ * }
458
+ * ```
459
+ */
460
+ async getMessages(afterId, sanitize = true) {
461
+ await this.ensureSession();
462
+ if (!this.sessionId) throw new Error("Session not created");
463
+ return this.client.sessions.getMessages(this.sessionId, afterId, sanitize);
464
+ }
465
+ /**
466
+ * Stream real-time events from the session via Server-Sent Events
467
+ *
468
+ * @param options - Stream options
469
+ * @yields SSEEvent objects
470
+ *
471
+ * @example
472
+ * ```typescript
473
+ * for await (const event of session.streamEvents()) {
474
+ * if (event.event === 'thought') {
475
+ * console.log('Agent:', event.data);
476
+ * }
477
+ * if (event.event === 'done') {
478
+ * console.log('Result:', event.data);
479
+ * break;
480
+ * }
481
+ * }
482
+ * ```
483
+ */
484
+ async *streamEvents(options) {
485
+ await this.ensureSession();
486
+ if (!this.sessionId) throw new Error("Session not created");
487
+ yield* this.client.sessions.streamEvents(this.sessionId, options);
488
+ }
489
+ /**
490
+ * Pause task execution
491
+ *
492
+ * @returns SuccessResponse confirming pause
493
+ *
494
+ * @example
495
+ * ```typescript
496
+ * await session.pause();
497
+ * ```
498
+ */
499
+ async pause() {
500
+ await this.ensureSession();
501
+ if (!this.sessionId) throw new Error("Session not created");
502
+ return this.client.sessions.pause(this.sessionId);
503
+ }
504
+ /**
505
+ * Resume paused task
506
+ *
507
+ * @returns SuccessResponse confirming resume
508
+ *
509
+ * @example
510
+ * ```typescript
511
+ * await session.resume();
512
+ * ```
513
+ */
514
+ async resume() {
515
+ await this.ensureSession();
516
+ if (!this.sessionId) throw new Error("Session not created");
517
+ return this.client.sessions.resume(this.sessionId);
518
+ }
519
+ /**
520
+ * Cancel task execution
521
+ *
522
+ * @returns SuccessResponse confirming cancellation
523
+ *
524
+ * @example
525
+ * ```typescript
526
+ * await session.cancel();
527
+ * ```
528
+ */
529
+ async cancel() {
530
+ await this.ensureSession();
531
+ if (!this.sessionId) throw new Error("Session not created");
532
+ return this.client.sessions.cancel(this.sessionId);
533
+ }
534
+ /**
535
+ * Navigate browser to URL
536
+ *
537
+ * @param url - URL to navigate to
538
+ * @returns NavigateResponse with current URL
539
+ *
540
+ * @example
541
+ * ```typescript
542
+ * await session.navigate('https://amazon.com');
543
+ * ```
544
+ */
545
+ async navigate(url) {
546
+ await this.ensureSession();
547
+ if (!this.sessionId) throw new Error("Session not created");
548
+ return this.client.sessions.navigate(this.sessionId, url);
549
+ }
550
+ /**
551
+ * Get browser screenshot
552
+ *
553
+ * @returns Screenshot with decoded image data and save() method
554
+ *
555
+ * @example
556
+ * ```typescript
557
+ * const screenshot = await session.screenshot();
558
+ * await screenshot.save('page.png');
559
+ * console.log(`Size: ${screenshot.width}x${screenshot.height}`);
560
+ * ```
561
+ */
562
+ async screenshot() {
563
+ await this.ensureSession();
564
+ if (!this.sessionId) throw new Error("Session not created");
565
+ const response = await this.client.sessions.screenshot(this.sessionId);
566
+ return Screenshot.fromBase64(response.screenshot, response.url, response.title);
567
+ }
568
+ };
569
+
570
+ // src/utils.ts
571
+ function normalizeSessionResponse(data) {
572
+ return {
573
+ sessionId: data.session_id ?? data.sessionId,
574
+ vncUrl: data.vnc_url ?? data.vncUrl,
575
+ agentUrl: data.agent_url ?? data.agentUrl,
576
+ agentName: data.agent_name ?? data.agentName,
577
+ status: data.status,
578
+ createdAt: data.created_at ?? data.createdAt,
579
+ environmentId: data.environment_id ?? data.environmentId,
580
+ goal: data.goal
581
+ };
582
+ }
583
+
584
+ // src/resources/sessions.ts
585
+ var SessionsResource = class {
586
+ constructor(http) {
587
+ this.http = http;
588
+ }
589
+ // ===== SESSION MANAGEMENT =====
590
+ /**
591
+ * Create a new agent session
592
+ *
593
+ * @param agentName - Agent model to use (e.g., "agi-0", "agi-0-fast", "agi-1")
594
+ * @param options - Session creation options
595
+ * @returns SessionResponse with session_id, vnc_url, status, etc.
596
+ *
597
+ * @example
598
+ * ```typescript
599
+ * const session = await client.sessions.create('agi-0', {
600
+ * webhookUrl: 'https://yourapp.com/webhook',
601
+ * maxSteps: 200
602
+ * });
603
+ * ```
604
+ */
605
+ async create(agentName = "agi-0", options) {
606
+ const payload = {
607
+ agent_name: agentName,
608
+ max_steps: options?.maxSteps ?? 100
609
+ };
610
+ if (options?.webhookUrl) payload.webhook_url = options.webhookUrl;
611
+ if (options?.goal) payload.goal = options.goal;
612
+ if (options?.restoreFromEnvironmentId) {
613
+ payload.restore_from_environment_id = options.restoreFromEnvironmentId;
614
+ }
615
+ const response = await this.http.request("POST", "/v1/sessions", {
616
+ json: payload
617
+ });
618
+ return normalizeSessionResponse(response);
619
+ }
620
+ /**
621
+ * List all sessions for the authenticated user
622
+ *
623
+ * @returns Array of SessionResponse objects
624
+ *
625
+ * @example
626
+ * ```typescript
627
+ * const sessions = await client.sessions.list();
628
+ * for (const session of sessions) {
629
+ * console.log(`${session.sessionId}: ${session.status}`);
630
+ * }
631
+ * ```
632
+ */
633
+ async list() {
634
+ const responses = await this.http.request(
635
+ "GET",
636
+ "/v1/sessions"
637
+ );
638
+ return responses.map(normalizeSessionResponse);
639
+ }
640
+ /**
641
+ * Get details for a specific session
642
+ *
643
+ * @param sessionId - Session UUID
644
+ * @returns SessionResponse with session details
645
+ *
646
+ * @example
647
+ * ```typescript
648
+ * const session = await client.sessions.get('session-uuid');
649
+ * console.log(session.status);
650
+ * ```
651
+ */
652
+ async get(sessionId) {
653
+ const response = await this.http.request(
654
+ "GET",
655
+ `/v1/sessions/${sessionId}`
656
+ );
657
+ return normalizeSessionResponse(response);
658
+ }
659
+ /**
660
+ * Delete a session and cleanup its resources
661
+ *
662
+ * @param sessionId - Session UUID
663
+ * @param saveSnapshotMode - Snapshot mode: "none", "memory", or "filesystem"
664
+ * @returns DeleteResponse confirming deletion
665
+ *
666
+ * @example
667
+ * ```typescript
668
+ * await client.sessions.delete('session-uuid', 'filesystem');
669
+ * ```
670
+ */
671
+ async delete(sessionId, saveSnapshotMode = "none") {
672
+ return this.http.request("DELETE", `/v1/sessions/${sessionId}`, {
673
+ query: { save_snapshot_mode: saveSnapshotMode }
674
+ });
675
+ }
676
+ /**
677
+ * Delete all sessions for the authenticated user
678
+ *
679
+ * @returns DeleteResponse with count of deleted sessions
680
+ *
681
+ * @example
682
+ * ```typescript
683
+ * const result = await client.sessions.deleteAll();
684
+ * console.log(result.message);
685
+ * ```
686
+ */
687
+ async deleteAll() {
688
+ return this.http.request("DELETE", "/v1/sessions");
689
+ }
690
+ // ===== AGENT INTERACTION =====
691
+ /**
692
+ * Send a message to the agent to start a task or respond to questions
693
+ *
694
+ * @param sessionId - Session UUID
695
+ * @param message - Message content (task instruction or response)
696
+ * @param options - Message options
697
+ * @returns SuccessResponse confirming message was sent
698
+ *
699
+ * @example
700
+ * ```typescript
701
+ * await client.sessions.sendMessage(
702
+ * 'session-uuid',
703
+ * 'Find flights from SFO to JFK under $450'
704
+ * );
705
+ * ```
706
+ */
707
+ async sendMessage(sessionId, message, options) {
708
+ return this.http.request("POST", `/v1/sessions/${sessionId}/message`, {
709
+ json: {
710
+ message,
711
+ start_url: options?.startUrl,
712
+ config_updates: options?.configUpdates
713
+ }
714
+ });
715
+ }
716
+ /**
717
+ * Get the current execution status of a session
718
+ *
719
+ * @param sessionId - Session UUID
720
+ * @returns ExecuteStatusResponse with status
721
+ *
722
+ * @example
723
+ * ```typescript
724
+ * const status = await client.sessions.getStatus('session-uuid');
725
+ * if (status.status === 'finished') {
726
+ * console.log('Task completed!');
727
+ * }
728
+ * ```
729
+ */
730
+ async getStatus(sessionId) {
731
+ return this.http.request("GET", `/v1/sessions/${sessionId}/status`);
732
+ }
733
+ /**
734
+ * Poll for messages and updates from the agent
735
+ *
736
+ * @param sessionId - Session UUID
737
+ * @param afterId - Return messages with ID > afterId (for polling)
738
+ * @param sanitize - Filter out system messages, prompts, and images
739
+ * @returns MessagesResponse with messages list and status
740
+ *
741
+ * @example
742
+ * ```typescript
743
+ * const messages = await client.sessions.getMessages('session-uuid', 0);
744
+ * for (const msg of messages.messages) {
745
+ * console.log(`[${msg.type}] ${msg.content}`);
746
+ * }
747
+ * ```
748
+ */
749
+ async getMessages(sessionId, afterId = 0, sanitize = true) {
750
+ const response = await this.http.request(
751
+ "GET",
752
+ `/v1/sessions/${sessionId}/messages`,
753
+ {
754
+ query: {
755
+ after_id: String(afterId),
756
+ sanitize: String(sanitize)
757
+ }
758
+ }
759
+ );
760
+ return {
761
+ messages: response.messages || [],
762
+ status: response.status,
763
+ hasAgent: response.has_agent ?? response.hasAgent ?? false
764
+ };
765
+ }
766
+ /**
767
+ * Stream real-time events from the session via Server-Sent Events
768
+ *
769
+ * @param sessionId - Session UUID
770
+ * @param options - Stream options
771
+ * @yields SSEEvent objects
772
+ *
773
+ * @example
774
+ * ```typescript
775
+ * for await (const event of client.sessions.streamEvents('session-uuid')) {
776
+ * if (event.event === 'thought') {
777
+ * console.log('Agent:', event.data);
778
+ * }
779
+ * if (event.event === 'done') {
780
+ * console.log('Result:', event.data);
781
+ * break;
782
+ * }
783
+ * }
784
+ * ```
785
+ */
786
+ async *streamEvents(sessionId, options) {
787
+ const query = {
788
+ sanitize: String(options?.sanitize ?? true),
789
+ include_history: String(options?.includeHistory ?? true)
790
+ };
791
+ if (options?.eventTypes) {
792
+ query.event_types = options.eventTypes.join(",");
793
+ }
794
+ yield* this.http.streamEvents(`/v1/sessions/${sessionId}/events`, query);
795
+ }
796
+ // ===== SESSION CONTROL =====
797
+ /**
798
+ * Temporarily pause task execution
799
+ *
800
+ * @param sessionId - Session UUID
801
+ * @returns SuccessResponse confirming pause
802
+ *
803
+ * @example
804
+ * ```typescript
805
+ * await client.sessions.pause('session-uuid');
806
+ * ```
807
+ */
808
+ async pause(sessionId) {
809
+ return this.http.request("POST", `/v1/sessions/${sessionId}/pause`);
810
+ }
811
+ /**
812
+ * Resume a paused task
813
+ *
814
+ * @param sessionId - Session UUID
815
+ * @returns SuccessResponse confirming resume
816
+ *
817
+ * @example
818
+ * ```typescript
819
+ * await client.sessions.resume('session-uuid');
820
+ * ```
821
+ */
822
+ async resume(sessionId) {
823
+ return this.http.request("POST", `/v1/sessions/${sessionId}/resume`);
824
+ }
825
+ /**
826
+ * Cancel task execution
827
+ *
828
+ * @param sessionId - Session UUID
829
+ * @returns SuccessResponse confirming cancellation
830
+ *
831
+ * @example
832
+ * ```typescript
833
+ * await client.sessions.cancel('session-uuid');
834
+ * ```
835
+ */
836
+ async cancel(sessionId) {
837
+ return this.http.request("POST", `/v1/sessions/${sessionId}/cancel`);
838
+ }
839
+ // ===== BROWSER CONTROL =====
840
+ /**
841
+ * Navigate the browser to a specific URL
842
+ *
843
+ * @param sessionId - Session UUID
844
+ * @param url - URL to navigate to
845
+ * @returns NavigateResponse with current URL
846
+ *
847
+ * @example
848
+ * ```typescript
849
+ * await client.sessions.navigate('session-uuid', 'https://amazon.com');
850
+ * ```
851
+ */
852
+ async navigate(sessionId, url) {
853
+ const response = await this.http.request(
854
+ "POST",
855
+ `/v1/sessions/${sessionId}/navigate`,
856
+ {
857
+ json: { url }
858
+ }
859
+ );
860
+ return {
861
+ currentUrl: response.current_url ?? response.currentUrl
862
+ };
863
+ }
864
+ /**
865
+ * Get a screenshot of the browser
866
+ *
867
+ * @param sessionId - Session UUID
868
+ * @returns ScreenshotResponse with base64-encoded image, URL, and title
869
+ *
870
+ * @example
871
+ * ```typescript
872
+ * const screenshot = await client.sessions.screenshot('session-uuid');
873
+ * console.log(screenshot.url);
874
+ * ```
875
+ */
876
+ async screenshot(sessionId) {
877
+ return this.http.request("GET", `/v1/sessions/${sessionId}/screenshot`);
878
+ }
879
+ };
880
+
881
+ // src/client.ts
882
+ var AGIClient = class {
883
+ http;
884
+ /** Sessions resource for low-level API access */
885
+ sessions;
886
+ /**
887
+ * Create a new AGI client
888
+ *
889
+ * @param options - Client configuration options
890
+ *
891
+ * @example
892
+ * ```typescript
893
+ * // With explicit API key
894
+ * const client = new AGIClient({ apiKey: 'your_api_key' });
895
+ *
896
+ * // With custom base URL
897
+ * const client = new AGIClient({
898
+ * apiKey: 'your_api_key',
899
+ * baseUrl: 'https://custom-api.example.com',
900
+ * timeout: 120000,
901
+ * });
902
+ * ```
903
+ */
904
+ constructor(options) {
905
+ if (!options.apiKey) {
906
+ throw new Error(
907
+ "api_key is required. Either pass it as a parameter or set the AGI_API_KEY environment variable."
908
+ );
909
+ }
910
+ this.http = new HTTPClient(options);
911
+ this.sessions = new SessionsResource(this.http);
912
+ }
913
+ /**
914
+ * Create a session context manager for easy session lifecycle management (recommended)
915
+ *
916
+ * This is the recommended way to use the SDK. The context manager automatically
917
+ * creates and deletes the session using `await using` syntax.
918
+ *
919
+ * @param agentName - Agent model to use (e.g., "agi-0", "agi-0-fast", "agi-1")
920
+ * @param options - Session creation options
921
+ * @returns SessionContext manager
922
+ *
923
+ * @example
924
+ * ```typescript
925
+ * // Simple usage
926
+ * await using session = client.session('agi-0');
927
+ * const result = await session.runTask('Find flights SFO→JFK under $450');
928
+ * console.log(result.data);
929
+ * // Session automatically deleted
930
+ *
931
+ * // With options
932
+ * await using session = client.session('agi-0', {
933
+ * webhookUrl: 'https://yourapp.com/webhook',
934
+ * maxSteps: 200
935
+ * });
936
+ * const result = await session.runTask('Research company XYZ');
937
+ * ```
938
+ */
939
+ session(agentName = "agi-0", options) {
940
+ return new SessionContext(this, agentName, options);
941
+ }
942
+ };
943
+
944
+ export { AGIClient, AGIError, APIError, AgentExecutionError, AuthenticationError, NotFoundError, PermissionError, RateLimitError, Screenshot, SessionContext, SessionsResource, ValidationError };
945
+ //# sourceMappingURL=index.mjs.map
946
+ //# sourceMappingURL=index.mjs.map