@langchain/deno 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,721 @@
1
+ import { Sandbox } from "@deno/sandbox";
2
+ import { BaseSandbox } from "deepagents";
3
+
4
+ //#region src/auth.ts
5
+ /**
6
+ * Get the authentication token for Deno Sandbox API.
7
+ *
8
+ * Authentication is resolved in the following priority order:
9
+ *
10
+ * 1. **Explicit token**: If `options.token` is provided, it is used directly.
11
+ * 2. **DENO_DEPLOY_TOKEN**: Environment variable for Deno Deploy access token.
12
+ *
13
+ * If no token is found, an error is thrown with setup instructions.
14
+ *
15
+ * ## Environment Variable Setup
16
+ *
17
+ * ```bash
18
+ * # Go to https://app.deno.com -> Settings -> Organization Tokens
19
+ * # Create a new token and set it as environment variable
20
+ * export DENO_DEPLOY_TOKEN=your_token_here
21
+ * ```
22
+ *
23
+ * @param options - Optional authentication configuration from DenoSandboxOptions
24
+ * @returns The authentication token string
25
+ * @throws {Error} If no authentication token is available
26
+ *
27
+ * @example
28
+ * ```typescript
29
+ * // With explicit token
30
+ * const token = getAuthToken({ token: "my-token" });
31
+ *
32
+ * // Using environment variables (auto-detected)
33
+ * const token = getAuthToken();
34
+ *
35
+ * // From DenoSandboxOptions
36
+ * const options: DenoSandboxOptions = {
37
+ * auth: { token: "my-token" }
38
+ * };
39
+ * const token = getAuthToken(options.auth);
40
+ * ```
41
+ */
42
+ function getAuthToken(options) {
43
+ if (options?.token) return options.token;
44
+ const deployToken = process.env.DENO_DEPLOY_TOKEN;
45
+ if (deployToken) return deployToken;
46
+ throw new Error("Deno Deploy authentication required. Provide a token using one of these methods:\n\n1. Set DENO_DEPLOY_TOKEN environment variable:\n Go to https://app.deno.com -> Settings -> Organization Tokens\n Create a new token and run: export DENO_DEPLOY_TOKEN=your_token_here\n\n2. Pass token directly in options:\n new DenoSandbox({ auth: { token: '...' } })");
47
+ }
48
+ /**
49
+ * Get authentication credentials for Deno Sandbox API.
50
+ *
51
+ * This function returns the credentials needed for the Deno SDK.
52
+ *
53
+ * @param options - Optional authentication configuration from DenoSandboxOptions
54
+ * @returns Complete authentication credentials
55
+ * @throws {Error} If no authentication token is available
56
+ */
57
+ function getAuthCredentials(options) {
58
+ return { token: getAuthToken(options) };
59
+ }
60
+
61
+ //#endregion
62
+ //#region src/types.ts
63
+ const DENO_SANDBOX_ERROR_SYMBOL = Symbol.for("deno.sandbox.error");
64
+ /**
65
+ * Custom error class for Deno Sandbox operations.
66
+ *
67
+ * Provides structured error information including:
68
+ * - Human-readable message
69
+ * - Error code for programmatic handling
70
+ * - Original cause for debugging
71
+ *
72
+ * @example
73
+ * ```typescript
74
+ * try {
75
+ * await sandbox.execute("some command");
76
+ * } catch (error) {
77
+ * if (error instanceof DenoSandboxError) {
78
+ * switch (error.code) {
79
+ * case "NOT_INITIALIZED":
80
+ * await sandbox.initialize();
81
+ * break;
82
+ * case "COMMAND_TIMEOUT":
83
+ * console.error("Command took too long");
84
+ * break;
85
+ * default:
86
+ * throw error;
87
+ * }
88
+ * }
89
+ * }
90
+ * ```
91
+ */
92
+ var DenoSandboxError = class DenoSandboxError extends Error {
93
+ [DENO_SANDBOX_ERROR_SYMBOL];
94
+ /** Error name for instanceof checks and logging */
95
+ name = "DenoSandboxError";
96
+ /**
97
+ * Creates a new DenoSandboxError.
98
+ *
99
+ * @param message - Human-readable error description
100
+ * @param code - Structured error code for programmatic handling
101
+ * @param cause - Original error that caused this error (for debugging)
102
+ */
103
+ constructor(message, code, cause) {
104
+ super(message);
105
+ this.code = code;
106
+ this.cause = cause;
107
+ Object.setPrototypeOf(this, DenoSandboxError.prototype);
108
+ }
109
+ /**
110
+ * Checks if the error is an instance of DenoSandboxError.
111
+ *
112
+ * @param error - The error to check
113
+ * @returns True if the error is an instance of DenoSandboxError, false otherwise
114
+ */
115
+ static isInstance(error) {
116
+ return typeof error === "object" && error !== null && error[DENO_SANDBOX_ERROR_SYMBOL] === true;
117
+ }
118
+ };
119
+
120
+ //#endregion
121
+ //#region src/sandbox.ts
122
+ /**
123
+ * Deno Sandbox implementation of the SandboxBackendProtocol.
124
+ *
125
+ * This module provides a Deno Sandbox backend for deepagents, enabling agents
126
+ * to execute commands, read/write files, and manage isolated Linux microVM
127
+ * environments using Deno Deploy's Sandbox infrastructure.
128
+ *
129
+ * @packageDocumentation
130
+ */
131
+ /**
132
+ * Deno Sandbox backend for deepagents.
133
+ *
134
+ * Extends `BaseSandbox` to provide command execution, file operations, and
135
+ * sandbox lifecycle management using Deno Deploy's Sandbox SDK.
136
+ *
137
+ * ## Basic Usage
138
+ *
139
+ * ```typescript
140
+ * import { DenoSandbox } from "@langchain/deno";
141
+ *
142
+ * // Create and initialize a sandbox
143
+ * const sandbox = await DenoSandbox.create({
144
+ * memoryMb: 1024,
145
+ * lifetime: "5m",
146
+ * });
147
+ *
148
+ * try {
149
+ * // Execute commands
150
+ * const result = await sandbox.execute("deno --version");
151
+ * console.log(result.output);
152
+ * } finally {
153
+ * // Always cleanup
154
+ * await sandbox.close();
155
+ * }
156
+ * ```
157
+ *
158
+ * ## Using with DeepAgent
159
+ *
160
+ * ```typescript
161
+ * import { createDeepAgent } from "deepagents";
162
+ * import { DenoSandbox } from "@langchain/deno";
163
+ *
164
+ * const sandbox = await DenoSandbox.create();
165
+ *
166
+ * const agent = createDeepAgent({
167
+ * model: new ChatAnthropic({ model: "claude-sonnet-4-20250514" }),
168
+ * systemPrompt: "You are a coding assistant with sandbox access.",
169
+ * backend: sandbox,
170
+ * });
171
+ * ```
172
+ */
173
+ var DenoSandbox = class DenoSandbox extends BaseSandbox {
174
+ /** Private reference to the underlying Deno Sandbox instance */
175
+ #sandbox = null;
176
+ /** Configuration options for this sandbox */
177
+ #options;
178
+ /** Unique identifier for this sandbox instance */
179
+ #id;
180
+ /**
181
+ * Get the unique identifier for this sandbox.
182
+ *
183
+ * Before initialization, returns a temporary ID.
184
+ * After initialization, returns the actual Deno sandbox ID.
185
+ */
186
+ get id() {
187
+ return this.#id;
188
+ }
189
+ /**
190
+ * Get the underlying Deno Sandbox instance.
191
+ *
192
+ * @throws {DenoSandboxError} If the sandbox is not initialized
193
+ *
194
+ * @example
195
+ * ```typescript
196
+ * const sandbox = await DenoSandbox.create();
197
+ * const denoSdk = sandbox.sandbox; // Access the raw SDK
198
+ * ```
199
+ */
200
+ get sandbox() {
201
+ if (!this.#sandbox) throw new DenoSandboxError("Sandbox not initialized. Call initialize() or use DenoSandbox.create()", "NOT_INITIALIZED");
202
+ return this.#sandbox;
203
+ }
204
+ /**
205
+ * Check if the sandbox is initialized and running.
206
+ */
207
+ get isRunning() {
208
+ return this.#sandbox !== null;
209
+ }
210
+ /**
211
+ * Create a new DenoSandbox instance.
212
+ *
213
+ * Note: This only creates the instance. Call `initialize()` to actually
214
+ * create the Deno Sandbox, or use the static `DenoSandbox.create()` method.
215
+ *
216
+ * @param options - Configuration options for the sandbox
217
+ *
218
+ * @example
219
+ * ```typescript
220
+ * // Two-step initialization
221
+ * const sandbox = new DenoSandbox({ memoryMb: 1024 });
222
+ * await sandbox.initialize();
223
+ *
224
+ * // Or use the factory method
225
+ * const sandbox = await DenoSandbox.create({ memoryMb: 1024 });
226
+ * ```
227
+ */
228
+ constructor(options = {}) {
229
+ super();
230
+ this.#options = {
231
+ memoryMb: 768,
232
+ lifetime: "session",
233
+ ...options
234
+ };
235
+ this.#id = `deno-sandbox-${Date.now()}`;
236
+ }
237
+ /**
238
+ * Initialize the sandbox by creating a new Deno Sandbox instance.
239
+ *
240
+ * This method authenticates with Deno Deploy and provisions a new microVM
241
+ * sandbox. After initialization, the `id` property will reflect the
242
+ * actual Deno sandbox ID.
243
+ *
244
+ * @throws {DenoSandboxError} If already initialized (`ALREADY_INITIALIZED`)
245
+ * @throws {DenoSandboxError} If authentication fails (`AUTHENTICATION_FAILED`)
246
+ * @throws {DenoSandboxError} If sandbox creation fails (`SANDBOX_CREATION_FAILED`)
247
+ *
248
+ * @example
249
+ * ```typescript
250
+ * const sandbox = new DenoSandbox();
251
+ * await sandbox.initialize();
252
+ * console.log(`Sandbox ID: ${sandbox.id}`);
253
+ * ```
254
+ */
255
+ async initialize() {
256
+ if (this.#sandbox) throw new DenoSandboxError("Sandbox is already initialized. Each DenoSandbox instance can only be initialized once.", "ALREADY_INITIALIZED");
257
+ let credentials;
258
+ try {
259
+ credentials = getAuthCredentials(this.#options.auth);
260
+ } catch (error) {
261
+ throw new DenoSandboxError("Failed to authenticate with Deno Deploy. Check your token configuration.", "AUTHENTICATION_FAILED", error instanceof Error ? error : void 0);
262
+ }
263
+ try {
264
+ process.env.DENO_DEPLOY_TOKEN = credentials.token;
265
+ const createOptions = {};
266
+ if (this.#options.memoryMb !== void 0) createOptions.memoryMb = this.#options.memoryMb;
267
+ if (this.#options.lifetime !== void 0) createOptions.lifetime = this.#options.lifetime;
268
+ if (this.#options.region !== void 0) createOptions.region = this.#options.region;
269
+ this.#sandbox = await Sandbox.create(createOptions);
270
+ this.#id = this.#sandbox.id;
271
+ if (this.#options.initialFiles) await this.#uploadInitialFiles(this.#options.initialFiles);
272
+ } catch (error) {
273
+ throw new DenoSandboxError(`Failed to create Deno Sandbox: ${error instanceof Error ? error.message : String(error)}`, "SANDBOX_CREATION_FAILED", error instanceof Error ? error : void 0);
274
+ }
275
+ }
276
+ /**
277
+ * Upload initial files to the sandbox.
278
+ *
279
+ * @param files - A map of file paths to their string contents
280
+ */
281
+ async #uploadInitialFiles(files) {
282
+ const encoder = new TextEncoder();
283
+ const fileEntries = Object.entries(files).map(([path, content]) => [path, encoder.encode(content)]);
284
+ const errors = (await this.uploadFiles(fileEntries)).filter((r) => r.error !== null);
285
+ if (errors.length > 0) throw new DenoSandboxError(`Failed to upload initial files: ${errors.map((e) => `${e.path}: ${e.error}`).join(", ")}`, "FILE_OPERATION_FAILED");
286
+ }
287
+ /**
288
+ * Execute a command in the sandbox.
289
+ *
290
+ * Commands are run using the sandbox's shell in the configured working directory.
291
+ *
292
+ * @param command - The shell command to execute
293
+ * @returns Execution result with output, exit code, and truncation flag
294
+ * @throws {DenoSandboxError} If the sandbox is not initialized
295
+ *
296
+ * @example
297
+ * ```typescript
298
+ * const result = await sandbox.execute("echo 'Hello World'");
299
+ * console.log(result.output); // "Hello World\n"
300
+ * console.log(result.exitCode); // 0
301
+ * ```
302
+ */
303
+ async execute(command) {
304
+ const sandbox = this.sandbox;
305
+ try {
306
+ const { status, stdoutText, stderrText } = await (await sandbox.spawn("/bin/bash", {
307
+ args: ["-c", command],
308
+ stdout: "piped",
309
+ stderr: "piped"
310
+ })).output();
311
+ return {
312
+ output: (stdoutText ?? "") + (stderrText ?? ""),
313
+ exitCode: status.code ?? 0,
314
+ truncated: false
315
+ };
316
+ } catch (error) {
317
+ if (error instanceof Error && error.message.includes("timeout")) throw new DenoSandboxError(`Command timed out: ${command}`, "COMMAND_TIMEOUT", error);
318
+ throw new DenoSandboxError(`Command execution failed: ${error instanceof Error ? error.message : String(error)}`, "COMMAND_FAILED", error instanceof Error ? error : void 0);
319
+ }
320
+ }
321
+ /**
322
+ * Upload files to the sandbox.
323
+ *
324
+ * Files are written to the sandbox filesystem. Parent directories are
325
+ * created automatically if they don't exist.
326
+ *
327
+ * @param files - Array of [path, content] tuples to upload
328
+ * @returns Upload result for each file, with success or error status
329
+ *
330
+ * @example
331
+ * ```typescript
332
+ * const encoder = new TextEncoder();
333
+ * const results = await sandbox.uploadFiles([
334
+ * ["src/index.js", encoder.encode("console.log('Hello')")],
335
+ * ["package.json", encoder.encode('{"name": "test"}')],
336
+ * ]);
337
+ * ```
338
+ */
339
+ async uploadFiles(files) {
340
+ const sandbox = this.sandbox;
341
+ const results = [];
342
+ for (const [path, content] of files) try {
343
+ const parentDir = path.substring(0, path.lastIndexOf("/"));
344
+ if (parentDir) await (await sandbox.spawn("/bin/bash", {
345
+ args: ["-c", `mkdir -p "${parentDir}"`],
346
+ stdout: "piped",
347
+ stderr: "piped"
348
+ })).output();
349
+ const textContent = new TextDecoder().decode(content);
350
+ await sandbox.writeTextFile(path, textContent);
351
+ results.push({
352
+ path,
353
+ error: null
354
+ });
355
+ } catch (error) {
356
+ results.push({
357
+ path,
358
+ error: this.#mapError(error)
359
+ });
360
+ }
361
+ return results;
362
+ }
363
+ /**
364
+ * Download files from the sandbox.
365
+ *
366
+ * Each file is read individually, allowing partial success when some
367
+ * files exist and others don't.
368
+ *
369
+ * @param paths - Array of file paths to download
370
+ * @returns Download result for each file, with content or error
371
+ *
372
+ * @example
373
+ * ```typescript
374
+ * const results = await sandbox.downloadFiles(["src/index.js", "missing.txt"]);
375
+ * for (const result of results) {
376
+ * if (result.content) {
377
+ * console.log(new TextDecoder().decode(result.content));
378
+ * } else {
379
+ * console.error(`Error: ${result.error}`);
380
+ * }
381
+ * }
382
+ * ```
383
+ */
384
+ async downloadFiles(paths) {
385
+ const sandbox = this.sandbox;
386
+ const results = [];
387
+ for (const path of paths) try {
388
+ const { status, stdoutText } = await (await sandbox.spawn("/bin/bash", {
389
+ args: ["-c", `cat "${path}"`],
390
+ stdout: "piped",
391
+ stderr: "piped"
392
+ })).output();
393
+ if (!status.success) results.push({
394
+ path,
395
+ content: null,
396
+ error: "file_not_found"
397
+ });
398
+ else {
399
+ const content = new TextEncoder().encode(stdoutText ?? "");
400
+ results.push({
401
+ path,
402
+ content,
403
+ error: null
404
+ });
405
+ }
406
+ } catch (error) {
407
+ results.push({
408
+ path,
409
+ content: null,
410
+ error: this.#mapError(error)
411
+ });
412
+ }
413
+ return results;
414
+ }
415
+ /**
416
+ * Read a file's content with line numbers.
417
+ *
418
+ * Override of BaseSandbox.read() to use awk instead of Python,
419
+ * since Deno sandboxes don't have Python installed.
420
+ *
421
+ * @param filePath - Absolute path to the file
422
+ * @param offset - Line offset (0-indexed, default 0)
423
+ * @param limit - Maximum lines to return (default 500)
424
+ * @returns Formatted file content with line numbers, or error message
425
+ */
426
+ async read(filePath, offset = 0, limit = 500) {
427
+ const safeOffset = Number.isFinite(offset) && offset > 0 ? Math.floor(offset) : 0;
428
+ const safeLimit = Number.isFinite(limit) && limit > 0 && limit < Number.MAX_SAFE_INTEGER ? Math.floor(limit) : 500;
429
+ const escapedPath = filePath.replace(/'/g, "'\\''");
430
+ const command = `
431
+ if [ ! -f '${escapedPath}' ]; then
432
+ echo "Error: File not found"
433
+ exit 1
434
+ fi
435
+ if [ ! -s '${escapedPath}' ]; then
436
+ echo "System reminder: File exists but has empty contents"
437
+ exit 0
438
+ fi
439
+ awk -v offset=${safeOffset} -v limit=${safeLimit} '
440
+ NR > offset && NR <= offset + limit {
441
+ printf "%6d\\t%s\\n", NR, $0
442
+ }
443
+ ' '${escapedPath}'
444
+ `;
445
+ const result = await this.execute(command);
446
+ if (result.exitCode !== 0) return `Error: File '${filePath}' not found`;
447
+ return result.output;
448
+ }
449
+ /**
450
+ * Create a new file with content.
451
+ *
452
+ * Override of BaseSandbox.write() to use shell commands instead of Python,
453
+ * since Deno sandboxes don't have Python installed.
454
+ *
455
+ * @param filePath - Absolute path for the new file
456
+ * @param content - File content to write
457
+ * @returns WriteResult with error populated on failure
458
+ */
459
+ async write(filePath, content) {
460
+ const escapedPath = filePath.replace(/'/g, "'\\''");
461
+ if ((await this.execute(`test -f '${escapedPath}'`)).exitCode === 0) return { error: `Cannot write to ${filePath} because it already exists. Read and then make an edit, or write to a new path.` };
462
+ const encoder = new TextEncoder();
463
+ const uploadResult = await this.uploadFiles([[filePath, encoder.encode(content)]]);
464
+ if (uploadResult[0]?.error) return { error: `Failed to write file: ${uploadResult[0].error}` };
465
+ return {
466
+ path: filePath,
467
+ filesUpdate: null
468
+ };
469
+ }
470
+ /**
471
+ * Edit a file by replacing string occurrences.
472
+ *
473
+ * Override of BaseSandbox.edit() to use shell commands instead of Python,
474
+ * since Deno sandboxes don't have Python installed.
475
+ *
476
+ * Uses sed for in-place replacement with proper escaping.
477
+ *
478
+ * @param filePath - Absolute path to the file
479
+ * @param oldString - String to find and replace
480
+ * @param newString - Replacement string
481
+ * @param replaceAll - If true, replace all occurrences (default: false)
482
+ * @returns EditResult with error, path, and occurrences
483
+ */
484
+ async edit(filePath, oldString, newString, replaceAll = false) {
485
+ const escapedPath = filePath.replace(/'/g, "'\\''");
486
+ if ((await this.execute(`test -f '${escapedPath}'`)).exitCode !== 0) return { error: `Error: File '${filePath}' not found` };
487
+ const escapedOldForGrep = oldString.replace(/'/g, "'\\''");
488
+ const countResult = await this.execute(`grep -oF '${escapedOldForGrep}' '${escapedPath}' | wc -l`);
489
+ const count = parseInt(countResult.output.trim(), 10) || 0;
490
+ if (count === 0) return { error: `String not found in file '${filePath}'` };
491
+ if (count > 1 && !replaceAll) return { error: `Multiple occurrences found in '${filePath}'. Use replaceAll=true to replace all.` };
492
+ const awkCommand = `
493
+ OLD=$(echo '${Buffer.from(oldString, "utf-8").toString("base64")}' | base64 -d)
494
+ NEW=$(echo '${Buffer.from(newString, "utf-8").toString("base64")}' | base64 -d)
495
+ awk -v old="$OLD" -v new="$NEW" -v replace_all=${replaceAll ? 1 : 0} '
496
+ {
497
+ if (replace_all) {
498
+ gsub(old, new)
499
+ } else {
500
+ sub(old, new)
501
+ }
502
+ print
503
+ }
504
+ ' '${escapedPath}' > '${escapedPath}.tmp' && mv '${escapedPath}.tmp' '${escapedPath}'
505
+ `;
506
+ if ((await this.execute(awkCommand)).exitCode !== 0) return { error: `Unknown error editing file '${filePath}'` };
507
+ return {
508
+ path: filePath,
509
+ filesUpdate: null,
510
+ occurrences: count
511
+ };
512
+ }
513
+ /**
514
+ * Close the sandbox and release all resources.
515
+ *
516
+ * After closing, the sandbox cannot be used again. Any unsaved data
517
+ * will be lost.
518
+ *
519
+ * @example
520
+ * ```typescript
521
+ * try {
522
+ * await sandbox.execute("deno run build.ts");
523
+ * } finally {
524
+ * await sandbox.close();
525
+ * }
526
+ * ```
527
+ */
528
+ async close() {
529
+ if (this.#sandbox) try {
530
+ await this.#sandbox.close();
531
+ } finally {
532
+ this.#sandbox = null;
533
+ }
534
+ }
535
+ /**
536
+ * Forcefully terminate the sandbox.
537
+ *
538
+ * Use this when you need to immediately stop the sandbox, even if
539
+ * operations are in progress.
540
+ *
541
+ * @example
542
+ * ```typescript
543
+ * await sandbox.kill();
544
+ * ```
545
+ */
546
+ async kill() {
547
+ if (this.#sandbox) try {
548
+ await this.#sandbox.kill();
549
+ } finally {
550
+ this.#sandbox = null;
551
+ }
552
+ }
553
+ /**
554
+ * Alias for close() to maintain compatibility with other sandbox implementations.
555
+ */
556
+ async stop() {
557
+ await this.close();
558
+ }
559
+ /**
560
+ * Set the sandbox from an existing Deno Sandbox instance.
561
+ * Used internally by the static `connect()` method.
562
+ */
563
+ #setFromExisting(existingSandbox, sandboxId) {
564
+ this.#sandbox = existingSandbox;
565
+ this.#id = sandboxId;
566
+ }
567
+ /**
568
+ * Map Deno SDK errors to standardized FileOperationError codes.
569
+ *
570
+ * @param error - The error from the Deno SDK
571
+ * @returns A standardized error code
572
+ */
573
+ #mapError(error) {
574
+ if (error instanceof Error) {
575
+ const msg = error.message.toLowerCase();
576
+ if (msg.includes("not found") || msg.includes("enoent")) return "file_not_found";
577
+ if (msg.includes("permission") || msg.includes("eacces")) return "permission_denied";
578
+ if (msg.includes("directory") || msg.includes("eisdir")) return "is_directory";
579
+ }
580
+ return "invalid_path";
581
+ }
582
+ /**
583
+ * Create and initialize a new DenoSandbox in one step.
584
+ *
585
+ * This is the recommended way to create a sandbox. It combines
586
+ * construction and initialization into a single async operation.
587
+ *
588
+ * @param options - Configuration options for the sandbox
589
+ * @returns An initialized and ready-to-use sandbox
590
+ *
591
+ * @example
592
+ * ```typescript
593
+ * const sandbox = await DenoSandbox.create({
594
+ * memoryMb: 1024,
595
+ * lifetime: "10m",
596
+ * region: "iad",
597
+ * });
598
+ * ```
599
+ */
600
+ static async create(options) {
601
+ const sandbox = new DenoSandbox(options);
602
+ await sandbox.initialize();
603
+ return sandbox;
604
+ }
605
+ /**
606
+ * Reconnect to an existing sandbox by ID.
607
+ *
608
+ * This allows you to resume working with a sandbox that was created
609
+ * earlier with a duration-based lifetime.
610
+ *
611
+ * @param sandboxId - The ID of the sandbox to reconnect to
612
+ * @param options - Optional auth configuration (for token)
613
+ * @returns A connected sandbox instance
614
+ *
615
+ * @example
616
+ * ```typescript
617
+ * // Resume a sandbox from a stored ID
618
+ * const sandbox = await DenoSandbox.connect("sandbox-abc123");
619
+ * const result = await sandbox.execute("ls -la");
620
+ * ```
621
+ */
622
+ static async connect(sandboxId, options) {
623
+ let credentials;
624
+ try {
625
+ credentials = getAuthCredentials(options?.auth);
626
+ } catch (error) {
627
+ throw new DenoSandboxError("Failed to authenticate with Deno Deploy. Check your token configuration.", "AUTHENTICATION_FAILED", error instanceof Error ? error : void 0);
628
+ }
629
+ try {
630
+ process.env.DENO_DEPLOY_TOKEN = credentials.token;
631
+ const existingSandbox = await Sandbox.connect({ id: sandboxId });
632
+ const denoSandbox = new DenoSandbox();
633
+ denoSandbox.#setFromExisting(existingSandbox, sandboxId);
634
+ return denoSandbox;
635
+ } catch (error) {
636
+ throw new DenoSandboxError(`Sandbox not found: ${sandboxId}`, "SANDBOX_NOT_FOUND", error instanceof Error ? error : void 0);
637
+ }
638
+ }
639
+ };
640
+ /**
641
+ * Create an async factory function that creates a new Deno Sandbox per invocation.
642
+ *
643
+ * Each call to the factory will create and initialize a new sandbox.
644
+ * This is useful when you want fresh, isolated environments for each
645
+ * agent invocation.
646
+ *
647
+ * **Important**: This returns an async factory. For use with middleware that
648
+ * requires synchronous BackendFactory, use `createDenoSandboxFactoryFromSandbox()`
649
+ * with a pre-created sandbox instead.
650
+ *
651
+ * @param options - Optional configuration for sandbox creation
652
+ * @returns An async factory function that creates new sandboxes
653
+ *
654
+ * @example
655
+ * ```typescript
656
+ * import { DenoSandbox, createDenoSandboxFactory } from "@langchain/deno";
657
+ *
658
+ * // Create a factory for new sandboxes
659
+ * const factory = createDenoSandboxFactory({ memoryMb: 1024 });
660
+ *
661
+ * // Each call creates a new sandbox
662
+ * const sandbox1 = await factory();
663
+ * const sandbox2 = await factory();
664
+ *
665
+ * try {
666
+ * // Use sandboxes...
667
+ * } finally {
668
+ * await sandbox1.close();
669
+ * await sandbox2.close();
670
+ * }
671
+ * ```
672
+ */
673
+ function createDenoSandboxFactory(options) {
674
+ return async () => {
675
+ return await DenoSandbox.create(options);
676
+ };
677
+ }
678
+ /**
679
+ * Create a backend factory that reuses an existing Deno Sandbox.
680
+ *
681
+ * This allows multiple agent invocations to share the same sandbox,
682
+ * avoiding the startup overhead of creating new sandboxes.
683
+ *
684
+ * Important: You are responsible for managing the sandbox lifecycle
685
+ * (calling `close()` when done).
686
+ *
687
+ * @param sandbox - An existing DenoSandbox instance (must be initialized)
688
+ * @returns A BackendFactory that returns the provided sandbox
689
+ *
690
+ * @example
691
+ * ```typescript
692
+ * import { createDeepAgent, createFilesystemMiddleware } from "deepagents";
693
+ * import { DenoSandbox, createDenoSandboxFactoryFromSandbox } from "@langchain/deno";
694
+ *
695
+ * // Create and initialize a sandbox
696
+ * const sandbox = await DenoSandbox.create({ memoryMb: 1024 });
697
+ *
698
+ * try {
699
+ * const agent = createDeepAgent({
700
+ * model: new ChatAnthropic({ model: "claude-sonnet-4-20250514" }),
701
+ * systemPrompt: "You are a coding assistant.",
702
+ * middlewares: [
703
+ * createFilesystemMiddleware({
704
+ * backend: createDenoSandboxFactoryFromSandbox(sandbox),
705
+ * }),
706
+ * ],
707
+ * });
708
+ *
709
+ * await agent.invoke({ messages: [...] });
710
+ * } finally {
711
+ * await sandbox.close();
712
+ * }
713
+ * ```
714
+ */
715
+ function createDenoSandboxFactoryFromSandbox(sandbox) {
716
+ return () => sandbox;
717
+ }
718
+
719
+ //#endregion
720
+ export { DenoSandbox, DenoSandboxError, createDenoSandboxFactory, createDenoSandboxFactoryFromSandbox, getAuthCredentials, getAuthToken };
721
+ //# sourceMappingURL=index.js.map