deepagents 1.10.2 → 1.10.4

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,4046 @@
1
+ import * as _langchain from "langchain";
2
+ import { AgentMiddleware, AgentMiddleware as AgentMiddleware$1, AgentRunStream, AgentTypeConfig, CreateAgentParams, HumanMessage, InferMiddlewareStates, InterruptOnConfig, ProviderStrategy, ReactAgent, ResponseFormat, ResponseFormatUndefined, Runtime, StructuredTool, SystemMessage, ToolCallStreamUnion, ToolMessage, ToolRuntime, ToolStrategy } from "langchain";
3
+ import * as _langgraph from "@langchain/langgraph";
4
+ import { AnnotationRoot, AnyStateSchema, ChatModelStream, Command, Namespace, NativeStreamTransformer, ReducedValue, StateDefinitionInit, StateSchema, StreamTransformer } from "@langchain/langgraph";
5
+ import { z } from "zod/v4";
6
+ import { BaseCheckpointSaver, BaseStore } from "@langchain/langgraph-checkpoint";
7
+ import * as _messages from "@langchain/core/messages";
8
+ import { ClientTool, ServerTool, StructuredTool as StructuredTool$1 } from "@langchain/core/tools";
9
+ import { BaseLanguageModel, LanguageModelLike } from "@langchain/core/language_models/base";
10
+ import { Runnable } from "@langchain/core/runnables";
11
+ import * as z$2 from "zod";
12
+ import { z as z$1 } from "zod";
13
+ import { BaseChatModel } from "@langchain/core/language_models/chat_models";
14
+ import { InteropZodObject } from "@langchain/core/utils/types";
15
+ import { Client } from "langsmith";
16
+ import { CaptureSnapshotOptions, CaptureSnapshotOptions as LangSmithCaptureSnapshotOptions, CreateSandboxOptions, Sandbox, Snapshot, Snapshot as LangSmithSnapshot, StartSandboxOptions, StartSandboxOptions as LangSmithStartSandboxOptions } from "langsmith/experimental/sandbox";
17
+
18
+ //#region src/backends/v1/protocol.d.ts
19
+ /**
20
+ * Protocol for pluggable memory backends (single, unified).
21
+ *
22
+ * Backends can store files in different locations (state, filesystem, database, etc.)
23
+ * and provide a uniform interface for file operations.
24
+ *
25
+ * All file data is represented as objects with the FileData structure.
26
+ *
27
+ * Methods can return either direct values or Promises, allowing both
28
+ * synchronous and asynchronous implementations.
29
+ *
30
+ * @deprecated Use {@link BackendProtocolV2} instead.
31
+ */
32
+ interface BackendProtocolV1 {
33
+ /**
34
+ * Structured listing with file metadata.
35
+ *
36
+ * Lists files and directories in the specified directory (non-recursive).
37
+ * Directories have a trailing / in their path and is_dir=true.
38
+ *
39
+ * @param path - Absolute path to directory
40
+ * @returns List of FileInfo objects for files and directories directly in the directory
41
+ */
42
+ lsInfo(path: string): MaybePromise<FileInfo[]>;
43
+ /**
44
+ * Read file content.
45
+ *
46
+ * @param filePath - Absolute file path
47
+ * @param offset - Line offset to start reading from (0-indexed), default 0
48
+ * @param limit - Maximum number of lines to read, default 500
49
+ * @returns File content as plain string on success or error on failure
50
+ */
51
+ read(filePath: string, offset?: number, limit?: number): MaybePromise<string>;
52
+ /**
53
+ * Read file content as raw FileData.
54
+ *
55
+ * @param filePath - Absolute file path
56
+ * @returns Raw file content as FileData
57
+ */
58
+ readRaw(filePath: string): MaybePromise<FileData>;
59
+ /**
60
+ * Search file contents for a literal text pattern.
61
+ *
62
+ * Binary files (determined by MIME type) are skipped.
63
+ *
64
+ * @param pattern - Literal text pattern to search for
65
+ * @param path - Base path to search from (default: null)
66
+ * @param glob - Optional glob pattern to filter files (e.g., "*.py")
67
+ * @returns Array of GrepMatch on success or error string on failure
68
+ */
69
+ grepRaw(pattern: string, path?: string | null, glob?: string | null): MaybePromise<GrepMatch[] | string>;
70
+ /**
71
+ * Structured glob matching returning FileInfo objects.
72
+ *
73
+ * @param pattern - Glob pattern (e.g., `*.py`, `**\/*.ts`)
74
+ * @param path - Base path to search from (default: "/")
75
+ * @returns List of FileInfo objects matching the pattern
76
+ */
77
+ globInfo(pattern: string, path?: string): MaybePromise<FileInfo[]>;
78
+ /**
79
+ * Create a new file.
80
+ *
81
+ * @param filePath - Absolute file path
82
+ * @param content - File content as string
83
+ * @returns WriteResult with error populated on failure
84
+ */
85
+ write(filePath: string, content: string): MaybePromise<WriteResult>;
86
+ /**
87
+ * Edit a file by replacing string occurrences.
88
+ *
89
+ * @param filePath - Absolute file path
90
+ * @param oldString - String to find and replace
91
+ * @param newString - Replacement string
92
+ * @param replaceAll - If true, replace all occurrences (default: false)
93
+ * @returns EditResult with error, path, filesUpdate, and occurrences
94
+ */
95
+ edit(filePath: string, oldString: string, newString: string, replaceAll?: boolean): MaybePromise<EditResult>;
96
+ /**
97
+ * Upload multiple files.
98
+ * Optional - backends that don't support file upload can omit this.
99
+ *
100
+ * @param files - List of [path, content] tuples to upload
101
+ * @returns List of FileUploadResponse objects, one per input file
102
+ */
103
+ uploadFiles?(files: Array<[string, Uint8Array]>): MaybePromise<FileUploadResponse[]>;
104
+ /**
105
+ * Download multiple files.
106
+ * Optional - backends that don't support file download can omit this.
107
+ *
108
+ * @param paths - List of file paths to download
109
+ * @returns List of FileDownloadResponse objects, one per input path
110
+ */
111
+ downloadFiles?(paths: string[]): MaybePromise<FileDownloadResponse[]>;
112
+ }
113
+ /**
114
+ * Protocol for sandboxed backends with isolated runtime.
115
+ * Sandboxed backends run in isolated environments (e.g., containers)
116
+ * and communicate via defined interfaces.
117
+ *
118
+ * @deprecated Use {@link SandboxBackendProtocolV2} instead.
119
+ */
120
+ interface SandboxBackendProtocolV1 extends BackendProtocolV1 {
121
+ /**
122
+ * Execute a command in the sandbox.
123
+ *
124
+ * @param command - Full shell command string to execute
125
+ * @returns ExecuteResponse with combined output, exit code, and truncation flag
126
+ */
127
+ execute(command: string): MaybePromise<ExecuteResponse>;
128
+ /** Unique identifier for the sandbox backend instance */
129
+ readonly id: string;
130
+ }
131
+ //#endregion
132
+ //#region src/backends/v2/protocol.d.ts
133
+ /**
134
+ * Updated protocol for pluggable memory backends.
135
+ *
136
+ * Key differences from {@link BackendProtocol}:
137
+ * - `read()` returns {@link ReadResult} instead of a plain string
138
+ * - `readRaw()` returns {@link ReadRawResult} instead of FileData
139
+ * - `grep()` returns {@link GrepResult} instead of `GrepMatch[] | string`
140
+ * - `ls()` returns {@link LsResult} instead of FileInfo[]
141
+ * - `glob()` returns {@link GlobResult} instead of FileInfo[]
142
+ *
143
+ * Existing v1 backends can be adapted to this interface using
144
+ * {@link adaptBackendProtocol} from utils.
145
+ */
146
+ interface BackendProtocolV2 extends Omit<BackendProtocolV1, "read" | "readRaw" | "grepRaw" | "lsInfo" | "globInfo"> {
147
+ /**
148
+ * Structured listing with file metadata.
149
+ *
150
+ * Lists files and directories in the specified directory (non-recursive).
151
+ * Directories have a trailing / in their path and is_dir=true.
152
+ *
153
+ * @param path - Absolute path to directory
154
+ * @returns LsResult with list of FileInfo objects on success or error on failure
155
+ */
156
+ ls(path: string): MaybePromise<LsResult>;
157
+ /**
158
+ * Read file content.
159
+ *
160
+ * For text files, content is paginated by line offset/limit.
161
+ * For binary files, the full raw Uint8Array content is returned.
162
+ *
163
+ * @param filePath - Absolute file path
164
+ * @param offset - Line offset to start reading from (0-indexed), default 0
165
+ * @param limit - Maximum number of lines to read, default 500
166
+ * @returns ReadResult with content on success or error on failure
167
+ */
168
+ read(filePath: string, offset?: number, limit?: number): MaybePromise<ReadResult>;
169
+ /**
170
+ * Read file content as raw FileData.
171
+ *
172
+ * @param filePath - Absolute file path
173
+ * @returns ReadRawResult with raw file data on success or error on failure
174
+ */
175
+ readRaw(filePath: string): MaybePromise<ReadRawResult>;
176
+ /**
177
+ * Search file contents for a literal text pattern.
178
+ *
179
+ * Binary files (determined by MIME type) are skipped.
180
+ *
181
+ * @param pattern - Literal text pattern to search for
182
+ * @param path - Base path to search from (default: null)
183
+ * @param glob - Optional glob pattern to filter files (e.g., "*.py")
184
+ * @returns GrepResult with matches on success or error on failure
185
+ */
186
+ grep(pattern: string, path?: string | null, glob?: string | null): MaybePromise<GrepResult>;
187
+ /**
188
+ * Structured glob matching returning FileInfo objects.
189
+ *
190
+ * @param pattern - Glob pattern (e.g., `*.py`, `**\/*.ts`)
191
+ * @param path - Base path to search from (default: "/")
192
+ * @returns GlobResult with list of FileInfo objects matching the pattern on success or error on failure
193
+ */
194
+ glob(pattern: string, path?: string): MaybePromise<GlobResult>;
195
+ }
196
+ /**
197
+ * Protocol for sandboxed backends with isolated runtime.
198
+ *
199
+ * Key differences from {@link SandboxBackendProtocol}:
200
+ * - Extends {@link BackendProtocolV2} instead of {@link BackendProtocol}
201
+ * - All methods return structured Result types for consistent error handling
202
+ */
203
+ interface SandboxBackendProtocolV2 extends BackendProtocolV2 {
204
+ /**
205
+ * Execute a command in the sandbox.
206
+ *
207
+ * @param command - Full shell command string to execute
208
+ * @returns ExecuteResponse with combined output, exit code, and truncation flag
209
+ */
210
+ execute(command: string): MaybePromise<ExecuteResponse>;
211
+ /** Unique identifier for the sandbox backend instance */
212
+ readonly id: string;
213
+ }
214
+ //#endregion
215
+ //#region src/backends/protocol.d.ts
216
+ /** @deprecated Use {@link BackendProtocolV2} instead. */
217
+ interface BackendProtocol extends BackendProtocolV1 {}
218
+ /** @deprecated Use {@link SandboxBackendProtocolV2} instead. */
219
+ interface SandboxBackendProtocol extends SandboxBackendProtocolV1 {}
220
+ type MaybePromise<T> = T | Promise<T>;
221
+ /**
222
+ * Structured file listing info.
223
+ *
224
+ * Minimal contract used across backends. Only "path" is required.
225
+ * Other fields are best-effort and may be absent depending on backend.
226
+ */
227
+ interface FileInfo {
228
+ /** File path */
229
+ path: string;
230
+ /** Whether this is a directory */
231
+ is_dir?: boolean;
232
+ /** File size in bytes (approximate) */
233
+ size?: number;
234
+ /** ISO 8601 timestamp of last modification */
235
+ modified_at?: string;
236
+ }
237
+ /**
238
+ * Structured grep match entry.
239
+ */
240
+ interface GrepMatch {
241
+ /** File path where match was found */
242
+ path: string;
243
+ /** Line number (1-indexed) */
244
+ line: number;
245
+ /** The matching line text */
246
+ text: string;
247
+ }
248
+ /**
249
+ * Structured result from grep/search operations.
250
+ */
251
+ interface GrepResult {
252
+ /** Error message on failure, undefined on success */
253
+ error?: string;
254
+ /** Structured grep match entries, undefined on failure */
255
+ matches?: GrepMatch[];
256
+ }
257
+ /**
258
+ * Legacy file data format (v1).
259
+ *
260
+ * Content is stored as an array of lines (split on "\n"). This format
261
+ * only supports text files and is retained for backwards compatibility
262
+ * with existing state/store data.
263
+ */
264
+ interface FileDataV1 {
265
+ /** File content as an array of lines */
266
+ content: string[];
267
+ /** ISO format timestamp of creation */
268
+ created_at: string;
269
+ /** ISO format timestamp of last modification */
270
+ modified_at: string;
271
+ }
272
+ /**
273
+ * Current file data format (v2).
274
+ *
275
+ * Content is stored as a string for text files, or as a Uint8Array for
276
+ * binary files (images, PDFs, audio, etc.). The MIME type is stored
277
+ * alongside the content, allowing backend implementations to determine
278
+ * it however they see fit (e.g. from file extension, HTTP headers,
279
+ * database metadata, etc.).
280
+ */
281
+ interface FileDataV2 {
282
+ /** File content: string for text, Uint8Array for binary */
283
+ content: string | Uint8Array;
284
+ /** MIME type of the file (e.g. "image/png", "text/plain") */
285
+ mimeType: string;
286
+ /** ISO format timestamp of creation */
287
+ created_at: string;
288
+ /** ISO format timestamp of last modification */
289
+ modified_at: string;
290
+ }
291
+ /**
292
+ * Union of v1 and v2 file data formats.
293
+ *
294
+ * Backends may encounter either format when reading from state or store
295
+ * (v1 from legacy data, v2 from new writes). Use {@link isFileDataV1}
296
+ * from utils for runtime discrimination.
297
+ */
298
+ type FileData = FileDataV1 | FileDataV2;
299
+ /**
300
+ * Structured result from backend read operations.
301
+ *
302
+ * Replaces the previous plain string return, giving callers a
303
+ * programmatic way to distinguish errors from content.
304
+ */
305
+ interface ReadResult {
306
+ /** Error message on failure, undefined on success */
307
+ error?: string;
308
+ /** File content: string for text, Uint8Array for binary. Undefined on failure. */
309
+ content?: string | Uint8Array;
310
+ /** MIME type of the file, when available */
311
+ mimeType?: string;
312
+ }
313
+ /**
314
+ * Structured result from backend readRaw operations.
315
+ */
316
+ interface ReadRawResult {
317
+ /** Error message on failure, undefined on success */
318
+ error?: string;
319
+ /** Raw file data, undefined on failure */
320
+ data?: FileData;
321
+ }
322
+ /**
323
+ * Structured result from backend ls operations.
324
+ */
325
+ interface LsResult {
326
+ /** Error message on failure, undefined on success */
327
+ error?: string;
328
+ /** List of FileInfo objects, undefined on failure */
329
+ files?: FileInfo[];
330
+ }
331
+ /**
332
+ * Structured result from backend glob operations.
333
+ */
334
+ interface GlobResult {
335
+ /** Error message on failure, undefined on success */
336
+ error?: string;
337
+ /** List of FileInfo objects matching the pattern, undefined on failure */
338
+ files?: FileInfo[];
339
+ }
340
+ /**
341
+ * Result from backend write operations.
342
+ *
343
+ * Checkpoint backends populate filesUpdate with {file_path: file_data} for LangGraph state.
344
+ * External backends set filesUpdate to null (already persisted to disk/S3/database/etc).
345
+ */
346
+ interface WriteResult {
347
+ /** Error message on failure, undefined on success */
348
+ error?: string;
349
+ /** File path of written file, undefined on failure */
350
+ path?: string;
351
+ /**
352
+ * State update dict for checkpoint backends, null for external storage.
353
+ * Checkpoint backends populate this with {file_path: file_data} for LangGraph state.
354
+ * External backends set null (already persisted to disk/S3/database/etc).
355
+ *
356
+ * @deprecated Zero-arg backends send state updates internally via
357
+ * `__pregel_send`. Check `if (result.filesUpdate)` before using.
358
+ */
359
+ filesUpdate?: Record<string, FileData> | null;
360
+ /** Metadata for the write operation, attached to the ToolMessage */
361
+ metadata?: Record<string, unknown>;
362
+ }
363
+ /**
364
+ * Result from backend edit operations.
365
+ *
366
+ * Checkpoint backends populate filesUpdate with {file_path: file_data} for LangGraph state.
367
+ * External backends set filesUpdate to null (already persisted to disk/S3/database/etc).
368
+ */
369
+ interface EditResult {
370
+ /** Error message on failure, undefined on success */
371
+ error?: string;
372
+ /** File path of edited file, undefined on failure */
373
+ path?: string;
374
+ /**
375
+ * State update dict for checkpoint backends, null for external storage.
376
+ * Checkpoint backends populate this with {file_path: file_data} for LangGraph state.
377
+ * External backends set null (already persisted to disk/S3/database/etc).
378
+ *
379
+ * @deprecated Zero-arg backends send state updates internally via
380
+ * `__pregel_send`. Check `if (result.filesUpdate)` before using.
381
+ */
382
+ filesUpdate?: Record<string, FileData> | null;
383
+ /** Number of replacements made, undefined on failure */
384
+ occurrences?: number;
385
+ /** Metadata for the edit operation, attached to the ToolMessage */
386
+ metadata?: Record<string, unknown>;
387
+ }
388
+ /**
389
+ * Result of code execution.
390
+ * Simplified schema optimized for LLM consumption.
391
+ */
392
+ interface ExecuteResponse {
393
+ /** Combined stdout and stderr output of the executed command */
394
+ output: string;
395
+ /** The process exit code. 0 indicates success, non-zero indicates failure */
396
+ exitCode: number | null;
397
+ /** Whether the output was truncated due to backend limitations */
398
+ truncated: boolean;
399
+ }
400
+ /**
401
+ * Standardized error codes for file upload/download operations.
402
+ */
403
+ type FileOperationError = "file_not_found" | "permission_denied" | "is_directory" | "invalid_path";
404
+ /**
405
+ * Result of a single file download operation.
406
+ */
407
+ interface FileDownloadResponse {
408
+ /** The file path that was requested */
409
+ path: string;
410
+ /** File contents as Uint8Array on success, null on failure */
411
+ content: Uint8Array | null;
412
+ /** Standardized error code on failure, null on success */
413
+ error: FileOperationError | null;
414
+ }
415
+ /**
416
+ * Result of a single file upload operation.
417
+ */
418
+ interface FileUploadResponse {
419
+ /** The file path that was requested */
420
+ path: string;
421
+ /** Standardized error code on failure, null on success */
422
+ error: FileOperationError | null;
423
+ }
424
+ /**
425
+ * Common options shared across backend constructors.
426
+ */
427
+ interface BackendOptions {
428
+ /** File data format to use for new writes. Defaults to "v2". */
429
+ fileFormat?: "v1" | "v2";
430
+ }
431
+ /**
432
+ * Type guard to check if a backend supports execution.
433
+ *
434
+ * @param backend - Backend instance to check
435
+ * @returns True if the backend implements SandboxBackendProtocolV2
436
+ */
437
+ declare function isSandboxBackend(backend: unknown): backend is SandboxBackendProtocolV2;
438
+ /**
439
+ * Union of v1 and v2 sandbox backend protocols.
440
+ *
441
+ * Use this when accepting either protocol version. Pass through
442
+ * {@link adaptSandboxProtocol} to normalize to {@link SandboxBackendProtocolV2}.
443
+ */
444
+ type AnySandboxProtocol = SandboxBackendProtocol | SandboxBackendProtocolV2;
445
+ /**
446
+ * Type guard to check if a backend is a sandbox protocol (v1 or v2).
447
+ *
448
+ * Checks for the presence of `execute` function and `id` string,
449
+ * which are the defining features of sandbox protocols.
450
+ *
451
+ * @param backend - Backend instance to check
452
+ * @returns True if the backend implements sandbox protocol (v1 or v2)
453
+ */
454
+ declare function isSandboxProtocol(backend: unknown): backend is AnySandboxProtocol;
455
+ /**
456
+ * Metadata for a single sandbox instance.
457
+ *
458
+ * This lightweight structure is returned from list operations and provides
459
+ * basic information about a sandbox without requiring a full connection.
460
+ *
461
+ * @typeParam MetadataT - Type of the metadata field. Providers can define
462
+ * their own interface for type-safe metadata access.
463
+ *
464
+ * @example
465
+ * ```typescript
466
+ * // Using default metadata type
467
+ * const info: SandboxInfo = {
468
+ * sandboxId: "sb_abc123",
469
+ * metadata: { status: "running", createdAt: "2024-01-15T10:30:00Z" },
470
+ * };
471
+ *
472
+ * // Using typed metadata
473
+ * interface MyMetadata {
474
+ * status: "running" | "stopped";
475
+ * createdAt: string;
476
+ * }
477
+ * const typedInfo: SandboxInfo<MyMetadata> = {
478
+ * sandboxId: "sb_abc123",
479
+ * metadata: { status: "running", createdAt: "2024-01-15T10:30:00Z" },
480
+ * };
481
+ * ```
482
+ */
483
+ interface SandboxInfo<MetadataT = Record<string, unknown>> {
484
+ /** Unique identifier for the sandbox instance */
485
+ sandboxId: string;
486
+ /** Optional provider-specific metadata (e.g., creation time, status, template) */
487
+ metadata?: MetadataT;
488
+ }
489
+ /**
490
+ * Paginated response from a sandbox list operation.
491
+ *
492
+ * This structure supports cursor-based pagination for efficiently browsing
493
+ * large collections of sandboxes.
494
+ *
495
+ * @typeParam MetadataT - Type of the metadata field in SandboxInfo items.
496
+ *
497
+ * @example
498
+ * ```typescript
499
+ * const response: SandboxListResponse = {
500
+ * items: [
501
+ * { sandboxId: "sb_001", metadata: { status: "running" } },
502
+ * { sandboxId: "sb_002", metadata: { status: "stopped" } },
503
+ * ],
504
+ * cursor: "eyJvZmZzZXQiOjEwMH0=",
505
+ * };
506
+ *
507
+ * // Fetch next page
508
+ * const nextResponse = await provider.list({ cursor: response.cursor });
509
+ * ```
510
+ */
511
+ interface SandboxListResponse<MetadataT = Record<string, unknown>> {
512
+ /** List of sandbox metadata objects for the current page */
513
+ items: SandboxInfo<MetadataT>[];
514
+ /**
515
+ * Opaque continuation token for retrieving the next page.
516
+ * null indicates no more pages available.
517
+ */
518
+ cursor: string | null;
519
+ }
520
+ /**
521
+ * Options for listing sandboxes.
522
+ */
523
+ interface SandboxListOptions {
524
+ /**
525
+ * Continuation token from a previous list() call.
526
+ * Pass undefined to start from the beginning.
527
+ */
528
+ cursor?: string;
529
+ }
530
+ /**
531
+ * Options for getting or creating a sandbox.
532
+ */
533
+ interface SandboxGetOrCreateOptions {
534
+ /**
535
+ * Unique identifier of an existing sandbox to retrieve.
536
+ * If undefined, creates a new sandbox instance.
537
+ * If provided but the sandbox doesn't exist, an error will be thrown.
538
+ */
539
+ sandboxId?: string;
540
+ }
541
+ /**
542
+ * Options for deleting a sandbox.
543
+ */
544
+ interface SandboxDeleteOptions {
545
+ /** Unique identifier of the sandbox to delete */
546
+ sandboxId: string;
547
+ }
548
+ /**
549
+ * Common error codes shared across all sandbox provider implementations.
550
+ *
551
+ * These represent the core error conditions that any sandbox provider may encounter.
552
+ * Provider-specific error codes should extend this type with additional codes.
553
+ *
554
+ * @example
555
+ * ```typescript
556
+ * // Provider-specific error code type extending the common codes:
557
+ * type MySandboxErrorCode = SandboxErrorCode | "CUSTOM_ERROR";
558
+ * ```
559
+ */
560
+ type SandboxErrorCode = /** Sandbox has not been initialized - call initialize() first */"NOT_INITIALIZED" /** Sandbox is already initialized - cannot initialize twice */ | "ALREADY_INITIALIZED" /** Command execution timed out */ | "COMMAND_TIMEOUT" /** Command execution failed */ | "COMMAND_FAILED" /** File operation (read/write) failed */ | "FILE_OPERATION_FAILED";
561
+ declare const SANDBOX_ERROR_SYMBOL: unique symbol;
562
+ /**
563
+ * Custom error class for sandbox operations.
564
+ *
565
+ * @param message - Human-readable error description
566
+ * @param code - Structured error code for programmatic handling
567
+ * @returns SandboxError with message and code
568
+ *
569
+ * @example
570
+ * ```typescript
571
+ * try {
572
+ * await sandbox.execute("some command");
573
+ * } catch (error) {
574
+ * if (error instanceof SandboxError) {
575
+ * switch (error.code) {
576
+ * case "NOT_INITIALIZED":
577
+ * await sandbox.initialize();
578
+ * break;
579
+ * case "COMMAND_TIMEOUT":
580
+ * console.error("Command took too long");
581
+ * break;
582
+ * default:
583
+ * throw error;
584
+ * }
585
+ * }
586
+ * }
587
+ * ```
588
+ */
589
+ declare class SandboxError extends Error {
590
+ readonly code: string;
591
+ readonly cause?: Error | undefined;
592
+ /** Symbol for identifying sandbox error instances */
593
+ [SANDBOX_ERROR_SYMBOL]: true;
594
+ /** Error name for instanceof checks and logging */
595
+ readonly name: string;
596
+ /**
597
+ * Creates a new SandboxError.
598
+ *
599
+ * @param message - Human-readable error description
600
+ * @param code - Structured error code for programmatic handling
601
+ */
602
+ constructor(message: string, code: string, cause?: Error | undefined);
603
+ static isInstance(error: unknown): error is SandboxError;
604
+ }
605
+ /**
606
+ * State and store container for backend initialization.
607
+ *
608
+ * This provides a clean interface for what backends need to access:
609
+ * - state: Current agent state (with files, messages, etc.)
610
+ * - store: Optional persistent store for cross-conversation data
611
+ *
612
+ * Different contexts build this differently:
613
+ * - Tools: Extract state via getCurrentTaskInput(config)
614
+ * - Middleware: Use request.state directly
615
+ *
616
+ * @deprecated Use {@link BackendRuntime} instead.
617
+ */
618
+ interface StateAndStore {
619
+ /** Current agent state with files, messages, etc. */
620
+ state: unknown;
621
+ /** Optional BaseStore for persistent cross-conversation storage */
622
+ store?: BaseStore;
623
+ /** Optional assistant ID for per-assistant isolation in store */
624
+ assistantId?: string;
625
+ }
626
+ /**
627
+ * Union of v1 and v2 backend protocols.
628
+ *
629
+ * Use this when accepting either protocol version. Pass through
630
+ * {@link adaptBackendProtocol} to normalize to {@link BackendProtocolV2}.
631
+ */
632
+ type AnyBackendProtocol = BackendProtocolV1 | BackendProtocolV2;
633
+ /**
634
+ * Agent {@link Runtime} with `state`
635
+ *
636
+ * @deprecated Backends now read state from the LangGraph execution context
637
+ * via `getCurrentTaskInput()`, `getConfig()`, and `getStore()`.
638
+ */
639
+ interface BackendRuntime<StateT = unknown> extends Runtime {
640
+ /** Current agent state with files, messages, etc. */
641
+ state: StateT;
642
+ }
643
+ /**
644
+ * Factory function type for creating backend instances.
645
+ *
646
+ * Backends receive {@link BackendRuntime} which contains the current state
647
+ * and runtime information, extracted from the execution context.
648
+ *
649
+ * @deprecated Pass a pre-constructed backend instance instead of a factory.
650
+ * E.g., `backend: new StateBackend()` instead of `backend: (runtime) => new StateBackend(runtime)`.
651
+ *
652
+ * @example
653
+ * ```typescript
654
+ * // Using in middleware
655
+ * const middleware = createFilesystemMiddleware({
656
+ * backend: (runtime) => new StateBackend(runtime)
657
+ * });
658
+ * ```
659
+ */
660
+ type BackendFactory = (runtime: BackendRuntime) => MaybePromise<AnyBackendProtocol>;
661
+ /**
662
+ * Resolve a backend instance or await a {@link BackendFactory}.
663
+ *
664
+ * Accepts {@link BackendRuntime} or {@link ToolRuntime} — store typing differs
665
+ * between LangGraph checkpoint stores and core `ToolRuntime`; factories receive
666
+ * a value that is structurally compatible at runtime.
667
+ *
668
+ * @internal
669
+ */
670
+ declare function resolveBackend(backend: AnyBackendProtocol | BackendFactory, runtime: BackendRuntime | ToolRuntime): Promise<BackendProtocolV2>;
671
+ //#endregion
672
+ //#region src/permissions/types.d.ts
673
+ /**
674
+ * The filesystem operations a permission rule can govern.
675
+ */
676
+ type FilesystemOperation = "read" | "write";
677
+ /**
678
+ * Whether a matched rule permits or blocks the operation.
679
+ */
680
+ type PermissionMode = "allow" | "deny";
681
+ /**
682
+ * A single filesystem permission rule.
683
+ *
684
+ * Rules are evaluated in declaration order; the first rule whose
685
+ * `operations` includes the requested operation AND whose `paths`
686
+ * glob-matches the target path determines the outcome. If no rule
687
+ * matches, access is **allowed** (permissive default).
688
+ *
689
+ * All `paths` must be absolute glob patterns (start with `/`, no `..` or `~`).
690
+ * Supports `**` (any depth), `*` (within one segment), and `{a,b}` brace expansion.
691
+ * Paths are validated when passed to {@link createFilesystemMiddleware}.
692
+ */
693
+ interface FilesystemPermission {
694
+ /**
695
+ * The operations this rule applies to.
696
+ */
697
+ operations: readonly FilesystemOperation[];
698
+ /**
699
+ * Absolute glob patterns for paths this rule matches.
700
+ * Must start with `/`; must not contain `..` or `~`.
701
+ * Supports `**` (any depth), `*` (within one segment), and `{a,b}` brace expansion.
702
+ */
703
+ paths: string[];
704
+ /**
705
+ * Whether matching paths are permitted or blocked. Defaults to `"allow"`.
706
+ */
707
+ mode?: PermissionMode;
708
+ }
709
+ //#endregion
710
+ //#region src/middleware/fs.d.ts
711
+ /**
712
+ * Tools that should be excluded from the large result eviction logic.
713
+ *
714
+ * This array contains tools that should NOT have their results evicted to the filesystem
715
+ * when they exceed token limits. Tools are excluded for different reasons:
716
+ *
717
+ * 1. Tools with built-in truncation (ls, glob, grep):
718
+ * These tools truncate their own output when it becomes too large. When these tools
719
+ * produce truncated output due to many matches, it typically indicates the query
720
+ * needs refinement rather than full result preservation. In such cases, the truncated
721
+ * matches are potentially more like noise and the LLM should be prompted to narrow
722
+ * its search criteria instead.
723
+ *
724
+ * 2. Tools with problematic truncation behavior (read_file):
725
+ * read_file is tricky to handle as the failure mode here is single long lines
726
+ * (e.g., imagine a jsonl file with very long payloads on each line). If we try to
727
+ * truncate the result of read_file, the agent may then attempt to re-read the
728
+ * truncated file using read_file again, which won't help.
729
+ *
730
+ * 3. Tools that never exceed limits (edit_file, write_file):
731
+ * These tools return minimal confirmation messages and are never expected to produce
732
+ * output large enough to exceed token limits, so checking them would be unnecessary.
733
+ */
734
+ /**
735
+ * All tool names registered by FilesystemMiddleware.
736
+ * This is the single source of truth — used by createDeepAgent to detect
737
+ * collisions with user-supplied tools at construction time.
738
+ */
739
+ declare const FILESYSTEM_TOOL_NAMES: readonly ["ls", "read_file", "write_file", "edit_file", "glob", "grep", "execute"];
740
+ /**
741
+ * Type for the files state record.
742
+ */
743
+ type FilesRecord = Record<string, FileData>;
744
+ /**
745
+ * Type for file updates, where null indicates deletion.
746
+ */
747
+ type FilesRecordUpdate = Record<string, FileData | null>;
748
+ /**
749
+ * Options for creating filesystem middleware.
750
+ */
751
+ interface FilesystemMiddlewareOptions {
752
+ /** Backend instance or factory (default: StateBackend) */
753
+ backend?: AnyBackendProtocol | BackendFactory;
754
+ /** Optional custom system prompt override */
755
+ systemPrompt?: string | null;
756
+ /** Optional custom tool descriptions override */
757
+ customToolDescriptions?: Record<string, string> | null;
758
+ /** Optional token limit before evicting a tool result to the filesystem (default: 20000 tokens, ~80KB) */
759
+ toolTokenLimitBeforeEvict?: number | null;
760
+ /** Optional token limit before evicting a HumanMessage to the filesystem (default: 50000 tokens, ~200KB) */
761
+ humanMessageTokenLimitBeforeEvict?: number | null;
762
+ /**
763
+ * Filesystem permission rules enforced on every tool call.
764
+ *
765
+ * Rules are evaluated in declaration order; first match wins; permissive
766
+ * default. Applies to `ls`, `read_file`, `write_file`, `edit_file`,
767
+ * `glob`, and `grep`.
768
+ *
769
+ * **Note on `execute`**: permissions are not enforced on `execute` because
770
+ * shell commands can access any path regardless of path-based rules. Using
771
+ * permissions with an execution-capable backend (one where `isSandboxBackend`
772
+ * returns `true`) throws a `ConfigurationError` unless the backend is a
773
+ * `CompositeBackend` and every permission path is scoped to a route prefix.
774
+ *
775
+ * When omitted or empty, all filesystem operations are permitted.
776
+ */
777
+ permissions?: FilesystemPermission[];
778
+ }
779
+ /**
780
+ * Create filesystem middleware with all tools and features.
781
+ */
782
+ declare function createFilesystemMiddleware(options?: FilesystemMiddlewareOptions): AgentMiddleware<StateSchema<{
783
+ files: ReducedValue<FilesRecord | undefined, FilesRecordUpdate | undefined>;
784
+ }>, undefined, unknown, (_langchain.DynamicStructuredTool<z.ZodObject<{
785
+ path: z.ZodDefault<z.ZodOptional<z.ZodString>>;
786
+ }, z.core.$strip>, {
787
+ path: string;
788
+ }, {
789
+ path?: string | undefined;
790
+ }, string, unknown, "ls"> | _langchain.DynamicStructuredTool<z.ZodObject<{
791
+ file_path: z.ZodString;
792
+ offset: z.ZodDefault<z.ZodOptional<z.ZodCoercedNumber<unknown>>>;
793
+ limit: z.ZodDefault<z.ZodOptional<z.ZodCoercedNumber<unknown>>>;
794
+ }, z.core.$strip>, {
795
+ file_path: string;
796
+ offset: number;
797
+ limit: number;
798
+ }, {
799
+ file_path: string;
800
+ offset?: unknown;
801
+ limit?: unknown;
802
+ }, {
803
+ type: string;
804
+ text: string;
805
+ }[] | {
806
+ type: string;
807
+ mimeType: string;
808
+ data: string;
809
+ }[], unknown, "read_file"> | _langchain.DynamicStructuredTool<z.ZodObject<{
810
+ file_path: z.ZodString;
811
+ content: z.ZodDefault<z.ZodString>;
812
+ }, z.core.$strip>, {
813
+ file_path: string;
814
+ content: string;
815
+ }, {
816
+ file_path: string;
817
+ content?: string | undefined;
818
+ }, string | ToolMessage<_messages.MessageStructure<_messages.MessageToolSet>> | Command<unknown, {
819
+ files: Record<string, FileData>;
820
+ messages: ToolMessage<_messages.MessageStructure<_messages.MessageToolSet>>[];
821
+ }, string>, unknown, "write_file"> | _langchain.DynamicStructuredTool<z.ZodObject<{
822
+ file_path: z.ZodString;
823
+ old_string: z.ZodString;
824
+ new_string: z.ZodString;
825
+ replace_all: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
826
+ }, z.core.$strip>, {
827
+ file_path: string;
828
+ old_string: string;
829
+ new_string: string;
830
+ replace_all: boolean;
831
+ }, {
832
+ file_path: string;
833
+ old_string: string;
834
+ new_string: string;
835
+ replace_all?: boolean | undefined;
836
+ }, string | ToolMessage<_messages.MessageStructure<_messages.MessageToolSet>> | Command<unknown, {
837
+ files: Record<string, FileData>;
838
+ messages: ToolMessage<_messages.MessageStructure<_messages.MessageToolSet>>[];
839
+ }, string>, unknown, "edit_file"> | _langchain.DynamicStructuredTool<z.ZodObject<{
840
+ pattern: z.ZodString;
841
+ path: z.ZodDefault<z.ZodOptional<z.ZodString>>;
842
+ }, z.core.$strip>, {
843
+ pattern: string;
844
+ path: string;
845
+ }, {
846
+ pattern: string;
847
+ path?: string | undefined;
848
+ }, string, unknown, "glob"> | _langchain.DynamicStructuredTool<z.ZodObject<{
849
+ pattern: z.ZodString;
850
+ path: z.ZodDefault<z.ZodOptional<z.ZodString>>;
851
+ glob: z.ZodDefault<z.ZodNullable<z.ZodOptional<z.ZodString>>>;
852
+ }, z.core.$strip>, {
853
+ pattern: string;
854
+ path: string;
855
+ glob: string | null;
856
+ }, {
857
+ pattern: string;
858
+ path?: string | undefined;
859
+ glob?: string | null | undefined;
860
+ }, string, unknown, "grep"> | _langchain.DynamicStructuredTool<z.ZodObject<{
861
+ command: z.ZodString;
862
+ }, z.core.$strip>, {
863
+ command: string;
864
+ }, {
865
+ command: string;
866
+ }, string, unknown, "execute">)[], readonly []>;
867
+ //#endregion
868
+ //#region src/errors.d.ts
869
+ /**
870
+ * Error codes for {@link ConfigurationError}.
871
+ *
872
+ * Each code represents a distinct misconfiguration that can be detected at
873
+ * agent-construction time. Add new codes here as new validations are added.
874
+ */
875
+ type ConfigurationErrorCode = "TOOL_NAME_COLLISION";
876
+ declare const CONFIGURATION_ERROR_SYMBOL: unique symbol;
877
+ /**
878
+ * Thrown when `createDeepAgent` receives invalid configuration.
879
+ *
880
+ * Follows the same pattern as {@link SandboxError}: a human-readable
881
+ * `message`, a structured `code` for programmatic handling, and a
882
+ * static `isInstance` guard that works across realms.
883
+ *
884
+ * @example
885
+ * ```typescript
886
+ * try {
887
+ * createDeepAgent({ tools: [myTool] });
888
+ * } catch (error) {
889
+ * if (ConfigurationError.isInstance(error)) {
890
+ * switch (error.code) {
891
+ * case "TOOL_NAME_COLLISION":
892
+ * console.error("Rename your tool:", error.message);
893
+ * break;
894
+ * }
895
+ * }
896
+ * }
897
+ * ```
898
+ */
899
+ declare class ConfigurationError extends Error {
900
+ readonly code: ConfigurationErrorCode;
901
+ readonly cause?: Error | undefined;
902
+ [CONFIGURATION_ERROR_SYMBOL]: true;
903
+ readonly name: string;
904
+ constructor(message: string, code: ConfigurationErrorCode, cause?: Error | undefined);
905
+ static isInstance(error: unknown): error is ConfigurationError;
906
+ }
907
+ //#endregion
908
+ //#region src/profiles/harness/types.d.ts
909
+ /**
910
+ * Middleware names that provide essential agent capabilities and cannot
911
+ * be excluded via `excludedMiddleware`.
912
+ *
913
+ * - `FilesystemMiddleware` backs all built-in file tools and enforces
914
+ * filesystem permissions.
915
+ * - `SubAgentMiddleware` backs the `task` tool for subagent delegation.
916
+ */
917
+ declare const REQUIRED_MIDDLEWARE_NAMES: Set<string>;
918
+ /**
919
+ * Configuration for the auto-added general-purpose subagent.
920
+ *
921
+ * All fields use three-state semantics: `undefined` inherits the
922
+ * default, an explicit value overrides it. This allows model-level
923
+ * profiles to selectively override provider-level defaults without
924
+ * clobbering fields they don't care about.
925
+ */
926
+ interface GeneralPurposeSubagentConfig {
927
+ /**
928
+ * Whether to auto-add the general-purpose subagent.
929
+ *
930
+ * - `undefined` — inherit the default (enabled).
931
+ * - `true` — force inclusion even if a provider profile disables it.
932
+ * - `false` — disable the GP subagent entirely.
933
+ *
934
+ * @default undefined
935
+ */
936
+ enabled?: boolean;
937
+ /**
938
+ * Override the default GP subagent description shown to the model.
939
+ *
940
+ * @default undefined (uses `DEFAULT_GENERAL_PURPOSE_DESCRIPTION`)
941
+ */
942
+ description?: string;
943
+ /**
944
+ * Override the default GP subagent system prompt.
945
+ *
946
+ * When both this and `HarnessProfile.baseSystemPrompt` are set, this
947
+ * more-specific value wins for the GP subagent.
948
+ *
949
+ * @default undefined (uses `DEFAULT_SUBAGENT_PROMPT`)
950
+ */
951
+ systemPrompt?: string;
952
+ }
953
+ /**
954
+ * User-facing options for creating a {@link HarnessProfile}.
955
+ *
956
+ * Accepts plain arrays and records; the factory function converts them
957
+ * to their frozen counterparts. All fields are optional — an empty
958
+ * object produces a no-op profile.
959
+ */
960
+ interface HarnessProfileOptions {
961
+ /**
962
+ * Replaces the default `BASE_AGENT_PROMPT` when set.
963
+ *
964
+ * Use this when a model requires a fundamentally different base
965
+ * prompt rather than an additive suffix. Most profiles should prefer
966
+ * `systemPromptSuffix` instead.
967
+ *
968
+ * @default undefined (keeps the default base prompt)
969
+ */
970
+ baseSystemPrompt?: string;
971
+ /**
972
+ * Text appended to the assembled base prompt with a blank-line
973
+ * separator (`\n\n`).
974
+ *
975
+ * This is the primary mechanism for model-specific prompt tuning.
976
+ * Applied uniformly to the main agent, declarative subagents, and
977
+ * the auto-added general-purpose subagent.
978
+ *
979
+ * @default undefined (no suffix appended)
980
+ */
981
+ systemPromptSuffix?: string;
982
+ /**
983
+ * Per-tool description replacements keyed by tool name.
984
+ *
985
+ * Allows profiles to rewrite tool descriptions for models that
986
+ * respond better to different phrasing. Keys that don't match any
987
+ * tool in the final tool set are silently ignored.
988
+ *
989
+ * @default {} (no overrides)
990
+ */
991
+ toolDescriptionOverrides?: Record<string, string>;
992
+ /**
993
+ * Tool names to remove from the agent's visible tool set.
994
+ *
995
+ * Applied via a filtering middleware after all tool-injecting
996
+ * middleware have run, so it catches both user-provided and
997
+ * middleware-provided tools.
998
+ *
999
+ * @default [] (no tools excluded)
1000
+ */
1001
+ excludedTools?: string[];
1002
+ /**
1003
+ * Middleware names to remove from the assembled middleware stack.
1004
+ *
1005
+ * Matched against each middleware's `.name` property. Cannot include
1006
+ * required scaffolding names (`FilesystemMiddleware`,
1007
+ * `SubAgentMiddleware`) — attempting to do so throws at construction
1008
+ * time.
1009
+ *
1010
+ * @default [] (no middleware excluded)
1011
+ */
1012
+ excludedMiddleware?: string[];
1013
+ /**
1014
+ * Additional middleware appended to the stack after user middleware.
1015
+ *
1016
+ * Can be a static array or a zero-arg factory that returns fresh
1017
+ * instances per agent construction (important when middleware carries
1018
+ * mutable state).
1019
+ *
1020
+ * @default [] (no extra middleware)
1021
+ */
1022
+ extraMiddleware?: AgentMiddleware[] | (() => AgentMiddleware[]);
1023
+ /**
1024
+ * Configuration for the auto-added general-purpose subagent.
1025
+ *
1026
+ * @default undefined (GP subagent uses all defaults)
1027
+ */
1028
+ generalPurposeSubagent?: GeneralPurposeSubagentConfig;
1029
+ }
1030
+ /**
1031
+ * Frozen runtime harness profile that shapes agent behavior at
1032
+ * assembly time.
1033
+ *
1034
+ * Created by {@link createHarnessProfile} from user-provided
1035
+ * {@link HarnessProfileOptions}. Collection types are narrowed
1036
+ * (arrays → `Set`, records frozen) and all fields are required.
1037
+ * The object is frozen via `Object.freeze()` to prevent mutation
1038
+ * after construction.
1039
+ *
1040
+ * Profiles are **orthogonal to model selection**: they control prompt
1041
+ * assembly, tool visibility, middleware composition, and subagent
1042
+ * configuration — not which model is used.
1043
+ */
1044
+ interface HarnessProfile {
1045
+ /**
1046
+ * Replaces the default `BASE_AGENT_PROMPT` when set.
1047
+ *
1048
+ * Use this when a model requires a fundamentally different base
1049
+ * prompt rather than an additive suffix. Most profiles should prefer
1050
+ * `systemPromptSuffix` instead.
1051
+ */
1052
+ baseSystemPrompt: string | undefined;
1053
+ /**
1054
+ * Text appended to the assembled base prompt with a blank-line
1055
+ * separator (`\n\n`).
1056
+ *
1057
+ * This is the primary mechanism for model-specific prompt tuning.
1058
+ * Applied uniformly to the main agent, declarative subagents, and
1059
+ * the auto-added general-purpose subagent.
1060
+ */
1061
+ systemPromptSuffix: string | undefined;
1062
+ /**
1063
+ * Per-tool description replacements keyed by tool name.
1064
+ *
1065
+ * Allows profiles to rewrite tool descriptions for models that
1066
+ * respond better to different phrasing. Keys that don't match any
1067
+ * tool in the final tool set are silently ignored.
1068
+ */
1069
+ toolDescriptionOverrides: Record<string, string>;
1070
+ /**
1071
+ * Tool names to remove from the agent's visible tool set.
1072
+ *
1073
+ * Applied via a filtering middleware after all tool-injecting
1074
+ * middleware have run, so it catches both user-provided and
1075
+ * middleware-provided tools.
1076
+ */
1077
+ excludedTools: Set<string>;
1078
+ /**
1079
+ * Middleware names to remove from the assembled middleware stack.
1080
+ *
1081
+ * Matched against each middleware's `.name` property. Cannot include
1082
+ * required scaffolding names (`FilesystemMiddleware`,
1083
+ * `SubAgentMiddleware`) — attempting to do so throws at construction
1084
+ * time.
1085
+ */
1086
+ excludedMiddleware: Set<string>;
1087
+ /**
1088
+ * Additional middleware appended to the stack after user middleware.
1089
+ *
1090
+ * Can be a static array or a zero-arg factory that returns fresh
1091
+ * instances per agent construction (important when middleware carries
1092
+ * mutable state).
1093
+ */
1094
+ extraMiddleware: AgentMiddleware[] | (() => AgentMiddleware[]);
1095
+ /**
1096
+ * Configuration for the auto-added general-purpose subagent.
1097
+ */
1098
+ generalPurposeSubagent: GeneralPurposeSubagentConfig | undefined;
1099
+ }
1100
+ //#endregion
1101
+ //#region src/profiles/harness/create.d.ts
1102
+ /**
1103
+ * Create a frozen {@link HarnessProfile} from user-provided options.
1104
+ *
1105
+ * Validates all fields, converts mutable collections to their
1106
+ * frozen counterparts, and returns a frozen object.
1107
+ * Empty options produce a no-op profile (all defaults).
1108
+ *
1109
+ * @param options - Partial profile configuration.
1110
+ * @returns A frozen, validated `HarnessProfile`.
1111
+ * @throws {Error} When any field violates validation rules (invalid
1112
+ * middleware names, scaffolding exclusion attempts).
1113
+ *
1114
+ * @example
1115
+ * ```typescript
1116
+ * const profile = createHarnessProfile({
1117
+ * systemPromptSuffix: "Think step by step.",
1118
+ * excludedTools: ["execute"],
1119
+ * });
1120
+ * ```
1121
+ */
1122
+ declare function createHarnessProfile(options?: HarnessProfileOptions): HarnessProfile;
1123
+ /**
1124
+ * An empty no-op profile used as the default when no registered
1125
+ * profile matches. Avoids creating a new object on every miss.
1126
+ */
1127
+ declare const EMPTY_HARNESS_PROFILE: HarnessProfile;
1128
+ //#endregion
1129
+ //#region src/profiles/harness/serialization.d.ts
1130
+ /**
1131
+ * Zod schema for the general-purpose subagent config section of an
1132
+ * external harness profile config file.
1133
+ */
1134
+ declare const generalPurposeSubagentConfigSchema: z.ZodObject<{
1135
+ enabled: z.ZodOptional<z.ZodBoolean>;
1136
+ description: z.ZodOptional<z.ZodString>;
1137
+ systemPrompt: z.ZodOptional<z.ZodString>;
1138
+ }, z.core.$strict>;
1139
+ /**
1140
+ * Zod schema for parsing a harness profile from an external JSON or
1141
+ * YAML config file.
1142
+ *
1143
+ * Uses `.strict()` to reject unknown keys (catches typos early). Array
1144
+ * fields (`excludedTools`, `excludedMiddleware`) accept arrays of
1145
+ * strings; the result is passed to {@link createHarnessProfile} which
1146
+ * converts them to `Set`.
1147
+ *
1148
+ * Does not include `extraMiddleware` — middleware instances cannot be
1149
+ * represented in JSON/YAML.
1150
+ *
1151
+ * @example
1152
+ * ```typescript
1153
+ * import { readFileSync } from "fs";
1154
+ * import YAML from "yaml";
1155
+ *
1156
+ * const raw = YAML.parse(readFileSync("profile.yaml", "utf-8"));
1157
+ * const config = harnessProfileConfigSchema.parse(raw);
1158
+ * const profile = createHarnessProfile(config);
1159
+ * ```
1160
+ */
1161
+ declare const harnessProfileConfigSchema: z.ZodObject<{
1162
+ baseSystemPrompt: z.ZodOptional<z.ZodString>;
1163
+ systemPromptSuffix: z.ZodOptional<z.ZodString>;
1164
+ toolDescriptionOverrides: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
1165
+ excludedTools: z.ZodOptional<z.ZodArray<z.ZodString>>;
1166
+ excludedMiddleware: z.ZodOptional<z.ZodArray<z.ZodString>>;
1167
+ generalPurposeSubagent: z.ZodOptional<z.ZodObject<{
1168
+ enabled: z.ZodOptional<z.ZodBoolean>;
1169
+ description: z.ZodOptional<z.ZodString>;
1170
+ systemPrompt: z.ZodOptional<z.ZodString>;
1171
+ }, z.core.$strict>>;
1172
+ }, z.core.$strict>;
1173
+ /**
1174
+ * TypeScript type inferred from the Zod config schema.
1175
+ *
1176
+ * Represents the JSON/YAML-compatible shape of a harness profile. This
1177
+ * is the type of data that comes out of `harnessProfileConfigSchema.parse()`.
1178
+ */
1179
+ type HarnessProfileConfigData = z.infer<typeof harnessProfileConfigSchema>;
1180
+ /**
1181
+ * Parse an untrusted JSON/YAML object into a validated
1182
+ * {@link HarnessProfile}.
1183
+ *
1184
+ * Combines Zod schema validation with prototype-pollution protection
1185
+ * and profile construction validation. Use this for any config data
1186
+ * that originates from files, network, or user input.
1187
+ *
1188
+ * @param data - Raw object from `JSON.parse()` or `YAML.parse()`.
1189
+ * @returns A frozen, validated `HarnessProfile`.
1190
+ * @throws {z.ZodError} When the data fails schema validation.
1191
+ * @throws {Error} When profile-level validation fails (e.g.,
1192
+ * scaffolding violation in `excludedMiddleware`).
1193
+ */
1194
+ declare function parseHarnessProfileConfig(data: unknown): HarnessProfile;
1195
+ /**
1196
+ * Serialize a {@link HarnessProfile} to a JSON-compatible object.
1197
+ *
1198
+ * Omits `undefined` fields and `extraMiddleware` (runtime-only).
1199
+ * Throws if `extraMiddleware` contains instances — callers should
1200
+ * strip it before serializing if they've set it.
1201
+ *
1202
+ * @param profile - The profile to serialize.
1203
+ * @returns A plain object matching {@link HarnessProfileConfigData}.
1204
+ * @throws {Error} When `extraMiddleware` is non-empty (cannot be
1205
+ * serialized to JSON).
1206
+ */
1207
+ declare function serializeProfile(profile: HarnessProfile): HarnessProfileConfigData;
1208
+ //#endregion
1209
+ //#region src/profiles/harness/registry.d.ts
1210
+ /**
1211
+ * Register a harness profile for a provider or specific model.
1212
+ *
1213
+ * Accepts either a pre-built {@link HarnessProfile} (from
1214
+ * {@link createHarnessProfile}) or raw {@link HarnessProfileOptions}
1215
+ * that will be validated and frozen automatically.
1216
+ *
1217
+ * Registrations are **additive**: if a profile already exists under
1218
+ * `key`, the new profile is merged on top. The incoming profile's
1219
+ * fields win on scalar conflicts; set fields union; middleware
1220
+ * sequences merge by name.
1221
+ *
1222
+ * @param key - Either a bare provider (`"openai"`) for provider-wide
1223
+ * defaults, or `"provider:model"` for a per-model override.
1224
+ * @param profile - A `HarnessProfile` or options to build one from.
1225
+ * @throws {Error} When `key` is malformed or profile validation
1226
+ * fails.
1227
+ *
1228
+ * @example
1229
+ * ```typescript
1230
+ * import { registerHarnessProfile } from "@langchain/deepagents";
1231
+ *
1232
+ * registerHarnessProfile("openai", {
1233
+ * systemPromptSuffix: "Respond concisely.",
1234
+ * });
1235
+ *
1236
+ * registerHarnessProfile("openai:gpt-5.4", {
1237
+ * excludedTools: ["execute"],
1238
+ * });
1239
+ * ```
1240
+ */
1241
+ declare function registerHarnessProfile(key: string, profile: HarnessProfile | HarnessProfileOptions): void;
1242
+ /**
1243
+ * Look up the {@link HarnessProfile} for a model spec string.
1244
+ *
1245
+ * Resolution order:
1246
+ *
1247
+ * 1. **Exact match** on `spec` (e.g., `"openai:gpt-5.4"`).
1248
+ * 2. **Provider prefix** (everything before `:`) when `spec` contains
1249
+ * a colon and both halves are non-empty.
1250
+ * 3. When both exist, they are **merged** (provider as base, exact as
1251
+ * override).
1252
+ * 4. `undefined` when nothing matches.
1253
+ *
1254
+ * Malformed specs (empty, multiple colons, empty halves) return
1255
+ * `undefined` without consulting the registry.
1256
+ *
1257
+ * @param spec - Model spec in `"provider:model"` format, or a bare
1258
+ * provider/model identifier.
1259
+ * @returns The matching profile, or `undefined`.
1260
+ */
1261
+ declare function getHarnessProfile(spec: string): HarnessProfile | undefined;
1262
+ //#endregion
1263
+ //#region src/middleware/subagents.d.ts
1264
+ /**
1265
+ * Config key used by task-tool callers to request dynamic response format.
1266
+ *
1267
+ * When set in `config.configurable`, the task tool recompiles the target
1268
+ * subagent with this response format instead of using the pre-compiled graph.
1269
+ */
1270
+ declare const SUBAGENT_RESPONSE_FORMAT_CONFIG_KEY = "__deepagents_subagent_response_format";
1271
+ /**
1272
+ * Default system prompt for subagents.
1273
+ * Provides a minimal base prompt that can be extended by specific subagent configurations.
1274
+ */
1275
+ declare const DEFAULT_SUBAGENT_PROMPT = "In order to complete the objective that the user asks of you, you have access to a number of standard tools.";
1276
+ /**
1277
+ * Default description for the general-purpose subagent.
1278
+ * This description is shown to the model when selecting which subagent to use.
1279
+ */
1280
+ declare const DEFAULT_GENERAL_PURPOSE_DESCRIPTION = "General-purpose agent for researching complex questions, searching for files and content, and executing multi-step tasks. When you are searching for a keyword or file and are not confident that you will find the right match in the first few tries use this agent to perform the search for you. This agent has access to all tools as the main agent.";
1281
+ /**
1282
+ * System prompt section that explains how to use the task tool for spawning subagents.
1283
+ *
1284
+ * This prompt is automatically appended to the main agent's system prompt when
1285
+ * using `createSubAgentMiddleware`. It provides guidance on:
1286
+ * - When to use the task tool
1287
+ * - Subagent lifecycle (spawn → run → return → reconcile)
1288
+ * - When NOT to use the task tool
1289
+ * - Best practices for parallel task execution
1290
+ *
1291
+ * You can provide a custom `systemPrompt` to `createSubAgentMiddleware` to override
1292
+ * or extend this default.
1293
+ */
1294
+ declare const TASK_SYSTEM_PROMPT: string;
1295
+ /**
1296
+ * Type definitions for pre-compiled agents.
1297
+ *
1298
+ * @typeParam TRunnable - The type of the runnable (ReactAgent or Runnable).
1299
+ * When using `createAgent` or `createDeepAgent`, this preserves the middleware
1300
+ * types for type inference. Uses `ReactAgent<any>` to accept agents with any
1301
+ * type configuration (including DeepAgent instances).
1302
+ */
1303
+ interface CompiledSubAgent<TRunnable extends ReactAgent<any> | Runnable = ReactAgent<any> | Runnable> {
1304
+ /** The name of the agent */
1305
+ name: string;
1306
+ /** The description of the agent */
1307
+ description: string;
1308
+ /** The agent instance */
1309
+ runnable: TRunnable;
1310
+ }
1311
+ /**
1312
+ * Specification for a subagent that can be dynamically created.
1313
+ *
1314
+ * When using `createDeepAgent`, subagents automatically receive a default middleware
1315
+ * stack (todoListMiddleware, filesystemMiddleware, summarizationMiddleware, etc.) before
1316
+ * any custom `middleware` specified in this spec.
1317
+ *
1318
+ * Required fields:
1319
+ * - `name`: Identifier used to select this subagent in the task tool
1320
+ * - `description`: Shown to the model for subagent selection
1321
+ * - `systemPrompt`: The system prompt for the subagent
1322
+ *
1323
+ * Optional fields:
1324
+ * - `model`: Override the default model for this subagent
1325
+ * - `tools`: Override the default tools for this subagent
1326
+ * - `middleware`: Additional middleware appended after defaults
1327
+ * - `interruptOn`: Human-in-the-loop configuration for specific tools
1328
+ * - `skills`: Skill source paths for SkillsMiddleware (e.g., `["/skills/user/", "/skills/project/"]`)
1329
+ *
1330
+ * @example
1331
+ * ```typescript
1332
+ * const researcher: SubAgent = {
1333
+ * name: "researcher",
1334
+ * description: "Research assistant for complex topics",
1335
+ * systemPrompt: "You are a research assistant.",
1336
+ * tools: [webSearchTool],
1337
+ * skills: ["/skills/research/"],
1338
+ * };
1339
+ * ```
1340
+ */
1341
+ interface SubAgent {
1342
+ /** Identifier used to select this subagent in the task tool */
1343
+ name: string;
1344
+ /** Description shown to the model for subagent selection */
1345
+ description: string;
1346
+ /** The system prompt to use for the agent */
1347
+ systemPrompt: string;
1348
+ /** The tools to use for the agent (tool instances, not names). Defaults to defaultTools */
1349
+ tools?: StructuredTool[];
1350
+ /** The model for the agent. Defaults to defaultModel */
1351
+ model?: LanguageModelLike | string;
1352
+ /** Additional middleware to append after default_middleware */
1353
+ middleware?: readonly AgentMiddleware$1[];
1354
+ /** Human-in-the-loop configuration for specific tools. Requires a checkpointer. */
1355
+ interruptOn?: Record<string, boolean | InterruptOnConfig>;
1356
+ /**
1357
+ * Skill source paths for SkillsMiddleware.
1358
+ *
1359
+ * List of paths to skill directories (e.g., `["/skills/user/", "/skills/project/"]`).
1360
+ * When specified, the subagent will have its own SkillsMiddleware that loads skills
1361
+ * from these paths. This allows subagents to have different skill sets than the main agent.
1362
+ *
1363
+ * Note: Custom subagents do NOT inherit skills from the main agent by default.
1364
+ * Only the general-purpose subagent inherits the main agent's skills.
1365
+ *
1366
+ * @example
1367
+ * ```typescript
1368
+ * const researcher: SubAgent = {
1369
+ * name: "researcher",
1370
+ * description: "Research assistant",
1371
+ * systemPrompt: "You are a researcher.",
1372
+ * skills: ["/skills/research/", "/skills/web-search/"],
1373
+ * };
1374
+ * ```
1375
+ */
1376
+ skills?: string[];
1377
+ /**
1378
+ * Structured output response format for the subagent.
1379
+ *
1380
+ * When specified, the subagent will produce a `structuredResponse` conforming to the
1381
+ * given schema. The structured response is JSON-serialized and returned as the
1382
+ * ToolMessage content to the parent agent, replacing the default last-message extraction.
1383
+ *
1384
+ * Accepts any format supported by `createAgent`: Zod schemas, JSON schema objects,
1385
+ * `toolStrategy(schema)`, `providerStrategy(schema)`, etc.
1386
+ *
1387
+ * @example
1388
+ * ```typescript
1389
+ * import { z } from "zod"
1390
+ *
1391
+ * const analyzer: SubAgent = {
1392
+ * name: "analyzer",
1393
+ * description: "Analyzes data and returns structured findings",
1394
+ * systemPrompt: "Analyze the data and return your findings.",
1395
+ * responseFormat: z.object({
1396
+ * findings: z.string(),
1397
+ * confidence: z.number(),
1398
+ * }),
1399
+ * };
1400
+ * ```
1401
+ */
1402
+ responseFormat?: CreateAgentParams["responseFormat"];
1403
+ /**
1404
+ * Filesystem permission rules for this subagent.
1405
+ *
1406
+ * When specified, these rules **replace** the parent agent's permissions
1407
+ * for all tool calls made by this subagent. When omitted, the subagent
1408
+ * inherits the parent agent's permissions.
1409
+ *
1410
+ * Subagent permissions are a full replacement, not a merge.
1411
+ *
1412
+ * @example
1413
+ * ```ts
1414
+ * // Parent denies /restricted/**; this subagent can read it.
1415
+ * const reader: SubAgent = {
1416
+ * name: "reader",
1417
+ * permissions: [
1418
+ * { operations: ["read"], paths: ["/restricted/**"] },
1419
+ * ],
1420
+ * };
1421
+ * ```
1422
+ */
1423
+ permissions?: FilesystemPermission[];
1424
+ }
1425
+ /**
1426
+ * Base specification for the general-purpose subagent.
1427
+ *
1428
+ * This constant provides the default configuration for the general-purpose subagent
1429
+ * that is automatically included when `generalPurposeAgent: true` (the default).
1430
+ *
1431
+ * The general-purpose subagent:
1432
+ * - Has access to all tools from the main agent
1433
+ * - Inherits skills from the main agent (when skills are configured)
1434
+ * - Uses the same model as the main agent (by default)
1435
+ * - Is ideal for delegating complex, multi-step tasks
1436
+ *
1437
+ * You can spread this constant and override specific properties when creating
1438
+ * custom subagents that should behave similarly to the general-purpose agent:
1439
+ *
1440
+ * @example
1441
+ * ```typescript
1442
+ * import { GENERAL_PURPOSE_SUBAGENT, createDeepAgent } from "@anthropic/deepagents";
1443
+ *
1444
+ * // Use as-is (automatically included with generalPurposeAgent: true)
1445
+ * const agent = createDeepAgent({ model: "claude-sonnet-4-5-20250929" });
1446
+ *
1447
+ * // Or create a custom variant with different tools
1448
+ * const customGP: SubAgent = {
1449
+ * ...GENERAL_PURPOSE_SUBAGENT,
1450
+ * name: "research-gp",
1451
+ * tools: [webSearchTool, readFileTool],
1452
+ * };
1453
+ *
1454
+ * const agent = createDeepAgent({
1455
+ * model: "claude-sonnet-4-5-20250929",
1456
+ * subagents: [customGP],
1457
+ * // Disable the default general-purpose agent since we're providing our own
1458
+ * // (handled automatically when using createSubAgentMiddleware directly)
1459
+ * });
1460
+ * ```
1461
+ */
1462
+ declare const GENERAL_PURPOSE_SUBAGENT: Pick<SubAgent, "name" | "description" | "systemPrompt">;
1463
+ /**
1464
+ * Create a runnable agent from a declarative `SubAgent` spec.
1465
+ *
1466
+ * This is the shared entrypoint for compiling a `SubAgent` into a
1467
+ * `ReactAgent`. Pre-compiled `CompiledSubAgent` runnables bypass this
1468
+ * function entirely.
1469
+ *
1470
+ * The spec must have `model` and `tools` set — the caller is responsible
1471
+ * for coalescing any defaults before calling this function.
1472
+ *
1473
+ * @param spec - Declarative subagent specification. Must specify `model` and `tools`.
1474
+ * @returns A compiled `ReactAgent` ready for task-tool invocation.
1475
+ */
1476
+ declare function createSubAgent(spec: SubAgent, options?: {
1477
+ responseFormat?: CreateAgentParams["responseFormat"];
1478
+ }): ReactAgent;
1479
+ /**
1480
+ * Options for creating subagent middleware
1481
+ */
1482
+ interface SubAgentMiddlewareOptions {
1483
+ /** The model to use for subagents */
1484
+ defaultModel: LanguageModelLike | string;
1485
+ /** The tools to use for the default general-purpose subagent */
1486
+ defaultTools?: StructuredTool[];
1487
+ /** Default middleware to apply to custom subagents (WITHOUT skills from main agent) */
1488
+ defaultMiddleware?: AgentMiddleware$1[] | null;
1489
+ /**
1490
+ * Middleware specifically for the general-purpose subagent (includes skills from main agent).
1491
+ * If not provided, falls back to defaultMiddleware.
1492
+ */
1493
+ generalPurposeMiddleware?: AgentMiddleware$1[] | null;
1494
+ /** The tool configs for the default general-purpose subagent */
1495
+ defaultInterruptOn?: Record<string, boolean | InterruptOnConfig> | null;
1496
+ /** A list of additional subagents to provide to the agent */
1497
+ subagents?: (SubAgent | CompiledSubAgent)[];
1498
+ /** Full system prompt override */
1499
+ systemPrompt?: string | null;
1500
+ /** Whether to include the general-purpose agent */
1501
+ generalPurposeAgent?: boolean;
1502
+ /** Custom description for the task tool */
1503
+ taskDescription?: string | null;
1504
+ }
1505
+ /**
1506
+ * Create subagent middleware with task tool
1507
+ */
1508
+ declare function createSubAgentMiddleware(options: SubAgentMiddlewareOptions): AgentMiddleware$1<undefined, undefined, unknown, readonly [import("langchain").DynamicStructuredTool<z.ZodObject<{
1509
+ description: z.ZodString;
1510
+ subagent_type: z.ZodString;
1511
+ }, z.core.$strip>, {
1512
+ description: string;
1513
+ subagent_type: string;
1514
+ }, {
1515
+ description: string;
1516
+ subagent_type: string;
1517
+ }, string | Command<unknown, Record<string, unknown>, string>, unknown, "task">], readonly []>;
1518
+ //#endregion
1519
+ //#region src/middleware/patch_tool_calls.d.ts
1520
+ /**
1521
+ * Create middleware that enforces strict tool call / tool response parity in
1522
+ * the messages history.
1523
+ *
1524
+ * Two kinds of violations are repaired:
1525
+ * 1. **Dangling tool_calls** — an AIMessage contains tool_calls with no
1526
+ * matching ToolMessage responses. Synthetic cancellation ToolMessages are
1527
+ * injected so every tool_call has a response.
1528
+ * 2. **Orphaned ToolMessages** — a ToolMessage exists whose `tool_call_id`
1529
+ * does not match any tool_call in a preceding AIMessage. These are removed.
1530
+ *
1531
+ * This is critical for providers like Google Gemini that reject requests with
1532
+ * mismatched function call / function response counts (400 INVALID_ARGUMENT).
1533
+ *
1534
+ * This middleware patches in two places:
1535
+ * 1. `beforeAgent`: Patches state at the start of the agent loop (handles most cases)
1536
+ * 2. `wrapModelCall`: Patches the request right before model invocation (handles
1537
+ * edge cases like HITL rejection during graph resume where state updates from
1538
+ * beforeAgent may not be applied in time)
1539
+ *
1540
+ * @returns AgentMiddleware that enforces tool call / response parity
1541
+ *
1542
+ * @example
1543
+ * ```typescript
1544
+ * import { createAgent } from "langchain";
1545
+ * import { createPatchToolCallsMiddleware } from "./middleware/patch_tool_calls";
1546
+ *
1547
+ * const agent = createAgent({
1548
+ * model: "claude-sonnet-4-5-20250929",
1549
+ * middleware: [createPatchToolCallsMiddleware()],
1550
+ * });
1551
+ * ```
1552
+ */
1553
+ declare function createPatchToolCallsMiddleware(): AgentMiddleware<undefined, undefined, unknown, readonly (import("@langchain/core/tools").ClientTool | import("@langchain/core/tools").ServerTool)[], readonly []>;
1554
+ //#endregion
1555
+ //#region src/backends/state.d.ts
1556
+ /**
1557
+ * Backend that stores files in agent state (ephemeral).
1558
+ *
1559
+ * Uses LangGraph's state management and checkpointing. Files persist within
1560
+ * a conversation thread but not across threads. State is automatically
1561
+ * checkpointed after each agent step.
1562
+ *
1563
+ * Special handling: Since LangGraph state must be updated via Command objects
1564
+ * (not direct mutation), operations return filesUpdate in WriteResult/EditResult
1565
+ * for the middleware to apply via Command.
1566
+ */
1567
+ declare class StateBackend implements BackendProtocolV2 {
1568
+ private runtime;
1569
+ private fileFormat;
1570
+ constructor(options?: BackendOptions);
1571
+ /**
1572
+ * @deprecated Pass no `runtime` argument
1573
+ */
1574
+ constructor(runtime: BackendRuntime, options?: BackendOptions);
1575
+ /**
1576
+ * Whether this instance was constructed with the legacy factory pattern.
1577
+ *
1578
+ * When true, state is read from the injected `runtime` and `filesUpdate`
1579
+ * is returned to the caller. When false, state is read from LangGraph's
1580
+ * execution context and updates are sent via `__pregel_send`.
1581
+ */
1582
+ private get isLegacy();
1583
+ /**
1584
+ * Get files from current state.
1585
+ *
1586
+ * In legacy mode, reads from the injected {@link BackendRuntime}.
1587
+ * In zero-arg mode, reads via {@link PREGEL_READ_KEY} with fresh=true,
1588
+ * which applies any pending task writes through the reducer before returning.
1589
+ */
1590
+ private get files();
1591
+ /**
1592
+ * Push a files state update through LangGraph's internal send channel.
1593
+ *
1594
+ * In zero-arg mode, sends the update via the `__pregel_send` function
1595
+ * from {@link getConfig}, mirroring Python's `CONFIG_KEY_SEND`.
1596
+ * In legacy mode, this is a no-op — the caller uses `filesUpdate`
1597
+ * from the return value instead.
1598
+ *
1599
+ * @param update - Map of file paths to their updated {@link FileData}
1600
+ */
1601
+ private sendFilesUpdate;
1602
+ /**
1603
+ * List files and directories in the specified directory (non-recursive).
1604
+ *
1605
+ * @param path - Absolute path to directory
1606
+ * @returns LsResult with list of FileInfo objects on success or error on failure.
1607
+ * Directories have a trailing / in their path and is_dir=true.
1608
+ */
1609
+ ls(path: string): LsResult;
1610
+ /**
1611
+ * Read file content.
1612
+ *
1613
+ * Text files are paginated by line offset/limit.
1614
+ * Binary files return full Uint8Array content (offset/limit ignored).
1615
+ *
1616
+ * @param filePath - Absolute file path
1617
+ * @param offset - Line offset to start reading from (0-indexed)
1618
+ * @param limit - Maximum number of lines to read
1619
+ * @returns ReadResult with content on success or error on failure
1620
+ */
1621
+ read(filePath: string, offset?: number, limit?: number): ReadResult;
1622
+ /**
1623
+ * Read file content as raw FileData.
1624
+ *
1625
+ * @param filePath - Absolute file path
1626
+ * @returns ReadRawResult with raw file data on success or error on failure
1627
+ */
1628
+ readRaw(filePath: string): ReadRawResult;
1629
+ /**
1630
+ * Create a new file with content.
1631
+ * Returns WriteResult with filesUpdate to update LangGraph state.
1632
+ */
1633
+ write(filePath: string, content: string): WriteResult;
1634
+ /**
1635
+ * Edit a file by replacing string occurrences.
1636
+ * Returns EditResult with filesUpdate and occurrences.
1637
+ */
1638
+ edit(filePath: string, oldString: string, newString: string, replaceAll?: boolean): EditResult;
1639
+ /**
1640
+ * Search file contents for a literal text pattern.
1641
+ * Binary files are skipped.
1642
+ */
1643
+ grep(pattern: string, path?: string, glob?: string | null): GrepResult;
1644
+ /**
1645
+ * Structured glob matching returning FileInfo objects.
1646
+ */
1647
+ glob(pattern: string, path?: string): GlobResult;
1648
+ /**
1649
+ * Upload multiple files.
1650
+ *
1651
+ * Note: Since LangGraph state must be updated via Command objects,
1652
+ * the caller must apply filesUpdate via Command after calling this method.
1653
+ *
1654
+ * @param files - List of [path, content] tuples to upload
1655
+ * @returns List of FileUploadResponse objects, one per input file
1656
+ */
1657
+ uploadFiles(files: Array<[string, Uint8Array]>): FileUploadResponse[] & {
1658
+ filesUpdate?: Record<string, FileData>;
1659
+ };
1660
+ /**
1661
+ * Download multiple files.
1662
+ *
1663
+ * @param paths - List of file paths to download
1664
+ * @returns List of FileDownloadResponse objects, one per input path
1665
+ */
1666
+ downloadFiles(paths: string[]): FileDownloadResponse[];
1667
+ }
1668
+ //#endregion
1669
+ //#region src/middleware/memory.d.ts
1670
+ /**
1671
+ * Options for the memory middleware.
1672
+ */
1673
+ interface MemoryMiddlewareOptions {
1674
+ /**
1675
+ * Backend instance or factory function for file operations.
1676
+ * Use a factory for StateBackend since it requires runtime state.
1677
+ */
1678
+ backend: AnyBackendProtocol | BackendFactory | ((config: {
1679
+ state: unknown;
1680
+ store?: BaseStore;
1681
+ }) => StateBackend);
1682
+ /**
1683
+ * List of memory file paths to load (e.g., ["~/.deepagents/AGENTS.md", "./.deepagents/AGENTS.md"]).
1684
+ * Display names are automatically derived from the paths.
1685
+ * Sources are loaded in order.
1686
+ */
1687
+ sources: string[];
1688
+ /**
1689
+ * Whether to add cache_control breakpoints to the memory content block.
1690
+ * When true, the memory block is tagged with `cache_control: { type: "ephemeral" }`
1691
+ * to enable prompt caching for providers that support it (e.g., Anthropic).
1692
+ * @default false
1693
+ */
1694
+ addCacheControl?: boolean;
1695
+ }
1696
+ /**
1697
+ * Create middleware for loading agent memory from AGENTS.md files.
1698
+ *
1699
+ * Loads memory content from configured sources and injects into the system prompt.
1700
+ * Supports multiple sources that are combined together.
1701
+ *
1702
+ * @param options - Configuration options
1703
+ * @returns AgentMiddleware for memory loading and injection
1704
+ *
1705
+ * @example
1706
+ * ```typescript
1707
+ * const middleware = createMemoryMiddleware({
1708
+ * backend: new FilesystemBackend({ rootDir: "/" }),
1709
+ * sources: [
1710
+ * "~/.deepagents/AGENTS.md",
1711
+ * "./.deepagents/AGENTS.md",
1712
+ * ],
1713
+ * });
1714
+ * ```
1715
+ */
1716
+ declare function createMemoryMiddleware(options: MemoryMiddlewareOptions): AgentMiddleware<StateSchema<{
1717
+ /**
1718
+ * Dict mapping source paths to their loaded content.
1719
+ * Marked as private so it's not included in the final agent state.
1720
+ */
1721
+ memoryContents: z$1.ZodOptional<z$1.ZodRecord<z$1.ZodString, z$1.ZodString>>;
1722
+ files: _langgraph.ReducedValue<FilesRecord | undefined, FilesRecordUpdate | undefined>;
1723
+ }>, undefined, unknown, readonly (import("@langchain/core/tools").ClientTool | import("@langchain/core/tools").ServerTool)[], readonly []>;
1724
+ //#endregion
1725
+ //#region src/middleware/skills.d.ts
1726
+ declare const MAX_SKILL_FILE_SIZE: number;
1727
+ declare const MAX_SKILL_NAME_LENGTH = 64;
1728
+ declare const MAX_SKILL_DESCRIPTION_LENGTH = 1024;
1729
+ /**
1730
+ * Metadata for a skill per Agent Skills specification.
1731
+ */
1732
+ interface SkillMetadata$1 {
1733
+ /**
1734
+ * Skill identifier.
1735
+ *
1736
+ * Constraints per Agent Skills specification:
1737
+ *
1738
+ * - 1-64 characters
1739
+ * - Unicode lowercase alphanumeric and hyphens only (`a-z` and `-`).
1740
+ * - Must not start or end with `-`
1741
+ * - Must not contain consecutive `--`
1742
+ * - Must match the parent directory name containing the `SKILL.md` file
1743
+ */
1744
+ name: string;
1745
+ /**
1746
+ * What the skill does.
1747
+ *
1748
+ * Constraints per Agent Skills specification:
1749
+ *
1750
+ * - 1-1024 characters
1751
+ * - Should describe both what the skill does and when to use it
1752
+ * - Should include specific keywords that help agents identify relevant tasks
1753
+ */
1754
+ description: string;
1755
+ /** Path to the SKILL.md file in the backend */
1756
+ path: string;
1757
+ /** License name or reference to bundled license file. */
1758
+ license?: string | null;
1759
+ /**
1760
+ * Environment requirements.
1761
+ *
1762
+ * Constraints per Agent Skills specification:
1763
+ *
1764
+ * - 1-500 characters if provided
1765
+ * - Should only be included if there are specific compatibility requirements
1766
+ * - Can indicate intended product, required packages, etc.
1767
+ */
1768
+ compatibility?: string | null;
1769
+ /**
1770
+ * Arbitrary key-value mapping for additional metadata.
1771
+ *
1772
+ * Clients can use this to store additional properties not defined by the spec.
1773
+ *
1774
+ * It is recommended to keep key names unique to avoid conflicts.
1775
+ */
1776
+ metadata?: Record<string, string>;
1777
+ /**
1778
+ * Tool names the skill recommends using.
1779
+ *
1780
+ * Warning: this is experimental.
1781
+ *
1782
+ * Constraints per Agent Skills specification:
1783
+ *
1784
+ * - Space-delimited list of tool names
1785
+ */
1786
+ allowedTools?: string[];
1787
+ /**
1788
+ * Path to a JS/TS entrypoint file for a QuickJS REPL module, relative to the skill
1789
+ * directory.
1790
+ */
1791
+ module?: string;
1792
+ }
1793
+ /**
1794
+ * Options for the skills middleware.
1795
+ */
1796
+ interface SkillsMiddlewareOptions {
1797
+ /**
1798
+ * Backend instance or factory function for file operations.
1799
+ * Use a factory for StateBackend since it requires runtime state.
1800
+ */
1801
+ backend: AnyBackendProtocol | BackendFactory | ((config: {
1802
+ state: unknown;
1803
+ store?: BaseStore;
1804
+ }) => StateBackend);
1805
+ /**
1806
+ * List of skill source paths to load.
1807
+ * Paths must use POSIX conventions (forward slashes).
1808
+ * Later sources override earlier ones for skills with the same name (last one wins).
1809
+ *
1810
+ * Two formats are accepted for each entry:
1811
+ *
1812
+ * - **Parent directory** (e.g. `"/skills/"`, `"/skills/user/"`): the directory
1813
+ * is scanned and every subdirectory that contains a `SKILL.md` is loaded as
1814
+ * a separate skill.
1815
+ *
1816
+ * - **Direct skill path** (e.g. `"/skills/my-skill/"`): the path points to a
1817
+ * single skill directory whose `SKILL.md` lives at its root. Detected
1818
+ * automatically when the directory listing contains a `SKILL.md` file.
1819
+ *
1820
+ * Both formats can be mixed in the same array:
1821
+ * ```typescript
1822
+ * sources: [
1823
+ * "/skills/", // loads all skills in the directory
1824
+ * "/skills/my-skill/", // loads a single skill by path
1825
+ * ]
1826
+ * ```
1827
+ */
1828
+ sources: string[];
1829
+ }
1830
+ /**
1831
+ * Create backend-agnostic middleware for loading and exposing agent skills.
1832
+ *
1833
+ * This middleware loads skills from configurable backend sources and injects
1834
+ * skill metadata into the system prompt. It implements the progressive disclosure
1835
+ * pattern: skill names and descriptions are shown in the prompt, but the agent
1836
+ * reads full SKILL.md content only when needed.
1837
+ *
1838
+ * @param options - Configuration options
1839
+ * @returns AgentMiddleware for skills loading and injection
1840
+ *
1841
+ * @example
1842
+ * ```typescript
1843
+ * const middleware = createSkillsMiddleware({
1844
+ * backend: new FilesystemBackend({ rootDir: "/" }),
1845
+ * sources: ["/skills/user/", "/skills/project/"],
1846
+ * });
1847
+ * ```
1848
+ */
1849
+ declare function createSkillsMiddleware(options: SkillsMiddlewareOptions): AgentMiddleware<StateSchema<{
1850
+ skillsMetadata: ReducedValue<{
1851
+ name: string;
1852
+ description: string;
1853
+ path: string;
1854
+ license?: string | null | undefined;
1855
+ compatibility?: string | null | undefined;
1856
+ metadata?: Record<string, string> | undefined;
1857
+ allowedTools?: string[] | undefined;
1858
+ module?: string | undefined;
1859
+ }[] | undefined, {
1860
+ name: string;
1861
+ description: string;
1862
+ path: string;
1863
+ license?: string | null | undefined;
1864
+ compatibility?: string | null | undefined;
1865
+ metadata?: Record<string, string> | undefined;
1866
+ allowedTools?: string[] | undefined;
1867
+ module?: string | undefined;
1868
+ }[] | undefined>;
1869
+ files: ReducedValue<FilesRecord | undefined, FilesRecordUpdate | undefined>;
1870
+ }>, undefined, unknown, readonly (import("@langchain/core/tools").ClientTool | import("@langchain/core/tools").ServerTool)[], readonly []>;
1871
+ //#endregion
1872
+ //#region src/middleware/completion_callback.d.ts
1873
+ /**
1874
+ * Options for creating the completion callback middleware.
1875
+ */
1876
+ interface CompletionCallbackOptions {
1877
+ /**
1878
+ * Callback graph or assistant identifier. Used as the `assistant_id`
1879
+ * argument in `runs.create()`.
1880
+ */
1881
+ callbackGraphId: string;
1882
+ /**
1883
+ * URL of the callback LangGraph server. Omit to use same-deployment
1884
+ * ASGI transport.
1885
+ */
1886
+ url?: string;
1887
+ /**
1888
+ * Additional headers to include in requests to the callback server.
1889
+ */
1890
+ headers?: Record<string, string>;
1891
+ }
1892
+ /**
1893
+ * Create a completion callback middleware for async subagents.
1894
+ *
1895
+ * **Experimental** — this middleware is experimental and may change.
1896
+ *
1897
+ * This middleware is added to a subagent's middleware stack. On success or
1898
+ * model-call error, it sends a notification to the configured callback
1899
+ * thread by calling `runs.create()`.
1900
+ *
1901
+ * The callback destination is configured with `callbackGraphId` and
1902
+ * optional `url` and `headers`. The target thread is read from
1903
+ * `callbackThreadId` in the subagent state.
1904
+ *
1905
+ * If `callbackThreadId` is not present in state, the middleware does
1906
+ * nothing.
1907
+ *
1908
+ * @param options - Configuration options.
1909
+ * @returns An `AgentMiddleware` instance.
1910
+ *
1911
+ * @example
1912
+ * ```typescript
1913
+ * import { createCompletionCallbackMiddleware } from "deepagents";
1914
+ *
1915
+ * const notifier = createCompletionCallbackMiddleware({
1916
+ * callbackGraphId: "supervisor",
1917
+ * });
1918
+ *
1919
+ * const agent = createDeepAgent({
1920
+ * model: "claude-sonnet-4-5-20250929",
1921
+ * middleware: [notifier],
1922
+ * });
1923
+ * ```
1924
+ */
1925
+ declare function createCompletionCallbackMiddleware(options: CompletionCallbackOptions): AgentMiddleware<z$2.ZodObject<{
1926
+ callbackThreadId: z$2.ZodOptional<z$2.ZodString>;
1927
+ }, z$2.core.$strip>, undefined, unknown, readonly (import("@langchain/core/tools").ClientTool | import("@langchain/core/tools").ServerTool)[], readonly []>;
1928
+ //#endregion
1929
+ //#region src/middleware/summarization.d.ts
1930
+ /**
1931
+ * Context size specification for summarization triggers and retention policies.
1932
+ */
1933
+ interface ContextSize {
1934
+ /** Type of context measurement */
1935
+ type: "messages" | "tokens" | "fraction";
1936
+ /** Threshold value */
1937
+ value: number;
1938
+ }
1939
+ /**
1940
+ * Settings for truncating large tool arguments in old messages.
1941
+ */
1942
+ interface TruncateArgsSettings {
1943
+ /**
1944
+ * Threshold to trigger argument truncation.
1945
+ * If not provided, truncation is disabled.
1946
+ */
1947
+ trigger?: ContextSize;
1948
+ /**
1949
+ * Context retention policy for message truncation.
1950
+ * Defaults to keeping last 20 messages.
1951
+ */
1952
+ keep?: ContextSize;
1953
+ /**
1954
+ * Maximum character length for tool arguments before truncation.
1955
+ * Defaults to 2000.
1956
+ */
1957
+ maxLength?: number;
1958
+ /**
1959
+ * Text to replace truncated arguments with.
1960
+ * Defaults to "...(argument truncated)".
1961
+ */
1962
+ truncationText?: string;
1963
+ }
1964
+ /**
1965
+ * Options for the summarization middleware.
1966
+ */
1967
+ interface SummarizationMiddlewareOptions {
1968
+ /**
1969
+ * The language model to use for generating summaries.
1970
+ * Can be a model string (e.g., "gpt-4o-mini") or a language model instance.
1971
+ * If omitted, middleware will use the active request model.
1972
+ */
1973
+ model?: string | BaseChatModel | BaseLanguageModel;
1974
+ /**
1975
+ * Backend instance or factory for persisting conversation history.
1976
+ */
1977
+ backend: AnyBackendProtocol | BackendFactory | ((config: {
1978
+ state: unknown;
1979
+ store?: BaseStore;
1980
+ }) => StateBackend);
1981
+ /**
1982
+ * Threshold(s) that trigger summarization.
1983
+ * Can be a single ContextSize or an array for multiple triggers.
1984
+ */
1985
+ trigger?: ContextSize | ContextSize[];
1986
+ /**
1987
+ * Context retention policy after summarization.
1988
+ * Defaults to keeping last 20 messages.
1989
+ */
1990
+ keep?: ContextSize;
1991
+ /**
1992
+ * Prompt template for generating summaries.
1993
+ */
1994
+ summaryPrompt?: string;
1995
+ /**
1996
+ * Max tokens to include when generating summary.
1997
+ * Defaults to 4000.
1998
+ */
1999
+ trimTokensToSummarize?: number;
2000
+ /**
2001
+ * Path prefix for storing conversation history.
2002
+ * Defaults to "/conversation_history".
2003
+ */
2004
+ historyPathPrefix?: string;
2005
+ /**
2006
+ * Settings for truncating large tool arguments in old messages.
2007
+ * If not provided, argument truncation is disabled.
2008
+ */
2009
+ truncateArgsSettings?: TruncateArgsSettings;
2010
+ }
2011
+ /**
2012
+ * Compute summarization defaults based on model profile.
2013
+ * Mirrors Python's `_compute_summarization_defaults`.
2014
+ *
2015
+ * If the model has a profile with `maxInputTokens`, uses fraction-based
2016
+ * settings. Otherwise, uses fixed token/message counts.
2017
+ *
2018
+ * @param resolvedModel - The resolved chat model instance.
2019
+ */
2020
+ declare function computeSummarizationDefaults(resolvedModel: BaseChatModel): {
2021
+ trigger: ContextSize;
2022
+ keep: ContextSize;
2023
+ truncateArgsSettings: TruncateArgsSettings;
2024
+ };
2025
+ /**
2026
+ * Create summarization middleware with backend support for conversation history offloading.
2027
+ *
2028
+ * This middleware:
2029
+ * 1. Monitors conversation length against configured thresholds
2030
+ * 2. When triggered, offloads old messages to backend storage
2031
+ * 3. Generates a summary of offloaded messages
2032
+ * 4. Replaces old messages with the summary, preserving recent context
2033
+ *
2034
+ * @param options - Configuration options
2035
+ * @returns AgentMiddleware for summarization and history offloading
2036
+ */
2037
+ declare function createSummarizationMiddleware(options: SummarizationMiddlewareOptions): AgentMiddleware<z$1.ZodObject<{
2038
+ _summarizationSessionId: z$1.ZodOptional<z$1.ZodString>;
2039
+ _summarizationEvent: z$1.ZodOptional<z$1.ZodObject<{
2040
+ cutoffIndex: z$1.ZodNumber;
2041
+ summaryMessage: z$1.ZodCustom<HumanMessage<_messages.MessageStructure<_messages.MessageToolSet>>, HumanMessage<_messages.MessageStructure<_messages.MessageToolSet>>>;
2042
+ filePath: z$1.ZodNullable<z$1.ZodString>;
2043
+ }, z$1.core.$strip>>;
2044
+ }, z$1.core.$strip>, undefined, unknown, readonly (ClientTool | ServerTool)[], readonly []>;
2045
+ //#endregion
2046
+ //#region src/middleware/async_subagents.d.ts
2047
+ /**
2048
+ * Specification for an async subagent running on a remote [Agent Protocol](https://github.com/langchain-ai/agent-protocol)
2049
+ * server.
2050
+ *
2051
+ * Async subagents connect to any Agent Protocol-compliant server via the
2052
+ * LangGraph SDK. They run as background tasks that the main agent can
2053
+ * monitor and update.
2054
+ *
2055
+ * Compatible with LangGraph Platform (managed) and self-hosted servers.
2056
+ * Authentication for LangGraph Platform is handled automatically by the SDK
2057
+ * via environment variables (`LANGGRAPH_API_KEY`, `LANGSMITH_API_KEY`, or
2058
+ * `LANGCHAIN_API_KEY`). For self-hosted servers, pass custom auth via `headers`.
2059
+ */
2060
+ interface AsyncSubAgent {
2061
+ /** Unique identifier for the async subagent. */
2062
+ name: string;
2063
+ /** What this subagent does. The main agent uses this to decide when to delegate. */
2064
+ description: string;
2065
+ /** The graph name or assistant ID on the Agent Protocol server. */
2066
+ graphId: string;
2067
+ /** URL of the Agent Protocol server. Defaults to the LangGraph SDK's default endpoint. */
2068
+ url?: string;
2069
+ /** Additional headers to include in requests to the server (e.g. for custom auth). */
2070
+ headers?: Record<string, string>;
2071
+ }
2072
+ /**
2073
+ * Possible statuses for an async subagent task.
2074
+ *
2075
+ * Statuses set by the middleware tools: `"running"`, `"success"`, `"error"`, `"cancelled"`.
2076
+ * Statuses that may be returned by the remote server: `"pending"`, `"timeout"`, `"interrupted"`.
2077
+ */
2078
+ type AsyncTaskStatus = "pending" | "running" | "success" | "error" | "cancelled" | "timeout" | "interrupted";
2079
+ /**
2080
+ * A tracked async subagent task persisted in agent state.
2081
+ *
2082
+ * Each task maps to a single thread + run on a remote Agent Protocol server.
2083
+ * The `taskId` is the same as `threadId`, so it can be used to look up
2084
+ * the thread directly via the SDK.
2085
+ */
2086
+ interface AsyncTask {
2087
+ /** Unique identifier for the task (same as thread id). */
2088
+ taskId: string;
2089
+ /** Name of the async subagent type that is running. */
2090
+ agentName: string;
2091
+ /** Thread ID on the remote server. */
2092
+ threadId: string;
2093
+ /** Run ID for the current execution on the thread. */
2094
+ runId: string;
2095
+ /** Current task status. */
2096
+ status: AsyncTaskStatus;
2097
+ /** ISO timestamp of when the task was launched. */
2098
+ createdAt: string;
2099
+ /** The prompt/description passed to the subagent when the task was launched. */
2100
+ description?: string;
2101
+ /** ISO timestamp of the most recent task update — set when the task status changes or a follow-up message is sent via the update tool. */
2102
+ updatedAt?: string;
2103
+ /** ISO timestamp of the most recent status poll via the check tool. */
2104
+ checkedAt?: string;
2105
+ }
2106
+ /**
2107
+ * Task statuses that will never change.
2108
+ *
2109
+ * When listing tasks, live-status fetches are skipped for tasks whose
2110
+ * cached status is in this set, since they are guaranteed to be final.
2111
+ */
2112
+ /**
2113
+ * Names of the tools added by the async subagent middleware.
2114
+ *
2115
+ * Exported so `agent.ts` can include them in `BUILTIN_TOOL_NAMES` and
2116
+ * surface a `ConfigurationError` if a user-provided tool collides.
2117
+ */
2118
+ declare const ASYNC_TASK_TOOL_NAMES: readonly ["start_async_task", "check_async_task", "update_async_task", "cancel_async_task", "list_async_tasks"];
2119
+ /**
2120
+ * Options for creating async subagent middleware.
2121
+ */
2122
+ interface AsyncSubAgentMiddlewareOptions {
2123
+ /** List of async subagent specifications. Must have at least one. */
2124
+ asyncSubAgents: AsyncSubAgent[];
2125
+ /** System prompt override. Set to `null` to disable. Defaults to {@link ASYNC_TASK_SYSTEM_PROMPT}. */
2126
+ systemPrompt?: string;
2127
+ }
2128
+ /**
2129
+ * Create middleware that adds async subagent tools to an agent.
2130
+ *
2131
+ * Provides five tools for launching, checking, updating, cancelling, and
2132
+ * listing background tasks on remote Agent Protocol servers. Task state is
2133
+ * persisted in the `asyncTasks` state channel so it survives
2134
+ * context compaction.
2135
+ *
2136
+ * Works with any Agent Protocol-compliant server — LangGraph Platform (managed)
2137
+ * or self-hosted (e.g. a Hono/Express server implementing the Agent Protocol spec).
2138
+ *
2139
+ * @throws {Error} If no async subagents are provided or names are duplicated.
2140
+ *
2141
+ * @example
2142
+ * ```ts
2143
+ * const middleware = createAsyncSubAgentMiddleware({
2144
+ * asyncSubAgents: [{
2145
+ * name: "researcher",
2146
+ * description: "Research agent for deep analysis",
2147
+ * url: "https://my-agent-protocol-server.example.com",
2148
+ * graphId: "research_agent",
2149
+ * }],
2150
+ * });
2151
+ * ```
2152
+ */
2153
+ /**
2154
+ * Type guard to distinguish async SubAgents from sync SubAgents/CompiledSubAgents.
2155
+ *
2156
+ * Uses the presence of the `graphId` field as the runtime discriminant —
2157
+ * `AsyncSubAgent` requires it, while `SubAgent` and `CompiledSubAgent` do not have it.
2158
+ */
2159
+ declare function isAsyncSubAgent(subAgent: AnySubAgent): subAgent is AsyncSubAgent;
2160
+ declare function createAsyncSubAgentMiddleware(options: AsyncSubAgentMiddlewareOptions): import("langchain").AgentMiddleware<StateSchema<{
2161
+ asyncTasks: ReducedValue<Record<string, {
2162
+ taskId: string;
2163
+ agentName: string;
2164
+ threadId: string;
2165
+ runId: string;
2166
+ status: string;
2167
+ createdAt: string;
2168
+ description?: string | undefined;
2169
+ updatedAt?: string | undefined;
2170
+ checkedAt?: string | undefined;
2171
+ }> | undefined, Record<string, {
2172
+ taskId: string;
2173
+ agentName: string;
2174
+ threadId: string;
2175
+ runId: string;
2176
+ status: string;
2177
+ createdAt: string;
2178
+ description?: string | undefined;
2179
+ updatedAt?: string | undefined;
2180
+ checkedAt?: string | undefined;
2181
+ }> | undefined>;
2182
+ }>, undefined, unknown, (import("langchain").DynamicStructuredTool<z.ZodObject<{
2183
+ description: z.ZodString;
2184
+ agentName: z.ZodString;
2185
+ }, z.core.$strip>, {
2186
+ description: string;
2187
+ agentName: string;
2188
+ }, {
2189
+ description: string;
2190
+ agentName: string;
2191
+ }, string | Command<unknown, Record<string, unknown>, string>, unknown, "start_async_task"> | import("langchain").DynamicStructuredTool<z.ZodObject<{
2192
+ taskId: z.ZodString;
2193
+ }, z.core.$strip>, {
2194
+ taskId: string;
2195
+ }, {
2196
+ taskId: string;
2197
+ }, string | Command<unknown, Record<string, unknown>, string>, unknown, "check_async_task"> | import("langchain").DynamicStructuredTool<z.ZodObject<{
2198
+ taskId: z.ZodString;
2199
+ message: z.ZodString;
2200
+ }, z.core.$strip>, {
2201
+ taskId: string;
2202
+ message: string;
2203
+ }, {
2204
+ taskId: string;
2205
+ message: string;
2206
+ }, string | Command<unknown, Record<string, unknown>, string>, unknown, "update_async_task"> | import("langchain").DynamicStructuredTool<z.ZodObject<{
2207
+ taskId: z.ZodString;
2208
+ }, z.core.$strip>, {
2209
+ taskId: string;
2210
+ }, {
2211
+ taskId: string;
2212
+ }, string | Command<unknown, Record<string, unknown>, string>, unknown, "cancel_async_task"> | import("langchain").DynamicStructuredTool<z.ZodObject<{
2213
+ statusFilter: z.ZodOptional<z.ZodNullable<z.ZodString>>;
2214
+ }, z.core.$strip>, {
2215
+ statusFilter?: string | null | undefined;
2216
+ }, {
2217
+ statusFilter?: string | null | undefined;
2218
+ }, string | Command<unknown, Record<string, unknown>, string>, unknown, "list_async_tasks">)[], readonly []>;
2219
+ //#endregion
2220
+ //#region src/types.d.ts
2221
+ type AnyAnnotationRoot = AnnotationRoot<any>;
2222
+ /**
2223
+ * Literal union of all built-in deep agent tool names.
2224
+ * These are always present on the agent regardless of user-provided tools.
2225
+ */
2226
+ type DeepAgentBuiltinToolName = (typeof FILESYSTEM_TOOL_NAMES)[number] | (typeof ASYNC_TASK_TOOL_NAMES)[number] | "task" | "write_todos";
2227
+ /**
2228
+ * A placeholder StructuredTool type with a literal `name` for each
2229
+ * built-in tool. Used to thread built-in tool names into the
2230
+ * `ToolCallStreamUnion` so they appear in `run.toolCalls` alongside
2231
+ * user-provided tools.
2232
+ */
2233
+ type BuiltinToolPlaceholder<N extends string> = {
2234
+ name: N;
2235
+ } & StructuredTool$1;
2236
+ /**
2237
+ * Tuple of placeholder tool types for all built-in deep agent tools.
2238
+ * Combined with `TTypes["Tools"]` in the `DeepAgentRunStream` return type.
2239
+ */
2240
+ type DeepAgentBuiltinToolsTuple = { [K in DeepAgentBuiltinToolName]: BuiltinToolPlaceholder<K> }[DeepAgentBuiltinToolName][];
2241
+ type InferDeepAgentStreamExtensions<T extends ReadonlyArray<() => StreamTransformer<any>>> = T extends readonly [] ? Record<string, never> : T extends readonly [() => StreamTransformer<infer P>, ...infer Rest extends ReadonlyArray<() => StreamTransformer<any>>] ? P & InferDeepAgentStreamExtensions<Rest> : Record<string, unknown>;
2242
+ /** Any subagent specification — sync, compiled, or async. */
2243
+ type AnySubAgent = SubAgent | CompiledSubAgent | AsyncSubAgent;
2244
+ interface TypedToolStrategy<T = unknown> extends Array<ToolStrategy<any>> {
2245
+ _schemaType?: T;
2246
+ }
2247
+ /**
2248
+ * Helper type to extract middleware from a SubAgent definition
2249
+ * Handles both mutable and readonly middleware arrays
2250
+ */
2251
+ type ExtractSubAgentMiddleware<T> = T extends {
2252
+ middleware?: infer M;
2253
+ } ? M extends readonly AgentMiddleware[] ? M : M extends AgentMiddleware[] ? M : readonly [] : readonly [];
2254
+ /**
2255
+ * Helper type to flatten and merge middleware from all subagents
2256
+ */
2257
+ type FlattenSubAgentMiddleware<T extends readonly AnySubAgent[]> = T extends readonly [] ? readonly [] : T extends readonly [infer First, ...infer Rest] ? Rest extends readonly AnySubAgent[] ? readonly [...ExtractSubAgentMiddleware<First>, ...FlattenSubAgentMiddleware<Rest>] : ExtractSubAgentMiddleware<First> : readonly [];
2258
+ /**
2259
+ * Helper type to merge states from subagent middleware
2260
+ */
2261
+ type InferSubAgentMiddlewareStates<T extends readonly AnySubAgent[]> = InferMiddlewareStates<FlattenSubAgentMiddleware<T>>;
2262
+ /**
2263
+ * Combined state type including custom middleware and subagent middleware states
2264
+ */
2265
+ type MergedDeepAgentState<TMiddleware extends readonly AgentMiddleware[], TSubagents extends readonly AnySubAgent[]> = InferMiddlewareStates<TMiddleware> & InferSubAgentMiddlewareStates<TSubagents>;
2266
+ /**
2267
+ * Union of all response format types accepted by `createDeepAgent`.
2268
+ *
2269
+ * Matches the formats supported by LangChain's `createAgent`:
2270
+ * - `ToolStrategy<T>` — from `ToolStrategy.fromSchema(schema)`
2271
+ * - `ProviderStrategy<T>` — from `providerStrategy(schema)`
2272
+ * - `TypedToolStrategy<T>` — from `toolStrategy(schema)`
2273
+ * - `ResponseFormat` — the base union of the above single-strategy types
2274
+ */
2275
+ type SupportedResponseFormat = ResponseFormat | TypedToolStrategy<any>;
2276
+ /**
2277
+ * Utility type to extract the parsed response type from a ResponseFormat strategy.
2278
+ *
2279
+ * Maps `ToolStrategy<T>`, `ProviderStrategy<T>`, and `TypedToolStrategy<T>` to `T`
2280
+ * (the parsed output type), so that `structuredResponse` is correctly typed as the
2281
+ * schema's inferred type rather than the strategy wrapper.
2282
+ *
2283
+ * When no `responseFormat` is provided (i.e. `T` defaults to the full
2284
+ * `SupportedResponseFormat` union), this resolves to `ResponseFormatUndefined` so
2285
+ * that `structuredResponse` is excluded from the agent's output state.
2286
+ *
2287
+ * @example
2288
+ * ```typescript
2289
+ * type T1 = InferStructuredResponse<ToolStrategy<{ city: string }>>; // { city: string }
2290
+ * type T2 = InferStructuredResponse<ProviderStrategy<{ answer: string }>>; // { answer: string }
2291
+ * type T3 = InferStructuredResponse<TypedToolStrategy<{ city: string }>>; // { city: string }
2292
+ * type T4 = InferStructuredResponse<SupportedResponseFormat>; // ResponseFormatUndefined (default/unset)
2293
+ * ```
2294
+ */
2295
+ type InferStructuredResponse<T extends SupportedResponseFormat> = SupportedResponseFormat extends T ? ResponseFormatUndefined : T extends TypedToolStrategy<infer U> ? U : T extends ToolStrategy<infer U> ? U : T extends ProviderStrategy<infer U> ? U : ResponseFormatUndefined;
2296
+ /**
2297
+ * Type bag that extends AgentTypeConfig with subagent type information.
2298
+ *
2299
+ * This interface bundles all the generic type parameters used throughout the deep agent system
2300
+ * including subagent types for type-safe streaming and delegation.
2301
+ *
2302
+ * @typeParam TResponse - The structured response type when using `responseFormat`.
2303
+ * @typeParam TState - The custom state schema type.
2304
+ * @typeParam TContext - The context schema type.
2305
+ * @typeParam TMiddleware - The middleware array type.
2306
+ * @typeParam TTools - The combined tools type.
2307
+ * @typeParam TSubagents - The subagents array type for type-safe streaming.
2308
+ *
2309
+ * @example
2310
+ * ```typescript
2311
+ * const agent = createDeepAgent({
2312
+ * middleware: [ResearchMiddleware],
2313
+ * subagents: [
2314
+ * { name: "researcher", description: "...", middleware: [CounterMiddleware] }
2315
+ * ] as const,
2316
+ * });
2317
+ *
2318
+ * // Type inference for streaming
2319
+ * type Types = InferDeepAgentType<typeof agent, "Subagents">;
2320
+ * ```
2321
+ */
2322
+ interface DeepAgentTypeConfig<TResponse extends Record<string, any> | ResponseFormatUndefined = Record<string, any> | ResponseFormatUndefined, TState extends StateDefinitionInit | undefined = StateDefinitionInit | undefined, TContext extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot | InteropZodObject, TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[], TTools extends readonly (ClientTool | ServerTool)[] = readonly (ClientTool | ServerTool)[], TSubagents extends readonly AnySubAgent[] = readonly AnySubAgent[], TStreamTransformers extends ReadonlyArray<() => StreamTransformer<any>> = ReadonlyArray<() => StreamTransformer<any>>> extends AgentTypeConfig<TResponse, TState, TContext, TMiddleware, TTools, TStreamTransformers> {
2323
+ /** The subagents array type for type-safe streaming */
2324
+ Subagents: TSubagents;
2325
+ }
2326
+ /**
2327
+ * Default type configuration for deep agents.
2328
+ * Used when no explicit type parameters are provided.
2329
+ */
2330
+ interface DefaultDeepAgentTypeConfig extends DeepAgentTypeConfig {
2331
+ Response: Record<string, any>;
2332
+ State: undefined;
2333
+ Context: AnyAnnotationRoot;
2334
+ Middleware: readonly AgentMiddleware[];
2335
+ Tools: readonly (ClientTool | ServerTool)[];
2336
+ Subagents: readonly AnySubAgent[];
2337
+ StreamTransformers: readonly [];
2338
+ }
2339
+ /**
2340
+ * DeepAgent extends ReactAgent with additional subagent type information.
2341
+ *
2342
+ * This type wraps ReactAgent but includes the DeepAgentTypeConfig which
2343
+ * contains subagent types for type-safe streaming and delegation.
2344
+ *
2345
+ * @typeParam TTypes - The DeepAgentTypeConfig containing all type parameters
2346
+ *
2347
+ * @example
2348
+ * ```typescript
2349
+ * const agent: DeepAgent<DeepAgentTypeConfig<...>> = createDeepAgent({ ... });
2350
+ *
2351
+ * // Access subagent types for streaming
2352
+ * type Subagents = InferDeepAgentSubagents<typeof agent>;
2353
+ * ```
2354
+ */
2355
+ interface DeepAgent<TTypes extends DeepAgentTypeConfig = DeepAgentTypeConfig> extends ReactAgent<TTypes> {
2356
+ /** Type brand for DeepAgent type inference */
2357
+ readonly "~deepAgentTypes": TTypes;
2358
+ /**
2359
+ * Executes the agent with the v3 streaming interface, returning an
2360
+ * {@link DeepAgentRunStream} that provides ergonomic, typed projections for
2361
+ * messages, tool calls, subagents, and middleware events.
2362
+ *
2363
+ * Pass `version: "v3"` to opt into this projection-oriented stream. Omitting
2364
+ * `version` preserves the legacy internal LangGraph event-stream behavior
2365
+ * for compatibility with LangGraph Platform integrations.
2366
+ *
2367
+ * This v3 stream is experimental and its API may change in future releases.
2368
+ * It will become the default in a future major release.
2369
+ *
2370
+ * @param state - The initial state for the agent execution. Can be:
2371
+ * - An object containing `messages` array and any middleware-specific state properties
2372
+ * - A Command object for more advanced control flow
2373
+ *
2374
+ * @param config - Runtime configuration including:
2375
+ * @param config.version - Must be `"v3"` to use the {@link DeepAgentRunStream}
2376
+ * interface. The default legacy event stream is maintained for internal
2377
+ * integrations and should not be used for new user-facing agent streaming.
2378
+ * @param config.context - The context for the agent execution.
2379
+ * @param config.configurable - LangGraph configuration options like `thread_id`, `run_id`, etc.
2380
+ * @param config.store - The store for the agent execution for persisting state.
2381
+ * @param config.signal - An optional AbortSignal for the agent execution.
2382
+ * @param config.recursionLimit - The recursion limit for the agent execution.
2383
+ *
2384
+ * @returns A Promise that resolves to an {@link DeepAgentRunStream} providing:
2385
+ * - `run.messages` — all AI message lifecycles with streaming `.text` and `.reasoning`
2386
+ * - `run.toolCalls` — individual tool call streams with `.input`, `.output`, `.status`
2387
+ * - `run.subagents` — subagent delegation streams
2388
+ * - `run.middleware` — middleware lifecycle events (before/after agent/model)
2389
+ * - `run.values` — state snapshots (async iterable + promise-like)
2390
+ * - `run.output` — final agent state when the run completes
2391
+ * - `run.subgraphs` — child subgraph run streams
2392
+ * - `run.extensions` — merged projections from user-supplied transformers
2393
+ *
2394
+ * @example
2395
+ * ```typescript
2396
+ * const run = await agent.streamEvents(
2397
+ * {
2398
+ * messages: [{ role: "user", content: "What's the weather in Paris?" }],
2399
+ * },
2400
+ * { version: "v3" }
2401
+ * );
2402
+ *
2403
+ * // Stream all messages
2404
+ * for await (const msg of run.messages) {
2405
+ * for await (const token of msg.text) {
2406
+ * process.stdout.write(token);
2407
+ * }
2408
+ * }
2409
+ *
2410
+ * // Observe tool calls
2411
+ * for await (const call of run.toolCalls) {
2412
+ * console.log(`Tool: ${call.name}`, call.input);
2413
+ * console.log(`Result:`, await call.output);
2414
+ * }
2415
+ *
2416
+ * // Observe subagent delegations
2417
+ * for await (const subagent of run.subagents) {
2418
+ * console.log(`Subagent: ${subagent.name}`);
2419
+ *
2420
+ * for await (const msg of subagent.messages) {
2421
+ * for await (const token of msg.text) {
2422
+ * process.stdout.write(token);
2423
+ * }
2424
+ * }
2425
+ * }
2426
+ *
2427
+ * // Get final state
2428
+ * const state = await run.output;
2429
+ * ```
2430
+ */
2431
+ streamEvents: ((state: Parameters<ReactAgent<TTypes>["invoke"]>[0], config: NonNullable<Parameters<ReactAgent<TTypes>["invoke"]>[1]> & {
2432
+ version: "v3";
2433
+ }) => Promise<DeepAgentRunStream<Awaited<ReturnType<ReactAgent<TTypes>["invoke"]>>, readonly [...TTypes["Tools"], ...DeepAgentBuiltinToolsTuple], TTypes["Subagents"], InferDeepAgentStreamExtensions<TTypes["StreamTransformers"]>>>) & ReactAgent<TTypes>["streamEvents"];
2434
+ }
2435
+ /**
2436
+ * Helper type to resolve a DeepAgentTypeConfig from either:
2437
+ * - A DeepAgentTypeConfig directly
2438
+ * - A DeepAgent instance (using `typeof agent`)
2439
+ *
2440
+ * @example
2441
+ * ```typescript
2442
+ * const agent = createDeepAgent({ ... });
2443
+ * type Types = ResolveDeepAgentTypeConfig<typeof agent>;
2444
+ * ```
2445
+ */
2446
+ type ResolveDeepAgentTypeConfig<T> = T extends {
2447
+ "~deepAgentTypes": infer Types;
2448
+ } ? Types extends DeepAgentTypeConfig ? Types : never : T extends DeepAgentTypeConfig ? T : never;
2449
+ /**
2450
+ * Helper type to extract any property from a DeepAgentTypeConfig or DeepAgent.
2451
+ *
2452
+ * @typeParam T - The DeepAgentTypeConfig or DeepAgent to extract from
2453
+ * @typeParam K - The property key to extract
2454
+ *
2455
+ * @example
2456
+ * ```typescript
2457
+ * const agent = createDeepAgent({ subagents: [...] });
2458
+ * type Subagents = InferDeepAgentType<typeof agent, "Subagents">;
2459
+ * ```
2460
+ */
2461
+ type InferDeepAgentType<T, K extends keyof DeepAgentTypeConfig> = ResolveDeepAgentTypeConfig<T>[K];
2462
+ /**
2463
+ * Shorthand helper to extract the Subagents type from a DeepAgentTypeConfig or DeepAgent.
2464
+ *
2465
+ * @example
2466
+ * ```typescript
2467
+ * const agent = createDeepAgent({ subagents: [subagent1, subagent2] });
2468
+ * type Subagents = InferDeepAgentSubagents<typeof agent>;
2469
+ * ```
2470
+ */
2471
+ type InferDeepAgentSubagents<T> = InferDeepAgentType<T, "Subagents">;
2472
+ /**
2473
+ * Helper type to extract a subagent by name from a DeepAgent.
2474
+ *
2475
+ * @typeParam T - The DeepAgent to extract from
2476
+ * @typeParam TName - The name of the subagent to extract
2477
+ *
2478
+ * @example
2479
+ * ```typescript
2480
+ * const agent = createDeepAgent({
2481
+ * subagents: [
2482
+ * { name: "researcher", description: "...", middleware: [ResearchMiddleware] }
2483
+ * ] as const,
2484
+ * });
2485
+ *
2486
+ * type ResearcherAgent = InferSubagentByName<typeof agent, "researcher">;
2487
+ * ```
2488
+ */
2489
+ type InferSubagentByName<T, TName extends string> = InferDeepAgentSubagents<T> extends readonly (infer SA)[] ? SA extends {
2490
+ name: TName;
2491
+ } ? SA : never : never;
2492
+ /**
2493
+ * Helper type to extract the ReactAgent type from a subagent definition.
2494
+ * This is useful for type-safe streaming of subagent events.
2495
+ *
2496
+ * @typeParam TSubagent - The subagent definition
2497
+ *
2498
+ * @example
2499
+ * ```typescript
2500
+ * type SubagentMiddleware = ExtractSubAgentMiddleware<typeof subagent>;
2501
+ * type SubagentState = InferMiddlewareStates<SubagentMiddleware>;
2502
+ * ```
2503
+ */
2504
+ type InferSubagentReactAgentType<TSubagent extends SubAgent | CompiledSubAgent> = TSubagent extends CompiledSubAgent ? TSubagent["runnable"] : TSubagent extends SubAgent ? ReactAgent<AgentTypeConfig<ResponseFormatUndefined, undefined, AnyAnnotationRoot, ExtractSubAgentMiddleware<TSubagent>, readonly []>> : never;
2505
+ /**
2506
+ * Configuration parameters for creating a Deep Agent
2507
+ * Matches Python's create_deep_agent parameters
2508
+ *
2509
+ * @typeParam TResponse - The structured response type when using responseFormat
2510
+ * @typeParam ContextSchema - The context schema type
2511
+ * @typeParam TMiddleware - The middleware array type for proper type inference
2512
+ * @typeParam TSubagents - The subagents array type for extracting subagent middleware states
2513
+ * @typeParam TTools - The tools array type
2514
+ * @typeParam TStreamTransformers - Custom stream transformer factories
2515
+ * @typeParam TStateSchema - The custom state schema type
2516
+ */
2517
+ interface CreateDeepAgentParams<TResponse extends SupportedResponseFormat = SupportedResponseFormat, ContextSchema extends AnnotationRoot<any> | InteropZodObject = AnnotationRoot<any>, TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[], TSubagents extends readonly AnySubAgent[] = readonly AnySubAgent[], TTools extends readonly (ClientTool | ServerTool)[] = readonly (ClientTool | ServerTool)[], TStreamTransformers extends ReadonlyArray<() => StreamTransformer<any>> = readonly [], TStateSchema extends AnyStateSchema | InteropZodObject | undefined = undefined> {
2518
+ /** The model to use (model name string or LanguageModelLike instance). Defaults to claude-sonnet-4-5-20250929 */
2519
+ model?: BaseLanguageModel | string;
2520
+ /** Tools the agent should have access to */
2521
+ tools?: TTools | StructuredTool$1[];
2522
+ /** Custom system prompt for the agent. This will be combined with the base agent prompt */
2523
+ systemPrompt?: string | SystemMessage;
2524
+ /**
2525
+ * Optional schema for custom agent state. Allows you to define custom state properties
2526
+ * beyond built-in `messages`, `todos`, and `files`. These properties can be accessed
2527
+ * in hooks, middleware, and throughout the agent's execution.
2528
+ *
2529
+ * Unlike `contextSchema` the state is persisted between agent invocations when using a
2530
+ * checkpointer, making it suitable for maintaining conversation history, user preferences,
2531
+ * or any other data that should persist across multiple interactions.
2532
+ *
2533
+ * @example
2534
+ * ```ts
2535
+ * import { StateSchema } from "@langchain/langgraph";
2536
+ * import { z } from "zod";
2537
+ *
2538
+ * const agent = createDeepAgent({
2539
+ * stateSchema: new StateSchema({
2540
+ * author: z.string().default("unknown"),
2541
+ * }),
2542
+ * });
2543
+ *
2544
+ * const result = await agent.invoke({
2545
+ * messages: [{ role: "user", content: "Take a note" }],
2546
+ * author: "Me",
2547
+ * });
2548
+ * // result.author is typed `string`
2549
+ * ```
2550
+ */
2551
+ stateSchema?: TStateSchema;
2552
+ /** Custom middleware to apply after standard middleware */
2553
+ middleware?: TMiddleware;
2554
+ /**
2555
+ * List of subagent specifications for task delegation.
2556
+ *
2557
+ * Supports sync SubAgents, CompiledSubAgents, and AsyncSubAgents in the same array.
2558
+ * AsyncSubAgents (identified by their `graphId` field) are automatically separated
2559
+ * at runtime and wired to the async SubAgent middleware.
2560
+ */
2561
+ subagents?: TSubagents;
2562
+ /** Structured output response format for the agent (Zod schema or other format) */
2563
+ responseFormat?: TResponse;
2564
+ /** Optional schema for context (not persisted between invocations) */
2565
+ contextSchema?: ContextSchema;
2566
+ /** Optional checkpointer for persisting agent state between runs */
2567
+ checkpointer?: BaseCheckpointSaver | boolean;
2568
+ /** Optional store for persisting longterm memories */
2569
+ store?: BaseStore;
2570
+ /**
2571
+ * Optional backend for filesystem operations.
2572
+ * Can be either a backend instance or a factory function that creates one.
2573
+ * The factory receives a config object with state and store.
2574
+ */
2575
+ backend?: AnyBackendProtocol | ((config: {
2576
+ state: unknown;
2577
+ store?: BaseStore;
2578
+ }) => AnyBackendProtocol);
2579
+ /** Optional interrupt configuration mapping tool names to interrupt configs */
2580
+ interruptOn?: Record<string, boolean | InterruptOnConfig>;
2581
+ /** The name of the agent */
2582
+ name?: string;
2583
+ /**
2584
+ * Optional list of memory file paths (AGENTS.md files) to load
2585
+ * (e.g., ["~/.deepagents/AGENTS.md", "./.deepagents/AGENTS.md"]).
2586
+ * Display names are automatically derived from paths.
2587
+ * Memory is loaded at agent startup and added into the system prompt.
2588
+ */
2589
+ memory?: string[];
2590
+ /**
2591
+ * Optional list of skill source paths (e.g., `["/skills/user/", "/skills/project/"]`).
2592
+ *
2593
+ * Paths use POSIX conventions (forward slashes) and are relative to the backend's root.
2594
+ * Later sources override earlier ones for skills with the same name (last one wins).
2595
+ *
2596
+ * @example
2597
+ * ```typescript
2598
+ * // With FilesystemBackend - skills loaded from disk
2599
+ * const agent = await createDeepAgent({
2600
+ * backend: new FilesystemBackend({ rootDir: "/home/user/.deepagents" }),
2601
+ * skills: ["/skills/"],
2602
+ * });
2603
+ *
2604
+ * // With StateBackend - skills provided in state
2605
+ * const agent = await createDeepAgent({
2606
+ * skills: ["/skills/"],
2607
+ * });
2608
+ * const result = await agent.invoke({
2609
+ * messages: [...],
2610
+ * files: {
2611
+ * "/skills/my-skill/SKILL.md": {
2612
+ * content: ["---", "name: my-skill", "description: ...", "---", "# My Skill"],
2613
+ * created_at: new Date().toISOString(),
2614
+ * modified_at: new Date().toISOString(),
2615
+ * },
2616
+ * },
2617
+ * });
2618
+ * ```
2619
+ */
2620
+ skills?: string[];
2621
+ /**
2622
+ * Filesystem permission rules for this agent.
2623
+ *
2624
+ * Rules are evaluated in declaration order; first match wins; permissive
2625
+ * default. Applied to `ls`, `read_file`, `write_file`, `edit_file`, `glob`,
2626
+ * and `grep`. Subagents inherit these rules unless they specify their own
2627
+ * `permissions` field.
2628
+ *
2629
+ * @example
2630
+ * ```ts
2631
+ * createDeepAgent({
2632
+ * permissions: [
2633
+ * { operations: ["read"], paths: ["/workspace/**"] },
2634
+ * { operations: ["read"], paths: ["/**"], mode: "deny" },
2635
+ * ],
2636
+ * });
2637
+ * ```
2638
+ */
2639
+ permissions?: FilesystemPermission[];
2640
+ /**
2641
+ * Optional {@link StreamTransformer} factories to register with the underlying agent.
2642
+ *
2643
+ * Deepagents always registers its built-in subagent transformer; custom
2644
+ * transformers are appended after it and are exposed on `run.extensions`
2645
+ * when using `streamEvents(..., { version: "v3" })`.
2646
+ */
2647
+ streamTransformers?: TStreamTransformers;
2648
+ }
2649
+ //#endregion
2650
+ //#region src/stream.d.ts
2651
+ /**
2652
+ * Represents a single subagent invocation observed during a deep agent run.
2653
+ *
2654
+ * @typeParam TOutput - The subagent's output state type. Defaults to
2655
+ * `unknown`; inferred to the subagent's `MergedAgentState` for
2656
+ * `CompiledSubAgent` via {@link SubagentRunStreamUnion}.
2657
+ */
2658
+ interface SubagentRunStream<TOutput = unknown, TTools extends readonly (ClientTool | ServerTool)[] = readonly (ClientTool | ServerTool)[]> {
2659
+ readonly name: string;
2660
+ readonly taskInput: Promise<string>;
2661
+ readonly output: Promise<TOutput>;
2662
+ readonly messages: AsyncIterable<ChatModelStream>;
2663
+ readonly toolCalls: AsyncIterable<ToolCallStreamUnion<TTools>>;
2664
+ readonly subagents: AsyncIterable<SubagentRunStream>;
2665
+ }
2666
+ /**
2667
+ * Extract the output state type from a subagent spec.
2668
+ * For `CompiledSubAgent<ReactAgent<Types>>`, resolves to the agent's
2669
+ * invoke return type. Falls back to `unknown` for `SubAgent` and
2670
+ * `AsyncSubAgent`.
2671
+ */
2672
+ type SubagentOutputOf<T extends AnySubAgent> = T extends CompiledSubAgent<infer R> ? R extends ReactAgent<infer Types> ? Awaited<ReturnType<ReactAgent<Types>["invoke"]>> : unknown : unknown;
2673
+ /**
2674
+ * Extract the tools tuple from a subagent spec.
2675
+ * For `CompiledSubAgent<ReactAgent<Types>>`, resolves to `Types["Tools"]`.
2676
+ * Falls back to the default `(ClientTool | ServerTool)[]` for `SubAgent`
2677
+ * and `AsyncSubAgent`.
2678
+ */
2679
+ type SubagentToolsOf<T extends AnySubAgent> = T extends CompiledSubAgent<infer R> ? R extends ReactAgent<infer Types> ? Types["Tools"] : readonly (ClientTool | ServerTool)[] : readonly (ClientTool | ServerTool)[];
2680
+ /**
2681
+ * A typed `SubagentRunStream` variant for a single subagent spec.
2682
+ * Narrows `.name` to the literal string type, `.output` to the
2683
+ * inferred state type, and `.toolCalls` to the subagent's tools
2684
+ * when available.
2685
+ */
2686
+ type NamedSubagentRunStream<T extends AnySubAgent> = T extends {
2687
+ name: infer N extends string;
2688
+ } ? SubagentRunStream<SubagentOutputOf<T>, SubagentToolsOf<T>> & {
2689
+ readonly name: N;
2690
+ } : SubagentRunStream;
2691
+ /**
2692
+ * Discriminated union of {@link SubagentRunStream} variants, one per
2693
+ * subagent in `TSubagents`. Enables TypeScript to narrow `.output`
2694
+ * when the consumer checks `sub.name === "someSubagentName"`.
2695
+ */
2696
+ type SubagentRunStreamUnion<TSubagents extends readonly AnySubAgent[]> = { [K in keyof TSubagents]: NamedSubagentRunStream<TSubagents[K]> }[number];
2697
+ /**
2698
+ * An {@link AgentRunStream} with native deep-agent projections assigned
2699
+ * directly on the instance by `createGraphRunStream` (via `__native`
2700
+ * transformers).
2701
+ *
2702
+ * This is a pure type overlay — no runtime class exists. The
2703
+ * `subagents` property is populated at runtime by the
2704
+ * `createSubagentTransformer` registered at compile time.
2705
+ */
2706
+ type DeepAgentRunStream<TValues = Record<string, unknown>, TTools extends readonly (ClientTool | ServerTool)[] = readonly (ClientTool | ServerTool)[], TSubagents extends readonly AnySubAgent[] = readonly AnySubAgent[], TExtensions extends Record<string, unknown> = Record<string, unknown>> = AgentRunStream<TValues, TTools, TExtensions> & {
2707
+ /** Subagent invocation streams from the native SubagentTransformer. */subagents: AsyncIterable<SubagentRunStreamUnion<TSubagents>>;
2708
+ };
2709
+ interface SubagentProjection {
2710
+ subagents: AsyncIterable<SubagentRunStream>;
2711
+ }
2712
+ /**
2713
+ * Native transformer that correlates `task` tool calls into
2714
+ * {@link SubagentRunStream} objects and routes child-namespace
2715
+ * `tools` and `messages` events into per-subagent channels.
2716
+ *
2717
+ * Marked `__native: true` — the `subagents` projection key lands
2718
+ * directly on the `GraphRunStream` instance as `run.subagents`.
2719
+ */
2720
+ declare function createSubagentTransformer(path: Namespace): () => NativeStreamTransformer<SubagentProjection>;
2721
+ //#endregion
2722
+ //#region src/config.d.ts
2723
+ /**
2724
+ * Configuration and settings for deepagents.
2725
+ *
2726
+ * Provides project detection, path management, and environment configuration
2727
+ * for skills and agent memory middleware.
2728
+ */
2729
+ /**
2730
+ * Options for creating a Settings instance.
2731
+ */
2732
+ interface SettingsOptions {
2733
+ /** Starting directory for project detection (defaults to cwd) */
2734
+ startPath?: string;
2735
+ }
2736
+ /**
2737
+ * Settings interface for project detection and path management.
2738
+ *
2739
+ * Provides access to:
2740
+ * - Project root detection (via .git directory)
2741
+ * - User-level deepagents directory (~/.deepagents)
2742
+ * - Agent-specific directories and files
2743
+ * - Skills directories (user and project level)
2744
+ */
2745
+ interface Settings {
2746
+ /** Detected project root directory, or null if not in a git project */
2747
+ readonly projectRoot: string | null;
2748
+ /** Base user-level .deepagents directory (~/.deepagents) */
2749
+ readonly userDeepagentsDir: string;
2750
+ /** Check if currently in a git project */
2751
+ readonly hasProject: boolean;
2752
+ /**
2753
+ * Get the agent directory path.
2754
+ * @param agentName - Name of the agent
2755
+ * @returns Path to ~/.deepagents/{agentName}
2756
+ * @throws Error if agent name is invalid
2757
+ */
2758
+ getAgentDir(agentName: string): string;
2759
+ /**
2760
+ * Ensure agent directory exists and return path.
2761
+ * @param agentName - Name of the agent
2762
+ * @returns Path to ~/.deepagents/{agentName}
2763
+ * @throws Error if agent name is invalid
2764
+ */
2765
+ ensureAgentDir(agentName: string): string;
2766
+ /**
2767
+ * Get user-level agent.md path for a specific agent.
2768
+ * @param agentName - Name of the agent
2769
+ * @returns Path to ~/.deepagents/{agentName}/agent.md
2770
+ */
2771
+ getUserAgentMdPath(agentName: string): string;
2772
+ /**
2773
+ * Get project-level agent.md path.
2774
+ * @returns Path to {projectRoot}/.deepagents/agent.md, or null if not in a project
2775
+ */
2776
+ getProjectAgentMdPath(): string | null;
2777
+ /**
2778
+ * Get user-level skills directory path for a specific agent.
2779
+ * @param agentName - Name of the agent
2780
+ * @returns Path to ~/.deepagents/{agentName}/skills/
2781
+ */
2782
+ getUserSkillsDir(agentName: string): string;
2783
+ /**
2784
+ * Ensure user-level skills directory exists and return path.
2785
+ * @param agentName - Name of the agent
2786
+ * @returns Path to ~/.deepagents/{agentName}/skills/
2787
+ */
2788
+ ensureUserSkillsDir(agentName: string): string;
2789
+ /**
2790
+ * Get project-level skills directory path.
2791
+ * @returns Path to {projectRoot}/.deepagents/skills/, or null if not in a project
2792
+ */
2793
+ getProjectSkillsDir(): string | null;
2794
+ /**
2795
+ * Ensure project-level skills directory exists and return path.
2796
+ * @returns Path to {projectRoot}/.deepagents/skills/, or null if not in a project
2797
+ */
2798
+ ensureProjectSkillsDir(): string | null;
2799
+ /**
2800
+ * Ensure project .deepagents directory exists.
2801
+ * @returns Path to {projectRoot}/.deepagents/, or null if not in a project
2802
+ */
2803
+ ensureProjectDeepagentsDir(): string | null;
2804
+ }
2805
+ /**
2806
+ * Find the project root by looking for .git directory.
2807
+ *
2808
+ * Walks up the directory tree from startPath (or cwd) looking for a .git
2809
+ * directory, which indicates the project root.
2810
+ *
2811
+ * @param startPath - Directory to start searching from. Defaults to current working directory.
2812
+ * @returns Path to the project root if found, null otherwise.
2813
+ */
2814
+ declare function findProjectRoot(startPath?: string): string | null;
2815
+ /**
2816
+ * Create a Settings instance with detected environment.
2817
+ *
2818
+ * @param options - Configuration options
2819
+ * @returns Settings instance with project detection and path management
2820
+ */
2821
+ declare function createSettings(options?: SettingsOptions): Settings;
2822
+ //#endregion
2823
+ //#region src/values.d.ts
2824
+ /**
2825
+ * Shared ReducedValue for file data state management.
2826
+ *
2827
+ * This provides a reusable pattern for managing file state with automatic
2828
+ * merging of concurrent updates from parallel subagents. Files can be updated
2829
+ * or deleted (using null values) and the reducer handles the merge logic.
2830
+ *
2831
+ * Similar to LangGraph's messagesValue, this encapsulates the common pattern
2832
+ * of managing files in agent state so you don't have to manually configure
2833
+ * the ReducedValue each time.
2834
+ *
2835
+ * @example
2836
+ * ```typescript
2837
+ * import { filesValue } from "@anthropic/deepagents";
2838
+ * import { StateSchema } from "@langchain/langgraph";
2839
+ *
2840
+ * const MyStateSchema = new StateSchema({
2841
+ * files: filesValue,
2842
+ * // ... other state fields
2843
+ * });
2844
+ * ```
2845
+ */
2846
+ declare const filesValue: ReducedValue<FilesRecord | undefined, FilesRecordUpdate | undefined>;
2847
+ //#endregion
2848
+ //#region src/middleware/agent-memory.d.ts
2849
+ /**
2850
+ * Options for the agent memory middleware.
2851
+ */
2852
+ interface AgentMemoryMiddlewareOptions {
2853
+ /** Settings instance with project detection and paths */
2854
+ settings: Settings;
2855
+ /** The agent identifier */
2856
+ assistantId: string;
2857
+ /** Optional custom template for injecting agent memory into system prompt */
2858
+ systemPromptTemplate?: string;
2859
+ }
2860
+ /**
2861
+ * Create middleware for loading agent-specific long-term memory.
2862
+ *
2863
+ * This middleware loads the agent's long-term memory from a file (agent.md)
2864
+ * and injects it into the system prompt. The memory is loaded once at the
2865
+ * start of the conversation and stored in state.
2866
+ *
2867
+ * @param options - Configuration options
2868
+ * @returns AgentMiddleware for memory loading and injection
2869
+ *
2870
+ * @deprecated Use `createMemoryMiddleware` from `./memory.js` instead.
2871
+ * This function uses direct filesystem access which limits portability.
2872
+ */
2873
+ declare function createAgentMemoryMiddleware(options: AgentMemoryMiddlewareOptions): AgentMiddleware<any, undefined, unknown, readonly (import("@langchain/core/tools").ClientTool | import("@langchain/core/tools").ServerTool)[], readonly []>;
2874
+ //#endregion
2875
+ //#region src/skills/loader.d.ts
2876
+ /**
2877
+ * Metadata for a skill per Agent Skills spec.
2878
+ * @see https://agentskills.io/specification
2879
+ */
2880
+ interface SkillMetadata {
2881
+ /** Name of the skill (max 64 chars, lowercase alphanumeric and hyphens) */
2882
+ name: string;
2883
+ /** Description of what the skill does (max 1024 chars) */
2884
+ description: string;
2885
+ /** Absolute path to the SKILL.md file */
2886
+ path: string;
2887
+ /** Source of the skill ('user' or 'project') */
2888
+ source: "user" | "project";
2889
+ /** Optional: License name or reference to bundled license file */
2890
+ license?: string;
2891
+ /** Optional: Environment requirements (max 500 chars) */
2892
+ compatibility?: string;
2893
+ /** Optional: Arbitrary key-value mapping for additional metadata */
2894
+ metadata?: Record<string, string>;
2895
+ /** Optional: Space-delimited list of pre-approved tools */
2896
+ allowedTools?: string;
2897
+ }
2898
+ /**
2899
+ * Options for listing skills.
2900
+ */
2901
+ interface ListSkillsOptions {
2902
+ /** Path to user-level skills directory */
2903
+ userSkillsDir?: string | null;
2904
+ /** Path to project-level skills directory */
2905
+ projectSkillsDir?: string | null;
2906
+ }
2907
+ /**
2908
+ * Parse YAML frontmatter from a SKILL.md file per Agent Skills spec.
2909
+ *
2910
+ * @param skillMdPath - Path to the SKILL.md file
2911
+ * @param source - Source of the skill ('user' or 'project')
2912
+ * @returns SkillMetadata with all fields, or null if parsing fails
2913
+ */
2914
+ declare function parseSkillMetadata(skillMdPath: string, source: "user" | "project"): SkillMetadata | null;
2915
+ /**
2916
+ * List skills from user and/or project directories.
2917
+ *
2918
+ * When both directories are provided, project skills with the same name as
2919
+ * user skills will override them.
2920
+ *
2921
+ * @param options - Options specifying which directories to search
2922
+ * @returns Merged list of skill metadata from both sources, with project skills
2923
+ * taking precedence over user skills when names conflict
2924
+ */
2925
+ declare function listSkills(options: ListSkillsOptions): SkillMetadata[];
2926
+ //#endregion
2927
+ //#region src/backends/store.d.ts
2928
+ /**
2929
+ * Context provided to dynamic namespace factory functions.
2930
+ */
2931
+ interface StoreBackendContext<StateT = unknown> {
2932
+ /**
2933
+ * Current graph state, when available.
2934
+ *
2935
+ * In legacy factory mode this is the injected runtime state. In zero-arg mode
2936
+ * this is read from the current LangGraph execution context.
2937
+ */
2938
+ state: StateT;
2939
+ /**
2940
+ * Runnable config, when available.
2941
+ *
2942
+ * This mirrors the Python implementation's access to config metadata for
2943
+ * namespace resolution.
2944
+ */
2945
+ config?: {
2946
+ metadata?: Record<string, unknown>;
2947
+ configurable?: Record<string, unknown>;
2948
+ };
2949
+ /**
2950
+ * Legacy assistant identifier, resolved from config metadata first and then
2951
+ * from the injected runtime for backwards compatibility.
2952
+ */
2953
+ assistantId?: string;
2954
+ }
2955
+ type StoreBackendNamespaceFactory<StateT = unknown> = (context: StoreBackendContext<StateT>) => string[];
2956
+ /**
2957
+ * Options for StoreBackend constructor.
2958
+ */
2959
+ interface StoreBackendOptions<StateT = unknown> extends BackendOptions {
2960
+ /**
2961
+ * Explicit store instance to use for persistence.
2962
+ *
2963
+ * This mirrors the Python API and allows constructing a backend directly with
2964
+ * a store instance, e.g. `new StoreBackend({ store })`.
2965
+ *
2966
+ * When omitted, the backend uses the legacy injected runtime store or the
2967
+ * LangGraph execution-context store.
2968
+ */
2969
+ store?: BaseStore;
2970
+ /**
2971
+ * Custom namespace for store operations.
2972
+ *
2973
+ * Accepts either a static namespace array or a factory that derives the
2974
+ * namespace from the current backend context.
2975
+ *
2976
+ * If not provided, falls back to legacy assistant-id detection from config
2977
+ * metadata, then the injected runtime's `assistantId`, and finally
2978
+ * `["filesystem"]`.
2979
+ *
2980
+ * @example
2981
+ * ```typescript
2982
+ * // Static namespace
2983
+ * new StoreBackend({
2984
+ * namespace: ["memories", orgId, userId, "filesystem"],
2985
+ * });
2986
+ *
2987
+ * // Dynamic namespace
2988
+ * new StoreBackend({
2989
+ * namespace: ({ state }) => [
2990
+ * "memories",
2991
+ * (state as { userId: string }).userId,
2992
+ * "filesystem",
2993
+ * ],
2994
+ * });
2995
+ * ```
2996
+ */
2997
+ namespace?: string[] | StoreBackendNamespaceFactory<StateT>;
2998
+ }
2999
+ /**
3000
+ * Backend that stores files in LangGraph's BaseStore (persistent).
3001
+ *
3002
+ * Uses LangGraph's Store for persistent, cross-conversation storage.
3003
+ * Files are organized via namespaces and persist across all threads.
3004
+ *
3005
+ * The namespace can be customized via a factory function for flexible
3006
+ * isolation patterns (user-scoped, org-scoped, etc.), or falls back
3007
+ * to legacy assistant_id-based isolation.
3008
+ */
3009
+ declare class StoreBackend implements BackendProtocolV2 {
3010
+ private stateAndStore;
3011
+ private storeOverride;
3012
+ private _namespace;
3013
+ private fileFormat;
3014
+ constructor(options?: StoreBackendOptions);
3015
+ /**
3016
+ * @deprecated Pass no `stateAndStore` argument
3017
+ */
3018
+ constructor(stateAndStore: StateAndStore, options?: StoreBackendOptions);
3019
+ /**
3020
+ * Get the BaseStore instance for persistent storage operations.
3021
+ *
3022
+ * In legacy mode, reads from the injected {@link StateAndStore}.
3023
+ * In zero-arg mode, retrieves the store from the LangGraph execution
3024
+ * context via {@link getLangGraphStore}.
3025
+ *
3026
+ * @returns BaseStore instance
3027
+ * @throws Error if no store is available in either mode
3028
+ */
3029
+ private getStore;
3030
+ /**
3031
+ * Get the current graph state when available.
3032
+ */
3033
+ private getState;
3034
+ /**
3035
+ * Get the most relevant runnable config for namespace resolution.
3036
+ */
3037
+ private getNamespaceConfig;
3038
+ /**
3039
+ * Legacy assistant-id detection compatible with both Python and the
3040
+ * historical TypeScript `assistantId` runtime property.
3041
+ */
3042
+ private getLegacyAssistantId;
3043
+ /**
3044
+ * Get the namespace for store operations.
3045
+ *
3046
+ * Resolution order:
3047
+ * 1. Explicit namespace from constructor options
3048
+ * 2. Namespace factory resolved from the current backend context
3049
+ * 3. Assistant ID from runtime config / LangGraph config metadata
3050
+ * 4. Legacy `assistantId` from the injected runtime
3051
+ * 5. `["filesystem"]`
3052
+ */
3053
+ protected getNamespace(): string[];
3054
+ /**
3055
+ * Convert a store Item to FileData format.
3056
+ *
3057
+ * @param storeItem - The store Item containing file data
3058
+ * @returns FileData object
3059
+ * @throws Error if required fields are missing or have incorrect types
3060
+ */
3061
+ private convertStoreItemToFileData;
3062
+ /**
3063
+ * Convert FileData to a value suitable for store.put().
3064
+ *
3065
+ * @param fileData - The FileData to convert
3066
+ * @returns Object with content, mimeType, created_at, and modified_at fields
3067
+ */
3068
+ private convertFileDataToStoreValue;
3069
+ /**
3070
+ * Search store with automatic pagination to retrieve all results.
3071
+ *
3072
+ * @param store - The store to search
3073
+ * @param namespace - Hierarchical path prefix to search within
3074
+ * @param options - Optional query, filter, and page_size
3075
+ * @returns List of all items matching the search criteria
3076
+ */
3077
+ private searchStorePaginated;
3078
+ /**
3079
+ * List files and directories in the specified directory (non-recursive).
3080
+ *
3081
+ * @param path - Absolute path to directory
3082
+ * @returns LsResult with list of FileInfo objects on success or error on failure.
3083
+ * Directories have a trailing / in their path and is_dir=true.
3084
+ */
3085
+ ls(path: string): Promise<LsResult>;
3086
+ /**
3087
+ * Read file content.
3088
+ *
3089
+ * Text files are paginated by line offset/limit.
3090
+ * Binary files return full Uint8Array content (offset/limit ignored).
3091
+ *
3092
+ * @param filePath - Absolute file path
3093
+ * @param offset - Line offset to start reading from (0-indexed)
3094
+ * @param limit - Maximum number of lines to read
3095
+ * @returns ReadResult with content on success or error on failure
3096
+ */
3097
+ read(filePath: string, offset?: number, limit?: number): Promise<ReadResult>;
3098
+ /**
3099
+ * Read file content as raw FileData.
3100
+ *
3101
+ * @param filePath - Absolute file path
3102
+ * @returns ReadRawResult with raw file data on success or error on failure
3103
+ */
3104
+ readRaw(filePath: string): Promise<ReadRawResult>;
3105
+ /**
3106
+ * Create a new file with content.
3107
+ * Returns WriteResult. External storage sets filesUpdate=null.
3108
+ */
3109
+ write(filePath: string, content: string): Promise<WriteResult>;
3110
+ /**
3111
+ * Edit a file by replacing string occurrences.
3112
+ * Returns EditResult. External storage sets filesUpdate=null.
3113
+ */
3114
+ edit(filePath: string, oldString: string, newString: string, replaceAll?: boolean): Promise<EditResult>;
3115
+ /**
3116
+ * Search file contents for a literal text pattern.
3117
+ * Binary files are skipped.
3118
+ */
3119
+ grep(pattern: string, path?: string, glob?: string | null): Promise<GrepResult>;
3120
+ /**
3121
+ * Structured glob matching returning FileInfo objects.
3122
+ */
3123
+ glob(pattern: string, path?: string): Promise<GlobResult>;
3124
+ /**
3125
+ * Upload multiple files.
3126
+ *
3127
+ * @param files - List of [path, content] tuples to upload
3128
+ * @returns List of FileUploadResponse objects, one per input file
3129
+ */
3130
+ uploadFiles(files: Array<[string, Uint8Array]>): Promise<FileUploadResponse[]>;
3131
+ /**
3132
+ * Download multiple files.
3133
+ *
3134
+ * @param paths - List of file paths to download
3135
+ * @returns List of FileDownloadResponse objects, one per input path
3136
+ */
3137
+ downloadFiles(paths: string[]): Promise<FileDownloadResponse[]>;
3138
+ }
3139
+ //#endregion
3140
+ //#region src/backends/filesystem.d.ts
3141
+ /**
3142
+ * Backend that reads and writes files directly from the filesystem.
3143
+ *
3144
+ * Files are accessed using their actual filesystem paths. Relative paths are
3145
+ * resolved relative to the current working directory. Content is read/written
3146
+ * as plain text, and metadata (timestamps) are derived from filesystem stats.
3147
+ */
3148
+ declare class FilesystemBackend implements BackendProtocolV2 {
3149
+ protected cwd: string;
3150
+ protected virtualMode: boolean;
3151
+ private maxFileSizeBytes;
3152
+ constructor(options?: {
3153
+ rootDir?: string;
3154
+ virtualMode?: boolean;
3155
+ maxFileSizeMb?: number;
3156
+ });
3157
+ /**
3158
+ * Resolve a file path with security checks.
3159
+ *
3160
+ * When virtualMode=true, treat incoming paths as virtual absolute paths under
3161
+ * this.cwd, disallow traversal (.., ~) and ensure resolved path stays within root.
3162
+ * When virtualMode=false, preserve legacy behavior: absolute paths are allowed
3163
+ * as-is; relative paths resolve under cwd.
3164
+ *
3165
+ * @param key - File path (absolute, relative, or virtual when virtualMode=true)
3166
+ * @returns Resolved absolute path string
3167
+ * @throws Error if path traversal detected or path outside root
3168
+ */
3169
+ private resolvePath;
3170
+ /**
3171
+ * List files and directories in the specified directory (non-recursive).
3172
+ *
3173
+ * @param dirPath - Absolute directory path to list files from
3174
+ * @returns List of FileInfo objects for files and directories directly in the directory.
3175
+ * Directories have a trailing / in their path and is_dir=true.
3176
+ */
3177
+ ls(dirPath: string): Promise<LsResult>;
3178
+ /**
3179
+ * Read file content with line numbers.
3180
+ *
3181
+ * @param filePath - Absolute or relative file path
3182
+ * @param offset - Line offset to start reading from (0-indexed)
3183
+ * @param limit - Maximum number of lines to read
3184
+ * @returns Formatted file content with line numbers, or error message
3185
+ */
3186
+ read(filePath: string, offset?: number, limit?: number): Promise<ReadResult>;
3187
+ /**
3188
+ * Read file content as raw FileData.
3189
+ *
3190
+ * @param filePath - Absolute file path
3191
+ * @returns ReadRawResult with raw file data on success or error on failure
3192
+ */
3193
+ readRaw(filePath: string): Promise<ReadRawResult>;
3194
+ /**
3195
+ * Create a new file with content.
3196
+ * Returns WriteResult. External storage sets filesUpdate=null.
3197
+ */
3198
+ write(filePath: string, content: string): Promise<WriteResult>;
3199
+ /**
3200
+ * Edit a file by replacing string occurrences.
3201
+ * Returns EditResult. External storage sets filesUpdate=null.
3202
+ */
3203
+ edit(filePath: string, oldString: string, newString: string, replaceAll?: boolean): Promise<EditResult>;
3204
+ /**
3205
+ * Search for a literal text pattern in files.
3206
+ *
3207
+ * Uses ripgrep if available, falling back to substring search.
3208
+ *
3209
+ * @param pattern - Literal string to search for (NOT regex).
3210
+ * @param dirPath - Directory or file path to search in. Defaults to current directory.
3211
+ * @param glob - Optional glob pattern to filter which files to search.
3212
+ * @returns List of GrepMatch dicts containing path, line number, and matched text.
3213
+ */
3214
+ grep(pattern: string, dirPath?: string, glob?: string | null): Promise<GrepResult>;
3215
+ /**
3216
+ * Search using ripgrep with fixed-string (literal) mode.
3217
+ *
3218
+ * @param pattern - Literal string to search for (unescaped).
3219
+ * @param baseFull - Resolved base path to search in.
3220
+ * @param includeGlob - Optional glob pattern to filter files.
3221
+ * @returns Dict mapping file paths to list of (line_number, line_text) tuples.
3222
+ * Returns null if ripgrep is unavailable or times out.
3223
+ */
3224
+ private ripgrepSearch;
3225
+ /**
3226
+ * Fallback search using literal substring matching when ripgrep is unavailable.
3227
+ *
3228
+ * Recursively searches files, respecting maxFileSizeBytes limit.
3229
+ *
3230
+ * @param pattern - Literal string to search for.
3231
+ * @param baseFull - Resolved base path to search in.
3232
+ * @param includeGlob - Optional glob pattern to filter files by name.
3233
+ * @returns Dict mapping file paths to list of (line_number, line_text) tuples.
3234
+ */
3235
+ private literalSearch;
3236
+ /**
3237
+ * Structured glob matching returning FileInfo objects.
3238
+ */
3239
+ glob(pattern: string, searchPath?: string): Promise<GlobResult>;
3240
+ /**
3241
+ * Upload multiple files to the filesystem.
3242
+ *
3243
+ * @param files - List of [path, content] tuples to upload
3244
+ * @returns List of FileUploadResponse objects, one per input file
3245
+ */
3246
+ uploadFiles(files: Array<[string, Uint8Array]>): Promise<FileUploadResponse[]>;
3247
+ /**
3248
+ * Download multiple files from the filesystem.
3249
+ *
3250
+ * @param paths - List of file paths to download
3251
+ * @returns List of FileDownloadResponse objects, one per input path
3252
+ */
3253
+ downloadFiles(paths: string[]): Promise<FileDownloadResponse[]>;
3254
+ }
3255
+ //#endregion
3256
+ //#region src/backends/composite.d.ts
3257
+ /**
3258
+ * Backend that routes file operations to different backends based on path prefix.
3259
+ *
3260
+ * This enables hybrid storage strategies like:
3261
+ * - `/memories/` → StoreBackend (persistent, cross-thread)
3262
+ * - Everything else → StateBackend (ephemeral, per-thread)
3263
+ *
3264
+ * The CompositeBackend handles path prefix stripping/re-adding transparently.
3265
+ */
3266
+ declare class CompositeBackend implements BackendProtocolV2 {
3267
+ private default;
3268
+ private routes;
3269
+ private sortedRoutes;
3270
+ constructor(defaultBackend: AnyBackendProtocol, routes: Record<string, AnyBackendProtocol>);
3271
+ /** Delegates to default backend's id if it is a sandbox, otherwise empty string. */
3272
+ get id(): string;
3273
+ /** Route prefixes registered on this backend (e.g. `["/workspace"]`). */
3274
+ get routePrefixes(): string[];
3275
+ /**
3276
+ * Type guard — returns true if `backend` is a {@link CompositeBackend}.
3277
+ *
3278
+ * Uses duck-typing on `routePrefixes` so it works across module boundaries
3279
+ * where `instanceof` may fail.
3280
+ */
3281
+ static isInstance(backend: unknown): backend is CompositeBackend;
3282
+ /**
3283
+ * Determine which backend handles this key and strip prefix.
3284
+ *
3285
+ * @param key - Original file path
3286
+ * @returns Tuple of [backend, stripped_key] where stripped_key has the route
3287
+ * prefix removed (but keeps leading slash).
3288
+ */
3289
+ private getBackendAndKey;
3290
+ /**
3291
+ * Returns true when `path` points at `routePrefix` or its descendants.
3292
+ */
3293
+ private isPathWithinRoute;
3294
+ /**
3295
+ * Returns true when `routePrefix` is inside `path` (or equal to it).
3296
+ *
3297
+ * Examples:
3298
+ * - path `/` includes all routes
3299
+ * - path `/workspace` includes route `/workspace/memories/`
3300
+ * - path `/workspace` excludes route `/skills/`
3301
+ */
3302
+ private isRouteUnderPath;
3303
+ /**
3304
+ * List files and directories in the specified directory (non-recursive).
3305
+ *
3306
+ * @param path - Absolute path to directory
3307
+ * @returns LsResult with list of FileInfo objects (with route prefixes added) on success or error on failure.
3308
+ * Directories have a trailing / in their path and is_dir=true.
3309
+ */
3310
+ ls(path: string): Promise<LsResult>;
3311
+ /**
3312
+ * Read file content, routing to appropriate backend.
3313
+ *
3314
+ * @param filePath - Absolute file path
3315
+ * @param offset - Line offset to start reading from (0-indexed)
3316
+ * @param limit - Maximum number of lines to read
3317
+ * @returns Formatted file content with line numbers, or error message
3318
+ */
3319
+ read(filePath: string, offset?: number, limit?: number): Promise<ReadResult>;
3320
+ /**
3321
+ * Read file content as raw FileData.
3322
+ *
3323
+ * @param filePath - Absolute file path
3324
+ * @returns ReadRawResult with raw file data on success or error on failure
3325
+ */
3326
+ readRaw(filePath: string): Promise<ReadRawResult>;
3327
+ /**
3328
+ * Structured search results or error string for invalid input.
3329
+ */
3330
+ grep(pattern: string, path?: string | null, glob?: string | null): Promise<GrepResult>;
3331
+ /**
3332
+ * Structured glob matching returning FileInfo objects.
3333
+ */
3334
+ glob(pattern: string, path?: string): Promise<GlobResult>;
3335
+ /**
3336
+ * Create a new file, routing to appropriate backend.
3337
+ *
3338
+ * @param filePath - Absolute file path
3339
+ * @param content - File content as string
3340
+ * @returns WriteResult with path or error
3341
+ */
3342
+ write(filePath: string, content: string): Promise<WriteResult>;
3343
+ /**
3344
+ * Edit a file, routing to appropriate backend.
3345
+ *
3346
+ * @param filePath - Absolute file path
3347
+ * @param oldString - String to find and replace
3348
+ * @param newString - Replacement string
3349
+ * @param replaceAll - If true, replace all occurrences
3350
+ * @returns EditResult with path, occurrences, or error
3351
+ */
3352
+ edit(filePath: string, oldString: string, newString: string, replaceAll?: boolean): Promise<EditResult>;
3353
+ /**
3354
+ * Execute a command via the default backend.
3355
+ * Execution is not path-specific, so it always delegates to the default backend.
3356
+ *
3357
+ * @param command - Full shell command string to execute
3358
+ * @returns ExecuteResponse with combined output, exit code, and truncation flag
3359
+ * @throws Error if the default backend doesn't support command execution
3360
+ */
3361
+ execute(command: string): Promise<ExecuteResponse>;
3362
+ /**
3363
+ * Upload multiple files, batching by backend for efficiency.
3364
+ *
3365
+ * @param files - List of [path, content] tuples to upload
3366
+ * @returns List of FileUploadResponse objects, one per input file
3367
+ */
3368
+ uploadFiles(files: Array<[string, Uint8Array]>): Promise<FileUploadResponse[]>;
3369
+ /**
3370
+ * Download multiple files, batching by backend for efficiency.
3371
+ *
3372
+ * @param paths - List of file paths to download
3373
+ * @returns List of FileDownloadResponse objects, one per input path
3374
+ */
3375
+ downloadFiles(paths: string[]): Promise<FileDownloadResponse[]>;
3376
+ }
3377
+ //#endregion
3378
+ //#region src/backends/context-hub.d.ts
3379
+ /**
3380
+ * Backend that stores files in a LangSmith Hub agent repo (persistent).
3381
+ */
3382
+ declare class ContextHubBackend implements BackendProtocolV2 {
3383
+ private identifier;
3384
+ private client;
3385
+ private cache;
3386
+ private linkedEntries;
3387
+ private commitHash;
3388
+ constructor(identifier: string, options?: {
3389
+ client?: Client;
3390
+ });
3391
+ private static stripPrefix;
3392
+ private static toHubUnavailableError;
3393
+ private loadTree;
3394
+ private ensureCache;
3395
+ private commit;
3396
+ /**
3397
+ * Return linked-entry paths mapped to their repo handles.
3398
+ */
3399
+ getLinkedEntries(): Promise<Record<string, string>>;
3400
+ /**
3401
+ * Return true if the hub repo already exists with at least one commit.
3402
+ */
3403
+ hasPriorCommits(): Promise<boolean>;
3404
+ ls(path?: string): Promise<LsResult>;
3405
+ read(filePath: string, offset?: number, limit?: number): Promise<ReadResult>;
3406
+ readRaw(filePath: string): Promise<ReadRawResult>;
3407
+ grep(pattern: string, path?: string | null, glob?: string | null): Promise<GrepResult>;
3408
+ glob(pattern: string, _path?: string): Promise<GlobResult>;
3409
+ write(filePath: string, content: string): Promise<WriteResult>;
3410
+ edit(filePath: string, oldString: string, newString: string, replaceAll?: boolean): Promise<EditResult>;
3411
+ uploadFiles(files: Array<[string, Uint8Array]>): Promise<FileUploadResponse[]>;
3412
+ downloadFiles(paths: string[]): Promise<FileDownloadResponse[]>;
3413
+ }
3414
+ //#endregion
3415
+ //#region src/backends/local-shell.d.ts
3416
+ /**
3417
+ * Options for creating a LocalShellBackend instance.
3418
+ */
3419
+ interface LocalShellBackendOptions {
3420
+ /**
3421
+ * Working directory for both filesystem operations and shell commands.
3422
+ * When set with `virtualMode: false` (default), absolute paths and `..` can
3423
+ * bypass rootDir for filesystem operations.
3424
+ * @defaultValue `process.cwd()`
3425
+ */
3426
+ rootDir?: string;
3427
+ /**
3428
+ * Enable virtual path mode for filesystem operations.
3429
+ * When true, treats rootDir as a virtual root filesystem.
3430
+ * When false (default), preserves legacy path behavior.
3431
+ * Does NOT restrict shell commands.
3432
+ * @defaultValue `false`
3433
+ */
3434
+ virtualMode?: boolean;
3435
+ /**
3436
+ * Maximum time in seconds to wait for shell command execution.
3437
+ * Commands exceeding this timeout will be terminated.
3438
+ * @defaultValue `120`
3439
+ */
3440
+ timeout?: number;
3441
+ /**
3442
+ * Maximum number of bytes to capture from command output.
3443
+ * Output exceeding this limit will be truncated.
3444
+ * @defaultValue `100_000`
3445
+ */
3446
+ maxOutputBytes?: number;
3447
+ /**
3448
+ * Environment variables for shell commands. If undefined, starts with an empty
3449
+ * environment (unless inheritEnv is true).
3450
+ * @defaultValue `undefined`
3451
+ */
3452
+ env?: Record<string, string>;
3453
+ /**
3454
+ * Whether to inherit the parent process's environment variables.
3455
+ * When false, only variables in env dict are available.
3456
+ * When true, inherits all process.env variables and applies env overrides.
3457
+ * @defaultValue `false`
3458
+ */
3459
+ inheritEnv?: boolean;
3460
+ /**
3461
+ * Files to create on disk during `create()`.
3462
+ * Keys are file paths (resolved via the backend's path handling),
3463
+ * values are string content.
3464
+ * @defaultValue `undefined`
3465
+ */
3466
+ initialFiles?: Record<string, string>;
3467
+ }
3468
+ /**
3469
+ * Filesystem backend with unrestricted local shell command execution.
3470
+ *
3471
+ * This backend extends FilesystemBackend to add shell command execution
3472
+ * capabilities. Commands are executed directly on the host system without any
3473
+ * sandboxing, process isolation, or security restrictions.
3474
+ *
3475
+ * **Security Warning:**
3476
+ * This backend grants agents BOTH direct filesystem access AND unrestricted
3477
+ * shell execution on your local machine. Use with extreme caution and only in
3478
+ * appropriate environments.
3479
+ *
3480
+ * **Appropriate use cases:**
3481
+ * - Local development CLIs (coding assistants, development tools)
3482
+ * - Personal development environments where you trust the agent's code
3483
+ * - CI/CD pipelines with proper secret management
3484
+ *
3485
+ * **Inappropriate use cases:**
3486
+ * - Production environments (e.g., web servers, APIs, multi-tenant systems)
3487
+ * - Processing untrusted user input or executing untrusted code
3488
+ *
3489
+ * Use StateBackend, StoreBackend, or extend BaseSandbox for production.
3490
+ *
3491
+ * @example
3492
+ * ```typescript
3493
+ * import { LocalShellBackend } from "@langchain/deepagents";
3494
+ *
3495
+ * // Create backend with explicit environment
3496
+ * const backend = new LocalShellBackend({
3497
+ * rootDir: "/home/user/project",
3498
+ * virtualMode: true,
3499
+ * env: { PATH: "/usr/bin:/bin" },
3500
+ * });
3501
+ *
3502
+ * // Execute shell commands (runs directly on host)
3503
+ * const result = await backend.execute("ls -la");
3504
+ * console.log(result.output);
3505
+ * console.log(result.exitCode);
3506
+ *
3507
+ * // Use filesystem operations (inherited from FilesystemBackend)
3508
+ * const content = await backend.read("/README.md");
3509
+ * await backend.write("/output.txt", "Hello world");
3510
+ *
3511
+ * // Inherit all environment variables
3512
+ * const backend2 = new LocalShellBackend({
3513
+ * rootDir: "/home/user/project",
3514
+ * virtualMode: true,
3515
+ * inheritEnv: true,
3516
+ * });
3517
+ * ```
3518
+ */
3519
+ declare class LocalShellBackend extends FilesystemBackend implements SandboxBackendProtocolV2 {
3520
+ #private;
3521
+ constructor(options?: LocalShellBackendOptions);
3522
+ /** Unique identifier for this backend instance (format: "local-{random_hex}"). */
3523
+ get id(): string;
3524
+ /** Whether the backend has been initialized and is ready to use. */
3525
+ get isInitialized(): boolean;
3526
+ /** Alias for `isInitialized`, matching the standard sandbox interface. */
3527
+ get isRunning(): boolean;
3528
+ /**
3529
+ * Initialize the backend by ensuring the rootDir exists.
3530
+ *
3531
+ * Creates the rootDir (and any parent directories) if it does not already
3532
+ * exist. Safe to call on an existing directory. Must be called before
3533
+ * `execute()`, or use the static `LocalShellBackend.create()` factory.
3534
+ *
3535
+ * @throws {SandboxError} If already initialized (`ALREADY_INITIALIZED`)
3536
+ */
3537
+ initialize(): Promise<void>;
3538
+ /**
3539
+ * Mark the backend as no longer running.
3540
+ *
3541
+ * For local shell backends there is no remote resource to tear down,
3542
+ * so this simply flips the `isRunning` / `isInitialized` flag.
3543
+ */
3544
+ close(): Promise<void>;
3545
+ /**
3546
+ * Read a file, adapting error messages to the standard sandbox format.
3547
+ */
3548
+ read(filePath: string, offset?: number, limit?: number): Promise<ReadResult>;
3549
+ /**
3550
+ * Edit a file, adapting error messages to the standard sandbox format.
3551
+ */
3552
+ edit(filePath: string, oldString: string, newString: string, replaceAll?: boolean): Promise<EditResult>;
3553
+ /**
3554
+ * List directory contents, returning paths relative to rootDir.
3555
+ */
3556
+ ls(dirPath: string): Promise<LsResult>;
3557
+ /**
3558
+ * Glob matching that returns relative paths and includes directories.
3559
+ */
3560
+ glob(pattern: string, searchPath?: string): Promise<GlobResult>;
3561
+ /**
3562
+ * Execute a shell command directly on the host system.
3563
+ *
3564
+ * Commands are executed directly on your host system using `spawn()`
3565
+ * with `shell: true`. There is NO sandboxing, isolation, or security
3566
+ * restrictions. The command runs with your user's full permissions.
3567
+ *
3568
+ * The command is executed using the system shell with the working directory
3569
+ * set to the backend's rootDir. Stdout and stderr are combined into a single
3570
+ * output stream, with stderr lines prefixed with `[stderr]`.
3571
+ *
3572
+ * @param command - Shell command string to execute
3573
+ * @returns ExecuteResponse containing output, exit code, and truncation flag
3574
+ */
3575
+ execute(command: string): Promise<ExecuteResponse>;
3576
+ /**
3577
+ * Create and initialize a new LocalShellBackend in one step.
3578
+ *
3579
+ * This is the recommended way to create a backend when the rootDir may
3580
+ * not exist yet. It combines construction and initialization (ensuring
3581
+ * rootDir exists) into a single async operation.
3582
+ *
3583
+ * @param options - Configuration options for the backend
3584
+ * @returns An initialized and ready-to-use backend
3585
+ */
3586
+ static create(options?: LocalShellBackendOptions): Promise<LocalShellBackend>;
3587
+ }
3588
+ //#endregion
3589
+ //#region src/backends/sandbox.d.ts
3590
+ /**
3591
+ * Base sandbox implementation with execute() as the only abstract method.
3592
+ *
3593
+ * This class provides default implementations for all SandboxBackendProtocol
3594
+ * methods using shell commands executed via execute(). Concrete implementations
3595
+ * only need to implement execute(), uploadFiles(), and downloadFiles().
3596
+ *
3597
+ * All shell commands use pure POSIX utilities (awk, grep, find, stat) that are
3598
+ * available on any Linux including Alpine/busybox. No Python, Node.js, or
3599
+ * other runtime is required on the sandbox host.
3600
+ */
3601
+ declare abstract class BaseSandbox implements SandboxBackendProtocolV2 {
3602
+ /** Unique identifier for the sandbox backend */
3603
+ abstract readonly id: string;
3604
+ /**
3605
+ * Execute a command in the sandbox.
3606
+ * This is the only method concrete implementations must provide.
3607
+ */
3608
+ abstract execute(command: string): MaybePromise<ExecuteResponse>;
3609
+ /**
3610
+ * Upload multiple files to the sandbox.
3611
+ * Implementations must support partial success.
3612
+ */
3613
+ abstract uploadFiles(files: Array<[string, Uint8Array]>): MaybePromise<FileUploadResponse[]>;
3614
+ /**
3615
+ * Download multiple files from the sandbox.
3616
+ * Implementations must support partial success.
3617
+ */
3618
+ abstract downloadFiles(paths: string[]): MaybePromise<FileDownloadResponse[]>;
3619
+ /**
3620
+ * List files and directories in the specified directory (non-recursive).
3621
+ *
3622
+ * Uses pure POSIX shell (find + stat) via execute() — works on any Linux
3623
+ * including Alpine. No Python or Node.js needed.
3624
+ *
3625
+ * @param path - Absolute path to directory
3626
+ * @returns LsResult with list of FileInfo objects on success or error on failure.
3627
+ */
3628
+ ls(path: string): Promise<LsResult>;
3629
+ /**
3630
+ * Read file content with line numbers.
3631
+ *
3632
+ * Uses pure POSIX shell (awk) via execute() — only the requested slice
3633
+ * is returned over the wire, making this efficient for large files.
3634
+ * Works on any Linux including Alpine (no Python or Node.js needed).
3635
+ *
3636
+ * @param filePath - Absolute file path
3637
+ * @param offset - Line offset to start reading from (0-indexed)
3638
+ * @param limit - Maximum number of lines to read
3639
+ * @returns Formatted file content with line numbers, or error message
3640
+ */
3641
+ read(filePath: string, offset?: number, limit?: number): Promise<ReadResult>;
3642
+ /**
3643
+ * Read file content as raw FileData.
3644
+ *
3645
+ * Uses downloadFiles() directly — no runtime needed on the sandbox host.
3646
+ *
3647
+ * @param filePath - Absolute file path
3648
+ * @returns ReadRawResult with raw file data on success or error on failure
3649
+ */
3650
+ readRaw(filePath: string): Promise<ReadRawResult>;
3651
+ /**
3652
+ * Search for a literal text pattern in files using grep.
3653
+ *
3654
+ * @param pattern - Literal string to search for (NOT regex).
3655
+ * @param path - Directory or file path to search in.
3656
+ * @param glob - Optional glob pattern to filter which files to search.
3657
+ * @returns List of GrepMatch dicts containing path, line number, and matched text.
3658
+ */
3659
+ grep(pattern: string, path?: string, glob?: string | null): Promise<GrepResult>;
3660
+ /**
3661
+ * Structured glob matching returning FileInfo objects.
3662
+ *
3663
+ * Uses pure POSIX shell (find + stat) via execute() to list all files,
3664
+ * then applies glob-to-regex matching in TypeScript. No Python or Node.js
3665
+ * needed on the sandbox host.
3666
+ *
3667
+ * Glob patterns are matched against paths relative to the search base:
3668
+ * - `*` matches any characters except `/`
3669
+ * - `**` matches any characters including `/` (recursive)
3670
+ * - `?` matches a single character except `/`
3671
+ * - `[...]` character classes
3672
+ */
3673
+ glob(pattern: string, path?: string): Promise<GlobResult>;
3674
+ /**
3675
+ * Create a new file with content.
3676
+ *
3677
+ * Uses downloadFiles() to check existence and uploadFiles() to write.
3678
+ * No runtime needed on the sandbox host.
3679
+ */
3680
+ write(filePath: string, content: string): Promise<WriteResult>;
3681
+ /**
3682
+ * Edit a file by replacing string occurrences.
3683
+ *
3684
+ * Uses downloadFiles() to read, performs string replacement in TypeScript,
3685
+ * then uploadFiles() to write back. No runtime needed on the sandbox host.
3686
+ *
3687
+ * Memory-conscious: releases intermediate references early so the GC can
3688
+ * reclaim buffers before the next large allocation is made.
3689
+ */
3690
+ edit(filePath: string, oldString: string, newString: string, replaceAll?: boolean): Promise<EditResult>;
3691
+ }
3692
+ //#endregion
3693
+ //#region src/backends/langsmith.d.ts
3694
+ /** Options for constructing a LangSmithSandbox from an existing Sandbox instance. */
3695
+ interface LangSmithSandboxOptions {
3696
+ /** An already-created LangSmith Sandbox instance to wrap. */
3697
+ sandbox: Sandbox;
3698
+ /**
3699
+ * Default command timeout in seconds.
3700
+ * @default 1800 (30 minutes)
3701
+ */
3702
+ defaultTimeout?: number;
3703
+ }
3704
+ /** Options for the `LangSmithSandbox.create()` static factory. */
3705
+ interface LangSmithSandboxCreateOptions extends Omit<CreateSandboxOptions, "name" | "timeout" | "waitForReady" | "snapshotName"> {
3706
+ /**
3707
+ * Snapshot ID to boot from.
3708
+ * Mutually exclusive with `templateName`.
3709
+ */
3710
+ snapshotId?: string;
3711
+ /**
3712
+ * Name of the LangSmith sandbox template to use.
3713
+ * Mutually exclusive with `snapshotId`.
3714
+ * @deprecated Use `snapshotId` instead. Template-based creation will be
3715
+ * removed in a future release.
3716
+ */
3717
+ templateName?: string;
3718
+ /**
3719
+ * LangSmith API key. Defaults to the `LANGSMITH_API_KEY` environment variable.
3720
+ */
3721
+ apiKey?: string;
3722
+ /**
3723
+ * Default command timeout in seconds.
3724
+ * @default 1800 (30 minutes)
3725
+ */
3726
+ defaultTimeout?: number;
3727
+ }
3728
+ /**
3729
+ * LangSmith Sandbox backend for deepagents.
3730
+ *
3731
+ * Extends `BaseSandbox` to provide command execution and file operations
3732
+ * via the LangSmith Sandbox API.
3733
+ *
3734
+ * Use the static `LangSmithSandbox.create()` factory for the simplest setup,
3735
+ * or construct directly with an existing `Sandbox` instance.
3736
+ *
3737
+ * @experimental This feature is experimental, and breaking changes are expected.
3738
+ */
3739
+ declare class LangSmithSandbox extends BaseSandbox {
3740
+ #private;
3741
+ constructor(options: LangSmithSandboxOptions);
3742
+ /** Whether the sandbox is currently active. */
3743
+ get isRunning(): boolean;
3744
+ /** Return the LangSmith sandbox name as the unique identifier. */
3745
+ get id(): string;
3746
+ /**
3747
+ * Execute a shell command in the LangSmith sandbox.
3748
+ *
3749
+ * @param command - Shell command string to execute
3750
+ * @param options.timeout - Override timeout in seconds; 0 disables timeout
3751
+ */
3752
+ execute(command: string, options?: {
3753
+ timeout?: number;
3754
+ }): Promise<ExecuteResponse>;
3755
+ /**
3756
+ * Download files from the sandbox using LangSmith's native file read API.
3757
+ * @param paths - List of file paths to download
3758
+ * @returns List of FileDownloadResponse objects, one per input path
3759
+ */
3760
+ downloadFiles(paths: string[]): Promise<FileDownloadResponse[]>;
3761
+ /**
3762
+ * Upload files to the sandbox using LangSmith's native file write API.
3763
+ * @param files - List of [path, content] tuples to upload
3764
+ * @returns List of FileUploadResponse objects, one per input file
3765
+ */
3766
+ uploadFiles(files: Array<[string, Uint8Array]>): Promise<FileUploadResponse[]>;
3767
+ /**
3768
+ * Delete this sandbox and mark it as no longer running.
3769
+ *
3770
+ * After calling this, `isRunning` will be `false` and the sandbox
3771
+ * cannot be used again.
3772
+ */
3773
+ close(): Promise<void>;
3774
+ /**
3775
+ * Start a stopped sandbox and wait until it is ready.
3776
+ *
3777
+ * After calling this, `isRunning` will be `true` and the sandbox
3778
+ * can be used for command execution and file operations again.
3779
+ *
3780
+ * @param options - Start options (timeout, signal).
3781
+ */
3782
+ start(options?: StartSandboxOptions): Promise<void>;
3783
+ /**
3784
+ * Stop the sandbox without deleting it.
3785
+ *
3786
+ * Sandbox files are preserved and the sandbox can be restarted later
3787
+ * with `start()`. After calling this, `isRunning` will be `false`.
3788
+ */
3789
+ stop(): Promise<void>;
3790
+ /**
3791
+ * Capture a snapshot from this running sandbox.
3792
+ *
3793
+ * Snapshots can be used to create new sandboxes via
3794
+ * `LangSmithSandbox.create({ snapshotId })`.
3795
+ *
3796
+ * @param name - Name for the snapshot.
3797
+ * @param options - Capture options (checkpoint, timeout).
3798
+ * @returns The created Snapshot in "ready" status.
3799
+ */
3800
+ captureSnapshot(name: string, options?: CaptureSnapshotOptions): Promise<Snapshot>;
3801
+ /**
3802
+ * Create and return a new LangSmithSandbox in one step.
3803
+ *
3804
+ * This is the recommended way to create a sandbox — no need to import
3805
+ * anything from `langsmith/experimental/sandbox` directly.
3806
+ *
3807
+ * @example
3808
+ * ```typescript
3809
+ * const sandbox = await LangSmithSandbox.create({
3810
+ * snapshotId: "abc-123",
3811
+ * });
3812
+ *
3813
+ * try {
3814
+ * const agent = createDeepAgent({ model, backend: sandbox });
3815
+ * await agent.invoke({ messages: [...] });
3816
+ * } finally {
3817
+ * await sandbox.close();
3818
+ * }
3819
+ * ```
3820
+ */
3821
+ static create(options: LangSmithSandboxCreateOptions): Promise<LangSmithSandbox>;
3822
+ }
3823
+ //#endregion
3824
+ //#region src/backends/utils.d.ts
3825
+ /**
3826
+ * Adapt a v1 {@link BackendProtocol} to {@link BackendProtocolV2}.
3827
+ *
3828
+ * If the backend already implements v2, it is returned as-is.
3829
+ * For v1 backends, wraps returns in Result types:
3830
+ * - `read()` string returns wrapped in {@link ReadResult}
3831
+ * - `readRaw()` FileData returns wrapped in {@link ReadRawResult}
3832
+ * - `grep()` returns wrapped in {@link GrepResult}
3833
+ * - `ls()` FileInfo[] returns wrapped in {@link LsResult}
3834
+ * - `glob()` FileInfo[] returns wrapped in {@link GlobResult}
3835
+ *
3836
+ * Note: For sandbox instances, use {@link adaptSandboxProtocol} instead.
3837
+ *
3838
+ * @param backend - Backend instance (v1 or v2)
3839
+ * @returns BackendProtocolV2-compatible backend
3840
+ */
3841
+ declare function adaptBackendProtocol(backend: AnyBackendProtocol): BackendProtocolV2;
3842
+ /**
3843
+ * Adapt a sandbox backend from v1 to v2 interface.
3844
+ *
3845
+ * This extends {@link adaptBackendProtocol} to also preserve sandbox-specific
3846
+ * properties from {@link SandboxBackendProtocol}: `execute` and `id`.
3847
+ *
3848
+ * @param sandbox - Sandbox backend (v1 or v2)
3849
+ * @returns SandboxBackendProtocolV2-compatible sandbox
3850
+ */
3851
+ declare function adaptSandboxProtocol(sandbox: AnySandboxProtocol): SandboxBackendProtocolV2;
3852
+ //#endregion
3853
+ //#region src/agent.d.ts
3854
+ /**
3855
+ * Create a Deep Agent.
3856
+ *
3857
+ * This is the main entry point for building a production-style agent with
3858
+ * deepagents. It gives you a strong default runtime (filesystem, tasks,
3859
+ * subagents, summarization) and lets you opt into skills, memory,
3860
+ * human-in-the-loop interrupts, async subagents, and custom middleware.
3861
+ *
3862
+ * The runtime is intentionally opinionated: defaults work out of the box, and
3863
+ * when you customize behavior, the middleware ordering stays deterministic.
3864
+ *
3865
+ * @param params Configuration parameters for the agent
3866
+ * @returns Deep Agent instance with inferred state/response types
3867
+ *
3868
+ * @example
3869
+ * ```typescript
3870
+ * // Custom state from middleware and/or the agent stateSchema param — both are merged
3871
+ * const ResearchMiddleware = createMiddleware({
3872
+ * name: "ResearchMiddleware",
3873
+ * stateSchema: z.object({ research: z.string().default("") }),
3874
+ * });
3875
+ *
3876
+ * const agent = createDeepAgent({
3877
+ * middleware: [ResearchMiddleware],
3878
+ * stateSchema: z.object({ author: z.string().default("Me") }),
3879
+ * });
3880
+ *
3881
+ * const result = await agent.invoke({ messages: [...] });
3882
+ * // result.research and result.author are properly typed as strings
3883
+ * ```
3884
+ */
3885
+ declare function createDeepAgent<TResponse extends SupportedResponseFormat = SupportedResponseFormat, ContextSchema extends InteropZodObject = InteropZodObject, const TMiddleware extends readonly AgentMiddleware[] = readonly [], const TSubagents extends readonly AnySubAgent[] = readonly [], const TTools extends readonly (ClientTool | ServerTool)[] = readonly [], const TStreamTransformers extends ReadonlyArray<() => StreamTransformer<any>> = readonly [], TStateSchema extends AnyStateSchema | InteropZodObject | undefined = undefined>(params?: CreateDeepAgentParams<TResponse, ContextSchema, TMiddleware, TSubagents, TTools, TStreamTransformers, TStateSchema>): DeepAgent<DeepAgentTypeConfig<InferStructuredResponse<TResponse>, TStateSchema, ContextSchema, readonly [AgentMiddleware<import("zod/v3").ZodObject<{
3886
+ todos: import("zod/v3").ZodDefault<import("zod/v3").ZodArray<import("zod/v3").ZodObject<{
3887
+ content: import("zod/v3").ZodString;
3888
+ status: import("zod/v3").ZodEnum<["pending", "in_progress", "completed"]>;
3889
+ }, "strip", import("zod/v3").ZodTypeAny, {
3890
+ content: string;
3891
+ status: "completed" | "in_progress" | "pending";
3892
+ }, {
3893
+ content: string;
3894
+ status: "completed" | "in_progress" | "pending";
3895
+ }>, "many">>;
3896
+ }, "strip", import("zod/v3").ZodTypeAny, {
3897
+ todos: {
3898
+ content: string;
3899
+ status: "completed" | "in_progress" | "pending";
3900
+ }[];
3901
+ }, {
3902
+ todos?: {
3903
+ content: string;
3904
+ status: "completed" | "in_progress" | "pending";
3905
+ }[] | undefined;
3906
+ }>, undefined, unknown, readonly [import("langchain").DynamicStructuredTool<import("zod/v3").ZodObject<{
3907
+ todos: import("zod/v3").ZodArray<import("zod/v3").ZodObject<{
3908
+ content: import("zod/v3").ZodString;
3909
+ status: import("zod/v3").ZodEnum<["pending", "in_progress", "completed"]>;
3910
+ }, "strip", import("zod/v3").ZodTypeAny, {
3911
+ content: string;
3912
+ status: "completed" | "in_progress" | "pending";
3913
+ }, {
3914
+ content: string;
3915
+ status: "completed" | "in_progress" | "pending";
3916
+ }>, "many">;
3917
+ }, "strip", import("zod/v3").ZodTypeAny, {
3918
+ todos: {
3919
+ content: string;
3920
+ status: "completed" | "in_progress" | "pending";
3921
+ }[];
3922
+ }, {
3923
+ todos: {
3924
+ content: string;
3925
+ status: "completed" | "in_progress" | "pending";
3926
+ }[];
3927
+ }>, {
3928
+ todos: {
3929
+ content: string;
3930
+ status: "completed" | "in_progress" | "pending";
3931
+ }[];
3932
+ }, {
3933
+ todos: {
3934
+ content: string;
3935
+ status: "completed" | "in_progress" | "pending";
3936
+ }[];
3937
+ }, _langgraph.Command<unknown, {
3938
+ todos: {
3939
+ content: string;
3940
+ status: "completed" | "in_progress" | "pending";
3941
+ }[];
3942
+ messages: _messages.ToolMessage<_messages.MessageStructure<_messages.MessageToolSet>>[];
3943
+ }, string>, unknown, "write_todos">], readonly []>, AgentMiddleware<_langgraph.StateSchema<{
3944
+ files: _langgraph.ReducedValue<FilesRecord | undefined, FilesRecordUpdate | undefined>;
3945
+ }>, undefined, unknown, (import("langchain").DynamicStructuredTool<import("zod").ZodObject<{
3946
+ path: import("zod").ZodDefault<import("zod").ZodOptional<import("zod").ZodString>>;
3947
+ }, import("zod/v4/core").$strip>, {
3948
+ path: string;
3949
+ }, {
3950
+ path?: string | undefined;
3951
+ }, string, unknown, "ls"> | import("langchain").DynamicStructuredTool<import("zod").ZodObject<{
3952
+ file_path: import("zod").ZodString;
3953
+ offset: import("zod").ZodDefault<import("zod").ZodOptional<import("zod").ZodCoercedNumber<unknown>>>;
3954
+ limit: import("zod").ZodDefault<import("zod").ZodOptional<import("zod").ZodCoercedNumber<unknown>>>;
3955
+ }, import("zod/v4/core").$strip>, {
3956
+ file_path: string;
3957
+ offset: number;
3958
+ limit: number;
3959
+ }, {
3960
+ file_path: string;
3961
+ offset?: unknown;
3962
+ limit?: unknown;
3963
+ }, {
3964
+ type: string;
3965
+ text: string;
3966
+ }[] | {
3967
+ type: string;
3968
+ mimeType: string;
3969
+ data: string;
3970
+ }[], unknown, "read_file"> | import("langchain").DynamicStructuredTool<import("zod").ZodObject<{
3971
+ file_path: import("zod").ZodString;
3972
+ content: import("zod").ZodDefault<import("zod").ZodString>;
3973
+ }, import("zod/v4/core").$strip>, {
3974
+ file_path: string;
3975
+ content: string;
3976
+ }, {
3977
+ file_path: string;
3978
+ content?: string | undefined;
3979
+ }, string | _messages.ToolMessage<_messages.MessageStructure<_messages.MessageToolSet>> | _langgraph.Command<unknown, {
3980
+ files: Record<string, FileData>;
3981
+ messages: _messages.ToolMessage<_messages.MessageStructure<_messages.MessageToolSet>>[];
3982
+ }, string>, unknown, "write_file"> | import("langchain").DynamicStructuredTool<import("zod").ZodObject<{
3983
+ file_path: import("zod").ZodString;
3984
+ old_string: import("zod").ZodString;
3985
+ new_string: import("zod").ZodString;
3986
+ replace_all: import("zod").ZodDefault<import("zod").ZodOptional<import("zod").ZodBoolean>>;
3987
+ }, import("zod/v4/core").$strip>, {
3988
+ file_path: string;
3989
+ old_string: string;
3990
+ new_string: string;
3991
+ replace_all: boolean;
3992
+ }, {
3993
+ file_path: string;
3994
+ old_string: string;
3995
+ new_string: string;
3996
+ replace_all?: boolean | undefined;
3997
+ }, string | _messages.ToolMessage<_messages.MessageStructure<_messages.MessageToolSet>> | _langgraph.Command<unknown, {
3998
+ files: Record<string, FileData>;
3999
+ messages: _messages.ToolMessage<_messages.MessageStructure<_messages.MessageToolSet>>[];
4000
+ }, string>, unknown, "edit_file"> | import("langchain").DynamicStructuredTool<import("zod").ZodObject<{
4001
+ pattern: import("zod").ZodString;
4002
+ path: import("zod").ZodDefault<import("zod").ZodOptional<import("zod").ZodString>>;
4003
+ }, import("zod/v4/core").$strip>, {
4004
+ pattern: string;
4005
+ path: string;
4006
+ }, {
4007
+ pattern: string;
4008
+ path?: string | undefined;
4009
+ }, string, unknown, "glob"> | import("langchain").DynamicStructuredTool<import("zod").ZodObject<{
4010
+ pattern: import("zod").ZodString;
4011
+ path: import("zod").ZodDefault<import("zod").ZodOptional<import("zod").ZodString>>;
4012
+ glob: import("zod").ZodDefault<import("zod").ZodNullable<import("zod").ZodOptional<import("zod").ZodString>>>;
4013
+ }, import("zod/v4/core").$strip>, {
4014
+ pattern: string;
4015
+ path: string;
4016
+ glob: string | null;
4017
+ }, {
4018
+ pattern: string;
4019
+ path?: string | undefined;
4020
+ glob?: string | null | undefined;
4021
+ }, string, unknown, "grep"> | import("langchain").DynamicStructuredTool<import("zod").ZodObject<{
4022
+ command: import("zod").ZodString;
4023
+ }, import("zod/v4/core").$strip>, {
4024
+ command: string;
4025
+ }, {
4026
+ command: string;
4027
+ }, string, unknown, "execute">)[], readonly []>, AgentMiddleware<undefined, undefined, unknown, readonly [import("langchain").DynamicStructuredTool<import("zod").ZodObject<{
4028
+ description: import("zod").ZodString;
4029
+ subagent_type: import("zod").ZodString;
4030
+ }, import("zod/v4/core").$strip>, {
4031
+ description: string;
4032
+ subagent_type: string;
4033
+ }, {
4034
+ description: string;
4035
+ subagent_type: string;
4036
+ }, string | _langgraph.Command<unknown, Record<string, unknown>, string>, unknown, "task">], readonly []>, AgentMiddleware<import("zod").ZodObject<{
4037
+ _summarizationSessionId: import("zod").ZodOptional<import("zod").ZodString>;
4038
+ _summarizationEvent: import("zod").ZodOptional<import("zod").ZodObject<{
4039
+ cutoffIndex: import("zod").ZodNumber;
4040
+ summaryMessage: import("zod").ZodCustom<_messages.HumanMessage<_messages.MessageStructure<_messages.MessageToolSet>>, _messages.HumanMessage<_messages.MessageStructure<_messages.MessageToolSet>>>;
4041
+ filePath: import("zod").ZodNullable<import("zod").ZodString>;
4042
+ }, import("zod/v4/core").$strip>>;
4043
+ }, import("zod/v4/core").$strip>, undefined, unknown, readonly (ClientTool | ServerTool)[], readonly []>, AgentMiddleware<undefined, undefined, unknown, readonly (ClientTool | ServerTool)[], readonly []>, ...TMiddleware, ...FlattenSubAgentMiddleware<TSubagents>], TTools, TSubagents, TStreamTransformers>>;
4044
+ //#endregion
4045
+ export { AsyncTaskStatus as $, FileDownloadResponse as $t, findProjectRoot as A, harnessProfileConfigSchema as At, FlattenSubAgentMiddleware as B, ConfigurationErrorCode as Bt, parseSkillMetadata as C, BackendProtocolV2 as Cn, TASK_SYSTEM_PROMPT as Ct, Settings as D, registerHarnessProfile as Dt, filesValue as E, SandboxBackendProtocolV1 as En, getHarnessProfile as Et, CreateDeepAgentParams as F, GeneralPurposeSubagentConfig as Ft, InferSubagentByName as G, PermissionMode as Gt, InferDeepAgentType as H, createFilesystemMiddleware as Ht, DeepAgent as I, HarnessProfile as It, ResolveDeepAgentTypeConfig as J, BackendProtocol as Jt, InferSubagentReactAgentType as K, AnyBackendProtocol as Kt, DeepAgentTypeConfig as L, HarnessProfileOptions as Lt, SubagentRunStream as M, serializeProfile as Mt, createSubagentTransformer as N, EMPTY_HARNESS_PROFILE as Nt, SettingsOptions as O, HarnessProfileConfigData as Ot, AnySubAgent as P, createHarnessProfile as Pt, AsyncTask as Q, FileData as Qt, DefaultDeepAgentTypeConfig as R, REQUIRED_MIDDLEWARE_NAMES as Rt, listSkills as S, resolveBackend as Sn, SubAgentMiddlewareOptions as St, createAgentMemoryMiddleware as T, BackendProtocolV1 as Tn, createSubAgentMiddleware as Tt, InferStructuredResponse as U, FilesystemOperation as Ut, InferDeepAgentSubagents as V, FilesystemMiddlewareOptions as Vt, InferSubAgentMiddlewareStates as W, FilesystemPermission as Wt, AsyncSubAgent as X, EditResult as Xt, SupportedResponseFormat as Y, BackendRuntime as Yt, AsyncSubAgentMiddlewareOptions as Z, ExecuteResponse as Zt, StoreBackendContext as _, SandboxListResponse as _n, DEFAULT_GENERAL_PURPOSE_DESCRIPTION as _t, adaptBackendProtocol as a, GrepResult as an, createCompletionCallbackMiddleware as at, ListSkillsOptions as b, isSandboxBackend as bn, SUBAGENT_RESPONSE_FORMAT_CONFIG_KEY as bt, LangSmithSandboxCreateOptions as c, ReadRawResult as cn, MAX_SKILL_NAME_LENGTH as ct, LocalShellBackend as d, SandboxDeleteOptions as dn, createSkillsMiddleware as dt, FileInfo as en, createAsyncSubAgentMiddleware as et, LocalShellBackendOptions as f, SandboxError as fn, MemoryMiddlewareOptions as ft, StoreBackend as g, SandboxListOptions as gn, CompiledSubAgent as gt, FilesystemBackend as h, SandboxInfo as hn, createPatchToolCallsMiddleware as ht, LangSmithStartSandboxOptions as i, GrepMatch as in, CompletionCallbackOptions as it, DeepAgentRunStream as j, parseHarnessProfileConfig as jt, createSettings as k, generalPurposeSubagentConfigSchema as kt, LangSmithSandboxOptions as l, ReadResult as ln, SkillMetadata$1 as lt, CompositeBackend as m, SandboxGetOrCreateOptions as mn, StateBackend as mt, LangSmithCaptureSnapshotOptions as n, FileUploadResponse as nn, computeSummarizationDefaults as nt, adaptSandboxProtocol as o, LsResult as on, MAX_SKILL_DESCRIPTION_LENGTH as ot, ContextHubBackend as p, SandboxErrorCode as pn, createMemoryMiddleware as pt, MergedDeepAgentState as q, BackendFactory as qt, LangSmithSnapshot as r, GlobResult as rn, createSummarizationMiddleware as rt, LangSmithSandbox as s, MaybePromise as sn, MAX_SKILL_FILE_SIZE as st, createDeepAgent as t, FileOperationError as tn, isAsyncSubAgent as tt, BaseSandbox as u, SandboxBackendProtocol as un, SkillsMiddlewareOptions as ut, StoreBackendNamespaceFactory as v, StateAndStore as vn, DEFAULT_SUBAGENT_PROMPT as vt, AgentMemoryMiddlewareOptions as w, SandboxBackendProtocolV2 as wn, createSubAgent as wt, SkillMetadata as x, isSandboxProtocol as xn, SubAgent as xt, StoreBackendOptions as y, WriteResult as yn, GENERAL_PURPOSE_SUBAGENT as yt, ExtractSubAgentMiddleware as z, ConfigurationError as zt };
4046
+ //# sourceMappingURL=agent-DNSq5NSK.d.cts.map