@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.
@@ -0,0 +1,576 @@
1
+ import { Sandbox } from "@deno/sandbox";
2
+ import { BackendFactory, BaseSandbox, EditResult, ExecuteResponse, FileDownloadResponse, FileUploadResponse, WriteResult } from "deepagents";
3
+
4
+ //#region src/types.d.ts
5
+ /**
6
+ * Type definitions for the Deno Sandbox backend.
7
+ *
8
+ * This module contains all type definitions for the @langchain/deno package,
9
+ * including options and error types.
10
+ */
11
+ /**
12
+ * Supported regions for Deno Deploy sandboxes.
13
+ *
14
+ * Currently available regions:
15
+ * - `ams`: Amsterdam
16
+ * - `ord`: Chicago
17
+ */
18
+ type DenoSandboxRegion = "ams" | "ord";
19
+ /**
20
+ * Sandbox lifetime configuration.
21
+ *
22
+ * - `"session"`: Sandbox shuts down when you close/dispose the client (default)
23
+ * - Duration string: Keep sandbox alive for a specific time (e.g., "5m", "30s")
24
+ */
25
+ type SandboxLifetime = "session" | `${number}s` | `${number}m`;
26
+ /**
27
+ * Configuration options for creating a Deno Sandbox.
28
+ *
29
+ * @example
30
+ * ```typescript
31
+ * const options: DenoSandboxOptions = {
32
+ * memoryMb: 1024, // 1GB memory
33
+ * lifetime: "5m", // 5 minutes
34
+ * region: "iad", // US East
35
+ * };
36
+ * ```
37
+ */
38
+ interface DenoSandboxOptions {
39
+ /**
40
+ * Amount of memory allocated to the sandbox in megabytes.
41
+ *
42
+ * Memory limits:
43
+ * - Minimum: 768MB
44
+ * - Maximum: 4096MB
45
+ *
46
+ * @default 768
47
+ */
48
+ memoryMb?: number;
49
+ /**
50
+ * Sandbox lifetime configuration.
51
+ *
52
+ * - `"session"`: Sandbox shuts down when you close/dispose the client (default)
53
+ * - Duration string: Keep sandbox alive for a specific time (e.g., "5m", "30s")
54
+ *
55
+ * Supported duration suffixes: `s` (seconds), `m` (minutes).
56
+ *
57
+ * @default "session"
58
+ */
59
+ lifetime?: SandboxLifetime;
60
+ /**
61
+ * Region where the sandbox will be created.
62
+ *
63
+ * If not specified, the sandbox will be created in the default region.
64
+ *
65
+ * @see DenoSandboxRegion for available regions
66
+ */
67
+ region?: DenoSandboxRegion;
68
+ /**
69
+ * Initial files to create in the sandbox after initialization.
70
+ *
71
+ * A map of file paths to their contents. Files will be created
72
+ * in the sandbox filesystem before any commands are executed.
73
+ * Parent directories are created automatically.
74
+ *
75
+ * @example
76
+ * ```typescript
77
+ * const options: DenoSandboxOptions = {
78
+ * memoryMb: 1024,
79
+ * initialFiles: {
80
+ * "/home/app/index.js": "console.log('Hello')",
81
+ * "/home/app/package.json": '{"name": "test"}',
82
+ * },
83
+ * };
84
+ * ```
85
+ */
86
+ initialFiles?: Record<string, string>;
87
+ /**
88
+ * Authentication configuration for Deno Deploy API.
89
+ *
90
+ * ### Environment Variable Setup
91
+ *
92
+ * ```bash
93
+ * # Go to https://app.deno.com -> Settings -> Organization Tokens
94
+ * # Create a new token and set it as environment variable
95
+ * export DENO_DEPLOY_TOKEN=your_token_here
96
+ * ```
97
+ *
98
+ * Or pass the token directly in this auth configuration.
99
+ */
100
+ auth?: {
101
+ /**
102
+ * Deno Deploy access token.
103
+ * If not provided, reads from `DENO_DEPLOY_TOKEN` environment variable.
104
+ */
105
+ token?: string;
106
+ };
107
+ }
108
+ /**
109
+ * Error codes for Deno Sandbox operations.
110
+ *
111
+ * Used to identify specific error conditions and handle them appropriately.
112
+ */
113
+ type DenoSandboxErrorCode = /** Sandbox has not been initialized - call initialize() first */"NOT_INITIALIZED" /** Sandbox is already initialized - cannot initialize twice */ | "ALREADY_INITIALIZED" /** Authentication failed - check token configuration */ | "AUTHENTICATION_FAILED" /** Failed to create sandbox - check options and quotas */ | "SANDBOX_CREATION_FAILED" /** Sandbox not found - may have been stopped or expired */ | "SANDBOX_NOT_FOUND" /** Command execution timed out */ | "COMMAND_TIMEOUT" /** Command execution failed */ | "COMMAND_FAILED" /** File operation (read/write) failed */ | "FILE_OPERATION_FAILED" /** Resource limits exceeded (CPU, memory, storage) */ | "RESOURCE_LIMIT_EXCEEDED";
114
+ declare const DENO_SANDBOX_ERROR_SYMBOL: unique symbol;
115
+ /**
116
+ * Custom error class for Deno Sandbox operations.
117
+ *
118
+ * Provides structured error information including:
119
+ * - Human-readable message
120
+ * - Error code for programmatic handling
121
+ * - Original cause for debugging
122
+ *
123
+ * @example
124
+ * ```typescript
125
+ * try {
126
+ * await sandbox.execute("some command");
127
+ * } catch (error) {
128
+ * if (error instanceof DenoSandboxError) {
129
+ * switch (error.code) {
130
+ * case "NOT_INITIALIZED":
131
+ * await sandbox.initialize();
132
+ * break;
133
+ * case "COMMAND_TIMEOUT":
134
+ * console.error("Command took too long");
135
+ * break;
136
+ * default:
137
+ * throw error;
138
+ * }
139
+ * }
140
+ * }
141
+ * ```
142
+ */
143
+ declare class DenoSandboxError extends Error {
144
+ readonly code: DenoSandboxErrorCode;
145
+ readonly cause?: Error | undefined;
146
+ [DENO_SANDBOX_ERROR_SYMBOL]: true;
147
+ /** Error name for instanceof checks and logging */
148
+ readonly name = "DenoSandboxError";
149
+ /**
150
+ * Creates a new DenoSandboxError.
151
+ *
152
+ * @param message - Human-readable error description
153
+ * @param code - Structured error code for programmatic handling
154
+ * @param cause - Original error that caused this error (for debugging)
155
+ */
156
+ constructor(message: string, code: DenoSandboxErrorCode, cause?: Error | undefined);
157
+ /**
158
+ * Checks if the error is an instance of DenoSandboxError.
159
+ *
160
+ * @param error - The error to check
161
+ * @returns True if the error is an instance of DenoSandboxError, false otherwise
162
+ */
163
+ static isInstance(error: unknown): error is DenoSandboxError;
164
+ }
165
+ //#endregion
166
+ //#region src/sandbox.d.ts
167
+ /**
168
+ * Deno Sandbox backend for deepagents.
169
+ *
170
+ * Extends `BaseSandbox` to provide command execution, file operations, and
171
+ * sandbox lifecycle management using Deno Deploy's Sandbox SDK.
172
+ *
173
+ * ## Basic Usage
174
+ *
175
+ * ```typescript
176
+ * import { DenoSandbox } from "@langchain/deno";
177
+ *
178
+ * // Create and initialize a sandbox
179
+ * const sandbox = await DenoSandbox.create({
180
+ * memoryMb: 1024,
181
+ * lifetime: "5m",
182
+ * });
183
+ *
184
+ * try {
185
+ * // Execute commands
186
+ * const result = await sandbox.execute("deno --version");
187
+ * console.log(result.output);
188
+ * } finally {
189
+ * // Always cleanup
190
+ * await sandbox.close();
191
+ * }
192
+ * ```
193
+ *
194
+ * ## Using with DeepAgent
195
+ *
196
+ * ```typescript
197
+ * import { createDeepAgent } from "deepagents";
198
+ * import { DenoSandbox } from "@langchain/deno";
199
+ *
200
+ * const sandbox = await DenoSandbox.create();
201
+ *
202
+ * const agent = createDeepAgent({
203
+ * model: new ChatAnthropic({ model: "claude-sonnet-4-20250514" }),
204
+ * systemPrompt: "You are a coding assistant with sandbox access.",
205
+ * backend: sandbox,
206
+ * });
207
+ * ```
208
+ */
209
+ declare class DenoSandbox extends BaseSandbox {
210
+ #private;
211
+ /**
212
+ * Get the unique identifier for this sandbox.
213
+ *
214
+ * Before initialization, returns a temporary ID.
215
+ * After initialization, returns the actual Deno sandbox ID.
216
+ */
217
+ get id(): string;
218
+ /**
219
+ * Get the underlying Deno Sandbox instance.
220
+ *
221
+ * @throws {DenoSandboxError} If the sandbox is not initialized
222
+ *
223
+ * @example
224
+ * ```typescript
225
+ * const sandbox = await DenoSandbox.create();
226
+ * const denoSdk = sandbox.sandbox; // Access the raw SDK
227
+ * ```
228
+ */
229
+ get sandbox(): Sandbox;
230
+ /**
231
+ * Check if the sandbox is initialized and running.
232
+ */
233
+ get isRunning(): boolean;
234
+ /**
235
+ * Create a new DenoSandbox instance.
236
+ *
237
+ * Note: This only creates the instance. Call `initialize()` to actually
238
+ * create the Deno Sandbox, or use the static `DenoSandbox.create()` method.
239
+ *
240
+ * @param options - Configuration options for the sandbox
241
+ *
242
+ * @example
243
+ * ```typescript
244
+ * // Two-step initialization
245
+ * const sandbox = new DenoSandbox({ memoryMb: 1024 });
246
+ * await sandbox.initialize();
247
+ *
248
+ * // Or use the factory method
249
+ * const sandbox = await DenoSandbox.create({ memoryMb: 1024 });
250
+ * ```
251
+ */
252
+ constructor(options?: DenoSandboxOptions);
253
+ /**
254
+ * Initialize the sandbox by creating a new Deno Sandbox instance.
255
+ *
256
+ * This method authenticates with Deno Deploy and provisions a new microVM
257
+ * sandbox. After initialization, the `id` property will reflect the
258
+ * actual Deno sandbox ID.
259
+ *
260
+ * @throws {DenoSandboxError} If already initialized (`ALREADY_INITIALIZED`)
261
+ * @throws {DenoSandboxError} If authentication fails (`AUTHENTICATION_FAILED`)
262
+ * @throws {DenoSandboxError} If sandbox creation fails (`SANDBOX_CREATION_FAILED`)
263
+ *
264
+ * @example
265
+ * ```typescript
266
+ * const sandbox = new DenoSandbox();
267
+ * await sandbox.initialize();
268
+ * console.log(`Sandbox ID: ${sandbox.id}`);
269
+ * ```
270
+ */
271
+ initialize(): Promise<void>;
272
+ /**
273
+ * Execute a command in the sandbox.
274
+ *
275
+ * Commands are run using the sandbox's shell in the configured working directory.
276
+ *
277
+ * @param command - The shell command to execute
278
+ * @returns Execution result with output, exit code, and truncation flag
279
+ * @throws {DenoSandboxError} If the sandbox is not initialized
280
+ *
281
+ * @example
282
+ * ```typescript
283
+ * const result = await sandbox.execute("echo 'Hello World'");
284
+ * console.log(result.output); // "Hello World\n"
285
+ * console.log(result.exitCode); // 0
286
+ * ```
287
+ */
288
+ execute(command: string): Promise<ExecuteResponse>;
289
+ /**
290
+ * Upload files to the sandbox.
291
+ *
292
+ * Files are written to the sandbox filesystem. Parent directories are
293
+ * created automatically if they don't exist.
294
+ *
295
+ * @param files - Array of [path, content] tuples to upload
296
+ * @returns Upload result for each file, with success or error status
297
+ *
298
+ * @example
299
+ * ```typescript
300
+ * const encoder = new TextEncoder();
301
+ * const results = await sandbox.uploadFiles([
302
+ * ["src/index.js", encoder.encode("console.log('Hello')")],
303
+ * ["package.json", encoder.encode('{"name": "test"}')],
304
+ * ]);
305
+ * ```
306
+ */
307
+ uploadFiles(files: Array<[string, Uint8Array]>): Promise<FileUploadResponse[]>;
308
+ /**
309
+ * Download files from the sandbox.
310
+ *
311
+ * Each file is read individually, allowing partial success when some
312
+ * files exist and others don't.
313
+ *
314
+ * @param paths - Array of file paths to download
315
+ * @returns Download result for each file, with content or error
316
+ *
317
+ * @example
318
+ * ```typescript
319
+ * const results = await sandbox.downloadFiles(["src/index.js", "missing.txt"]);
320
+ * for (const result of results) {
321
+ * if (result.content) {
322
+ * console.log(new TextDecoder().decode(result.content));
323
+ * } else {
324
+ * console.error(`Error: ${result.error}`);
325
+ * }
326
+ * }
327
+ * ```
328
+ */
329
+ downloadFiles(paths: string[]): Promise<FileDownloadResponse[]>;
330
+ /**
331
+ * Read a file's content with line numbers.
332
+ *
333
+ * Override of BaseSandbox.read() to use awk instead of Python,
334
+ * since Deno sandboxes don't have Python installed.
335
+ *
336
+ * @param filePath - Absolute path to the file
337
+ * @param offset - Line offset (0-indexed, default 0)
338
+ * @param limit - Maximum lines to return (default 500)
339
+ * @returns Formatted file content with line numbers, or error message
340
+ */
341
+ read(filePath: string, offset?: number, limit?: number): Promise<string>;
342
+ /**
343
+ * Create a new file with content.
344
+ *
345
+ * Override of BaseSandbox.write() to use shell commands instead of Python,
346
+ * since Deno sandboxes don't have Python installed.
347
+ *
348
+ * @param filePath - Absolute path for the new file
349
+ * @param content - File content to write
350
+ * @returns WriteResult with error populated on failure
351
+ */
352
+ write(filePath: string, content: string): Promise<WriteResult>;
353
+ /**
354
+ * Edit a file by replacing string occurrences.
355
+ *
356
+ * Override of BaseSandbox.edit() to use shell commands instead of Python,
357
+ * since Deno sandboxes don't have Python installed.
358
+ *
359
+ * Uses sed for in-place replacement with proper escaping.
360
+ *
361
+ * @param filePath - Absolute path to the file
362
+ * @param oldString - String to find and replace
363
+ * @param newString - Replacement string
364
+ * @param replaceAll - If true, replace all occurrences (default: false)
365
+ * @returns EditResult with error, path, and occurrences
366
+ */
367
+ edit(filePath: string, oldString: string, newString: string, replaceAll?: boolean): Promise<EditResult>;
368
+ /**
369
+ * Close the sandbox and release all resources.
370
+ *
371
+ * After closing, the sandbox cannot be used again. Any unsaved data
372
+ * will be lost.
373
+ *
374
+ * @example
375
+ * ```typescript
376
+ * try {
377
+ * await sandbox.execute("deno run build.ts");
378
+ * } finally {
379
+ * await sandbox.close();
380
+ * }
381
+ * ```
382
+ */
383
+ close(): Promise<void>;
384
+ /**
385
+ * Forcefully terminate the sandbox.
386
+ *
387
+ * Use this when you need to immediately stop the sandbox, even if
388
+ * operations are in progress.
389
+ *
390
+ * @example
391
+ * ```typescript
392
+ * await sandbox.kill();
393
+ * ```
394
+ */
395
+ kill(): Promise<void>;
396
+ /**
397
+ * Alias for close() to maintain compatibility with other sandbox implementations.
398
+ */
399
+ stop(): Promise<void>;
400
+ /**
401
+ * Create and initialize a new DenoSandbox in one step.
402
+ *
403
+ * This is the recommended way to create a sandbox. It combines
404
+ * construction and initialization into a single async operation.
405
+ *
406
+ * @param options - Configuration options for the sandbox
407
+ * @returns An initialized and ready-to-use sandbox
408
+ *
409
+ * @example
410
+ * ```typescript
411
+ * const sandbox = await DenoSandbox.create({
412
+ * memoryMb: 1024,
413
+ * lifetime: "10m",
414
+ * region: "iad",
415
+ * });
416
+ * ```
417
+ */
418
+ static create(options?: DenoSandboxOptions): Promise<DenoSandbox>;
419
+ /**
420
+ * Reconnect to an existing sandbox by ID.
421
+ *
422
+ * This allows you to resume working with a sandbox that was created
423
+ * earlier with a duration-based lifetime.
424
+ *
425
+ * @param sandboxId - The ID of the sandbox to reconnect to
426
+ * @param options - Optional auth configuration (for token)
427
+ * @returns A connected sandbox instance
428
+ *
429
+ * @example
430
+ * ```typescript
431
+ * // Resume a sandbox from a stored ID
432
+ * const sandbox = await DenoSandbox.connect("sandbox-abc123");
433
+ * const result = await sandbox.execute("ls -la");
434
+ * ```
435
+ */
436
+ static connect(sandboxId: string, options?: Pick<DenoSandboxOptions, "auth">): Promise<DenoSandbox>;
437
+ }
438
+ /**
439
+ * Async factory function type for creating Deno Sandbox instances.
440
+ *
441
+ * This is similar to BackendFactory but supports async creation,
442
+ * which is required for Deno Sandbox since initialization is async.
443
+ */
444
+ type AsyncDenoSandboxFactory = () => Promise<DenoSandbox>;
445
+ /**
446
+ * Create an async factory function that creates a new Deno Sandbox per invocation.
447
+ *
448
+ * Each call to the factory will create and initialize a new sandbox.
449
+ * This is useful when you want fresh, isolated environments for each
450
+ * agent invocation.
451
+ *
452
+ * **Important**: This returns an async factory. For use with middleware that
453
+ * requires synchronous BackendFactory, use `createDenoSandboxFactoryFromSandbox()`
454
+ * with a pre-created sandbox instead.
455
+ *
456
+ * @param options - Optional configuration for sandbox creation
457
+ * @returns An async factory function that creates new sandboxes
458
+ *
459
+ * @example
460
+ * ```typescript
461
+ * import { DenoSandbox, createDenoSandboxFactory } from "@langchain/deno";
462
+ *
463
+ * // Create a factory for new sandboxes
464
+ * const factory = createDenoSandboxFactory({ memoryMb: 1024 });
465
+ *
466
+ * // Each call creates a new sandbox
467
+ * const sandbox1 = await factory();
468
+ * const sandbox2 = await factory();
469
+ *
470
+ * try {
471
+ * // Use sandboxes...
472
+ * } finally {
473
+ * await sandbox1.close();
474
+ * await sandbox2.close();
475
+ * }
476
+ * ```
477
+ */
478
+ declare function createDenoSandboxFactory(options?: DenoSandboxOptions): AsyncDenoSandboxFactory;
479
+ /**
480
+ * Create a backend factory that reuses an existing Deno Sandbox.
481
+ *
482
+ * This allows multiple agent invocations to share the same sandbox,
483
+ * avoiding the startup overhead of creating new sandboxes.
484
+ *
485
+ * Important: You are responsible for managing the sandbox lifecycle
486
+ * (calling `close()` when done).
487
+ *
488
+ * @param sandbox - An existing DenoSandbox instance (must be initialized)
489
+ * @returns A BackendFactory that returns the provided sandbox
490
+ *
491
+ * @example
492
+ * ```typescript
493
+ * import { createDeepAgent, createFilesystemMiddleware } from "deepagents";
494
+ * import { DenoSandbox, createDenoSandboxFactoryFromSandbox } from "@langchain/deno";
495
+ *
496
+ * // Create and initialize a sandbox
497
+ * const sandbox = await DenoSandbox.create({ memoryMb: 1024 });
498
+ *
499
+ * try {
500
+ * const agent = createDeepAgent({
501
+ * model: new ChatAnthropic({ model: "claude-sonnet-4-20250514" }),
502
+ * systemPrompt: "You are a coding assistant.",
503
+ * middlewares: [
504
+ * createFilesystemMiddleware({
505
+ * backend: createDenoSandboxFactoryFromSandbox(sandbox),
506
+ * }),
507
+ * ],
508
+ * });
509
+ *
510
+ * await agent.invoke({ messages: [...] });
511
+ * } finally {
512
+ * await sandbox.close();
513
+ * }
514
+ * ```
515
+ */
516
+ declare function createDenoSandboxFactoryFromSandbox(sandbox: DenoSandbox): BackendFactory;
517
+ //#endregion
518
+ //#region src/auth.d.ts
519
+ /**
520
+ * Authentication credentials for Deno Sandbox API.
521
+ */
522
+ interface DenoCredentials {
523
+ /** Deno Deploy access token */
524
+ token: string;
525
+ }
526
+ /**
527
+ * Get the authentication token for Deno Sandbox API.
528
+ *
529
+ * Authentication is resolved in the following priority order:
530
+ *
531
+ * 1. **Explicit token**: If `options.token` is provided, it is used directly.
532
+ * 2. **DENO_DEPLOY_TOKEN**: Environment variable for Deno Deploy access token.
533
+ *
534
+ * If no token is found, an error is thrown with setup instructions.
535
+ *
536
+ * ## Environment Variable Setup
537
+ *
538
+ * ```bash
539
+ * # Go to https://app.deno.com -> Settings -> Organization Tokens
540
+ * # Create a new token and set it as environment variable
541
+ * export DENO_DEPLOY_TOKEN=your_token_here
542
+ * ```
543
+ *
544
+ * @param options - Optional authentication configuration from DenoSandboxOptions
545
+ * @returns The authentication token string
546
+ * @throws {Error} If no authentication token is available
547
+ *
548
+ * @example
549
+ * ```typescript
550
+ * // With explicit token
551
+ * const token = getAuthToken({ token: "my-token" });
552
+ *
553
+ * // Using environment variables (auto-detected)
554
+ * const token = getAuthToken();
555
+ *
556
+ * // From DenoSandboxOptions
557
+ * const options: DenoSandboxOptions = {
558
+ * auth: { token: "my-token" }
559
+ * };
560
+ * const token = getAuthToken(options.auth);
561
+ * ```
562
+ */
563
+ declare function getAuthToken(options?: DenoSandboxOptions["auth"]): string;
564
+ /**
565
+ * Get authentication credentials for Deno Sandbox API.
566
+ *
567
+ * This function returns the credentials needed for the Deno SDK.
568
+ *
569
+ * @param options - Optional authentication configuration from DenoSandboxOptions
570
+ * @returns Complete authentication credentials
571
+ * @throws {Error} If no authentication token is available
572
+ */
573
+ declare function getAuthCredentials(options?: DenoSandboxOptions["auth"]): DenoCredentials;
574
+ //#endregion
575
+ export { type AsyncDenoSandboxFactory, type DenoCredentials, DenoSandbox, DenoSandboxError, type DenoSandboxErrorCode, type DenoSandboxOptions, type DenoSandboxRegion, type SandboxLifetime, createDenoSandboxFactory, createDenoSandboxFactoryFromSandbox, getAuthCredentials, getAuthToken };
576
+ //# sourceMappingURL=index.d.ts.map