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